API to Get Market Data: A Crypto Trader's Complete Guide
Learn how to use APIs to pull live and historical market data for crypto and stocks, with real Python code examples covering Binance, CoinGecko, IBKR, Schwab, and Indian markets.
Learn how to use APIs to pull live and historical market data for crypto and stocks, with real Python code examples covering Binance, CoinGecko, IBKR, Schwab, and Indian markets.
Market data is the oxygen of trading. Without it, every decision is a guess. Whether you're building a bot that scalps on Binance, running a signal pipeline like VoiceOfChain, or just pulling charts into your own dashboard, you need a reliable way to query prices, order books, volume, and historical candles — and you need it fast. That's where a market data API comes in: a programmatic interface that lets your code ask an exchange or data provider for current prices and receive a structured JSON response in milliseconds. No scraping, no browser — just clean data over HTTP or WebSocket. This guide covers free APIs to get market data, exchange-specific APIs from Binance, OKX, Bybit, and Coinbase, broker APIs like IBKR and Schwab, options for the Indian stock market, and working Python code you can run today.
Most retail traders consume data through someone else's interface — TradingView, Binance's terminal, their broker's dashboard. That works fine for manual trading. The moment you want to automate anything, the interface becomes the bottleneck. You can't programmatically read a candlestick chart on a screen. With direct API access to market data, you bypass the interface entirely and work with raw, structured data you control.
This is the same infrastructure professional quant desks use, and it's increasingly accessible to retail traders. Many exchanges provide free market data APIs with generous rate limits, and third-party aggregators like CoinGecko deliver cross-exchange price data without requiring individual API keys for each platform. The barrier to entry has never been lower.
You don't need to pay for market data to get started. Several free APIs to get market data are genuinely production-quality and will cover most retail and early-stage algo trading use cases. The key is knowing which one fits your use case — crypto vs. equities, real-time vs. historical, authenticated vs. open access.
| Provider | Coverage | Auth Required | Rate Limit | Best For |
|---|---|---|---|---|
| Binance Public API | Crypto — spot and futures | No | 1,200 req/min by weight | Crypto real-time and historical data |
| CoinGecko Free Tier | 10,000+ coins, aggregated | No (API key optional) | 30 calls/min | Cross-exchange consensus prices |
| Alpha Vantage | Stocks, forex, crypto | API key (free tier) | 25 calls/day | Daily equity analysis pipelines |
| NSEpy (Python library) | Indian equities via NSE | No (unofficial) | Unlisted | Indian market backtesting |
| Upstox API v3 | Indian equities and F&O | Yes — Upstox account | Generous | Indian real-time trading data |
CoinGecko is the most popular free API to get market data for crypto. The free tier gives you prices, market caps, 24h volume, historical candles, and metadata for thousands of coins — no key required for basic endpoints. For stock traders, Alpha Vantage provides a solid free API to get stock market data covering US equities, forex, and crypto, though the 25 calls/day free limit means you'll want to batch requests efficiently rather than poll continuously. For Indian equities, the NSEpy Python library wraps NSE's unofficial public endpoints and is widely used for backtesting without a brokerage account — making it the practical choice when you need a free API to get Indian stock market data with zero friction.
For crypto market data, exchange-native APIs are the gold standard. First-party data, lowest latency for that specific order book, and the most comprehensive coverage of that exchange's markets. Each major exchange maintains its own REST and WebSocket API ecosystem.
The Binance API to get market data is the most documented and widely used crypto data API in the world. All public endpoints — spot prices, futures funding rates, order books at any depth, aggregate trades, and OHLCV klines from 1-second to 1-month intervals — are accessible without any authentication. On OKX you can pull real-time mark prices for derivatives, index prices, and funding rate history going back to the launch of each instrument, which is particularly valuable for strategies built around funding premium analysis. Platforms like Bybit and OKX have heavily invested in WebSocket infrastructure — Bybit streams order book snapshots at 25ms intervals, making it suitable for high-frequency data collection. The Coinbase Advanced Trade API provides institutional-grade spot market data with ECDSA signature-based authentication, preferred by traders operating in regulated US jurisdictions who need Coinbase's compliance framework. Gate.io and KuCoin also maintain clean public APIs, with Gate.io being especially useful for smaller altcoin data that isn't available on the big four exchanges.
Always use WebSocket APIs instead of polling REST endpoints for anything that needs to update faster than once per second. REST is for setup and historical pulls; WebSocket is for streaming. Mixing them for real-time data leads to unnecessary rate limit consumption and stale reads. Most exchanges offer WebSocket streams for tickers, order books, and trades as a direct drop-in replacement.
Most exchange APIs have two tiers: public endpoints with no authentication (price data, order books, klines) and private endpoints requiring an API key plus a cryptographic signature (balances, orders, trade history). For market data, you almost always start public. Here is a complete working example pulling real-time price data from Binance — no API key needed.
import requests
BASE_URL = 'https://api.binance.com'
def get_ticker_price(symbol='BTCUSDT'):
endpoint = f'{BASE_URL}/api/v3/ticker/price'
params = {'symbol': symbol}
try:
response = requests.get(endpoint, params=params, timeout=5)
response.raise_for_status()
data = response.json()
return float(data['price'])
except requests.exceptions.RequestException as e:
print(f'Request failed: {e}')
return None
# Works for any trading pair on Binance — no API key required
print(get_ticker_price('BTCUSDT')) # e.g. 94532.18
print(get_ticker_price('ETHUSDT')) # e.g. 3241.07
print(get_ticker_price('SOLUSDT')) # e.g. 178.44
For a free cross-exchange API to get market data without any credentials at all, CoinGecko is the best option. It returns aggregated data sourced from hundreds of exchanges, so you get a market-wide consensus price rather than a single exchange's feed — useful when you need a reference price that isn't biased toward one platform's liquidity.
import requests
def get_coin_market_data(coin_id='bitcoin'):
url = 'https://api.coingecko.com/api/v3/coins/markets'
params = {
'vs_currency': 'usd',
'ids': coin_id,
'sparkline': 'false'
}
try:
resp = requests.get(url, params=params, timeout=10)
resp.raise_for_status()
coin = resp.json()[0]
return {
'price': coin['current_price'],
'change_24h': coin['price_change_percentage_24h'],
'volume': coin['total_volume'],
'market_cap': coin['market_cap']
}
except (requests.exceptions.RequestException, IndexError) as e:
print(f'Error fetching data: {e}')
return None
data = get_coin_market_data('bitcoin')
if data:
price = data['price']
change = data['change_24h']
vol = data['volume']
print(f'Price: ${price:}')
print(f'24h change: {change:.2f}%')
print(f'Volume: ${vol:}')
When you move beyond public endpoints — or when working with authenticated APIs like IBKR or Schwab — you need to sign each request. Binance uses HMAC-SHA256 signatures with a millisecond timestamp. The pattern is consistent: build the query string, sign it with your secret key, append the signature, and pass your API key in the request header. Here is a complete authenticated request with full error handling, including rate limit detection.
import hashlib
import hmac
import time
import requests
API_KEY = 'your_api_key'
SECRET = 'your_secret_key'
BASE = 'https://api.binance.com'
def signed_request(endpoint, params=None):
if params is None:
params = {}
params['timestamp'] = int(time.time() * 1000)
query = '&'.join(f'{k}={v}' for k, v in params.items())
sig = hmac.new(
SECRET.encode('utf-8'),
query.encode('utf-8'),
hashlib.sha256
).hexdigest()
url = f'{BASE}{endpoint}?{query}&signature={sig}'
headers = {'X-MBX-APIKEY': API_KEY}
try:
resp = requests.get(url, headers=headers, timeout=5)
resp.raise_for_status()
return resp.json()
except requests.exceptions.HTTPError as e:
if resp.status_code == 429:
print('Rate limited — add exponential backoff before retrying')
else:
print(f'HTTP error {resp.status_code}: {e}')
return None
except requests.exceptions.RequestException as e:
print(f'Connection error: {e}')
return None
# Fetch non-zero account balances
account = signed_request('/api/v3/account')
if account:
non_zero = [b for b in account['balances'] if float(b['free']) > 0]
for b in non_zero:
print(b['asset'] + ': ' + b['free'])
The error handling here covers three separate failure modes: HTTP errors (4xx/5xx), rate limiting specifically (429), and connection-level failures like timeouts or DNS errors. In production code, add exponential backoff on 429s — start with a 1-second wait, double it each retry, and cap at around 60 seconds. Most APIs, including Binance, include a Retry-After header on 429 responses that tells you exactly how long to wait.
Not every trader is crypto-only. If you need equity data alongside your crypto feeds, several well-maintained APIs cover traditional markets — and the ecosystem for Indian stock market data in particular has matured considerably in recent years.
The IBKR API to get market data comes in two flavors: the TWS API (socket-based, runs through Trader Workstation) and the Client Portal API (REST and WebSocket, requires their local gateway process). Both support real-time streaming, historical bars, options chains, and fundamental data. The IBKR API is one of the most powerful available for global equities, but it requires an active IBKR account and their software running locally — it is not a standalone data service you can query in isolation.
The Schwab API to get market data was relaunched in 2024 following the Charles Schwab and TD Ameritrade integration. It uses OAuth 2.0 authentication and provides streaming quotes, historical OHLCV candles, option chains, and market hours data for US equities and ETFs. For Schwab account holders it functions as an effective free API to get stock market data, with solid official documentation and a developer portal. The Schwab API replaced the TD Ameritrade API that many retail algo traders had been using — migration is straightforward, mostly an authentication update.
For Indian markets, the best free API to get Indian stock market data depends on your situation. Zerodha Kite Connect remains the industry standard for reliable tick data and a mature SDK ecosystem, though it costs ₹2,000 per month after the trial. Upstox API v3 is free for Upstox account holders and covers equities plus F&O with WebSocket streaming. For a completely free API to get Indian stock market data without a brokerage relationship, the NSEpy Python library is the practical choice — it wraps NSE's unofficial public endpoints and is widely used in the Indian quant community for historical backtesting.
Choosing the right API to get market data comes down to what you are building and where you trade. For crypto, start with Binance's public endpoints or CoinGecko — both are free, fast, and exceptionally well-documented. If your activity is on OKX, Bybit, or Gate.io, their native APIs give you the lowest-latency data for those specific order books. For US equities, the Schwab API is a clean free option for account holders, while the IBKR API unlocks institutional-level data coverage for serious quant work. Indian traders now have a solid set of options between Zerodha, Upstox, and AngelOne — with NSEpy filling the gap for pure backtesting without needing a live brokerage account.
The code examples in this guide give you a working foundation you can run today. From here, the natural evolution is moving from polling REST endpoints to subscribing to WebSocket streams for real-time data, then building a local data store that your strategies can query without hitting rate limits on every tick. If you would rather consume pre-processed signals than manage raw data pipelines yourself, platforms like VoiceOfChain handle the data infrastructure and deliver actionable trading signals directly — but understanding how the underlying API layer works will always make you a more capable and independent trader.