How to Pause a Python Trading Bot Around NFP and CPI

To pause a Python trading bot around NFP, CPI and other high-impact news, load the release schedule for your currency pair, then check it before every new entry and hold off inside a window around each release. One Finance Calendar request returns the high-impact releases and central bank decisions for both currencies in a pair, with every release time in UTC. This guide gives you a complete filter in about 60 lines of Python.

Contents

You need Python 3.9 or later, the requests package and a Finance Calendar API key in the FC_API_KEY environment variable. Pair requests work on every paid plan, including Starter.

The one request you need

GET https://www.financecalendar.com/wp-json/fc/v1/calendar?pair=EURUSD&impact=high
X-API-Key: YOUR_KEY

For EURUSD this returns euro area, German, French, Italian, Spanish and United States releases in one list, soonest first, from today to 14 days ahead. Use pair=XAUUSD for gold, or currency=USD,EUR,GBP to follow several currencies at once. Each event looks like this, shortened to the fields the filter reads:

{
  "name": "Eurozone Flash CPI",
  "country": "EU",
  "impact": "high",
  "date": "2026-12-01",
  "release_at_utc": "2026-12-01T10:00:00+00:00",
  "time_precision": "minute",
  "status": "confirmed",
  "consensus": "3.9",
  "prior": "4",
  "actual": null,
  "source_name": "Eurostat"
}

That is a real record from 1 December 2026. The US jobs report (NFP), US CPI, FOMC decisions, ECB decisions and the other market-moving releases arrive in the same shape.

The filter

Save this as news_filter.py. It refreshes the schedule every 15 minutes, which is 96 requests a day and fits inside Starter, and answers one question: can the bot open a new trade right now?

import os
import time
from datetime import datetime, timedelta, timezone

import requests

API = "https://www.financecalendar.com/wp-json/fc/v1/calendar"
KEY = os.environ["FC_API_KEY"]
PAIR = "EURUSD"                    # XAUUSD for gold
BEFORE = timedelta(minutes=30)
AFTER = timedelta(minutes=30)
REFRESH_SECONDS = 15 * 60          # 96 requests a day
MAX_AGE_SECONDS = 26 * 60 * 60     # stand aside if the schedule is older

_events = []
_loaded_at = 0.0


def refresh_calendar():
    """Load the high-impact releases for both currencies in the pair."""
    global _events, _loaded_at
    response = requests.get(
        API,
        params={"pair": PAIR, "impact": "high", "limit": 50},
        headers={"X-API-Key": KEY},
        timeout=10,
    )
    response.raise_for_status()
    events = response.json()["events"]
    _events = [e for e in events if e.get("status") != "cancelled"]
    _loaded_at = time.time()


def news_state(now=None):
    """Return ("blocked", name), ("clear", None) or ("unknown", reason)."""
    now = now or datetime.now(timezone.utc)
    if time.time() - _loaded_at > MAX_AGE_SECONDS:
        return "unknown", "no recent schedule loaded"
    for event in _events:
        release = event.get("release_at_utc")
        if release is None:
            if event["date"] == now.date().isoformat():
                return "unknown", event["name"] + " has no published time"
            continue
        at = datetime.fromisoformat(release.replace("Z", "+00:00"))
        if at - BEFORE <= now <= at + AFTER:
            return "blocked", event["name"]
    return "clear", None


def run(open_trade_if_signal):
    """Your bot's loop: refresh on a timer, ask before each new entry."""
    while True:
        if time.time() - _loaded_at > REFRESH_SECONDS:
            try:
                refresh_calendar()
            except requests.RequestException as error:
                print("calendar refresh failed:", error)
        state, detail = news_state()
        if state == "clear":
            open_trade_if_signal()
        else:
            print("holding new entries:", state, detail)
        time.sleep(60)

What each answer means

  • blocked: the current time is inside the window around a release. The second value is the release name, ready for your log.
  • clear: no high-impact release for either currency is within the window.
  • unknown: the bot has no schedule from the last 26 hours, or a release today has a date but no published time. The safe choice is to hold new entries, which is what the loop does.

Cancelled releases are dropped when the schedule loads. A failed refresh keeps the last good schedule, so a short network fault does not stop the bot or switch the filter off.

Choose your window

BEFORE and AFTER set the minutes either side of each release. Thirty either side is a common starting point. Widen AFTER if your strategy is sensitive to spreads, which can stay wide for some minutes after a major release. To include medium-impact releases, send impact=high,medium.

Use it in your bot

from news_filter import refresh_calendar, news_state

refresh_calendar()
state, detail = news_state()
if state == "clear":
    place_order()          # your own entry logic
else:
    print("holding new entries:", state, detail)

The filter only decides whether a new entry is allowed. What to do with open positions around a release is your strategy’s decision.

Trade the result, not only the clock

The same response carries the consensus forecast and the previous figure before each release, and the actual figure after it, for 60 measures across 10 economies. A bot can compare actual with consensus to size the surprise and decide whether to re-enter, which a schedule-only calendar cannot support.

One call instead of a loop

Build and Scale add a route that does the window check on the server. It answers blocked, clear or unknown for the current moment, lists the releases inside the window and gives the next release:

GET https://www.financecalendar.com/wp-json/fc/v1/news-window?pair=EURUSD&before=30&after=30

Related guides

Free and Starter at a glance

Starter is US$4.99/month or US$53.89/year with 250 requests per UTC day and 5,000 per UTC calendar month for consensus across 10 economies, results and history, wider dates and integration tools. Ongoing Free Developer provides 100 successful schedule JSON responses per UTC calendar month, up to 10 per UTC day, with 1 active key issued after approval of your request. Its allowance renews monthly; no card or automatic paid conversion.

Free-to-Starter integration details

Starter adds recorded figures, history, wider dates and paid integration tools. Keep your existing active API key linked to the same verified account when paid access is confirmed. Free Developer and paid access use different JSON response schemas: Free returns compact schedules and omits numerical fields; paid access adds richer event fields and endpoint-specific responses. Use the documented paid response model when adding these features, including the different /today envelope. Compare Free and paid response models.

Compare current plans · Current machine-readable prices and allowances.

About Finance Calendar

Economic release schedules, market calendars and practical guides to using the data.

About the site
Back to Resources

Keep reading

All articles

From Resources

From Resources

From Resources