Home Article COMPLETE -Trending stretegy intraday COMPLETE -Trending stretegy intraday Software Technique Web Technique All Computer Language and Computer Language Practice Computer Educa January 19, 2025 0 Comments Share: Facebook Twitter Google+ Pinterest Whatsapp TREDING import numpy as np import datetime from SmartApi import SmartConnect import pyotp from logzero import logger import os # Setup API connection api_key = 'API KEY' username = 'CLINED ID' password = 'PASSWORD' 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 calculate trailing stop losses dynamically def calculate_trailing_stop_losses(entry_price, range_offset): """ Calculate trailing stop losses dynamically based on entry price and a predefined range. """ trailing_stop_loss_range = np.array([0.01, 0.02, 0.03, 0.04, 0.05, 0.1, 0.2, 0.3, 1, 1.5, 2, 3, 4, 5, 6, 7, 8, 9, 10]) return np.round(entry_price + trailing_stop_loss_range, 3) # Function to prepare order parameters for placing a NORMAL order def prepare_order_params(entry_price, stop_loss, trailing_stop_loss, lot_size, quantity, correlation_id): """ Prepares the order parameters for placing a NORMAL order (LIMIT). """ order_params = { "variety": "ROBO", # Use NORMAL variety instead of STOPLOSS ROBO "tradingsymbol": "NIFTY13FEB2524500CE", "symboltoken": "51279", "transactiontype": "BUY", "instrumenttype": "OPTIDX", "lotsize": str(lot_size), "exchange": "NFO", "ordertype": "LIMIT", # Use LIMIT STOPLOSS_LIMIT STOPLOSS_MARKET order type "producttype": "INTRADAY", "duration": "DAY", "price": str(entry_price), "stoploss": str(stop_loss), "squareoff": "15", # Target for order "trailingstoploss": str(trailing_stop_loss), "quantity": str(quantity) } logger.info(f"[{correlation_id}] Order Parameters (Variety=ROBO, TSL={trailing_stop_loss}): {order_params}") return order_params # Function to place an order with trailing stop loss def place_order_with_trailing_stop(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 (Trailing Stop Loss {order_params['trailingstoploss']}): {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 try: # Generate OTP token = os.getenv("OTP_SECRET_TOKEN", "YOUR TOKEN ") # 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 = 2 lot_size = 75 quantity = num_lots * lot_size # Define dynamic entry price (this can be updated as per market data) entry_price = 70 # Example entry price # Define stop loss values stop_loss_1 = np.round(entry_price - 0.001, 3) # Stop loss for 0.0001 stop_loss_2 = np.round(entry_price - 0.1, 3) # Stop loss for 0.1 stop_loss_3 = np.round(entry_price - 0.2, 3) # Stop loss for 0.2 # Log the stop losses logger.info(f"[{correlation_id}] Stop loss for value 0.0001: {stop_loss_1}") logger.info(f"[{correlation_id}] Stop loss for value 0.1: {stop_loss_2}") logger.info(f"[{correlation_id}] Stop loss for value 0.2: {stop_loss_3}") # Calculate trailing stop losses dynamically trailing_stop_losses = calculate_trailing_stop_losses(entry_price, 0.1) # Select the first trailing stop loss value (or adjust based on logic) selected_trailing_stop_loss = trailing_stop_losses[0] # Prepare the order parameters (always using NORMAL variety) order_params = prepare_order_params(entry_price, stop_loss_1, selected_trailing_stop_loss, lot_size, quantity, correlation_id) # Place the order with trailing stop loss (only call this once) order_id = place_order_with_trailing_stop(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