The Simple Mental Model
Think of an API like a waiter at a restaurant. You (your code) don't walk into the kitchen and cook your own food β you give your order to the waiter (the API), the kitchen (the broker/service) prepares it, and the waiter brings back the result. You never need to understand how the kitchen works internally.
Every time your firm fetches a stock price, places an order, sends a Telegram message, or asks Claude a question β it is making an API call.
Anatomy of an API Call
| Component | What It Is | Example |
|---|---|---|
| Endpoint | The URL you send the request to | api.telegram.org/bot{TOKEN}/sendMessage |
| Method | GET (fetch data) or POST (send data) | POST |
| Auth | Your API key or token β proves identity | Bearer sk-ant-... |
| Response | JSON data the server sends back | {"ok": true, "result": {...}} |
REST vs. WebSocket vs. SDK
You'll encounter three main API styles in trading:
- REST API β you ask, it answers, connection closes. Used for placing orders, fetching account info, sending messages. Most APIs you'll use are REST.
- WebSocket β a persistent live connection that streams data continuously. Used for real-time price feeds and order book data.
- SDK / Client Library β a pre-built Python package that wraps API calls for you. IBKR's
ibapi, Alpaca'salpaca-trade-api, and Anthropic'santhropicpackage are all SDKs. You call Python functions; the SDK handles the raw HTTP.
What Is Paper Trading?
Paper trading is a simulated trading environment where orders are placed and executed using fake money against real market prices. Everything behaves exactly like live trading β fills, partial fills, order types, account P&L β except no real capital is at risk.
The DeadCatFound firm runs all strategies on paper until they pass a defined set of validation gates: minimum trade count, win rate, profit factor, and max drawdown thresholds.
| Dimension | Paper Trading | Live Trading |
|---|---|---|
| Capital at risk | None β simulated | Real money |
| Price feeds | Real market prices | Real market prices |
| Order fills | Simulated (optimistic) | Real market fills |
| Slippage | Not modeled accurately | Real β can hurt |
| API endpoint | Separate paper URL/port | Live URL/port |
| Approval needed | No | Yes β firm board |
How the API Switches Between Paper and Live
For IBKR, the difference between paper and live is just the port number. Paper TWS runs on port 7497. Live TWS runs on port 7496. The firm's config file controls which port is used β that single value is the entire safety barrier between paper and live.
The Validation Gates
Before any strategy flips to live, it must pass all of these on the paper account:
- Minimum 30 completed trades
- Win rate > 52%
- Profit factor > 1.25 (gross profit / gross loss)
- Max drawdown < 15% of allocated capital
- At least 20 consecutive trading days without a system error
Persistent socket connection to Trader Workstation (TWS) running locally. Not REST β uses a custom binary protocol wrapped by the ibapi SDK.
TWS must be running and logged in. No API key β authentication is the TWS session itself. Client ID separates multiple connections.
127.0.0.1:7497
127.0.0.1:7496
Free with an IBKR account. No monthly API fee. Commission per trade applies on live only.
pip install ibapi Β· or download from IBKR website
How the IBKR API Works
Unlike REST APIs, IBKR uses an event-driven callback model. You send a request and IBKR responds by calling a method on your wrapper class β asynchronously. Your code must inherit from both EClient (sends requests) and EWrapper (receives callbacks).
What the Firm Uses IBKR For
- place_order() β market and limit orders for equities and futures
- place_bracket() β entry + stop-loss + profit target in one atomic submission
- get_positions() β all open positions across all strategies
- get_nav() β net asset value (NetLiquidation) of the account
- cancel_all() / cancel_order() β emergency order management
- close_position() β flatten a specific position by market order
eTradeOnly=True and firmQuoteOnly=True on all orders. Paper accounts reject these. Always set both to False explicitly or your orders will be rejected with error 10268.
https://paper-api.alpaca.markets
https://api.alpaca.markets
API key + secret in request headers. APCA-API-KEY-ID and APCA-API-SECRET-KEY.
Free. Commission-free trading. Paper account requires no deposit.
Why Alpaca Was Used First
Alpaca's REST API is significantly simpler than IBKR's callback-based SDK. For early strategy validation it was the faster path β no TWS to run locally, no port configuration, just HTTP calls with an API key.
Why the Firm Moved to IBKR
- IBKR supports futures (MES, MNQ) β Alpaca does not
- IBKR has bracket orders natively β Alpaca requires manual stop management
- IBKR is the intended live trading broker β validating on paper with the same API removes a migration risk
- IBKR has far more global market access for future expansion
Historical OHLCV, live quotes, fundamentals, VIX, SPY regime filter, dividend-adjusted data. Covers stocks, ETFs, futures, crypto, indices.
Unofficial β no documented limits. In practice: batch up to ~100 tickers, avoid hammering it. 15-min delayed quotes on free tier.
Free. No API key required.
pip install yfinance
Anti-Lookahead Bias
The most common backtesting mistake is using today's data to make yesterday's decision. In the firm's executors, all signal generation uses .shift(1) on the data β yesterday's close drives today's order, never today's close.
signals = data["Close"].pct_change().shift(1) β this is non-negotiable.
https://api.anthropic.com/v1/messages
API key in header: x-api-key: sk-ant-...
claude-haiku-4-5 (~$0.25/M tokens) for fast scoring. claude-sonnet-4-6 for complex analysis. Always use the cheapest model that does the job.
Pay per token. Haiku: ~$0.25/M input, ~$1.25/M output. Sonnet: ~$3/M input, ~$15/M output.
https://api.telegram.org/bot{TOKEN}/
Bot token from @BotFather embedded in the URL. No separate header needed.
sendMessage β push alertgetUpdates β poll for commandssendDocument β send files/logs
Free. No rate limit for personal bots. Supports HTML formatting in messages.
https://api.binance.us/api/v3/
API key in header X-MBX-APIKEY + HMAC-SHA256 signature on requests that modify account state.
/order β place order/account β balances/klines β OHLCV candles/ticker/price β live price
Withdrawals are disabled on the firm's API key. IP whitelist enforced. Read + trade permissions only β never withdrawal.
Crypto vs. Stock APIs β Key Differences
| Feature | Stock Broker (IBKR) | Crypto Exchange (Binance) |
|---|---|---|
| Market hours | 9:30amβ4pm ET weekdays | 24/7/365 |
| Settlement | T+2 (2 business days) | Instant |
| Custody | SIPC protected up to $500K | Exchange custodies your funds |
| Order types | Market, limit, stop, bracket, etc. | Market, limit, stop-limit |
| Paper trading | Separate TWS paper account | No official paper mode |
| API style | SDK / socket callbacks | Clean REST + WebSocket |
Data & Research APIs
| API | What It Does | Free Tier | Best For |
|---|---|---|---|
| Alpha Vantage | OHLCV, fundamentals, forex, crypto, economic indicators | 25 calls/day | Fundamentals screening |
| Polygon.io | Real-time + historical tick data, options, aggregates | 2 years delay on free | Institutional-grade data |
| FRED API | Federal Reserve economic data β CPI, GDP, rates, unemployment | Free, unlimited | Macro regime filters |
| NewsAPI | Real-time news headlines from 150,000+ sources | 100 calls/day | Sentiment filtering |
| SEC EDGAR | All public company filings β 10-K, 10-Q, 8-K, insider trades | Free, unlimited | Fundamental analysis |
| Quandl / Nasdaq Data Link | Alternative data, commodity prices, futures | Limited free | Alternative data |
Broker & Execution APIs
| Broker | Best For | Paper? | Key Strength |
|---|---|---|---|
| TD Ameritrade / Schwab | US equities, options | Yes | Options flow data, thinkorswim integration |
| Tradier | Options-heavy strategies | Yes | Clean REST API, cheap commissions |
| Coinbase Advanced | Crypto β US regulated | No | FDIC-insured cash, regulated exchange |
| Kraken | Crypto + futures | Sandbox only | Crypto futures, European users |
| Oanda | Forex / CFDs | Yes | Clean REST API, fractional pip pricing |
Automation & Infrastructure APIs
| API | Purpose | Used In Firm |
|---|---|---|
| Cloudflare Workers API | Deploy static sites + serverless functions programmatically | Yes β wrangler CLI |
| GitHub API | Automate commits, PRs, releases, and CI from scripts | Planned |
| SendGrid / Mailgun | Transactional email at scale β better than SMTP for volume | Not yet |
| Twilio | SMS alerts as backup to Telegram | Not yet |
| Discord Webhooks | Team alerts into a Discord server β free, instant | Not yet |
| TradingView Webhooks | Receive TradingView alerts into your Python strategy | Planned |
You Now Speak API.
Every service in the firm is a connection between two systems. Now you know what those connections are, why they exist, and how to extend them.
Continue building on DeadCatFound β all tracks build on each other.
Back to DeadCatFound βDeadCatFound is an educational platform only. We are not a registered financial advisor, broker-dealer, investment advisor, or financial institution of any kind. Nothing in this course constitutes financial advice, investment advice, or any recommendation to buy or sell any security.
All content is for educational and informational purposes only. Trading involves substantial risk of loss. Always consult a licensed financial professional. By accessing this course you acknowledge that DeadCatFound bears no liability for any financial outcomes.