Wednesday, April 7, 2021

Python Code for Straddle Algotrading using Zerodha KITE API

In this post I am sharing code of Short Straddle Order execution using Zerodha Kite API and Python Programming Language explained in Youtube Video 

Like and Subscribe channel for more such videos.

Code:

 


import logging
from datetime import datetime

from dateutil.relativedelta import relativedelta, TH
from kiteconnect import KiteConnect


def get_kite():
    kiteObj = KiteConnect(api_key='API_KEY')
    kiteObj.set_access_token('ACCESS_TOKEN')
    return kiteObj


kite = get_kite()
instrumentsList = None


def getCMP(tradingSymbol):
    quote = kite.quote(tradingSymbol)
    if quote:
        return quote[tradingSymbol]['last_price']
    else:
        return 0


def get_symbols(expiry, name, strike, ins_type):
    global instrumentsList

    if instrumentsList is None:
        instrumentsList = kite.instruments('NFO')

    lst_b = [num for num in instrumentsList if num['expiry'] == expiry and num['strike'] == strike
             and num['instrument_type'] == ins_type and num['name'] == name]
    return lst_b[0]['tradingsymbol']


def place_order(tradingSymbol, price, qty, direction, exchangeType, product, orderType):
    try:
        orderId = kite.place_order(
            variety=kite.VARIETY_REGULAR,
            exchange=exchangeType,
            tradingsymbol=tradingSymbol,
            transaction_type=direction,
            quantity=qty,
            price=price,
            product=product,
            order_type=orderType)

        logging.info('Order placed successfully, orderId = %s', orderId)
        return orderId
    except Exception as e:
        logging.info('Order placement failed: %s', e.message)


if __name__ == '__main__':
    # Find ATM Strike of Nifty
    atm_strike = round(getCMP('NSE:NIFTY 50'), -2)

    next_thursday_expiry = datetime.today() + relativedelta(weekday=TH(1))

    symbol_ce = get_symbols(next_thursday_expiry.date(), 'NIFTY', atm_strike, 'CE')
    symbol_pe = get_symbols(next_thursday_expiry.date(), 'NIFTY', atm_strike, 'PE')

    place_order(symbol_ce, 0, 75, kite.TRANSACTION_TYPE_SELL, KiteConnect.EXCHANGE_NFO, KiteConnect.PRODUCT_MIS,
                KiteConnect.ORDER_TYPE_MARKET)

    place_order(symbol_pe, 0, 75, kite.TRANSACTION_TYPE_SELL, KiteConnect.EXCHANGE_NFO, KiteConnect.PRODUCT_MIS,
                KiteConnect.ORDER_TYPE_MARKET) 

If you have any doubt then write it in comment box below.

Enjoy Coding and Algo Trading. 

7 comments:

  1. Hi, Thanks so much for this code. I am totally new to programming. Can you please help me how to edit the code to include the following things:
    1. Particular time when i want to execute everyday, like 10 am everyday
    2. Stop Loss order

    Thanks a ton in advance

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. thanks alot for sharing,
    but i am getting error kite.instruments('NFO')
    if possible ping me at telegram @Navin25
    otherwise give me your id, i will connect with you.

    ReplyDelete
  4. What if next expiry day Thursday is bank holiday. It should shift to wednesday.

    ReplyDelete
  5. Can you make the video on how to run this code properly

    ReplyDelete
  6. Hi, am a newbee in Python.. am getting the below error when try to get the cmp. any help would be appeciated.

    File "h:\Python_Workspace\zerodha_shortStraddle.py", line 22, in
    atm = get_CMP("NSE:INFY")
    File "h:\Python_Workspace\zerodha_shortStraddle.py", line 15, in get_CMP
    quote = kite.quote(tradingSymbol)
    File "C:\Users\sms\AppData\Local\Programs\Python\Python39\lib\site-packages\kiteconnect\connect.py", line 571, in quote
    data = self._get("market.quote", params={"i": ins})
    File "C:\Users\sms\AppData\Local\Programs\Python\Python39\lib\site-packages\kiteconnect\connect.py", line 836, in _get
    return self._request(route, "GET", url_args=url_args, params=params, is_json=is_json)
    File "C:\Users\sms\AppData\Local\Programs\Python\Python39\lib\site-packages\kiteconnect\connect.py", line 868, in _request
    auth_header = self.api_key + ":" + self.access_token
    TypeError: can only concatenate str (not "list") to str

    ReplyDelete
  7. I read your code and this is just placing order

    ReplyDelete