How to automate the Simple Moving Average Strategy using Alice Blue

The calculation of the Simple Moving Average is fairly simple. It has two properties – Length, Source.

 Like – SMA(5, Close) takes the closing prices of the last 5 points and divides it by 5.

It is regardless of the timeframe. If you take the points on an hourly timeframe i.e. you feed the data one closing point at the end of each hour. SMA(5, Close) will take the closing prices of the last 5 points and divides it by 5.

Here is SMA(5,Close) and SMA(10,Close) plotted into INFY. 

Here is the Tradingview Chart published – Infy Alice Blue Crossover Strategy Reference for NSE:INFY by Amit_Ghosh

Strategy

As per the Moving Average Crossover Strategy’s theory, when SMA of smaller length crosses the SMA of bigger length, it will generate a buy signal. And, vice-versa.

Also, the source has to be (here, it is assumed close) the same.

Apart from normal Python local IDEs, You can also use Google Collab which is a sort of online Jupyter Notebooks. Let’s install the Python SDK for Alice Blue API written by krishnavelu.

Type pip install alice-blue and press enter.

The Code Snippet

Here goes the code snippet of Simple Moving Average Strategy written by krishnavelu

				
					import logging
import datetime
import statistics
from time import sleep
from alice_blue import *

# Config
username = 'username'
password = 'password'
api_secret = 'api_secret'
twoFA = 'a'
EMA_CROSS_SCRIP = 'INFY'
logging.basicConfig(level=logging.DEBUG)        # Optional for getting debug messages.
# Config

ltp = 0
socket_opened = False
alice = None
def event_handler_quote_update(message):
    global ltp
    ltp = message['ltp']

def open_callback():
    global socket_opened
    socket_opened = True

def buy_signal(ins_scrip):
    global alice
    alice.place_order(transaction_type = TransactionType.Buy,
                         instrument = ins_scrip,
                         quantity = 1,
                         order_type = OrderType.Market,
                         product_type = ProductType.Intraday,
                         price = 0.0,
                         trigger_price = None,
                         stop_loss = None,
                         square_off = None,
                         trailing_sl = None,
                         is_amo = False)

def sell_signal(ins_scrip):
    global alice
    alice.place_order(transaction_type = TransactionType.Sell,
                         instrument = ins_scrip,
                         quantity = 1,
                         order_type = OrderType.Market,
                         product_type = ProductType.Intraday,
                         price = 0.0,
                         trigger_price = None,
                         stop_loss = None,
                         square_off = None,
                         trailing_sl = None,
                         is_amo = False)
    
def main():
    global socket_opened
    global alice
    global username
    global password
    global twoFA
    global api_secret
    global EMA_CROSS_SCRIP
    minute_close = []
    access_token =  AliceBlue.login_and_get_access_token(username=username, password=password, twoFA=twoFA,  api_secret=api_secret)
    alice = AliceBlue(username=username, password=password, access_token=access_token, master_contracts_to_download=['NSE'])
    
    print(alice.get_balance()) # get balance / margin limits
    print(alice.get_profile()) # get profile
    print(alice.get_daywise_positions()) # get daywise positions
    print(alice.get_netwise_positions()) # get netwise positions
    print(alice.get_holding_positions()) # get holding positions
    
    ins_scrip = alice.get_instrument_by_symbol('NSE', EMA_CROSS_SCRIP)
    
    socket_opened = False
    alice.start_websocket(subscribe_callback=event_handler_quote_update,
                          socket_open_callback=open_callback,
                          run_in_background=True)
    while(socket_opened==False):    # wait till socket open & then subscribe
        pass
    alice.subscribe(ins_scrip, LiveFeedType.COMPACT)
    
    current_signal = ''
    while True:
        if(datetime.datetime.now().second == 0):
            minute_close.append(ltp)
            if(len(minute_close) > 20):
                sma_5 = statistics.mean(minute_close[-5:])
                sma_20 = statistics.mean(minute_close[-20:])
                if(current_signal != 'buy'):
                    if(sma_5 > sma_20):
                        buy_signal(ins_scrip)
                        current_signal = 'buy'
                if(current_signal != 'sell'):
                    if(sma_5 < sma_20):
                        sell_signal(ins_scrip)
                        current_signal = 'sell'
            sleep(1)
        sleep(0.2)  # sleep for 200ms
    
if(__name__ == '__main__'):
    main()
				
			

Explanation of Code

Let’s explain this following code block of the strategy – 

				
					while True:
    if(datetime.datetime.now().second == 0):
        minute_close.append(ltp)
        if(len(minute_close) > 20):
            sma_5 = statistics.mean(minute_close[-5:])
            sma_20 = statistics.mean(minute_close[-20:])
            if(sma_5 > sma_20):
                buy_signal(ins_scrip)
            elif(sma_5 < sma_20):
                sell_signal(ins_scrip)
        sleep(1)
    sleep(0.2) 
				
			
  • It is seeking for LTP of the stock at the time when seconds are 00 like 19:16:00
  • It appends the LTP to an array minute_close array.
  • Now unless there is 20 points in that array we can not get SMA(20, Close) right? That’s why the if function is there.

Why Sleep functions? It is because we will get tons of LTP in one second alone. Don’t forget microseconds. It will be flooded. Exchanges do not have a concept of timeframe. They just throw the LTPs and we create the chart based on it with time frames.

So, the first moment we get a price, it tells to sleep for one second. If that second is over, it will hence wait for whole 59 seconds more before seconds became 00.

So, This is how We are creating mean of Candlesticks in Different Timeframes to get SMA.

buy_signal and sell_signal are pretty small functions that execute orders. That’s all.

				
					# Config
username = 'username'
password = 'password'
api_secret = 'api_secret'
twoFA = 'a'
				
			

The above snippet is the basic configuration of AliceBlue API.

API Secret is an API Key that you get from Alice. If You’ve opened your Aliceblue account with us, We will provide you. Check here.

It’s pretty basic but a good layman tutorial with a program that automates a simple strategy that can be tweaked around for many things. If You have any questions, feel free to ask in this thread of our forum.

Join The Conversation?