feat: мультисимвольный daemon — per-symbol params, выбор лучшего сигнала
- 3 монеты (BTC/ETH/SOL) с индивидуальными параметрами из OOS бэктеста - При одновременных сигналах — одна позиция, выбор по risk_pct (ширина breakout) - dotenv для загрузки API ключей из .env - capital: 0 = авто-баланс с биржи - DB schema: symbol в positions и sessions Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -33,7 +33,8 @@ def run():
|
||||
|
||||
from executor import run_cycle
|
||||
|
||||
click.echo(f"Running cycle ({cfg.mode} mode, {cfg.symbol})...")
|
||||
symbols = ", ".join(s.split("/")[0] for s in cfg.symbols.keys())
|
||||
click.echo(f"Running cycle ({cfg.mode} mode, {symbols})...")
|
||||
logs = run_cycle(conn, cfg)
|
||||
for msg in logs:
|
||||
click.echo(f" {msg}")
|
||||
@@ -62,7 +63,8 @@ def status():
|
||||
|
||||
click.echo()
|
||||
click.echo(f"{'=' * 50}")
|
||||
click.echo(f" SCALP-BOT — {cfg.mode.upper()} | {cfg.symbol}")
|
||||
symbols = ", ".join(s.split("/")[0] for s in cfg.symbols.keys())
|
||||
click.echo(f" SCALP-BOT — {cfg.mode.upper()} | {symbols}")
|
||||
click.echo(f"{'=' * 50}")
|
||||
click.echo(f" Equity: ${equity:,.2f} (peak ${peak:,.2f})")
|
||||
click.echo(f" PnL: ${total_pnl:+,.2f}")
|
||||
@@ -72,7 +74,8 @@ def status():
|
||||
if positions:
|
||||
click.echo(f"\n Open Positions:")
|
||||
for p in positions:
|
||||
click.echo(f" {p['direction'].upper()} @ ${p['entry_price']:,.2f} "
|
||||
tag = (p.get('symbol') or '').split("/")[0] or "?"
|
||||
click.echo(f" {tag} {p['direction'].upper()} @ ${p['entry_price']:,.2f} "
|
||||
f"SL=${p['stop_price']:,.2f} TP=${p['tp_price']:,.2f} "
|
||||
f"size={p['pos_size']:.4f}")
|
||||
else:
|
||||
@@ -117,7 +120,8 @@ def daemon():
|
||||
|
||||
cfg = load_config()
|
||||
|
||||
click.echo(f"scalp-bot daemon starting ({cfg.mode} mode, {cfg.symbol})")
|
||||
symbols = ", ".join(s.split("/")[0] for s in cfg.symbols.keys())
|
||||
click.echo(f"scalp-bot daemon starting ({cfg.mode} mode, {symbols})")
|
||||
click.echo(f"Strategy: RR={cfg.strategy.rr_ratio} OR={cfg.strategy.or_minutes}m "
|
||||
f"max_trades={cfg.strategy.max_trades}")
|
||||
click.echo(f"Risk: {cfg.risk.per_trade*100:.0f}% per trade, {cfg.risk.leverage}x leverage")
|
||||
|
||||
@@ -7,6 +7,9 @@ from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
import yaml
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv()
|
||||
|
||||
from strategy import Params
|
||||
|
||||
@@ -65,14 +68,33 @@ class TelegramConfig:
|
||||
class Config:
|
||||
mode: str = "paper"
|
||||
capital: float = 1000.0
|
||||
symbol: str = "BTC/USDT:USDT"
|
||||
symbols: dict[str, StrategyConfig] = field(default_factory=dict)
|
||||
timeframe: str = "5m"
|
||||
strategy: StrategyConfig = field(default_factory=StrategyConfig)
|
||||
risk: RiskConfig = field(default_factory=RiskConfig)
|
||||
exchange: ExchangeConfig = field(default_factory=ExchangeConfig)
|
||||
telegram: TelegramConfig = field(default_factory=TelegramConfig)
|
||||
|
||||
|
||||
def _parse_symbols(raw: dict) -> dict[str, StrategyConfig]:
|
||||
"""Parse symbols from YAML — dict of symbol -> strategy params."""
|
||||
syms_raw = raw.get("symbols", {})
|
||||
|
||||
# Old format: list of strings or single string
|
||||
if isinstance(syms_raw, str):
|
||||
return {syms_raw: StrategyConfig()}
|
||||
if isinstance(syms_raw, list):
|
||||
return {s: StrategyConfig() for s in syms_raw}
|
||||
|
||||
# New format: dict of symbol -> params
|
||||
result = {}
|
||||
for symbol, params_raw in syms_raw.items():
|
||||
if params_raw is None:
|
||||
result[symbol] = StrategyConfig()
|
||||
else:
|
||||
result[symbol] = StrategyConfig(**params_raw)
|
||||
return result
|
||||
|
||||
|
||||
def load_config(path: Path | None = None) -> Config:
|
||||
"""Load configuration from YAML + env var overrides."""
|
||||
path = path or CONFIG_PATH
|
||||
@@ -82,7 +104,6 @@ def load_config(path: Path | None = None) -> Config:
|
||||
with open(path) as f:
|
||||
raw = yaml.safe_load(f) or {}
|
||||
|
||||
strat_raw = raw.get("strategy", {})
|
||||
risk_raw = raw.get("risk", {})
|
||||
exchange_raw = raw.get("exchange", {})
|
||||
tg_raw = raw.get("telegram", {})
|
||||
@@ -97,9 +118,8 @@ def load_config(path: Path | None = None) -> Config:
|
||||
return Config(
|
||||
mode=raw.get("mode", "paper"),
|
||||
capital=raw.get("capital", 1000.0),
|
||||
symbol=raw.get("symbol", "BTC/USDT:USDT"),
|
||||
symbols=_parse_symbols(raw),
|
||||
timeframe=raw.get("timeframe", "5m"),
|
||||
strategy=StrategyConfig(**strat_raw),
|
||||
risk=RiskConfig(**risk_raw),
|
||||
exchange=exchange,
|
||||
telegram=telegram,
|
||||
|
||||
+27
-8
@@ -1,14 +1,33 @@
|
||||
mode: paper # paper | live
|
||||
capital: 1000.0
|
||||
symbol: "BTC/USDT:USDT"
|
||||
capital: 0 # 0 = auto-fetch from exchange balance
|
||||
timeframe: "5m"
|
||||
|
||||
strategy:
|
||||
rr_ratio: 2.5
|
||||
max_trades: 2
|
||||
fvg_expiry: 12
|
||||
or_minutes: 15
|
||||
session_end_h: 11
|
||||
# Per-symbol strategy params (from walk-forward backtest OOS)
|
||||
symbols:
|
||||
BTC/USDT:USDT:
|
||||
rr_ratio: 3.0
|
||||
max_trades: 1
|
||||
fvg_expiry: 6
|
||||
or_minutes: 15
|
||||
session_end_h: 11
|
||||
|
||||
ETH/USDT:USDT:
|
||||
rr_ratio: 3.0
|
||||
max_trades: 1
|
||||
fvg_expiry: 6
|
||||
or_minutes: 15
|
||||
session_end_h: 11
|
||||
first_fvg_only: true
|
||||
|
||||
SOL/USDT:USDT:
|
||||
rr_ratio: 3.0
|
||||
max_trades: 1
|
||||
fvg_expiry: 12
|
||||
or_minutes: 15
|
||||
session_end_h: 11
|
||||
min_range_pct: 0.2
|
||||
min_fvg_pct: 0.02
|
||||
first_fvg_only: true
|
||||
|
||||
risk:
|
||||
per_trade: 0.02
|
||||
|
||||
+143
-73
@@ -1,11 +1,11 @@
|
||||
"""Trade executor — replay approach for ORB+FVG+Engulfing strategy.
|
||||
|
||||
Every 5 minutes during NYSE session:
|
||||
Every 5 minutes during NYSE session, for each symbol:
|
||||
1. Fetch all 5m candles from 9:30 to now
|
||||
2. Call run_day() — same function as backtest
|
||||
3. Reconcile with DB positions
|
||||
4. New trades → open on exchange + SL/TP orders
|
||||
5. EOD → close remaining positions
|
||||
3. Reconcile exits with DB positions
|
||||
4. Collect entry candidates across all symbols
|
||||
5. Pick best candidate (widest risk %) → open on exchange + SL/TP
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -18,7 +18,7 @@ from zoneinfo import ZoneInfo
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from config import Config
|
||||
from config import Config, StrategyConfig
|
||||
from exchange import FuturesExecutor
|
||||
from notify import notify_entry, notify_exit, notify_or
|
||||
from state import (
|
||||
@@ -44,15 +44,22 @@ def _get_futures(cfg: Config) -> FuturesExecutor:
|
||||
|
||||
@dataclass
|
||||
class SessionState:
|
||||
"""In-memory state for current trading session."""
|
||||
date: date | None = None
|
||||
"""In-memory state for current trading session (per symbol)."""
|
||||
or_high: float = 0.0
|
||||
or_low: float = 0.0
|
||||
or_computed: bool = False
|
||||
last_trade_ids: set[str] = field(default_factory=set)
|
||||
|
||||
|
||||
_session = SessionState()
|
||||
# Per-symbol session state, keyed by symbol string
|
||||
_sessions: dict[str, SessionState] = {}
|
||||
_session_date: date | None = None
|
||||
|
||||
|
||||
def _get_session(symbol: str) -> SessionState:
|
||||
if symbol not in _sessions:
|
||||
_sessions[symbol] = SessionState()
|
||||
return _sessions[symbol]
|
||||
|
||||
|
||||
def _is_nyse_hours(now_ny: datetime) -> bool:
|
||||
@@ -73,9 +80,14 @@ def _trade_key(t: Trade) -> str:
|
||||
return f"{t.direction}_{t.entry:.2f}_{t.stop:.2f}"
|
||||
|
||||
|
||||
def _risk_pct(t: Trade) -> float:
|
||||
"""Normalized risk distance — proxy for signal strength."""
|
||||
return abs(t.entry - t.stop) / t.entry if t.entry > 0 else 0
|
||||
|
||||
|
||||
def run_cycle(conn: sqlite3.Connection, cfg: Config) -> list[str]:
|
||||
"""Run one trading cycle. Returns list of log messages."""
|
||||
global _session
|
||||
"""Run one trading cycle for all symbols. Returns list of log messages."""
|
||||
global _sessions, _session_date
|
||||
logs: list[str] = []
|
||||
now_utc = datetime.now(timezone.utc)
|
||||
now_ny = now_utc.astimezone(NY)
|
||||
@@ -86,34 +98,108 @@ def run_cycle(conn: sqlite3.Connection, cfg: Config) -> list[str]:
|
||||
logs.append(f"Outside NYSE hours ({now_ny.strftime('%H:%M')} NY)")
|
||||
return logs
|
||||
|
||||
# Init equity from config on first run
|
||||
# Init equity from config or exchange balance on first run
|
||||
equity = get_equity(conn)
|
||||
if equity <= 0:
|
||||
update_equity(conn, cfg.capital)
|
||||
set_state_val(conn, "peak_equity", cfg.capital)
|
||||
equity = cfg.capital
|
||||
capital = cfg.capital
|
||||
if capital <= 0:
|
||||
futures = _get_futures(cfg)
|
||||
capital = futures.get_balance()
|
||||
if capital <= 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
|
||||
logs.append(f"Equity initialized: ${equity:,.2f}")
|
||||
|
||||
# New day → reset session
|
||||
if _session.date != today:
|
||||
_session = SessionState(date=today)
|
||||
# Try restore OR from DB
|
||||
saved = get_session(conn, today)
|
||||
# New day → reset all sessions
|
||||
if _session_date != today:
|
||||
_sessions = {}
|
||||
_session_date = today
|
||||
|
||||
# Phase 1: for each symbol — exits, OR, collect entry candidates
|
||||
candidates: list[tuple[str, Trade]] = [] # (symbol, trade)
|
||||
|
||||
for symbol, strat_cfg in cfg.symbols.items():
|
||||
sym_logs, sym_candidates = _run_symbol_phase1(
|
||||
conn, cfg, symbol, strat_cfg, now_ny, today)
|
||||
if sym_logs:
|
||||
tag = symbol.split("/")[0]
|
||||
logs.append(f"[{tag}]")
|
||||
logs.extend(f" {msg}" for msg in sym_logs)
|
||||
candidates.extend(sym_candidates)
|
||||
|
||||
# Phase 2: pick best entry candidate (if no open positions)
|
||||
if candidates:
|
||||
all_open = get_open_positions(conn)
|
||||
if not all_open:
|
||||
# Sort by risk_pct descending — widest breakout = strongest signal
|
||||
candidates.sort(key=lambda c: _risk_pct(c[1]), reverse=True)
|
||||
best_symbol, best_trade = candidates[0]
|
||||
tag = best_symbol.split("/")[0]
|
||||
|
||||
if len(candidates) > 1:
|
||||
others = ", ".join(
|
||||
f"{s.split('/')[0]}({_risk_pct(t)*100:.3f}%)"
|
||||
for s, t in candidates[1:]
|
||||
)
|
||||
logs.append(f" Candidates: {tag}({_risk_pct(best_trade)*100:.3f}%) > {others}")
|
||||
|
||||
sess = _get_session(best_symbol)
|
||||
key = _trade_key(best_trade)
|
||||
|
||||
if best_trade.exit_price > 0:
|
||||
# Flash trade
|
||||
_execute_entry(conn, cfg, best_trade, best_symbol,
|
||||
get_equity(conn), logs)
|
||||
sess.last_trade_ids.add(key)
|
||||
new_positions = get_open_positions(conn, best_symbol)
|
||||
for pos in new_positions:
|
||||
pos_key = f"{pos['direction']}_{pos['entry_price']:.2f}_{pos['stop_price']:.2f}"
|
||||
if pos_key == key:
|
||||
_execute_exit(conn, cfg, pos, best_symbol,
|
||||
best_trade.exit_price, best_trade.result, logs)
|
||||
break
|
||||
else:
|
||||
_execute_entry(conn, cfg, best_trade, best_symbol,
|
||||
get_equity(conn), logs)
|
||||
sess.last_trade_ids.add(key)
|
||||
else:
|
||||
logs.append(f" {len(candidates)} candidate(s) skipped — position already open")
|
||||
|
||||
return logs
|
||||
|
||||
|
||||
def _run_symbol_phase1(conn: sqlite3.Connection, cfg: Config, symbol: str,
|
||||
strat_cfg: StrategyConfig, now_ny: datetime,
|
||||
today: date) -> tuple[list[str], list[tuple[str, Trade]]]:
|
||||
"""Phase 1: exits + OR computation + collect new trade candidates.
|
||||
|
||||
Returns (logs, candidates) where candidates are new trades not yet in DB.
|
||||
"""
|
||||
logs: list[str] = []
|
||||
candidates: list[tuple[str, Trade]] = []
|
||||
sess = _get_session(symbol)
|
||||
|
||||
# Try restore OR from DB on first cycle
|
||||
if not sess.or_computed:
|
||||
saved = get_session(conn, today, symbol)
|
||||
if saved:
|
||||
_session.or_high = saved["or_high"]
|
||||
_session.or_low = saved["or_low"]
|
||||
_session.or_computed = True
|
||||
logs.append(f"Session restored: OR {_session.or_high:.2f}/{_session.or_low:.2f}")
|
||||
sess.or_high = saved["or_high"]
|
||||
sess.or_low = saved["or_low"]
|
||||
sess.or_computed = True
|
||||
logs.append(f"Session restored: OR {sess.or_high:.2f}/{sess.or_low:.2f}")
|
||||
|
||||
# Fetch 5m candles from 9:30 NY to now
|
||||
futures = _get_futures(cfg)
|
||||
nyse_open = now_ny.replace(hour=9, minute=30, second=0, microsecond=0)
|
||||
since_ms = int(nyse_open.astimezone(timezone.utc).timestamp() * 1000)
|
||||
raw_candles = futures.fetch_candles(cfg.symbol, cfg.timeframe, since_ms)
|
||||
raw_candles = futures.fetch_candles(symbol, cfg.timeframe, since_ms)
|
||||
|
||||
if not raw_candles:
|
||||
logs.append("No candles fetched")
|
||||
return logs
|
||||
return logs, candidates
|
||||
|
||||
df = pd.DataFrame(raw_candles, columns=["timestamp", "open", "high", "low", "close", "volume"])
|
||||
df["timestamp"] = pd.to_datetime(df["timestamp"], unit="ms", utc=True)
|
||||
@@ -124,40 +210,39 @@ def run_cycle(conn: sqlite3.Connection, cfg: Config) -> list[str]:
|
||||
logs.append(f"Candles: {len(df)} ({df.iloc[0]['timestamp'].strftime('%H:%M')}"
|
||||
f"-{df.iloc[-1]['timestamp'].strftime('%H:%M')} UTC)")
|
||||
|
||||
# Run strategy (replay)
|
||||
params = cfg.strategy.to_params()
|
||||
strategy_trades = run_day(df, params, cfg.strategy.or_minutes)
|
||||
# Run strategy (replay) with per-symbol params
|
||||
params = strat_cfg.to_params()
|
||||
strategy_trades = run_day(df, params, strat_cfg.or_minutes)
|
||||
|
||||
# Track OR computation (convert or_minutes to candle count)
|
||||
tf_minutes = {"1m": 1, "5m": 5, "15m": 15}.get(cfg.timeframe, 5)
|
||||
or_candles_needed = max(1, cfg.strategy.or_minutes // tf_minutes)
|
||||
if not _session.or_computed and len(df) >= or_candles_needed:
|
||||
or_candles_needed = max(1, strat_cfg.or_minutes // tf_minutes)
|
||||
if not sess.or_computed and len(df) >= or_candles_needed:
|
||||
from strategy import get_opening_range
|
||||
rng = get_opening_range(df, cfg.strategy.or_minutes)
|
||||
rng = get_opening_range(df, strat_cfg.or_minutes)
|
||||
if rng:
|
||||
_session.or_high, _session.or_low = rng
|
||||
_session.or_computed = True
|
||||
save_session(conn, today, _session.or_high, _session.or_low)
|
||||
logs.append(f"OR computed: {_session.or_high:.2f}/{_session.or_low:.2f}")
|
||||
notify_or(cfg.telegram, str(today), _session.or_high, _session.or_low)
|
||||
sess.or_high, sess.or_low = rng
|
||||
sess.or_computed = True
|
||||
save_session(conn, today, sess.or_high, sess.or_low, symbol)
|
||||
logs.append(f"OR computed: {sess.or_high:.2f}/{sess.or_low:.2f}")
|
||||
notify_or(cfg.telegram, f"{today} {symbol}", sess.or_high, sess.or_low)
|
||||
|
||||
logs.append(f"Strategy signals: {len(strategy_trades)} trades")
|
||||
|
||||
# Get DB open positions
|
||||
db_positions = get_open_positions(conn)
|
||||
# Get DB open positions for this symbol
|
||||
db_positions = get_open_positions(conn, symbol)
|
||||
|
||||
# Reconcile: check if DB positions are still valid
|
||||
# Reconcile exits: check if DB positions are still valid
|
||||
for pos in db_positions:
|
||||
key = f"{pos['direction']}_{pos['entry_price']:.2f}_{pos['stop_price']:.2f}"
|
||||
|
||||
# First: check if exchange position is gone (SL/TP fired between cycles)
|
||||
if cfg.mode == "live":
|
||||
ex_pos = futures.get_position(cfg.symbol)
|
||||
ex_pos = futures.get_position(symbol)
|
||||
if ex_pos is None:
|
||||
# Exchange has no position — SL/TP fired
|
||||
price = futures.get_price(cfg.symbol) or pos["entry_price"]
|
||||
price = futures.get_price(symbol) or pos["entry_price"]
|
||||
logs.append(f"Exchange position gone — SL/TP fired between cycles")
|
||||
_execute_exit(conn, cfg, pos, price, "sl_tp_exchange", logs)
|
||||
_execute_exit(conn, cfg, pos, symbol, price, "sl_tp_exchange", logs)
|
||||
continue
|
||||
|
||||
# Second: check if strategy replay says trade is closed
|
||||
@@ -168,47 +253,29 @@ def run_cycle(conn: sqlite3.Connection, cfg: Config) -> list[str]:
|
||||
break
|
||||
|
||||
if matched_trade:
|
||||
_execute_exit(conn, cfg, pos, matched_trade.exit_price,
|
||||
_execute_exit(conn, cfg, pos, symbol, matched_trade.exit_price,
|
||||
matched_trade.result, logs)
|
||||
elif _is_eod(now_ny):
|
||||
price = futures.get_price(cfg.symbol) or pos["entry_price"]
|
||||
_execute_exit(conn, cfg, pos, price, "eod", logs)
|
||||
price = futures.get_price(symbol) or pos["entry_price"]
|
||||
_execute_exit(conn, cfg, pos, symbol, price, "eod", logs)
|
||||
|
||||
# Reconcile: new trades from strategy not yet in DB
|
||||
# Collect new trade candidates (not yet in DB, not seen before)
|
||||
db_keys = {f"{p['direction']}_{p['entry_price']:.2f}_{p['stop_price']:.2f}"
|
||||
for p in db_positions}
|
||||
|
||||
for t in strategy_trades:
|
||||
key = _trade_key(t)
|
||||
if key in db_keys or key in _session.last_trade_ids:
|
||||
if key in db_keys or key in sess.last_trade_ids:
|
||||
continue
|
||||
candidates.append((symbol, t))
|
||||
|
||||
if t.exit_price > 0:
|
||||
# "Flash trade": entered and exited within this cycle's candle window.
|
||||
# Execute both entry and exit on exchange.
|
||||
_execute_entry(conn, cfg, t, get_equity(conn), logs)
|
||||
_session.last_trade_ids.add(key)
|
||||
# Now close the just-opened position
|
||||
new_positions = get_open_positions(conn)
|
||||
for pos in new_positions:
|
||||
pos_key = f"{pos['direction']}_{pos['entry_price']:.2f}_{pos['stop_price']:.2f}"
|
||||
if pos_key == key:
|
||||
_execute_exit(conn, cfg, pos, t.exit_price, t.result, logs)
|
||||
break
|
||||
continue
|
||||
|
||||
# New active trade → execute entry (re-read equity for fresh value)
|
||||
_execute_entry(conn, cfg, t, get_equity(conn), logs)
|
||||
_session.last_trade_ids.add(key)
|
||||
|
||||
return logs
|
||||
return logs, candidates
|
||||
|
||||
|
||||
def _execute_entry(conn: sqlite3.Connection, cfg: Config, trade: Trade,
|
||||
equity: float, logs: list[str]) -> None:
|
||||
symbol: str, equity: float, logs: list[str]) -> None:
|
||||
"""Open a new position on exchange and in DB."""
|
||||
futures = _get_futures(cfg)
|
||||
symbol = cfg.symbol
|
||||
|
||||
# Position sizing
|
||||
risk_dollar = equity * cfg.risk.per_trade
|
||||
@@ -250,6 +317,7 @@ def _execute_entry(conn: sqlite3.Connection, cfg: Config, trade: Trade,
|
||||
pos_id = open_position(
|
||||
conn,
|
||||
date=str(datetime.now(timezone.utc).astimezone(NY).date()),
|
||||
symbol=symbol,
|
||||
direction=trade.direction,
|
||||
entry_price=filled_price,
|
||||
stop_price=trade.stop,
|
||||
@@ -262,7 +330,8 @@ def _execute_entry(conn: sqlite3.Connection, cfg: Config, trade: Trade,
|
||||
)
|
||||
log_order(conn, pos_id, side, symbol, trade.entry, order)
|
||||
|
||||
logs.append(f"ENTRY {trade.direction.upper()} @ ${filled_price:,.2f} "
|
||||
tag = symbol.split("/")[0]
|
||||
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})")
|
||||
|
||||
@@ -271,10 +340,10 @@ def _execute_entry(conn: sqlite3.Connection, cfg: Config, trade: Trade,
|
||||
|
||||
|
||||
def _execute_exit(conn: sqlite3.Connection, cfg: Config, pos: dict,
|
||||
exit_price: float, reason: str, logs: list[str]) -> None:
|
||||
symbol: str, exit_price: float, reason: str,
|
||||
logs: list[str]) -> None:
|
||||
"""Close a position on exchange and in DB."""
|
||||
futures = _get_futures(cfg)
|
||||
symbol = cfg.symbol
|
||||
side = "buy" if pos["direction"] == "long" else "sell"
|
||||
|
||||
# If SL/TP already fired on exchange, skip close + cancel
|
||||
@@ -324,8 +393,9 @@ def _execute_exit(conn: sqlite3.Connection, cfg: Config, pos: dict,
|
||||
close_side = "sell" if side == "buy" else "buy"
|
||||
log_order(conn, pos["id"], close_side, symbol, exit_price, order)
|
||||
|
||||
tag = symbol.split("/")[0]
|
||||
result = "WIN" if pnl_net > 0 else "LOSS"
|
||||
logs.append(f"EXIT {pos['direction'].upper()} @ ${exit_price:,.2f} "
|
||||
logs.append(f"EXIT {pos['direction'].upper()} {tag} @ ${exit_price:,.2f} "
|
||||
f"({reason}) PnL ${pnl_net:+,.2f} [{result}]")
|
||||
|
||||
notify_exit(cfg.telegram, symbol, pnl_net, reason)
|
||||
|
||||
@@ -4,3 +4,4 @@ pyyaml>=6.0
|
||||
click>=8.1
|
||||
apscheduler>=3.10,<4
|
||||
httpx>=0.27
|
||||
python-dotenv>=1.0
|
||||
|
||||
@@ -29,15 +29,18 @@ def init_db(conn: sqlite3.Connection) -> None:
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
date TEXT PRIMARY KEY,
|
||||
date TEXT NOT NULL,
|
||||
symbol TEXT NOT NULL,
|
||||
or_high REAL NOT NULL,
|
||||
or_low REAL NOT NULL,
|
||||
created_at TEXT DEFAULT (datetime('now'))
|
||||
created_at TEXT DEFAULT (datetime('now')),
|
||||
PRIMARY KEY (date, symbol)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS positions (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
date TEXT NOT NULL,
|
||||
symbol TEXT NOT NULL DEFAULT '',
|
||||
direction TEXT NOT NULL, -- long | short
|
||||
entry_price REAL NOT NULL,
|
||||
exit_price REAL,
|
||||
@@ -116,19 +119,20 @@ def update_equity(conn: sqlite3.Connection, equity: float) -> None:
|
||||
|
||||
# -- Sessions --
|
||||
|
||||
def save_session(conn: sqlite3.Connection, dt: date,
|
||||
or_high: float, or_low: float) -> None:
|
||||
def save_session(conn: sqlite3.Connection, dt: date, or_high: float,
|
||||
or_low: float, symbol: str = "") -> None:
|
||||
conn.execute(
|
||||
"INSERT INTO sessions (date, or_high, or_low) VALUES (?, ?, ?) "
|
||||
"ON CONFLICT(date) DO UPDATE SET or_high=?, or_low=?",
|
||||
(str(dt), or_high, or_low, or_high, or_low),
|
||||
"INSERT INTO sessions (date, symbol, or_high, or_low) VALUES (?, ?, ?, ?) "
|
||||
"ON CONFLICT(date, symbol) DO UPDATE SET or_high=?, or_low=?",
|
||||
(str(dt), symbol, or_high, or_low, or_high, or_low),
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
|
||||
def get_session(conn: sqlite3.Connection, dt: date) -> dict | None:
|
||||
def get_session(conn: sqlite3.Connection, dt: date,
|
||||
symbol: str = "") -> dict | None:
|
||||
row = conn.execute(
|
||||
"SELECT * FROM sessions WHERE date=?", (str(dt),)
|
||||
"SELECT * FROM sessions WHERE date=? AND symbol=?", (str(dt), symbol)
|
||||
).fetchone()
|
||||
return dict(row) if row else None
|
||||
|
||||
@@ -154,10 +158,17 @@ def close_position(conn: sqlite3.Connection, pos_id: int, **kwargs) -> None:
|
||||
conn.commit()
|
||||
|
||||
|
||||
def get_open_positions(conn: sqlite3.Connection) -> list[dict]:
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM positions WHERE status='open' ORDER BY id"
|
||||
).fetchall()
|
||||
def get_open_positions(conn: sqlite3.Connection,
|
||||
symbol: str | None = None) -> list[dict]:
|
||||
if symbol:
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM positions WHERE status='open' AND symbol=? ORDER BY id",
|
||||
(symbol,),
|
||||
).fetchall()
|
||||
else:
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM positions WHERE status='open' ORDER BY id"
|
||||
).fetchall()
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user