0% found this document useful (0 votes)
18 views

straddlesell_code

The document outlines a Python script that utilizes the Shoonya API for trading operations, including logging in, searching for scripts, and placing orders. It handles user credentials, retrieves market data, and manages order placements and cancellations. The script also calculates stop-loss and target prices for options trading based on the latest market prices.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

straddlesell_code

The document outlines a Python script that utilizes the Shoonya API for trading operations, including logging in, searching for scripts, and placing orders. It handles user credentials, retrieves market data, and manages order placements and cancellations. The script also calculates stop-loss and target prices for options trading based on the latest market prices.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 4

import datetime

from NorenRestApiPy.NorenApi import NorenApi


import pandas as pd
class ShoonyaApiPy(NorenApi):
def __init__(self):
NorenApi.__init__(self, host='https://api.shoonya.com/NorenWClientTP/',
websocket='wss://api.shoonya.com/NorenWSTP/')
global api
api = self

# import logging
import pyotp
#enable dbug to see request and responses
# logging.basicConfig(level=logging.DEBUG)

#start of our program


api = ShoonyaApiPy()

#credentials
# Open the file in read mode
with open('C:\\Users\\Kishan\\Desktop\\Python works\\ShoonyaAPI\\credentials.txt',
'r') as f:
lines = f.readlines() # Read the file and process the data

# Extract the values from the lines


uid = lines[0].strip()
pwd = lines[1].strip()
vc = lines[2].strip()
app_key = lines[3].strip()
imei = lines[4].strip()
token = lines[5].strip()
twoFA = pyotp.TOTP(token).now

# Use the variables to make API calls or perform other operations


ret = api.login(userid=uid, password=pwd, twoFA=pyotp.TOTP(token).now(),
vendor_code=vc, api_secret=app_key, imei=imei)

import re
sd = api.searchscrip('NFO', 'NIFTY')
sd = (sd['values'])
for Symbol in sd:
(Symbol['tsym'])

tsym_values = [Symbol['tsym'] for Symbol in sd]


dates = [re.search(r'\d+[A-Z]{3}\d+', tsym).group() for tsym in tsym_values]
formatted_dates = [datetime.datetime.strptime(date, '%d%b%y').strftime('%Y-%m-%d')
for date in dates]
sorted_formatted_dates = sorted(formatted_dates)
sorted_dates = [datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%d%b
%y').upper() for date in sorted_formatted_dates]
Expiry_date = (sorted_dates[0])
print(Expiry_date)

ret = api.get_quotes(exchange='NSE', token='26000')


ret

ret = api.get_quotes(exchange='NSE', token='26000')


ltp = ret.get("lp")
ltp = float(ltp)
ltp_str = str(ltp)
sym = ret.get("symname")
ExpDate = Expiry_date
TYPE = "P"
Strike = int(round(ltp/50,0)*50)

For_token = sym+ExpDate+TYPE+str(Strike)

opc = api.get_option_chain('NFO', For_token , Strike, 1)


opc1 = (opc['values'])

#df = pd.DataFrame(opc["values"])

#print(df)
#print(df['strprc'])
#print(df['strprc'].dtype)
#df['strprc'] = df['strprc'].astype(float)
CE_SYMBOL = sym+ExpDate+'C'+str(Strike)
PE_SYMBOL = sym+ExpDate+'P'+str(Strike)
print(CE_SYMBOL,PE_SYMBOL)
#print(Strike)

def get_token(opc1, tsym):


for item in opc1:
if item['tsym'] == tsym:
return item['token']
return None

# Test the function


CE_token = (get_token(opc1, CE_SYMBOL)) # should print '86406'
PE_token = (get_token(opc1, PE_SYMBOL)) # should print '86407'
print(CE_token ,PE_token)

CE_order = api.place_order(buy_or_sell='S', product_type='I',


exchange='NFO', tradingsymbol=CE_SYMBOL,
quantity=50, discloseqty=0,price_type='MKT', price=0,
trigger_price=0,
retention='DAY', remarks='my_order_001')
CE_orderno = CE_order['norenordno']
PE_order = api.place_order(buy_or_sell='S', product_type='I',
exchange='NFO', tradingsymbol=PE_SYMBOL,
quantity=50, discloseqty=0,price_type='MKT', price=0,
trigger_price=0,
retention='DAY', remarks='my_order_001')
PE_orderno = PE_order['norenordno']
print(CE_orderno,PE_orderno)

#import csv

TB = api.get_trade_book()
TB
#pd.DataFrame(ret)
#pd.DataFrame(ret).to_csv('output.csv',index=True)

def get_fillprice(TB, norenordno):


for item in TB:
if item['norenordno'] == norenordno:
return item['flprc']
return None

# Test the function


CE_fillprice = (get_fillprice(TB, CE_orderno)) # should print '86406'
PE_fillprice = (get_fillprice(TB, '22122300070640')) # should print '86407'
print(CE_fillprice,PE_fillprice)

CE_fillprice = float(CE_fillprice)
PE_fillprice = float(PE_fillprice)
SL_CE = float(format(round(CE_fillprice * 0.9 / 0.05) * 0.05,'.2f'))
SL_PE = float(format(round(PE_fillprice * 0.9 / 0.05) * 0.05,'.2f'))
SLT_CE = format(round(SL_CE * 1.03 / 0.05) * 0.05,'.2f')
SLT_PE = format(round(SL_PE * 1.03 / 0.05) * 0.05,'.2f')

print(SL_PE,SLT_PE)
print(SL_CE,SLT_CE )

PE_orderSL = api.place_order(buy_or_sell='B', product_type='I',


exchange='NFO', tradingsymbol=PE_SYMBOL,
quantity=50, discloseqty=0,price_type='SL-LMT',
price=SL_PE, trigger_price=SLT_PE,
retention='DAY', remarks='my_order_002')
CE_orderSL = api.place_order(buy_or_sell='B', product_type='I',
exchange='NFO', tradingsymbol=CE_SYMBOL,
quantity=50, discloseqty=0,price_type='SL-LMT',
price=SL_CE, trigger_price=SLT_CE,
retention='DAY', remarks='my_order_002')

OB = api.get_order_book()
OB

OB = api.get_order_book()

def get_openorder(OB, norenordno):


for item in OB:
if item['norenordno'] == norenordno:
return item['status']
return None
ret = get_openorder(OB, PE_orderno)
ret

OB = api.get_order_book()

open_orders = [] # list to store norenorderno values of completed orders

for order in OB:


if order['status'] == 'REJECTED':
open_orders.append(order['norenordno'])

print(open_orders) # this will print the list of norenorderno values for completed
orders

open_orders_C = open_orders

for order_number in open_orders:


ret = api.cancel_order(orderno=order_number)
if ret['stat'] == 'Ok':
print(f"Order {order_number} successfully cancelled")
else:
print(f"Error cancelling order {order_number}: {ret['stat']}")

You might also like