"""Tk chart rendering and viewport interaction for the desktop simulator.""" from __future__ import annotations from datetime import datetime import tkinter as tk import strategy class ChartView: 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()