"""Real trading for the «Симулятор» tab: a paper position the simulator opens on a coin's futures exchange is repeated with a real market order of the same size and closed with a real reduce-only order when the paper one closes. Strictly one real trade per coin at a time: while real mode is on, the simulator opens nothing new on the coin until the previous real trade is closed AND the exchange shows no position left on the symbol (`gate`). A paper position whose real order did not go through is closed at once, so paper and real trades stay one to one. Results (prices, fees) are the exchange's own fills; `exact` is False where the exchange did not report a figure. - the tab-wide switch is in web_sim_data/real_simulator.json; it gates new trades only — an open real trade is always closed with its paper twin; - real positions are saved (web_sim_data/real_positions_.json); a saved real position is conservatively closed right after a restart («осиротевшая»), independently of the restored paper account; - every order and every error goes to web_sim_data/real_orders.jsonl (journal on the page). """ from __future__ import annotations import json import os from persistence import atomic_write_json import queue import threading import time from pathlib import Path import live ROOT = Path(__file__).resolve().parent DATA_DIR = Path(os.environ.get("CRYPTO_SCAM_DATA_DIR", ROOT / "web_sim_data")).resolve() SETTINGS_FILE = DATA_DIR / "real_simulator.json" JOURNAL = DATA_DIR / "real_orders.jsonl" _journal_lock = threading.Lock() RECENT: list[dict] = [] # last events of both tabs, newest last def journal(tab: str, exchange: str, coin: str, action: str, ok: bool, text: str, **extra) -> dict: event = {"time": time.time(), "tab": tab, "exchange": exchange, "coin": coin, "action": action, "ok": ok, "text": text, **extra} with _journal_lock: RECENT.append(event) del RECENT[:-300] try: DATA_DIR.mkdir(exist_ok=True) with JOURNAL.open("a", encoding="utf-8") as f: f.write(json.dumps(event, ensure_ascii=False) + "\n") except OSError: pass return event def load_recent(limit: int = 300) -> None: try: lines = JOURNAL.read_text(encoding="utf-8").splitlines()[-limit:] except OSError: return with _journal_lock: RECENT[:] = [json.loads(x) for x in lines if x.strip()] DEFAULT_SL_PCT = 1.5 # stop-loss of a real position on the exchange, % from the entry DEFAULT_MAX_PING_MS = 400.0 # no new entry while the round trip to the exchange is above this (0 = no check) FEES: dict[str, float] = {} # exchange → real taker rate %, measured from the exchange's own fills FEE_LISTENERS: list = [] # fn(exchange, pct): called when a new real rate is measured def load_settings() -> dict: """{"coins": {coin_key: {"on": bool, "since": t}}, "exchange_tpsl": bool} — real mode is per coin; `since` = from when the coin's real statistics are taken from the exchange (first switch-on or a reset).""" s = {"coins": {}, "exchange_tpsl": True, "auto_transfer": True, "sl_pct": DEFAULT_SL_PCT, "max_ping_ms": DEFAULT_MAX_PING_MS, "fees": {}} try: s.update(json.loads(SETTINGS_FILE.read_text(encoding="utf-8"))) except (OSError, ValueError): pass s.pop("enabled", None) # the old tab-wide switch: real mode is per coin now return s def save_settings(values: dict) -> str: s = load_settings() for key in ("exchange_tpsl", "auto_transfer"): if key in values: s[key] = values[key] in (True, "true", 1, "1") if "sl_pct" in values: try: v = float(values["sl_pct"]) except (TypeError, ValueError): return "неверный стоп-лосс" if not 0 <= v <= 50: return "стоп-лосс должен быть от 0 до 50 %" s["sl_pct"] = v if "max_ping_ms" in values: try: v = float(values["max_ping_ms"]) except (TypeError, ValueError): return "неверный порог пинга" if not 0 <= v <= 10000: return "порог пинга должен быть от 0 до 10000 мс" s["max_ping_ms"] = v for ex, pct in (values.get("fee") or {}).items(): s.setdefault("fees", {})[ex] = round(float(pct), 5) coin = values.get("coin") if coin: c = s["coins"].setdefault(str(coin), {"on": False, "since": 0.0}) if "enabled" in values: c["on"] = values["enabled"] in (True, "true", 1, "1") if c["on"] and not c.get("since"): c["since"] = time.time() if values.get("reset_stats"): c["since"] = time.time() DATA_DIR.mkdir(exist_ok=True) atomic_write_json(SETTINGS_FILE, s) return "" def symbol_units(symbol: str) -> float: """Coins in one unit of a futures symbol: 1000PEPEUSDT → 1000, SI_USDT → 1.""" base = symbol.upper().replace("_USDT", "").replace("-USDT", "").removesuffix("USDT") return live._units(base) def trades_from_fills(fills: list[dict]) -> list[dict]: """Round trips (flat → position → flat) rebuilt from the exchange's own fills, in time order. Prices, fees and — where the exchange reports it (MEXC `profit`, Binance `realizedPnl`) — the realized result of each closing fill are the exchange's figures; otherwise the result is (exit − entry) × coins of the closed part.""" trades, pos, cost, fees_open, opened = [], 0.0, 0.0, 0.0, 0.0 gross = fees = closed_coins = closed_value = in_coins = in_value = 0.0 # fills of the same second: openings before closings (the exchange's time has 1 s resolution on MEXC) for f in sorted(fills, key=lambda x: (x["time"], 1 if x.get("close") else 0, str(x.get("order", "")))): signed = f["coins"] if f["side"] == "buy" else -f["coins"] if abs(pos) < 1e-12 or (pos > 0) == (signed > 0): if abs(pos) < 1e-12: opened, cost, fees_open, gross, fees, closed_coins, closed_value = f["time"], 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 in_coins = in_value = 0.0 pos += signed cost += f["coins"] * f["price"] fees_open += f["fee"] in_coins += f["coins"] in_value += f["coins"] * f["price"] continue # closing (part of) the position closing = min(abs(signed), abs(pos)) entry = cost / abs(pos) side = 1 if pos > 0 else -1 share = closing / f["coins"] gross += f["pnl"] * share if f.get("pnl") is not None else side * (f["price"] - entry) * closing fees += fees_open * closing / abs(pos) + f["fee"] * share fees_open -= fees_open * closing / abs(pos) cost -= entry * closing pos -= side * closing closed_coins += closing closed_value += f["price"] * closing if abs(pos) < 1e-9: exit_price = closed_value / closed_coins entry_avg = in_value / in_coins if in_coins else entry trades.append({"side": "LONG" if side > 0 else "SHORT", "coins": closed_coins, "entry": entry_avg, "exit": exit_price, "opened": opened, "closed": f["time"], "gross": gross, "fees": fees, "net": gross - fees, "pct": side * (exit_price / entry_avg - 1) * 100 if entry_avg else 0.0, "reason": "по данным биржи", "exact": True}) pos, cost, fees_open = 0.0, 0.0, 0.0 rest = abs(signed) - closing # a fill that flips the position opens the new one if rest > 1e-12: pos, cost, fees_open, opened = (rest if signed > 0 else -rest), rest * f["price"], f["fee"] * (1 - share), f["time"] gross = fees = closed_coins = closed_value = 0.0 in_coins, in_value = rest, rest * f["price"] return trades def trade_stats(trades: list[dict]) -> dict: """Totals of real trades, all from the exchange's fills.""" n = len(trades) wins = sum(t["net"] > 0 for t in trades) notional = sum(t["entry"] * t["coins"] for t in trades) net = sum(t["net"] for t in trades) return {"trades": n, "wins": wins, "winrate": wins / n * 100 if n else None, "net": net, "fees": sum(t["fees"] for t in trades), "gross": sum(t["gross"] for t in trades), "net_pct": net / notional * 100 if notional else None, "exact": all(t.get("exact", True) for t in trades)} class FuturesMirror: RETRY_S = 0.7 # a refused close is tried again after this, then ×1.5 each time (up to RETRY_MAX_S) RETRY_MAX_S = 5.0 VERIFY_TOLERANCE = 1e-9 def __init__(self, coin_key: str, coin: str, exchange: str, symbol: str, data_dir: Path = DATA_DIR, client_for=live.client, settings=load_settings) -> None: self.coin_key, self.coin, self.exchange, self.symbol = coin_key, coin, exchange, symbol self.file = data_dir / f"real_positions_{coin_key}.json" self.client_for, self.settings = client_for, settings self.lock = threading.Lock() self.position: dict | None = None # the one real position (opening / open / closing) self.trades: list[dict] = [] self.state = "" # "" idle · "opening" · "open" · "closing" · "check" (verify zero) self.storage_error = "" self.problem = "" # last error that keeps the coin blocked self.on_failed_open = None # callback(uid): close the paper twin of a real order that failed self.exchange_trades: list[dict] | None = None # rebuilt from the exchange's fills (None: not synced yet) self.synced, self.sync_error, self.last_sync = 0.0, "", 0.0 self.last_error, self.paused_until = "", 0.0 # the exchange's last refusal of an entry, and the pause self.ping = lambda: None # → current round trip to the exchange's futures API, ms (or None) self.jobs: queue.Queue = queue.Queue() for ex, pct in (self.settings().get("fees") or {}).items(): FEES.setdefault(ex, pct) self._load() threading.Thread(target=self._worker, daemon=True).start() # --- persistence ------------------------------------------------------------------------------------------- def _load(self) -> None: try: d = json.loads(self.file.read_text(encoding="utf-8")) except FileNotFoundError: return except (OSError, ValueError) as exc: self.state, self.problem = "blocked", f"не прочитано состояние реальных ордеров: {exc}" return self.trades = d.get("trades", [])[-500:] pos = d.get("position") if pos: pos["uid"] = None self.position = pos if pos.get("phase") in ("prepared", "submitted"): self.state = "recover" self.jobs.put(("recover", None)) else: self.state = "closing" self.jobs.put(("close", "осиротевшая после перезапуска")) def _save(self) -> None: try: atomic_write_json(self.file, {"version": 2, "state": self.state, "position": self.position, "trades": self.trades[-500:]}) except (OSError, ValueError) as exc: self.storage_error = f"не сохранено состояние ордеров: {exc}" raise self.storage_error = "" def _recover_open(self) -> None: """Never replay an entry after a crash. Resolve known orders; contain unknown submissions.""" pos = self.position if not pos: return if pos.get("phase") == "prepared": self._failed_open("перезапуск до отправки ордера") return c = self.client_for(self.exchange) oid = pos.get("order_in") if pos.get("phase") != "filled": if not oid: # A lost submit response cannot be declared absent from one flat position snapshot. held = c.fut_position(self.symbol) if abs(held) > self.VERIFY_TOLERANCE: expected = 1 if pos["side"] == "LONG" else -1 if held * expected <= 0: self.problem = "позиция другого направления — требуется ручная сверка" return c.fut_order(self.symbol, "sell" if held > 0 else "buy", abs(held), reduce_only=True) self.problem = "результат входа без ID неизвестен; новые входы заблокированы, сверяю и закрываю остаток" return status = c.fut_order_status(self.symbol, oid) if not status["final"]: c.fut_cancel(self.symbol, oid) status = c.fut_order_status(self.symbol, oid) if not status["final"]: self.problem = "ожидаю окончательный статус входа" return pos.update(phase="filled", coins=status["coins"], entry=status["price"] or pos["paper_entry"], fee_in=status["fee"], exact=False) with self.lock: self.state = "closing" self._save() self._close("восстановление незавершённого входа") # --- the simulator's side ---------------------------------------------------------------------------------- def coin_settings(self) -> dict: return (self.settings().get("coins") or {}).get(self.coin_key) or {} def enabled(self) -> bool: return bool(self.coin_settings().get("on")) def gate(self) -> str: """Why the simulator may not open a new position on this coin now ("" = it may).""" if not self.enabled(): return "" with self.lock: if self.storage_error: return self.storage_error left = self.paused_until - time.time() if self.state == "" and left > 0: # the exchange refused the last entry: no new trade (paper or real) until the pause ends return f"пауза после отказа биржи ещё {left:.0f} с: {self.last_error}" if self.state == "": # a slow connection now = the order arrives late and fills far from the signal price: skip limit = float(self.settings().get("max_ping_ms", DEFAULT_MAX_PING_MS) or 0) ping = self.ping() if limit > 0 and ping is not None and ping > limit: return f"пинг до биржи {ping:.0f} мс выше порога {limit:.0f} мс — вход пропущен" return "" what = {"opening": "открывается реальный ордер", "open": "открыта реальная позиция", "closing": "реальная позиция закрывается", "check": "жду подтверждения биржи, что позиция закрыта"} return f"{what.get(self.state, self.state)} — новая сделка только после закрытия" + ( f" ({self.problem})" if self.problem else "") def hook(self, event: str, pos) -> None: """Paper events, called under the engine's lock: only queue work here.""" with self.lock: if event == "open": if not self.enabled() or self.state or self.storage_error or time.time() < self.paused_until: return # real mode off, or a real trade still runs (gate was bypassed) self.state = "opening" units = symbol_units(self.symbol) self.position = {"uid": pos.uid, "side": pos.side, "coins": pos.qty * units, "paper_entry": pos.entry / units, "opened": time.time(), # the paper take-profit as a distance from the entry: the real TP is placed at # the same distance from the REAL fill price, not at the paper price "tp_pct": (pos.target / pos.entry - 1) * 100 if getattr(pos, "target", None) else None, "ping": self.ping(), "phase": "prepared"} try: self._save() except (OSError, ValueError): self.state, self.problem = "recover", self.storage_error return self.jobs.put(("open", None)) elif event == "close" and self.position and self.position.get("uid") == pos.uid: self.jobs.put(("close", "закрыта в симуляторе")) def request_close(self, reason: str = "удаление подключения") -> None: """Also close a recovered real position whose paper twin no longer exists.""" with self.lock: if self.position and self.state not in ("recover", "blocked"): self.jobs.put(("close", reason)) def ready_to_remove(self) -> bool: with self.lock: return self.position is None and self.state == "" and not self.storage_error and self.jobs.empty() # --- worker ------------------------------------------------------------------------------------------------ WATCH_S = 1.0 # while a real position is open: how often to ask the exchange whether TP/SL closed it def _worker(self) -> None: while True: try: kind, arg = self.jobs.get(timeout=self.WATCH_S) except queue.Empty: kind, arg = "watch", None try: if kind == "open": self._open() elif kind == "close": self._close(arg) elif kind == "recover": self._recover_open() elif kind == "watch": self._watch() except Exception as exc: # never let the worker die with self.lock: self.problem = f"сбой: {exc}" if kind == "open" and self.position: self.state = "recover" journal("simulator", self.exchange, self.coin, kind, False, f"сбой: {exc}") if kind == "close": self._retry_close(arg) SYNC_S = 10.0 # how often the coin's trades are rebuilt from the exchange's fill history def reset_stats(self) -> None: """Real statistics of the coin start again from now (the exchange's history before is left out).""" if self.settings is load_settings: # (tests pass their own settings and must not write the file) save_settings({"coin": self.coin_key, "reset_stats": True}) with self.lock: self.trades, self.exchange_trades, self.last_sync = [], None, 0.0 self._save() def sync(self) -> None: """Trades and statistics of the coin from the exchange's own fills since real mode was switched on.""" since = self.coin_settings().get("since") if not since: return self.last_sync = time.time() try: fills = self.client_for(self.exchange).fut_fills(self.symbol, since) except (live.LiveError, AttributeError) as exc: with self.lock: self.sync_error = str(exc) return trades = trades_from_fills(fills) with self.lock: self.exchange_trades, self.synced, self.sync_error = trades, time.time(), "" # the fee rate the exchange really charges, from its own fills (orders no longer ask for it separately) rates = sorted(f["fee"] / (f["coins"] * f["price"]) * 100 for f in fills[-50:] if f.get("fee") and f.get("coins") and f.get("price")) if rates: rate = rates[len(rates) // 2] if abs(rate - FEES.get(self.exchange, 0.0)) > 0.0005: self._record_fee(rate) def _watch(self) -> None: """An open real position may be closed by the exchange itself (its TP / SL): then record it now. Every SYNC_S seconds (and right after a close) the trades are synced with the exchange's history.""" if self.storage_error and self.position is None: with self.lock: self._save() if self.state == "recover": self._recover_open() return if (self.state in ("", "open") and time.time() - self.last_sync >= self.SYNC_S and (self.enabled() or self.exchange_trades is None)): self.sync() with self.lock: if self.state != "open" or not (self.position or {}).get("tpsl_on"): return try: held = self.client_for(self.exchange).fut_position(self.symbol) except live.LiveError: return if abs(held) <= self.VERIFY_TOLERANCE: self._close("закрыта биржей по TP/SL") def _retry_close(self, reason: str) -> None: # fast first (a «510 too frequent» passes in under a second), slower if the exchange keeps refusing with self.lock: fails = (self.position or {}).get("close_fails", 0) if self.position is not None: self.position["close_fails"] = fails + 1 delay = min(self.RETRY_MAX_S, self.RETRY_S * 1.5 ** fails) timer = threading.Timer(delay, lambda: self.jobs.put(("close", reason))) timer.daemon = True timer.start() TP_MARGIN_PCT = 0.05 # the TP must be at least two fees + this beyond the real entry to leave a profit def _open(self) -> None: pos = self.position if pos is None or self.state != "opening": return with self.lock: pos["phase"] = "submitted" try: self._save() # must complete before an exchange request is allowed except (OSError, ValueError): pos["phase"] = "prepared" # no request was sent raise side = "buy" if pos["side"] == "LONG" else "sell" sign = 1 if side == "buy" else -1 c = None s = self.settings() use_tpsl = s.get("exchange_tpsl", True) sl_pct = float(s.get("sl_pct", DEFAULT_SL_PCT) or 0) # stop-loss goes with the entry (Bybit / MEXC attach it to the order; Binance sets it right after the fill) sl = pos["paper_entry"] * (1 - sign * sl_pct / 100) if use_tpsl and sl_pct > 0 else None try: c = self.client_for(self.exchange) if sl: fill = c.fut_order(self.symbol, side, pos["coins"], reduce_only=False, sl=sl) else: fill = c.fut_order(self.symbol, side, pos["coins"], reduce_only=False) except live.LiveError as exc: if getattr(exc, "sent", False): with self.lock: pos["order_in"] = exc.order_id self.state, self.problem = "recover", str(exc) self._save() try: held = c.fut_position(self.symbol) except live.LiveError: return if held * sign <= self.VERIFY_TOLERANCE: return fill = live.Fill(abs(held), pos["paper_entry"], 0.0, exc.order_id, exact=False) else: self._top_up_futures(c, str(exc), pos["coins"] * pos["paper_entry"]) self._failed_open(str(exc)) return # Persist the accepted fill before any additional network call (TP, fee sync, etc.). with self.lock: pos.update(phase="filled", coins=fill.coins, entry=fill.price, fee_in=fill.fee_usd, exact=fill.exact, order_in=fill.order_id) self._save() # the exchange's real fee rate (it decides how far the TP has to be, and the paper model uses it too) fee_pct = fill.fee_usd / (fill.coins * fill.price) * 100 if fill.exact and fill.coins and fill.price else None if fee_pct: self._record_fee(fee_pct) notes = [] sl_set = bool(sl) and getattr(fill, "tpsl", "") == "на бирже" if sl: notes.append(f"SL {sl:.10g} (−{sl_pct:g}%) на бирже" if sl_set else f"SL НЕ выставлен: {fill.tpsl or 'нет ответа'}") tp_id = "" if use_tpsl and pos.get("tp_pct") is not None: # TP: a reduce-only LIMIT order at the paper distance from the REAL entry (never closer than two fees # plus a margin) — it fills at the TP price or better, not through the spread like a triggered market order need = 2 * (fee_pct or FEES.get(self.exchange) or 0.1) + self.TP_MARGIN_PCT dist = max(abs(pos["tp_pct"]), need) tp = fill.price * (1 + sign * dist / 100) try: tp_id = c.fut_take_profit(self.symbol, "sell" if side == "buy" else "buy", fill.coins, tp) notes.append(f"TP лимит {tp:.10g} ({'+' if sign > 0 else '−'}{dist:.3f}% от реального входа" + (f", бумажный {abs(pos['tp_pct']):.3f}% меньше двух комиссий — отодвинут" if dist > abs(pos['tp_pct']) else "") + ")") except (live.LiveError, AttributeError) as exc: notes.append(f"TP НЕ выставлен: {exc}") with self.lock: pos.update(coins=fill.coins, entry=fill.price, fee_in=fill.fee_usd, exact=fill.exact, order_in=fill.order_id, tp_order=tp_id, tpsl_on=sl_set or bool(tp_id)) closing_requested = self.state == "closing" self.state, self.problem = ("closing" if closing_requested else "open"), "" self._save() journal("simulator", self.exchange, self.coin, "open", True, f"{'лонг' if side == 'buy' else 'шорт'} {fill.coins:g} по {fill.price:.10g} (сигнал " f"{pos['paper_entry']:.10g}, {(fill.price / pos['paper_entry'] - 1) * 100 * sign:+.3f}% проскальзывание" + (f", пинг {pos['ping']:.0f} мс" if pos.get("ping") is not None else "") + "), " f"комиссия {fill.fee_usd:.4f} $" + (f"; {'; '.join(notes)}" if notes else ""), side=pos["side"], coins=fill.coins, price=fill.price, order=fill.order_id, ping=pos.get("ping"), slip=(fill.price / pos["paper_entry"] - 1) * 100 * sign) def _top_up_futures(self, c, error: str, notional: float) -> None: """The exchange refused for lack of money: move USDT from the spot account so the NEXT signal can trade (this one is gone: no extra requests before an entry, they would delay every order).""" if c is None or not self.settings().get("auto_transfer", True): return if not any(k in error.lower() for k in ("2005", "insufficient", "not enough", "недостаточно")): return try: moved = live.ensure_usdt(c, 0.0, notional * 1.03) if moved: journal("simulator", self.exchange, self.coin, "transfer", True, moved + " — для следующей сделки") except (live.LiveError, AttributeError) as exc: journal("simulator", self.exchange, self.coin, "transfer", False, f"перевод не удался: {exc}") def _record_fee(self, pct: float) -> None: """Remember the exchange's real taker rate; listeners (the paper model) use it from now on.""" FEES[self.exchange] = pct if self.settings is load_settings: # (tests pass their own settings and must not write the file) save_settings({"fee": {self.exchange: pct}}) for fn in FEE_LISTENERS: fn(self.exchange, pct) def _blocked(self, problem: str, text: str, pos: dict) -> None: """The close is not confirmed yet: keep the coin blocked; journal only when the reason changes.""" with self.lock: changed = problem != self.problem self.state, self.problem = "closing", problem self._save() if changed: journal("simulator", self.exchange, self.coin, "close", False, text, side=pos["side"]) PAUSE_S = 30.0 # after the exchange refused an entry: no new trade on the coin for this long BLOCKED_PAUSE_S = 900.0 # …and this long when the account itself is restricted (MEXC 6002) or rate-limited def _failed_open(self, why: str) -> None: account = any(k in why for k in ("6002", "restricted", "510", "too frequent", "10006", "Too many")) pause = self.BLOCKED_PAUSE_S if account else self.PAUSE_S with self.lock: uid = self.position["uid"] if self.position else None side = self.position["side"] if self.position else "" self.position, self.state, self.problem = None, "", "" self.last_error, self.paused_until = why, time.time() + pause self._save() hint = (" — биржа ограничила аккаунт или частоту запросов: проверьте почту и уведомления биржи" if account else "") journal("simulator", self.exchange, self.coin, "open", False, f"{why}{hint}; бумажная позиция тоже закрыта, новые входы по монете на паузе {pause / 60:.0f} мин" if pause >= 60 else f"{why}; бумажная позиция тоже закрыта, пауза {pause:.0f} с", side=side) if uid is not None and self.on_failed_open: self.on_failed_open(uid) def _close(self, reason: str) -> None: if self.position and self.position.get("phase") in ("prepared", "submitted"): self.state = "recover" self._recover_open() return with self.lock: pos = self.position if pos is None or self.state == "": return self.state = "closing" c = self.client_for(self.exchange) side = "sell" if pos["side"] == "LONG" else "buy" fills = pos.setdefault("exit_fills", []) try: if pos.get("tp_order") and not pos.get("tp_cancelled"): try: # the TP limit must not fill on top of our close c.fut_cancel_all(self.symbol) pos["tp_cancelled"] = True except (live.LiveError, AttributeError): pass # reduce-only orders cannot overshoot anyway held = c.fut_position(self.symbol) # what is really open: TP/SL may have closed it already if abs(held) > self.VERIFY_TOLERANCE: try: fill = c.fut_order(self.symbol, side, abs(held), reduce_only=True) fills.append({"coins": fill.coins, "price": fill.price, "fee": fill.fee_usd, "exact": fill.exact, "order": fill.order_id}) except live.LiveError as exc: if not getattr(exc, "sent", False): raise # accepted, not confirmed: the position check below decides with self.lock: self.state = "check" self._save() held = c.fut_position(self.symbol) except live.LiveError as exc: self._blocked(str(exc), f"не закрыта: {exc} — повторяю через {self.RETRY_S:g} с и дальше", pos) self._retry_close(reason) return left = abs(held) if left > self.VERIFY_TOLERANCE: with self.lock: pos["left"] = left self._blocked(f"на бирже ещё {held:+g} {self.coin}", f"на бирже осталась позиция {held:+g} — докрываю", pos) self._retry_close(reason) return # confirmed: no position on the symbol any more done_ours = sum(f["coins"] for f in fills) if done_ours < pos["coins"] * 0.999: # (part of) it was closed by the exchange (TP / SL): its own closing fills give the result try: theirs = c.fut_closes(self.symbol, side, pos["opened"] - 2) ours = {f.get("order") for f in fills} for f in theirs: if f.order_id not in ours and done_ours < pos["coins"] * 0.999: fills.append({"coins": f.coins, "price": f.price, "fee": f.fee_usd, "exact": f.exact, "order": f.order_id}) done_ours += f.coins if theirs and "биржей" not in reason: reason = f"закрыта биржей по TP/SL ({reason})" except (live.LiveError, AttributeError): pass if pos.get("tpsl_on") and not pos.get("tp_cancelled"): try: # (already done before our own close: not twice) c.fut_cancel_all(self.symbol) # TP / SL orders left after the exchange's close except (live.LiveError, AttributeError): pass done = sum(f["coins"] for f in fills) exit_price = sum(f["coins"] * f["price"] for f in fills) / done if done else pos.get("entry", 0.0) sign = 1 if pos["side"] == "LONG" else -1 coins = min(done, pos["coins"]) if done else pos["coins"] gross = sign * (exit_price - pos.get("entry", exit_price)) * coins fees = pos.get("fee_in", 0.0) + sum(f["fee"] for f in fills) trade = {"side": pos["side"], "coins": coins, "entry": pos.get("entry", 0.0), "exit": exit_price, "opened": pos["opened"], "closed": time.time(), "gross": gross, "fees": fees, "net": gross - fees, "pct": sign * (exit_price / pos["entry"] - 1) * 100 if pos.get("entry") else 0.0, "reason": reason, "exact": pos.get("exact", True) and all(f["exact"] for f in fills) and bool(fills)} with self.lock: self.trades.append(trade) self.position, self.state, self.problem = None, "", "" self._save() self.last_sync = 0.0 # pull the exchange's own figures for this trade soon journal("simulator", self.exchange, self.coin, "close", True, f"закрыта по {exit_price:.10g}, биржа подтвердила: позиции нет; итог {trade['net']:+.4f} $ " f"(комиссии {fees:.4f} $, {reason})", side=pos["side"], coins=coins, price=exit_price, net=trade["net"]) # --- view ------------------------------------------------------------------------------------------------------ def view(self) -> dict: with self.lock: # the exchange's history when synced; until then the program's own record of its orders trades = self.exchange_trades if self.exchange_trades is not None else [ t for t in self.trades if t.get("closed", 0) >= (self.coin_settings().get("since") or 0)] stats = trade_stats(trades) pos = dict(self.position) if self.position and self.state else None return {"open": 1 if pos else 0, "state": self.state, "problem": self.storage_error or self.problem, "position": pos, **stats, "positions": [pos] if pos else [], "enabled": self.enabled(), "source": "биржа" if self.exchange_trades is not None else "программа", "synced": self.synced, "sync_error": self.sync_error, "since": self.coin_settings().get("since"), "last_error": self.last_error, "paused_s": max(0.0, self.paused_until - time.time()), "trade_list": list(reversed(trades[-200:]))}