Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

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. 

Wednesday, November 25, 2020

Read Option chain data from Nifty using Python

Read Option chain data from Nifty using Python


Option chain data is very crucial for Future and Options(FnO) trader analysis, many use it for positional while many use it to find day trend and it's strength as well as option strike selection for trading.


In this blog post we will try to figure out how to read options data from NSE APIs using Python.

Code:

   
  #!/usr/bin/env python3
 
import requests
import pandas as pd
from datetime import datetime
from dateutil.relativedelta import relativedelta, TH
 
# Find next thursday to figure out weekly expiry.
def next_thu_expiry_date():
    todayte = datetime.today()
 
    next_thursday_expiry = todayte + relativedelta(weekday=TH(1))
 
    str_next_thursday_expiry = str(next_thursday_expiry.strftime("%d")) + "-" + next_thursday_expiry.strftime(
        "%b") + "-" + next_thursday_expiry.strftime("%Y")
    print(str_next_thursday_expiry)
    return str_next_thursday_expiry
 
 
def find_ce_pe(spot_price, ce_values, pe_values):
    spot_price = round(spot_price, -2)
    otm_calls = []
    otm_puts = []
 
    ce_dt = pd.DataFrame(ce_values).sort_values(['strikePrice'])
    pe_dt = pd.DataFrame(pe_values).sort_values(['strikePrice'], ascending=False)
 
    for ce_value in ce_dt['strikePrice']:
        if ce_value >= spot_price:
            otm_calls.append(ce_value)
            if len(otm_calls) > 10:
                break
 
    for ce_value in pe_dt['strikePrice']:
        if ce_value <= spot_price:
            otm_puts.append(ce_value)
            if len(otm_puts) > 10:
                break
 
    return otm_calls, otm_puts
 
 
def read_oi(spot_price, ce_values, pe_values, symbol):
    sheet_name = str(datetime.today().strftime("%d-%m-%Y")) + symbol
 
    strike_oi_ce_pe = find_ce_pe(float(spot_price), ce_values, pe_values)
 
    ce_dt = pd.DataFrame(ce_values).sort_values(['strikePrice'])
    pe_dt = pd.DataFrame(pe_values).sort_values(['strikePrice'], ascending=False)
 
    drop_col = ['pchangeinOpenInterest', 'askQty', 'askPrice', 'underlyingValue', 'totalBuyQuantity',
                'totalSellQuantity', 'bidQty', 'bidprice', 'change', 'pChange', 'impliedVolatility',
                'totalTradedVolume']
    ce_dt.drop(drop_col, inplace=True, axis=1)
    pe_dt.drop(drop_col, inplace=True, axis=1)
 
    ce_dt = ce_dt.loc[ce_dt['strikePrice'].isin(strike_oi_ce_pe[0])]
    pe_dt = pe_dt.loc[pe_dt['strikePrice'].isin(strike_oi_ce_pe[1])]
 
    # print(ce_dt[['strikePrice', 'lastPrice']])
    # print(pe_dt[['strikePrice', 'changeinOpenInterest']])
 
    print(ce_dt.head(1))
    print(pe_dt.head(1))
 
    print(str([spot_price, (ce_dt['changeinOpenInterest'].sum()),
               (pe_dt['changeinOpenInterest'].sum())]))
 
 
def main():
    symbols = ["BANKNIFTY", "NIFTY"]
    base_url = 'https://www.nseindia.com/api/option-chain-indices?symbol='
    url_oc = "https://www.nseindia.com/option-chain"
 
    for symbol in symbols:
        headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, ''like Gecko) '
                                 'Chrome/80.0.3987.149 Safari/537.36',
                   'accept-language': 'en,gu;q=0.9,hi;q=0.8', 'accept-encoding': 'gzip, deflate, br'}
        session = requests.Session()
        request = session.get(url_oc, headers=headers, timeout=5)
        cookies = dict(request.cookies)
        response = session.get(base_url + symbol, headers=headers, timeout=5, cookies=cookies)
        print(response.status_code)
        dajs = response.json()
        expiry = next_thu_expiry_date()
 
        spot_price = dajs['records']['underlyingValue']
        ce_values = [data['CE'] for data in dajs['records']['data'] if "CE" in data and data['expiryDate']
                     == expiry]
        pe_values = [data['PE'] for data in dajs['records']['data'] if "PE" in data and data['expiryDate']
                     == expiry]
 
        read_oi(spot_price, ce_values, pe_values, symbol)
 
        print(len(dajs))
 
 
if __name__ == '__main__':
    main()
  
  


In case of any doubt leave a comment I will try to answer.

Note: This post is for educational purpose only.

Sunday, November 22, 2020

Automatic Login to Zerodha using Python and Selenium

Hello Readers,

 

Today we will try to learn browser automation using Python and Selenium automation tool.

 

We will write a code to automate login process of Zerodha trading platform using selenium and python in Google Chrome browser.

Place a file named zerodha-credentials.json at the same location as the actual python script with zerodha credentials as below:



Run the below script to automatically login, code is mostly self-explanatory leave a comment if any doubt, I will try to respond.

 

Note: Think before storing your credentials in plain text, potential risk of it being compromised. This post is for education purpose to learn how we can automate web surfing using Python.