4559 lines
269 KiB
Python
4559 lines
269 KiB
Python
from __future__ import annotations
|
||
|
||
import json
|
||
import hashlib
|
||
import math
|
||
import os
|
||
import queue
|
||
import re
|
||
import threading
|
||
import time
|
||
import urllib.parse
|
||
import urllib.request
|
||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||
from collections import deque
|
||
from datetime import datetime
|
||
from pathlib import Path
|
||
import tkinter as tk
|
||
from tkinter import messagebox, ttk
|
||
from bybit_live import BybitAPIError, BybitLiveClient
|
||
from credential_store import CredentialStoreError, delete_credentials, load_credentials, save_credentials
|
||
from historical_backtest import (fetch_funding_history, fetch_klines, prepare_universe, run_backtest,
|
||
run_mode_backtest, save_report)
|
||
import strategy
|
||
from desktop_models import Position, ClosedTrade, CurrencyState
|
||
from desktop_chart import ChartView
|
||
from persistence import atomic_write_json
|
||
|
||
try:
|
||
import websocket
|
||
except ImportError:
|
||
websocket = None
|
||
|
||
|
||
WS_URL = "wss://stream.bybit.com/v5/public/linear"
|
||
WINDOW_MS = 60_000
|
||
CHART_SECONDS = 30 * 60
|
||
CANDLE_INTERVAL_MINUTES = 1
|
||
TAKER_FEE_PCT = 0.055
|
||
AUTO_CURRENCY_SCAN_SECONDS = 10 * 60
|
||
TOP_LIQUID_SYMBOLS = 100
|
||
PUBLIC_MARKET_API_HOSTS = ("https://api.bybit.com", "https://api.bytick.com")
|
||
STRATEGY_DEFAULTS_VERSION = 2
|
||
DEFAULT_CURRENCY_STRATEGY = {
|
||
"stake_pct": "5",
|
||
"max_adds": "2",
|
||
"leverage": "1",
|
||
"trigger_pct": "0.2",
|
||
"add_step_pct": "1.5",
|
||
"stop_loss_pct": "0",
|
||
"take_profit_pct": "10",
|
||
}
|
||
SETTINGS_FILE = Path(__file__).with_name("settings.json")
|
||
STATE_FILE = Path(__file__).with_name("account_state.json")
|
||
BACKTEST_REPORTS_DIR = Path(__file__).with_name("historical_reports")
|
||
HISTORICAL_MODE = "Исторический прогон"
|
||
UI_REDRAW_INTERVAL_MS = 250
|
||
TILE_WIDTH = 184
|
||
TILE_HEIGHT = 186
|
||
TILE_GAP = 8
|
||
MAX_EVENTS_PER_POLL = 2000
|
||
MANUAL_CLOSE_CONFIRM_SECONDS = 15
|
||
|
||
|
||
class PaperSimulator(ChartView):
|
||
def __init__(self, root: tk.Tk) -> None:
|
||
self.root = root
|
||
self.root.title("Bybit — симулятор сделок в реальном времени")
|
||
self.root.geometry("1200x850")
|
||
self.root.minsize(900, 650)
|
||
self.events: queue.Queue[tuple] = queue.Queue()
|
||
self.ws_app = None
|
||
self.ws_thread: threading.Thread | None = None
|
||
self.running = False
|
||
self.historical_running = False
|
||
self._backtest_cancel = threading.Event()
|
||
self.symbol = "BTCUSDT"
|
||
self.symbol_states: dict[str, CurrencyState] = {}
|
||
self.currencies: list[str] = []
|
||
self.enabled_symbols: set[str] = set()
|
||
self.currency_settings: dict[str, dict[str, str]] = {}
|
||
self.strategy_by_symbol: dict[str, dict[str, float]] = {}
|
||
self._has_saved_enabled_symbols = False
|
||
self.tile_widgets: dict[str, dict] = {}
|
||
self.detail_windows: dict[str, tk.Toplevel] = {}
|
||
self.ticker_24h: dict[str, float] = {}
|
||
self.ticker_turnover_24h: dict[str, float] = {}
|
||
self.ticker_prices: dict[str, float] = {}
|
||
self._ticker_poll_busy = False
|
||
self.ws_symbols: list[str] = []
|
||
self.session_started_at = time.time()
|
||
self.prices: deque[tuple[float, float]] = deque()
|
||
# Candle fields: minute timestamp, open, high, low, close.
|
||
self.candles: deque[list[float]] = deque()
|
||
self.entry_markers: deque[tuple[float, float, int]] = deque()
|
||
self.last_price: float | None = None
|
||
self.balance = 5000.0
|
||
self.initial_balance = 5000.0
|
||
self.total_fees = 0.0
|
||
self.position: Position | None = None
|
||
self.trades: list[ClosedTrade] = []
|
||
self.next_id = 1
|
||
self.last_signal_pct: float | None = None
|
||
self.last_signal_ready = False
|
||
self._previous_entry_signal_pct: float | None = None
|
||
self.applied_settings: dict[str, float] | None = None
|
||
self.baseline_close: float | None = None
|
||
self.interval_minutes = CANDLE_INTERVAL_MINUTES
|
||
self._last_signal_refresh_at = 0.0
|
||
self._live_minute_prices: deque[tuple[float, float]] = deque()
|
||
self.last_ws_message = 0.0
|
||
self.chart_visible_seconds = CHART_SECONDS
|
||
self.chart_view_end: float | None = None
|
||
self.chart_price_center: float | None = None
|
||
self.chart_price_span: float | None = None
|
||
self._drag_anchor: tuple[int, int, float, float, float, float] | None = None
|
||
self._settings_save_job: str | None = None
|
||
self.mode_var = tk.StringVar(value="Симуляция")
|
||
self.auto_currency_growth_var = tk.StringVar(value="20")
|
||
self.auto_currency_status_var = tk.StringVar(value="Загружаю список Bybit…")
|
||
self.ticker_data_source = ""
|
||
self.max_active_sim_positions_var = tk.StringVar(value="5")
|
||
self.rotation_pending_disable: set[str] = set()
|
||
self.auto_enabling_symbols: set[str] = set()
|
||
self.auto_symbol_retry_after: dict[str, float] = {}
|
||
self.next_auto_currency_scan_at = 0.0
|
||
self.startup_currency_filter_busy = False
|
||
self.startup_currency_filter_approved_for: str | None = None
|
||
self.historical_days_var = tk.StringVar(value="30")
|
||
self.historical_initial_capital_var = tk.StringVar(value="5000")
|
||
self.historical_growth_var = tk.StringVar(value="30")
|
||
self.historical_min_equity_var = tk.StringVar(value="10")
|
||
self.api_key_var = tk.StringVar(value="")
|
||
self.api_secret_var = tk.StringVar(value="")
|
||
self.credentials_status_var = tk.StringVar(value="Ключи ещё не сохранены на этом компьютере.")
|
||
self.testnet_var = tk.BooleanVar(value=True)
|
||
self.live_account_var = tk.StringVar(value="")
|
||
self.live_position: Position | None = None
|
||
self.live_position_info: dict | None = None
|
||
self.live_trades: list[ClosedTrade] = []
|
||
self.next_live_id = 1
|
||
self.live_wallet: dict[str, float] | None = None
|
||
self.live_positions: list[dict] = []
|
||
self.live_orders: list[dict] = []
|
||
self.live_closed_pnl: list[dict] = []
|
||
self.live_initial_deposits: dict[str, float] = {}
|
||
self.api_connecting = False
|
||
self.live_client: BybitLiveClient | None = None
|
||
self.live_spec: dict[str, str] | None = None
|
||
self.live_fee_pct = TAKER_FEE_PCT
|
||
self.live_commands: queue.Queue[tuple] = queue.Queue()
|
||
self.live_commands_by_symbol: dict[str, queue.Queue] = {}
|
||
self.live_workers: dict[str, threading.Thread] = {}
|
||
self.live_preparing_symbols: set[str] = set()
|
||
self.live_order_lock = threading.Lock()
|
||
# Trade ids are allocated from worker threads and the UI thread.
|
||
self._live_id_lock = threading.Lock()
|
||
self._redraw_job: str | None = None
|
||
self._dirty_symbols: set[str] = set()
|
||
self._dirty_main = False
|
||
self.ws_subscribed: set[str] = set()
|
||
self._ws_lock = threading.Lock()
|
||
self.historical_universe_var = tk.BooleanVar(value=False)
|
||
self.historical_funding_var = tk.BooleanVar(value=True)
|
||
# Strategy mode (classic / A / B) for simulation and the historical run.
|
||
self.strategy_mode = strategy.STRATEGY_CLASSIC
|
||
self.strategy_mode_var = tk.StringVar(value=strategy.STRATEGY_TITLES[self.strategy_mode])
|
||
self.mode_settings: dict[str, dict[str, str]] = {
|
||
mode: {key: f"{value:g}" for key, value in defaults.items()}
|
||
for mode, defaults in strategy.MODE_DEFAULTS.items()
|
||
}
|
||
self.strategy_window: tk.Toplevel | None = None
|
||
self.ticker_funding_pct: dict[str, float] = {}
|
||
self._btc_regime_cache: tuple[float, int, bool | None] = (0.0, 0, None)
|
||
self._btc_regime_lock = threading.Lock()
|
||
self._signal_pool = ThreadPoolExecutor(max_workers=4)
|
||
self.live_control_thread: threading.Thread | None = None
|
||
self.live_order_busy = False
|
||
self.live_preflight = False
|
||
self.live_halted = False
|
||
self.live_transition_pending = False
|
||
self._build_ui()
|
||
self.default_currency_settings = {
|
||
"stake_pct": self.stake_var.get(), "max_adds": self.max_adds_var.get(),
|
||
"leverage": self.leverage_var.get(), "trigger_pct": self.trigger_var.get(),
|
||
"add_step_pct": self.add_step_var.get(), "stop_loss_pct": self.stop_loss_var.get(),
|
||
"take_profit_pct": self.take_profit_var.get(),
|
||
}
|
||
self._load_saved_settings()
|
||
self._load_saved_credentials()
|
||
self._load_saved_state()
|
||
self._load_currency_settings(self.symbol)
|
||
if not self.currencies:
|
||
self._ensure_symbol(self.symbol)
|
||
if not self.enabled_symbols and not self._has_saved_enabled_symbols:
|
||
self.enabled_symbols.add(self.symbol)
|
||
self._ensure_symbol(self.symbol)
|
||
if self.position:
|
||
self._ensure_symbol(self.position.symbol).position = self.position
|
||
self.enabled_symbols.add(self.position.symbol)
|
||
if self.live_position:
|
||
self._ensure_symbol(self.live_position.symbol).live_position = self.live_position
|
||
self.enabled_symbols.add(self.live_position.symbol)
|
||
self._render_currency_tiles()
|
||
if self.live_position is not None:
|
||
self.mode_var.set("Реальная торговля")
|
||
self._refresh_settings_summary()
|
||
self.root.after(100, self._poll_events)
|
||
self.root.after(5000, self._refresh_rolling_change)
|
||
self.root.after(5000, self._poll_mode_signals)
|
||
self.root.protocol("WM_DELETE_WINDOW", self._on_close)
|
||
self._refresh_ui()
|
||
self._poll_ticker_24h()
|
||
|
||
def _build_ui(self) -> None:
|
||
outer = ttk.Frame(self.root, padding=10)
|
||
outer.pack(fill="both", expand=True)
|
||
|
||
header = ttk.Frame(outer)
|
||
header.pack(fill="x")
|
||
historical_controls = ttk.Frame(outer)
|
||
self.historical_controls_frame = historical_controls
|
||
self.auto_currency_controls_frame = ttk.Frame(outer)
|
||
self.simulation_controls_frame = ttk.Frame(outer)
|
||
self.start_btn = ttk.Button(header, text="Старт", command=self.start)
|
||
self.start_btn.pack(side="left")
|
||
self.stop_btn = ttk.Button(header, text="Стоп", command=self.stop, state="disabled")
|
||
self.stop_btn.pack(side="left", padx=6)
|
||
ttk.Label(header, text="Режим:").pack(side="left", padx=(12, 3))
|
||
self.mode_combo = ttk.Combobox(header, textvariable=self.mode_var,
|
||
values=("Симуляция", HISTORICAL_MODE, "Реальная торговля"),
|
||
state="readonly", width=22)
|
||
self.mode_combo.pack(side="left")
|
||
self.mode_combo.bind("<<ComboboxSelected>>", self._on_mode_change)
|
||
strategy_row = ttk.Frame(outer)
|
||
strategy_row.pack(fill="x", pady=(4, 0))
|
||
ttk.Label(strategy_row, text="Режим стратегии (симуляция и исторический прогон):").pack(side="left", padx=(0, 4))
|
||
self.strategy_combo = ttk.Combobox(
|
||
strategy_row, textvariable=self.strategy_mode_var, state="readonly", width=42,
|
||
values=[strategy.STRATEGY_TITLES[mode] for mode in strategy.STRATEGY_MODES],
|
||
)
|
||
self.strategy_combo.pack(side="left")
|
||
self.strategy_combo.bind("<<ComboboxSelected>>", self._on_strategy_mode_selected)
|
||
self.strategy_settings_btn = ttk.Button(strategy_row, text="Настройки режима…",
|
||
command=self.open_strategy_settings)
|
||
self.strategy_settings_btn.pack(side="left", padx=6)
|
||
self.strategy_hint_var = tk.StringVar(value="")
|
||
ttk.Label(strategy_row, textvariable=self.strategy_hint_var, foreground="#55606b").pack(side="left", padx=6)
|
||
self.historical_days_spin = ttk.Spinbox(
|
||
historical_controls, from_=1, to=365, textvariable=self.historical_days_var, width=5,
|
||
command=self._schedule_settings_save,
|
||
)
|
||
self.historical_days_var.trace_add("write", self._schedule_settings_save)
|
||
self.historical_days_label = ttk.Label(historical_controls, text="Дней:")
|
||
self.historical_capital_label = ttk.Label(historical_controls, text="Депозит, USDT:")
|
||
self.historical_capital_entry = ttk.Entry(
|
||
historical_controls, textvariable=self.historical_initial_capital_var, width=9,
|
||
)
|
||
self.historical_initial_capital_var.trace_add("write", self._schedule_settings_save)
|
||
self.historical_growth_label = ttk.Label(historical_controls, text="Рост 24 ч, мин. %:")
|
||
self.historical_growth_spin = ttk.Spinbox(
|
||
historical_controls, from_=0, to=1000, increment=0.1,
|
||
textvariable=self.historical_growth_var, width=7,
|
||
command=self._schedule_settings_save,
|
||
)
|
||
self.historical_growth_var.trace_add("write", self._schedule_settings_save)
|
||
self.historical_equity_label = ttk.Label(historical_controls, text="Стоп капитала, %:")
|
||
self.historical_equity_spin = ttk.Spinbox(
|
||
historical_controls, from_=1, to=100, increment=1,
|
||
textvariable=self.historical_min_equity_var, width=5,
|
||
command=self._schedule_settings_save,
|
||
)
|
||
self.historical_min_equity_var.trace_add("write", self._schedule_settings_save)
|
||
self.historical_days_label.pack(side="left", padx=(0, 2))
|
||
self.historical_days_spin.pack(side="left")
|
||
self.historical_capital_label.pack(side="left", padx=(8, 2))
|
||
self.historical_capital_entry.pack(side="left")
|
||
self.historical_growth_label.pack(side="left", padx=(8, 2))
|
||
self.historical_growth_spin.pack(side="left")
|
||
self.historical_equity_label.pack(side="left", padx=(8, 2))
|
||
self.historical_equity_spin.pack(side="left")
|
||
self.historical_universe_check = ttk.Checkbutton(
|
||
historical_controls,
|
||
text="Отбор валют как в реальном режиме (топ-100 по обороту, порог автоподбора, лимит позиций)",
|
||
variable=self.historical_universe_var, command=self._schedule_settings_save,
|
||
)
|
||
self.historical_universe_check.pack(side="left", padx=(12, 0))
|
||
ttk.Checkbutton(
|
||
historical_controls, text="Учитывать funding",
|
||
variable=self.historical_funding_var, command=self._schedule_settings_save,
|
||
).pack(side="left", padx=(12, 0))
|
||
ttk.Label(
|
||
self.auto_currency_controls_frame,
|
||
text="Автоподбор: топ-100 USDT perpetual по обороту · скан каждые 10 мин · рост за 24 ч выше:",
|
||
).pack(side="left")
|
||
self.auto_currency_growth_spin = ttk.Spinbox(
|
||
self.auto_currency_controls_frame, from_=0, to=1000, increment=0.1,
|
||
textvariable=self.auto_currency_growth_var, width=7,
|
||
command=self._schedule_settings_save,
|
||
)
|
||
self.auto_currency_growth_spin.pack(side="left", padx=(5, 2))
|
||
ttk.Label(self.auto_currency_controls_frame, text="%").pack(side="left")
|
||
ttk.Label(
|
||
self.auto_currency_controls_frame,
|
||
textvariable=self.auto_currency_status_var,
|
||
).pack(side="left", padx=(10, 0))
|
||
self.auto_currency_growth_var.trace_add("write", self._schedule_settings_save)
|
||
self.live_settings_btn = ttk.Button(header, text="API Bybit…", command=self.open_live_settings)
|
||
self.live_settings_btn.pack(side="left", padx=5)
|
||
self.connect_btn = ttk.Button(header, text="Подключиться", command=self.connect_bybit)
|
||
self.connect_btn.pack(side="left", padx=5)
|
||
self.status_var = tk.StringVar(value="Остановлен")
|
||
ttk.Label(header, textvariable=self.status_var).pack(side="left", padx=8)
|
||
|
||
self._build_settings_window()
|
||
self._build_live_settings_window()
|
||
|
||
ttk.Label(self.simulation_controls_frame, text="Депозит симуляции, USDT:").pack(side="left")
|
||
self.simulation_deposit_entry = ttk.Entry(
|
||
self.simulation_controls_frame, textvariable=self.initial_var, width=9,
|
||
)
|
||
self.simulation_deposit_entry.pack(side="left", padx=(4, 10))
|
||
# The simultaneous-position limit is shared by simulation, live trading and the
|
||
# backtest, so it lives in the auto-selection row shown in both trading modes.
|
||
ttk.Label(self.auto_currency_controls_frame, text=" Макс. одновременных позиций:").pack(side="left")
|
||
self.max_active_sim_positions_spin = ttk.Spinbox(
|
||
self.auto_currency_controls_frame, from_=1, to=100, increment=1,
|
||
textvariable=self.max_active_sim_positions_var, width=5,
|
||
command=self._schedule_settings_save,
|
||
)
|
||
self.max_active_sim_positions_spin.pack(side="left", padx=(4, 8))
|
||
self.max_active_sim_positions_var.trace_add("write", self._schedule_settings_save)
|
||
ttk.Button(
|
||
self.simulation_controls_frame, text="Применить",
|
||
command=self.apply_simulation_controls,
|
||
).pack(side="left")
|
||
|
||
self.strategy_summary_var = tk.StringVar(value="")
|
||
self.strategy_summary_label = ttk.Label(
|
||
outer,
|
||
textvariable=self.strategy_summary_var,
|
||
padding=(8, 5),
|
||
relief="groove",
|
||
justify="left",
|
||
)
|
||
# Legacy account/chart/history views stay instantiated for the existing
|
||
# refresh and persistence code, but are no longer part of the home screen.
|
||
|
||
self.currencies_frame = ttk.LabelFrame(outer, text="Валюты · независимые параллельные стратегии", padding=6)
|
||
self.currencies_frame.pack(fill="both", expand=True, pady=(6, 0))
|
||
self.main_metrics_frame = ttk.Frame(outer)
|
||
self.main_metrics_frame.pack(fill="x", pady=(6, 0), before=self.currencies_frame)
|
||
self.main_metric_vars: dict[str, tk.StringVar] = {}
|
||
self.main_metric_titles: dict[str, ttk.LabelFrame] = {}
|
||
for key, title in (("balance", "Баланс"), ("pnl", "P&L"), ("equity", "Общий баланс с P&L"),
|
||
("free", "Свободно для новых сделок")):
|
||
box = ttk.LabelFrame(self.main_metrics_frame, text=title, padding=(8, 5))
|
||
box.pack(side="left", fill="x", expand=True, padx=(0, 6))
|
||
value_var = tk.StringVar(value="—")
|
||
ttk.Label(box, textvariable=value_var, font=("Segoe UI", 12, "bold")).pack(anchor="w")
|
||
self.main_metric_vars[key] = value_var
|
||
self.main_metric_titles[key] = box
|
||
# Tiles are laid out as a grid that wraps to the window width and scrolls vertically.
|
||
self.tiles_canvas = tk.Canvas(self.currencies_frame, highlightthickness=0, background="#eef2f5")
|
||
tiles_scroll = ttk.Scrollbar(self.currencies_frame, orient="vertical", command=self.tiles_canvas.yview)
|
||
self.tiles_canvas.configure(yscrollcommand=tiles_scroll.set)
|
||
tiles_scroll.pack(side="right", fill="y")
|
||
self.tiles_canvas.pack(side="left", fill="both", expand=True)
|
||
self.tiles_inner = ttk.Frame(self.tiles_canvas)
|
||
self.tiles_canvas_window = self.tiles_canvas.create_window((0, 0), window=self.tiles_inner, anchor="nw")
|
||
self.tiles_inner.bind("<Configure>", lambda _event: self.tiles_canvas.configure(scrollregion=self.tiles_canvas.bbox("all")))
|
||
self.tiles_canvas.bind("<Configure>", lambda _event: self._layout_currency_tiles())
|
||
for sequence in ("<MouseWheel>", "<Button-4>", "<Button-5>"):
|
||
self.tiles_canvas.bind_all(sequence, self._on_tiles_wheel, add="+")
|
||
self.tile_frames: dict[str, ttk.Frame] = {}
|
||
self.tile_add_button: ttk.Button | None = None
|
||
self._tile_layout_key: tuple | None = None
|
||
self._render_currency_tiles()
|
||
|
||
self._legacy_views = ttk.Frame(outer)
|
||
metrics = ttk.Frame(self._legacy_views)
|
||
metrics.pack(fill="x", pady=5)
|
||
self.metric_vars: dict[str, tk.StringVar] = {}
|
||
self.metric_title_vars: dict[str, tk.StringVar] = {}
|
||
self.metric_boxes: dict[str, ttk.LabelFrame] = {}
|
||
for title, key in (("Баланс", "balance"), ("Бюджет всего", "equity"), ("Без стартового", "pnl"), ("Свободно", "free"), ("Комиссии", "fees")):
|
||
box = ttk.LabelFrame(metrics, text=title, padding=(8, 5))
|
||
box.pack(side="left", fill="x", expand=True, padx=(0, 6))
|
||
var = tk.StringVar(value="—")
|
||
self.metric_vars[key] = var
|
||
title_var = tk.StringVar(value=title)
|
||
self.metric_title_vars[key] = title_var
|
||
self.metric_boxes[key] = box
|
||
box.configure(text=title)
|
||
ttk.Label(box, textvariable=var, font=("Segoe UI", 12, "bold")).pack(anchor="w")
|
||
|
||
chart_frame = ttk.LabelFrame(self._legacy_views, text="Рыночная цена · публичные сделки Bybit", padding=4)
|
||
chart_frame.pack(fill="both", expand=True, pady=(5, 8))
|
||
chart_toolbar = ttk.Frame(chart_frame)
|
||
chart_toolbar.pack(fill="x", pady=(0, 3))
|
||
self.market_price_var = tk.StringVar(value="Ожидание цены…")
|
||
ttk.Label(chart_toolbar, textvariable=self.market_price_var, font=("Segoe UI", 12, "bold")).pack(side="left", padx=4)
|
||
self.live_button = ttk.Button(chart_toolbar, text="К текущему времени", command=self._go_to_live)
|
||
self.live_button.pack(side="right", padx=4)
|
||
self.canvas = tk.Canvas(chart_frame, background="#101820", highlightthickness=0, height=340)
|
||
self.canvas.pack(fill="both", expand=True)
|
||
self.canvas.bind("<Configure>", lambda _event: self._draw_chart())
|
||
self.canvas.bind("<MouseWheel>", self._on_chart_wheel)
|
||
self.canvas.bind("<Button-4>", lambda event: self._on_chart_wheel_linux(event, 1))
|
||
self.canvas.bind("<Button-5>", lambda event: self._on_chart_wheel_linux(event, -1))
|
||
self.canvas.bind("<ButtonPress-1>", self._on_chart_press)
|
||
self.canvas.bind("<B1-Motion>", self._on_chart_drag)
|
||
self.canvas.bind("<ButtonRelease-1>", self._on_chart_release)
|
||
self.canvas.bind("<Double-Button-1>", self._reset_chart_view)
|
||
self.chart_hint_var = tk.StringVar(value="Колесо: масштаб · перетаскивание: перемещение · двойной щелчок: сброс масштаба")
|
||
ttk.Label(chart_frame, textvariable=self.chart_hint_var).pack(anchor="w")
|
||
|
||
pos_frame = ttk.LabelFrame(self._legacy_views, text="Открытая сделка", padding=5)
|
||
pos_frame.pack(fill="x", pady=(0, 6))
|
||
self.position_var = tk.StringVar(value="Нет открытой сделки")
|
||
ttk.Label(pos_frame, textvariable=self.position_var).pack(side="left", anchor="w", fill="x", expand=True)
|
||
self.close_trade_btn = ttk.Button(pos_frame, text="Закрыть сделку", command=self._manual_close_position, state="disabled")
|
||
self.close_trade_btn.pack(side="right", padx=(8, 0))
|
||
|
||
history_frame = ttk.LabelFrame(self._legacy_views, text="История и данные Bybit", padding=5)
|
||
history_frame.pack(fill="both", expand=False)
|
||
self.history_tabs = ttk.Notebook(history_frame)
|
||
self.history_tabs.pack(fill="both", expand=True)
|
||
trades_tab = ttk.Frame(self.history_tabs, padding=3)
|
||
orders_tab = ttk.Frame(self.history_tabs, padding=3)
|
||
positions_tab = ttk.Frame(self.history_tabs, padding=3)
|
||
self.history_tabs.add(trades_tab, text="Сделки / P&L")
|
||
self.history_tabs.add(orders_tab, text="Ордера Bybit")
|
||
self.history_tabs.add(positions_tab, text="Открытые позиции")
|
||
cols = ("id", "symbol", "entry", "exit", "roi", "gross", "fees", "net", "reason")
|
||
self.table = ttk.Treeview(trades_tab, columns=cols, show="headings", height=5)
|
||
self.table.tag_configure("profit", foreground="#13843b")
|
||
self.table.tag_configure("loss", foreground="#c62828")
|
||
headings = {"id": "#", "symbol": "Тикер", "entry": "Вход", "exit": "Выход", "roi": "ROI %", "gross": "Gross USDT", "fees": "Комиссии", "net": "Net USDT", "reason": "Причина"}
|
||
widths = {"id": 45, "symbol": 100, "entry": 115, "exit": 115, "roi": 80, "gross": 105, "fees": 100, "net": 100, "reason": 115}
|
||
for col in cols:
|
||
self.table.heading(col, text=headings[col])
|
||
self.table.column(col, width=widths[col], anchor="center")
|
||
scrollbar = ttk.Scrollbar(trades_tab, orient="vertical", command=self.table.yview)
|
||
self.table.configure(yscrollcommand=scrollbar.set)
|
||
self.table.pack(side="left", fill="both", expand=True)
|
||
scrollbar.pack(side="right", fill="y")
|
||
|
||
order_cols = ("time", "symbol", "side", "type", "qty", "price", "fill", "status", "id")
|
||
self.bybit_orders_table = ttk.Treeview(orders_tab, columns=order_cols, show="headings", height=5)
|
||
order_heads = {"time": "Время", "symbol": "Тикер", "side": "Сторона", "type": "Тип", "qty": "Количество", "price": "Цена", "fill": "Средняя исполнения", "status": "Статус", "id": "Order ID"}
|
||
order_widths = {"time": 135, "symbol": 90, "side": 70, "type": 95, "qty": 95, "price": 95, "fill": 130, "status": 110, "id": 210}
|
||
for col in order_cols:
|
||
self.bybit_orders_table.heading(col, text=order_heads[col])
|
||
self.bybit_orders_table.column(col, width=order_widths[col], anchor="center")
|
||
order_scroll = ttk.Scrollbar(orders_tab, orient="vertical", command=self.bybit_orders_table.yview)
|
||
self.bybit_orders_table.configure(yscrollcommand=order_scroll.set)
|
||
self.bybit_orders_table.pack(side="left", fill="both", expand=True)
|
||
order_scroll.pack(side="right", fill="y")
|
||
|
||
position_cols = ("symbol", "side", "size", "entry", "mark", "upl", "leverage", "tp", "sl")
|
||
self.bybit_positions_table = ttk.Treeview(positions_tab, columns=position_cols, show="headings", height=5)
|
||
position_heads = {"symbol": "Тикер", "side": "Сторона", "size": "Объём", "entry": "Средняя цена", "mark": "Mark price", "upl": "Unrealized P&L", "leverage": "Плечо", "tp": "TP", "sl": "SL"}
|
||
for col in position_cols:
|
||
self.bybit_positions_table.heading(col, text=position_heads[col])
|
||
self.bybit_positions_table.column(col, width=110, anchor="center")
|
||
position_scroll = ttk.Scrollbar(positions_tab, orient="vertical", command=self.bybit_positions_table.yview)
|
||
self.bybit_positions_table.configure(yscrollcommand=position_scroll.set)
|
||
self.bybit_positions_table.pack(side="left", fill="both", expand=True)
|
||
position_scroll.pack(side="right", fill="y")
|
||
|
||
def _ensure_symbol(self, symbol: str) -> CurrencyState:
|
||
symbol = symbol.strip().upper()
|
||
if symbol not in self.symbol_states:
|
||
self.symbol_states[symbol] = CurrencyState()
|
||
if symbol not in self.currencies:
|
||
self.currencies.append(symbol)
|
||
return self.symbol_states[symbol]
|
||
|
||
def _capture_active_symbol(self) -> None:
|
||
if not hasattr(self, "symbol_states"):
|
||
return
|
||
state = self._ensure_symbol(self.symbol)
|
||
state.prices = self.prices
|
||
state.candles = self.candles
|
||
state.entry_markers = self.entry_markers
|
||
state.last_price = self.last_price
|
||
state.baseline_close = self.baseline_close
|
||
state.last_signal_pct = self.last_signal_pct
|
||
state.last_signal_ready = self.last_signal_ready
|
||
state.previous_entry_signal_pct = self._previous_entry_signal_pct
|
||
state.live_minute_prices = self._live_minute_prices
|
||
state.last_ws_message = self.last_ws_message
|
||
state.position = self.position
|
||
state.live_position = self.live_position
|
||
state.live_position_info = self.live_position_info
|
||
state.live_order_busy = self.live_order_busy
|
||
state.live_transition_pending = self.live_transition_pending
|
||
state.live_halted = self.live_halted
|
||
|
||
def _activate_symbol_state(self, symbol: str) -> None:
|
||
state = self._ensure_symbol(symbol)
|
||
self.symbol = symbol
|
||
self.prices = state.prices
|
||
self.candles = state.candles
|
||
self.entry_markers = state.entry_markers
|
||
self.last_price = state.last_price
|
||
self.baseline_close = state.baseline_close
|
||
self.last_signal_pct = state.last_signal_pct
|
||
self.last_signal_ready = state.last_signal_ready
|
||
self._previous_entry_signal_pct = state.previous_entry_signal_pct
|
||
self._live_minute_prices = state.live_minute_prices
|
||
self.last_ws_message = state.last_ws_message
|
||
self.position = state.position
|
||
self.live_position = state.live_position
|
||
self.live_position_info = state.live_position_info
|
||
self.live_order_busy = state.live_order_busy
|
||
self.live_transition_pending = state.live_transition_pending
|
||
self.live_halted = state.live_halted
|
||
|
||
def _render_currency_tiles(self) -> None:
|
||
if not hasattr(self, "tiles_inner"):
|
||
return
|
||
for child in self.tiles_inner.winfo_children():
|
||
child.destroy()
|
||
self.tile_widgets.clear()
|
||
self.tile_frames.clear()
|
||
self._tile_layout_key = None
|
||
for symbol in list(self.currencies):
|
||
self._ensure_symbol(symbol)
|
||
tile = ttk.Frame(self.tiles_inner, width=TILE_WIDTH, height=TILE_HEIGHT, padding=7, relief="ridge")
|
||
# Fixed tile size so the grid stays even regardless of the text inside.
|
||
tile.grid_propagate(False)
|
||
tile.pack_propagate(False)
|
||
self.tile_frames[symbol] = tile
|
||
enabled = tk.BooleanVar(value=symbol in self.enabled_symbols)
|
||
toggle = ttk.Checkbutton(tile, text="В торгах", variable=enabled,
|
||
command=lambda s=symbol, v=enabled: self._toggle_symbol(s, v.get()))
|
||
toggle.pack(anchor="w")
|
||
title = ttk.Label(tile, text=symbol, font=("Segoe UI", 11, "bold"), cursor="hand2")
|
||
title.pack(anchor="w", pady=(3, 2))
|
||
price = ttk.Label(tile, text="Цена: ждём данные", cursor="hand2")
|
||
price.pack(anchor="w")
|
||
change = ttk.Label(tile, text="24 ч: —", cursor="hand2")
|
||
change.pack(anchor="w")
|
||
session = ttk.Label(tile, text="Запуск: +0.00 USDT", cursor="hand2")
|
||
session.pack(anchor="w", pady=(4, 0))
|
||
account = ttk.Label(tile, text="Аккаунт: +0.00 USDT", cursor="hand2")
|
||
account.pack(anchor="w")
|
||
status = ttk.Label(tile, text="Ожидание", foreground="#576574", cursor="hand2",
|
||
wraplength=TILE_WIDTH - 20)
|
||
status.pack(anchor="w", pady=(3, 0))
|
||
for widget in (tile, title, price, change, session, account, status):
|
||
widget.bind("<Double-Button-1>", lambda _e, s=symbol: self._open_currency_details(s))
|
||
widget.bind("<Button-1>", lambda _e, s=symbol: self._open_currency_details(s))
|
||
self.tile_widgets[symbol] = {"enabled": enabled, "price": price, "change": change,
|
||
"session": session, "account": account, "status": status}
|
||
self.tile_add_button = ttk.Button(self.tiles_inner, text="+\nДобавить\nвалюту",
|
||
command=self._add_currency_dialog, width=19)
|
||
self._refresh_currency_tiles()
|
||
self._layout_currency_tiles()
|
||
|
||
def _tile_order(self) -> list[str]:
|
||
"""Enabled pairs first, then the rest; each group by 24 h change, highest first."""
|
||
def change(symbol: str) -> float:
|
||
value = self.ticker_24h.get(symbol)
|
||
return value if value is not None and math.isfinite(value) else float("-inf")
|
||
enabled = sorted((s for s in self.tile_frames if s in self.enabled_symbols),
|
||
key=lambda s: (-change(s), s))
|
||
disabled = sorted((s for s in self.tile_frames if s not in self.enabled_symbols),
|
||
key=lambda s: (-change(s), s))
|
||
return enabled + disabled
|
||
|
||
def _layout_currency_tiles(self) -> None:
|
||
if not hasattr(self, "tiles_canvas") or not hasattr(self, "tile_frames"):
|
||
return
|
||
width = max(int(self.tiles_canvas.winfo_width()), TILE_WIDTH + TILE_GAP)
|
||
columns = max(1, width // (TILE_WIDTH + TILE_GAP))
|
||
order = self._tile_order()
|
||
key = (columns, tuple(order))
|
||
if key == self._tile_layout_key:
|
||
return # nothing moved: avoid re-gridding (and flicker) on every refresh
|
||
self._tile_layout_key = key
|
||
for index, symbol in enumerate(order):
|
||
self.tile_frames[symbol].grid(row=index // columns, column=index % columns,
|
||
padx=TILE_GAP // 2, pady=TILE_GAP // 2)
|
||
if self.tile_add_button is not None:
|
||
index = len(order)
|
||
self.tile_add_button.grid(row=index // columns, column=index % columns,
|
||
padx=TILE_GAP // 2, pady=TILE_GAP // 2, sticky="nsew")
|
||
self.tiles_inner.update_idletasks()
|
||
self.tiles_canvas.configure(scrollregion=self.tiles_canvas.bbox("all"))
|
||
|
||
def _on_tiles_wheel(self, event: tk.Event) -> None:
|
||
# Scroll the tile grid only when the pointer is over it (charts use their own wheel zoom).
|
||
widget = event.widget
|
||
while widget is not None:
|
||
if widget is self.tiles_canvas:
|
||
break
|
||
widget = getattr(widget, "master", None)
|
||
else:
|
||
return
|
||
if getattr(event, "num", None) == 4 or getattr(event, "delta", 0) > 0:
|
||
self.tiles_canvas.yview_scroll(-1, "units")
|
||
else:
|
||
self.tiles_canvas.yview_scroll(1, "units")
|
||
|
||
def _add_currency_dialog(self) -> None:
|
||
dialog = tk.Toplevel(self.root)
|
||
dialog.title("Добавить валюту")
|
||
dialog.transient(self.root)
|
||
dialog.resizable(False, False)
|
||
body = ttk.Frame(dialog, padding=14)
|
||
body.pack(fill="both", expand=True)
|
||
ttk.Label(body, text="Тикер USDT perpetual, например ETHUSDT").pack(anchor="w")
|
||
value = tk.StringVar()
|
||
entry = ttk.Entry(body, textvariable=value, width=24)
|
||
entry.pack(fill="x", pady=8)
|
||
entry.focus_set()
|
||
def add() -> None:
|
||
symbol = value.get().strip().upper()
|
||
if not re.fullmatch(r"[A-Z0-9]{2,30}", symbol):
|
||
messagebox.showerror("Неверный тикер", "Введите тикер контракта, например ETHUSDT.", parent=dialog)
|
||
return
|
||
self._ensure_symbol(symbol)
|
||
self.enabled_symbols.add(symbol)
|
||
self._select_symbol(symbol)
|
||
self._save_settings()
|
||
self._render_currency_tiles()
|
||
if self.running:
|
||
self._subscribe_running_symbols()
|
||
self._fetch_baseline_async(symbol, self.interval_minutes)
|
||
dialog.destroy()
|
||
ttk.Button(body, text="Добавить и включить", command=add).pack(anchor="e")
|
||
entry.bind("<Return>", lambda _event: add())
|
||
|
||
def _toggle_symbol(self, symbol: str, enabled: bool) -> None:
|
||
self._ensure_symbol(symbol)
|
||
if enabled:
|
||
self.enabled_symbols.add(symbol)
|
||
self.rotation_pending_disable.discard(symbol)
|
||
else:
|
||
self.enabled_symbols.discard(symbol)
|
||
self.rotation_pending_disable.discard(symbol)
|
||
self._save_settings()
|
||
if self.running:
|
||
if enabled and self.mode_var.get() == "Реальная торговля" and symbol not in self.live_commands_by_symbol and symbol not in self.live_preparing_symbols:
|
||
self._begin_live_additional_symbol(symbol)
|
||
if enabled and self.symbol_states[symbol].baseline_close is None:
|
||
self._fetch_baseline_async(symbol, self.interval_minutes)
|
||
self._subscribe_running_symbols()
|
||
self._refresh_currency_tiles()
|
||
self._refresh_ui()
|
||
|
||
def _begin_live_additional_symbol(self, symbol: str) -> None:
|
||
client = self.live_client
|
||
if client is None:
|
||
self.status_var.set("Сначала подключите Bybit API")
|
||
return
|
||
base = self.applied_settings or self._safe_read_settings()
|
||
defaults = self._read_default_strategy(base)
|
||
settings = self._strategy_for_symbol(symbol, defaults)
|
||
self.live_preparing_symbols.add(symbol)
|
||
thread = threading.Thread(target=self._live_additional_symbol_worker,
|
||
args=(client, symbol, settings), daemon=True)
|
||
thread.start()
|
||
|
||
def _live_additional_symbol_worker(self, client: BybitLiveClient, symbol: str,
|
||
settings: dict[str, float]) -> None:
|
||
try:
|
||
spec = client.get_instrument(symbol)
|
||
fee_pct = client.get_taker_fee_pct(symbol)
|
||
rows = client.get_positions(symbol)
|
||
if any(int(row.get("positionIdx", 0)) != 0 for row in rows):
|
||
raise BybitAPIError(f"{symbol}: для бота нужен режим позиции One-Way")
|
||
position_row = next((row for row in rows if float(row.get("size") or 0) > 0), None)
|
||
state = self.symbol_states.get(symbol)
|
||
shadow = state.live_position if state else None
|
||
if position_row:
|
||
if position_row.get("side") != "Buy":
|
||
raise BybitAPIError(f"{symbol}: бот сопровождает только LONG-позиции")
|
||
avg, qty = float(position_row.get("avgPrice") or 0), float(position_row.get("size") or 0)
|
||
leverage = float(position_row.get("leverage") or settings["leverage"])
|
||
settings["leverage"] = leverage
|
||
shadow = Position(**vars(shadow)) if shadow else Position(
|
||
self._allocate_live_id(), symbol, avg, qty, avg * qty / leverage,
|
||
avg * qty * fee_pct / 100, time.time(), avg, settings["max_adds"])
|
||
shadow.entry_price, shadow.qty, shadow.stake = avg, qty, avg * qty / leverage
|
||
tp_pct = max(settings["take_profit"], self._fee_cover_pct(fee_pct))
|
||
client.update_position_stops(symbol,
|
||
avg * (1 + tp_pct / 100) if settings["take_profit"] > 0 else 0.0,
|
||
avg * (1 - settings["stop_loss"] / 100) if settings["stop_loss"] > 0 else 0.0,
|
||
spec["tick_size"])
|
||
else:
|
||
wallet = client.get_wallet()
|
||
required = settings["stake"] * (1 + settings["leverage"] * fee_pct / 100)
|
||
if wallet["available"] < required:
|
||
raise BybitAPIError(f"{symbol}: недостаточно свободной маржи для первого входа")
|
||
client.set_leverage(symbol, settings["leverage"])
|
||
settings["fee"] = fee_pct
|
||
self.events.put(("live_symbol_ready", symbol, settings, spec, fee_pct, position_row, shadow))
|
||
except Exception as exc:
|
||
self.events.put(("live_symbol_failed", symbol, str(exc)))
|
||
|
||
def _activate_live_symbol(self, symbol: str, settings: dict[str, float], spec: dict[str, str],
|
||
fee_pct: float, position_row: dict | None, shadow: Position | None) -> None:
|
||
self.auto_enabling_symbols.discard(symbol)
|
||
state = self._ensure_symbol(symbol)
|
||
state.live_position = shadow
|
||
state.live_position_info = position_row
|
||
state.live_halted = False
|
||
state.live_order_busy = False
|
||
state.live_transition_pending = False
|
||
if shadow:
|
||
self._reserve_live_id(shadow.trade_id)
|
||
self.strategy_by_symbol[symbol] = settings.copy()
|
||
commands = self.live_commands_by_symbol[symbol] = queue.Queue()
|
||
worker = threading.Thread(target=self._live_worker,
|
||
args=(self.live_client, symbol, settings.copy(), spec, fee_pct, shadow, commands), daemon=True)
|
||
self.live_workers[symbol] = worker
|
||
worker.start()
|
||
if position_row:
|
||
self._replace_cached_position(position_row)
|
||
self._fetch_baseline_async(symbol, self.interval_minutes)
|
||
self._subscribe_running_symbols()
|
||
self._save_account_state()
|
||
self._refresh_currency_tiles()
|
||
self.status_var.set(f"Параллельное управление включено · {symbol}")
|
||
|
||
def _select_symbol(self, symbol: str) -> None:
|
||
changed = symbol != self.symbol
|
||
if changed:
|
||
self._capture_active_symbol()
|
||
self._activate_symbol_state(symbol)
|
||
self.symbol_var.set(symbol)
|
||
self._load_currency_settings(symbol)
|
||
if symbol in self.strategy_by_symbol:
|
||
self.applied_settings = self.strategy_by_symbol[symbol].copy()
|
||
elif self.currency_settings.get(symbol):
|
||
self.applied_settings = self._strategy_for_symbol(symbol, self._safe_read_settings())
|
||
if changed:
|
||
self.chart_view_end = None
|
||
self.chart_visible_seconds = self.interval_minutes * 60 * 30
|
||
self._refresh_price_label()
|
||
self._refresh_ui()
|
||
self._draw_chart()
|
||
|
||
def _load_currency_settings(self, symbol: str) -> None:
|
||
values = self.currency_settings.get(symbol) or self.default_currency_settings
|
||
variable_map = {"stake_pct": self.stake_var, "max_adds": self.max_adds_var,
|
||
"leverage": self.leverage_var, "trigger_pct": self.trigger_var,
|
||
"add_step_pct": self.add_step_var, "stop_loss_pct": self.stop_loss_var,
|
||
"take_profit_pct": self.take_profit_var}
|
||
for key, variable in variable_map.items():
|
||
if key in values:
|
||
variable.set(str(values[key]))
|
||
|
||
def _strategy_for_symbol(self, symbol: str, fallback: dict[str, float]) -> dict[str, float]:
|
||
if not self.currency_settings.get(symbol):
|
||
return fallback.copy()
|
||
variables = (self.stake_var, self.max_adds_var, self.leverage_var, self.trigger_var,
|
||
self.add_step_var, self.stop_loss_var, self.take_profit_var)
|
||
snapshot = [(variable, variable.get()) for variable in variables]
|
||
try:
|
||
self._load_currency_settings(symbol)
|
||
parsed = self._read_settings()
|
||
parsed["initial"] = fallback["initial"]
|
||
parsed["deposit_basis"] = fallback.get("deposit_basis", fallback["initial"])
|
||
parsed["stake"] = parsed["deposit_basis"] * parsed["stake_pct"] / 100
|
||
return parsed
|
||
except ValueError:
|
||
return fallback.copy()
|
||
finally:
|
||
for variable, value in snapshot:
|
||
variable.set(value)
|
||
|
||
def _read_default_strategy(self, fallback: dict[str, float]) -> dict[str, float]:
|
||
variables = {"stake_pct": self.stake_var, "max_adds": self.max_adds_var,
|
||
"leverage": self.leverage_var, "trigger_pct": self.trigger_var,
|
||
"add_step_pct": self.add_step_var, "stop_loss_pct": self.stop_loss_var,
|
||
"take_profit_pct": self.take_profit_var}
|
||
snapshot = [(variable, variable.get()) for variable in variables.values()]
|
||
try:
|
||
for key, variable in variables.items():
|
||
variable.set(str(self.default_currency_settings.get(key, variable.get())))
|
||
parsed = self._read_settings()
|
||
parsed["initial"] = fallback["initial"]
|
||
parsed["deposit_basis"] = fallback.get("deposit_basis", fallback["initial"])
|
||
parsed["stake"] = parsed["deposit_basis"] * parsed["stake_pct"] / 100
|
||
return parsed
|
||
except ValueError:
|
||
return fallback.copy()
|
||
finally:
|
||
for variable, value in snapshot:
|
||
variable.set(value)
|
||
|
||
def _open_currency_details(self, symbol: str) -> None:
|
||
self._select_symbol(symbol)
|
||
window = self.detail_windows.get(symbol)
|
||
if window and window.winfo_exists():
|
||
self._load_detail_strategy_fields(symbol, window)
|
||
window.deiconify()
|
||
window.lift()
|
||
return
|
||
window = tk.Toplevel(self.root)
|
||
window.title(f"{symbol} · стратегия и график")
|
||
window.geometry("1100x800")
|
||
window.minsize(820, 600)
|
||
self.detail_windows[symbol] = window
|
||
if len(self.symbol_states[symbol].candles) < 10:
|
||
self._fetch_chart_candles_async(symbol, self.interval_minutes)
|
||
toolbar = ttk.Frame(window, padding=8)
|
||
toolbar.pack(fill="x")
|
||
ttk.Label(toolbar, text=symbol, font=("Segoe UI", 13, "bold")).pack(side="left")
|
||
metrics = ttk.Label(toolbar, text="")
|
||
metrics.pack(side="left", padx=16)
|
||
close_button = ttk.Button(toolbar, text="Закрыть сделку",
|
||
command=lambda s=symbol: self._close_from_detail(s), state="disabled")
|
||
close_button.pack(side="right", padx=(6, 0))
|
||
window._close_button = close_button
|
||
strategy_frame = ttk.LabelFrame(window, text=f"Стратегия · {symbol}", padding=8)
|
||
strategy_frame.pack(fill="x", padx=8, pady=(0, 6))
|
||
fields = (
|
||
("stake_pct", "Ставка, % депозита"), ("max_adds", "Количество доливок"),
|
||
("leverage", "Плечо"), ("trigger_pct", "Рост для входа, %"),
|
||
("add_step_pct", "Шаг доливки при снижении, %"),
|
||
("stop_loss_pct", "Стоп от средней цены, %"),
|
||
("take_profit_pct", "TP от средней цены, %"),
|
||
)
|
||
window._strategy_vars = {}
|
||
for index, (key, label) in enumerate(fields):
|
||
row, column = divmod(index, 4)
|
||
cell = ttk.Frame(strategy_frame)
|
||
cell.grid(row=row, column=column, sticky="w", padx=(0, 12), pady=3)
|
||
ttk.Label(cell, text=label).pack(anchor="w")
|
||
variable = tk.StringVar()
|
||
window._strategy_vars[key] = variable
|
||
ttk.Entry(cell, textvariable=variable, width=15).pack(anchor="w")
|
||
ttk.Button(strategy_frame, text="Применить для этой валюты",
|
||
command=lambda s=symbol, w=window: self._apply_detail_strategy(s, w)).grid(
|
||
row=1, column=3, sticky="e", padx=4, pady=4)
|
||
ttk.Button(strategy_frame, text="Сделать дефолтными и применить ко всем",
|
||
command=lambda s=symbol, w=window: self._apply_detail_strategy(s, w, all_symbols=True)).grid(
|
||
row=2, column=3, sticky="e", padx=4, pady=4)
|
||
window._strategy_status = tk.StringVar(value="Настройки сохраняются отдельно для этой валюты.")
|
||
ttk.Label(strategy_frame, textvariable=window._strategy_status).grid(
|
||
row=3, column=0, columnspan=4, sticky="w", pady=(4, 0))
|
||
for index in range(4):
|
||
strategy_frame.columnconfigure(index, weight=1)
|
||
self._load_detail_strategy_fields(symbol, window)
|
||
chart = tk.Canvas(window, background="#101820", highlightthickness=0)
|
||
chart.pack(fill="both", expand=True, padx=8, pady=(0, 8))
|
||
window._symbol_chart = chart
|
||
window._symbol_metrics = metrics
|
||
chart.bind("<Configure>", lambda _event, s=symbol: self._draw_detail_chart(s))
|
||
chart.bind("<MouseWheel>", lambda event, s=symbol: self._detail_chart_action(s, self._on_chart_wheel, event))
|
||
chart.bind("<Button-4>", lambda event, s=symbol: self._detail_chart_action(s, self._on_chart_wheel_linux, event, 1))
|
||
chart.bind("<Button-5>", lambda event, s=symbol: self._detail_chart_action(s, self._on_chart_wheel_linux, event, -1))
|
||
chart.bind("<ButtonPress-1>", lambda event, s=symbol: self._detail_chart_action(s, self._on_chart_press, event))
|
||
chart.bind("<B1-Motion>", lambda event, s=symbol: self._detail_chart_action(s, self._on_chart_drag, event))
|
||
chart.bind("<ButtonRelease-1>", lambda event, s=symbol: self._detail_chart_action(s, self._on_chart_release, event))
|
||
chart.bind("<Double-Button-1>", lambda event, s=symbol: self._detail_chart_action(s, self._reset_chart_view, event))
|
||
window.protocol("WM_DELETE_WINDOW", lambda s=symbol: self._close_detail(s))
|
||
self._draw_detail_chart(symbol)
|
||
|
||
def _load_detail_strategy_fields(self, symbol: str, window: tk.Toplevel) -> None:
|
||
if not hasattr(window, "_strategy_vars"):
|
||
return
|
||
values = self.currency_settings.get(symbol) or self.default_currency_settings
|
||
for key, variable in window._strategy_vars.items():
|
||
variable.set(str(values.get(key, "")))
|
||
if hasattr(window, "_strategy_status"):
|
||
window._strategy_status.set(
|
||
f"Индивидуальные настройки классического режима: {symbol}"
|
||
if self.strategy_mode == strategy.STRATEGY_CLASSIC else
|
||
f"Сейчас выбран режим «{strategy.STRATEGY_TITLES[self.strategy_mode]}»: его параметры общие для всех "
|
||
"валют («Настройки режима…»). Поля ниже относятся только к классическому режиму."
|
||
)
|
||
|
||
def _apply_detail_strategy(self, symbol: str, window: tk.Toplevel, *, all_symbols: bool = False) -> None:
|
||
if not window.winfo_exists():
|
||
return
|
||
self._ensure_symbol(symbol)
|
||
values = {key: variable.get().strip().replace(",", ".")
|
||
for key, variable in window._strategy_vars.items()}
|
||
try:
|
||
stake_pct = float(values["stake_pct"])
|
||
max_adds = float(values["max_adds"])
|
||
leverage = float(values["leverage"])
|
||
trigger = float(values["trigger_pct"])
|
||
add_step = float(values["add_step_pct"])
|
||
stop_loss = float(values["stop_loss_pct"])
|
||
take_profit = float(values["take_profit_pct"])
|
||
numeric = (stake_pct, max_adds, leverage, trigger, add_step, stop_loss, take_profit)
|
||
if any(not math.isfinite(value) for value in numeric):
|
||
raise ValueError("Все поля должны содержать конечные числа.")
|
||
if stake_pct <= 0 or stake_pct > 100:
|
||
raise ValueError("Ставка должна быть больше 0% и не больше 100%.")
|
||
if max_adds < 0 or not max_adds.is_integer() or max_adds > 100:
|
||
raise ValueError("Количество доливок должно быть целым числом от 0 до 100.")
|
||
if leverage < 1 or leverage > 100:
|
||
raise ValueError("Плечо должно быть от 1 до 100 (Bybit не принимает плечо меньше 1).")
|
||
if trigger <= 0 or add_step < 0 or stop_loss < 0 or take_profit < 0:
|
||
raise ValueError("Рост для входа должен быть больше 0; остальные проценты не могут быть отрицательными.")
|
||
if stop_loss == 0 and take_profit == 0:
|
||
raise ValueError("Укажите TP, стоп-лосс или оба уровня.")
|
||
except (KeyError, ValueError) as exc:
|
||
messagebox.showerror("Проверьте настройки", str(exc), parent=window)
|
||
return
|
||
|
||
self._capture_active_symbol()
|
||
targets = list(self.currencies) if all_symbols else [symbol]
|
||
if symbol not in targets:
|
||
targets.append(symbol)
|
||
account_settings = self.applied_settings or self._safe_read_settings()
|
||
deposit_basis = (self._current_live_deposit_basis() or account_settings.get("deposit_basis", 0)
|
||
if self.mode_var.get() == "Реальная торговля"
|
||
else account_settings.get("initial", self.initial_balance))
|
||
target_stake = deposit_basis * stake_pct / 100
|
||
if self.mode_var.get() == "Реальная торговля":
|
||
incompatible = [target for target in targets
|
||
if self._ensure_symbol(target).live_position
|
||
and self.strategy_by_symbol.get(target, {}).get("leverage") != leverage]
|
||
if incompatible:
|
||
messagebox.showerror(
|
||
"Открыта реальная позиция",
|
||
"Нельзя изменить плечо для валют с открытыми позициями: " + ", ".join(incompatible),
|
||
parent=window,
|
||
)
|
||
return
|
||
elif self.running and target_stake > self.balance:
|
||
messagebox.showerror("Проверьте ставку", "Ставка на каждый вход не может превышать свободный баланс.", parent=window)
|
||
return
|
||
|
||
for target in targets:
|
||
self._ensure_symbol(target)
|
||
settings = {
|
||
**account_settings,
|
||
"initial": account_settings.get("initial", self.initial_balance),
|
||
"deposit_basis": deposit_basis,
|
||
"stake_pct": stake_pct,
|
||
"stake": target_stake,
|
||
"max_adds": int(max_adds),
|
||
"leverage": leverage,
|
||
"trigger": trigger,
|
||
"add_step": add_step,
|
||
"stop_loss": stop_loss,
|
||
"take_profit": take_profit,
|
||
"fee": self.live_fee_pct if self.mode_var.get() == "Реальная торговля" else TAKER_FEE_PCT,
|
||
"interval": float(CANDLE_INTERVAL_MINUTES),
|
||
}
|
||
self.currency_settings[target] = values.copy()
|
||
self.strategy_by_symbol[target] = settings.copy()
|
||
if self.symbol == target:
|
||
self._load_currency_settings(target)
|
||
self.applied_settings = settings.copy()
|
||
commands = self.live_commands_by_symbol.get(target)
|
||
state = self._ensure_symbol(target)
|
||
if commands and not state.live_order_busy:
|
||
state.live_order_busy = True
|
||
commands.put(("settings", time.time(), state.last_price or 0.0, settings.copy()))
|
||
if all_symbols:
|
||
self.default_currency_settings = values.copy()
|
||
self._save_settings()
|
||
self._save_account_state()
|
||
self._refresh_currency_tiles(set(targets))
|
||
self._refresh_settings_summary()
|
||
if all_symbols:
|
||
window._strategy_status.set(
|
||
f"Настройки применены к {len(targets)} валютам и сохранены как значения по умолчанию."
|
||
)
|
||
self.status_var.set(f"Дефолтная стратегия обновлена и применена к {len(targets)} валютам")
|
||
else:
|
||
window._strategy_status.set(f"Настройки применены только для {symbol}.")
|
||
self.status_var.set(f"Индивидуальная стратегия {symbol} сохранена")
|
||
|
||
def _close_detail(self, symbol: str) -> None:
|
||
window = self.detail_windows.pop(symbol, None)
|
||
if window and window.winfo_exists():
|
||
window.destroy()
|
||
|
||
def _close_from_detail(self, symbol: str) -> None:
|
||
self._select_symbol(symbol)
|
||
self._manual_close_position()
|
||
|
||
def _draw_detail_chart(self, symbol: str) -> None:
|
||
window = self.detail_windows.get(symbol)
|
||
if not window or not window.winfo_exists():
|
||
return
|
||
self._capture_active_symbol()
|
||
active_symbol = self.symbol
|
||
active_canvas = self.canvas
|
||
self._activate_symbol_state(symbol)
|
||
self.canvas = window._symbol_chart
|
||
try:
|
||
self._draw_chart()
|
||
state = self._ensure_symbol(symbol)
|
||
pct = self.ticker_24h.get(symbol)
|
||
position = state.live_position if self.mode_var.get() == "Реальная торговля" else state.position
|
||
exchange_position = next((row for row in self.live_positions if row.get("symbol") == symbol
|
||
and float(row.get("size") or 0) > 0), None)
|
||
window._symbol_metrics.configure(text=(
|
||
f"Цена {self._fmt_price(state.last_price or self.ticker_prices.get(symbol)) if (state.last_price or self.ticker_prices.get(symbol)) else '—'} · "
|
||
f"24 ч {pct:+.2f}%" if pct is not None else "24 ч —"
|
||
) + (f" · позиция {position.entry_price:g}" if position else
|
||
f" · Bybit {exchange_position.get('side')} · P&L {float(exchange_position.get('unrealisedPnl') or 0):+.2f}"
|
||
if exchange_position else " · без позиции"))
|
||
window._close_button.configure(state="normal" if self.running and position else "disabled")
|
||
finally:
|
||
self.canvas = active_canvas
|
||
self._activate_symbol_state(active_symbol)
|
||
|
||
def _detail_chart_action(self, symbol: str, callback, *args):
|
||
window = self.detail_windows.get(symbol)
|
||
if not window or not window.winfo_exists():
|
||
return
|
||
active_symbol = self.symbol
|
||
active_canvas = self.canvas
|
||
self._capture_active_symbol()
|
||
self._activate_symbol_state(symbol)
|
||
self.canvas = window._symbol_chart
|
||
try:
|
||
callback(*args)
|
||
finally:
|
||
self._capture_active_symbol()
|
||
self.canvas = active_canvas
|
||
self._activate_symbol_state(active_symbol)
|
||
self._refresh_currency_tiles()
|
||
return "break"
|
||
|
||
def _refresh_currency_tiles(self, only_symbols: set[str] | None = None) -> None:
|
||
if not hasattr(self, "tile_widgets"):
|
||
return
|
||
for symbol, widgets in list(self.tile_widgets.items()):
|
||
if only_symbols is not None and symbol not in only_symbols:
|
||
continue
|
||
state = self._ensure_symbol(symbol)
|
||
if not widgets["price"].winfo_exists():
|
||
continue
|
||
widgets["enabled"].set(symbol in self.enabled_symbols)
|
||
current_price = state.last_price or self.ticker_prices.get(symbol)
|
||
widgets["price"].configure(text=f"Цена: {self._fmt_price(current_price) if current_price else '—'}")
|
||
pct = self.ticker_24h.get(symbol)
|
||
widgets["change"].configure(text=f"24 ч: {pct:+.2f}%" if pct is not None else "24 ч: —",
|
||
foreground="#13843b" if pct and pct > 0 else "#c62828" if pct and pct < 0 else "")
|
||
session_pnl = sum(t.net_pnl for t in self.trades if t.symbol == symbol and t.opened_at >= getattr(self, "session_started_at", 0))
|
||
session_pnl += sum(t.net_pnl for t in self.live_trades if t.symbol == symbol and t.opened_at >= getattr(self, "session_started_at", 0))
|
||
account_pnl = sum(t.net_pnl for t in self.trades if t.symbol == symbol)
|
||
local_live_total = sum(t.net_pnl for t in self.live_trades if t.symbol == symbol)
|
||
exchange_live_total = sum(float(row.get("closedPnl") or 0) for row in self.live_closed_pnl
|
||
if row.get("symbol") == symbol)
|
||
account_pnl += max(local_live_total, exchange_live_total)
|
||
state_position = state.live_position if self.mode_var.get() == "Реальная торговля" else state.position
|
||
exchange_position = next((row for row in self.live_positions if row.get("symbol") == symbol
|
||
and float(row.get("size") or 0) > 0), None)
|
||
if state_position and state.last_price:
|
||
current_unrealized = strategy.unrealized_pnl(state_position.side, state_position.entry_price,
|
||
state.last_price, state_position.qty)
|
||
if state.live_position:
|
||
current_unrealized = float((state.live_position_info or {}).get("unrealisedPnl") or current_unrealized)
|
||
session_pnl += current_unrealized
|
||
account_pnl += current_unrealized
|
||
elif exchange_position:
|
||
exchange_unrealized = float(exchange_position.get("unrealisedPnl") or 0)
|
||
account_pnl += exchange_unrealized
|
||
widgets["session"].configure(text=f"Запуск: {session_pnl:+.2f} USDT")
|
||
widgets["account"].configure(text=f"Аккаунт: {account_pnl:+.2f} USDT")
|
||
pos = state.live_position if self.mode_var.get() == "Реальная торговля" else state.position
|
||
if pos:
|
||
status_text = ("Сделка · выключится после закрытия"
|
||
if symbol in self.rotation_pending_disable else
|
||
f"{pos.side.upper()} · стоп {self._fmt_price(pos.stop_price)}"
|
||
if pos.mode != strategy.STRATEGY_CLASSIC else
|
||
f"В позиции · {pos.add_count + 1} входов")
|
||
elif state.mode_signal and self.running and self.mode_var.get() == "Симуляция":
|
||
status_text = f"Сигнал {state.mode_signal['side'].upper()} · ждёт входа"
|
||
elif exchange_position:
|
||
status_text = ("Сделка · выключится после закрытия"
|
||
if symbol in self.rotation_pending_disable else
|
||
f"Bybit {exchange_position.get('side')} · P&L {float(exchange_position.get('unrealisedPnl') or 0):+.2f}")
|
||
else:
|
||
status_text = ("Выключена" if symbol in self.rotation_pending_disable else
|
||
"В торгах" if symbol in self.enabled_symbols else "Выключена")
|
||
widgets["status"].configure(text=status_text)
|
||
if only_symbols is None:
|
||
self._layout_currency_tiles()
|
||
|
||
def _poll_ticker_24h(self) -> None:
|
||
if not self._ticker_poll_busy:
|
||
self._ticker_poll_busy = True
|
||
def worker() -> None:
|
||
try:
|
||
snapshot, source, funding = self._fetch_ticker_snapshot()
|
||
self.events.put(("ticker_24h", snapshot, source, funding))
|
||
except Exception as exc:
|
||
# Keep market-data failures visible: otherwise the scanner appears
|
||
# connected via WebSocket while its separate REST feed is empty.
|
||
self.events.put(("ticker_24h_error", str(exc)))
|
||
finally:
|
||
self._ticker_poll_busy = False
|
||
threading.Thread(target=worker, daemon=True).start()
|
||
if self.root.winfo_exists():
|
||
self.root.after(15000, self._poll_ticker_24h)
|
||
|
||
@staticmethod
|
||
def _fetch_ticker_snapshot() -> tuple[dict[str, tuple[float, float, float]], str, dict[str, float]]:
|
||
"""(symbol → (price, 24h change %, 24h turnover), host, symbol → current funding rate %)."""
|
||
errors = []
|
||
for host in PUBLIC_MARKET_API_HOSTS:
|
||
try:
|
||
request = urllib.request.Request(
|
||
f"{host}/v5/market/tickers?category=linear",
|
||
headers={"User-Agent": "RealtimePaperSimulator/1.0"},
|
||
)
|
||
with urllib.request.urlopen(request, timeout=10) as response:
|
||
payload = json.loads(response.read().decode("utf-8"))
|
||
if payload.get("retCode") != 0:
|
||
raise RuntimeError(f"Bybit retCode {payload.get('retCode')}: {payload.get('retMsg', 'ошибка запроса')}")
|
||
snapshot = {}
|
||
funding: dict[str, float] = {}
|
||
for row in payload.get("result", {}).get("list", []):
|
||
symbol = str(row.get("symbol") or "").upper()
|
||
if not symbol.endswith("USDT"):
|
||
continue
|
||
try:
|
||
snapshot[symbol] = (
|
||
float(row.get("lastPrice") or 0),
|
||
float(row.get("price24hPcnt") or 0) * 100,
|
||
float(row.get("turnover24h") or 0),
|
||
)
|
||
if row.get("fundingRate") not in (None, ""):
|
||
funding[symbol] = float(row["fundingRate"]) * 100
|
||
except (TypeError, ValueError):
|
||
continue
|
||
if not snapshot:
|
||
raise RuntimeError("Bybit вернул пустой список USDT-контрактов")
|
||
return snapshot, host, funding
|
||
except Exception as exc:
|
||
errors.append(f"{host}: {exc}")
|
||
raise RuntimeError("Не удалось загрузить тикеры. " + " · ".join(errors))
|
||
|
||
def _symbol_has_open_position(self, symbol: str) -> bool:
|
||
state = self.symbol_states.get(symbol)
|
||
if state and (state.position is not None or state.live_position is not None):
|
||
return True
|
||
return any(row.get("symbol") == symbol and float(row.get("size") or 0) > 0
|
||
for row in self.live_positions)
|
||
|
||
def _finish_auto_retirement(self, symbol: str) -> bool:
|
||
if symbol not in self.rotation_pending_disable or self._symbol_has_open_position(symbol):
|
||
return False
|
||
self.rotation_pending_disable.discard(symbol)
|
||
self.enabled_symbols.discard(symbol)
|
||
if self.running:
|
||
self._subscribe_running_symbols()
|
||
self._save_settings()
|
||
self._render_currency_tiles()
|
||
return True
|
||
|
||
def _auto_enable_symbol(self, symbol: str) -> bool:
|
||
if symbol in self.enabled_symbols:
|
||
self.rotation_pending_disable.discard(symbol)
|
||
return False
|
||
if time.monotonic() < self.auto_symbol_retry_after.get(symbol, 0.0):
|
||
return False
|
||
self._ensure_symbol(symbol)
|
||
self.enabled_symbols.add(symbol)
|
||
self.rotation_pending_disable.discard(symbol)
|
||
base = self.applied_settings or self._safe_read_settings()
|
||
defaults = self._read_default_strategy(base)
|
||
settings = self._strategy_for_symbol(symbol, defaults)
|
||
self.strategy_by_symbol[symbol] = settings.copy()
|
||
if self.running:
|
||
if self.mode_var.get() == "Реальная торговля":
|
||
if symbol not in self.live_commands_by_symbol and symbol not in self.live_preparing_symbols:
|
||
self.auto_enabling_symbols.add(symbol)
|
||
self._begin_live_additional_symbol(symbol)
|
||
else:
|
||
self._fetch_baseline_async(symbol, self.interval_minutes)
|
||
return True
|
||
|
||
def _maybe_auto_rotate_currencies(self) -> None:
|
||
if not self.running or self.mode_var.get() not in ("Симуляция", "Реальная торговля"):
|
||
return
|
||
now = time.monotonic()
|
||
if now < self.next_auto_currency_scan_at:
|
||
return
|
||
try:
|
||
threshold = float(self.auto_currency_growth_var.get().strip().replace(",", "."))
|
||
except (ValueError, tk.TclError):
|
||
self.auto_currency_status_var.set("Ошибка: проверьте порог роста за 24 ч")
|
||
self.next_auto_currency_scan_at = now + AUTO_CURRENCY_SCAN_SECONDS
|
||
return
|
||
if not math.isfinite(threshold) or not 0 <= threshold <= 1000:
|
||
self.auto_currency_status_var.set("Ошибка: порог должен быть от 0 до 1000%")
|
||
self.next_auto_currency_scan_at = now + AUTO_CURRENCY_SCAN_SECONDS
|
||
return
|
||
if not self.ticker_turnover_24h:
|
||
self.auto_currency_status_var.set("Ожидаю котировки Bybit REST…")
|
||
self.next_auto_currency_scan_at = now + 30
|
||
return
|
||
self.next_auto_currency_scan_at = now + AUTO_CURRENCY_SCAN_SECONDS
|
||
ranked = sorted(
|
||
((symbol, turnover) for symbol, turnover in self.ticker_turnover_24h.items()
|
||
if re.fullmatch(r"[A-Z0-9]+USDT", symbol) and turnover > 0),
|
||
key=lambda item: item[1], reverse=True,
|
||
)[:TOP_LIQUID_SYMBOLS]
|
||
top_symbols = {symbol for symbol, _turnover in ranked}
|
||
eligible = {symbol for symbol in top_symbols
|
||
if self.ticker_24h.get(symbol, float("-inf")) > threshold}
|
||
for symbol in list(self.auto_symbol_retry_after):
|
||
if symbol not in eligible:
|
||
self.auto_symbol_retry_after.pop(symbol, None)
|
||
observed = set(self.ticker_turnover_24h)
|
||
removed = 0
|
||
deferred = 0
|
||
changed = False
|
||
for symbol in list(self.enabled_symbols):
|
||
# Missing ticker data is treated as a temporary API omission, not as a reason to retire a pair.
|
||
if symbol not in observed or symbol in eligible:
|
||
if symbol in eligible:
|
||
self.rotation_pending_disable.discard(symbol)
|
||
continue
|
||
if self._symbol_has_open_position(symbol):
|
||
self.rotation_pending_disable.add(symbol)
|
||
deferred += 1
|
||
else:
|
||
self.rotation_pending_disable.discard(symbol)
|
||
self.enabled_symbols.discard(symbol)
|
||
removed += 1
|
||
changed = True
|
||
added = 0
|
||
for symbol in sorted(eligible):
|
||
if symbol not in self.enabled_symbols:
|
||
if self._auto_enable_symbol(symbol):
|
||
added += 1
|
||
changed = True
|
||
if changed:
|
||
if self.mode_var.get() == "Симуляция":
|
||
self._subscribe_running_symbols()
|
||
self._save_settings()
|
||
self._refresh_currency_tiles()
|
||
self.auto_currency_status_var.set(
|
||
f"Подходят: {len(eligible)} · новых: {added} · отключено: {removed} · ждут закрытия: {deferred}"
|
||
)
|
||
|
||
def _begin_startup_currency_filter(self, mode: str, threshold: float) -> None:
|
||
"""Fetch fresh Bybit tickers before enabling any strategy entries."""
|
||
if self.startup_currency_filter_busy:
|
||
return
|
||
self.startup_currency_filter_busy = True
|
||
self.start_btn.configure(state="disabled")
|
||
self.mode_combo.configure(state="disabled")
|
||
self.status_var.set(f"Проверяю рост за 24 ч перед запуском · порог {threshold:g}%…")
|
||
|
||
def worker() -> None:
|
||
try:
|
||
snapshot, source, funding = self._fetch_ticker_snapshot()
|
||
self.ticker_funding_pct.update(funding)
|
||
self.events.put(("startup_currency_filter_ready", mode, threshold, snapshot, source))
|
||
except Exception as exc:
|
||
self.events.put(("startup_currency_filter_failed", mode, str(exc)))
|
||
|
||
threading.Thread(target=worker, daemon=True).start()
|
||
|
||
def _apply_startup_currency_filter(
|
||
self, mode: str, threshold: float,
|
||
snapshot: dict[str, tuple[float, float, float]], source: str,
|
||
) -> None:
|
||
for symbol, (price, change, turnover) in snapshot.items():
|
||
self.ticker_prices[symbol] = price
|
||
self.ticker_24h[symbol] = change
|
||
self.ticker_turnover_24h[symbol] = turnover
|
||
self.ticker_data_source = source
|
||
|
||
ranked = sorted(
|
||
((symbol, row[2]) for symbol, row in snapshot.items()
|
||
if re.fullmatch(r"[A-Z0-9]+USDT", symbol) and row[2] > 0),
|
||
key=lambda item: item[1], reverse=True,
|
||
)[:TOP_LIQUID_SYMBOLS]
|
||
top_symbols = {symbol for symbol, _turnover in ranked}
|
||
eligible = {symbol for symbol in top_symbols if snapshot[symbol][1] > threshold}
|
||
known_symbols = set(self.currencies) | set(self.symbol_states)
|
||
known_symbols.update(str(row.get("symbol") or "").upper() for row in self.live_positions)
|
||
open_symbols = {symbol for symbol in known_symbols if self._symbol_has_open_position(symbol)}
|
||
|
||
# Existing positions remain managed even when their currency misses the entry filter.
|
||
selected = eligible | open_symbols
|
||
self.rotation_pending_disable = open_symbols - eligible
|
||
self.enabled_symbols = set(selected)
|
||
for symbol in sorted(eligible):
|
||
self._ensure_symbol(symbol)
|
||
self._save_settings()
|
||
self._render_currency_tiles()
|
||
self._refresh_currency_tiles()
|
||
self.auto_currency_status_var.set(
|
||
f"Предстартовый отбор · топ-{len(top_symbols)} по обороту · порог > {threshold:g}% · подходит {len(eligible)}"
|
||
)
|
||
self.startup_currency_filter_approved_for = mode
|
||
if not selected:
|
||
self.startup_currency_filter_approved_for = None
|
||
self.start_btn.configure(state="normal")
|
||
self.status_var.set(f"Запуск отменён: в топ-{TOP_LIQUID_SYMBOLS} нет валют с ростом выше {threshold:g}% за 24 ч")
|
||
messagebox.showwarning(
|
||
"Нет валют для запуска",
|
||
f"В топ-{TOP_LIQUID_SYMBOLS} по обороту сейчас нет валют с ростом выше {threshold:g}% за 24 часа.",
|
||
)
|
||
return
|
||
self.start_btn.configure(state="normal")
|
||
self.status_var.set(f"Отбор завершён · подходит {len(eligible)} валют · продолжаю запуск")
|
||
self.start()
|
||
|
||
@staticmethod
|
||
def _ws_send_topics(ws, op: str, symbols: list[str]) -> None:
|
||
# Bybit accepts a limited number of args per request; send in chunks of 10.
|
||
for index in range(0, len(symbols), 10):
|
||
chunk = symbols[index:index + 10]
|
||
ws.send(json.dumps({"op": op, "args": [f"publicTrade.{symbol}" for symbol in chunk]}))
|
||
|
||
def _subscribe_running_symbols(self) -> None:
|
||
symbols = sorted(self.enabled_symbols | {s for s, state in self.symbol_states.items()
|
||
if state.position or state.live_position})
|
||
self.ws_symbols = symbols
|
||
app = self.ws_app
|
||
sock = getattr(app, "sock", None) if app else None
|
||
if sock is not None and getattr(sock, "connected", False):
|
||
# Change topics on the live socket so trades of other pairs are not lost
|
||
# during a reconnect (open positions keep receiving prices).
|
||
try:
|
||
with self._ws_lock:
|
||
wanted = set(symbols)
|
||
added = sorted(wanted - self.ws_subscribed)
|
||
removed = sorted(self.ws_subscribed - wanted)
|
||
if removed:
|
||
self._ws_send_topics(app, "unsubscribe", removed)
|
||
if added:
|
||
self._ws_send_topics(app, "subscribe", added)
|
||
self.ws_subscribed = wanted
|
||
except Exception:
|
||
try:
|
||
app.close() # fall back to a reconnect, which resubscribes everything
|
||
except Exception:
|
||
pass
|
||
if self.running and symbols and not (self.ws_thread and self.ws_thread.is_alive()):
|
||
self.ws_thread = threading.Thread(target=self._ws_worker, args=(symbols,), daemon=True)
|
||
self.ws_thread.start()
|
||
|
||
def _build_settings_window(self) -> None:
|
||
self.settings_window = tk.Toplevel(self.root)
|
||
self.settings_window.title("Настройки стратегии и симуляции")
|
||
self.settings_window.geometry("1200x700")
|
||
self.settings_window.minsize(1000, 600)
|
||
self.settings_window.withdraw()
|
||
self.settings_window.protocol("WM_DELETE_WINDOW", self.settings_window.withdraw)
|
||
|
||
body = ttk.Frame(self.settings_window, padding=12)
|
||
body.pack(fill="both", expand=True)
|
||
controls = ttk.LabelFrame(body, text="Параметры", padding=10)
|
||
controls.pack(fill="x", pady=(0, 10))
|
||
|
||
self.symbol_var = tk.StringVar(value="BTCUSDT")
|
||
symbol_cell = ttk.Frame(controls)
|
||
symbol_cell.grid(row=0, column=0, sticky="w", padx=(0, 10), pady=2)
|
||
ttk.Label(symbol_cell, text="Тикер Bybit").pack(anchor="w")
|
||
ttk.Entry(symbol_cell, textvariable=self.symbol_var, width=14).pack(anchor="w")
|
||
self.symbol_var.trace_add("write", self._schedule_settings_save)
|
||
|
||
self.initial_var = self._setting(controls, "Начальный капитал, USDT", "5000", 0, 2)
|
||
self.stake_var = self._setting(controls, "Ставка на каждый вход, % стартового депозита", "5", 0, 4)
|
||
self.max_adds_var = self._setting(controls, "Максимум доливок, шт. (0 = выкл.)", "2", 0, 6)
|
||
self.leverage_var = self._setting(controls, "Плечо", "1", 1, 0)
|
||
self.trigger_var = self._setting(controls, "Рост от прошлой 1-мин свечи для входа, %", "0.2", 1, 2)
|
||
self.add_step_var = self._setting(controls, "Шаг доливки при снижении, %", "1.5", 1, 4)
|
||
self.stop_loss_var = self._setting(controls, "Стоп от средней цены, %", "0", 2, 0)
|
||
self.take_profit_var = self._setting(controls, "TP от средней цены, %", "10", 2, 2)
|
||
self.apply_btn = ttk.Button(controls, text="Применить", command=self.apply_settings)
|
||
self.apply_btn.grid(row=2, column=4, sticky="w", padx=(8, 0), pady=2)
|
||
ttk.Label(controls, text="Первый вход — по росту от закрытия прошлой минутной свечи. Доливки срабатывают при снижении от последней покупки на заданный шаг, пока не достигнут их лимит. Максимум 0 или шаг 0 отключает доливки. TP и стоп применяются ко всему объёму от средневзвешенной цены. В симуляции ставка считается от начального капитала, в реальной торговле — от первого загруженного USDT-депозита аккаунта.").grid(
|
||
row=3, column=0, columnspan=8, sticky="w", pady=(6, 0)
|
||
)
|
||
|
||
preview = ttk.LabelFrame(body, text="Как настройки влияют на входы и выходы", padding=6)
|
||
preview.pack(fill="both", expand=True)
|
||
self.preview_canvas = tk.Canvas(preview, background="#101820", highlightthickness=0, height=390)
|
||
self.preview_canvas.pack(fill="both", expand=True)
|
||
self.preview_canvas.bind("<Configure>", lambda _event: self._refresh_strategy_preview())
|
||
for variable in (self.trigger_var, self.add_step_var, self.max_adds_var, self.stop_loss_var, self.take_profit_var, self.stake_var, self.leverage_var):
|
||
variable.trace_add("write", lambda *_args: self._refresh_strategy_preview())
|
||
self._refresh_strategy_preview()
|
||
|
||
def open_settings(self) -> None:
|
||
self.settings_window.deiconify()
|
||
self.settings_window.lift()
|
||
self.settings_window.focus_force()
|
||
self._refresh_strategy_preview()
|
||
|
||
def _build_live_settings_window(self) -> None:
|
||
self.live_settings_window = tk.Toplevel(self.root)
|
||
self.live_settings_window.title("Настройки подключения Bybit")
|
||
self.live_settings_window.geometry("700x340")
|
||
self.live_settings_window.resizable(False, False)
|
||
self.live_settings_window.withdraw()
|
||
self.live_settings_window.protocol("WM_DELETE_WINDOW", self.live_settings_window.withdraw)
|
||
body = ttk.Frame(self.live_settings_window, padding=14)
|
||
body.pack(fill="both", expand=True)
|
||
ttk.Label(body, text="API key").grid(row=0, column=0, sticky="w", pady=5)
|
||
self.api_key_entry = ttk.Entry(body, textvariable=self.api_key_var, width=58)
|
||
self.api_key_entry.grid(row=0, column=1, sticky="ew", pady=5)
|
||
ttk.Button(body, text="Вставить", command=lambda: self._paste_into(self.api_key_entry)).grid(row=0, column=2, padx=(6, 0))
|
||
ttk.Label(body, text="API secret").grid(row=1, column=0, sticky="w", pady=5)
|
||
self.api_secret_entry = ttk.Entry(body, textvariable=self.api_secret_var, width=58, show="•")
|
||
self.api_secret_entry.grid(row=1, column=1, sticky="ew", pady=5)
|
||
ttk.Button(body, text="Вставить", command=lambda: self._paste_into(self.api_secret_entry)).grid(row=1, column=2, padx=(6, 0))
|
||
ttk.Checkbutton(body, text="Testnet (тестовая среда, без реальных средств)", variable=self.testnet_var,
|
||
command=self._schedule_settings_save).grid(row=2, column=1, sticky="w", pady=(8, 3))
|
||
ttk.Label(body, text="Режим Mainnet отправляет реальные рыночные ордера.", foreground="#a52626").grid(
|
||
row=3, column=1, sticky="w", pady=2
|
||
)
|
||
ttk.Label(body, text="Создайте ключ с чтением аккаунта и торговлей контрактами, без права вывода средств.",
|
||
wraplength=560).grid(row=4, column=1, sticky="w", pady=2)
|
||
ttk.Label(body, text="Сохранённые ключи шифруются Windows DPAPI и доступны только этому пользователю Windows.",
|
||
wraplength=560).grid(row=5, column=1, sticky="w", pady=2)
|
||
ttk.Label(body, textvariable=self.credentials_status_var, wraplength=560).grid(
|
||
row=6, column=1, sticky="w", pady=(8, 2)
|
||
)
|
||
actions = ttk.Frame(body)
|
||
actions.grid(row=7, column=1, columnspan=2, sticky="e", pady=(8, 0))
|
||
ttk.Button(actions, text="Сохранить ключи", command=self._save_api_credentials).pack(side="left", padx=(0, 6))
|
||
ttk.Button(actions, text="Удалить сохранённые", command=self._delete_api_credentials).pack(side="left", padx=(0, 6))
|
||
ttk.Button(actions, text="Готово", command=self.live_settings_window.withdraw).pack(side="left")
|
||
body.columnconfigure(1, weight=1)
|
||
|
||
def _load_saved_credentials(self) -> None:
|
||
try:
|
||
credentials = load_credentials()
|
||
except CredentialStoreError as exc:
|
||
self.credentials_status_var.set(str(exc))
|
||
return
|
||
if credentials:
|
||
self.api_key_var.set(credentials["api_key"])
|
||
self.api_secret_var.set(credentials["api_secret"])
|
||
self.credentials_status_var.set("Зашифрованные ключи загружены из хранилища Windows.")
|
||
|
||
def _save_api_credentials(self) -> None:
|
||
try:
|
||
save_credentials(self.api_key_var.get(), self.api_secret_var.get())
|
||
except CredentialStoreError as exc:
|
||
self.credentials_status_var.set(str(exc))
|
||
messagebox.showerror("Не удалось сохранить ключи", str(exc), parent=self.live_settings_window)
|
||
return
|
||
self.credentials_status_var.set("Ключи сохранены в зашифрованном виде для текущего пользователя Windows.")
|
||
|
||
def _delete_api_credentials(self) -> None:
|
||
try:
|
||
delete_credentials()
|
||
except CredentialStoreError as exc:
|
||
self.credentials_status_var.set(str(exc))
|
||
messagebox.showerror("Не удалось удалить ключи", str(exc), parent=self.live_settings_window)
|
||
return
|
||
self.api_key_var.set("")
|
||
self.api_secret_var.set("")
|
||
self.credentials_status_var.set("Сохранённые ключи удалены.")
|
||
|
||
@staticmethod
|
||
def _paste_into(entry: ttk.Entry) -> None:
|
||
entry.focus_set()
|
||
entry.event_generate("<<Paste>>")
|
||
|
||
def open_live_settings(self) -> None:
|
||
self.live_settings_window.deiconify()
|
||
self.live_settings_window.lift()
|
||
self.live_settings_window.focus_force()
|
||
|
||
# ----- strategy modes (classic / A / B) -------------------------------------------------
|
||
|
||
def _mode_from_title(self, title: str) -> str:
|
||
return next((mode for mode, text in strategy.STRATEGY_TITLES.items() if text == title),
|
||
strategy.STRATEGY_CLASSIC)
|
||
|
||
def _on_strategy_mode_selected(self, _event: tk.Event | None = None) -> None:
|
||
selected = self._mode_from_title(self.strategy_mode_var.get())
|
||
if selected == self.strategy_mode:
|
||
return
|
||
if self.running or self.historical_running or self.live_preflight:
|
||
self.strategy_mode_var.set(strategy.STRATEGY_TITLES[self.strategy_mode])
|
||
messagebox.showinfo("Режим стратегии", "Остановите торговлю или прогон, затем смените режим стратегии.")
|
||
return
|
||
self.strategy_mode = selected
|
||
for state in self.symbol_states.values():
|
||
state.mode_signal = None
|
||
state.mode_signal_bucket = 0
|
||
self._save_settings()
|
||
self._update_strategy_hint()
|
||
self._refresh_settings_summary()
|
||
if self.strategy_window is not None and self.strategy_window.winfo_exists():
|
||
self._build_strategy_settings_content()
|
||
self.status_var.set(f"Режим стратегии: {strategy.STRATEGY_TITLES[selected]}")
|
||
|
||
def _update_strategy_hint(self) -> None:
|
||
if not hasattr(self, "strategy_hint_var"):
|
||
return
|
||
if self.strategy_mode == strategy.STRATEGY_CLASSIC:
|
||
text = "настройки — в плитке каждой валюты"
|
||
else:
|
||
try:
|
||
params = self._strategy_mode_params(self.strategy_mode)
|
||
text = (f"ставка {params['stake_pct']:g}% × плечо {params['leverage']:g} · "
|
||
f"свечи {int(params['timeframe_min'])} мин · общие для всех валют")
|
||
except ValueError as exc:
|
||
text = f"ошибка настроек: {exc}"
|
||
if self.mode_var.get() == "Реальная торговля":
|
||
text += " · в реальной торговле доступна только классика"
|
||
self.strategy_hint_var.set(text)
|
||
|
||
def _strategy_mode_params(self, mode: str | None = None) -> dict[str, float]:
|
||
mode = mode or self.strategy_mode
|
||
return strategy.parse_mode_params(mode, self.mode_settings.get(mode, {}))
|
||
|
||
def open_strategy_settings(self) -> None:
|
||
window = self.strategy_window
|
||
if window is None or not window.winfo_exists():
|
||
window = tk.Toplevel(self.root)
|
||
window.title("Настройки режима стратегии")
|
||
window.geometry("980x600")
|
||
window.minsize(760, 480)
|
||
self.strategy_window = window
|
||
top = ttk.Frame(window, padding=(12, 10, 12, 4))
|
||
top.pack(fill="x")
|
||
ttk.Label(top, text="Режим:").pack(side="left")
|
||
combo = ttk.Combobox(top, textvariable=self.strategy_mode_var, state="readonly", width=44,
|
||
values=[strategy.STRATEGY_TITLES[mode] for mode in strategy.STRATEGY_MODES])
|
||
combo.pack(side="left", padx=6)
|
||
combo.bind("<<ComboboxSelected>>", self._on_strategy_mode_selected)
|
||
window._content = ttk.Frame(window, padding=(12, 4, 12, 12))
|
||
window._content.pack(fill="both", expand=True)
|
||
self._build_strategy_settings_content()
|
||
window.deiconify()
|
||
window.lift()
|
||
window.focus_force()
|
||
|
||
def _build_strategy_settings_content(self) -> None:
|
||
window = self.strategy_window
|
||
if window is None or not window.winfo_exists():
|
||
return
|
||
content = window._content
|
||
for child in content.winfo_children():
|
||
child.destroy()
|
||
mode = self.strategy_mode
|
||
ttk.Label(content, text=strategy.STRATEGY_TITLES[mode], font=("Segoe UI", 12, "bold")).pack(anchor="w")
|
||
ttk.Label(content, text=strategy.STRATEGY_DESCRIPTIONS[mode], wraplength=930, justify="left").pack(
|
||
anchor="w", pady=(4, 10))
|
||
grid = ttk.LabelFrame(content, text="Параметры режима", padding=8)
|
||
grid.pack(fill="x")
|
||
window._strategy_vars = {}
|
||
if mode == strategy.STRATEGY_CLASSIC:
|
||
fields = [("stake_pct", "Ставка, % депозита"), ("max_adds", "Количество доливок"),
|
||
("leverage", "Плечо"), ("trigger_pct", "Рост для входа, %"),
|
||
("add_step_pct", "Шаг доливки при снижении, %"),
|
||
("stop_loss_pct", "Стоп от средней цены, %"), ("take_profit_pct", "TP от средней цены, %")]
|
||
values = self.default_currency_settings
|
||
else:
|
||
fields = [(key, label) for key, label, *_rest in strategy.MODE_FIELDS[mode]]
|
||
values = self.mode_settings.get(mode, {})
|
||
for index, (key, label) in enumerate(fields):
|
||
row, column = divmod(index, 3)
|
||
cell = ttk.Frame(grid)
|
||
cell.grid(row=row, column=column, sticky="w", padx=(0, 18), pady=3)
|
||
ttk.Label(cell, text=label).pack(anchor="w")
|
||
variable = tk.StringVar(value=str(values.get(key, "")))
|
||
window._strategy_vars[key] = variable
|
||
ttk.Entry(cell, textvariable=variable, width=18).pack(anchor="w")
|
||
for column in range(3):
|
||
grid.columnconfigure(column, weight=1)
|
||
actions = ttk.Frame(content)
|
||
actions.pack(fill="x", pady=(10, 0))
|
||
if mode == strategy.STRATEGY_CLASSIC:
|
||
ttk.Button(actions, text="Применить ко всем валютам",
|
||
command=lambda: self._apply_detail_strategy(self.symbol, window, all_symbols=True)).pack(side="left")
|
||
else:
|
||
ttk.Button(actions, text="Применить", command=self._apply_strategy_mode_settings).pack(side="left")
|
||
ttk.Button(actions, text="Рекомендуемые значения", command=self._reset_strategy_mode_fields).pack(side="left", padx=6)
|
||
ttk.Button(actions, text="Закрыть", command=window.withdraw).pack(side="right")
|
||
window._strategy_status = tk.StringVar(value=(
|
||
"Шаблон классики: применяется ко всем валютам, индивидуальные настройки задаются в плитке валюты."
|
||
if mode == strategy.STRATEGY_CLASSIC else
|
||
"Параметры общие для всех валют. Стоп и цели открытых позиций рассчитываются при входе; "
|
||
"доля частичной фиксации, безубыток, трейлинг и время удержания берутся из текущих настроек."
|
||
))
|
||
ttk.Label(content, textvariable=window._strategy_status, wraplength=930, justify="left").pack(
|
||
anchor="w", pady=(8, 0))
|
||
if mode != strategy.STRATEGY_CLASSIC:
|
||
ttk.Label(content, wraplength=930, justify="left", foreground="#55606b", text=(
|
||
"R — расстояние от входа до начального стопа. Funding указывается в процентах за расчётный период "
|
||
"(0.01 = 0.01%). Режимы A и B работают в симуляции и историческом прогоне; реальная торговля "
|
||
"использует только классический режим. Лимит одновременных позиций и автоподбор валют — общие."
|
||
)).pack(anchor="w", pady=(6, 0))
|
||
|
||
def _reset_strategy_mode_fields(self) -> None:
|
||
window = self.strategy_window
|
||
if window is None or not window.winfo_exists():
|
||
return
|
||
defaults = (DEFAULT_CURRENCY_STRATEGY if self.strategy_mode == strategy.STRATEGY_CLASSIC
|
||
else {key: f"{value:g}" for key, value in strategy.MODE_DEFAULTS[self.strategy_mode].items()})
|
||
for key, variable in window._strategy_vars.items():
|
||
if key in defaults:
|
||
variable.set(str(defaults[key]))
|
||
window._strategy_status.set("Подставлены рекомендуемые значения. Нажмите «Применить», чтобы сохранить.")
|
||
|
||
def _apply_strategy_mode_settings(self) -> None:
|
||
window = self.strategy_window
|
||
mode = self.strategy_mode
|
||
if window is None or not window.winfo_exists() or mode == strategy.STRATEGY_CLASSIC:
|
||
return
|
||
raw = {key: variable.get().strip().replace(",", ".") for key, variable in window._strategy_vars.items()}
|
||
try:
|
||
strategy.parse_mode_params(mode, raw)
|
||
except ValueError as exc:
|
||
messagebox.showerror("Проверьте настройки режима", str(exc), parent=window)
|
||
return
|
||
self.mode_settings[mode] = raw
|
||
self._save_settings()
|
||
self._update_strategy_hint()
|
||
self._refresh_settings_summary()
|
||
window._strategy_status.set(f"Настройки режима сохранены: {strategy.STRATEGY_TITLES[mode]}.")
|
||
self.status_var.set("Настройки режима стратегии применены")
|
||
|
||
def _on_mode_change(self, _event: tk.Event | None = None) -> None:
|
||
selected = self.mode_var.get()
|
||
if self.running or self.historical_running or self.live_preflight:
|
||
self.mode_var.set("Реальная торговля" if self.live_client else "Симуляция")
|
||
return
|
||
if selected == "Реальная торговля" and any(state.position for state in self.symbol_states.values()):
|
||
messagebox.showerror("Открыта симуляционная сделка", "Сначала закройте позицию в режиме симуляции.")
|
||
self.mode_var.set("Симуляция")
|
||
elif selected == "Симуляция" and any(state.live_position for state in self.symbol_states.values()):
|
||
messagebox.showerror("Открыта реальная позиция", "Сначала закройте позицию на Bybit в реальном режиме.")
|
||
self.mode_var.set("Реальная торговля")
|
||
else:
|
||
self.start_btn.configure(text="Запустить прогон" if selected == HISTORICAL_MODE else "Старт")
|
||
self.applied_settings = self._safe_read_settings()
|
||
self._refresh_settings_summary()
|
||
self._update_historical_controls()
|
||
self._update_auto_currency_controls()
|
||
self._update_simulation_controls()
|
||
self._update_strategy_hint()
|
||
self._refresh_ui()
|
||
|
||
def _update_historical_controls(self) -> None:
|
||
if self.mode_var.get() == HISTORICAL_MODE:
|
||
if not self.historical_controls_frame.winfo_manager():
|
||
self.historical_controls_frame.pack(fill="x", pady=(4, 0), before=self.currencies_frame)
|
||
else:
|
||
self.historical_controls_frame.pack_forget()
|
||
|
||
def _update_auto_currency_controls(self) -> None:
|
||
if self.mode_var.get() in ("Симуляция", "Реальная торговля"):
|
||
if not self.auto_currency_controls_frame.winfo_manager():
|
||
self.auto_currency_controls_frame.pack(fill="x", pady=(4, 0), before=self.currencies_frame)
|
||
else:
|
||
self.auto_currency_controls_frame.pack_forget()
|
||
|
||
def _update_simulation_controls(self) -> None:
|
||
if self.mode_var.get() == "Симуляция":
|
||
if not self.simulation_controls_frame.winfo_manager():
|
||
self.simulation_controls_frame.pack(fill="x", pady=(4, 0), before=self.currencies_frame)
|
||
else:
|
||
self.simulation_controls_frame.pack_forget()
|
||
|
||
def _simulation_position_limit(self) -> int:
|
||
raw = self.max_active_sim_positions_var.get().strip().replace(",", ".")
|
||
try:
|
||
value = float(raw)
|
||
except (ValueError, tk.TclError) as exc:
|
||
raise ValueError("Количество одновременных сделок должно быть целым числом от 1 до 100.") from exc
|
||
if not math.isfinite(value) or not value.is_integer() or not 1 <= value <= 100:
|
||
raise ValueError("Количество одновременных сделок должно быть целым числом от 1 до 100.")
|
||
return int(value)
|
||
|
||
def apply_simulation_controls(self) -> None:
|
||
try:
|
||
deposit = float(self.initial_var.get().strip().replace(",", "."))
|
||
if not math.isfinite(deposit) or deposit <= 0:
|
||
raise ValueError
|
||
self._simulation_position_limit()
|
||
except (ValueError, tk.TclError):
|
||
messagebox.showerror(
|
||
"Проверьте настройки симуляции",
|
||
"Укажите депозит больше нуля и целый лимит сделок от 1 до 100.",
|
||
)
|
||
return
|
||
|
||
deposit_changed = abs(deposit - self.initial_balance) > 1e-9
|
||
has_open_positions = any(state.position is not None for state in self.symbol_states.values())
|
||
if deposit_changed and (self.running or has_open_positions):
|
||
messagebox.showerror(
|
||
"Нельзя изменить депозит",
|
||
"Остановите симуляцию и закройте открытые сделки, затем примените новый депозит.",
|
||
)
|
||
return
|
||
if deposit_changed:
|
||
# Preserve already-earned simulation P&L when changing the starting capital.
|
||
self.balance += deposit - self.initial_balance
|
||
self.initial_balance = deposit
|
||
self._save_account_state()
|
||
self._save_settings()
|
||
self._refresh_ui()
|
||
self.status_var.set("Настройки симуляции применены")
|
||
|
||
def _refresh_strategy_preview(self) -> None:
|
||
canvas = getattr(self, "preview_canvas", None)
|
||
if canvas is None or not canvas.winfo_exists():
|
||
return
|
||
canvas.delete("all")
|
||
width = max(canvas.winfo_width(), 900)
|
||
height = max(canvas.winfo_height(), 360)
|
||
|
||
def value(var: tk.StringVar, fallback: float) -> float:
|
||
try:
|
||
return max(0.0, float(var.get().strip().replace(",", ".")))
|
||
except (ValueError, tk.TclError):
|
||
return fallback
|
||
|
||
trigger = value(self.trigger_var, .3)
|
||
add_step = value(self.add_step_var, .5)
|
||
max_adds = int(value(self.max_adds_var, 2))
|
||
stop_loss = value(self.stop_loss_var, .45)
|
||
take_profit = value(self.take_profit_var, .5)
|
||
stake_pct = value(self.stake_var, 2)
|
||
try:
|
||
simulation_capital = max(0.0, float(self.initial_var.get().strip().replace(",", ".")))
|
||
except (ValueError, tk.TclError):
|
||
simulation_capital = 5000.0
|
||
deposit_basis = (self._current_live_deposit_basis()
|
||
if self.mode_var.get() == "Реальная торговля" else None) or simulation_capital
|
||
stake = deposit_basis * stake_pct / 100
|
||
leverage = value(self.leverage_var, 10)
|
||
reference = 100.0
|
||
entry_prices = [reference * (1 + trigger / 100)]
|
||
for _ in range(max_adds if add_step > 0 else 0):
|
||
entry_prices.append(entry_prices[-1] * (1 - add_step / 100))
|
||
notional_per_entry = stake * leverage
|
||
quantities = [notional_per_entry / price for price in entry_prices]
|
||
total_qty = sum(quantities)
|
||
total_notional = notional_per_entry * len(entry_prices)
|
||
average = total_notional / total_qty if total_qty else entry_prices[-1]
|
||
effective_tp = max(take_profit, self._fee_cover_pct(TAKER_FEE_PCT))
|
||
tp_price = average * (1 + effective_tp / 100) if take_profit > 0 else None
|
||
sl_price = average * (1 - stop_loss / 100) if stop_loss > 0 else None
|
||
next_add_price = entry_prices[-1] * (1 - add_step / 100) if add_step > 0 and len(entry_prices) <= max_adds else None
|
||
gross = ((tp_price - average) * total_qty) if tp_price is not None else 0.0
|
||
exit_notional = (tp_price * total_qty) if tp_price is not None else 0.0
|
||
fees = (total_notional + exit_notional) * TAKER_FEE_PCT / 100
|
||
net = gross - fees
|
||
total_margin = stake * len(entry_prices)
|
||
roi = net / total_margin * 100 if total_margin else 0.0
|
||
|
||
canvas.create_text(16, 12, anchor="nw", fill="#e5edf5", font=("Segoe UI", 11, "bold"), text=f"Пример усреднения · условная прошлая цена = 100.00 USDT · максимум доливок: {max_adds} · 1-мин свечи")
|
||
left, right = 78, width - 30
|
||
top, bottom = 52, height - 95
|
||
preview_levels = [reference, *entry_prices, sl_price if sl_price else average]
|
||
if next_add_price is not None:
|
||
preview_levels.append(next_add_price)
|
||
if tp_price is not None:
|
||
preview_levels.append(tp_price)
|
||
low = min(preview_levels) * .998
|
||
high = max(preview_levels) * 1.002
|
||
if high <= low:
|
||
high = low + 1
|
||
|
||
def y_for(price: float) -> float:
|
||
return bottom - (price - low) / (high - low) * (bottom - top)
|
||
|
||
def fmt(price: float) -> str:
|
||
return f"{price:.6f}".rstrip("0").rstrip(".")
|
||
|
||
def level(price: float, label: str, color: str, dash: tuple[int, ...] = (4, 3)) -> None:
|
||
y = y_for(price)
|
||
canvas.create_line(left, y, right, y, fill=color, dash=dash, width=1)
|
||
canvas.create_text(left + 5, y - 13, anchor="sw", fill=color, font=("Segoe UI", 8), text=f"{label}: {fmt(price)}")
|
||
|
||
level(reference, "Закрытие прошлой свечи", "#9fb2c4")
|
||
for index, price in enumerate(entry_prices):
|
||
title = f"Вход #{index + 1}" if index == 0 else f"Доливка #{index} (−{add_step:g}%)"
|
||
level(price, title, "#63a8ff" if index == 0 else "#b49cff")
|
||
level(average, "Средняя цена позиции", "#f2c14e", (2, 3))
|
||
if tp_price is not None:
|
||
level(tp_price, f"TP +{effective_tp:g}%", "#40d6b0")
|
||
if sl_price is not None:
|
||
level(sl_price, f"Стоп −{stop_loss:g}%", "#ff6969")
|
||
if next_add_price is not None:
|
||
level(next_add_price, f"Следующая доливка −{add_step:g}%", "#d28cff")
|
||
|
||
# Draw only the entry levels enabled by the add-step setting.
|
||
entry_x = [left + (right-left) * (.24 + index * .18) for index in range(len(entry_prices))]
|
||
path = [(left + 10, reference), *zip(entry_x, entry_prices), (right - 10, tp_price if tp_price is not None else average)]
|
||
coords = [(x, y_for(price)) for x, price in path]
|
||
candle_width = min(34, max(16, (right - left) / (len(path) * 2.8)))
|
||
for index, ((x1, open_price), (x2, close_price)) in enumerate(zip(path, path[1:])):
|
||
wick = max(abs(close_price - open_price) * .2, max(open_price, close_price) * .0005)
|
||
center_x = (x1 + x2) / 2
|
||
canvas.create_line(center_x, y_for(max(open_price, close_price) + wick), center_x, y_for(min(open_price, close_price) - wick), fill="#ef5965" if close_price < open_price else "#38d996", width=2)
|
||
color = "#38d996" if close_price >= open_price else "#ef5965"
|
||
body_top, body_bottom = sorted((y_for(open_price), y_for(close_price)))
|
||
if body_bottom - body_top < 3:
|
||
body_bottom = body_top + 3
|
||
canvas.create_rectangle(center_x-candle_width/2, body_top, center_x+candle_width/2, body_bottom, fill=color, outline=color)
|
||
for index in range(len(entry_prices)):
|
||
x, y = coords[index + 1]
|
||
label = "ВХОД" if index == 0 else f"ДОЛИВКА {index}"
|
||
canvas.create_oval(x-4, y-4, x+4, y+4, fill="#63a8ff" if index == 0 else "#b49cff", outline="white")
|
||
canvas.create_text(x, y-8, anchor="s", fill="#c6b4ff" if index else "#8fc2ff", font=("Segoe UI", 8, "bold"), text=label)
|
||
if tp_price is not None:
|
||
x, y = coords[-1]
|
||
canvas.create_oval(x-4, y-4, x+4, y+4, fill="#40d6b0", outline="white")
|
||
canvas.create_text(x, y-8, anchor="s", fill="#63e6c2", font=("Segoe UI", 8, "bold"), text="ЗАКРЫТИЕ TP")
|
||
|
||
pnl_text = f"При TP после {len(entry_prices)} вход(а/ов): Gross {gross:+.4f} · комиссии {fees:.4f} · Net {net:+.4f} USDT ({roi:+.2f}% на суммарную ставку {total_margin:g})"
|
||
entries_text = " → ".join((f"вход {fmt(entry_prices[0])}", *(f"доливка {fmt(price)}" for price in entry_prices[1:])))
|
||
canvas.create_text(16, height-58, anchor="nw", fill="#dce7f0", font=("Segoe UI", 9), text=f"Пример: 100.00 → {entries_text} → средняя {fmt(average)} → TP {fmt(tp_price) if tp_price else 'выкл.'} / стоп {fmt(sl_price) if sl_price else 'выкл.'}")
|
||
canvas.create_text(16, height-38, anchor="nw", fill="#dce7f0", font=("Segoe UI", 9), text=pnl_text)
|
||
canvas.create_text(16, height-18, anchor="nw", fill="#9fb2c4", font=("Segoe UI", 8), text=f"Ставка {stake_pct:g}% от базы {deposit_basis:g} USDT = {stake:g} USDT × плечо {leverage:g} на каждый вход · taker-комиссия {TAKER_FEE_PCT:g}% за сторону · расчёт примерный, без проскальзывания и funding.")
|
||
|
||
def _setting(self, parent: ttk.Widget, label: str, default: str, row: int, col: int) -> tk.StringVar:
|
||
cell = ttk.Frame(parent)
|
||
cell.grid(row=row, column=col, sticky="w", padx=(0, 10), pady=2)
|
||
ttk.Label(cell, text=label).pack(anchor="w")
|
||
var = tk.StringVar(value=default)
|
||
ttk.Entry(cell, textvariable=var, width=13).pack(anchor="w")
|
||
var.trace_add("write", self._schedule_settings_save)
|
||
return var
|
||
|
||
def _settings_payload(self) -> dict[str, object]:
|
||
return {
|
||
"symbol": self.symbol_var.get().strip().upper(),
|
||
"currencies": self.currencies,
|
||
"enabled_symbols": sorted(self.enabled_symbols),
|
||
"currency_settings": self.currency_settings,
|
||
"default_currency_settings": self.default_currency_settings,
|
||
"strategy_defaults_version": STRATEGY_DEFAULTS_VERSION,
|
||
"initial_capital": self.initial_var.get(),
|
||
"stake_pct": self.stake_var.get(),
|
||
"max_adds": self.max_adds_var.get(),
|
||
"leverage": self.leverage_var.get(),
|
||
"trigger_pct": self.trigger_var.get(),
|
||
"add_step_pct": self.add_step_var.get(),
|
||
"stop_loss_pct": self.stop_loss_var.get(),
|
||
"take_profit_pct": self.take_profit_var.get(),
|
||
"historical_days": self.historical_days_var.get(),
|
||
"historical_initial_capital": self.historical_initial_capital_var.get(),
|
||
"historical_growth_threshold_pct": self.historical_growth_var.get(),
|
||
"historical_min_equity_pct": self.historical_min_equity_var.get(),
|
||
"historical_universe_mode": bool(self.historical_universe_var.get()),
|
||
"historical_include_funding": bool(self.historical_funding_var.get()),
|
||
"strategy_mode": self.strategy_mode,
|
||
"strategy_mode_settings": self.mode_settings,
|
||
"auto_currency_min_growth_24h_pct": self.auto_currency_growth_var.get(),
|
||
"max_active_sim_positions": self.max_active_sim_positions_var.get(),
|
||
"live_testnet": bool(self.testnet_var.get()),
|
||
}
|
||
|
||
def _load_saved_settings(self) -> None:
|
||
try:
|
||
saved = json.loads(SETTINGS_FILE.read_text(encoding="utf-8"))
|
||
except (OSError, json.JSONDecodeError, TypeError):
|
||
return
|
||
variables = {
|
||
"symbol": self.symbol_var,
|
||
"initial_capital": self.initial_var,
|
||
"max_adds": self.max_adds_var,
|
||
"leverage": self.leverage_var,
|
||
"trigger_pct": self.trigger_var,
|
||
"add_step_pct": self.add_step_var,
|
||
"stop_loss_pct": self.stop_loss_var,
|
||
"take_profit_pct": self.take_profit_var,
|
||
}
|
||
if "historical_days" in saved:
|
||
self.historical_days_var.set(str(saved["historical_days"]))
|
||
if "historical_initial_capital" in saved:
|
||
self.historical_initial_capital_var.set(str(saved["historical_initial_capital"]))
|
||
elif "initial_capital" in saved:
|
||
self.historical_initial_capital_var.set(str(saved["initial_capital"]))
|
||
if "historical_growth_threshold_pct" in saved:
|
||
self.historical_growth_var.set(str(saved["historical_growth_threshold_pct"]))
|
||
if "historical_min_equity_pct" in saved:
|
||
self.historical_min_equity_var.set(str(saved["historical_min_equity_pct"]))
|
||
if "historical_universe_mode" in saved:
|
||
self.historical_universe_var.set(bool(saved["historical_universe_mode"]))
|
||
if "historical_include_funding" in saved:
|
||
self.historical_funding_var.set(bool(saved["historical_include_funding"]))
|
||
saved_modes = saved.get("strategy_mode_settings")
|
||
if isinstance(saved_modes, dict):
|
||
for mode, values in saved_modes.items():
|
||
if mode in self.mode_settings and isinstance(values, dict):
|
||
self.mode_settings[mode].update({str(key): str(value) for key, value in values.items()
|
||
if key in strategy.MODE_DEFAULTS[mode]})
|
||
if saved.get("strategy_mode") in strategy.STRATEGY_MODES:
|
||
self.strategy_mode = saved["strategy_mode"]
|
||
self.strategy_mode_var.set(strategy.STRATEGY_TITLES[self.strategy_mode])
|
||
self._update_strategy_hint()
|
||
if "auto_currency_min_growth_24h_pct" in saved:
|
||
self.auto_currency_growth_var.set(str(saved["auto_currency_min_growth_24h_pct"]))
|
||
if "max_active_sim_positions" in saved:
|
||
self.max_active_sim_positions_var.set(str(saved["max_active_sim_positions"]))
|
||
for key, variable in variables.items():
|
||
if key in saved:
|
||
variable.set(str(saved[key]))
|
||
if "stake_pct" in saved:
|
||
self.stake_var.set(str(saved["stake_pct"]))
|
||
elif "stake" in saved:
|
||
# Migrate earlier settings where stake was saved as a fixed USDT amount.
|
||
try:
|
||
old_capital = float(str(saved.get("initial_capital", self.initial_var.get())).replace(",", "."))
|
||
old_stake = float(str(saved["stake"]).replace(",", "."))
|
||
if old_capital > 0 and old_stake > 0:
|
||
self.stake_var.set(f"{old_stake / old_capital * 100:.8g}")
|
||
except (ValueError, TypeError):
|
||
pass
|
||
if "live_testnet" in saved:
|
||
self.testnet_var.set(bool(saved["live_testnet"]))
|
||
if "add_step_pct" not in saved:
|
||
self.add_step_var.set("0.5")
|
||
if "max_adds" not in saved:
|
||
self.max_adds_var.set("2")
|
||
configured = saved.get("currencies", [])
|
||
if isinstance(configured, list):
|
||
for value in configured:
|
||
symbol = str(value).strip().upper()
|
||
if re.fullmatch(r"[A-Z0-9]{2,30}", symbol):
|
||
self._ensure_symbol(symbol)
|
||
active = saved.get("enabled_symbols")
|
||
if isinstance(active, list):
|
||
self._has_saved_enabled_symbols = True
|
||
self.enabled_symbols = {str(value).strip().upper() for value in active
|
||
if re.fullmatch(r"[A-Z0-9]{2,30}", str(value).strip().upper())}
|
||
else:
|
||
self.enabled_symbols = {self.symbol_var.get().strip().upper()}
|
||
saved_overrides = saved.get("currency_settings", {})
|
||
if isinstance(saved_overrides, dict):
|
||
self.currency_settings = {str(symbol).strip().upper(): dict(values)
|
||
for symbol, values in saved_overrides.items()
|
||
if isinstance(values, dict)}
|
||
if not self.currencies:
|
||
self.currencies = [self.symbol_var.get().strip().upper()]
|
||
self.default_currency_settings = {
|
||
"stake_pct": self.stake_var.get(), "max_adds": self.max_adds_var.get(),
|
||
"leverage": self.leverage_var.get(), "trigger_pct": self.trigger_var.get(),
|
||
"add_step_pct": self.add_step_var.get(), "stop_loss_pct": self.stop_loss_var.get(),
|
||
"take_profit_pct": self.take_profit_var.get(),
|
||
}
|
||
saved_defaults = saved.get("default_currency_settings", {})
|
||
try:
|
||
saved_defaults_version = int(saved.get("strategy_defaults_version", 0))
|
||
except (TypeError, ValueError):
|
||
saved_defaults_version = 0
|
||
if saved_defaults_version >= STRATEGY_DEFAULTS_VERSION and isinstance(saved_defaults, dict):
|
||
self.default_currency_settings.update({str(key): str(value) for key, value in saved_defaults.items()
|
||
if key in self.default_currency_settings})
|
||
else:
|
||
# Upgrade the old shared template to the requested defaults while
|
||
# preserving individual overrides already saved for specific symbols.
|
||
self.default_currency_settings = DEFAULT_CURRENCY_STRATEGY.copy()
|
||
self._load_currency_settings(self.symbol_var.get().strip().upper())
|
||
self._render_currency_tiles()
|
||
self._update_historical_controls()
|
||
self._update_auto_currency_controls()
|
||
self._update_simulation_controls()
|
||
|
||
def _load_saved_state(self) -> None:
|
||
"""Restore the virtual account and closed-trade history from the prior run."""
|
||
if not STATE_FILE.exists():
|
||
try:
|
||
configured_capital = float(self.initial_var.get().strip().replace(",", "."))
|
||
if configured_capital > 0:
|
||
self.initial_balance = self.balance = configured_capital
|
||
except (ValueError, tk.TclError):
|
||
pass
|
||
return
|
||
try:
|
||
state = json.loads(STATE_FILE.read_text(encoding="utf-8"))
|
||
initial = float(state["initial_balance"])
|
||
balance = float(state["balance"])
|
||
fees = float(state.get("total_fees", 0.0))
|
||
next_id = int(state.get("next_id", 1))
|
||
if initial <= 0 or balance < 0 or fees < 0 or next_id < 1:
|
||
raise ValueError("Некорректные значения счёта")
|
||
loaded_trades = [ClosedTrade(**row) for row in state.get("trades", [])]
|
||
position_data = state.get("position")
|
||
loaded_position = Position(**position_data) if position_data else None
|
||
loaded_positions = {str(symbol): Position(**row) for symbol, row in state.get("positions", {}).items()}
|
||
loaded_live_trades = [ClosedTrade(**row) for row in state.get("live_trades", [])]
|
||
loaded_deposit_bases = {str(key): float(value) for key, value in state.get("live_initial_deposits", {}).items()
|
||
if float(value) > 0}
|
||
live_position_data = state.get("live_position")
|
||
loaded_live_position = Position(**live_position_data) if live_position_data else None
|
||
loaded_live_positions = {str(symbol): Position(**row) for symbol, row in state.get("live_positions_managed", {}).items()}
|
||
if loaded_position and (loaded_position.qty <= 0 or loaded_position.entry_price <= 0):
|
||
raise ValueError("Некорректные данные открытой позиции")
|
||
if loaded_live_position and (loaded_live_position.qty <= 0 or loaded_live_position.entry_price <= 0):
|
||
raise ValueError("Некорректные данные реальной позиции")
|
||
except (OSError, json.JSONDecodeError, TypeError, KeyError, ValueError) as exc:
|
||
self.status_var.set(f"Не удалось загрузить счёт из {STATE_FILE.name}: {exc}")
|
||
return
|
||
|
||
self.initial_balance = initial
|
||
self.balance = balance
|
||
self.total_fees = fees
|
||
self.trades = loaded_trades
|
||
self.position = loaded_position
|
||
self.live_trades = loaded_live_trades
|
||
self.live_initial_deposits = loaded_deposit_bases
|
||
self.live_position = loaded_live_position
|
||
for symbol, position in loaded_positions.items():
|
||
self._ensure_symbol(symbol).position = position
|
||
self.enabled_symbols.add(symbol)
|
||
for symbol, position in loaded_live_positions.items():
|
||
self._ensure_symbol(symbol).live_position = position
|
||
self.enabled_symbols.add(symbol)
|
||
if loaded_position:
|
||
self._ensure_symbol(loaded_position.symbol).position = loaded_position
|
||
if loaded_live_position:
|
||
self._ensure_symbol(loaded_live_position.symbol).live_position = loaded_live_position
|
||
max_trade_id = max((trade.trade_id for trade in loaded_trades), default=0)
|
||
max_open_id = max((position.trade_id for position in loaded_positions.values()), default=0)
|
||
self.next_id = max(next_id, max_trade_id + 1, max_open_id + 1,
|
||
loaded_position.trade_id + 1 if loaded_position else 1)
|
||
self.next_live_id = max(int(state.get("next_live_id", 1)), max((trade.trade_id for trade in loaded_live_trades), default=0) + 1,
|
||
max((position.trade_id for position in loaded_live_positions.values()), default=0) + 1,
|
||
loaded_live_position.trade_id + 1 if loaded_live_position else 1)
|
||
self.initial_var.set(str(initial))
|
||
if loaded_position or loaded_live_position:
|
||
restored_symbol = loaded_position.symbol if loaded_position else loaded_live_position.symbol
|
||
self.symbol = restored_symbol
|
||
self.symbol_var.set(restored_symbol)
|
||
for trade in reversed(loaded_trades):
|
||
tag = "profit" if trade.net_pnl > 0 else "loss" if trade.net_pnl < 0 else ""
|
||
self.table.insert(
|
||
"", "end",
|
||
values=(trade.trade_id, trade.symbol, self._fmt_price(trade.entry_price), self._fmt_price(trade.exit_price),
|
||
f"{trade.roi_pct:+.2f}", f"{trade.gross_pnl:+.4f}", f"{trade.fees:.4f}",
|
||
f"{trade.net_pnl:+.4f}", trade.reason),
|
||
tags=(tag,),
|
||
)
|
||
for trade in reversed(loaded_live_trades):
|
||
tag = "profit" if trade.net_pnl > 0 else "loss" if trade.net_pnl < 0 else ""
|
||
self.table.insert(
|
||
"", "end",
|
||
values=(f"R{trade.trade_id}", trade.symbol, self._fmt_price(trade.entry_price), self._fmt_price(trade.exit_price),
|
||
f"{trade.roi_pct:+.2f}", f"{trade.gross_pnl:+.4f}", f"{trade.fees:.4f}",
|
||
f"{trade.net_pnl:+.4f}", f"LIVE · {trade.reason}"),
|
||
tags=(tag,),
|
||
)
|
||
self.status_var.set(f"Загружено сделок: {len(loaded_trades)} · баланс {self.balance:,.2f} USDT")
|
||
|
||
def _save_account_state(self) -> None:
|
||
self._capture_active_symbol()
|
||
state = {
|
||
"version": 1,
|
||
"initial_balance": self.initial_balance,
|
||
"balance": self.balance,
|
||
"total_fees": self.total_fees,
|
||
"next_id": self.next_id,
|
||
"trades": [vars(trade) for trade in self.trades],
|
||
"position": vars(self.position) if self.position else None,
|
||
"positions": {symbol: vars(state.position) for symbol, state in self.symbol_states.items() if state.position},
|
||
"next_live_id": self.next_live_id,
|
||
"live_trades": [vars(trade) for trade in self.live_trades],
|
||
"live_position": vars(self.live_position) if self.live_position else None,
|
||
"live_positions_managed": {symbol: vars(state.live_position) for symbol, state in self.symbol_states.items() if state.live_position},
|
||
"live_initial_deposits": self.live_initial_deposits,
|
||
}
|
||
try:
|
||
atomic_write_json(STATE_FILE, state)
|
||
except (OSError, ValueError) as exc:
|
||
if hasattr(self, "status_var"):
|
||
self.status_var.set(f"Не удалось сохранить историю счёта: {exc}")
|
||
|
||
def _schedule_settings_save(self, *_args) -> None:
|
||
if not hasattr(self, "root") or not self.root.winfo_exists():
|
||
return
|
||
if self._settings_save_job is not None:
|
||
try:
|
||
self.root.after_cancel(self._settings_save_job)
|
||
except tk.TclError:
|
||
pass
|
||
self._settings_save_job = self.root.after(350, self._save_settings)
|
||
|
||
def _save_settings(self) -> None:
|
||
self._settings_save_job = None
|
||
try:
|
||
atomic_write_json(SETTINGS_FILE, self._settings_payload())
|
||
except (OSError, ValueError) as exc:
|
||
self.status_var.set(f"Не удалось сохранить настройки: {exc}")
|
||
|
||
@staticmethod
|
||
def _num(var: tk.StringVar, label: str, *, minimum: float = 0, allow_zero: bool = False) -> float:
|
||
try:
|
||
value = float(var.get().strip().replace(",", "."))
|
||
except ValueError as exc:
|
||
raise ValueError(f"Проверьте значение «{label}».") from exc
|
||
if not math.isfinite(value) or value < minimum or (not allow_zero and value == 0):
|
||
raise ValueError(f"«{label}» должно быть {('не меньше' if allow_zero else 'больше')} {minimum}.")
|
||
return value
|
||
|
||
def _read_settings(self) -> dict[str, float]:
|
||
take_profit = self._num(self.take_profit_var, "TP", allow_zero=True)
|
||
stop_loss = self._num(self.stop_loss_var, "стоп-лосс", allow_zero=True)
|
||
max_adds_value = self._num(self.max_adds_var, "максимум доливок", allow_zero=True)
|
||
if not max_adds_value.is_integer() or max_adds_value > 100:
|
||
raise ValueError("Максимум доливок должен быть целым числом от 0 до 100.")
|
||
if take_profit == 0 and stop_loss == 0:
|
||
raise ValueError("Укажите TP, стоп-лосс или оба уровня — нельзя запускать позицию без условий выхода.")
|
||
initial = self._num(self.initial_var, "начальный капитал")
|
||
stake_pct = self._num(self.stake_var, "ставка от депозита")
|
||
if stake_pct > 100:
|
||
raise ValueError("Ставка на каждый вход должна быть не больше 100% депозита.")
|
||
deposit_basis = self._current_live_deposit_basis() if self.mode_var.get() == "Реальная торговля" else None
|
||
stake = (deposit_basis if deposit_basis is not None else initial) * stake_pct / 100
|
||
return {
|
||
"initial": initial,
|
||
"stake_pct": stake_pct,
|
||
"deposit_basis": deposit_basis or initial,
|
||
"stake": stake,
|
||
"leverage": self._num(self.leverage_var, "плечо", minimum=1, allow_zero=True),
|
||
"trigger": self._num(self.trigger_var, "порог роста"),
|
||
"add_step": self._num(self.add_step_var, "шаг доливки", allow_zero=True),
|
||
"max_adds": int(max_adds_value),
|
||
"stop_loss": stop_loss,
|
||
"take_profit": take_profit,
|
||
"fee": TAKER_FEE_PCT,
|
||
"interval": float(CANDLE_INTERVAL_MINUTES),
|
||
}
|
||
|
||
def _deposit_baseline_key(self, api_key: str | None = None, testnet: bool | None = None) -> str | None:
|
||
key = (api_key if api_key is not None else self.api_key_var.get()).strip()
|
||
if not key:
|
||
return None
|
||
network = self.testnet_var.get() if testnet is None else testnet
|
||
fingerprint = hashlib.sha256(key.encode("utf-8")).hexdigest()[:16]
|
||
return f"{'testnet' if network else 'mainnet'}:{fingerprint}"
|
||
|
||
def _current_live_deposit_basis(self) -> float | None:
|
||
key = self._deposit_baseline_key()
|
||
value = self.live_initial_deposits.get(key) if key else None
|
||
return float(value) if value and value > 0 else None
|
||
|
||
def _remember_live_deposit(self, api_key: str, testnet: bool, wallet: dict[str, float], baseline: float | None = None) -> float:
|
||
key = self._deposit_baseline_key(api_key, testnet)
|
||
if not key:
|
||
return float(baseline or wallet.get("wallet") or 0)
|
||
saved = self.live_initial_deposits.get(key)
|
||
if saved and saved > 0:
|
||
return float(saved)
|
||
value = float(baseline or wallet.get("wallet") or 0)
|
||
if value > 0:
|
||
self.live_initial_deposits[key] = value
|
||
self._save_account_state()
|
||
return value
|
||
|
||
def connect_bybit(self) -> None:
|
||
"""Read the account snapshot without starting the trading loop or placing orders."""
|
||
if self.running or self.live_preflight:
|
||
self.status_var.set("Остановите торговый цикл перед новым подключением аккаунта")
|
||
return
|
||
if self.api_connecting:
|
||
return
|
||
api_key = self.api_key_var.get().strip()
|
||
api_secret = self.api_secret_var.get().strip()
|
||
if not api_key or not api_secret:
|
||
self.open_live_settings()
|
||
self.status_var.set("Вставьте API key и secret, затем нажмите «Подключиться»")
|
||
return
|
||
self.api_connecting = True
|
||
self.connect_btn.configure(state="disabled")
|
||
self.status_var.set(f"Подключаюсь к Bybit ({'Testnet' if self.testnet_var.get() else 'Mainnet'}) · только чтение…")
|
||
threading.Thread(target=self._api_connect_worker,
|
||
args=(api_key, api_secret, self.testnet_var.get()), daemon=True).start()
|
||
|
||
def _api_connect_worker(self, api_key: str, api_secret: str, testnet: bool) -> None:
|
||
try:
|
||
client = BybitLiveClient(api_key, api_secret, testnet)
|
||
wallet = client.get_wallet()
|
||
optional_results = []
|
||
warnings = []
|
||
for label, method in (
|
||
("позиции", client.get_open_positions),
|
||
("ордера", lambda: client.get_order_history(50)),
|
||
("историю P&L", lambda: client.get_closed_pnl_history(50)),
|
||
):
|
||
try:
|
||
optional_results.append(method())
|
||
except Exception as exc:
|
||
optional_results.append([])
|
||
warnings.append(f"{label}: {exc}")
|
||
positions, orders, closed_pnl = optional_results
|
||
self.events.put(("api_connected", client, wallet, positions, orders, closed_pnl,
|
||
self._deposit_baseline_key(api_key, testnet), warnings))
|
||
except Exception as exc:
|
||
self.events.put(("api_connect_failed", str(exc)))
|
||
|
||
def _show_api_snapshot(self, client: BybitLiveClient, wallet: dict[str, float], positions: list[dict],
|
||
orders: list[dict], closed_pnl: list[dict], baseline_key: str | None,
|
||
warnings: list[str] | None = None) -> None:
|
||
self.live_client = client
|
||
self.live_wallet = wallet
|
||
self.live_positions = positions
|
||
for row in positions:
|
||
symbol = str(row.get("symbol") or "").upper()
|
||
if symbol:
|
||
self._ensure_symbol(symbol)
|
||
self.enabled_symbols.add(symbol)
|
||
self._render_currency_tiles()
|
||
self.live_orders = orders
|
||
self.live_closed_pnl = closed_pnl
|
||
self.testnet_var.set(client.testnet)
|
||
if baseline_key:
|
||
baseline = self.live_initial_deposits.get(baseline_key)
|
||
if not baseline or baseline <= 0:
|
||
baseline = float(wallet.get("wallet") or 0)
|
||
if baseline > 0:
|
||
self.live_initial_deposits[baseline_key] = baseline
|
||
else:
|
||
baseline = float(wallet.get("wallet") or 0)
|
||
if wallet.get("unrealized_pnl") is None:
|
||
wallet["unrealized_pnl"] = sum(float(row.get("unrealisedPnl") or 0) for row in positions)
|
||
self._render_bybit_orders()
|
||
self._render_bybit_positions()
|
||
self.mode_var.set("Реальная торговля")
|
||
self._update_historical_controls()
|
||
self._update_auto_currency_controls()
|
||
self._update_simulation_controls()
|
||
self.applied_settings = self._safe_read_settings()
|
||
if positions:
|
||
self.history_tabs.select(2)
|
||
else:
|
||
self.history_tabs.select(1)
|
||
recent_realized = sum(float(row.get("closedPnl") or 0) for row in closed_pnl)
|
||
network = "Testnet" if client.testnet else "MAINNET"
|
||
self.live_account_var.set(
|
||
f"{network} подключён · стартовый депозит {baseline:,.2f} · кошелёк {wallet['wallet']:,.2f} · "
|
||
f"equity {wallet['equity']:,.2f} · P&L нереализованный {wallet.get('unrealized_pnl', 0):+,.2f} · "
|
||
f"реализованный за загруженную историю {recent_realized:+,.2f} USDT · "
|
||
f"ордеров {len(orders)} · открытых позиций {len(positions)}"
|
||
)
|
||
if self.live_position is None:
|
||
selected = next((row for row in positions if row.get("symbol") == self.symbol_var.get().strip().upper()), None)
|
||
if selected:
|
||
self.position_var.set(
|
||
f"Bybit · {selected.get('symbol')} {selected.get('side')} · объём {selected.get('size')} · "
|
||
f"средняя {selected.get('avgPrice')} · P&L {float(selected.get('unrealisedPnl') or 0):+.4f} USDT · "
|
||
f"TP {selected.get('takeProfit') or '—'} · SL {selected.get('stopLoss') or '—'} · "
|
||
"подключено для просмотра; нажмите «Старт» для сопровождения ботом"
|
||
)
|
||
elif positions:
|
||
self.position_var.set(f"На аккаунте открыто позиций: {len(positions)} · подробности во вкладке «Открытые позиции»")
|
||
else:
|
||
self.position_var.set("Bybit · открытых позиций нет")
|
||
self._save_account_state()
|
||
self._save_settings()
|
||
self._refresh_settings_summary()
|
||
self._refresh_ui()
|
||
status = f"Bybit подключён · торговля не запущена · ордеров: {len(orders)} · позиций: {len(positions)}"
|
||
if warnings:
|
||
status += " · часть данных не загружена: " + "; ".join(warnings)
|
||
self.status_var.set(status)
|
||
|
||
def _render_bybit_orders(self) -> None:
|
||
if not hasattr(self, "bybit_orders_table"):
|
||
return
|
||
for item in self.bybit_orders_table.get_children():
|
||
self.bybit_orders_table.delete(item)
|
||
for row in self.live_orders:
|
||
stamp = int(row.get("updatedTime") or row.get("createdTime") or 0) / 1000
|
||
try:
|
||
time_text = datetime.fromtimestamp(stamp).strftime("%Y-%m-%d %H:%M:%S")
|
||
except (OverflowError, OSError, ValueError):
|
||
time_text = "—"
|
||
self.bybit_orders_table.insert("", "end", values=(
|
||
time_text, row.get("symbol", ""), row.get("side", ""), row.get("orderType", ""),
|
||
row.get("qty", ""), row.get("price", ""), row.get("avgPrice", ""),
|
||
row.get("orderStatus", ""), row.get("orderId", ""),
|
||
))
|
||
|
||
def _render_bybit_positions(self) -> None:
|
||
if not hasattr(self, "bybit_positions_table"):
|
||
return
|
||
for item in self.bybit_positions_table.get_children():
|
||
self.bybit_positions_table.delete(item)
|
||
for row in self.live_positions:
|
||
self.bybit_positions_table.insert("", "end", values=(
|
||
row.get("symbol", ""), row.get("side", ""), row.get("size", ""), row.get("avgPrice", ""),
|
||
row.get("markPrice", ""), row.get("unrealisedPnl", ""), row.get("leverage", ""),
|
||
row.get("takeProfit", "") or "—", row.get("stopLoss", "") or "—",
|
||
))
|
||
|
||
def apply_settings(self) -> None:
|
||
requested_symbol = self.symbol_var.get().strip().upper()
|
||
if not re.fullmatch(r"[A-Z0-9]{2,30}", requested_symbol):
|
||
messagebox.showerror("Неверный тикер", "Введите тикер USDT-перпетуального контракта, например BTCUSDT.")
|
||
return
|
||
self._ensure_symbol(requested_symbol)
|
||
self.enabled_symbols.add(requested_symbol)
|
||
self._capture_active_symbol()
|
||
self._activate_symbol_state(requested_symbol)
|
||
try:
|
||
settings = self._read_settings()
|
||
except ValueError as exc:
|
||
messagebox.showerror("Проверьте настройки", str(exc))
|
||
return
|
||
if self.mode_var.get() == "Реальная торговля" and any(s.live_position for s in self.symbol_states.values()) and self.applied_settings:
|
||
if settings["leverage"] != self.applied_settings["leverage"]:
|
||
messagebox.showerror("Открыта реальная позиция", "Нельзя менять плечо, пока позиция открыта. Закройте её и примените новое плечо.")
|
||
self.leverage_var.set(str(self.applied_settings["leverage"]))
|
||
return
|
||
if self.mode_var.get() == "Симуляция" and settings["stake"] > self.balance:
|
||
messagebox.showerror("Проверьте ставку", "Ставка не может быть больше текущего баланса.")
|
||
return
|
||
if not self.running and self.mode_var.get() == "Симуляция" and settings["stake"] > settings["initial"]:
|
||
messagebox.showerror("Проверьте ставку", "Ставка не может быть больше начального капитала.")
|
||
return
|
||
if not self.running and self.mode_var.get() == "Симуляция":
|
||
self.balance += settings["initial"] - self.initial_balance
|
||
self.initial_balance = settings["initial"]
|
||
if self.mode_var.get() == "Реальная торговля":
|
||
settings["fee"] = self.live_fee_pct
|
||
self.currency_settings[requested_symbol] = {
|
||
"stake_pct": self.stake_var.get(), "max_adds": self.max_adds_var.get(),
|
||
"leverage": self.leverage_var.get(), "trigger_pct": self.trigger_var.get(),
|
||
"add_step_pct": self.add_step_var.get(), "stop_loss_pct": self.stop_loss_var.get(),
|
||
"take_profit_pct": self.take_profit_var.get(),
|
||
}
|
||
self.strategy_by_symbol[requested_symbol] = settings.copy()
|
||
old_interval = self.interval_minutes
|
||
self.applied_settings = settings
|
||
self.interval_minutes = int(settings["interval"])
|
||
if self.running:
|
||
for state in self.symbol_states.values():
|
||
state.baseline_close = None
|
||
state.last_signal_ready = False
|
||
state.last_signal_pct = None
|
||
if old_interval != self.interval_minutes:
|
||
state.candles.clear()
|
||
if old_interval != self.interval_minutes:
|
||
self.chart_view_end = None
|
||
self.chart_visible_seconds = self.interval_minutes * 60 * 30
|
||
self.chart_price_center = None
|
||
self.chart_price_span = None
|
||
for symbol in sorted(self.enabled_symbols):
|
||
self._fetch_baseline_async(symbol, self.interval_minutes)
|
||
if self.mode_var.get() == "Симуляция":
|
||
self._subscribe_running_symbols()
|
||
self._refresh_price_label()
|
||
if self.mode_var.get() == "Реальная торговля":
|
||
for symbol, commands in self.live_commands_by_symbol.items():
|
||
state = self._ensure_symbol(symbol)
|
||
if not state.live_order_busy:
|
||
state.live_order_busy = True
|
||
symbol_settings = self.strategy_by_symbol.get(symbol, settings).copy()
|
||
commands.put(("settings", time.time(), state.last_price or 0.0, symbol_settings))
|
||
self._save_settings()
|
||
self._render_currency_tiles()
|
||
self._save_account_state()
|
||
self._refresh_settings_summary()
|
||
self._refresh_ui()
|
||
self.status_var.set("Настройки применены")
|
||
|
||
def start(self) -> None:
|
||
if self.running:
|
||
return
|
||
mode = self.mode_var.get()
|
||
if mode == HISTORICAL_MODE:
|
||
self._start_historical_backtest()
|
||
return
|
||
if mode == "Реальная торговля" and self.strategy_mode != strategy.STRATEGY_CLASSIC:
|
||
messagebox.showerror(
|
||
"Режим стратегии",
|
||
"Режимы A и B пока работают только в симуляции и историческом прогоне. "
|
||
"Для реальной торговли выберите классический режим стратегии.",
|
||
)
|
||
return
|
||
if self.strategy_mode != strategy.STRATEGY_CLASSIC:
|
||
try:
|
||
self._strategy_mode_params()
|
||
except ValueError as exc:
|
||
messagebox.showerror("Проверьте настройки режима", str(exc))
|
||
return
|
||
if websocket is None:
|
||
messagebox.showerror("Нет зависимости", "Не найден websocket-client. Запустите приложение через run.bat.")
|
||
return
|
||
if self.startup_currency_filter_busy:
|
||
return
|
||
if self.startup_currency_filter_approved_for != mode:
|
||
try:
|
||
threshold = float(self.auto_currency_growth_var.get().strip().replace(",", "."))
|
||
except (ValueError, tk.TclError):
|
||
messagebox.showerror("Проверьте порог", "Введите корректный порог роста за 24 часа.")
|
||
return
|
||
if not math.isfinite(threshold) or not 0 <= threshold <= 1000:
|
||
messagebox.showerror("Проверьте порог", "Порог роста за 24 часа должен быть от 0 до 1000%.")
|
||
return
|
||
self._begin_startup_currency_filter(mode, threshold)
|
||
return
|
||
self.startup_currency_filter_approved_for = None
|
||
self.startup_currency_filter_busy = False
|
||
self.mode_combo.configure(state="readonly")
|
||
symbols = sorted(self.enabled_symbols)
|
||
if not symbols:
|
||
messagebox.showerror("Нет активных валют", "Включите переключатель «В торгах» хотя бы у одной валюты.")
|
||
return
|
||
invalid = next((symbol for symbol in symbols if not re.fullmatch(r"[A-Z0-9]{2,30}", symbol)), None)
|
||
if invalid:
|
||
messagebox.showerror("Неверный тикер", f"Проверьте тикер {invalid}.")
|
||
return
|
||
classic = self.strategy_mode == strategy.STRATEGY_CLASSIC
|
||
try:
|
||
# Modes A/B do not use the classic per-currency settings, so those cannot block a start.
|
||
visible_settings = self._read_settings() if classic else self._safe_read_settings()
|
||
if self.mode_var.get() == "Симуляция":
|
||
self._simulation_position_limit()
|
||
except ValueError as exc:
|
||
messagebox.showerror("Проверьте настройки", str(exc))
|
||
return
|
||
default_settings = self._read_default_strategy(visible_settings)
|
||
selected_symbol = self.symbol_var.get().strip().upper()
|
||
if selected_symbol not in symbols:
|
||
selected_symbol = symbols[0]
|
||
per_symbol_settings = {symbol: self._strategy_for_symbol(symbol, default_settings) for symbol in symbols}
|
||
settings = per_symbol_settings[selected_symbol]
|
||
if classic and self.mode_var.get() == "Симуляция" and any(
|
||
item["stake"] > item["initial"] for item in per_symbol_settings.values()
|
||
):
|
||
messagebox.showerror("Проверьте ставку", "Ставка не может быть больше начального капитала.")
|
||
return
|
||
if self.mode_var.get() == "Реальная торговля":
|
||
self._begin_live_preflight(symbols[0], settings, per_symbol_settings)
|
||
return
|
||
self.strategy_by_symbol = per_symbol_settings
|
||
self.applied_settings = settings.copy()
|
||
self.interval_minutes = int(settings["interval"])
|
||
self._refresh_settings_summary()
|
||
self.chart_visible_seconds = self.interval_minutes * 60 * 30
|
||
self._save_settings()
|
||
for symbol in symbols:
|
||
state = self._ensure_symbol(symbol)
|
||
state.mode_signal = None
|
||
state.mode_signal_bucket = 0
|
||
state.mode_eval_busy = False
|
||
if state.position:
|
||
# Keep its restored position and indicators; only refresh market data.
|
||
state.baseline_close = None
|
||
else:
|
||
state.prices.clear()
|
||
state.candles.clear()
|
||
state.entry_markers.clear()
|
||
state.last_price = None
|
||
state.baseline_close = None
|
||
state.previous_entry_signal_pct = None
|
||
state.last_signal_pct = None
|
||
state.last_signal_ready = False
|
||
state.live_minute_prices.clear()
|
||
self._last_signal_refresh_at = 0.0
|
||
selected = selected_symbol
|
||
if selected not in symbols:
|
||
selected = symbols[0]
|
||
self.symbol_var.set(selected)
|
||
self._activate_symbol_state(selected)
|
||
self.market_price_var.set(f"{selected}: ожидаю данные Bybit…")
|
||
self.running = True
|
||
self.next_auto_currency_scan_at = 0.0
|
||
self.start_btn.configure(state="disabled")
|
||
self.stop_btn.configure(state="normal")
|
||
self.session_started_at = time.time()
|
||
self.status_var.set(f"Подключение к Bybit: {', '.join(symbols)} · параллельно")
|
||
for symbol in symbols:
|
||
self._fetch_baseline_async(symbol, self.interval_minutes)
|
||
self._save_account_state()
|
||
self.ws_symbols = symbols
|
||
self.ws_thread = threading.Thread(target=self._ws_worker, args=(symbols,), daemon=True)
|
||
self.ws_thread.start()
|
||
|
||
def _start_historical_backtest(self) -> None:
|
||
if self.running or self.live_preflight or self.historical_running:
|
||
self.status_var.set("Сначала завершите текущий торговый цикл или прогон")
|
||
return
|
||
universe_mode = bool(self.historical_universe_var.get())
|
||
symbols = sorted(self.enabled_symbols)
|
||
if universe_mode:
|
||
# Symbols come from the point-in-time selection; strategies are prepared for
|
||
# every pair with saved overrides, the rest use the default strategy.
|
||
symbols = sorted(set(self.currency_settings) | set(self.enabled_symbols))
|
||
if not symbols and not universe_mode:
|
||
messagebox.showerror("Нет активных валют", "Включите валюты, которые нужно проверить исторически.")
|
||
return
|
||
invalid = next((symbol for symbol in symbols if not re.fullmatch(r"[A-Z0-9]{2,30}", symbol)), None)
|
||
if invalid:
|
||
messagebox.showerror("Неверный тикер", f"Проверьте тикер {invalid}.")
|
||
return
|
||
try:
|
||
# Modes A/B do not use the classic per-currency settings, so those cannot block a run.
|
||
visible = (self._read_settings() if self.strategy_mode == strategy.STRATEGY_CLASSIC
|
||
else self._safe_read_settings())
|
||
days = int(self.historical_days_var.get().strip())
|
||
if not 1 <= days <= 365:
|
||
raise ValueError("Количество дней для прогона должно быть от 1 до 365.")
|
||
historical_capital = float(
|
||
self.historical_initial_capital_var.get().strip().replace(",", ".")
|
||
)
|
||
if not math.isfinite(historical_capital) or historical_capital <= 0:
|
||
raise ValueError("Начальный депозит для прогона должен быть больше 0 USDT.")
|
||
growth_threshold = float(self.historical_growth_var.get().strip().replace(",", "."))
|
||
if not math.isfinite(growth_threshold) or not 0 <= growth_threshold <= 1000:
|
||
raise ValueError("Порог роста за 24 часа должен быть от 0 до 1000%.")
|
||
min_equity_pct = float(self.historical_min_equity_var.get().strip().replace(",", "."))
|
||
if not math.isfinite(min_equity_pct) or not 1 <= min_equity_pct <= 100:
|
||
raise ValueError("Порог остановки капитала должен быть от 1 до 100%.")
|
||
max_positions = self._simulation_position_limit()
|
||
if universe_mode:
|
||
growth_threshold = float(self.auto_currency_growth_var.get().strip().replace(",", "."))
|
||
if not math.isfinite(growth_threshold) or not 0 <= growth_threshold <= 1000:
|
||
raise ValueError("Порог автоподбора (рост за 24 ч) должен быть от 0 до 1000%.")
|
||
# Historical stake percentages must use the historical deposit, not the
|
||
# separate paper-account capital currently configured in the main UI.
|
||
visible["initial"] = historical_capital
|
||
visible["deposit_basis"] = historical_capital
|
||
visible["stake"] = historical_capital * visible["stake_pct"] / 100
|
||
defaults = self._read_default_strategy(visible)
|
||
settings_by_symbol = {
|
||
symbol: self._strategy_for_symbol(symbol, defaults) for symbol in symbols
|
||
}
|
||
mode_params = (self._strategy_mode_params() if self.strategy_mode != strategy.STRATEGY_CLASSIC
|
||
else None)
|
||
except ValueError as exc:
|
||
messagebox.showerror("Проверьте настройки", str(exc))
|
||
return
|
||
self._save_settings()
|
||
def compact(settings: dict[str, float]) -> dict[str, float]:
|
||
return {
|
||
"stake": settings["stake"], "leverage": settings["leverage"],
|
||
"trigger": settings["trigger"], "add_step": settings["add_step"],
|
||
"max_adds": settings["max_adds"], "stop_loss": settings["stop_loss"],
|
||
"take_profit": settings["take_profit"],
|
||
}
|
||
|
||
strategies = {symbol: compact(settings) for symbol, settings in settings_by_symbol.items()}
|
||
default_strategy = compact(defaults)
|
||
self._backtest_cancel.clear()
|
||
self.historical_running = True
|
||
self.mode_combo.configure(state="disabled")
|
||
self.start_btn.configure(state="disabled")
|
||
self.stop_btn.configure(state="normal")
|
||
self.status_var.set(
|
||
f"{strategy.STRATEGY_TITLES[self.strategy_mode]} · "
|
||
f"загружаю свечи за {days} дн. · депозит {historical_capital:g} USDT · "
|
||
f"{'автоподбор' if universe_mode else 'фильтр роста 24 ч'}: {growth_threshold:g}% · "
|
||
f"лимит позиций {max_positions} · стоп капитала: {min_equity_pct:g}%"
|
||
+ ("" if universe_mode else f": {', '.join(symbols)}") + "…"
|
||
)
|
||
thread = threading.Thread(
|
||
target=self._historical_backtest_worker,
|
||
args=(symbols, strategies, historical_capital, int(visible["interval"]),
|
||
days, growth_threshold, min_equity_pct),
|
||
kwargs={"max_open_positions": max_positions, "universe_mode": universe_mode,
|
||
"default_strategy": default_strategy,
|
||
"include_funding": bool(self.historical_funding_var.get()),
|
||
"strategy_mode": self.strategy_mode, "mode_params": mode_params},
|
||
daemon=True,
|
||
)
|
||
thread.start()
|
||
|
||
def _historical_backtest_worker(self, symbols: list[str], strategies: dict[str, dict[str, float]],
|
||
initial_capital: float, interval: int, days: int = 30,
|
||
growth_threshold: float = 30.0,
|
||
min_equity_pct: float = 10.0,
|
||
max_open_positions: int | None = None,
|
||
universe_mode: bool = False,
|
||
default_strategy: dict[str, float] | None = None,
|
||
include_funding: bool = True,
|
||
strategy_mode: str = strategy.STRATEGY_CLASSIC,
|
||
mode_params: dict[str, float] | None = None) -> None:
|
||
step_ms = interval * 60_000
|
||
end_ms = (int(time.time() * 1000) // step_ms) * step_ms - 1
|
||
period_ms = days * 24 * 60 * 60 * 1000
|
||
trading_start_ms = ((end_ms - period_ms) // step_ms) * step_ms
|
||
start_ms = trading_start_ms - 24 * 60 * 60 * 1000 - step_ms
|
||
mode_run = strategy_mode != strategy.STRATEGY_CLASSIC and mode_params is not None
|
||
# Modes A/B need closed signal candles before the first decision (24h covers B's growth).
|
||
warmup_ms = (max(strategy.required_bars(strategy_mode, mode_params) + 2,
|
||
strategy.bars_for_hours(24, mode_params["timeframe_min"]) + 2)
|
||
* int(mode_params["timeframe_min"]) * 60_000 if mode_run else 2 * step_ms)
|
||
if mode_run:
|
||
start_ms = min(start_ms, trading_start_ms - warmup_ms)
|
||
|
||
def progress(symbol: str, count: int, total: int, stage: str = "") -> None:
|
||
self.events.put(("historical_progress", symbol, count, total, stage))
|
||
|
||
candles_by_symbol: dict[str, list[list[float]]] = {}
|
||
try:
|
||
windows = None
|
||
ranges = {symbol: start_ms for symbol in symbols}
|
||
skipped: list[str] = []
|
||
if universe_mode:
|
||
windows, skipped = prepare_universe(trading_start_ms, end_ms, growth_threshold,
|
||
cancel=self._backtest_cancel.is_set, progress=progress)
|
||
if not windows:
|
||
raise RuntimeError(
|
||
f"За период ни одна валюта из топ-100 по обороту не выросла за 24 ч больше {growth_threshold:g}%"
|
||
)
|
||
symbols = sorted(windows)
|
||
fallback = default_strategy or next(iter(strategies.values()))
|
||
strategies = {symbol: strategies.get(symbol, fallback) for symbol in symbols}
|
||
# Minute data is needed from just before a pair first qualifies.
|
||
ranges = {symbol: max(start_ms, windows[symbol][0][0] - warmup_ms) for symbol in symbols}
|
||
with ThreadPoolExecutor(max_workers=max(1, min(2, len(symbols)))) as pool:
|
||
futures = {
|
||
pool.submit(fetch_klines, symbol, interval, ranges[symbol], end_ms,
|
||
self._backtest_cancel.is_set, progress, with_turnover=mode_run): symbol
|
||
for symbol in symbols
|
||
}
|
||
for future in as_completed(futures):
|
||
symbol = futures[future]
|
||
try:
|
||
candles_by_symbol[symbol] = future.result()
|
||
except InterruptedError:
|
||
raise
|
||
except Exception:
|
||
if not universe_mode:
|
||
raise
|
||
skipped.append(symbol)
|
||
if self._backtest_cancel.is_set():
|
||
raise InterruptedError("Исторический прогон отменён")
|
||
funding_by_symbol: dict[str, dict[int, float]] | None = None
|
||
funding_failed: list[str] = []
|
||
if include_funding:
|
||
funding_by_symbol = {}
|
||
loaded = sorted(candles_by_symbol)
|
||
with ThreadPoolExecutor(max_workers=4) as pool:
|
||
futures = {pool.submit(fetch_funding_history, symbol, int(candles_by_symbol[symbol][0][0]),
|
||
end_ms, self._backtest_cancel.is_set): symbol for symbol in loaded}
|
||
for done, future in enumerate(as_completed(futures), start=1):
|
||
symbol = futures[future]
|
||
try:
|
||
funding_by_symbol[symbol] = future.result()
|
||
except InterruptedError:
|
||
raise
|
||
except Exception:
|
||
funding_failed.append(symbol)
|
||
progress("Funding", done, len(loaded), f"история funding: {done}/{len(loaded)}")
|
||
if mode_run:
|
||
btc_hourly = None
|
||
if strategy_mode == strategy.STRATEGY_BREAKOUT and mode_params["btc_filter"] >= 1:
|
||
hour_ms = 3_600_000
|
||
btc_start = trading_start_ms - (int(mode_params["btc_ema"]) * 3 + 48) * hour_ms
|
||
btc_hourly = fetch_klines("BTCUSDT", 60, btc_start, end_ms, self._backtest_cancel.is_set, progress)
|
||
result = run_mode_backtest(
|
||
candles_by_symbol, strategy_mode, mode_params, initial_capital, TAKER_FEE_PCT,
|
||
self._backtest_cancel.is_set, trading_start_ms=trading_start_ms,
|
||
min_growth_24h_pct=None if universe_mode else growth_threshold,
|
||
min_equity_pct=min_equity_pct, max_open_positions=max_open_positions,
|
||
universe_windows=windows, funding_by_symbol=funding_by_symbol, btc_hourly=btc_hourly,
|
||
)
|
||
else:
|
||
result = run_backtest(candles_by_symbol, strategies, initial_capital,
|
||
TAKER_FEE_PCT, self._backtest_cancel.is_set,
|
||
trading_start_ms=trading_start_ms,
|
||
pause_below_24h_pct=growth_threshold,
|
||
resume_above_24h_pct=growth_threshold + 1.0,
|
||
min_equity_pct=min_equity_pct,
|
||
max_open_positions=max_open_positions,
|
||
universe_windows=windows,
|
||
funding_by_symbol=funding_by_symbol)
|
||
result["summary"]["unavailable_symbols"] = sorted(skipped)
|
||
result["summary"]["funding_unavailable_symbols"] = sorted(funding_failed)
|
||
csv_path, json_path = save_report(result, BACKTEST_REPORTS_DIR)
|
||
self.events.put(("historical_completed", result, str(csv_path), str(json_path)))
|
||
except InterruptedError:
|
||
self.events.put(("historical_cancelled",))
|
||
except Exception as exc:
|
||
self.events.put(("historical_failed", str(exc)))
|
||
|
||
def _show_historical_report(self, result: dict, csv_path: str, json_path: str) -> None:
|
||
summary = result["summary"]
|
||
window = tk.Toplevel(self.root)
|
||
window.title("Результат исторического прогона · Bybit")
|
||
window.geometry("1100x680")
|
||
window.minsize(820, 480)
|
||
body = ttk.Frame(window, padding=10)
|
||
body.pack(fill="both", expand=True)
|
||
net = summary["total_net_including_open_usdt"]
|
||
candle_items = list(summary["candles"].items())
|
||
ttk.Label(body, text=(
|
||
f"{summary['period_start_utc'][:16]} — {summary['period_end_utc'][:16]} UTC · "
|
||
f"валют: {len(summary['symbols'])} · свечей: " + ", ".join(
|
||
f"{symbol} {count:,}" for symbol, count in candle_items[:30])
|
||
+ (f" … ещё {len(candle_items) - 30}" if len(candle_items) > 30 else "")
|
||
), wraplength=1050).pack(anchor="w", pady=(0, 6))
|
||
funding_text = (
|
||
f" · funding {summary.get('funding_usdt', 0.0):+.4f} USDT ({summary.get('funding_events', 0)} начислений)"
|
||
if summary.get("funding_included") else " · funding не учтён"
|
||
)
|
||
ttk.Label(body, text=(
|
||
f"{summary.get('strategy_title', strategy.STRATEGY_TITLES[strategy.STRATEGY_CLASSIC])} · "
|
||
f"Капитал {summary['initial_capital']:.2f} → оценка {summary['ending_equity_estimate']:.2f} USDT · "
|
||
f"Net {net:+.2f} USDT ({summary['return_pct']:+.2f}%) · "
|
||
f"закрыто {summary['closed_trades']} · прибыльных {summary['wins']} · "
|
||
f"процент прибыльных {summary['win_rate_pct']:.1f}% · "
|
||
f"комиссии {summary['fees_usdt']:.4f} USDT{funding_text} · открытых позиций {summary['open_positions']}"
|
||
), font=("Segoe UI", 10, "bold"), wraplength=1050).pack(anchor="w", pady=(0, 8))
|
||
if "avg_win_usdt" in summary:
|
||
profit_factor = summary.get("profit_factor")
|
||
ttk.Label(body, text=(
|
||
f"Средняя прибыльная {summary['avg_win_usdt']:+.4f} · средняя убыточная "
|
||
f"{summary['avg_loss_usdt']:+.4f} USDT · profit factor "
|
||
f"{profit_factor:.2f}" if profit_factor is not None else
|
||
f"Средняя прибыльная {summary['avg_win_usdt']:+.4f} · средняя убыточная "
|
||
f"{summary['avg_loss_usdt']:+.4f} USDT · profit factor —"
|
||
) + f" · сигналов {summary.get('signals', 0)} · отменено при входе "
|
||
f"{summary.get('signals_rejected_at_fill', 0)}", wraplength=1050).pack(anchor="w", pady=(0, 6))
|
||
if summary.get("funding_unavailable_symbols"):
|
||
ttk.Label(body, text="Нет истории funding (без funding): "
|
||
+ ", ".join(summary["funding_unavailable_symbols"][:40]), wraplength=1050).pack(anchor="w")
|
||
if "max_drawdown_pct" in summary:
|
||
hold_days = summary.get("longest_hold_hours", 0.0) / 24
|
||
risk_text = (
|
||
f"Риск: макс. просадка {summary['max_drawdown_pct']:.2f}% "
|
||
f"({summary['max_drawdown_usdt']:.2f} USDT) · минимум капитала {summary['min_equity_usdt']:.2f} USDT · "
|
||
f"стопов {summary.get('stops', 0)} · ликвидаций {summary.get('liquidations', 0)} · "
|
||
f"открытых в минусе {summary.get('open_losing_positions', 0)} · "
|
||
f"самое долгое удержание {hold_days:.1f} дн. · макс. маржа в позициях "
|
||
f"{summary.get('max_margin_used_usdt', 0.0):.2f} USDT · одновременно позиций до "
|
||
f"{summary.get('max_simultaneous_positions', 0)}"
|
||
+ (f" (лимит {summary['max_open_positions_limit']}, пропущено сигналов "
|
||
f"{summary.get('skipped_entries_position_limit', 0)})"
|
||
if summary.get("max_open_positions_limit") else "")
|
||
)
|
||
ttk.Label(body, text=risk_text, foreground="#b45309", wraplength=1050).pack(anchor="w", pady=(0, 8))
|
||
if summary.get("unavailable_symbols"):
|
||
ttk.Label(body, text="Нет данных Bybit (пропущены): " + ", ".join(summary["unavailable_symbols"][:40])
|
||
+ (" …" if len(summary["unavailable_symbols"]) > 40 else ""),
|
||
wraplength=1050).pack(anchor="w", pady=(0, 6))
|
||
if summary.get("equity_stop_triggered"):
|
||
stop_message = (
|
||
f"Прогон остановлен: капитал достиг {summary['equity_stop_pct']:g}% "
|
||
f"от начального ({summary['equity_stop_value_usdt']:.2f} USDT). "
|
||
f"Оценка капитала в момент остановки: {summary['equity_at_stop_usdt']:.2f} USDT; "
|
||
"открытые позиции показаны по цене срабатывания."
|
||
)
|
||
ttk.Label(body, text=stop_message, foreground="#b42318", wraplength=1050).pack(
|
||
anchor="w", pady=(0, 8)
|
||
)
|
||
else:
|
||
ttk.Label(body, text=(
|
||
f"Защитный порог капитала: {summary['equity_stop_pct']:g}% от начального "
|
||
"(с учётом открытого P&L и оценочной комиссии закрытия); не достигнут."
|
||
), wraplength=1050).pack(anchor="w", pady=(0, 8))
|
||
gate_items = list(summary["entry_allowed_at_end"].items())
|
||
gate_state = " · ".join(
|
||
f"{symbol}: входы {'разрешены' if allowed else 'заблокированы'}"
|
||
for symbol, allowed in gate_items[:30]
|
||
) + (f" · … ещё {len(gate_items) - 30}" if len(gate_items) > 30 else "")
|
||
ttk.Label(body, text=f"{summary['entry_filter']} {gate_state}", wraplength=1050).pack(anchor="w", pady=(0, 6))
|
||
table_frame = ttk.Frame(body)
|
||
table_frame.pack(fill="both", expand=True)
|
||
columns = ("symbol", "side", "status", "opened", "closed", "entry", "exit", "entries", "gross", "fees",
|
||
"funding", "net", "roi", "reason")
|
||
tree = ttk.Treeview(table_frame, columns=columns, show="headings")
|
||
heads = {"symbol": "Тикер", "side": "Сторона", "status": "Статус", "opened": "Вход UTC", "closed": "Выход UTC",
|
||
"entry": "Средняя входа", "exit": "Выход / цена", "entries": "Входов",
|
||
"gross": "Gross USDT", "fees": "Комиссии", "funding": "Funding", "net": "Net USDT",
|
||
"roi": "ROI %", "reason": "Причина"}
|
||
widths = {"symbol": 90, "side": 60, "status": 66, "opened": 135, "closed": 135, "entry": 100, "exit": 100,
|
||
"entries": 55, "gross": 88, "fees": 80, "funding": 80, "net": 88, "roi": 70, "reason": 210}
|
||
for column in columns:
|
||
tree.heading(column, text=heads[column])
|
||
tree.column(column, width=widths[column], anchor="center")
|
||
tree.tag_configure("profit", foreground="#13843b")
|
||
tree.tag_configure("loss", foreground="#c62828")
|
||
tree.pack(side="left", fill="both", expand=True)
|
||
scrollbar = ttk.Scrollbar(table_frame, orient="vertical", command=tree.yview)
|
||
tree.configure(yscrollcommand=scrollbar.set)
|
||
scrollbar.pack(side="right", fill="y")
|
||
for trade in result["trades"]:
|
||
tree.insert("", "end", values=(
|
||
trade["symbol"], trade.get("side", "LONG"), trade["status"], trade["opened_at"][:19].replace("T", " "),
|
||
trade["closed_at"][:19].replace("T", " ") if trade["closed_at"] else "—",
|
||
f"{trade['entry']:.10g}", f"{trade['exit']:.10g}", trade["entries"],
|
||
f"{trade['gross_usdt']:+.4f}", f"{trade['fees_usdt']:.4f}", f"{trade.get('funding_usdt', 0.0):+.4f}",
|
||
f"{trade['net_usdt']:+.4f}", f"{trade['roi_pct']:+.2f}", trade["reason"],
|
||
), tags=("profit" if trade["net_usdt"] > 0 else "loss" if trade["net_usdt"] < 0 else "",))
|
||
ttk.Label(body, text=summary["assumptions"], wraplength=1050, justify="left").pack(anchor="w", pady=8)
|
||
ttk.Label(body, text=f"CSV: {csv_path} · Сводка: {json_path}", wraplength=1050).pack(anchor="w")
|
||
|
||
def _begin_live_preflight(self, symbol: str, settings: dict[str, float],
|
||
per_symbol_settings: dict[str, dict[str, float]] | None = None) -> None:
|
||
api_key = self.api_key_var.get().strip()
|
||
api_secret = self.api_secret_var.get().strip()
|
||
if not api_key or not api_secret:
|
||
messagebox.showerror("Нет API-данных", "Откройте «API Bybit…» и вставьте API key и API secret.")
|
||
self.open_live_settings()
|
||
return
|
||
all_settings = list((per_symbol_settings or {}).values()) or [settings]
|
||
no_stop = [item for item in all_settings if item.get("stop_loss", 0) <= 0]
|
||
if no_stop and not self.testnet_var.get():
|
||
worst_leverage = max(item.get("leverage", 1) for item in no_stop)
|
||
if not messagebox.askyesno(
|
||
"Стоп-лосс выключен",
|
||
"У части валют стоп-лосс равен 0: убыток позиции ничем не ограничен, а доливки "
|
||
"увеличивают объём при падении цены"
|
||
+ (f". При плече {worst_leverage:g}x позицию может ликвидировать биржа" if worst_leverage > 1 else "")
|
||
+ ".\n\nВсё равно запустить на Mainnet?",
|
||
icon="warning",
|
||
):
|
||
return
|
||
if not self.testnet_var.get() and not messagebox.askyesno(
|
||
"Подтвердите реальные ордера",
|
||
f"Будут отправляться реальные рыночные ордера по {', '.join(sorted(self.enabled_symbols))} "
|
||
f"с плечом {settings['leverage']:g}. "
|
||
"Биржевые TP/SL останутся активны, пока позиция открыта. Продолжить на Mainnet?",
|
||
icon="warning",
|
||
):
|
||
return
|
||
self.live_preflight = True
|
||
self.mode_combo.configure(state="disabled")
|
||
self.start_btn.configure(state="disabled")
|
||
network_name = "Testnet" if self.testnet_var.get() else "Mainnet"
|
||
self.status_var.set(f"Проверяю API Bybit ({network_name})…")
|
||
thread = threading.Thread(
|
||
target=self._live_preflight_multi_worker,
|
||
args=(api_key, api_secret, self.testnet_var.get(), sorted(self.enabled_symbols),
|
||
settings.copy(), per_symbol_settings or {}),
|
||
daemon=True,
|
||
)
|
||
thread.start()
|
||
|
||
def _live_preflight_multi_worker(self, api_key: str, api_secret: str, testnet: bool,
|
||
symbols: list[str], base_settings: dict[str, float],
|
||
per_symbol_settings: dict[str, dict[str, float]]) -> None:
|
||
"""Validate and reconcile every enabled symbol before starting parallel live loops."""
|
||
try:
|
||
client = BybitLiveClient(api_key, api_secret, testnet)
|
||
wallet = client.get_wallet()
|
||
baseline_key = self._deposit_baseline_key(api_key, testnet)
|
||
baseline = float(self.live_initial_deposits.get(baseline_key, 0) or wallet.get("wallet") or 0)
|
||
if baseline <= 0:
|
||
raise BybitAPIError("Не удалось определить стартовый депозит аккаунта для расчёта ставки")
|
||
prepared = []
|
||
projected_available = float(wallet.get("available") or 0)
|
||
for symbol in symbols:
|
||
settings = per_symbol_settings.get(symbol, base_settings).copy()
|
||
settings["deposit_basis"] = baseline
|
||
settings["stake"] = baseline * settings["stake_pct"] / 100
|
||
spec = client.get_instrument(symbol)
|
||
fee_pct = client.get_taker_fee_pct(symbol)
|
||
rows = client.get_positions(symbol)
|
||
if any(int(row.get("positionIdx", 0)) != 0 for row in rows):
|
||
raise BybitAPIError(f"{symbol}: для бота нужен режим позиции One-Way (positionIdx=0), а не Hedge")
|
||
exchange_position = next((row for row in rows if float(row.get("size") or 0) > 0), None)
|
||
saved_position = self.symbol_states.get(symbol, CurrencyState()).live_position
|
||
if saved_position is None and self.live_position and self.live_position.symbol == symbol:
|
||
saved_position = self.live_position
|
||
resume_position = None
|
||
if exchange_position:
|
||
if exchange_position.get("side") != "Buy":
|
||
raise BybitAPIError(f"{symbol}: найдена SHORT-позиция; бот сопровождает только LONG")
|
||
actual_leverage = float(exchange_position.get("leverage") or settings["leverage"])
|
||
settings["leverage"] = actual_leverage
|
||
avg = float(exchange_position.get("avgPrice") or (saved_position.entry_price if saved_position else 0))
|
||
qty = float(exchange_position.get("size") or 0)
|
||
if avg <= 0 or qty <= 0:
|
||
raise BybitAPIError(f"{symbol}: у Bybit-позиции нет цены или размера")
|
||
if saved_position:
|
||
resume_position = Position(**vars(saved_position))
|
||
changed = abs(qty - saved_position.qty) > float(spec["qty_step"]) * 2
|
||
resume_position.entry_price = avg
|
||
resume_position.qty = qty
|
||
resume_position.stake = avg * qty / actual_leverage
|
||
if changed:
|
||
resume_position.add_count = settings["max_adds"]
|
||
else:
|
||
resume_position = Position(self._allocate_live_id(), symbol, avg, qty,
|
||
avg * qty / actual_leverage, avg * qty * fee_pct / 100,
|
||
time.time(), avg, settings["max_adds"])
|
||
tp_pct = max(settings["take_profit"], self._fee_cover_pct(fee_pct))
|
||
client.update_position_stops(symbol,
|
||
avg * (1 + tp_pct / 100) if settings["take_profit"] > 0 else 0.0,
|
||
avg * (1 - settings["stop_loss"] / 100) if settings["stop_loss"] > 0 else 0.0,
|
||
spec["tick_size"])
|
||
else:
|
||
if saved_position:
|
||
# The saved position was closed on Bybit while the app was off:
|
||
# record its realized result instead of silently dropping it.
|
||
closed = client.get_latest_closed_pnl(symbol, int(saved_position.opened_at * 1000))
|
||
self.events.put(("live_restored_closed", closed, saved_position))
|
||
required = settings["stake"] * (1 + settings["leverage"] * fee_pct / 100)
|
||
if projected_available < required:
|
||
raise BybitAPIError(
|
||
f"{symbol}: для всех включённых валют не хватает свободной маржи; "
|
||
f"после предыдущих резервов осталось {projected_available:.2f} USDT, нужно около {required:.2f} USDT"
|
||
)
|
||
projected_available -= required
|
||
client.set_leverage(symbol, settings["leverage"])
|
||
settings["fee"] = fee_pct
|
||
prepared.append((symbol, settings, spec, fee_pct, exchange_position, resume_position))
|
||
self.events.put(("live_ready_multi", client, wallet, prepared, baseline_key, baseline))
|
||
except Exception as exc:
|
||
self.events.put(("live_preflight_failed", str(exc)))
|
||
|
||
def _activate_live_multi(self, client: BybitLiveClient, wallet: dict[str, float], prepared: list,
|
||
baseline_key: str | None, baseline: float) -> None:
|
||
self._capture_active_symbol()
|
||
self.live_preflight = False
|
||
self.mode_combo.configure(state="readonly")
|
||
self.live_client = client
|
||
self.live_wallet = wallet
|
||
if baseline_key:
|
||
self.live_initial_deposits[baseline_key] = float(baseline)
|
||
self.live_order_lock = threading.Lock()
|
||
self.running = True
|
||
self.next_auto_currency_scan_at = 0.0
|
||
self.session_started_at = time.time()
|
||
self.start_btn.configure(state="disabled")
|
||
self.stop_btn.configure(state="normal")
|
||
for symbol, settings, spec, fee_pct, exchange_position, resume_position in prepared:
|
||
state = self._ensure_symbol(symbol)
|
||
self.enabled_symbols.add(symbol)
|
||
state.live_position = resume_position
|
||
state.live_position_info = exchange_position
|
||
state.live_order_busy = False
|
||
state.live_transition_pending = False
|
||
state.live_halted = False
|
||
self.live_commands_by_symbol[symbol] = queue.Queue()
|
||
if resume_position:
|
||
self._reserve_live_id(resume_position.trade_id)
|
||
if exchange_position:
|
||
self._replace_cached_position(exchange_position)
|
||
else:
|
||
self._replace_cached_position(None, symbol)
|
||
self._fetch_baseline_async(symbol, self.interval_minutes)
|
||
worker = threading.Thread(target=self._live_worker,
|
||
args=(client, symbol, settings.copy(), spec, fee_pct, resume_position,
|
||
self.live_commands_by_symbol[symbol]), daemon=True)
|
||
self.live_workers[symbol] = worker
|
||
worker.start()
|
||
selected = self.symbol_var.get().strip().upper()
|
||
if selected not in self.enabled_symbols:
|
||
selected = prepared[0][0]
|
||
self.symbol_var.set(selected)
|
||
selected_config = next((item for item in prepared if item[0] == selected), prepared[0])
|
||
self.applied_settings = selected_config[1].copy()
|
||
self.live_spec = selected_config[2]
|
||
self.live_fee_pct = selected_config[3]
|
||
self._activate_symbol_state(selected)
|
||
self.ws_symbols = sorted(self.enabled_symbols | {s for s, state in self.symbol_states.items() if state.live_position})
|
||
self.ws_thread = threading.Thread(target=self._ws_worker, args=(self.ws_symbols,), daemon=True)
|
||
self.ws_thread.start()
|
||
self.status_var.set(f"Реальный бот запущен параллельно · {len(prepared)} валют · {'Testnet' if client.testnet else 'MAINNET'}")
|
||
self.live_account_var.set(f"{'Testnet' if client.testnet else 'MAINNET'} · equity {wallet['equity']:.2f} · доступно {wallet['available']:.2f} USDT")
|
||
self._refresh_settings_summary()
|
||
self._refresh_ui()
|
||
self._refresh_currency_tiles()
|
||
self._save_account_state()
|
||
|
||
def _live_preflight_worker(self, api_key: str, api_secret: str, testnet: bool, symbol: str,
|
||
settings: dict[str, float], saved_position: Position | None) -> None:
|
||
try:
|
||
client = BybitLiveClient(api_key, api_secret, testnet)
|
||
wallet = client.get_wallet()
|
||
baseline_key = self._deposit_baseline_key(api_key, testnet)
|
||
baseline = float(self.live_initial_deposits.get(baseline_key, 0) or wallet.get("wallet") or 0)
|
||
if baseline <= 0:
|
||
raise BybitAPIError("Не удалось определить стартовый депозит аккаунта для расчёта ставки")
|
||
settings["deposit_basis"] = baseline
|
||
settings["stake"] = baseline * settings["stake_pct"] / 100
|
||
spec = client.get_instrument(symbol)
|
||
fee_pct = client.get_taker_fee_pct(symbol)
|
||
rows = client.get_positions(symbol)
|
||
if any(int(row.get("positionIdx", 0)) != 0 for row in rows):
|
||
raise BybitAPIError("Для этого бота нужен режим позиции One-Way (positionIdx=0), а не Hedge")
|
||
exchange_position = next((row for row in rows if float(row.get("size") or 0) > 0), None)
|
||
resume_position = None
|
||
if exchange_position:
|
||
if exchange_position.get("side") != "Buy":
|
||
raise BybitAPIError("По тикеру уже открыта SHORT-позиция; бот управляет только LONG")
|
||
if saved_position and saved_position.symbol != symbol:
|
||
raise BybitAPIError(
|
||
f"В истории программы есть позиция {saved_position.symbol}, а на бирже обнаружена {symbol}. "
|
||
"Укажите тикер открытой позиции, чтобы продолжить её сопровождение."
|
||
)
|
||
actual_leverage = float(exchange_position.get("leverage") or settings["leverage"])
|
||
settings["leverage"] = actual_leverage
|
||
avg = float(exchange_position.get("avgPrice") or (saved_position.entry_price if saved_position else 0))
|
||
qty = float(exchange_position.get("size") or 0)
|
||
if avg <= 0 or qty <= 0:
|
||
raise BybitAPIError("Bybit вернул открытую позицию без цены или размера; сопровождение не запущено")
|
||
if saved_position:
|
||
# Reconcile local shadow against the authoritative position.
|
||
# This also recovers fills that happened just before a shutdown.
|
||
resume_position = Position(**vars(saved_position))
|
||
quantity_changed = abs(qty - saved_position.qty) > float(spec["qty_step"]) * 2
|
||
resume_position.entry_price = avg
|
||
resume_position.qty = qty
|
||
resume_position.stake = avg * qty / actual_leverage
|
||
resume_position.last_add_price = resume_position.last_add_price or avg
|
||
if quantity_changed:
|
||
# The precise number of fills may be unknown after a
|
||
# crash; avoid exceeding the configured add limit.
|
||
resume_position.add_count = settings["max_adds"]
|
||
else:
|
||
# Adopt an existing LONG even when the app has no local
|
||
# shadow (e.g. the process restarted after a fill).
|
||
now = time.time()
|
||
resume_position = Position(
|
||
self._allocate_live_id(), symbol, avg, qty, avg * qty / actual_leverage,
|
||
avg * qty * fee_pct / 100, now, avg, settings["max_adds"],
|
||
)
|
||
tp_pct = max(settings["take_profit"], self._fee_cover_pct(fee_pct))
|
||
tp = avg * (1 + tp_pct / 100) if settings["take_profit"] > 0 else 0.0
|
||
sl = avg * (1 - settings["stop_loss"] / 100) if settings["stop_loss"] > 0 else 0.0
|
||
client.update_position_stops(symbol, tp, sl, spec["tick_size"])
|
||
else:
|
||
if saved_position:
|
||
closed = client.get_latest_closed_pnl(symbol, int(saved_position.opened_at * 1000))
|
||
self.events.put(("live_restored_closed", closed, saved_position))
|
||
required = settings["stake"] * (1 + settings["leverage"] * fee_pct / 100)
|
||
if wallet["available"] < required:
|
||
raise BybitAPIError(f"Доступно {wallet['available']:.2f} USDT, требуется около {required:.2f} USDT на маржу и комиссию")
|
||
client.set_leverage(symbol, settings["leverage"])
|
||
self.events.put(("live_ready", client, wallet, spec, fee_pct, settings, symbol,
|
||
exchange_position, resume_position, baseline_key, baseline))
|
||
except Exception as exc:
|
||
self.events.put(("live_preflight_failed", str(exc)))
|
||
|
||
def _activate_live(self, client: BybitLiveClient, wallet: dict[str, float], spec: dict[str, str],
|
||
fee_pct: float, settings: dict[str, float], symbol: str, exchange_position: dict | None,
|
||
resume_position: Position | None, baseline_key: str | None = None,
|
||
baseline: float | None = None) -> None:
|
||
self.live_preflight = False
|
||
self.mode_combo.configure(state="readonly")
|
||
self.live_client = client
|
||
self.live_wallet = wallet
|
||
if baseline_key:
|
||
self.live_initial_deposits[baseline_key] = float(baseline or settings.get("deposit_basis") or wallet.get("wallet") or 0)
|
||
self._save_account_state()
|
||
self.live_spec = spec
|
||
self.live_fee_pct = fee_pct
|
||
settings["fee"] = fee_pct
|
||
self.applied_settings = settings.copy()
|
||
self.symbol = symbol
|
||
self.interval_minutes = CANDLE_INTERVAL_MINUTES
|
||
self.live_halted = False
|
||
self.live_order_busy = False
|
||
self.live_transition_pending = False
|
||
if exchange_position:
|
||
if resume_position is None:
|
||
raise RuntimeError("Не удалось восстановить данные открытой позиции Bybit")
|
||
self.live_position = resume_position
|
||
self._reserve_live_id(resume_position.trade_id)
|
||
self.leverage_var.set(str(settings["leverage"]))
|
||
self.live_position_info = exchange_position
|
||
self._replace_cached_position(exchange_position)
|
||
self.live_account_var.set(f"{'Testnet' if client.testnet else 'MAINNET'} · Equity {wallet['equity']:.2f} · доступно {wallet['available']:.2f} USDT")
|
||
self._save_account_state()
|
||
self.status_var.set(
|
||
f"Открытая позиция Bybit восстановлена · {symbol} · средняя {resume_position.entry_price:g} · "
|
||
f"объём {resume_position.qty:g}; управление возобновлено"
|
||
)
|
||
else:
|
||
self.live_position_info = None
|
||
self.live_positions = [row for row in self.live_positions if row.get("symbol") != symbol]
|
||
self._render_bybit_positions()
|
||
self.live_account_var.set(f"{'Testnet' if client.testnet else 'MAINNET'} · стартовый депозит {settings.get('deposit_basis', wallet['wallet']):.2f} · кошелёк {wallet['wallet']:.2f} · доступно {wallet['available']:.2f} USDT")
|
||
self.running = True
|
||
self.start_btn.configure(state="disabled")
|
||
self.stop_btn.configure(state="normal")
|
||
restored = " · сопровождение открытой позиции восстановлено" if exchange_position else ""
|
||
self.status_var.set(f"Реальный бот запущен · {symbol} · {'Testnet' if client.testnet else 'MAINNET'}{restored}")
|
||
self._refresh_settings_summary()
|
||
self._refresh_ui()
|
||
self._fetch_baseline_async(symbol, self.interval_minutes)
|
||
self.ws_thread = threading.Thread(target=self._ws_worker, args=(symbol,), daemon=True)
|
||
self.ws_thread.start()
|
||
self.live_control_thread = threading.Thread(target=self._live_worker, args=(client, symbol, settings.copy(), spec, fee_pct, self.live_position), daemon=True)
|
||
self.live_control_thread.start()
|
||
self._save_account_state()
|
||
|
||
def _allocate_live_id(self) -> int:
|
||
"""Return a unique live trade id; safe to call from worker threads."""
|
||
with self._live_id_lock:
|
||
trade_id = self.next_live_id
|
||
self.next_live_id += 1
|
||
return trade_id
|
||
|
||
def _reserve_live_id(self, trade_id: int) -> None:
|
||
"""Make sure future ids are above an id restored from disk or the exchange."""
|
||
with self._live_id_lock:
|
||
self.next_live_id = max(self.next_live_id, trade_id + 1)
|
||
|
||
def _replace_cached_position(self, row: dict | None, symbol: str | None = None) -> None:
|
||
target = symbol or (row.get("symbol") if row else None)
|
||
if target:
|
||
self.live_positions = [item for item in self.live_positions if item.get("symbol") != target]
|
||
if row and float(row.get("size") or 0) > 0:
|
||
self.live_positions.append(row)
|
||
self._render_bybit_positions()
|
||
|
||
def _live_worker(self, client: BybitLiveClient, symbol: str, settings: dict[str, float],
|
||
spec: dict[str, str], fee_pct: float, shadow: Position | None,
|
||
command_queue: queue.Queue | None = None) -> None:
|
||
command_queue = command_queue or self.live_commands
|
||
try:
|
||
self._live_worker_loop(client, symbol, settings, spec, fee_pct, shadow, command_queue)
|
||
finally:
|
||
# Let the UI thread unregister this worker's queue so the symbol can get a
|
||
# fresh worker when it is enabled again (manually or by auto-rotation).
|
||
self.events.put(("live_worker_exited", symbol, command_queue))
|
||
|
||
def _live_worker_loop(self, client: BybitLiveClient, symbol: str, settings: dict[str, float],
|
||
spec: dict[str, str], fee_pct: float, shadow: Position | None,
|
||
command_queue: queue.Queue) -> None:
|
||
last_wallet_at = 0.0
|
||
last_position_at = 0.0
|
||
while self.running:
|
||
if symbol not in self.enabled_symbols and shadow is None:
|
||
return
|
||
try:
|
||
command = command_queue.get(timeout=0.4)
|
||
except queue.Empty:
|
||
command = None
|
||
try:
|
||
if command:
|
||
action, timestamp, price, *extra = command
|
||
if action == "settings":
|
||
updated_settings = extra[0]
|
||
updated_settings["fee"] = fee_pct
|
||
if updated_settings["leverage"] != settings["leverage"]:
|
||
client.set_leverage(symbol, updated_settings["leverage"])
|
||
settings = updated_settings
|
||
if shadow:
|
||
action = "stops"
|
||
else:
|
||
self.events.put(("live_settings_updated", symbol))
|
||
action = "settings_done"
|
||
if action in ("open", "add"):
|
||
skip_reason = None
|
||
with self.live_order_lock:
|
||
wallet_now = client.get_wallet()
|
||
required = settings["stake"] * (1 + settings["leverage"] * fee_pct / 100)
|
||
order_qty = ""
|
||
notional = 0.0
|
||
if wallet_now["available"] < required:
|
||
skip_reason = (f"недостаточно доступной маржи: {wallet_now['available']:.2f} USDT; "
|
||
f"требуется около {required:.2f} USDT с учётом комиссии")
|
||
else:
|
||
try:
|
||
order_qty = client.floor_qty(settings["stake"] * settings["leverage"] / price, spec)
|
||
except BybitAPIError as exc:
|
||
skip_reason = str(exc)
|
||
else:
|
||
notional = float(order_qty) * price
|
||
minimum = float(spec.get("min_notional") or 0)
|
||
if notional < minimum:
|
||
skip_reason = (f"размер заявки {notional:.4f} USDT меньше минимума "
|
||
f"контракта {minimum:g} USDT")
|
||
if skip_reason:
|
||
# A skipped signal is not an exchange failure: keep managing the
|
||
# symbol. For an add, consume this level (same rule as simulation
|
||
# and backtest) so the next add is measured from this price.
|
||
if action == "add" and shadow is not None:
|
||
shadow.last_add_price = price
|
||
self.events.put(("live_order_skipped", symbol, action, skip_reason, price))
|
||
continue
|
||
added_qty = float(order_qty)
|
||
expected_avg = price if shadow is None else (shadow.entry_price * shadow.qty + price * added_qty) / (shadow.qty + added_qty)
|
||
target_pct = max(settings["take_profit"], self._fee_cover_pct(fee_pct))
|
||
tp = expected_avg * (1 + target_pct / 100) if settings["take_profit"] > 0 else 0.0
|
||
sl = expected_avg * (1 - settings["stop_loss"] / 100) if settings["stop_loss"] > 0 else 0.0
|
||
submitted_at_ms = int(time.time() * 1000)
|
||
order_id = client.place_market_buy(symbol, order_qty, tp, sl, spec["tick_size"])
|
||
row = None
|
||
order_info = None
|
||
closed_row = None
|
||
no_fill_status = None
|
||
for attempt in range(20):
|
||
time.sleep(.5)
|
||
row = client.get_open_position(symbol)
|
||
if row and row.get("side") == "Buy":
|
||
break
|
||
if attempt % 4 == 3 and order_id:
|
||
order_info = client.get_order(symbol, order_id)
|
||
if order_info:
|
||
order_status = str(order_info.get("orderStatus") or "")
|
||
executed_qty = float(order_info.get("cumExecQty") or 0)
|
||
if order_status in {"Cancelled", "Rejected", "Deactivated"} and executed_qty <= 0:
|
||
no_fill_status = order_status
|
||
break
|
||
if order_status == "Filled":
|
||
closed_row = client.get_latest_closed_pnl(symbol, submitted_at_ms - 2000)
|
||
if (closed_row and int(closed_row.get("updatedTime") or 0) >= submitted_at_ms - 2000
|
||
and float(closed_row.get("closedSize") or 0) > 0):
|
||
break
|
||
if no_fill_status:
|
||
self.events.put(("live_order_no_fill", symbol, action, no_fill_status))
|
||
continue
|
||
if not row and not closed_row:
|
||
# Keep the execution worker alive and block further
|
||
# entries until the exchange can confirm the order.
|
||
# Never resend an order whose result is ambiguous.
|
||
self.events.put(("live_order_pending", symbol, order_id))
|
||
while self.running and not row and not no_fill_status and not closed_row:
|
||
time.sleep(2.0)
|
||
try:
|
||
row = client.get_open_position(symbol)
|
||
if row:
|
||
break
|
||
order_info = client.get_order(symbol, order_id) if order_id else None
|
||
if order_info:
|
||
order_status = str(order_info.get("orderStatus") or "")
|
||
executed_qty = float(order_info.get("cumExecQty") or 0)
|
||
if order_status in {"Cancelled", "Rejected", "Deactivated"} and executed_qty <= 0:
|
||
no_fill_status = order_status
|
||
break
|
||
if order_status == "Filled" or executed_qty > 0:
|
||
closed_row = client.get_latest_closed_pnl(symbol, submitted_at_ms - 2000)
|
||
if (closed_row and int(closed_row.get("updatedTime") or 0) >= submitted_at_ms - 2000
|
||
and float(closed_row.get("closedSize") or 0) > 0):
|
||
break
|
||
except Exception:
|
||
# Transient API failures do not justify
|
||
# duplicating an order with unknown status.
|
||
continue
|
||
if not self.running:
|
||
return
|
||
if no_fill_status:
|
||
self.events.put(("live_order_no_fill", symbol, action, no_fill_status))
|
||
continue
|
||
if not row and closed_row:
|
||
# A fast TP/SL can close the position before the
|
||
# position endpoint ever observes it. Record the
|
||
# exchange's realized result and continue the loop.
|
||
closed_avg = float(closed_row.get("avgEntryPrice") or expected_avg)
|
||
closed_qty = float(closed_row.get("closedSize") or closed_row.get("qty") or added_qty)
|
||
if shadow is None:
|
||
recovered_id = self._allocate_live_id()
|
||
shadow = Position(
|
||
recovered_id, symbol, closed_avg, closed_qty,
|
||
closed_avg * closed_qty / settings["leverage"],
|
||
float(closed_row.get("openFee") or 0), timestamp, closed_avg, 0,
|
||
)
|
||
else:
|
||
shadow.entry_price = closed_avg
|
||
shadow.qty = closed_qty
|
||
shadow.stake = closed_avg * closed_qty / settings["leverage"]
|
||
wallet = client.get_wallet()
|
||
self.symbol_states.setdefault(symbol, CurrencyState()).live_transition_pending = True
|
||
self.events.put(("live_closed", shadow, closed_row, wallet,
|
||
"TP/стоп Bybit сработал сразу после входа"))
|
||
shadow = None
|
||
last_position_at = time.time()
|
||
last_wallet_at = last_position_at
|
||
continue
|
||
if not row or row.get("side") != "Buy":
|
||
raise BybitAPIError("Bybit подтвердил позицию в неизвестном направлении; автоматическое управление остановлено")
|
||
avg = float(row["avgPrice"])
|
||
qty = float(row["size"])
|
||
stake_total = avg * qty / settings["leverage"]
|
||
if shadow is None:
|
||
shadow = Position(self._allocate_live_id(), symbol, avg, qty, stake_total,
|
||
notional * fee_pct / 100, timestamp, price, 0)
|
||
else:
|
||
shadow.entry_price = avg
|
||
shadow.qty = qty
|
||
shadow.stake = stake_total
|
||
shadow.entry_fee += notional * fee_pct / 100
|
||
shadow.last_add_price = price
|
||
shadow.add_count += 1
|
||
# Persist the confirmed fill before any follow-up API call can fail.
|
||
self.events.put(("live_order_result", symbol, action, shadow, row, None))
|
||
actual_tp_pct = max(settings["take_profit"], self._fee_cover_pct(fee_pct))
|
||
actual_tp = avg * (1 + actual_tp_pct / 100) if settings["take_profit"] > 0 else 0.0
|
||
actual_sl = avg * (1 - settings["stop_loss"] / 100) if settings["stop_loss"] > 0 else 0.0
|
||
client.update_position_stops(symbol, actual_tp, actual_sl, spec["tick_size"])
|
||
wallet = client.get_wallet()
|
||
self.events.put(("live_sync", symbol, shadow, row, wallet))
|
||
last_position_at = time.time()
|
||
last_wallet_at = last_position_at
|
||
elif action == "close" and not shadow:
|
||
self.events.put(("live_order_skipped", symbol, action, "нет открытой позиции", price))
|
||
elif action == "close" and shadow:
|
||
qty = client.floor_qty(shadow.qty, spec)
|
||
client.close_long_market(symbol, qty)
|
||
# Poll for the exchange to confirm instead of failing after one short check.
|
||
deadline = time.time() + MANUAL_CLOSE_CONFIRM_SECONDS
|
||
row = None
|
||
while self.running:
|
||
time.sleep(0.5)
|
||
try:
|
||
row = client.get_open_position(symbol)
|
||
except BybitAPIError:
|
||
row = shadow # unknown state: keep waiting until the deadline
|
||
if not row or time.time() >= deadline:
|
||
break
|
||
if row:
|
||
# Still open (or unknown): keep managing the position; the user can retry.
|
||
self.events.put(("live_order_skipped", symbol, action,
|
||
"Bybit не подтвердил закрытие за "
|
||
f"{MANUAL_CLOSE_CONFIRM_SECONDS} с; позиция остаётся под управлением, "
|
||
"проверьте её на бирже", price))
|
||
last_position_at = 0.0
|
||
continue
|
||
closed_row = client.get_latest_closed_pnl(symbol, int(shadow.opened_at * 1000))
|
||
wallet = client.get_wallet()
|
||
self.symbol_states.setdefault(symbol, CurrencyState()).live_transition_pending = True
|
||
self.events.put(("live_closed", shadow, closed_row, wallet, "Ручное закрытие"))
|
||
shadow = None
|
||
last_wallet_at = time.time()
|
||
elif action == "stops" and shadow:
|
||
avg = shadow.entry_price
|
||
target_pct = max(settings["take_profit"], self._fee_cover_pct(fee_pct))
|
||
tp = avg * (1 + target_pct / 100) if settings["take_profit"] > 0 else 0.0
|
||
sl = avg * (1 - settings["stop_loss"] / 100) if settings["stop_loss"] > 0 else 0.0
|
||
client.update_position_stops(symbol, tp, sl, spec["tick_size"])
|
||
self.events.put(("live_stops_updated", symbol))
|
||
now = time.time()
|
||
if now - last_position_at >= 2.0:
|
||
row = client.get_open_position(symbol)
|
||
if row is None and shadow is not None:
|
||
closed_row = client.get_latest_closed_pnl(symbol, int(shadow.opened_at * 1000))
|
||
wallet = client.get_wallet()
|
||
self.symbol_states.setdefault(symbol, CurrencyState()).live_transition_pending = True
|
||
self.events.put(("live_closed", shadow, closed_row, wallet, "TP/стоп на Bybit"))
|
||
shadow = None
|
||
last_wallet_at = now
|
||
elif row is not None and shadow is None:
|
||
raise BybitAPIError("На аккаунте появилась позиция без записи бота. Автоматическая торговля остановлена")
|
||
elif row is not None:
|
||
shadow.entry_price = float(row.get("avgPrice") or shadow.entry_price)
|
||
shadow.qty = float(row.get("size") or shadow.qty)
|
||
shadow.stake = shadow.entry_price * shadow.qty / settings["leverage"]
|
||
wallet = client.get_wallet() if now - last_wallet_at >= 8.0 else None
|
||
self.events.put(("live_sync", symbol, shadow, row, wallet))
|
||
if wallet:
|
||
last_wallet_at = now
|
||
last_position_at = now
|
||
except Exception as exc:
|
||
self.events.put(("live_worker_failed", symbol, str(exc)))
|
||
break
|
||
|
||
def _position_limit_or_none(self) -> int | None:
|
||
try:
|
||
return self._simulation_position_limit()
|
||
except ValueError:
|
||
return None
|
||
|
||
def _live_slots_in_use(self) -> int:
|
||
"""Open live positions plus entries already sent and not yet reconciled."""
|
||
self._capture_active_symbol()
|
||
return sum(1 for state in self.symbol_states.values()
|
||
if state.live_position is not None
|
||
or (state.live_order_busy and state.live_position is None))
|
||
|
||
def _on_live_tick(self, timestamp: float, price: float, crossed_entry_threshold: bool) -> None:
|
||
if self.live_order_busy or self.live_halted or self.live_transition_pending or not self.live_client:
|
||
return
|
||
settings = self.strategy_by_symbol.get(self.symbol) or self.applied_settings or self._safe_read_settings()
|
||
if self.live_position is None:
|
||
if (crossed_entry_threshold and self.symbol in self.enabled_symbols
|
||
and self.symbol not in self.rotation_pending_disable):
|
||
limit = self._position_limit_or_none()
|
||
if limit is not None and self._live_slots_in_use() >= limit:
|
||
self.status_var.set(f"Вход {self.symbol} пропущен: лимит одновременных позиций {limit} занят")
|
||
return
|
||
self.live_order_busy = True
|
||
commands = self.live_commands_by_symbol.get(self.symbol, self.live_commands)
|
||
commands.put(("open", timestamp, price))
|
||
self.status_var.set(f"Сигнал входа · отправляю рыночный ордер {self.symbol}")
|
||
elif (self.symbol in self.enabled_symbols and self.symbol not in self.rotation_pending_disable
|
||
and strategy.can_add(self.live_position.add_count, settings["max_adds"], settings["add_step"])
|
||
and price <= strategy.add_level(self.live_position.last_add_price, settings["add_step"])):
|
||
# Pairs waiting for retirement only manage their position (same rule as the backtest).
|
||
self.live_order_busy = True
|
||
commands = self.live_commands_by_symbol.get(self.symbol, self.live_commands)
|
||
commands.put(("add", timestamp, price))
|
||
self.status_var.set(f"Уровень доливки · отправляю ордер {self.symbol}")
|
||
|
||
def _ws_worker(self, symbols: list[str] | str) -> None:
|
||
if isinstance(symbols, str):
|
||
symbols = [symbols]
|
||
while self.running:
|
||
try:
|
||
symbols = list(self.ws_symbols)
|
||
if not symbols:
|
||
time.sleep(1)
|
||
continue
|
||
def on_open(ws) -> None:
|
||
# Subscribe to whatever is current at connect time; later changes are
|
||
# applied with subscribe/unsubscribe on this socket (no reconnect).
|
||
with self._ws_lock:
|
||
selected = sorted(set(self.ws_symbols))
|
||
self._ws_send_topics(ws, "subscribe", selected)
|
||
self.ws_subscribed = set(selected)
|
||
|
||
app = websocket.WebSocketApp(
|
||
WS_URL,
|
||
on_open=on_open,
|
||
on_message=self._on_message,
|
||
on_error=lambda _ws, err: self.events.put(("status", f"Ошибка потока: {err}")),
|
||
on_close=lambda _ws, code, _msg: self.events.put(("status", f"Соединение закрыто ({code}); переподключение…")),
|
||
)
|
||
self.ws_app = app
|
||
app.run_forever(ping_interval=20, ping_timeout=10)
|
||
except Exception as exc:
|
||
self.events.put(("status", f"Ошибка подключения: {exc}"))
|
||
if self.running:
|
||
time.sleep(2)
|
||
|
||
def _on_message(self, _ws, message: str) -> None:
|
||
try:
|
||
packet = json.loads(message)
|
||
if packet.get("op") == "subscribe":
|
||
self.events.put(("status", "Поток Bybit подключён" if packet.get("success") else f"Подписка: {packet}"))
|
||
topic = str(packet.get("topic") or "")
|
||
symbol = topic.removeprefix("publicTrade.").upper()
|
||
if symbol not in self.ws_symbols:
|
||
return
|
||
for trade in packet.get("data", []):
|
||
price = float(trade["p"])
|
||
timestamp = int(trade["T"]) / 1000.0
|
||
self.events.put(("trade", symbol, timestamp, price))
|
||
except (ValueError, KeyError, TypeError, json.JSONDecodeError) as exc:
|
||
self.events.put(("status", f"Не удалось разобрать сообщение Bybit: {exc}"))
|
||
|
||
def stop(self) -> None:
|
||
if self.historical_running:
|
||
self._backtest_cancel.set()
|
||
self.status_var.set("Останавливаю исторический прогон…")
|
||
self.stop_btn.configure(state="disabled")
|
||
return
|
||
if not self.running:
|
||
return
|
||
self.running = False
|
||
self._save_account_state()
|
||
for commands in [self.live_commands, *self.live_commands_by_symbol.values()]:
|
||
while True:
|
||
try:
|
||
commands.get_nowait()
|
||
except queue.Empty:
|
||
break
|
||
if self.ws_app:
|
||
try:
|
||
self.ws_app.close()
|
||
except Exception:
|
||
pass
|
||
if self.mode_var.get() == "Реальная торговля" and any(s.live_position for s in self.symbol_states.values()):
|
||
self.status_var.set("Мониторинг остановлен · биржевые TP/SL продолжают действовать на Bybit")
|
||
else:
|
||
self.status_var.set("Остановлен")
|
||
self.start_btn.configure(state="normal")
|
||
self.stop_btn.configure(state="disabled")
|
||
self._refresh_ui()
|
||
self._draw_chart()
|
||
|
||
def _poll_events(self) -> None:
|
||
handled = 0
|
||
while handled < MAX_EVENTS_PER_POLL:
|
||
try:
|
||
event = self.events.get_nowait()
|
||
except queue.Empty:
|
||
break
|
||
handled += 1
|
||
if event[0] == "historical_progress":
|
||
_, symbol, count, total, *stage = event
|
||
if self.historical_running:
|
||
detail = f" · {stage[0]}" if stage and stage[0] else ""
|
||
if symbol == "Отбор валют":
|
||
self.status_var.set(f"Отбор валют по истории: {count:,} из {total:,} контрактов{detail}")
|
||
elif symbol == "Funding":
|
||
self.status_var.set(f"Загружаю историю funding: {count:,} из {total:,} валют")
|
||
else:
|
||
self.status_var.set(f"Загружаю {symbol}: {count:,} из ~{total:,} свечей{detail}")
|
||
elif event[0] == "historical_completed":
|
||
_, result, csv_path, json_path = event
|
||
self.historical_running = False
|
||
self.mode_combo.configure(state="readonly")
|
||
self.start_btn.configure(state="normal", text="Запустить прогон")
|
||
self.stop_btn.configure(state="disabled")
|
||
summary = result["summary"]
|
||
self.status_var.set(
|
||
(f"Прогон остановлен по лимиту капитала {summary['equity_stop_pct']:g}% · "
|
||
if summary.get("equity_stop_triggered") else "Прогон завершён · ")
|
||
+ f"Net {summary['total_net_including_open_usdt']:+.2f} USDT · отчёт {csv_path}"
|
||
)
|
||
self._show_historical_report(result, csv_path, json_path)
|
||
elif event[0] == "historical_cancelled":
|
||
self.historical_running = False
|
||
self.mode_combo.configure(state="readonly")
|
||
self.start_btn.configure(state="normal", text="Запустить прогон")
|
||
self.stop_btn.configure(state="disabled")
|
||
self.status_var.set("Исторический прогон отменён")
|
||
elif event[0] == "historical_failed":
|
||
self.historical_running = False
|
||
self.mode_combo.configure(state="readonly")
|
||
self.start_btn.configure(state="normal", text="Запустить прогон")
|
||
self.stop_btn.configure(state="disabled")
|
||
self.status_var.set(f"Исторический прогон не выполнен: {event[1]}")
|
||
messagebox.showerror("Исторический прогон не выполнен", event[1])
|
||
elif event[0] == "startup_currency_filter_ready":
|
||
_, mode, threshold, snapshot, source = event
|
||
self.startup_currency_filter_busy = False
|
||
self.mode_combo.configure(state="readonly")
|
||
if mode != self.mode_var.get():
|
||
self.start_btn.configure(state="normal")
|
||
self.status_var.set("Режим изменён во время проверки. Нажмите «Старт» ещё раз.")
|
||
continue
|
||
self._apply_startup_currency_filter(mode, threshold, snapshot, source)
|
||
elif event[0] == "startup_currency_filter_failed":
|
||
_, mode, error = event
|
||
self.startup_currency_filter_busy = False
|
||
self.startup_currency_filter_approved_for = None
|
||
self.mode_combo.configure(state="readonly")
|
||
self.start_btn.configure(state="normal")
|
||
self.status_var.set(f"Предстартовая проверка не выполнена: {error}")
|
||
messagebox.showerror(
|
||
"Проверка валют не выполнена",
|
||
"Не удалось получить актуальные данные Bybit за 24 часа. Сделки не запущены.\n\n" + error,
|
||
)
|
||
elif event[0] == "status":
|
||
if self.running:
|
||
self.status_var.set(event[1])
|
||
elif event[0] == "api_connected":
|
||
self.api_connecting = False
|
||
self.connect_btn.configure(state="normal")
|
||
self._show_api_snapshot(*event[1:])
|
||
elif event[0] == "api_connect_failed":
|
||
self.api_connecting = False
|
||
self.connect_btn.configure(state="normal")
|
||
self.status_var.set(f"Не удалось подключиться к Bybit: {event[1]}")
|
||
messagebox.showerror("Подключение Bybit не выполнено", event[1])
|
||
elif event[0] == "baseline":
|
||
if self.running and int(event[2]) == self.interval_minutes:
|
||
self._capture_active_symbol()
|
||
state = self._ensure_symbol(event[1])
|
||
state.baseline_close = float(event[3])
|
||
state.previous_entry_signal_pct = None
|
||
if event[1] == self.symbol:
|
||
self._activate_symbol_state(event[1])
|
||
self.status_var.set(f"База сигнала {event[1]} загружена: закрытие {self.interval_minutes}-мин свечи")
|
||
self._refresh_rolling_change(reschedule=False)
|
||
elif event[0] == "trade" and self.running:
|
||
if len(event) >= 4:
|
||
self._on_trade(event[1], event[2], event[3])
|
||
else:
|
||
self._on_trade(self.symbol, event[1], event[2])
|
||
elif event[0] == "ticker_24h":
|
||
for symbol, (price, change, turnover) in event[1].items():
|
||
self.ticker_prices[symbol] = price
|
||
self.ticker_24h[symbol] = change
|
||
self.ticker_turnover_24h[symbol] = turnover
|
||
self.ticker_data_source = event[2] if len(event) > 2 else "Bybit"
|
||
if len(event) > 3:
|
||
self.ticker_funding_pct.update(event[3])
|
||
if self.auto_currency_status_var.get().startswith("Ошибка"):
|
||
self.auto_currency_status_var.set(f"Данные восстановлены · пар: {len(event[1])}")
|
||
self._refresh_currency_tiles()
|
||
for symbol in list(self.detail_windows):
|
||
self._draw_detail_chart(symbol)
|
||
self._maybe_auto_rotate_currencies()
|
||
elif event[0] == "mode_signal":
|
||
_, symbol, mode, bucket, tf_ms, signal, error = event
|
||
state = self._ensure_symbol(symbol)
|
||
state.mode_eval_busy = False
|
||
if mode != self.strategy_mode or not self.running:
|
||
continue
|
||
if error:
|
||
# Retry on the next poll unless the candle is long gone (e.g. a delisted pair).
|
||
if time.time() * 1000 - (bucket + tf_ms) > 60_000:
|
||
state.mode_signal_bucket = bucket
|
||
self.status_var.set(f"Сигнал {symbol}: {error}")
|
||
continue
|
||
state.mode_signal_bucket = bucket
|
||
self._capture_active_symbol()
|
||
if signal is not None and state.position is None:
|
||
signal["valid_until"] = (bucket + 2 * tf_ms) / 1000
|
||
signal["mode"] = mode
|
||
state.mode_signal = signal
|
||
side = "SHORT" if signal["side"] == "short" else "LONG"
|
||
self.status_var.set(
|
||
f"Сигнал {side} {symbol} · закрытие {self._fmt_price(signal['close'])} · "
|
||
f"ATR {self._fmt_price(signal['atr'])} · вход на следующей сделке"
|
||
)
|
||
self._request_redraw(symbol)
|
||
else:
|
||
state.mode_signal = None
|
||
elif event[0] == "ticker_24h_error":
|
||
self.auto_currency_status_var.set(f"Ошибка котировок: {event[1][:150]}")
|
||
elif event[0] == "chart_candles":
|
||
_, symbol, interval, candles, baseline = event
|
||
self._capture_active_symbol()
|
||
state = self._ensure_symbol(symbol)
|
||
if interval == self.interval_minutes:
|
||
merged = {int(row[0]): row for row in candles}
|
||
merged.update({int(row[0]): row for row in state.candles})
|
||
state.candles = deque([merged[key] for key in sorted(merged)[-300:]])
|
||
state.baseline_close = baseline
|
||
if symbol == self.symbol:
|
||
self._activate_symbol_state(symbol)
|
||
self._draw_chart()
|
||
self._draw_detail_chart(symbol)
|
||
elif event[0] == "live_ready":
|
||
self._activate_live(*event[1:])
|
||
elif event[0] == "live_ready_multi":
|
||
self._activate_live_multi(*event[1:])
|
||
elif event[0] == "live_symbol_ready":
|
||
_, symbol, settings, spec, fee_pct, row, shadow = event
|
||
self.live_preparing_symbols.discard(symbol)
|
||
self._activate_live_symbol(symbol, settings, spec, fee_pct, row, shadow)
|
||
elif event[0] == "live_symbol_failed":
|
||
_, symbol, error = event
|
||
self.live_preparing_symbols.discard(symbol)
|
||
was_auto_added = symbol in self.auto_enabling_symbols
|
||
self.auto_enabling_symbols.discard(symbol)
|
||
if was_auto_added:
|
||
self.auto_symbol_retry_after[symbol] = time.monotonic() + AUTO_CURRENCY_SCAN_SECONDS
|
||
self.enabled_symbols.discard(symbol)
|
||
self._save_settings()
|
||
self._render_currency_tiles()
|
||
self.status_var.set(f"Не удалось включить {symbol}: {error}")
|
||
if not was_auto_added:
|
||
messagebox.showerror("Не удалось включить валюту", f"{symbol}: {error}")
|
||
elif event[0] == "live_preflight_failed":
|
||
self.live_preflight = False
|
||
self.mode_combo.configure(state="readonly")
|
||
self.start_btn.configure(state="normal")
|
||
self.status_var.set(f"Реальный режим не запущен: {event[1]}")
|
||
messagebox.showerror("Проверка Bybit не пройдена", event[1])
|
||
elif event[0] == "live_restored_closed":
|
||
self._record_live_close(event[2], event[1], None, "Закрыта на Bybit во время перерыва")
|
||
elif event[0] == "live_order_result":
|
||
if len(event) == 6:
|
||
_kind, symbol, action, position, row, wallet = event
|
||
else:
|
||
_kind, action, position, row, wallet = event
|
||
symbol = position.symbol
|
||
selected = self.symbol
|
||
self._capture_active_symbol()
|
||
state = self._ensure_symbol(symbol)
|
||
state.live_position = position
|
||
state.live_position_info = row
|
||
state.live_order_busy = False
|
||
state.entry_markers.append((time.time(), position.last_add_price, position.trade_id))
|
||
if wallet:
|
||
self.live_wallet = wallet
|
||
self._replace_cached_position(row)
|
||
self._activate_symbol_state(selected)
|
||
self._save_account_state()
|
||
self.status_var.set(("Открыта реальная позиция" if action == "open" else "Доливка реальной позиции") +
|
||
f" #{position.trade_id} · {position.qty:.8g} {position.symbol}")
|
||
self._refresh_ui()
|
||
self._draw_chart()
|
||
elif event[0] == "live_order_no_fill":
|
||
_kind, symbol, action, order_status = event
|
||
self._capture_active_symbol()
|
||
self._ensure_symbol(symbol).live_order_busy = False
|
||
self._activate_symbol_state(self.symbol)
|
||
self.status_var.set(
|
||
f"Bybit не исполнил ордер ({order_status or 'без исполнения'}); бот продолжает работу"
|
||
)
|
||
self._refresh_ui()
|
||
elif event[0] == "live_order_pending":
|
||
_kind, symbol, order_id = event
|
||
self.status_var.set(
|
||
f"Жду подтверждения ордера Bybit {symbol} {order_id or ''}; повторный ордер заблокирован до сверки"
|
||
)
|
||
elif event[0] == "live_sync":
|
||
if len(event) == 5:
|
||
_kind, symbol, position, row, wallet = event
|
||
else:
|
||
_kind, position, row, wallet = event
|
||
symbol = position.symbol if position else str((row or {}).get("symbol") or self.symbol)
|
||
selected = self.symbol
|
||
self._capture_active_symbol()
|
||
state = self._ensure_symbol(symbol)
|
||
state.live_position = position
|
||
state.live_position_info = row
|
||
self._replace_cached_position(row, position.symbol if position else None)
|
||
if wallet:
|
||
self.live_wallet = wallet
|
||
self._activate_symbol_state(selected)
|
||
self._save_account_state()
|
||
self._refresh_ui()
|
||
self._draw_chart()
|
||
elif event[0] == "live_closed":
|
||
_kind, position, row, wallet, reason = event
|
||
self._record_live_close(position, row, wallet, reason)
|
||
elif event[0] == "live_worker_failed":
|
||
symbol, error = event[1], event[2]
|
||
self._capture_active_symbol()
|
||
state = self._ensure_symbol(symbol)
|
||
state.live_halted = True
|
||
state.live_transition_pending = False
|
||
state.live_order_busy = False
|
||
self._activate_symbol_state(self.symbol)
|
||
self.status_var.set(f"Реальная торговля {symbol} приостановлена: {error}")
|
||
messagebox.showerror("Реальная торговля приостановлена", f"{symbol}: {error}\nПроверьте позицию и TP/SL на Bybit.")
|
||
self._refresh_ui()
|
||
elif event[0] == "live_stops_updated":
|
||
self._capture_active_symbol()
|
||
self._ensure_symbol(event[1]).live_order_busy = False
|
||
self._activate_symbol_state(self.symbol)
|
||
self.status_var.set(f"Биржевые TP/SL обновлены · {event[1]}")
|
||
self._refresh_ui()
|
||
elif event[0] == "live_settings_updated":
|
||
self._capture_active_symbol()
|
||
self._ensure_symbol(event[1]).live_order_busy = False
|
||
self._activate_symbol_state(self.symbol)
|
||
self.status_var.set("Настройки реальной стратегии применены")
|
||
self._refresh_ui()
|
||
elif event[0] == "live_order_skipped":
|
||
_kind, symbol, action, reason, price = event
|
||
self._capture_active_symbol()
|
||
state = self._ensure_symbol(symbol)
|
||
state.live_order_busy = False
|
||
if action == "add" and state.live_position is not None:
|
||
state.live_position.last_add_price = min(state.live_position.last_add_price, price)
|
||
self._activate_symbol_state(self.symbol)
|
||
labels = {"open": "Вход", "add": "Доливка", "close": "Закрытие"}
|
||
self.status_var.set(f"{labels.get(action, action)} {symbol} пропущен(а): {reason}")
|
||
self._request_redraw(symbol, main=True)
|
||
elif event[0] == "live_worker_exited":
|
||
_kind, symbol, command_queue = event
|
||
if self.live_commands_by_symbol.get(symbol) is command_queue:
|
||
self.live_commands_by_symbol.pop(symbol, None)
|
||
self.live_workers.pop(symbol, None)
|
||
if self.running and symbol in self.enabled_symbols:
|
||
state = self._ensure_symbol(symbol)
|
||
if not state.live_halted and self.mode_var.get() == "Реальная торговля" \
|
||
and symbol not in self.live_preparing_symbols:
|
||
# The worker ended although the pair is enabled (e.g. it was
|
||
# re-enabled right as the old worker retired): start a new one.
|
||
self._begin_live_additional_symbol(symbol)
|
||
# Drain bursts without starving Tk: continue immediately if events remain.
|
||
self.root.after(1 if handled >= MAX_EVENTS_PER_POLL else 100, self._poll_events)
|
||
|
||
# ----- strategy modes A/B in the simulation ------------------------------------------
|
||
|
||
def _poll_mode_signals(self) -> None:
|
||
"""Evaluate mode A/B signals once per closed signal candle for every enabled pair."""
|
||
try:
|
||
if (self.running and self.mode_var.get() == "Симуляция"
|
||
and self.strategy_mode != strategy.STRATEGY_CLASSIC):
|
||
params = self._strategy_mode_params()
|
||
tf_ms = int(params["timeframe_min"]) * 60_000
|
||
now_ms = int(time.time() * 1000)
|
||
last_closed = (now_ms // tf_ms) * tf_ms - tf_ms
|
||
# Give Bybit a few seconds to publish the closed candle.
|
||
if now_ms - (last_closed + tf_ms) >= 3000:
|
||
self._capture_active_symbol()
|
||
for symbol in sorted(self.enabled_symbols):
|
||
if symbol in self.rotation_pending_disable:
|
||
continue
|
||
state = self._ensure_symbol(symbol)
|
||
if state.mode_eval_busy or state.mode_signal_bucket == last_closed:
|
||
continue
|
||
if state.position is not None:
|
||
state.mode_signal = None
|
||
state.mode_signal_bucket = last_closed
|
||
continue
|
||
state.mode_eval_busy = True
|
||
self._signal_pool.submit(self._mode_signal_worker, symbol, self.strategy_mode,
|
||
dict(params), last_closed)
|
||
except ValueError as exc:
|
||
self.status_var.set(f"Настройки режима стратегии: {exc}")
|
||
finally:
|
||
if self.root.winfo_exists():
|
||
self.root.after(5000, self._poll_mode_signals)
|
||
|
||
@staticmethod
|
||
def _fetch_recent_klines(symbol: str, interval: int, limit: int) -> list[list[float]]:
|
||
"""Closed candles [start_ms, o, h, l, c, turnover], oldest first."""
|
||
query = urllib.parse.urlencode({"category": "linear", "symbol": symbol, "interval": str(interval),
|
||
"limit": str(max(2, min(1000, limit)))})
|
||
request = urllib.request.Request(f"https://api.bybit.com/v5/market/kline?{query}",
|
||
headers={"User-Agent": "RealtimePaperSimulator/1.0"})
|
||
with urllib.request.urlopen(request, timeout=10) as response:
|
||
payload = json.loads(response.read().decode("utf-8"))
|
||
if payload.get("retCode") != 0:
|
||
raise RuntimeError(f"Bybit {payload.get('retCode')}: {payload.get('retMsg', 'ошибка свечей')}")
|
||
now_ms = int(time.time() * 1000)
|
||
interval_ms = interval * 60_000
|
||
rows = [[int(row[0]), float(row[1]), float(row[2]), float(row[3]), float(row[4]),
|
||
float(row[6]) if len(row) > 6 and row[6] not in (None, "") else 0.0]
|
||
for row in payload.get("result", {}).get("list", [])
|
||
if int(row[0]) + interval_ms <= now_ms]
|
||
rows.sort(key=lambda row: row[0])
|
||
return rows
|
||
|
||
def _btc_regime(self, ema_period: int) -> bool | None:
|
||
"""BTC closed-hour close above its EMA, refreshed once per hour."""
|
||
hour = int(time.time() // 3600)
|
||
with self._btc_regime_lock:
|
||
cached_hour, cached_period, value = self._btc_regime_cache
|
||
if cached_hour == hour and cached_period == ema_period and value is not None:
|
||
return value
|
||
rows = self._fetch_recent_klines("BTCUSDT", 60, ema_period * 3 + 5)
|
||
value = strategy.btc_regime_ok([row[4] for row in rows], ema_period)
|
||
self._btc_regime_cache = (hour, ema_period, value)
|
||
return value
|
||
|
||
def _mode_signal_worker(self, symbol: str, mode: str, params: dict[str, float], bucket: int) -> None:
|
||
tf = int(params["timeframe_min"])
|
||
try:
|
||
rows = self._fetch_recent_klines(symbol, tf, strategy.required_bars(mode, params) + 5)
|
||
rows = [row for row in rows if row[0] <= bucket]
|
||
if not rows or rows[-1][0] != bucket:
|
||
raise RuntimeError("Bybit ещё не опубликовал закрытую свечу")
|
||
btc_ok: bool | None = True
|
||
if mode == strategy.STRATEGY_BREAKOUT and params["btc_filter"] >= 1:
|
||
btc_ok = self._btc_regime(int(params["btc_ema"]))
|
||
signal = strategy.evaluate_signal(mode, rows, params, self.ticker_funding_pct.get(symbol), btc_ok)
|
||
self.events.put(("mode_signal", symbol, mode, bucket, tf * 60_000, signal, None))
|
||
except Exception as exc:
|
||
self.events.put(("mode_signal", symbol, mode, bucket, tf * 60_000, None, str(exc)[:160]))
|
||
|
||
def _maybe_enter_mode_position(self, price: float, timestamp: float) -> None:
|
||
state = self.symbol_states.get(self.symbol)
|
||
signal = state.mode_signal if state else None
|
||
if not signal:
|
||
return
|
||
if timestamp > signal["valid_until"] or signal.get("mode") != self.strategy_mode:
|
||
state.mode_signal = None
|
||
return
|
||
if self.symbol not in self.enabled_symbols or self.symbol in self.rotation_pending_disable:
|
||
return
|
||
try:
|
||
params = self._strategy_mode_params(signal["mode"])
|
||
position_limit = self._simulation_position_limit()
|
||
except ValueError as exc:
|
||
self.status_var.set(str(exc))
|
||
return
|
||
active_positions = sum(item.position is not None for item in self.symbol_states.values())
|
||
stake = self.initial_balance * params["stake_pct"] / 100
|
||
if active_positions >= position_limit or stake > max(0.0, self._sim_free_margin()):
|
||
if not signal.get("skip_noted"):
|
||
signal["skip_noted"] = True
|
||
self.status_var.set(
|
||
f"Сигнал {self.symbol} ждёт: " + ("лимит одновременных сделок занят"
|
||
if active_positions >= position_limit
|
||
else "свободного баланса меньше ставки")
|
||
)
|
||
return
|
||
plan = strategy.entry_plan(signal, price, params)
|
||
state.mode_signal = None
|
||
if plan is None:
|
||
self.status_var.set(f"Сигнал {self.symbol} отменён: цена ушла за уровень сигнала или стоп слишком далеко")
|
||
return
|
||
notional = stake * params["leverage"]
|
||
qty = notional / price
|
||
entry_fee = notional * TAKER_FEE_PCT / 100
|
||
self.balance -= entry_fee
|
||
self.total_fees += entry_fee
|
||
self.position = Position(
|
||
self.next_id, self.symbol, price, qty, stake, entry_fee, timestamp, price,
|
||
side=plan["side"], mode=signal["mode"], leverage=params["leverage"],
|
||
stop_price=plan["stop"], initial_stop=plan["stop"], atr=plan["atr"], extreme=price,
|
||
partial_target=plan["partial_target"] or 0.0, final_target=plan["final_target"] or 0.0,
|
||
opened_stake=stake,
|
||
)
|
||
state.position = self.position
|
||
self.entry_markers.append((timestamp, price, self.position.trade_id))
|
||
self.next_id += 1
|
||
self._save_account_state()
|
||
self.status_var.set(
|
||
f"Открыта {plan['side'].upper()} #{self.position.trade_id} · {self.symbol} · {price:g} · "
|
||
f"стоп {self._fmt_price(plan['stop'])}"
|
||
)
|
||
|
||
def _partial_close_position(self, price: float, params: dict[str, float]) -> None:
|
||
pos = self.position
|
||
if pos is None:
|
||
return
|
||
fraction = min(1.0, params["partial_pct"] / 100)
|
||
qty = pos.qty * fraction
|
||
gross = strategy.unrealized_pnl(pos.side, pos.entry_price, price, qty)
|
||
exit_fee = price * qty * TAKER_FEE_PCT / 100
|
||
self.balance += gross - exit_fee
|
||
self.total_fees += exit_fee
|
||
pos.realized_gross += gross
|
||
pos.realized_fees += exit_fee
|
||
pos.qty -= qty
|
||
pos.stake *= 1 - fraction
|
||
pos.partial_done = True
|
||
if params["breakeven"] >= 1:
|
||
pos.stop_price = strategy.tighten_stop(pos.side, pos.stop_price,
|
||
strategy.breakeven_price(pos.side, pos.entry_price, TAKER_FEE_PCT))
|
||
self._save_account_state()
|
||
self.status_var.set(
|
||
f"Частичная фиксация {params['partial_pct']:g}% #{pos.trade_id} · {pos.symbol} · {price:g} · "
|
||
f"gross {gross:+.4f} · стоп {self._fmt_price(pos.stop_price)}"
|
||
)
|
||
|
||
def _manage_mode_position(self, price: float, timestamp: float) -> None:
|
||
pos = self.position
|
||
if pos is None:
|
||
return
|
||
try:
|
||
params = self._strategy_mode_params(pos.mode)
|
||
except ValueError:
|
||
params = strategy.parse_mode_params(pos.mode, {})
|
||
side = pos.side
|
||
liquidation = strategy.liquidation_price(pos.entry_price, pos.leverage, side=side)
|
||
if liquidation is not None and strategy.stop_hit(side, price, liquidation):
|
||
self._close_position(price, f"Ликвидация (плечо {pos.leverage:g}x)", liquidation=True)
|
||
return
|
||
if strategy.stop_hit(side, price, pos.stop_price):
|
||
moved = abs(pos.stop_price - pos.initial_stop) > 1e-12
|
||
self._close_position(price, "Стоп (трейлинг/безубыток)" if moved else "Стоп")
|
||
return
|
||
if params["max_hold_hours"] > 0 and timestamp - pos.opened_at >= params["max_hold_hours"] * 3600:
|
||
self._close_position(price, f"Время удержания {params['max_hold_hours']:g} ч")
|
||
return
|
||
if (not pos.partial_done and pos.partial_target > 0
|
||
and strategy.target_hit(side, price, pos.partial_target)):
|
||
if params["partial_pct"] >= 100:
|
||
self._close_position(pos.partial_target, f"TP на {params['partial_r']:g}R")
|
||
return
|
||
self._partial_close_position(pos.partial_target, params)
|
||
if pos.final_target > 0 and strategy.target_hit(side, price, pos.final_target):
|
||
self._close_position(pos.final_target, f"TP на {params['take_profit_r']:g}R")
|
||
return
|
||
pos.extreme = max(pos.extreme, price) if side == "long" else min(pos.extreme, price)
|
||
if strategy.trailing_active(pos.partial_done, params):
|
||
pos.stop_price = strategy.trailing_stop(side, pos.stop_price, pos.extreme, pos.atr, params["trail_atr"])
|
||
|
||
def _on_trade(self, symbol: str, timestamp: float, price: float) -> None:
|
||
display_symbol = self.symbol
|
||
balance_before = self.balance
|
||
self._display_symbol_during_tick = display_symbol
|
||
self._capture_active_symbol()
|
||
self._activate_symbol_state(symbol)
|
||
try:
|
||
self._process_active_trade(timestamp, price)
|
||
finally:
|
||
self._capture_active_symbol()
|
||
self._activate_symbol_state(display_symbol)
|
||
self._display_symbol_during_tick = None
|
||
self._request_redraw(symbol, main=symbol == display_symbol or self.balance != balance_before)
|
||
|
||
def _request_redraw(self, symbol: str | None = None, main: bool = False) -> None:
|
||
"""Coalesce UI updates: at most one redraw every UI_REDRAW_INTERVAL_MS.
|
||
|
||
Redrawing the whole chart on every public trade starves the Tk thread when many
|
||
pairs are subscribed, so prices would be processed late.
|
||
"""
|
||
if symbol:
|
||
self._dirty_symbols.add(symbol)
|
||
self._dirty_main = self._dirty_main or main
|
||
if self._redraw_job is None and self.root.winfo_exists():
|
||
self._redraw_job = self.root.after(UI_REDRAW_INTERVAL_MS, self._flush_redraw)
|
||
|
||
def _flush_redraw(self) -> None:
|
||
self._redraw_job = None
|
||
symbols, self._dirty_symbols = self._dirty_symbols, set()
|
||
main, self._dirty_main = self._dirty_main, False
|
||
if symbols:
|
||
self._refresh_currency_tiles(symbols)
|
||
if main or self.symbol in symbols:
|
||
self._refresh_price_label()
|
||
self._refresh_ui()
|
||
self._draw_chart()
|
||
for symbol in symbols:
|
||
if symbol in self.detail_windows:
|
||
self._draw_detail_chart(symbol)
|
||
|
||
def _process_active_trade(self, timestamp: float, price: float) -> None:
|
||
self.last_ws_message = time.time()
|
||
self.last_price = price
|
||
self._live_minute_prices.append((timestamp, price))
|
||
while self._live_minute_prices and self._live_minute_prices[0][0] < timestamp - 2 * WINDOW_MS / 1000:
|
||
self._live_minute_prices.popleft()
|
||
self.prices.append((timestamp, price))
|
||
cutoff = timestamp - WINDOW_MS / 1000
|
||
while self.prices and self.prices[0][0] < cutoff - 2:
|
||
self.prices.popleft()
|
||
candle_start = int(timestamp // (self.interval_minutes * 60)) * (self.interval_minutes * 60)
|
||
new_candle = not self.candles or self.candles[-1][0] != candle_start
|
||
if new_candle:
|
||
self._previous_entry_signal_pct = None
|
||
self._update_candle(timestamp, price)
|
||
keep_seconds = max(CHART_SECONDS, self.interval_minutes * 60 * 30)
|
||
while self.candles and self.candles[0][0] < timestamp - keep_seconds:
|
||
expired = self.candles.popleft()
|
||
while self.entry_markers and self.entry_markers[0][0] < expired[0]:
|
||
self.entry_markers.popleft()
|
||
|
||
settings = self.strategy_by_symbol.get(self.symbol) or self.applied_settings or self._safe_read_settings()
|
||
|
||
signal_pct =((price / self.baseline_close) - 1) * 100 if self.baseline_close and self.baseline_close > 0 else None
|
||
crossed_entry_threshold = (
|
||
signal_pct is not None
|
||
and signal_pct >= settings["trigger"]
|
||
and (self._previous_entry_signal_pct is None or self._previous_entry_signal_pct < settings["trigger"])
|
||
)
|
||
if self.mode_var.get() == "Реальная торговля":
|
||
self._on_live_tick(timestamp, price, crossed_entry_threshold)
|
||
self._previous_entry_signal_pct = signal_pct
|
||
return
|
||
self._previous_entry_signal_pct = signal_pct
|
||
if self.position and self.position.mode != strategy.STRATEGY_CLASSIC:
|
||
self._manage_mode_position(price, timestamp)
|
||
return
|
||
if self.position is None and self.strategy_mode != strategy.STRATEGY_CLASSIC:
|
||
self._maybe_enter_mode_position(price, timestamp)
|
||
return
|
||
if self.position:
|
||
stop_price = strategy.stop_loss_price(self.position.entry_price, settings["stop_loss"])
|
||
effective_tp_pct = strategy.effective_take_profit_pct(settings["take_profit"], settings["fee"])
|
||
take_profit_price = strategy.take_profit_price(self.position.entry_price, settings["take_profit"], settings["fee"])
|
||
liquidation_price = strategy.liquidation_price(self.position.entry_price, settings["leverage"])
|
||
add_price = strategy.add_level(self.position.last_add_price, settings["add_step"])
|
||
if liquidation_price is not None and price <= liquidation_price:
|
||
self._close_position(price, f"Ликвидация (плечо {settings['leverage']:g}x)", liquidation=True)
|
||
elif stop_price is not None and price <= stop_price:
|
||
stop_pct = (self.position.entry_price - price) / self.position.entry_price * 100
|
||
self._close_position(price, f"Стоп от средней цены {stop_pct:.2f}%")
|
||
elif take_profit_price is not None and price >= take_profit_price:
|
||
# Exchange TP is a trigger at the level; do not credit the overshoot of a jump.
|
||
self._close_position(take_profit_price, f"TP от средней цены +{effective_tp_pct:.3f}%")
|
||
elif (self.symbol in self.enabled_symbols and self.symbol not in self.rotation_pending_disable
|
||
and strategy.can_add(self.position.add_count, settings["max_adds"], settings["add_step"])
|
||
and add_price is not None and price <= add_price):
|
||
self._add_position(price, timestamp, settings)
|
||
elif (crossed_entry_threshold and self.symbol in self.enabled_symbols
|
||
and self.symbol not in self.rotation_pending_disable):
|
||
self._open_position(price, timestamp, settings)
|
||
|
||
def _refresh_rolling_change(self, reschedule: bool = True, now: float | None = None) -> None:
|
||
if now is None:
|
||
now = time.time()
|
||
self._last_signal_refresh_at = now
|
||
current = self.last_price
|
||
self.last_signal_pct = ((current / self.baseline_close) - 1) * 100 if current and self.baseline_close and self.baseline_close > 0 else None
|
||
self.last_signal_ready = self.last_signal_pct is not None
|
||
if hasattr(self, "market_price_var"):
|
||
self._refresh_price_label()
|
||
if hasattr(self, "root") and self.root.winfo_exists():
|
||
self._refresh_ui()
|
||
if reschedule:
|
||
self.root.after(5000, self._refresh_rolling_change)
|
||
|
||
def _refresh_price_label(self) -> None:
|
||
current = self.last_price
|
||
if not current:
|
||
self.market_price_var.set(f"{self.symbol}: ожидаю цену Bybit…")
|
||
elif self.last_signal_ready and self.last_signal_pct is not None:
|
||
self.market_price_var.set(
|
||
f"{self.symbol}: {self._fmt_price(current)} USDT "
|
||
f"Изменение от закрытия прошлой {self.interval_minutes}-мин свечи: {self.last_signal_pct:+.2f}%"
|
||
)
|
||
else:
|
||
self.market_price_var.set(
|
||
f"{self.symbol}: {self._fmt_price(current)} USDT "
|
||
f"Изменение от закрытия прошлой {self.interval_minutes}-мин свечи: ждём базу…"
|
||
)
|
||
|
||
def _sim_free_margin(self) -> float:
|
||
"""Money available for new simulated entries/adds.
|
||
|
||
Like Bybit's available balance: cash minus margin locked in open positions, plus
|
||
their current unrealized P&L after the estimated closing fee. Losing positions
|
||
therefore reduce what can still be invested; the same figure is shown on screen.
|
||
"""
|
||
self._capture_active_symbol()
|
||
free = self.balance
|
||
for state in self.symbol_states.values():
|
||
pos = state.position
|
||
if pos is None:
|
||
continue
|
||
settings = self.strategy_by_symbol.get(pos.symbol) or self.applied_settings or {}
|
||
fee_pct = settings.get("fee", TAKER_FEE_PCT) if pos.mode == strategy.STRATEGY_CLASSIC else TAKER_FEE_PCT
|
||
mark = state.last_price or pos.entry_price
|
||
free += (strategy.unrealized_pnl(pos.side, pos.entry_price, mark, pos.qty)
|
||
- mark * pos.qty * fee_pct / 100 - pos.stake)
|
||
return free
|
||
|
||
def _open_position(self, price: float, timestamp: float, settings: dict[str, float]) -> None:
|
||
try:
|
||
position_limit = self._simulation_position_limit()
|
||
except ValueError as exc:
|
||
self.status_var.set(str(exc))
|
||
return
|
||
active_positions = sum(state.position is not None for state in self.symbol_states.values())
|
||
if active_positions >= position_limit:
|
||
self.status_var.set(
|
||
f"Вход пропущен: лимит одновременных сделок {position_limit} уже занят"
|
||
)
|
||
return
|
||
if settings["stake"] > max(0.0, self._sim_free_margin()):
|
||
self.status_var.set("Вход пропущен: свободного баланса меньше ставки")
|
||
return
|
||
notional = settings["stake"] * settings["leverage"]
|
||
qty = notional / price
|
||
entry_fee = notional * settings["fee"] / 100
|
||
self.balance -= entry_fee
|
||
self.total_fees += entry_fee
|
||
self.position = Position(self.next_id, self.symbol, price, qty, settings["stake"], entry_fee, timestamp, price)
|
||
self.entry_markers.append((timestamp, price, self.position.trade_id))
|
||
self.next_id += 1
|
||
self._save_account_state()
|
||
self.status_var.set(f"Открыта LONG #{self.position.trade_id} · {self.symbol} · {price:g}")
|
||
|
||
def _add_position(self, price: float, timestamp: float, settings: dict[str, float]) -> None:
|
||
pos = self.position
|
||
if pos is None:
|
||
return
|
||
free_margin = self._sim_free_margin()
|
||
if free_margin < settings["stake"]:
|
||
# Same rule as live and backtest: the level is consumed, the next add is measured from here.
|
||
pos.last_add_price = price
|
||
self.status_var.set("Доливка пропущена: недостаточно свободного капитала")
|
||
return
|
||
notional = settings["stake"] * settings["leverage"]
|
||
added_qty = notional / price
|
||
added_fee = notional * settings["fee"] / 100
|
||
total_qty = pos.qty + added_qty
|
||
pos.entry_price = (pos.entry_price * pos.qty + price * added_qty) / total_qty
|
||
pos.qty = total_qty
|
||
pos.stake += settings["stake"]
|
||
pos.entry_fee += added_fee
|
||
pos.last_add_price = price
|
||
pos.add_count += 1
|
||
self.balance -= added_fee
|
||
self.total_fees += added_fee
|
||
self.entry_markers.append((timestamp, price, pos.trade_id))
|
||
self._save_account_state()
|
||
self.status_var.set(f"Доливка #{pos.add_count} в сделку #{pos.trade_id} · {price:g} · средняя {pos.entry_price:g}")
|
||
|
||
def _mark_position(self, price: float, settings: dict[str, float]) -> tuple[float, float, float]:
|
||
assert self.position is not None
|
||
p = self.position
|
||
gross = strategy.unrealized_pnl(p.side, p.entry_price, price, p.qty)
|
||
exit_fee = price * p.qty * settings["fee"] / 100
|
||
fees = p.entry_fee + exit_fee
|
||
return gross - fees, fees, gross
|
||
|
||
def _close_position(self, price: float, reason: str, liquidation: bool = False) -> None:
|
||
if not self.position:
|
||
return
|
||
pos = self.position
|
||
if pos.mode != strategy.STRATEGY_CLASSIC:
|
||
settings = {"fee": TAKER_FEE_PCT} # modes A/B never read the classic currency settings
|
||
else:
|
||
settings = (self.strategy_by_symbol.get(pos.symbol) or self.applied_settings
|
||
or self._safe_read_settings())
|
||
if liquidation:
|
||
# Isolated-margin liquidation forfeits the position margin (as in the backtest).
|
||
gross, exit_fee = -pos.stake, 0.0
|
||
else:
|
||
_net, fees, gross = self._mark_position(price, settings)
|
||
exit_fee = max(0, fees - pos.entry_fee)
|
||
self.balance += gross - exit_fee
|
||
self.total_fees += exit_fee
|
||
# A partial take-profit (modes A/B) was already credited; report the whole trade.
|
||
gross += pos.realized_gross
|
||
fees = pos.entry_fee + pos.realized_fees + exit_fee
|
||
net = gross - fees
|
||
roi = net / (pos.opened_stake or pos.stake) * 100
|
||
if pos.mode != strategy.STRATEGY_CLASSIC:
|
||
reason = f"{pos.side.upper()} · {reason}"
|
||
closed = ClosedTrade(pos.trade_id, pos.symbol, pos.entry_price, price, pos.qty, gross, fees, net, roi, pos.opened_at, time.time(), reason)
|
||
self.trades.append(closed)
|
||
self.table.insert("", 0, values=(closed.trade_id, closed.symbol, self._fmt_price(closed.entry_price), self._fmt_price(closed.exit_price), f"{closed.roi_pct:+.2f}", f"{closed.gross_pnl:+.4f}", f"{closed.fees:.4f}", f"{closed.net_pnl:+.4f}", closed.reason), tags=("profit" if closed.net_pnl > 0 else "loss" if closed.net_pnl < 0 else "",))
|
||
self.position = None
|
||
state = self._ensure_symbol(pos.symbol)
|
||
state.position = None
|
||
self._save_account_state()
|
||
self.status_var.set(f"Закрыта сделка #{closed.trade_id}: {closed.reason} · net {closed.net_pnl:+.4f} USDT")
|
||
self._finish_auto_retirement(pos.symbol)
|
||
|
||
def _manual_close_position(self) -> None:
|
||
if self.mode_var.get() == "Реальная торговля":
|
||
if not self.live_position:
|
||
self.status_var.set("Нет открытой реальной позиции")
|
||
return
|
||
if not self.running or self.live_order_busy or self.live_halted:
|
||
self.status_var.set("Для ручного закрытия запустите реальный бот; дождитесь завершения текущего ордера")
|
||
return
|
||
if not messagebox.askyesno("Закрыть позицию Bybit", f"Отправить рыночный ордер на закрытие LONG {self.live_position.symbol}?"):
|
||
return
|
||
self.live_order_busy = True
|
||
commands = self.live_commands_by_symbol.get(self.live_position.symbol, self.live_commands)
|
||
commands.put(("close", time.time(), self.last_price or self.live_position.entry_price))
|
||
self.status_var.set("Отправляю reduce-only ордер на закрытие…")
|
||
self._refresh_ui()
|
||
return
|
||
if not self.position:
|
||
self.status_var.set("Нет открытой сделки для закрытия")
|
||
return
|
||
if not self.running or not self.last_price or self.last_price <= 0:
|
||
self.status_var.set("Для ручного закрытия запустите поток цен Bybit")
|
||
return
|
||
self._close_position(self.last_price, "Закрыта вручную")
|
||
self._refresh_ui()
|
||
self._draw_chart()
|
||
|
||
def _record_live_close(self, position: Position, row: dict | None,
|
||
wallet: dict[str, float] | None, reason: str) -> None:
|
||
if row:
|
||
state = self._ensure_symbol(position.symbol)
|
||
exit_price = float(row.get("avgExitPrice") or row.get("avgEntryPrice") or state.last_price or position.entry_price)
|
||
entry_price = float(row.get("avgEntryPrice") or position.entry_price)
|
||
qty = float(row.get("closedSize") or row.get("qty") or position.qty)
|
||
# Bybit's closedPnl is the authoritative net result. Gross is derived from the
|
||
# fill prices so it never depends on how funding is reported in the record;
|
||
# any difference between gross − fees and net is funding/other charges.
|
||
net = float(row.get("closedPnl") or 0.0)
|
||
fees = float(row.get("openFee") or 0.0) + float(row.get("closeFee") or 0.0)
|
||
gross = (exit_price - entry_price) * qty
|
||
close_time = float(row.get("updatedTime") or int(time.time() * 1000)) / 1000
|
||
else:
|
||
exit_price = self._ensure_symbol(position.symbol).last_price or position.entry_price
|
||
qty = position.qty
|
||
fees = position.entry_fee + exit_price * qty * self.live_fee_pct / 100
|
||
gross = (exit_price - position.entry_price) * qty
|
||
net = gross - fees
|
||
close_time = time.time()
|
||
reason += " · PnL не подтверждён API"
|
||
roi = net / position.stake * 100 if position.stake else 0.0
|
||
closed = ClosedTrade(position.trade_id, position.symbol, position.entry_price, exit_price,
|
||
qty, gross, fees, net, roi, position.opened_at, close_time, reason)
|
||
# Replayed close events can occur when an app closes while Bybit already closed the position.
|
||
if not any(existing.trade_id == closed.trade_id for existing in self.live_trades):
|
||
self.live_trades.append(closed)
|
||
tag = "profit" if net > 0 else "loss" if net < 0 else ""
|
||
self.table.insert("", 0, values=(f"R{closed.trade_id}", closed.symbol,
|
||
self._fmt_price(closed.entry_price), self._fmt_price(closed.exit_price),
|
||
f"{closed.roi_pct:+.2f}", f"{closed.gross_pnl:+.4f}", f"{closed.fees:.4f}",
|
||
f"{closed.net_pnl:+.4f}", f"LIVE · {closed.reason}"), tags=(tag,))
|
||
state = self._ensure_symbol(position.symbol)
|
||
if state.live_position and state.live_position.trade_id == position.trade_id:
|
||
state.live_position = None
|
||
state.live_position_info = None
|
||
state.live_order_busy = False
|
||
state.live_transition_pending = False
|
||
if self.live_position and self.live_position.trade_id == position.trade_id:
|
||
self.live_position = None
|
||
self._replace_cached_position(None, position.symbol)
|
||
self._finish_auto_retirement(position.symbol)
|
||
if self.symbol == position.symbol:
|
||
self.live_order_busy = False
|
||
self.live_transition_pending = False
|
||
if wallet:
|
||
self.live_wallet = wallet
|
||
self._save_account_state()
|
||
self.status_var.set(f"Реальная сделка #{closed.trade_id} закрыта · net {closed.net_pnl:+.4f} USDT · {reason}")
|
||
self._refresh_ui()
|
||
self._draw_chart()
|
||
|
||
@staticmethod
|
||
def _fmt_price(price: float) -> str:
|
||
return f"{price:.10g}"
|
||
|
||
@staticmethod
|
||
def _fee_cover_pct(fee_pct: float) -> float:
|
||
"""Minimum gross price rise that offsets taker fees on entry and exit fills."""
|
||
return strategy.fee_cover_pct(fee_pct)
|
||
|
||
def _safe_read_settings(self) -> dict[str, float]:
|
||
try:
|
||
return self._read_settings()
|
||
except ValueError:
|
||
return {"initial": self.initial_balance, "stake_pct": 2, "deposit_basis": self.initial_balance,
|
||
"stake": 0, "leverage": 1, "trigger": 5, "add_step": .5, "max_adds": 2,
|
||
"stop_loss": 1, "take_profit": 1, "fee": TAKER_FEE_PCT,
|
||
"interval": float(CANDLE_INTERVAL_MINUTES)}
|
||
|
||
def _refresh_settings_summary(self) -> None:
|
||
"""Show the active strategy thresholds in the main window."""
|
||
settings = self.applied_settings or self._safe_read_settings()
|
||
stop_loss = "выключен" if settings["stop_loss"] == 0 else f"−{settings['stop_loss']:g}%"
|
||
take_profit = (
|
||
"выключен"
|
||
if settings["take_profit"] == 0
|
||
else f"+{settings['take_profit']:g}% (уровень с учётом комиссий не ниже {self._fee_cover_pct(settings['fee']):.3f}%)"
|
||
)
|
||
add_text = (f"доливка через −{settings['add_step']:g}% от последнего входа, максимум {settings['max_adds']}"
|
||
if settings["add_step"] > 0 and settings["max_adds"] > 0 else "доливки выключены")
|
||
self.strategy_summary_var.set(
|
||
f"Параметры: 1-мин свеча · первый вход при росте +{settings['trigger']:g}% от предыдущего закрытия · "
|
||
f"{add_text} · ставка {settings.get('stake_pct', 0):g}% от стартового депозита "
|
||
f"({settings.get('deposit_basis', settings['initial']):g} USDT = {settings['stake']:g} USDT на вход) × плечо {settings['leverage']:g} · "
|
||
f"TP {take_profit} / стоп {stop_loss} от средней цены · "
|
||
f"комиссия taker {settings['fee']:g}% за сторону"
|
||
)
|
||
|
||
def _refresh_ui(self) -> None:
|
||
current = self.last_price or 0.0
|
||
self._refresh_price_label()
|
||
settings = self.applied_settings or self._safe_read_settings()
|
||
if self.mode_var.get() == HISTORICAL_MODE:
|
||
self.main_metrics_frame.pack_forget()
|
||
elif not self.main_metrics_frame.winfo_manager():
|
||
self.main_metrics_frame.pack(fill="x", pady=(6, 0), before=self.currencies_frame)
|
||
if self.mode_var.get() == "Реальная торговля":
|
||
wallet = self.live_wallet or {"wallet": 0.0, "equity": 0.0, "available": 0.0, "unrealized_pnl": 0.0}
|
||
if self.live_client:
|
||
network = "Testnet" if self.live_client.testnet else "MAINNET"
|
||
baseline = self._current_live_deposit_basis() or wallet["wallet"]
|
||
realized = sum(float(row.get("closedPnl") or 0) for row in self.live_closed_pnl)
|
||
self.live_account_var.set(
|
||
f"{network} · стартовый депозит {baseline:,.2f} · кошелёк {wallet['wallet']:,.2f} · "
|
||
f"equity {wallet['equity']:,.2f} · нереализованный P&L {wallet.get('unrealized_pnl', 0):+,.2f} · "
|
||
f"реализованный P&L (последние {len(self.live_closed_pnl)}) {realized:+,.2f} USDT · "
|
||
f"ордеров {len(self.live_orders)} · позиций {len(self.live_positions)}"
|
||
)
|
||
position = self.live_position
|
||
unrealized = float((self.live_position_info or {}).get("unrealisedPnl") or 0.0)
|
||
if position:
|
||
mark_price = current or float((self.live_position_info or {}).get("markPrice") or position.entry_price)
|
||
unrealized = float((self.live_position_info or {}).get("unrealisedPnl") or ((mark_price - position.entry_price) * position.qty))
|
||
margin = position.stake
|
||
pnl_pct = unrealized / margin * 100 if margin else 0.0
|
||
self.position_var.set(
|
||
f"LIVE LONG #{position.trade_id} · {position.symbol} · средняя {self._fmt_price(position.entry_price)} · "
|
||
f"входов {position.add_count + 1} · текущая {self._fmt_price(mark_price)} · размер {position.qty:.8g} · "
|
||
f"unrealized PnL {unrealized:+.4f} USDT ({pnl_pct:+.2f}%)"
|
||
)
|
||
else:
|
||
selected = next((row for row in self.live_positions if row.get("symbol") == self.symbol_var.get().strip().upper()), None)
|
||
if selected:
|
||
self.position_var.set(
|
||
f"Bybit · {selected.get('symbol')} {selected.get('side')} · объём {selected.get('size')} · "
|
||
f"средняя {selected.get('avgPrice')} · P&L {float(selected.get('unrealisedPnl') or 0):+.4f} USDT · "
|
||
f"TP {selected.get('takeProfit') or '—'} · SL {selected.get('stopLoss') or '—'} · "
|
||
"нажмите «Старт» для сопровождения ботом"
|
||
)
|
||
elif self.live_positions:
|
||
self.position_var.set(f"На аккаунте открыто позиций: {len(self.live_positions)} · подробности во вкладке «Открытые позиции»")
|
||
else:
|
||
self.position_var.set("LIVE · открытых позиций нет; ждём сигнал")
|
||
self.close_trade_btn.configure(state="normal" if self.running and position and not self.live_order_busy else "disabled")
|
||
for key, title in (("balance", "Bybit кошелёк"), ("equity", "Equity"),
|
||
("pnl", "Нереализованный PnL"), ("free", "Доступно"),
|
||
("fees", "Комиссии сделки · оценка")):
|
||
self.metric_title_vars[key].set(title)
|
||
self.metric_boxes[key].configure(text=title)
|
||
values = {
|
||
"balance": f"{wallet['wallet']:,.2f} USDT",
|
||
"equity": f"{wallet['equity']:,.2f} USDT",
|
||
"free": f"{wallet['available']:,.2f} USDT",
|
||
"pnl": f"{float(wallet.get('unrealized_pnl', unrealized)):+,.2f} USDT",
|
||
"fees": (f"{position.entry_fee + position.entry_price * position.qty * self.live_fee_pct / 100:,.4f} USDT"
|
||
if position else "см. историю Bybit"),
|
||
}
|
||
for key, value in values.items():
|
||
self.metric_vars[key].set(value)
|
||
live_open = sum(1 for state in self.symbol_states.values() if state.live_position is not None)
|
||
self._set_main_metrics(
|
||
wallet["wallet"], float(wallet.get("unrealized_pnl", unrealized)), wallet["equity"],
|
||
"Баланс Bybit", "Нереализованный P&L", "Общий баланс с P&L",
|
||
free=float(wallet.get("available") or 0.0), open_positions=live_open,
|
||
free_title="Свободно на Bybit для новых сделок",
|
||
)
|
||
return
|
||
for key, title in (("balance", "Баланс"), ("equity", "Бюджет всего"), ("pnl", "Без стартового"),
|
||
("free", "Свободно"), ("fees", "Комиссии")):
|
||
self.metric_title_vars[key].set(title)
|
||
self.metric_boxes[key].configure(text=title)
|
||
open_positions = [(symbol, state.position, state.last_price or state.position.entry_price)
|
||
for symbol, state in self.symbol_states.items() if state.position]
|
||
unrealized_gross = 0.0
|
||
estimated_exit_fees = 0.0
|
||
used_margin = 0.0
|
||
position_lines = []
|
||
for symbol, pos, mark in open_positions:
|
||
assert pos is not None
|
||
gross = strategy.unrealized_pnl(pos.side, pos.entry_price, mark, pos.qty)
|
||
exit_fee = mark * pos.qty * settings["fee"] / 100
|
||
unrealized_gross += gross
|
||
estimated_exit_fees += exit_fee
|
||
used_margin += pos.stake
|
||
net = gross - exit_fee - pos.entry_fee + pos.realized_gross - pos.realized_fees
|
||
side = f"{pos.side.upper()} " if pos.mode != strategy.STRATEGY_CLASSIC else ""
|
||
position_lines.append(
|
||
f"{symbol}: {side}#{pos.trade_id} · {self._fmt_price(pos.entry_price)} → {self._fmt_price(mark)} · "
|
||
+ (f"стоп {self._fmt_price(pos.stop_price)}" if pos.mode != strategy.STRATEGY_CLASSIC
|
||
else f"{pos.add_count + 1} вход(ов)")
|
||
+ f" · net {net:+.3f} USDT"
|
||
)
|
||
equity = self.balance + unrealized_gross - estimated_exit_fees
|
||
free = max(0.0, self._sim_free_margin())
|
||
pnl = equity - self.initial_balance
|
||
if position_lines:
|
||
self.position_var.set("Открытые позиции · " + " | ".join(position_lines))
|
||
selected_position = self.position is not None and self.last_price is not None
|
||
self.close_trade_btn.configure(state="normal" if self.running and selected_position else "disabled")
|
||
else:
|
||
self.position_var.set("Нет открытых сделок")
|
||
self.close_trade_btn.configure(state="disabled")
|
||
values = {
|
||
"balance": f"{self.balance:,.2f} USDT",
|
||
"equity": f"{equity:,.2f} USDT",
|
||
"free": f"{free:,.2f} USDT",
|
||
"pnl": f"{pnl:+,.2f} USDT",
|
||
"fees": f"{self.total_fees:,.4f} USDT",
|
||
}
|
||
for key, value in values.items():
|
||
self.metric_vars[key].set(value)
|
||
self._set_main_metrics(
|
||
self.balance, pnl, equity, "Баланс симуляции", "P&L с запуска", "Общий баланс с P&L",
|
||
free=free, open_positions=len(open_positions),
|
||
free_title="Свободно для новых сделок",
|
||
)
|
||
|
||
def _set_main_metrics(self, balance: float, pnl: float, equity: float,
|
||
balance_title: str, pnl_title: str, equity_title: str, *,
|
||
free: float | None = None, open_positions: int = 0,
|
||
free_title: str = "Свободно для новых сделок") -> None:
|
||
titles = {"balance": balance_title, "pnl": pnl_title, "equity": equity_title, "free": free_title}
|
||
values = {
|
||
"balance": f"{balance:,.2f} USDT",
|
||
"pnl": f"{pnl:+,.2f} USDT",
|
||
"equity": f"{equity:,.2f} USDT",
|
||
"free": "—" if free is None else f"{free:,.2f} USDT" + self._entries_left_text(free, open_positions),
|
||
}
|
||
for key in ("balance", "pnl", "equity", "free"):
|
||
self.main_metric_titles[key].configure(text=titles[key])
|
||
self.main_metric_vars[key].set(values[key])
|
||
|
||
def _entries_left_text(self, free: float, open_positions: int) -> str:
|
||
"""How many more default-size entries fit into free money and the position limit."""
|
||
settings = self._safe_read_settings()
|
||
if self.strategy_mode != strategy.STRATEGY_CLASSIC and self.mode_var.get() == "Симуляция":
|
||
# Modes A/B size entries from their own settings, not the classic currency template.
|
||
try:
|
||
params = self._strategy_mode_params()
|
||
settings = {"stake": self.initial_balance * params["stake_pct"] / 100,
|
||
"leverage": params["leverage"]}
|
||
except ValueError:
|
||
return ""
|
||
stake = float(settings.get("stake") or 0.0) if settings else 0.0
|
||
if stake <= 0:
|
||
return ""
|
||
by_money = max(0, int(free // (stake * (1 + float(settings.get("leverage", 1)) * TAKER_FEE_PCT / 100))))
|
||
limit = self._position_limit_or_none()
|
||
if limit is not None:
|
||
by_limit = max(0, limit - open_positions)
|
||
return f"\nвходов ещё: {min(by_money, by_limit)} · ставка {stake:,.2f} · позиций {open_positions}/{limit}"
|
||
return f"\nвходов ещё: {by_money} · ставка {stake:,.2f}"
|
||
|
||
def _update_candle(self, timestamp: float, price: float) -> None:
|
||
interval_seconds = self.interval_minutes * 60
|
||
candle_start = int(timestamp // interval_seconds) * interval_seconds
|
||
if self.chart_view_end is None:
|
||
self.chart_view_end = candle_start + interval_seconds
|
||
elif self.chart_view_end >= candle_start - interval_seconds:
|
||
# Keep the live candle on screen when the view is following the market.
|
||
self.chart_view_end = candle_start + interval_seconds
|
||
if not self.candles or self.candles[-1][0] != candle_start:
|
||
if self.candles:
|
||
self.baseline_close = self.candles[-1][4]
|
||
self.candles.append([candle_start, price, price, price, price])
|
||
else:
|
||
candle = self.candles[-1]
|
||
candle[2] = max(candle[2], price)
|
||
candle[3] = min(candle[3], price)
|
||
candle[4] = price
|
||
|
||
def reset_statistics(self) -> None:
|
||
if self.mode_var.get() == "Реальная торговля":
|
||
messagebox.showinfo("Сброс статистики", "Реальная история загружается с Bybit и не может быть сброшена из симулятора. Сброс доступен только для виртуального счёта.")
|
||
return
|
||
if any(state.position for state in self.symbol_states.values()):
|
||
messagebox.showerror("Сброс статистики", "Сначала дождитесь закрытия открытой позиции по TP или стопу.")
|
||
return
|
||
if not messagebox.askyesno(
|
||
"Сброс статистики",
|
||
"Очистить историю, комиссии и результат симуляции?",
|
||
):
|
||
return
|
||
self.trades.clear()
|
||
self.total_fees = 0.0
|
||
self.balance = self.initial_balance
|
||
self.next_id = 1
|
||
self.entry_markers.clear()
|
||
for state in self.symbol_states.values():
|
||
state.entry_markers.clear()
|
||
for item in self.table.get_children():
|
||
self.table.delete(item)
|
||
self._save_account_state()
|
||
self._refresh_ui()
|
||
self._draw_chart()
|
||
self.status_var.set("Статистика сброшена; симуляция продолжает работу" if self.running else "Статистика сброшена")
|
||
|
||
def _fetch_baseline_async(self, symbol: str, interval: int) -> None:
|
||
threading.Thread(target=self._fetch_baseline, args=(symbol, interval), daemon=True).start()
|
||
|
||
def _fetch_chart_candles_async(self, symbol: str, interval: int) -> None:
|
||
def worker() -> None:
|
||
query = urllib.parse.urlencode({"category": "linear", "symbol": symbol,
|
||
"interval": str(interval), "limit": "50"})
|
||
request = urllib.request.Request(f"https://api.bybit.com/v5/market/kline?{query}",
|
||
headers={"User-Agent": "RealtimePaperSimulator/1.0"})
|
||
try:
|
||
with urllib.request.urlopen(request, timeout=8) as response:
|
||
result = json.loads(response.read().decode("utf-8"))
|
||
if result.get("retCode") != 0:
|
||
return
|
||
interval_seconds = interval * 60
|
||
now = time.time()
|
||
candles = [[int(row[0]) / 1000, float(row[1]), float(row[2]), float(row[3]), float(row[4])]
|
||
for row in result.get("result", {}).get("list", [])
|
||
if int(row[0]) / 1000 + interval_seconds <= now]
|
||
candles.sort(key=lambda row: row[0])
|
||
if candles:
|
||
self.events.put(("chart_candles", symbol, interval, candles, candles[-1][4]))
|
||
except Exception:
|
||
return
|
||
threading.Thread(target=worker, daemon=True).start()
|
||
|
||
def _fetch_baseline(self, symbol: str, interval: int) -> None:
|
||
query = urllib.parse.urlencode({"category": "linear", "symbol": symbol, "interval": str(interval), "limit": "3"})
|
||
request = urllib.request.Request(f"https://api.bybit.com/v5/market/kline?{query}", headers={"User-Agent": "RealtimePaperSimulator/1.0"})
|
||
try:
|
||
with urllib.request.urlopen(request, timeout=8) as response:
|
||
result = json.loads(response.read().decode("utf-8"))
|
||
if result.get("retCode") != 0:
|
||
raise RuntimeError(result.get("retMsg", "Bybit kline request failed"))
|
||
interval_ms = interval * 60_000
|
||
now_ms = int(time.time() * 1000)
|
||
closed = [row for row in result.get("result", {}).get("list", []) if int(row[0]) + interval_ms <= now_ms]
|
||
if not closed:
|
||
raise RuntimeError("Bybit не вернул закрытую свечу")
|
||
latest = max(closed, key=lambda row: int(row[0]))
|
||
self.events.put(("baseline", symbol, interval, float(latest[4])))
|
||
except Exception as exc:
|
||
self.events.put(("status", f"Не удалось загрузить закрытие свечи: {exc}"))
|
||
|
||
@staticmethod
|
||
def _draw_level(canvas: tk.Canvas, price: float, low: float, high: float, left: int, right: int, top: int, bottom: int, label: str, color: str) -> None:
|
||
if not low <= price <= high:
|
||
return
|
||
y = bottom - (price - low) / (high - low) * (bottom - top)
|
||
canvas.create_line(left, y, right, y, fill=color, dash=(5, 3))
|
||
canvas.create_text(left + 4, y - 3, anchor="sw", fill=color, text=f"{label}: {PaperSimulator._fmt_price(price)}")
|
||
|
||
def _on_close(self) -> None:
|
||
if self.running:
|
||
self.stop()
|
||
self._save_settings()
|
||
self._save_account_state()
|
||
self._signal_pool.shutdown(wait=False, cancel_futures=True)
|
||
self.root.destroy()
|
||
|
||
|
||
def main() -> None:
|
||
root = tk.Tk()
|
||
PaperSimulator(root)
|
||
root.mainloop()
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|