1
This commit is contained in:
1 parent
2ea1a79bda
commit
85425483c0
50 files changed
+6468
-1854
No files matched your search
@@ -12,7 +12,6 @@ import urllib.parse
|
||||
import urllib.request
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from collections import deque
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
import tkinter as tk
|
||||
@@ -22,6 +21,9 @@ from credential_store import CredentialStoreError, delete_credentials, load_cred
|
||||
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
|
||||
@@ -59,75 +61,7 @@ MAX_EVENTS_PER_POLL = 2000
|
||||
MANUAL_CLOSE_CONFIRM_SECONDS = 15
|
||||
|
||||
|
||||
@dataclass
|
||||
class Position:
|
||||
trade_id: int
|
||||
symbol: str
|
||||
entry_price: float
|
||||
qty: float
|
||||
stake: float
|
||||
entry_fee: float
|
||||
opened_at: float
|
||||
last_add_price: float
|
||||
add_count: int = 0
|
||||
# Strategy-mode fields; classic positions keep the defaults.
|
||||
side: str = "long"
|
||||
mode: str = strategy.STRATEGY_CLASSIC
|
||||
leverage: float = 1.0
|
||||
stop_price: float = 0.0
|
||||
initial_stop: float = 0.0
|
||||
atr: float = 0.0
|
||||
extreme: float = 0.0
|
||||
partial_target: float = 0.0 # 0 = none
|
||||
final_target: float = 0.0 # 0 = none
|
||||
partial_done: bool = False
|
||||
realized_gross: float = 0.0
|
||||
realized_fees: float = 0.0
|
||||
opened_stake: float = 0.0
|
||||
|
||||
|
||||
@dataclass
|
||||
class ClosedTrade:
|
||||
trade_id: int
|
||||
symbol: str
|
||||
entry_price: float
|
||||
exit_price: float
|
||||
qty: float
|
||||
gross_pnl: float
|
||||
fees: float
|
||||
net_pnl: float
|
||||
roi_pct: float
|
||||
opened_at: float
|
||||
closed_at: float
|
||||
reason: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class CurrencyState:
|
||||
"""Independent market and position state for one concurrently traded symbol."""
|
||||
prices: deque = field(default_factory=deque)
|
||||
candles: deque = field(default_factory=deque)
|
||||
entry_markers: deque = field(default_factory=deque)
|
||||
last_price: float | None = None
|
||||
baseline_close: float | None = None
|
||||
last_signal_pct: float | None = None
|
||||
last_signal_ready: bool = False
|
||||
previous_entry_signal_pct: float | None = None
|
||||
live_minute_prices: deque = field(default_factory=deque)
|
||||
last_ws_message: float = 0.0
|
||||
position: Position | None = None
|
||||
live_position: Position | None = None
|
||||
live_position_info: dict | None = None
|
||||
live_order_busy: bool = False
|
||||
live_transition_pending: bool = False
|
||||
live_halted: bool = False
|
||||
# Strategy modes A/B: last evaluated signal candle and the signal valid until the next close.
|
||||
mode_signal: dict | None = None
|
||||
mode_signal_bucket: int = 0
|
||||
mode_eval_busy: bool = False
|
||||
|
||||
|
||||
class PaperSimulator:
|
||||
class PaperSimulator(ChartView):
|
||||
def __init__(self, root: tk.Tk) -> None:
|
||||
self.root = root
|
||||
self.root.title("Bybit — симулятор сделок в реальном времени")
|
||||
@@ -2134,10 +2068,8 @@ class PaperSimulator:
|
||||
"live_initial_deposits": self.live_initial_deposits,
|
||||
}
|
||||
try:
|
||||
temp_path = STATE_FILE.with_suffix(".json.tmp")
|
||||
temp_path.write_text(json.dumps(state, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
os.replace(temp_path, STATE_FILE)
|
||||
except OSError as exc:
|
||||
atomic_write_json(STATE_FILE, state)
|
||||
except (OSError, ValueError) as exc:
|
||||
if hasattr(self, "status_var"):
|
||||
self.status_var.set(f"Не удалось сохранить историю счёта: {exc}")
|
||||
|
||||
@@ -2154,10 +2086,8 @@ class PaperSimulator:
|
||||
def _save_settings(self) -> None:
|
||||
self._settings_save_job = None
|
||||
try:
|
||||
temp_path = SETTINGS_FILE.with_suffix(".json.tmp")
|
||||
temp_path.write_text(json.dumps(self._settings_payload(), ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
os.replace(temp_path, SETTINGS_FILE)
|
||||
except OSError as exc:
|
||||
atomic_write_json(SETTINGS_FILE, self._settings_payload())
|
||||
except (OSError, ValueError) as exc:
|
||||
self.status_var.set(f"Не удалось сохранить настройки: {exc}")
|
||||
|
||||
@staticmethod
|
||||
@@ -4513,199 +4443,6 @@ class PaperSimulator:
|
||||
return f"\nвходов ещё: {min(by_money, by_limit)} · ставка {stake:,.2f} · позиций {open_positions}/{limit}"
|
||||
return f"\nвходов ещё: {by_money} · ставка {stake:,.2f}"
|
||||
|
||||
def _draw_chart(self) -> None:
|
||||
if not hasattr(self, "canvas"):
|
||||
return
|
||||
c = self.canvas
|
||||
c.delete("all")
|
||||
width, height = c.winfo_width(), c.winfo_height()
|
||||
if width < 80 or height < 80:
|
||||
return
|
||||
left, right, top, bottom = 58, width - 82, 22, height - 34
|
||||
c.create_text(10, 8, anchor="nw", fill="#d3dce6", text=f"{self.symbol} · свечи {self.interval_minutes} мин · последние 30 свечей")
|
||||
candles = list(self.candles)
|
||||
if not candles:
|
||||
c.create_text(width / 2, height / 2, fill="#b9c6d4", text="Ожидание данных Bybit…")
|
||||
return
|
||||
prices = [p for candle in candles for p in (candle[2], candle[3])]
|
||||
low, high = min(prices), max(prices)
|
||||
pad = (high - low) * .08 if high != low else max(high * .001, 1e-8)
|
||||
low -= pad
|
||||
high += pad
|
||||
t0 = candles[0][0]
|
||||
t1 = max(candles[-1][0] + 60, t0 + 60)
|
||||
view_end = self.chart_view_end if self.chart_view_end is not None else t1
|
||||
view_start = view_end - self.chart_visible_seconds
|
||||
visible_candles = [candle for candle in candles if view_start - 60 <= candle[0] <= view_end]
|
||||
visible_markers = [marker for marker in self.entry_markers if view_start <= marker[0] <= view_end]
|
||||
if visible_candles:
|
||||
candles = visible_candles
|
||||
prices = [p for candle in candles for p in (candle[2], candle[3])]
|
||||
low, high = min(prices), max(prices)
|
||||
base_span = high - low
|
||||
pad = base_span * .08 if base_span else max(high * .001, 1e-8)
|
||||
natural_low, natural_high = low - pad, high + pad
|
||||
if self.chart_price_center is None or self.chart_price_span is None:
|
||||
low, high = natural_low, natural_high
|
||||
if self.chart_price_center is not None and self.chart_price_span is not None:
|
||||
span = self.chart_price_span
|
||||
low = self.chart_price_center - span / 2
|
||||
high = self.chart_price_center + span / 2
|
||||
t0 = view_start
|
||||
t1 = view_end
|
||||
if t1 <= t0:
|
||||
return
|
||||
for i in range(5):
|
||||
y = top + i * (bottom - top) / 4
|
||||
value = high - i * (high - low) / 4
|
||||
c.create_line(left, y, right, y, fill="#263746")
|
||||
c.create_text(right + 5, y, anchor="w", fill="#9fb2c4", text=self._fmt_price(value))
|
||||
c.create_line(left, bottom, right, bottom, fill="#6c7e8c")
|
||||
candle_seconds = self.interval_minutes * 60
|
||||
slot = (right - left) * candle_seconds / (t1 - t0)
|
||||
body_width = max(2.0, min(16.0, slot * .62))
|
||||
for candle in candles:
|
||||
t, open_price, high_price, low_price, close_price = candle
|
||||
if t < t0 - candle_seconds or t > t1:
|
||||
continue
|
||||
x = left + (t + candle_seconds / 2 - t0) / (t1 - t0) * (right - left)
|
||||
y_high = bottom - (high_price - low) / (high - low) * (bottom - top)
|
||||
y_low = bottom - (low_price - low) / (high - low) * (bottom - top)
|
||||
y_open = bottom - (open_price - low) / (high - low) * (bottom - top)
|
||||
y_close = bottom - (close_price - low) / (high - low) * (bottom - top)
|
||||
color = "#38d996" if close_price >= open_price else "#ef5965"
|
||||
c.create_line(x, y_high, x, y_low, fill=color, width=1)
|
||||
body_top, body_bottom = sorted((y_open, y_close))
|
||||
if body_bottom - body_top < 1:
|
||||
body_bottom = body_top + 1
|
||||
c.create_rectangle(x - body_width / 2, body_top, x + body_width / 2, body_bottom, fill=color, outline=color)
|
||||
for marker_time, marker_price, trade_id in visible_markers:
|
||||
if not t0 <= marker_time <= t1:
|
||||
continue
|
||||
x = left + (marker_time - t0) / (t1 - t0) * (right - left)
|
||||
y = bottom - (marker_price - low) / (high - low) * (bottom - top)
|
||||
if top <= y <= bottom:
|
||||
c.create_oval(x - 5, y - 5, x + 5, y + 5, fill="#63a8ff", outline="white", width=1)
|
||||
c.create_text(x + 8, y - 10, anchor="sw", fill="#9fcaff", text=f"Вход #{trade_id}")
|
||||
position = self.live_position if self.mode_var.get() == "Реальная торговля" else self.position
|
||||
if position and position.mode != strategy.STRATEGY_CLASSIC:
|
||||
self._draw_level(c, position.entry_price, low, high, left, right, top, bottom,
|
||||
f"Вход {position.side.upper()}", "#63a8ff")
|
||||
self._draw_level(c, position.stop_price, low, high, left, right, top, bottom,
|
||||
"Стоп" if position.stop_price == position.initial_stop else "Стоп (подтянут)", "#ff8c42")
|
||||
if position.partial_target > 0 and not position.partial_done:
|
||||
self._draw_level(c, position.partial_target, low, high, left, right, top, bottom,
|
||||
"Частичная фиксация", "#40d6b0")
|
||||
if position.final_target > 0:
|
||||
self._draw_level(c, position.final_target, low, high, left, right, top, bottom, "Финальный TP", "#40d6b0")
|
||||
liquidation = strategy.liquidation_price(position.entry_price, position.leverage, side=position.side)
|
||||
if liquidation is not None:
|
||||
self._draw_level(c, liquidation, low, high, left, right, top, bottom, "Ликвидация", "#ff4d4d")
|
||||
elif position:
|
||||
self._draw_level(c, position.entry_price, low, high, left, right, top, bottom, "Средняя цена входа", "#63a8ff")
|
||||
s = self.applied_settings or self._safe_read_settings()
|
||||
if s["add_step"] > 0 and position.add_count < s["max_adds"]:
|
||||
next_add = position.last_add_price * (1 - s["add_step"] / 100)
|
||||
self._draw_level(c, next_add, low, high, left, right, top, bottom, f"Доливка #{position.add_count + 1}", "#b49cff")
|
||||
if s["stop_loss"] > 0:
|
||||
stop_price = position.entry_price * (1 - s["stop_loss"] / 100)
|
||||
self._draw_level(c, stop_price, low, high, left, right, top, bottom, "Стоп-лосс", "#ff8c42")
|
||||
if s["take_profit"] > 0:
|
||||
effective_tp_pct = max(s["take_profit"], self._fee_cover_pct(s["fee"]))
|
||||
take_profit_price = position.entry_price * (1 + effective_tp_pct / 100)
|
||||
self._draw_level(c, take_profit_price, low, high, left, right, top, bottom, "Фиксация TP", "#40d6b0")
|
||||
if self.last_price:
|
||||
y = bottom - (self.last_price - low) / (high - low) * (bottom - top)
|
||||
if top <= y <= bottom:
|
||||
c.create_line(left, y, right, y, fill="#f2c14e", dash=(4, 3))
|
||||
c.create_text(left, height - 17, anchor="w", fill="#9fb2c4", text=datetime.fromtimestamp(t0).strftime("%H:%M"))
|
||||
c.create_text(right, height - 17, anchor="e", fill="#9fb2c4", text=datetime.fromtimestamp(t1).strftime("%H:%M"))
|
||||
|
||||
def _chart_bounds(self) -> tuple[int, int, int, int]:
|
||||
width, height = self.canvas.winfo_width(), self.canvas.winfo_height()
|
||||
return 58, width - 82, 22, height - 34
|
||||
|
||||
def _on_chart_wheel(self, event: tk.Event) -> None:
|
||||
direction = 1 if event.delta > 0 else -1
|
||||
self._zoom_chart(event.x, event.y, direction)
|
||||
|
||||
def _on_chart_wheel_linux(self, event: tk.Event, direction: int) -> None:
|
||||
self._zoom_chart(event.x, event.y, direction)
|
||||
|
||||
def _zoom_chart(self, x: int, y: int, direction: int) -> None:
|
||||
if not self.candles:
|
||||
return
|
||||
old_span = self.chart_visible_seconds
|
||||
factor = 0.8 if direction > 0 else 1.25
|
||||
self.chart_visible_seconds = max(60, min(6 * 60 * 60, old_span * factor))
|
||||
if self.chart_view_end is None:
|
||||
self.chart_view_end = self.candles[-1][0] + 60
|
||||
left, right, top, bottom = self._chart_bounds()
|
||||
fraction_x = min(1, max(0, (x - left) / max(1, right - left)))
|
||||
old_start = self.chart_view_end - old_span
|
||||
anchor_time = old_start + fraction_x * old_span
|
||||
self.chart_view_end = anchor_time + (1 - fraction_x) * self.chart_visible_seconds
|
||||
if self.chart_price_center is None or self.chart_price_span is None:
|
||||
prices = [p for candle in self.candles for p in (candle[2], candle[3])]
|
||||
center = (max(prices) + min(prices)) / 2
|
||||
self.chart_price_center = center
|
||||
self.chart_price_span = (max(prices) - min(prices)) * 1.16 or max(center * .002, 1e-8)
|
||||
fraction_y = min(1, max(0, (y - top) / max(1, bottom - top)))
|
||||
anchor_price = self.chart_price_center + (0.5 - fraction_y) * self.chart_price_span
|
||||
self.chart_price_span = max(anchor_price * 1e-7, self.chart_price_span * factor)
|
||||
self.chart_price_center = anchor_price + (fraction_y - 0.5) * self.chart_price_span
|
||||
self._draw_chart()
|
||||
|
||||
def _on_chart_press(self, event: tk.Event) -> None:
|
||||
if not self.candles:
|
||||
return
|
||||
left, right, top, bottom = self._chart_bounds()
|
||||
if not left <= event.x <= right or not top <= event.y <= bottom:
|
||||
return
|
||||
if self.chart_view_end is None:
|
||||
self.chart_view_end = self.candles[-1][0] + 60
|
||||
if self.chart_price_center is None or self.chart_price_span is None:
|
||||
prices = [p for candle in self.candles for p in (candle[2], candle[3])]
|
||||
low, high = min(prices), max(prices)
|
||||
pad = (high - low) * .08 if high != low else max(high * .001, 1e-8)
|
||||
self.chart_price_center = (high + low) / 2
|
||||
self.chart_price_span = high - low + 2 * pad
|
||||
self._drag_anchor = (event.x, event.y, self.chart_view_end, self.chart_price_center,
|
||||
self.chart_price_span, self.chart_visible_seconds)
|
||||
self.canvas.configure(cursor="fleur")
|
||||
|
||||
def _on_chart_drag(self, event: tk.Event) -> None:
|
||||
if not self._drag_anchor:
|
||||
return
|
||||
x0, y0, end0, center0, price_span, time_span = self._drag_anchor
|
||||
left, right, top, bottom = self._chart_bounds()
|
||||
self.chart_view_end = end0 - (event.x - x0) / max(1, right - left) * time_span
|
||||
self.chart_price_center = center0 + (event.y - y0) / max(1, bottom - top) * price_span
|
||||
self.chart_price_span = price_span
|
||||
self._draw_chart()
|
||||
|
||||
def _on_chart_release(self, _event: tk.Event) -> None:
|
||||
self._drag_anchor = None
|
||||
self.canvas.configure(cursor="")
|
||||
|
||||
def _reset_chart_view(self, _event: tk.Event | None = None) -> None:
|
||||
self.chart_visible_seconds = self.interval_minutes * 60 * 30
|
||||
self.chart_view_end = None
|
||||
self.chart_price_center = None
|
||||
self.chart_price_span = None
|
||||
self._drag_anchor = None
|
||||
self._draw_chart()
|
||||
|
||||
def _go_to_live(self) -> None:
|
||||
"""Return the chart's right edge to the newest market candle."""
|
||||
if self.candles:
|
||||
self.chart_view_end = self.candles[-1][0] + self.interval_minutes * 60
|
||||
else:
|
||||
self.chart_view_end = None
|
||||
self.chart_price_center = None
|
||||
self.chart_price_span = None
|
||||
self._draw_chart()
|
||||
|
||||
def _update_candle(self, timestamp: float, price: float) -> None:
|
||||
interval_seconds = self.interval_minutes * 60
|
||||
candle_start = int(timestamp // interval_seconds) * interval_seconds
|
||||
|
||||
Reference in new issue
Block a user