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


import { clamp } from 'lodash-es';
import { IPrimitivePaneView, PrimitiveHoveredItem, Time, UTCTimestamp } from 'lightweight-charts';

import {
  CustomPriceAxisPaneView,
  CustomPriceAxisView,
  CustomTimeAxisPaneView,
  CustomTimeAxisView,
} from '@core/Drawings/axis';
import { DrawingBase } from '@core/Drawings/DrawingBase';
import {
  clampPointToContainer as clampPointToContainerInElement,
  getAnchorFromPoint,
  getContainerSize as getElementContainerSize,
  getTimeFromXCoordinate,
  getXCoordinateFromTime,
  getYCoordinateFromPrice,
  isPointInBounds,
} from '@core/Drawings/helpers';
import { updateViews } from '@core/Drawings/utils';

import { Defaults } from '@src/types/defaults';
import { formatPrice } from '@src/utils';
import { formatDate } from '@src/utils/formatter';

import { VolumeProfilePaneView } from './paneView';
import {
  createDefaultSettings,
  getVolumeProfileSettingsTabs,
  VolumeProfileSettings,
  VolumeProfileStyle,
} from './settings';

import type { DrawingHandle } from '@core/Drawings/handles';
import type { Anchor, AxisLabel, AxisSegment, Bounds, Point } from '@core/Drawings/types';
import type { BaseDrawingParams, ISeriesDrawing } from '@core/Drawings/DrawingBase';
import type { ChartOptionsModel, SettingsTab } from '@src/types';

export type VolumeProfileKind = 'fixedRange' | 'visibleRange';

type VolumeProfileMode = 'idle' | 'drawing' | 'ready' | 'dragging';
type DragTarget = 'body' | 'poc' | 'start' | 'end' | null;
type VolumeProfileHandleId = Exclude<DragTarget, 'body' | null>;

interface VolumeProfileParams extends BaseDrawingParams {
  profileKind?: VolumeProfileKind;
}

interface SeriesCandleData {
  time: Time;
  open?: number;
  high?: number;
  low?: number;
  close?: number;
  value?: number;
  volume?: number;
  customValues?: {
    open?: number;
    high?: number;
    low?: number;
    close?: number;
    value?: number;
    volume?: number;
  };
}

export interface VolumeProfileState {
  hidden: boolean;
  mode: VolumeProfileMode;
  startAnchor: Anchor | null;
  endAnchor: Anchor | null;
  visibleRangeStartRatio: number;
  settings: VolumeProfileSettings;
}

interface VolumeProfileDataRow {
  priceLow: number;
  priceHigh: number;
  buyVolume: number;
  sellVolume: number;
  totalVolume: number;
}

interface VolumeProfileGeometry extends Bounds {
  width: number;
  height: number;
  startPoint: Point;
  endPoint: Point;
}

interface VolumeProfileRenderRow {
  top: number;
  height: number;
  buyWidth: number;
  sellWidth: number;
}

export interface VolumeProfileRenderData extends VolumeProfileGeometry, VolumeProfileStyle {
  profileKind: VolumeProfileKind;
  rows: VolumeProfileRenderRow[];
  pocY: number | null;
}

const PROFILE_ROW_COUNT = 24;
const BODY_HIT_TOLERANCE = 4;
const MIN_PROFILE_SIZE = 8;
const MAX_VISIBLE_RANGE_START_RATIO = 0.95;

export class VolumeProfile
  extends DrawingBase<VolumeProfileSettings, VolumeProfileHandleId>
  implements ISeriesDrawing
{
  private removeSelf?: () => void;
  private openSettings?: () => void;

  private readonly profileKind: VolumeProfileKind;

  protected settings: VolumeProfileSettings = createDefaultSettings();
  protected mode: VolumeProfileMode = 'idle';

  private startAnchor: Anchor | null = null;
  private endAnchor: Anchor | null = null;

  private profileRows: VolumeProfileDataRow[] = [];
  private profileMinPrice: number | null = null;
  private profileMaxPrice: number | null = null;
  private visibleRangeStartRatio = 0;

  private activeDragTarget: DragTarget = null;
  private dragPointerId: number | null = null;
  private dragStartPoint: Point | null = null;
  private dragGeometrySnapshot: VolumeProfileGeometry | null = null;

  private displayFormat: ChartOptionsModel = {
    dateFormat: Defaults.dateFormat,
    timeFormat: Defaults.timeFormat,
    showTime: Defaults.showTime,
  };

  private readonly paneView: VolumeProfilePaneView;
  private readonly timeAxisPaneView: CustomTimeAxisPaneView;
  private readonly priceAxisPaneView: CustomPriceAxisPaneView;
  private readonly startTimeAxisView: CustomTimeAxisView;
  private readonly endTimeAxisView: CustomTimeAxisView;
  private readonly startPriceAxisView: CustomPriceAxisView;
  private readonly endPriceAxisView: CustomPriceAxisView;

  constructor({
    chart,
    series,
    container,
    interaction,
    profileKind = 'fixedRange',
    formatObservable,
    removeSelf,
    openSettings,
    initialEvent,
  }: VolumeProfileParams) {
    super({ chart, series, container, interaction });

    this.profileKind = profileKind;
    this.removeSelf = removeSelf;
    this.openSettings = openSettings;

    if (this.profileKind === 'visibleRange') {
      this.mode = 'ready';
    }

    this.paneView = new VolumeProfilePaneView(this);
    this.timeAxisPaneView = this.createTimeAxisPaneView();
    this.priceAxisPaneView = this.createPriceAxisPaneView();
    this.startTimeAxisView = this.createTimeAxisView('start');
    this.endTimeAxisView = this.createTimeAxisView('end');
    this.startPriceAxisView = this.createPriceAxisView('start');
    this.endPriceAxisView = this.createPriceAxisView('end');

    this.subscribeFormat(formatObservable, (format) => {
      this.displayFormat = format;
    });

    if (this.profileKind === 'visibleRange') {
      this.chart.timeScale().subscribeVisibleLogicalRangeChange(this.handleVisibleLogicalRangeChange);
      this.calculateProfile();
    }

    this.series.attachPrimitive(this);

    if (initialEvent?.sourceEvent) {
      this.applyInitialPoint(this.getEventPoint(initialEvent.sourceEvent));
    }
  }

  public destroy(): void {
    if (this.profileKind === 'visibleRange') {
      this.chart.timeScale().unsubscribeVisibleLogicalRangeChange(this.handleVisibleLogicalRangeChange);
    }

    super.destroy();
  }

  public isCreationPending(): boolean {
    if (this.profileKind === 'visibleRange') {
      return false;
    }

    return this.mode === 'idle' || this.mode === 'drawing';
  }

  public shouldShowInObjectTree(): boolean {
    if (this.profileKind === 'visibleRange') {
      return true;
    }

    return super.shouldShowInObjectTree();
  }

  public getState(): VolumeProfileState {
    return {
      hidden: this.hidden,
      mode: this.mode,
      startAnchor: this.startAnchor,
      endAnchor: this.endAnchor,
      visibleRangeStartRatio: this.visibleRangeStartRatio,
      settings: { ...this.settings },
    };
  }

  public setState(state: unknown): void {
    if (!state || typeof state !== 'object') {
      return;
    }

    const nextState = state as Partial<VolumeProfileState>;

    this.hidden = typeof nextState.hidden === 'boolean' ? nextState.hidden : this.hidden;

    if (this.profileKind === 'fixedRange') {
      this.mode = nextState.mode ?? this.mode;

      if ('startAnchor' in nextState) {
        this.startAnchor = nextState.startAnchor ?? null;
      }

      if ('endAnchor' in nextState) {
        this.endAnchor = nextState.endAnchor ?? null;
      }
    }

    if (this.profileKind === 'visibleRange') {
      this.mode = 'ready';
      this.resolveReady?.();

      if (typeof nextState.visibleRangeStartRatio === 'number') {
        this.visibleRangeStartRatio = clamp(
          nextState.visibleRangeStartRatio,
          0,
          MAX_VISIBLE_RANGE_START_RATIO,
        );
      }
    }

    if ('settings' in nextState && nextState.settings) {
      this.settings = {
        ...createDefaultSettings(),
        ...nextState.settings,
      };
    }

    this.calculateProfile();
    this.render();
  }

  public getSettingsTabs(): SettingsTab[] {
    return getVolumeProfileSettingsTabs(this.settings);
  }

  public updateAllViews(): void {
    updateViews([
      this.paneView,
      this.timeAxisPaneView,
      this.priceAxisPaneView,
      this.startTimeAxisView,
      this.endTimeAxisView,
      this.startPriceAxisView,
      this.endPriceAxisView,
    ]);
  }

  public paneViews(): readonly IPrimitivePaneView[] {
    return [this.paneView];
  }

  public timeAxisPaneViews(): readonly IPrimitivePaneView[] {
    return this.profileKind === 'visibleRange' ? [] : [this.timeAxisPaneView];
  }

  public priceAxisPaneViews(): readonly IPrimitivePaneView[] {
    return this.profileKind === 'visibleRange' ? [] : [this.priceAxisPaneView];
  }

  public timeAxisViews() {
    return this.profileKind === 'visibleRange'
      ? [this.startTimeAxisView]
      : [this.startTimeAxisView, this.endTimeAxisView];
  }

  public priceAxisViews() {
    return this.profileKind === 'visibleRange'
      ? []
      : [this.startPriceAxisView, this.endPriceAxisView];
  }

  public getRenderData(): VolumeProfileRenderData | null {
    if (this.hidden) {
      return null;
    }

    const geometry = this.getGeometry();

    if (!geometry) {
      return null;
    }

    const { rows, pocY } = this.getProfileRenderRows(geometry);

    return {
      ...geometry,
      profileKind: this.profileKind,
      rows,
      pocY,
      ...this.settings,
    };
  }

  protected getDrawingHandles(): readonly DrawingHandle<VolumeProfileHandleId>[] {
    const geometry = this.getGeometry();

    if (!geometry) {
      return [];
    }

    if (this.profileKind === 'visibleRange') {
      const pocY = this.getPocY(geometry);

      return pocY === null
        ? []
        : [{ id: 'poc', x: geometry.left, y: pocY, shape: 'circle' }];
    }

    return [
      { id: 'end', ...geometry.endPoint, shape: 'circle' },
      { id: 'start', ...geometry.startPoint, shape: 'circle' },
    ];
  }

  protected getTimeAxisSegments(): AxisSegment[] {
    if (this.profileKind === 'visibleRange' || !this.shouldShowInteractiveAxis()) {
      return [];
    }

    const geometry = this.getGeometry();

    return geometry ? [this.createAxisSegment(geometry.left, geometry.right)] : [];
  }

  protected getPriceAxisSegments(): AxisSegment[] {
    if (this.profileKind === 'visibleRange' || !this.shouldShowInteractiveAxis()) {
      return [];
    }

    const geometry = this.getGeometry();

    return geometry ? [this.createAxisSegment(geometry.top, geometry.bottom)] : [];
  }

  protected getHoveredItem(x: number, y: number): PrimitiveHoveredItem | null {
    if (this.hidden || this.mode === 'idle' || this.mode === 'drawing') {
      return null;
    }

    const dragTarget = this.getDragTarget({ x, y });

    if (!dragTarget) {
      return null;
    }

    if (dragTarget === 'poc') {
      return {
        cursorStyle: 'ew-resize',
        externalId: 'volume-profile',
        zOrder: 'top',
      };
    }

    return {
      cursorStyle: this.isSelected() ? 'grab' : 'pointer',
      externalId: 'volume-profile',
      zOrder: 'top',
    };
  }

  protected getTimeAxisLabel(kind: string): AxisLabel | null {
    if (!this.shouldShowInteractiveAxis()) {
      return null;
    }

    if (this.profileKind === 'visibleRange') {
      if (kind !== 'start') {
        return null;
      }

      const geometry = this.getGeometry();

      if (!geometry) {
        return null;
      }

      const time = getTimeFromXCoordinate(this.chart, geometry.left);

      if (typeof time !== 'number') {
        return null;
      }

      return this.createAxisLabel(
        geometry.left,
        this.formatTime(time),
      );
    }

    if (kind !== 'start' && kind !== 'end') {
      return null;
    }

    const anchor = kind === 'start' ? this.startAnchor : this.endAnchor;

    if (!anchor || typeof anchor.time !== 'number') {
      return null;
    }

    const coordinate = getXCoordinateFromTime(this.chart, anchor.time, this.series);

    return this.createAxisLabel(
      coordinate === null ? null : Number(coordinate),
      this.formatTime(anchor.time),
    );
  }

  protected getPriceAxisLabel(kind: string): AxisLabel | null {
    if (
      this.profileKind === 'visibleRange' ||
      !this.shouldShowInteractiveAxis() ||
      (kind !== 'start' && kind !== 'end')
    ) {
      return null;
    }

    // const anchor = kind === 'start' ? this.startAnchor : this.endAnchor;
    const price = kind === 'start' ? this.profileMinPrice : this.profileMaxPrice;

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

    const coordinate = getYCoordinateFromPrice(this.series, price);

    return this.createAxisLabel(
      coordinate === null ? null : Number(coordinate),
      formatPrice(price) ?? '',
    );
  }

  protected handleDoubleClick = (event: MouseEvent): void => {
    if (this.hidden || this.mode !== 'ready' || !this.isSelected()) {
      return;
    }

    const point = this.getEventPoint(event as PointerEvent);

    if (!this.getDragTarget(point)) {
      return;
    }

    event.preventDefault();
    event.stopPropagation();
    this.openSettings?.();
  };

  protected handlePointerDown = (event: PointerEvent): void => {
    if (this.hidden || event.button !== 0) {
      return;
    }

    const point = this.getEventPoint(event);

    if (this.profileKind === 'visibleRange') {
      this.handleVisibleRangePointerDown(event, point);
      return;
    }

    this.handleFixedRangePointerDown(event, point);
  };

  protected handlePointerMove = (event: PointerEvent): void => {
    const point = this.getEventPoint(event);

    if (this.profileKind === 'visibleRange') {
      this.handleVisibleRangePointerMove(event, point);
      return;
    }

    this.handleFixedRangePointerMove(event, point);
  };

  protected handlePointerUp = (event: PointerEvent): void => {
    if (this.mode !== 'dragging' || this.dragPointerId !== event.pointerId) {
      return;
    }

    this.finishDragging();
  };

  protected getGeometry(): VolumeProfileGeometry | null {
    return this.profileKind === 'visibleRange'
      ? this.getAnchoredVolumeProfileGeometry()
      : this.getFixedRangeVolumeProfileGeometry();
  }

  private handleVisibleLogicalRangeChange = (): void => {
    if (this.profileKind !== 'visibleRange') {
      return;
    }

    this.calculateProfile();
    this.render();
  };

  private handleVisibleRangePointerDown(event: PointerEvent, point: Point): void {
    let dragTarget = this.getVisibleRangeDragTarget(point);

    if (!dragTarget) {
      if (this.isSelected()) {
        this.deselect();
      }

      return;
    }

    event.preventDefault();
    event.stopPropagation();

    if (!this.isSelected()) {
      this.select();
      dragTarget = this.getVisibleRangeDragTarget(point);
    }

    if (dragTarget !== 'poc') {
      return;
    }

    this.activeDragTarget = 'poc';
    this.dragPointerId = event.pointerId;
    this.mode = 'dragging';

    this.hideCrosshair();
    this.render();
  }

  private handleFixedRangePointerDown(event: PointerEvent, point: Point): void {
    if (this.mode === 'idle') {
      event.preventDefault();
      event.stopPropagation();
      this.startDrawing(point);
      return;
    }

    if (this.mode === 'drawing') {
      event.preventDefault();
      event.stopPropagation();
      this.updateDrawing(point);
      this.finishDrawing();
      return;
    }

    if (this.mode !== 'ready') {
      return;
    }

    const dragTarget = this.getFixedRangeDragTarget(point);

    if (!this.isSelected()) {
      if (!dragTarget) {
        return;
      }

      event.preventDefault();
      event.stopPropagation();
      this.select();
      return;
    }

    if (!dragTarget) {
      this.deselect();
      return;
    }

    event.preventDefault();
    event.stopPropagation();
    this.startDragging(point, event.pointerId, dragTarget);
  }

  private handleVisibleRangePointerMove(event: PointerEvent, point: Point): void {
    if (
      this.mode !== 'dragging' ||
      this.dragPointerId !== event.pointerId ||
      this.activeDragTarget !== 'poc'
    ) {
      return;
    }

    event.preventDefault();

    this.moveVisibleRangeStart(point);
    this.calculateProfile();
    this.render();
  }

  private handleFixedRangePointerMove(event: PointerEvent, point: Point): void {
    if (this.mode === 'drawing') {
      this.updateDrawing(point);
      return;
    }

    if (this.mode !== 'dragging' || this.dragPointerId !== event.pointerId) {
      return;
    }

    event.preventDefault();

    if (this.activeDragTarget === 'body') {
      this.moveBody(point);
      this.render();
      return;
    }

    this.moveHandle(point);
    this.render();
  }

  private applyInitialPoint(point: Point): void {
    if (this.profileKind === 'visibleRange') {
      this.moveVisibleRangeStart(point);
      this.calculateProfile();
      this.render();
      return;
    }

    this.startDrawing(point);
  }

  private startDrawing(point: Point): void {
    const anchor = this.createAnchor(this.clampPointToContainer(point));

    if (!anchor) {
      return;
    }

    this.startAnchor = anchor;
    this.endAnchor = anchor;
    this.mode = 'drawing';

    this.calculateProfile();
    this.render();
  }

  private updateDrawing(point: Point): void {
    const anchor = this.createAnchor(this.clampPointToContainer(point));

    if (!anchor) {
      return;
    }

    this.endAnchor = anchor;

    this.calculateProfile();
    this.render();
  }

  private finishDrawing(): void {
    const geometry = this.getGeometry();

    if (
      this.profileKind === 'fixedRange' &&
      (!geometry || geometry.width < MIN_PROFILE_SIZE || geometry.height < MIN_PROFILE_SIZE)
    ) {
      if (this.removeSelf) {
        this.removeSelf();
        return;
      }

      this.resetToIdle();
      return;
    }

    this.mode = 'ready';
    this.resolveReady?.();

    this.showCrosshair();
    this.render();
  }

  private startDragging(
    point: Point,
    pointerId: number,
    dragTarget: Exclude<DragTarget, null>,
  ): void {
    this.mode = 'dragging';
    this.activeDragTarget = dragTarget;
    this.dragPointerId = pointerId;
    this.dragStartPoint = point;
    this.dragGeometrySnapshot = this.getGeometry();

    this.hideCrosshair();
    this.render();
  }

  private finishDragging(): void {
    this.mode = 'ready';
    this.activeDragTarget = null;
    this.dragPointerId = null;
    this.dragStartPoint = null;
    this.dragGeometrySnapshot = null;

    this.showCrosshair();
    this.render();
  }

  private resetToIdle(): void {
    this.hidden = false;
    this.mode = 'idle';

    this.startAnchor = null;
    this.endAnchor = null;

    this.clearProfile();

    this.activeDragTarget = null;
    this.dragPointerId = null;
    this.dragStartPoint = null;
    this.dragGeometrySnapshot = null;

    this.showCrosshair();
    this.render();
  }

  private moveVisibleRangeStart(point: Point): void {
    const { width } = this.getContainerSize();

    if (width <= 0) {
      return;
    }

    this.visibleRangeStartRatio = clamp(
      point.x / width,
      0,
      MAX_VISIBLE_RANGE_START_RATIO,
    );
  }

  private moveHandle(point: Point): void {
    if (
      !this.activeDragTarget ||
      this.activeDragTarget === 'body' ||
      this.activeDragTarget === 'poc'
    ) {
      return;
    }

    const anchor = this.createAnchor(this.clampPointToContainer(point));

    if (!anchor) {
      return;
    }

    if (this.activeDragTarget === 'start') {
      this.startAnchor = anchor;
    }

    if (this.activeDragTarget === 'end') {
      this.endAnchor = anchor;
    }

    this.calculateProfile();
  }

  private moveBody(point: Point): void {
    const geometry = this.dragGeometrySnapshot;
    const dragStartPoint = this.dragStartPoint;

    if (!geometry || !dragStartPoint) {
      return;
    }

    const { width, height } = this.getContainerSize();
    const rawOffsetX = point.x - dragStartPoint.x;
    const rawOffsetY = point.y - dragStartPoint.y;
    const offsetX = clamp(rawOffsetX, -geometry.left, width - geometry.right);
    const offsetY = clamp(rawOffsetY, -geometry.top, height - geometry.bottom);

    this.setAnchorsFromPoints(
      {
        x: geometry.startPoint.x + offsetX,
        y: geometry.startPoint.y + offsetY,
      },
      {
        x: geometry.endPoint.x + offsetX,
        y: geometry.endPoint.y + offsetY,
      },
    );
  }

  private setAnchorsFromPoints(startPoint: Point, endPoint: Point): void {
    const startAnchor = this.createAnchor(this.clampPointToContainer(startPoint));
    const endAnchor = this.createAnchor(this.clampPointToContainer(endPoint));

    if (!startAnchor || !endAnchor) {
      return;
    }

    this.startAnchor = startAnchor;
    this.endAnchor = endAnchor;

    this.calculateProfile();
  }

  private getDragTarget(point: Point): Exclude<DragTarget, null> | null {
    return this.profileKind === 'visibleRange'
      ? this.getVisibleRangeDragTarget(point)
      : this.getFixedRangeDragTarget(point);
  }

  private getVisibleRangeDragTarget(point: Point): Exclude<DragTarget, null> | null {
    const handle = this.getDrawingHandleAtPoint(point);

    if (handle?.id === 'poc') {
      return 'poc';
    }

    return this.containsPoint(point) ? 'body' : null;
  }

  private getFixedRangeDragTarget(point: Point): Exclude<DragTarget, null> | null {
    const handle = this.getDrawingHandleAtPoint(point);

    if (handle) {
      return handle.id;
    }

    return this.containsPoint(point) ? 'body' : null;
  }

  private containsPoint(point: Point): boolean {
    const geometry = this.getGeometry();

    return geometry !== null && isPointInBounds(point, geometry, BODY_HIT_TOLERANCE);
  }

  private calculateProfile(): void {
    if (this.profileKind === 'visibleRange') {
      this.calculateAnchoredVolumeProfile();
      return;
    }

    this.calculateFixedRangeVolumeProfile();
  }

  private calculateAnchoredVolumeProfile(): void {
    const visibleRange = this.chart.timeScale().getVisibleLogicalRange();

    if (!visibleRange) {
      this.clearProfile();
      return;
    }

    const from = Number(visibleRange.from);
    const to = Number(visibleRange.to);
    const start = from + (to - from) * this.visibleRangeStartRatio;

    this.calculateProfileByLogicalRange(start, to);
  }

  private calculateFixedRangeVolumeProfile(): void {
    if (!this.startAnchor || !this.endAnchor) {
      this.clearProfile();
      return;
    }

    const leftFrameTime = Math.min(
      Number(this.startAnchor.time),
      Number(this.endAnchor.time),
    );
    const rightFrameTime = Math.max(
      Number(this.startAnchor.time),
      Number(this.endAnchor.time),
    );

    const candles = this.series.data() as SeriesCandleData[];
    const selectedCandles = candles.filter((candle) => {
      const candleTime = Number(candle.time);

      return candleTime >= leftFrameTime && candleTime <= rightFrameTime;
    });

    this.calculateProfileByCandles(selectedCandles);
  }

  private calculateProfileByLogicalRange(fromLogical: number, toLogical: number): void {
    const candles = this.series.data() as SeriesCandleData[];

    if (!candles.length) {
      this.clearProfile();
      return;
    }

    const fromIndex = Math.max(0, Math.floor(Math.min(fromLogical, toLogical)));
    const toIndex = Math.min(
      candles.length - 1,
      Math.ceil(Math.max(fromLogical, toLogical)),
    );

    if (fromIndex > toIndex) {
      this.clearProfile();
      return;
    }

    this.calculateProfileByCandles(candles.slice(fromIndex, toIndex + 1));
  }

  private calculateProfileByCandles(
    candles: SeriesCandleData[],
    fixedMinPrice?: number,
    fixedMaxPrice?: number,
  ): void {
    if (!candles.length && (fixedMinPrice === undefined || fixedMaxPrice === undefined)) {
      this.clearProfile();
      return;
    }

    let minPrice = fixedMinPrice ?? Infinity;
    let maxPrice = fixedMaxPrice ?? -Infinity;

    if (fixedMinPrice === undefined || fixedMaxPrice === undefined) {
      candles.forEach((candle) => {
        const price = this.getCandlePrice(candle);

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

        minPrice = Math.min(minPrice, this.getCandleLow(candle, price));
        maxPrice = Math.max(maxPrice, this.getCandleHigh(candle, price));
      });
    }

    if (!Number.isFinite(minPrice) || !Number.isFinite(maxPrice)) {
      this.clearProfile();
      return;
    }

    if (minPrice === maxPrice) {
      maxPrice = minPrice + Math.max(Math.abs(minPrice) * 0.001, 1);
    }

    this.profileMinPrice = minPrice;
    this.profileMaxPrice = maxPrice;

    const priceStep = (maxPrice - minPrice) / PROFILE_ROW_COUNT;
    const profileRows = this.createEmptyProfileRows(minPrice, priceStep);

    candles.forEach((candle) => {
      const volume = this.getCandleVolume(candle);

      if (volume <= 0) {
        return;
      }

      const price = this.getCandlePrice(candle);

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

      const candleHigh = this.getCandleHigh(candle, price);
      const candleLow = this.getCandleLow(candle, price);

      if (candleHigh < minPrice || candleLow > maxPrice) {
        return;
      }

      const isBuyVolume = this.isBuyVolume(candle);

      if (candleHigh === candleLow) {
        addPointVolume(profileRows, candleHigh, volume, isBuyVolume);
        return;
      }

      const highInRange = Math.min(maxPrice, candleHigh);
      const lowInRange = Math.max(minPrice, candleLow);
      const candleRange = candleHigh - candleLow;

      profileRows.forEach((row) => {
        const overlap = Math.max(
          0,
          Math.min(row.priceHigh, highInRange) - Math.max(row.priceLow, lowInRange),
        );

        if (overlap <= 0) {
          return;
        }

        addVolumeToRow(row, volume * (overlap / candleRange), isBuyVolume);
      });
    });

    this.profileRows = profileRows;
  }

  private createEmptyProfileRows(
    minPrice: number,
    priceStep: number,
  ): VolumeProfileDataRow[] {
    const rows: VolumeProfileDataRow[] = [];

    for (let index = 0; index < PROFILE_ROW_COUNT; index += 1) {
      rows.push({
        priceLow: minPrice + priceStep * index,
        priceHigh: minPrice + priceStep * (index + 1),
        buyVolume: 0,
        sellVolume: 0,
        totalVolume: 0,
      });
    }

    return rows;
  }

  private clearProfile(): void {
    this.profileRows = [];
    this.profileMinPrice = null;
    this.profileMaxPrice = null;
  }

  private getCandleVolume(candle: SeriesCandleData): number {
    return this.getNumber(candle.customValues?.volume) ?? this.getNumber(candle.volume) ?? 0;
  }

  private getCandlePrice(candle: SeriesCandleData): number | null {
    return (
      this.getNumber(candle.close) ??
      this.getNumber(candle.customValues?.close) ??
      this.getNumber(candle.value) ??
      this.getNumber(candle.customValues?.value)
    );
  }

  private getCandleOpen(candle: SeriesCandleData): number | null {
    return this.getNumber(candle.open) ?? this.getNumber(candle.customValues?.open);
  }

  private getCandleClose(candle: SeriesCandleData): number | null {
    return (
      this.getNumber(candle.close) ??
      this.getNumber(candle.customValues?.close) ??
      this.getNumber(candle.value) ??
      this.getNumber(candle.customValues?.value)
    );
  }

  private getCandleHigh(candle: SeriesCandleData, fallbackPrice: number): number {
    return this.getNumber(candle.high) ?? this.getNumber(candle.customValues?.high) ?? fallbackPrice;
  }

  private getCandleLow(candle: SeriesCandleData, fallbackPrice: number): number {
    return this.getNumber(candle.low) ?? this.getNumber(candle.customValues?.low) ?? fallbackPrice;
  }

  private isBuyVolume(candle: SeriesCandleData): boolean {
    const open = this.getCandleOpen(candle);
    const close = this.getCandleClose(candle);

    if (open === null || close === null) {
      return true;
    }

    return close >= open;
  }

  private getNumber(value: unknown): number | null {
    return typeof value === 'number' && Number.isFinite(value) ? value : null;
  }

  private getAnchoredVolumeProfileGeometry(): VolumeProfileGeometry | null {
    if (this.profileMinPrice === null || this.profileMaxPrice === null) {
      return null;
    }

    const { width, height } = this.getContainerSize();
    const topCoordinate = getYCoordinateFromPrice(this.series, this.profileMaxPrice);
    const bottomCoordinate = getYCoordinateFromPrice(this.series, this.profileMinPrice);

    if (topCoordinate === null || bottomCoordinate === null) {
      return null;
    }

    const left = clamp(Math.round(width * this.visibleRangeStartRatio), 0, width);
    const right = width;
    const top = clamp(
      Math.round(Math.min(Number(topCoordinate), Number(bottomCoordinate))),
      0,
      height,
    );
    const bottom = clamp(
      Math.round(Math.max(Number(topCoordinate), Number(bottomCoordinate))),
      0,
      height,
    );

    return {
      startPoint: { x: left, y: top },
      endPoint: { x: right, y: bottom },
      left,
      right,
      top,
      bottom,
      width: right - left,
      height: bottom - top,
    };
  }

  private getFixedRangeVolumeProfileGeometry(): VolumeProfileGeometry | null {
    if (
      !this.startAnchor ||
      !this.endAnchor ||
      this.profileMinPrice === null ||
      this.profileMaxPrice === null
    ) {
      return null;
    }

    const startX = getXCoordinateFromTime(this.chart, this.startAnchor.time, this.series);
    const endX = getXCoordinateFromTime(this.chart, this.endAnchor.time, this.series);
    const startY = getYCoordinateFromPrice(this.series, this.profileMinPrice);
    const endY = getYCoordinateFromPrice(this.series, this.profileMaxPrice);

    if (startX === null || endX === null || startY === null || endY === null) {
      return null;
    }

    const { width, height } = this.getContainerSize();

    const startPoint = {
      x: clamp(Math.round(Number(startX)), 0, width),
      y: clamp(Math.round(Number(startY)), 0, height),
    };

    const endPoint = {
      x: clamp(Math.round(Number(endX)), 0, width),
      y: clamp(Math.round(Number(endY)), 0, height),
    };

    const left = Math.min(startPoint.x, endPoint.x);
    const right = Math.max(startPoint.x, endPoint.x);
    const top = Math.min(startPoint.y, endPoint.y);
    const bottom = Math.max(startPoint.y, endPoint.y);

    return {
      startPoint,
      endPoint,
      left,
      right,
      top,
      bottom,
      width: right - left,
      height: bottom - top,
    };
  }

  private getPocY(geometry: VolumeProfileGeometry): number | null {
    return this.getProfileRenderRows(geometry).pocY;
  }

  private getProfileRenderRows(geometry: VolumeProfileGeometry): {
    rows: VolumeProfileRenderRow[];
    pocY: number | null;
  } {
    if (!this.profileRows.length) {
      return {
        rows: [],
        pocY: null,
      };
    }

    const maxVolume = this.profileRows.reduce(
      (max, row) => Math.max(max, row.totalVolume),
      0,
    );

    if (maxVolume <= 0) {
      return {
        rows: [],
        pocY: null,
      };
    }

    let pocY: number | null = null;
    let pocVolume = 0;

    const rows = this.profileRows
      .map((row) => {
        const highY = getYCoordinateFromPrice(this.series, row.priceHigh);
        const lowY = getYCoordinateFromPrice(this.series, row.priceLow);

        if (highY === null || lowY === null) {
          return null;
        }

        const top = clamp(
          Math.min(Number(highY), Number(lowY)),
          geometry.top,
          geometry.bottom,
        );
        const bottom = clamp(
          Math.max(Number(highY), Number(lowY)),
          geometry.top,
          geometry.bottom,
        );

        if (row.totalVolume > pocVolume) {
          pocVolume = row.totalVolume;
          pocY = (top + bottom) / 2;
        }

        return {
          top,
          height: Math.max(1, bottom - top),
          buyWidth: (geometry.width * row.buyVolume) / maxVolume,
          sellWidth: (geometry.width * row.sellVolume) / maxVolume,
        };
      })
      .filter((row): row is VolumeProfileRenderRow => row !== null);

    return {
      rows,
      pocY,
    };
  }

  private formatTime(time: number): string {
    return formatDate(
      time as UTCTimestamp,
      this.displayFormat.dateFormat,
      this.displayFormat.timeFormat,
      this.displayFormat.showTime,
    );
  }

  private createAnchor(point: Point): Anchor | null {
    return getAnchorFromPoint(this.chart, this.series, point);
  }

  private getContainerSize(): { width: number; height: number } {
    return getElementContainerSize(this.container);
  }

  private clampPointToContainer(point: Point): Point {
    return clampPointToContainerInElement(point, this.container);
  }
}

function addPointVolume(
  profileRows: VolumeProfileDataRow[],
  price: number,
  volume: number,
  isBuyVolume: boolean,
): void {
  const row = profileRows.find((item, index) => {
    const isLastRow = index === profileRows.length - 1;

    return price >= item.priceLow && (price < item.priceHigh || isLastRow);
  });

  if (!row) {
    return;
  }

  addVolumeToRow(row, volume, isBuyVolume);
}

function addVolumeToRow(
  row: VolumeProfileDataRow,
  volume: number,
  isBuyVolume: boolean,
): void {
  if (isBuyVolume) {
    row.buyVolume += volume;
  } else {
    row.sellVolume += volume;
  }

  row.totalVolume += volume;
}

















import {
  CustomPriceAxisPaneView,
  CustomPriceAxisView,
  CustomTimeAxisPaneView,
  CustomTimeAxisView,
} from '@core/Drawings/axis';
import { DrawingBase } from '@core/Drawings/DrawingBase';
import {
  getTimeFromXCoordinate,
  getXCoordinateFromTime,
  getYCoordinateFromPrice,
} from '@core/Drawings/helpers';
import { getDistanceToSegment, updateViews } from '@core/Drawings/utils';

import { Defaults } from '@src/types/defaults';
import { formatPrice } from '@src/utils';
import { formatDate } from '@src/utils/formatter';

import { RegressionTrendPaneView } from './paneView';
import {
  createDefaultSettings,
  getRegressionTrendSettingsTabs,
  RegressionTrendSettings,
  RegressionTrendStyle,
} from './settings';

import type { DrawingHandle } from '@core/Drawings/handles';
import type { AxisLabel, AxisSegment, Point } from '@core/Drawings/types';
import type { BaseDrawingParams, ISeriesDrawing } from '@core/Drawings/DrawingBase';
import type { ChartOptionsModel, SettingsTab } from '@src/types';
import type { IPrimitivePaneView, PrimitiveHoveredItem, Time, UTCTimestamp } from 'lightweight-charts';

type RegressionTrendMode = 'idle' | 'drawing' | 'ready' | 'dragging';
type DragTarget = 'start' | 'end' | 'body' | null;
type RegressionTrendHandleKey = Exclude<DragTarget, 'body' | null>;
type TimeLabelKind = 'start' | 'end';
type PriceLabelKind = 'start' | 'end';

type RegressionTrendParams = BaseDrawingParams;

interface RegressionTrendState {
  hidden: boolean;
  mode: RegressionTrendMode;
  startTime: Time | null;
  endTime: Time | null;
  settings: RegressionTrendSettings;
}

interface RegressionSeriesData {
  time: Time;
  close?: number;
  value?: number;
}

interface RegressionResult {
  baseStartPrice: number;
  baseEndPrice: number;
  upperStartPrice: number;
  upperEndPrice: number;
  lowerStartPrice: number;
  lowerEndPrice: number;
  correlation: number;
}

interface RegressionTrendGeometry {
  baseStartPoint: Point;
  baseEndPoint: Point;
  upperStartPoint: Point;
  upperEndPoint: Point;
  lowerStartPoint: Point;
  lowerEndPoint: Point;
  baseStartPrice: number;
  baseEndPrice: number;
  correlation: number;
  left: number;
  right: number;
  top: number;
  bottom: number;
}

export interface RegressionTrendRenderData
  extends RegressionTrendGeometry,
    RegressionTrendStyle {
  showChannel: boolean;
}

const LINE_HIT_TOLERANCE = 8;
const MIN_BAR_DISTANCE = 1;
const REGRESSION_DEVIATION = 2;

export class RegressionTrend
  extends DrawingBase<RegressionTrendSettings, RegressionTrendHandleKey>
  implements ISeriesDrawing
{
  private openSettings?: () => void;

  protected settings: RegressionTrendSettings = createDefaultSettings();
  protected mode: RegressionTrendMode = 'idle';

  private startTime: Time | null = null;
  private endTime: Time | null = null;

  private activeDragTarget: DragTarget = null;
  private dragPointerId: number | null = null;
  private dragStartPoint: Point | null = null;
  private dragStateSnapshot: RegressionTrendState | null = null;

  private displayFormat: ChartOptionsModel = {
    dateFormat: Defaults.dateFormat,
    timeFormat: Defaults.timeFormat,
    showTime: Defaults.showTime,
  };

  private readonly paneView: RegressionTrendPaneView;
  private readonly timeAxisPaneView: CustomTimeAxisPaneView;
  private readonly priceAxisPaneView: CustomPriceAxisPaneView;
  private readonly startTimeAxisView: CustomTimeAxisView;
  private readonly endTimeAxisView: CustomTimeAxisView;
  private readonly startPriceAxisView: CustomPriceAxisView;
  private readonly endPriceAxisView: CustomPriceAxisView;

  constructor({
    chart,
    series,
    container,
    interaction,
    formatObservable,
    openSettings,
    initialEvent,
  }: RegressionTrendParams) {
    super({ chart, series, container, interaction });

    this.openSettings = openSettings;

    this.paneView = new RegressionTrendPaneView(this);
    this.timeAxisPaneView = this.createTimeAxisPaneView();
    this.priceAxisPaneView = this.createPriceAxisPaneView();
    this.startTimeAxisView = this.createTimeAxisView('start');
    this.endTimeAxisView = this.createTimeAxisView('end');
    this.startPriceAxisView = this.createPriceAxisView('start');
    this.endPriceAxisView = this.createPriceAxisView('end');

    this.subscribeFormat(formatObservable, (format) => {
      this.displayFormat = format;
    });

    this.series.attachPrimitive(this);

    if (initialEvent?.sourceEvent) {
      this.startDrawing(this.getEventPoint(initialEvent.sourceEvent));
    }
  }

  public isCreationPending(): boolean {
    return this.mode === 'idle' || this.mode === 'drawing';
  }

  public getState(): RegressionTrendState {
    return {
      hidden: this.hidden,
      mode: this.mode,
      startTime: this.startTime,
      endTime: this.endTime,
      settings: { ...this.settings },
    };
  }

  public setState(state: unknown): void {
    if (!state || typeof state !== 'object') {
      return;
    }

    const nextState = state as Partial<RegressionTrendState>;

    this.hidden = nextState.hidden ?? this.hidden;

    if (nextState.mode) {
      this.mode = nextState.mode === 'dragging' ? 'ready' : nextState.mode;
    }

    if ('startTime' in nextState) {
      this.startTime = nextState.startTime ?? null;
    }

    if ('endTime' in nextState) {
      this.endTime = nextState.endTime ?? null;
    }

    if (nextState.settings) {
      this.settings = {
        ...createDefaultSettings(),
        ...nextState.settings,
      };
    }

    this.render();
  }

  public getSettingsTabs(): SettingsTab[] {
    return getRegressionTrendSettingsTabs(this.settings);
  }

  public updateAllViews(): void {
    updateViews([
      this.paneView,
      this.timeAxisPaneView,
      this.priceAxisPaneView,
      this.startTimeAxisView,
      this.endTimeAxisView,
      this.startPriceAxisView,
      this.endPriceAxisView,
    ]);
  }

  public paneViews(): readonly IPrimitivePaneView[] {
    return [this.paneView];
  }

  public timeAxisPaneViews(): readonly IPrimitivePaneView[] {
    return [this.timeAxisPaneView];
  }

  public priceAxisPaneViews(): readonly IPrimitivePaneView[] {
    return [this.priceAxisPaneView];
  }

  public timeAxisViews() {
    return [this.startTimeAxisView, this.endTimeAxisView];
  }

  public priceAxisViews() {
    return [this.startPriceAxisView, this.endPriceAxisView];
  }

  public getRenderData(): RegressionTrendRenderData | null {
    if (this.hidden) {
      return null;
    }

    const geometry = this.getGeometry();

    if (!geometry) {
      return null;
    }

    return {
      ...geometry,
      ...this.settings,
      showChannel: this.mode === 'ready' || this.mode === 'dragging',
    };
  }

  protected getDrawingHandles(): readonly DrawingHandle<RegressionTrendHandleKey>[] {
    const geometry = this.getGeometry();

    if (!geometry) {
      return [];
    }

    return [
      {
        id: 'start',
        ...geometry.baseStartPoint,
        shape: 'circle',
      },
      {
        id: 'end',
        ...geometry.baseEndPoint,
        shape: 'circle',
      },
    ];
  }

  protected getHoveredItem(x: number, y: number): PrimitiveHoveredItem | null {
    if (this.hidden || this.mode !== 'ready') {
      return null;
    }

    const point = { x, y };

    if (!this.isSelected()) {
      if (!this.containsPoint(point)) {
        return null;
      }

      return {
        cursorStyle: 'pointer',
        externalId: 'regression-trend',
        zOrder: 'top',
      };
    }

    const dragTarget = this.getDragTarget(point);

    if (!dragTarget) {
      return null;
    }

    return {
      cursorStyle: dragTarget === 'body' ? 'grab' : 'ew-resize',
      externalId: 'regression-trend',
      zOrder: 'top',
    };
  }

  protected getTimeAxisSegments(): AxisSegment[] {
    if (!this.shouldShowInteractiveAxis()) {
      return [];
    }

    const geometry = this.getGeometry();

    return geometry ? [this.createAxisSegment(geometry.left, geometry.right)] : [];
  }

  protected getPriceAxisSegments(): AxisSegment[] {
    if (!this.shouldShowInteractiveAxis()) {
      return [];
    }

    const geometry = this.getGeometry();

    if (!geometry) {
      return [];
    }

    return [
      this.createAxisSegment(
        Math.min(geometry.baseStartPoint.y, geometry.baseEndPoint.y),
        Math.max(geometry.baseStartPoint.y, geometry.baseEndPoint.y),
      ),
    ];
  }

  protected getTimeAxisLabel(kind: string): AxisLabel | null {
    if (!this.shouldShowInteractiveAxis() || (kind !== 'start' && kind !== 'end')) {
      return null;
    }

    const labelKind = kind as TimeLabelKind;
    const time = labelKind === 'start' ? this.startTime : this.endTime;

    if (typeof time !== 'number') {
      return null;
    }

    const coordinate = getXCoordinateFromTime(this.chart, time, this.series);

    return this.createAxisLabel(
      coordinate === null ? null : Number(coordinate),
      this.formatTime(time),
    );
  }

  protected getPriceAxisLabel(kind: string): AxisLabel | null {
    if (!this.shouldShowInteractiveAxis() || (kind !== 'start' && kind !== 'end')) {
      return null;
    }

    const geometry = this.getGeometry();

    if (!geometry) {
      return null;
    }

    const price =
      kind === 'start'
        ? geometry.baseStartPrice
        : geometry.baseEndPrice;

    const coordinate = getYCoordinateFromPrice(this.series, price);

    return this.createAxisLabel(
      coordinate === null ? null : Number(coordinate),
      formatPrice(price) ?? '',
    );
  }

  protected handleDoubleClick = (event: MouseEvent): void => {
    if (this.hidden || this.mode !== 'ready' || !this.isSelected()) {
      return;
    }

    const point = this.getEventPoint(event as PointerEvent);

    if (!this.containsPoint(point) && !this.getDrawingHandleAtPoint(point)) {
      return;
    }

    event.preventDefault();
    event.stopPropagation();
    this.openSettings?.();
  };

  protected handlePointerDown = (event: PointerEvent): void => {
    if (this.hidden || event.button !== 0) {
      return;
    }

    const point = this.getEventPoint(event);

    if (this.mode === 'idle') {
      event.preventDefault();
      event.stopPropagation();
      this.startDrawing(point);
      return;
    }

    if (this.mode === 'drawing') {
      const time = this.getBarTime(point.x);

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

      event.preventDefault();
      event.stopPropagation();

      this.endTime = time;

      if (!this.hasValidRange()) {
        this.render();
        return;
      }

      this.mode = 'ready';
      this.resolveReady?.();
      this.render();
      return;
    }

    if (this.mode !== 'ready') {
      return;
    }

    if (!this.isSelected()) {
      if (!this.containsPoint(point)) {
        return;
      }

      event.preventDefault();
      event.stopPropagation();
      this.select();
      return;
    }

    const dragTarget = this.getDragTarget(point);

    if (!dragTarget) {
      this.deselect();
      return;
    }

    event.preventDefault();
    event.stopPropagation();

    this.activeDragTarget = dragTarget;
    this.dragPointerId = event.pointerId;
    this.dragStartPoint = point;
    this.dragStateSnapshot = this.getState();
    this.mode = 'dragging';

    this.hideCrosshair();
    this.render();
  };

  protected handlePointerMove = (event: PointerEvent): void => {
    const point = this.getEventPoint(event);

    if (this.mode === 'drawing') {
      const time = this.getBarTime(point.x);

      if (time !== null) {
        this.endTime = time;
        this.render();
      }

      return;
    }

    if (
      this.mode !== 'dragging' ||
      this.dragPointerId !== event.pointerId ||
      !this.dragStateSnapshot
    ) {
      return;
    }

    event.preventDefault();

    this.applyDrag(point);
    this.render();
  };

  protected handlePointerUp = (event: PointerEvent): void => {
    if (this.mode !== 'dragging' || this.dragPointerId !== event.pointerId) {
      return;
    }

    this.activeDragTarget = null;
    this.dragPointerId = null;
    this.dragStartPoint = null;
    this.dragStateSnapshot = null;
    this.mode = 'ready';

    this.showCrosshair();
    this.render();
  };

  protected getGeometry(): RegressionTrendGeometry | null {
    if (this.startTime === null || this.endTime === null) {
      return null;
    }

    const regression = this.getRegression();

    if (!regression) {
      return null;
    }

    const baseStartPoint = this.getPoint(this.startTime, regression.baseStartPrice);
    const baseEndPoint = this.getPoint(this.endTime, regression.baseEndPrice);
    const upperStartPoint = this.getPoint(this.startTime, regression.upperStartPrice);
    const upperEndPoint = this.getPoint(this.endTime, regression.upperEndPrice);
    const lowerStartPoint = this.getPoint(this.startTime, regression.lowerStartPrice);
    const lowerEndPoint = this.getPoint(this.endTime, regression.lowerEndPrice);

    if (
      !baseStartPoint ||
      !baseEndPoint ||
      !upperStartPoint ||
      !upperEndPoint ||
      !lowerStartPoint ||
      !lowerEndPoint
    ) {
      return null;
    }

    const points = [
      upperStartPoint,
      upperEndPoint,
      lowerStartPoint,
      lowerEndPoint,
    ];

    return {
      baseStartPoint,
      baseEndPoint,
      upperStartPoint,
      upperEndPoint,
      lowerStartPoint,
      lowerEndPoint,
      baseStartPrice: regression.baseStartPrice,
      baseEndPrice: regression.baseEndPrice,
      correlation: regression.correlation,
      left: Math.min(...points.map((point) => point.x)),
      right: Math.max(...points.map((point) => point.x)),
      top: Math.min(...points.map((point) => point.y)),
      bottom: Math.max(...points.map((point) => point.y)),
    };
  }

  private startDrawing(point: Point): void {
    const time = this.getBarTime(point.x);

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

    this.startTime = time;
    this.endTime = time;
    this.mode = 'drawing';
    this.render();
  }

  private applyDrag(point: Point): void {
    const snapshot = this.dragStateSnapshot;

    if (!snapshot || snapshot.startTime === null || snapshot.endTime === null) {
      return;
    }

    switch (this.activeDragTarget) {
      case 'start':
        this.moveEdge('start', point);
        break;
      case 'end':
        this.moveEdge('end', point);
        break;
      case 'body':
        this.moveWhole(snapshot, point);
        break;
      default:
        break;
    }
  }

  private moveEdge(kind: TimeLabelKind, point: Point): void {
    const time = this.getBarTime(point.x);

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

    const previousTime = kind === 'start' ? this.startTime : this.endTime;

    if (kind === 'start') {
      this.startTime = time;
    } else {
      this.endTime = time;
    }

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

    if (kind === 'start') {
      this.startTime = previousTime;
    } else {
      this.endTime = previousTime;
    }
  }

  private moveWhole(snapshot: RegressionTrendState, point: Point): void {
    if (!this.dragStartPoint || snapshot.startTime === null || snapshot.endTime === null) {
      return;
    }

    const data = this.getSeriesData();

    const dragStartIndex = this.getBarIndexByX(this.dragStartPoint.x, data);
    const currentIndex = this.getBarIndexByX(point.x, data);
    const startIndex = this.getBarIndex(snapshot.startTime, data);
    const endIndex = this.getBarIndex(snapshot.endTime, data);

    if (
      dragStartIndex === null ||
      currentIndex === null ||
      startIndex === null ||
      endIndex === null
    ) {
      return;
    }

    const rawOffset = currentIndex - dragStartIndex;
    const minIndex = Math.min(startIndex, endIndex);
    const maxIndex = Math.max(startIndex, endIndex);
    const minOffset = -minIndex;
    const maxOffset = data.length - 1 - maxIndex;
    const offset = Math.max(minOffset, Math.min(rawOffset, maxOffset));

    this.startTime = data[startIndex + offset].time;
    this.endTime = data[endIndex + offset].time;
  }

  private getRegression(): RegressionResult | null {
    const data = this.getSeriesData();
    const range = this.getBarRange(data);

    if (!range) {
      return null;
    }

    const values: number[] = [];

    for (let index = range.left; index <= range.right; index += 1) {
      const value = getSeriesValue(data[index]);

      if (value !== null) {
        values.push(value);
      }
    }

    if (values.length < 2) {
      return null;
    }

    const regression = calculateRegression(values);
    const offset = regression.deviation * REGRESSION_DEVIATION;

    const baseStartPrice = range.reversed
      ? regression.endValue
      : regression.startValue;

    const baseEndPrice = range.reversed
      ? regression.startValue
      : regression.endValue;

    return {
      baseStartPrice,
      baseEndPrice,
      upperStartPrice: baseStartPrice + offset,
      upperEndPrice: baseEndPrice + offset,
      lowerStartPrice: baseStartPrice - offset,
      lowerEndPrice: baseEndPrice - offset,
      correlation: regression.correlation,
    };
  }

  private getBarRange(
    data = this.getSeriesData(),
  ): {
    left: number;
    right: number;
    reversed: boolean;
  } | null {
    if (this.startTime === null || this.endTime === null) {
      return null;
    }

    const startIndex = this.getBarIndex(this.startTime, data);
    const endIndex = this.getBarIndex(this.endTime, data);

    if (startIndex === null || endIndex === null) {
      return null;
    }

    return {
      left: Math.min(startIndex, endIndex),
      right: Math.max(startIndex, endIndex),
      reversed: startIndex > endIndex,
    };
  }

  private hasValidRange(): boolean {
    const range = this.getBarRange();

    return range !== null && range.right - range.left >= MIN_BAR_DISTANCE;
  }

  private getBarTime(x: number): Time | null {
    const time = getTimeFromXCoordinate(this.chart, x);

    if (typeof time !== 'number') {
      return null;
    }

    const data = this.getSeriesData();
    const index = findNearestBarIndex(data, time);

    return index === null ? null : data[index].time;
  }

  private getBarIndexByX(
    x: number,
    data: readonly RegressionSeriesData[],
  ): number | null {
    const time = getTimeFromXCoordinate(this.chart, x);

    return typeof time === 'number'
      ? findNearestBarIndex(data, time)
      : null;
  }

  private getBarIndex(
    time: Time,
    data: readonly RegressionSeriesData[],
  ): number | null {
    return typeof time === 'number'
      ? findNearestBarIndex(data, time)
      : null;
  }

  private getSeriesData(): readonly RegressionSeriesData[] {
    return this.series.data() as readonly RegressionSeriesData[];
  }

  private getPoint(time: Time, price: number): Point | null {
    const x = getXCoordinateFromTime(this.chart, time, this.series);
    const y = getYCoordinateFromPrice(this.series, price);

    if (x === null || y === null) {
      return null;
    }

    return {
      x: Number(x),
      y: Number(y),
    };
  }

  private getDragTarget(point: Point): DragTarget {
    const handle = this.getDrawingHandleAtPoint(point);

    if (handle) {
      return handle.id;
    }

    return this.containsPoint(point) ? 'body' : null;
  }

  private containsPoint(point: Point): boolean {
    const geometry = this.getGeometry();

    if (!geometry) {
      return false;
    }

    if (
      getDistanceToSegment(
        point,
        geometry.upperStartPoint,
        geometry.upperEndPoint,
      ) <= LINE_HIT_TOLERANCE
    ) {
      return true;
    }

    if (
      getDistanceToSegment(
        point,
        geometry.lowerStartPoint,
        geometry.lowerEndPoint,
      ) <= LINE_HIT_TOLERANCE
    ) {
      return true;
    }

    if (
      getDistanceToSegment(
        point,
        geometry.baseStartPoint,
        geometry.baseEndPoint,
      ) <= LINE_HIT_TOLERANCE
    ) {
      return true;
    }

    return isPointInPolygon(point, [
      geometry.upperStartPoint,
      geometry.upperEndPoint,
      geometry.lowerEndPoint,
      geometry.lowerStartPoint,
    ]);
  }

  private formatTime(time: number): string {
    return formatDate(
      time as UTCTimestamp,
      this.displayFormat.dateFormat,
      this.displayFormat.timeFormat,
      this.displayFormat.showTime,
    );
  }
}

function calculateRegression(values: readonly number[]): {
  startValue: number;
  endValue: number;
  deviation: number;
  correlation: number;
} {
  const count = values.length;
  const meanX = (count - 1) / 2;
  const meanY = values.reduce((sum, value) => sum + value, 0) / count;

  let sumXX = 0;
  let sumXY = 0;
  let sumYY = 0;

  for (let index = 0; index < count; index += 1) {
    const x = index - meanX;
    const y = values[index] - meanY;

    sumXX += x * x;
    sumXY += x * y;
    sumYY += y * y;
  }

  const slope = sumXX === 0 ? 0 : sumXY / sumXX;
  const intercept = meanY - slope * meanX;

  let residualSum = 0;

  for (let index = 0; index < count; index += 1) {
    const expected = intercept + slope * index;
    const residual = values[index] - expected;

    residualSum += residual * residual;
  }

  const denominator = Math.sqrt(sumXX * sumYY);

  return {
    startValue: intercept,
    endValue: intercept + slope * (count - 1),
    deviation: Math.sqrt(residualSum / count),
    correlation: denominator === 0 ? 0 : sumXY / denominator,
  };
}

function getSeriesValue(data: RegressionSeriesData): number | null {
  if (typeof data.close === 'number' && Number.isFinite(data.close)) {
    return data.close;
  }

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

  return null;
}

function findNearestBarIndex(
  data: readonly RegressionSeriesData[],
  targetTime: number,
): number | null {
  if (!data.length) {
    return null;
  }

  let left = 0;
  let right = data.length - 1;

  while (left <= right) {
    const middle = Math.floor((left + right) / 2);
    const { time } = data[middle];

    if (typeof time !== 'number') {
      return findNearestBarIndexLinear(data, targetTime);
    }

    if (time === targetTime) {
      return middle;
    }

    if (time < targetTime) {
      left = middle + 1;
    } else {
      right = middle - 1;
    }
  }

  const nextIndex = Math.min(left, data.length - 1);
  const previousIndex = Math.max(0, nextIndex - 1);
  const nextTime = data[nextIndex].time;
  const previousTime = data[previousIndex].time;

  if (typeof nextTime !== 'number' || typeof previousTime !== 'number') {
    return findNearestBarIndexLinear(data, targetTime);
  }

  return Math.abs(previousTime - targetTime) <= Math.abs(nextTime - targetTime)
    ? previousIndex
    : nextIndex;
}

function findNearestBarIndexLinear(
  data: readonly RegressionSeriesData[],
  targetTime: number,
): number | null {
  let result: number | null = null;
  let minDistance = Number.POSITIVE_INFINITY;

  data.forEach((item, index) => {
    if (typeof item.time !== 'number') {
      return;
    }

    const distance = Math.abs(item.time - targetTime);

    if (distance >= minDistance) {
      return;
    }

    minDistance = distance;
    result = index;
  });

  return result;
}

function isPointInPolygon(point: Point, polygon: Point[]): boolean {
  let inside = false;

  for (
    let index = 0, previousIndex = polygon.length - 1;
    index < polygon.length;
    previousIndex = index, index += 1
  ) {
    const current = polygon[index];
    const previous = polygon[previousIndex];

    const intersects =
      current.y > point.y !== previous.y > point.y &&
      point.x <
        ((previous.x - current.x) * (point.y - current.y)) /
          (previous.y - current.y) +
          current.x;

    if (intersects) {
      inside = !inside;
    }
  }

  return inside;
}