linux
This commit is contained in:
1 parent
f6f1ae20c2
commit
efd4e1dcf4
43 files changed
+25641
No files matched your search
@@ -0,0 +1,692 @@
|
||||
"""Paper trading window: a leader exchange (KuCoin futures) predicts the follower (Bybit perpetual).
|
||||
|
||||
Both feeds are read directly (KuCoin futures and Bybit public WebSockets); MetaScalp is not needed for the data.
|
||||
When KuCoin's mid price moves more than Bybit's over a short window, a virtual market order is opened on Bybit in
|
||||
KuCoin's direction; take-profit, stop-loss and a holding-time limit close it. Nothing is ever sent to an exchange.
|
||||
|
||||
Run: py -3 scalp_hint.py (this window)
|
||||
py -3 scalp_hint.py --legacy (the previous window with all the old strategies)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import queue
|
||||
import statistics
|
||||
import time
|
||||
from collections import deque
|
||||
|
||||
import scalp_hint as sh
|
||||
import scalp_paper as sp
|
||||
|
||||
MODES = {"lead": "Ведущая биржа: биржа для ставок отстала → догонит",
|
||||
"vector": "Вектор: куда идёт ведущая, туда ставка",
|
||||
"basis": "Разрыв цен: ставка на схождение к ведущей"}
|
||||
COMMON_FIELDS = (("budget", "Бюджет, $"), ("stake", "Ставка, $"), ("leverage", "Плечо"),
|
||||
("min_target_pct", "Тейк-профит, %"), ("stop_loss_pct", "Стоп-лосс, %"),
|
||||
("max_hold_seconds", "Макс. удержание, с"), ("cooldown_ms", "Пауза после сделки, мс"),
|
||||
("max_positions", "Позиций одновременно"), ("entry_gap_seconds", "Между входами, с"),
|
||||
("min_confidence", "Мин. уверенность (0–1)"))
|
||||
INT_FIELDS = {"max_positions"}
|
||||
MODE_FIELDS = {"lead": (("lead_threshold_pct", "Отставание для входа, %"), ("lead_window_ms", "Окно сравнения, мс")),
|
||||
"vector": (("vector_window_seconds", "Вектор ведущей за, с"),
|
||||
("vector_min_move_pct", "Мин. движение ведущей, %")),
|
||||
"basis": (("basis_entry_z", "Вход: отклонение, σ"), ("basis_min_gap_pct", "Мин. разрыв, %"))}
|
||||
AUTO_FIELDS = (("auto_tp_share_pct", "Доля догоняния, %"), ("auto_tp_horizon_seconds", "Горизонт прогноза, с"))
|
||||
FIELDS = COMMON_FIELDS + MODE_FIELDS["lead"] + MODE_FIELDS["vector"] + MODE_FIELDS["basis"] + AUTO_FIELDS
|
||||
TEXT_FIELDS = (("lead_ticker", "KuCoin (ведущая), тикер"), ("lead_pool", "Пул DEX Solana (адрес)"),
|
||||
("follow_ticker", "Ставки: тикер фьючерса"))
|
||||
# Its own account and journal, so the old strategies' history stays untouched.
|
||||
STATE_FILE = sp.DATA_DIR / "lead_paper_state.json"
|
||||
TRADES_FILE = sp.DATA_DIR / "lead_paper_trades.csv"
|
||||
|
||||
|
||||
def inherit_settings(paper: sp.PaperTrader) -> None:
|
||||
"""First run: budget, stake and leverage as they were in the previous window."""
|
||||
try:
|
||||
old = json.loads(sp.STATE_FILE.read_text(encoding="utf-8")).get("settings", {})
|
||||
except (OSError, ValueError):
|
||||
return
|
||||
for key in ("budget", "stake", "leverage"):
|
||||
if key in old:
|
||||
setattr(paper.settings, key, float(old[key]))
|
||||
paper.ledger.balance = paper.settings.budget
|
||||
paper.ledger.save()
|
||||
|
||||
|
||||
LEAD_MARKETS = {"futures": "KuCoin фьючерсы", "spot": "KuCoin спот",
|
||||
"raydium": "DEX пул Solana (Raydium / PumpSwap / Meteora / Orca / PancakeSwap)"}
|
||||
FOLLOW_EXCHANGES = {"bybit": "Bybit фьючерс", "mexc": "MEXC фьючерс"}
|
||||
|
||||
|
||||
CONNECTIONS_FILE = sp.DATA_DIR / "lead_connections.json"
|
||||
CONNECTION_KEYS = ("lead_market", "lead_ticker", "lead_pool", "follow_exchange", "follow_ticker")
|
||||
# Connections already used; every new one is added so it can be picked again later (removed only by the user).
|
||||
DEFAULT_CONNECTIONS = [
|
||||
{"lead_market": "raydium", "lead_ticker": "SIUSDTM", "lead_pool": "8uwFMFCUDi61rgT1e6bUuDEfaUcN6roSoL7qHkp2NtHk",
|
||||
"follow_exchange": "mexc", "follow_ticker": "SI_USDT"},
|
||||
{"lead_market": "raydium", "lead_ticker": "CLAUDIAUSDTM", "lead_pool": "Fe7bpDYCs74GqiCUF14HwgUMToPKV1d9mDYVX5BTohFr",
|
||||
"follow_exchange": "mexc", "follow_ticker": "CLAUDIA_USDT"},
|
||||
{"lead_market": "futures", "lead_ticker": "MARSCOINUSDTM", "lead_pool": "",
|
||||
"follow_exchange": "bybit", "follow_ticker": "MARSCOINUSDT"},
|
||||
{"lead_market": "spot", "lead_ticker": "MARSCOIN-USDT", "lead_pool": "",
|
||||
"follow_exchange": "bybit", "follow_ticker": "MARSCOINUSDT"},
|
||||
]
|
||||
|
||||
|
||||
def connection_name(c: dict) -> str:
|
||||
coin = c["follow_ticker"].replace("_USDT", "").removesuffix("USDT")
|
||||
if c["lead_market"] == "raydium":
|
||||
lead = f"DEX пул {c['lead_pool'][:6]}…"
|
||||
else:
|
||||
lead = f"KuCoin {'спот' if c['lead_market'] == 'spot' else 'фьючерс'} {c['lead_ticker']}"
|
||||
follow = {"bybit": "Bybit", "mexc": "MEXC"}.get(c["follow_exchange"], c["follow_exchange"])
|
||||
return f"{coin}: {lead} → {follow} {c['follow_ticker']}"
|
||||
|
||||
|
||||
def same_connection(a: dict, b: dict) -> bool:
|
||||
keys = ["lead_market", "follow_exchange", "follow_ticker"]
|
||||
keys.append("lead_pool" if a["lead_market"] == "raydium" else "lead_ticker")
|
||||
return all(a.get(k) == b.get(k) for k in keys)
|
||||
|
||||
|
||||
REMOVED_FILE = sp.DATA_DIR / "lead_connections_removed.json" # deleted by the user (× on a web tile)
|
||||
|
||||
|
||||
def _read_list(path) -> list[dict]:
|
||||
try:
|
||||
saved = json.loads(path.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return []
|
||||
return [dict(c) for c in saved if isinstance(c, dict) and all(k in c for k in CONNECTION_KEYS)] \
|
||||
if isinstance(saved, list) else []
|
||||
|
||||
|
||||
def _write_list(path, items: list[dict]) -> None:
|
||||
tmp = path.with_suffix(".tmp")
|
||||
tmp.write_text(json.dumps(items, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
tmp.replace(path)
|
||||
|
||||
|
||||
def is_removed(conn: dict, removed_path=None) -> bool:
|
||||
return any(same_connection(conn, r) for r in _read_list(removed_path or REMOVED_FILE))
|
||||
|
||||
|
||||
def load_connections(path=None, removed_path=None) -> list[dict]:
|
||||
removed = _read_list(removed_path or REMOVED_FILE)
|
||||
out = [c for c in _read_list(path or CONNECTIONS_FILE) if c.get("follow_exchange") in FOLLOW_EXCHANGES
|
||||
and not any(same_connection(c, r) for r in removed)]
|
||||
for c in DEFAULT_CONNECTIONS:
|
||||
if not any(same_connection(c, s) for s in out) and not any(same_connection(c, r) for r in removed):
|
||||
out.append(dict(c))
|
||||
return out
|
||||
|
||||
|
||||
def remove_connection(conn: dict, path=None, removed_path=None) -> None:
|
||||
"""Delete a connection on the user's request: out of the list, and remembered as removed so neither the
|
||||
built-in defaults nor the autonomous search bring it back (adding it again by hand undoes this)."""
|
||||
path, removed_path = path or CONNECTIONS_FILE, removed_path or REMOVED_FILE
|
||||
_write_list(path, [c for c in _read_list(path) if not same_connection(c, conn)])
|
||||
removed = _read_list(removed_path)
|
||||
if not any(same_connection(conn, r) for r in removed):
|
||||
removed.append({k: conn[k] for k in CONNECTION_KEYS})
|
||||
_write_list(removed_path, removed)
|
||||
|
||||
|
||||
def unremove_connection(conn: dict, removed_path=None) -> None:
|
||||
removed_path = removed_path or REMOVED_FILE
|
||||
removed = _read_list(removed_path)
|
||||
keep = [r for r in removed if not same_connection(conn, r)]
|
||||
if len(keep) != len(removed):
|
||||
_write_list(removed_path, keep)
|
||||
|
||||
|
||||
def remember_connection(connections: list[dict], current: dict, path=None) -> list[dict]:
|
||||
"""Add the current connection to the list (if new) and save; nothing is ever removed. The file is re-read
|
||||
first, so connections added meanwhile by the autonomous search (meme_matcher/autoscan.py) are kept."""
|
||||
current = {k: current[k] for k in CONNECTION_KEYS}
|
||||
if path is None:
|
||||
unremove_connection(current) # picked again by hand: no longer deleted
|
||||
for c in load_connections(path):
|
||||
if not any(same_connection(c, x) for x in connections):
|
||||
connections.append(c)
|
||||
if not any(same_connection(current, c) for c in connections):
|
||||
connections.append(current)
|
||||
try:
|
||||
(path or CONNECTIONS_FILE).write_text(json.dumps(connections, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
except OSError:
|
||||
pass
|
||||
return connections
|
||||
|
||||
|
||||
def futures_ticker(ticker: str, exchange: str) -> str:
|
||||
"""SI_USDT on MEXC, SIUSDT on Bybit / Binance."""
|
||||
t = ticker.strip().upper().replace("-", "")
|
||||
base = t.removesuffix("_USDT").removesuffix("USDT")
|
||||
return f"{base}_USDT" if exchange == "mexc" else f"{base}USDT"
|
||||
|
||||
|
||||
def kucoin_ticker(ticker: str, market: str) -> str:
|
||||
"""MARSCOINUSDTM (futures) ↔ MARSCOIN-USDT (spot)."""
|
||||
t = ticker.strip().upper()
|
||||
base = t.removesuffix("-USDT") if t.endswith("-USDT") else t.removesuffix("USDTM").removesuffix("USDT")
|
||||
return f"{base}-USDT" if market == "spot" else f"{base}USDTM"
|
||||
|
||||
|
||||
def validate(values: dict[str, float]) -> str:
|
||||
if values["stake"] <= 0 or values["budget"] <= 0 or not 1 <= values["leverage"] <= 100:
|
||||
return "ставка и бюджет больше 0, плечо от 1 до 100"
|
||||
if values["min_target_pct"] <= 0 or values["stop_loss_pct"] <= 0:
|
||||
return "тейк-профит и стоп-лосс больше 0"
|
||||
if values["max_hold_seconds"] <= 0 or values["cooldown_ms"] < 0:
|
||||
return "удержание больше 0, пауза не меньше 0"
|
||||
if values["lead_threshold_pct"] <= 0 or values["lead_window_ms"] < 50:
|
||||
return "порог больше 0, окно не меньше 50 мс"
|
||||
if values["vector_window_seconds"] <= 0 or values["vector_min_move_pct"] < 0:
|
||||
return "окно вектора больше 0, мин. движение не меньше 0"
|
||||
if values["max_positions"] < 1 or values["max_positions"] != int(values["max_positions"]) \
|
||||
or values["entry_gap_seconds"] < 0:
|
||||
return "позиций одновременно — целое число от 1, интервал между входами не меньше 0"
|
||||
if not 0 <= values["min_confidence"] <= 1:
|
||||
return "мин. уверенность от 0 до 1 (0 — не проверять)"
|
||||
if not 0 < values["auto_tp_share_pct"] <= 300 or values["auto_tp_horizon_seconds"] <= 0:
|
||||
return "доля догоняния от 0 до 300%, горизонт прогноза больше 0"
|
||||
if values.get("basis_entry_z", 2) <= 0 or values.get("basis_min_gap_pct", 0.15) < 0 \
|
||||
or values.get("basis_window_seconds", 60) < 5 or values.get("basis_exit_z", 0.5) < 0 \
|
||||
or values.get("basis_exit_z", 0.5) >= values.get("basis_entry_z", 2):
|
||||
return "разрыв: вход больше 0σ и больше выхода, мин. разрыв ≥ 0, окно не меньше 5 с"
|
||||
return ""
|
||||
|
||||
|
||||
def run() -> None:
|
||||
import tkinter as tk
|
||||
from tkinter import ttk
|
||||
|
||||
settings = sp.PaperSettings(mode="lead")
|
||||
first_run = not STATE_FILE.exists()
|
||||
paper = sp.PaperTrader(settings, sh.HintSettings(), STATE_FILE, TRADES_FILE)
|
||||
if first_run:
|
||||
inherit_settings(paper)
|
||||
try:
|
||||
saved = json.loads(STATE_FILE.read_text(encoding="utf-8")).get("settings", {})
|
||||
except (OSError, ValueError):
|
||||
saved = {}
|
||||
if "cooldown_ms" not in saved:
|
||||
settings.cooldown_ms = settings.cooldown_seconds * 1000 # the pause used to be in seconds
|
||||
paper.set_mode(settings.mode if settings.mode in MODES else "lead")
|
||||
paper.policy = paper._make_policy()
|
||||
ps = paper.settings
|
||||
events: queue.Queue = queue.Queue()
|
||||
book = sh.OrderBook()
|
||||
state = {"leader_feed": None, "follower_feed": None, "recorder": None, "tick": 0.0, "leader": None,
|
||||
"leader_status": "KuCoin: подключаюсь…", "follower_status": "Bybit: подключаюсь…",
|
||||
"last_leader": 0.0, "last_follower": 0.0}
|
||||
lat_follow: deque[float] = deque(maxlen=200)
|
||||
lat_lead: deque[float] = deque(maxlen=200)
|
||||
|
||||
root = tk.Tk()
|
||||
root.title("Ведущая биржа → тестовые ставки на фьючерсе")
|
||||
root.geometry("1080x860")
|
||||
body = ttk.Frame(root, padding=10)
|
||||
body.pack(fill="both", expand=True)
|
||||
header = tk.StringVar()
|
||||
ttk.Label(body, textvariable=header, font=("Segoe UI", 10, "bold"), wraplength=940).pack(anchor="w")
|
||||
|
||||
panel = ttk.LabelFrame(body, text="Цены сейчас", padding=6)
|
||||
panel.pack(fill="x", pady=(6, 4))
|
||||
lead_var, follow_var, signal_var = tk.StringVar(), tk.StringVar(), tk.StringVar()
|
||||
for var in (lead_var, follow_var):
|
||||
ttk.Label(panel, textvariable=var, font=("Consolas", 11)).pack(anchor="w")
|
||||
signal_label = tk.Label(panel, textvariable=signal_var, font=("Segoe UI", 13, "bold"), anchor="w")
|
||||
signal_label.pack(fill="x", pady=(4, 0))
|
||||
bar = tk.Canvas(panel, height=16, width=600, highlightthickness=0, background="#e8e8e8")
|
||||
bar.pack(anchor="w", pady=(2, 0))
|
||||
|
||||
box = ttk.LabelFrame(body, text="Тестовые сделки на Bybit (виртуальный счёт, ордера на биржу не уходят)",
|
||||
padding=6)
|
||||
box.pack(fill="both", expand=True, pady=(4, 0))
|
||||
connections = load_connections()
|
||||
conn_row = ttk.Frame(box)
|
||||
conn_row.pack(fill="x", pady=(0, 4))
|
||||
ttk.Label(conn_row, text="Подключение:").pack(side="left")
|
||||
conn_var = tk.StringVar()
|
||||
conn_combo = ttk.Combobox(conn_row, textvariable=conn_var, state="readonly", width=90)
|
||||
conn_combo.pack(side="left", padx=6)
|
||||
ttk.Label(conn_row, text="(новые добавляются сами при «Применить», старые не удаляются)",
|
||||
foreground="#777").pack(side="left")
|
||||
|
||||
def show_connections() -> None:
|
||||
conn_combo.configure(values=[connection_name(c) for c in connections])
|
||||
current = {k: getattr(ps, k) for k in CONNECTION_KEYS}
|
||||
match = next((c for c in connections if same_connection(c, current)), None)
|
||||
conn_var.set(connection_name(match) if match else "")
|
||||
|
||||
def on_connection(_event=None) -> None:
|
||||
c = next((c for c in connections if connection_name(c) == conn_var.get()), None)
|
||||
if c is None:
|
||||
return
|
||||
market_var.set(LEAD_MARKETS[c["lead_market"]])
|
||||
follow_ex_var.set(FOLLOW_EXCHANGES[c["follow_exchange"]])
|
||||
for key in ("lead_ticker", "lead_pool", "follow_ticker"):
|
||||
vars_[key].set(c[key])
|
||||
apply()
|
||||
|
||||
conn_combo.bind("<<ComboboxSelected>>", on_connection)
|
||||
mode_row = ttk.Frame(box)
|
||||
mode_row.pack(fill="x", pady=(0, 4))
|
||||
ttk.Label(mode_row, text="Режим:").pack(side="left")
|
||||
mode_var = tk.StringVar(value=MODES[ps.mode])
|
||||
mode_combo = ttk.Combobox(mode_row, textvariable=mode_var, values=list(MODES.values()), state="readonly",
|
||||
width=58)
|
||||
mode_combo.pack(side="left", padx=6)
|
||||
ttk.Label(mode_row, text=" Ведущая:").pack(side="left")
|
||||
market_var = tk.StringVar(value=LEAD_MARKETS.get(ps.lead_market, LEAD_MARKETS["futures"]))
|
||||
market_combo = ttk.Combobox(mode_row, textvariable=market_var, values=list(LEAD_MARKETS.values()),
|
||||
state="readonly", width=16)
|
||||
market_combo.pack(side="left", padx=6)
|
||||
|
||||
ttk.Label(mode_row, text=" Ставки на:").pack(side="left")
|
||||
follow_ex_var = tk.StringVar(value=FOLLOW_EXCHANGES.get(ps.follow_exchange, FOLLOW_EXCHANGES["bybit"]))
|
||||
follow_combo = ttk.Combobox(mode_row, textvariable=follow_ex_var, values=list(FOLLOW_EXCHANGES.values()),
|
||||
state="readonly", width=16)
|
||||
follow_combo.pack(side="left", padx=6)
|
||||
|
||||
def on_market(_event=None) -> None:
|
||||
market = next(k for k, v in LEAD_MARKETS.items() if v == market_var.get())
|
||||
if market in ("futures", "spot"):
|
||||
vars_["lead_ticker"].set(kucoin_ticker(vars_["lead_ticker"].get(), market))
|
||||
apply()
|
||||
|
||||
market_combo.bind("<<ComboboxSelected>>", on_market)
|
||||
follow_combo.bind("<<ComboboxSelected>>", lambda _e: apply())
|
||||
form = ttk.Frame(box)
|
||||
form.pack(fill="x")
|
||||
vars_: dict[str, tk.StringVar] = {}
|
||||
mode_cells: dict[str, list] = {m: [] for m in MODES}
|
||||
|
||||
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, 4))
|
||||
ttk.Label(cell, text=label).pack(anchor="w")
|
||||
value = getattr(ps, key)
|
||||
var = tk.StringVar(value=value if isinstance(value, str) else f"{value:g}")
|
||||
ttk.Entry(cell, textvariable=var, width=16 if isinstance(value, str) else 12).pack(anchor="w")
|
||||
vars_[key] = var
|
||||
return cell
|
||||
|
||||
for i, (key, label) in enumerate(COMMON_FIELDS):
|
||||
add_field(key, label, i // 6, i % 6)
|
||||
mode_row_index = (len(COMMON_FIELDS) + 5) // 6
|
||||
for mode, items in MODE_FIELDS.items():
|
||||
for i, (key, label) in enumerate(items):
|
||||
mode_cells[mode].append(add_field(key, label, mode_row_index, i))
|
||||
for i, (key, label) in enumerate(TEXT_FIELDS):
|
||||
add_field(key, label, mode_row_index, 2 + i)
|
||||
auto_var = tk.BooleanVar(value=ps.auto_tp)
|
||||
learn_var = tk.BooleanVar(value=ps.auto_tp_learn)
|
||||
auto_cell = ttk.Frame(form)
|
||||
auto_cell.grid(row=mode_row_index + 1, column=0, columnspan=2, sticky="w", pady=(0, 4))
|
||||
ttk.Checkbutton(auto_cell, text="Авто тейк-профит по прогнозу:\nтейк = доля × отставание фьючерса от ведущей",
|
||||
variable=auto_var, command=lambda: apply()).pack(anchor="w")
|
||||
for i, (key, label) in enumerate(AUTO_FIELDS):
|
||||
add_field(key, label, mode_row_index + 1, 2 + i)
|
||||
learn_cell = ttk.Frame(form)
|
||||
learn_cell.grid(row=mode_row_index + 1, column=4, columnspan=2, sticky="w", pady=(0, 4))
|
||||
ttk.Checkbutton(learn_cell, text="Учить долю на истории сигналов\n(после 10 сигналов — вместо ручной)",
|
||||
variable=learn_var, command=lambda: apply()).pack(anchor="w")
|
||||
|
||||
def current_mode() -> str:
|
||||
return next(k for k, v in MODES.items() if v == mode_var.get())
|
||||
|
||||
def show_mode_fields() -> None:
|
||||
for mode, cells in mode_cells.items():
|
||||
for cell in cells:
|
||||
cell.grid() if mode == current_mode() else cell.grid_remove()
|
||||
|
||||
def on_mode(_event=None) -> None:
|
||||
show_mode_fields()
|
||||
apply()
|
||||
|
||||
mode_combo.bind("<<ComboboxSelected>>", on_mode)
|
||||
show_mode_fields()
|
||||
actions = ttk.Frame(box)
|
||||
actions.pack(fill="x", pady=(2, 2))
|
||||
enabled_var = tk.BooleanVar(value=ps.enabled)
|
||||
start_btn = tk.Button(actions, text="▶ Старт", width=9, command=lambda: set_trading(True))
|
||||
start_btn.pack(side="left")
|
||||
stop_btn = tk.Button(actions, text="■ Стоп", width=9, command=lambda: set_trading(False))
|
||||
stop_btn.pack(side="left", padx=(4, 0))
|
||||
trading_label = tk.Label(actions, text="", font=("Segoe UI", 9, "bold"))
|
||||
trading_label.pack(side="left", padx=8)
|
||||
|
||||
def show_trading() -> None:
|
||||
on = ps.enabled
|
||||
start_btn.configure(state="disabled" if on else "normal", bg="#d8f0dc" if on else "SystemButtonFace")
|
||||
stop_btn.configure(state="normal" if on else "disabled", bg="SystemButtonFace" if on else "#f6d6d6")
|
||||
trading_label.configure(text="Сделки открываются" if on else
|
||||
"Новые сделки остановлены · цены, сравнение и прогноз продолжают работать",
|
||||
fg="#1f8a4c" if on else "#c23b3b")
|
||||
|
||||
def set_trading(on: bool) -> None:
|
||||
"""Start/stop opening new paper positions only; the feeds, the comparison, the forecast learning and the
|
||||
exits of positions already open keep running."""
|
||||
enabled_var.set(on)
|
||||
ps.enabled = on
|
||||
paper.ledger.save()
|
||||
show_trading()
|
||||
message.set("Старт: новые сделки открываются" if on else
|
||||
"Стоп: новые сделки не открываются; открытые позиции закроются по тейку, стопу или времени")
|
||||
|
||||
ttk.Button(actions, text="Применить", command=lambda: apply()).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()).pack(side="left", padx=6)
|
||||
cut_row = ttk.Frame(box)
|
||||
cut_row.pack(fill="x", pady=(0, 2))
|
||||
cut_var = tk.BooleanVar(value=ps.cut_loss)
|
||||
ttk.Checkbutton(cut_row, text="Сразу закрывать, если ушло в минус на", variable=cut_var,
|
||||
command=lambda: apply()).pack(side="left")
|
||||
cut_ticks_var = tk.StringVar(value=str(ps.cut_loss_ticks))
|
||||
ttk.Entry(cut_row, textvariable=cut_ticks_var, width=4).pack(side="left", padx=4)
|
||||
ttk.Label(cut_row, text="шаг(а) цены (середина Bybit против цены при входе) — и сразу брать следующий сигнал "
|
||||
"без паузы").pack(side="left")
|
||||
tick_row = ttk.Frame(box)
|
||||
tick_row.pack(fill="x", pady=(0, 2))
|
||||
one_tick_var = tk.BooleanVar(value=ps.one_per_tick)
|
||||
ttk.Checkbutton(tick_row, text="Не больше одной позиции на один шаг цены Bybit (в каждую сторону); всего "
|
||||
"параллельно — до «Позиций одновременно»", variable=one_tick_var,
|
||||
command=lambda: apply()).pack(side="left")
|
||||
record_var = tk.BooleanVar(value=True)
|
||||
ttk.Checkbutton(actions, text=f"Записывать поток в {sp.RECORD_DIR.name}\\", variable=record_var).pack(
|
||||
side="left", padx=10)
|
||||
summary, status, position, message = (tk.StringVar() for _ in range(4))
|
||||
ttk.Label(box, textvariable=summary, font=("Segoe UI", 10, "bold")).pack(anchor="w")
|
||||
ttk.Label(box, textvariable=status, foreground="#1d4f91", wraplength=940).pack(anchor="w")
|
||||
ttk.Label(box, textvariable=position, wraplength=940).pack(anchor="w")
|
||||
ttk.Label(box, textvariable=message, foreground="#555", wraplength=940).pack(anchor="w")
|
||||
columns = ("time", "ticker", "side", "qty", "usd", "entry", "exit", "pct", "net", "fee", "reason", "hold", "why")
|
||||
heads = {"time": "Закрыта (UTC)", "ticker": "Тикер", "side": "Напр.", "qty": "Объём", "usd": "Объём в $",
|
||||
"entry": "Цена откр.", "exit": "Цена закр.", "pct": "Процент", "net": "Чистая, $", "fee": "Комиссия, $",
|
||||
"reason": "Причина", "hold": "Сек.", "why": "Почему вошли"}
|
||||
widths = {"time": 115, "ticker": 95, "side": 45, "qty": 65, "usd": 60, "entry": 75, "exit": 75, "pct": 60,
|
||||
"net": 70, "fee": 65, "reason": 60, "hold": 40, "why": 200}
|
||||
table = ttk.Frame(box)
|
||||
table.pack(fill="both", expand=True, pady=(4, 0))
|
||||
tree = ttk.Treeview(table, columns=columns, show="headings", height=10)
|
||||
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, 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 start_feeds() -> None:
|
||||
for key in ("leader_feed", "follower_feed"):
|
||||
if state[key]:
|
||||
state[key].stop()
|
||||
if state["recorder"]:
|
||||
state["recorder"].close()
|
||||
state["recorder"] = None
|
||||
book.clear()
|
||||
lat_follow.clear()
|
||||
lat_lead.clear()
|
||||
state["leader"] = None
|
||||
paper.policy = paper._make_policy()
|
||||
if ps.follow_exchange == "mexc":
|
||||
state["tick"], size = sh.mexc_contract(ps.follow_ticker)
|
||||
state["follower_feed"] = sh.MexcFeed(ps.follow_ticker, events, size)
|
||||
else:
|
||||
state["tick"] = sh.bybit_tick(ps.follow_ticker)
|
||||
state["follower_feed"] = sh.BybitFeed(ps.follow_ticker, events)
|
||||
if state["tick"] <= 0:
|
||||
message.set(f"{FOLLOW_EXCHANGES[ps.follow_exchange]}: нет тикера {ps.follow_ticker} — проверьте настройку")
|
||||
state["follower_status"] = f"{FOLLOW_EXCHANGES[ps.follow_exchange]}: подключаюсь…"
|
||||
if ps.lead_market == "raydium":
|
||||
if not ps.lead_pool:
|
||||
message.set("Укажите адрес пула Raydium (например, из Meme Matcher)")
|
||||
state["leader_feed"] = None
|
||||
else:
|
||||
state["leader_feed"] = sh.RaydiumFeed(ps.lead_pool, events)
|
||||
else:
|
||||
state["leader_feed"] = sh.KucoinFeed(ps.lead_ticker, events, spot=ps.lead_market == "spot")
|
||||
state["leader_status"] = f"{LEAD_MARKETS[ps.lead_market]}: подключаюсь…"
|
||||
state["follower_feed"].start()
|
||||
if state["leader_feed"]:
|
||||
state["leader_feed"].start()
|
||||
|
||||
def apply() -> None:
|
||||
try:
|
||||
values = {key: float(vars_[key].get().replace(",", ".")) for key, _ in FIELDS}
|
||||
except ValueError:
|
||||
message.set("Проверьте настройки: нужны числа")
|
||||
return
|
||||
problem = validate(values)
|
||||
try:
|
||||
cut_ticks = int(cut_ticks_var.get())
|
||||
if cut_ticks < 1:
|
||||
raise ValueError
|
||||
except ValueError:
|
||||
problem = problem or "минус для закрытия — целое число шагов, не меньше 1"
|
||||
if problem:
|
||||
message.set(f"Проверьте настройки: {problem}")
|
||||
return
|
||||
ps.cut_loss = bool(cut_var.get())
|
||||
ps.one_per_tick = bool(one_tick_var.get())
|
||||
ps.auto_tp = bool(auto_var.get())
|
||||
ps.auto_tp_learn = bool(learn_var.get())
|
||||
ps.cut_loss_ticks = cut_ticks
|
||||
# tickers upper case; a Solana pool address is case-sensitive
|
||||
tickers = {key: vars_[key].get().strip() if key == "lead_pool" else vars_[key].get().strip().upper()
|
||||
for key, _ in TEXT_FIELDS}
|
||||
budget_changed = values["budget"] != ps.budget
|
||||
for key, value in values.items():
|
||||
setattr(ps, key, int(value) if key in INT_FIELDS else value)
|
||||
ps.enabled = bool(enabled_var.get())
|
||||
market = next(k for k, v in LEAD_MARKETS.items() if v == market_var.get())
|
||||
follow = next(k for k, v in FOLLOW_EXCHANGES.items() if v == follow_ex_var.get())
|
||||
tickers["follow_ticker"] = futures_ticker(tickers["follow_ticker"], follow)
|
||||
vars_["follow_ticker"].set(tickers["follow_ticker"])
|
||||
if market in ("futures", "spot"):
|
||||
tickers["lead_ticker"] = kucoin_ticker(tickers["lead_ticker"], market)
|
||||
vars_["lead_ticker"].set(tickers["lead_ticker"])
|
||||
restart = (tickers["lead_ticker"] != ps.lead_ticker or tickers["follow_ticker"] != ps.follow_ticker
|
||||
or tickers["lead_pool"] != ps.lead_pool or market != ps.lead_market
|
||||
or follow != ps.follow_exchange)
|
||||
if restart:
|
||||
paper.close_now(book, time.time(), "смена тикера")
|
||||
ps.lead_ticker, ps.follow_ticker = tickers["lead_ticker"], tickers["follow_ticker"]
|
||||
ps.lead_pool, ps.lead_market, ps.follow_exchange = tickers["lead_pool"], market, follow
|
||||
if budget_changed and not paper.trades and paper.position is None:
|
||||
paper.ledger.balance = ps.budget
|
||||
mode = current_mode()
|
||||
if mode != ps.mode:
|
||||
paper.close_now(book, time.time(), "смена режима")
|
||||
paper.set_mode(mode) # the new policy gathers its own window of prices first
|
||||
paper.ledger.save()
|
||||
remember_connection(connections, {k: getattr(ps, k) for k in CONNECTION_KEYS})
|
||||
show_connections()
|
||||
if restart:
|
||||
start_feeds()
|
||||
message.set("Настройки применены" + (" · новый бюджет начнёт действовать после «Сбросить счёт»"
|
||||
if budget_changed and (paper.trades or paper.position) else ""))
|
||||
|
||||
def reset() -> None:
|
||||
apply()
|
||||
paper.reset()
|
||||
shown["count"] = -1
|
||||
message.set(f"Счёт сброшен: {ps.budget:g}$")
|
||||
|
||||
def pump() -> None:
|
||||
if record_var.get() and state["recorder"] is None and state["tick"] > 0:
|
||||
try:
|
||||
state["recorder"] = sp.Recorder(ps.follow_ticker, 111 if ps.follow_exchange == "bybit" else 0,
|
||||
state["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
|
||||
now = time.time()
|
||||
if kind == "book_snapshot":
|
||||
book.apply_snapshot(data)
|
||||
state["last_follower"] = now
|
||||
if recorder:
|
||||
recorder.write("S", {"asks": data.get("asks", []), "bids": data.get("bids", [])}, now)
|
||||
paper.on_book(now, book, state["tick"])
|
||||
elif kind == "book_update":
|
||||
book.apply_updates(data)
|
||||
state["last_follower"] = now
|
||||
if recorder:
|
||||
recorder.write("U", data, now)
|
||||
paper.on_book(now, book, state["tick"])
|
||||
elif kind == "trades":
|
||||
if recorder:
|
||||
recorder.write("T", data, now)
|
||||
for raw in data:
|
||||
try:
|
||||
trade = sh.Trade(now, float(raw["price"]), float(raw["size"]), str(raw.get("side")))
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
paper.on_trade(trade)
|
||||
elif kind == "leader":
|
||||
bid, ask = data
|
||||
state["leader"] = (bid, ask)
|
||||
state["last_leader"] = now
|
||||
if recorder:
|
||||
recorder.write("L", [bid, ask], now)
|
||||
paper.on_leader(now, bid, ask)
|
||||
elif kind == "latency":
|
||||
lat_follow.append(float(data))
|
||||
elif kind == "leader_latency":
|
||||
lat_lead.append(float(data))
|
||||
elif kind == "status":
|
||||
state["follower_status"] = data
|
||||
elif kind == "leader_status":
|
||||
state["leader_status"] = data
|
||||
root.after(50, pump)
|
||||
|
||||
def threshold() -> float:
|
||||
return ps.vector_min_move_pct if ps.mode == "vector" else ps.lead_threshold_pct
|
||||
|
||||
def draw_signal(value: float) -> None:
|
||||
bar.delete("all")
|
||||
width, mid = 600, 300
|
||||
thr = threshold()
|
||||
scale = mid / max(thr * 3, 0.01)
|
||||
x = mid + max(-mid, min(mid, value * scale))
|
||||
bar.create_rectangle(min(mid, x), 3, max(mid, x), 13, fill="#2e9d57" if value >= 0 else "#d04a4a",
|
||||
outline="")
|
||||
for t in (thr, -thr):
|
||||
tx = mid + t * scale
|
||||
bar.create_line(tx, 0, tx, 16, fill="#333", dash=(2, 2))
|
||||
bar.create_line(mid, 0, mid, 16, fill="#999")
|
||||
|
||||
def refresh() -> None:
|
||||
now = time.time()
|
||||
lf = f" · задержка ~{statistics.median(lat_follow):.0f} мс" if len(lat_follow) >= 5 else ""
|
||||
ll = f" · задержка ~{statistics.median(lat_lead):.0f} мс" if len(lat_lead) >= 5 else ""
|
||||
header.set(f"{state['leader_status']}{ll} | {state['follower_status']}{lf}")
|
||||
pol = paper.policy
|
||||
if state["leader"]:
|
||||
bid, ask = state["leader"]
|
||||
age = (now - state["last_leader"]) * 1000
|
||||
if ps.lead_market == "raydium":
|
||||
lead_var.set(f"{pol.L:8s} пул {ps.lead_pool[:10]}… цена {bid:<12.10g} (по последнему обмену) · "
|
||||
f"{age:.0f} мс назад")
|
||||
else:
|
||||
lead_var.set(f"{pol.L:8s} {ps.lead_ticker:16s} bid {bid:<12.10g} ask {ask:<12.10g} mid "
|
||||
f"{(bid + ask) / 2:<12.10g} спред {(ask - bid) / ((bid + ask) / 2) * 100:.3f}% · "
|
||||
f"{age:.0f} мс назад")
|
||||
best_bid, best_ask = book.best()
|
||||
if best_bid and best_ask:
|
||||
age = (now - state["last_follower"]) * 1000
|
||||
follow_var.set(f"{pol.F:8s} {ps.follow_ticker:16s} bid {best_bid:<12.10g} ask {best_ask:<12.10g} mid "
|
||||
f"{(best_bid + best_ask) / 2:<12.10g} спред {(best_ask - best_bid) / ((best_ask + best_bid) / 2) * 100:.3f}%"
|
||||
f" · {age:.0f} мс назад")
|
||||
sig = getattr(pol, "signal", 0.0)
|
||||
thr = threshold()
|
||||
if ps.mode == "vector":
|
||||
active = f"{'LONG' if sig > 0 else 'SHORT'}: {pol.L} {'растёт' if sig > 0 else 'падает'} " \
|
||||
f"{sig:+.3f}% за {ps.vector_window_seconds:g} с"
|
||||
idle = f"Ждём направление: {pol.L} {sig:+.3f}% за {ps.vector_window_seconds:g} с (порог ±{thr:g}%)"
|
||||
else:
|
||||
active = f"{'LONG' if sig > 0 else 'SHORT'}: {pol.F} отстаёт от {pol.L} на {sig:+.3f}%"
|
||||
idle = f"Ждём: отставание {sig:+.3f}% (порог ±{thr:g}%)"
|
||||
conf = getattr(pol, "conf", 0.0)
|
||||
conf_text = f" · уверенность {conf:.2f} (порог {ps.min_confidence:g})"
|
||||
active += conf_text
|
||||
idle += conf_text
|
||||
if abs(sig) >= thr and thr > 0 and conf >= ps.min_confidence:
|
||||
signal_var.set(active)
|
||||
signal_label.configure(fg="#1f8a4c" if sig > 0 else "#c23b3b")
|
||||
else:
|
||||
signal_var.set(idle)
|
||||
signal_label.configure(fg="#666")
|
||||
draw_signal(sig)
|
||||
status.set(pol.status)
|
||||
positions = paper.ledger.positions
|
||||
if positions:
|
||||
best_bid, best_ask = book.best()
|
||||
lines = [f"Открыто позиций: {len(positions)} из {ps.max_positions} · вместе сейчас "
|
||||
f"{paper.unrealized(book):+.4f}$"]
|
||||
for pos in positions[:8]:
|
||||
price = best_bid if pos.side == "LONG" else best_ask
|
||||
pnl = (1 if pos.side == "LONG" else -1) * (price - pos.entry) * pos.qty if price else 0.0
|
||||
lines.append(f" {pos.side} {pos.qty:.6g} по {pos.entry:.10g} · тейк {pos.target:.10g} · стоп "
|
||||
f"{pos.stop:.10g} · {now - pos.opened:.0f} из {ps.max_hold_seconds:g} с · {pnl:+.4f}$")
|
||||
if len(positions) > 8:
|
||||
lines.append(f" … и ещё {len(positions) - 8}")
|
||||
position.set("\n".join(lines))
|
||||
else:
|
||||
position.set("Позиции нет" + ("" if ps.enabled else " · новые сделки остановлены (кнопка «Старт»)"))
|
||||
summary.set(paper.summary())
|
||||
if paper.message:
|
||||
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}", t.regime), tags=("win" if t.net_usd > 0 else "loss",))
|
||||
if now - state.get("conn_check", 0.0) > 30:
|
||||
# pick up connections added by the autonomous search without a restart
|
||||
state["conn_check"] = now
|
||||
before = len(connections)
|
||||
for c in load_connections():
|
||||
if not any(same_connection(c, x) for x in connections):
|
||||
connections.append(c)
|
||||
if len(connections) != before:
|
||||
show_connections()
|
||||
message.set(f"Автопоиск добавил подключений: {len(connections) - before} — смотрите список «Подключение»")
|
||||
root.after(300, refresh)
|
||||
|
||||
def on_close() -> None:
|
||||
if state["recorder"]:
|
||||
state["recorder"].close()
|
||||
for key in ("leader_feed", "follower_feed"):
|
||||
if state[key]:
|
||||
state[key].stop()
|
||||
paper.ledger.save()
|
||||
root.destroy()
|
||||
|
||||
root.protocol("WM_DELETE_WINDOW", on_close)
|
||||
start_feeds()
|
||||
show_trading()
|
||||
remember_connection(connections, {k: getattr(ps, k) for k in CONNECTION_KEYS})
|
||||
show_connections()
|
||||
pump()
|
||||
refresh()
|
||||
root.mainloop()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run()
|
||||
Reference in new issue
Block a user