Tutorial: Plot OHLCV candlestick charts in Python with a candlestick API
A candlestick chart is the first thing most traders look at, and the first thing most trading tools need to draw. To build one yourself you need two things: clean OHLCV candles and a few lines of plotting code.
This tutorial gets you both. You’ll fetch candles from the TAAPI.IO candlestick API, load them into pandas, and plot a BTCUSDT chart with a volume panel and the 21 and 50-period EMA, all in one Python script you can copy and run. Then you’ll point the same script at Apple stock.
What are OHLCV candles?
Each candle sums up the trading in one timeframe, for example one day, in five numbers:
- Open: the first price
- High: the highest price
- Low: the lowest price
- Close: the last price
- Volume: how much traded
Almost every technical indicator is calculated from these five numbers, and every candlestick chart is drawn from them.
Why use a candlestick API instead of the exchange’s own?
Every exchange has its own candle endpoint, and each one is a little different: different URLs, different symbol formats, different field orders, different limits. If your code should work on more than one market, you end up writing and maintaining one adapter per exchange.
The /candles endpoint gives you one format for all of them: Binance, Binance Futures, Bybit, Gate.io, Kraken and US stocks. You change exchange and symbol, and nothing else in your code changes. The same API also returns indicator values, so the EMA in Step 3 comes from the same place as the candles.
What you need
- Python 3.9 or newer, and three packages:
pip install requests pandas mplfinance - A TAAPI.IO API key, saved in an environment variable so it never ends up in your code:
export TAAPI_KEY_V2="your_api_key"
The script makes two requests per chart, so it runs on the Basic plan (5 requests per 15 seconds). US stocks, in Step 4, need the Pro plan or higher. Both plans come with a 7-day free trial.
Step 1: Fetch the candles
One GET request returns the candles as JSON:
curl -G https://v2.taapi.io/candles \
-H "Authorization: Bearer YOUR_API_KEY" \
--data-urlencode "exchange=binance" \
--data-urlencode "symbol=BTCUSDT" \
--data-urlencode "timeframe=1d" \
--data-urlencode "results=50" \
--data-urlencode "backtrack=1"
results=50asks for 50 candles. Basic includes 50 candles of history per request, Pro 300.backtrack=1skips the newest candle, which is still forming. You get only closed candles, so the chart doesn’t change while you look at it.
This is the real response from 23 November 2026, shortened to the last two of the 50 candles:
[
{
"open": 58951.51,
"high": 60996,
"low": 55130,
"close": 60215.77,
"volume": 48558.10096999997,
"timestamp": 1795219200,
"takerBuyVolume": 22529.434169999964,
"timestampHuman": "2026-11-21 00:00:00"
},
{
"open": 60215.78,
"high": 61669.99,
"low": 58768.51,
"close": 61271.08,
"volume": 20137.13077999999,
"timestamp": 1795305600,
"takerBuyVolume": 10218.945410000015,
"timestampHuman": "2026-11-22 00:00:00"
}
]
The array is ordered oldest first, so the last element is the most recent closed candle. timestamp is the candle’s open time in Unix seconds (UTC), and volume is in the base currency, BTC here. On Binance and Binance Futures you also get takerBuyVolume, the part of the volume bought with market orders. We won’t need it for the chart.
In Python, the same request is a few lines. The call() helper also handles the two responses you should expect from any API like this: 202 when the data is still being fetched, and 429 when you’ve hit your rate limit:
import os
import time
import requests
API_URL = 'https://v2.taapi.io'
API_KEY = os.environ.get('TAAPI_KEY_V2')
def call(method, path, **kwargs):
"""Send a request, wait and retry on 202 (queued) and 429 (rate limit)."""
for _ in range(5):
r = requests.request(method, f'{API_URL}{path}', timeout=30,
headers={'Authorization': f'Bearer {API_KEY}'}, **kwargs)
if r.status_code == 202:
time.sleep(2)
elif r.status_code == 429:
time.sleep(r.json().get('retryAfter', 15))
else:
r.raise_for_status()
return r.json()
raise RuntimeError(f'{path}: no result after 5 attempts')
candles = call('GET', '/candles', params={
'exchange': 'binance', 'symbol': 'BTCUSDT', 'timeframe': '1d',
'results': 50, 'backtrack': 1,
})
Prefer Node.js? The fetch step looks like this (Node.js 18 or newer):
const params = new URLSearchParams({
exchange: 'binance', symbol: 'BTCUSDT', timeframe: '1d', results: 50, backtrack: 1
});
const res = await fetch(`https://v2.taapi.io/candles?${params}`, {
headers: { Authorization: `Bearer ${process.env.TAAPI_KEY_V2}` }
});
if (!res.ok) throw new Error(`HTTP ${res.status}: ${await res.text()}`);
const candles = await res.json();
const last = candles.at(-1);
console.log(`${candles.length} candles, last: ${last.timestampHuman} ` +
`O ${last.open} H ${last.high} L ${last.low} C ${last.close} V ${last.volume.toFixed(2)}`);
Save it as candles.mjs and run node candles.mjs. When we ran it:
50 candles, last: 2026-11-22 00:00:00 O 60215.78 H 61669.99 L 58768.51 C 61271.08 V 20137.13
Step 2: Load into pandas and plot candles with volume
mplfinance draws candlestick charts from a pandas DataFrame with a DatetimeIndex and open, high, low, close and volume columns. The API already uses those names, so the conversion is two lines:
import mplfinance as mpf
import pandas as pd
df = pd.DataFrame(candles)
df.index = pd.to_datetime(df['timestamp'], unit='s')
df = df[['open', 'high', 'low', 'close', 'volume']]
mpf.plot(df, type='candle', style='yahoo', volume=True,
title='BTCUSDT 1d (binance)', savefig='btcusdt-1d.png')
volume=True adds the volume panel under the candles. That’s a complete candlestick chart. Next, the moving averages.
Step 3: Add EMA 21 and 50 from the same API
You could calculate the EMA yourself in pandas. But with only the 50 candles on your chart, the result is wrong. An EMA carries the effect of every earlier candle, so it needs a long run of history before its values settle. When we calculated the 50-period EMA in pandas from the same 50 daily candles, the last value came out at 74,555.51. The API’s value for the same day is 73,481.04: the local one was off by 1,074, or 1.5%. Calculate it the textbook way, starting from a simple average, and you get exactly one value, for the last candle.
The EMA endpoint calculates on the full history, so every one of the 50 values is already settled. To get both EMAs in a single request, use /bulk, which counts as one request however many indicators it contains:
body = {'constructs': [{
'id': 'chart', 'exchange': 'binance', 'symbol': 'BTCUSDT', 'timeframe': '1d',
'indicators': [
{'id': 'ema21', 'indicator': 'ema', 'period': 21, 'results': 50, 'backtrack': 1},
{'id': 'ema50', 'indicator': 'ema', 'period': 50, 'results': 50, 'backtrack': 1},
],
}]}
data = call('POST', '/bulk', json=body)['chart']
The response has one entry per id, each with a value array and a matching timestamp array, oldest first, just like the candles. These are the last three values from our run:
{
"chart": {
"ema21": {
"value": [69776.26279684993, 68907.12708804538, 68212.94098913216],
"timestamp": [1795132800, 1795219200, 1795305600]
},
"ema50": {
"value": [74541.18359483621, 73979.40266954852, 73481.03707466427],
"timestamp": [1795132800, 1795219200, 1795305600]
}
}
}
Because both requests use the same results and backtrack, the timestamps line up with the candles one for one. Turn each EMA into a pandas Series, line it up with the candles by timestamp, and hand it to mplfinance with make_addplot:
emas = pd.DataFrame()
for p in (21, 50):
s = data[f'ema{p}']
emas[f'EMA {p}'] = pd.Series(s['value'], index=pd.to_datetime(s['timestamp'], unit='s'))
emas = emas.reindex(df.index)
lines = [mpf.make_addplot(emas['EMA 21'], color='#3b82f6', label='EMA 21'),
mpf.make_addplot(emas['EMA 50'], color='#f59e0b', label='EMA 50')]
mpf.plot(df, type='candle', style='yahoo', volume=True, addplot=lines,
savefig='btcusdt-1d.png')
Here is the chart from our run, the same 50 candles and EMA values:
How to read it: Bitcoin spent most of October between 80,000 and 85,000, with the 21 EMA above the 50 EMA. On 2 November the 21 EMA crossed below the 50, and from 5 November every close was below both lines. On 21 November price dipped to 55,130 on the heaviest volume of the whole period, then closed back above 60,000. With the price below both EMAs and the faster one below the slower one, a trend follower would read this as a downtrend, and the gap to the 21 EMA, about 10%, shows how stretched the move is.
Step 4: The same code for US stocks
To chart a stock, change two values: exchange=stocks and the ticker as the symbol. The full script below takes them as arguments:
python candlestick_chart.py stocks AAPL
When we ran it:
50 candles, 2026-09-14 to 2026-11-20
Last close 344.87 EMA 21 347.74 EMA 50 340.75
Chart saved to aapl-1d.png
Same code, same output format. Two things are different on stocks:
- Plan: US stocks are included on the Pro plan and above.
- Trading hours: stocks have no candles on weekends and holidays, so 50 daily candles reach further back, to 14 September here. Daily stock candles include pre-market and after-hours trading. We ran this before the US open on Monday 23 November: Monday’s candle had already started with pre-market trades, and
backtrack=1left it out, so the chart ends on Friday’s close.
The full script
Everything above in one file. Save it as candlestick_chart.py, set TAAPI_KEY_V2, and run it:
import os
import sys
import time
import mplfinance as mpf
import pandas as pd
import requests
API_URL = 'https://v2.taapi.io'
API_KEY = os.environ.get('TAAPI_KEY_V2')
EXCHANGE = sys.argv[1] if len(sys.argv) > 1 else 'binance'
SYMBOL = sys.argv[2] if len(sys.argv) > 2 else 'BTCUSDT'
TIMEFRAME = '1d'
RESULTS = 50 # candles to chart
EMA_PERIODS = (21, 50)
def call(method, path, **kwargs):
"""Send a request, wait and retry on 202 (queued) and 429 (rate limit)."""
for _ in range(5):
r = requests.request(method, f'{API_URL}{path}', timeout=30,
headers={'Authorization': f'Bearer {API_KEY}'}, **kwargs)
if r.status_code == 202:
time.sleep(2)
elif r.status_code == 429:
time.sleep(r.json().get('retryAfter', 15))
else:
r.raise_for_status()
return r.json()
raise RuntimeError(f'{path}: no result after 5 attempts')
def fetch_candles():
candles = call('GET', '/candles', params={
'exchange': EXCHANGE, 'symbol': SYMBOL, 'timeframe': TIMEFRAME,
'results': RESULTS, 'backtrack': 1,
})
df = pd.DataFrame(candles)
df.index = pd.to_datetime(df['timestamp'], unit='s')
return df[['open', 'high', 'low', 'close', 'volume']]
def fetch_emas():
body = {'constructs': [{
'id': 'chart', 'exchange': EXCHANGE, 'symbol': SYMBOL, 'timeframe': TIMEFRAME,
'indicators': [{'id': f'ema{p}', 'indicator': 'ema', 'period': p,
'results': RESULTS, 'backtrack': 1} for p in EMA_PERIODS],
}]}
data = call('POST', '/bulk', json=body)['chart']
emas = pd.DataFrame()
for p in EMA_PERIODS:
series = data[f'ema{p}']
emas[f'EMA {p}'] = pd.Series(series['value'],
index=pd.to_datetime(series['timestamp'], unit='s'))
return emas
def main():
if not API_KEY:
sys.exit('Set the TAAPI_KEY_V2 environment variable to your TAAPI.IO API key.')
try:
candles = fetch_candles()
emas = fetch_emas().reindex(candles.index)
except (requests.RequestException, RuntimeError) as err:
sys.exit(f'Request failed: {err}')
colors = ('#3b82f6', '#f59e0b')
lines = [mpf.make_addplot(emas[col], color=c, width=1.2, label=col)
for col, c in zip(emas.columns, colors)]
filename = f'{SYMBOL.lower()}-{TIMEFRAME}.png'
mpf.plot(candles, type='candle', style='yahoo', volume=True, addplot=lines,
title=f'{SYMBOL} {TIMEFRAME} ({EXCHANGE}) with EMA 21 and 50',
ylabel='Price', ylabel_lower='Volume', figsize=(11, 6),
savefig=dict(fname=filename, dpi=150, bbox_inches='tight'))
last = candles.iloc[-1]
print(f'{len(candles)} candles, {candles.index[0]:%Y-%m-%d} to {candles.index[-1]:%Y-%m-%d}')
print(f'Last close {last.close:,.2f} ' +
' '.join(f'{col} {emas[col].iloc[-1]:,.2f}' for col in emas.columns))
print(f'Chart saved to {filename}')
if __name__ == '__main__':
main()
Run it with no arguments for BTCUSDT on Binance. When we ran it on 23 November 2026, the output was:
50 candles, 2026-10-04 to 2026-11-22
Last close 61,271.08 EMA 21 68,212.94 EMA 50 73,481.04
Chart saved to btcusdt-1d.png
The chart is saved as a PNG next to the script. A few ways to adapt it:
- Another market:
python candlestick_chart.py bybit ETHUSDTorpython candlestick_chart.py kraken BTCUSD. Check the exchanges page for each exchange’s symbol format. - Another timeframe: set
TIMEFRAMEto1hor4hfor intraday charts. - More history: raise
RESULTS, up to the history your plan includes (50 candles on Basic, 300 on Pro). - Other indicators: add more entries to the
indicatorslist infetch_emas(). Any indicator that returns one value per candle can be drawn withmake_addplotthe same way.
Where to go from here
- Every parameter and field of the candles endpoint: Candles API
- Trend and pullback checks with the 21, 50 and 200 EMA: EMA API
- Keep your chart live without polling: Stream real-time indicators over WebSocket
- Compare history limits and request rates: Pricing
Ready to plot your own? Start for free with a 7-day trial on Basic or Pro. If you build something with it, we’d love to hear about it: get in touch.