Python Scripts for CCXT Crypto Candlestick (OHLCV) Charting Data
Cryptocurrency traders are obsessed with data. Analyzing trade by trade to find the perfect entry or exit point. Looking for the next big breakout. Every data point matters.
That’s why this tutorial will focus on the exchange charting data which most developers need when charting.
Real-time candlestick data is critical for accurate charting, quick decision making, and calculating the perfect trade.
Let’s dig into the different ways we can access candlestick data and how we can use this data to generate historical price charts.
Install Libraries
Before we begin, let’s go ahead and install the necessary libraries for the following examples. Pandas and Plotly will help us chart the data we collect from CCXT and Shrimpy.
pip install ccxt
pip install shrimpy-python
pip install pandas
pip install plotly==4.1.0
CCXT Example
Jumping right into the first example, we will take the LTC/BTC trading pair and collect the OHLCV candles from Binance.
Once we’ve collected the necessary data, we will use a plotting library to graph the candlesticks. The results of this example will be included at the end of the tutorial.
Imports
Import the necessary libraries for this example. In addition to the CCXT library, we will be using the Plotly library to chart the data and datetime to convert the candlestick data to our desired time format.
import ccxt
from datetime import datetime
import plotly.graph_objects as go
Create an Exchange Object
In this example, we will access candlestick data from the Binance exchange. Before we can request candlestick data, we must first create the Binance object that helps us manage the requests to the exchange.
binance = ccxt.binance()
trading_pair = 'LTC/BTC'
Get Data
Access the data by requesting the OHLCV candlestick data from the exchange. This will return the candlesticks based on the interval which is specified in the second argument. In this example, we will collect 1-hour candlesticks.
candles = binance.fetch_ohlcv(trading_pair, '1h')
Format Data
To plot the data from the exchange, we will use the Plotly library. This library requires our data to be formatted differently than what is returned from Binance. As a result, we will need to reformat this data to match the expected data format for the Plotly library.
dates = []
open_data = []
high_data = []
low_data = []
close_data = []for candle in candles:
dates.append(datetime.fromtimestamp(candle[0] / 1000.0).strftime('%Y-%m-%d %H:%M:%S.%f'))
open_data.append(candle[1])
high_data.append(candle[2])
low_data.append(candle[3])
close_data.append(candle[4])
Plot Candlesticks
Use the plotting library to display the candlesticks on a chart. This chart will be generated in a new browser window where you can click around on the chart and tinker with some of the data.
fig = go.Figure(data=[go.Candlestick(x=dates,
open=open_data, high=high_data,
low=low_data, close=close_data)])fig.show()
The final graph will look something like the following.
Complete Script
Putting everything we covered together, we find the full final version of the script would look something like the following.
import ccxt
from datetime import datetime
import plotly.graph_objects as go# collect the candlestick data from Binance
binance = ccxt.binance()
trading_pair = 'LTC/BTC'
candles = binance.fetch_ohlcv(trading_pair, '1h')
dates = []
open_data = []
high_data = []
low_data = []
close_data = []# format the data to match the charting library
for candle in candles:
dates.append(datetime.fromtimestamp(candle[0] / 1000.0).strftime('%Y-%m-%d %H:%M:%S.%f'))
open_data.append(candle[1])
high_data.append(candle[2])
low_data.append(candle[3])
close_data.append(candle[4])# plot the candlesticks
fig = go.Figure(data=[go.Candlestick(x=dates,
open=open_data, high=high_data,
low=low_data, close=close_data)])fig.show()
You can chart different assets across every major exchange by changing the trading pair and exchange from which you collect the OHLCV data.
Shrimpy Example
Besides CCXT, there are other libraries that can help you manage live and historical data from exchanges. One of those libraries is the Shrimpy Universal Crypto Trading APIs. These APIs provide candlestick data for every major exchange going back as far as 2011.
Before starting this script, you will need to sign up for a free Shrimpy Universal Crypto Trading APIs account.
After signing up, select the “Create Api Key” button to generate your free Master API Keys. Once you’ve generated your keys, ensure you have enabled “Data” permissions on the API keys and store them in a secure location.
Imports
We will start by importing the Shrimpy and Plotly libraries. These will be the only necessary libraries for this example tutorial.
import shrimpy
import plotly.graph_objects as go
Create a Client
Use your Shrimpy public and secret keys to create the Shrimpy client. This will allow you to access every exchange through the same client.
public_key = '...'
secret_key = '...'client = shrimpy.ShrimpyApiClient(public_key, secret_key)
Note: There are both a rest API client and websocket client for Shrimpy. We will be using the rest API client for this tutorial.
Get Data
Request data from the exchange. You are welcome to select any exchange or pair, but we will use the XRP/BTC pair on Bittrex.
candles = client.get_candles(
'bittrex', # exchange
'XRP', # base_trading_symbol
'BTC', # quote_trading_symbol
'1d' # interval
)
The “Get Candles” endpoint we used in the above snippet will allow us to get the latest 1,000 candlesticks for free. If your service requires additional historical data, the Shrimpy APIs support candlestick data all the way back to 2011 through the “Get Historical Candles” endpoint. The historical data endpoint requires a data subscription.
Using the historical data endpoint would look something like the example below.
candles = client.get_historical_candles(
'bittrex', # exchange
'XRP', # base_trading_symbol
'BTC', # quote_trading_symbol
'2017-02-11T00:00:00.000Z',# start_time
'2019-10-20T00:00:00.000Z',# end_time
1000, # limit
'1d' # interval
)
Notice how the request requires a starting date, end date, and a max candlestick limit (max 1,000). Since this endpoint is designed for collecting historical data, you would iterate over the candlesticks 1,000 at a time depending on what you want to collect.
Whichever endpoint you decide to access, the rest of the example will be identical. For the sake of brevity, we will assume you decide to use the “Get Candles” endpoint for the rest of the example code.
Format Data
Similar to the previous example with CCXT, we will need to format the Shrimpy candles to match the format required by the plotting library.
dates = []
open_data = []
high_data = []
low_data = []
close_data = []for candle in candles:
dates.append(candle['time'])
open_data.append(candle['open'])
high_data.append(candle['high'])
low_data.append(candle['low'])
close_data.append(candle['close'])
Plot Candlesticks
As the last step, we will plot the candles using the Plotly library.
fig = go.Figure(data=[go.Candlestick(x=dates,
open=open_data, high=high_data,
low=low_data, close=close_data)])fig.show()
The outcome of running all of these snippets would look something like the following chart.
Complete Script
Combining each code snippet above, we can construct the final script which we can use to run and get the candlestick data we need. Feel free to adjust the exchange, trading pair, and interval to access the data which matters to you.
import shrimpy
import plotly.graph_objects as go# sign up for the Shrimpy Developer APIs for your free API keys
public_key = '...'
secret_key = '...'# collect the historical candlestick data
client = shrimpy.ShrimpyApiClient(public_key, secret_key)
candles = client.get_candles(
'bittrex', # exchange
'XRP', # base_trading_symbol
'BTC', # quote_trading_symbol
'1d' # interval
)dates = []
open_data = []
high_data = []
low_data = []
close_data = []# format the data to match the plotting library
for candle in candles:
dates.append(candle['time'])
open_data.append(candle['open'])
high_data.append(candle['high'])
low_data.append(candle['low'])
close_data.append(candle['close'])# plot the candlesticks
fig = go.Figure(data=[go.Candlestick(x=dates,
open=open_data, high=high_data,
low=low_data, close=close_data)])fig.show()
That’s everything we have for this example, so let’s wrap up and send you on your way. A world of data awaits!
Conclusion
The Shrimpy Universal Crypto Trading APIs provide the easiest way to connect to every major exchange. Instead of writing custom code for every exchange, maintaining connections, storing data, and managing users, Shrimpy can replace your infrastructure to simplify your development cycle.
Collect historical market data, access real-time websockets, execute advanced trading strategies, and manage an unlimited number of users.
Don’t forget to follow us on Twitter and Facebook for updates, and ask any questions to our amazing, active community on Telegram.
The Shrimpy Team
Also, Read
- The Best Bitcoin Hardware wallet
- The Best Crypto Tax Software
- Best Crypto Trading Platforms
- Best Wallet for Uniswap
- Best Crypto Lending Platforms
- Top DeFi Projects
- 3Commas vs Cryptohopper vs Shrimpy
- The Idiots Guide to Margin Trading on Bitmex
- The Definitive Guide to Crypto Swing Trading
- Bitmex Advanced Margin Trading Guide
- Best Crypto APIs for Developers
- Crypto arbitrage guide: How to make money as a beginner
- Top Bitcoin Node Providers
- Best Crypto Charting Tool