DEV Community

shady shafik
shady shafik

Posted on • Originally published at Medium

Algorithmic Trading: A Beginners Guide series.

What is algorithmic Trading ?!

In simple words, algorithmic trading is the use of programs to make systematic trades based on the strategy implemented by the programming language.
algorithmic trading can be fully-automated, semi-automated, or give signals to be executed manually.


In this article, we will develop a simple semi-automated strategy using Binance API to get data and execute trades.
I am working with Jupiter notebook, using python, pandas, and NumPy

Starting with importing the libraries needed install python-binance to connect to Binance API.

I am using binance testnet API to make anyone able to go and execute the code even if you don’t have binance account.


first, you have to have an API KEY and SECRET KEY to provide to the client function to establish a connection
to generate an API key and secret key go to Binance Spot Test Network sign with GitHub and generate HMAC SHA256 key.
finally, replace APIKEY and SECRETKEY variables in the code with actual keys.



import pandas as pd
import numpy as np
!pip install python-binance
from binance import Client

APIKEY = 'Your API KEY'
SECRETKEY = 'Your Secret KEY'
client =Client(APIKEY,SECRETKEY)
client.API_URL = 'https://testnet.binance.vision/api'
acc = client.get_account()
acc
Enter fullscreen mode Exit fullscreen mode

after establishing connection let’s see our TEST account balance Info with client.get_account() function, and here is the result.


---


{'makerCommission': 0,
 'takerCommission': 0,
 'buyerCommission': 0,
 'sellerCommission': 0,
 'canTrade': True,
 'canWithdraw': False,
 'canDeposit': False,
 'updateTime': 1644598822834,
 'accountType': 'SPOT',
 'balances': [{'asset': 'BNB',
   'free': '1000.00000000',
   'locked': '0.00000000'},
  {'asset': 'BTC', 'free': '1.01300000', 'locked': '0.00000000'},
  {'asset': 'BUSD', 'free': '10000.00000000', 'locked': '0.00000000'},
  {'asset': 'ETH', 'free': '100.00000000', 'locked': '0.00000000'},
  {'asset': 'LTC', 'free': '500.00000000', 'locked': '0.00000000'},
  {'asset': 'TRX', 'free': '500000.00000000', 'locked': '0.00000000'},
  {'asset': 'USDT', 'free': '9449.55739000', 'locked': '0.00000000'},
  {'asset': 'XRP', 'free': '50000.00000000', 'locked': '0.00000000'}],
 'permissions': ['SPOT']}
Enter fullscreen mode Exit fullscreen mode

Now it’s time to get crypto data stream

we have more than one option about how to get data from Binance, in this article I want to make it simple enough so I am using

client.get_historical_klines() function

Parameters provided to this function are:

symbol: which is the cryptocurrency symbol you want to trade in our case its BTCUSDT

Time Frame: time frame which you’ll trade in our case I chose a 1minute time frame.

Period: How many past periods to get in our case I chose 20 minutes.



def dataorg(symbol):
    data = pd.DataFrame(client.get_historical_klines( symbol ,
                                                      '1m',                                               
                                            '20 min ago UTC'))
    df = data.iloc[:,:6]
    df.columns = ['Time', 'Open', 'High' , 'Low',
                                         'Close','Volume']
    df = df.set_index('Time')
    df.index = pd.to_datetime(df.index,unit='ms')
    df = df.astype(float)
    return df


dataorg('BTCUSDT')
Enter fullscreen mode Exit fullscreen mode

I defined a function that takes a symbol argument to organize data,
and make a data frame out of it

here is the resulting data frame containing:

Time , Open Price , Low Price , Close Price and Volume.

dataframe


Here we want to calculate the cumulative return of the last 20 minutes to start work on the trading strategy.

Cumulative return formula: (1+ 1min return)*(1+cumlative return of last min)-1

pct_change(): calcluate the change in price in the last period.

cumprod(): calculate the second half of the formula.


test = dataorg('BTCUSDT')
ret = (test.Open.pct_change() + 1).cumprod() -1
ret
Time
2022-02-11 16:52:00         NaN
2022-02-11 16:53:00    0.000279
2022-02-11 16:54:00    0.000974
2022-02-11 16:55:00    0.001551
2022-02-11 16:56:00    0.001645
2022-02-11 16:57:00    0.002303
2022-02-11 16:58:00    0.002782
2022-02-11 16:59:00    0.002060
2022-02-11 17:00:00    0.001818
2022-02-11 17:01:00    0.000858
2022-02-11 17:02:00    0.001216
2022-02-11 17:03:00    0.002534
2022-02-11 17:04:00    0.002666
2022-02-11 17:05:00    0.003242
2022-02-11 17:06:00    0.002548
2022-02-11 17:07:00    0.001416
2022-02-11 17:08:00    0.002460
2022-02-11 17:09:00    0.002109
2022-02-11 17:10:00    0.002550
2022-02-11 17:11:00    0.003376
Name: Open, dtype: float64
Enter fullscreen mode Exit fullscreen mode

Strategy implementation

We will develop a trend following strategy which as simple as:
If the price of Bitcoin increases by more than a certain percentage (0.2%) then BUY order and after buy If price increased or decreased by certain percentage ( 0.2% , -0.2%) then SELL.


BTC chart


def strategy(symbol,qty,inPosition=False):
    while True:
        df = dataorg(symbol)
        cumret = (df.Open.pct_change()+1).cumprod()-1
        if not inPosition:
               if cumret[-1] > 0.002:
                    ordertime = df.index[-1]
                    order = client.create_order(symbol=symbol,  
                    side='BUY',type='MARKET', quantity=qty)

                    print(order)
                    inPosition=True
                    break
                else:
                    print('No trade excuted')
     if inPosition:
        while True:
            df=dataorg(symbol)
            afterbuy = df.loc[df.index > pd.to_datetime(
            order['transactTime'],
            unit='ms')]

            if len(afterbuy) > 0:
                afterbuyret =  (df.Open.pct_change()+1).cumprod()-1                    
                print(afterbuyret)
                if afterbuyret[-1]>0.002 or afterbuyret[-1]< -0.002:

                    sellorder = client.create_order(symbol=symbol,
                                        side='SELL',type='MARKET',
                                                 quantity=qty)
                    print(sellorder)
                    break
Enter fullscreen mode Exit fullscreen mode

it’s time to see the prices in the last 20 mins in a plot.

test.Open.plot()

Enter fullscreen mode Exit fullscreen mode

BTC Price plot

It seems like we have an uptrend .


Trade execution

Our final step is to call strategy() function and wait for a trade to be filled,

In this case we have a buy order filled then list of cumulative return after a trade and when the return exceed our threshold (+0.2% or -0.2%) then a sell trade been filled
and it’s a profitable trade 😀

strategy('BTCUSDT', 0.001)
{'symbol': 'BTCUSDT', 'orderId': 4982968, 'orderListId': -1, 'clientOrderId': 'oappYtNU1466jYiXCV3URd', 'transactTime': 1644599469117, 'price': '0.00000000', 'origQty': '0.00100000', 'executedQty': '0.00100000', 'cummulativeQuoteQty': '43.65218000', 'status': 'FILLED', 'timeInForce': 'GTC', 'type': 'MARKET', 'side': 'BUY', 'fills': [{'price': '43652.18000000', 'qty': '0.00100000', 'commission': '0.00000000', 'commissionAsset': 'BTC', 'tradeId': 1240296}]}
Time
2022-02-11 16:52:00         NaN
2022-02-11 16:53:00    0.000279
2022-02-11 16:54:00    0.000974
2022-02-11 16:55:00    0.001551
2022-02-11 16:56:00    0.001645
2022-02-11 16:57:00    0.002303
2022-02-11 16:58:00    0.002782
2022-02-11 16:59:00    0.002060
2022-02-11 17:00:00    0.001818
2022-02-11 17:01:00    0.000858
2022-02-11 17:02:00    0.001216
2022-02-11 17:03:00    0.002534
2022-02-11 17:04:00    0.002666
2022-02-11 17:05:00    0.003242
2022-02-11 17:06:00    0.002548
2022-02-11 17:07:00    0.001416
2022-02-11 17:08:00    0.002460
2022-02-11 17:09:00    0.002109
2022-02-11 17:10:00    0.002550
2022-02-11 17:11:00    0.003376
2022-02-11 17:12:00    0.003520
Name: Open, dtype: float64

{'symbol': 'BTCUSDT', 'orderId': 4983220, 'orderListId': -1, 'clientOrderId': 'OWLlWGmI044UlKEFaURffy', 'transactTime': 1644599521374, 'price': '0.00000000', 'origQty': '0.00100000', 'executedQty': '0.00100000', 'cummulativeQuoteQty': '43.65542000', 'status': 'FILLED', 'timeInForce': 'GTC', 'type': 'MARKET', 'side': 'SELL', 'fills': [{'price': '43655.42000000', 'qty': '0.00100000', 'commission': '0.00000000', 'commissionAsset': 'USDT', 'tradeId': 1240505}]}

Enter fullscreen mode Exit fullscreen mode

what's next

Ok guys, that's it for this article of course this isn't the best trading bot to make profits and it lacks a lot,
especially data anlysis and backtesting ,
I'll provide more insights in my upcoming article,
I hope you enjoy.

Top comments (0)