0% found this document useful (0 votes)
369 views12 pages

How To Build A Crypto Trading - ABM

Uploaded by

alexbemu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
369 views12 pages

How To Build A Crypto Trading - ABM

Uploaded by

alexbemu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Open in app Get unlimited access

Search Medium

Published in Coinmonks

James Hinton Follow

Oct 13, 2022 · 6 min read · · Listen

Save

How to Build a Crypto Trading Bot with Binance and Python

H OW TO BUILD A C RYPTO TRADING BOT WITH BINANC E AND PYTH ON

How to Build a Crypto Trading Bot with Binance


and Python: Trading Bot Strategy Example
Welcome back to my series on building your own trading bot using Binance.
12 1
Crypto bot trading can be a lot of fun. There can be a lot of joy found in analyzing data,
identifying trends, and then making (hopefully lots) of money from your decisions. In
the stock market world, many people have stated that the discipline of quantitative
analysis can make you a better trader overall.

Whatever your motivation, I hope you enjoy this series.

About the Series


In this series, I show you how to use the REST API of Binance, the world’s largest
centralized crypto trading platform, to build a crypto trading bot. Together, we build an
example trading bot that identifies fast-rising crypto assets, buying them low and
selling them high. By the end of the series, you’ll have everything you need to build
your own trading bot. If you’d like further assistance, contact me here.

All activity is demonstrated in Python. Each episode contains working code samples,
with the full code accessible on GitHub here.

Note: all code is for example use only and I make no guarantees about the strategy. Do
your own research and use it at your own risk 😊.

In This Episode
By the end of this episode, you’ll have built your very own trading strategy and to
actively analyze market data.

Strategy Development

A Quick Note
Before diving into strategy development, I want to make a quick note about the
strategy. The strategy I’m demonstrating should only be used at your own risk — after
you do your own research. I cannot and do not make any statements about its viability.

If you do choose to use it, I only ask that you give me a quick shout-out on LinkedIn ❤

Strategy
The strategy I’ll be demonstrating is designed to take advantage of momentum-based
trading events. Here are the rules:
Condition 1: If the closing price of a token experiences a 10% or more price rise per
hour, for three consecutive hours, then open a trade. Call this a pump.

Condition 2: If a previously pumped token experiences price rises of less than 5%


per 30 minutes for two consecutive time periods, exit the position.

Condition 3: Use a trailing stop to constantly lock in profit.

Here’s what this would look like visually:


Visual representation of strategy for How to Build a Crypto Trading Bot with Binance and Python

To simplify code development, I’ll also implement the following restrictions:

Restriction 1: Only trade in tokens with a Quote Asset of Binance USD (BUSD) pairs.
This helps us avoid having to dynamically shift around our liquid capital to esoteric
pairs.

Restriction 2: Only trade on the Spot Market.

Restriction 3: Never risk more than 10% of available capital.

Note. If you’re someone who tracks crypto pump and dump events, this strategy could
be easily modified to identify these events. You could then filter these out from your
trading.

Getting Data
Strategy implementation starts with correctly formatting data.

I’ll start by updating the function get_candlestick_data from Episode 1 (episode list at
the bottom of the article). Readers who have seen my previous series How to Build a
MetaTrader 5 Python Trading Bot will recognize the data format. Without giving too
much away, I’ve standardized the format in preparation for a future series 😉

The Binance API documentation for Kline/Candlestick Data explains how to interpret
the results from the queries. Expressed in code, it looks like this:

1 # Function to query Binance for candlestick data


2 def get_candlestick_data(symbol, timeframe, qty):
3 # Retrieve the raw data
4 raw_data = Spot().klines(symbol=symbol, interval=timeframe, limit=qty)
5 # Set up the return array
6 converted_data = []
7 # Convert each element into a Python dictionary object, then add to converted_data
8 for candle in raw_data:
9 # Dictionary object
10 converted_candle = {
11 'time': candle[0],
12 'open': float(candle[1]),
13 'high': float(candle[2]),
g ( [ ]),
Updated
14 function for get_candlestick_data.
'low': float(candle[3]),Converts the data retrieved from Binance into a format consistent
with MetaTrader 5. Part of the series How to Build a Crypto Trading Bot with Binance and Python
15 'close': float(candle[4]),
16 'volume': float(candle[5]),
If17you’re following on from Episode
'close_time': 1, press Play on your IDE and you should see some
candle[6],
18
nicely results come back 😊
formatted'quote_asset_volume': float(candle[7]),
19 'number_of_trades': int(candle[8]),
20 'taker_buy_base_asset_volume': float(candle[9]),
Next, I’ll convert this data into a Pandas DataFrame. To do this, create a new Python file
21 'taker_buy_quote_asset_volume': float(candle[10])
called
22 strategy.py
} in your project. Add the below code to this file, noting that I’ve
added
23 a column
# AddRedOrGreen to the original data to identify if it’s ‘Red’ (trending down)
to converted_data

or24‘Green’ (trending
converted_data.append(converted_candle)
up):
25 # Return converted data
26 return converted_data
1 import pandas
binance_interaction.py hosted with ❤ by GitHub view raw
2 import numpy
3 import binance_interaction
4
5
6 # Function to convert candle data from Binance into a dataframe
7 def get_and_transform_binance_data(symbol, timeframe, number_of_candles):
8 # Retrieve the raw data from Binance
9 raw_data = binance_interaction.get_candlestick_data(symbol=symbol, timeframe=timeframe, q
10 print(raw_data[0]['time'])
11 # Transform raw_data into a Pandas DataFrame
12 df_data = pandas.DataFrame(raw_data)
13 # Convert the time to human readable format. Note that Binance uses micro-seconds.
14 df_data['time'] = pandas.to_datetime(df_data['time'], unit='ms')
15 # Convert the close time to human readable format. Note that Binance uses micro-seconds.
16 df_data['close_time'] = pandas.to_datetime(df_data['close_time'], unit='ms')
17 # Calculate if Red or Green
18 df_data['RedOrGreen'] = numpy.where((df_data['open'] < df_data['close']), 'Green', 'Red')
19 # Return the dataframe
20 return df_data

strategy.py hosted with ❤ by GitHub view raw

Update strategy.py with a function to convert raw Binance Data into a Pandas DataFrame. Part of the series How
to Build a Crypto Trading Bot with Binance and Python.

So far so good! Our Binance trading bot is coming along well!

Identifying a Buy
The strategy provides a series of rules which can be used to identify a buy . Here they

are in normal human speak:

1. Ensure the previous three candles are Green (rising)

2. If they are, ensure the closing price rise for each was ≥ 10%

3. If true, buy

4. Discard everything else.

Analyzing Individual Symbols


To implement this signal, a method is needed to analyze a given symbol. This can be
done by passing each symbol into a function called determine_buy_event . Here’s the
code, placed in strategy.py :
Code to programmatically determine a buy signal. Part of the series How to Build a Crypto Trading Bot with
Binance and Python

Note. Astute programmers will note the use of hard-coded functions for determining
buy events. This could certainly be abstracted into a simple for loop. I’ve done it this
way to emphasize the calculation.

Retrieving a List of Symbols


Next, a method is needed to generate a list of all the signals to be analyzed. To do this,
extract all the symbols with a specified base asset. Do this by adding the function
query_quote_asset_list in binance_interaction.py :
Function to query the full list of Binance trading pairs and extract only those with a specified quote asset. Part of
the series ‘How to Build a Crypto Trading Bot with Binance and Python’

At the time of writing, this returned 365 assets (tokens).

Analyze Each Symbol


It’s time to analyze the symbols!

This is done through a series of logical steps:

1. Query Binance for a list of symbols

2. Iterate through the symbol list and check each one

3. Return a True or False value for each symbol

Note. Binance has strict API Request limits, explained here.

Binance has strict request limits for its API. They are certainly generous but need to be
respected. To see the latest updates on the limit, check this webpage out. At the time of
writing, this is 1200 weighted requests per minute (reasonably generous).

To ensure that you stay below the request limit, I’ve implemented a time.sleep of 1
second per iteration. This doesn’t impact the performance of the algorithm, but stops
your API Key from getting banned ❤

Here’s the initial code to analyze your symbols:


Initial code for a function to analyze Binance symbols. Part of the series ‘How to Build a Crypto Trading Bot with
Binance and Python’.

I’ll return to this function in a future episode.

If you’d like to play with what you’ve developed so far, update your main as below:

__main__ updated to incorporate the analysis functions described so far. Part of the series ‘How to Build a Crypto
Trading Bot with Binance and Python’.
Make sure you’ve imported the functions we’ve developed import binance_interaction

and import strategy then press Play on your IDE.

Here’s what mine looked like with a 10% setting:

Demonstration of strategy for ‘How to Build a Crypto Trading Bot with Binance and Python’

Have some fun with this. Because of the design, you can modify the percentage gain
and quote assets pretty easily. See if you can find some trending tokens and then check
them out on Binance.

Wrapping Up
What a big episode! If you’ve been following along, you’re now analyzing symbols on
Binance to see if they’re trending!

We’ve developed a cohesive strategy, and now it’s time for us to take the next step by
learning how to place trades!

Check out Episode 3 to see just how to do that.

List of Episodes
1. Connecting to Binance

2. Crypto Trading Bot Strategy Example

3. Automating Trade Placement

4. Binance Crypto Bot Take Off: Putting it All Together

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.

New to trading? Try crypto trading bots or copy


trading
Binance Cryptocurrency Crypto Algorithmic Trading Trading Bot

Sign up for Coinmonks


By Coinmonks

A newsletter that brings you day's best crypto news, Technical analysis, Discount Offers, and MEMEs directly in your
inbox, by CoinCodeCap.com Take a look.

Emails will be sent to [email protected]. Not you?

Get this newsletter

You might also like