Stale Market Data in Trading Bots: Detect It and Pause Orders

Live trading code should check every price before it uses it: is it live or delayed, when did it last change, is it plausible, and which exchange rate and timestamp belong to it? If a check fails, the sensible default is to block new orders that add risk and to alert a person, not to keep trading on the last known value. Interactive Brokers shows why this matters: according to its API documentation, free delayed data runs 15 to 20 minutes behind the market and arrives with its own tick types, so code that ignores the market data type can mistake a delayed quote for a live one. This guide covers delayed versus real-time data and subscriptions at IBKR, how to tell a quiet market from a dead feed, gaps and outliers, FX rates with timestamps, and what the code should do when data fails, with a tested Python check (as of November 2026).

What stale, delayed and missing prices look like in trading code

Bad data does not need to crash a trading bot to do damage. The bot keeps running and decides with numbers that look normal. Six problems are worth separating, because each one needs its own check:

ProblemWhat the code seesTypical causeCheck
DelayedPlausible prices, minutes oldNo live subscription, fallback to delayed dataMarket data type and tick type
StaleThe last value stays, nothing updatesBroken subscription, lost connection, trading haltAge of the last update, last-trade time
MissingEmpty fields, -1 or 0Market closed, no permission, ticker limit reachedValidity rules per field
GapBars or ticks missing from a seriesReconnect, session break, data farm outageExpected bars per session
OutlierOne price far from the othersBad print, busted trade, unit mix-upDistance from a recent median
Wrong FX rateConversion with an old or unsuitable rateDaily reference rate used intradayRate source and timestamp

The checks run before every decision that adds risk, not once at startup: a price that was fine at 10:00 can be stale at 10:05. They also need a written policy for what happens when a check fails. Without one, every failure turns into an improvised decision at runtime.

Delayed vs real-time market data at Interactive Brokers

Interactive Brokers (IBKR) distinguishes four market data types. In the TWS API, reqMarketDataType selects the type before a request, and IBKR reports every switch to a non-live type through the marketDataType callback, together with the ticker ID. IBKR also notes that the most recent data available with the user’s subscriptions is returned regardless of the requested type. According to IBKR’s documentation (as of November 2026):

TypeIDMeaning
Live1Streaming in real time; requires market data subscriptions
Frozen2Last data recorded at market close; needs the same subscriptions as live data
Delayed3Free, 15 to 20 minutes delayed, delivered with delayed tick types (IDs 66 to 76)
Delayed frozen4Delayed “frozen” data for users without market data subscriptions

Live data through the API requires an IBKR Pro account, subscriptions booked in Client Portal and Market Data API access enabled there; IBKR asks clients to hold USD 500 in the account on top of the subscription costs. A quote on the Trader Workstation (TWS) screen does not prove that the API receives it: IBKR states that live data in TWS is not always available through the API.

The API reports most data problems as messages. Treat them as data-quality events, not as log noise:

  • 354: the requested market data is not subscribed.
  • 10089 and 10091: the subscription does not extend to API use, fully or in part; 10090: part of the requested data is not subscribed.
  • 2186: real-time data needs an extra API subscription, so delayed data is used instead.
  • 10186: the data is not subscribed, and delayed data is not enabled.
  • 101: the maximum number of tickers has been reached, so the request receives nothing.
  • 10197: no market data during a competing session; IBKR describes paper and live accounts requesting live data at the same time, with preference given to the live account.

The rule for the code follows from this. Unless a strategy was designed for delayed data on purpose, it trades only on type 1. A ticker that reports type 3 or 4, or one of these codes, is marked as not tradable and raises an alert, even if prices keep arriving.

How to tell a quiet market from a dead feed

According to IBKR, streaming data is not tick-by-tick but consists of aggregated snapshots: every 250 milliseconds for US stocks, futures, bonds and indices, every 100 milliseconds for US options and every 5 milliseconds for forex. A new price tick arrives only when the price changes; a change in size alone arrives as a size tick. Silence therefore has three explanations: nothing is trading, the instrument is halted, or the data path is broken. The code has to find out which one applies.

  • Age per instrument: store the local arrival time of every price or size update and compare its age with a threshold that fits the instrument and the session. A liquid index future and a small stock need very different values.
  • Last-trade time and halts: IBKR’s Last Timestamp tick (ID 45) carries the time of the last trade, and the Halted tick (ID 49) distinguishes general halts from volatility halts.
  • Cross-check: when all subscribed instruments go silent at the same moment, suspect the connection, not the market.
  • Connection messages: code 1100 means the connection to IBKR’s servers is lost. Code 1102 means it is restored with data maintained; 1101 means it is restored with data lost, and IBKR says the market data requests must be resubmitted. Code 2103 reports a broken market data farm connection, while 2104 and 2108 are normal notifications. IBKR warns that API clients are very likely to lose connectivity at least once a day because of its daily server maintenance.
  • Bust events: after a bust event, IBKR deactivates real-time bar subscriptions (code 10225) and asks for an immediate resubscription.

MetaTrader 5 has its own trap. SymbolInfoTick() fills an MqlTick structure whose time_msc field holds the time of the last price update in milliseconds. Comparing it with TimeCurrent() is unreliable: MetaQuotes defines that function as the last known server time, the time of the last quote received for any symbol in Market Watch, and inside OnTick() the time of the tick being handled. When the feed stops, it stops too, and a stale tick looks fresh. TimeTradeServer() is calculated in the terminal and depends on the computer’s clock, so it keeps running; keep that clock synchronized. In the Strategy Tester, however, it always equals TimeCurrent(), which means the staleness check has to be tested on a demo account.

Gaps and outliers in bars and ticks

A gap is a missing interval; an outlier is a value that should not be there. Both need a reference for what is normal.

  • Gaps: compare the bars received with the exchange calendar for the session. A missing bar after a reconnect is a data problem; no bar on a holiday is expected. Do not fill a live gap by silently copying the previous bar, because indicators would then run on invented prices. Mark the gap, and let the specification decide whether the strategy pauses or recalculates once the missing data has been reloaded.
  • Order and duplicates: a bar whose timestamp is equal to or earlier than the previous one can point to a resubscription or a replay. Detect it, and make sure no update is counted twice.
  • Outliers: compare each new price with a robust reference, such as the median of the last 20 mid prices, and with the current bid/ask spread. Hold back a price far from the rest until the next quotes confirm or reject it. Canceled prints are not a theoretical case: IBKR’s documentation mentions busted trades in its volume data and bust events for real-time bars.
  • Units: when data from several sources is combined, check that prices use the same unit and contract multiplier before comparing them.

Keep both the raw and the checked values in the log. When a trade is reviewed later, the question is what the code saw at that moment, not what the cleaned history says.

FX rates with timestamps

Many systems convert values into the account currency: a daily loss limit in euros for US futures, position sizes in the account currency, or exposure across several currencies. The conversion is part of the risk logic and needs the same checks as a price.

One shortcut causes trouble: a daily reference rate used intraday. The European Central Bank (ECB) usually updates its euro reference rates around 16:00 CET on working days, except on TARGET closing days; they are based on a concertation procedure that normally takes place around 14:10 CET. The ECB publishes them for information purposes only and strongly discourages using them for transactions. They suit a report, not an intraday limit.

For every conversion, store:

  • the currency pair and the direction of the quote (USD per EUR or EUR per USD);
  • the source: broker quote, data vendor or reference rate;
  • bid, ask or mid, and the reason for that choice;
  • the time the rate was observed, in UTC;
  • a maximum age after which the risk check refuses the rate.

With these five fields, every limit decision can be reproduced later. When FX quotes pause, the last rate ages like any other price, and the specification decides whether the risk check then uses it with a safety margin or blocks.

What the code should do: warn, block or flatten?

Not every problem deserves the same reaction. A policy written into the specification avoids improvised decisions at runtime. A typical example:

ConditionReaction
Spread wider than usual, one late updateWarn: log, continue, alert if it repeats
Delayed or frozen data, no valid bid/ask, last update older than the limitBlock new and increasing orders, alert
Price jump not yet confirmedBlock entries until the next quotes confirm the level
Connection lost (1100) or data lost (1101)Block, resubscribe, reconcile positions and open orders, resume after several fresh updates
FX rate older than its limitBlock orders whose risk check needs the conversion
Data problem lasting longer than a set timeEscalate to a person; flatten only if the specification says so

Two details matter. Blocking applies to new and increasing orders; orders that reduce risk and protective stops already at the broker stay in place. And the system resumes only after several consecutive good updates, not after the first one, so it does not flip back and forth.

The Python function below rates one quote before an order that adds risk may use it. It returns ok, warn or block with the reasons. Tested with Python 3.9 and 3.12, standard library only; it connects to nothing and sends no orders. The thresholds are placeholders and have to be set per instrument and session.

# quote_guard.py: rates one quote before an order that adds risk may use it.
# Standard library only; connects to nothing and sends no orders.
from dataclasses import dataclass
from statistics import median

OK, WARN, BLOCK = "ok", "warn", "block"


@dataclass
class Quote:
    bid: float
    ask: float
    received: float  # time.monotonic() when the last price or size update arrived
    data_type: int   # IBKR market data type: 1 live, 2 frozen, 3 delayed, 4 delayed frozen


def assess(q, now, recent_mids, in_session,
           max_age=10.0, max_spread=0.002, max_jump=0.01):
    """Returns (OK | WARN | BLOCK, reasons). Thresholds are placeholders."""
    block, warn = [], []
    if not in_session:
        block.append("outside the trading session")
    if q.data_type != 1:
        block.append(f"market data type {q.data_type}, not live")
    if q.bid <= 0 or q.ask <= 0 or q.ask < q.bid:
        block.append("no valid bid/ask")
    else:
        mid = (q.bid + q.ask) / 2
        if q.ask - q.bid > max_spread * mid:
            warn.append(f"spread {q.ask - q.bid:.4g} above limit")
        if len(recent_mids) >= 5:
            ref = median(recent_mids)
            if abs(mid - ref) > max_jump * ref:
                block.append(f"mid {mid:.4g} jumped from median {ref:.4g}, wait for confirmation")
    age = now - q.received
    if age > max_age:
        block.append(f"no update for {age:.1f} s")
    elif age > max_age / 2:
        warn.append(f"last update {age:.1f} s ago")
    return (BLOCK if block else WARN if warn else OK), block + warn


if __name__ == "__main__":
    mids = [100.0, 100.01, 99.99, 100.02, 100.0]
    print(assess(Quote(99.99, 100.01, 99.0, 1), 100.0, mids, True))  # ok
    print(assess(Quote(99.99, 100.01, 99.0, 3), 100.0, mids, True))  # block: delayed
    print(assess(Quote(101.9, 102.1, 80.0, 1), 100.0, mids, True))   # block: jump, stale

In a bot, every price or size callback stores time.monotonic() as received, the last 20 mid prices sit in a collections.deque, and the order path calls assess() first. Because the reference is a median, a single bad print barely moves it, while a genuine move is accepted once enough quotes at the new level have entered the window.

Limits and risks of data checks

  • Thresholds are a trade-off. Too tight, and the system blocks during quiet phases, auctions and halts; too loose, and it trades on stale prices. Set them per instrument and session, and review them with logged data.
  • The code only sees its own data. Orders already at the broker are handled with the broker’s data. IBKR notes that during its daily reset, execution reports and simulated orders are delayed until the reset is complete.
  • Blocking has a cost. A missed exit can hurt more than a missed entry, which is why orders that reduce risk stay allowed.
  • Clean data is not an edge. These checks prevent decisions on wrong inputs; they say nothing about whether the rules make money. Trading with leverage can lose more than the capital deployed.

Next steps: test the data checks before going live

Data checks are only as good as their tests. Before going live, provoke each failure in a paper account or on a demo server and read the log:

  1. Request an instrument without a live subscription and confirm that the bot blocks it.
  2. Cut the network for a minute: block, alert, resubscription, position reconciliation, resume after fresh updates.
  3. Restart IB Gateway, TWS or the MetaTrader terminal during the session.
  4. Replay a recorded series with an artificial spike and a missing bar through the strategy offline.
  5. Feed the risk check an FX rate older than its limit.
  6. For every blocked order, check that the log shows the raw value, the checked value, the decision and the reason.

These failure paths deserve the same attention as the order handling, especially in code written with AI coding assistants. The pre-live checklist for AI-built trading bots covers both.

Frequently asked questions

How do you know if IBKR market data is delayed?

Check the market data type, not the prices. When the API delivers a non-live type for a request, IBKR calls marketDataType with the ticker ID and the type: 3 for delayed and 4 for delayed frozen. Delayed prices also arrive with their own tick types, IDs 66 to 76, and message 2186 announces that delayed data is used instead of real-time data. A bot meant to trade live should block new orders on any of these signals.

How delayed is Interactive Brokers delayed market data?

According to IBKR’s API documentation, free delayed data is 15 to 20 minutes behind the market; for US network exchanges, including NYSE and Nasdaq listed stocks, IBKR states a 15-minute delay. Delayed data needs no subscription. Live streaming data through the API does, together with Market Data API access enabled in Client Portal and an IBKR Pro account.

What is stale market data in trading?

Stale data is a price that is still displayed or used but no longer updated: the last value stays while the market moves on. Typical causes are a broken subscription, a lost connection, a missing resubscription after a reconnect, or a trading halt. Trading code detects it by measuring the age of the last update per instrument and by cross-checking last-trade timestamps, other instruments and connection messages.

Should a trading bot close positions when market data fails?

Usually not automatically. Closing positions on a stale feed means sending orders without a reliable price. A common default is to block new and increasing orders, keep protective orders at the broker in place, alert a person and reconcile positions once data returns. Whether and when to flatten is a decision for the specification, made in advance and tested before going live.

Can a trading bot use ECB reference rates?

For reports, often yes; for intraday risk decisions, rather not. The ECB updates its euro reference rates once per working day, usually around 16:00 CET, publishes them for information purposes only and strongly discourages using them for transactions. An intraday loss limit or position size in another currency needs a recent rate with a known source, side and timestamp, plus a maximum age after which the check refuses it.

Sources and status

As of November 2026. Third-party rules, prices and APIs may have changed since; the providers' current documentation and the official texts are authoritative.

This article is also available in German: Datenqualität im Live-Betrieb: veraltete Kurse im Code abfangen.

Want your bot’s data checks reviewed before it goes live? Get in touch — a free intro call clarifies which checks to review, how the failure cases are tested and what the report contains. More: Trading system code review and audit.