946 lines
49 KiB
Python
946 lines
49 KiB
Python
"""Algo Hunter: detect market-maker / HFT quoting patterns in the order book and trade them virtually.
|
||
|
||
Layers
|
||
* AlgoDetector - recognises an algorithm from level-size patterns (only aggregated levels are visible:
|
||
neither Bybit nor MetaScalp publish individual orders, so "the algo's order" is a level whose size and
|
||
behaviour match the pattern).
|
||
* AlgoTracker - follows those levels over time: lifetime, replace frequency, typical offset from the touch,
|
||
where it re-quotes next; flags adaptation (confidence falling below adaptive_exit_threshold).
|
||
* Executor - virtual limit orders only (no market entries): front-run the algo's level or pre-place on
|
||
its predicted re-quote; queue position is modelled from the visible level size; TP/SL/trailing/time/
|
||
emergency exits.
|
||
* RiskGuard - daily loss, trades per minute, losing streak pause, latency limits, cool-down after exit.
|
||
|
||
Nothing is ever sent to an exchange. dry_run=True only detects and logs. All events go to algo_hunter.log
|
||
with the [ALGO_HUNTER] tag; every trade goes to algo_hunter_trades.csv.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import csv
|
||
import json
|
||
import logging
|
||
import statistics
|
||
import time
|
||
from collections import deque
|
||
from dataclasses import asdict, dataclass, field, fields
|
||
from datetime import datetime, timezone
|
||
from logging.handlers import RotatingFileHandler
|
||
from pathlib import Path
|
||
|
||
import scalp_hint as sh
|
||
|
||
ROOT = Path(__file__).resolve().parent
|
||
CONFIG_FILE = ROOT / "algo_hunter_config.json"
|
||
LOG_FILE = ROOT / "algo_hunter.log"
|
||
TRADES_FILE = ROOT / "algo_hunter_trades.csv"
|
||
TRADE_COLUMNS = ["closed_utc", "ticker", "side", "scenario", "confidence", "signals", "algo_side", "algo_levels",
|
||
"algo_volumes", "order_price", "order_size_usd", "ts_sent", "ts_ack", "queue_ahead_usd",
|
||
"front_run_success", "entry", "exit", "pnl_ticks", "net_usd", "hold_ms", "exit_reason"]
|
||
SIZE_TOLERANCE = 0.02 # two sizes are "the same" within 2%
|
||
GROUP_TOLERANCE = 0.25 # sizes within ±25% of the dominant size belong to the candidate group
|
||
|
||
|
||
@dataclass
|
||
class AlgoHunterConfig:
|
||
# detector
|
||
detection_window_ms: float = 2000
|
||
min_interval_ms: float = 80
|
||
max_interval_ms: float = 500
|
||
max_spread_ticks: int = 3
|
||
min_levels_cluster: int = 2
|
||
max_volume_cv: float = 0.15
|
||
batch_size_threshold: int = 3
|
||
reaction_latency_ms: float = 150
|
||
min_signals_to_confirm: int = 3
|
||
depth_levels: int = 10
|
||
size_tolerance: float = 0.02 # orders within this share of each other count as the algo's "same size"
|
||
# tracker
|
||
adaptive_exit_threshold: float = 0.3
|
||
adaptive_exit_ms: float = 4000 # confidence must stay below the threshold this long to count as adapted
|
||
rearm_after_ms: float = 0 # >0: switch back on by itself once the algo is confirmed again this long
|
||
prediction_confidence: float = 0.75
|
||
# executor
|
||
dry_run: bool = True
|
||
min_confidence: float = 0.7
|
||
entry_tape_window_ms: float = 1000
|
||
max_entry_spread_ticks: int = 2
|
||
min_entry_spread_ticks: int = 0 # no entries while the spread is narrower than this (0 = off)
|
||
vol_cap_ticks: float = 4 # mid range over the last second, in ticks
|
||
tp_ticks: int = 2
|
||
sl_ticks: int = 3
|
||
trailing: bool = False
|
||
tp_partial_ticks: int = 1
|
||
max_hold_ms: float = 2000
|
||
order_ttl_ms: float = 2000 # an unfilled order is cancelled after this
|
||
quick_exit: bool = False # close at the next trade at another price, in profit or not (no TP/SL/time)
|
||
requote: bool = False # re-place the order on every book update instead of cancelling and waiting
|
||
require_tape_pressure: bool = True # False: an empty tape does not block the entry
|
||
front_run_max_ticks: int = 2 # front-run an algo level at most this far behind the touch
|
||
fallback: bool = False # no confirmed algo: direction from microprice + who moved the spread
|
||
fallback_window_ms: float = 2000 # how far back best-price moves count for the fallback
|
||
# risk guard
|
||
max_position_usd: float = 50.0 # 0 = no limit
|
||
max_daily_loss_usd: float = 5.0 # 0 = no limit
|
||
max_trades_per_minute: int = 20
|
||
max_consecutive_losses: int = 3
|
||
pause_minutes: float = 5.0
|
||
max_order_latency_ms: float = 100
|
||
max_data_latency_ms: float = 50
|
||
cooldown_after_exit_ms: float = 1000
|
||
|
||
@classmethod
|
||
def load(cls, path: Path = CONFIG_FILE) -> "AlgoHunterConfig":
|
||
cfg = cls()
|
||
try:
|
||
data = json.loads(path.read_text(encoding="utf-8"))
|
||
section = data.get("algo_hunter", data)
|
||
for f in fields(cls):
|
||
if f.name in section:
|
||
setattr(cfg, f.name, type(getattr(cfg, f.name))(section[f.name]))
|
||
except (OSError, ValueError, TypeError):
|
||
pass
|
||
return cfg
|
||
|
||
def save(self, path: Path = CONFIG_FILE) -> None:
|
||
try:
|
||
path.write_text(json.dumps({"algo_hunter": asdict(self)}, ensure_ascii=False, indent=2), encoding="utf-8")
|
||
except OSError:
|
||
pass
|
||
|
||
|
||
def _logger() -> logging.Logger:
|
||
log = logging.getLogger("algo_hunter")
|
||
if not log.handlers:
|
||
log.setLevel(logging.INFO)
|
||
try:
|
||
handler = RotatingFileHandler(LOG_FILE, maxBytes=5_000_000, backupCount=3, encoding="utf-8")
|
||
handler.setFormatter(logging.Formatter("%(asctime)s [ALGO_HUNTER] %(message)s"))
|
||
log.addHandler(handler)
|
||
except OSError:
|
||
log.addHandler(logging.NullHandler())
|
||
log.propagate = False
|
||
return log
|
||
|
||
|
||
def _same(a: float, b: float, tol: float = SIZE_TOLERANCE) -> bool:
|
||
return a > 0 and b > 0 and abs(a - b) <= tol * max(a, b)
|
||
|
||
|
||
# --------------------------------------------------------------------------------------------
|
||
# Detector
|
||
# --------------------------------------------------------------------------------------------
|
||
|
||
@dataclass
|
||
class LevelEvent:
|
||
ts: float
|
||
side: str # "bid" / "ask"
|
||
price: float
|
||
size: float # size after the change (add/increase) or the removed size (cancel/fill)
|
||
action: str # add / cancel / fill
|
||
offset: int # distance from the best price on that side, ticks
|
||
|
||
|
||
@dataclass
|
||
class AlgoSignature:
|
||
side: str # "bid", "ask" or "both"
|
||
price_levels: list[float]
|
||
volumes: list[float]
|
||
confidence: float
|
||
detected_at: float
|
||
signals: list[str] = field(default_factory=list)
|
||
size: float = 0.0 # the algo's typical order size
|
||
batch_cancel_side: str = "" # side where the algo just pulled several levels at once
|
||
|
||
|
||
class AlgoDetector:
|
||
def __init__(self, cfg: AlgoHunterConfig) -> None:
|
||
self.cfg = cfg
|
||
self.prev: dict[str, dict[float, float]] = {"bid": {}, "ask": {}}
|
||
self.events: deque[LevelEvent] = deque()
|
||
self.updates: deque[tuple[float, list[LevelEvent]]] = deque()
|
||
self.trades: deque[sh.Trade] = deque()
|
||
self.update_times: deque[float] = deque(maxlen=200)
|
||
self.last: AlgoSignature | None = None
|
||
|
||
# cadence of the data source: an algo reacting faster than this is invisible
|
||
def cadence_ms(self) -> float:
|
||
if len(self.update_times) < 10:
|
||
return 0.0
|
||
times = list(self.update_times)
|
||
return statistics.median(b - a for a, b in zip(times, times[1:])) * 1000
|
||
|
||
def effective_reaction_ms(self) -> float:
|
||
return max(self.cfg.reaction_latency_ms, 1.2 * self.cadence_ms())
|
||
|
||
def on_trade(self, trade: sh.Trade) -> None:
|
||
self.trades.append(trade)
|
||
|
||
def _top(self, book: sh.OrderBook) -> dict[str, dict[float, float]]:
|
||
k = self.cfg.depth_levels
|
||
return {"bid": dict(sorted(book.bids.items(), reverse=True)[:k]), "ask": dict(sorted(book.asks.items())[:k])}
|
||
|
||
def on_book(self, now: float, book: sh.OrderBook, tick: float) -> tuple[AlgoSignature | None, list[LevelEvent]]:
|
||
cur = self._top(book)
|
||
self.update_times.append(now)
|
||
if not self.prev["bid"] and not self.prev["ask"]:
|
||
self.prev = cur # the first book is the baseline, not a burst of new orders
|
||
return None, []
|
||
window = self.cfg.detection_window_ms / 1000
|
||
while self.trades and self.trades[0].ts < now - window:
|
||
self.trades.popleft()
|
||
recent_trades = [t for t in self.trades if t.ts >= (self.update_times[-2] if len(self.update_times) > 1 else now - 1)]
|
||
events: list[LevelEvent] = []
|
||
for side in ("bid", "ask"):
|
||
best = max(cur[side]) if side == "bid" and cur[side] else min(cur[side]) if cur[side] else None
|
||
if best is None or tick <= 0:
|
||
continue
|
||
old, new = self.prev[side], cur[side]
|
||
# Only compare inside the overlapping price range: levels sliding out of the top-K are not cancels.
|
||
edge = min(new) if side == "bid" else max(new)
|
||
for price in set(old) | set(new):
|
||
if (side == "bid" and price < edge) or (side == "ask" and price > edge):
|
||
continue
|
||
before, after = old.get(price, 0.0), new.get(price, 0.0)
|
||
if after > before * (1 + SIZE_TOLERANCE):
|
||
offset = int(round(abs(best - price) / tick))
|
||
events.append(LevelEvent(now, side, price, after - before if before else after, "add", offset))
|
||
elif after < before * (1 - SIZE_TOLERANCE):
|
||
traded = sum(t.size for t in recent_trades if abs(t.price - price) < tick / 2)
|
||
action = "fill" if traded >= 0.5 * (before - after) else "cancel"
|
||
offset = int(round(abs(best - price) / tick))
|
||
events.append(LevelEvent(now, side, price, before - after, action, offset))
|
||
self.prev = cur
|
||
self.updates.append((now, events))
|
||
self.events.extend(events)
|
||
while self.events and self.events[0].ts < now - window:
|
||
self.events.popleft()
|
||
while self.updates and self.updates[0][0] < now - window:
|
||
self.updates.popleft()
|
||
sig = self._evaluate(now, cur, book, tick, events)
|
||
self.last = sig
|
||
return sig, events
|
||
|
||
def _dominant_size(self) -> tuple[float, list[LevelEvent]] | None:
|
||
adds = [e for e in self.events if e.action == "add"]
|
||
if len(adds) < 3:
|
||
return None
|
||
best_size, best_group = 0.0, []
|
||
for candidate in adds:
|
||
group = [e for e in adds if _same(e.size, candidate.size, self.cfg.size_tolerance)]
|
||
if len(group) > len(best_group):
|
||
best_size, best_group = candidate.size, group
|
||
if len(best_group) < 3:
|
||
return None
|
||
return statistics.median(e.size for e in best_group), best_group
|
||
|
||
def _evaluate(self, now: float, cur: dict, book: sh.OrderBook, tick: float,
|
||
events: list[LevelEvent]) -> AlgoSignature | None:
|
||
cfg = self.cfg
|
||
signals: list[str] = []
|
||
side_votes = {"bid": 0, "ask": 0}
|
||
dominant = self._dominant_size()
|
||
size = dominant[0] if dominant else 0.0
|
||
group = dominant[1] if dominant else []
|
||
for e in group:
|
||
side_votes[e.side] += 1
|
||
# 1) periodicity: the same size re-appears at regular intervals for most of the window
|
||
if len(group) >= 3:
|
||
times = sorted({round(e.ts, 3) for e in group})
|
||
gaps = [(b - a) * 1000 for a, b in zip(times, times[1:])]
|
||
span = (times[-1] - times[0]) * 1000
|
||
in_range = [g for g in gaps if cfg.min_interval_ms <= g <= cfg.max_interval_ms]
|
||
if gaps and len(in_range) / len(gaps) >= 0.6 and span >= 0.5 * cfg.detection_window_ms:
|
||
signals.append("периодичность")
|
||
# 2) volume stability: most new orders near the touch carry the same size, and that group barely varies
|
||
near_adds = [e for e in self.events if e.action == "add" and e.offset <= cfg.max_spread_ticks + 2]
|
||
if len(group) >= 3 and near_adds:
|
||
share = sum(1 for e in group if e.offset <= cfg.max_spread_ticks + 2) / len(near_adds)
|
||
sizes = [e.size for e in group]
|
||
cv = statistics.pstdev(sizes) / statistics.mean(sizes)
|
||
if share >= 0.5 and cv < cfg.max_volume_cv:
|
||
signals.append("стабильный объём")
|
||
# 3) cluster: consecutive best levels holding the same size
|
||
cluster_side, cluster_levels = "", []
|
||
for side in ("bid", "ask"):
|
||
levels = sorted(cur[side].items(), reverse=(side == "bid"))[:5]
|
||
run = [levels[0]] if levels else []
|
||
for prev_level, level in zip(levels, levels[1:]):
|
||
if _same(prev_level[1], level[1], cfg.size_tolerance):
|
||
run.append(level)
|
||
else:
|
||
if len(run) >= cfg.min_levels_cluster:
|
||
break
|
||
run = [level]
|
||
if len(run) >= cfg.min_levels_cluster and len(run) > len(cluster_levels):
|
||
cluster_side, cluster_levels = side, run
|
||
if cluster_levels:
|
||
signals.append("кластер уровней")
|
||
side_votes[cluster_side] += 2
|
||
if not size:
|
||
size = cluster_levels[0][1]
|
||
# 4) symmetry: bid and ask quoted together at the same distance from the touch
|
||
symmetric = 0
|
||
for _ts, evs in self.updates:
|
||
bids = [e for e in evs if e.side == "bid" and e.action == "add" and e.offset <= cfg.max_spread_ticks]
|
||
asks = [e for e in evs if e.side == "ask" and e.action == "add" and e.offset <= cfg.max_spread_ticks]
|
||
if any(abs(b.offset - a.offset) <= 1 and _same(b.size, a.size, 0.2) for b in bids for a in asks):
|
||
symmetric += 1
|
||
if symmetric >= 2:
|
||
signals.append("симметрия bid/ask")
|
||
# 5) reactivity: the same-size level is restored right after a market order hit it
|
||
reaction = self.effective_reaction_ms() / 1000
|
||
reactive = 0
|
||
for trade in self.trades:
|
||
passive = "bid" if trade.side == "Sell" else "ask"
|
||
if any(e.side == passive and e.action == "add" and 0 <= e.ts - trade.ts <= reaction
|
||
and abs(e.price - trade.price) <= 2 * tick and (not size or abs(e.size - size) <= GROUP_TOLERANCE * size)
|
||
for e in self.events):
|
||
reactive += 1
|
||
if reactive >= 2:
|
||
signals.append("реакция на сделки")
|
||
# 6) batch: several levels of exactly the algo's size added or pulled in one update, making up most of
|
||
# that update (data sources that bundle many changes per message would otherwise always look "batched")
|
||
batch_side = ""
|
||
if size:
|
||
for ts, evs in self.updates:
|
||
for side in ("bid", "ask"):
|
||
side_events = [e for e in evs if e.side == side and e.action in ("add", "cancel")]
|
||
same_size = [e for e in side_events if _same(e.size, size, max(0.05, cfg.size_tolerance))]
|
||
if len(same_size) >= cfg.batch_size_threshold and len(same_size) >= 0.6 * len(side_events):
|
||
if "пачка снятий/постановок" not in signals:
|
||
signals.append("пачка снятий/постановок")
|
||
if ts == now and sum(e.action == "cancel" for e in same_size) >= cfg.batch_size_threshold:
|
||
batch_side = side
|
||
if not signals:
|
||
return None
|
||
n = len(signals)
|
||
confidence = min(1.0, 0.25 + 0.15 * n) if n >= 1 else 0.0
|
||
if n < cfg.min_signals_to_confirm:
|
||
confidence = min(confidence, cfg.min_confidence - 0.01)
|
||
if symmetric >= 2 and abs(side_votes["bid"] - side_votes["ask"]) <= 1:
|
||
side = "both"
|
||
else:
|
||
side = "bid" if side_votes["bid"] >= side_votes["ask"] else "ask"
|
||
# The algo's levels: prices where an order of its size was added recently and still rests
|
||
# (its order sits on top of the crowd, so the level total is at least ~its size).
|
||
levels = []
|
||
sides = ("bid", "ask") if side == "both" else (side,)
|
||
seen = set()
|
||
for e in reversed(group):
|
||
if e.side in sides and e.price not in seen and cur[e.side].get(e.price, 0.0) >= 0.8 * size:
|
||
seen.add(e.price)
|
||
levels.append((e.price, cur[e.side][e.price]))
|
||
if not levels and cluster_levels:
|
||
levels = cluster_levels
|
||
levels.sort(key=lambda pv: pv[0], reverse=True)
|
||
return AlgoSignature(side, [p for p, _ in levels], [v for _, v in levels], confidence, now, signals, size,
|
||
batch_side)
|
||
|
||
|
||
# --------------------------------------------------------------------------------------------
|
||
# Tracker
|
||
# --------------------------------------------------------------------------------------------
|
||
|
||
class AlgoTracker:
|
||
def __init__(self, cfg: AlgoHunterConfig) -> None:
|
||
self.cfg = cfg
|
||
self.history: deque[LevelEvent] = deque(maxlen=2000)
|
||
self.live: dict[tuple[str, float], float] = {}
|
||
self.lifetimes: deque[float] = deque(maxlen=200)
|
||
self.offsets: dict[str, deque[int]] = {"bid": deque(maxlen=50), "ask": deque(maxlen=50)}
|
||
self.replaces: deque[float] = deque(maxlen=500)
|
||
self.peak_confidence = 0.0
|
||
self.adapted = False
|
||
self.low_since: float | None = None
|
||
|
||
def update(self, now: float, sig: AlgoSignature | None, events: list[LevelEvent]) -> None:
|
||
confidence = sig.confidence if sig else 0.0
|
||
if confidence >= self.cfg.min_confidence:
|
||
self.peak_confidence = max(self.peak_confidence, confidence)
|
||
# Adapted = after a confirmed algo, confidence stays below the threshold for adaptive_exit_ms in a row.
|
||
if self.peak_confidence >= self.cfg.min_confidence and confidence < self.cfg.adaptive_exit_threshold:
|
||
if self.low_since is None:
|
||
self.low_since = now
|
||
if (now - self.low_since) * 1000 >= self.cfg.adaptive_exit_ms:
|
||
self.adapted = True
|
||
else:
|
||
self.low_since = None
|
||
if not sig or not sig.size:
|
||
return
|
||
mine = [e for e in events if abs(e.size - sig.size) <= GROUP_TOLERANCE * sig.size]
|
||
for side in ("bid", "ask"):
|
||
adds = [e for e in mine if e.side == side and e.action == "add"]
|
||
cancels = [e for e in mine if e.side == side and e.action == "cancel"]
|
||
if adds and cancels:
|
||
self.replaces.append(now)
|
||
for e in mine:
|
||
self.history.append(e)
|
||
key = (e.side, e.price)
|
||
if e.action == "add":
|
||
self.live[key] = e.ts
|
||
self.offsets[e.side].append(e.offset)
|
||
elif key in self.live:
|
||
self.lifetimes.append((e.ts - self.live.pop(key)) * 1000)
|
||
|
||
def reset_adaptation(self) -> None:
|
||
self.adapted = False
|
||
self.peak_confidence = 0.0
|
||
|
||
@property
|
||
def avg_lifetime_ms(self) -> float:
|
||
return statistics.mean(self.lifetimes) if self.lifetimes else 0.0
|
||
|
||
def replace_frequency(self, now: float, seconds: float = 10.0) -> float:
|
||
return sum(1 for t in self.replaces if t >= now - seconds) / seconds
|
||
|
||
def typical_offset_ticks(self, side: str) -> int | None:
|
||
offsets = self.offsets[side]
|
||
return int(statistics.median(offsets)) if len(offsets) >= 3 else None
|
||
|
||
def prediction(self, side: str, book: sh.OrderBook, tick: float) -> tuple[float, float] | None:
|
||
"""Where the algo re-quotes next on `side` and how consistent that has been (share of recent adds)."""
|
||
offset = self.typical_offset_ticks(side)
|
||
best_bid, best_ask = book.best()
|
||
if offset is None or best_bid is None or best_ask is None:
|
||
return None
|
||
recent = list(self.offsets[side])[-10:]
|
||
share = sum(o == offset for o in recent) / len(recent)
|
||
price = best_bid - offset * tick if side == "bid" else best_ask + offset * tick
|
||
return sh._to_tick(price, tick, None), share
|
||
|
||
|
||
# --------------------------------------------------------------------------------------------
|
||
# Risk guard
|
||
# --------------------------------------------------------------------------------------------
|
||
|
||
class RiskGuard:
|
||
def __init__(self, cfg: AlgoHunterConfig) -> None:
|
||
self.cfg = cfg
|
||
self.day = ""
|
||
self.daily_pnl = 0.0
|
||
self.trade_times: deque[float] = deque()
|
||
self.losses = 0
|
||
self.pause_until = 0.0
|
||
self.last_exit = 0.0
|
||
self.disabled_reason = ""
|
||
|
||
def _roll_day(self, now: float) -> None:
|
||
day = datetime.fromtimestamp(now, timezone.utc).strftime("%Y-%m-%d")
|
||
if day != self.day:
|
||
self.day, self.daily_pnl = day, 0.0
|
||
if self.disabled_reason.startswith("дневной убыток"):
|
||
self.disabled_reason = ""
|
||
|
||
def latency_problem(self, latency_ms: float | None) -> str:
|
||
if latency_ms is None:
|
||
return ""
|
||
if latency_ms > self.cfg.max_order_latency_ms:
|
||
return (f"задержка {latency_ms:.0f} мс > {self.cfg.max_order_latency_ms:g} мс — гонку за очередь с "
|
||
"алгосом не выиграть, виртуальные входы отключены")
|
||
return ""
|
||
|
||
def allow(self, now: float, notional: float, latency_ms: float | None) -> tuple[bool, str]:
|
||
self._roll_day(now)
|
||
cfg = self.cfg
|
||
if self.disabled_reason:
|
||
return False, self.disabled_reason
|
||
problem = self.latency_problem(latency_ms)
|
||
if problem:
|
||
return False, problem
|
||
if cfg.max_position_usd > 0 and notional > cfg.max_position_usd:
|
||
return False, f"позиция {notional:.2f}$ больше лимита {cfg.max_position_usd:g}$"
|
||
if now < self.pause_until:
|
||
return False, f"пауза после {cfg.max_consecutive_losses} убытков подряд ещё {self.pause_until - now:.0f} с"
|
||
if (now - self.last_exit) * 1000 < cfg.cooldown_after_exit_ms:
|
||
return False, "пауза после выхода"
|
||
while self.trade_times and self.trade_times[0] < now - 60:
|
||
self.trade_times.popleft()
|
||
if len(self.trade_times) >= cfg.max_trades_per_minute:
|
||
return False, f"лимит {cfg.max_trades_per_minute} сделок в минуту"
|
||
return True, ""
|
||
|
||
def on_entry(self, now: float) -> None:
|
||
self.trade_times.append(now)
|
||
|
||
def on_close(self, now: float, pnl: float) -> None:
|
||
self._roll_day(now)
|
||
self.last_exit = now
|
||
self.daily_pnl += pnl
|
||
self.losses = self.losses + 1 if pnl < 0 else 0
|
||
if self.losses >= self.cfg.max_consecutive_losses:
|
||
self.pause_until = now + self.cfg.pause_minutes * 60
|
||
self.losses = 0
|
||
if self.cfg.max_daily_loss_usd > 0 and self.daily_pnl <= -self.cfg.max_daily_loss_usd:
|
||
self.disabled_reason = (f"дневной убыток {self.daily_pnl:.2f}$ достиг лимита {self.cfg.max_daily_loss_usd:g}$ — "
|
||
"режим выключен до следующего дня (UTC)")
|
||
|
||
|
||
# --------------------------------------------------------------------------------------------
|
||
# Executor (paper policy plugged into scalp_paper.PaperTrader)
|
||
# --------------------------------------------------------------------------------------------
|
||
|
||
@dataclass
|
||
class HunterOrder:
|
||
side: str # LONG / SHORT
|
||
price: float
|
||
size_usd: float
|
||
sent: float
|
||
ack: float
|
||
scenario: str
|
||
signature: AlgoSignature
|
||
ahead: float | None = None # queue volume in front of us (USD), set at ack
|
||
algo_ahead: float = 0.0 # part of `ahead` that belongs to the algo's level
|
||
front_run: bool = False
|
||
|
||
|
||
class AlgoHunterPolicy:
|
||
name = "algo_hunter"
|
||
|
||
def __init__(self, settings, cfg: AlgoHunterConfig | None = None, trades_path: Path | None = TRADES_FILE) -> None:
|
||
self.s = settings
|
||
self.cfg = cfg or AlgoHunterConfig.load()
|
||
self.detector = AlgoDetector(self.cfg)
|
||
self.tracker = AlgoTracker(self.cfg)
|
||
self.guard = RiskGuard(self.cfg)
|
||
self.trades_path = trades_path
|
||
self.log = _logger()
|
||
self.order: HunterOrder | None = None
|
||
self.entry_order: HunterOrder | None = None
|
||
self.filled_at = 0.0
|
||
self.stop = 0.0
|
||
self.target = 0.0
|
||
self.tick = 0.0
|
||
self.ticker = ""
|
||
self.sig: AlgoSignature | None = None
|
||
self.mids: deque[tuple[float, float]] = deque()
|
||
self.status = "Algo Hunter: жду стакан…"
|
||
self.stats = {"entries": 0, "wins": 0, "pnl_ticks": 0.0, "front_run": 0, "detections": 0, "orders": 0,
|
||
"requotes": 0}
|
||
self.best: tuple[float | None, float | None] = (None, None)
|
||
self.spread_moves: deque[tuple[float, int]] = deque() # (ts, +1 bid up / ask up, -1 bid down / ask down)
|
||
self.fallback_info = ""
|
||
self.last_direction = "LONG"
|
||
self.was_confirmed = False
|
||
self.confirmed_since: float | None = None
|
||
self.warned = ""
|
||
self.status_reason = ""
|
||
|
||
# --- helpers ------------------------------------------------------------------------
|
||
def _latency(self, trader) -> float | None:
|
||
"""Effective delay of our view of the book: measured data latency, or the source cadence at least."""
|
||
measured = getattr(trader, "data_latency_ms", None)
|
||
cadence = self.detector.cadence_ms() or None
|
||
values = [v for v in (measured, cadence) if v is not None]
|
||
return max(values) if values else None
|
||
|
||
def _vol_ticks(self, now: float) -> float:
|
||
recent = [m for t, m in self.mids if t >= now - 1.0]
|
||
if len(recent) < 2 or self.tick <= 0:
|
||
return 0.0
|
||
return (max(recent) - min(recent)) / self.tick
|
||
|
||
def _tape_pressure(self, now: float, side: str) -> bool:
|
||
window = self.cfg.entry_tape_window_ms / 1000
|
||
recent = [t for t in self.detector.trades if t.ts >= now - window]
|
||
buy = sum(t.size for t in recent if t.side == "Buy")
|
||
sell = sum(t.size for t in recent if t.side == "Sell")
|
||
if not self.cfg.require_tape_pressure and buy == sell:
|
||
return True
|
||
return buy > sell if side == "LONG" else sell > buy
|
||
|
||
# --- book updates: detection, queue model, emergency exit, new orders -----------------
|
||
def on_book(self, trader, now: float, book: sh.OrderBook, tick: float) -> None:
|
||
if tick > 0:
|
||
self.tick = tick
|
||
best_bid, best_ask = book.best()
|
||
if best_bid is None or best_ask is None or self.tick <= 0:
|
||
return
|
||
prev_bid, prev_ask = self.best
|
||
if prev_bid is not None and prev_ask is not None:
|
||
# A bid stepping into the spread / an ask pulled away push the price up; the opposite pushes it down.
|
||
for moved in (best_bid - prev_bid, best_ask - prev_ask):
|
||
if abs(moved) >= self.tick / 2:
|
||
self.spread_moves.append((now, 1 if moved > 0 else -1))
|
||
while self.spread_moves and self.spread_moves[0][0] < now - self.cfg.fallback_window_ms / 1000:
|
||
self.spread_moves.popleft()
|
||
self.best = (best_bid, best_ask)
|
||
self.mids.append((now, (best_bid + best_ask) / 2))
|
||
while self.mids and self.mids[0][0] < now - 5:
|
||
self.mids.popleft()
|
||
sig, events = self.detector.on_book(now, book, self.tick)
|
||
self.sig = sig
|
||
self.tracker.update(now, sig, events)
|
||
confirmed = bool(sig and sig.confidence >= self.cfg.min_confidence
|
||
and len(sig.signals) >= self.cfg.min_signals_to_confirm)
|
||
if confirmed and not self.was_confirmed:
|
||
self.stats["detections"] += 1
|
||
self.log.info("detect %s side=%s conf=%.2f signals=%s size=%.2f levels=%s", self.ticker, sig.side,
|
||
sig.confidence, ",".join(sig.signals), sig.size,
|
||
",".join(f"{p:.10g}x{v:.0f}" for p, v in zip(sig.price_levels, sig.volumes)))
|
||
self.was_confirmed = confirmed
|
||
if not confirmed:
|
||
self.confirmed_since = None
|
||
elif self.confirmed_since is None:
|
||
self.confirmed_since = now
|
||
if (self.cfg.rearm_after_ms > 0 and self.guard.disabled_reason.startswith("алгос адаптировался")
|
||
and self.confirmed_since is not None
|
||
and (now - self.confirmed_since) * 1000 >= self.cfg.rearm_after_ms):
|
||
self.rearm()
|
||
if self.tracker.adapted and not self.guard.disabled_reason and not self.cfg.fallback:
|
||
self.guard.disabled_reason = "алгос адаптировался (уверенность ниже порога) — режим выключен"
|
||
self.log.info("adapted: confidence fell below %.2f, mode disabled", self.cfg.adaptive_exit_threshold)
|
||
self._cancel(trader, now, "алгос адаптировался")
|
||
self._update_queue(book, events)
|
||
led = trader.ledger
|
||
pos = led.position
|
||
if pos is not None:
|
||
our_side = "bid" if pos.side == "LONG" else "ask"
|
||
if sig and sig.batch_cancel_side == our_side:
|
||
self._close(trader, best_bid if pos.side == "LONG" else best_ask, now, "алгос снял пачку — экстренный выход",
|
||
sh.TAKER_FEE_PCT)
|
||
return
|
||
if not self.cfg.quick_exit and (now - self.filled_at) * 1000 >= self.cfg.max_hold_ms:
|
||
self._close(trader, best_bid if pos.side == "LONG" else best_ask, now, "время", sh.TAKER_FEE_PCT)
|
||
return
|
||
if self.order is not None and self.cfg.requote:
|
||
# Re-quote: follow the book every update; the order goes only when there is no candidate at all.
|
||
order = self.order
|
||
if now < order.ack:
|
||
return # still on its way to the exchange
|
||
cand = self._candidate(trader, now, book, sig, confirmed)
|
||
if cand is None:
|
||
self._cancel(trader, now, self.status_reason or "условия входа пропали", quiet=True)
|
||
elif (cand[0], cand[1]) != (order.side, order.price):
|
||
self.stats["requotes"] += 1
|
||
self.order = None
|
||
self._place(trader, now, sig, cand, log=False)
|
||
return
|
||
if self.order is not None:
|
||
order = self.order
|
||
spread_ticks = (best_ask - best_bid) / self.tick
|
||
if (now - order.sent) * 1000 > self.cfg.order_ttl_ms:
|
||
self._cancel(trader, now, "не исполнилась за отведённое время")
|
||
elif (not confirmed and not self.cfg.fallback) or spread_ticks > self.cfg.max_entry_spread_ticks:
|
||
self._cancel(trader, now, "алгос пропал или спред расширился")
|
||
elif spread_ticks < self.cfg.min_entry_spread_ticks - 1e-9:
|
||
self._cancel(trader, now, "спред сузился")
|
||
return
|
||
self._maybe_enter(trader, now, book, sig, confirmed)
|
||
|
||
def _update_queue(self, book: sh.OrderBook, events: list[LevelEvent]) -> None:
|
||
order = self.order
|
||
if order is None or order.ahead is None:
|
||
return
|
||
side = "bid" if order.side == "LONG" else "ask"
|
||
for e in events:
|
||
if e.side != side or abs(e.price - order.price) > self.tick / 2 or e.action != "cancel":
|
||
continue
|
||
# Cancels are assumed to come from behind us, except when the algo pulls its whole level:
|
||
# then its size leaves the queue in front of us and its re-quote lands behind us.
|
||
if order.algo_ahead and e.size >= 0.8 * order.algo_ahead:
|
||
order.ahead = max(0.0, order.ahead - order.algo_ahead)
|
||
order.algo_ahead = 0.0
|
||
order.front_run = True
|
||
self.log.info("queue: algo pulled its level %.10g, we are ahead now (ahead %.0f$)", order.price,
|
||
order.ahead)
|
||
|
||
def _maybe_enter(self, trader, now: float, book: sh.OrderBook, sig: AlgoSignature | None, confirmed: bool) -> None:
|
||
cand = self._candidate(trader, now, book, sig, confirmed)
|
||
if cand is not None:
|
||
self._place(trader, now, sig, cand)
|
||
|
||
def _candidate(self, trader, now: float, book: sh.OrderBook, sig: AlgoSignature | None,
|
||
confirmed: bool) -> tuple[str, float, str, float] | None:
|
||
"""(direction, price, scenario, algo volume in front) of the order to place now, or None (reason in status)."""
|
||
cfg = self.cfg
|
||
self.status_reason = ""
|
||
if not self.s.enabled or ((not confirmed or sig is None) and not cfg.fallback):
|
||
return None
|
||
best_bid, best_ask = book.best()
|
||
spread_ticks = (best_ask - best_bid) / self.tick
|
||
if spread_ticks > cfg.max_entry_spread_ticks:
|
||
self.status_reason = f"спред {spread_ticks:.0f} шаг. > {cfg.max_entry_spread_ticks}"
|
||
return None
|
||
if spread_ticks < cfg.min_entry_spread_ticks - 1e-9:
|
||
self.status_reason = f"спред {spread_ticks:.0f} шаг. < {cfg.min_entry_spread_ticks}"
|
||
return None
|
||
if self._vol_ticks(now) > cfg.vol_cap_ticks:
|
||
self.status_reason = "волатильность за 1 с выше порога"
|
||
return None
|
||
notional = self.s.stake * self.s.leverage
|
||
allowed, reason = self.guard.allow(now, notional, self._latency(trader))
|
||
if not allowed:
|
||
if reason != self.warned:
|
||
self.log.info("risk: %s", reason)
|
||
self.warned = reason
|
||
self.status_reason = reason
|
||
return None
|
||
candidates = []
|
||
algo_sides = () if not confirmed or sig is None else ("bid", "ask") if sig.side == "both" else (sig.side,)
|
||
for side in algo_sides:
|
||
direction = "LONG" if side == "bid" else "SHORT"
|
||
if not self._tape_pressure(now, direction):
|
||
continue
|
||
best = best_bid if side == "bid" else best_ask
|
||
algo_levels = [(p, v) for p, v in zip(sig.price_levels, sig.volumes)
|
||
if (p <= best if side == "bid" else p >= best)]
|
||
# Scenario 1: front-run the algo's level that is 0..front_run_max_ticks behind the touch.
|
||
for price, vol in sorted(algo_levels, key=lambda pv: abs(pv[0] - best)):
|
||
k = round(abs(best - price) / self.tick)
|
||
if 0 <= k <= cfg.front_run_max_ticks:
|
||
better = price + self.tick if side == "bid" else price - self.tick
|
||
crosses = better >= best_ask if side == "bid" else better <= best_bid
|
||
candidates.append((direction, price if crosses else better, "встать перед алгосом",
|
||
vol if crosses else 0.0))
|
||
break
|
||
# Scenario 2: pre-place on the level where the algo re-quotes next.
|
||
pred = self.tracker.prediction(side, book, self.tick)
|
||
if pred and pred[1] >= cfg.prediction_confidence:
|
||
candidates.append((direction, pred[0], "перестановка алгоса", 0.0))
|
||
if not candidates and cfg.fallback:
|
||
return self._fallback_candidate(book)
|
||
if not candidates:
|
||
self.status_reason = "нет давления в ленте в сторону алгоса"
|
||
return None
|
||
return candidates[0]
|
||
|
||
def _fallback_candidate(self, book: sh.OrderBook) -> tuple[str, float, str, float]:
|
||
"""No usable algo: direction from the microprice tilt plus which side moved the spread lately; always
|
||
returns an order one tick inside the spread on that side (or at the touch when the spread is 1 tick)."""
|
||
best_bid, best_ask = book.best()
|
||
bid_size, ask_size = book.bids.get(best_bid, 0.0), book.asks.get(best_ask, 0.0)
|
||
# Microprice tilt in [-1, 1]: a heavy bid queue (> 0) pulls the microprice towards the ask.
|
||
tilt = (bid_size - ask_size) / (bid_size + ask_size) if bid_size + ask_size > 0 else 0.0
|
||
flow = sum(sign for _, sign in self.spread_moves)
|
||
score = tilt + max(-1.0, min(1.0, flow / 3))
|
||
if score > 0:
|
||
direction = "LONG"
|
||
elif score < 0:
|
||
direction = "SHORT"
|
||
else:
|
||
direction = self.last_direction
|
||
self.last_direction = direction
|
||
inside = (best_ask - best_bid) / self.tick >= 2
|
||
if direction == "LONG":
|
||
price = best_bid + self.tick if inside else best_bid
|
||
else:
|
||
price = best_ask - self.tick if inside else best_ask
|
||
price = sh._to_tick(price, self.tick, None)
|
||
self.fallback_info = (f"без алгоса: микроцена {tilt:+.2f}, сдвиги спреда {flow:+d} → {direction}")
|
||
return direction, price, "микроцена + спред", 0.0
|
||
|
||
def _place(self, trader, now: float, sig: AlgoSignature, cand: tuple[str, float, str, float],
|
||
log: bool = True) -> None:
|
||
cfg = self.cfg
|
||
direction, price, scenario, algo_vol = cand
|
||
notional = self.s.stake * self.s.leverage
|
||
latency = (self._latency(trader) or 0.0) / 1000
|
||
if sig is None:
|
||
sig_copy = AlgoSignature("none", [], [], 0.0, now, [self.fallback_info], 0.0)
|
||
else:
|
||
sig_copy = AlgoSignature(sig.side, list(sig.price_levels), list(sig.volumes), sig.confidence,
|
||
sig.detected_at, list(sig.signals), sig.size)
|
||
self.order = HunterOrder(direction, price, notional, now, now + latency, scenario, sig_copy,
|
||
algo_ahead=algo_vol)
|
||
self.stats["orders"] += 1
|
||
if log:
|
||
self.log.info("order %s %s %.10g size=%.2f$ scenario=%s conf=%.2f dry_run=%s", self.ticker, direction,
|
||
price, notional, scenario, sig_copy.confidence, cfg.dry_run)
|
||
if cfg.dry_run:
|
||
# Dry run: the decision is logged, no virtual order is kept.
|
||
self.order = None
|
||
self.status_reason = f"dry-run: был бы вход {direction} {price:.10g} ({scenario})"
|
||
|
||
# --- trades: queue progress, fills, TP/SL ---------------------------------------------
|
||
def on_trade(self, trader, trade: sh.Trade) -> None:
|
||
self.detector.on_trade(trade)
|
||
order = self.order
|
||
if order is not None:
|
||
if trade.ts < order.ack:
|
||
return # not at the exchange yet
|
||
if order.ahead is None:
|
||
book_side = self.detector.prev["bid" if order.side == "LONG" else "ask"]
|
||
order.ahead = book_side.get(order.price, 0.0)
|
||
order.algo_ahead = min(order.algo_ahead, order.ahead)
|
||
order.front_run = order.front_run or order.algo_ahead == 0.0
|
||
long = order.side == "LONG"
|
||
hits_us = (trade.side == "Sell") if long else (trade.side == "Buy")
|
||
if (trade.price < order.price) if long else (trade.price > order.price):
|
||
self._fill(trader, trade.ts)
|
||
elif hits_us and abs(trade.price - order.price) < self.tick / 2:
|
||
consumed = min(order.ahead, trade.size)
|
||
order.ahead -= consumed
|
||
order.algo_ahead = max(0.0, order.algo_ahead - consumed)
|
||
if trade.size > consumed or order.ahead <= 0:
|
||
self._fill(trader, trade.ts)
|
||
return
|
||
pos = trader.ledger.position
|
||
if pos is None:
|
||
return
|
||
long = pos.side == "LONG"
|
||
if self.cfg.quick_exit:
|
||
# The next trade at another price closes the position at market, in profit or not.
|
||
if abs(trade.price - pos.entry) >= self.tick / 2:
|
||
best_bid, best_ask = self.best
|
||
exit_price = (best_bid if long else best_ask) or trade.price
|
||
way = "вверх" if trade.price > pos.entry else "вниз"
|
||
self._close(trader, exit_price, trade.ts, f"следующий тик: цена {way}", sh.TAKER_FEE_PCT)
|
||
return
|
||
if self.cfg.trailing and (trade.price >= pos.entry + self.cfg.tp_partial_ticks * self.tick if long
|
||
else trade.price <= pos.entry - self.cfg.tp_partial_ticks * self.tick):
|
||
self.stop = max(self.stop, pos.entry) if long else min(self.stop, pos.entry)
|
||
if (trade.price <= self.stop) if long else (trade.price >= self.stop):
|
||
slip = self.tick
|
||
self._close(trader, self.stop - slip if long else self.stop + slip, trade.ts,
|
||
"стоп (безубыток)" if self.stop == pos.entry else "стоп", sh.TAKER_FEE_PCT)
|
||
elif (trade.price > self.target) if long else (trade.price < self.target):
|
||
self._close(trader, self.target, trade.ts, "цель", sh.MAKER_FEE_PCT)
|
||
|
||
def _fill(self, trader, now: float) -> None:
|
||
order = self.order
|
||
self.order = None
|
||
long = order.side == "LONG"
|
||
trader.ledger.open(self.ticker, order.side, order.price, now, sh.MAKER_FEE_PCT, 0.0, None, order.price,
|
||
order.scenario)
|
||
self.entry_order = order
|
||
self.filled_at = now
|
||
self.target = order.price + (1 if long else -1) * self.cfg.tp_ticks * self.tick
|
||
self.stop = order.price - (1 if long else -1) * self.cfg.sl_ticks * self.tick
|
||
trader.ledger.position.target = self.target
|
||
trader.ledger.position.stop = self.stop
|
||
self.guard.on_entry(now)
|
||
self.stats["entries"] += 1
|
||
if order.front_run:
|
||
self.stats["front_run"] += 1
|
||
trader.message = f"Algo Hunter: исполнена {order.side} {order.price:.10g} ({order.scenario})"
|
||
self.log.info("fill %s %s %.10g front_run=%s", self.ticker, order.side, order.price, order.front_run)
|
||
|
||
def _cancel(self, trader, now: float, reason: str, quiet: bool = False) -> None:
|
||
if self.order is not None:
|
||
if not quiet:
|
||
self.log.info("cancel %s %s %.10g: %s", self.ticker, self.order.side, self.order.price, reason)
|
||
trader.message = f"Algo Hunter: заявка снята — {reason}"
|
||
self.order = None
|
||
|
||
def _close(self, trader, price: float, now: float, reason: str, fee_pct: float) -> None:
|
||
pos = trader.ledger.position
|
||
if pos is None:
|
||
return
|
||
order = self.entry_order
|
||
trader.close(price, now, reason, fee_pct)
|
||
trade = trader.ledger.trades[-1]
|
||
pnl_ticks = (price - pos.entry) / self.tick * (1 if pos.side == "LONG" else -1)
|
||
self.stats["pnl_ticks"] += pnl_ticks
|
||
if trade.net_usd > 0:
|
||
self.stats["wins"] += 1
|
||
self.guard.on_close(now, trade.net_usd)
|
||
self.log.info("exit %s %s entry=%.10g exit=%.10g pnl_ticks=%.1f net=%.4f$ hold_ms=%.0f reason=%s", self.ticker,
|
||
pos.side, pos.entry, price, pnl_ticks, trade.net_usd, (now - self.filled_at) * 1000, reason)
|
||
if self.trades_path and order is not None:
|
||
new = not self.trades_path.exists()
|
||
try:
|
||
with self.trades_path.open("a", encoding="utf-8-sig", newline="") as file:
|
||
writer = csv.writer(file)
|
||
if new:
|
||
writer.writerow(TRADE_COLUMNS)
|
||
sig = order.signature
|
||
writer.writerow([trade.closed_utc, self.ticker, pos.side, order.scenario, f"{sig.confidence:.2f}",
|
||
"|".join(sig.signals), sig.side, "|".join(f"{p:.10g}" for p in sig.price_levels),
|
||
"|".join(f"{v:.0f}" for v in sig.volumes), f"{order.price:.10g}",
|
||
f"{order.size_usd:.2f}", f"{order.sent:.3f}", f"{order.ack:.3f}",
|
||
f"{order.ahead if order.ahead is not None else 0:.0f}", order.front_run,
|
||
f"{pos.entry:.10g}", f"{price:.10g}", f"{pnl_ticks:.1f}", f"{trade.net_usd:.6f}",
|
||
f"{(now - self.filled_at) * 1000:.0f}", reason])
|
||
except OSError:
|
||
pass
|
||
self.entry_order = None
|
||
|
||
def rearm(self) -> None:
|
||
"""Switch the mode back on after an 'algo adapted' shutdown (user pressed Apply, or a new ticker)."""
|
||
self.tracker.reset_adaptation()
|
||
self.tracker.low_since = None
|
||
if self.guard.disabled_reason.startswith("алгос адаптировался"):
|
||
self.guard.disabled_reason = ""
|
||
self.log.info("rearmed after adaptation")
|
||
|
||
def entry_blockers(self, trader, now: float, book: sh.OrderBook) -> list[str]:
|
||
"""Every condition that currently prevents an entry (all of them, not only the first)."""
|
||
cfg = self.cfg
|
||
out = []
|
||
if cfg.dry_run:
|
||
out.append("включена «Только проверка»")
|
||
if not self.s.enabled:
|
||
out.append("тестовые сделки выключены")
|
||
if self.guard.disabled_reason:
|
||
out.append(self.guard.disabled_reason)
|
||
sig = self.sig
|
||
n = len(sig.signals) if sig else 0
|
||
if cfg.fallback:
|
||
pass # without a confirmed algo the microprice + spread fallback places the order
|
||
elif n < cfg.min_signals_to_confirm:
|
||
out.append(f"алгос не подтверждён: признаков {n} из {cfg.min_signals_to_confirm}")
|
||
elif sig.confidence < cfg.min_confidence:
|
||
out.append(f"уверенность {sig.confidence:.2f} < {cfg.min_confidence:g}")
|
||
best_bid, best_ask = book.best()
|
||
if best_bid is not None and best_ask is not None and self.tick > 0:
|
||
spread = (best_ask - best_bid) / self.tick
|
||
if spread > cfg.max_entry_spread_ticks + 1e-9:
|
||
out.append(f"спред {spread:.0f} шаг. > {cfg.max_entry_spread_ticks}")
|
||
if spread < cfg.min_entry_spread_ticks - 1e-9:
|
||
out.append(f"спред {spread:.0f} шаг. < {cfg.min_entry_spread_ticks}")
|
||
if self._vol_ticks(now) > cfg.vol_cap_ticks:
|
||
out.append(f"волатильность за 1 с {self._vol_ticks(now):.0f} шаг. > {cfg.vol_cap_ticks:g}")
|
||
problem = self.guard.latency_problem(self._latency(trader))
|
||
if problem:
|
||
out.append(problem.split(" — ")[0])
|
||
allowed, reason = self.guard.allow(now, self.s.stake * self.s.leverage, None)
|
||
if not allowed and reason not in out:
|
||
out.append(reason)
|
||
return out
|
||
|
||
# --- periodic: status for the window ----------------------------------------------------
|
||
def on_tick(self, trader, now: float, ticker: str, hint, book: sh.OrderBook, tick: float) -> None:
|
||
if ticker != self.ticker and self.ticker:
|
||
self.detector = AlgoDetector(self.cfg)
|
||
self.tracker = AlgoTracker(self.cfg)
|
||
self.rearm()
|
||
self.ticker = ticker
|
||
if tick > 0:
|
||
self.tick = tick
|
||
sig = self.sig
|
||
latency = self._latency(trader)
|
||
parts = []
|
||
if latency is not None:
|
||
parts.append(f"задержка данных ~{latency:.0f} мс" + (" (больше 50 мс: гонку за очередь не выиграть)"
|
||
if latency > self.cfg.max_data_latency_ms else ""))
|
||
if sig:
|
||
parts.append(f"уверенность {sig.confidence:.2f} ({', '.join(sig.signals)})")
|
||
if sig.price_levels:
|
||
shown = ", ".join(f"{p:.10g}×{v:,.0f}$" for p, v in list(zip(sig.price_levels, sig.volumes))[:4])
|
||
parts.append(f"уровни алгоса [{sig.side}]: {shown}")
|
||
else:
|
||
parts.append("алгос не найден")
|
||
if self.order is not None and self.order.scenario == "микроцена + спред":
|
||
parts.append(self.fallback_info)
|
||
lifetime = self.tracker.avg_lifetime_ms
|
||
if lifetime:
|
||
offset_b = self.tracker.typical_offset_ticks("bid")
|
||
offset_a = self.tracker.typical_offset_ticks("ask")
|
||
parts.append(f"живёт {lifetime:.0f} мс · перестановок {self.tracker.replace_frequency(now):.1f}/с · отступ "
|
||
f"bid {offset_b if offset_b is not None else '—'} / ask {offset_a if offset_a is not None else '—'} шаг.")
|
||
e = self.stats["entries"]
|
||
parts.append(f"находок {self.stats['detections']} · заявок {self.stats['orders']} · входов {e} · в плюс "
|
||
f"{(self.stats['wins'] / e * 100 if e else 0):.0f}% · ср. {self.stats['pnl_ticks'] / e if e else 0:+.2f} шаг. · "
|
||
f"впереди алгоса {(self.stats['front_run'] / e * 100 if e else 0):.0f}%")
|
||
if self.cfg.dry_run:
|
||
parts.append("ПРОВЕРОЧНЫЙ РЕЖИМ: только детект и лог")
|
||
status = " · ".join(parts)
|
||
if trader.ledger.position is None and self.order is None:
|
||
blockers = self.entry_blockers(trader, now, book)
|
||
if not blockers and self.status_reason:
|
||
blockers = [self.status_reason]
|
||
if blockers:
|
||
status += "\nПочему нет входа: " + " · ".join(f"✗ {b}" for b in blockers)
|
||
self.status = status
|