Learn how to code a simple trading algorithm in python on google colab with crypto on binance — Coding Part III

Marko Laesseriger, PhD
4 min readFeb 22, 2023

--

In the following article you will learn to set up and implement your own trading alogrithm for binance. This will work, so be careful when implementing it. Furthermore this is not an optimized trading strategy and should be applied with caution. If you don’t understand a thing don’t use/apply it as you may loose all your money. The purpose of this article thus is just for education reason and is not any sort of investment adivse or so.

You can use Google Colab to implement this algorithm.

First you need to download the necessary connection to binance:

pip install python-binance

Then you need to download the necessary libraries (not you might need to install them too, if you just set them up, this is again done via the “pip install [name of library]” command:

from binance import Client, ThreadedWebsocketManager, ThreadedDepthCacheManager
import pandas as pd
import numpy as np

Next, we connect our later to be written code to the Binance account via the key pair (keep them YOUR secret). To do so, you first need to activate your binance account. You can do that under the API menu on your binance account (a step-by-step guide can be found here). Note: I recommend not ticking the real trading option, so you can keep it as a test.

When done enter the keys between “ ” and you are ready to connect.

api_key= ""
api_secret= ""

client = Client(api_key, api_secret)

client.get_account()

In the next step we dive into the analysis of stock market data, to build upon previous market data our own algorithm. To do so, we get previous price data of a specific ticker (e.g. Bitcoin to Tether; BTC to USDT) as datastream via websocket. The code below get us the data (klines=as kandlesticks) for the air BTC/USDT, for every minute, starting from 30min ago. With pandas (pd), we can organize the data in a dataframe. As such, we can easily exclude everything we don’t need after the column volume (done via the command: pd.DataFrame()). Note further information for the binance API can be found here.

pd.DataFrame(client.get_historical_klines('BTCUSDT', '1m', '30 min ago UTC' ))

Next, we define the function for getting the data. You see we just want the columns [‘Time’,’Open’,’High’,’Low’,’Close’,’Volume’], so that we can build our algorithm based on these parameters.

def getminutedata(symbol, interval, lookback):
frame = pd.DataFrame(client.get_historical_klines(symbol, interval, lookback+ 'min ago UTC' ))
frame = frame.iloc[:,:6] #get first six columns
frame.columns = ['Time','Open','High','Low','Close','Volume']#naming columns
frame = frame.set_index('Time') #Time stemps in uniques time since year
frame.index = pd.to_datetime(frame.index, unit='ms') #transform index to readable time stamp
frame = frame.astype(float) #numbers are strings, we need to transform them to float values
return frame

You can test this code and even plot some things, so you see that we get now the necessary base information to build our algorithm:

test = getminutedata('BTCUSDT', '1m', '30')
test.Open.plot()

Finally we can define now our trading strategy:

This strategy is a naive trading algorithm and basically is doing the following:

  1. Buy if asset fell by more than 3% within the last 30min
  2. Sell if asset rises by more than 1.5% (1.5% return) or falls further by 1.5% (our exit).

The code would look like this for this strategy, the explenation of each main code line can be found as # next to the line. Be aware: This code is fully functionally and if applied and connected to you binance account, you start trading for real!

def strategy_1_launch(symbol, qty, entried=False): 
df = getminutedata(symbol, '1m', '30m') #we first check the data
cumulret = (df.Open.pct_change() +1).cumprod() - 1 #with this line we check the single series and take a look how asset was performing over last 30min
if not entried: #if we did not buy the asset yet, we define the buying condition
if cumulret[-1] < -0.03 #here check the very last entry of this vector to check for the buy condition (e.g. drop of 3%), if this is the case, the next line defines the buy order
order = client.create_order(symbol=symbol,
side='BUY',
type='MARKET'
quantity=qty) #Its recommendend to make this a limit or stop-loss order
print(order) #we print the order to get the confirmation that we made the order
entried=True
else:
print('No Trade has been executed')
if entried: #we check the data endless till the sell condition is set, if the order is done the next lines describe the sell condition
while True:
df = getminutedata(symbol, '1m', '30m')
sincebuy = df.loc[df.index > pd.to_datetime(
order['transactTime'], unit='ms')] #we this, we learn how my bought asset performs
if len(sincebuy) > 0:
sincebuyret= (sincebuy.Open.pct_change() +1).cumprod() - 1
if sincebuyret[-1] > 0.015 or sincebuyret[-1] < -0.015: #points where we make the sell order
order = client.create_order(symbol=symbol,
side='SELL',
type='MARKET'
quantity=qty)
print(order)
break #stop algorithm

strategy_1_launch('BTCUSDT', 0.001) #0.001 is the quantity BTC/USDT we buy/sell

The most important question now, does this code makes sense from a finance perspective? Well, you see that we just look 30min to the past, so this must be seen critical as maybe we should look further in the past to identify certain patterns (see technical analysis for this). Moreover, be aware to account for possible slippage and trading fees. Hence there is some improvements to do. These are up to you, but you have now a fully functional code to start automatic trading with the Binance API. Have fun coding and trading!

--

--

Marko Laesseriger, PhD

Entrepreneur and tech enthusiast. Finance background and PhD in Social Science. Work experience Big4, M&A, IT consulting.