# Trading Strategy Logic
def trading_strategy():
global trades_df, allocation_percentages, top_n_symbols, top_n, account_df, last_rebalance_time
# Counters
coins_sold_counter = 0
coins_bought_counter = 0
try:
print("Starting Strategy Execution...")
update_top_n_symbols()
# print(f"Top {top_n} @ {(datetime.utcnow() + timedelta(hours=5.5)).strftime('%d/%m %H:%M')} IST : {top_n_symbols}")
# Get current active positions and symbols
current_positions = get_active_positions()
current_symbols = [pos['symbol'] for pos in current_positions]
# print(f"Current Positions Symbols: {current_symbols}")
# Sell non-top_n positions
for position in tqdm(current_positions, desc="Selling non-top_n coins"):
if position['symbol'] not in top_n_symbols:
sell_non_top_n_position(position, coins_sold_counter)
print("Sells Completed~!")
# Buy new top_n positions
for symbol in tqdm(top_n_symbols, desc="Buying new top_n coins"):
if symbol not in current_symbols:
buy_new_top_n_position(symbol, coins_bought_counter)
print("Buys Completed~!")
# Check for changes in the top_n list every 5 minutes
current_time = time.time()
if current_time - last_rebalance_time >= 300:
symbols_added, symbols_removed = check_top_n_changes(current_symbols)
print(f"symbols_added: {symbols_added} | symbols_removed: {symbols_removed}")
if symbols_added or symbols_removed:
print(f"Top N list has changed. Rebalancing...")
rebalance_allocations()
last_rebalance_time = current_time
except Exception as e:
handle_error(e)
print("Strategy Execution Completed!")