### Install oandapyV20 using pip Source: https://github.com/hootnot/oanda-api-v20/blob/master/README.rst Installs the oandapyV20 library using pip. It can be installed from PyPI or directly from the GitHub repository for the latest development version. ```bash pip install oandapyV20 ``` ```bash pip install git+https://github.com/hootnot/oanda-api-v20.git ``` -------------------------------- ### InstrumentsCandlesFactory Usage Source: https://github.com/hootnot/oanda-api-v20/blob/master/jupyter/historical.ipynb This example demonstrates how to use the InstrumentsCandlesFactory to fetch historical candle data for EUR_USD with a M5 granularity, starting from 2017-01-01. It processes the data and writes it to a file. ```APIDOC ## InstrumentsCandlesFactory ### Description The `InstrumentsCandlesFactory` is a utility class designed to simplify the retrieval of extensive historical candle data. It acts as a generator, automatically creating and managing consecutive API requests to fetch all available data for an instrument from a specified start date up to the current date, or a specified end date. ### Method GET ### Endpoint /v3/instruments/{instrument}/candles ### Parameters #### Path Parameters - **instrument** (string) - Required - The instrument ID (e.g., EUR_USD). #### Query Parameters - **from** (string) - Required - The start date and time in ISO format (e.g., "2017-01-01T00:00:00Z"). - **to** (string) - Optional - The end date and time in ISO format. - **granularity** (string) - Required - The granularity of the candles (e.g., "M5", "H1", "D1"). - **count** (integer) - Optional - The number of candles to retrieve per request. Defaults to 500. Setting this to a higher value (e.g., 5000) can reduce the number of API calls but may hit API limits. ### Request Example ```python import oandapyV20 from oandapyV20.contrib.factories import InstrumentsCandlesFactory client = oandapyV20.API(access_token="YOUR_ACCESS_TOKEN") instrument = "EUR_USD" params = { "from": "2017-01-01T00:00:00Z", "granularity": "M5", } # The factory generates requests, and we process each one for r in InstrumentsCandlesFactory(instrument=instrument, params=params): response = client.request(r) # Process the response data here print(f"Received {len(response.get('candles'))} candles") ``` ### Response #### Success Response (200) - **candles** (array) - An array of candle objects. - **complete** (boolean) - Indicates if the candle is complete. - **time** (string) - The timestamp of the candle. - **mid** (object) - Mid-point prices. - **o** (string) - Opening price. - **h** (string) - High price. - **l** (string) - Low price. - **c** (string) - Closing price. - **volume** (integer) - The volume of trading for the candle. #### Response Example ```json { "instrument": "EUR_USD", "granularity": "M5", "candles": [ { "complete": true, "time": "2017-01-01T00:00:00.000Z", "mid": { "o": "1.05000", "h": "1.05010", "l": "1.04990", "c": "1.05005" }, "volume": 100 } // ... more candles ] } ``` ``` -------------------------------- ### Fetch Historical Data with includeFirst Parameter Source: https://github.com/hootnot/oanda-api-v20/blob/master/jupyter/historical.ipynb Shows how to include the includeFirst parameter in the request to ensure the starting candle is included in the returned dataset. ```python instrument = "EUR_USD" params = { "from": "2017-01-01T00:00:00Z", "granularity": "H1", "includeFirst": True, "count": 10, } r = instruments.InstrumentsCandles(instrument=instrument, params=params) response = client.request(r) print("Request: {} #candles received: {}".format(r, len(r.response.get('candles')))) print(json.dumps(response, indent=2)) ``` -------------------------------- ### Initialize OANDA API Client with Logging Source: https://github.com/hootnot/oanda-api-v20/blob/master/docs/oanda-api-v20.rst Demonstrates how to configure the Python logging module to capture API activity and initialize the OANDA API client. This setup logs INFO-level events to a file named v20.log, providing visibility into request execution and errors. ```python 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() ``` -------------------------------- ### GET /accounts/{accountID}/pricing/stream Source: https://github.com/hootnot/oanda-api-v20/blob/master/README.rst Establishes a persistent connection to receive real-time price updates for a list of instruments. ```APIDOC ## GET /accounts/{accountID}/pricing/stream ### Description This endpoint provides a streaming connection to receive real-time pricing information for one or more instruments. The stream will continue to push updates until the connection is closed or terminated. ### Method GET ### Endpoint /accounts/{accountID}/pricing/stream ### Parameters #### Path Parameters - **accountID** (string) - Required - The ID of the account to fetch pricing for. #### Query Parameters - **instruments** (string) - Required - A comma-separated list of instruments to stream (e.g., "EUR_USD,EUR_JPY"). ### Request Example GET /accounts/123-456/pricing/stream?instruments=EUR_USD,EUR_JPY ### Response #### Success Response (200) - **type** (string) - The type of message (e.g., "PRICE" or "HEARTBEAT"). - **instrument** (string) - The instrument name (only for PRICE type). - **time** (string) - RFC3339 timestamp of the update. - **bids** (array) - List of bid prices and liquidity. - **asks** (array) - List of ask prices and liquidity. #### Response Example { "type": "PRICE", "instrument": "EUR_USD", "time": "2016-10-17T12:25:43.689619691Z", "bids": [{"price": "1.09953", "liquidity": 10000000}], "asks": [{"price": "1.09966", "liquidity": 10000000}] } ``` -------------------------------- ### Place Market Order with Take Profit and Stop Loss Source: https://github.com/hootnot/oanda-api-v20/blob/master/README.rst This example shows how to place a market order for EUR_USD with specified units, a take-profit price, and a stop-loss price using the OANDA API v20. It utilizes helper classes for order details and handles potential API errors. ```python import json from oandapyV20.contrib.requests import MarketOrderRequest from oandapyV20.contrib.requests import TakeProfitDetails, StopLossDetails import oandapyV20.endpoints.orders as orders import oandapyV20 from exampleauth import exampleAuth accountID, access_token = exampleAuth() api = oandapyV20.API(access_token=access_token) # EUR_USD (today 1.0750) EUR_USD_STOP_LOSS = 1.07 EUR_USD_TAKE_PROFIT = 1.10 mktOrder = MarketOrderRequest( instrument="EUR_USD", units=10000, takeProfitOnFill=TakeProfitDetails(price=EUR_USD_TAKE_PROFIT).data, stopLossOnFill=StopLossDetails(price=EUR_USD_STOP_LOSS).data) # create the OrderCreate request r = orders.OrderCreate(accountID, data=mktOrder.data) try: # create the OrderCreate request rv = api.request(r) except oandapyV20.exceptions.V20Error as err: print(r.status_code, err) else: print(json.dumps(rv, indent=2)) ``` -------------------------------- ### Manage Account Positions Source: https://context7.com/hootnot/oanda-api-v20/llms.txt Demonstrates how to list all positions, open positions, get details for a specific instrument, and close a position. These operations utilize the oandapyV20.endpoints.positions module. ```python import oandapyV20 import oandapyV20.endpoints.positions as positions client = oandapyV20.API(access_token="your-access-token") accountID = "101-004-1435156-001" # List all positions r = positions.PositionList(accountID=accountID) client.request(r) # Close position data = {"longUnits": "ALL"} r = positions.PositionClose(accountID=accountID, instrument="EUR_USD", data=data) client.request(r) ``` -------------------------------- ### Retrieve Pricing Information Source: https://context7.com/hootnot/oanda-api-v20/llms.txt Fetches current pricing for specific instruments or establishes a real-time stream for market updates. The streaming example includes error handling and termination logic. ```python import json from oandapyV20 import API from oandapyV20.endpoints.pricing import PricingStream api = API(access_token="your-access-token", environment="practice") instruments = "EUR_USD,EUR_JPY" s = PricingStream(accountID="101-004-1435156-001", params={"instruments": instruments}) for R in api.request(s): print(json.dumps(R, indent=2)) ``` -------------------------------- ### GET /v3/accounts/{accountID}/pricing Source: https://github.com/hootnot/oanda-api-v20/blob/master/docs/endpoints/pricing/pricinginfo.rst Retrieves the current pricing information for a specified list of instruments. ```APIDOC ## GET /v3/accounts/{accountID}/pricing ### Description Retrieves the current pricing information for a specified list of instruments for a given account. ### Method GET ### Endpoint /v3/accounts/{accountID}/pricing ### Parameters #### Path Parameters - **accountID** (string) - Required - The ID of the account to retrieve pricing for. #### Query Parameters - **instruments** (string) - Required - A comma-separated list of instruments to retrieve pricing for. ### Request Example GET /v3/accounts/101-001-1234567-001/pricing?instruments=EUR_USD,USD_JPY ### Response #### Success Response (200) - **prices** (array) - A list of Price objects. #### Response Example { "prices": [ { "type": "PRICE", "instrument": "EUR_USD", "bids": [{"price": "1.12345", "liquidity": 1000000}], "asks": [{"price": "1.12355", "liquidity": 1000000}], "status": "tradeable" } ] } ``` -------------------------------- ### OANDA API v20: Get Account Pricing Source: https://github.com/hootnot/oanda-api-v20/blob/master/README.rst This snippet demonstrates fetching pricing information for instruments from the OANDA API v20. It includes details for DE30_EUR and EUR_GBP, showing bid/ask prices, liquidity, and available units. ```json { "request": "v3/accounts/101-004-1435156-001/pricing", "response": { "prices": [ { "status": "tradeable", "quoteHomeConversionFactors": { "negativeUnits": "1.00000000", "positiveUnits": "1.00000000" }, "asks": [ { "price": "10295.1", "liquidity": 25 }, { "price": "10295.3", "liquidity": 75 }, { "price": "10295.5", "liquidity": 150 } ], "unitsAvailable": { "default": { "short": "60", "long": "100" }, "reduceOnly": { "short": "0", "long": "20" }, "openOnly": { "short": "60", "long": "0" }, "reduceFirst": { "short": "60", "long": "100" } }, "closeoutBid": "10293.5", "bids": [ { "price": "10293.9", "liquidity": 25 }, { "price": "10293.7", "liquidity": 75 }, { "price": "10293.5", "liquidity": 150 } ], "instrument": "DE30_EUR", "time": "2016-09-29T17:07:19.598030528Z", "closeoutAsk": "10295.5" }, { "status": "tradeable", "quoteHomeConversionFactors": { "negativeUnits": "1.15679152", "positiveUnits": "1.15659083" }, "asks": [ { "price": "0.86461", "liquidity": 1000000 }, { "price": "0.86462", "liquidity": 2000000 }, { "price": "0.86463", "liquidity": 5000000 }, { "price": "0.86465", "liquidity": 10000000 } ], "unitsAvailable": { "default": { "short": "624261", "long": "624045" }, "reduceOnly": { "short": "0", "long": "0" }, "openOnly": { "short": "624261", "long": "624045" }, "reduceFirst": { "short": "624261", "long": "624045" } }, "closeoutBid": "0.86442", "bids": [ { "price": "0.86446", "liquidity": 1000000 }, { "price": "0.86445", "liquidity": 2000000 }, { "price": "0.86444", "liquidity": 5000000 }, { "price": "0.86442", "liquidity": 10000000 } ], "instrument": "EUR_GBP", "time": "2016-09-29T17:07:19.994271769Z", "closeoutAsk": "0.86465", "type": "PRICE" } ] } } ``` -------------------------------- ### Get Pricing Information Source: https://github.com/hootnot/oanda-api-v20/blob/master/README.rst Retrieves real-time pricing information for specified instruments. This includes bid and ask prices, liquidity, and other relevant market data. ```APIDOC ## GET /v3/accounts/{accountID}/pricing ### Description Retrieves real-time pricing information for specified instruments. ### Method GET ### Endpoint /v3/accounts/{accountID}/pricing ### Parameters #### Path Parameters - **accountID** (string) - Required - The identifier of the account. ### Response #### Success Response (200) - **prices** (array) - A list of pricing objects for different instruments. - **status** (string) - The trading status of the instrument (e.g., tradeable). - **quoteHomeConversionFactors** (object) - Conversion factors for quoting in the home currency. - **negativeUnits** (string) - Conversion factor for negative units. - **positiveUnits** (string) - Conversion factor for positive units. - **asks** (array) - A list of ask price objects. - **price** (string) - The ask price. - **liquidity** (integer) - The available liquidity at this price. - **unitsAvailable** (object) - The available units for trading. - **default** (object) - Default available units. - **short** (string) - Available short units. - **long** (string) - Available long units. - **reduceOnly** (object) - Available units for reduce-only orders. - **short** (string) - Available short units. - **long** (string) - Available long units. - **openOnly** (object) - Available units for open orders. - **short** (string) - Available short units. - **long** (string) - Available long units. - **reduceFirst** (object) - Available units for reduce-first orders. - **short** (string) - Available short units. - **long** (string) - Available long units. - **closeoutBid** (string) - The closeout bid price. - **bids** (array) - A list of bid price objects. - **price** (string) - The bid price. - **liquidity** (integer) - The available liquidity at this price. - **instrument** (string) - The instrument identifier. - **time** (string) - The timestamp of the price data. - **closeoutAsk** (string) - The closeout ask price. - **type** (string) - The type of pricing data (e.g., PRICE). #### Response Example ```json { "prices": [ { "status": "tradeable", "quoteHomeConversionFactors": { "negativeUnits": "1.00000000", "positiveUnits": "1.00000000" }, "asks": [ { "price": "10295.1", "liquidity": 25 }, { "price": "10295.3", "liquidity": 75 }, { "price": "10295.5", "liquidity": 150 } ], "unitsAvailable": { "default": { "short": "60", "long": "100" }, "reduceOnly": { "short": "0", "long": "20" }, "openOnly": { "short": "60", "long": "0" }, "reduceFirst": { "short": "60", "long": "100" } }, "closeoutBid": "10293.5", "bids": [ { "price": "10293.9", "liquidity": 25 }, { "price": "10293.7", "liquidity": 75 }, { "price": "10293.5", "liquidity": 150 } ], "instrument": "DE30_EUR", "time": "2016-09-29T17:07:19.598030528Z", "closeoutAsk": "10295.5" }, { "status": "tradeable", "quoteHomeConversionFactors": { "negativeUnits": "1.15679152", "positiveUnits": "1.15659083" }, "asks": [ { "price": "0.86461", "liquidity": 1000000 }, { "price": "0.86462", "liquidity": 2000000 }, { "price": "0.86463", "liquidity": 5000000 }, { "price": "0.86465", "liquidity": 10000000 } ], "unitsAvailable": { "default": { "short": "624261", "long": "624045" }, "reduceOnly": { "short": "0", "long": "0" }, "openOnly": { "short": "624261", "long": "624045" }, "reduceFirst": { "short": "624261", "long": "624045" } }, "closeoutBid": "0.86442", "bids": [ { "price": "0.86446", "liquidity": 1000000 }, { "price": "0.86445", "liquidity": 2000000 }, { "price": "0.86444", "liquidity": 5000000 }, { "price": "0.86442", "liquidity": 10000000 } ], "instrument": "EUR_GBP", "time": "2016-09-29T17:07:19.994271769Z", "closeoutAsk": "0.86465", "type": "PRICE" } ] } ``` ``` -------------------------------- ### OANDA API Log Output Format Source: https://github.com/hootnot/oanda-api-v20/blob/master/docs/oanda-api-v20.rst An example of the log output generated by the oandapyV20 package. It shows standard request lifecycle events, including connection establishment and error responses. ```text 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'"}] ``` -------------------------------- ### GET /v3/accounts/{accountID}/transactions/sinceid Source: https://github.com/hootnot/oanda-api-v20/blob/master/docs/endpoints/transactions/transactionssinceid.rst Retrieves a list of transactions for an account starting from a specific transaction ID. ```APIDOC ## GET /v3/accounts/{accountID}/transactions/sinceid ### Description Fetches all transactions for the specified account that occurred after the provided transaction ID. ### Method GET ### Endpoint /v3/accounts/{accountID}/transactions/sinceid ### Parameters #### Path Parameters - **accountID** (string) - Required - The identifier of the account to fetch transactions for. #### Query Parameters - **id** (string) - Required - The ID of the transaction to start the list from. ### Request Example GET /v3/accounts/101-001-1234567-001/transactions/sinceid?id=1234 ### Response #### Success Response (200) - **transactions** (array) - A list of transaction objects. - **lastTransactionID** (string) - The ID of the most recent transaction in the account. #### Response Example { "transactions": [ { "id": "1235", "type": "ORDER_FILL", "accountID": "101-001-1234567-001" } ], "lastTransactionID": "1235" } ``` -------------------------------- ### API Client Initialization and Usage Source: https://context7.com/hootnot/oanda-api-v20/llms.txt Demonstrates how to initialize the API client with an access token and environment, and how to make a request to retrieve a list of accounts. ```APIDOC ## API Client ### Description The `API` class is the main client for making requests to the OANDA REST-V20 API. It handles authentication, request execution, and response parsing for both regular and streaming endpoints. ### Method Initialization: `API(access_token, environment)` Request: `client.request(request_object)` ### Endpoint N/A (Client-level operations) ### Parameters #### Initialization Parameters - **access_token** (string) - Required - Your OANDA API access token. - **environment** (string) - Required - 'practice' or 'live'. ### Request Example ```python import json from oandapyV20 import API from oandapyV20.exceptions import V20Error import oandapyV20.endpoints.accounts as accounts # Initialize the API client access_token = "your-access-token" client = API(access_token=access_token, environment="practice") # Or use with context manager for automatic connection cleanup with API(access_token=access_token, environment="practice") as client: r = accounts.AccountList() try: response = client.request(r) print(json.dumps(response, indent=2)) except V20Error as e: print(f"Error {e.code}: {e.msg}") ``` ### Response #### Success Response (200) - **accounts** (list) - A list of account objects. #### Response Example ```json { "accounts": [ {"id": "101-004-1435156-001", "tags": []}, {"id": "101-004-1435156-002", "tags": []} ] } ``` ``` -------------------------------- ### Initialize OANDA API Client Source: https://context7.com/hootnot/oanda-api-v20/llms.txt Demonstrates how to instantiate the API client using an access token and environment setting. It also shows the use of a context manager for automatic connection handling. ```python import json from oandapyV20 import API from oandapyV20.exceptions import V20Error import oandapyV20.endpoints.accounts as accounts access_token = "your-access-token" client = API(access_token=access_token, environment="practice") with API(access_token=access_token, environment="practice") as client: r = accounts.AccountList() try: response = client.request(r) print(json.dumps(response, indent=2)) except V20Error as e: print(f"Error {e.code}: {e.msg}") ``` -------------------------------- ### OpenTrades API Source: https://context7.com/hootnot/oanda-api-v20/llms.txt Gets the list of currently open trades for a specified account. ```APIDOC ## GET /v3/accounts/{accountID}/openTrades ### Description Retrieves a list of all currently open trades for a given account. ### Method GET ### Endpoint /v3/accounts/{accountID}/openTrades ### Parameters #### Path Parameters - **accountID** (string) - Required - The ID of the account whose open trades are to be retrieved. ### Request Example ```bash GET /v3/accounts/101-004-1435156-001/openTrades ``` ### Response #### Success Response (200) - **trades** (array) - A list of open trade objects. - **lastTransactionID** (string) - The ID of the last transaction. #### Response Example ```json { "trades": [ { "id": "1030", "instrument": "EUR_USD", "price": "1.08463", "openTime": "2016-07-21T15:47:04Z", "state": "OPEN", "currentUnits": "10000", "unrealizedPL": "23.0000" } ], "lastTransactionID": "1040" } ``` ``` -------------------------------- ### Create Market Order with Take Profit and Stop Loss (Python) Source: https://github.com/hootnot/oanda-api-v20/blob/master/jupyter/orders.ipynb This snippet shows how to construct a MARKET order request with specified units, instrument, and includes 'takeProfitOnFill' and 'stopLossOnFill' details. It uses direct dictionary construction for the order body. The order is set to 'FOK' (Fill-or-kill) time in force. ```python import json import oandapyV20 import oandapyV20.endpoints.orders as orders from exampleauth import exampleauth accountID, access_token = exampleauth.exampleauth() client = oandapyV20.API(access_token=access_token) # create a market order to enter a LONG position 10000 EUR_USD, stopLoss @1.07 takeProfit @1.10 ( current: 1.055) # according to the docs at developer.oanda.com the requestbody looks like: mktOrder = { "order": { "timeInForce": "FOK", # Fill-or-kill "instrument": "EUR_USD", "positionFill": "DEFAULT", "type": "MARKET", "units": 10000, # as integer "takeProfitOnFill": { "timeInForce": "GTC", # Good-till-cancelled "price": 1.10 # as float }, "stopLossOnFill": { "timeInForce": "GTC", "price": "1.07" # as string } } } r = orders.OrderCreate(accountID=accountID, data=mktOrder) print("Request: ", r) print("MarketOrder specs: ", json.dumps(mktOrder, indent=2)) ``` -------------------------------- ### Construct Market Order with Take Profit and Stop Loss Source: https://github.com/hootnot/oanda-api-v20/blob/master/README.rst Demonstrates how to construct a market order request with take profit and stop loss details using the oandapyV20 library's contrib.requests module. This provides a more readable alternative to manually creating the dictionary structure. ```python from oandapyV20.contrib.requests import MarketOrderRequest, TakeProfitDetails, StopLossDetails mktOrder = MarketOrderRequest(instrument="EUR_USD", units=10000, takeProfitOnFill=TakeProfitDetails(price=1.10).data, stopLossOnFill=StopLossDetails(price=1.07).data ).data ``` -------------------------------- ### TradesList API Source: https://context7.com/hootnot/oanda-api-v20/llms.txt Gets a list of trades for a specified account, with optional filtering. ```APIDOC ## GET /v3/accounts/{accountID}/trades ### Description Retrieves a list of trades for a given account. Supports filtering by instrument and state. ### Method GET ### Endpoint /v3/accounts/{accountID}/trades ### Parameters #### Path Parameters - **accountID** (string) - Required - The ID of the account whose trades are to be retrieved. #### Query Parameters - **instrument** (string) - Optional - Filter trades by instrument (e.g., "EUR_USD"). - **state** (string) - Optional - Filter trades by their state (e.g., "OPEN", "CLOSED"). ### Request Example ```bash GET /v3/accounts/101-004-1435156-001/trades?instrument=EUR_USD&state=OPEN ``` ### Response #### Success Response (200) - **trades** (array) - A list of trade objects. - **lastTransactionID** (string) - The ID of the last transaction. #### Response Example ```json { "trades": [ { "id": "1030", "instrument": "EUR_USD", "price": "1.08463", "openTime": "2016-07-21T15:47:04Z", "state": "OPEN", "currentUnits": "10000", "unrealizedPL": "23.0000" } ], "lastTransactionID": "1040" } ``` ``` -------------------------------- ### OrderDetails API Source: https://context7.com/hootnot/oanda-api-v20/llms.txt Gets detailed information for a specific order within an account. ```APIDOC ## GET /v3/accounts/{accountID}/orders/{orderID} ### Description Retrieves detailed information about a specific order identified by its ID. ### Method GET ### Endpoint /v3/accounts/{accountID}/orders/{orderID} ### Parameters #### Path Parameters - **accountID** (string) - Required - The ID of the account. - **orderID** (string) - Required - The ID of the order to retrieve. ### Request Example ```bash GET /v3/accounts/101-004-1435156-001/orders/2503 ``` ### Response #### Success Response (200) - **order** (object) - The order object containing detailed information. - **lastTransactionID** (string) - The ID of the last transaction. #### Response Example ```json { "order": { "id": "2503", "instrument": "EUR_USD", "units": "10000", "type": "MARKET", "timeInForce": "FOK", "createTime": "2016-07-21T15:47:04Z", "state": "PENDING" }, "lastTransactionID": "2504" } ``` ``` -------------------------------- ### OrderList API Source: https://context7.com/hootnot/oanda-api-v20/llms.txt Gets a list of orders for a specified account, with optional filtering. ```APIDOC ## GET /v3/accounts/{accountID}/orders ### Description Retrieves a list of orders for a given account. Supports filtering by instrument and state. ### Method GET ### Endpoint /v3/accounts/{accountID}/orders ### Parameters #### Path Parameters - **accountID** (string) - Required - The ID of the account whose orders are to be retrieved. #### Query Parameters - **instrument** (string) - Optional - Filter orders by instrument (e.g., "EUR_USD"). - **state** (string) - Optional - Filter orders by their state (e.g., "PENDING", "FILLED", "CANCELLED"). ### Request Example ```bash GET /v3/accounts/101-004-1435156-001/orders?instrument=EUR_USD&state=PENDING ``` ### Response #### Success Response (200) - **orders** (array) - A list of order objects. - **lastTransactionID** (string) - The ID of the last transaction. #### Response Example ```json { "orders": [ { "id": "2503", "instrument": "EUR_USD", "units": "10000", "type": "MARKET", "timeInForce": "FOK", "createTime": "2016-07-21T15:47:04Z", "state": "PENDING" } ], "lastTransactionID": "2504" } ``` ``` -------------------------------- ### GET /v3/accounts Source: https://github.com/hootnot/oanda-api-v20/blob/master/jupyter/accounts.ipynb Retrieves a list of all accounts associated with the provided access token. ```APIDOC ## GET /v3/accounts ### Description Retrieves a list of all accounts belonging to the authenticated user. ### Method GET ### Endpoint /v3/accounts ### Parameters None ### Request Example N/A (No body required) ### Response #### Success Response (200) - **accounts** (array) - A list of account objects containing account IDs and tags. #### Response Example { "accounts": [ { "tags": [], "id": "101-004-1435156-002" }, { "tags": [], "id": "101-004-1435156-001" } ] } ``` -------------------------------- ### Create Market Order Request (Python) Source: https://github.com/hootnot/oanda-api-v20/blob/master/jupyter/orders.ipynb Constructs a MarketOrderRequest object for a LONG position in EUR_USD with specified units, take profit, and stop loss prices. It then prepares an OrderCreate request using this data. The output shows the generated order data and the request details. ```python mktOrder = MarketOrderRequest(instrument="EUR_USD", units=10000, takeProfitOnFill=TakeProfitDetails(price=1.10).data, stopLossOnFill=StopLossDetails(price=1.07).data ).data r = orders.OrderCreate(accountID=accountID, data=mktOrder) print("Request: ", r) print("MarketOrder specs: ", json.dumps(mktOrder, indent=2)) ``` -------------------------------- ### GET /accounts/{accountID}/trades Source: https://github.com/hootnot/oanda-api-v20/blob/master/docs/examples.rst List all open trades for a specific account. ```APIDOC ## GET /accounts/{accountID}/trades ### Description Retrieves a list of all open trades for the specified account. ### Method GET ### Endpoint /accounts/{accountID}/trades ### Parameters #### Path Parameters - **accountID** (string) - Required - The unique identifier of the OANDA account. ### Response #### Success Response (200) - **trades** (array) - A list of trade objects. #### Response Example { "trades": [ { "id": "1234", "instrument": "EUR_USD", "price": "1.1234" } ] } ``` -------------------------------- ### GET /accounts/{accountID}/orders Source: https://github.com/hootnot/oanda-api-v20/blob/master/docs/endpoints/orders/orderlist.rst Retrieves a list of orders for a specified account. ```APIDOC ## GET /accounts/{accountID}/orders ### Description Retrieves a list of orders for the specified account. This endpoint allows users to view all pending orders currently held in the account. ### Method GET ### Endpoint /accounts/{accountID}/orders ### Parameters #### Path Parameters - **accountID** (string) - Required - The identifier of the account to retrieve orders for. #### Query Parameters - **ids** (string) - Optional - List of Order IDs to retrieve. - **state** (string) - Optional - Filter orders by state (e.g., PENDING, FILLED, CANCELLED). - **instrument** (string) - Optional - Filter orders by instrument. ### Request Example GET /v3/accounts/101-001-1234567-001/orders ### Response #### Success Response (200) - **orders** (array) - A list of order objects. #### Response Example { "orders": [ { "id": "100", "instrument": "EUR_USD", "units": "1000", "state": "PENDING" } ] } ``` -------------------------------- ### Create GTD Limit Order - Python Source: https://github.com/hootnot/oanda-api-v20/blob/master/jupyter/orders.ipynb This example shows how to create a Limit Order with a 'Good-Til-Date' (GTD) time in force using the `LimitOrderRequest` helper class. It specifies the instrument, units, time in force, GTD time, and price. The code first prints the order data before sending the request and then prints the API response, which includes the `orderCreateTransaction` details. ```python from oandapyV20.contrib.requests import LimitOrderRequest # make sure GTD_TIME is in the future # also make sure the price condition is not met # and specify GTD_TIME as UTC or local # GTD_TIME="2018-07-02T00:00:00Z" # UTC GTD_TIME="2018-07-02T00:00:00" ordr = LimitOrderRequest(instrument="EUR_USD", units=10000, timeInForce="GTD", gtdTime=GTD_TIME, price=1.08) print(json.dumps(ordr.data, indent=4)) r = orders.OrderCreate(accountID=accountID, data=ordr.data) rv = client.request(r) print(json.dumps(rv, indent=2)) ``` -------------------------------- ### GET /accounts/{accountID}/summary Source: https://github.com/hootnot/oanda-api-v20/blob/master/docs/endpoints/accounts/accountsummary.rst Retrieves the summary of a specific OANDA account. ```APIDOC ## GET /accounts/{accountID}/summary ### Description Retrieves a summary of the specified account, including balance, margin, and open trade information. ### Method GET ### Endpoint /accounts/{accountID}/summary ### Parameters #### Path Parameters - **accountID** (string) - Required - The unique identifier of the OANDA account. ### Request Example GET /v3/accounts/101-004-1234567-001/summary ### Response #### Success Response (200) - **account** (object) - The account summary object containing balance, margin, and position data. #### Response Example { "account": { "id": "101-004-1234567-001", "balance": "10000.00", "marginAvailable": "9000.00", "openTradeCount": 2 } } ``` -------------------------------- ### Create Market Order Source: https://context7.com/hootnot/oanda-api-v20/llms.txt Shows how to construct and submit a market order using the contrib request helpers for simplified order creation. ```python import json import oandapyV20 import oandapyV20.endpoints.orders as orders from oandapyV20.contrib.requests import MarketOrderRequest from oandapyV20.contrib.requests import TakeProfitDetails, StopLossDetails client = oandapyV20.API(access_token="your-access-token") accountID = "101-004-1435156-001" ``` -------------------------------- ### GET /v3/accounts/{accountID} Source: https://github.com/hootnot/oanda-api-v20/blob/master/docs/endpoints/accounts/accountdetails.rst Retrieves the full details for a specific OANDA account. ```APIDOC ## GET /v3/accounts/{accountID} ### Description Fetches the complete details of a specific account, including balance, open positions, and account settings. ### Method GET ### Endpoint /v3/accounts/{accountID} ### Parameters #### Path Parameters - **accountID** (string) - Required - The unique identifier of the OANDA account. ### Request Example GET /v3/accounts/101-001-1234567-001 ### Response #### Success Response (200) - **account** (object) - The account details object containing balance, NAV, and margin information. #### Response Example { "account": { "id": "101-001-1234567-001", "balance": "10000.00", "currency": "USD" } } ``` -------------------------------- ### Create Market Order using contrib.requests (Python) Source: https://github.com/hootnot/oanda-api-v20/blob/master/jupyter/orders.ipynb This snippet demonstrates a more robust and readable way to create a MARKET order using the oandapyV20.contrib.requests module. It utilizes helper classes like MarketOrderRequest, TakeProfitDetails, and StopLossDetails to construct the order body, reducing the likelihood of errors and improving code clarity compared to direct JSON construction. ```python import json import oandapyV20 import oandapyV20.endpoints.orders as orders from oandapyV20.contrib.requests import ( MarketOrderRequest, TakeProfitDetails, StopLossDetails) from exampleauth import exampleauth accountID, access_token = exampleauth.exampleauth() client = oandapyV20.API(access_token=access_token) ``` -------------------------------- ### TradeDetails API Source: https://context7.com/hootnot/oanda-api-v20/llms.txt Gets detailed information for a specific open trade within an account. ```APIDOC ## GET /v3/accounts/{accountID}/trades/{tradeID} ### Description Retrieves detailed information about a specific open trade identified by its ID. ### Method GET ### Endpoint /v3/accounts/{accountID}/trades/{tradeID} ### Parameters #### Path Parameters - **accountID** (string) - Required - The ID of the account. - **tradeID** (string) - Required - The ID of the trade to retrieve. ### Request Example ```bash GET /v3/accounts/101-004-1435156-001/trades/1030 ``` ### Response #### Success Response (200) - **trade** (object) - The trade object containing detailed information. - **lastTransactionID** (string) - The ID of the last transaction. #### Response Example ```json { "trade": { "id": "1030", "instrument": "EUR_USD", "price": "1.08463", "openTime": "2016-07-21T15:47:04Z", "state": "OPEN", "currentUnits": "10000", "unrealizedPL": "23.0000" }, "lastTransactionID": "1040" } ``` ``` -------------------------------- ### GET /accounts/{accountID}/openPositions Source: https://github.com/hootnot/oanda-api-v20/blob/master/docs/endpoints/positions/openpositions.rst Retrieves the list of all open positions for a specific account. ```APIDOC ## GET /accounts/{accountID}/openPositions ### Description Retrieves a list of all open positions for the specified account. This endpoint provides details on current market exposure. ### Method GET ### Endpoint /accounts/{accountID}/openPositions ### Parameters #### Path Parameters - **accountID** (string) - Required - The identifier of the account to retrieve positions for. ### Request Example GET /v3/accounts/101-004-1234567-001/openPositions ### Response #### Success Response (200) - **positions** (array) - A list of open position objects. #### Response Example { "positions": [ { "instrument": "EUR_USD", "long": { "units": "1000" }, "short": { "units": "0" } } ] } ``` -------------------------------- ### Instantiating and Validating PriceValue Source: https://github.com/hootnot/oanda-api-v20/blob/master/docs/oandapyV20.types.rst Demonstrates how to use the PriceValue type to normalize numerical inputs into string representations. It shows that both float and string inputs result in a consistent string value. ```python from oandapyV20.types import PriceValue pv1 = PriceValue(122.345) pv2 = PriceValue("122.345") print(pv1.value) # Output: "122.345" print(pv1.value == pv2.value) # Output: True ``` -------------------------------- ### GET /accounts/{accountID}/positions Source: https://github.com/hootnot/oanda-api-v20/blob/master/docs/endpoints/positions/positionlist.rst Retrieves the list of all open positions for the specified account. ```APIDOC ## GET /accounts/{accountID}/positions ### Description Retrieves a list of all open positions for the specified account. A position is the net sum of all open trades for a specific instrument. ### Method GET ### Endpoint /accounts/{accountID}/positions ### Parameters #### Path Parameters - **accountID** (string) - Required - The identifier of the account to retrieve positions for. ### Request Example GET /v3/accounts/101-001-1234567-001/positions ### Response #### Success Response (200) - **positions** (array) - A list of Position objects. #### Response Example { "positions": [ { "instrument": "EUR_USD", "long": { "units": "1000", "pl": "0.0000" }, "short": { "units": "0", "pl": "0.0000" } } ], "lastTransactionID": "1234" } ```