OANDA REST API Forex Trading with Python: From First Request to a Working Bot
OANDA's v20 REST API lets you trade forex from Python with plain HTTPS requests: generate a personal access token, send it as a Bearer header to the practice or live endpoint, then call endpoints for accounts, candles, prices, orders and trades. A few dozen lines of Python using the requests library are enough to pull hourly candles for EUR_USD and place a market order with a stop-loss attached. The harder parts are sizing correctly for your account currency, handling errors and restarts, and respecting the rules of the OANDA entity you are a client of in the US, Canada or UK.
Key takeaways
- Use the practice host (api-fxpractice.oanda.com) until your code is proven; the live host is api-fxtrade.oanda.com and streaming uses separate stream hosts.
- Instruments are written with an underscore (EUR_USD), sizes are in units, and positive units buy while negative units sell.
- Prices and units are sent and returned as strings, so convert carefully and format prices to the instrument's precision.
- Attach stops at entry with stopLossOnFill, and tag orders with clientExtensions so retries can be recognised.
- US accounts follow FIFO and no-hedging rules with 50:1 on majors; UK retail is capped at 30:1; Canadian margin follows CIRO rules.
Before you write any code
You need an OANDA account with v20 API access. Open a free practice (demo) account first; it has its own token and account IDs and behaves like a live account with simulated money. In the account management area of OANDA's website, generate a personal access token for the API. Treat it like a password: anyone with it can trade your account. Store it in an environment variable, never in your source code or a public repository.
Which OANDA entity you sign up with depends on where you live, and that decides the rules your code must follow. US residents are served by OANDA's US entity, registered with the CFTC and an NFA member. Canadian residents are served by OANDA's Canadian entity, regulated under CIRO. UK residents are served by an FCA-authorised entity. Our OANDA review and comparison of OANDA versus FOREX.com cover the broker itself; confirm current account terms on OANDA's official site.
Endpoints and authentication
| Purpose | Practice | Live |
|---|---|---|
| REST requests | https://api-fxpractice.oanda.com | https://api-fxtrade.oanda.com |
| Price and transaction streams | https://stream-fxpractice.oanda.com | https://stream-fxtrade.oanda.com |
Every request carries two headers: Authorization: Bearer YOUR_TOKEN and Content-Type: application/json. A minimal set-up in Python:
import os, requests
BASE = "https://api-fxpractice.oanda.com/v3"
S = requests.Session()
S.headers.update({"Authorization": f"Bearer {os.environ['OANDA_TOKEN']}", "Content-Type": "application/json"})
accounts = S.get(f"{BASE}/accounts", timeout=10).json()["accounts"]
The response lists your account IDs. Pick the one you will trade and fetch its summary from /v3/accounts/{id}/summary, which returns balance, NAV, margin used, margin available and open trade count. Using a Session reuses the connection, which is faster and gentler on OANDA's rate limits. OANDA documents limits on requests per second and on new connections; check the current figures in the developer documentation and design to stay well inside them.
Getting candles and prices
Historical bars come from the instrument candles endpoint:
params = {"granularity": "H1", "count": 500, "price": "M"}
r = S.get(f"{BASE}/instruments/EUR_USD/candles", params=params, timeout=10)
candles = [c for c in r.json()["candles"] if c["complete"]]
Granularity codes include S5, M1, M5, M15, H1, H4, D and W. The price parameter chooses mid ("M"), bid ("B"), ask ("A") or a combination such as "BA". For signal calculation, mid prices are fine; for realistic backtesting of fills, use bid and ask, because a buy fills at the ask and a sell at the bid. If you are unsure why that matters, see our explainer on reading bid and ask quotes.
Two details catch people out. First, OHLC values arrive as strings such as "1.08512" and must be converted to floats (or Decimals) before calculation. Second, the latest candle is usually still forming; its complete flag is false. Acting on an incomplete candle in live trading, when your backtest used only completed candles, is a classic way to make live results differ from tests. A single request returns a limited number of candles, so for long histories you page through using from and to timestamps.
For the current quote, call /v3/accounts/{id}/pricing?instruments=EUR_USD,USD_JPY. For continuous prices, open the streaming endpoint /v3/accounts/{id}/pricing/stream on the stream host with stream=True in requests; it sends price lines and periodic heartbeat messages. If heartbeats stop arriving, assume the connection is dead and reconnect.
Placing a market order with a stop-loss
Orders are created by POSTing to /v3/accounts/{id}/orders. A market buy of 10,000 units of EUR/USD with a stop and target attached:
order = {"order": {"type": "MARKET", "instrument": "EUR_USD", "units": "10000", "timeInForce": "FOK", "positionFill": "DEFAULT", "stopLossOnFill": {"price": "1.08150"}, "takeProfitOnFill": {"price": "1.09050"}, "clientExtensions": {"id": "bot-240-0001", "tag": "breakout"}}}
r = S.post(f"{BASE}/accounts/{ACCOUNT_ID}/orders", json=order, timeout=10)
A successful market order returns HTTP 201 with an orderFillTransaction describing the fill price and the trade opened. If the order is rejected or cancelled, for example because the stop is on the wrong side of the price or margin is insufficient, the response contains a cancel or reject transaction with a reason. Always inspect it; a 201 status alone does not guarantee a fill.
Points to get right:
- Units sign. "10000" buys; "-10000" sells. There are no separate buy and sell order types.
- Price precision. EUR/USD prices use five decimal places, USD/JPY three. Format with the instrument's display precision (available from the account instruments endpoint) or the order may be rejected.
- Stops at entry.
stopLossOnFillmeans the protective stop exists the moment the trade does. Sending the stop in a second request leaves a window where a disconnect leaves you unprotected. Adistancefield can be used instead of an absolute price. - Client IDs.
clientExtensionslets you tag orders and trades with your own identifiers, which is how a restarted bot can recognise its own positions and avoid duplicating them after a timeout.
To manage open positions, list them from /v3/accounts/{id}/openTrades, close a specific trade with a PUT to /v3/accounts/{id}/trades/{tradeID}/close, or modify its stop through the trade orders endpoint. On a US account, closing must respect FIFO, so closing the oldest trade in an instrument first is not optional.
Sizing for your account currency: worked examples
OANDA sizes in units, which makes risk-based sizing straightforward once you know the pip value per unit in your account currency.
USD account, EUR/USD
Equity $8,000, risk 1% = $80, stop 40 pips. Pip size 0.0001, quote currency USD, so pip value per unit is $0.0001. Units = 80 ÷ (40 × 0.0001) = 20,000 units. Margin at the US 50:1 cap: 20,000 × 1.0850 ÷ 50 = $434.
CAD account, EUR/USD
Equity C$15,000, risk 0.75% = C$112.50, stop 25 pips. Pip value per unit is $0.0001, converted at USD/CAD 1.3700 = C$0.000137. Units = 112.50 ÷ (25 × 0.000137) = 32,846, rounded down to 32,800 units.
GBP account, USD/JPY
Equity £10,000, risk 1% = £100, stop 30 pips. Pip size 0.01 yen. At USD/JPY 150.00 and GBP/USD 1.2700, one yen is worth 1 ÷ (150 × 1.27) = £0.00525, so pip value per unit is 0.01 × 0.00525 = £0.0000525. Units = 100 ÷ (30 × 0.0000525) = 63,492, rounded down to 63,400 units. Margin at the UK 30:1 cap: 63,400 USD notional ÷ 30 = $2,113, about £1,664.
Fetch the conversion rates live from the pricing endpoint rather than hard-coding them, and cap the result with a maximum units setting in case of a bad price.
Most important risk point: an API bot can open real positions in milliseconds, and the same speed applies to its mistakes. Retrying a request that timed out but actually filled, using a live token in testing, or mis-signing units can open unintended exposure. Leverage magnifies losses, and most retail forex and CFD accounts lose money. Develop on the practice host, attach stops at entry, cap units in code, keep the token out of your source, and reconcile with openTrades before any retry.
Rules by country: USA, Canada and UK
| Region | Regulatory framework | Leverage for retail | What your code must respect |
|---|---|---|---|
| USA | CFTC registration, NFA membership | Up to 50:1 on major pairs, 20:1 on others | FIFO closing; no simultaneous long and short in the same pair; no CFDs |
| Canada | CIRO (formerly IIROC) rules | Set by CIRO margin requirements and the broker's schedule | Check OANDA Canada's current margin rates and product list |
| UK | FCA authorisation | 30:1 on majors, lower on minors and other assets | 50% margin close-out; negative balance protection |
For US accounts, the API returns an error if you try to open an opposing position in an instrument where you already hold one, and orders are reduced FIFO. Design your strategy to hold one net position per instrument. Canadian traders can read our guide to CIRO-regulated brokers, and US traders the list of CFTC-regulated brokers.
From script to dependable bot
A working order script is not yet a bot you can leave running. The gap is mostly operational:
- Scheduling. Run the strategy when a candle completes, using UTC throughout, rather than polling in a tight loop.
- Reconciliation. On start-up and periodically, compare your local record of trades with
openTradesand resolve differences before acting. - Error handling. Distinguish client errors (bad request, invalid price precision) that should not be retried from transient errors (timeouts, server errors) that can be, after checking whether the order went through.
- Transaction stream. Subscribe to the account transactions stream to learn immediately when a stop-loss or take-profit fills.
- Hosting. Run on an always-on server rather than a laptop; our comparison of forex VPS hosting covers options. Python on Linux works fine with this API.
- Testing. Backtest with bid/ask candles and realistic slippage, then walk-forward test before running the strategy on practice for several weeks.
Community Python wrappers for the v20 API exist and can save boilerplate, but plain requests keeps you close to the documentation and makes debugging easier. For a broader look at other brokers' APIs, see our guide to Python forex trading bot APIs.
Frequently asked questions
Is the OANDA API free to use?
OANDA has historically provided v20 API access to account holders without a separate API fee, with normal trading costs (spreads and any commission) applying to trades. Practice accounts can also use the API. Terms can change and some features or account types may have conditions, so confirm the current position on OANDA's developer pages and in your account agreement.
What is the difference between the OANDA practice and live API?
They use separate hosts, separate tokens and separate account IDs. Practice is api-fxpractice.oanda.com with simulated money; live is api-fxtrade.oanda.com with real money. The request formats are the same, so code can switch by changing the base URL and token. Keep them in separate configuration files to avoid accidentally sending test orders to a live account.
Why is my OANDA API order rejected?
Common reasons are a price formatted with too many decimal places, a stop-loss on the wrong side of the current price, insufficient margin, an instrument not available to your account, or, on US accounts, an attempt to open a position opposite one you already hold. Read the reject or cancel transaction in the response, which includes a reason code.
Can I hedge with the OANDA API in the US?
No. US accounts follow NFA rules that prohibit holding simultaneous long and short positions in the same currency pair in one account and require positions to be closed first-in, first-out. The API enforces these rules for US clients. Accounts with OANDA's non-US entities may support different position modes, depending on the entity's terms.
How many candles can I download from the OANDA API at once?
Each candles request returns a limited number of bars, with a documented maximum per request. For longer histories, page through the data using from and to timestamps, respecting rate limits between calls. Store downloaded data locally so you do not re-request it repeatedly, and check for gaps around weekends and holidays.
Should I use mid, bid or ask prices for backtesting?
Use mid prices for indicator calculation if your live strategy does the same, but simulate fills with bid and ask: buys fill at the ask, sells at the bid, and stop-losses on longs trigger on the bid. Backtesting fills on mid prices understates costs by roughly half the spread on every entry and exit, which can make short-term strategies look profitable when they are not.
This article is general information, not personal financial advice. Figures such as spreads, fees, leverage and rules change; confirm them with the provider and check the provider is authorised for your country of residence.