How to handle stale market data in a trading bot's loss limits
One stale price makes a trading bot's P&L unknown while it still looks like a number. How to measure each price's age, and what the bot may do meanwhile.
Contents
- How can a loss limit pass when the loss is unknown?
- How do you measure a price’s age?
- Is the market quiet, or is the feed dead?
- What may the bot do while one price is stale?
- What happens to the drawdown peak during the gap?
- What should you check in your own bot?
- What does each venue document?
- What does it look like in pseudocode?
- What else do people ask?
- Where should I read next?
Your bot’s daily loss limit shows 900 USD of headroom, the WebSocket answers every ping, and one symbol has not sent a price for four minutes: the real loss is already past the limit.
- 09:00:05 - the ETH feed goes quiet. The bot holds 0.5 BTC bought at 60,000 USD and 10 ETH at 3,000. The socket stays up, pongs arrive, BTC keeps ticking; the bot keeps ETH at 3,000.
- 09:02:00 - both fall. The bot sees BTC drop and computes -500 USD. ETH is at 2,900 unseen: the real loss, -1,500, has reached the limit.
- 09:04:00 - the bot buys 0.2 BTC. It counts 900 USD of headroom; the real loss is -2,100.
- 09:05:00 - ETH is resubscribed. Its first price, 2,850, shows -2,100: the bot learns three minutes late.
- One stale price makes the account’s P&L unknown. An account-wide limit sums every position, so a frozen mark on one symbol corrupts the check for orders on all of them.
- Age is measured at decision time, from the source’s clock. Source time against receive time shows how far behind the bot is; time since receipt shows how much older the price has become since.
- A live socket is not a live subscription. WebSocket ping and pong prove the connection; a silent symbol is quiet rather than dead only with evidence for the price you use: a per-symbol heartbeat for trade activity, a fresh book snapshot for a price taken from the book.
- Unknown is a state, not a number. While any required price is stale, the bot opens no new exposure and sends only orders that reduce a position by at most its worst-case size.
- A fresh snapshot restores the current P&L, not the peak. A trailing drawdown measured from a peak the bot never saw is looser than the one you configured.
How can a loss limit pass when the loss is unknown?
The bot sums the last price it has for each position, and nothing in that sum records how old each price is.
Checking freshness only for the order’s own symbol would not have caught it: the BTC order at 09:04 was priced from a current BTC price, and the stale input was the ETH mark inside the account-wide limit.
The fix is a valuation that returns “unknown” instead of a number. With a maximum age of 5 seconds on ETH, the account’s P&L becomes unknown at 09:00:10 and the BTC buy is refused. Unknown carries no partial total: a sum of the fresh positions is a number, and a number gets compared with the limit. The prices it needs include conversion rates: a position quoted in EUR in a USD account needs a fresh EURUSD as much as a fresh mark.
The cost: a dead feed on one symbol stops new trading on every symbol, and a maximum age set too tight stops the bot on every quiet minute.
Terms this article uses
A stale price is a price whose age at the moment of a decision has reached the maximum age you set for that instrument. Unknown P&L is P&L with at least one stale or missing input: it cannot be compared with a limit, however normal the number looks. A trailing drawdown peak is the highest account equity the bot has observed since the limit’s window started; the trailing limit measures the current equity’s distance from it.
The example, step by step
The account holds two positions and has a daily loss limit of 1,500 USD on realized plus open P&L, the way Tradovate’s daily loss limit includes “realized and open P&L” and is monitored in real time (the venue notes). Tradovate also counts fees and commissions; the example assumes none. Long 0.5 BTC entered at 60,000 USD, long 10 ETH entered at 3,000 USD, no realized P&L today. Prices and times are illustrative.
| Time | BTC | ETH, bot / real | P&L, bot / real |
|---|---|---|---|
| 09:00:00 | 60,000 | 3,000 / 3,000 | 0 / 0 |
| 09:00:05 | 60,000 | 3,000 / 3,000 | 0 / 0 |
| 09:02:00 | 59,000 | 3,000 / 2,900 | -500 / -1,500 |
| 09:04:00 | 58,800 | 3,000 / 2,850 | -600 / -2,100 |
| 09:05:00 | 58,800 | 2,850 / 2,850 | -2,100 / -2,100 |
At 09:00:05 the last ETH message arrives, then silence; at 09:04:00 the bot buys 0.2 BTC; at 09:05:00 ETH is resubscribed. The real loss reached the limit at 09:02 and passed it by 09:04. The bot learned at 09:05, three minutes late, and in between it added exposure on a symbol whose feed was fine.
How do you measure a price’s age?
A price’s age is its source lag plus the time since your code read it, measured when the check runs.
Source lag shows how far behind the bot is reading; the time since receipt shows how much older the price has become since. Only their sum is the age a decision should see. Source lag needs the wall clock, because the venue’s timestamp is wall-clock time; time since receipt needs a monotonic clock, so that an NTP step on the host does not make every price suddenly older or younger.
Check at decision time, not on every tick: it costs one clock read per decision and a comparison per required price, while a timer that marks prices stale every second leaves the check only as current as the timer. A timer is still needed for the alert on P&L unknown for too long: a bot that checks only when it sends an order never notices that state while idle. The pseudocode is at the end.
The three clocks, in detail
- Source time is the timestamp the venue puts on the message: the time on a Coinbase Exchange ticker, or the trade time on a Binance trade stream rather than the message’s event time. The venue notes give the fields.
- Receive time is when your code reads the message, not when the network delivered it. A message can sit in a socket buffer or an in-process queue for a long time before that.
- Decision time is when the check runs: when the bot evaluates a limit or sends an order.
An answer on Alpaca’s forum advises always comparing source and receive time, and warns that a client that reads too slowly gets buffered and can fall 30 minutes or more behind without noticing; its figures are in the venue notes.
A consumer that falls behind its own buffer
Symbols keep updating, so nothing looks silent, but source lag grows at once on every symbol still sending updates. Alert on rising lag across the feed, not only on per-symbol silence, and treat it as a symptom: a delayed source and a clock step raise it too.
Clock skew between source and host
Skew enters source lag directly. A host clock ahead of the venue makes every price look older and can stop the bot for nothing; a clock behind makes prices look younger, and clamping negative lag to zero hides exactly how much. Synchronize the host clock, alert on negative lag, and treat a sudden change in the minimum lag as a possible clock event, to check against the host’s clock-sync status: a delivery delay added to every message raises it too.
With the OpenPit SDK 0.8
A pre-trade engine can hold the same model. Since version 0.8.0 of the OpenPit
SDK (released 2026-09-06),
a quote expires when its source
age, the time from the source’s observation to publication, plus the time
since publication reaches its time-to-live; the engine trusts the source age
the publisher passes with each quote. A checked read of an expired quote
returns a QuoteExpired error that carries the stale quote, and the built-in
Spot Funds
policy rejects a market order whose pricing quote is stale with
MarkPriceUnavailable instead of pricing it. In the 0.8 releases, Spot Funds’
P&L kill switch evaluates realized account P&L, which its accounting converts
with the last available FX quote, stale or not, so the account-wide check on
open P&L above stays your code.
Is the market quiet, or is the feed dead?
You cannot tell from silence: the answer has to come from a message that would have arrived in either case.
WebSocket ping and pong do not give it. The WebSocket standard (RFC 6455) defines a ping as a keepalive or a check that the other endpoint still responds: it proves the connection, and in the timeline above the connection was fine. A per-symbol heartbeat does: on its heartbeat channel, Coinbase Exchange sends one per subscribed product every second, with a sequence number and the last trade ID (channels). What it proves is trade activity, so it confirms only a price that is the last trade.
- Its last trade is yours. Nothing has traded since: a last-trade price is confirmed as of the heartbeat’s time. A bid, an ask or a mark from the book is not; it can move without a trade.
- Its last trade is ahead of yours. You missed trades: mark the price as a gap until a backfill of the missed trades or a snapshot.
- No heartbeat for that symbol, others keep arriving. The evidence that the symbol is live is gone, so the price ages until it goes stale.
A matching heartbeat proves that nothing has traded since, as of its timestamp, not that the last trade is still a price you could close at: on an illiquid symbol the bids can fall without a print. So the trade’s own age keeps a second, longer limit that no heartbeat resets. A price with no liveness signal is judged by its last update, and its maximum age is a guess at how long that market can legitimately stay quiet: too short stops the bot on quiet markets, too long lets a dead feed pass.
What each heartbeat case means, in full
- The heartbeat’s last trade ID equals the last trade you received. A last-trade price is confirmed as of the heartbeat’s time; keep that confirmation apart from the trade’s own timestamp. A bid, an ask or a mark derived from the book needs evidence from the book itself, such as a fresh book snapshot.
- The heartbeat’s last trade ID is ahead of yours. Coinbase documents fetching missed trades through its REST API from the last trade ID the heartbeat reports; a snapshot works too.
- No heartbeat for that symbol. The heartbeat may only be delayed or dropped, but you cannot tell.
A price confirmed by a heartbeat every second can have a maximum age of a few seconds. The trade’s own age still runs against its longer limit.
Sequence numbers catch lost messages of other kinds
Coinbase’s sequence numbers are per product and grow by exactly one per message: a number more than one above the previous means a dropped message, a lower one an out-of-order message. Check for forward gaps only on a stream you are meant to receive in full: compared only with each other, consecutive heartbeats can show jumps on a healthy feed, because the product’s other messages sit between them.
Where the venue has no per-symbol heartbeat
Know what triggers each message. Kraken’s Spot WebSocket ticker sends updates on trades by default and can be switched to changes in the best bid and offer (the venue notes). On the trade trigger, an illiquid pair is silent while its book moves. On the best-bid-and-offer trigger, silence matches an unchanged book, and it also matches a dropped subscription. Silence alone proves neither, so confirm with a REST request for the symbol once its silence reaches its maximum age, at the cost of rate-limit budget and a second code path that can fail on its own.
An illiquid instrument that is quiet but correct
With a liveness signal its last trade stays confirmed while nothing trades, but it still reaches the limit on the trade’s own age, and from then on it is too old to value at, whatever the heartbeats say. Without a liveness signal, the price goes stale on schedule and stops the bot; that is the right answer when the bot cannot tell the difference.
Option marks frozen after hours
Outside the session the last mark stops moving because the market is closed, not because the feed failed. Treat it as a separate state with its own rule (for example, the session close is accepted until the next open while nothing else in the account’s limit can trade; otherwise P&L is unknown), not as a fresh price and not as a dead feed.
A stream that omits symbols
Binance’s all-market mini-ticker stream documents that only tickers that have changed appear in each array (the venue notes). An array that omits a symbol carries no timestamp for it and does not show that its updates are still delivered; a symbol missing from every array looks the same as one that never moves. Refresh a symbol’s age only from a message that contains that symbol.
What may the bot do while one price is stale?
Open no new exposure on any symbol, cancel working orders that would add exposure, and send only orders that reduce a position by at most its worst-case size.
- New exposure. Refused on every symbol: the limit it would be checked against is unknown.
- A working order that adds exposure. Its cancel is requested; until the venue confirms it, the order still counts in the position range.
- A reducing order. Sent only if it cannot flip or grow the position, and priced from something fresh or not at all.
- Unknown past a set time. It stops being a pause and becomes an alert a person must answer.
The FIA’s best practices for automated trading risk controls (July 2024, section 3.1) go further: checks should cover incoming market data and “values generated using the market data”, and when data may be stale “any orders should be blocked while the deviation is investigated”. Blocking every order is the simplest rule to verify. Allowing reductions trades that simplicity for the ability to get out of a position whose loss you cannot measure; the price is a second code path that must be right.
While orders are in flight the position is a range, not a number (how to track it), so the reducing-order check uses the range’s worst side: a sell must leave the lowest possible position long or flat, a buy the highest one short or flat.
Price the reducing order from something fresh, or not at all
A limit price derived from the stale mark is wrong by however far the market has moved: a sell limit at 3,000 does not fill while the best bid is 2,850. A market order, or a limit set from a fresh order-book request, reduces the position if it fills. It may not: the book can move before the order arrives, liquidity can run short, and a venue’s price protection can cap a market order’s fill. The cost is slippage you cannot estimate while the price is unknown.
A reducing order that times out is not resent blindly
If the first one filled, the second can flip the position, and the check that it reduces risk no longer holds. Resolve the first order’s status first (what a timeout leaves unknown).
Your own fills are prices with a timestamp
A fill on the stale symbol tells you where it traded at the fill’s time. Check that time before treating it as recent: a fill can arrive late or be replayed. A fill does not make the feed live, and a single fill is not a mark to value the whole position at.
What happens to the drawdown peak during the gap?
The peak is lost, and a fresh snapshot does not bring it back. A snapshot gives the current equity, but the peak depends on every equity value during the gap, and the bot saw none of them.
The same two positions, a different gap (illustrative): equity is 100,000 USD at 09:00:00, BTC is exactly 60,000 at every time in the table, and the trailing limit is 1,500 USD measured in real time.
| Time | ETH, real | Bot: equity / peak | Real: equity / peak |
|---|---|---|---|
| 09:00:05 | 3,000 | 100,000 / 100,000 | 100,000 / 100,000 |
| 09:01:30, ETH stale | 3,150 | 100,000 / 100,000 | 101,500 / 101,500 |
| 09:05:00, after a snapshot | 2,990 | 99,900 / 100,000 | 99,900 / 101,500 |
After the snapshot the bot measures a drawdown of 100 USD. The real drawdown is 1,600 USD, past the limit, and nothing will ever tell the bot: the limit that ran was looser by however far equity rose during the gap.
- Bound the peak from above. Value every position at its most favorable price over the gap. With BTC’s high at 60,100 and ETH’s at 3,150 the bound is 101,550 and the drawdown 1,650: the bot stops, correctly. The cost: the highs need not coincide, so it can stop the bot when the real peak was lower.
- Trail on end-of-day values. A peak that moves only at the session close does not depend on intraday prices. The cost: a limit that does not tighten during the day, and a gap that spans the close still loses the value the rule uses.
- Mark the peak unverified. If you can do neither, record that the peak is uncertain and require a person to confirm it before new exposure resumes.
A daily loss limit measured from the start of the session loses no reference point: it was fixed before the gap. Once positions, realized P&L, fees and conversion rates are reconciled, a fresh snapshot restores the current valuation. It cannot tell you whether the limit was crossed during the gap.
What the extremes must bound
Fetch each valuation input’s highest value over the gap (lowest, for shorts). The extremes have to bound the prices you actually value at: candles of last trades bound a last-trade mark, not a mark taken from the book, and conversion rates need their own extremes. The bound assumes the positions did not change during the gap; if the bot traded, value each interval with the quantities it held then.
End-of-day trailing, where a venue offers it
Tradovate offers both end-of-day and real-time trailing drawdown: the first is calculated at the end of each daily session, the second immediately (the venue notes). A gap that leaves a trustworthy session-close equity loses nothing under the end-of-day rule.
What should you check in your own bot?
- Every price the bot stores keeps its source lag and a monotonic receive time.
- The valuation behind every account-wide limit returns “unknown”, not a number, when any required price is stale, missing or behind a sequence gap.
- The required prices include conversion rates, not only marks.
- Each instrument has its own maximum age, a last-trade price also a limit on the trade’s own age that no heartbeat resets, and you know which instruments have a liveness signal and which are judged by their last update.
- Ping and pong are not used as evidence that any symbol is live.
- Source lag is monitored across the whole feed, and negative lag raises an alert.
- While P&L is unknown, only cancels and orders that reduce the worst-case position are sent, and none is priced from the stale mark.
- After a gap, the trailing peak is bounded, re-derived from end-of-day values, or flagged for a person; it is never left at its pre-gap value.
What does each venue document?
The fields, channels and rules behind everything above, source by source.
Coinbase Exchange
- Source time.
timeon a ticker message. - Heartbeat. The
heartbeatchannel sends one message per subscribed product every second, carrying a sequence number and the last trade ID, which the documentation says “can be used to verify that no messages were missed”. Missed trades can be fetched through the REST API from the last trade ID the heartbeat reports. - Sequence numbers. Per product, growing by exactly one per message: a number more than one above the previous means a dropped message, a lower one an out-of-order message (feed overview).
Binance Spot
- Source time. The trade time
Ton a trade stream, rather than the message’s event timeE. - Omitted symbols. The all-market mini-ticker stream documents that “only tickers that have changed will be present in the array”.
Kraken Spot WebSocket v2
The ticker
sends updates on trades by default; its event_trigger parameter, added on
2024-03-01 according to the
changelog, switches it to
changes in the best bid and offer.
Alpaca
An answer on Alpaca’s forum (2025-08-20) advises always comparing source and receive timestamps, expects quote deltas “typically under 25ms”, and notes that trades can be reported up to 10 seconds after execution; a client that reads too slowly gets buffered, and it warns that an algorithm can fall 30 minutes or more behind without noticing.
Tradovate
- Daily loss limit. Includes “realized and open P&L” and is monitored in real time; it also counts fees and commissions (daily loss limit).
- Trailing drawdown. Both end-of-day and real-time: the first calculated at the end of each daily session, the second immediately (trailing max drawdown).
WebSocket, RFC 6455
Section 5.5.2 defines a Ping as a keepalive or a check that the other endpoint still responds.
What does it look like in pseudocode?
The age check, the heartbeat and the reducing-order test, in pseudocode
The age check keeps each price’s source lag and a monotonic receive time, and returns unknown P&L when any required price is stale.
# Pseudocode.
on_price(msg): # called when your code reads the message
p = prices.setdefault(msg.symbol, {gap: false, confirmed: none, seq: none})
# msg.seq: the venue's per-symbol sequence or the trade ID, where the
# feed has one; without either, this check is skipped
if msg.seq is not none and p.seq is not none and msg.seq <= p.seq:
return # late or out of order: keep the newer price
lag = wall_now() - msg.source_time
if lag < 0: # host clock behind the venue's
report_skew(msg.symbol, lag)
lag = 0
p.value, p.source_lag, p.recv, p.seq = msg.price, lag, mono_now(), msg.seq
p.last_trade_id = msg.trade_id # for a last-trade price, else none
# p.gap is left as it is: only a backfill or a snapshot clears it
trade_age(p, now): # age of the price itself
return p.source_lag + (now - p.recv)
age(p, now): # age of the evidence it is still current
if p.confirmed is none:
return trade_age(p, now)
c = p.confirmed # set by a heartbeat, see below
return min(trade_age(p, now), c.source_lag + (now - c.recv))
is_stale(s, now):
p = prices.get(s)
if p is none or p.gap or age(p, now) >= max_age[s]:
return true
# a last trade has a second limit, which no heartbeat resets
return p.last_trade_id is not none and trade_age(p, now) >= max_trade_age[s]
account_pnl():
now = mono_now() # one clock read per decision
stale = [s for s in required_symbols(positions) # every mark, every FX rate
if is_stale(s, now)]
if stale:
return Unknown(stale) # which symbols, for the alert; no total
return Known(realized_today + sum(open_pnl(pos, prices) for pos in positions))
may_open_exposure(order):
pnl = account_pnl()
return pnl is Known and pnl.value > -daily_loss_limitThe heartbeat handler, for a last-trade price:
# Pseudocode, continuing the block above. For a last-trade price.
on_heartbeat(hb):
p = prices.get(hb.symbol)
if p is none or p.last_trade_id is none:
return # no last-trade price yet: nothing to confirm
if hb.last_trade_id > p.last_trade_id:
p.gap = true # missed trades: backfill or snapshot
elif hb.last_trade_id == p.last_trade_id:
p.confirmed = {source_lag: max(0, wall_now() - hb.source_time),
recv: mono_now()} # no trade since: last trade confirmedThe reducing-order test, on the worst side of the position range:
# Pseudocode.
reduces_risk(order):
low, _, high = position_range(order.symbol) # confirmed minus open sells,
if order.side == SELL: # confirmed plus open buys
return low - order.qty >= 0 # stays long or flat
return high + order.qty <= 0 # stays short or flat
may_send(order):
return may_open_exposure(order) or reduces_risk(order)What else do people ask?
What should my bot do when the connection is fine but one feed goes quiet?
Treat the account’s P&L as unknown once that symbol’s price passes its maximum age, stop new exposure on every symbol, and resubscribe or fall back to a REST request for that symbol. Whether silence means quiet or dead is settled only by evidence for the price you use: a per-symbol heartbeat for a last-trade price, a fresh book snapshot for a price taken from the book.
How do I detect stale quotes in a trading bot?
Store the venue’s timestamp and your own receive time with every price, and at decision time compare the price’s age, source lag plus time since receipt, with a maximum set per instrument. Watch the lag itself too: when it grows on every symbol at once, the bot is most likely reading its buffer late, though a delayed source or a clock step look the same.
Is WebSocket ping/pong enough to know the data is fresh?
No. RFC 6455 defines ping and pong for the connection, and a connection can stay healthy while the subscription for one symbol delivers nothing.
Can I value the stale position at its last known price and keep trading?
You can value it, but not compare the result with a limit. The last known price is a number with no bound on its error: with 10 ETH held and the ETH feed silent for four minutes, that error reached 1,500 USD.
Where should I read next?
- Why your trading bot’s position drifts from the broker’s: the position range the reducing-order check uses.
- Duplicate orders after a timeout: resolving an order whose outcome is unknown before you resend it.
- RFC 6455, section 5.5.2 and Coinbase Exchange’s WebSocket channels: connection liveness against per-product heartbeats.
- FIA, Best Practices for Automated Trading Risk Controls and System Safeguards, section 3.1.
- OpenPit SDK: Market Data TTL, Spot Funds, and the 0.8.0 release that made freshness count from the source’s observation.