oandapy は、OANDA の REST API の Python ラッパーです。
ピップの使用:
$ pip install git+https://github.com/oanda/oandapy.git
oandapy は python-requests に依存しており、自動的にインストールされます。
oandapy モジュールを組み込み、アカウントの資格情報を使用して oandapy インスタンスを作成します。 FxGame および FxTrade の場合、アクセス トークンを提供する必要があります。
import oandapy
oanda = oandapy.API(environment="practice", access_token="abcdefghijk...")
関数へのキーワード引数は、Oanda API ドキュメントの各エンドポイントで利用可能な関数にマップされているため、API への変更がこのライブラリによって使用されなくなることはありません。 API 呼び出しごとに、oandapy は JSON から変換されたネイティブ Python オブジェクトを返すため、その必要はありません。
oandapy.py の EndpointsMixin クラスは、すべての Oanda API エンドポイントのミックスインを保持します。
response = oanda.get_prices(instruments="EUR_USD")
prices = response.get("prices")
asking_price = prices[0].get("ask")
# required datetime functions
from datetime import datetime, timedelta
# sample account_id
account_id = 1813880
# set the trade to expire after one day
trade_expire = datetime.utcnow() + timedelta(days=1)
trade_expire = trade_expire.isoformat("T") + "Z"
response = oanda.create_order(account_id,
instrument="USD_CAD",
units=1000,
side='sell',
type='limit',
price=1.15,
expiry=trade_expire
)
カスタム ストリーマ クラスを作成して、データの処理方法を設定します。各ティックは、 on_success
関数およびon_error
関数を通じて送信されます。これらのメソッドは抽象メソッドであるため、ストリーミング データを処理するにはこれらのメソッドをオーバーライドする必要があります。
次の例では、ストリームからcountティックを出力してから切断します。
class MyStreamer(oandapy.Streamer):
def __init__(self, count=10, *args, **kwargs):
super(MyStreamer, self).__init__(*args, **kwargs)
self.count = count
self.reccnt = 0
def on_success(self, data):
print data, "n"
self.reccnt += 1
if self.reccnt == self.count:
self.disconnect()
def on_error(self, data):
self.disconnect()
カスタム ストリーマのインスタンスを初期化し、ストリームへの接続を開始します。詳細なドキュメントについては、http://developer.oanda.com/rest-live/streaming/ を参照してください。
account = "12345"
stream = MyStreamer(environment="practice", access_token="abcdefghijk...")
stream.rates(account, instruments="EUR_USD,EUR_JPY,US30_USD,DE30_EUR")
ストリーミング イベントにも同じ手順を使用できます。
stream = MyStreamer(environment="practice", access_token="abcdefghijk...")
stream.events(ignore_heartbeat=False)