Home Article ROBO-ORDER-NIFTY BANKNIFTY OPTION CHAIN ALGO TREDING ORDER ROBO-ORDER-NIFTY BANKNIFTY OPTION CHAIN ALGO TREDING ORDER Software Technique Web Technique All Computer Language and Computer Language Practice Computer Educa January 27, 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 = 'hbbnnxxcI' username = 'M5273464565' password = '74646' 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, trailing_stop_level): """ Prepares the order parameters for placing a NORMAL order (LIMIT). The trailing stop loss will be set based on the value passed. """ order_params = { "variety": "ROBO", # Use NORMAL variety instead of STOPLOSS "tradingsymbol": "NIFTY20FEB2524350CE", "symboltoken": "63700", "transactiontype": "BUY", "stoploss": "0.05", # You can adjust this if needed "trailingstoploss": str(trailing_stop_level), # Set dynamic trailing stop loss "instrumenttype": "OPTIDX", "optiontype": "call", "exchange": "NFO", "ordertype": "LIMIT", # Use LIMIT order type instead of STOPLOSS_LIMIT "producttype": "INTRADAY", "duration": "DAY", "price": str(entry_price), "squareoff":"2", # target price exit "quantity": str(quantity) } logger.info(f"[{correlation_id}] Order Parameters (Variety=NORMAL, Trailing Stop Loss={trailing_stop_level}): {order_params}") return order_params # 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": "ROBO", # 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 trailing_stop_levels = [0.05, 0.1, 0.2, 0.3, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # Trailing stop levels try: # Generate OTP token = os.getenv("OTP_SECRET_TOKEN", "hdbbhdvjfjjfmsnnsjdjfbfbfnmsmdbddbJM") # 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 = 1 # Example entry price # Here we loop through the trailing stop levels for trailing_stop_level in trailing_stop_levels: # Prepare the order parameters (using NORMAL variety) order_params = prepare_order_params(entry_price, lot_size, quantity, correlation_id, trailing_stop_level) # Place the order (only call this once for each trailing stop level) order_id = place_order(order_params, correlation_id) if order_id: logger.info(f"[{correlation_id}] Order placed successfully with ID: {order_id}") # Ask the user if they want to cancel the order from the terminal cancel_input = input(f"[{correlation_id}] Do you want to cancel order {order_id}? (y/n): ").strip().lower() if cancel_input == 'y': cancel_order(order_id, 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