ORB_Code
ORB_Code
try:
# Create a DataFrame with the fixed column structure
tick_df = pd.DataFrame([{
'symbol': tick.get('symbol', ''),
'open': tick.get('open', 0),
'last': tick.get('last', 0),
'high': tick.get('high', 0),
'low': tick.get('low', 0),
'ltt': tick.get('ltt', ''),
'close': tick.get('close', 0),
'exchange': tick.get('exchange', ''),
'stock_name': tick.get('stock_name', '')
}], columns=COLUMNS)
except Exception as e:
log_message(f"Error saving tick for {symbol}: {e}")
# Remove temp file in case of failure
if os.path.exists(temp_filename):
os.remove(temp_filename)
def is_valid_csv(filename):
"""
Check if the CSV file has valid content and can be read.
Returns True if valid, False if corrupted.
"""
try:
with open(filename, 'r') as f:
reader = csv.reader(f)
headers = next(reader, None)
# Check if headers are present and match expected columns
if headers is None or len(headers) != len(COLUMNS):
log_message(f"CSV file {filename} is corrupted or missing
columns.")
return False
return True
except Exception as e:
log_message(f"Error checking validity of {filename}: {e}")
return False
return latest_tick_row.to_dict()
except Exception as e:
log_message(f"Error getting latest tick for {symbol}: {e}, Attempt
{attempts+1}/{retries}")
attempts += 1
if attempts == retries:
log_message(f"Failed to get latest tick for {symbol} after {retries}
retries.")
return None
def first_order_placed(stock_token):
return first_orders.get(stock_token) is not None
def set_first_order(stock_token, action, price):
first_orders[stock_token] = (action, price)
def initialize_order_count(symbol):
order_counts[symbol] = {
'buy_count': 0,
'sell_count': 0,
'total_orders': 0
}
def check_order_limits(symbol):
return order_counts[symbol]['total_orders'] < MAX_ORDERS_PER_STOCK
def check_ticks():
global first_order
log_message("Checking ticks...")
current_time = datetime.now(pytz.timezone("Asia/Kolkata")).time()
if current_time >= datetime.strptime("15:00:00", "%H:%M:%S").time():
log_message("Order placing is disabled after 3:00 PM.")
return
latest_tick = get_latest_tick(symbol)
if latest_tick is None:
log_message(f"No valid tick for {symbol}, skipping this iteration.")
continue # Ignore this symbol and move to the next one
if latest_tick:
last_price = latest_tick['last'] # Assuming 'ltp' is the last traded
price
high = stock_high_low[symbol]['high']
low = stock_high_low[symbol]['low']
else:
# First order already placed
first_order_action, first_order_price = first_orders[symbol]
if os.path.exists(filename):
# Append to the existing CSV file
existing_df = pd.read_csv(filename)
df = pd.concat([existing_df, tick_df], ignore_index=True, sort=False)
else:
# Create a new CSV file if it doesn't exist
df = tick_df
df.to_csv(filename, index=False)
log_message(f"Tick saved for {symbol}: {tick.get('symbol')}, LTP:
{tick.get('last')}, LTT: {tick.get('ltt')}")
except Exception as e:
log_message(f"Error saving tick: {e}")
def log_tick_information(tick):
"""Log only essential information about the tick."""
try:
symbol = tick.get('symbol')
last_price = tick.get('last')
ltt = tick.get('ltt')
except Exception as e:
log_message(f"Error logging tick information: {e}")
def on_ticks(ticks):
log_message("Received ticks")
try:
if isinstance(ticks, dict):
ticks_list = [ticks]
elif isinstance(ticks, list):
ticks_list = ticks
else:
log_message(f"Error: Ticks should be a list or a dictionary, but
received: {type(ticks)}")
return
symbol = tick.get('symbol')
if symbol:
log_tick_information(tick) # Log only necessary fields
save_tick_to_file(symbol, tick) # Save filtered columns
else:
log_message("Error: Symbol missing in tick data")
except Exception as e:
log_message(f"Error in on_ticks: {e}")
def get_stock_names(filename):
log_message("Getting stock names...")
try:
# filename = 'Stock_List_Nifty50.csv'
df = pd.read_csv(filename)
stock_names = df.iloc[:, 0].tolist()
log_message(f"Extracted stock names: {stock_names}")
stock_isec_codes = {}
for stock_name in stock_names:
response = breeze.get_names(exchange_code='NSE', stock_code=stock_name)
return stock_isec_codes
except Exception as e:
log_message(f"Error getting stock names: {e}")
return {}
def get_high_low_for_stocks(stock_isec_codes):
log_message("Getting high and low values for stocks...")
try:
today = datetime.now(pytz.timezone("Asia/Kolkata"))
if datetime.now().time() >= datetime.strptime("09:30:00", "%H:%M:
%S").time() and datetime.now().time() < datetime.strptime("09:45:00", "%H:%M:
%S").time():
from_date = today.replace(hour=9, minute=15, second=0, microsecond=0)
to_date = today.replace(hour=9, minute=30, second=0, microsecond=0)
else:
from_date = today.replace(hour=9, minute=15, second=0, microsecond=0)
to_date = today.replace(hour=9, minute=45, second=0, microsecond=0)
from_date_str = from_date.strftime("%Y-%m-%dT%H:%M:%S.000Z")
to_date_str = to_date.strftime("%Y-%m-%dT%H:%M:%S.000Z")
stock_high_low = {}
for stock_name, codes in stock_isec_codes.items():
response = breeze.get_historical_data_v2(
stock_code=codes['isec_stock_code'],
interval="5minute",
from_date=from_date_str,
to_date=to_date_str,
exchange_code="NSE",
product_type="cash"
)
if isinstance(response, dict) and 'Success' in response:
highs = [item['high'] for item in response['Success']]
lows = [item['low'] for item in response['Success']]
highest = max(highs)
lowest = min(lows)
stock_token = codes['stock_token']
stock_high_low[stock_token] = {'high': highest, 'low': lowest}
log_message(f"Token {stock_token}: High = {highest}, Low =
{lowest}")
else:
log_message(f"No data found for {stock_name}.")
return stock_high_low
except Exception as e:
log_message(f"Error getting high and low values: {e}")
return {}
def get_isec_tokens(stock_isec_codes):
log_message("Getting isec_tokens for WebSocket subscription...")
try:
isec_tokens = []
for stock_name, codes in stock_isec_codes.items():
isec_tokens.append(codes['stock_token'])
return isec_tokens
except Exception as e:
log_message(f"Error getting isec_tokens: {e}")
return []
def place_order(order_params):
try:
response = breeze.place_order(**order_params)
if response.get('Status') == 200:
order_id = response['Success'].get('order_id')
log_message(f"Order placed: {order_params}, Order ID: {order_id}")
return order_id
else:
log_message(f"Failed to place order: {response.get('Error')}")
return None
except Exception as e:
log_message(f"Error placing order: {e}")
return None
def verify_orders():
global buy_order_count, sell_order_count
today_date = datetime.now().strftime("%Y-%m-%d")
from_date = f"{today_date}T07:00:00.000Z"
to_date = datetime.now().strftime("%Y-%m-%dT%H:%M:%S.000Z")
try:
order_response = breeze.get_order_list(
exchange_code="NSE",
from_date=from_date,
to_date=to_date
)
orders = order_response.get('Success', [])
if not orders: # Check if orders list is empty or None
log_message("No strategy orders found in the verification step.")
return 0, 0
buy_order_count = 0
sell_order_count = 0
for order in orders:
if order.get('user_remark') == 'strategyorder':
log_message(f"Order verified: {order}")
if order.get('action', '').lower() == 'buy':
buy_order_count += 1
elif order.get('action', '').lower() == 'sell':
sell_order_count += 1
return buy_order_count, sell_order_count
except Exception as e:
log_message(f"Error verifying orders: {e}")
return 0, 0
def run_check_ticks():
check_ticks()
def log_message(message):
"""Log messages to a file."""
log_filename = "trade_log.txt"
with open(log_filename, 'a') as log_file:
log_file.write(f"{datetime.now()}: {message}\n")
print(message)
def main():
try:
log_message("Starting main function")
global stock_isec_codes
global stock_high_low
global order_ids # Define order_ids as a global variable
global sell_order_count, buy_order_count # Define sell_order_count and
buy_order_count as global variables
# Initialize variables
order_ids = []
sell_order_count = 0
buy_order_count = 0
filename = "Stock_List_Nifty50.csv"
stock_isec_codes = get_stock_names(filename)
if not stock_isec_codes:
log_message("Error: No stock names found.")
return
isec_tokens = get_isec_tokens(stock_isec_codes)
if not isec_tokens:
log_message("Error: No isec_tokens found for WebSocket subscription.")
return
breeze.on_ticks = on_ticks
breeze.subscribe_feeds(isec_tokens)
except Exception as e:
log_message(f"Error in main execution: {e}")
if __name__ == "__main__":
main()