fix: add missing random import and ensure cleanup on thread crash
This commit is contained in:
@@ -62,6 +62,7 @@ def run_ticker_lifecycle(client, yf_ticker, t212_ticker, tz):
|
||||
|
||||
logger.info(f"Bot thread started for {yf_ticker} ({t212_ticker}).")
|
||||
|
||||
try:
|
||||
now = datetime.now(tz)
|
||||
target_entry_time = now.replace(hour=9, minute=45, second=0, microsecond=0)
|
||||
|
||||
@@ -142,10 +143,14 @@ def run_ticker_lifecycle(client, yf_ticker, t212_ticker, tz):
|
||||
logger.info(f"Waiting {wait_seconds:.0f} seconds until 11:00 EST forced exit...")
|
||||
time.sleep(wait_seconds)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Unexpected error in {yf_ticker} lifecycle: {e}", exc_info=True)
|
||||
finally:
|
||||
# 3. 11:00 EST - Cleanup (with jitter to prevent 429s)
|
||||
# We put this in finally to ensure it runs even on crash
|
||||
time.sleep(random.uniform(0.1, 5.0))
|
||||
|
||||
logger.info(f"Time exit reached for {yf_ticker}. Cleaning up.")
|
||||
logger.info(f"Cleanup phase reached for {yf_ticker}.")
|
||||
if execution.is_in_position:
|
||||
exit_price = execution.close_all(t212_ticker)
|
||||
if hasattr(execution, 'params') and exit_price > 0:
|
||||
@@ -154,7 +159,7 @@ def run_ticker_lifecycle(client, yf_ticker, t212_ticker, tz):
|
||||
trading_ticker = execution.params.get('trading_ticker', yf_ticker)
|
||||
|
||||
pnl_r = calculate_r_multiple("BUY" if execution.is_etp else execution.params['direction'], final_entry, exit_price, final_sl)
|
||||
record_pnl(yf_ticker, execution.params['direction'], final_entry, exit_price, "11:00 Time Exit", pnl_r, trading_ticker=trading_ticker)
|
||||
record_pnl(yf_ticker, execution.params['direction'], final_entry, exit_price, "Forced Exit (Final)", pnl_r, trading_ticker=trading_ticker)
|
||||
else:
|
||||
execution.close_all(t212_ticker)
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import time
|
||||
import logging
|
||||
import os
|
||||
import random
|
||||
from typing import Dict, Any, Optional
|
||||
from src.api.client import Trading212Client
|
||||
from src.strategy.inverse_mapping import INVERSE_TICKER_MAP, LEVERAGE_MAP
|
||||
|
||||
Reference in New Issue
Block a user