Загрузка данных


import { BehaviorSubject, combineLatest, map, Observable, Subscription } from 'rxjs';

import { ChartOptionsModel, ChartSeriesType, Intervals, TimeFormat } from '@src/types';

import { Defaults } from '@src/types/defaults';
import { Timeframes } from '@src/types/timeframes';
import { DateFormat, getInstrumentDisplayValue, getTimeframeByInterval, shouldShowTime } from '@src/utils';

import { ChartSettings, ChartSettingsSource, parseChartSettings } from './ChartSettings';
import { UndoKey, UndoRedo } from './UndoRedo';

interface EventManagerParams {
  initialTimeframe: Timeframes;
  initialSeries: ChartSeriesType;
  initialSymbol: string;
  initialInstrumentName?: string;
  initialInstrumentTicker?: string;
  initialTimeFormat?: TimeFormat;
  initialDateFormat?: DateFormat;
  initialInterval?: Intervals | null;
}

interface SetWithHistoryOptions {
  history?: boolean;
}

/**
 * Менеджер (настроек)*, которые меняются во время использование
 * Отвечает за централизованное управление (настроек)
 * * имеются в виду настройки, которые пользователь применяет к графику
 */
export class EventManager {
  private timeframe$: BehaviorSubject<Timeframes>;
  private seriesSelected$: BehaviorSubject<ChartSeriesType>;
  private symbol$: BehaviorSubject<string>;
  private instrumentName$: BehaviorSubject<string>;
  private instrumentTicker$: BehaviorSubject<string>;
  private timeFormat$: BehaviorSubject<TimeFormat>;
  private dateFormat$: BehaviorSubject<DateFormat>;
  private interval$: BehaviorSubject<Intervals | null>;

  private controlBarVisible$ = new BehaviorSubject<boolean>(false); // todo: move to render

  private undoRedo: UndoRedo;

  constructor({
    initialTimeframe,
    initialSeries,
    initialSymbol,
    initialInstrumentName,
    initialInstrumentTicker,
    initialTimeFormat,
    initialDateFormat,
    initialInterval = null,
  }: EventManagerParams) {
    const fallbackDisplayValue = getInstrumentDisplayValue(initialSymbol);

    this.timeframe$ = new BehaviorSubject<Timeframes>(initialTimeframe);
    this.seriesSelected$ = new BehaviorSubject<ChartSeriesType>(initialSeries);
    this.symbol$ = new BehaviorSubject<string>(initialSymbol);
    this.instrumentName$ = new BehaviorSubject<string>(initialInstrumentName?.trim() || fallbackDisplayValue);
    this.instrumentTicker$ = new BehaviorSubject<string>(initialInstrumentTicker?.trim() || fallbackDisplayValue);
    this.timeFormat$ = new BehaviorSubject<TimeFormat>(initialTimeFormat ?? Defaults.timeFormat);
    this.dateFormat$ = new BehaviorSubject<DateFormat>(initialDateFormat ?? Defaults.dateFormat);
    this.interval$ = new BehaviorSubject<Intervals | null>(initialInterval);

    this.undoRedo = new UndoRedo({
      timeframe: (value) => this.timeframe$.next(value),
      seriesSelected: (value) => this.seriesSelected$.next(value),
      symbol: (value) => this.symbol$.next(value),
      instrumentName: (value) => this.instrumentName$.next(value),
      instrumentTicker: (value) => this.instrumentTicker$.next(value),
      timeFormat: (value) => this.timeFormat$.next(value),
      dateFormat: (value) => this.dateFormat$.next(value),
      interval: (value) => this.interval$.next(value),
    });
  }

  private setWithHistory<K extends UndoKey, V>(
    key: K,
    subject: BehaviorSubject<V>,
    next: V,
    options?: SetWithHistoryOptions,
  ): void {
    const prev = subject.getValue();

    if (Object.is(prev, next)) {
      return;
    }

    subject.next(next);

    const historyEnabled = options?.history ?? true;

    if (historyEnabled) {
      this.undoRedo.push(key, prev, next);
    }
  }

  public getUndoRedo(): UndoRedo {
    return this.undoRedo;
  }

  public getTimeframe(): Timeframes {
    return this.timeframe$.value;
  }

  public setInterval = (next: Intervals, options?: SetWithHistoryOptions) => {
    const timeframe = getTimeframeByInterval(next);

    this.undoRedo.group(() => {
      this.setWithHistory('timeframe', this.timeframe$, timeframe, options);
      this.setWithHistory('interval', this.interval$, next, options);
    });
  };

  public resetInterval = (options?: SetWithHistoryOptions) =>
    this.setWithHistory('interval', this.interval$, null, options);

  public getInterval(): Observable<Intervals | null> {
    return this.interval$.asObservable();
  }

  public setSymbol = (symbol: string, options?: SetWithHistoryOptions): void => {
    this.setInstrument(symbol, undefined, undefined, options);
  };

  public getSymbol(): Observable<string> {
    return this.symbol$.asObservable();
  }

  public setInstrument(
    symbol: string,
    instrumentName?: string,
    instrumentTicker?: string,
    options?: SetWithHistoryOptions,
  ): void {
    const fallbackDisplayValue = getInstrumentDisplayValue(symbol);

    const nextInstrumentName = instrumentName?.trim() || fallbackDisplayValue;
    const nextInstrumentTicker = instrumentTicker?.trim() || fallbackDisplayValue;

    this.undoRedo.group(() => {
      this.setWithHistory('instrumentName', this.instrumentName$, nextInstrumentName, options);
      this.setWithHistory('instrumentTicker', this.instrumentTicker$, nextInstrumentTicker, options);
      this.setWithHistory('symbol', this.symbol$, symbol, options);
    });
  }

  public instrumentName(): Observable<string> {
    return this.instrumentName$.asObservable();
  }

  public getInstrumentName(): string {
    return this.instrumentName$.value;
  }

  public instrumentTicker(): Observable<string> {
    return this.instrumentTicker$.asObservable();
  }

  public getInstrumentTicker(): string {
    return this.instrumentTicker$.value;
  }

  public setTimeFormat = (next: TimeFormat, options?: SetWithHistoryOptions): void =>
    this.setWithHistory('timeFormat', this.timeFormat$, next, options);

  public setDateFormat = (next: DateFormat, options?: SetWithHistoryOptions): void =>
    this.setWithHistory('dateFormat', this.dateFormat$, next, options);

  public getChartOptionsModel(): Observable<ChartOptionsModel> {
    // todo: подумать - стоит ли унести это в чарт
    return combineLatest([this.timeFormat$, this.dateFormat$, this.timeframe$]).pipe(
      map(([timeFormat, dateFormat, timeframe]) => ({
        timeFormat,
        dateFormat,
        showTime: shouldShowTime(timeframe),
      })),
    );
  }

  public setTimeframe = (next: Timeframes, options?: SetWithHistoryOptions) =>
    this.undoRedo.group(() => {
      this.resetInterval(options);
      this.setWithHistory('timeframe', this.timeframe$, next, options);
    });

  public symbol(): Observable<string> {
    return this.symbol$.asObservable();
  }

  public timeframe(): Observable<Timeframes> {
    return this.timeframe$.asObservable();
  }

  public subscribeTimeframe(callback: (format: Timeframes) => void): Subscription {
    return this.timeframe$.subscribe(callback);
  }

  public getTimeframeObs(): Observable<Timeframes> {
    return this.timeframe$.asObservable();
  }

  public setSeriesSelected = (next: ChartSeriesType, options?: SetWithHistoryOptions) =>
    this.setWithHistory('seriesSelected', this.seriesSelected$, next, options);

  public getSelectedSeries(): Observable<ChartSeriesType> {
    return this.seriesSelected$.asObservable();
  }

  public subscribeSeriesSelected(callback: (next: ChartSeriesType) => void): Subscription {
    return this.seriesSelected$.subscribe(callback);
  }

  public setControlBarVisible(visible: boolean): void {
    this.controlBarVisible$.next(visible);
  }

  public getControlBarVisible(): Observable<boolean> {
    return this.controlBarVisible$.asObservable();
  }

  public exportChartSettings(): ChartSettings {
    return {
      timeframe: this.timeframe$.value,
      seriesSelected: this.seriesSelected$.value,
      symbol: this.symbol$.value,
      timeFormat: this.timeFormat$.value,
      dateFormat: this.dateFormat$.value,
      interval: this.interval$.value,
    };
  }

  public importChartSettings(settings: ChartSettingsSource): void {
    const { symbol, seriesSelected, timeframe, timeFormat, dateFormat, interval } = parseChartSettings(settings);
    const setOptions = { history: false };

    if (symbol) {
      this.setSymbol(symbol, setOptions);
    }
    if (seriesSelected) {
      this.setSeriesSelected(seriesSelected, setOptions);
    }
    if (timeFormat) {
      this.setTimeFormat(timeFormat, setOptions);
    }
    if (dateFormat) {
      this.setDateFormat(dateFormat, setOptions);
    }
    if (interval != null) {
      this.setInterval(interval, setOptions);
      return;
    }
    if (timeframe) {
      this.setTimeframe(timeframe, setOptions);
      return;
    }
    if (interval === null) {
      this.resetInterval(setOptions);
    }
  }

  public destroy(): void {
    this.timeFormat$.complete();
    this.dateFormat$.complete();
    this.timeframe$.complete();
    this.controlBarVisible$.complete();
    this.interval$.complete();
    this.symbol$.complete();
    this.instrumentName$.complete();
    this.instrumentTicker$.complete();
    this.seriesSelected$.complete();
  }
}


import { ChartSeriesType, Intervals, TimeFormat, Timeframes } from '@src/types';
import { DateFormat } from '@src/utils';

export type UndoKey = keyof UndoConfig;

interface UndoConfig {
  timeframe: (value: Timeframes) => void;
  seriesSelected: (value: ChartSeriesType) => void;
  symbol: (value: string) => void;
  instrumentName: (value: string) => void;
  instrumentTicker: (value: string) => void;
  timeFormat: (value: TimeFormat) => void;
  dateFormat: (value: DateFormat) => void;
  interval: (value: Intervals | null) => void;
}

interface HistoryItem {
  kind: 'item';
  key: UndoKey;
  prev: unknown;
  next: unknown;
}

interface HistoryGroup {
  kind: 'group';
  entries: HistoryEntry[];
}

type HistoryEntry = HistoryItem | HistoryGroup;

export class UndoRedo {
  private undoStack: HistoryEntry[] = [];
  private redoStack: HistoryEntry[] = [];

  private groupStack: HistoryEntry[][] = [];

  constructor(private readonly config: UndoConfig) {}

  private beginGroup(): void {
    this.groupStack.push([]);
  }

  private endGroup(): void {
    const entries = this.groupStack.pop();
    if (!entries || entries.length === 0) return;

    const group: HistoryGroup = { kind: 'group', entries };

    const parent = this.groupStack[this.groupStack.length - 1];
    if (parent) {
      parent.push(group);
      return;
    }

    this.undoStack.push(group);
    this.redoStack = [];
  }

  public group<T>(fn: () => T): T {
    this.beginGroup();
    try {
      return fn();
    } finally {
      this.endGroup();
    }
  }

  public push(key: UndoKey, prev: unknown, next: unknown): void {
    if (Object.is(prev, next)) return;

    const item: HistoryItem = { kind: 'item', key, prev, next };

    if (this.redoStack.length > 0) {
      this.redoStack = [];
    }

    const currentGroup = this.groupStack[this.groupStack.length - 1];
    if (currentGroup) {
      currentGroup.push(item);
      return;
    }

    this.undoStack.push(item);
  }

  public undo(): void {
    const entry = this.undoStack.pop();
    if (!entry) return;

    this.applyEntry(entry, 'undo');
    this.redoStack.push(entry);
  }

  public redo(): void {
    const entry = this.redoStack.pop();
    if (!entry) return;

    this.applyEntry(entry, 'redo');
    this.undoStack.push(entry);
  }

  private applyEntry(entry: HistoryEntry, direction: 'undo' | 'redo'): void {
    if (entry.kind === 'group') {
      const list = entry.entries;
      if (direction === 'undo') {
        for (let i = list.length - 1; i >= 0; i -= 1) this.applyEntry(list[i], direction);
      } else {
        for (let i = 0; i < list.length; i += 1) this.applyEntry(list[i], direction);
      }
      return;
    }

    const apply = this.config[entry.key] as (v: unknown) => void;
    apply(direction === 'undo' ? entry.prev : entry.next);
  }

  public canUndo(): boolean {
    return this.undoStack.length > 0;
  }

  public canRedo(): boolean {
    return this.redoStack.length > 0;
  }

  public clear(): void {
    this.undoStack = [];
    this.redoStack = [];
    this.groupStack = [];
  }
}


import { DataSource } from '@core/DataSource';
import { DrawingsManagerSnapshot } from '@core/DrawingsManager';
import { ChartSeriesType, DateFormat, IndicatorsIds, Intervals, Timeframes } from '@lib';
import { Direction } from '@src/types/chart';
import { IndicatorConfig } from '@src/types/indicator';
import { TimeFormat } from '@src/types/timeScale';

import type { PriceScaleMode } from 'lightweight-charts';

export type PriceScaleSide = Direction.Left | Direction.Right;

export interface ISerializable<T extends object> {
  getSnapshot: () => T;
}

export interface InitialSnapshot {
  timeframe: Timeframes; // todo: move to snap
  chartSeriesType: ChartSeriesType; // todo: move to snap
  symbol: string; // todo: move to snap
}

export interface MoexChartSnapshot {
  // settings: ChartSettingsSnapshot;
  charts: ChartSnapshot[];
}

export interface ChartSnapshot {
  timeframe: Timeframes;
  chartSeriesType: ChartSeriesType;
  symbol: string;
  instrumentName?: string;
  instrumentTicker?: string;
  timeFormat?: TimeFormat;
  dateFormat?: DateFormat;
  interval?: Intervals | null;
  panes: PaneSnapshot[];
}

export interface PriceScaleSnapshot {
  side: PriceScaleSide;
  mode: PriceScaleMode;
}

export interface PaneSnapshot {
  isMain: boolean;
  id: number;
  indicators: IndicatorSnapshot[];
  drawings: DrawingsManagerSnapshot;
  priceScales?: PriceScaleSnapshot[];
}

export interface IndicatorSnapshot extends Partial<DOMObjectSnapshot> {
  dataSource?: DataSource;
  indicatorType: IndicatorsIds | undefined; // if indicatorType is undefined, then its compareIndicator
  config?: IndicatorConfig;
}

// todo: move DrawingsManagerSnapshot here

export interface DOMObjectSnapshot {
  id: string;
  name: string;
  zIndex: number;
  hidden: boolean;
  paneId: number;
}

import dayjs from 'dayjs';

import {
  BarPrice,
  ChartOptions,
  createChart,
  CrosshairMode,
  DeepPartial,
  IChartApi,
  IRange,
  LocalizationOptionsBase,
  LogicalRange,
  Time,
  UTCTimestamp,
} from 'lightweight-charts';

import { BehaviorSubject, combineLatest, Observable, Subscription } from 'rxjs';
import { map, withLatestFrom } from 'rxjs/operators';

import { ChartMouseEvents } from '@core/ChartMouseEvents';
import { DataSource } from '@core/DataSource';
import { DOMModel } from '@core/DOMModel';
import { DrawingsManager } from '@core/DrawingsManager';
import { EventManager } from '@core/EventManager';
import { Hotkeys } from '@core/Hotkeys';
import { IndicatorManager } from '@core/IndicatorManager';
import { ModalRenderer } from '@core/ModalRenderer';
import { PaneManager } from '@core/PaneManager';
import { CompareManager } from '@src/core/CompareManager';
import { SeriesStrategies } from '@src/modules/series-strategies/SeriesFactory';
import { getThemeStore } from '@src/theme/store';
import { ThemeKey, ThemeMode } from '@src/theme/types';
import { getLocale } from '@src/translations';
import {
  Candle,
  ChartOptionsModel,
  ChartSeriesType,
  ChartTypeOptions,
  Direction,
  OHLCConfig,
  TooltipConfig,
} from '@src/types';
import { Defaults } from '@src/types/defaults';
import { DayjsOffset, Intervals, intervalsToDayjs } from '@src/types/intervals';
import { ChartSnapshot, ISerializable, PaneSnapshot } from '@src/types/snapshot';
import { formatCompactNumber } from '@src/utils';
import { createTickMarkFormatter, formatDate } from '@src/utils/formatter';

export interface ChartConfig extends Partial<ChartOptionsModel> {
  container: HTMLElement;
  seriesTypes: ChartSeriesType[];
  theme: ThemeKey;
  mode?: ThemeMode;
  chartOptions?: ChartTypeOptions;
  localization?: LocalizationOptionsBase;
}

export enum Resize {
  Shrink,
  Expand,
}

const HISTORY_LOAD_THRESHOLD = 50;

interface ChartParams {
  params: {
    dataSource: DataSource;
    eventManager: EventManager;
    modalRenderer: ModalRenderer;
    ohlcConfig: OHLCConfig;
    tooltipConfig: TooltipConfig;
    panes: PaneSnapshot[];
    hotkeys: Hotkeys;
  };
  lwcChartConfig: ChartConfig;
}

function splitIndicatorSnapshots(panes: PaneSnapshot[]) {
  const snapshots = panes.flatMap(({ id, indicators }) =>
    indicators.map((indicator) => ({
      ...indicator,
      paneId: id,
    })),
  );

  return {
    indicatorSnapshots: snapshots.filter(({ indicatorType }) => indicatorType !== undefined),
    compareSnapshots: snapshots.filter(({ indicatorType }) => indicatorType === undefined),
  };
}

/**
 * Абстракция над библиотекой для построения графиков
 */
export class Chart implements ISerializable<ChartSnapshot> {
  private lwcChart!: IChartApi;
  private container: HTMLElement;
  private eventManager: EventManager;
  private paneManager!: PaneManager;
  private compareManager: CompareManager;
  private mouseEvents: ChartMouseEvents;
  private indicatorManager: IndicatorManager;
  private optionsSubscription: Subscription;
  private dataSource: DataSource;
  private chartConfig: ChartConfig;
  private mainSeries: BehaviorSubject<SeriesStrategies | null>; // Main Series. Exists in a single copy
  private DOM: DOMModel;

  private isPointerDown = false;
  private didResetOnDrag = false;

  private subscriptions = new Subscription();

  private currentInterval: Intervals | null = null;

  private activeSymbols: string[] = [];

  private historyBatchRunning = false;

  constructor({ params, lwcChartConfig }: ChartParams) {
    const { eventManager, dataSource, modalRenderer, ohlcConfig, tooltipConfig, panes: panesSnapshot } = params;

    this.eventManager = eventManager;
    this.dataSource = dataSource;
    this.container = lwcChartConfig.container;
    this.chartConfig = lwcChartConfig;

    this.lwcChart = createChart(this.container, getOptions(lwcChartConfig));

    this.optionsSubscription = this.eventManager
      .getChartOptionsModel()
      .subscribe(({ dateFormat, timeFormat, showTime }) => {
        this.chartConfig = {
          ...this.chartConfig,
          dateFormat,
          timeFormat,
          showTime,
        };

        this.lwcChart.applyOptions({
          ...getOptions(this.chartConfig),
          localization: {
            timeFormatter: (time: UTCTimestamp) => formatDate(time, dateFormat, timeFormat, showTime),
          },
        });
      });

    this.subscriptions.add(this.optionsSubscription);

    this.mouseEvents = new ChartMouseEvents({
      lwcChart: this.lwcChart,
      container: this.container,
    });

    this.mouseEvents.subscribe('wheel', this.onWheel);
    this.mouseEvents.subscribe('pointerDown', this.onPointerDown);
    this.mouseEvents.subscribe('pointerMove', this.onPointerMove);
    this.mouseEvents.subscribe('pointerUp', this.onPointerUp);
    this.mouseEvents.subscribe('pointerCancel', this.onPointerUp);

    this.DOM = new DOMModel({
      modalRenderer,
    });

    this.paneManager = new PaneManager({
      eventManager: this.eventManager,
      panesSnapshot,
      lwcChart: this.lwcChart,
      dataSource,
      DOM: this.DOM,
      ohlcConfig,
      subscribeChartEvent: this.subscribeChartEvent,
      chartContainer: this.container,
      tooltipConfig,
      modalRenderer,
      hotkeys: params.hotkeys,
    });

    this.mainSeries = this.paneManager.getMainPane().getMainSerie();

    const { indicatorSnapshots, compareSnapshots } = splitIndicatorSnapshots(panesSnapshot);

    this.indicatorManager = new IndicatorManager({
      eventManager,
      initialIndicators: indicatorSnapshots,
      DOM: this.DOM,
      dataSource: this.dataSource,
      lwcChart: this.lwcChart,
      paneManager: this.paneManager,
      chartOptions: lwcChartConfig.chartOptions,
    });

    this.compareManager = new CompareManager({
      chart: this.lwcChart,
      initialIndicators: compareSnapshots,
      eventManager: this.eventManager,
      dataSource: this.dataSource,
      indicatorManager: this.indicatorManager,
      paneManager: this.paneManager,
    });

    this.paneManager.start({
      compareEntities$: this.compareManager.entities(),
      indicatorEntities$: this.indicatorManager.entities(),
    });

    this.paneManager.setVisibleLogicalRange(this.lwcChart.timeScale().getVisibleLogicalRange());
    this.paneManager.invalidate();

    this.setupDataSourceSubs();
    this.setupHistoricalDataLoading();
  }

  public getPriceScaleWidth(direction: Direction): number {
    try {
      const priceScale = this.lwcChart.priceScale(direction);

      return priceScale ? priceScale.width() : 0;
    } catch {
      return 0;
    }
  }

  public getDrawingsManager = (): DrawingsManager => {
    return this.paneManager.getDrawingsManager();
  };

  public getIndicatorManager = (): IndicatorManager => {
    return this.indicatorManager;
  };

  private onWheel = () => {
    this.eventManager.resetInterval({
      history: false,
    });
  };

  private onPointerDown = () => {
    this.isPointerDown = true;
    this.didResetOnDrag = false;
  };

  private onPointerMove = () => {
    if (!this.isPointerDown) return;
    if (this.didResetOnDrag) return;

    this.didResetOnDrag = true;

    this.eventManager.resetInterval({
      history: false,
    });
  };

  private onPointerUp = () => {
    this.isPointerDown = false;
  };

  public getDom(): DOMModel {
    return this.DOM;
  }

  public getMainSeries(): Observable<SeriesStrategies | null> {
    return this.mainSeries.asObservable();
  }

  public getCompareManager(): CompareManager {
    return this.compareManager;
  }

  public updateTheme(theme: ThemeKey, mode: ThemeMode) {
    this.chartConfig = {
      ...this.chartConfig,
      theme,
      mode,
    };

    this.lwcChart.applyOptions(getOptions(this.chartConfig));

    this.paneManager.invalidate();
  }

  public destroy(): void {
    this.subscriptions.unsubscribe();
    this.mouseEvents.destroy();
    this.compareManager.destroy();
    this.paneManager.destroy();
    this.lwcChart.remove();
  }

  public subscribeChartEvent: ChartMouseEvents['subscribe'] = (event, callback) =>
    this.mouseEvents.subscribe(event, callback);

  public unsubscribeChartEvent: ChartMouseEvents['unsubscribe'] = (event, callback) => {
    this.mouseEvents.unsubscribe(event, callback);
  };

  // todo: add/move to undo/redo model(eventManager)
  public scrollTimeScale = (direction: Direction) => {
    this.eventManager.resetInterval({
      history: false,
    });

    const diff = direction === Direction.Left ? -2 : 2;
    const currentPosition = this.lwcChart.timeScale().scrollPosition();
    this.lwcChart.timeScale().scrollToPosition(currentPosition + diff, false);
  };

  // todo: add/move to undo/redo model(eventManager)
  public zoomTimeScale = (resize: Resize) => {
    this.eventManager.resetInterval({
      history: false,
    });

    const diff = resize === Resize.Shrink ? -1 : 1;

    const currentRange = this.lwcChart.timeScale().getVisibleRange();

    if (!currentRange) return;

    const { from, to } = currentRange as IRange<number>;

    if (!from || !to) return;

    const next: IRange<Time> = {
      from: (from + (to - from) * 0.1 * diff) as Time,
      to: to as Time,
    };

    this.lwcChart.timeScale().setVisibleRange(next);
  };

  // todo: add to undo/redo model(eventManager)
  public resetZoom = () => {
    this.eventManager.resetInterval({
      history: false,
    });

    this.lwcChart.timeScale().resetTimeScale();

    this.paneManager.resetPriceScalesAutoScale();
  };

  public getRealtimeApi() {
    return {
      getTimeframe: () => this.eventManager.getTimeframe(),
      getSymbols: () => this.activeSymbols,
      update: (symbol: string, candle: Candle) => {
        this.dataSource.updateRealtime(symbol, candle);
      },
    };
  }

  public getSnapshot(): ChartSnapshot {
    const { seriesSelected, timeframe, dateFormat, timeFormat, interval } = this.eventManager.exportChartSettings();

    return {
      panes: this.paneManager.getSnapshot(),
      chartSeriesType: seriesSelected,
      timeframe,
      dateFormat,
      timeFormat,
      interval,
      symbol: this.activeSymbols[0],
      instrumentName: this.eventManager.getInstrumentName(),
      instrumentTicker: this.eventManager.getInstrumentTicker(),
    };
  }

  private scheduleHistoryBatch = () => {
    if (this.historyBatchRunning) return;

    this.historyBatchRunning = true;

    requestAnimationFrame(() => {
      const symbols = this.activeSymbols.slice();

      Promise.all(symbols.map((symbol) => this.dataSource.loadMoreHistory(symbol))).finally(() => {
        this.historyBatchRunning = false;

        const range = this.lwcChart.timeScale().getVisibleLogicalRange();

        if (range && range.from < HISTORY_LOAD_THRESHOLD) {
          this.scheduleHistoryBatch();
        }
      });
    });
  };

  private setupDataSourceSubs() {
    const getWarmupFrom = (): number => {
      if (this.currentInterval && this.currentInterval !== Intervals.All) {
        return getIntervalRange(this.currentInterval).from;
      }

      const range = this.lwcChart.timeScale().getVisibleRange();

      if (!range) return 0;

      const { from } = range as IRange<number>;

      return from as number;
    };

    const warmupSymbols = (symbols: string[]) => {
      if (!symbols.length) return;

      const from = getWarmupFrom();

      if (!from) return;

      Promise.all(symbols.map((symbol) => this.dataSource.loadTill(symbol, from))).catch((error) => {
        console.error('[Chart] Ошибка при прогреве символов:', error);
      });
    };

    const symbols$ = combineLatest([this.eventManager.symbol(), this.compareManager.itemsObs()]).pipe(
      map(([main, items]) => Array.from(new Set([main, ...items.map((item) => item.symbol)]))),
    );

    this.subscriptions.add(
      this.eventManager
        .getInterval()
        .pipe(withLatestFrom(symbols$))
        .subscribe(([interval, symbols]) => {
          this.currentInterval = interval;

          if (!interval) return;

          if (interval === Intervals.All) {
            Promise.all(symbols.map((symbol) => this.dataSource.loadAllHistory(symbol)))
              .then(() => {
                requestAnimationFrame(() => this.lwcChart.timeScale().fitContent());
              })
              .catch((error) => console.error('[Chart] Ошибка при загрузке всей истории:', error));

            return;
          }

          const { from, to } = getIntervalRange(interval);

          Promise.all(symbols.map((symbol) => this.dataSource.loadTill(symbol, from)))
            .then(() => {
              this.lwcChart.timeScale().setVisibleRange({
                from: from as Time,
                to: to as Time,
              });
            })
            .catch((error) => {
              console.error('[Chart] Ошибка при применении интервала:', error);
            });
        }),
    );

    this.subscriptions.add(
      symbols$.subscribe((symbols) => {
        const previousSymbols = this.activeSymbols;

        this.activeSymbols = symbols;

        this.dataSource.setSymbols(symbols);

        const previousSymbolsSet = new Set(previousSymbols);
        const addedSymbols: string[] = [];

        for (let index = 0; index < symbols.length; index += 1) {
          const symbol = symbols[index];

          if (!symbol) continue;
          if (previousSymbolsSet.has(symbol)) {
            continue;
          }

          addedSymbols.push(symbol);
        }

        if (addedSymbols.length) {
          warmupSymbols(addedSymbols);
        }
      }),
    );
  }

  private setupHistoricalDataLoading(): void {
    // todo (не)вызвать loadMoreHistory после проверки на необходимость дозагрузки после смены таймфрейма
    this.mouseEvents.subscribe('visibleLogicalRangeChange', (logicalRange: LogicalRange | null) => {
      this.paneManager.setVisibleLogicalRange(logicalRange);

      if (!logicalRange) return;

      if (this.currentInterval === Intervals.All) {
        return;
      }

      const needsMoreData = logicalRange.from < HISTORY_LOAD_THRESHOLD;

      if (!needsMoreData) return;

      this.scheduleHistoryBatch();
    });
  }
}

function getIntervalRange(interval: Intervals): {
  from: number;
  to: number;
} {
  const { value, unit } = intervalsToDayjs[interval] as DayjsOffset;

  const from = Math.floor(dayjs().subtract(value, unit).valueOf() / 1000);
  const to = Math.floor(dayjs().valueOf() / 1000);

  return {
    from,
    to,
  };
}

function getOptions(config: ChartConfig): DeepPartial<ChartOptions> {
  const timeFormat = config.timeFormat ?? Defaults.timeFormat;
  const showTime = config.showTime ?? Defaults.showTime;

  const use12HourFormat = timeFormat === '12h';
  const timeFormatString = use12HourFormat ? 'h:mm A' : 'HH:mm';

  const { colors } = getThemeStore();

  const localization: LocalizationOptionsBase = {
    locale: getLocale(),
    priceFormatter: (priceValue: BarPrice) => {
      return formatCompactNumber(priceValue);
    },
  };

  return {
    width: config.container.clientWidth,
    height: config.container.clientHeight,
    autoSize: true,
    layout: {
      background: {
        color: colors.chartBackground,
      },
      textColor: colors.chartTextPrimary,
    },
    grid: {
      vertLines: {
        color: colors.chartGridLine,
      },
      horzLines: {
        color: colors.chartGridLine,
      },
    },
    crosshair: {
      mode: CrosshairMode.Normal,
      vertLine: {
        color: colors.chartCrosshairLine,
        labelBackgroundColor: colors.chartCrosshairLabel,
        style: 0,
      },
      horzLine: {
        color: colors.chartCrosshairLine,
        labelBackgroundColor: colors.chartCrosshairLabel,
        style: 2,
      },
    },
    timeScale: {
      timeVisible: showTime,
      secondsVisible: false,
      tickMarkFormatter: createTickMarkFormatter(timeFormatString),
      borderVisible: false,
      allowBoldLabels: false,
      rightOffset: 25,
    },
    rightPriceScale: {
      textColor: colors.chartTextPrimary,
      borderVisible: false,
    },
    localization,
  };
}


import { combineLatest, Subscription } from 'rxjs';

import { ControlBar } from '@components/ControlBar';
import { Footer } from '@components/Footer';

import { Header } from '@components/Header';
import { DataSource, DataSourceParams } from '@core/DataSource';
import { Hotkeys } from '@core/Hotkeys';
import { ModalRenderer } from '@core/ModalRenderer';
import { SettingsModal } from '@src/components/SettingsModal';

import Toolbar from '@src/components/Toolbar';
import { IndicatorsIds } from '@src/constants';
import { CompareManager } from '@src/core/CompareManager';
import { FullscreenController } from '@src/core/Fullscreen';

import { configureThemeStore } from '@src/theme/store';
import { ThemeKey, ThemeMode } from '@src/theme/types';
import { Locale, setLocale, t } from '@src/translations';
import { Candle, ChartSeriesType, ChartTypeOptions, OHLCConfig, TooltipConfig } from '@src/types';
import { ISerializable, MoexChartSnapshot } from '@src/types/snapshot';
import { Timeframes } from '@src/types/timeframes';

import { setPricePrecision } from '@src/utils';

import { Chart } from './Chart';
import { ChartSettings, ChartSettingsSource } from './ChartSettings';
import { ContainerManager } from './ContainerManager';
import { EventManager } from './EventManager';
import { ReactRenderer } from './ReactRenderer';
import { TimeScaleHoverController } from './TimescaleHoverController';
import { UIRenderer } from './UIRenderer';

import 'exchange-elements/dist/fonts/inter/font.css';
import 'exchange-elements/dist/style.css';
import 'exchange-elements/dist/tokens/moex.css';
import '../styles/global.scss';

// todo: forbid @lib in /src
export interface ChartCollectionPreset {
  undoRedoEnabled?: boolean;
  showMenuButton?: boolean;
  showBottomPanel?: boolean;
  showControlBar?: boolean;
  showFullscreenButton?: boolean;
  showSettingsButton?: boolean;
  showCompareButton?: boolean;
  showSymbolSearchButton?: boolean;
  /**
   * Дефолтная конфигурация тултипа - всегда показывается по умолчанию.
   * При добавлении/изменении полей в конфиге - они объединяются с дефолтными значениями.
   *
   * Полная кастомизация:
   * @example
   * ```typescript
   *    tooltipConfig: {
   *      time: { visible: true, label: 'Дата и время' },
   *      symbol: { visible: true, label: 'Инструмент' },
   *      close: { visible: true, label: 'Курс' },
   *      change: { visible: true, label: 'Изменение' },
   *      volume: { visible: true, label: 'Объем' },
   *      open: { visible: false },
   *      high: { visible: false },
   *      low: { visible: false }
   *    }
   *```
   */
  tooltipConfig?: TooltipConfig;

  size?:
    | {
        width: number;
        height: number;
      }
    | false;
  supportedTimeframes: Timeframes[];
  supportedChartSeriesTypes: ChartSeriesType[];
  getDataSource: DataSourceParams['getData'];
  startRealtime: (
    getSymbols: () => string[],
    getTimeframe: () => Timeframes,
    update: (symbol: string, candle: Candle) => void,
    periodMs?: number,
  ) => () => void;
  theme: ThemeKey; // 'mb' | 'mxt' | 'tr'
  ohlc: OHLCConfig;
  locale: Locale;
  mode?: ThemeMode; // 'light' | 'dark'
  openCompareModal?: () => void;
  openSymbolSearchModal?: () => void;
}

export interface IMoexChart {
  snapshot: MoexChartSnapshot;
  chartCollectionPreset: ChartCollectionPreset;

  container: HTMLElement;
  lwcInheritedChartOptions?: ChartTypeOptions;
}

export class MoexChart implements ISerializable<MoexChartSnapshot> {
  private chart!: Chart;
  private resizeObserver?: ResizeObserver;
  private eventManager!: EventManager;
  private hotkeys!: Hotkeys;
  private rootContainer!: HTMLElement;

  private headerRenderer!: UIRenderer;
  private modalRenderer!: ModalRenderer;
  private toolbarRenderer: UIRenderer | undefined;
  private controlBarRenderer?: UIRenderer;
  private footerRenderer?: UIRenderer;

  private timeScaleHoverController!: TimeScaleHoverController;
  private dataSource!: DataSource;

  private subscriptions = new Subscription();

  private fullscreen!: FullscreenController;

  private chartCollectionPresetSettings!: ChartCollectionPreset;

  constructor(config: IMoexChart) {
    setLocale(config.chartCollectionPreset.locale);
    this.setup(config);
  }

  private setup = (config: IMoexChart) => {
    this.chartCollectionPresetSettings = config.chartCollectionPreset;

    setPricePrecision(config.chartCollectionPreset.ohlc.precision);

    const { chartSeriesType, symbol, instrumentName, instrumentTicker, timeframe, interval, dateFormat, timeFormat } =
      config.snapshot.charts[0];

    this.eventManager = new EventManager({
      initialTimeframe: timeframe,
      initialSeries: chartSeriesType,
      initialSymbol: symbol,
      initialInstrumentName: instrumentName,
      initialInstrumentTicker: instrumentTicker,
      initialTimeFormat: timeFormat,
      initialDateFormat: dateFormat,
      initialInterval: interval,
    });

    // todo: сюда прокидывается не подходящий под сигнатуру интерфейс. Функция не работает
    // if (config.lwcInheritedChartOptions) {
    //   this.setSettings(config.lwcInheritedChartOptions);
    // }

    this.dataSource = new DataSource({
      getData: config.chartCollectionPreset.getDataSource,
      eventManager: this.eventManager,
    });

    this.rootContainer = config.container;

    this.fullscreen = new FullscreenController(this.rootContainer);

    const store = configureThemeStore(config.chartCollectionPreset);

    const {
      chartAreaContainer,
      toolBarContainer,
      headerContainer,
      modalContainer,
      controlBarContainer,
      footerContainer,
      toggleToolbar, // todo: move this function to toolbarModel
    } = ContainerManager.createContainers({
      parentContainer: this.rootContainer,
      showBottomPanel: config.chartCollectionPreset.showBottomPanel, // todo: apply config.showBottomPanel in FullscreenController
      showMenuButton: config.chartCollectionPreset.showMenuButton,
    });

    this.hotkeys = new Hotkeys();

    this.modalRenderer = new ModalRenderer(modalContainer);

    this.chart = new Chart({
      params: {
        dataSource: this.dataSource,
        eventManager: this.eventManager,
        modalRenderer: this.modalRenderer,
        ohlcConfig: config.chartCollectionPreset.ohlc, // todo: omptimize
        tooltipConfig: config.chartCollectionPreset.tooltipConfig ?? {},
        panes: config.snapshot.charts[0].panes,
        hotkeys: this.hotkeys,
      },
      lwcChartConfig: {
        container: chartAreaContainer,
        seriesTypes: config.chartCollectionPreset.supportedChartSeriesTypes,
        theme: store.theme,
        mode: store.mode,
        chartOptions: config.lwcInheritedChartOptions, // todo: remove, use only model from eventManager
      },
    });

    this.subscriptions.add(
      combineLatest([store.theme$, store.mode$]).subscribe(([theme, mode]) => {
        this.chart.updateTheme(theme, mode);

        document.documentElement.dataset.theme = theme;
        document.documentElement.dataset.mode = mode;
      }),
    );

    const realtimeParams = this.chart.getRealtimeApi();

    this.subscriptions.add(
      config.chartCollectionPreset.startRealtime(
        realtimeParams.getSymbols,
        realtimeParams.getTimeframe,
        realtimeParams.update,
      ),
    );

    this.headerRenderer = new ReactRenderer(headerContainer);
    this.toolbarRenderer = new ReactRenderer(toolBarContainer);

    if (config.chartCollectionPreset.showControlBar) {
      this.controlBarRenderer = new ReactRenderer(controlBarContainer);
    }

    if (config.chartCollectionPreset.showBottomPanel) {
      this.footerRenderer = new ReactRenderer(footerContainer);
    }

    this.timeScaleHoverController = new TimeScaleHoverController({
      eventManager: this.eventManager,
      controlBarContainer,
      chartContainer: chartAreaContainer,
    });

    this.renderAttachments(config, toggleToolbar);
  };

  public setSettings(settings: ChartSettingsSource): void {
    this.eventManager.importChartSettings(settings);
  }

  public getSettings(): ChartSettings {
    return this.eventManager.exportChartSettings();
  }

  // todo: описать подробнее в доке. Точно ли public?
  public getRealtimeApi() {
    return this.chart.getRealtimeApi();
  }

  // todo: описать подробнее в доке
  public getCompareManager(): CompareManager {
    return this.chart.getCompareManager();
  }

  public setSnapshot(snap: MoexChartSnapshot) {
    const configConstructorLike: IMoexChart = {
      snapshot: snap,
      chartCollectionPreset: this.chartCollectionPresetSettings,
      container: this.rootContainer,
    };
    this.destroy();

    this.setup(configConstructorLike);
  }

  // todo: описать в доке
  public getSnapshot(): MoexChartSnapshot {
    const res = {
      settings: this.getSettings(),
      charts: [this.chart.getSnapshot()], // todo: в будущем может быть несколько инстансов чартов
    };

    return res;
  }

  public setSymbol(symbol: string, instrumentName?: string, instrumentTicker?: string): void {
    if (!symbol) return;

    this.eventManager.setInstrument(symbol, instrumentName, instrumentTicker);
  }

  private renderAttachments(config: IMoexChart, toggleToolbar: () => boolean) {
    this.headerRenderer.renderComponent(
      <Header
        timeframes={config.chartCollectionPreset.supportedTimeframes}
        selectedTimeframeObs={this.eventManager.getTimeframeObs()}
        setTimeframe={(value) => {
          this.eventManager.setTimeframe(value);
        }}
        seriesTypes={config.chartCollectionPreset.supportedChartSeriesTypes}
        selectedSeriesObs={this.eventManager.getSelectedSeries()}
        setSelectedSeries={(value) => {
          this.eventManager.setSeriesSelected(value);
        }}
        showSettingsModal={
          config.chartCollectionPreset.showSettingsButton
            ? () =>
                this.modalRenderer.renderComponent(
                  <SettingsModal
                    // todo: deal with onSave
                    changeTimeFormat={(format) => this.eventManager.setTimeFormat(format)}
                    changeDateFormat={(format) => this.eventManager.setDateFormat(format)}
                    chartDateTimeFormatObs={this.eventManager.getChartOptionsModel()}
                  />,
                  { title: t('Settings') },
                )
            : undefined
        }
        addIndicatorToChart={(indicatorType: IndicatorsIds) =>
          this.chart.getIndicatorManager().addIndicator({ indicatorType })
        }
        showMenuButton={!!config.chartCollectionPreset.showMenuButton}
        showFullscreenButton={!!config.chartCollectionPreset.showFullscreenButton}
        fullscreen={this.fullscreen}
        undoRedo={config.chartCollectionPreset.undoRedoEnabled ? this.eventManager.getUndoRedo() : undefined}
        toggleToolbarVisible={toggleToolbar}
        showCompareButton={!!config.chartCollectionPreset.showCompareButton}
        openCompareModal={
          config.chartCollectionPreset.openCompareModal ? config.chartCollectionPreset.openCompareModal : undefined
        }
        showSymbolSearchButton={!!config.chartCollectionPreset.openSymbolSearchModal}
        openSymbolSearchModal={config.chartCollectionPreset.openSymbolSearchModal}
        isMXT={config.chartCollectionPreset.theme === 'mxt'}
      />,
    );

    if (this.toolbarRenderer && config.chartCollectionPreset.showMenuButton) {
      this.toolbarRenderer.renderComponent(
        <Toolbar
          toggleDOM={this.chart.getDom().toggleDOM}
          addDrawing={this.chart.getDrawingsManager().addDrawingForce} // todo: deal with new panes logic
          setEndlessDrawingsMode={this.chart.getDrawingsManager().setEndlessDrawingMode}
          isEndlessDrawingsMode$={this.chart.getDrawingsManager().isEndlessDrawingsMode()}
          activateCrosshair={() => this.chart.getDrawingsManager().activateCrosshair()}
          activeTool$={this.chart.getDrawingsManager().getActiveTool()}
          hotkeys={this.hotkeys}
        />,
      );
    }

    if (this.controlBarRenderer && config.chartCollectionPreset.showControlBar) {
      this.controlBarRenderer.renderComponent(
        <ControlBar
          scroll={this.chart.scrollTimeScale}
          zoom={this.chart.zoomTimeScale}
          reset={this.chart.resetZoom}
          visible={this.eventManager.getControlBarVisible()}
        />,
      );
    }

    if (this.footerRenderer && config.chartCollectionPreset.showBottomPanel) {
      this.footerRenderer.renderComponent(
        <Footer
          supportedTimeframes={config.chartCollectionPreset.supportedTimeframes}
          setInterval={this.eventManager.setInterval}
          intervalObs={this.eventManager.getInterval()}
        />,
      );
    }
  }

  /**
   * Уничтожение графика и очистка ресурсов
   * @returns void
   */
  destroy(): void {
    this.headerRenderer.destroy();
    this.subscriptions.unsubscribe();
    this.timeScaleHoverController.destroy();

    if (this.resizeObserver) {
      this.resizeObserver.disconnect();
      this.resizeObserver = undefined;
    }

    if (this.controlBarRenderer) {
      this.controlBarRenderer.destroy();
    }

    if (this.footerRenderer) {
      this.footerRenderer.destroy();
    }

    if (this.chart) {
      this.chart.destroy();
    }

    if (this.eventManager) {
      this.eventManager.destroy();
    }

    this.dataSource.destroy();

    ContainerManager.clearContainers(this.rootContainer);
  }
}


import { IChartApi, PriceScaleMode, SeriesType } from 'lightweight-charts';

import { flatten } from 'lodash-es';
import { BehaviorSubject, distinctUntilChanged, map, Observable, Subscription } from 'rxjs';

import { DataSource } from '@core/DataSource';
import { EventManager } from '@core/EventManager';
import { Indicator } from '@core/Indicator';
import { IndicatorManager } from '@core/IndicatorManager';
import { PaneManager } from '@core/PaneManager';
import { PriceScale } from '@core/PriceScale';
import { COMPARE_COLOR_PALETTE } from '@src/theme';
import { CompareInstrument, CompareItem, CompareMode, Direction, IndicatorConfig } from '@src/types';
import { IndicatorSnapshot } from '@src/types/snapshot';
import { createFallbackColor, getInstrumentDisplayValue, normalizeColor, normalizeSymbol } from '@src/utils';

interface CompareEntry extends CompareItem {
  key: string;
  symbol$: BehaviorSubject<string>;
  instrumentTicker$: BehaviorSubject<string>;
  entity: Indicator;
}

interface CompareManagerParams {
  chart: IChartApi;
  eventManager: EventManager;
  dataSource: DataSource;
  indicatorManager: IndicatorManager;
  paneManager: PaneManager;
  initialIndicators?: IndicatorSnapshot[];
}

export class CompareManager {
  private readonly chart: IChartApi;
  private readonly eventManager: EventManager;
  private readonly dataSource: DataSource;
  private readonly indicatorManager: IndicatorManager;
  private readonly paneManager: PaneManager;
  private readonly entries = new Map<string, CompareEntry>();
  private readonly itemsSubject = new BehaviorSubject<CompareItem[]>([]);
  private readonly entitiesSubject = new BehaviorSubject<Indicator[]>([]);
  private readonly subscriptions = new Subscription();

  private percentageComparisonActive = false;
  private restoringInitialIndicators = false;

  constructor({
    chart,
    eventManager,
    dataSource,
    indicatorManager,
    paneManager,
    initialIndicators = [],
  }: CompareManagerParams) {
    this.chart = chart;
    this.eventManager = eventManager;
    this.dataSource = dataSource;
    this.indicatorManager = indicatorManager;
    this.paneManager = paneManager;

    this.subscriptions.add(
      this.eventManager.timeframe().subscribe(() => {
        this.applyPolicy();
      }),
    );

    this.setup(initialIndicators);
  }

  public itemsObs(): Observable<CompareItem[]> {
    return this.itemsSubject.asObservable();
  }

  public entities(): Observable<Indicator[]> {
    return this.entitiesSubject.asObservable();
  }

  public clear(): void {
    const keys = Array.from(this.entries.keys());

    for (let index = 0; index < keys.length; index += 1) {
      this.removeEntry(keys[index]);
    }

    this.commitEntriesChange();
  }

  public async setSymbolMode(
    seriesType: SeriesType,
    value: string | CompareInstrument,
    mode: CompareMode,
    paneId?: number,
  ): Promise<void> {
    const instrument = typeof value === 'string' ? { symbol: value } : value;

    const symbol = normalizeSymbol(instrument.symbol);

    if (!symbol) {
      return;
    }

    const fallbackDisplayValue = getInstrumentDisplayValue(symbol);

    const instrumentName = instrument.instrumentName?.trim() || fallbackDisplayValue;
    const instrumentTicker = instrument.instrumentTicker?.trim() || fallbackDisplayValue;

    if (mode === CompareMode.NewScale && this.isNewScaleDisabled() && !this.restoringInitialIndicators) {
      return;
    }

    const key = makeKey(symbol, mode);

    if (this.entries.has(key)) {
      return;
    }

    const symbol$ = new BehaviorSubject(symbol);
    const instrumentTicker$ = new BehaviorSubject(instrumentTicker);

    const entity = this.indicatorManager.addEntity<Indicator>((zIndex, moveUp, moveDown) => {
      const usedColorsByCompare = this.entitiesSubject.value.map(
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-ignore
        (indicator) => indicator.getConfig().series?.[0]?.seriesOptions?.color,
      );

      const existingIndicators = Array.from(this.indicatorManager.getIndicators().value.values());

      const usedColorsByIndicatorsRaw = existingIndicators.map((indicator) =>
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-ignore
        indicator.config?.series?.map((series) => series.seriesOptions?.color),
      );

      const usedColorsByIndicators = flatten(usedColorsByIndicatorsRaw).filter((color) => color !== undefined);
      const usedColors = usedColorsByCompare.concat(usedColorsByIndicators);
      const config = getDefaultCompareIndicatorConfig(seriesType, symbol, instrumentName, instrumentTicker, usedColors);

      const associatedPane =
        mode === CompareMode.NewPane
          ? paneId !== undefined
            ? (this.paneManager.getPaneById(paneId) ?? this.paneManager.addPane())
            : this.paneManager.addPane()
          : this.paneManager.getMainPane();

      return new Indicator({
        id: key,
        lwcChart: this.chart,
        mainSymbol$: symbol$,
        mainInstrumentTicker$: instrumentTicker$,
        dataSource: this.dataSource,
        associatedPane,
        config: {
          ...config,
          series: [
            {
              ...config.series[0],
              seriesOptions: {
                ...config.series[0]?.seriesOptions,
                priceScaleId: mode === CompareMode.NewScale ? Direction.Left : Direction.Right,
              },
            },
          ],
          newPane: mode === CompareMode.NewPane,
        },
        zIndex,
        onDelete: () => {
          if (this.removeEntry(key)) {
            this.commitEntriesChange();
          }
        },
        moveUp,
        moveDown,
        paneId: associatedPane.getId(),
      });
    });

    this.entries.set(key, {
      key,
      symbol,
      instrumentName,
      instrumentTicker,
      mode,
      symbol$,
      instrumentTicker$,
      entity,
    });

    this.commitEntriesChange();

    await this.dataSource.isReady(symbol);
  }

  public removeSymbolMode(symbolRaw: string, mode: CompareMode): void {
    const symbol = normalizeSymbol(symbolRaw);

    if (!symbol) {
      return;
    }

    if (this.removeEntry(makeKey(symbol, mode))) {
      this.commitEntriesChange();
    }
  }

  public removeSymbol(symbolRaw: string): void {
    const symbol = normalizeSymbol(symbolRaw);

    if (!symbol) {
      return;
    }

    const entries = Array.from(this.entries.entries());
    let removed = false;

    for (let index = 0; index < entries.length; index += 1) {
      const [key, entry] = entries[index];

      if (entry.symbol !== symbol) {
        continue;
      }

      removed = this.removeEntry(key) || removed;
    }

    if (removed) {
      this.commitEntriesChange();
    }
  }

  public isNewScaleDisabled(): boolean {
    return this.itemsSubject.value.length > 0;
  }

  public isNewScaleDisabledObservable(): Observable<boolean> {
    return this.itemsSubject.pipe(
      map((items) => items.length > 0),
      distinctUntilChanged(),
    );
  }

  public getAllEntities() {
    return Array.from(this.entries.values()).map(({ symbol, instrumentName, instrumentTicker, entity, mode }) => ({
      symbol,
      instrumentName,
      instrumentTicker,
      entity,
      mode,
    }));
  }

  public destroy(): void {
    this.subscriptions.unsubscribe();
    this.clear();
    this.itemsSubject.complete();
    this.entitiesSubject.complete();
  }

  private async setup(initialIndicators: IndicatorSnapshot[]): Promise<void> {
    this.restoringInitialIndicators = true;

    try {
      for (const indicator of initialIndicators) {
        if (indicator.indicatorType !== undefined) {
          continue;
        }

        if (!indicator.config?.label) {
          continue;
        }

        const series = indicator.config.series[0];
        const symbol = indicator.config.symbol ?? indicator.config.label;

        if (!symbol) {
          continue;
        }

        const fallbackDisplayValue = getInstrumentDisplayValue(symbol);

        const instrumentName = indicator.config.instrumentName?.trim() ?? fallbackDisplayValue;
        const instrumentTicker = indicator.config.instrumentTicker?.trim() ?? fallbackDisplayValue;

        const compareMode =
          series.seriesOptions?.priceScaleId === Direction.Left
            ? CompareMode.NewScale
            : indicator.config.newPane
              ? CompareMode.NewPane
              : CompareMode.Percentage;

        // eslint-disable-next-line no-await-in-loop
        await this.setSymbolMode(
          series.name,
          {
            symbol,
            instrumentName,
            instrumentTicker,
          },
          compareMode,
          indicator.paneId,
        );
      }
    } finally {
      this.restoringInitialIndicators = false;
    }
  }

  private removeEntry(key: string): boolean {
    const entry = this.entries.get(key);

    if (!entry) {
      return false;
    }

    this.entries.delete(key);
    this.indicatorManager.removeEntity(entry.entity);
    entry.entity.destroy();
    entry.symbol$.complete();
    entry.instrumentTicker$.complete();

    return true;
  }

  private commitEntriesChange(): void {
    this.applyPolicy();
    this.publish();
  }

  private publish(): void {
    const values = Array.from(this.entries.values());
    const items: CompareItem[] = [];
    const entities: Indicator[] = [];

    for (let index = 0; index < values.length; index += 1) {
      items.push({
        symbol: values[index].symbol,
        instrumentName: values[index].instrumentName,
        instrumentTicker: values[index].instrumentTicker,
        mode: values[index].mode,
      });

      entities.push(values[index].entity);
    }

    this.itemsSubject.next(items);
    this.entitiesSubject.next(entities);
  }

  private syncPercentageMode(priceScale: PriceScale, shouldEnablePercentageMode: boolean): void {
    if (this.restoringInitialIndicators) {
      this.percentageComparisonActive = shouldEnablePercentageMode;
      return;
    }

    if (this.percentageComparisonActive === shouldEnablePercentageMode) {
      return;
    }

    this.percentageComparisonActive = shouldEnablePercentageMode;

    if (shouldEnablePercentageMode) {
      priceScale.setMode(PriceScaleMode.Percentage);
      return;
    }

    if (priceScale.getMode() === PriceScaleMode.Percentage) {
      priceScale.setMode(PriceScaleMode.Normal);
    }
  }

  private applyPolicy(): void {
    const entries = Array.from(this.entries.values());

    let percentageComparisonActive = false;
    let newScaleComparisonActive = false;

    for (let index = 0; index < entries.length; index += 1) {
      if (entries[index].mode === CompareMode.Percentage) {
        percentageComparisonActive = true;
      }

      if (entries[index].mode === CompareMode.NewScale) {
        newScaleComparisonActive = true;
      }
    }

    for (let index = 0; index < entries.length; index += 1) {
      const entry = entries[index];
      const pane = entry.entity.getPane();

      // [0 - в индикаторах compare сущности может быть только одна серия] [1 - entry]
      const series = Array.from(entry.entity.getSeriesMap().values())[0];

      if (!series) {
        continue;
      }

      series.applyOptions({
        priceScaleId: pane.isMainPane() && entry.mode === CompareMode.NewScale ? Direction.Left : Direction.Right,
      });
    }

    this.paneManager.setPriceScaleSideVisible(Direction.Left, newScaleComparisonActive);
    this.paneManager.setPriceScaleSideVisible(Direction.Right, true);

    const mainRightPriceScale = this.paneManager.getMainPane().getPriceScale(Direction.Right);

    this.syncPercentageMode(mainRightPriceScale, percentageComparisonActive);

    this.paneManager.invalidate();
  }
}

function makeKey(symbol: string, mode: CompareMode): string {
  return `${symbol}|${mode}`;
}

function getPaletteColorFromIndex(usedColors: Set<string>, startIndex: number): string {
  for (let offset = 0; offset < COMPARE_COLOR_PALETTE.length; offset += 1) {
    const color = COMPARE_COLOR_PALETTE[(startIndex + offset) % COMPARE_COLOR_PALETTE.length];

    if (!usedColors.has(normalizeColor(color))) {
      return color;
    }
  }

  return createFallbackColor(usedColors.size);
}

const getDefaultCompareIndicatorConfig = (
  seriesType: SeriesType,
  symbol: string,
  instrumentName: string,
  instrumentTicker: string,
  usedColors: string[],
): IndicatorConfig => {
  const reservedColors = new Set(usedColors.map(normalizeColor));

  return {
    symbol,
    instrumentName,
    instrumentTicker,
    newPane: true,
    label: instrumentName,
    series: [
      {
        name: 'Line', // todo: change with enum
        id: `compare-${crypto.randomUUID()}`,
        seriesOptions: {
          visible: true,
          color: getPaletteColorFromIndex(reservedColors, 0),
        },
      },
    ],
  };
};


export enum CompareMode {
  Percentage = 'PCT',
  NewScale = 'SCALE',
  NewPane = 'PANE',
}

export interface CompareInstrument {
  symbol: string;
  instrumentName?: string;
  instrumentTicker?: string;
}
export interface CompareItem extends Required<CompareInstrument> {
  mode: CompareMode;
}


import { MouseEventParams, Point, Time } from 'lightweight-charts';

import { BehaviorSubject, combineLatest, Observable, Subscription } from 'rxjs';

import { ChartMouseEvents } from '@core/ChartMouseEvents';

import { EventManager } from '@core/EventManager';
import { Indicator } from '@core/Indicator';
import { IndicatorsIds } from '@src/constants';
import { SeriesStrategies } from '@src/modules/series-strategies/SeriesFactory';
import { CompareMode, IndicatorLabel, OHLCConfig } from '@src/types';

export interface LegendParams {
  config: OHLCConfig;
  eventManager: EventManager;
  indicators: BehaviorSubject<Map<string, Indicator>>;
  subscribeChartEvent: ChartMouseEvents['subscribe'];
  mainSeries: BehaviorSubject<SeriesStrategies | null> | null;
  paneId: number;
  paneIndex: () => number;
  openIndicatorSettings: (id: IndicatorsIds, indicator: Indicator) => void;
}

export interface Ohlc {
  time: Time;
  open?: number;
  high?: number;
  low?: number;
  close?: number;
  value?: number;
  absoluteChange?: number;
  percentageChange?: number;
}

export interface CompareLegendItem {
  symbol: string;
  instrumentName: string;
  mode: CompareMode;
  value: string;
  color: string;
}

export interface LegendVM {
  vm: LegendModel;
}

export type LegendModel = {
  id: string;
  name: IndicatorLabel | string;
  isIndicator: boolean;
  values: Partial<Record<keyof Ohlc, { value: number | string | Time; color: string; name?: string }>>;
  remove?: () => void;
  settings?: () => void;
}[];

export const ohlcValuesToShowForMainSerie = [
  // 'time',
  'open',
  'high',
  'low',
  'close',
  'value',
  // 'absoluteChange',
  'percentageChange',
];

export const ohlcValuesToShowForIndicators = [
  // 'time',
  'open',
  // 'high',
  // 'low',
  // 'close',
  'value',
  // 'absoluteChange',
  // 'percentageChange'
];

export class Legend {
  private eventManager: EventManager;
  private indicators: Map<string, Indicator> = new Map();
  private config: OHLCConfig;

  private mainSeries!: SeriesStrategies;
  private mainInstrumentName = '';
  private isChartHovered = false;
  private model$ = new BehaviorSubject<LegendModel>([]);
  private tooltipVisability = new BehaviorSubject<boolean>(false);
  private tooltipPos = new BehaviorSubject<null | Point>(null);
  private paneId: number;
  private paneIndex: () => number;

  private openIndicatorSettings: (id: IndicatorsIds, indicator: Indicator) => void;
  private subscriptions = new Subscription();
  private indicatorSubscriptions = new Subscription();
  private mainSeriesSubscription = new Subscription();

  constructor({
    config,
    eventManager,
    indicators,
    subscribeChartEvent,
    mainSeries,
    paneId,
    paneIndex,
    openIndicatorSettings,
  }: LegendParams) {
    this.config = config;
    this.eventManager = eventManager;
    this.paneId = paneId;
    this.paneIndex = paneIndex;
    this.openIndicatorSettings = openIndicatorSettings;

    this.subscriptions.add(
      this.eventManager.instrumentName().subscribe((instrumentName) => {
        this.mainInstrumentName = instrumentName;
        this.updateWithLastCandle();
      }),
    );

    if (!mainSeries) {
      this.subscriptions.add(
        indicators.subscribe((value: Map<string, Indicator>) => {
          this.indicators = value;
          this.handleIndicatorSeriesDataChange();
        }),
      );
    } else {
      this.subscriptions.add(
        combineLatest([mainSeries, indicators]).subscribe(([mainSerie, inds]) => {
          if (!mainSerie) {
            return;
          }
          this.mainSeries = mainSerie;
          this.indicators = inds;
          this.handleMainSeriesChange();
          this.handleIndicatorSeriesDataChange();
        }),
      );
    }
    this.subscriptions.add(subscribeChartEvent('crosshairMove', this.handleCrosshairMove));
  }

  public subscribeCursorPosition(cb: (point: Point | null) => void) {
    this.subscriptions.add(this.tooltipPos.subscribe(cb));
  }

  public subscribeCursorVisability(cb: (isVisible: boolean) => void) {
    this.subscriptions.add(this.tooltipVisability.subscribe(cb));
  }

  private handleIndicatorSeriesDataChange = () => {
    this.indicatorSubscriptions.unsubscribe();
    this.indicatorSubscriptions = new Subscription();

    for (const [_, indicator] of this.indicators) {
      this.indicatorSubscriptions.add(indicator.subscribeDataChange(this.updateWithLastCandle));
    }

    this.updateWithLastCandle();
  };

  private handleMainSeriesChange = () => {
    this.mainSeriesSubscription.unsubscribe();
    this.mainSeriesSubscription = new Subscription();

    const handler = () => this.updateWithLastCandle();

    this.mainSeries?.subscribeDataChanged(handler);

    this.mainSeriesSubscription.add(() => this.mainSeries?.unsubscribeDataChanged(handler));
  };

  private updateWithLastCandle = () => {
    if (this.isChartHovered) return;

    const model: LegendModel = [];

    if (this.mainSeries) {
      const series = new Map();

      const serieData = this.mainSeries.getLegendData();

      Object.entries(serieData).forEach(([key, sd]) => {
        series.set(`${key}`, {
          ...sd,
        });
      });

      model.push({
        id: `main-series-${this.paneId}`,
        name: this.mainInstrumentName,
        values: series as Partial<Record<keyof Ohlc, { value: number | string | Time; color: string; name: string }>>,
        isIndicator: false,
      });
    }

    if (!this.indicators) {
      return;
    }

    for (const [_, indicator] of this.indicators) {
      const indicatorType = indicator.getType();
      const indicatorSeries = new Map();

      for (const [serieName, serie] of indicator.getSeriesMap()) {
        if (!serie.isVisible()) {
          continue;
        }

        const serieData = serie.getLegendData();
        const value = serieData.value ?? serieData.close;

        if (!value) continue;

        indicatorSeries.set(serieName, { ...value, name: indicator.getSeriesLabel(serieName) });
      }

      model.push({
        id: indicator.getId(),
        name: indicator.getLabel(),
        values: indicatorSeries as Partial<
          Record<keyof Ohlc, { value: number | string | Time; color: string; name?: string }>
        >,
        isIndicator: true,
        remove: () => indicator.delete(),
        settings:
          indicatorType && indicator.hasSettings()
            ? () => this.openIndicatorSettings(indicatorType, indicator)
            : undefined,
      });
    }

    this.model$.next(model);
  };

  private handleCrosshairMove = (param: MouseEventParams) => {
    // todo: есть одинаковый код с updateWithLastCandle
    if (param.point === undefined || !param.time || param.point.x < 0 || param.point.y < 0) {
      this.tooltipVisability.next(false);

      this.isChartHovered = false;
      this.updateWithLastCandle();
      return;
    }

    if (this.paneIndex() === param.paneIndex) {
      this.tooltipVisability.next(true);
    } else {
      this.tooltipVisability.next(false);
    }

    this.isChartHovered = true;

    const model: LegendModel = [];

    if (this.mainSeries) {
      const series = new Map();
      const serieData = this.mainSeries.getLegendData(param);

      Object.entries(serieData).forEach(([key, sd]) => {
        series.set(`${key}`, {
          ...sd,
        });
      });

      model.push({
        id: `main-series-${this.paneId}`,
        name: this.mainInstrumentName,
        values: series as Partial<Record<keyof Ohlc, { value: number | string | Time; color: string; name: string }>>,
        isIndicator: false,
      });
    }

    if (!this.indicators) {
      return;
    }

    for (const [_, indicator] of this.indicators) {
      const indicatorType = indicator.getType();
      const indicatorSeries = new Map();

      for (const [serieName, serie] of indicator.getSeriesMap()) {
        if (!serie.isVisible()) {
          continue;
        }

        const serieData = serie.getLegendData(param);
        const value = serieData.value ?? serieData.close;

        if (!value) continue;

        indicatorSeries.set(serieName, { ...value, name: indicator.getSeriesLabel(serieName) });
      }

      model.push({
        id: indicator.getId(),
        name: indicator.getLabel(),
        values: indicatorSeries as Partial<
          Record<keyof Ohlc, { value: number | string | Time; color: string; name?: string }>
        >,
        isIndicator: true,
        remove: () => indicator.delete(),
        settings:
          indicatorType && indicator.hasSettings()
            ? () => this.openIndicatorSettings(indicatorType, indicator)
            : undefined,
      });
    }

    this.model$.next(model);
    this.tooltipPos.next(param.point);
  };

  public getConfig(): OHLCConfig {
    return this.config;
  }

  public getLegendViewModel(): Observable<LegendModel> {
    return this.model$;
  }

  public destroy = () => {
    this.subscriptions.unsubscribe();
    this.indicatorSubscriptions.unsubscribe();
    this.mainSeriesSubscription.unsubscribe();

    this.model$.complete();
    this.tooltipVisability.complete();
    this.tooltipPos.complete();
  };
}

import { MismatchDirection, PriceScaleMode } from 'lightweight-charts';

import { Subscription } from 'rxjs';

import { Indicator } from '@core/Indicator';
import { IndicatorsIds, MAIN_PANE_INDEX } from '@src/constants';
import { SeriesStrategies } from '@src/modules/series-strategies/SeriesFactory';
import { getThemeStore } from '@src/theme';
import { Direction } from '@src/types';
import { formatCompactNumber, formatPercent, formatPrice } from '@src/utils';
import { removeAlphaFromHex } from '@src/utils/removeAlphaFromHex';

import { PriceAxisLabelsPrimitive } from './PriceAxisLabelsPrimitive';
import { getAxisSideBySeries, getContrastTextColor } from './utils';

import type { PriceAxisLabel } from './types';

import type { IPriceLine, LogicalRange } from 'lightweight-charts';
import type { Observable } from 'rxjs';

type EntityCollection = 'compare' | 'indicator';
type SourceRole = 'main' | 'compare' | 'indicator' | 'volume';
type PriceAxisSide = Direction.Left | Direction.Right;

interface PriceAxisLabelsParams {
  mainSeries$: Observable<SeriesStrategies | null>;
  mainInstrumentTicker$: Observable<string>;
  compareEntities$: Observable<Indicator[]>;
  indicatorEntities$: Observable<Indicator[]>;
}

interface PriceLabelSource {
  id: string;
  role: SourceRole;
  series: SeriesStrategies;
  priority: number;
}

interface SourceDefaults {
  lastValueVisible: boolean;
  priceLineVisible: boolean;
  title: string;
}

interface AxisLabelsGroup {
  paneIndex: number;
  side: PriceAxisSide;
  labels: PriceAxisLabel[];
  reservedCoordinate: number | null;
}

interface AxisLayer {
  host: SeriesStrategies;
  primitive: PriceAxisLabelsPrimitive;
}

interface EntitySubscription {
  entity: Indicator;
  subscription: Subscription;
}

const SOURCE_PRIORITY: Record<SourceRole, number> = {
  main: 100,
  compare: 80,
  indicator: 60,
  volume: 40,
};

function getDataPrice(data: unknown): number | null {
  if (!data || typeof data !== 'object') {
    return null;
  }

  if ('close' in data && typeof data.close === 'number') {
    return data.close;
  }

  if ('value' in data && typeof data.value === 'number') {
    return data.value;
  }

  return null;
}

function getSeriesColor(series: SeriesStrategies, data: unknown): string {
  if (data && typeof data === 'object' && 'color' in data && typeof data.color === 'string') {
    return removeAlphaFromHex(data.color);
  }

  const options = series.options();

  if (
    data &&
    typeof data === 'object' &&
    'open' in data &&
    'close' in data &&
    typeof data.open === 'number' &&
    typeof data.close === 'number'
  ) {
    if (data.close >= data.open && 'upColor' in options && typeof options.upColor === 'string') {
      return removeAlphaFromHex(options.upColor);
    }

    if (data.close < data.open && 'downColor' in options && typeof options.downColor === 'string') {
      return removeAlphaFromHex(options.downColor);
    }
  }

  if ('color' in options && typeof options.color === 'string') {
    return removeAlphaFromHex(options.color);
  }

  if ('lineColor' in options && typeof options.lineColor === 'string') {
    return removeAlphaFromHex(options.lineColor);
  }

  if ('topLineColor' in options && typeof options.topLineColor === 'string') {
    return removeAlphaFromHex(options.topLineColor);
  }

  if ('bottomLineColor' in options && typeof options.bottomLineColor === 'string') {
    return removeAlphaFromHex(options.bottomLineColor);
  }

  return removeAlphaFromHex(getThemeStore().colors.chartLineColor);
}

function getAxisSide(source: PriceLabelSource): PriceAxisSide {
  if (source.role === 'volume') {
    return Direction.Right;
  }

  return getAxisSideBySeries(source.series);
}

export class PriceAxisLabels {
  private subscriptions = new Subscription();
  private entitySubscriptions = new Map<string, EntitySubscription>();
  private sourceDefaults = new WeakMap<SeriesStrategies, SourceDefaults>();
  private layers = new Map<string, AxisLayer>();

  private mainSeries: SeriesStrategies | null = null;
  private mainSeriesDataHandler: (() => void) | null = null;
  private compareEntities: Indicator[] = [];
  private indicatorEntities: Indicator[] = [];
  private visibleLogicalRange: LogicalRange | null = null;
  private currentPriceLine: IPriceLine | null = null;
  private currentPriceLineHost: SeriesStrategies | null = null;
  private mainInstrumentTicker = '';
  private isHistoryMode = false;
  private updateFrame: number | null = null;

  constructor({ mainSeries$, mainInstrumentTicker$, compareEntities$, indicatorEntities$ }: PriceAxisLabelsParams) {
    this.subscriptions.add(
      mainInstrumentTicker$.subscribe((instrumentTicker) => {
        this.mainInstrumentTicker = instrumentTicker;

        this.applyDisplayMode();
        this.scheduleUpdate();
      }),
    );

    this.subscriptions.add(
      mainSeries$.subscribe((series) => {
        this.setMainSeries(series);
      }),
    );

    this.subscriptions.add(
      compareEntities$.subscribe((entities) => {
        this.setEntities('compare', entities);
      }),
    );

    this.subscriptions.add(
      indicatorEntities$.subscribe((entities) => {
        this.setEntities('indicator', entities);
      }),
    );
  }

  public setVisibleLogicalRange(logicalRange: LogicalRange | null): void {
    this.visibleLogicalRange = logicalRange;

    this.refreshHistoryMode();
    this.scheduleUpdate();
  }

  public invalidate(): void {
    this.scheduleUpdate();
  }

  public destroy(): void {
    if (this.updateFrame !== null) {
      cancelAnimationFrame(this.updateFrame);
      this.updateFrame = null;
    }

    this.unsubscribeMainSeries();
    this.subscriptions.unsubscribe();

    this.entitySubscriptions.forEach(({ subscription }) => {
      subscription.unsubscribe();
    });

    this.getSources().forEach(({ series }) => {
      this.restoreSourceOptions(series);
    });

    this.layers.forEach(({ host, primitive }) => {
      try {
        host.detachPrimitive(primitive);
      } catch {
        // Серия могла быть удалена раньше объекта PriceAxisLabels.
      }
    });

    this.entitySubscriptions.clear();
    this.layers.clear();
    this.removeCurrentPriceLine();
  }

  private setMainSeries(series: SeriesStrategies | null): void {
    if (this.mainSeries === series) {
      return;
    }

    const previousSeries = this.mainSeries;

    this.unsubscribeMainSeries();

    if (previousSeries) {
      this.restoreSourceOptions(previousSeries);
    }

    this.mainSeries = series;

    if (series) {
      this.ensureSourceDefaults(series);

      this.mainSeriesDataHandler = () => {
        this.refreshHistoryMode();
        this.scheduleUpdate();
      };

      series.subscribeDataChanged(this.mainSeriesDataHandler);
    }

    if (this.currentPriceLineHost && this.currentPriceLineHost !== series) {
      this.removeCurrentPriceLine();
    }

    this.refreshHistoryMode();
    this.applyDisplayMode();
    this.scheduleUpdate();
  }

  private unsubscribeMainSeries(): void {
    if (!this.mainSeries || !this.mainSeriesDataHandler) {
      this.mainSeriesDataHandler = null;
      return;
    }

    try {
      this.mainSeries.unsubscribeDataChanged(this.mainSeriesDataHandler);
    } catch {
      // Серия могла быть удалена раньше объекта PriceAxisLabels.
    }

    this.mainSeriesDataHandler = null;
  }

  private setEntities(collection: EntityCollection, entities: Indicator[]): void {
    if (collection === 'compare') {
      this.compareEntities = entities;
    } else {
      this.indicatorEntities = entities;
    }

    const activeKeys = new Set(entities.map((entity) => `${collection}:${entity.getId()}`));

    this.entitySubscriptions.forEach((entry, key) => {
      if (!key.startsWith(`${collection}:`) || activeKeys.has(key)) {
        return;
      }

      entry.entity.getSeriesMap().forEach((series) => {
        this.restoreSourceOptions(series);
      });

      entry.subscription.unsubscribe();
      this.entitySubscriptions.delete(key);
    });

    entities.forEach((entity) => {
      const key = `${collection}:${entity.getId()}`;
      const current = this.entitySubscriptions.get(key);

      if (current?.entity === entity) {
        return;
      }

      if (current) {
        current.entity.getSeriesMap().forEach((series) => {
          this.restoreSourceOptions(series);
        });

        current.subscription.unsubscribe();
      }

      const subscription = entity.subscribeDataChange(() => {
        this.applyDisplayModeToSources(this.getEntitySources(collection, entity));

        this.scheduleUpdate();
      });

      this.entitySubscriptions.set(key, {
        entity,
        subscription,
      });

      this.applyDisplayModeToSources(this.getEntitySources(collection, entity));
    });

    this.applyDisplayMode();
    this.scheduleUpdate();
  }

  private getSources(): PriceLabelSource[] {
    const sources: PriceLabelSource[] = [];

    if (this.mainSeries) {
      sources.push({
        id: 'main',
        role: 'main',
        series: this.mainSeries,
        priority: SOURCE_PRIORITY.main,
      });
    }

    this.compareEntities.forEach((entity) => {
      sources.push(...this.getEntitySources('compare', entity));
    });

    this.indicatorEntities.forEach((entity) => {
      sources.push(...this.getEntitySources('indicator', entity));
    });

    return sources;
  }

  private getEntitySources(collection: EntityCollection, entity: Indicator): PriceLabelSource[] {
    let role: SourceRole = 'indicator';

    if (collection === 'compare') {
      role = 'compare';
    } else if (entity.getType() === IndicatorsIds.Volume) {
      role = 'volume';
    }

    return Array.from(entity.getSeriesMap().entries(), ([seriesId, series]) => ({
      id: `${collection}:${entity.getId()}:${seriesId}`,
      role,
      series,
      priority: SOURCE_PRIORITY[role],
    }));
  }

  private ensureSourceDefaults(series: SeriesStrategies): SourceDefaults {
    const savedDefaults = this.sourceDefaults.get(series);

    if (savedDefaults) {
      return savedDefaults;
    }

    const options = series.options();

    const defaults = {
      lastValueVisible: options.lastValueVisible,
      priceLineVisible: options.priceLineVisible,
      title: options.title ?? '',
    };

    this.sourceDefaults.set(series, defaults);

    return defaults;
  }

  private restoreSourceOptions(series: SeriesStrategies): void {
    const defaults = this.sourceDefaults.get(series);

    if (!defaults) {
      return;
    }

    try {
      series.applyOptions(defaults);
    } catch {
      // Серия могла быть удалена раньше объекта PriceAxisLabels.
    }
  }

  private applyDisplayMode(): void {
    this.applyDisplayModeToSources(this.getSources());

    if (!this.isHistoryMode) {
      this.hideCurrentPriceLine();
    }
  }

  private applyDisplayModeToSources(sources: PriceLabelSource[]): void {
    sources.forEach((source) => {
      const defaults = this.ensureSourceDefaults(source.series);

      try {
        if (source.role === 'volume') {
          source.series.applyOptions({
            lastValueVisible: false,
            priceLineVisible: false,
          });

          return;
        }

        if (source.role === 'main') {
          source.series.applyOptions({
            lastValueVisible: this.isHistoryMode ? false : defaults.lastValueVisible,
            title: this.isHistoryMode ? '' : this.mainInstrumentTicker || defaults.title,
          });

          return;
        }

        source.series.applyOptions({
          lastValueVisible: this.isHistoryMode ? false : defaults.lastValueVisible,
        });
      } catch {
        // Серия могла быть удалена раньше объекта PriceAxisLabels.
      }
    });
  }

  private refreshHistoryMode(): void {
    const barsInfo =
      this.visibleLogicalRange && this.mainSeries ? this.mainSeries.barsInLogicalRange(this.visibleLogicalRange) : null;

    const nextHistoryMode = (barsInfo?.barsAfter ?? 0) > 0;

    if (nextHistoryMode === this.isHistoryMode) {
      return;
    }

    this.isHistoryMode = nextHistoryMode;
    this.applyDisplayMode();
  }

  private scheduleUpdate(): void {
    if (this.updateFrame !== null) {
      return;
    }

    this.updateFrame = requestAnimationFrame(() => {
      this.updateFrame = null;
      this.update();
    });
  }

  private update(): void {
    const sources = this.getSources();

    this.updateCurrentPriceLine(sources);
    this.updateAxisLayers(this.collectAxisGroups(sources), sources);
  }

  private collectAxisGroups(sources: PriceLabelSource[]): Map<string, AxisLabelsGroup> {
    const groups = new Map<string, AxisLabelsGroup>();

    sources.forEach((source) => {
      if (!source.series.isVisible() || (source.role !== 'volume' && !this.isHistoryMode)) {
        return;
      }

      const label = this.createLabel(source);

      if (!label) {
        return;
      }

      const paneIndex = source.series.getPane().paneIndex();

      const side = getAxisSide(source);
      const key = `${paneIndex}:${side}`;
      const group = groups.get(key);

      if (group) {
        group.labels.push(label);
        return;
      }

      groups.set(key, {
        paneIndex,
        side,
        labels: [label],
        reservedCoordinate: null,
      });
    });

    const mainSource = sources.find((source) => source.role === 'main');

    if (!mainSource) {
      return groups;
    }

    const showRealtimeLabel = this.isHistoryMode || this.ensureSourceDefaults(mainSource.series).lastValueVisible;

    if (!showRealtimeLabel) {
      return groups;
    }

    const reservedCoordinate = this.getCurrentMainPriceCoordinate();

    if (reservedCoordinate === null) {
      return groups;
    }

    const paneIndex = mainSource.series.getPane().paneIndex();

    const side = getAxisSide(mainSource);
    const group = groups.get(`${paneIndex}:${side}`);

    if (group) {
      group.reservedCoordinate = reservedCoordinate;
    }

    return groups;
  }

  private createLabel(source: PriceLabelSource): PriceAxisLabel | null {
    const data = this.getSourceData(source);
    const price = getDataPrice(data);

    if (price === null) {
      return null;
    }

    const coordinate = source.series.priceToCoordinate(price);

    if (coordinate === null) {
      return null;
    }

    return {
      id: source.id,
      desiredCoordinate: coordinate,
      text: source.role === 'volume' ? formatCompactNumber(price) : this.formatValue(source.series, price),
      color: getSeriesColor(source.series, data),
      style: this.isHistoryMode ? 'outlined' : 'filled',
      priority: source.priority,
    };
  }

  private getSourceData(source: PriceLabelSource): unknown {
    if (this.isHistoryMode && this.visibleLogicalRange) {
      return source.series.dataByIndex(Math.floor(this.visibleLogicalRange.to), MismatchDirection.NearestLeft);
    }

    const data = source.series.data();

    return data[data.length - 1] ?? null;
  }

  private updateAxisLayers(groups: Map<string, AxisLabelsGroup>, sources: PriceLabelSource[]): void {
    const activeKeys = new Set<string>();

    groups.forEach((group, key) => {
      const host = this.getAxisHost(group.paneIndex, group.side, sources);

      if (!host) {
        return;
      }

      activeKeys.add(key);

      this.getOrCreateLayer(key, host).primitive.setLabels(group.labels, group.reservedCoordinate);
    });

    this.layers.forEach((layer, key) => {
      if (activeKeys.has(key)) {
        return;
      }

      try {
        layer.host.detachPrimitive(layer.primitive);
      } catch {
        // Серия могла быть удалена раньше объекта PriceAxisLabels.
      }

      this.layers.delete(key);
    });
  }

  private getAxisHost(paneIndex: number, side: PriceAxisSide, sources: PriceLabelSource[]): SeriesStrategies | null {
    if (paneIndex === MAIN_PANE_INDEX && side === Direction.Right && this.mainSeries) {
      return this.mainSeries;
    }

    const regularSource = sources.find(
      (source) =>
        source.role !== 'volume' && source.series.getPane().paneIndex() === paneIndex && getAxisSide(source) === side,
    );

    if (regularSource) {
      return regularSource.series;
    }

    return (
      sources.find((source) => source.series.getPane().paneIndex() === paneIndex && getAxisSide(source) === side)
        ?.series ?? null
    );
  }

  private getOrCreateLayer(key: string, host: SeriesStrategies): AxisLayer {
    const currentLayer = this.layers.get(key);

    if (currentLayer?.host === host) {
      return currentLayer;
    }

    if (currentLayer) {
      try {
        currentLayer.host.detachPrimitive(currentLayer.primitive);
      } catch {
        // Серия могла быть удалена раньше объекта PriceAxisLabels.
      }
    }

    const layer = {
      host,
      primitive: new PriceAxisLabelsPrimitive(),
    };

    host.attachPrimitive(layer.primitive);
    this.layers.set(key, layer);

    return layer;
  }

  private updateCurrentPriceLine(sources: PriceLabelSource[]): void {
    const mainSource = sources.find((source) => source.role === 'main');

    if (!this.isHistoryMode || !mainSource || !mainSource.series.isVisible()) {
      this.hideCurrentPriceLine();
      return;
    }

    const data = mainSource.series.data();
    const lastData = data[data.length - 1];
    const price = getDataPrice(lastData);

    if (price === null) {
      this.hideCurrentPriceLine();
      return;
    }

    const color = getSeriesColor(mainSource.series, lastData);

    this.getCurrentPriceLine(mainSource.series, color).applyOptions({
      price,
      color,
      lineVisible: false,
      axisLabelVisible: true,
      axisLabelColor: color,
      axisLabelTextColor: getContrastTextColor(color),
      title: this.mainInstrumentTicker,
    });
  }

  private getCurrentMainPriceCoordinate(): number | null {
    if (!this.mainSeries) {
      return null;
    }

    const data = this.mainSeries.data();
    const price = getDataPrice(data[data.length - 1]);

    return price === null ? null : this.mainSeries.priceToCoordinate(price);
  }

  private getCurrentPriceLine(series: SeriesStrategies, color: string): IPriceLine {
    if (this.currentPriceLine && this.currentPriceLineHost === series) {
      return this.currentPriceLine;
    }

    this.removeCurrentPriceLine();

    this.currentPriceLine = series.createPriceLine({
      price: 0,
      color,
      lineVisible: false,
      axisLabelVisible: false,
      title: '',
    });

    this.currentPriceLineHost = series;

    return this.currentPriceLine;
  }

  private hideCurrentPriceLine(): void {
    this.currentPriceLine?.applyOptions({
      lineVisible: false,
      axisLabelVisible: false,
      title: '',
    });
  }

  private removeCurrentPriceLine(): void {
    if (this.currentPriceLine && this.currentPriceLineHost) {
      try {
        this.currentPriceLineHost.removePriceLine(this.currentPriceLine);
      } catch {
        // Серия могла быть удалена раньше объекта PriceAxisLabels.
      }
    }

    this.currentPriceLine = null;
    this.currentPriceLineHost = null;
  }

  private formatValue(series: SeriesStrategies, price: number): string {
    const { mode } = series.priceScale().options();

    const formattedPrice = formatPrice(price) ?? series.priceFormatter().format(price);

    if (mode !== PriceScaleMode.Percentage && mode !== PriceScaleMode.IndexedTo100) {
      return formattedPrice;
    }

    if (!this.visibleLogicalRange) {
      return formattedPrice;
    }

    const firstVisiblePrice = getDataPrice(
      series.dataByIndex(Math.ceil(this.visibleLogicalRange.from), MismatchDirection.NearestRight),
    );

    if (firstVisiblePrice === null || firstVisiblePrice === 0) {
      return formattedPrice;
    }

    if (mode === PriceScaleMode.Percentage) {
      return formatPercent(((price - firstVisiblePrice) / firstVisiblePrice) * 100);
    }

    const indexedValue = (price / firstVisiblePrice) * 100;

    return formatPrice(indexedValue) ?? String(indexedValue);
  }
}