Implementation of Simple Moving Average for Buy/Sell Order placing automatically and grabing the profit at the end from KiteConnect.

Hello Everyone,As in Last Session and Video I Discussed about Automating Trading Strategy in python with the help of KiteConnect in that process i had only explained about getting API for order place.


In this Session i'm gonna discuss about Implementation of Simple Moving Average for Buy/Sell Order placing automatically and grabing the profit at the end.


To do this I Suggest Please Refer my Previous Post Included with the Video on Some Basic Simple Buy/Sell Order after this you need an Historical API offered by Zerodha Brokers which need to be Subscribed to Perform this SMA Strategy.


This Strategy Performs in Smooth Way with the Help of Access Token you need to follow the Same Procedure as Described in Previous post to Obtain an Access token and after getting that Follow this Input Code Below which is an Strategy Available in GitHub Posted by Zerodha .As i'am Doing in Windows Platform for that you need some basic Platform I Python Notebook and Python IDLE Version 3.6 for Smooth Operation.

From I Python Notebook i'm Usually extracting the Access Token which i have been explained in my previous video and after that you need to grab the Access Token and Place it in Access Token Column and Place the required API Key,Client ID of yours provided by Zerodha and fill up the other Credentials as of your's need.


As of Know just Run the Programme to Do this Please follow the Video for Proper Instructions and The Code Input to Backtest this Strategy




from kiteconnect import KiteConnect 

# Initialize all the variables we need
api_key='YOUR_API_KEY'
access_token = "YOUR_ACCESS_TOKEN_FROM_IPYTHON"
client_id = "YOUR_CLIENT-ID"

# Instrument token of RELIANCE
instrument_token = "738561" 

# Dates between which we need historical data
from_date = "2016-10-01"
to_date = "2016-10-17"

# Interval(minute, day, 3 minute, 5 minute...)
interval = "5minute"

kite = KiteConnect(api_key=api_key)
kite.set_access_token(access_token)

# Gets historical data from Kite Connect
def get_historical_data():
 return kite.historical(instrument_token, from_date, to_date, interval)

"""
  Implementation of the moving average strategy.
  We go through the historical records that 
  we received form Kite Connect, calculate moving average,
  and place a BUY or SELL order.
"""
def strategy(records):
 total_closing_price = 0
 record_count = 0
 order_placed = False
 last_order_placed = None
 last_order_price = 0
 profit = 0

 for record in records:
  record_count += 1
  total_closing_price += record["close"]
  
  #Moving avearge is calculated for every 5 ticks(records)
  if record_count >= 5:
   moving_average = total_closing_price/5

   # If moving average is greater than last tick, place a buy order
   if record["close"] > moving_average:
    if last_order_placed == "SELL" or last_order_placed is None:
     
     # If last order was sell, exit the stock first
     if last_order_placed == "SELL":
      print ("Exit SELL")

      # Calculate profit
      profit += last_order_price - record["close"]
      last_order_price = record["close"]

     # Fresh BUY order
     print ("place new BUY order")
     last_order_placed = "BUY"

  # If moving average is lesser than last tick, and there is a position, place a sell order
   elif record["close"] < moving_average:
    if last_order_placed == "BUY":
     
     # As last order was a buy, first let's exit the position
     print ("Exit BUY")
     
     # Calculate profit
     profit += record["close"] - last_order_price
     last_order_price = record["close"]
     
     # Fresh SELL order
     print ("place new SELL order")
     last_order_placed = "SELL"
     

   
   total_closing_price -= records[record_count-5]["close"]
 print ("Gross Profit ", profit)
 # PLace the last order 
 place_order(last_order_placed)

# Place an order based upon transaction type(BUY/SELL)
def place_order(transaction_type):
 kite.order_place(tradingsymbol="RELIANCE", exchange="NSE", quantity=1, transaction_type=transaction_type, order_type="MARKET", product="CNC")


def start():
 records = get_historical_data()
 strategy(records)

start()

--End Of Code Input--


Have any Doubt Regarding This Please Feel Free to Comment and Please Support us by Sharing us on other Social Media Platform