Pythonを用いて為替取引(FX)を自動化する
FXの自動売買と言えばMT4が有名ですが、Python等からOANDAのAPIサービスを利用することでも取引を自動化することができます。
口座開設
APIを利用するためにはまずは口座開設が必要です。
本番口座だけでなくデモ口座も利用することができるので、動作確認のために最初はデモ申込をしましょう。
【OANDAの口座開設】
アカウントIDとトークンを取得する
APIの利用にはアカウントIDとPersonal Access Tokenが必要です。
ログイン後、「口座情報」のPrimaryの右側にある数字がアカウントIDです。
また、「MT4/API関連」の「APIアクセスの管理」を選び、その先のページでトークンを発行できます。
アカウントIDとトークンは重要な情報なので厳重に管理してください。
Pythonを用いて操作する
OANDAのREST API用のwrapperであるoandapyを利用すると、簡単に取引等の操作を行うことができます。
以下のコマンドでインストール。
$ pip install git+https://github.com/oanda/oandapy.git
引数と戻り値の詳細は公式ドキュメントを参照。
ドル円(USD/JPY)の1時間足を取得する
ソースコード
import oandapy access_token = "xxxxxxxxxxxxx" oanda = oandapy.API(environment="practice", access_token=access_token) res = oanda.get_history(instrument="USD_JPY",granularity="H1",count=2) print(res)
実行結果
{'instrument': 'USD_JPY', 'granularity': 'H1', 'candles': [{'time': '2018-04-02T18:00:00.000000Z', 'openBid': 105.66, 'openAsk': 105.675, 'highBid': 105.866, 'highAsk': 105.88, 'lowBid': 105.654, 'lowAsk': 105.669, 'closeBid': 105.842, 'closeAsk': 105.856, 'volume': 1937, 'complete': True}, {'time': '2018-04-02T19:00:00.000000Z', 'openBid': 105.844, 'openAsk': 105.859, 'highBid': 105.898, 'highAsk': 105.915, 'lowBid': 105.815, 'lowAsk': 105.828, 'closeBid': 105.829, 'closeAsk': 105.843, 'volume': 831, 'complete': False}]}
ドル円(USD/JPY)を1000通貨買って10秒後に決済する
ソースコード
import time import oandapy account_id = "xxxxxxxx" access_token = "xxxxxxxxxxxxx" oanda = oandapy.API(environment="practice", access_token=access_token) res = oanda.create_order(account_id, instrument="USD_JPY", units=1000, side='buy', type='market' ) print(res) time.sleep(10) res = oanda.close_position(account_id,"USD_JPY") print(res)
実行結果
{'instrument': 'USD_JPY', 'time': '2018-04-02T19:56:13.000000Z', 'price': 105.914, 'tradeOpened': {'id': 10976287346, 'units': 1000, 'side': 'buy', 'takeProfit': 0, 'stopLoss': 0, 'trailingStop': 0}, 'tradesClosed': [], 'tradeReduced': {}} {'ids': [10976287346, 10976287940], 'instrument': 'USD_JPY', 'totalUnits': 1000, 'price': 105.908}
まとめ
取得したローソク足を元に条件を設定して売買させれば完全に自動化できます。
【OANDAでFXを始める】