Interface OANDA’s REST-V20¶
The client¶
The oandapyV20
package contains a client class, oandapyV20.API
, to
communicate with the REST-V20 interface. It processes requests that
can be created from the endpoint classes.
For it’s communication it relies on: requests
(requests).
The client keeps no state of a requests. The response of a request is assigned to the request instance. The response is also returned as a return value by the client.
-
class
oandapyV20.
API
(access_token, environment='practice', headers=None, request_params=None)¶ Bases:
object
API - class to handle APIRequests objects to access API endpoints.
Examples
# get a list of trades from oandapyV20 import API import oandapyV20.endpoints.trades as trades api = API(access_token="xxx") accountID = "101-305-3091856-001" r = trades.TradesList(accountID) # show the endpoint as it is constructed for this call print("REQUEST:{}".format(r)) rv = api.request(r) print("RESPONSE:\n{}".format(json.dumps(rv, indent=2)))
Output:
REQUEST:v3/accounts/101-305-3091856-001/trades RESPONSE: "trades": [ { "financing": "0.0000", "openTime": "2016-07-21T15:47:05.170212014Z", "price": "10133.9", "unrealizedPL": "8.0000", "realizedPL": "0.0000", "instrument": "DE30_EUR", "state": "OPEN", "initialUnits": "-10", "currentUnits": "-10", "id": "1032" }, { "financing": "0.0000", "openTime": "2016-07-21T15:47:04.963590941Z", "price": "10134.4", "unrealizedPL": "13.0000", "realizedPL": "0.0000", "instrument": "DE30_EUR", "state": "OPEN", "initialUnits": "-10", "currentUnits": "-10", "id": "1030" } ], "lastTransactionID": "1040" }
# reduce a trade by it's id from oandapyV20 import API import oandapyV20.endpoints.trades as trades api = API(access_token="...") accountID = "101-305-3091856-001" tradeID = "1030" cfg = {"units": 5} r = trades.TradeClose(accountID, tradeID=tradeID, data=cfg) # show the endpoint as it is constructed for this call print("REQUEST:{}".format(r)) rv = api.request(r) print("RESPONSE\n{}".format(json.dumps(rv, indent=2)))
Output:
REQUEST:v3/accounts/101-305-3091856-001/trades/1030/close RESPONSE: { "orderFillTransaction": { "orderID": "1041", "financing": "-0.1519", "instrument": "DE30_EUR", "userID": 1435156, "price": "10131.6", "tradeReduced": { "units": "5", "financing": "-0.1519", "realizedPL": "14.0000", "tradeID": "1030" }, "batchID": "1041", "accountBalance": "44876.2548", "reason": "MARKET_ORDER_TRADE_CLOSE", "time": "2016-07-21T17:32:51.361464739Z", "units": "5", "type": "ORDER_FILL", "id": "1042", "pl": "14.0000", "accountID": "101-305-3091856-001" }, "orderCreateTransaction": { "timeInForce": "FOK", "positionFill": "REDUCE_ONLY", "userID": 1435156, "batchID": "1041", "instrument": "DE30_EUR", "reason": "TRADE_CLOSE", "tradeClose": { "units": "5", "tradeID": "1030" }, "time": "2016-07-21T17:32:51.361464739Z", "units": "5", "type": "MARKET_ORDER", "id": "1041", "accountID": "101-305-3091856-001" }, "relatedTransactionIDs": [ "1041", "1042" ], "lastTransactionID": "1042" }
-
__init__
(access_token, environment='practice', headers=None, request_params=None)¶ Instantiate an instance of OandaPy’s API wrapper.
Parameters: - access_token (string) – Provide a valid access token.
- environment (string) – Provide the environment for OANDA’s REST api. Valid values: ‘practice’ or ‘live’. Default: ‘practice’.
- headers (dict (optional)) – Provide request headers to be set for a request.
Note
There is no need to set the ‘Content-Type: application/json’ for the endpoints that require this header. The API-request classes covering those endpoints will take care of the header.
- request_params : (optional)
parameters to be passed to the request. This can be used to apply for instance a timeout value:
request_params={“timeout”: 0.1}See specs of the requests module for full details of possible parameters.
Warning
parameters belonging to a request need to be set on the requestinstance and are NOT passed via the client.
-
request
(endpoint)¶ Perform a request for the APIRequest instance ‘endpoint’.
Parameters: endpoint (APIRequest) – The endpoint parameter contains an instance of an APIRequest containing the endpoint, method and optionally other parameters or body data. Raises: V20Error in case of HTTP response code >= 400
-
request_params
¶ request_params property.
-
Exceptions¶
-
class
oandapyV20.
V20Error
(code, msg)¶ Bases:
exceptions.Exception
Generic error class.
In case of HTTP response codes >= 400 this class can be used to raise an exception representing that error.
-
__init__
(code, msg)¶ Instantiate a V20Error.
Parameters: - code (int) – the HTTP-code of the response
- msg (str) – the message returned with the response
-
Logging¶
The oandapyV20
package has logging integrated. Logging can be
simply applied by enabling a logger.
The example below will log INFO-level logging to the file v20.log.
For details check the logger
module in the standard Python
documentation.
# code snippet
from oandapyV20 import API
import oandapyV20.endpoints.orders as orders
from oandapyV20.exceptions import V20Error
from exampleauth import exampleAuth
import logging
logging.basicConfig(
filename="v20.log",
level=logging.INFO,
format='%(asctime)s [%(levelname)s] %(name)s : %(message)s',
)
accountID, token = exampleAuth()
...
Resulting loglines:
2016-10-22 17:50:37,988 [INFO] oandapyV20.oandapyV20 : setting up API-client for environment practice
2016-10-22 17:50:37,990 [INFO] oandapyV20.oandapyV20 : performing request https://api-fxpractice.oanda.com/v3/accounts/101-004-1435156-001/orders
2016-10-22 17:50:37,998 [INFO] requests.packages.urllib3.connectionpool : Starting new HTTPS connection (1): api-fxpractice.oanda.com
2016-10-22 17:50:38,866 [INFO] oandapyV20.oandapyV20 : performing request https://api-fxpractice.oanda.com/v3/accounts/101-004-1435156-001/orders
2016-10-22 17:50:39,066 [ERROR] oandapyV20.oandapyV20 : request https://api-fxpractice.oanda.com/v3/accounts/101-004-1435156-001/orders failed [400,{"errorMessage":"Invalid value specified for 'order.instrument'"}]