# How to Use OANDA v20 API with FXMacroData for Macro-Aware FX Execution

Canonical: https://fxmacrodata.com/articles/how-to-use-oanda-v20-api-with-fxmacrodata
Author: FXMacroData
Published: 2026-07-12T11:01:38Z

Use OANDA v20 REST API with FXMacroData by checking macro calendars, announcements, and pair context before submitting automated FX orders.

[OANDA v20 REST API](https://developer.oanda.com/rest-live-v20/introduction/) is a direct route into OANDA's trading engine for account, pricing, order, trade, position, and transaction workflows. FXMacroData fits beside it as the macro-risk layer: release calendars, announcement history,[EUR/USD](/dashboard/EUR_USD) context,[FX sessions](/dashboard/fx-sessions) , and event windows that should be checked before a strategy sends an FX order.

**Quick answer:**use OANDA v20 API for broker-side account, pricing, and order operations. Use FXMacroData REST in your execution service before the OANDA order call, so each candidate order is classified as allow, wait, reduce, or review based on current macro context. Use FXMacroData MCP for research and blocked-order review, not as the live order-control path.

The goal is not to make a broker API predict macro outcomes. The goal is to stop an automated FX workflow from treating every valid signal as equally tradeable. A clean signal on EUR/USD can carry a different risk profile when[US CPI](/united-states/inflation#api-docs) ,[Non-Farm Payrolls](/united-states/non-farm-payrolls#api-docs) , or a[Federal Reserve](/dashboard/press-releases/usd) event is close. FXMacroData gives the execution service the evidence it needs before it decides whether to proceed.

**Fit**

**Use this for**

OANDA practice or live-account automation that needs a macro checkpoint before order submission.

**OANDA works best when**

It handles broker connectivity while your service owns macro policy, credentials, audit logs, and final decision rules.

**Avoid**

Letting a model, notebook, or webhook submit live orders without a deterministic macro and risk gate.

## Why OANDA v20 Fits Macro Gates

OANDA's documentation describes the v20 REST API as programmatic access to its trading engine for users with a v20 trading account. The visible API surface includes account, order, trade, position, transaction, and pricing endpoints, plus streaming pricing and transaction workflows. The development guide also separates the practice host from the live host, which makes practice-first testing a natural default.

That shape is useful for a macro gate. OANDA can handle the broker-facing side of the workflow. FXMacroData can answer whether a currency pair is near a known macro event, whether the release calendar is active, and whether the signal should be allowed, delayed, reduced, or sent for review.

## What Changes for the Trader

The change is auditability. A strategy should not only record that it produced a long or short signal. It should also record whether that signal was allowed to reach the broker, and what macro evidence affected the decision.

**Trading desk scenario**

A model proposes a EUR/USD market order during the hour before US[inflation](/indicators/inflation) data. The execution service queries the FXMacroData[release calendar](/dashboard/release-calendar) , sees an active[USD](/united-states) macro window, and marks the OANDA order candidate as`wait`. The system records the blocked ticket, event reason, and intended units so the trader can evaluate the rule later.

This approach keeps the workflow honest. The broker API is not asked to understand macro context, and the macro data layer is not asked to manage broker accounts. The application between them owns the decision.

## Workflow Shape

**1. Signal**

A strategy, alert receiver, or analyst workflow creates an order candidate.

**2. Context**

The service fetches FXMacroData calendar, announcement, and pair context.

**3. Gate**

Policy decides whether the candidate is allow, wait, reduce, or review.

**4. Submit**

Only approved tickets are submitted to the OANDA v20 order endpoint.

**5. Review**

Blocked and allowed tickets are measured against later trade outcomes.

## Where Each Layer Belongs

Layer Use it for Do not use it for**OANDA v20 REST API**Broker account, pricing, order, trade, position, and transaction workflows. Deciding macro-event truth or storing FXMacroData credentials.**FXMacroData REST**Production macro checks against calendars, announcements, FX pair context, and sessions. Broker-side order submission or account management.**FXMacroData MCP**Research assistant workflows, blocked-order review, and code-support tasks. Real-time order routing or broker authorization.**Execution service**Policy, secrets, retries, logging, and final allow/review decisions. Unlogged discretionary behavior hidden inside a notebook or prompt.

## Prerequisites

- An OANDA v20 account and API access configured in the account portal.

- A personal access token stored securely and passed to OANDA as a bearer token.

- A practice environment for first implementation and regression testing.

- An FXMacroData API key held server-side and sent in the`X-API-Key`header in examples.

- A written policy for which events, sessions, currency pairs, and missing-data states should block or review orders.

## Step 1: Separate Practice and Live Environments

OANDA documents separate hosts for practice and live trading. Use the practice host while building the macro gate. The execution service should require an explicit environment setting so tests cannot accidentally drift into live order submission.

```
# OANDA broker API examples use bearer-token auth.
export OANDA_ROOT="https://api-fxpractice.oanda.com"
export OANDA_ACCOUNT_ID="YOUR_OANDA_ACCOUNT_ID"
export OANDA_TOKEN="YOUR_OANDA_TOKEN"

curl -H "Authorization: Bearer $OANDA_TOKEN" \
  "$OANDA_ROOT/v3/accounts"
```

Keep OANDA credentials separate from FXMacroData credentials. The broker token should only be available to the process that is allowed to submit or inspect broker-side resources.

## Step 2: Define the Macro Execution Policy

Start with a compact policy that a trader can inspect. The first version should focus on one pair and one macro currency, then expand after the team can measure the behavior of blocked and allowed tickets.

```
pair: EUR_USD
macro_currency: USD
block_before_minutes: 30
block_after_minutes: 10
events:
  - inflation
  - non_farm_payrolls
  - policy_rate
missing_data_decision: review
```

The output should be a reasoned decision, not a silent boolean. A ticket marked`review`because data is unavailable should be different from a ticket marked`wait`because a scheduled release is close.

## Step 3: Fetch FXMacroData Context

Fetch macro context before creating the OANDA order request. Keep the first version narrow: calendar rows, the relevant announcement family, and current pair context.

```
curl -H "X-API-Key: YOUR_API_KEY" "https://api.fxmacrodata.com/v1/calendar/usd"

curl -H "X-API-Key: YOUR_API_KEY" "https://api.fxmacrodata.com/v1/announcements/usd/inflation"

curl -H "X-API-Key: YOUR_API_KEY" "https://api.fxmacrodata.com/v1/forex/eur/usd"
```

In code, normalize OANDA's instrument format, such as`EUR_USD`, into the pair and macro currency that your policy understands.

```
import os
import requests

FXMD_ROOT = "https://api.fxmacrodata.com"
FXMD_API_KEY = os.environ["FXMD_API_KEY"]

def fxmd_get(path):
    response = requests.get(
        f"{FXMD_ROOT}{path}",
        headers={"X-API-Key": FXMD_API_KEY},
        timeout=5,
    )
    response.raise_for_status()
    return response.json()

def macro_context_for_eurusd():
    return {
        "calendar": fxmd_get("/v1/calendar/usd"),
        "inflation": fxmd_get("/v1/announcements/usd/inflation"),
        "spot": fxmd_get("/v1/forex/eur/usd"),
    }
```

## Step 4: Gate the OANDA Order Candidate

The gate should run before the OANDA order payload is sent. Own the decision in ordinary code so it can be tested, logged, and reviewed by a trader.

```
def decide_candidate(context, policy):
    if macro_data_missing(context):
        return {"decision": "review", "reason": "Macro data unavailable"}
    if has_blocked_event(context["calendar"], policy):
        return {"decision": "wait", "reason": "Blocked USD macro window"}
    return {"decision": "allow", "reason": "No blocked macro window"}

candidate = {"instrument": "EUR_USD", "units": "1000"}
decision = decide_candidate(macro_context_for_eurusd(), policy)
```

**Example decision output**

```
{
  "instrument": "EUR_USD",
  "units": "1000",
  "decision": "wait",
  "reason": "Blocked USD macro window",
  "checked_paths": [
    "/v1/calendar/usd",
    "/v1/announcements/usd/inflation"
  ]
}
```

## Step 5: Submit Only Approved Orders

Only build and submit the OANDA order request when the macro decision allows it. The example below uses a practice host and placeholders. Keep live order submission behind separate deployment, risk, and account controls.

```
if [ "$DECISION" = "allow" ]; then
  curl -X POST "$OANDA_ROOT/v3/accounts/$OANDA_ACCOUNT_ID/orders" \
    -H "Authorization: Bearer $OANDA_TOKEN" \
    -H "Content-Type: application/json" \
    -d '{
      "order": {
        "type": "MARKET",
        "instrument": "EUR_USD",
        "units": "1000",
        "timeInForce": "FOK",
        "positionFill": "DEFAULT"
      }
    }'
fi
```

For every allowed order, record the OANDA transaction or order identifiers together with the FXMacroData context that permitted the submission. For every blocked candidate, record enough detail to backtest whether the filter helped.

Metric Why it matters Review cadence**Allowed versus reviewed orders**Shows whether the gate changes behavior often enough to matter. Daily.**Post-release slippage**Shows whether the release window is too wide or too narrow. After major events.**Manual override rate**Reveals whether traders trust the macro policy. Weekly.**Missing-data reviews**Prevents silent trading when macro context is incomplete. Every run.

## Optional MCP Research Layer

Use[FXMacroData MCP](/documentation/mcp-server) at`https://mcp.fxmacrodata.com`when a compatible assistant should inspect blocked orders, explain macro windows, or help draft policy tests. Keep the live order gate on REST and deterministic code.

```
{
  "servers": {
    "FXMacroData": {
      "type": "http",
      "url": "https://mcp.fxmacrodata.com",
      "headers": {"Authorization": "Bearer YOUR_API_KEY"}
    }
  }
}
```

A useful assistant prompt is narrow: "Review yesterday's EUR/USD OANDA order candidates marked wait, identify the macro events involved, and compare them with allowed tickets outside the release window." That keeps the model in review mode, not execution control.

## Operational Guardrails

**Minimum controls**

- Use the OANDA practice environment before any live-account workflow.

- Store OANDA bearer tokens and FXMacroData API keys server-side.

- Fail to review, not allow, when macro data cannot be fetched.

- Separate signal generation from order submission.

- Record the macro decision, source paths, and broker order response for every approved order.

- Keep AI assistants out of the live order-submission path.

**Related guides**

- [Interactive Brokers TWS API with FXMacroData](/articles/how-to-use-interactive-brokers-tws-api-with-fxmacrodata)

- [TradingView alerts with FXMacroData](/articles/how-to-use-tradingview-alerts-with-fxmacrodata)

- [MetaTrader 5 Python with FXMacroData](/articles/how-to-use-metatrader-5-python-with-fxmacrodata)

- [FXMacroData API reference](/documentation/reference)

**Sources**

- [OANDA v20 REST API introduction](https://developer.oanda.com/rest-live-v20/introduction/)

- [OANDA v20 development guide](https://developer.oanda.com/rest-live-v20/development-guide/)

- [OANDA v20 authentication documentation](https://developer.oanda.com/rest-live-v20/authentication/)

- [OANDA v20 order endpoints](https://developer.oanda.com/rest-live-v20/order-ep/)

- [OANDA v20 pricing endpoints](https://developer.oanda.com/rest-live-v20/pricing-ep/)

- [OANDA API comparison](https://developer.oanda.com/rest-live-v20/api-comparison/)

- [FXMacroData production OpenAPI schema](https://api.fxmacrodata.com/openapi.json)

- [FXMacroData MCP documentation](https://fxmacrodata.com/documentation/mcp-server)

Source: FXMacroData
