feat: логирование всех действий — file + journald
- cli.py: RotatingFileHandler (data/scalp-bot.log, 5MB, 3 backup) - executor: log.info/warning/error на каждое действие (cycle, entry, exit, slippage, equity, candidates, holiday/weekend skip) - state: логирование open/close_position, equity changes, peak equity - Все log.* дублируют logs.append — и в journald, и в CLI output Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
+29
-1
@@ -98,9 +98,15 @@ def run_cycle(conn: sqlite3.Connection, cfg: Config) -> list[str]:
|
||||
|
||||
# Check NYSE hours
|
||||
if not _is_nyse_hours(now_ny):
|
||||
logs.append(f"Outside NYSE hours ({now_ny.strftime('%H:%M')} NY)")
|
||||
reason = "weekend" if now_ny.weekday() >= 5 else (
|
||||
"holiday" if is_nyse_holiday(today) else "off-hours")
|
||||
msg = f"Outside NYSE hours ({now_ny.strftime('%H:%M')} NY, {reason})"
|
||||
log.debug(msg)
|
||||
logs.append(msg)
|
||||
return logs
|
||||
|
||||
log.info("Cycle start (%s NY, equity=$%.2f)", now_ny.strftime('%H:%M'), get_equity(conn))
|
||||
|
||||
# Init equity from config or exchange balance on first run
|
||||
equity = get_equity(conn)
|
||||
if equity <= 0:
|
||||
@@ -109,15 +115,18 @@ def run_cycle(conn: sqlite3.Connection, cfg: Config) -> list[str]:
|
||||
futures = _get_futures(cfg)
|
||||
capital = futures.get_balance()
|
||||
if capital <= 0:
|
||||
log.error("Cannot init equity: no config capital and exchange balance is 0")
|
||||
logs.append("Cannot init equity: no config capital and exchange balance is 0")
|
||||
return logs
|
||||
update_equity(conn, capital)
|
||||
set_state_val(conn, "peak_equity", capital)
|
||||
equity = capital
|
||||
log.info("Equity initialized: $%.2f", equity)
|
||||
logs.append(f"Equity initialized: ${equity:,.2f}")
|
||||
|
||||
# New day → reset all sessions
|
||||
if _session_date != today:
|
||||
log.info("New trading day: %s (prev=%s)", today, _session_date)
|
||||
_sessions = {}
|
||||
_session_date = today
|
||||
|
||||
@@ -142,6 +151,10 @@ def run_cycle(conn: sqlite3.Connection, cfg: Config) -> list[str]:
|
||||
best_symbol, best_trade = candidates[0]
|
||||
tag = best_symbol.split("/")[0]
|
||||
|
||||
log.info("Best candidate: %s %s entry=%.2f risk=%.3f%%",
|
||||
tag, best_trade.direction, best_trade.entry,
|
||||
_risk_pct(best_trade) * 100)
|
||||
|
||||
if len(candidates) > 1:
|
||||
others = ", ".join(
|
||||
f"{s.split('/')[0]}({_risk_pct(t)*100:.3f}%)"
|
||||
@@ -167,8 +180,10 @@ def run_cycle(conn: sqlite3.Connection, cfg: Config) -> list[str]:
|
||||
get_equity(conn), logs)
|
||||
sess.last_trade_ids.add(key)
|
||||
else:
|
||||
log.info("Skipped %d candidate(s) — position already open", len(candidates))
|
||||
logs.append(f" {len(candidates)} candidate(s) skipped — position already open")
|
||||
|
||||
log.info("Cycle end (%s NY)", now_ny.strftime('%H:%M'))
|
||||
return logs
|
||||
|
||||
|
||||
@@ -201,6 +216,7 @@ def _run_symbol_phase1(conn: sqlite3.Connection, cfg: Config, symbol: str,
|
||||
raw_candles = futures.fetch_candles(symbol, cfg.timeframe, since_ms)
|
||||
|
||||
if not raw_candles:
|
||||
log.warning("%s: no candles fetched", symbol)
|
||||
logs.append("No candles fetched")
|
||||
return logs, candidates
|
||||
|
||||
@@ -244,6 +260,7 @@ def _run_symbol_phase1(conn: sqlite3.Connection, cfg: Config, symbol: str,
|
||||
ex_pos = futures.get_position(symbol)
|
||||
if ex_pos is None:
|
||||
price = futures.get_price(symbol) or pos["entry_price"]
|
||||
log.warning("%s: exchange position gone — SL/TP fired between cycles, price=%.2f", symbol, price)
|
||||
logs.append(f"Exchange position gone — SL/TP fired between cycles")
|
||||
_execute_exit(conn, cfg, pos, symbol, price, "sl_tp_exchange", logs)
|
||||
continue
|
||||
@@ -284,6 +301,7 @@ def _execute_entry(conn: sqlite3.Connection, cfg: Config, trade: Trade,
|
||||
risk_dollar = equity * cfg.risk.per_trade
|
||||
risk_dist = abs(trade.entry - trade.stop)
|
||||
if risk_dist <= 0:
|
||||
log.warning("SKIP entry: zero risk distance for %s %s", symbol, trade.direction)
|
||||
logs.append(f"SKIP entry: zero risk distance")
|
||||
return
|
||||
|
||||
@@ -304,6 +322,7 @@ def _execute_entry(conn: sqlite3.Connection, cfg: Config, trade: Trade,
|
||||
order = futures.open_short(symbol, pos_value)
|
||||
|
||||
if order is None:
|
||||
log.error("ENTRY FAILED: %s %s @ %.2f (order=None)", symbol, trade.direction, trade.entry)
|
||||
logs.append(f"ENTRY FAILED: {trade.direction} @ {trade.entry:.2f}")
|
||||
return
|
||||
|
||||
@@ -334,6 +353,11 @@ def _execute_entry(conn: sqlite3.Connection, cfg: Config, trade: Trade,
|
||||
log_order(conn, pos_id, side, symbol, trade.entry, order)
|
||||
|
||||
tag = symbol.split("/")[0]
|
||||
slippage = (filled_price - trade.entry) / trade.entry * 100 if trade.entry > 0 else 0
|
||||
log.info("ENTRY %s %s @ $%.2f (signal=%.2f, slip=%.4f%%) SL=$%.2f TP=$%.2f "
|
||||
"size=%.4f val=$%.2f equity=$%.2f pos_id=%d",
|
||||
trade.direction.upper(), tag, filled_price, trade.entry, slippage,
|
||||
trade.stop, trade.tp, filled_qty, pos_value, equity, pos_id)
|
||||
logs.append(f"ENTRY {trade.direction.upper()} {tag} @ ${filled_price:,.2f} "
|
||||
f"SL=${trade.stop:,.2f} TP=${trade.tp:,.2f} "
|
||||
f"size={filled_qty:.4f} (${pos_value:,.2f})")
|
||||
@@ -399,6 +423,10 @@ def _execute_exit(conn: sqlite3.Connection, cfg: Config, pos: dict,
|
||||
|
||||
tag = symbol.split("/")[0]
|
||||
result = "WIN" if pnl_net > 0 else "LOSS"
|
||||
log.info("EXIT %s %s @ $%.2f (%s) gross=$%.2f comm=$%.2f pnl=$%.2f [%s] "
|
||||
"equity=$%.2f→$%.2f pos_id=%d",
|
||||
pos['direction'].upper(), tag, exit_price, reason,
|
||||
gross, commission, pnl_net, result, equity, new_equity, pos["id"])
|
||||
logs.append(f"EXIT {pos['direction'].upper()} {tag} @ ${exit_price:,.2f} "
|
||||
f"({reason}) PnL ${pnl_net:+,.2f} [{result}]")
|
||||
|
||||
|
||||
Reference in New Issue
Block a user