πŸ”’ Private Access

DeadCatFound is in development.
Enter your access code to continue.

Incorrect access code.
← DeadCatFound
Courses Performance Live Trades
Track 05 β€” APIs & Integrations M-01
What Is an API?
API stands for Application Programming Interface. It is the language two pieces of software use to talk to each other β€” and every automated trading firm runs on them.

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.

Why APIs Matter for Trading
Without APIs, automated trading doesn't exist. APIs are what let your Python script talk to Interactive Brokers, pull live prices from Yahoo Finance, send you a Telegram alert, and ask Claude to score a stock β€” all without you touching a keyboard.

Anatomy of an API Call

Every API call has these four components
ComponentWhat It IsExample
EndpointThe URL you send the request toapi.telegram.org/bot{TOKEN}/sendMessage
MethodGET (fetch data) or POST (send data)POST
AuthYour API key or token β€” proves identityBearer sk-ant-...
ResponseJSON 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's alpaca-trade-api, and Anthropic's anthropic package are all SDKs. You call Python functions; the SDK handles the raw HTTP.
The Firm's API Stack
IBKR (execution) Β· Alpaca (paper fallback) Β· yfinance (prices) Β· Telegram Bot API (alerts) Β· Claude API (AI scoring) Β· Binance (crypto) Β· Cloudflare Workers API (deployment) Β· GitHub API (version control)
Track 05 β€” APIs & Integrations M-02
Paper vs. Live Trading
Every strategy in this firm runs on paper first. Understanding the difference between paper and live trading APIs is not optional β€” it's the line between learning and losing real money.

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.

Paper vs. Live β€” Key Differences
DimensionPaper TradingLive Trading
Capital at riskNone β€” simulatedReal money
Price feedsReal market pricesReal market prices
Order fillsSimulated (optimistic)Real market fills
SlippageNot modeled accuratelyReal β€” can hurt
API endpointSeparate paper URL/portLive URL/port
Approval neededNoYes β€” firm board
Hard Rule β€” This Firm
config/ibkr.json must have "mode": "paper" at all times. Every executor checks this on startup and throws a RuntimeError if it's set to anything else. Switching to live requires explicit board approval. This is non-negotiable.

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.

config/ibkr.json
{ "host": "127.0.0.1", "port": 7497, // 7497 = paper TWS, 7496 = live TWS "account": "DUQ090929", "mode": "paper" // executor hard-blocks if this != "paper" }

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
Track 05 β€” APIs & Integrations M-03
IBKR β€” The Execution Engine
Interactive Brokers is the primary broker for all real-money execution. Their API is the most powerful in retail trading β€” and the most complex.

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).

ibkr basic pattern
from ibapi.client import EClient from ibapi.wrapper import EWrapper from ibapi.contract import Contract from ibapi.order import Order class MyApp(EWrapper, EClient): def __init__(self): EClient.__init__(self, self) def nextValidId(self, orderId): # Called when TWS is ready β€” this is your entry point self.place_my_order(orderId) def orderStatus(self, orderId, status, filled, ...): print(f"Order {orderId}: {status}, filled={filled}") app = MyApp() app.connect("127.0.0.1", 7497, clientId=1) app.run() # starts the event loop

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
Key Gotcha
IBKR's newer ibapi versions default 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.
Track 05 β€” APIs & Integrations M-04
Alpaca β€” Paper Trading API
Alpaca is a commission-free broker with a clean REST API. The firm used Alpaca for initial paper testing before migrating all execution to IBKR.
πŸ¦™
Alpaca Markets API
REST API β€” JSON over HTTPS β€” clean and beginner-friendly
Retired β€” Historical

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.

alpaca basic usage
import alpaca_trade_api as tradeapi api = tradeapi.REST( key_id = "YOUR_KEY", secret_key = "YOUR_SECRET", base_url = "https://paper-api.alpaca.markets" ) # Place a market order order = api.submit_order( symbol = "AAPL", qty = 10, side = "buy", type = "market", time_in_force = "day" ) # Get account account = api.get_account() print(f"Portfolio value: ${account.portfolio_value}")

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
Track 05 β€” APIs & Integrations M-05
Market Data APIs
Every trading decision starts with data. The firm uses two market data sources: yfinance for free historical and live prices, and the IBKR feed for execution-time quotes.
πŸ“ˆ
yfinance
Unofficial Yahoo Finance wrapper β€” free, no API key, 1min to daily OHLCV
Active β€” Price Feeds

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

yfinance usage in the firm
import yfinance as yf import pandas as pd # Single ticker β€” 6 months of daily data aapl = yf.download("AAPL", period="6mo", interval="1d") # Batch download β€” all firm universe at once (fast) universe = ["AAPL","NVDA","MSFT","GOOGL","AMZN","META","TSLA"] data = yf.download(universe, period="6mo", interval="1d") # VIX regime filter (used in momentum strategy) vix = yf.download("^VIX", period="5d", interval="1d") vix_now = float(vix["Close"].iloc[-1]) if vix_now > 25: print("High volatility regime β€” reduce position size") # Live quote ticker = yf.Ticker("SPY") info = ticker.fast_info print(f"SPY last: ${info.last_price:.2f}")

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.

Lookahead Bias β€” The Silent Killer
A strategy that "works" in backtest but fails live is almost always lookahead bias. Always shift your signal by one period. signals = data["Close"].pct_change().shift(1) β€” this is non-negotiable.
Track 05 β€” APIs & Integrations M-06
Claude & Telegram APIs
Two APIs that give the firm its intelligence and its voice. Claude scores and filters. Telegram communicates. Together they make the system feel alive.
πŸ€–
Anthropic Claude API
REST API β€” AI scoring, analysis, agent orchestration
Active β€” AI Scoring

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.

claude api β€” stock scoring
import anthropic client = anthropic.Anthropic(api_key="sk-ant-...") def score_stock(symbol: str, metrics: dict) -> int: prompt = f""" You are a quantitative analyst. Score {symbol} from 0-100. Metrics: {metrics} Return ONLY a JSON object: {{"score": 75, "reason": "..."}} """ message = client.messages.create( model = "claude-haiku-4-5-20251001", max_tokens = 256, messages = [{"role": "user", "content": prompt}] ) import json result = json.loads(message.content[0].text) return result["score"]
πŸ“±
Telegram Bot API
REST API β€” push notifications, command listener, real-time alerts
Active β€” All Alerts

https://api.telegram.org/bot{TOKEN}/

Bot token from @BotFather embedded in the URL. No separate header needed.

sendMessage β€” push alert
getUpdates β€” poll for commands
sendDocument β€” send files/logs

Free. No rate limit for personal bots. Supports HTML formatting in messages.

Track 05 β€” APIs & Integrations M-07
Crypto β€” Binance API
The firm runs a live crypto hybrid strategy on Binance US. Understanding the difference between a crypto exchange API and a stock broker API is essential before touching either.
β‚Ώ
Binance US API
REST + WebSocket β€” spot crypto trading, live prices, account management
Active β€” Crypto Strategy

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

Stock Broker API vs. Crypto Exchange API
FeatureStock Broker (IBKR)Crypto Exchange (Binance)
Market hours9:30am–4pm ET weekdays24/7/365
SettlementT+2 (2 business days)Instant
CustodySIPC protected up to $500KExchange custodies your funds
Order typesMarket, limit, stop, bracket, etc.Market, limit, stop-limit
Paper tradingSeparate TWS paper accountNo official paper mode
API styleSDK / socket callbacksClean REST + WebSocket
Critical Security Note
Always disable withdrawal permissions on your Binance API key. If your key is ever compromised, the attacker can drain your account to an external wallet in seconds. Withdrawal OFF + IP whitelist = the minimum acceptable security posture.
Track 05 β€” APIs & Integrations M-08
Other Useful APIs
The ecosystem of APIs for trading, data, and automation is enormous. Here are the most useful plug-ins to know about beyond the firm's current stack.

Data & Research APIs

Market Data & Research
APIWhat It DoesFree TierBest For
Alpha VantageOHLCV, fundamentals, forex, crypto, economic indicators25 calls/dayFundamentals screening
Polygon.ioReal-time + historical tick data, options, aggregates2 years delay on freeInstitutional-grade data
FRED APIFederal Reserve economic data β€” CPI, GDP, rates, unemploymentFree, unlimitedMacro regime filters
NewsAPIReal-time news headlines from 150,000+ sources100 calls/daySentiment filtering
SEC EDGARAll public company filings β€” 10-K, 10-Q, 8-K, insider tradesFree, unlimitedFundamental analysis
Quandl / Nasdaq Data LinkAlternative data, commodity prices, futuresLimited freeAlternative data

Broker & Execution APIs

Other Broker APIs Worth Knowing
BrokerBest ForPaper?Key Strength
TD Ameritrade / SchwabUS equities, optionsYesOptions flow data, thinkorswim integration
TradierOptions-heavy strategiesYesClean REST API, cheap commissions
Coinbase AdvancedCrypto β€” US regulatedNoFDIC-insured cash, regulated exchange
KrakenCrypto + futuresSandbox onlyCrypto futures, European users
OandaForex / CFDsYesClean REST API, fractional pip pricing

Automation & Infrastructure APIs

Infrastructure Plug-ins
APIPurposeUsed In Firm
Cloudflare Workers APIDeploy static sites + serverless functions programmaticallyYes β€” wrangler CLI
GitHub APIAutomate commits, PRs, releases, and CI from scriptsPlanned
SendGrid / MailgunTransactional email at scale β€” better than SMTP for volumeNot yet
TwilioSMS alerts as backup to TelegramNot yet
Discord WebhooksTeam alerts into a Discord server β€” free, instantNot yet
TradingView WebhooksReceive TradingView alerts into your Python strategyPlanned
The Rule for Adding New APIs
Only add an API when it solves a specific, identified gap in the firm's capability. Every new dependency is a new attack surface, a new rate limit to manage, and a new potential point of failure. Add deliberately, not enthusiastically.

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 β†’
⚠ Important Disclaimer

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.