1711 lines
86 KiB
Python
1711 lines
86 KiB
Python
"""Scalping hint from the MetaScalp order book and tape: which side, where to enter, stop and target.
|
||
|
||
Read-only: connects to the local MetaScalp API (127.0.0.1:17845-17855), follows the order book that
|
||
is open in the terminal and never sends orders. The rules mirror a manual read of the book:
|
||
|
||
* book imbalance - resting size near the price on the bid side versus the ask side;
|
||
* tape delta and momentum - who hits the market and where the price moved recently;
|
||
* absorption - heavy market selling that does not push the price down (or the mirror case);
|
||
* plan - enter next to the density on the chosen side, keep the stop BEHIND that density,
|
||
aim just before the opposite density and skip moves that do not cover the trading costs.
|
||
|
||
Every hint that becomes actionable is also checked against the following trades (would the limit
|
||
fill, then stop or target first) and appended to a CSV journal, so the hints build their own statistics.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import csv
|
||
import json
|
||
import math
|
||
import queue
|
||
import statistics
|
||
import threading
|
||
import time
|
||
import urllib.request
|
||
from collections import deque
|
||
from dataclasses import dataclass, field, fields
|
||
from datetime import datetime, timezone
|
||
from pathlib import Path
|
||
|
||
API_HOST = "127.0.0.1"
|
||
API_PORTS = range(17845, 17856)
|
||
JOURNAL_FILE = Path(__file__).with_name("scalp_hint_journal.csv")
|
||
MAKER_FEE_PCT = 0.02
|
||
TAKER_FEE_PCT = 0.055
|
||
# Weights of the score components; the adaptive paper policy re-weights them from its own results.
|
||
DEFAULT_WEIGHTS = {"book_imb": 0.35, "near_imb": 0.15, "tape_delta": 0.3, "momentum": 0.2, "absorption": 0.15}
|
||
|
||
|
||
@dataclass
|
||
class HintSettings:
|
||
weights: dict = field(default_factory=lambda: dict(DEFAULT_WEIGHTS))
|
||
window_pct: float = 0.3 # depth window around the mid price for imbalance and densities
|
||
near_levels: int = 5 # levels per side for the "near the price" imbalance
|
||
density_mult: float = 4.0 # a density is a level >= mult x median level size in the window
|
||
tape_seconds: float = 60.0 # tape window for delta, momentum and absorption
|
||
entry_offset_ticks: int = 1 # enter this many ticks in front of the density
|
||
stop_buffer_ticks: int = 2 # stop this many ticks behind the density / recent extreme
|
||
min_target_pct: float = 0.15 # the move must at least cover fees and slippage
|
||
min_rr: float = 1.5 # minimum reward / risk
|
||
max_entry_distance_pct: float = 0.3
|
||
score_threshold: float = 0.25 # below this |score| the hint is "wait"
|
||
min_trades: int = 5 # fewer tape trades than this: the tape is ignored
|
||
min_risk_pct: float = 0.1 # stop at least this far, and at least half the recent tape range
|
||
smooth_seconds: float = 8.0 # time constant of the score smoothing (removes flicker)
|
||
fill_minutes: float = 2.0 # how long a hinted limit order may wait for a fill
|
||
hold_minutes: float = 5.0 # time stop once filled
|
||
|
||
|
||
class OrderBook:
|
||
"""Absolute-size price levels; an update with size 0 removes the level."""
|
||
|
||
def __init__(self) -> None:
|
||
self.asks: dict[float, float] = {}
|
||
self.bids: dict[float, float] = {}
|
||
|
||
def clear(self) -> None:
|
||
self.asks.clear()
|
||
self.bids.clear()
|
||
|
||
def apply_snapshot(self, data: dict) -> None:
|
||
self.clear()
|
||
for level in data.get("asks", []):
|
||
self._set(self.asks, level)
|
||
for level in data.get("bids", []):
|
||
self._set(self.bids, level)
|
||
marks = [level for level in (data.get("bestAsk"), data.get("bestBid")) if isinstance(level, dict)]
|
||
if marks:
|
||
self.apply_updates(marks)
|
||
|
||
def apply_updates(self, updates: list[dict]) -> None:
|
||
best_ask_mark = best_bid_mark = None
|
||
for level in updates:
|
||
kind = str(level.get("type", ""))
|
||
if kind in ("Ask", "BestAsk"):
|
||
self._set(self.asks, level)
|
||
elif kind in ("Bid", "BestBid"):
|
||
self._set(self.bids, level)
|
||
try:
|
||
if kind == "BestAsk" and float(level["size"]) > 0:
|
||
best_ask_mark = float(level["price"])
|
||
elif kind == "BestBid" and float(level["size"]) > 0:
|
||
best_bid_mark = float(level["price"])
|
||
except (KeyError, TypeError, ValueError):
|
||
pass
|
||
# MetaScalp marks the current best prices; levels in front of them are stale (consumed or
|
||
# cancelled without an explicit removal), so they are dropped.
|
||
if best_ask_mark is not None:
|
||
for price in [p for p in self.asks if p < best_ask_mark]:
|
||
del self.asks[price]
|
||
if best_bid_mark is not None:
|
||
for price in [p for p in self.bids if p > best_bid_mark]:
|
||
del self.bids[price]
|
||
if self.asks and self.bids:
|
||
best_ask, best_bid = min(self.asks), max(self.bids)
|
||
if best_bid >= best_ask:
|
||
# Still crossed without best-price marks: drop the crossing bids until the next update.
|
||
for price in [p for p in self.bids if p >= best_ask]:
|
||
del self.bids[price]
|
||
|
||
@staticmethod
|
||
def _set(side: dict[float, float], level: dict) -> None:
|
||
try:
|
||
price, size = float(level["price"]), float(level["size"])
|
||
except (KeyError, TypeError, ValueError):
|
||
return
|
||
if size <= 0:
|
||
side.pop(price, None)
|
||
else:
|
||
side[price] = size
|
||
|
||
def best(self) -> tuple[float | None, float | None]:
|
||
return (max(self.bids) if self.bids else None, min(self.asks) if self.asks else None)
|
||
|
||
|
||
@dataclass
|
||
class Trade:
|
||
ts: float
|
||
price: float
|
||
size: float
|
||
side: str # "Buy" or "Sell" (aggressor)
|
||
|
||
|
||
class Tape:
|
||
def __init__(self, keep_seconds: float = 900.0) -> None:
|
||
self.trades: deque[Trade] = deque()
|
||
self.keep = keep_seconds
|
||
|
||
def add(self, trade: Trade) -> None:
|
||
self.trades.append(trade)
|
||
while self.trades and self.trades[0].ts < trade.ts - self.keep:
|
||
self.trades.popleft()
|
||
|
||
def window(self, seconds: float, now: float) -> list[Trade]:
|
||
return [t for t in self.trades if t.ts >= now - seconds]
|
||
|
||
def clear(self) -> None:
|
||
self.trades.clear()
|
||
|
||
|
||
@dataclass
|
||
class Hint:
|
||
side: str # "LONG", "SHORT" or "WAIT"
|
||
confidence: str
|
||
score: float
|
||
entry: float | None = None
|
||
stop: float | None = None
|
||
target: float | None = None
|
||
rr: float | None = None
|
||
reasons: list[str] = field(default_factory=list)
|
||
metrics: dict = field(default_factory=dict)
|
||
|
||
|
||
def _clip(value: float) -> float:
|
||
return max(-1.0, min(1.0, value))
|
||
|
||
|
||
def _to_tick(price: float, tick: float, up: bool | None = None) -> float:
|
||
steps = price / tick
|
||
steps = math.ceil(steps - 1e-9) if up else math.floor(steps + 1e-9) if up is False else round(steps)
|
||
decimals = max(0, -int(math.floor(math.log10(tick)))) if tick < 1 else 0
|
||
return round(steps * tick, decimals + 2)
|
||
|
||
|
||
def _imbalance(bid: float, ask: float) -> float:
|
||
total = bid + ask
|
||
return (bid - ask) / total if total > 0 else 0.0
|
||
|
||
|
||
def significant_imbalance(book: OrderBook, depth_pct: float = 0.3, low_pct: float = 20.0,
|
||
high_pct: float = 90.0) -> dict | None:
|
||
"""Imbalance of the 'significant' resting orders near the price.
|
||
|
||
Levels within ±depth_pct of the mid are pooled (both sides); levels below the low percentile of their
|
||
sizes (noise) and above the high percentile (outsized walls, often pulled before the price arrives)
|
||
are dropped, and the remaining sizes are summed per side. Returns None without a usable book.
|
||
"""
|
||
best_bid, best_ask = book.best()
|
||
if best_bid is None or best_ask is None:
|
||
return None
|
||
mid = (best_bid + best_ask) / 2
|
||
window = mid * depth_pct / 100
|
||
levels = sorted([(s, "ask") for p, s in book.asks.items() if p <= mid + window]
|
||
+ [(s, "bid") for p, s in book.bids.items() if p >= mid - window])
|
||
if len(levels) < 4:
|
||
return None
|
||
# Cut by count, not by value: many identical sizes at a percentile would otherwise all be
|
||
# kept or all be dropped. The smallest low_pct% and the largest (100 - high_pct)% of levels go.
|
||
n = len(levels)
|
||
drop_low = int(n * low_pct / 100)
|
||
drop_high = int(n * (100 - high_pct) / 100)
|
||
kept = levels[drop_low:n - drop_high] or levels
|
||
bid_sum = sum(s for s, side in kept if side == "bid")
|
||
ask_sum = sum(s for s, side in kept if side == "ask")
|
||
return {"mid": mid, "bid_sum": bid_sum, "ask_sum": ask_sum, "imbalance": _imbalance(bid_sum, ask_sum),
|
||
"low": kept[0][0], "high": kept[-1][0], "used": len(kept), "levels": n}
|
||
|
||
|
||
class HintEngine:
|
||
"""Smooths the score over time so the hint does not flip on every book update."""
|
||
|
||
def __init__(self, settings: HintSettings) -> None:
|
||
self.settings = settings
|
||
self.score: float | None = None
|
||
self.at = 0.0
|
||
|
||
def reset(self) -> None:
|
||
self.score = None
|
||
|
||
def __call__(self, book: OrderBook, tape: Tape, tick: float, now: float) -> Hint:
|
||
raw = evaluate(book, tape, tick, self.settings, now)
|
||
if not raw.metrics:
|
||
return raw
|
||
if self.score is None:
|
||
self.score = raw.score
|
||
else:
|
||
alpha = 1 - math.exp(-max(0.0, now - self.at) / self.settings.smooth_seconds)
|
||
self.score += alpha * (raw.score - self.score)
|
||
self.at = now
|
||
return evaluate(book, tape, tick, self.settings, now, score_override=self.score)
|
||
|
||
|
||
def evaluate(book: OrderBook, tape: Tape, tick: float, settings: HintSettings, now: float,
|
||
score_override: float | None = None) -> Hint:
|
||
best_bid, best_ask = book.best()
|
||
if best_bid is None or best_ask is None or tick <= 0:
|
||
return Hint("WAIT", "—", 0.0, reasons=["Нет стакана — жду данные MetaScalp"])
|
||
mid = (best_bid + best_ask) / 2
|
||
spread_pct = (best_ask - best_bid) / mid * 100
|
||
window = mid * settings.window_pct / 100
|
||
asks = sorted((p, s) for p, s in book.asks.items() if p <= mid + window)
|
||
bids = sorted(((p, s) for p, s in book.bids.items() if p >= mid - window), reverse=True)
|
||
if not asks or not bids:
|
||
return Hint("WAIT", "—", 0.0, reasons=["Стакан слишком тонкий в окне ±{:g}%".format(settings.window_pct)])
|
||
|
||
# Book imbalance, levels closer to the price weigh more.
|
||
def weighted(levels):
|
||
return sum(s * (1 - abs(p - mid) / window) for p, s in levels)
|
||
|
||
book_imb = _imbalance(weighted(bids), weighted(asks))
|
||
near_imb = _imbalance(sum(s for _, s in bids[:settings.near_levels]),
|
||
sum(s for _, s in asks[:settings.near_levels]))
|
||
|
||
# Safety: the book must agree with the tape, otherwise it is out of sync and nothing is hinted.
|
||
if tape.trades:
|
||
last_price = tape.trades[-1].price
|
||
if abs(last_price - mid) / mid * 100 > 0.3:
|
||
return Hint("WAIT", "—", 0.0, reasons=[
|
||
f"Стакан расходится с лентой ({mid:.10g} против последней сделки {last_price:.10g}) — "
|
||
"жду обновления данных"])
|
||
|
||
# Tape delta, momentum and absorption.
|
||
recent = tape.window(settings.tape_seconds, now)
|
||
buy = sum(t.size for t in recent if t.side == "Buy")
|
||
sell = sum(t.size for t in recent if t.side == "Sell")
|
||
enough = len(recent) >= settings.min_trades
|
||
tape_delta = _imbalance(buy, sell) if enough else 0.0
|
||
if enough:
|
||
momentum = _clip((recent[-1].price - recent[0].price) / mid / (settings.window_pct / 100))
|
||
tape_high = max(t.price for t in recent)
|
||
tape_low = min(t.price for t in recent)
|
||
else:
|
||
momentum, tape_high, tape_low = 0.0, best_ask, best_bid
|
||
absorption = 0.0
|
||
if enough and buy + sell > 0:
|
||
if tape_delta < -0.3 and momentum >= 0:
|
||
absorption = 1.0 # sellers hit hard, price does not fall: buyers absorb
|
||
elif tape_delta > 0.3 and momentum <= 0:
|
||
absorption = -1.0 # buyers hit hard, price does not rise: sellers absorb
|
||
|
||
w = settings.weights
|
||
raw_score = (w["book_imb"] * book_imb + w["near_imb"] * near_imb + w["tape_delta"] * tape_delta
|
||
+ w["momentum"] * momentum + w["absorption"] * absorption)
|
||
score = raw_score if score_override is None else score_override
|
||
min_risk = max(mid * settings.min_risk_pct / 100, (tape_high - tape_low) / 2, 2 * tick)
|
||
sizes = [s for _, s in asks] + [s for _, s in bids]
|
||
median = statistics.median(sizes) if sizes else 0.0
|
||
threshold = median * settings.density_mult
|
||
resistance = next(((p, s) for p, s in asks if s >= threshold and p > best_ask - tick / 2), None)
|
||
support = next(((p, s) for p, s in bids if s >= threshold and p < best_bid + tick / 2), None)
|
||
|
||
metrics = {"mid": mid, "spread_pct": spread_pct, "book_imb": book_imb, "near_imb": near_imb,
|
||
"tape_delta": tape_delta, "momentum": momentum, "absorption": absorption,
|
||
"trades": len(recent), "resistance": resistance, "support": support,
|
||
"ask_volume": sum(s for _, s in asks), "bid_volume": sum(s for _, s in bids)}
|
||
reasons = [
|
||
f"Стакан ±{settings.window_pct:g}%: покупатели {metrics['bid_volume']:,.0f} / продавцы "
|
||
f"{metrics['ask_volume']:,.0f} (перекос {book_imb:+.2f}, у цены {near_imb:+.2f})",
|
||
(f"Лента {settings.tape_seconds:.0f} с: покупки {buy:,.0f} / продажи {sell:,.0f} "
|
||
f"(перевес {tape_delta:+.2f}), импульс {momentum:+.2f}, сделок {len(recent)}")
|
||
if enough else f"Лента: мало сделок за {settings.tape_seconds:.0f} с ({len(recent)}) — не учитывается",
|
||
]
|
||
if absorption > 0:
|
||
reasons.append("Поглощение: продают по рынку, но цена не падает — снизу держат")
|
||
elif absorption < 0:
|
||
reasons.append("Поглощение: покупают по рынку, но цена не растёт — сверху держат")
|
||
if resistance:
|
||
reasons.append(f"Плотность продавцов {resistance[1]:,.0f} на {resistance[0]:.10g}")
|
||
if support:
|
||
reasons.append(f"Плотность покупателей {support[1]:,.0f} на {support[0]:.10g}")
|
||
reasons.append(f"Спред {spread_pct:.3f}%")
|
||
thin = min(metrics["ask_volume"], metrics["bid_volume"]) / max(metrics["ask_volume"], metrics["bid_volume"])
|
||
if thin < 0.08:
|
||
reasons.append("Внимание: одна сторона стакана почти пустая — так бывает при резком движении; "
|
||
"сверьтесь со стаканом в терминале")
|
||
|
||
strength = abs(score)
|
||
if strength < settings.score_threshold:
|
||
reasons.insert(0, "Перевеса нет — боковик, вход не нужен")
|
||
return Hint("WAIT", "—", score, reasons=reasons, metrics=metrics)
|
||
confidence = "высокая" if strength >= 0.65 else "средняя" if strength >= 0.45 else "низкая"
|
||
side = "LONG" if score > 0 else "SHORT"
|
||
offset = settings.entry_offset_ticks * tick
|
||
buffer = settings.stop_buffer_ticks * tick
|
||
if side == "SHORT":
|
||
if resistance and resistance[0] - offset >= best_ask:
|
||
entry = resistance[0] - offset
|
||
stop = resistance[0] + buffer
|
||
else:
|
||
entry = best_ask
|
||
stop = max(entry, tape_high) + buffer
|
||
stop = max(stop, entry + min_risk)
|
||
risk = stop - entry
|
||
target = support[0] + offset if support and support[0] + offset < entry - risk else entry - 2 * risk
|
||
reward = entry - target
|
||
else:
|
||
if support and support[0] + offset <= best_bid:
|
||
entry = support[0] + offset
|
||
stop = support[0] - buffer
|
||
else:
|
||
entry = best_bid
|
||
stop = min(entry, tape_low) - buffer
|
||
stop = min(stop, entry - min_risk)
|
||
risk = entry - stop
|
||
target = resistance[0] - offset if resistance and resistance[0] - offset > entry + risk else entry + 2 * risk
|
||
reward = target - entry
|
||
# Orders sit on the price grid: the stop rounds away from the entry, the target towards it.
|
||
if side == "SHORT":
|
||
entry, stop, target = _to_tick(entry, tick), _to_tick(stop, tick, up=True), _to_tick(target, tick, up=True)
|
||
risk, reward = stop - entry, entry - target
|
||
else:
|
||
entry, stop, target = _to_tick(entry, tick), _to_tick(stop, tick, up=False), _to_tick(target, tick, up=False)
|
||
risk, reward = entry - stop, target - entry
|
||
rr = reward / risk if risk > 0 else 0.0
|
||
reward_pct = reward / entry * 100
|
||
entry_distance = abs(entry - mid) / mid * 100
|
||
hint = Hint(side, confidence, score, entry, stop, target, rr, reasons, metrics)
|
||
problems = []
|
||
if reward_pct < settings.min_target_pct:
|
||
problems.append(f"ход до цели {reward_pct:.2f}% меньше издержек ({settings.min_target_pct:g}%)")
|
||
if rr < settings.min_rr:
|
||
problems.append(f"риск/прибыль 1:{rr:.1f} хуже 1:{settings.min_rr:g}")
|
||
if entry_distance > settings.max_entry_distance_pct:
|
||
problems.append(f"вход далеко от цены ({entry_distance:.2f}%)")
|
||
if problems:
|
||
hint.reasons.insert(0, f"Перевес в {side}, но сделка невыгодна: " + "; ".join(problems))
|
||
hint.side = "WAIT"
|
||
return hint
|
||
|
||
|
||
@dataclass
|
||
class Tracked:
|
||
ticker: str
|
||
side: str
|
||
entry: float
|
||
stop: float
|
||
target: float
|
||
created: float
|
||
confidence: str
|
||
score: float
|
||
filled_at: float | None = None
|
||
result: str = ""
|
||
pnl_pct: float = 0.0
|
||
|
||
|
||
class Journal:
|
||
"""Checks each actionable hint against later trades: fill, then stop or target first."""
|
||
|
||
def __init__(self, settings: HintSettings, path: Path = JOURNAL_FILE) -> None:
|
||
self.settings = settings
|
||
self.path = path
|
||
self.active: Tracked | None = None
|
||
self.done: list[Tracked] = []
|
||
self._load()
|
||
|
||
def _load(self) -> None:
|
||
try:
|
||
with self.path.open(encoding="utf-8-sig") as file:
|
||
for row in csv.DictReader(file):
|
||
self.done.append(Tracked(row["ticker"], row["side"], float(row["entry"]), float(row["stop"]),
|
||
float(row["target"]), 0.0, row["confidence"], float(row["score"]),
|
||
result=row["result"], pnl_pct=float(row["pnl_pct"] or 0)))
|
||
except (OSError, KeyError, ValueError):
|
||
pass
|
||
|
||
def offer(self, ticker: str, hint: Hint, now: float) -> None:
|
||
if self.active is not None or hint.side == "WAIT" or hint.entry is None:
|
||
return
|
||
self.active = Tracked(ticker, hint.side, hint.entry, hint.stop, hint.target, now, hint.confidence, hint.score)
|
||
|
||
def cancel(self, reason: str) -> None:
|
||
if self.active and self.active.filled_at is None:
|
||
self._finish(reason, 0.0)
|
||
elif self.active:
|
||
self._finish(reason, self.active.pnl_pct)
|
||
|
||
def on_trade(self, trade: Trade) -> None:
|
||
tr = self.active
|
||
if tr is None:
|
||
return
|
||
long = tr.side == "LONG"
|
||
if tr.filled_at is None:
|
||
# A resting limit fills only when the market trades through it (queue is unknown).
|
||
through = trade.price < tr.entry if long else trade.price > tr.entry
|
||
if through:
|
||
tr.filled_at = trade.ts
|
||
elif trade.ts - tr.created > self.settings.fill_minutes * 60:
|
||
self._finish("не исполнился", 0.0)
|
||
return
|
||
stop_hit = trade.price <= tr.stop if long else trade.price >= tr.stop
|
||
target_hit = trade.price >= tr.target if long else trade.price <= tr.target
|
||
sign = 1 if long else -1
|
||
if stop_hit:
|
||
self._finish("стоп", sign * (tr.stop - tr.entry) / tr.entry * 100 - MAKER_FEE_PCT - TAKER_FEE_PCT)
|
||
elif target_hit:
|
||
self._finish("цель", sign * (tr.target - tr.entry) / tr.entry * 100 - 2 * MAKER_FEE_PCT)
|
||
elif trade.ts - tr.filled_at > self.settings.hold_minutes * 60:
|
||
self._finish("время", sign * (trade.price - tr.entry) / tr.entry * 100 - MAKER_FEE_PCT - TAKER_FEE_PCT)
|
||
|
||
def _finish(self, result: str, pnl: float) -> None:
|
||
tr = self.active
|
||
self.active = None
|
||
if tr is None:
|
||
return
|
||
tr.result, tr.pnl_pct = result, pnl
|
||
self.done.append(tr)
|
||
new_file = not self.path.exists()
|
||
try:
|
||
with self.path.open("a", encoding="utf-8-sig", newline="") as file:
|
||
writer = csv.writer(file)
|
||
if new_file:
|
||
writer.writerow(["time_utc", "ticker", "side", "confidence", "score", "entry", "stop", "target",
|
||
"result", "pnl_pct"])
|
||
writer.writerow([datetime.now(timezone.utc).isoformat(timespec="seconds"), tr.ticker, tr.side,
|
||
tr.confidence, f"{tr.score:.3f}", f"{tr.entry:.10g}", f"{tr.stop:.10g}",
|
||
f"{tr.target:.10g}", result, f"{pnl:.4f}"])
|
||
except OSError:
|
||
pass
|
||
|
||
def stats(self) -> str:
|
||
filled = [t for t in self.done if t.result in ("стоп", "цель", "время")]
|
||
if not filled:
|
||
unfilled = sum(t.result == "не исполнился" for t in self.done)
|
||
return f"Проверено подсказок: 0 исполненных · не исполнилось {unfilled}"
|
||
wins = sum(t.pnl_pct > 0 for t in filled)
|
||
avg = sum(t.pnl_pct for t in filled) / len(filled)
|
||
return (f"Исполнено {len(filled)} · в плюс {wins} ({wins / len(filled) * 100:.0f}%) · "
|
||
f"средний итог {avg:+.3f}% после комиссий · не исполнилось "
|
||
f"{sum(t.result == 'не исполнился' for t in self.done)}")
|
||
|
||
|
||
# --------------------------------------------------------------------------------------------
|
||
# MetaScalp connection
|
||
# --------------------------------------------------------------------------------------------
|
||
|
||
def discover_port() -> int | None:
|
||
for port in API_PORTS:
|
||
try:
|
||
with urllib.request.urlopen(f"http://{API_HOST}:{port}/ping", timeout=1) as response:
|
||
if json.loads(response.read().decode("utf-8")).get("app") == "MetaScalp":
|
||
return port
|
||
except Exception:
|
||
continue
|
||
return None
|
||
|
||
|
||
def active_order_book(port: int) -> dict | None:
|
||
"""The order book document of the selected tab: connection id, ticker and price step."""
|
||
with urllib.request.urlopen(f"http://{API_HOST}:{port}/api/ui/state", timeout=3) as response:
|
||
state = json.loads(response.read().decode("utf-8"))
|
||
for window in state.get("windows", []):
|
||
tabs = window.get("tabs", [])
|
||
for tab in sorted(tabs, key=lambda t: not t.get("isSelected")):
|
||
for doc in tab.get("documents", []):
|
||
if doc.get("kind") == "orderBook" and doc.get("orderBook"):
|
||
return {"connectionId": doc["connectionId"], "ticker": doc["ticker"],
|
||
"tick": float(doc["orderBook"].get("priceIncrement") or 0)}
|
||
return None
|
||
|
||
|
||
def connection_name(port: int, connection_id: int) -> str:
|
||
try:
|
||
with urllib.request.urlopen(f"http://{API_HOST}:{port}/api/connections/{connection_id}", timeout=3) as r:
|
||
data = json.loads(r.read().decode("utf-8"))
|
||
return str(data.get("Name") or data.get("name") or connection_id)
|
||
except Exception:
|
||
return str(connection_id)
|
||
|
||
|
||
def connection_info(port: int, connection_id: int) -> dict:
|
||
try:
|
||
with urllib.request.urlopen(f"http://{API_HOST}:{port}/api/connections/{connection_id}", timeout=3) as r:
|
||
return json.loads(r.read().decode("utf-8"))
|
||
except Exception:
|
||
return {}
|
||
|
||
|
||
BYBIT_WS = "wss://stream.bybit.com/v5/public/linear"
|
||
|
||
|
||
class ClockSync:
|
||
"""Exchange-minus-local clock offset, re-measured every `period` seconds (the PC clock drifts and Windows
|
||
steps it now and then, which would otherwise show up as a sudden jump in measured latency)."""
|
||
|
||
def __init__(self, period: float = 60.0) -> None:
|
||
self.period = period
|
||
self.offset: float | None = None
|
||
self.measured = -1e9
|
||
|
||
def get(self) -> float | None:
|
||
if time.monotonic() - self.measured > self.period:
|
||
self.measured = time.monotonic()
|
||
value = bybit_clock_offset()
|
||
if value is not None:
|
||
self.offset = value
|
||
return self.offset
|
||
|
||
|
||
def bybit_clock_offset() -> float | None:
|
||
"""Exchange clock minus local clock, seconds (round-trip corrected); None when Bybit is unreachable."""
|
||
try:
|
||
t0 = time.time()
|
||
with urllib.request.urlopen("https://api.bybit.com/v5/market/time", timeout=5) as response:
|
||
payload = json.loads(response.read().decode("utf-8"))
|
||
t1 = time.time()
|
||
server = int(payload["result"]["timeNano"]) / 1e9
|
||
return server - (t0 + t1) / 2
|
||
except Exception:
|
||
return None
|
||
|
||
|
||
def parse_time(value: str) -> float:
|
||
try:
|
||
return datetime.fromisoformat(value.replace("Z", "+00:00")).timestamp()
|
||
except (ValueError, AttributeError):
|
||
return time.time()
|
||
|
||
|
||
class Feed(threading.Thread):
|
||
"""WebSocket reader: pushes ("book_snapshot"|"book_update"|"trades", data) into a queue."""
|
||
|
||
def __init__(self, port: int, connection_id: int, ticker: str, out: queue.Queue) -> None:
|
||
super().__init__(daemon=True)
|
||
self.port, self.connection_id, self.ticker, self.out = port, connection_id, ticker, out
|
||
self.stopped = threading.Event()
|
||
self.ws = None
|
||
|
||
def stop(self) -> None:
|
||
self.stopped.set()
|
||
try:
|
||
if self.ws:
|
||
self.ws.close()
|
||
except Exception:
|
||
pass
|
||
|
||
def run(self) -> None:
|
||
import websocket
|
||
clock = ClockSync()
|
||
while not self.stopped.is_set():
|
||
try:
|
||
self.ws = websocket.create_connection(f"ws://{API_HOST}:{self.port}/", timeout=30)
|
||
base = {"connectionId": self.connection_id, "ticker": self.ticker}
|
||
self.ws.send(json.dumps({"Type": "orderbook_subscribe",
|
||
"Data": {**base, "zoomIndex": 0, "depthLevels": 100, "depthPercent": 1.0}}))
|
||
self.ws.send(json.dumps({"Type": "trade_subscribe", "Data": {**base, "zoomIndex": 1}}))
|
||
self.out.put(("status", f"Подключено: {self.ticker}"))
|
||
while not self.stopped.is_set():
|
||
message = json.loads(self.ws.recv())
|
||
kind = message.get("Type")
|
||
data = message.get("Data") or {}
|
||
if data.get("ticker") not in (None, self.ticker):
|
||
continue
|
||
if kind == "orderbook_snapshot":
|
||
self.out.put(("book_snapshot", data))
|
||
elif kind == "orderbook_update":
|
||
self.out.put(("book_update", data.get("updates", [])))
|
||
elif kind == "trade_update":
|
||
trades = data.get("trades", [])
|
||
self.out.put(("trades", trades))
|
||
offset = clock.get()
|
||
if offset is not None and trades:
|
||
exchange_time = parse_time(trades[-1].get("time"))
|
||
self.out.put(("latency", (time.time() + offset - exchange_time) * 1000))
|
||
except Exception as exc:
|
||
if self.stopped.is_set():
|
||
return
|
||
self.out.put(("status", f"Нет связи с MetaScalp: {exc}; переподключение…"))
|
||
time.sleep(2)
|
||
|
||
|
||
class BybitFeed(threading.Thread):
|
||
"""Direct Bybit public WebSocket (orderbook.50 every ~20 ms + public trades), converted to the same events
|
||
as the MetaScalp feed. Sizes are converted from coins to USDT so both sources look alike."""
|
||
|
||
def __init__(self, ticker: str, out: queue.Queue) -> None:
|
||
super().__init__(daemon=True)
|
||
self.ticker, self.out = ticker, out
|
||
self.stopped = threading.Event()
|
||
self.ws = None
|
||
|
||
def stop(self) -> None:
|
||
self.stopped.set()
|
||
try:
|
||
if self.ws:
|
||
self.ws.close()
|
||
except Exception:
|
||
pass
|
||
|
||
@staticmethod
|
||
def _levels(rows, kind: str) -> list[dict]:
|
||
out = []
|
||
for price, size in rows:
|
||
p, s = float(price), float(size)
|
||
out.append({"price": p, "size": s * p, "type": kind})
|
||
return out
|
||
|
||
def run(self) -> None:
|
||
import websocket
|
||
clock = ClockSync()
|
||
while not self.stopped.is_set():
|
||
try:
|
||
self.ws = websocket.create_connection(BYBIT_WS, timeout=10)
|
||
self.ws.send(json.dumps({"op": "subscribe",
|
||
"args": [f"orderbook.50.{self.ticker}", f"publicTrade.{self.ticker}"]}))
|
||
self.out.put(("status", f"Bybit напрямую: {self.ticker}"))
|
||
last_ping = time.time()
|
||
self.ws.settimeout(5)
|
||
while not self.stopped.is_set():
|
||
if time.time() - last_ping > 20:
|
||
self.ws.send(json.dumps({"op": "ping"}))
|
||
last_ping = time.time()
|
||
try:
|
||
message = json.loads(self.ws.recv())
|
||
except websocket.WebSocketTimeoutException:
|
||
continue
|
||
topic = str(message.get("topic", ""))
|
||
data = message.get("data")
|
||
if topic.startswith("orderbook.") and isinstance(data, dict):
|
||
if message.get("type") == "snapshot":
|
||
self.out.put(("book_snapshot", {"asks": self._levels(data.get("a", []), "Ask"),
|
||
"bids": self._levels(data.get("b", []), "Bid")}))
|
||
else:
|
||
self.out.put(("book_update", self._levels(data.get("a", []), "Ask")
|
||
+ self._levels(data.get("b", []), "Bid")))
|
||
elif topic.startswith("publicTrade.") and isinstance(data, list):
|
||
trades = []
|
||
for row in data:
|
||
try:
|
||
p = float(row["p"])
|
||
trades.append({"price": p, "size": float(row["v"]) * p, "side": row.get("S"),
|
||
"time": datetime.fromtimestamp(int(row["T"]) / 1000,
|
||
timezone.utc).isoformat()})
|
||
except (KeyError, TypeError, ValueError):
|
||
continue
|
||
if trades:
|
||
self.out.put(("trades", trades))
|
||
offset = clock.get()
|
||
if offset is not None:
|
||
self.out.put(("latency", (time.time() + offset - int(data[-1]["T"]) / 1000) * 1000))
|
||
except Exception as exc:
|
||
if self.stopped.is_set():
|
||
return
|
||
self.out.put(("status", f"Нет связи с Bybit: {exc}; переподключение…"))
|
||
time.sleep(2)
|
||
|
||
|
||
KUCOIN_BULLET = "https://api-futures.kucoin.com/api/v1/bullet-public"
|
||
KUCOIN_SPOT_BULLET = "https://api.kucoin.com/api/v1/bullet-public"
|
||
|
||
|
||
class KucoinFeed(threading.Thread):
|
||
"""KuCoin public WebSocket: best bid/ask of one futures contract (tickerV2, e.g. MARSCOINUSDTM) or one spot pair
|
||
(/market/ticker, e.g. MARSCOIN-USDT), pushed as ("leader", (bid, ask)) plus ("leader_latency", ms) measured
|
||
against Bybit's clock."""
|
||
|
||
def __init__(self, ticker: str, out: queue.Queue, spot: bool = False) -> None:
|
||
super().__init__(daemon=True)
|
||
self.ticker, self.out, self.spot = ticker, out, spot
|
||
self.stopped = threading.Event()
|
||
self.ws = None
|
||
|
||
def stop(self) -> None:
|
||
self.stopped.set()
|
||
try:
|
||
if self.ws:
|
||
self.ws.close()
|
||
except Exception:
|
||
pass
|
||
|
||
def parse(self, message: dict) -> tuple[float, float, float] | None:
|
||
"""(bid, ask, exchange time in s) from a futures tickerV2 or a spot /market/ticker message."""
|
||
data = message.get("data") or {}
|
||
try:
|
||
if self.spot and message.get("subject") == "trade.ticker":
|
||
return float(data["bestBid"]), float(data["bestAsk"]), float(data.get("time") or 0) / 1e3
|
||
if not self.spot and message.get("subject") == "tickerV2":
|
||
return float(data["bestBidPrice"]), float(data["bestAskPrice"]), float(data.get("ts") or 0) / 1e9
|
||
except (KeyError, TypeError, ValueError):
|
||
return None
|
||
return None
|
||
|
||
def run(self) -> None:
|
||
import websocket
|
||
clock = ClockSync()
|
||
while not self.stopped.is_set():
|
||
try:
|
||
req = urllib.request.Request(KUCOIN_SPOT_BULLET if self.spot else KUCOIN_BULLET, data=b"",
|
||
method="POST", headers={"User-Agent": "Mozilla/5.0"})
|
||
with urllib.request.urlopen(req, timeout=10) as resp:
|
||
bullet = json.loads(resp.read())["data"]
|
||
server = bullet["instanceServers"][0]
|
||
self.ws = websocket.create_connection(f"{server['endpoint']}?token={bullet['token']}", timeout=5)
|
||
topic = f"/market/ticker:{self.ticker}" if self.spot else f"/contractMarket/tickerV2:{self.ticker}"
|
||
self.ws.send(json.dumps({"id": "1", "type": "subscribe", "response": True, "topic": topic}))
|
||
self.out.put(("leader_status", f"KuCoin {'спот' if self.spot else 'фьючерс'}: {self.ticker}"))
|
||
last_ping = time.time()
|
||
while not self.stopped.is_set():
|
||
if time.time() - last_ping > 15:
|
||
self.ws.send(json.dumps({"id": "ping", "type": "ping"}))
|
||
last_ping = time.time()
|
||
try:
|
||
message = json.loads(self.ws.recv())
|
||
except websocket.WebSocketTimeoutException:
|
||
continue
|
||
bid_ask = self.parse(message)
|
||
if bid_ask is None:
|
||
continue
|
||
bid, ask, exchange_time = bid_ask
|
||
self.out.put(("leader", (bid, ask)))
|
||
offset = clock.get()
|
||
if offset is not None and exchange_time:
|
||
self.out.put(("leader_latency", (time.time() + offset - exchange_time) * 1000))
|
||
except Exception as exc:
|
||
if self.stopped.is_set():
|
||
return
|
||
self.out.put(("leader_status", f"Нет связи с KuCoin: {exc}; переподключение…"))
|
||
time.sleep(2)
|
||
|
||
|
||
BINANCE_PUBLIC_WS = "wss://fstream.binance.com/public/stream?streams=" # bookTicker
|
||
BINANCE_MARKET_WS = "wss://fstream.binance.com/market/stream?streams=" # aggTrade
|
||
|
||
|
||
class BinanceFeed(threading.Thread):
|
||
"""Binance USDⓈ-M futures: best bid/ask (bookTicker, every change) as a one-level book plus aggregated trades,
|
||
as the same events as the Bybit feed (sizes in USDT)."""
|
||
|
||
def __init__(self, ticker: str, out: queue.Queue) -> None:
|
||
super().__init__(daemon=True)
|
||
self.ticker, self.out = ticker, out
|
||
self.stopped = threading.Event()
|
||
self.sockets: list = []
|
||
|
||
def stop(self) -> None:
|
||
self.stopped.set()
|
||
for ws in self.sockets:
|
||
try:
|
||
ws.close()
|
||
except Exception:
|
||
pass
|
||
|
||
def book_event(self, data: dict) -> tuple | None:
|
||
try:
|
||
bid, ask = float(data["b"]), float(data["a"])
|
||
return ("book_snapshot", {"bids": [{"price": bid, "size": float(data["B"]) * bid, "type": "Bid"}],
|
||
"asks": [{"price": ask, "size": float(data["A"]) * ask, "type": "Ask"}]})
|
||
except (KeyError, TypeError, ValueError):
|
||
return None
|
||
|
||
@staticmethod
|
||
def trade_event(data: dict) -> tuple | None:
|
||
try:
|
||
p = float(data["p"])
|
||
return ("trades", [{"price": p, "size": float(data["q"]) * p, "side": "Sell" if data.get("m") else "Buy",
|
||
"time": datetime.fromtimestamp(int(data["T"]) / 1000, timezone.utc).isoformat()}])
|
||
except (KeyError, TypeError, ValueError):
|
||
return None
|
||
|
||
def _loop(self, url: str, kind: str) -> None:
|
||
import websocket
|
||
clock = ClockSync()
|
||
while not self.stopped.is_set():
|
||
try:
|
||
ws = websocket.create_connection(url, timeout=5)
|
||
self.sockets.append(ws)
|
||
self.out.put(("status", f"Binance фьючерс напрямую: {self.ticker}"))
|
||
while not self.stopped.is_set():
|
||
try:
|
||
message = json.loads(ws.recv())
|
||
except websocket.WebSocketTimeoutException:
|
||
continue
|
||
data = message.get("data") or {}
|
||
event = self.book_event(data) if kind == "book" else self.trade_event(data)
|
||
if event:
|
||
self.out.put(event)
|
||
offset = clock.get()
|
||
if kind == "trades" and offset is not None and data.get("T"):
|
||
self.out.put(("latency", (time.time() + offset - int(data["T"]) / 1000) * 1000))
|
||
except Exception as exc:
|
||
if self.stopped.is_set():
|
||
return
|
||
self.out.put(("status", f"Нет связи с Binance: {exc}; переподключение…"))
|
||
time.sleep(2)
|
||
|
||
def run(self) -> None:
|
||
s = self.ticker.lower()
|
||
threading.Thread(target=self._loop, args=(f"{BINANCE_MARKET_WS}{s}@aggTrade", "trades"), daemon=True).start()
|
||
self._loop(f"{BINANCE_PUBLIC_WS}{s}@bookTicker", "book")
|
||
|
||
|
||
MEXC_WS = "wss://contract.mexc.com/edge"
|
||
|
||
|
||
def mexc_contract(ticker: str) -> tuple[float, float]:
|
||
"""(price step, coins per contract) of a MEXC USDT perpetual such as SI_USDT."""
|
||
try:
|
||
with urllib.request.urlopen(f"https://contract.mexc.com/api/v1/contract/detail?symbol={ticker}",
|
||
timeout=15) as resp:
|
||
data = json.loads(resp.read())["data"]
|
||
return float(data["priceUnit"]), float(data["contractSize"])
|
||
except (OSError, ValueError, KeyError, TypeError):
|
||
return 0.0, 1.0
|
||
|
||
|
||
class MexcFeed(threading.Thread):
|
||
"""MEXC USDT perpetual (e.g. SI_USDT): the top 5 levels of the book (push.depth.full) and trades (push.deal),
|
||
as the same events as the Bybit feed (sizes in USDT, from contracts × contract size)."""
|
||
|
||
def __init__(self, ticker: str, out: queue.Queue, contract_size: float = 1.0) -> None:
|
||
super().__init__(daemon=True)
|
||
self.ticker, self.out, self.contract_size = ticker, out, contract_size
|
||
self.stopped = threading.Event()
|
||
self.ws = None
|
||
|
||
def stop(self) -> None:
|
||
self.stopped.set()
|
||
try:
|
||
if self.ws:
|
||
self.ws.close()
|
||
except Exception:
|
||
pass
|
||
|
||
def parse(self, message: dict) -> list[tuple]:
|
||
channel, data = message.get("channel"), message.get("data")
|
||
events = []
|
||
try:
|
||
if channel == "push.depth.full" and isinstance(data, dict):
|
||
def levels(rows, kind):
|
||
return [{"price": float(p), "size": float(v) * self.contract_size * float(p), "type": kind}
|
||
for p, v, *_ in rows]
|
||
events.append(("book_snapshot", {"asks": levels(data.get("asks", []), "Ask"),
|
||
"bids": levels(data.get("bids", []), "Bid")}))
|
||
elif channel == "push.deal":
|
||
rows = data if isinstance(data, list) else [data]
|
||
trades = [{"price": float(d["p"]), "size": float(d["v"]) * self.contract_size * float(d["p"]),
|
||
"side": "Buy" if int(d.get("T", 1)) == 1 else "Sell",
|
||
"time": datetime.fromtimestamp(int(d["t"]) / 1000, timezone.utc).isoformat()}
|
||
for d in rows]
|
||
if trades:
|
||
events.append(("trades", trades))
|
||
except (KeyError, TypeError, ValueError):
|
||
return []
|
||
return events
|
||
|
||
def run(self) -> None:
|
||
import websocket
|
||
clock = ClockSync()
|
||
while not self.stopped.is_set():
|
||
try:
|
||
self.ws = websocket.create_connection(MEXC_WS, timeout=5)
|
||
self.ws.send(json.dumps({"method": "sub.depth.full", "param": {"symbol": self.ticker, "limit": 5}}))
|
||
self.ws.send(json.dumps({"method": "sub.deal", "param": {"symbol": self.ticker}}))
|
||
self.out.put(("status", f"MEXC фьючерс напрямую: {self.ticker}"))
|
||
last_ping = time.time()
|
||
while not self.stopped.is_set():
|
||
if time.time() - last_ping > 15:
|
||
self.ws.send(json.dumps({"method": "ping"}))
|
||
last_ping = time.time()
|
||
try:
|
||
message = json.loads(self.ws.recv())
|
||
except websocket.WebSocketTimeoutException:
|
||
continue
|
||
for event in self.parse(message):
|
||
self.out.put(event)
|
||
offset = clock.get()
|
||
if event[0] == "trades" and offset is not None and message.get("ts"):
|
||
self.out.put(("latency", (time.time() + offset - int(message["ts"]) / 1000) * 1000))
|
||
except Exception as exc:
|
||
if self.stopped.is_set():
|
||
return
|
||
self.out.put(("status", f"Нет связи с MEXC: {exc}; переподключение…"))
|
||
time.sleep(2)
|
||
|
||
|
||
def binance_tick(ticker: str) -> float:
|
||
"""Price step of a Binance USDⓈ-M perpetual (public REST)."""
|
||
try:
|
||
with urllib.request.urlopen("https://fapi.binance.com/fapi/v1/exchangeInfo", timeout=15) as resp:
|
||
symbols = json.loads(resp.read())["symbols"]
|
||
for s in symbols:
|
||
if s["symbol"] == ticker.upper():
|
||
return float(next(f["tickSize"] for f in s["filters"] if f["filterType"] == "PRICE_FILTER"))
|
||
except (OSError, ValueError, KeyError, StopIteration):
|
||
pass
|
||
return 0.0
|
||
|
||
|
||
SOLANA_RPC = "https://api.mainnet-beta.solana.com"
|
||
SOLANA_WS = "wss://api.mainnet-beta.solana.com"
|
||
RAYDIUM_AMM_V4 = "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8"
|
||
RAYDIUM_CPMM = "CPMMoo8L3F4NbTegBCKVNunggL7H1ZpdTHKxQB5qKP1C"
|
||
PUMPSWAP = "pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA"
|
||
WSOL = "So11111111111111111111111111111111111111112"
|
||
STABLES = {"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB"}
|
||
_B58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
|
||
|
||
|
||
def b58encode(raw: bytes) -> str:
|
||
n = int.from_bytes(raw, "big")
|
||
out = ""
|
||
while n:
|
||
n, r = divmod(n, 58)
|
||
out = _B58[r] + out
|
||
return "1" * (len(raw) - len(raw.lstrip(b"\0"))) + out
|
||
|
||
|
||
def solana_rpc(method: str, params: list):
|
||
body = json.dumps({"jsonrpc": "2.0", "id": 1, "method": method, "params": params}).encode()
|
||
req = urllib.request.Request(SOLANA_RPC, data=body, headers={"Content-Type": "application/json"})
|
||
with urllib.request.urlopen(req, timeout=20) as resp:
|
||
return json.loads(resp.read())["result"]
|
||
|
||
|
||
def raydium_pool(owner: str, data: bytes) -> dict:
|
||
"""Vaults and mints of a Raydium constant-product pool (AMM v4 or CPMM) from its account data."""
|
||
import struct
|
||
if owner == RAYDIUM_AMM_V4:
|
||
return {"vault0": b58encode(data[336:368]), "vault1": b58encode(data[368:400]),
|
||
"mint0": b58encode(data[400:432]), "mint1": b58encode(data[432:464])}
|
||
if owner == RAYDIUM_CPMM:
|
||
return {"vault0": b58encode(data[72:104]), "vault1": b58encode(data[104:136]),
|
||
"mint0": b58encode(data[168:200]), "mint1": b58encode(data[200:232])}
|
||
if owner == PUMPSWAP:
|
||
# pool_bump u8, index u16, creator, base_mint, quote_mint, lp_mint, base vault, quote vault
|
||
return {"vault0": b58encode(data[139:171]), "vault1": b58encode(data[171:203]),
|
||
"mint0": b58encode(data[43:75]), "mint1": b58encode(data[75:107])}
|
||
raise ValueError("тип пула не поддерживается: нужен Raydium AMM v4 / CPMM / CLMM, PumpSwap, Meteora DLMM, "
|
||
"Orca Whirlpool или PancakeSwap CLMM")
|
||
|
||
|
||
METEORA_DLMM = "LBUZKhRxPF3XUpBCjp4YzTKgLccjZhTSDM9YuVaPwxo"
|
||
|
||
|
||
def dlmm_state(data: bytes) -> tuple[int, int, str, str]:
|
||
"""(active bin id, bin step in bps, token X mint, token Y mint) of a Meteora DLMM LbPair account."""
|
||
import struct
|
||
active_id, bin_step = struct.unpack_from("<iH", data, 76)
|
||
return active_id, bin_step, b58encode(data[88:120]), b58encode(data[120:152])
|
||
|
||
|
||
def dlmm_price(active_id: int, bin_step: int, decimals_x: int, decimals_y: int) -> float:
|
||
"""Price of X in Y of the active bin: (1 + bin_step/10000) ** active_id, scaled by the decimals."""
|
||
return (1 + bin_step / 10000) ** active_id * 10 ** (decimals_x - decimals_y)
|
||
|
||
|
||
ORCA_WHIRLPOOL = "whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc"
|
||
RAYDIUM_CLMM = "CAMMCzo5YL8w4VFF8KVHrK22GGUsp5VTaW7grrKgrWqK"
|
||
PANCAKE_CLMM = "HpNfyc2Saw7RKkQd8nEL4khUcuPhQ7WwY1B2qjx8jxFq" # a Raydium CLMM fork, same pool layout
|
||
CLMM_KINDS = {ORCA_WHIRLPOOL: "Orca Whirlpool", RAYDIUM_CLMM: "Raydium CLMM", PANCAKE_CLMM: "PancakeSwap CLMM"}
|
||
|
||
|
||
def clmm_state(owner: str, data: bytes) -> tuple[int, str, str]:
|
||
"""(sqrt price Q64.64, mint of token 0/A, mint of token 1/B) of a concentrated-liquidity pool account."""
|
||
if owner == ORCA_WHIRLPOOL:
|
||
# discriminator, config, bump, tick spacing, seed, fee, protocol fee, liquidity u128, sqrt_price u128 @65
|
||
return int.from_bytes(data[65:81], "little"), b58encode(data[101:133]), b58encode(data[181:213])
|
||
# Raydium CLMM PoolState: discriminator, bump, amm config, owner, mint0 @73, mint1 @105, …, sqrt_price_x64 @253
|
||
return int.from_bytes(data[253:269], "little"), b58encode(data[73:105]), b58encode(data[105:137])
|
||
|
||
|
||
def clmm_price(sqrt_price_x64: int, decimals_0: int, decimals_1: int) -> float:
|
||
"""Price of token 0 in token 1: (sqrt_price / 2**64) ** 2, scaled by the decimals."""
|
||
return (sqrt_price_x64 / 2 ** 64) ** 2 * 10 ** (decimals_0 - decimals_1)
|
||
|
||
|
||
def mint_decimals(mint: str) -> int:
|
||
return int(solana_rpc("getAccountInfo", [mint, {"encoding": "jsonParsed"}])["value"]["data"]["parsed"]["info"]
|
||
["decimals"])
|
||
|
||
|
||
def pool_price_usd(amounts: dict, token_vault: str, quote_vault: str, quote_usd: float) -> float | None:
|
||
token, quote = amounts.get(token_vault), amounts.get(quote_vault)
|
||
if not token or not quote or quote_usd <= 0:
|
||
return None
|
||
return quote / token * quote_usd
|
||
|
||
|
||
class RaydiumFeed(threading.Thread):
|
||
"""A Raydium pool on Solana in real time: the two vault balances over the public Solana RPC WebSocket
|
||
(accountSubscribe, 'processed' commitment); price = quote vault / token vault, in USD through Binance's SOL price
|
||
when the pool is quoted in SOL. Pushed as ("leader", (price, price)) on every swap (never on SOL moves alone)."""
|
||
|
||
def __init__(self, pool: str, out: queue.Queue) -> None:
|
||
super().__init__(daemon=True)
|
||
self.pool, self.out = pool, out
|
||
self.stopped = threading.Event()
|
||
self.ws = None
|
||
self.sol_usd = 0.0
|
||
|
||
def stop(self) -> None:
|
||
self.stopped.set()
|
||
try:
|
||
if self.ws:
|
||
self.ws.close()
|
||
except Exception:
|
||
pass
|
||
|
||
def _start_sol_price(self) -> None:
|
||
if not getattr(self, "_sol_thread", None):
|
||
self._sol_thread = threading.Thread(target=self._sol_price, daemon=True)
|
||
self._sol_thread.start()
|
||
|
||
def _run_dlmm(self, owner: str = METEORA_DLMM) -> None:
|
||
"""Pools whose price lives in the pool account itself — the pool account is watched, so every swap
|
||
refreshes the price. Meteora DLMM: the active bin's (1 + bin step) ** active id; Orca Whirlpool and
|
||
Raydium/PancakeSwap CLMM: (sqrt price) ** 2."""
|
||
import base64
|
||
import websocket
|
||
data = base64.b64decode(solana_rpc("getAccountInfo", [self.pool, {"encoding": "base64"}])["value"]["data"][0])
|
||
if owner == METEORA_DLMM:
|
||
_, _, mint_x, mint_y = dlmm_state(data)
|
||
kind = "Meteora DLMM"
|
||
else:
|
||
_, mint_x, mint_y = clmm_state(owner, data)
|
||
kind = CLMM_KINDS[owner]
|
||
dec_x, dec_y = mint_decimals(mint_x), mint_decimals(mint_y)
|
||
token_is_x = mint_y in (WSOL, *STABLES) or mint_x not in (WSOL, *STABLES)
|
||
quote_mint = mint_y if token_is_x else mint_x
|
||
if quote_mint == WSOL:
|
||
self._start_sol_price()
|
||
self.ws = websocket.create_connection(SOLANA_WS, timeout=30)
|
||
self.ws.send(json.dumps({"jsonrpc": "2.0", "id": 1, "method": "accountSubscribe",
|
||
"params": [self.pool, {"encoding": "base64", "commitment": "processed"}]}))
|
||
self.out.put(("leader_status", f"{kind} пул {self.pool[:6]}… (Solana, в реальном времени)"))
|
||
last_ping = time.time()
|
||
while not self.stopped.is_set():
|
||
if time.time() - last_ping > 30:
|
||
self.ws.ping()
|
||
last_ping = time.time()
|
||
try:
|
||
message = json.loads(self.ws.recv())
|
||
except websocket.WebSocketTimeoutException:
|
||
continue
|
||
try:
|
||
raw = base64.b64decode(message["params"]["result"]["value"]["data"][0])
|
||
except (KeyError, TypeError, IndexError):
|
||
continue
|
||
if owner == METEORA_DLMM:
|
||
active_id, bin_step, _, _ = dlmm_state(raw)
|
||
price_y_per_x = dlmm_price(active_id, bin_step, dec_x, dec_y)
|
||
else:
|
||
price_y_per_x = clmm_price(clmm_state(owner, raw)[0], dec_x, dec_y)
|
||
if price_y_per_x <= 0:
|
||
continue
|
||
in_quote = price_y_per_x if token_is_x else 1 / price_y_per_x
|
||
quote_usd = self.sol_usd if quote_mint == WSOL else 1.0
|
||
if quote_usd > 0:
|
||
price = in_quote * quote_usd
|
||
self.out.put(("leader", (price, price)))
|
||
|
||
def _sol_price(self) -> None:
|
||
import websocket
|
||
while not self.stopped.is_set():
|
||
try:
|
||
ws = websocket.create_connection(f"{BINANCE_PUBLIC_WS}solusdt@bookTicker", timeout=5)
|
||
while not self.stopped.is_set():
|
||
try:
|
||
d = json.loads(ws.recv()).get("data") or {}
|
||
except websocket.WebSocketTimeoutException:
|
||
continue
|
||
if d.get("b") and d.get("a"):
|
||
self.sol_usd = (float(d["b"]) + float(d["a"])) / 2
|
||
except Exception:
|
||
time.sleep(2)
|
||
|
||
def run(self) -> None:
|
||
import base64
|
||
import websocket
|
||
while not self.stopped.is_set():
|
||
try:
|
||
info = solana_rpc("getAccountInfo", [self.pool, {"encoding": "base64"}])["value"]
|
||
if info["owner"] == METEORA_DLMM or info["owner"] in CLMM_KINDS:
|
||
self._run_dlmm(info["owner"])
|
||
continue
|
||
pool = raydium_pool(info["owner"], base64.b64decode(info["data"][0]))
|
||
if pool["mint0"] in (WSOL, *STABLES) and pool["mint1"] not in (WSOL, *STABLES):
|
||
token_vault, quote_vault, quote_mint = pool["vault1"], pool["vault0"], pool["mint0"]
|
||
else:
|
||
token_vault, quote_vault, quote_mint = pool["vault0"], pool["vault1"], pool["mint1"]
|
||
quote_is_sol = quote_mint == WSOL
|
||
if quote_is_sol:
|
||
self._start_sol_price()
|
||
accounts = solana_rpc("getMultipleAccounts", [[token_vault, quote_vault],
|
||
{"encoding": "jsonParsed", "commitment": "processed"}])
|
||
amounts = {acc: v["data"]["parsed"]["info"]["tokenAmount"]["uiAmount"]
|
||
for acc, v in zip((token_vault, quote_vault), accounts["value"])}
|
||
self.ws = websocket.create_connection(SOLANA_WS, timeout=30)
|
||
ids = {}
|
||
for i, acc in enumerate((token_vault, quote_vault), start=1):
|
||
ids[i] = acc
|
||
self.ws.send(json.dumps({"jsonrpc": "2.0", "id": i, "method": "accountSubscribe",
|
||
"params": [acc, {"encoding": "jsonParsed", "commitment": "processed"}]}))
|
||
subs, slots = {}, {}
|
||
kind = "PumpSwap" if info["owner"] == PUMPSWAP else "Raydium"
|
||
self.out.put(("leader_status", f"{kind} пул {self.pool[:6]}… (Solana, в реальном времени)"))
|
||
last_ping = time.time()
|
||
while not self.stopped.is_set():
|
||
if time.time() - last_ping > 30:
|
||
self.ws.ping()
|
||
last_ping = time.time()
|
||
try:
|
||
message = json.loads(self.ws.recv())
|
||
except websocket.WebSocketTimeoutException:
|
||
continue
|
||
if "id" in message and "result" in message:
|
||
subs[message["result"]] = ids.get(message["id"])
|
||
continue
|
||
params = message.get("params") or {}
|
||
acc = subs.get(params.get("subscription"))
|
||
if acc is None:
|
||
continue
|
||
try:
|
||
amounts[acc] = params["result"]["value"]["data"]["parsed"]["info"]["tokenAmount"]["uiAmount"]
|
||
slots[acc] = params["result"]["context"]["slot"]
|
||
except (KeyError, TypeError):
|
||
continue
|
||
# a swap changes both vaults in one slot: price only when both are from the same slot
|
||
if slots.get(token_vault) != slots.get(quote_vault):
|
||
continue
|
||
price = pool_price_usd(amounts, token_vault, quote_vault, self.sol_usd if quote_is_sol else 1.0)
|
||
if price:
|
||
self.out.put(("leader", (price, price)))
|
||
except Exception as exc:
|
||
if self.stopped.is_set():
|
||
return
|
||
self.out.put(("leader_status", f"Нет связи с Solana: {exc}; переподключение…"))
|
||
time.sleep(3)
|
||
|
||
|
||
def bybit_tick(ticker: str) -> float:
|
||
"""Price step of a Bybit USDT perpetual (public REST)."""
|
||
try:
|
||
with urllib.request.urlopen(f"https://api.bybit.com/v5/market/instruments-info?category=linear&symbol={ticker}",
|
||
timeout=10) as resp:
|
||
items = json.loads(resp.read())["result"]["list"]
|
||
return float(items[0]["priceFilter"]["tickSize"]) if items else 0.0
|
||
except (OSError, ValueError, KeyError, IndexError):
|
||
return 0.0
|
||
|
||
|
||
# --------------------------------------------------------------------------------------------
|
||
# Window
|
||
# --------------------------------------------------------------------------------------------
|
||
|
||
def run_legacy_window() -> None:
|
||
"""The previous window with every strategy (simple, adaptive, pulse, sums, Algo Hunter): py -3 scalp_hint.py --legacy"""
|
||
import tkinter as tk
|
||
from tkinter import messagebox, ttk
|
||
|
||
import scalp_paper as sp
|
||
|
||
settings = HintSettings()
|
||
root = tk.Tk()
|
||
root.title("Подсказка скальпера · MetaScalp")
|
||
root.geometry("940x960")
|
||
root.attributes("-topmost", True)
|
||
events: queue.Queue = queue.Queue()
|
||
book, tape, journal = OrderBook(), Tape(), Journal(settings)
|
||
paper = sp.PaperTrader(sp.PaperSettings(), settings)
|
||
engine = HintEngine(settings)
|
||
state = {"port": None, "doc": None, "feed": None, "name": "", "last_side": "WAIT", "recorder": None}
|
||
|
||
header = tk.StringVar(value="Ищу MetaScalp…")
|
||
side_var = tk.StringVar(value="—")
|
||
plan_var = tk.StringVar(value="")
|
||
reasons_var = tk.StringVar(value="")
|
||
stats_var = tk.StringVar(value=journal.stats())
|
||
follow = tk.BooleanVar(value=True)
|
||
|
||
body = ttk.Frame(root, padding=10)
|
||
body.pack(fill="both", expand=True)
|
||
ttk.Label(body, textvariable=header, font=("Segoe UI", 10, "bold"), wraplength=860).pack(anchor="w")
|
||
top_row = ttk.Frame(body)
|
||
top_row.pack(fill="x")
|
||
ttk.Checkbutton(top_row, text="Следовать за стаканом, открытым в MetaScalp", variable=follow).pack(side="left")
|
||
sources = {"metascalp": "MetaScalp (стакан ~раз в 220 мс)", "bybit": "Bybit напрямую (стакан ~раз в 20 мс)"}
|
||
ttk.Label(top_row, text=" Источник стакана:").pack(side="left")
|
||
source_var = tk.StringVar(value=sources.get(paper.settings.data_source, sources["metascalp"]))
|
||
source_combo = ttk.Combobox(top_row, textvariable=source_var, values=list(sources.values()), state="readonly",
|
||
width=36)
|
||
source_combo.pack(side="left", padx=4)
|
||
latency_var = tk.StringVar(value="")
|
||
ttk.Label(top_row, textvariable=latency_var, foreground="#555").pack(side="left", padx=8)
|
||
latencies: deque[float] = deque(maxlen=300)
|
||
|
||
def on_source_change(_event=None) -> None:
|
||
paper.settings.data_source = next(k for k, v in sources.items() if v == source_var.get())
|
||
paper.ledger.save()
|
||
if state["doc"] is not None:
|
||
switch(state["doc"]) # reconnect with the new source
|
||
|
||
source_combo.bind("<<ComboboxSelected>>", on_source_change)
|
||
side_label = tk.Label(body, textvariable=side_var, font=("Segoe UI", 22, "bold"), anchor="w")
|
||
side_label.pack(fill="x", pady=(8, 2))
|
||
tk.Label(body, textvariable=plan_var, font=("Consolas", 11), justify="left", anchor="w").pack(fill="x")
|
||
bars = {}
|
||
for key, title in (("book_imb", "Стакан"), ("tape_delta", "Лента"), ("momentum", "Импульс")):
|
||
row = ttk.Frame(body)
|
||
row.pack(fill="x", pady=1)
|
||
ttk.Label(row, text=f"{title:8s}", width=9).pack(side="left")
|
||
canvas = tk.Canvas(row, height=14, width=300, highlightthickness=0, background="#e8e8e8")
|
||
canvas.pack(side="left")
|
||
value = ttk.Label(row, width=7)
|
||
value.pack(side="left", padx=4)
|
||
bars[key] = (canvas, value)
|
||
ttk.Label(body, textvariable=reasons_var, wraplength=860, justify="left").pack(anchor="w", pady=(8, 4))
|
||
ttk.Label(body, textvariable=stats_var, wraplength=860, foreground="#334").pack(anchor="w")
|
||
|
||
# --- paper trading -------------------------------------------------------------------
|
||
paper_box = ttk.LabelFrame(body, text="Тестовые сделки (виртуальный счёт, ордера на биржу не уходят)", padding=6)
|
||
paper_box.pack(fill="both", expand=True, pady=(8, 0))
|
||
ps = paper.settings
|
||
mode_row = ttk.Frame(paper_box)
|
||
mode_row.pack(fill="x", pady=(0, 4))
|
||
ttk.Label(mode_row, text="Схема решений:").pack(side="left")
|
||
mode_var = tk.StringVar(value=sp.MODES.get(ps.mode, sp.MODES["adaptive"]))
|
||
mode_combo = ttk.Combobox(mode_row, textvariable=mode_var, values=list(sp.MODES.values()), state="readonly",
|
||
width=42)
|
||
mode_combo.pack(side="left", padx=6)
|
||
mode_combo.bind("<<ComboboxSelected>>", lambda _e: (show_mode_fields(), apply_paper()))
|
||
record_var = tk.BooleanVar(value=True)
|
||
ttk.Checkbutton(mode_row, text=f"Записывать поток в {sp.RECORD_DIR.name}\\ (для сравнения схем)",
|
||
variable=record_var).pack(side="left", padx=10)
|
||
# Common settings in the first row; the second row shows only the fields of the selected scheme.
|
||
common_fields = (("budget", "Бюджет, $"), ("stake", "Ставка, $"), ("leverage", "Плечо"),
|
||
("min_target_pct", "Цель не меньше, %"), ("max_hold_minutes", "Макс. удержание, мин"))
|
||
mode_fields = {
|
||
"simple": (("adverse_ticks", "Закрыть при откате, шагов цены"),),
|
||
"adaptive": (("noise_mult", "Стоп × шум"), ("min_rr", "Прибыль / риск после комиссий")),
|
||
"pulse": (("pulse_offset_pct", "Лимитка от цены, %"),),
|
||
"sums": (("sums_depth_pct", "Глубина стакана, ±%"), ("sums_low_pct", "Без мелких: ниже перцентиля"),
|
||
("sums_high_pct", "Без крупных: выше перцентиля"), ("sums_threshold", "Перевес для входа (0–1)")),
|
||
# Algo Hunter keeps its own config (algo_hunter_config.json); the key prefix "ah." marks those fields.
|
||
"algo_hunter": (("ah.min_confidence", "Мин. уверенность (0–1)"), ("ah.tp_ticks", "TP, шагов цены"),
|
||
("ah.sl_ticks", "SL, шагов цены"), ("ah.max_hold_ms", "Удержание, мс"),
|
||
("ah.min_entry_spread_ticks", "Мин. спред для входа,\nшагов цены (0 = выкл)")),
|
||
}
|
||
import algo_hunter as ah
|
||
ah_cfg = paper.algo_config or ah.AlgoHunterConfig.load()
|
||
paper.algo_config = ah_cfg
|
||
if ps.mode == "algo_hunter" and getattr(paper.policy, "cfg", None) is not ah_cfg:
|
||
paper.policy = paper._make_policy()
|
||
paper_vars: dict[str, tk.StringVar] = {}
|
||
mode_cells: dict[str, list] = {}
|
||
form = ttk.Frame(paper_box)
|
||
form.pack(fill="x")
|
||
|
||
def add_field(key: str, label: str, row: int, column: int):
|
||
cell = ttk.Frame(form)
|
||
cell.grid(row=row, column=column, sticky="w", padx=(0, 8), pady=(0, 2))
|
||
ttk.Label(cell, text=label).pack(anchor="w")
|
||
source = ah_cfg if key.startswith("ah.") else ps
|
||
var = tk.StringVar(value=f"{getattr(source, key.removeprefix('ah.')):g}")
|
||
ttk.Entry(cell, textvariable=var, width=12).pack(anchor="w")
|
||
paper_vars[key] = var
|
||
return cell
|
||
|
||
for index, (key, label) in enumerate(common_fields):
|
||
add_field(key, label, 0, index)
|
||
mode_title = ttk.Label(form, text="", foreground="#1d4f91")
|
||
mode_title.grid(row=1, column=0, sticky="sw", pady=(4, 0))
|
||
for mode, items in mode_fields.items():
|
||
mode_cells[mode] = [add_field(key, label, 1, index + 1) for index, (key, label) in enumerate(items)]
|
||
invert_var = tk.BooleanVar(value=ps.sums_invert)
|
||
invert_cell = ttk.Checkbutton(form, text="Торговать против перевеса\n(LONG ↔ SHORT)", variable=invert_var,
|
||
command=lambda: apply_paper())
|
||
invert_cell.grid(row=1, column=len(mode_fields["sums"]) + 1, sticky="sw", padx=(4, 0))
|
||
mode_cells["sums"].append(invert_cell)
|
||
dry_run_var = tk.BooleanVar(value=ah_cfg.dry_run)
|
||
dry_run_cell = ttk.Checkbutton(form, text="Только проверка (dry-run):\nдетект и лог, без сделок",
|
||
variable=dry_run_var, command=lambda: apply_paper())
|
||
dry_run_cell.grid(row=1, column=len(mode_fields["algo_hunter"]) + 1, sticky="sw", padx=(4, 0))
|
||
mode_cells["algo_hunter"].append(dry_run_cell)
|
||
quick_exit_var = tk.BooleanVar(value=ah_cfg.quick_exit)
|
||
requote_var = tk.BooleanVar(value=ah_cfg.requote)
|
||
quick_cell = ttk.Frame(form)
|
||
quick_cell.grid(row=1, column=len(mode_fields["algo_hunter"]) + 2, sticky="sw", padx=(4, 0))
|
||
ttk.Checkbutton(quick_cell, text="Закрывать на следующем тике\n(без TP/SL/времени)", variable=quick_exit_var,
|
||
command=lambda: apply_paper()).pack(anchor="w")
|
||
ttk.Checkbutton(quick_cell, text="Переставлять заявку за стаканом", variable=requote_var,
|
||
command=lambda: apply_paper()).pack(anchor="w")
|
||
fallback_var = tk.BooleanVar(value=ah_cfg.fallback)
|
||
ttk.Checkbutton(quick_cell, text="Без алгоса: микроцена + сдвиги спреда\n(заявка всегда стоит)",
|
||
variable=fallback_var, command=lambda: apply_paper()).pack(anchor="w")
|
||
mode_cells["algo_hunter"].append(quick_cell)
|
||
|
||
def show_mode_fields(*_args) -> None:
|
||
mode = next((k for k, v in sp.MODES.items() if v == mode_var.get()), "adaptive")
|
||
mode_title.configure(text="Настройки схемы:")
|
||
for name, cells in mode_cells.items():
|
||
for cell in cells:
|
||
if name == mode:
|
||
cell.grid()
|
||
else:
|
||
cell.grid_remove()
|
||
|
||
show_mode_fields()
|
||
enabled_var = tk.BooleanVar(value=ps.enabled)
|
||
actions = ttk.Frame(paper_box)
|
||
actions.pack(fill="x", pady=(4, 2))
|
||
ttk.Checkbutton(actions, text="Открывать тестовые сделки по сигналам", variable=enabled_var,
|
||
command=lambda: apply_paper()).pack(side="left")
|
||
ttk.Button(actions, text="Применить", command=lambda: apply_paper()).pack(side="left", padx=6)
|
||
ttk.Button(actions, text="Закрыть позицию", command=lambda: paper.close_now(book, time.time(), "вручную")).pack(
|
||
side="left")
|
||
ttk.Button(actions, text="Сбросить счёт", command=lambda: reset_paper()).pack(side="left", padx=6)
|
||
paper_summary = tk.StringVar(value=paper.summary())
|
||
paper_position = tk.StringVar(value="")
|
||
paper_message = tk.StringVar(value="")
|
||
paper_status = tk.StringVar(value="")
|
||
ttk.Label(paper_box, textvariable=paper_summary, font=("Segoe UI", 10, "bold")).pack(anchor="w")
|
||
ttk.Label(paper_box, textvariable=paper_status, foreground="#1d4f91", wraplength=880).pack(anchor="w")
|
||
ttk.Label(paper_box, textvariable=paper_position, wraplength=880).pack(anchor="w")
|
||
ttk.Label(paper_box, textvariable=paper_message, foreground="#555", wraplength=860).pack(anchor="w")
|
||
columns = ("time", "ticker", "side", "qty", "usd", "entry", "exit", "pct", "net", "fee", "reason", "hold")
|
||
heads = {"time": "Закрыта (UTC)", "ticker": "Тикер", "side": "Напр.", "qty": "Объём", "usd": "Объём в $",
|
||
"entry": "Цена откр.", "exit": "Цена закр.", "pct": "Процент", "net": "Чистая, $",
|
||
"fee": "Комиссия, $", "reason": "Причина", "hold": "Сек."}
|
||
widths = {"time": 120, "ticker": 90, "side": 50, "qty": 70, "usd": 70, "entry": 80, "exit": 80, "pct": 65,
|
||
"net": 75, "fee": 75, "reason": 150, "hold": 45}
|
||
table_frame = ttk.Frame(paper_box)
|
||
table_frame.pack(fill="both", expand=True, pady=(4, 0))
|
||
tree = ttk.Treeview(table_frame, columns=columns, show="headings", height=8)
|
||
for col in columns:
|
||
tree.heading(col, text=heads[col])
|
||
tree.column(col, width=widths[col], anchor="center")
|
||
tree.tag_configure("win", foreground="#13843b")
|
||
tree.tag_configure("loss", foreground="#c62828")
|
||
scroll = ttk.Scrollbar(table_frame, orient="vertical", command=tree.yview)
|
||
tree.configure(yscrollcommand=scroll.set)
|
||
tree.pack(side="left", fill="both", expand=True)
|
||
scroll.pack(side="right", fill="y")
|
||
shown = {"count": -1}
|
||
|
||
def apply_paper() -> None:
|
||
try:
|
||
values = {key: float(var.get().replace(",", ".")) for key, var in paper_vars.items()}
|
||
if values["stake"] <= 0 or values["budget"] <= 0 or not 1 <= values["leverage"] <= 100:
|
||
raise ValueError("ставка и бюджет больше 0, плечо от 1 до 100")
|
||
if values["min_target_pct"] < 0 or values["adverse_ticks"] < 1 or values["max_hold_minutes"] <= 0:
|
||
raise ValueError("цель ≥ 0, откат ≥ 1 шага, удержание > 0")
|
||
if values["noise_mult"] <= 0 or values["min_rr"] <= 0:
|
||
raise ValueError("множитель шума и прибыль/риск больше 0")
|
||
if values["pulse_offset_pct"] < 0:
|
||
raise ValueError("отступ лимитки не может быть отрицательным")
|
||
if not (values["sums_depth_pct"] > 0 and 0 <= values["sums_low_pct"] < values["sums_high_pct"] <= 100
|
||
and 0 < values["sums_threshold"] < 1):
|
||
raise ValueError("глубина > 0, перцентили 0 ≤ мелкие < крупные ≤ 100, перевес от 0 до 1")
|
||
if not (0 < values["ah.min_confidence"] <= 1 and values["ah.tp_ticks"] >= 1 and values["ah.sl_ticks"] >= 1
|
||
and values["ah.max_hold_ms"] > 0 and values["ah.min_entry_spread_ticks"] >= 0):
|
||
raise ValueError("Algo Hunter: уверенность от 0 до 1, TP и SL ≥ 1 шага (SL обязателен), удержание > 0, "
|
||
"мин. спред ≥ 0")
|
||
except ValueError as exc:
|
||
paper_message.set(f"Проверьте настройки: {exc}")
|
||
return
|
||
budget_changed = values["budget"] != ps.budget
|
||
# Settings that live only in algo_hunter_config.json may have been edited by hand: take them from the file.
|
||
on_disk = ah.AlgoHunterConfig.load()
|
||
for f in fields(ah.AlgoHunterConfig):
|
||
if f"ah.{f.name}" not in values and f.name not in ("dry_run", "quick_exit", "requote", "fallback"):
|
||
setattr(ah_cfg, f.name, getattr(on_disk, f.name))
|
||
for key, value in values.items():
|
||
if key.startswith("ah."):
|
||
name = key.removeprefix("ah.")
|
||
setattr(ah_cfg, name, type(getattr(ah_cfg, name))(value))
|
||
else:
|
||
setattr(ps, key, int(value) if key == "adverse_ticks" else value)
|
||
ah_cfg.dry_run = bool(dry_run_var.get())
|
||
ah_cfg.quick_exit = bool(quick_exit_var.get())
|
||
ah_cfg.requote = bool(requote_var.get())
|
||
ah_cfg.fallback = bool(fallback_var.get())
|
||
ah_cfg.save()
|
||
if hasattr(paper.policy, "rearm"):
|
||
paper.policy.rearm() # «Применить» switches Algo Hunter back on after an adaptation shutdown
|
||
ps.enabled = bool(enabled_var.get())
|
||
ps.sums_invert = bool(invert_var.get())
|
||
mode = next((k for k, v in sp.MODES.items() if v == mode_var.get()), "adaptive")
|
||
if mode != ps.mode:
|
||
paper.close_now(book, time.time(), "смена схемы")
|
||
paper.set_mode(mode)
|
||
if budget_changed and not paper.trades and paper.position is None:
|
||
paper.ledger.balance = ps.budget
|
||
paper.ledger.save()
|
||
paper_message.set("Настройки тестовых сделок применены" +
|
||
(" · новый бюджет начнёт действовать после «Сбросить счёт»"
|
||
if budget_changed and (paper.trades or paper.position) else ""))
|
||
|
||
def reset_paper() -> None:
|
||
apply_paper()
|
||
paper.reset()
|
||
shown["count"] = -1
|
||
paper_message.set(f"Счёт сброшен: {ps.budget:g}$")
|
||
|
||
ttk.Label(body, text="Это подсказка по текущему стакану, не гарантия. Ордера не отправляются. "
|
||
f"Журналы: {JOURNAL_FILE.name}, {sp.TRADES_FILE.name}; записи потока: "
|
||
f"{sp.RECORD_DIR.name}\\ (сравнение: py -3 scalp_paper.py compare)", wraplength=880,
|
||
foreground="#777").pack(anchor="w", side="bottom")
|
||
|
||
def draw_bar(key: str, value: float) -> None:
|
||
canvas, label = bars[key]
|
||
canvas.delete("all")
|
||
width, mid = 300, 150
|
||
x = mid + value * mid
|
||
canvas.create_line(mid, 0, mid, 14, fill="#999")
|
||
canvas.create_rectangle(min(mid, x), 2, max(mid, x), 12, fill="#2e9d57" if value >= 0 else "#d04a4a",
|
||
outline="")
|
||
label.configure(text=f"{value:+.2f}")
|
||
|
||
def switch(doc: dict) -> None:
|
||
if state["feed"]:
|
||
state["feed"].stop()
|
||
journal.cancel("смена тикера")
|
||
paper.close_now(book, time.time(), "смена тикера")
|
||
book.clear()
|
||
tape.clear()
|
||
engine.reset()
|
||
state["last_side"] = "WAIT"
|
||
state["doc"] = doc
|
||
state["name"] = connection_name(state["port"], doc["connectionId"])
|
||
if state["recorder"]:
|
||
state["recorder"].close()
|
||
state["recorder"] = None
|
||
if record_var.get():
|
||
try:
|
||
state["recorder"] = sp.Recorder(doc["ticker"], doc["connectionId"], doc["tick"])
|
||
except OSError as exc:
|
||
paper_message.set(f"Запись потока недоступна: {exc}")
|
||
latencies.clear()
|
||
paper.data_latency_ms = None
|
||
feed = None
|
||
if paper.settings.data_source == "bybit":
|
||
info = connection_info(state["port"], doc["connectionId"])
|
||
if info.get("Exchange") == "Bybit" and "USDT" in str(info.get("Market", "")) \
|
||
and "Perpetual" in str(info.get("Market", "")):
|
||
feed = BybitFeed(doc["ticker"], events)
|
||
else:
|
||
paper_message.set(f"Bybit напрямую доступен только для фьючерсов Bybit USDT; {doc['ticker']} "
|
||
f"({info.get('Name', '?')}) читается через MetaScalp")
|
||
if feed is None:
|
||
feed = Feed(state["port"], doc["connectionId"], doc["ticker"], events)
|
||
state["feed"] = feed
|
||
state["source_name"] = "Bybit напрямую" if isinstance(feed, BybitFeed) else "MetaScalp"
|
||
feed.start()
|
||
|
||
def poll_ui() -> None:
|
||
try:
|
||
if state["port"] is None:
|
||
state["port"] = discover_port()
|
||
if state["port"] is None:
|
||
header.set("MetaScalp не найден на 127.0.0.1:17845–17855 — запустите терминал")
|
||
if state["port"] is not None and follow.get():
|
||
doc = active_order_book(state["port"])
|
||
if doc and (state["doc"] is None or (doc["connectionId"], doc["ticker"]) !=
|
||
(state["doc"]["connectionId"], state["doc"]["ticker"])):
|
||
switch(doc)
|
||
elif doc is None and state["doc"] is None:
|
||
header.set("Откройте стакан в MetaScalp")
|
||
except Exception as exc:
|
||
header.set(f"Ошибка API MetaScalp: {exc}")
|
||
state["port"] = None
|
||
root.after(2000, poll_ui)
|
||
|
||
def pump() -> None:
|
||
if record_var.get() and state["recorder"] is None and state["doc"] is not None:
|
||
try:
|
||
doc = state["doc"]
|
||
state["recorder"] = sp.Recorder(doc["ticker"], doc["connectionId"], doc["tick"])
|
||
except OSError:
|
||
pass
|
||
recorder = state["recorder"] if record_var.get() else None
|
||
for _ in range(5000):
|
||
try:
|
||
kind, data = events.get_nowait()
|
||
except queue.Empty:
|
||
break
|
||
# Receive time is used everywhere (tape, paper trades, recording) so a replay of the
|
||
# recording sees exactly the same sequence as the window.
|
||
now = time.time()
|
||
if kind == "book_snapshot":
|
||
book.apply_snapshot(data)
|
||
if recorder:
|
||
recorder.write("S", {"asks": data.get("asks", []), "bids": data.get("bids", []),
|
||
"bestAsk": data.get("bestAsk"), "bestBid": data.get("bestBid")}, now)
|
||
if state["doc"]:
|
||
paper.on_book(now, book, state["doc"]["tick"])
|
||
elif kind == "book_update":
|
||
book.apply_updates(data)
|
||
if recorder:
|
||
recorder.write("U", data, now)
|
||
if state["doc"]:
|
||
paper.on_book(now, book, state["doc"]["tick"])
|
||
elif kind == "latency":
|
||
latencies.append(float(data))
|
||
if len(latencies) >= 5:
|
||
paper.data_latency_ms = statistics.median(latencies)
|
||
elif kind == "trades":
|
||
if recorder:
|
||
recorder.write("T", data, now)
|
||
for raw in data:
|
||
try:
|
||
trade = Trade(now, float(raw["price"]), float(raw["size"]), str(raw.get("side")))
|
||
except (KeyError, TypeError, ValueError):
|
||
continue
|
||
tape.add(trade)
|
||
journal.on_trade(trade)
|
||
paper.on_trade(trade)
|
||
elif kind == "status":
|
||
header.set(data)
|
||
root.after(100, pump)
|
||
|
||
def refresh() -> None:
|
||
doc = state["doc"]
|
||
if doc:
|
||
hint = engine(book, tape, doc["tick"], time.time())
|
||
m = hint.metrics
|
||
header.set(f"{doc['ticker']} · {state['name']} · данные: {state.get('source_name', '')}" +
|
||
(f" · цена {m['mid']:.10g} · спред {m['spread_pct']:.3f}%" if m else ""))
|
||
if paper.data_latency_ms is not None:
|
||
latency_var.set(f"задержка данных ~{paper.data_latency_ms:.0f} мс (по часам Bybit)")
|
||
if (paper.settings.mode == "algo_hunter" and not state.get("latency_warned")
|
||
and paper.data_latency_ms > ah_cfg.max_data_latency_ms):
|
||
state["latency_warned"] = True
|
||
messagebox.showwarning(
|
||
"Algo Hunter: задержка слишком большая",
|
||
f"Данные приходят с задержкой ~{paper.data_latency_ms:.0f} мс (порог "
|
||
f"{ah_cfg.max_data_latency_ms:g} мс). Реальную гонку за место в очереди перед алгосом "
|
||
"с такой задержкой не выиграть: режим полезен только как проверка (dry-run) и для "
|
||
"виртуальной статистики, а RiskGuard не пустит виртуальные входы при задержке выше "
|
||
f"{ah_cfg.max_order_latency_ms:g} мс.", parent=root)
|
||
colors = {"LONG": "#1f8a4c", "SHORT": "#c23b3b", "WAIT": "#666"}
|
||
side_label.configure(fg=colors[hint.side])
|
||
if hint.side == "WAIT":
|
||
side_var.set("ЖДАТЬ")
|
||
plan_var.set("")
|
||
else:
|
||
mid = m["mid"]
|
||
side_var.set(f"{hint.side} · уверенность {hint.confidence}")
|
||
plan_var.set(
|
||
f"Вход лимиткой {hint.entry:.10g} ({(hint.entry / mid - 1) * 100:+.2f}%)\n"
|
||
f"Стоп {hint.stop:.10g} ({(hint.stop / mid - 1) * 100:+.2f}%)\n"
|
||
f"Цель {hint.target:.10g} ({(hint.target / mid - 1) * 100:+.2f}%)\n"
|
||
f"Риск/прибыль 1:{hint.rr:.1f} стоп по времени {settings.hold_minutes:g} мин")
|
||
if state["last_side"] != hint.side:
|
||
journal.offer(doc["ticker"], hint, time.time())
|
||
state["last_side"] = hint.side
|
||
for key in bars:
|
||
draw_bar(key, m.get(key, 0.0) if m else 0.0)
|
||
reasons_var.set("\n".join("• " + r for r in hint.reasons))
|
||
active = journal.active
|
||
stats_var.set("Проверка подсказок лимиткой: " + journal.stats() + (
|
||
f"\nПроверяется: {active.side} от {active.entry:.10g} — "
|
||
+ ("ждём исполнения" if active.filled_at is None else "в позиции") if active else ""))
|
||
if book.asks and book.bids:
|
||
paper.on_tick(time.time(), doc["ticker"], hint, book, doc["tick"])
|
||
pos = paper.position
|
||
order = paper.pending_order()
|
||
if pos:
|
||
pnl = paper.unrealized(book)
|
||
if paper.settings.mode == "pulse":
|
||
plan = "закрытие по рынку на следующем тике"
|
||
elif paper.settings.mode == "sums":
|
||
plan = (f"цель {pos.target:.10g} · выход при развороте перевеса или через "
|
||
f"{paper.settings.max_hold_minutes:g} мин")
|
||
else:
|
||
plan = (f"цель {pos.target:.10g} · " + (f"стоп {pos.stop:.10g}" if pos.stop is not None else
|
||
f"закрытие при откате на {paper.settings.adverse_ticks} шаг(а)"))
|
||
paper_position.set(
|
||
f"Позиция: {pos.side} {pos.ticker} {pos.qty:.6g} по {pos.entry:.10g} ({pos.entry * pos.qty:.2f}$) · "
|
||
f"{plan}{' · ' + pos.regime if pos.regime else ''} · сейчас {pnl:+.4f}$")
|
||
elif order and paper.settings.mode == "algo_hunter":
|
||
ahead = f"{order.ahead:,.0f}$" if order.ahead is not None else "ещё не на бирже"
|
||
paper_position.set(f"Лимитка {order.side} {order.price:.10g} ({order.scenario}) · в очереди перед нами "
|
||
f"{ahead} · впереди алгоса: {'да' if order.front_run else 'пока нет'}")
|
||
elif order and paper.settings.mode == "sums":
|
||
paper_position.set(f"Лимитка {order.side} {order.price:.10g} по лучшей цене — держится, пока есть перевес · "
|
||
f"цель {order.target:.10g}")
|
||
elif order and paper.settings.mode == "pulse":
|
||
paper_position.set(f"Лимитка {order.side} {order.price:.10g} — снимется и переставится на следующем тике, "
|
||
"если не исполнится")
|
||
elif order:
|
||
paper_position.set(f"Ждёт исполнения: лимитка {order.side} {order.price:.10g} ({order.regime}) · стоп "
|
||
f"{order.stop:.10g} · цель {order.target:.10g} · {time.time() - order.created:.0f} с")
|
||
else:
|
||
paper_position.set("Позиции нет" + ("" if paper.settings.enabled else " · тестовые сделки выключены"))
|
||
status = paper.policy.status
|
||
if paper.settings.mode == "pulse":
|
||
status = "Импульс + стакан: " + status
|
||
elif paper.settings.mode == "sums":
|
||
status = "Суммы: " + status
|
||
elif paper.settings.mode == "algo_hunter":
|
||
status = "Algo Hunter: " + status
|
||
elif paper.settings.mode == "adaptive":
|
||
weights = ", ".join(f"{k} {v:.2f}" for k, v in settings.weights.items())
|
||
status = f"Адаптивная: {status}\nВеса признаков: {weights}"
|
||
paper_status.set(status)
|
||
paper_summary.set(paper.summary())
|
||
if paper.message:
|
||
paper_message.set(paper.message)
|
||
if shown["count"] != len(paper.trades):
|
||
shown["count"] = len(paper.trades)
|
||
tree.delete(*tree.get_children())
|
||
for t in reversed(paper.trades[-300:]):
|
||
tree.insert("", "end", values=(
|
||
t.closed_utc[:19].replace("T", " "), t.ticker, t.side, f"{t.qty:.6g}", f"{t.notional_usd:.2f}",
|
||
f"{t.entry:.10g}", f"{t.exit:.10g}", f"{t.pct:+.3f}%", f"{t.net_usd:+.4f}", f"{t.fee_usd:.4f}",
|
||
t.reason, f"{t.hold_seconds:.0f}"), tags=("win" if t.net_usd > 0 else "loss",))
|
||
root.after(500, refresh)
|
||
|
||
def on_close() -> None:
|
||
if state["recorder"]:
|
||
state["recorder"].close()
|
||
if state["feed"]:
|
||
state["feed"].stop()
|
||
root.destroy()
|
||
|
||
root.protocol("WM_DELETE_WINDOW", on_close)
|
||
poll_ui()
|
||
pump()
|
||
refresh()
|
||
root.mainloop()
|
||
|
||
|
||
def run_console(seconds: float) -> None:
|
||
"""Headless check: print a hint every few seconds (used for testing the connection)."""
|
||
settings = HintSettings()
|
||
port = discover_port()
|
||
if port is None:
|
||
raise SystemExit("MetaScalp не найден")
|
||
doc = active_order_book(port)
|
||
if not doc:
|
||
raise SystemExit("В MetaScalp не открыт стакан")
|
||
events: queue.Queue = queue.Queue()
|
||
book, tape = OrderBook(), Tape()
|
||
engine = HintEngine(settings)
|
||
feed = Feed(port, doc["connectionId"], doc["ticker"], events)
|
||
feed.start()
|
||
end = time.time() + seconds
|
||
next_print = time.time() + 5
|
||
while time.time() < end:
|
||
try:
|
||
kind, data = events.get(timeout=0.2)
|
||
if kind == "book_snapshot":
|
||
book.apply_snapshot(data)
|
||
elif kind == "book_update":
|
||
book.apply_updates(data)
|
||
elif kind == "trades":
|
||
for raw in data:
|
||
tape.add(Trade(parse_time(raw.get("time")), float(raw["price"]), float(raw["size"]), raw["side"]))
|
||
except queue.Empty:
|
||
pass
|
||
hint = engine(book, tape, doc["tick"], time.time()) if book.asks else None
|
||
if hint and time.time() >= next_print:
|
||
next_print = time.time() + 5
|
||
plan = (f" вход {hint.entry:.10g} стоп {hint.stop:.10g} цель {hint.target:.10g} 1:{hint.rr:.1f}"
|
||
if hint.side != "WAIT" else "")
|
||
print(f"{doc['ticker']} {hint.side} ({hint.confidence}, score {hint.score:+.2f}){plan}")
|
||
for reason in hint.reasons:
|
||
print(" ", reason)
|
||
feed.stop()
|
||
|
||
|
||
if __name__ == "__main__":
|
||
import sys
|
||
if len(sys.argv) > 2 and sys.argv[1] == "--console":
|
||
run_console(float(sys.argv[2]))
|
||
elif len(sys.argv) > 1 and sys.argv[1] == "--legacy":
|
||
run_legacy_window()
|
||
else:
|
||
import lead_window
|
||
lead_window.run()
|