1
This commit is contained in:
1 parent
3ae4e18211
commit
730adb3ff2
9 files changed
+206
-33
No files matched your search
@@ -21,6 +21,7 @@ from persistence import atomic_write_json
|
||||
import queue
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
import live
|
||||
@@ -36,6 +37,10 @@ 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}
|
||||
# Keep epoch seconds for calculations and an ISO-8601 UTC rendering for humans.
|
||||
for key, value in tuple(event.items()):
|
||||
if key.endswith("_time") and isinstance(value, (int, float)) and not isinstance(value, bool):
|
||||
event[f"{key}_utc"] = datetime.fromtimestamp(value, timezone.utc).isoformat(timespec="milliseconds")
|
||||
with _journal_lock:
|
||||
RECENT.append(event)
|
||||
del RECENT[:-300]
|
||||
@@ -312,6 +317,7 @@ class FuturesMirror:
|
||||
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(),
|
||||
"decision_open_time": pos.opened, "decision_open_price": pos.entry / units,
|
||||
# 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,
|
||||
@@ -323,6 +329,9 @@ class FuturesMirror:
|
||||
return
|
||||
self.jobs.put(("open", None))
|
||||
elif event == "close" and self.position and self.position.get("uid") == pos.uid:
|
||||
self.position["decision_close_time"] = getattr(pos, "close_decision_time", time.time())
|
||||
self.position["decision_close_price"] = getattr(pos, "close_decision_price", 0.0)
|
||||
self.position["decision_close_reason"] = getattr(pos, "close_reason", "закрыта в симуляторе")
|
||||
self.jobs.put(("close", "закрыта в симуляторе"))
|
||||
|
||||
def request_close(self, reason: str = "удаление подключения") -> None:
|
||||
@@ -473,9 +482,11 @@ class FuturesMirror:
|
||||
self._failed_open(str(exc))
|
||||
return
|
||||
# Persist the accepted fill before any additional network call (TP, fee sync, etc.).
|
||||
fill_time = time.time()
|
||||
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)
|
||||
exact=fill.exact, order_in=fill.order_id, actual_open_time=fill_time,
|
||||
actual_open_price=fill.price)
|
||||
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
|
||||
@@ -511,7 +522,9 @@ class FuturesMirror:
|
||||
+ (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)
|
||||
slip=(fill.price / pos["paper_entry"] - 1) * 100 * sign,
|
||||
decision_open_time=pos.get("decision_open_time"), decision_open_price=pos.get("decision_open_price"),
|
||||
actual_open_time=pos.get("actual_open_time"), actual_open_price=pos.get("actual_open_price"))
|
||||
|
||||
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
|
||||
@@ -588,7 +601,7 @@ class FuturesMirror:
|
||||
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})
|
||||
"order": fill.order_id, "time": time.time()})
|
||||
except live.LiveError as exc:
|
||||
if not getattr(exc, "sent", False):
|
||||
raise
|
||||
@@ -618,7 +631,7 @@ class FuturesMirror:
|
||||
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})
|
||||
"order": f.order_id, "time": time.time()})
|
||||
done_ours += f.coins
|
||||
if theirs and "биржей" not in reason:
|
||||
reason = f"закрыта биржей по TP/SL ({reason})"
|
||||
@@ -635,8 +648,9 @@ class FuturesMirror:
|
||||
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)
|
||||
closed_at = time.time()
|
||||
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,
|
||||
"opened": pos["opened"], "closed": closed_at, "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:
|
||||
@@ -646,7 +660,12 @@ class FuturesMirror:
|
||||
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"])
|
||||
f"(комиссии {fees:.4f} $, {reason})", side=pos["side"], coins=coins, price=exit_price, net=trade["net"],
|
||||
decision_open_time=pos.get("decision_open_time"), decision_open_price=pos.get("decision_open_price"),
|
||||
actual_open_time=pos.get("actual_open_time"), actual_open_price=pos.get("actual_open_price"),
|
||||
decision_close_time=pos.get("decision_close_time"), decision_close_price=pos.get("decision_close_price"),
|
||||
actual_close_time=closed_at, actual_close_price=exit_price,
|
||||
actual_close_fill_time=max((f.get("time", closed_at) for f in fills), default=closed_at))
|
||||
|
||||
# --- view ------------------------------------------------------------------------------------------------------
|
||||
def view(self) -> dict:
|
||||
|
||||
Reference in new issue
Block a user