Technical Trading Bot – Strategy 3, Bollinger Bands

In this strategy I will be using Bollinger bands which are volatility bands plotted at a standard deviation level above and below a simple moving average of the price. Prices moving closer to the upper Bollinger band signal that the instrument is being overbought and prices moving closer to the lower Bollinger band signal that the instrument is being oversold. So, when in an overbought situation I will look to sell and in an oversold situation I will look to buy.

To achieve the above I will be creating a script in Python that will retrieve price data via Binance, once the data has been received, I will manipulate it further to derive to the values of the indicators above using the Python BTALIB library.

Find the full source code below. If you are requiring a Binance API and secret key, click here to create an account with them.

import pandas as pd
import btalib
from datetime import datetime
from binance.client import Client

api_key = 'BINANCE API KEY'
api_secret = 'BINANCE SECRET KEY'
client = Client(api_key,api_secret)

def Main(Instrument):
    #Here we define our data from date, in this case I want hourly data starting from yesterday
    Data = client.get_historical_klines(Instrument, '1h', '20 February, 2022')
    #Define the data for frame
    bnb_df = pd.DataFrame(Data, columns=['timestamp', 'Open', 'High', 'Low', 'Close','Volume', 'Ctime', 'Quotes', 'Trades', 'Taker base','Taker quote', 'Ignore'])
    #Set the index
    bnb_df.set_index('timestamp', inplace=True)
    #Convert the timestamp which is in MS to an appropriate timestamp
    bnb_df.index = pd.to_datetime(bnb_df.index, unit='ms')
    #Prepping the OHLCV data for validation
    ohlcv_columns = ['Open', 'High', 'Low', 'Close','Volume']
    #Validating the data types for the OHLCV data columns
    bnb_df[ohlcv_columns] = bnb_df[ohlcv_columns].astype('float')
    #Generating the Bollinger Bands
    BBANDS = btalib.bbands(bnb_df, period=12)
    #Merging the Bollinger Bands to our data frame
    bnb_df = bnb_df.join([BBANDS.df])
    #Writing the data frame to a CSV file
    bnb_df.to_csv(Instrument+'.csv') 

Main("BNBGBP") #For this example we are using BNB TO GBP although any pair would be available to you

Leave a Reply