Hi, I NEED FUCTION FOR LONG ONLY POSITIONS. BUT I DIDNT CHANGE YOUR EXISTING STRUCTURE OF LONG AS WELL AS SHORT.
I am in need of a function similar to def cancel_all_order function which is available for squaring off all intraday trades through MIS product type. I built an algo for positional equity trading with product type as CNC.
pls help me with this.
I tried it by myself by copying the fuction from Dhan_tradehull.py and saved it by modifying it in my codebase. Pls review and help me if it is written correct.
from dhanhq import DhanContext, dhanhq, FullDepth, DhanLogin
import mibian
import datetime
import numpy as np
import pandas as pd
import traceback
import pytz
import requests
import pdb
import os
import time
import json
from pprint import pprint
import logging
import warnings
from typing import Tuple, Dict
from collections import Counter
import urllib.parse
import threading
import io
import sys
import re
from collections import OrderedDict
import pyotp
warnings.filterwarnings("ignore")
def cancel_all_CNC_orders(tsl) -> dict:
try:
order_details=dict()
product_detail ={'MIS':tsl.Dhan.INTRA, 'MARGIN':tsl.Dhan.MARGIN, 'MTF':tsl.Dhan.MTF, 'CO':tsl.Dhan.CO,'BO':tsl.Dhan.BO, 'CNC': tsl.Dhan.CNC}
product = product_detail['CNC']
time.sleep(1)
data = tsl.Dhan.get_order_list()["data"]
if data is None or len(data)==0:
return order_details
orders = pd.DataFrame(data)
if orders.empty:
return order_details
trigger_pending_orders = orders.loc[(orders['orderStatus'] == 'PENDING') & (orders['productType'] == product)]
open_orders = orders.loc[(orders['orderStatus'] == 'TRANSIT') & (orders['productType'] == product)]
for index, row in trigger_pending_orders.iterrows():
response = tsl.Dhan.cancel_order(row['orderId'])
for index, row in open_orders.iterrows():
response = tsl.Dhan.cancel_order(row['orderId'])
position_dict = tsl.Dhan.get_positions()["data"]
positions_df = pd.DataFrame(position_dict)
if positions_df.empty:
return order_details
positions_df['netQty']=positions_df['netQty'].astype(int)
bought = positions_df.loc[(positions_df['netQty'] > 0) & (positions_df["productType"] == product)]
sold = positions_df.loc[(positions_df['netQty'] < 0) & (positions_df['productType'] == product)]
for index, row in bought.iterrows():
qty = int(row["netQty"])
order = tsl.Dhan.place_order(security_id=str(row["securityId"]), exchange_segment=row["exchangeSegment"],
transaction_type=tsl.Dhan.SELL, quantity=qty,
order_type=tsl.Dhan.MARKET, product_type=row["productType"], price=0,
trigger_price=0)
tradingsymbol = row['tradingSymbol']
sell_order_id= order["data"]["orderId"]
order_details[tradingsymbol]=dict({'orderid':sell_order_id,'price':0})
time.sleep(0.5)
for index, row in sold.iterrows():
qty = int(row["netQty"]) * -1
order = tsl.Dhan.place_order(security_id=str(row["securityId"]), exchange_segment=row["exchangeSegment"],
transaction_type=tsl.Dhan.BUY, quantity=qty,
order_type=tsl.Dhan.MARKET, product_type=row["productType"], price=0,
trigger_price=0)
tradingsymbol = row['tradingSymbol']
buy_order_id=order["data"]["orderId"]
order_details[tradingsymbol]=dict({'orderid':buy_order_id,'price':0})
time.sleep(1)
if len(order_details)!=0:
_,order_price = tsl.order_report()
for key,value in order_details.items():
orderid = str(value['orderid'])
if orderid in order_price:
order_details[key]['price'] = order_price[orderid]
return order_details
except Exception as e:
print(e)
print("problem close all trades")
tsl.logger.exception("problem close all trades")
traceback.print_exc()