Why pair OpenAI Codex with FXMacroData
OpenAI Codex is OpenAI's coding agent — available as a terminal CLI and as a cloud agent inside ChatGPT. It is designed to plan, write and execute code on your behalf, which is a very different workflow from a chat box. Once you give it a goal, it can run shell commands, edit files, call APIs and verify its own work in a loop.
That makes it a natural front-end for systematic FX research. Instead of writing every data-pull, every join, every chart and every backtest yourself, you describe what you want — "compare the last twelve USD inflation prints to consensus and tell me where the surprise was largest" — and Codex assembles the script. The only thing missing is the data.
FXMacroData fills that gap with a clean REST API plus a hosted MCP server. Codex can either call the API directly from scripts it writes, or speak to FXMacroData as a native MCP tool with no glue code at all. This guide walks through both paths and shows a realistic FX trading workflow at the end.
Prerequisites
- An OpenAI account with API access, and the Codex CLI installed (
npm install -g @openai/codexor the platform installer). - Node.js 18+ on your machine (only needed for the MCP bridge step).
- An FXMacroData API key from the API management page. USD data is free; multi-currency coverage requires a paid plan.
- A working Python environment if you want to run the example backtests Codex produces.
Two ways to wire Codex to FXMacroData
You have a choice of integration model, and they are not mutually exclusive:
- Direct REST API — Codex writes Python (or Node, Go, R) that calls FXMacroData endpoints. Best when you want reproducible scripts checked into a repo.
- MCP server — Codex talks to FXMacroData as a tool. Best when you want fast, conversational lookups and ad-hoc analysis without scaffolding a project.
Most quant workflows end up using both: MCP for exploration, REST for the production script.
Option 1: Use Codex with the REST API
This is the simplest path. You hand Codex your API key in the working environment, point it at the docs, and let it generate scripts that call the endpoints directly.
Step 1. Export your API key once per session
export FXMD_API_KEY="YOUR_API_KEY"
Putting it in the environment (rather than pasting it into chat) keeps the key out of Codex's context window and out of any code it commits.
Step 2. Start a Codex session in your project
codex
Then prompt the agent with the task and the endpoint contract it should use. A prompt that works well in practice:
Write a Python script that pulls the last 24 USD inflation announcements
from the FXMacroData REST API, joins each release to the matching
consensus forecast from the predictions endpoint, computes the surprise
in basis points, and prints the five largest absolute surprises with
their announcement_datetime.
API base: https://fxmacrodata.com/api/v1
Auth: query param ?api_key=$FXMD_API_KEY
Endpoints to use:
/announcements/usd/inflation
/predictions/usd/inflation
Use the `requests` library. Read the API key from FXMD_API_KEY.
Codex will draft the script, run it in your shell, read the output, and iterate if the response shape surprises it. A reasonable first iteration looks like this:
import os
import requests
API = "https://fxmacrodata.com/api/v1"
KEY = os.environ["FXMD_API_KEY"]
def get(path):
r = requests.get(f"{API}{path}", params={"api_key": KEY}, timeout=15)
r.raise_for_status()
return r.json()
actuals = get("/announcements/usd/inflation")["data"][-24:]
forecasts = {
g["announcement_id"]: g["predictions"]
for g in get("/predictions/usd/inflation")["data"]
}
surprises = []
for a in actuals:
preds = forecasts.get(a["announcement_id"], [])
consensus = next(
(p["predicted_value"] for p in preds
if p["prediction_type"] == "market_consensus"),
None,
)
if consensus is None or a.get("value") is None:
continue
surprises.append({
"datetime": a["announcement_datetime"],
"actual": a["value"],
"consensus": consensus,
"surprise_bps": round((a["value"] - consensus) * 100, 1),
})
surprises.sort(key=lambda r: abs(r["surprise_bps"]), reverse=True)
for row in surprises[:5]:
print(row)
Two things to notice. First, Codex picks up the announcement_id join key from the docs and uses it correctly — you do not need to explain it. Second, the script is reproducible: the same prompt and the same data return the same five rows, so you can commit it.
Step 3. Let Codex extend the script
Once a small script works, you can ask Codex to grow it. Useful next prompts:
- "Plot the actual vs consensus series with matplotlib and save to
cpi_surprise.png." - "Fetch USD/JPY spot from
/forex/USDJPYand overlay a 60-minute return after each release datetime." - "Add a CLI flag so I can swap inflation for non-farm payrolls or policy rate without editing the file."
Because Codex is a coding agent rather than a chatbot, each of those becomes a real diff against the script — usually in a single turn.
Option 2: Connect Codex to the FXMacroData MCP server
The Codex CLI supports the Model Context Protocol, so it can call FXMacroData as a first-class tool. With MCP wired in, you skip the "write a script that calls the API" step entirely for ad-hoc questions — the agent calls indicator_query, release_calendar, cot_data, commodities and forex directly.
Step 1. Add the FXMacroData server to your Codex config
Codex reads MCP server definitions from ~/.codex/config.toml. Open that file and add an entry for FXMacroData. The hosted MCP server is a remote HTTP endpoint, so we bridge it to stdio with the standard mcp-remote helper:
[mcp_servers.fxmacrodata]
command = "npx"
args = [
"-y",
"mcp-remote",
"https://fxmacrodata.com/mcp?api_key=YOUR_API_KEY"
]
If you want OAuth instead of a query-param key, point mcp-remote at the bare URL https://fxmacrodata.com/mcp and complete the browser-based login flow the first time the server starts.
Step 2. Verify the tools load
Restart Codex and ask it to list its tools:
What MCP tools do you have available?
You should see the FXMacroData tools alongside the built-ins:
data_catalogue— list every supported currency and indicator.indicator_query— pull announcement time series for a currency + indicator pair.release_calendar— upcoming scheduled releases for a currency.cot_data— CFTC Commitment of Traders positioning.commodities— gold, silver, platinum prices.forex— current spot rates for FX pairs.indicator_visual_artifact— generate a chart of any indicator.market_sessions— current state of the four FX sessions.
Step 3. Ask in natural language
The point of MCP is that prompts get shorter. Once the server is loaded, this works:
Pull the last 12 EUR policy rate decisions and the last 12 USD policy
rate decisions, and tell me whether the ECB-Fed differential is widening
or narrowing right now. Then show me the current EUR/USD spot.
Codex will call indicator_query twice for the European Central Bank and Federal Reserve rate series, then forex for EUR/USD, and answer in one turn — no scripting required.
Practical example: building a release-driven trade scanner
Here is a realistic prompt that uses both integration paths. The goal is a small scanner that runs before the London open and flags pairs with a high-impact release due in the next 24 hours, plus the prevailing positioning bias.
Build a Python module called release_scanner.py that:
1. Pulls the upcoming 24 hours of releases for USD, EUR, GBP, JPY, AUD,
CAD and CHF from /api/v1/calendar/{currency}.
2. Filters to releases tagged high impact.
3. For each release, looks up the most recent CFTC positioning for the
corresponding currency from /api/v1/cot/{currency} and reports net
non-commercial position and weekly change.
4. Prints a markdown table sorted by release datetime with columns:
datetime, currency, indicator, consensus, prior, net positioning,
weekly change.
Use FXMDAPIKEY from the environment. Use requests. Add type hints.
Codex generates the module, runs it, and prints something like:
| datetime (UTC) | ccy | indicator | consensus | prior | net pos | wk Δ |
|---------------------|-----|------------------|-----------|-------|------------|---------|
| 2026-05-21 12:30:00 | USD | non_farm_payrolls| 185k | 175k | +120,430 | +8,210 |
| 2026-05-21 06:00:00 | GBP | inflation | 3.2% | 3.4% | -42,180 | -2,940 |
| 2026-05-21 01:30:00 | AUD | unemployment | 4.1% | 4.1% | -68,920 | -5,110 |
Now you can fold in MCP for the interactive layer. Drop into a Codex session and ask:
From the release_scanner.py output, which release is the most asymmetric
trade if it surprises in the consensus direction? Use COT positioning,
the indicator's average surprise impact on the matching pair (use
/announcements and join to /forex spot at announcement_datetime), and
suggest the cleanest pair to express it.
Codex will call FXMacroData via MCP for the joins, run the analysis, and produce a one-paragraph thesis with the supporting numbers. That is the workflow loop: scripts for reproducibility, MCP for thinking.
Tips for getting good output
- Pin the endpoint paths in your prompt. Codex hallucinates less when you list the exact routes it should call.
- Keep API keys in the environment. Never paste a key into the chat; Codex will happily commit it to a file otherwise.
- Use
announcement_idfor every join. It is the stable key that links actuals, forecasts and revisions across endpoints. - Let Codex verify against the API itself. If you are unsure about a field name, end your prompt with "first call the endpoint with a small range and print the JSON, then build the parser" — the agent's run-loop will use the live schema rather than guessing.
- Reach for MCP for exploration, REST for production. MCP is wonderful when you are thinking; once you know what you want, ask Codex to commit it as a script.
Wrapping up
With one TOML entry and an API key in the environment, OpenAI Codex becomes a competent FX research assistant. It can pull live policy rates, inflation prints, COT positioning, spot rates and commodities, and it can write — and then refactor — the Python that ties them into a trading workflow.
From here, sensible next steps are: hook the same MCP server into Claude or Cursor so different agents share the same data surface, schedule the release scanner with cron or a workflow runner, and add the predictions endpoint so Codex can reason about surprise rather than just the print itself.