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


import { IPaneApi, IPriceScaleApi, PriceScaleMode, Time } from 'lightweight-charts';

import type { PriceScaleSide, PriceScaleSnapshot } from '@src/types/snapshot';

interface PriceScaleParams {
  paneId: number;
  side: PriceScaleSide;
  pane: IPaneApi<Time>;
  initialMode?: PriceScaleMode;
  initialVisible: boolean;
  hasVisibleSeriesData: () => boolean;
}

export class PriceScale {
  public readonly paneId: number;
  public readonly side: PriceScaleSide;

  private readonly pane: IPaneApi<Time>;
  private readonly hasVisibleSeriesDataCallback: () => boolean;

  private mode: PriceScaleMode;
  private autoScaleEnabled: boolean;
  private visible: boolean;

  constructor({
    paneId,
    side,
    pane,
    initialMode = PriceScaleMode.Normal,
    initialVisible,
    hasVisibleSeriesData,
  }: PriceScaleParams) {
    this.paneId = paneId;
    this.side = side;
    this.pane = pane;
    this.mode = initialMode;
    this.visible = initialVisible;
    this.hasVisibleSeriesDataCallback = hasVisibleSeriesData;

    const priceScale = this.getPriceScaleApi();

    this.autoScaleEnabled = priceScale.options().autoScale ?? true;

    priceScale.applyOptions({
      mode: this.mode,
      autoScale: this.autoScaleEnabled,
      visible: this.visible,
      borderVisible: false,
    });
  }

  public getMode(): PriceScaleMode {
    return this.mode;
  }

  public setMode(mode: PriceScaleMode): void {
    if (this.mode === mode) {
      return;
    }

    this.mode = mode;

    this.getPriceScaleApi().applyOptions({
      mode,
      autoScale: this.autoScaleEnabled,
    });
  }

  public toggleLogarithmic(): void {
    const nextMode =
      this.mode === PriceScaleMode.Logarithmic
        ? PriceScaleMode.Normal
        : PriceScaleMode.Logarithmic;

    this.setMode(nextMode);
  }

  public isAutoScaleEnabled(): boolean {
    return this.autoScaleEnabled;
  }

  public toggleAutoScale(): void {
    this.autoScaleEnabled = !this.autoScaleEnabled;

    this.getPriceScaleApi().setAutoScale(this.autoScaleEnabled);
  }

  public enableAutoScale(): void {
    if (this.autoScaleEnabled) {
      return;
    }

    this.autoScaleEnabled = true;
    this.getPriceScaleApi().setAutoScale(true);
  }

  public isVisible(): boolean {
    return this.visible;
  }

  public setVisible(visible: boolean): void {
    if (this.visible === visible) {
      return;
    }

    this.visible = visible;

    this.getPriceScaleApi().applyOptions({
      visible,
      borderVisible: false,
    });
  }

  public hasVisibleSeriesData(): boolean {
    return this.hasVisibleSeriesDataCallback();
  }

  public getSnapshot(): PriceScaleSnapshot {
    return {
      side: this.side,
      mode: this.mode,
    };
  }

  private getPriceScaleApi(): IPriceScaleApi {
    return this.pane.priceScale(this.side);
  }
}



import { PriceScaleMode } from 'lightweight-charts';

import { PriceScaleControls as PriceScaleControlsView } from '@components/PriceScaleControls';
import { ReactRenderer } from '@core/ReactRenderer';
import { Direction } from '@src/types';

import { PriceScale } from './PriceScale';

interface PriceScaleControlsParams {
  leftPriceScale: PriceScale;
  rightPriceScale: PriceScale;
  onPriceScaleChange: () => void;
}

export class PriceScaleControls {
  private readonly leftPriceScale: PriceScale;
  private readonly rightPriceScale: PriceScale;
  private readonly onPriceScaleChange: () => void;
  private readonly container: HTMLElement;
  private readonly renderer: ReactRenderer;

  private paneElement: HTMLElement | null = null;
  private hoveredPriceScale: PriceScale | null = null;

  constructor({
    leftPriceScale,
    rightPriceScale,
    onPriceScaleChange,
  }: PriceScaleControlsParams) {
    this.leftPriceScale = leftPriceScale;
    this.rightPriceScale = rightPriceScale;
    this.onPriceScaleChange = onPriceScaleChange;

    this.container = document.createElement('div');
    this.container.className = 'moex-price-scale-controls';
    this.container.style.position = 'absolute';
    this.container.style.inset = '0';
    this.container.style.display = 'flex';
    this.container.style.alignItems = 'center';
    this.container.style.justifyContent = 'center';
    this.container.style.zIndex = '10';
    this.container.style.pointerEvents = 'none';

    this.renderer = new ReactRenderer(this.container);
  }

  public mount(paneElement: HTMLElement): void {
    if (this.paneElement === paneElement) {
      this.refresh();
      return;
    }

    this.unmount();

    this.paneElement = paneElement;
    this.paneElement.addEventListener('pointermove', this.handlePointerMove);
    this.paneElement.addEventListener('pointerleave', this.handlePointerLeave);

    this.refresh();
  }

  public refresh(): void {
    if (!this.hoveredPriceScale) {
      this.hide();
      return;
    }

    this.render(this.hoveredPriceScale);
  }

  public destroy(): void {
    this.unmount();
    this.renderer.destroy();
  }

  private handlePointerMove = (event: PointerEvent): void => {
    const nextPriceScale = this.getHoveredPriceScale(event.clientX);

    if (this.hoveredPriceScale === nextPriceScale) {
      return;
    }

    this.hoveredPriceScale = nextPriceScale;
    this.refresh();
  };

  private handlePointerLeave = (): void => {
    this.hoveredPriceScale = null;
    this.refresh();
  };

  private render(priceScale: PriceScale): void {
    const priceScaleElement = this.getPriceScaleElement(priceScale);

    if (!priceScaleElement || !this.canShowControls(priceScale, priceScaleElement)) {
      this.hide();
      return;
    }

    priceScaleElement.style.position = 'relative';

    if (this.container.parentElement !== priceScaleElement) {
      priceScaleElement.appendChild(this.container);
    }

    this.renderer.renderComponent(
      <PriceScaleControlsView
        isAutoScale={priceScale.isAutoScaleEnabled()}
        isLogarithmic={priceScale.getMode() === PriceScaleMode.Logarithmic}
        onToggleAutoScale={() => {
          priceScale.toggleAutoScale();
          this.refresh();
          this.onPriceScaleChange();
        }}
        onToggleLogarithmic={() => {
          priceScale.toggleLogarithmic();
          this.refresh();
          this.onPriceScaleChange();
        }}
      />,
    );

    this.container.classList.add('moex-price-scale-controls_visible');
  }

  private hide(): void {
    this.container.classList.remove('moex-price-scale-controls_visible');
  }

  private getHoveredPriceScale(clientX: number): PriceScale | null {
    if (this.isPointerInsidePriceScale(this.leftPriceScale, clientX)) {
      return this.leftPriceScale;
    }

    if (this.isPointerInsidePriceScale(this.rightPriceScale, clientX)) {
      return this.rightPriceScale;
    }

    return null;
  }

  private isPointerInsidePriceScale(priceScale: PriceScale, clientX: number): boolean {
    const priceScaleElement = this.getPriceScaleElement(priceScale);

    if (!priceScaleElement || !this.canShowControls(priceScale, priceScaleElement)) {
      return false;
    }

    const rect = priceScaleElement.getBoundingClientRect();

    return clientX >= rect.left && clientX <= rect.right;
  }

  private canShowControls(priceScale: PriceScale, priceScaleElement: HTMLElement): boolean {
    return (
      priceScale.isVisible() &&
      priceScale.hasVisibleSeriesData() &&
      priceScaleElement.getBoundingClientRect().width > 0
    );
  }

  private getPriceScaleElement(priceScale: PriceScale): HTMLElement | null {
    if (!this.paneElement) {
      return null;
    }

    const element =
      priceScale.side === Direction.Left
        ? this.paneElement.firstElementChild
        : this.paneElement.lastElementChild;

    return element instanceof HTMLElement ? element : null;
  }

  private unmount(): void {
    if (this.paneElement) {
      this.paneElement.removeEventListener('pointermove', this.handlePointerMove);
      this.paneElement.removeEventListener('pointerleave', this.handlePointerLeave);
    }

    this.paneElement = null;
    this.hoveredPriceScale = null;
    this.container.remove();
    this.hide();
  }
}



import { DataSource } from '@core/DataSource';
import { DrawingsManager, DrawingsManagerSnapshot } from '@core/DrawingsManager';
import { Pane, PaneParams } from '@core/Pane';
import { PriceAxisLabels } from '@core/PriceAxisLabels';
import { Direction } from '@src/types';
import {
  ISerializable,
  PaneSnapshot,
  PriceScaleSide,
  PriceScaleSnapshot,
} from '@src/types/snapshot';

import type { Indicator } from '@core/Indicator';
import type { LogicalRange } from 'lightweight-charts';
import type { Observable } from 'rxjs';

interface PaneManagerParams
  extends Omit<
    PaneParams,
    | 'id'
    | 'isMainPane'
    | 'basedOn'
    | 'onDelete'
    | 'initialPriceScales'
    | 'onPriceScaleStateChange'
    | 'leftPriceScaleVisible'
    | 'rightPriceScaleVisible'
  > {
  panesSnapshot: PaneSnapshot[];
}

interface PriceAxisLabelsSources {
  compareEntities$: Observable<Indicator[]>;
  indicatorEntities$: Observable<Indicator[]>;
}

type SharedPaneParams = Omit<PaneManagerParams, 'panesSnapshot'>;

// todo: PaneManager, регулирует порядок пейнов. Знает про MainPane.
// todo: Также перекинуть соответствующие/необходимые свойства из чарта, и из чарта удалить
// todo: в CompareManage, при создании нового пейна для сравнения - инициализируем новый dataSource, принадлежащий только конкретному пейну. Убираем возможность добавлять индикаторы на такие пейны
// todo: на каждый символ свой DataSource (учитывать что есть MainPane и "главный" DataSource, который инициализиурется во время старта moexChart)
// todo: сделать два разных представления для compare, в зависимости от отображения на главном пейне или на второстепенном

export class PaneManager implements ISerializable<PaneSnapshot[]> {
  private readonly sharedPaneParams: SharedPaneParams;
  private readonly panesMap = new Map<number, Pane>();

  private mainPane: Pane;
  private nextPaneId: number;
  private priceAxisLabels: PriceAxisLabels | null = null;
  private leftPriceScaleVisible = false;
  private rightPriceScaleVisible = true;

  constructor({ panesSnapshot, ...sharedPaneParams }: PaneManagerParams) {
    this.sharedPaneParams = sharedPaneParams;

    const mainPaneSnapshot = panesSnapshot.find((paneSnapshot) => paneSnapshot.isMain);
    const mainPaneId = mainPaneSnapshot?.id ?? 0;

    this.mainPane = new Pane({
      ...this.sharedPaneParams,
      id: mainPaneId,
      isMainPane: true,
      onDelete: () => {},
      initialPriceScales: mainPaneSnapshot?.priceScales,
      onPriceScaleStateChange: this.handlePriceScaleStateChange,
      leftPriceScaleVisible: this.leftPriceScaleVisible,
      rightPriceScaleVisible: this.rightPriceScaleVisible,
    });

    this.panesMap.set(mainPaneId, this.mainPane);

    if (mainPaneSnapshot) {
      this.mainPane.setDrawingsSnapshot(mainPaneSnapshot.drawings);
    }

    const greatestPaneId = panesSnapshot.reduce(
      (greatestId, paneSnapshot) => Math.max(greatestId, paneSnapshot.id),
      mainPaneId,
    );

    this.nextPaneId = greatestPaneId + 1;

    panesSnapshot.forEach((paneSnapshot) => {
      if (paneSnapshot.isMain) {
        return;
      }

      const pane = this.addPane(undefined, paneSnapshot.id, paneSnapshot.priceScales);

      pane.setDrawingsSnapshot(paneSnapshot.drawings);
    });

    this.syncPaneContainers();
  }

  public initializePriceAxisLabels({
    compareEntities$,
    indicatorEntities$,
  }: PriceAxisLabelsSources): void {
    this.priceAxisLabels?.destroy();

    this.priceAxisLabels = new PriceAxisLabels({
      mainSeries$: this.mainPane.getMainSerie().asObservable(),
      mainSymbol$: this.sharedPaneParams.eventManager.symbol(),
      compareEntities$,
      indicatorEntities$,
    });
  }

  public setVisibleLogicalRange(logicalRange: LogicalRange | null): void {
    this.priceAxisLabels?.setVisibleLogicalRange(logicalRange);
  }

  public invalidatePriceAxisLabels(): void {
    this.priceAxisLabels?.invalidate();
  }

  public setPriceScaleSideVisible(side: PriceScaleSide, visible: boolean): void {
    if (side === Direction.Left) {
      this.leftPriceScaleVisible = visible;
    } else {
      this.rightPriceScaleVisible = visible;
    }

    this.panesMap.forEach((pane) => {
      pane.getPriceScale(side).setVisible(visible);
    });
  }

  public getPaneById(id: number): Pane | undefined {
    return this.panesMap.get(id);
  }

  public getDrawingsSnapshot(): DrawingsManagerSnapshot {
    return this.mainPane.getDrawingsSnapshot();
  }

  public setDrawingsSnapshot(snapshot: DrawingsManagerSnapshot): void {
    this.mainPane.setDrawingsSnapshot(snapshot);
  }

  public getPanes(): Map<number, Pane> {
    return this.panesMap;
  }

  public getMainPane = (): Pane => {
    return this.mainPane;
  };

  public addPane(
    dataSource?: DataSource,
    paneId?: number,
    initialPriceScales?: PriceScaleSnapshot[],
  ): Pane {
    const id = paneId ?? this.nextPaneId++;

    this.nextPaneId = Math.max(this.nextPaneId, id + 1);

    const pane = new Pane({
      ...this.sharedPaneParams,
      id,
      isMainPane: false,
      dataSource: dataSource ?? null,
      basedOn: dataSource ? undefined : this.mainPane,
      onDelete: () => this.destroyPane(id),
      initialPriceScales,
      onPriceScaleStateChange: this.handlePriceScaleStateChange,
      leftPriceScaleVisible: this.leftPriceScaleVisible,
      rightPriceScaleVisible: this.rightPriceScaleVisible,
    });

    this.panesMap.set(id, pane);
    this.syncPaneContainers();
    this.priceAxisLabels?.invalidate();

    return pane;
  }

  public refreshPriceScaleControls(): void {
    this.panesMap.forEach((pane) => {
      pane.refreshPriceScaleControls();
    });
  }

  public resetPriceScalesAutoScale(): void {
    this.panesMap.forEach((pane) => {
      pane.resetPriceScalesAutoScale();
    });
  }

  public getDrawingsManager(): DrawingsManager {
    // todo: temp
    return this.mainPane.getDrawingManager();
  }

  public getSnapshot(): PaneSnapshot[] {
    const snapshot: PaneSnapshot[] = [];

    this.panesMap.forEach((pane) => {
      snapshot.push(pane.getSnapshot());
    });

    return snapshot;
  }

  public destroy(): void {
    this.priceAxisLabels?.destroy();
    this.priceAxisLabels = null;

    this.panesMap.forEach((pane) => {
      pane.destroy();
    });

    this.panesMap.clear();
  }

  private destroyPane(id: number): void {
    const pane = this.panesMap.get(id);

    if (!pane) {
      return;
    }

    const paneIndex = pane.paneIndex();

    this.panesMap.delete(id);
    pane.destroy();

    if (paneIndex >= 0) {
      this.sharedPaneParams.lwcChart.removePane(paneIndex);
    }

    this.syncPaneContainers();
    this.priceAxisLabels?.invalidate();
  }

  private syncPaneContainers(): void {
    this.panesMap.forEach((pane) => {
      pane.schedulePaneContainerSync();
    });
  }

  private handlePriceScaleStateChange = (): void => {
    this.priceAxisLabels?.invalidate();
  };
}




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 { CompareItem, CompareMode, Direction, IndicatorConfig } from '@src/types';
import { IndicatorSnapshot } from '@src/types/snapshot';
import { createFallbackColor, normalizeColor, normalizeSymbol } from '@src/utils';

interface CompareEntry {
  key: string;
  symbol: string;
  mode: CompareMode;
  symbol$: 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 hasPercentageComparison = 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();
      }),
    );

    void 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,
    symbolRaw: string,
    mode: CompareMode,
    paneId?: number,
  ): Promise<void> {
    const symbol = normalizeSymbol(symbolRaw);

    if (!symbol) {
      return;
    }

    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 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(symbol, 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$,
        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,
      mode,
      symbol$,
      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, entity, mode }) => ({
      symbol,
      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 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, indicator.config.label, 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();

    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,
        mode: values[index].mode,
      });

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

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

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

    if (this.hasPercentageComparison === hasPercentageComparison) {
      return;
    }

    const hadPercentageComparison = this.hasPercentageComparison;

    this.hasPercentageComparison = hasPercentageComparison;

    if (hasPercentageComparison && !hadPercentageComparison) {
      priceScale.setMode(PriceScaleMode.Percentage);
      return;
    }

    if (!hasPercentageComparison && hadPercentageComparison && priceScale.getMode() === PriceScaleMode.Percentage) {
      priceScale.setMode(PriceScaleMode.Normal);
    }
  }

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

    let hasPercentageComparison = false;
    let hasNewScaleComparison = false;

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

      if (entries[index].mode === CompareMode.NewScale) {
        hasNewScaleComparison = 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, hasNewScaleComparison);
    this.paneManager.setPriceScaleSideVisible(Direction.Right, true);

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

    this.syncPercentageMode(mainRightPriceScale, hasPercentageComparison);

    this.paneManager.refreshPriceScaleControls();
    this.paneManager.invalidatePriceAxisLabels();
  }
}

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 = (symbol: string, usedColors: string[]): IndicatorConfig => {
  const reservedColors = new Set(usedColors.map(normalizeColor));

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