A small demo that fetches Binance kline (candlestick) data and visualizes it with Matplotlib. It includes a live plot that seeds recent history via the REST API and then subscribes to Binance's WebSocket kline stream for real-time updates.
- Clone the repository
git clone https://github.com/tarsislimadev/fatec-lp2-matplotlib.git- Install Python 3.10+ (or use your existing Python environment).
- Install required packages:
python -m pip install -r requirements.txt- Start the live plot (example):
python scripts/live_ws_plot.py --symbol BTCUSDT --interval 1m --window 200What the command does:
- Seeds the plot with the last
--windowhistorical klines for--symbol. - Subscribes to Binance's WebSocket
klinestream and updates the plot in real time.
Common options:
--symbol(default:BTCUSDT) — trading pair to display--interval(default:1m) — kline interval--window(default:200) — number of historical points to seed and show--refresh(default:1000) — plot refresh interval in ms
- If you see an error about
seaborn-darkgridnot found, installseabornor adjust the script's style fallback. - If
websocket-clientis missing, runpython -m pip install websocket-client. - The script prints
WebSocket connectedthenWebSocket closedwhen the plot window is closed or the connection drops; network interruptions can also close the socket.
- Add candlestick (OHLC) rendering instead of close-only lines.
- Persist finalized kline data (
x==true) to CSV or a local database. - Implement automatic reconnect with exponential backoff.
If you want any of the above, open an issue or submit a PR.
To fetch historical klines and save a static close-price plot:
python scripts/historical_plot.py --symbol BTCUSDT --interval 1m --limit 200 --output figures/btcusdt_1m.pngThe generated image will be saved under figures/.
- scripts/live_ws_plot.py — live WebSocket plot (real-time updates)
- scripts/historical_plot.py — fetch historical klines and save PNG
- requirements.txt — Python dependencies
It's recommended to use a virtual environment:
python -m venv .venv
source .venv/bin/activate # or .venv\Scripts\Activate.ps1 on Windows PowerShell
python -m pip install -r requirements.txtBinance REST & WebSocket docs: