How to Calculate a 200-Day SMA on Binance with Python
Python Trading Bot
One of the most popular trading indicators used across all timeframes is the SMA, formally known as the Simple Moving Average.
As the crypto market continues to mature, and CEX’s / DEX’s make themselves popular, I thought it would be a great time to show you how easy it is to bring this indicator to your Crypto Trading Bot. You can use it on pretty much any of trading pairs, with the most popular ones being BTCETH, BTCBUSD, SOLETH, and more.
I’ll be demonstrating how to calculate this indicator using Python 3, Python Pandas, and data from Binance. I’ve linked all these resources at the bottom of this article.
What is the 200-Day SMA?
The 200-Day SMA is an indicator that is thought to be effective at indicating future price moves of a stock / crypto / forex pair. Formally, it is a simple (or unweighted) average of the past 200 daily price candles, although many traders use a 200-SMA on other timeframes as well.
The 200-Day SMA is also frequently used to identify SMA Cross events, such as the ‘Death Cross’ and ‘Golden Cross’. I’ll cover both of these in future articles.
How to Calculate
The calculation for the 200-Day SMA is as follows:
SMA = (Day 1 + Day 2 … + Day 200) / 200
What You’ll Need
- Python 3
- Python Panda’s
- (useful) An IDE. I use Jetbrains Pycharm, link at the bottom
How to Code
Start by retrieving data from Binance. To do this:
- Import the official Binance Python Connector
from binance.spot import Spot()
- Add the following function:
# Function to query Binance for candlestick data
def get_candlestick_data(symbol, timeframe, qty):
# Retrieve the raw data
raw_data = Spot().klines(symbol=symbol, interval=timeframe, limit=qty)
# Set up the return array
converted_data = []
# Convert each element into a Python dictionary object, then add to converted_data
for candle in raw_data:
# Dictionary object
converted_candle = {
'time': candle[0],
'open': float(candle[1]),
'high': float(candle[2]),
'low': float(candle[3]),
'close': float(candle[4]),
'volume': float(candle[5]),
'close_time': candle[6],
'quote_asset_volume': float(candle[7]),
'number_of_trades': int(candle[8]),
'taker_buy_base_asset_volume': float(candle[9]),
'taker_buy_quote_asset_volume': float(candle[10])
}
# Add to converted_data
converted_data.append(converted_candle)
# Return converted data
return converted_data
This function retrieves data for your desired asset pair, converts it into a dictionary, then returns the whole thing as an array.
P.S. The data has been formatted to comply with my ongoing open-sourced Python Trading Bot. Follow me here and my GitHub to stay updated!
Create An SMA Calculator Using Python and Pandas
Creating a generic SMA calculator is super simple with Python and Pandas! All you need is the symbol (trading pair), timeframe, and the size of the SMA you want and they’ll do the rest.
Here’s how:
- Retrieve
raw_data
usingget_candlestick_data
(I’ve assumed the maximum of 1000 rows for this) - Convert
raw_data
into a dataframe - ‘Roll’ through the dataframe and calculate the mean
# Function to calculate a generic SMA
def calc_sma(symbol, timeframe, sma):
# Get the raw data
raw_data = get_candlestick_data(symbol=symbol, timeframe=timeframe, qty=1000)
# Convert into dataframe
df_data = pandas.DataFrame(raw_data)
# Create name for new column
name = "SMA_" + str(sma)
# Roll through the dataframe to get the SMA
df_data[name] = df_data['close'].rolling(sma).mean()
return df_data
That’s literally it!
Get the 200-Day SMA from Binance
To retrieve the 200-day SMA, add the line below to your code base wherever you want to import it. Assuming a Bitcoin Ethereum pair (BTCETH):
calc_sma("BTCETH", "1d", 200)
Full Code
import pandas
from binance.spot import Spot
# Function to calculate a generic SMA
def calc_sma(symbol, timeframe, sma):
# Get the raw data
raw_data = get_candlestick_data(symbol=symbol, timeframe=timeframe, qty=1000)
# Convert into dataframe
df_data = pandas.DataFrame(raw_data)
# Create name for new column
name = "SMA_" + str(sma)
# Roll through the dataframe to get the SMA
df_data[name] = df_data['close'].rolling(sma).mean()
return df_data
# Function to query Binance for candlestick data
def get_candlestick_data(symbol, timeframe, qty):
# Retrieve the raw data
raw_data = Spot().klines(symbol=symbol, interval=timeframe, limit=qty)
# Set up the return array
converted_data = []
# Convert each element into a Python dictionary object, then add to converted_data
for candle in raw_data:
# Dictionary object
converted_candle = {
'time': candle[0],
'open': float(candle[1]),
'high': float(candle[2]),
'low': float(candle[3]),
'close': float(candle[4]),
'volume': float(candle[5]),
'close_time': candle[6],
'quote_asset_volume': float(candle[7]),
'number_of_trades': int(candle[8]),
'taker_buy_base_asset_volume': float(candle[9]),
'taker_buy_quote_asset_volume': float(candle[10])
}
# Add to converted_data
converted_data.append(converted_candle)
# Return converted data
return converted_data
Say Hi!
I love hearing from my readers, so feel free to reach out. It means a ton to me when you clap for my articles or drop a friendly comment — it helps me know that my content is helping.
❤