Home Article BUY SELL OR TARGET ORDER BUY SELL OR TARGET ORDER Software Technique Web Technique All Computer Language and Computer Language Practice Computer Educa March 09, 2025 0 Comments Share: Facebook Twitter Google+ Pinterest Whatsapp TREDING NIFTY SYMBALTOKEN-26000 , BANKNIFTY - SYMBALTOKEN-26009 import numpy as np import datetime from SmartApi import SmartConnect import pyotp from logzero import logger import os # Setup API connection api_key = 'xjsjbb' username = 'hgggsgdh' password = '23626378' smartApi = SmartConnect(api_key) # Function to generate OTP def generate_otp(token, correlation_id): """ Generates an OTP using the provided token. """ try: otp = pyotp.TOTP(token).now() logger.info(f"[{correlation_id}] Generated OTP: {otp}") return otp except Exception as e: logger.error(f"[{correlation_id}] Invalid Token: The provided token is not valid. Error: {str(e)}") raise e # Function to prepare order parameters for placing a NORMAL order def prepare_order_params(entry_price, lot_size, quantity, correlation_id): """ Prepares the order parameters for placing both BUY and SELL orders (LIMIT). """ buy_order_params = { "variety": "NORMAL", "tradingsymbol": "NIFTY13MAR2522750CE", "symboltoken": "45478", "transactiontype": "BUY", "instrumenttype": "OPTIDX", "optiontype": "call", "exchange": "NFO", "ordertype": "LIMIT", # Use LIMIT order type instead of STOPLOSS_LIMIT "producttype": "INTRADAY", "duration": "DAY", "price": str(entry_price), "quantity": str(quantity) } sell_order_params_1 = { "variety": "NORMAL", "tradingsymbol": "NIFTY13MAR2522750CE", "symboltoken": "45478", "transactiontype": "SELL", "instrumenttype": "OPTIDX", "optiontype": "call", "exchange": "NFO", "ordertype": "LIMIT", # Use LIMIT order type instead of STOPLOSS_LIMIT "producttype": "INTRADAY", "duration": "DAY", "price": str(entry_price - 2), # Example of selling at a lower price "quantity": str(quantity) } sell_order_params_2 = { "variety": "NORMAL", "tradingsymbol": "NIFTY13MAR2522750CE", "symboltoken": "45478", "transactiontype": "SELL", "instrumenttype": "OPTIDX", "optiontype": "call", "exchange": "NFO", "ordertype": "LIMIT", # Use LIMIT order type instead of STOPLOSS_LIMIT "producttype": "INTRADAY", "duration": "DAY", "price": str(entry_price + 2), # Example of selling at an even lower price "quantity": str(quantity) } logger.info(f"[{correlation_id}] Buy Order Parameters: {buy_order_params}") logger.info(f"[{correlation_id}] Sell Order 1 Parameters: {sell_order_params_1}") logger.info(f"[{correlation_id}] Sell Order 2 Parameters: {sell_order_params_2}") return buy_order_params, sell_order_params_1, sell_order_params_2 # Function to place an order def place_order(order_params, correlation_id): """ Places an order using the provided order parameters. """ try: order_id = smartApi.placeOrder(order_params) logger.info(f"[{correlation_id}] Order placed: {order_id}") return order_id # Return the order ID so we can cancel it later except Exception as e: logger.error(f"[{correlation_id}] Failed to place order: {str(e)}") return None # Function to cancel an order def cancel_order(order_id, correlation_id): """ Cancels the order using the provided order ID. """ try: cancel_params = { "variety": "NORMAL", # Always using NORMAL variety "orderid": order_id # The unique order ID to be canceled } response = smartApi.cancelOrder(cancel_params) # Call the cancel order API method if response.get("status", "") == "success": logger.info(f"[{correlation_id}] Order {order_id} successfully cancelled.") else: logger.error(f"[{correlation_id}] Failed to cancel order {order_id}: {response}") except Exception as e: logger.error(f"[{correlation_id}] Failed to cancel order {order_id}: {str(e)}") # Main Logic def main(): correlation_id = "abcde" # Unique identifier for tracking the flow try: # Generate OTP token = os.getenv("OTP_SECRET_TOKEN", "4345PGSFHLZIIDAXMMVGEJH2DHGHGSR3BJM") # Secure OTP token otp = generate_otp(token, correlation_id) # Generate session data session_data = smartApi.generateSession(username, password, otp) # Handle session generation failure if session_data.get('status', False): jwt_token = session_data['data'].get('jwtToken', None) refresh_token = session_data['data'].get('refreshToken', None) if jwt_token and refresh_token: # Fetch feed token feed_token = smartApi.getfeedToken() # Get user profile information profile_response = smartApi.getProfile(refresh_token) smartApi.generateToken(refresh_token) exchanges = profile_response['data']['exchanges'] # Define number of lots and lot size num_lots = 1 lot_size = 75 quantity = num_lots * lot_size # Define dynamic entry price (this can be updated as per market data) entry_price = 30 # Example entry price # Prepare the order parameters (using NORMAL variety) buy_order_params, sell_order_params_1, sell_order_params_2 = prepare_order_params(entry_price, lot_size, quantity, correlation_id) # Place both BUY and SELL orders simultaneously buy_order_id = place_order(buy_order_params, correlation_id) sell_order_id_1 = place_order(sell_order_params_1, correlation_id) sell_order_id_2 = place_order(sell_order_params_2, correlation_id) if buy_order_id and sell_order_id_1 and sell_order_id_2: logger.info(f"[{correlation_id}] Buy Order and two Sell Orders placed successfully with IDs: {buy_order_id}, {sell_order_id_1}, {sell_order_id_2}") # Ask the user if they want to cancel any of the orders from the terminal cancel_input = input(f"[{correlation_id}] Do you want to cancel any order? (buy/sell1/sell2/both/n): ").strip().lower() if cancel_input == 'buy': cancel_order(buy_order_id, correlation_id) elif cancel_input == 'sell1': cancel_order(sell_order_id_1, correlation_id) elif cancel_input == 'sell2': cancel_order(sell_order_id_2, correlation_id) elif cancel_input == 'both': cancel_order(buy_order_id, correlation_id) cancel_order(sell_order_id_1, correlation_id) cancel_order(sell_order_id_2, correlation_id) else: logger.error(f"[{correlation_id}] Missing JWT or refresh token in session data.") else: logger.error(f"[{correlation_id}] Session generation failed: {session_data}") except Exception as e: logger.exception(f"[{correlation_id}] An error occurred: {e}") # Execute the main logic if __name__ == "__main__": main() Copy Copied Text:
No comments