@naresh_janagama HI let me share script with you plz check as i m not sure what is going wrong
import logging
import threading
from fyers_apiv3 import fyersModel
from fyers_apiv3.FyersWebsocket import data_ws
from datetime import datetime, timezone, timedelta
import time
import credentials as cd
Logging Configuration
logging.basicConfig(
level=[logging.INFO](http://logging.INFO),
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('trading_bot.log'),
logging.StreamHandler()
]
)
Configuration
CLIENT_ID = cd.CLIENT_ID # Replace with your actual Fyers Client ID
ACCESS_TOKEN = cd.ACCESS_TOKEN # Replace with your actual access token
SYMBOLS = [“NSE:NIFTY24D1924550CE”, “NSE:NIFTY24D1924300PE”] # Example Symbols (will update this later)
MINIMUM_LOT_SIZE = 25
MAX_POSITIONS = 2
INITIAL_STOP_LOSS_OFFSET = 0.05
class TradingBot:
def **init**(self):
self.fyers = fyersModel.FyersModel(
client_id=CLIENT_ID,
token=ACCESS_TOKEN,
log_path="",
is_async=False
)
self.positions = {}
self.latest_prices = {}
self.lock = threading.Lock()
[self.ws](http://self.ws) = None
self.entry_prices = {}
self.stop_losses = {}
self.trailing_stop_losses = {} # For storing trailing stop loss
self.price_crossed_below = {symbol: True for symbol in SYMBOLS} # Initialized to True
self.price_above_threshold = {symbol: False for symbol in SYMBOLS}
def get_user_inputs(self):
global SYMBOLS
symbols_input = input("Enter symbols separated by comma (e.g., NSE:SYMBOL1,NSE:SYMBOL2): ")
SYMBOLS = [symbol.strip() for symbol in symbols_input.split(",")]
[logging.info](http://logging.info)(f"Trading Symbols : {SYMBOLS}")
for symbol in SYMBOLS:
while True:
try:
entry_price = float(input(f"Enter entry price for {symbol}: "))
stop_loss = float(input(f"Enter stop loss for {symbol}: "))
if stop_loss >= entry_price:
logging.error("Stop loss can not be greater or equal to Entry price. Please enter correct values")
continue
self.entry_prices[symbol] = entry_price
self.stop_losses[symbol] = stop_loss
break
except ValueError:
print("Invalid input. Please enter a valid number.")
[logging.info](http://logging.info)(f"User defined entry prices : {self.entry_prices}")
[logging.info](http://logging.info)(f"User defined stop loss : {self.stop_losses}")
def place_order(self, symbol, side, quantity, stop_loss=0):
try:
adjusted_quantity = max(MINIMUM_LOT_SIZE,
(quantity // MINIMUM_LOT_SIZE) * MINIMUM_LOT_SIZE)
order_data = {
"symbol": symbol,
"qty": adjusted_quantity,
"type": 3 if side == 1 else 2, # Stop-Market order for buy, Market for sell
"side": side,
"productType": "INTRADAY",
"validity": "DAY",
"takeProfit": 0,
"offlineOrder": False, # Set this as False if you're trading during market hours
"disclosedQty": 0
}
if side == 1: # For buying we need stop loss
stop_price = stop_loss
stop_loss_offset = abs(self.entry_prices[symbol] - stop_price)
order_data["stopLoss"] = stop_loss_offset
order_data["stopPrice"] = stop_price # Add stop price for Stop Order
logging.debug(f"Placing order with data: {order_data}")
response = [self.fyers.place](http://self.fyers.place)_order(order_data)
if response.get('code') == 200:
[logging.info](http://logging.info)(f"Cover Order placed successfully: {symbol} - {side} - Quantity: {adjusted_quantity}, Response: {response}")
return response.get('data', {}).get('id'), response.get('data', {}).get('price', self.entry_prices[symbol])
else:
logging.error(f"Cover Order placement failed: {response}")
return None, None
except Exception as e:
logging.error(f"Error placing cover order: {e}")
return None, None
def get_positions(self):
try:
response = self.fyers.positions()
if response and response.get('code') == 200:
return response.get('netPositions', [])
else:
logging.error(f"Error fetching positions: {response}")
return []
except Exception as e:
logging.error(f"Error fetching positions: {e}")
return []
def calculate_trailing_stop_loss(self, entry_price, current_price):
percentage_increase = ((current_price - entry_price) / entry_price) * 100
if percentage_increase >= 250:
return None # Close position
elif percentage_increase >= 175:
return entry_price + (entry_price * 1.5)
elif percentage_increase >= 150:
return entry_price + (entry_price * 1.25)
elif percentage_increase >= 125:
return entry_price + (entry_price * 1.0)
elif percentage_increase >= 100:
return entry_price + (entry_price * 0.75)
elif percentage_increase >= 75:
return entry_price + (entry_price * 0.5)
elif percentage_increase >= 50:
return entry_price + (entry_price * 0.4)
elif percentage_increase >= 40:
return entry_price + (entry_price * 0.3)
elif percentage_increase >= 30:
return entry_price + (entry_price * 0.2)
elif percentage_increase >= 20:
return entry_price + (entry_price * 0.1)
else:
return self.stop_losses[symbol]
def on_message(self, msg):
try:
logging.debug(f"Received message: {msg}") # Log the entire message for debugging
if 'symbol' in msg: # Filter messages containing symbol
symbol = msg.get('symbol') # Get symbol using .get(), default value can be None or empty string if required
price = msg.get('ltp')
if symbol is None or price is None:
logging.warning("Symbol or price is missing in the message, skipping this message")
return
self.latest_prices[symbol] = price
logging.debug(f"Received price for {symbol}: {price}")
# Track if price is above the threshold
if price >= self.entry_prices[symbol]:
self.price_above_threshold[symbol] = True
logging.debug(f"{symbol}: Price is above or equal to threshold: {price}")
else:
self.price_above_threshold[symbol] = False
logging.debug(f"{symbol}: Price is below threshold: {price}")
# Update price crossing status
if price < self.entry_prices[symbol]:
self.price_crossed_below[symbol] = True # Mark crossing only when it goes from above to below
logging.debug(f"{symbol}: Price crossed below threshold from above. self.price_crossed_below : {self.price_crossed_below[symbol]}")
# Check entry conditions
if (len(self.positions) < MAX_POSITIONS and
symbol not in self.positions):
# Enter only if price crosses from below and is not already above the threshold
if price >= self.entry_prices[symbol] and self.price_crossed_below[symbol]:
[logging.info](http://logging.info)(f"Entry conditions met for {symbol}. Price: {price}, Crossed from below: {self.price_crossed_below[symbol]}")
quantity = MINIMUM_LOT_SIZE
order_id, executed_price = [self.place](http://self.place)_order(symbol, 1, quantity, self.stop_losses[symbol])
if order_id and executed_price != 0:
# Wait for a short time to get the new position update
time.sleep(1)
positions = self.get_positions()
position_found = False
for position in positions:
if position['symbol'] == symbol and position['netQty'] > 0:
position_found = True
self.positions[symbol] = {
'entry_price': executed_price,
'stop_loss': self.stop_losses[symbol],
'quantity': quantity,
'side': 1
}
self.trailing_stop_losses[symbol] = self.stop_losses[symbol]
self.price_crossed_below[symbol] = False # Reset cross flag
[logging.info](http://logging.info)(f"Opened new position for {symbol} at {executed_price} with SL: {self.stop_losses[symbol]}")
break
if not position_found:
logging.warning(f"Order placed for {symbol}, but position not found in response. Not considering it as opened position.")
else:
logging.debug(f"Entry conditions not met for {symbol}. self.price_crossed_below: {self.price_crossed_below[symbol]}, not self.price_above_threshold: {not self.price_above_threshold[symbol]}")
elif symbol in self.positions:
current_position = self.positions[symbol]
trailing_stop = self.calculate_trailing_stop_loss(current_position['entry_price'], price)
if trailing_stop is None:
[logging.info](http://logging.info)(f"Price of {symbol} reached 250%. Closing position")
self.close_position(symbol)
elif trailing_stop > self.trailing_stop_losses[symbol]:
[logging.info](http://logging.info)(f"Updating trailing stop loss of {symbol} from {self.trailing_stop_losses[symbol]} to {trailing_stop}")
self.trailing_stop_losses[symbol] = trailing_stop
[self.place](http://self.place)_order(symbol, 1, current_position['quantity'], trailing_stop)
else:
logging.debug(f"Message doesn't contain symbol, skipping:{msg}")
except KeyError as ke:
logging.error(f"KeyError processing message: {ke} , Message: {msg}")
except Exception as e:
logging.error(f"Error processing message: {e}, Message: {msg}")
def start_websocket(self):
def on_connect():
[logging.info](http://logging.info)("WebSocket connected")
[self.ws](http://self.ws).subscribe(SYMBOLS)
[logging.info](http://logging.info)(f"Subscription initiated for {SYMBOLS}")
def on_close():
[logging.info](http://logging.info)("WebSocket connection closed")
def on_error(error):
logging.error(f"WebSocket error: {error}")
[self.ws](http://self.ws) = data_ws.FyersDataSocket(
access_token=ACCESS_TOKEN,
log_path="",
litemode=False,
write_to_file=False,
reconnect=True,
on_connect=on_connect,
on_close=on_close,
on_error=on_error,
on_message=self.on_message,
reconnect_retry=10
)
[self.ws](http://self.ws).connect()
def run(self):
[logging.info](http://logging.info)("Starting trading bot...")
self.get_user_inputs()
websocket_thread = threading.Thread(target=self.start_websocket, daemon=True)
websocket_thread.start()
while True:
try:
current_time = [datetime.now](http://datetime.now)(timezone.utc) + timedelta(hours=5, minutes=30)
if current_time.time() > datetime.strptime("15:15", "%H:%M").time():
[logging.info](http://logging.info)("Market closed. Closing all positions...")
for symbol in list(self.positions.keys()):
self.close_position(symbol)
break
time.sleep(1)
except Exception as e:
logging.error(f"Error in main loop: {e}")
time.sleep(1)
def close_position(self, symbol):
with self.lock:
if symbol in self.positions:
position = self.positions[symbol]
order_id, * = *[*self.place*](http://self.place)order(symbol, -position['side'], position['quantity']) #for closing we will use market order no need to pass any stop loss while closing
if order_id:
[logging.info](http://logging.info)(f"Closed position for {symbol}")
del self.positions[symbol]
if symbol in self.trailing_stop_losses:
del self.trailing_stop_losses[symbol]
if name == “main”:
try:
bot = TradingBot()
[bot.run](http://bot.run)()
except Exception as e:
logging.error(f"Fatal error: {e}")