Skip to main content
Execution Systems
Advanced·Execution Systems

API Trading Introduction: How to Connect Code to Exchanges Safely

Trading via API unlocks automation, custom analytics, and faster execution. The setup has specific safety requirements that protect you from the worst failure modes.

7 min readUpdated 2025-07-15

Most exchanges offer programmatic access via APIs. Trading via API enables automation, custom analytics, faster execution, and integration with your own tools. The setup has specific security and operational requirements that, done correctly, are routine, done incorrectly, can lose your account in minutes. This chapter covers the basics of safe API setup and use.

What exchange APIs actually expose

Most major exchanges offer:

REST APIs. Request-response endpoints for queries and orders. Standard HTTP/JSON. Examples: get account balance, place limit order, fetch candlestick history.

WebSocket APIs. Persistent connections that push real-time data. Examples: live tick prices, fill notifications, order updates.

FIX protocol (sometimes). Industry-standard protocol used by institutional traders. Lower latency than REST. Mostly relevant for HFT.

For most retail automation, REST + WebSocket is sufficient. REST for orders and account queries; WebSocket for live data and fill notifications.

API authentication, the critical layer

To use an API, you need API credentials. These typically include:

API key. Public identifier (like a username).

API secret. Cryptographic secret used to sign requests. Like a password, keep it secret.

Passphrase / second factor (some exchanges). Additional credential.

API keys are different from your login credentials. They authenticate your programmatic access. Most exchanges let you create multiple API keys with different permissions.

API permissions, the make-or-break decision

Exchanges typically let you set permissions per API key:

Read-only. Can query account info, balances, positions. Cannot place orders or withdraw. Lowest risk; useful for analytics tools that don't need to trade.

Trade-only. Can place and cancel orders. Cannot withdraw funds. Most automated trading should use this level. Even if compromised, attacker can lose your money to bad trades but can't withdraw it elsewhere.

Trade + withdraw. Can do everything including withdraw funds. Highest risk; should almost never be used for automated systems.

The single most important security decision for API trading: trade-only permissions, never withdraw. If your API key is compromised, the attacker can make bad trades (lose money) but can't transfer funds out. The damage is bounded. Most automated trading disasters are at least partially containable because of this rule.

If you need to withdraw, do it through the web interface (which has its own security flow: 2FA, email confirmation, etc.), not through the API.

IP whitelisting, an additional layer

Many exchanges let you restrict an API key to specific IP addresses. If your bot runs on a known server, whitelist that server's IP. The API key becomes useless from any other IP.

This protects against API key theft via malware on your laptop or other devices. Even if the key is stolen, it can only be used from the whitelisted IP.

For VPS-hosted bots, this is essentially free security. Set it up.

Rate limits, the operational constraint

Exchanges rate-limit API requests to prevent abuse and maintain system stability. Typical limits:

  • 10-50 requests per second for general endpoints
  • Lower limits for some specific endpoints
  • Order placement may have separate limits

Exceeding limits results in temporary blocks (your requests get rejected for some period). Persistent abuse can lead to API access being revoked entirely.

Pragmatic implications:

  • Cache data when possible (don't re-query the same thing repeatedly)
  • Use WebSocket for real-time data instead of polling REST endpoints
  • Implement exponential backoff on rate-limit errors
  • Test your bot's request patterns under load before deploying

Well-built bots stay well within rate limits. Naive implementations hit limits constantly.

Order types and special parameters via API

API order placement supports the same order types as the web interface, plus often more:

  • Market, limit, stop, stop-limit, trailing stop
  • Post-only, reduce-only, time-in-force flags
  • Sometimes: iceberg, hidden, FOK, IOC

Some advanced features (basket orders, conditional orders, complex bracket setups) may be more easily accessible via API than via web UI.

For automation, mastering the order type flags is critical. Most exchange API docs have detailed specifications.

A common mistake: API keys with full permissions

A trader creates an API key with all permissions "to make sure things work." The key is later compromised. The attacker withdraws everything.

The fix: minimum-necessary permissions. Trade-only for trading bots. Read-only for analytics tools. Never give withdraw permission to an API key unless absolutely required (and then with extreme care).

A common mistake: storing API keys in code

A trader hardcodes API keys in their bot's source code. They commit the code to GitHub. Public repository. Within hours, bots scrape the keys and drain the account.

The fix: keys in environment variables or secret management systems, never in source code. Even private repos can be accidentally made public; even "local-only" code can leak through backups, sharing, etc. Treat keys with the security of passwords.

A common mistake: not rotating API keys

A trader creates API keys once and uses them indefinitely. Years pass. The key may have been exposed in any of dozens of past incidents.

The fix: rotate API keys periodically (every 6-12 months). When rotating, also review permissions (might have changed since you last reviewed). Rotation limits the window during which any exposure can be exploited.

A common mistake: testing in production

A trader's first version of their bot has bugs. They deploy it directly to production with real funds. The bugs cost real money before being noticed.

The fix: most exchanges offer testnets / sandbox environments. Use them for initial development and integration testing. Deploy to production only after the bot is working reliably in test.

A common mistake: ignoring partial fills

A bot places a limit order for 1 BTC. Fills 0.6 BTC partially. The bot doesn't track this and treats the position as fully filled. Subsequent decisions are based on wrong position size.

The fix: handle partial fills explicitly. Track filled vs unfilled quantity. Update position state based on actual fill messages, not just order placement.

A common mistake: not handling API errors gracefully

A bot encounters an API error (rate limit, network issue, exchange downtime). The error isn't handled; the bot crashes or enters a weird state.

The fix: explicit error handling for every API call. Retry logic with backoff for transient errors. Alerting for persistent errors. The bot should degrade gracefully when the exchange is having issues, not amplify them.

A common mistake: forgetting time synchronization

Many exchange APIs require accurate timestamps in requests (to prevent replay attacks). If your bot's clock is off by more than a few seconds, requests get rejected.

The fix: ensure NTP time sync on the bot's host. Most modern systems do this automatically; verify on production servers. Out-of-sync clocks cause subtle hard-to-debug issues.

A common mistake: insufficient logging

Something goes wrong. The trader looks at logs to diagnose. The logs are sparse: not enough detail to reconstruct what happened.

The fix: comprehensive logging from the start. Every order placed, every fill, every error, every state change. Logs should let you reconstruct exactly what the bot was doing at any past moment. Disk is cheap; insight is expensive.

API trading, a pragmatic starting setup

For a trader getting started with API trading:

1. Pick the right exchange. Most major exchanges have decent APIs. Binance, Bybit, OKX, Kraken all offer mature APIs. Read the docs of your primary exchange.

2. Set up safe credentials. Create a trade-only API key. Whitelist your bot's IP. Store credentials in environment variables.

3. Start with read-only operations. Build code that fetches your account, balances, positions. Verify it works correctly. This builds familiarity with the API without trade risk.

4. Add order placement in test mode. Use exchange testnet to place test orders. Verify order types, response handling, error cases.

5. Deploy to production with small size. Real production trades but with sizes you don't mind losing if something goes wrong. Run for weeks. Monitor closely.

6. Scale up only after live validation. Once the bot has reliably executed many real trades, scale size gradually.

This progression takes weeks-to-months. Skipping steps causes the disasters that turn beginning algo traders into ex-algo traders.

Mental model, API trading as giving someone keys to your trading account

Giving an API key with full permissions is like giving someone full keys to your house, they can take whatever they want.

Giving a trade-only key is like giving them keys to move things around inside the house, they can rearrange but can't carry anything out.

IP whitelisting is like giving them keys that only work when they're at a specific location.

Choose the appropriate access level for what you're trying to enable. The temptation to give "all keys just in case" creates the worst-case exposure.

Why this matters for trading

API trading is the gateway to automation, custom analytics, and integration with your own tools. Setup correctly, it's safe and powerful. Setup poorly, it's the most common cause of catastrophic account loss. The few specific safety practices covered here (trade-only permissions, IP whitelisting, secret management, error handling) prevent the worst outcomes.

Takeaway

API trading enables automation and custom integration with exchanges. Critical safety practices: trade-only API permissions (never withdraw), IP whitelisting, credentials in environment variables (not source code), periodic key rotation, testnet for development, comprehensive error handling, comprehensive logging, time synchronization. Start read-only, add trading in testnet, deploy production with small size, scale gradually after validation. The setup time is real but pays off across all automated trading from then on.

Related chapters

All chapters