NOONOO TRADINGStart in the bot

WebSocket Disconnects: The Danger of a Bot Running on Frozen Prices

An automated program can remain open without errors, with quiet logs, while the price has not changed for 30 minutes. Its WebSocket connection has failed, but nothing has told the program.

A WebSocket Can Fail Through Silence

REST sends a request and waits for a reply. A missing reply is recognized as failure. WebSocket reverses the pattern: after connecting, the exchange pushes updates, so waiting quietly is normal behavior.

Two Failure Patterns

REST: You Ask
Request → No reply → Timeout error.
The code recognizes failure.

WebSocket: The Exchange Pushes
Connect → Data → Data →
Nothing happens.
The code believes it is still waiting normally.

─────────────
A disconnected stream and a quiet market
can be indistinguishable to the program.

Routers, company firewalls, and mobile networks can drop long-idle connections. Sometimes they send a proper closure notice; often they simply discard packets. In the latter case, the program can wait indefinitely while believing the connection remains alive.

What a Frozen Last Price Does

Most bots store the last received price in a variable and use it for decisions. If the stream stops, that variable remains fixed at the last value, but the bot keeps treating it as current.

A Stop That Never Triggers

Long entry: 100,000.
Stop: 98,000.

12:00: Last received price 99,800.
12:00: Connection drops, unnoticed.

12:05: Actual market 97,000.
Bot sees 99,800.
99,800 > 98,000 → No stop.

12:20: Actual market 95,500.
Bot still sees 99,800.

─────────────
Actual loss: −4,500, or −4.5%.
Displayed bot loss: −200.
The bot believes nothing is wrong.

At 20× leverage, the −4.5% underlying move is −90% of margin. Having a stop in code does not ensure it executes: it needs incoming data. This distinguishes a bot-generated exit from an order already resting at the exchange. An exchange-submitted stop can remain active even if your program dies.

Missing Data Distorts the Whole Indicator

Candles are affected too. Candles during a stream outage simply go missing, and a bot may concatenate observations before and after the gap without recognizing it.

A 20-Period Moving Average on One-Minute Candles

Normal latest 20 candles: 12:00–12:19.

Disconnected 12:05–12:12: Eight candles lost.

Bot's array:
11:52–12:04 + 12:13–12:19.
Still 20 candles: The count is correct.

─────────────
It actually compresses 28 minutes into 20 observations.
The effective period is 1.4× longer.

Worse, if the missing interval contained a sharp decline,
that decline disappears from the indicator.

Count checks pass. Moving averages, RSI, and ATR silently produce incorrect values. Losses commonly happen at the busiest moments, when trading and data volumes surge and connections fail. Indicators are then calculated without the most important interval.

Distinguishing Quiet from Failure: Heartbeats

For a channel where silence can be normal, require a periodic signal even when nothing else happens.

Connection Monitoring

Exchange sends periodic ping.
Your client promptly sends pong.

Local timer:
Record the last received time.
If nothing arrives for more than N seconds,
treat the connection as dead, close, and reconnect.

─────────────
Example: Ping every 20 seconds.
Threshold 60 seconds, or three missed pings.

Too short → Disconnects healthy connections.
Too long → Leaves frozen data in use for too long.

Act when the threshold is exceeded rather than continuing to hope the stream is alive. Waiting a little longer creates the stop failure described above. Reconnection costs seconds; frozen-data operation can cost the position. As with API clock errors, do not assume an ambiguous state is healthy.

Stop New Entries When Data Is Stale

The entire bot need not stop during recovery, but separate action types.

Data-Freshness Gate

Time since last reception:
0–5 seconds → Normal; all actions allowed.
5–30 seconds → Block new entries.
Keep existing-position management and exits active.
More than 30 seconds → Force reconnection and alert.

─────────────
Why leave exits available?
Entering on stale data takes new risk.
Exiting on stale data is defensive.

Blocking both together can trap the position.

A common design blocks entry and exit as one unit, removing the escape route while data is disconnected. Keep the route out available.

First After Reconnecting: Query Actual State

Prices resume after reconnection, but the stream does not necessarily report what happened to your account during the outage.

Possible Events During the Gap

A resting stop executed.
A limit order partially filled.
Liquidation occurred.
Funding was deducted.

Reconnecting does not replay those past events;
the stream pushes events from now onward.

─────────────
Required Recovery Steps
1) Query positions through REST.
2) Query open orders through REST.
3) If internal records differ, adopt exchange state.
4) Log the discrepancy.

If internal records show a 0.1 long but the actual position has already closed to zero, selling to “close” can create a new opposite position. Position reconciliation covers these differences. The principle is that the exchange is authoritative; local records are an estimate.

Reconnection Storms: Recovery That Blocks Itself

Immediate reconnect loops can create their own outage.

Immediate-Retry Consequences

Exchange maintenance lasts 60 seconds.
Retry every 0.1 seconds.
60 ÷ 0.1 = 600 attempts.

Connection limit exceeded → IP blocked for ten minutes.
The exchange recovers, but you cannot reconnect.

─────────────
Backoff
1 second → 2 → 4 → 8 → 16 → 30-second cap.
Add 0–1 seconds of random delay
to spread simultaneous attempts from multiple processes.

Jitter matters especially when several bots share one IP. Without it, they retry in sync and trigger their own HTTP 429 rate limits. A cap also matters: unbounded intervals can delay recovery for minutes after the exchange is available again.

Order Books Can Become Quietly Corrupted

Order-book subscriptions add another problem. They commonly send one full snapshot followed only by changes.

Missing Deltas Create Ghost Orders

Snapshot sequence: 1000.
Deltas 1001, 1002, 1003 arrive normally.

1004 is lost during a brief interruption.
Reception resumes at 1005.

The local book retains a sell wall removed in 1004.

─────────────
Consequences:
You delay entry because of a nonexistent wall.
You submit limits using incorrect best quotes, so they do not fill.

Prevention:
Check every delta's sequence number.
If even one is skipped,
discard the local book and restart from a snapshot.

Without sequence validation, the book diverges from reality while still displaying plausible numbers. Limits derived from it have mysteriously poor fill rates; switching to market orders produces more slippage than expected.

Checklist

For automated trading, build these into the standard process. See the exchange API integration guide for connection details.

Include

Always record the last reception time.
Close and reconnect immediately after the threshold.
Block only new entries on stale data.
Requery positions and orders through REST after reconnecting.
Use backoff, jitter, and a cap.
Check order-book sequences and resubscribe on gaps.
Place protective stops at the exchange in advance where possible.
Log disconnect count and duration.

─────────────
Most importantly:
Do not assume silence means normal operation.

Disconnect records let you check whether data existed at the time of a losing trade. Without them, strategy error and absent data may remain impossible to distinguish.

Key Points

A WebSocket can fail through silence rather than an error.
A quiet market and disconnection can look identical to code.
A frozen price can prevent a stop condition from ever triggering.
Missing candles can still pass count-based checks.
Gaps often occur during the busiest periods.
Heartbeats and thresholds distinguish quiet from failure.
Reconnect when the threshold is exceeded.
Block stale-data entries while keeping exits available.
Requery positions and orders after recovery.
Immediate retry storms can block your own connection; use backoff and jitter.
Restart order books from a snapshot after sequence gaps.

Nothing guarantees that the bot's view matches the market. The strategy has meaning only when the program also verifies that its data remains alive.

Notice

Thresholds, ping periods, backoff intervals, prices, and quantities are hypothetical examples, not measurements from a particular exchange. Ping/pong conventions, connection lifetimes, connection-rate limits, order-book sequence rules, and resubscription procedures vary by exchange. Check the relevant documentation and test with small amounts. Leveraged trading can lose all principal. Investment decisions and their consequences are your responsibility.

NOONOO TRADING invites you to follow live trading in our free chat.

Start in the bot

📈 OKX trading fee discount for new registrations

Register for the OKX Fee Discount →