Cross-post. Original: stellarbytecapital.com/blog/exchange-api-integration
Every trading system eventually meets an exchange API, and that’s where clean architecture meets messy reality. The strategy is deterministic and testable; the exchange connection is asynchronous, rate-limited, occasionally down, and the sole authority on whether your order actually exists. Most “the bot lost money” incidents trace back not to the strategy but to this seam — a dropped WebSocket, a throttled cancel, an order placed twice.
REST and WebSocket: two channels, two jobs
- REST is request/response: place and cancel orders, query balances/positions, fetch history. Authoritative but slower and rate-limited. Use it for actions and reconciliation queries.
- WebSocket is a push stream: real-time market data and private order/balance updates. Use it to stay current, not to place orders. Fast but unreliable — it will drop, and messages get missed.
The rule: act over REST, listen over WebSocket, and never trust the stream as the source of truth. The stream says something probably happened; REST confirms it.
Authentication and request signing
Most exchanges sign private calls with an API key + HMAC. Three things break constantly:
- Clock skew. Signed requests carry a timestamp; the exchange rejects anything outside a small window. Sync time (NTP) and correct offset against the exchange’s server time.
- Signature construction. The exact signed string — parameter order, encoding, body vs query — must match the spec byte-for-byte. Build it from one canonical serializer.
- Key scope and secrecy. Minimum permissions (trade yes, withdraw almost never), IP-allowlisted. The key lives on the execution agent, never in a central database.
Rate limits: budget them or get throttled at the worst moment
Every exchange throttles requests, and the penalty is a temporary ban — which arrives exactly when volatility spikes and you need to cancel.
- Track your budget locally and back off before the exchange rejects you.
- Prioritize critical calls — a cancel or risk-driven flatten must win over a routine balance poll.
- Prefer WebSocket for data so you’re not burning REST budget polling prices.
-
Respect
429/Retry-Afterwith exponential backoff and jitter — never a tight retry loop.
WebSocket lifecycle: assume it drops
- Heartbeat. Ping/expect ping; if the peer goes quiet, treat the connection as dead.
- Reconnect with backoff and re-subscribe on every reconnect.
- Resync on reconnect — the critical step. You may have missed fills while disconnected. Query REST for open orders, positions, and balances and rebuild your view before trusting the stream again.
- Sequence gaps. For order-book streams, track sequence numbers; a gap means resnapshot, not patch forward.
The disconnect isn’t the danger. Trading on what you believed before the disconnect is.
Order lifecycle and idempotency
The place-order request can time out after the exchange accepted it but before you got the response; retry naively and you’ve doubled your position.
- Client order IDs on every order → retries are idempotent and you can always look the order up by your ID even if the response was lost.
-
Track the state machine:
submitted → accepted → partially filled → filled / canceled / rejected. Persist transitions; don’t infer them. - Reconcile against the exchange as truth on any doubt — timeout, reconnect, restart.
- Handle partial fills explicitly — position and average price update per fill, not per order.
Test against a testnet first
Most major exchanges offer a sandbox. Wire it up there first and exercise the ugly paths deliberately: kill the WebSocket mid-order, blow the rate limit, submit a duplicate client ID, restart with open orders. The failures you induce in testing are the ones you won’t debug with real money at 3am.
What to avoid
- Placing orders over WebSocket / trusting it as truth — act and confirm over REST.
- No client order IDs — a timeout becomes unrecoverable and retries double orders.
- Resuming after a disconnect without resync — the most expensive shortcut.
-
Tight retry loops on
429— you’ll turn a throttle into a ban. - Withdraw permission on trading keys — a leaked key should never be able to move funds out.
An exchange integration done right respects one fact: the exchange, not your program, is the source of truth about your money and orders. Everything above is machinery for staying in agreement with that truth when the network doesn’t cooperate.
We’re Xingyao Byte — building quant trading systems, exchange integrations, secure AI-execution layers, and payment platforms. Remote, async-first → stellarbytecapital.com
답글 남기기