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


import { SeriesType, Time } from 'lightweight-charts';

import { DateFormat } from '@src/utils/formatter';

import { TimeFormat } from './timeScale';

export type ChartSeriesType = SeriesType;

export interface ChartDataPoint {
  time?: Time;
  value?: number;
  open?: number;
  high?: number;
  low?: number;
  close?: number;
  volume?: number;
}

export interface LineCandle {
  time: number;
  value: number;
  volume?: number;
}

export interface Candle {
  time: number;
  open: number;
  high: number;
  low: number;
  close: number;
  volume?: number; // todo: volume & future metaData to customFields
}

export type Destroyable = {
  destroy(): void;
};

export enum Direction {
  Top = 'top',
  Bottom = 'bottom',
  Left = 'left',
  Right = 'right',
}

// Настройки графика, которые могут изменяться в рантайме
export interface ChartOptionsModel {
  dateFormat: DateFormat;
  timeFormat: TimeFormat;
  showTime: boolean;
}

















import { ChartIcon, SeasonalityIcon } from '@src/components/Icon';
import { ChartViewType } from '@src/types';

interface ChartViewTypeIconProps {
  type?: ChartViewType;
}

export function ChartViewTypeIcon({ type }: ChartViewTypeIconProps) {
  if (type === ChartViewType.Seasonality) {
    return <SeasonalityIcon />;
  }

  return <ChartIcon />;
}

















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, Keys } from '@core/Hotkeys';
import { ModalRenderer } from '@core/ModalRenderer';

import { FloatingDrawingToolbar } from '@src/components/FloatingToolbar';
import { SeasonalityControls } from '@src/components/SeasonalityControls';
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 { SeasonalityManager } from '@src/core/SeasonalityManager';
import { configureThemeStore } from '@src/theme/store';
import { ThemeKey, ThemeMode } from '@src/theme/types';
import { Locale, setLocale, t } from '@src/translations';

import {
  Candle,
  ChartSeriesType,
  ChartViewType,
  OHLCConfig,
  SeasonalityRange,
  SymbolInfoInput,
  TooltipConfig,
} from '@src/types';
import { ISerializable, MoexChartSnapshot, MoexChartSnapshotInput } 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;
  showSnapshotButton?: boolean;
  showSeasonalityButton?: 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'];
  getSeasonalityDataSource?: DataSourceParams['getData'];

  startRealtime: (
    getSymbols: () => string[],
    getTimeframe: () => Timeframes,
    update: (symbolId: 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: MoexChartSnapshotInput;
  chartCollectionPreset: ChartCollectionPreset;

  container: HTMLElement;
}

export class MoexChart implements ISerializable<MoexChartSnapshot> {
  private chart!: Chart;
  private seasonalityManager!: SeasonalityManager;

  private resizeObserver?: ResizeObserver;

  private eventManager!: EventManager;
  private hotkeys!: Hotkeys;
  private rootContainer!: HTMLElement;

  private seasonalityControlsRenderer!: UIRenderer;
  private headerRenderer!: UIRenderer;
  private modalRenderer!: ModalRenderer;
  private toolbarRenderer: UIRenderer | undefined;
  private controlBarRenderer?: UIRenderer;
  private footerRenderer?: UIRenderer;
  private drawingToolbarRenderer!: 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.subscriptions = new Subscription();

    this.toolbarRenderer = undefined;
    this.controlBarRenderer = undefined;
    this.footerRenderer = undefined;

    this.chartCollectionPresetSettings = config.chartCollectionPreset;

    setPricePrecision(config.chartCollectionPreset.ohlc.precision);

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

    this.eventManager = new EventManager({
      initialTimeframe: timeframe,
      initialSeries: chartSeriesType,
      initialSymbolInfo: {
        symbolId: symbolId ?? '',
        symbol,
        symbolName,
      },
      initialTimeFormat: timeFormat,
      initialDateFormat: dateFormat,
      initialInterval: interval,
    });

    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,
      chartContainer,
      seasonalityContainer,
      seasonalityControlsContainer,
      seasonalityPlotContainer,
      toolBarContainer,
      headerContainer,
      modalContainer,
      controlBarContainer,
      drawingToolbarContainer,
      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.rootContainer, () => !this.seasonalityManager.isActive());

    this.registerUndoRedoHotkeys(config.chartCollectionPreset.undoRedoEnabled);

    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,
      },
    });

    const chartGridTemplateRows = this.rootContainer.style.gridTemplateRows;

    const setSeasonalityVisible = (visible: boolean): void => {
      Object.assign(this.rootContainer.style, {
        gridTemplateRows: visible ? 'auto minmax(0, 1fr)' : chartGridTemplateRows,
      });

      Object.assign(chartContainer.style, {
        visibility: visible ? 'hidden' : 'visible',
      });

      chartContainer.inert = visible;

      Object.assign(footerContainer.style, {
        display: visible ? 'none' : '',
      });

      Object.assign(seasonalityContainer.style, {
        visibility: visible ? 'visible' : 'hidden',
        pointerEvents: visible ? 'auto' : 'none',
      });

      seasonalityContainer.inert = !visible;
    };

    this.seasonalityManager = new SeasonalityManager({
      container: seasonalityPlotContainer,
      getData: config.chartCollectionPreset.getSeasonalityDataSource ?? config.chartCollectionPreset.getDataSource,
      precision: config.chartCollectionPreset.ohlc.precision,

      onOpen: () => {
        this.chart.setActive(false);
        setSeasonalityVisible(true);
        seasonalityContainer.focus({ preventScroll: true });
      },

      onBack: () => {
        setSeasonalityVisible(false);
        this.chart.setActive(true);
        chartAreaContainer.focus({ preventScroll: true });
      },
    });

    this.seasonalityControlsRenderer = new ReactRenderer(seasonalityControlsContainer);

    this.seasonalityControlsRenderer.renderComponent(
      <SeasonalityControls
        stateObs={this.seasonalityManager.getState()}
        setScale={this.seasonalityManager.setScale}
        setRange={this.seasonalityManager.setRange}
      />,
    );

    this.subscriptions.add(
      this.hotkeys.register({
        keys: [Keys.escape],
        enabled: () => this.seasonalityManager.isActive() && modalContainer.hidden,
        callback: this.backToChart,
      }),
    );

    this.subscriptions.add(this.eventManager.symbolId().subscribe(this.backToChart));

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

        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.createRenderers(config.chartCollectionPreset, {
      headerContainer,
      toolBarContainer,
      drawingToolbarContainer,
      controlBarContainer,
      footerContainer,
    });

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

    this.renderAttachments(config, toggleToolbar);
  };

  private registerUndoRedoHotkeys(enabled = false): void {
    if (!enabled) return;

    const undoRedo = this.eventManager.getUndoRedo();

    this.hotkeys.register({ keys: [Keys.mod, Keys.z], callback: undoRedo.undo });
    this.hotkeys.register({ keys: [Keys.mod, Keys.y], callback: undoRedo.redo });
    this.hotkeys.register({ keys: [Keys.mod, Keys.shift, Keys.z], callback: undoRedo.redo });
  }

  private createRenderers(
    preset: ChartCollectionPreset,
    containers: Pick<
      ReturnType<typeof ContainerManager.createContainers>,
      'headerContainer' | 'toolBarContainer' | 'drawingToolbarContainer' | 'controlBarContainer' | 'footerContainer'
    >,
  ): void {
    const { headerContainer, toolBarContainer, drawingToolbarContainer, controlBarContainer, footerContainer } = containers;

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

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

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

  public setSettings(settings: ChartSettingsSource): void {
    this.seasonalityManager.back();

    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(snapshot: MoexChartSnapshotInput) {
    const configConstructorLike: IMoexChart = {
      snapshot,
      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(symbolInfo: SymbolInfoInput): void {
    this.seasonalityManager.back();

    this.eventManager.setSymbol(symbolInfo);
  }

  public clearSymbol(): void {
    this.seasonalityManager.back();

    this.eventManager.clearSymbol();
  }

  public showSeasonality(range?: SeasonalityRange): Promise<void> {
    const { symbolInfo } = this.eventManager.exportChartSettings();

    return this.seasonalityManager.show(symbolInfo.symbolId, range);
  }

  public backToChart = (): void => {
    this.seasonalityManager.back();
  };

  private setChartView = (view: ChartViewType): void => {
    if (view === ChartViewType.Chart) {
      this.backToChart();
      return;
    }

    this.showSeasonality();
  };

  private renderHeader(config: IMoexChart, toggleToolbar: () => boolean): void {
    this.headerRenderer.renderComponent(
      <Header
        seasonalityStateObs={this.seasonalityManager.getState()}
        setChartView={config.chartCollectionPreset.showSeasonalityButton ? this.setChartView : undefined}
        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 })
        }
        copyImage={
          config.chartCollectionPreset.showSnapshotButton
            ? () => (this.seasonalityManager.isActive() ? this.seasonalityManager.copyImage() : this.chart.copyImage())
            : undefined
        }
        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'}
      />,
    );
  }

  private renderAttachments(config: IMoexChart, toggleToolbar: () => boolean) {
    const drawingsCollectionManager = this.chart.getDrawingsCollectionManager();

    this.drawingToolbarRenderer.renderComponent(
      // этот тулбар к drawingManger бы прибить, сильно на него завязан
      <FloatingDrawingToolbar
        selectedDrawing$={drawingsCollectionManager.selectedDrawing()}
        onUpdateSettings={drawingsCollectionManager.updateSelectedDrawingSettings}
        onToggleLock={() => drawingsCollectionManager.toggleSelectedDrawingLock()}
        onOpenSettings={() => drawingsCollectionManager.openSelectedDrawingSettings()}
        onDelete={() => drawingsCollectionManager.deleteSelectedDrawing()}
      />,
    );

    this.renderHeader(config, toggleToolbar);

    if (this.toolbarRenderer && config.chartCollectionPreset.showMenuButton) {
      const drawingCollection = this.chart.getDrawingsCollectionManager();

      this.toolbarRenderer.renderComponent(
        <Toolbar
          toggleDOM={this.chart.getDom().toggleDOM}
          addDrawing={drawingCollection.activateDrawingTool}
          setEndlessDrawingsMode={drawingCollection.setEndlessDrawingMode}
          isEndlessDrawingsMode$={drawingCollection.isEndlessDrawingsMode()}
          activateCrosshair={() => drawingCollection.activateCrosshair()}
          activeTool$={drawingCollection.getActiveTool()}
        />,
      );
    }

    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.seasonalityControlsRenderer.destroy();
    this.seasonalityManager.destroy();

    this.headerRenderer.destroy();
    this.drawingToolbarRenderer.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();
    }

    this.hotkeys.destroy();

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

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

    this.dataSource.destroy();

    ContainerManager.clearContainers(this.rootContainer);
  }
}

















import dayjs from 'dayjs';

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

import { BehaviorSubject, combineLatest, defer, EMPTY, Observable, Subscription } from 'rxjs';
import { catchError, distinctUntilChanged, filter, ignoreElements, map, switchMap, tap } from 'rxjs/operators';

import { ChartMouseEvents } from '@core/ChartMouseEvents';
import { DataSource } from '@core/DataSource';
import { DOMModel } from '@core/DOMModel';
import { DrawingsManagerCollection } from '@core/DrawingsManagerCollection';
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 { CHART_PANE_LEGEND_CONTAINER } from '@src/constants';
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,
  Direction,
  OHLCConfig,
  TooltipConfig,
} from '@src/types';
import { Defaults } from '@src/types/defaults';
import { DayjsOffset, Intervals, intervalsToDayjs } from '@src/types/intervals';
import { ChartSnapshot, CompareSnapshot, IndicatorSnapshot, ISerializable, PaneSnapshot } from '@src/types/snapshot';
import { canvasToBlob, drawTextLayer, 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;
  localization?: LocalizationOptionsBase;
}

export enum Resize {
  Shrink,
  Expand,
}

const HISTORY_LOAD_THRESHOLD = 500;

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

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

  function isIndicatorSnapshot(
    input: (IndicatorSnapshot | CompareSnapshot) & { indicatorType?: unknown },
  ): input is IndicatorSnapshot {
    return input.indicatorType !== undefined;
  }

  function isCompareSnapshot(
    input: (IndicatorSnapshot | CompareSnapshot) & { indicatorType?: unknown },
  ): input is CompareSnapshot {
    return input.indicatorType === undefined;
  }

  return {
    indicatorSnapshots: snapshots.filter((snapshot) => isIndicatorSnapshot(snapshot)),
    compareSnapshots: snapshots.filter((snapshot) => isCompareSnapshot(snapshot)),
  };
}

/**
 * Абстракция над библиотекой для построения графиков
 */
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 activeSymbolIds: string[] = [];

  private historyBatchRunning = false;

  private active = true;
  private savedViewport: {
    logicalRange: LogicalRange | null;
    timeRange: IRange<Time> | null;
    oldestTimes: (number | null)[];
    shiftVisibleRangeOnNewBar: boolean;
    allowShiftVisibleRangeOnWhitespaceReplacement: boolean;
  } | null = null;

  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.preserveInactiveTimeScale();
      });

    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({
      lwcChart: this.lwcChart,
      eventManager,
      dataSource: this.dataSource,
      paneManager: this.paneManager,
      initialIndicators: indicatorSnapshots,
      DOM: this.DOM,
    });

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

    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 getDrawingsCollectionManager = (): DrawingsManagerCollection => {
    return this.paneManager.getDrawingsCollectionManager();
  };

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

  private onWheel = () => {
    if (!this.active) return;

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

  private onPointerDown = (event: PointerEvent) => {
    if (!this.active) return;

    if (event.composedPath().includes(this.lwcChart.chartElement())) {
      this.container.focus({ preventScroll: true });
    }

    this.isPointerDown = true;
    this.didResetOnDrag = false;
  };

  private onPointerMove = () => {
    if (!this.active) return;
    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.preserveInactiveTimeScale();

    this.paneManager.invalidate();
  }

  public setActive(active: boolean): void {
    if (this.active === active) return;

    this.active = active;
    this.isPointerDown = false;

    const timeScale = this.lwcChart.timeScale();

    if (!active) {
      const options = timeScale.options();

      this.savedViewport = {
        logicalRange: timeScale.getVisibleLogicalRange(),
        timeRange: timeScale.getVisibleRange(),
        oldestTimes: this.activeSymbolIds.map((symbolId) => this.dataSource.getOldestTime(symbolId)),
        shiftVisibleRangeOnNewBar: options.shiftVisibleRangeOnNewBar,
        allowShiftVisibleRangeOnWhitespaceReplacement: options.allowShiftVisibleRangeOnWhitespaceReplacement,
      };

      this.preserveInactiveTimeScale();
      return;
    }

    const saved = this.savedViewport;
    this.savedViewport = null;

    if (saved) {
      timeScale.applyOptions({
        shiftVisibleRangeOnNewBar: saved.shiftVisibleRangeOnNewBar,
        allowShiftVisibleRangeOnWhitespaceReplacement: saved.allowShiftVisibleRangeOnWhitespaceReplacement,
      });

      const historyChanged = this.activeSymbolIds.some(
        (symbolId, index) => this.dataSource.getOldestTime(symbolId) !== saved.oldestTimes[index],
      );

      if (historyChanged && saved.timeRange) {
        timeScale.setVisibleRange(saved.timeRange);
      } else if (saved.logicalRange) {
        timeScale.setVisibleLogicalRange(saved.logicalRange);
      }
    }
  }

  private preserveInactiveTimeScale(): void {
    if (this.active) return;

    this.lwcChart.timeScale().applyOptions({
      shiftVisibleRangeOnNewBar: false,
      allowShiftVisibleRangeOnWhitespaceReplacement: false,
    });
  }

  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) => {
    if (!this.active) return;

    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) => {
    if (!this.active) return;

    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 = () => {
    if (!this.active) return;

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

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

    this.paneManager.resetPriceScalesAutoScale();
  };

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

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

    return {
      panes: this.paneManager.getSnapshot(),
      chartSeriesType: seriesSelected,
      timeframe,
      dateFormat,
      timeFormat,
      interval,
      ...symbolInfo,
    };
  }

  public async copyImage(): Promise<void> {
    const canvas = this.lwcChart.takeScreenshot(true, false);
    const chartElement = this.lwcChart.chartElement();

    chartElement.querySelectorAll<HTMLElement>(`.${CHART_PANE_LEGEND_CONTAINER}`).forEach((legend) => {
      if (legend.hidden || window.getComputedStyle(legend).display === 'none') {
        return;
      }

      drawTextLayer(canvas, legend, chartElement);
    });

    const blob = await canvasToBlob(canvas);

    await navigator.clipboard.write([
      new ClipboardItem({
        'image/png': blob,
      }),
    ]);
  }

  private scheduleHistoryBatch(): void {
    if (!this.active || this.subscriptions.closed || this.historyBatchRunning || this.activeSymbolIds.length === 0) {
      return;
    }

    this.historyBatchRunning = true;

    requestAnimationFrame(() => {
      if (!this.active || this.subscriptions.closed) {
        this.historyBatchRunning = false;
        return;
      }

      const symbolIds = this.activeSymbolIds.slice();
      const timeframe = this.eventManager.getTimeframe();
      const oldestTimes = symbolIds.map((symbolId) => this.dataSource.getOldestTime(symbolId));

      Promise.all(symbolIds.map((symbolId) => this.dataSource.loadMoreHistory(symbolId)))
        .catch((error) => console.error('[Chart] History batch failed:', error))
        .finally(() => this.finishHistoryBatch(symbolIds, oldestTimes, timeframe));
    });
  }

  private finishHistoryBatch(
    symbolIds: string[],
    oldestTimes: (number | null)[],
    timeframe: ReturnType<EventManager['getTimeframe']>,
  ): void {
    this.historyBatchRunning = false;

    if (!this.active || this.subscriptions.closed) {
      return;
    }

    const contextChanged =
      timeframe !== this.eventManager.getTimeframe() || isUniqueSymbolId(symbolIds, this.activeSymbolIds);

    const hasProgress = this.hasHistoryProgress(symbolIds, oldestTimes);

    if (!contextChanged && !hasProgress) {
      return;
    }

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

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

  private hasHistoryProgress(symbolIds: string[], oldestTimes: (number | null)[]): boolean {
    return symbolIds.some((symbolId, index) => {
      if (!this.activeSymbolIds.includes(symbolId)) {
        return false;
      }

      const previousOldestTime = oldestTimes[index];
      const currentOldestTime = this.dataSource.getOldestTime(symbolId);

      return currentOldestTime !== null && (previousOldestTime === null || currentOldestTime < previousOldestTime);
    });
  }

  private async warmupSymbols(symbolIds: string[]): Promise<void> {
    const range = this.lwcChart.timeScale().getVisibleRange() as IRange<number> | null;

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

    await Promise.all(symbolIds.map((symbolId) => this.dataSource.loadTill(symbolId, range.from)));
  }

  private async loadIntervalRange(interval: Intervals, symbolIds: string[]): Promise<IRange<Time> | null> {
    if (interval === Intervals.All) {
      await Promise.all(symbolIds.map((symbolId) => this.dataSource.loadAllHistory(symbolId)));

      const firstTimes = symbolIds
        .map((symbolId) => this.dataSource.getOldestTime(symbolId))
        .filter((time): time is number => time !== null);

      const lastTimes = symbolIds
        .map((symbolId) => this.dataSource.getLastCandle(symbolId)?.time)
        .filter((time): time is number => time !== undefined);

      if (firstTimes.length === 0 || lastTimes.length === 0) {
        return null;
      }

      return {
        from: Math.min(...firstTimes) as Time,
        to: Math.max(...lastTimes) as Time,
      };
    }

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

    await Promise.all(symbolIds.map((symbolId) => this.dataSource.loadTill(symbolId, from)));

    const hasData = symbolIds.some((symbolId) => this.dataSource.getOldestTime(symbolId) !== null);

    if (!hasData) {
      return null;
    }

    return {
      from: from as Time,
      to: to as Time,
    };
  }

  private setupDataSourceSubs(): void {
    let symbolsRegistered = false;

    const symbols$ = combineLatest([this.eventManager.symbolId(), this.compareManager.itemsObs()]).pipe(
      map(([mainSymbolId, items]) => {
        const symbolIds = Array.from(
          new Set([mainSymbolId, ...items.map(({ symbolId }) => symbolId)].filter((symbolId) => symbolId !== '')),
        );

        return {
          mainSymbolId,
          symbolIds,
        };
      }),
      distinctUntilChanged(
        (previous, next) =>
          previous.mainSymbolId === next.mainSymbolId && !isUniqueSymbolId(previous.symbolIds, next.symbolIds),
      ),
    );

    this.subscriptions.add(
      combineLatest([this.eventManager.getInterval().pipe(distinctUntilChanged()), symbols$])
        .pipe(
          switchMap(([interval, { symbolIds }]) => {
            const previousSymbolIds = this.activeSymbolIds;
            const previousSymbolIdsSet = new Set(previousSymbolIds);
            const addedSymbolIds = symbolIds.filter((symbolId) => !previousSymbolIdsSet.has(symbolId));

            this.activeSymbolIds = symbolIds;

            if (!symbolsRegistered || isUniqueSymbolId(previousSymbolIds, symbolIds)) {
              symbolsRegistered = true;
              this.dataSource.setSymbols(symbolIds);
            }

            if (symbolIds.length === 0) {
              return EMPTY;
            }

            if (interval === null) {
              if (addedSymbolIds.length === 0) {
                return EMPTY;
              }

              return defer(() => this.warmupSymbols(addedSymbolIds)).pipe(
                ignoreElements(),
                catchError((error) => {
                  console.error('[Chart] Ошибка при прогреве символов:', error);

                  return EMPTY;
                }),
              );
            }

            return defer(() => this.loadIntervalRange(interval, symbolIds)).pipe(
              filter((range): range is IRange<Time> => range !== null),
              tap((range) => {
                if (this.active) this.lwcChart.timeScale().setVisibleRange(range);
              }),
              catchError((error) => {
                console.error('[Chart] Ошибка при применении интервала:', error);

                return EMPTY;
              }),
            );
          }),
        )
        .subscribe(),
    );
  }

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

      if (!logicalRange) return;

      const needsMoreData = logicalRange.from < HISTORY_LOAD_THRESHOLD;

      if (!needsMoreData) return;

      this.scheduleHistoryBatch();
    });
  }
}

function isUniqueSymbolId(previous: string[], next: string[]): boolean {
  if (previous.length !== next.length) {
    return true;
  }

  const nextSet = new Set(next);

  return previous.some((symbolId) => !nextSet.has(symbolId));
}

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,
    defaultVisiblePriceScaleId: Direction.Right,
    layout: {
      background: {
        color: colors.chartBackground,
      },
      textColor: colors.chartTextPrimary,
      panes: {
        separatorColor: colors.chartPaneSeparator,
        separatorHoverColor: colors.chartPaneSeparator,
        enableResize: true,
      },
    },
    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: 10,
      shiftVisibleRangeOnNewBar: true,
      allowShiftVisibleRangeOnWhitespaceReplacement: true,
    },
    rightPriceScale: {
      minimumWidth: 60,
      borderVisible: false,
    },
    leftPriceScale: {
      minimumWidth: 60,
      borderVisible: false,
    },
    localization,
  };
}

















import { IChartApi } from 'lightweight-charts';
import { BehaviorSubject, map, Observable } from 'rxjs';

import { DataSource } from '@core/DataSource';
import { DOMModel } from '@core/DOMModel';
import { EventManager } from '@core/EventManager';
import { Indicator } from '@core/Indicator';
import { PaneManager } from '@core/PaneManager';
import { IndicatorsIds } from '@src/constants';
import { DOMObject } from '@src/core/DOMObject';
import { indicatorsMap as indicatorsConfigMap } from '@src/core/Indicators';
import { IndicatorConfig } from '@src/types';
import { IndicatorSnapshot } from '@src/types/snapshot';
import { applyNextIndicatorColors, getIndicatorColors } from '@src/utils';

interface IndicatorManagerParams {
  eventManager: EventManager;
  dataSource: DataSource;
  lwcChart: IChartApi;
  paneManager: PaneManager;
  DOM: DOMModel;
  initialIndicators?: IndicatorSnapshot[];
}

export class IndicatorManager {
  private readonly eventManager: EventManager;
  private readonly lwcChart: IChartApi;
  private readonly indicatorsMap$ = new BehaviorSubject<Map<string, Indicator>>(new Map());
  private readonly DOM: DOMModel;
  private readonly dataSource: DataSource;
  private readonly paneManager: PaneManager;

  constructor({
    eventManager,
    dataSource,
    lwcChart,
    DOM,
    initialIndicators,
    paneManager,
  }: IndicatorManagerParams) {
    this.eventManager = eventManager;
    this.lwcChart = lwcChart;
    this.DOM = DOM;
    this.dataSource = dataSource;
    this.paneManager = paneManager;

    initialIndicators?.forEach((indicator) => {
      this.addIndicator(indicator);
    });
  }

  public addEntity<T extends Indicator>(
    factory: (zIndex: number, moveUp: (id: string) => void, moveDown: (id: string) => void) => T,
  ): T {
    return this.DOM.setEntity(factory);
  }

  public addIndicator(snap: Partial<IndicatorSnapshot>): void {
    if (!snap.indicatorType) {
      console.error('[IndicatorManager] Не был получен тип индиктора');
      return;
    }

    const indicatorsMap = new Map(this.indicatorsMap$.value);
    const id = snap.id ?? `${snap.indicatorType}-${crypto.randomUUID()}`;
    const config = getConfigByIndicatorType({
      indicatorType: snap.indicatorType,
      existedIndicators: this.indicatorsMap$.value,
    });

    const associatedPane =
      snap.paneId !== undefined
        ? (this.paneManager.getPaneById(snap.paneId) ?? this.paneManager.addPane())
        : config.newPane
          ? this.paneManager.addPane()
          : this.paneManager.getMainPane();

    const indicatorToSet = this.addEntity<Indicator>((zIndex, moveUp, moveDown) => {
      return new Indicator({
        id,
        paneId: associatedPane.getId(),
        zIndex,
        onDelete: this.deleteIndicator,
        moveUp,
        moveDown,
        mainSymbolId$: this.eventManager.symbolId(),
        mainSymbol$: this.eventManager.symbol(),
        lwcChart: this.lwcChart,
        dataSource: this.dataSource,
        associatedPane,
        config,
        settings: snap.settings,
        type: snap.indicatorType,
      });
    });

    indicatorsMap.set(id, indicatorToSet);
    this.indicatorsMap$.next(indicatorsMap);
  }

  public getIndicators(): BehaviorSubject<Map<string, Indicator>> {
    return this.indicatorsMap$;
  }

  public removeEntity(entity: DOMObject): void {
    this.DOM.removeEntity(entity);
  }

  public deleteIndicator = (id: string): void => {
    const indicator = this.indicatorsMap$.value.get(id);

    if (!indicator) {
      return;
    }

    const indicators = new Map(this.indicatorsMap$.value);
    indicators.delete(id);

    this.indicatorsMap$.next(indicators);

    this.removeEntity(indicator);
    indicator.destroy();
  };

  public entities(): Observable<Indicator[]> {
    return this.indicatorsMap$.pipe(map((indicators) => Array.from(indicators.values())));
  }
}

function getConfigByIndicatorType({
  indicatorType,
  existedIndicators,
}: {
  indicatorType: IndicatorsIds;
  existedIndicators: ReadonlyMap<string, Indicator>;
}): IndicatorConfig {
  const configWithAppliedSettings = indicatorsConfigMap()[indicatorType] as IndicatorConfig;
  const usedColors = getUsedIndicatorColorsByType({
    indicatorType,
    existedIndicators,
  });

  return applyNextIndicatorColors(configWithAppliedSettings, usedColors);
}

function getUsedIndicatorColorsByType({
  indicatorType,
  existedIndicators,
}: {
  indicatorType: IndicatorSnapshot['indicatorType'];
  existedIndicators: ReadonlyMap<string, Indicator>;
}): string[] {
  const colors: string[] = [];

  existedIndicators.forEach((indicator) => {
    if (indicator.getIndicatorType() !== indicatorType) {
      return;
    }

    colors.push(...getIndicatorColors(indicator.getConfig()));
  });

  return colors;
}

















import { IChartApi } from 'lightweight-charts';
import { Observable, Subscription } from 'rxjs';

import { DataSource } from '@core/DataSource';
import { DOMObject, DOMObjectParams } from '@core/DOMObject';
import { Pane } from '@core/Pane';

import { indicatorLabelById, indicatorSeriesLabelById, IndicatorsIds } from '@src/constants';
import { SeriesFactory, SeriesStrategies } from '@src/modules/series-strategies/SeriesFactory';
import { Direction, IndicatorConfig, SettingsValues } from '@src/types';
import { CompareSnapshot, DOMObjectSnapshot, IndicatorSnapshot, ISerializable } from '@src/types/snapshot';

type IIndicator = DOMObject;

export interface IndicatorParams extends DOMObjectParams {
  mainSymbolId$: Observable<string>;
  mainSymbol$: Observable<string>;
  lwcChart: IChartApi;
  dataSource: DataSource;
  associatedPane: Pane;
  config: IndicatorConfig;
  settings?: SettingsValues;
  type?: IndicatorsIds;
}

// todo: сделать отдельно представление для Compare, и попобовать убрать CompareManager из Chart
export class Indicator extends DOMObject implements ISerializable<IndicatorSnapshot | CompareSnapshot> {
  private indicatorType?: IndicatorsIds;
  private series: SeriesStrategies[] = [];
  private seriesMap: Map<string, SeriesStrategies> = new Map();
  private lwcChart: IChartApi;
  private dataSource: DataSource;
  private mainSymbolId$: Observable<string>;
  private mainSymbol$: Observable<string>;
  private associatedPane: Pane;
  private config: IndicatorConfig;
  private settings: SettingsValues = {};

  private dataChangeHandlers = new Set<() => void>();
  private seriesSubscriptions = new Subscription();

  constructor({
    id,
    type,
    lwcChart,
    dataSource,
    zIndex,
    onDelete,
    moveUp,
    moveDown,
    mainSymbolId$,
    mainSymbol$,
    associatedPane,
    paneId,
    config,
    settings,
  }: IndicatorParams) {
    super({ id, name: config?.label ?? id, zIndex, onDelete, moveUp, moveDown, paneId });

    this.lwcChart = lwcChart;
    this.dataSource = dataSource;
    this.mainSymbolId$ = mainSymbolId$;
    this.mainSymbol$ = mainSymbol$;
    this.indicatorType = type;
    this.config = config;
    this.name = this.getLabel();

    this.settings = { ...this.getDefaultSettings(), ...settings };

    this.associatedPane = associatedPane;

    this.createSeries();

    this.associatedPane.setIndicator(this.id, this);
  }

  public recreateSeries() {
    this.destroySeries();
    this.createSeries();
  }

  public subscribeDataChange(handler: () => void): Subscription {
    this.dataChangeHandlers.add(handler);

    return new Subscription(() => {
      this.dataChangeHandlers.delete(handler);
    });
  }

  public getLabel = () => {
    if (this.config.label) {
      return this.config.label;
    }

    if (this.indicatorType) {
      return indicatorLabelById()[this.indicatorType];
    }

    return this.id;
  };

  public getSeriesLabel(serieName: string): string | undefined {
    if (this.config.seriesLabels?.[serieName]) {
      return this.config.seriesLabels[serieName];
    }

    if (this.indicatorType) {
      return indicatorSeriesLabelById[this.indicatorType]?.[serieName];
    }

    return undefined;
  }

  public getId(): string {
    return this.id;
  }

  public getType(): IndicatorsIds | undefined {
    return this.indicatorType;
  }

  public getPane(): Pane {
    return this.associatedPane;
  }

  public getSeriesMap(): Map<string, SeriesStrategies> {
    return this.seriesMap;
  }

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

  public getIndicatorType(): IndicatorSnapshot['indicatorType'] | undefined {
    return this.indicatorType;
  }

  public getSettingsValues(): SettingsValues {
    return { ...this.settings };
  }

  public getSettingsFields() {
    return this.config.settings ?? [];
  }

  public hasSettings(): boolean {
    return Boolean(this.config.settings?.length);
  }

  public updateSettings(settings: SettingsValues): void {
    this.settings = settings;

    // todo: обновлять данные серий без удаления и повторного создания
    this.recreateSeries();

    this.notifyDataChanged();
  }

  public show() {
    this.series.forEach((s) => {
      s.show();
    });

    super.show();
  }

  public hide() {
    this.series.forEach((s) => {
      s.hide();
    });

    super.hide();
  }

  public override getSnapshot(): DOMObjectSnapshot & (IndicatorSnapshot | CompareSnapshot) {
    const domSnap = super.getSnapshot();

    if (this.indicatorType) {
      return {
        ...domSnap,
        indicatorType: this.indicatorType,
        settings: this.getSettingsValues(),
      };
    }

    const seriesName = this.config.series[0]?.name;

    if (!seriesName) {
      throw new Error('[Indicator]: невозможно сохранить состояние compare индикатора');
    }

    const scale = (this.series[0]?.options().priceScaleId ??
      this.lwcChart.options().defaultVisiblePriceScaleId) as Direction;

    return {
      ...domSnap,
      symbolInfo: this.config.symbolInfo!,
      seriesName,
      scale,
    };
  }

  public setSnapshot(snap: IndicatorSnapshot): void {}

  // destroy и delete принципиально отличаются!
  // delete вызовет destroy в конце концов. По сути - это destroy с сайд-эффектом в eventManager
  public delete() {
    super.delete();
  }

  // destroy и delete принципиально отличаются!
  public destroy() {
    this.destroySeries();
    this.dataChangeHandlers.clear();
    this.associatedPane.removeIndicator(this.id);
  }

  private createSeries(): void {
    this.config.series.forEach(
      ({ name, id: serieId, dataFormatter, seriesOptions, priceScaleOptions, actLikeMainSerie, onSerieInit }) => {
        const serie = SeriesFactory.create(name!)({
          lwcChart: this.lwcChart,
          dataSource: this.dataSource,
          customFormatter: dataFormatter
            ? (params) =>
                dataFormatter({
                  ...params,
                  settings: this.settings,
                  indicatorReference: this,
                })
            : undefined,
          seriesOptions,
          priceScaleOptions,
          mainSymbolId$: this.mainSymbolId$,
          mainSymbol$: this.mainSymbol$,
          mainSerie$: this.associatedPane.getMainSerie(),
          showSymbolLabel: false,
          paneIndex: this.associatedPane.paneIndex(),
          indicatorReference: this,
          actLikeMainSerie,
        });

        onSerieInit?.(serie);

        const handleDataChanged = () => {
          this.notifyDataChanged();
        };

        serie.subscribeDataChanged(handleDataChanged);

        this.seriesSubscriptions.add(() => {
          serie.unsubscribeDataChanged(handleDataChanged);
        });

        this.seriesMap.set(serieId, serie);

        this.series.push(serie);
      },
    );

    if (!this.associatedPane.getLocalMainSeries()) {
      const mainSeriesCandidates = this.series.filter((serie) => serie.actLikeMainSerie);

      if (mainSeriesCandidates.length < 1) {
        throw new Error('[Indicator]: there is no mainSerie in this indicator');
      }

      this.associatedPane.setLocalMainSeries(mainSeriesCandidates[0]);
    }
  }

  private destroySeries(): void {
    this.seriesSubscriptions.unsubscribe();
    this.seriesSubscriptions = new Subscription();

    this.series.forEach((s) => {
      s.destroy();
    });

    this.series = [];
    this.seriesMap.clear();
  }

  private notifyDataChanged(): void {
    this.dataChangeHandlers.forEach((handler) => {
      handler();
    });
  }

  private getDefaultSettings(): SettingsValues {
    const settings: SettingsValues = {};

    this.config.settings?.forEach((field) => {
      settings[field.key] = field.defaultValue;
    });

    return settings;
  }
}

















import dayjs from 'dayjs';
import {
  ColorType,
  createChart,
  createSeriesMarkers,
  CrosshairMode,
  type IChartApi,
  type ISeriesApi,
  type ISeriesMarkersPluginApi,
  LineSeries,
  LineStyle,
  type MouseEventParams,
  PriceScaleMode,
  type Time,
} from 'lightweight-charts';
import { BehaviorSubject } from 'rxjs';

import { createInitialSeasonalityState } from '@src/constants';
import { ZIndex } from '@src/core/ContainerManager';
import { COMPARE_COLOR_PALETTE } from '@src/theme';
import { getThemeStore } from '@src/theme/store';
import { getLocale, t } from '@src/translations';
import { ChartViewType } from '@src/types';
import { Timeframes } from '@src/types/timeframes';
import {
  buildSeasonality,
  canvasToBlob,
  drawTextLayer,
  formatCompactNumber,
  normalizeRange,
  toSeriesData,
} from '@src/utils';

import type { DataSourceParams } from '@src/core/DataSource';
import type {
  Candle,
  DailyClose,
  SeasonalityRange,
  SeasonalityScale,
  SeasonalityYear,
} from '@src/types';

interface SeasonalityManagerParams {
  container: HTMLElement;
  getData: DataSourceParams['getData'];
  precision?: number;
  onOpen: () => void;
  onBack: () => void;
}

interface SeasonalityPlot {
  year: SeasonalityYear;
  series: ISeriesApi<'Line'>;
  legend: HTMLSpanElement;
  legendValue: HTMLSpanElement;
  markers?: ISeriesMarkersPluginApi<Time>;
}

const DEFAULT_YEARS = 5;

export class SeasonalityManager {
  private readonly currentYear = dayjs().year();
  private readonly state = new BehaviorSubject(createInitialSeasonalityState());
  private readonly chartContainer = document.createElement('div');
  private readonly legend = document.createElement('div');
  private readonly statusElement = document.createElement('div');
  private readonly plots = new Map<number, SeasonalityPlot>();

  private chart: IChartApi | null = null;
  private allYears: SeasonalityYear[] = [];
  private requestId = 0;
  private renderFrame: number | null = null;
  private destroyed = false;

  constructor(private readonly params: SeasonalityManagerParams) {
    Object.assign(this.chartContainer.style, {
      position: 'absolute',
      inset: 0,
    });

    Object.assign(this.legend.style, {
      width: 'max-content',
      position: 'absolute',
      top: 0,
      left: 0,
      display: 'grid',
      gridTemplateColumns: 'max-content max-content',
      justifyContent: 'start',
      alignItems: 'center',
      gap: 'var(--space-0125) var(--space-0500)',
      fontSize: 'var(--space-0750)',
      lineHeight: 'var(--space-1000)',
      fontVariantNumeric: 'tabular-nums',
      pointerEvents: 'none',
      zIndex: ZIndex.Legend,
    });

    Object.assign(this.statusElement.style, {
      position: 'absolute',
      inset: 0,
      display: 'none',
      alignItems: 'center',
      justifyContent: 'center',
      textAlign: 'center',
      pointerEvents: 'none',
    });

    params.container.append(this.chartContainer, this.legend, this.statusElement);

    this.updateTheme();
  }

  public getState() {
    return this.state.asObservable();
  }

  public isActive(): boolean {
    return this.state.value.view === ChartViewType.Seasonality;
  }

  public async show(symbolId: string, range?: SeasonalityRange): Promise<void> {
    if (this.destroyed || this.reuseHistory(symbolId, range)) {
      return;
    }

    const requestId = ++this.requestId;

    this.reset();

    if (!this.isActive()) {
      this.params.onOpen();
    }

    this.showStatus(t('Loading seasonality'));

    this.state.next({
      ...this.state.value,
      symbolId,
      view: ChartViewType.Seasonality,
      status: 'loading',
      error: null,
    });

    try {
      if (!symbolId) {
        throw new Error('Select an instrument');
      }

      const rows = await this.loadHistory(symbolId, requestId);

      if (!this.isCurrent(requestId)) {
        return;
      }

      this.allYears = buildSeasonality(rows);
      this.setInitialRange(range);
    } catch (error) {
      if (!this.isCurrent(requestId)) {
        return;
      }

      this.reset();
      this.showStatus(t('Unable to load seasonality'));

      this.state.next({
        ...this.state.value,
        status: 'error',
        error: String(error),
      });

      console.error('[Seasonality] History loading failed:', error);
    }
  }

  public setRange = (range: SeasonalityRange): void => {
    if (this.destroyed || !this.isActive() || this.allYears.length === 0) {
      return;
    }

    const state = this.state.value;
    const next = normalizeRange(range, state.minYear, state.maxYear);

    if (next.fromYear === state.fromYear && next.toYear === state.toYear) {
      return;
    }

    this.state.next({ ...state, ...next });

    if (this.renderFrame !== null) {
      return;
    }

    this.renderFrame = requestAnimationFrame(() => {
      this.renderFrame = null;

      if (!this.destroyed && this.isActive()) {
        this.renderRange();
      }
    });
  };

  public setScale = (scale: SeasonalityScale): void => {
    if (this.destroyed || !this.isActive() || this.state.value.scale === scale) {
      return;
    }

    this.state.next({ ...this.state.value, scale });

    if (!this.chart) {
      return;
    }

    this.plots.forEach((plot) => this.updateSeries(plot));

    this.fitCalendar();

    this.updateStatus();
    this.updateLegend();
  };

  public back = (): void => {
    if (this.destroyed || !this.isActive()) {
      return;
    }

    this.requestId += 1;

    this.reset();

    this.state.next({
      ...this.state.value,
      view: ChartViewType.Chart,
      status: 'idle',
      error: null,
    });

    this.params.onBack();
  };

  public updateTheme(): void {
    const { colors } = getThemeStore();

    Object.assign(this.params.container.style, {
      backgroundColor: colors.chartBackground,
    });

    Object.assign(this.statusElement.style, {
      color: colors.chartTextPrimary,
    });

    this.legend.style.color = colors.chartTextPrimary;

    this.chart?.applyOptions(getThemeOptions());
  }

  public async copyImage(): Promise<void> {
    if (!this.chart || this.state.value.status !== 'ready') {
      return;
    }

    const canvas = this.chart.takeScreenshot(true, false);

    drawTextLayer(canvas, this.legend, this.chart.chartElement());

    const blob = await canvasToBlob(canvas);

    await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]);
  }

  public destroy(): void {
    if (this.destroyed) {
      return;
    }

    this.destroyed = true;
    this.requestId += 1;

    this.reset();

    this.chartContainer.remove();
    this.legend.remove();
    this.statusElement.remove();

    this.state.complete();
  }

  private isCurrent(requestId: number): boolean {
    return !this.destroyed && requestId === this.requestId;
  }

  private reuseHistory(symbolId: string, range?: SeasonalityRange): boolean {
    const state = this.state.value;

    if (!this.isActive() || state.symbolId !== symbolId) {
      return false;
    }

    if (state.status === 'loading') {
      return true;
    }

    if (this.allYears.length === 0) {
      return false;
    }

    if (range) {
      this.setRange(range);
    }

    return true;
  }

  private async loadHistory(symbolId: string, requestId: number): Promise<DailyClose[]> {
    const candles = new Map<number, Candle>();

    const loadPage = async (cursor?: Candle): Promise<void> => {
      if (!this.isCurrent(requestId)) {
        return;
      }

      const loaded = await this.params.getData(Timeframes['1d'], symbolId, cursor);

      if (!this.isCurrent(requestId) || !loaded?.length) {
        return;
      }

      const { oldest, newestTime } = mergeHistoryPage(loaded, candles);

      if (cursor && oldest.time >= cursor.time) {
        const isBoundaryOnly = oldest.time === cursor.time && newestTime === cursor.time;

        if (isBoundaryOnly) {
          return;
        }

        throw new Error(
          `History pagination made no progress: cursor=${cursor.time}, ` +
            `oldest=${oldest.time}, newest=${newestTime}, count=${loaded.length}`,
        );
      }

      return loadPage(oldest);
    };

    await loadPage();

    if (!this.isCurrent(requestId)) {
      return [];
    }

    return Array.from(candles.values(), (candle) => ({
      date: dayjs.unix(candle.time).format('YYYY-MM-DD'),
      close: candle.close,
    }));
  }

  private setInitialRange(range?: SeasonalityRange): void {
    if (this.allYears.length === 0) {
      this.showStatus(t('No seasonality data'));
      this.state.next({
        ...this.state.value,
        status: 'empty',
      });

      return;
    }

    const minYear = this.allYears[0].year;
    const maxYear = this.allYears[this.allYears.length - 1].year;

    const selected = normalizeRange(
      range ?? {
        fromYear: maxYear - DEFAULT_YEARS + 1,
        toYear: maxYear,
      },
      minYear,
      maxYear,
    );

    this.state.next({
      ...this.state.value,
      ...selected,
      minYear,
      maxYear,
    });

    this.renderRange();
  }

  private createChart(): IChartApi {
    const chart = createChart(this.chartContainer, {
      ...getThemeOptions(),
      autoSize: true,
      handleScroll: false,
      handleScale: false,
      kineticScroll: {
        mouse: false,
        touch: false,
      },
      rightPriceScale: {
        mode: PriceScaleMode.Normal,
        autoScale: true,
        alignLabels: true,
        visible: true,
        borderVisible: false,
      },
      leftPriceScale: {
        visible: false,
      },
      timeScale: {
        timeVisible: false,
        secondsVisible: false,
        borderVisible: false,
        allowBoldLabels: false,
        rightOffset: 0,
        tickMarkFormatter: formatSeasonDate,
        lockVisibleTimeRangeOnResize: true,
      },
      localization: {
        locale: getLocale(),
        timeFormatter: formatSeasonDate,
      },
    });

    chart.subscribeCrosshairMove(this.onCrosshairMove);

    this.chart = chart;

    return chart;
  }

  private renderRange(): void {
    const chart = this.chart ?? this.createChart();
    const { fromYear, toYear } = this.state.value;

    const years = this.allYears.filter((year) => year.year >= fromYear && year.year <= toYear);

    this.plots.forEach((plot, year) => {
      if (year < fromYear || year > toYear) {
        plot.markers?.detach();
        chart.removeSeries(plot.series);
        this.plots.delete(year);
      }
    });

    const plots = years.map((year) => {
      const existing = this.plots.get(year.year);

      if (existing) {
        return existing;
      }

      const plot = this.createPlot(chart, year);

      this.plots.set(year.year, plot);

      return plot;
    });

    this.legend.replaceChildren(...plots.flatMap((plot) => [plot.legend, plot.legendValue]));

    if (plots.length > 0) {
      this.fitCalendar();
    }

    this.updateStatus();
    this.updateLegend();

    this.state.next({
      ...this.state.value,
      status: plots.length > 0 ? 'ready' : 'empty',
    });
  }

  private fitCalendar(): void {
    this.chart?.timeScale().setVisibleRange({
      from: '2000-01-01',
      to: '2000-12-31',
    });
  }

  private createPlot(chart: IChartApi, year: SeasonalityYear): SeasonalityPlot {
    const color = getYearColor(year.year);
    const legend = document.createElement('span');
    const legendValue = document.createElement('span');

    legend.textContent = String(year.year);

    Object.assign(legendValue.style, {
      color,
      textAlign: 'right',
    });

    const plot: SeasonalityPlot = {
      year,
      legend,
      legendValue,
      series: chart.addSeries(LineSeries, {
        title: String(year.year),
        color,
        priceLineVisible: false,
        lastValueVisible: true,
        lineWidth: year.year === this.currentYear ? 3 : 1,
        pointMarkersVisible: false,
        crosshairMarkerVisible: true,
      }),
    };

    if (year.year === this.currentYear) {
      plot.markers = createSeriesMarkers(plot.series, [], {
        autoScale: false,
      });
    }

    this.updateSeries(plot);

    return plot;
  }

  private updateSeries({ series, year, markers }: SeasonalityPlot): void {
    const { scale } = this.state.value;
    const isPercentage = scale === PriceScaleMode.Percentage;

    series.applyOptions({
      priceFormat: {
        type: 'custom',
        minMove: isPercentage ? 0.01 : 10 ** -(this.params.precision ?? 2),
        formatter: (value: number) => (isPercentage ? `${value.toFixed(2)}%` : formatCompactNumber(value)),
      },
    });

    series.setData(toSeriesData(year, scale));

    if (markers) {
      const lastPoint = year.points[year.points.length - 1];
      const value = isPercentage ? lastPoint.percentage : lastPoint.price;

      markers.setMarkers(
        value === null
          ? []
          : [
              {
                time: lastPoint.chartDate,
                position: 'inBar',
                shape: 'circle',
                color: getYearColor(year.year),
                size: 1,
              },
            ],
      );
    }
  }

  private updateStatus(): void {
    if (this.plots.size === 0) {
      this.showStatus(t('No seasonality data'));

      return;
    }

    const isPercentage = this.state.value.scale === PriceScaleMode.Percentage;

    const hasBaseline = Array.from(this.plots.values()).some((plot) => plot.year.baselinePrice > 0);

    if (isPercentage && !hasBaseline) {
      this.showStatus(t('Percentage requires a positive baseline'));

      return;
    }

    this.statusElement.style.display = 'none';
  }

  private onCrosshairMove = (event: MouseEventParams): void => {
    this.updateLegend(event);
  };

  private updateLegend(event?: MouseEventParams): void {
    const isPercentage = this.state.value.scale === PriceScaleMode.Percentage;

    this.plots.forEach(({ year, series, legendValue }) => {
      const lastPoint = year.points[year.points.length - 1];

      let value = isPercentage ? lastPoint.percentage : lastPoint.price;

      if (event?.time !== undefined) {
        const point = event.seriesData.get(series);

        value = point && 'value' in point && typeof point.value === 'number' ? point.value : null;
      }

      legendValue.textContent = value === null ? '—' : series.priceFormatter().format(value);
    });
  }

  private showStatus(message: string): void {
    this.statusElement.textContent = message;
    this.statusElement.style.display = 'flex';
  }

  private reset(): void {
    if (this.renderFrame !== null) {
      cancelAnimationFrame(this.renderFrame);
      this.renderFrame = null;
    }

    this.chart?.unsubscribeCrosshairMove(this.onCrosshairMove);
    this.plots.forEach((plot) => plot.markers?.detach());
    this.chart?.remove();

    this.chart = null;
    this.allYears = [];

    this.plots.clear();
    this.legend.replaceChildren();

    this.statusElement.style.display = 'none';
  }
}

function mergeHistoryPage(loaded: Candle[], candles: Map<number, Candle>): { oldest: Candle; newestTime: number } {
  let oldest = loaded[0];
  let oldestTime = Infinity;
  let newestTime = -Infinity;

  for (let index = loaded.length - 1; index >= 0; index -= 1) {
    const candle = loaded[index];

    if (!Number.isFinite(candle.time) || !Number.isFinite(candle.close)) {
      throw new Error('Invalid daily candle');
    }

    const time = Math.floor(candle.time > 1e10 ? candle.time / 1000 : candle.time);

    const normalized = time === candle.time ? candle : { ...candle, time };

    newestTime = Math.max(newestTime, time);

    if (time < oldestTime) {
      oldest = normalized;
      oldestTime = time;
    }

    if (!candles.has(time)) {
      candles.set(time, normalized);
    }
  }

  return { oldest, newestTime };
}

function getThemeOptions() {
  const { colors } = getThemeStore();

  return {
    layout: {
      background: {
        type: ColorType.Solid,
        color: colors.chartBackground,
      },
      textColor: colors.chartTextPrimary,
      panes: {
        separatorColor: colors.chartPaneSeparator,
        separatorHoverColor: colors.chartPaneSeparator,
        enableResize: false,
      },
    },

    grid: {
      vertLines: {
        color: colors.chartGridLine,
      },
      horzLines: {
        color: colors.chartGridLine,
      },
    },

    crosshair: {
      mode: CrosshairMode.Normal,
      vertLine: {
        color: colors.chartCrosshairLine,
        labelBackgroundColor: colors.chartCrosshairLabel,
        style: LineStyle.Solid,
      },
      horzLine: {
        color: colors.chartCrosshairLine,
        labelBackgroundColor: colors.chartCrosshairLabel,
        style: LineStyle.Dashed,
      },
    },
  };
}

function formatSeasonDate(time: Time): string {
  if (typeof time === 'object') {
    const day = String(time.day).padStart(2, '0');
    const month = String(time.month).padStart(2, '0');

    return `${day}.${month}`;
  }

  const date = typeof time === 'number' ? new Date(time * 1000).toISOString() : time;

  return `${date.slice(8, 10)}.${date.slice(5, 7)}`;
}

function getYearColor(year: number): string {
  return COMPARE_COLOR_PALETTE[year % COMPARE_COLOR_PALETTE.length];
}

















import dayjs from 'dayjs';

import { BehaviorSubject, Observable, Subject } from 'rxjs';

import { Candle } from '@src/types';
import { Timeframes } from '@src/types/timeframes';
import { normalizeSeriesData, parseTimeframe } from '@src/utils';

const FUTURE_WHITESPACES = 5000;

export interface SymbolSourceParams {
  symbol: string;
  getData: (timeframe: Timeframes, symbol: string, until?: Candle) => Promise<Candle[] | null>;
  getTimeframe: () => Timeframes;
}

export class SymbolSource {
  public readonly symbol: string;

  private readonly getData: SymbolSourceParams['getData'];
  private readonly getTimeframe: SymbolSourceParams['getTimeframe'];

  private readonly currentDataSubject = new BehaviorSubject<Candle[]>([]);
  private readonly realtimeSubject = new Subject<Candle>();
  private readonly lastCandleSubject = new BehaviorSubject<Candle | null>(null);
  private readonly isLoadingSubject = new BehaviorSubject<boolean>(false);
  private readonly isInitializedSubject = new BehaviorSubject<boolean>(false);

  private realtimeCache: Candle[] = [];
  private realtimeBuffer: Candle[] = [];

  private oldestCandle: Candle | null = null;
  private newestCandle: Candle | null = null;

  private loadSeq = 0;
  private loadingPromise: Promise<void> | null = null;

  private isEndOfData = false;

  constructor({ symbol, getData, getTimeframe }: SymbolSourceParams) {
    this.symbol = symbol;
    this.getData = getData;
    this.getTimeframe = getTimeframe;
  }

  public init(): void {
    this.reload(this.getTimeframe());
  }

  public data$(): Observable<Candle[]> {
    return this.currentDataSubject.asObservable();
  }

  public realtime$(): Observable<Candle> {
    return this.realtimeSubject.asObservable();
  }

  public lastCandle$(): Observable<Candle | null> {
    return this.lastCandleSubject.asObservable();
  }

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

  public waitUntilReady(): Promise<void> {
    if (this.isInitializedSubject.value) {
      return Promise.resolve();
    }

    const { loadingPromise } = this;

    if (!loadingPromise) {
      return Promise.resolve();
    }

    return loadingPromise.then(() => {
      if (this.isInitializedSubject.value) {
        return;
      }

      return this.waitUntilReady();
    });
  }

  public isLoadingValue(): boolean {
    return this.isLoadingSubject.value;
  }

  public getOldestTime(): number | null {
    return this.oldestCandle?.time ?? null;
  }

  public getLastValue(): Candle | null {
    return this.lastCandleSubject.value;
  }

  public destroy(): void {
    this.loadSeq += 1;
    this.loadingPromise = null;

    this.currentDataSubject.complete();
    this.realtimeSubject.complete();
    this.lastCandleSubject.complete();
    this.isLoadingSubject.complete();
    this.isInitializedSubject.complete();

    this.realtimeCache = [];
    this.realtimeBuffer = [];
    this.oldestCandle = null;
    this.newestCandle = null;
  }

  public pushRealtime(next: Candle): void {
    const candle = this.normalizeCandle(next);

    this.realtimeCache = this.normalizeList(this.realtimeCache.concat(candle));

    if (!this.newestCandle || candle.time >= this.newestCandle.time) {
      this.newestCandle = candle;
      this.lastCandleSubject.next(candle);
    }

    if (!this.isInitializedSubject.value) {
      this.realtimeBuffer.push(candle);
      return;
    }

    this.realtimeSubject.next(candle);
  }

  public saveRealtimeCache(): void {
    if (this.realtimeCache.length === 0) return;

    const timeframe = this.getTimeframe();

    const current = this.currentDataSubject.value.filter((candle) => candle.open !== undefined);
    const next = this.normalizeList(current.concat(this.realtimeCache));

    this.newestCandle = next[next.length - 1] ?? null;
    this.realtimeCache = [];

    this.currentDataSubject.next(applyWhitespacesToFuture(next, timeframe));
    this.lastCandleSubject.next(this.newestCandle);
  }

  public async loadMoreHistory(): Promise<void> {
    await this.waitUntilReady();

    if (this.isEndOfData) return;

    if (this.loadingPromise) {
      return this.loadingPromise;
    }

    const { oldestCandle } = this;

    if (!oldestCandle) return;

    const seq = ++this.loadSeq;
    const timeframe = this.getTimeframe();
    const task = this.loadHistoryPage(seq, timeframe, oldestCandle);

    this.loadingPromise = task;

    try {
      await task;
    } finally {
      if (this.loadingPromise === task) {
        this.loadingPromise = null;
      }
    }
  }

  private async loadHistoryPage(seq: number, timeframe: Timeframes, oldestCandle: Candle): Promise<void> {
    this.isLoadingSubject.next(true);

    try {
      const olderData = await this.getData(timeframe, this.symbol, oldestCandle);

      if (seq !== this.loadSeq) return;

      if (olderData === null) {
        this.isEndOfData = true;
        return;
      }

      this.mergeHistoryPage(olderData, timeframe);
    } catch (error) {
      console.error('[DataSource] Ошибка при догрузке истории:', error);
    } finally {
      this.finishLoading(seq);
    }
  }

  private mergeHistoryPage(olderData: Candle[], timeframe: Timeframes): void {
    const older = this.normalizeList(olderData);

    if (older.length === 0) return;

    const current = this.currentDataSubject.value.filter((candle) => candle.open !== undefined);
    const combined = this.normalizeList(older.concat(current));
    const nextOldest = combined[0];

    if (!nextOldest || !this.oldestCandle || nextOldest.time >= this.oldestCandle.time) {
      return;
    }

    this.oldestCandle = nextOldest;
    this.newestCandle = combined[combined.length - 1] ?? this.newestCandle;

    this.currentDataSubject.next(applyWhitespacesToFuture(combined, timeframe));
    this.lastCandleSubject.next(this.newestCandle);

    this.saveRealtimeCache();
  }

  public async loadAllHistory(): Promise<void> {
    await this.waitUntilReady();

    if (this.isEndOfData) return;

    if (this.loadingPromise) {
      await this.loadingPromise;
    }

    const seq = ++this.loadSeq;
    const timeframe = this.getTimeframe();

    const task = (async () => {
      this.isLoadingSubject.next(true);

      try {
        let current = this.currentDataSubject.value.filter((candle) => candle.open !== undefined);
        let oldest = current[0] ?? null;

        if (!oldest) return;

        const seenOldestTimes = new Set<number>();

        while (oldest) {
          if (seq !== this.loadSeq) return;

          if (seenOldestTimes.has(oldest.time)) {
            break;
          }

          seenOldestTimes.add(oldest.time);

          // eslint-disable-next-line no-await-in-loop
          const olderData = await this.getData(timeframe, this.symbol, oldest);

          if (seq !== this.loadSeq) return;

          if (olderData === null) {
            this.isEndOfData = true;
            break;
          }

          const older = this.normalizeList(olderData);

          if (older.length === 0) break;

          const combined = this.normalizeList(older.concat(current));
          const nextOldest = combined[0] ?? null;

          if (!nextOldest || nextOldest.time >= oldest.time) {
            break;
          }

          oldest = nextOldest;
          current = combined;
        }

        this.oldestCandle = current[0] ?? null;
        this.newestCandle = current[current.length - 1] ?? null;

        this.currentDataSubject.next(applyWhitespacesToFuture(current, timeframe));
        this.lastCandleSubject.next(this.newestCandle);

        this.saveRealtimeCache();
      } catch (error) {
        console.error('[DataSource] Ошибка при полной загрузке истории:', error);
      } finally {
        this.finishLoading(seq);
      }
    })();

    this.loadingPromise = task;

    task.finally(() => {
      if (this.loadingPromise === task) {
        this.loadingPromise = null;
      }
    });

    await task;
  }

  public async loadTill(time: number): Promise<void> {
    await this.waitUntilReady();

    while (this.oldestCandle && this.oldestCandle.time >= time) {
      const before = this.oldestCandle.time;

      // eslint-disable-next-line no-await-in-loop
      await this.loadMoreHistory();

      if (!this.oldestCandle) break;
      if (this.oldestCandle.time === before) break;
    }
  }

  public async reload(timeframe: Timeframes): Promise<void> {
    this.loadSeq += 1;

    const seq = this.loadSeq;

    this.isInitializedSubject.next(false);
    this.isLoadingSubject.next(true);

    this.currentDataSubject.next([]);
    this.realtimeCache = [];
    this.realtimeBuffer = [];
    this.oldestCandle = null;
    this.newestCandle = null;
    this.isEndOfData = false;
    this.lastCandleSubject.next(null);

    const task = (async () => {
      try {
        const loaded = (await this.getData(timeframe, this.symbol)) ?? [];

        if (seq !== this.loadSeq) return;

        const normalized = this.normalizeList(loaded);

        this.oldestCandle = normalized[0] ?? null;
        this.newestCandle = normalized[normalized.length - 1] ?? null;

        this.currentDataSubject.next(applyWhitespacesToFuture(normalized, timeframe));
        this.lastCandleSubject.next(this.newestCandle);

        this.isInitializedSubject.next(true);
        this.flushRealtimeBuffer();
      } catch (error) {
        console.error('[DataSource] Ошибка при загрузке данных:', error);
      } finally {
        this.finishLoading(seq);
      }
    })();

    this.loadingPromise = task;

    task.finally(() => {
      if (this.loadingPromise === task) {
        this.loadingPromise = null;
      }
    });

    await task;
  }

  private finishLoading(seq: number): void {
    if (seq === this.loadSeq) {
      this.isLoadingSubject.next(false);
    }
  }

  private flushRealtimeBuffer(): void {
    if (this.realtimeBuffer.length === 0) return;

    const newestTime = this.newestCandle?.time ?? Number.NEGATIVE_INFINITY;

    const bufferedCandles = this.normalizeList(this.realtimeBuffer.filter((candle) => candle.time >= newestTime));

    for (const candle of bufferedCandles) {
      this.realtimeSubject.next(candle);
    }

    this.realtimeBuffer = [];
  }

  private normalizeCandle(candle: Candle): Candle {
    const time = candle.time > 1e10 ? Math.floor(candle.time / 1000) : Math.floor(candle.time);

    if (time === candle.time) {
      return candle;
    }

    return {
      ...candle,
      time,
    };
  }

  private normalizeList(candles: Candle[]): Candle[] {
    return normalizeSeriesData(candles.map((candle) => this.normalizeCandle(candle)));
  }
}

export function applyWhitespacesToFuture(data: Candle[], timeframe: Timeframes): Candle[] {
  const lastCandle = data[data.length - 1];

  if (!lastCandle) {
    return data;
  }

  const { candleWidth, dayjsUnit } = parseTimeframe(timeframe);
  const startTime = dayjs.unix(lastCandle.time).utc();
  const result = data.slice();

  for (let index = 1; index <= FUTURE_WHITESPACES; index += 1) {
    result.push({
      time: startTime.add(candleWidth * index, dayjsUnit).unix(),
    } as Candle);
  }

  return result;
}