Загрузка данных
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,
ChartTypeOptions,
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;
chartOptions?: ChartTypeOptions;
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;
constructor({ params, lwcChartConfig }: ChartParams) {
const { eventManager, dataSource, modalRenderer, ohlcConfig, tooltipConfig, panes: panesSnapshot } = params;
this.eventManager = eventManager;
this.dataSource = dataSource;
this.container = lwcChartConfig.container;
this.chartConfig = lwcChartConfig;
this.lwcChart = createChart(this.container, getOptions(lwcChartConfig));
this.optionsSubscription = this.eventManager
.getChartOptionsModel()
.subscribe(({ dateFormat, timeFormat, showTime }) => {
this.chartConfig = {
...this.chartConfig,
dateFormat,
timeFormat,
showTime,
};
this.lwcChart.applyOptions({
...getOptions(this.chartConfig),
localization: {
timeFormatter: (time: UTCTimestamp) => formatDate(time, dateFormat, timeFormat, showTime),
},
});
});
this.subscriptions.add(this.optionsSubscription);
this.mouseEvents = new ChartMouseEvents({
lwcChart: this.lwcChart,
container: this.container,
});
this.mouseEvents.subscribe('wheel', this.onWheel);
this.mouseEvents.subscribe('pointerDown', this.onPointerDown);
this.mouseEvents.subscribe('pointerMove', this.onPointerMove);
this.mouseEvents.subscribe('pointerUp', this.onPointerUp);
this.mouseEvents.subscribe('pointerCancel', this.onPointerUp);
this.DOM = new DOMModel({
modalRenderer,
});
this.paneManager = new PaneManager({
eventManager: this.eventManager,
panesSnapshot,
lwcChart: this.lwcChart,
dataSource,
DOM: this.DOM,
ohlcConfig,
subscribeChartEvent: this.subscribeChartEvent,
chartContainer: this.container,
tooltipConfig,
modalRenderer,
hotkeys: params.hotkeys,
});
this.mainSeries = this.paneManager.getMainPane().getMainSerie();
const { indicatorSnapshots, compareSnapshots } = splitIndicatorSnapshots(panesSnapshot);
this.indicatorManager = new IndicatorManager({
lwcChart: this.lwcChart,
eventManager,
dataSource: this.dataSource,
paneManager: this.paneManager,
initialIndicators: indicatorSnapshots,
DOM: this.DOM,
chartOptions: lwcChartConfig.chartOptions,
});
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 = () => {
this.eventManager.resetInterval({
history: false,
});
};
private onPointerDown = (event: PointerEvent) => {
if (event.composedPath().includes(this.lwcChart.chartElement())) {
this.container.focus({ preventScroll: true });
}
this.isPointerDown = true;
this.didResetOnDrag = false;
};
private onPointerMove = () => {
if (!this.isPointerDown) return;
if (this.didResetOnDrag) return;
this.didResetOnDrag = true;
this.eventManager.resetInterval({
history: false,
});
};
private onPointerUp = () => {
this.isPointerDown = false;
};
public getDom(): DOMModel {
return this.DOM;
}
public getMainSeries(): Observable<SeriesStrategies | null> {
return this.mainSeries.asObservable();
}
public getCompareManager(): CompareManager {
return this.compareManager;
}
public updateTheme(theme: ThemeKey, mode: ThemeMode) {
this.chartConfig = {
...this.chartConfig,
theme,
mode,
};
this.lwcChart.applyOptions(getOptions(this.chartConfig));
this.paneManager.invalidate();
}
public destroy(): void {
this.subscriptions.unsubscribe();
this.mouseEvents.destroy();
this.compareManager.destroy();
this.paneManager.destroy();
this.lwcChart.remove();
}
public subscribeChartEvent: ChartMouseEvents['subscribe'] = (event, callback) =>
this.mouseEvents.subscribe(event, callback);
public unsubscribeChartEvent: ChartMouseEvents['unsubscribe'] = (event, callback) => {
this.mouseEvents.unsubscribe(event, callback);
};
// todo: add/move to undo/redo model(eventManager)
public scrollTimeScale = (direction: Direction) => {
this.eventManager.resetInterval({
history: false,
});
const diff = direction === Direction.Left ? -2 : 2;
const currentPosition = this.lwcChart.timeScale().scrollPosition();
this.lwcChart.timeScale().scrollToPosition(currentPosition + diff, false);
};
// todo: add/move to undo/redo model(eventManager)
public zoomTimeScale = (resize: Resize) => {
this.eventManager.resetInterval({
history: false,
});
const diff = resize === Resize.Shrink ? -1 : 1;
const currentRange = this.lwcChart.timeScale().getVisibleRange();
if (!currentRange) return;
const { from, to } = currentRange as IRange<number>;
if (!from || !to) return;
const next: IRange<Time> = {
from: (from + (to - from) * 0.1 * diff) as Time,
to: to as Time,
};
this.lwcChart.timeScale().setVisibleRange(next);
};
// todo: add to undo/redo model(eventManager)
public resetZoom = () => {
this.eventManager.resetInterval({
history: false,
});
this.lwcChart.timeScale().resetTimeScale();
this.paneManager.resetPriceScalesAutoScale();
};
public getRealtimeApi() {
return {
getTimeframe: () => this.eventManager.getTimeframe(),
getSymbols: () => this.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.subscriptions.closed || this.historyBatchRunning || this.activeSymbolIds.length === 0) {
return;
}
this.historyBatchRunning = true;
requestAnimationFrame(() => {
if (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))).finally(() => {
this.finishHistoryBatch(symbolIds, oldestTimes, timeframe);
});
});
}
private finishHistoryBatch(
symbolIds: string[],
oldestTimes: (number | null)[],
timeframe: ReturnType<EventManager['getTimeframe']>,
): void {
this.historyBatchRunning = false;
if (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) => {
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 { 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 { SettingsModal } from '@src/components/SettingsModal';
import Toolbar from '@src/components/Toolbar';
import { IndicatorsIds } from '@src/constants';
import { CompareManager } from '@src/core/CompareManager';
import { FullscreenController } from '@src/core/Fullscreen';
import { configureThemeStore } from '@src/theme/store';
import { ThemeKey, ThemeMode } from '@src/theme/types';
import { Locale, setLocale, t } from '@src/translations';
import { Candle, ChartSeriesType, ChartTypeOptions, OHLCConfig, 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;
/**
* Дефолтная конфигурация тултипа - всегда показывается по умолчанию.
* При добавлении/изменении полей в конфиге - они объединяются с дефолтными значениями.
*
* Полная кастомизация:
* @example
* ```typescript
* tooltipConfig: {
* time: { visible: true, label: 'Дата и время' },
* symbol: { visible: true, label: 'Инструмент' },
* close: { visible: true, label: 'Курс' },
* change: { visible: true, label: 'Изменение' },
* volume: { visible: true, label: 'Объем' },
* open: { visible: false },
* high: { visible: false },
* low: { visible: false }
* }
*```
*/
tooltipConfig?: TooltipConfig;
size?:
| {
width: number;
height: number;
}
| false;
supportedTimeframes: Timeframes[];
supportedChartSeriesTypes: ChartSeriesType[];
getDataSource: DataSourceParams['getData'];
startRealtime: (
getSymbols: () => string[],
getTimeframe: () => Timeframes,
update: (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;
lwcInheritedChartOptions?: ChartTypeOptions;
}
export class MoexChart implements ISerializable<MoexChartSnapshot> {
private chart!: Chart;
private resizeObserver?: ResizeObserver;
private eventManager!: EventManager;
private hotkeys!: Hotkeys;
private rootContainer!: HTMLElement;
private headerRenderer!: UIRenderer;
private modalRenderer!: ModalRenderer;
private toolbarRenderer: UIRenderer | undefined;
private controlBarRenderer?: UIRenderer;
private footerRenderer?: UIRenderer;
private 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.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,
});
// todo: сюда прокидывается не подходящий под сигнатуру интерфейс. Функция не работает
// if (config.lwcInheritedChartOptions) {
// this.setSettings(config.lwcInheritedChartOptions);
// }
this.dataSource = new DataSource({
getData: config.chartCollectionPreset.getDataSource,
eventManager: this.eventManager,
});
this.rootContainer = config.container;
this.fullscreen = new FullscreenController(this.rootContainer);
const store = configureThemeStore(config.chartCollectionPreset);
const {
chartAreaContainer,
toolBarContainer,
headerContainer,
modalContainer,
controlBarContainer,
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();
if (config.chartCollectionPreset.undoRedoEnabled) {
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,
});
}
this.modalRenderer = new ModalRenderer(modalContainer);
this.chart = new Chart({
params: {
dataSource: this.dataSource,
eventManager: this.eventManager,
modalRenderer: this.modalRenderer,
ohlcConfig: config.chartCollectionPreset.ohlc, // todo: omptimize
tooltipConfig: config.chartCollectionPreset.tooltipConfig ?? {},
panes: config.snapshot.charts[0].panes,
hotkeys: this.hotkeys,
},
lwcChartConfig: {
container: chartAreaContainer,
seriesTypes: config.chartCollectionPreset.supportedChartSeriesTypes,
theme: store.theme,
mode: store.mode,
chartOptions: config.lwcInheritedChartOptions, // todo: remove, use only model from eventManager
},
});
this.subscriptions.add(
combineLatest([store.theme$, store.mode$]).subscribe(([theme, mode]) => {
this.chart.updateTheme(theme, mode);
document.documentElement.dataset.theme = theme;
document.documentElement.dataset.mode = mode;
}),
);
const realtimeParams = this.chart.getRealtimeApi();
this.subscriptions.add(
config.chartCollectionPreset.startRealtime(
realtimeParams.getSymbols,
realtimeParams.getTimeframe,
realtimeParams.update,
),
);
this.headerRenderer = new ReactRenderer(headerContainer);
this.toolbarRenderer = new ReactRenderer(toolBarContainer);
this.drawingToolbarRenderer = new ReactRenderer(drawingToolbarContainer);
if (config.chartCollectionPreset.showControlBar) {
this.controlBarRenderer = new ReactRenderer(controlBarContainer);
}
if (config.chartCollectionPreset.showBottomPanel) {
this.footerRenderer = new ReactRenderer(footerContainer);
}
this.timeScaleHoverController = new TimeScaleHoverController({
eventManager: this.eventManager,
controlBarContainer,
chartContainer: chartAreaContainer,
});
this.renderAttachments(config, toggleToolbar);
};
public setSettings(settings: ChartSettingsSource): void {
this.eventManager.importChartSettings(settings);
}
public getSettings(): ChartSettings {
return this.eventManager.exportChartSettings();
}
// todo: описать подробнее в доке. Точно ли public?
public getRealtimeApi() {
return this.chart.getRealtimeApi();
}
// todo: описать подробнее в доке
public getCompareManager(): CompareManager {
return this.chart.getCompareManager();
}
public setSnapshot(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.eventManager.setSymbol(symbolInfo);
}
public clearSymbol(): void {
this.eventManager.clearSymbol();
}
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.headerRenderer.renderComponent(
<Header
timeframes={config.chartCollectionPreset.supportedTimeframes}
selectedTimeframeObs={this.eventManager.getTimeframeObs()}
setTimeframe={(value) => {
this.eventManager.setTimeframe(value);
}}
seriesTypes={config.chartCollectionPreset.supportedChartSeriesTypes}
selectedSeriesObs={this.eventManager.getSelectedSeries()}
setSelectedSeries={(value) => {
this.eventManager.setSeriesSelected(value);
}}
showSettingsModal={
config.chartCollectionPreset.showSettingsButton
? () =>
this.modalRenderer.renderComponent(
<SettingsModal
// todo: deal with onSave
changeTimeFormat={(format) => this.eventManager.setTimeFormat(format)}
changeDateFormat={(format) => this.eventManager.setDateFormat(format)}
chartDateTimeFormatObs={this.eventManager.getChartOptionsModel()}
/>,
{ title: t('Settings') },
)
: undefined
}
addIndicatorToChart={(indicatorType: IndicatorsIds) =>
this.chart.getIndicatorManager().addIndicator({ indicatorType })
}
copyImage={config.chartCollectionPreset.showSnapshotButton ? () => 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'}
/>,
);
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.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 { BarIcon, CandleStickIcon, LineIcon } from '@src/components/Icon';
import { MenuList, MenuOption } from '@src/components/Menu/MenuList';
import { t } from '@src/translations';
import { ChartSeriesType } from '@src/types';
interface SeriesMenuProps {
selectedType?: ChartSeriesType;
seriesTypes: ChartSeriesType[];
onClick: (next: ChartSeriesType) => void;
}
const seriesOptions = (): Partial<Record<ChartSeriesType, MenuOption<ChartSeriesType>>> => {
return {
Candlestick: {
icon: <CandleStickIcon />,
value: 'Candlestick',
label: t('Candles'),
},
Line: {
icon: <LineIcon />,
value: 'Line',
label: t('Line'),
},
Bar: {
icon: <BarIcon />,
value: 'Bar',
label: t('Bars'),
},
};
};
export function SeriesMenu({ selectedType, seriesTypes, onClick }: SeriesMenuProps) {
const options: MenuOption<ChartSeriesType>[] = seriesTypes.map((type) => ({
value: type,
icon: seriesOptions()[type]?.icon,
label: seriesOptions()[type]?.label,
}));
return (
<MenuList
mode="single"
value={selectedType}
options={options}
onClick={onClick}
/>
);
}
import { Divider } from 'exchange-elements/v2';
import { useEffect, useState } from 'react';
import { type Observable, of } from 'rxjs';
import { IndicatorsSelect } from '@components/IndicatorsSelect';
import { Button } from '@src/components/Button';
import { Tooltip } from '@src/components/Tooltip';
import { IndicatorsIds } from '@src/constants';
import { FullscreenController } from '@src/core/Fullscreen';
import { UndoRedo, type UndoRedoState } from '@src/core/UndoRedo';
import { t } from '@src/translations';
import { ChartSeriesType } from '@src/types';
import { Timeframes } from '@src/types/timeframes';
import { useObservable } from '@src/utils';
import { Dropdown } from '../Dropdown';
import {
BarIcon,
BurgerMenuIcon,
CameraIcon,
CandleStickIcon,
FullscreenIcon,
LineIcon,
PlusCircleIcon,
RedoIcon,
SearchIcon,
UndoIcon,
} from '../Icon';
import { SeriesMenu, SnapshotMenu, TimeframesMenu } from '../Menu';
import styles from './index.module.scss';
const defaultUndoRedoState: UndoRedoState = {
canUndo: false,
canRedo: false,
};
const defaultUndoRedoState$ = of(defaultUndoRedoState);
interface HeaderProps {
timeframes: Timeframes[];
selectedTimeframeObs: Observable<Timeframes>;
setTimeframe: (value: Timeframes) => void;
seriesTypes: ChartSeriesType[];
setSelectedSeries: (next: ChartSeriesType) => void;
selectedSeriesObs: Observable<ChartSeriesType>;
showSettingsModal: (() => void) | undefined;
addIndicatorToChart: (id: IndicatorsIds) => void;
toggleToolbarVisible: () => boolean;
showCompareButton: boolean;
showSymbolSearchButton: boolean;
undoRedo: UndoRedo | undefined;
showMenuButton?: boolean;
showFullscreenButton?: boolean;
fullscreen: FullscreenController;
openCompareModal?: () => void;
openSymbolSearchModal?: () => void;
copyImage?: () => Promise<void>;
isMXT: boolean;
}
export function Header({
setTimeframe,
selectedTimeframeObs,
setSelectedSeries,
selectedSeriesObs,
timeframes,
seriesTypes,
showSettingsModal,
addIndicatorToChart,
toggleToolbarVisible,
showCompareButton,
showSymbolSearchButton,
fullscreen,
undoRedo,
showFullscreenButton,
showMenuButton,
openCompareModal,
openSymbolSearchModal,
copyImage,
isMXT,
}: HeaderProps) {
const [isToolbarOpen, setIsToolbarOpen] = useState(showMenuButton ?? false);
const [isFullscreen, setIsFullscreen] = useState(fullscreen.isFullscreen);
const undoRedoState = useObservable(undoRedo?.getState() ?? defaultUndoRedoState$, defaultUndoRedoState);
useEffect(() => {
const unsubscribe = fullscreen.onChange(() => {
setIsFullscreen(fullscreen.isFullscreen);
});
return unsubscribe;
}, [fullscreen]);
const selectedTimeframe = useObservable(selectedTimeframeObs);
const selectedSeries = useObservable(selectedSeriesObs);
const seriesDropdownValue =
selectedSeries === 'Line' ? <LineIcon /> : selectedSeries === 'Bar' ? <BarIcon /> : <CandleStickIcon />;
const handleOpenToolbar = (): void => {
setIsToolbarOpen(toggleToolbarVisible());
};
return (
<header className={styles.header}>
<div className={styles.group}>
{showMenuButton && (
<Tooltip
location="bottom"
label={t(isToolbarOpen ? 'Hide drawing toolbar' : 'Show drawing toolbar')}
>
<Button
pressed={isToolbarOpen}
onClick={handleOpenToolbar}
label={<BurgerMenuIcon />}
/>
</Tooltip>
)}
{showSymbolSearchButton && (
<Tooltip
location="bottom"
label={t('Symbol search')}
>
<Button
onClick={openSymbolSearchModal}
label={<SearchIcon />}
/>
</Tooltip>
)}
{showCompareButton && (
<Tooltip
location="bottom"
label={t('Compare symbols')}
>
<Button
onClick={openCompareModal}
label={<PlusCircleIcon />}
/>
</Tooltip>
)}
</div>
{(showMenuButton || showCompareButton || showSymbolSearchButton) && (
<Divider
direction="vertical"
pt={{ divider: { className: styles.divider } }}
/>
)}
<Tooltip
location="bottom"
label={t('Timeframe')}
>
<Dropdown
menuClassName={styles.menu}
selectedValue={selectedTimeframe ? t(selectedTimeframe) : selectedTimeframe}
>
<TimeframesMenu
onClick={setTimeframe}
{...{ selectedTimeframe, timeframes }}
/>
</Dropdown>
</Tooltip>
<Divider
direction="vertical"
pt={{ divider: { className: styles.divider } }}
/>
<div className={styles.group}>
<IndicatorsSelect
addIndicatorToChart={addIndicatorToChart}
isMXT={isMXT}
/>
{showSettingsModal && (
<Button
onClick={showSettingsModal}
label={t('Settings')}
/>
)}
<Tooltip
location="bottom"
label={t('Chart type')}
>
<Dropdown
menuClassName={styles.menu}
selectedValue={seriesDropdownValue}
>
<SeriesMenu
selectedType={selectedSeries}
seriesTypes={seriesTypes}
onClick={setSelectedSeries}
/>
</Dropdown>
</Tooltip>
</div>
{undoRedo && (
<>
<Divider
direction="vertical"
pt={{ divider: { className: styles.divider } }}
/>
<div className={styles.group}>
<Tooltip
location="bottom"
label={t('Undo')}
>
<Button
onClick={undoRedo.undo}
disabled={!undoRedoState?.canUndo}
label={<UndoIcon />}
/>
</Tooltip>
<Tooltip
location="bottom"
label={t('Redo')}
>
<Button
onClick={undoRedo.redo}
disabled={!undoRedoState?.canRedo}
label={<RedoIcon />}
/>
</Tooltip>
</div>
</>
)}
{(copyImage || showFullscreenButton) && (
<>
<Divider
direction="vertical"
pt={{ divider: { className: styles.divider } }}
/>
<div className={styles.group}>
{copyImage && (
<Tooltip
location="bottom"
label={t('Snapshot')}
>
<Dropdown
menuClassName={styles.menu}
selectedValue={<CameraIcon />}
>
<SnapshotMenu onCopyImage={copyImage} />
</Dropdown>
</Tooltip>
)}
{showFullscreenButton && (
<Tooltip
location="bottom"
label={t(isFullscreen ? 'Exit fullscreen' : 'Fullscreen')}
>
<Button
pressed={isFullscreen}
onClick={() => fullscreen.toggle()}
label={<FullscreenIcon />}
/>
</Tooltip>
)}
</div>
</>
)}
</header>
);
}
import { BehaviorSubject, combineLatest, distinctUntilChanged, map, Observable, Subscription } from 'rxjs';
import { ChartOptionsModel, ChartSeriesType, Intervals, SymbolInfo, SymbolInfoInput, TimeFormat } from '@src/types';
import { Defaults } from '@src/types/defaults';
import { Timeframes } from '@src/types/timeframes';
import { DateFormat, getTimeframeByInterval, normalizeSymbolInfo, shouldShowTime } from '@src/utils';
import { ChartSettings, ChartSettingsSource, parseChartSettings } from './ChartSettings';
import { UndoKey, UndoRedo } from './UndoRedo';
interface EventManagerParams {
initialTimeframe: Timeframes;
initialSeries: ChartSeriesType;
initialSymbolInfo: SymbolInfoInput;
initialTimeFormat?: TimeFormat;
initialDateFormat?: DateFormat;
initialInterval?: Intervals | null;
}
interface SetWithHistoryOptions {
history?: boolean;
}
const EMPTY_SYMBOL_INFO: SymbolInfo = {
symbolId: '',
symbol: '',
symbolName: '',
};
/**
* Менеджер настроек, которые меняются во время использования.
* Отвечает за централизованное управление настройками графика.
*/
export class EventManager {
private timeframe$: BehaviorSubject<Timeframes>;
private seriesSelected$: BehaviorSubject<ChartSeriesType>;
private symbolInfo$: BehaviorSubject<SymbolInfo>;
private timeFormat$: BehaviorSubject<TimeFormat>;
private dateFormat$: BehaviorSubject<DateFormat>;
private interval$: BehaviorSubject<Intervals | null>;
private controlBarVisible$ = new BehaviorSubject<boolean>(false); // todo: move to render
private undoRedo: UndoRedo;
constructor({
initialTimeframe,
initialSeries,
initialSymbolInfo,
initialTimeFormat,
initialDateFormat,
initialInterval = null,
}: EventManagerParams) {
const normalizedSymbolInfo = normalizeSymbolInfo(initialSymbolInfo);
this.timeframe$ = new BehaviorSubject<Timeframes>(initialTimeframe);
this.seriesSelected$ = new BehaviorSubject<ChartSeriesType>(initialSeries);
this.symbolInfo$ = new BehaviorSubject<SymbolInfo>(normalizedSymbolInfo ?? EMPTY_SYMBOL_INFO);
this.timeFormat$ = new BehaviorSubject<TimeFormat>(initialTimeFormat ?? Defaults.timeFormat);
this.dateFormat$ = new BehaviorSubject<DateFormat>(initialDateFormat ?? Defaults.dateFormat);
this.interval$ = new BehaviorSubject<Intervals | null>(initialInterval);
this.undoRedo = new UndoRedo({
timeframe: (value) => this.timeframe$.next(value),
seriesSelected: (value) => this.seriesSelected$.next(value),
symbolInfo: (value) => this.symbolInfo$.next(value),
timeFormat: (value) => this.timeFormat$.next(value),
dateFormat: (value) => this.dateFormat$.next(value),
interval: (value) => this.interval$.next(value),
});
}
private setWithHistory<K extends UndoKey, V>(
key: K,
subject: BehaviorSubject<V>,
next: V,
options?: SetWithHistoryOptions,
): void {
const prev = subject.getValue();
if (Object.is(prev, next)) {
return;
}
subject.next(next);
const historyEnabled = options?.history ?? true;
if (historyEnabled) {
this.undoRedo.push(key, prev, next);
}
}
public getUndoRedo(): UndoRedo {
return this.undoRedo;
}
public getTimeframe(): Timeframes {
return this.timeframe$.value;
}
public setInterval = (next: Intervals, options?: SetWithHistoryOptions): void => {
const timeframe = getTimeframeByInterval(next);
this.undoRedo.group(() => {
this.setWithHistory('timeframe', this.timeframe$, timeframe, options);
this.setWithHistory('interval', this.interval$, next, options);
});
};
public resetInterval = (options?: SetWithHistoryOptions): void =>
this.setWithHistory('interval', this.interval$, null, options);
public getInterval(): Observable<Intervals | null> {
return this.interval$.asObservable();
}
public setSymbol = (symbolInfoInput: SymbolInfoInput, options?: SetWithHistoryOptions): void => {
const nextSymbolInfo = normalizeSymbolInfo(symbolInfoInput);
if (!nextSymbolInfo) {
return;
}
const currentSymbolInfo = this.symbolInfo$.value;
if (
currentSymbolInfo.symbolId === nextSymbolInfo.symbolId &&
currentSymbolInfo.symbol === nextSymbolInfo.symbol &&
currentSymbolInfo.symbolName === nextSymbolInfo.symbolName
) {
return;
}
this.setWithHistory('symbolInfo', this.symbolInfo$, nextSymbolInfo, options);
};
public clearSymbol = (options?: SetWithHistoryOptions): void => {
if (!this.symbolInfo$.value.symbolId) {
return;
}
this.setWithHistory('symbolInfo', this.symbolInfo$, EMPTY_SYMBOL_INFO, options);
};
public hasSymbol(): Observable<boolean> {
return this.symbolInfo$.pipe(
map(({ symbolId }) => Boolean(symbolId)),
distinctUntilChanged(),
);
}
public symbolId(): Observable<string> {
return this.symbolInfo$.pipe(
map(({ symbolId }) => symbolId),
distinctUntilChanged(),
);
}
public symbol(): Observable<string> {
return this.symbolInfo$.pipe(
map(({ symbol }) => symbol),
distinctUntilChanged(),
);
}
public symbolName(): Observable<string> {
return this.symbolInfo$.pipe(
map(({ symbolName }) => symbolName),
distinctUntilChanged(),
);
}
public setTimeFormat = (next: TimeFormat, options?: SetWithHistoryOptions): void =>
this.setWithHistory('timeFormat', this.timeFormat$, next, options);
public setDateFormat = (next: DateFormat, options?: SetWithHistoryOptions): void =>
this.setWithHistory('dateFormat', this.dateFormat$, next, options);
public getChartOptionsModel(): Observable<ChartOptionsModel> {
// todo: подумать - стоит ли унести это в чарт
return combineLatest([this.timeFormat$, this.dateFormat$, this.timeframe$]).pipe(
map(([timeFormat, dateFormat, timeframe]) => ({
timeFormat,
dateFormat,
showTime: shouldShowTime(timeframe),
})),
);
}
public setTimeframe = (next: Timeframes, options?: SetWithHistoryOptions): void =>
this.undoRedo.group(() => {
this.resetInterval(options);
this.setWithHistory('timeframe', this.timeframe$, next, options);
});
public timeframe(): Observable<Timeframes> {
return this.timeframe$.asObservable();
}
public subscribeTimeframe(callback: (format: Timeframes) => void): Subscription {
return this.timeframe$.subscribe(callback);
}
public getTimeframeObs(): Observable<Timeframes> {
return this.timeframe$.asObservable();
}
public setSeriesSelected = (next: ChartSeriesType, options?: SetWithHistoryOptions): void =>
this.setWithHistory('seriesSelected', this.seriesSelected$, next, options);
public getSelectedSeries(): Observable<ChartSeriesType> {
return this.seriesSelected$.asObservable();
}
public subscribeSeriesSelected(callback: (next: ChartSeriesType) => void): Subscription {
return this.seriesSelected$.subscribe(callback);
}
public setControlBarVisible(visible: boolean): void {
this.controlBarVisible$.next(visible);
}
public getControlBarVisible(): Observable<boolean> {
return this.controlBarVisible$.asObservable();
}
public exportChartSettings(): ChartSettings {
return {
symbolInfo: this.symbolInfo$.value,
timeframe: this.timeframe$.value,
seriesSelected: this.seriesSelected$.value,
timeFormat: this.timeFormat$.value,
dateFormat: this.dateFormat$.value,
interval: this.interval$.value,
};
}
public importChartSettings(settings: ChartSettingsSource): void {
const { symbolInfo, seriesSelected, timeframe, timeFormat, dateFormat, interval } = parseChartSettings(settings);
const setOptions = { history: false };
if (symbolInfo) {
if (symbolInfo.symbolId) {
this.setSymbol(symbolInfo, setOptions);
} else {
this.clearSymbol(setOptions);
}
}
if (seriesSelected) {
this.setSeriesSelected(seriesSelected, setOptions);
}
if (timeFormat) {
this.setTimeFormat(timeFormat, setOptions);
}
if (dateFormat) {
this.setDateFormat(dateFormat, setOptions);
}
if (interval != null) {
this.setInterval(interval, setOptions);
return;
}
if (timeframe) {
this.setTimeframe(timeframe, setOptions);
return;
}
if (interval === null) {
this.resetInterval(setOptions);
}
}
public destroy(): void {
this.timeFormat$.complete();
this.dateFormat$.complete();
this.timeframe$.complete();
this.controlBarVisible$.complete();
this.interval$.complete();
this.symbolInfo$.complete();
this.seriesSelected$.complete();
}
}
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;
}
interface CandlestickChartOptions {
upColor?: string;
downColor?: string;
wickUpColor?: string;
wickDownColor?: string;
borderVisible?: boolean;
}
interface LineChartOptions {
lineStyle?: 'solid' | 'dotted' | 'dashed';
}
interface AreaChartOptions {
topColor?: string;
bottomColor?: string;
}
interface BaselineChartOptions {
baseValue?: number;
topLineColor?: string;
bottomLineColor?: string;
topFillColor1?: string;
topFillColor2?: string;
bottomFillColor1?: string;
bottomFillColor2?: string;
}
interface TimescaleOptions {
timeVisible?: boolean;
secondsVisible?: boolean;
timeFormat?: TimeFormat;
dateFormat?: DateFormat;
}
interface CrosshairOptions {
crosshairLineXColor?: string;
crosshairLineYColor?: string;
crosshairLabelXBgColor?: string;
crosshairLabelYBgColor?: string;
}
interface HistogramOptions {
scaleMargins?: {
top: number;
bottom: number;
};
}
/**
* @deprecated
* Опции для разных типов графиков
*/
export interface ChartTypeOptions // todo: неверный интерфейс
extends HistogramOptions,
CrosshairOptions,
TimescaleOptions,
BaselineChartOptions,
AreaChartOptions,
LineChartOptions,
CandlestickChartOptions {
// Общие опции
color?: string;
lineWidth?: 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 { DrawingsManagerSnapshot } from '@core/DrawingsManager';
import { ChartSeriesType, DateFormat, IndicatorsIds, Intervals, Timeframes } from '@lib';
import { Direction } from '@src/types/chart';
import { MainSymbolSnapshotInput, SymbolInfo, SymbolInfoInput } from '@src/types/symbol';
import { TimeFormat } from '@src/types/timeScale';
import { SettingsValues } from './settings';
import type { PriceScaleMode } from 'lightweight-charts';
export type PriceScaleSide = Direction.Left | Direction.Right;
export interface ISerializable<T extends object> {
getSnapshot: () => T;
}
export interface InitialSnapshot extends MainSymbolSnapshotInput {
timeframe: Timeframes; // todo: move to snap
chartSeriesType: ChartSeriesType; // todo: move to snap
}
export interface MoexChartSnapshotInput {
// settings: ChartSettingsSnapshot;
charts: ChartSnapshotInput[];
}
export interface MoexChartSnapshot {
// settings: ChartSettingsSnapshot;
charts: ChartSnapshot[];
}
interface ChartSnapshotBase {
timeframe: Timeframes;
chartSeriesType: ChartSeriesType;
timeFormat?: TimeFormat;
dateFormat?: DateFormat;
interval?: Intervals | null;
panes: PaneSnapshot[];
}
export interface ChartSnapshotInput extends ChartSnapshotBase, MainSymbolSnapshotInput {}
export interface ChartSnapshot extends ChartSnapshotBase, SymbolInfo {}
export interface PriceScaleSnapshot {
side: PriceScaleSide;
mode: PriceScaleMode;
}
export interface PaneSnapshot {
isMain: boolean;
id: number;
indicators: (IndicatorSnapshot | CompareSnapshot)[];
drawings: DrawingsManagerSnapshot;
priceScales?: PriceScaleSnapshot[];
}
export interface CompareSnapshot extends Partial<DOMObjectSnapshot> {
symbolInfo: SymbolInfoInput;
seriesName: ChartSeriesType;
scale: Direction;
}
export interface IndicatorSnapshot extends Partial<DOMObjectSnapshot> {
indicatorType: IndicatorsIds;
settings?: SettingsValues;
}
// todo: move DrawingsManagerSnapshot here
export interface DOMObjectSnapshot {
id: string;
name: string;
zIndex: number;
hidden: boolean;
paneId: number;
}
export interface SymbolInfo {
symbolId: string;
symbol: string;
symbolName: string;
}
export interface SymbolInfoInput {
symbolId: string;
symbol?: string;
symbolName?: string;
}
export interface MainSymbolSnapshotInput extends Omit<SymbolInfoInput, 'symbolId'> {
symbolId: string | null;
}
import { IChartApi, IPaneApi, PriceScaleMode, Time } from 'lightweight-charts';
import { BehaviorSubject, combineLatest, Subscription } from 'rxjs';
import { ChartTooltip } from '@components/ChartTooltip';
import { LegendComponent } from '@components/Legend';
import { ChartMouseEvents } from '@core/ChartMouseEvents';
import { ContainerManager } from '@core/ContainerManager';
import { DataSource } from '@core/DataSource';
import { DOMModel } from '@core/DOMModel';
import { DrawingsManager, DrawingsManagerSnapshot } from '@core/DrawingsManager';
import { EventManager } from '@core/EventManager';
import { Hotkeys } from '@core/Hotkeys';
import { Indicator } from '@core/Indicator';
import { Legend } from '@core/Legend';
import { PriceScale, PriceScaleControls } from '@core/PriceScale';
import { ReactRenderer } from '@core/ReactRenderer';
import { TooltipService } from '@core/Tooltip';
import { UIRenderer } from '@core/UIRenderer';
import { EntitySettingsModal } from '@src/components/EntitySettingsModal';
import { DrawingsNames, indicatorLabelById, MAIN_PANE_INDEX } from '@src/constants';
import { ModalRenderer } from '@src/core/ModalRenderer';
import { SeriesFactory, SeriesStrategies } from '@src/modules/series-strategies/SeriesFactory';
import { t } from '@src/translations';
import { ActiveDrawingTool, Direction, OHLCConfig, TooltipConfig } from '@src/types';
import {
CompareSnapshot,
DOMObjectSnapshot,
IndicatorSnapshot,
ISerializable,
PaneSnapshot,
PriceScaleSide,
PriceScaleSnapshot,
} from '@src/types/snapshot';
import { ensureDefined } from '@src/utils';
export interface PaneParams {
id: number;
lwcChart: IChartApi;
eventManager: EventManager;
DOM: DOMModel;
isMainPane: boolean;
ohlcConfig: OHLCConfig;
dataSource: DataSource | null; // todo: deal with dataSource. На каких то пейнах он нужен, на каких то нет
basedOn?: Pane; // Pane на котором находится главная серия, или серия, по которой строятся серии на текущем пейне
subscribeChartEvent: ChartMouseEvents['subscribe'];
tooltipConfig: TooltipConfig;
onDelete: () => void;
chartContainer: HTMLElement;
modalRenderer: ModalRenderer;
initialPriceScales?: PriceScaleSnapshot[];
onPriceScaleStateChange: () => void;
leftPriceScaleVisible: boolean;
rightPriceScaleVisible: boolean;
hotkeys: Hotkeys;
addDrawingManager: (manager: DrawingsManager, paneId: number) => void;
removeDrawingManager: (paneId: number) => void;
setActiveTool: (name: ActiveDrawingTool) => void;
getActiveTool: () => ActiveDrawingTool;
getIsEndlessMode: () => boolean;
continueDrawing: (name: DrawingsNames) => void;
}
// todo: Pane, ему должна принадлежать mainSerie, а также IndicatorManager и drawingsManager, mouseEvents. Также перекинуть соответствующие/необходимые свойства из чарта, и из чарта удалить
// todo: Учитывать, что есть линейка, которая рисуется одна для всех пейнов
// todo: в CompareManage, при создании нового пейна для сравнения - инициализируем новый dataSource, принадлежащий только конкретному пейну. Убираем возможность добавлять индикаторы на такие пейны
// todo: на каждый символ свой DataSource (учитывать что есть MainPane и "главный" DataSource, который инициализиурется во время старта moexChart)
// todo: сделать два разных представления для compare, в зависимости от отображения на главном пейне или на второстепенном
export class Pane implements ISerializable<PaneSnapshot> {
private readonly id: number;
private readonly isMain: boolean;
private mainSeries = new BehaviorSubject<SeriesStrategies | null>(null); // Main Series. Exists in a single copy
// todo: Отвратительный нейминг. Нужно оставить главной только эту серию и переименовать её localMainSeries => mainSerie
// Если вдруг понадобится главная серия главного пейна, то брать из КоллекцииПейнов(-сейчас PaneManager)
// serie to attach drawings
private localMainSeries = new BehaviorSubject<SeriesStrategies | null>(null);
private legend!: Legend;
private tooltip: TooltipService | undefined;
private readonly indicatorsMap = new BehaviorSubject<Map<string, Indicator>>(new Map());
private readonly lwcPane: IPaneApi<Time>;
private readonly lwcChart: IChartApi;
private readonly eventManager: EventManager;
private readonly drawingsManager: DrawingsManager;
private legendContainer!: HTMLElement;
private paneOverlayContainer!: HTMLElement;
private paneEmptyStateContainer!: HTMLElement;
private legendRenderer!: UIRenderer;
private tooltipRenderer: UIRenderer | undefined;
private readonly modalRenderer: ModalRenderer;
private readonly leftPriceScale: PriceScale;
private readonly rightPriceScale: PriceScale;
private readonly priceScaleControls: PriceScaleControls;
private readonly subscribeChartEvent: ChartMouseEvents['subscribe'];
private readonly onDelete: () => void;
private readonly onPriceScaleStateChange: () => void;
private readonly subscriptions = new Subscription();
private paneContainerSyncFrameId: number | null = null;
constructor({
lwcChart,
eventManager,
dataSource,
DOM,
isMainPane,
ohlcConfig,
id,
basedOn,
subscribeChartEvent,
tooltipConfig,
onDelete,
chartContainer,
modalRenderer,
initialPriceScales = [],
onPriceScaleStateChange,
leftPriceScaleVisible,
rightPriceScaleVisible,
hotkeys,
addDrawingManager,
removeDrawingManager,
setActiveTool,
getActiveTool,
getIsEndlessMode,
continueDrawing,
}: PaneParams) {
this.onDelete = onDelete;
this.onPriceScaleStateChange = onPriceScaleStateChange;
this.eventManager = eventManager;
this.lwcChart = lwcChart;
this.modalRenderer = modalRenderer;
this.subscribeChartEvent = subscribeChartEvent;
this.isMain = isMainPane;
this.id = id;
if (isMainPane) {
this.lwcPane = this.lwcChart.panes()[MAIN_PANE_INDEX];
} else {
this.lwcPane = this.lwcChart.addPane(true);
}
this.leftPriceScale = this.createPriceScale(Direction.Left, initialPriceScales, leftPriceScaleVisible);
this.rightPriceScale = this.createPriceScale(Direction.Right, initialPriceScales, rightPriceScaleVisible);
// TODO: Перенести PriceScaleControls внутрь PriceScale, чтобы каждая шкала владела собственными контролами, а PriceScaleControls работал только с одной шкалой.
this.priceScaleControls = new PriceScaleControls({
leftPriceScale: this.leftPriceScale,
rightPriceScale: this.rightPriceScale,
onPriceScaleChange: this.handlePriceScaleStateChange,
});
this.initializeLegend({ ohlcConfig });
this.tooltip = new TooltipService({
config: tooltipConfig,
legend: this.legend,
paneOverlayContainer: this.paneOverlayContainer,
});
this.tooltipRenderer = new ReactRenderer(this.paneOverlayContainer);
this.tooltipRenderer.renderComponent(
<ChartTooltip
formatObs={this.eventManager.getChartOptionsModel()}
timeframeObs={this.eventManager.getTimeframeObs()}
viewModel={this.tooltip.getTooltipViewModel()}
tooltipConfig={this.tooltip.getConfig()}
/>,
);
if (dataSource) {
this.initializeMainSerie({ lwcChart, dataSource });
} else if (basedOn) {
this.mainSeries = basedOn.getMainSerie();
} else {
console.error('[Pane]: There is no any mainSerie for new pane');
}
this.subscriptions.add(
this.mainSeries.subscribe(() => {
this.rebindIndicators();
}),
);
this.subscriptions.add(
combineLatest([this.eventManager.hasSymbol(), this.indicatorsMap]).subscribe(([hasMainSymbol, indicators]) => {
const hasIndicator = Array.from(indicators.values()).some(
(indicator) => indicator.getIndicatorType() !== undefined,
);
this.paneEmptyStateContainer.hidden = hasMainSymbol || !hasIndicator;
}),
);
this.drawingsManager = new DrawingsManager({
// todo: менеджер дровингов должен быть один на чарт, не на пейн
pane: this,
eventManager,
DOM,
mainSeries$: this.localMainSeries.asObservable(),
lwcChart,
container: chartContainer,
modalRenderer: this.modalRenderer,
paneId: this.id,
hotkeys,
setActiveTool,
getActiveTool,
getIsEndlessMode,
continueDrawing,
});
addDrawingManager(this.drawingsManager, this.id);
this.subscriptions.add(() => removeDrawingManager(this.id));
this.subscriptions.add(
this.drawingsManager.entities().subscribe((drawings) => {
const hasRuler = drawings.some((drawing) => drawing.getDrawingName() === DrawingsNames.ruler);
this.legendContainer.style.display = hasRuler ? 'none' : '';
}),
);
}
public getLocalMainSeries = () => {
return this.localMainSeries.value;
};
public setLocalMainSeries = (next: SeriesStrategies) => {
if (!this.isMain) {
this.localMainSeries.next(next);
}
};
public isMainPane = () => {
return this.isMain;
};
public getDrawingsSnapshot(): DrawingsManagerSnapshot {
return this.drawingsManager.getSnapshot();
}
public setDrawingsSnapshot(snapshot: DrawingsManagerSnapshot): void {
this.drawingsManager.setSnapshot(snapshot);
}
public getMainSerie = () => {
return this.mainSeries;
};
public getId = () => {
return this.id;
};
public isReady = async (interval = 50): Promise<void> => {
return new Promise((resolve) => {
const check = () => {
if (this.lwcPane.getHTMLElement() === null) {
setTimeout(check, interval);
} else {
resolve();
}
};
check();
});
};
public getHTMLElement = () => {
return this.lwcPane.getHTMLElement();
};
public paneIndex = () => {
return this.lwcPane.paneIndex();
};
public getPriceScale(side: PriceScaleSide): PriceScale {
return side === Direction.Left ? this.leftPriceScale : this.rightPriceScale;
}
public setIndicator(indicatorId: string, indicator: Indicator): void {
const indicators = new Map(this.indicatorsMap.value);
indicators.set(indicatorId, indicator);
this.indicatorsMap.next(indicators);
this.priceScaleControls.refresh();
}
public removeIndicator(indicatorId: string): void {
if (!this.indicatorsMap.value.has(indicatorId)) {
return;
}
const indicators = new Map(this.indicatorsMap.value);
indicators.delete(indicatorId);
this.indicatorsMap.next(indicators);
this.priceScaleControls.refresh();
if (indicators.size === 0 && !this.isMain) {
this.onDelete();
}
}
public getDrawingManager(): DrawingsManager {
return this.drawingsManager;
}
public schedulePaneContainerSync(): void {
if (this.paneContainerSyncFrameId !== null) {
return;
}
this.paneContainerSyncFrameId = requestAnimationFrame(() => {
this.paneContainerSyncFrameId = null;
this.syncPaneContainers();
});
}
public refreshPriceScaleControls(): void {
this.priceScaleControls.refresh();
}
public resetPriceScalesAutoScale(): void {
this.leftPriceScale.enableAutoScale();
this.rightPriceScale.enableAutoScale();
this.handlePriceScaleStateChange();
}
public getSnapshot(): PaneSnapshot {
const indicators: (DOMObjectSnapshot & (IndicatorSnapshot | CompareSnapshot))[] = [];
this.indicatorsMap.value.forEach((indicator) => {
indicators.push(indicator.getSnapshot());
});
return {
isMain: this.isMain,
id: this.id,
indicators,
drawings: this.getDrawingsSnapshot(),
priceScales: [this.leftPriceScale.getSnapshot(), this.rightPriceScale.getSnapshot()],
};
}
public destroy(): void {
if (this.paneContainerSyncFrameId !== null) {
cancelAnimationFrame(this.paneContainerSyncFrameId);
this.paneContainerSyncFrameId = null;
}
this.drawingsManager.destroy();
this.subscriptions.unsubscribe();
this.tooltip?.destroy();
this.legend?.destroy();
this.legendRenderer.destroy();
this.tooltipRenderer?.destroy();
this.priceScaleControls.destroy();
this.paneEmptyStateContainer.remove();
this.legendContainer.remove();
this.paneOverlayContainer.remove();
this.indicatorsMap.complete();
this.localMainSeries.complete();
if (this.isMain) {
this.mainSeries.value?.destroy();
this.mainSeries.complete();
}
}
private createPriceScale(
side: PriceScaleSide,
initialPriceScales: PriceScaleSnapshot[],
initialVisible: boolean,
): PriceScale {
const initialMode =
initialPriceScales.find((priceScaleSnapshot) => priceScaleSnapshot.side === side)?.mode ?? PriceScaleMode.Normal;
return new PriceScale({
paneId: this.id,
side,
pane: this.lwcPane,
initialMode,
initialVisible,
hasVisibleSeriesData: () => this.hasVisibleSeriesData(side),
});
}
private hasVisibleSeriesData(side: PriceScaleSide): boolean {
const mainSeries = this.mainSeries.value;
const defaultPriceScaleSide = this.lwcChart.options().defaultVisiblePriceScaleId as PriceScaleSide;
if (this.isMain && side === defaultPriceScaleSide && mainSeries?.isVisible() && mainSeries.data().length > 0) {
return true;
}
const indicators = Array.from(this.indicatorsMap.value.values());
for (let indicatorIndex = 0; indicatorIndex < indicators.length; indicatorIndex += 1) {
const series = Array.from(indicators[indicatorIndex].getSeriesMap().values());
for (let seriesIndex = 0; seriesIndex < series.length; seriesIndex += 1) {
const currentSeries = series[seriesIndex];
const seriesPriceScaleSide = (currentSeries.options().priceScaleId ?? defaultPriceScaleSide) as PriceScaleSide;
if (currentSeries.isVisible() && currentSeries.data().length > 0 && seriesPriceScaleSide === side) {
return true;
}
}
}
return false;
}
private handlePriceScaleStateChange = (): void => {
this.priceScaleControls.refresh();
this.onPriceScaleStateChange();
};
private initializeLegend({ ohlcConfig }: { ohlcConfig: OHLCConfig }): void {
const { legendContainer, paneOverlayContainer, paneEmptyStateContainer } = ContainerManager.createPaneContainers();
this.legendContainer = legendContainer;
this.paneOverlayContainer = paneOverlayContainer;
this.paneEmptyStateContainer = paneEmptyStateContainer;
this.paneEmptyStateContainer.textContent = t('Add a main instrument to display indicators');
this.legendRenderer = new ReactRenderer(legendContainer);
this.schedulePaneContainerSync();
this.legend = new Legend({
config: ohlcConfig,
indicators: this.indicatorsMap,
eventManager: this.eventManager,
subscribeChartEvent: this.subscribeChartEvent,
mainSeries: this.isMain ? this.mainSeries : null,
paneId: this.id,
paneIndex: this.paneIndex,
openIndicatorSettings: (indicatorId, indicator) => {
let settings = indicator.getSettingsValues();
this.modalRenderer.renderComponent(
<EntitySettingsModal
tabs={[
{
key: 'arguments',
label: t('Arguments'),
fields: indicator.getSettingsFields(),
},
]}
values={settings}
onChange={(nextSettings) => {
settings = nextSettings;
}}
initialTabKey="arguments"
/>,
{
size: 'sm',
title: indicatorLabelById()[indicatorId],
onSave: () => indicator.updateSettings(settings),
},
);
},
// todo: throw isMainPane
});
this.legendRenderer.renderComponent(
<LegendComponent
ohlcConfig={this.legend.getConfig()}
viewModel={this.legend.getLegendViewModel()}
/>,
);
}
private rebindIndicators(): void {
for (const indicator of this.indicatorsMap.value.values()) {
indicator.recreateSeries();
}
}
private initializeMainSerie({ lwcChart, dataSource }: { lwcChart: IChartApi; dataSource: DataSource }): void {
this.localMainSeries = this.mainSeries;
this.subscriptions.add(
this.eventManager.subscribeSeriesSelected((nextSeries) => {
this.mainSeries.value?.destroy();
const next = ensureDefined(SeriesFactory.create(nextSeries))({
lwcChart,
dataSource,
mainSymbolId$: this.eventManager.symbolId(),
mainSymbol$: this.eventManager.symbol(),
mainSerie$: this.mainSeries,
});
this.mainSeries.next(next);
this.priceScaleControls.refresh();
}),
);
}
private syncPaneContainers(): void {
const lwcPaneElement = this.lwcPane.getHTMLElement();
if (!lwcPaneElement) {
this.schedulePaneContainerSync();
return;
}
/*
Внутри lightweight-chart DOM построен как таблица из 3 td
[0] left priceScale, [1] center chart, [2] right priceScale
Кладём легенду в td[1] и тогда легенда сама будет адаптироваться при изменении ширины шкал
*/
const cells = lwcPaneElement.querySelectorAll<HTMLTableCellElement>(':scope > td');
const chartCell = cells.item(1);
if (!chartCell) {
this.schedulePaneContainerSync();
return;
}
chartCell.style.position = 'relative';
chartCell.appendChild(this.legendContainer);
chartCell.appendChild(this.paneEmptyStateContainer);
chartCell.appendChild(this.paneOverlayContainer);
this.priceScaleControls.mount(lwcPaneElement);
}
}
import { type Observable, Subscription } from 'rxjs';
import { DataSource } from '@core/DataSource';
import { DrawingsManagerSnapshot } from '@core/DrawingsManager';
import { DrawingsManagerCollection } from '@core/DrawingsManagerCollection';
import { Pane, PaneParams } from '@core/Pane';
import { PriceAxisLabels } from '@core/PriceAxisLabels';
import { DrawingsNames } from '@src/constants';
import { ActiveDrawingTool, Direction } from '@src/types';
import { ISerializable, PaneSnapshot, PriceScaleSide, PriceScaleSnapshot } from '@src/types/snapshot';
import type { Indicator } from '@core/Indicator';
import type { IChartApi, LogicalRange, MouseEventParams } from 'lightweight-charts';
interface PaneManagerParams
extends Omit<
PaneParams,
'id' | 'isMainPane' | 'basedOn' | 'onDelete' | 'initialPriceScales' | CollectionDependencies
> {
panesSnapshot: PaneSnapshot[];
}
type CollectionDependencies =
| 'onPriceScaleStateChange'
| 'leftPriceScaleVisible'
| 'rightPriceScaleVisible'
| 'addDrawingManager'
| 'removeDrawingManager'
| 'setActiveTool'
| 'getActiveTool'
| 'getIsEndlessMode'
| 'continueDrawing';
interface PaneManagerStartParams {
compareEntities$: Observable<Indicator[]>;
indicatorEntities$: Observable<Indicator[]>;
}
type SharedPaneParams = Omit<PaneManagerParams, 'panesSnapshot'>;
// todo: PaneManager, регулирует порядок пейнов. Знает про MainPane.
// todo: Также перекинуть соответствующие/необходимые свойства из чарта, и из чарта удалить
// todo: в CompareManage, при создании нового пейна для сравнения - инициализируем новый dataSource, принадлежащий только конкретному пейну. Убираем возможность добавлять индикаторы на такие пейны
// todo: на каждый символ свой DataSource (учитывать что есть MainPane и "главный" DataSource, который инициализиурется во время старта moexChart)
// todo: сделать два разных представления для compare, в зависимости от отображения на главном пейне или на второстепенном
export class PaneManager implements ISerializable<PaneSnapshot[]> {
private readonly sharedPaneParams: SharedPaneParams;
private readonly lwcChart: IChartApi;
private readonly panesMap = new Map<number, Pane>();
private mainPane: Pane;
private nextPaneId: number;
private priceAxisLabels: PriceAxisLabels | null = null;
private leftPriceScaleVisible = false;
private rightPriceScaleVisible = true;
private drawingsManagerCollection: DrawingsManagerCollection;
private readonly subscriptions = new Subscription();
constructor({ panesSnapshot, ...sharedPaneParams }: PaneManagerParams) {
this.sharedPaneParams = {
...sharedPaneParams,
};
this.lwcChart = sharedPaneParams.lwcChart;
const mainPaneSnapshot = panesSnapshot.find((paneSnapshot) => paneSnapshot.isMain);
const mainPaneId = mainPaneSnapshot?.id ?? 0;
this.drawingsManagerCollection = new DrawingsManagerCollection({
hotkeys: sharedPaneParams.hotkeys,
});
this.mainPane = new Pane({
...this.sharedPaneParams,
...this.getCollectionDependencies(),
id: mainPaneId,
isMainPane: true,
onDelete: () => {},
initialPriceScales: mainPaneSnapshot?.priceScales, // todo: add to sharedParams?
});
this.panesMap.set(mainPaneId, this.mainPane);
if (mainPaneSnapshot) {
this.mainPane.setDrawingsSnapshot(mainPaneSnapshot.drawings);
}
const greatestPaneId = panesSnapshot.reduce(
(greatestId, paneSnapshot) => Math.max(greatestId, paneSnapshot.id),
mainPaneId,
);
this.nextPaneId = greatestPaneId + 1;
panesSnapshot.forEach((paneSnapshot) => {
if (paneSnapshot.isMain) {
return;
}
if (paneSnapshot.indicators.length === 0 && paneSnapshot.drawings.length === 0) {
return;
}
const pane = this.addPane(undefined, paneSnapshot.id, paneSnapshot.priceScales);
pane.setDrawingsSnapshot(paneSnapshot.drawings);
});
this.initClickListener();
this.syncPaneContainers();
}
public start({ compareEntities$, indicatorEntities$ }: PaneManagerStartParams): void {
this.priceAxisLabels?.destroy();
this.priceAxisLabels = new PriceAxisLabels({
mainSeries$: this.mainPane.getMainSerie().asObservable(),
mainSymbol$: this.sharedPaneParams.eventManager.symbol(),
compareEntities$,
indicatorEntities$,
});
}
public getDrawingsCollectionManager(): DrawingsManagerCollection {
return this.drawingsManagerCollection;
}
public setVisibleLogicalRange(logicalRange: LogicalRange | null): void {
this.priceAxisLabels?.setVisibleLogicalRange(logicalRange);
}
public invalidate(): void {
this.priceAxisLabels?.invalidate();
this.refreshPriceScaleControls();
}
public setPriceScaleSideVisible(side: PriceScaleSide, visible: boolean): void {
if (side === Direction.Left) {
this.leftPriceScaleVisible = visible;
} else {
this.rightPriceScaleVisible = visible;
}
this.panesMap.forEach((pane) => {
pane.getPriceScale(side).setVisible(visible);
});
}
public getPaneByIndex(index: number): Pane | undefined {
for (const pane of this.panesMap.values()) {
if (pane.paneIndex() === index) {
return pane;
}
}
return undefined;
}
public getPaneById(id: number): Pane | undefined {
return this.panesMap.get(id);
}
public getDrawingsSnapshot(): DrawingsManagerSnapshot {
return this.mainPane.getDrawingsSnapshot();
}
public setDrawingsSnapshot(snapshot: DrawingsManagerSnapshot): void {
this.mainPane.setDrawingsSnapshot(snapshot);
}
public getPanes(): Map<number, Pane> {
return this.panesMap;
}
public getMainPane = (): Pane => {
return this.mainPane;
};
public addPane(dataSource?: DataSource, paneId?: number, initialPriceScales?: PriceScaleSnapshot[]): Pane {
const id = paneId ?? this.nextPaneId++;
this.nextPaneId = Math.max(this.nextPaneId, id + 1);
const pane = new Pane({
...this.sharedPaneParams,
...this.getCollectionDependencies(),
id,
isMainPane: false,
dataSource: dataSource ?? null,
basedOn: dataSource ? undefined : this.mainPane,
onDelete: () => this.destroyPane(id),
initialPriceScales,
});
this.panesMap.set(id, pane);
this.syncPaneContainers();
this.priceAxisLabels?.invalidate();
return pane;
}
public resetPriceScalesAutoScale(): void {
this.panesMap.forEach((pane) => {
pane.resetPriceScalesAutoScale();
});
}
public getSnapshot(): PaneSnapshot[] {
const snapshot: PaneSnapshot[] = [];
this.panesMap.forEach((pane) => {
snapshot.push(pane.getSnapshot());
});
return snapshot;
}
public destroy(): void {
this.priceAxisLabels?.destroy();
this.priceAxisLabels = null;
this.subscriptions.unsubscribe();
this.panesMap.forEach((pane) => {
pane.destroy();
});
this.drawingsManagerCollection.destroy();
this.panesMap.clear();
}
private initClickListener(): void {
const handler = (param: MouseEventParams) => {
if (param.paneIndex === undefined) {
return;
}
const clickedPane = this.getPaneByIndex(param.paneIndex);
if (!clickedPane) {
return;
}
this.drawingsManagerCollection.handlePaneClick(clickedPane, param);
};
this.lwcChart.subscribeClick(handler);
this.subscriptions.add(() => this.lwcChart.unsubscribeClick(handler));
}
private refreshPriceScaleControls(): void {
this.panesMap.forEach((pane) => {
pane.refreshPriceScaleControls();
});
}
private destroyPane(id: number): void {
const pane = this.panesMap.get(id);
if (!pane) {
return;
}
const paneIndex = pane.paneIndex();
this.panesMap.delete(id);
pane.destroy();
if (paneIndex >= 0) {
this.sharedPaneParams.lwcChart.removePane(paneIndex);
}
this.syncPaneContainers();
this.priceAxisLabels?.invalidate();
}
private syncPaneContainers(): void {
this.panesMap.forEach((pane) => {
pane.schedulePaneContainerSync();
});
}
private getCollectionDependencies(): Pick<PaneParams, CollectionDependencies> {
return {
onPriceScaleStateChange: this.handlePriceScaleStateChange,
leftPriceScaleVisible: this.leftPriceScaleVisible,
rightPriceScaleVisible: this.rightPriceScaleVisible,
addDrawingManager: (manager, paneId) => this.drawingsManagerCollection.addDrawingManager(manager, paneId),
removeDrawingManager: (paneId: number) => this.drawingsManagerCollection.removeDrawingManager(paneId),
setActiveTool: (name: ActiveDrawingTool) => this.drawingsManagerCollection.setActiveTool(name),
getActiveTool: () => this.drawingsManagerCollection.getActiveToolValue(),
getIsEndlessMode: () => this.drawingsManagerCollection.getIsEndlessMode(),
continueDrawing: (name: DrawingsNames) => this.drawingsManagerCollection.activateDrawingTool(name),
};
}
private handlePriceScaleStateChange = (): void => {
this.priceAxisLabels?.invalidate();
};
}
import { CandlestickSeriesStrategy, LineSeriesStrategy } from '@core';
import { BaseSeriesParams } from '@core/Series/BaseSeries';
import { BarSeriesStrategy } from '@src/core/Series/BarSeriesStrategy';
import { HistogramSeriesStrategy } from '@src/core/Series/HistogramSeriesStrategy';
import { ISeries } from '@src/modules/series-strategies/ISeries';
import { ChartSeriesType } from '@src/types';
export type SeriesStrategies =
| CandlestickSeriesStrategy
| LineSeriesStrategy
| HistogramSeriesStrategy
| BarSeriesStrategy;
// ISeries<'Baseline'> теперь несовместима с *SeriesStrategy
// todo: расширить ISeries<Baseline | Area | Custom>
// | ISeries<'Baseline'>
// | ISeries<'Area'>
// | ISeries<'Custom'>;
/**
x * Фабрика для создания стратегий серий
* Реализует паттерн Factory для создания нужной стратегии по типу графика
*/
export class SeriesFactory {
static create(
type: ChartSeriesType,
):
| ((params: BaseSeriesParams<'Candlestick'>) => CandlestickSeriesStrategy)
| ((params: BaseSeriesParams<'Histogram'>) => HistogramSeriesStrategy)
| ((params: BaseSeriesParams<'Line'>) => LineSeriesStrategy)
| ((params: BaseSeriesParams<'Bar'>) => BarSeriesStrategy) {
if (type === 'Candlestick') {
return ((params) => new CandlestickSeriesStrategy(params)) as (
params: BaseSeriesParams<'Candlestick'>,
) => CandlestickSeriesStrategy;
}
if (type === 'Histogram') {
return ((params) => new HistogramSeriesStrategy(params)) as (
params: BaseSeriesParams<'Histogram'>,
) => HistogramSeriesStrategy;
}
if (type === 'Line') {
return ((params) => new LineSeriesStrategy(params)) as (params: BaseSeriesParams<'Line'>) => LineSeriesStrategy;
}
if (type === 'Bar') {
return ((params) => new BarSeriesStrategy(params)) as (params: BaseSeriesParams<'Bar'>) => BarSeriesStrategy;
}
throw new Error(`Unsupported chart type: ${type}`);
}
}
import { SeriesType } from 'lightweight-charts';
import { IBaseSeries } from '@core/Series/BaseSeries';
import { Candle, Destroyable, LineCandle } from '../../types/chart';
export interface ISeries<TSeries extends SeriesType> extends IBaseSeries<TSeries>, Destroyable {
show(): void;
isVisible(): boolean;
hide(): void;
validateData(data: (Partial<Candle> & Partial<LineCandle>)[]): boolean;
getTypeName(): string;
}
import { type BehaviorSubject, distinctUntilChanged, type Observable, Subscription } from 'rxjs';
import { MAIN_PANE_INDEX } from '@src/constants';
import { type Candle } from '@src/types';
import { formatPrice, getPricePrecisionStep, isBarData, isLineData, normalizeSeriesData } from '@src/utils';
import type { DataSource } from '@core/DataSource';
import type { Indicator } from '@core/Indicator';
import type { ChartTypeToCandleData, IndicatorDataFormatter } from '@core/Indicators';
import type { Ohlc } from '@core/Legend';
import type { SeriesStrategies } from '@src/modules/series-strategies/SeriesFactory';
import type {
BarData,
BarPrice,
BarsInfo,
Coordinate,
CreatePriceLineOptions,
CustomData,
DataChangedHandler,
DeepPartial,
HistogramData,
IChartApi,
IPaneApi,
IPriceFormatter,
IPriceLine,
IPriceScaleApi,
IRange,
ISeriesApi,
ISeriesPrimitive,
LineData,
MismatchDirection,
MouseEventParams,
PriceScaleOptions,
SeriesDataItemTypeMap,
SeriesDefinition,
SeriesOptionsMap,
SeriesPartialOptionsMap,
SeriesType,
Time,
} from 'lightweight-charts';
export interface SerieData {
time: Time;
customValues: Candle;
}
export interface CreateSeriesParams<TSeries extends SeriesType> {
chart: IChartApi;
seriesOptions?: SeriesPartialOptionsMap[TSeries];
paneIndex?: number;
priceScaleOptions?: DeepPartial<PriceScaleOptions>;
}
export interface IBaseSeries<TSeries extends SeriesType> extends ISeriesApi<TSeries> {
getLwcSeries: () => ISeriesApi<TSeries>;
getLegendData: (param?: MouseEventParams) => Partial<
Record<
keyof Ohlc,
{
value: number | string | Time;
color: string;
name: string;
}
>
>;
}
export interface BaseSeriesParams<TSeries extends SeriesType = SeriesType> {
lwcChart: IChartApi;
dataSource: DataSource;
mainSymbolId$: Observable<string>;
mainSymbol$: Observable<string>;
mainSerie$: BehaviorSubject<SeriesStrategies | null>;
actLikeMainSerie?: boolean;
customFormatter?: (params: IndicatorDataFormatter<TSeries>) => SeriesDataItemTypeMap<Time>[TSeries][];
seriesOptions?: SeriesPartialOptionsMap[TSeries];
priceScaleOptions?: DeepPartial<PriceScaleOptions>;
showSymbolLabel?: boolean;
paneIndex?: number;
indicatorReference?: Indicator;
}
export abstract class BaseSeries<TSeries extends SeriesType> implements IBaseSeries<TSeries> {
protected lwcSeries: ISeriesApi<TSeries>;
protected customFormatter?: (params: IndicatorDataFormatter<TSeries>) => SeriesDataItemTypeMap<Time>[TSeries][];
protected lwcChart: IChartApi;
protected mainSymbolId$: Observable<string>;
protected mainSymbol$: Observable<string>;
protected mainSerie$: BehaviorSubject<SeriesStrategies | null>;
protected paneIndex: number | null = null;
protected indicatorReference: Indicator | null = null;
protected showSymbolLabel: boolean;
private subscriptions = new Subscription();
private dataSub: Subscription | null = null;
private realtimeSub: Subscription | null = null;
public actLikeMainSerie = false;
constructor({
lwcChart,
mainSymbolId$,
mainSymbol$,
mainSerie$,
customFormatter,
seriesOptions,
priceScaleOptions,
showSymbolLabel = true,
paneIndex,
indicatorReference,
actLikeMainSerie,
}: BaseSeriesParams<TSeries>) {
this.lwcSeries = this.createSeries({
chart: lwcChart,
seriesOptions,
paneIndex,
priceScaleOptions,
});
this.actLikeMainSerie = actLikeMainSerie ?? false;
this.lwcChart = lwcChart;
this.customFormatter = customFormatter;
this.mainSymbolId$ = mainSymbolId$;
this.mainSymbol$ = mainSymbol$;
this.mainSerie$ = mainSerie$;
this.showSymbolLabel = showSymbolLabel;
this.indicatorReference = indicatorReference ?? null;
}
public getLegendData = (
param?: MouseEventParams,
): Partial<
Record<
keyof Ohlc,
{
value: number | string | Time;
color: string;
name: string;
}
>
> => {
if (!param) {
const seriesData = this.data();
const currentBar = seriesData[seriesData.length - 1];
if (!currentBar) {
return {};
}
return this.formatLegendValues(currentBar, seriesData[seriesData.length - 2] ?? null);
}
const currentBar = param.seriesData.get(this.lwcSeries) ?? null;
const previousBar = param.logical === null ? null : this.dataByIndex(param.logical! - 1);
return this.formatLegendValues(currentBar, previousBar);
};
public show(): void {
this.lwcSeries.applyOptions({
visible: true,
});
}
public hide(): void {
this.lwcSeries.applyOptions({
visible: false,
});
}
public isVisible(): boolean {
return this.lwcSeries.options().visible;
}
public destroy(): void {
this.dataSub?.unsubscribe();
this.realtimeSub?.unsubscribe();
this.subscriptions.unsubscribe();
this.lwcChart.removeSeries(this.lwcSeries);
}
public getLwcSeries(): ISeriesApi<TSeries> {
return this.lwcSeries;
}
public applyOptions(options: SeriesPartialOptionsMap[TSeries]): void {
this.lwcSeries.applyOptions(options);
}
public attachPrimitive(primitive: ISeriesPrimitive<Time>): void {
this.lwcSeries.attachPrimitive(primitive);
}
public barsInLogicalRange(range: IRange<number>): BarsInfo<Time> | null {
return this.lwcSeries.barsInLogicalRange(range);
}
public coordinateToPrice(coordinate: number): BarPrice | null {
return this.lwcSeries.coordinateToPrice(coordinate);
}
public createPriceLine(options: CreatePriceLineOptions): IPriceLine {
return this.lwcSeries.createPriceLine(options);
}
public data(): readonly SeriesDataItemTypeMap<Time>[TSeries][] {
return this.lwcSeries.data();
}
public pop(count: number): SeriesDataItemTypeMap<Time>[TSeries][] {
return this.lwcSeries.pop(count);
}
public dataByIndex(
logicalIndex: number,
mismatchDirection?: MismatchDirection,
): SeriesDataItemTypeMap<Time>[TSeries] | null {
return this.lwcSeries.dataByIndex(logicalIndex, mismatchDirection);
}
public detachPrimitive(primitive: ISeriesPrimitive<Time>): void {
this.lwcSeries.detachPrimitive(primitive);
}
public getPane(): IPaneApi<Time> {
return this.lwcSeries.getPane();
}
public moveToPane(paneIndex: number): void {
this.lwcSeries.moveToPane(paneIndex);
}
public options(): Readonly<SeriesOptionsMap[TSeries]> {
return this.lwcSeries.options();
}
public priceFormatter(): IPriceFormatter {
return this.lwcSeries.priceFormatter();
}
public priceLines(): IPriceLine[] {
return this.lwcSeries.priceLines();
}
public priceScale(): IPriceScaleApi {
return this.lwcSeries.priceScale();
}
public priceToCoordinate(price: number): Coordinate | null {
return this.lwcSeries.priceToCoordinate(price);
}
public removePriceLine(line: IPriceLine): void {
this.lwcSeries.removePriceLine(line);
}
public seriesOrder(): number {
return this.lwcSeries.seriesOrder();
}
public seriesType(): TSeries {
return this.lwcSeries.seriesType();
}
public lastValueData(globalLast: boolean): ReturnType<ISeriesApi<TSeries>['lastValueData']> {
return this.lwcSeries.lastValueData(globalLast);
}
public setData(data: SeriesDataItemTypeMap<Time>[TSeries][]): void {
this.lwcSeries.setData(normalizeSeriesData(data));
}
public setSeriesOrder(order: number): void {
this.lwcSeries.setSeriesOrder(order);
}
public subscribeDataChanged(handler: DataChangedHandler): void {
this.lwcSeries.subscribeDataChanged(handler);
}
public unsubscribeDataChanged(handler: DataChangedHandler): void {
this.lwcSeries.unsubscribeDataChanged(handler);
}
public update(bar: SeriesDataItemTypeMap<Time>[TSeries], historicalUpdate?: boolean): void {
const data = this.lwcSeries.data();
const lastBar = data[data.length - 1];
if (!lastBar) {
this.lwcSeries.update(bar, false);
return;
}
const isHistoricalUpdate =
historicalUpdate ?? (typeof lastBar.time === 'number' && typeof bar.time === 'number' && bar.time < lastBar.time);
this.lwcSeries.update(bar, isHistoricalUpdate);
}
protected createSeries({
chart,
seriesOptions,
paneIndex = MAIN_PANE_INDEX,
priceScaleOptions = {},
}: CreateSeriesParams<TSeries>): ISeriesApi<TSeries> {
this.paneIndex = paneIndex;
const options = {
...this.getDefaultOptions(),
...seriesOptions,
};
const series = chart.addSeries<TSeries>(this.seriesDefinition(), options, paneIndex);
series.priceScale().applyOptions(priceScaleOptions);
return series;
}
protected abstract dataSourceSubscription(next: Candle[]): void;
protected abstract seriesDefinition(): SeriesDefinition<TSeries>;
protected abstract dataSourceRealtimeSubscription(next: Candle): void;
protected abstract getDefaultOptions(): SeriesPartialOptionsMap[TSeries];
protected abstract formatMainSerie(inputData: Candle[]): SeriesDataItemTypeMap<Time>[TSeries][];
protected abstract formatLegendValues(
currentBar: BarData | LineData | HistogramData | CustomData | null,
prevBar: BarData | LineData | HistogramData | CustomData | null,
): Partial<
Record<
keyof Ohlc,
{
value: number | string | Time;
color: string;
name: string;
}
>
>;
protected formatData(inputData: Candle[]): SeriesDataItemTypeMap<Time>[TSeries][] {
if (!this.customFormatter) {
return this.formatMainSerie(inputData);
}
const mainSeriesData = (this.mainSerie$.value?.data() ?? []) as unknown as SerieData[];
const selfData = this.data() as unknown as ChartTypeToCandleData[TSeries][];
if (inputData.length !== 1) {
return this.customFormatter({
mainSeriesData,
selfData,
indicatorReference: this.indicatorReference ?? undefined,
});
}
const candle = this.formatMainSerie(inputData)[0];
if (!candle) {
return [];
}
return this.customFormatter({
mainSeriesData,
selfData,
candle: candle as unknown as SerieData,
indicatorReference: this.indicatorReference ?? undefined,
});
}
protected subscribeDataSource = (dataSource: DataSource): void => {
const minMove = getPricePrecisionStep();
this.lwcSeries.applyOptions({
priceFormat: {
type: 'custom',
minMove,
formatter: (price: number) => formatPrice(price) ?? String(price),
},
});
this.subscriptions.add(
this.mainSymbol$.pipe(distinctUntilChanged()).subscribe((symbol) => {
this.lwcSeries.applyOptions({
title: this.showSymbolLabel ? symbol : '',
});
}),
);
this.subscriptions.add(
this.mainSymbolId$.pipe(distinctUntilChanged()).subscribe((symbolId) => {
this.dataSub?.unsubscribe();
this.realtimeSub?.unsubscribe();
this.dataSub = dataSource.subscribe(symbolId, (next) => {
this.dataSourceSubscription(next);
});
this.realtimeSub = dataSource.subscribeRealtime(symbolId, (next: Candle) => {
this.dataSourceRealtimeSubscription(next);
});
}),
);
};
}
export function calcCandleChange(
prev: BarData | LineData | HistogramData | CustomData | null,
current: BarData | LineData | HistogramData | CustomData | null,
):
| (Ohlc & {
customValues?: Record<string, unknown>;
})
| null {
if (!current) {
return null;
}
if (!prev) {
return current;
}
if (isBarData(prev) && isBarData(current)) {
const absoluteChange = current.close - prev.close;
const percentageChange = ((current.close - prev.close) / prev.close) * 100;
return {
...current,
absoluteChange,
percentageChange: Number.isNaN(percentageChange) ? 0 : percentageChange,
};
}
if (isLineData(prev) && isLineData(current)) {
const absoluteChange = current.value - prev.value;
const percentageChange = ((current.value - prev.value) / prev.value) * 100;
const high = current.customValues?.high;
const low = current.customValues?.low;
return {
time: current.time,
value: current.value,
high: typeof high === 'number' ? high : current.value,
low: typeof low === 'number' ? low : current.value,
absoluteChange,
percentageChange: Number.isNaN(percentageChange) ? 0 : percentageChange,
customValues: current.customValues,
};
}
return null;
}
import {
BarData,
BarSeries,
CustomData,
HistogramData,
LineData,
SeriesDataItemTypeMap,
SeriesDefinition,
SeriesPartialOptionsMap,
Time,
} from 'lightweight-charts';
import { Ohlc } from '@core/Legend';
import { BaseSeries, BaseSeriesParams, calcCandleChange } from '@src/core/Series/BaseSeries';
import { ISeries } from '@src/modules/series-strategies';
import { getThemeStore } from '@src/theme';
import { t } from '@src/translations';
import { Candle, LineCandle } from '@src/types';
import { ensureDefined, formatCompactNumber, isBarData } from '@src/utils';
import { removeAlphaFromHex } from '@src/utils/removeAlphaFromHex';
export class BarSeriesStrategy extends BaseSeries<'Bar'> implements ISeries<'Bar'> {
constructor(params: BaseSeriesParams<'Bar'>) {
super(params);
this.subscribeDataSource(params.dataSource);
}
protected seriesDefinition(): SeriesDefinition<'Bar'> {
return BarSeries;
}
getDefaultOptions(): SeriesPartialOptionsMap['Bar'] {
const { colors } = getThemeStore();
return {
upColor: colors.chartCandleUp,
downColor: colors.chartCandleDown,
};
}
getTypeName(): string {
return 'Bar';
}
public validateData(data: (Partial<Candle> & Partial<LineCandle>)[]): boolean {
if (!Array.isArray(data)) {
return false;
}
return data.every((point) => typeof point.time === 'number');
}
protected dataSourceSubscription = (dataToSet: Candle[]): void => {
if (!this.validateData(dataToSet)) {
console.error(`LightweightAPI: Invalid data format for ${this.getTypeName()} chart`);
return;
}
this.setData(this.formatData(dataToSet));
};
protected dataSourceRealtimeSubscription = (dataToSet: Candle): void => {
if (!this.validateData([dataToSet])) {
console.error(`LightweightAPI: Invalid data format for ${this.getTypeName()} chart`);
return;
}
const formattedData = this.formatData([dataToSet]);
this.update(formattedData[0], true);
};
protected formatMainSerie(inputData: Candle[]): SeriesDataItemTypeMap<Time>['Bar'][] {
return inputData.map((point) => ({
time: point.time as Time,
open: point.open,
high: point.high,
low: point.low,
close: point.close,
customValues: point as unknown as Record<string, unknown>,
}));
}
protected formatLegendValues(
currentBar: null | BarData | LineData | HistogramData | CustomData,
prevBar: null | BarData | LineData | HistogramData | CustomData,
): Partial<Record<keyof Ohlc, { value: number | string | Time; color: string; name: string }>> {
if (!currentBar || !isBarData(currentBar)) {
return {};
}
const { colors } = getThemeStore();
const color = removeAlphaFromHex(
currentBar.close < currentBar.open ? colors.chartCandleWickDown : colors.chartCandleWickUp,
);
const { absoluteChange, percentageChange, time } = ensureDefined(calcCandleChange(prevBar, currentBar));
return {
open: {
value: formatCompactNumber(currentBar.open) ?? '',
name: t('Open'),
color,
},
high: {
value: formatCompactNumber(currentBar.high) ?? '',
name: t('High'),
color,
},
low: {
value: formatCompactNumber(currentBar.low) ?? '',
name: t('Low'),
color,
},
close: {
value: formatCompactNumber(currentBar.close) ?? '',
name: t('Close'),
color,
},
absoluteChange: {
value: formatCompactNumber(absoluteChange ?? 0),
name: t('Change'),
color,
},
percentageChange: {
value: percentageChange !== undefined ? `${formatCompactNumber(percentageChange)}%` : '',
name: t('Change'),
color,
},
time: {
value: time,
name: t('Time'),
color,
},
};
}
}
import {
BarData,
CandlestickSeries,
CustomData,
HistogramData,
LineData,
SeriesDataItemTypeMap,
SeriesDefinition,
SeriesPartialOptionsMap,
Time,
} from 'lightweight-charts';
import { Ohlc } from '@core/Legend';
import { BaseSeries, BaseSeriesParams, calcCandleChange } from '@core/Series/BaseSeries';
import { ISeries } from '@src/modules/series-strategies';
import { getThemeStore } from '@src/theme/store';
import { t } from '@src/translations';
import { Candle, LineCandle } from '@src/types';
import { ensureDefined, formatCompactNumber, isBarData } from '@src/utils';
import { removeAlphaFromHex } from '@src/utils/removeAlphaFromHex';
export class CandlestickSeriesStrategy extends BaseSeries<'Candlestick'> implements ISeries<'Candlestick'> {
constructor(params: BaseSeriesParams<'Candlestick'>) {
super(params);
this.subscribeDataSource(params.dataSource);
}
protected seriesDefinition(): SeriesDefinition<'Candlestick'> {
return CandlestickSeries;
}
public getDefaultOptions(): SeriesPartialOptionsMap['Candlestick'] {
const { colors } = getThemeStore();
return {
upColor: colors.chartCandleUp,
downColor: colors.chartCandleDown,
borderVisible: false,
wickUpColor: colors.chartCandleWickUp,
wickDownColor: colors.chartCandleWickDown,
};
}
public validateData(data: (Partial<Candle> & Partial<LineCandle>)[]): boolean {
// todo: should be private
if (!Array.isArray(data)) {
return false;
}
return data.every((point) => {
if (!point) {
return false;
}
// Проверяем обязательные поля
if (typeof point.time !== 'number') {
return false;
}
// Если указаны OHLC, проверяем их корректность
if (
point.open !== undefined &&
point.high !== undefined &&
point.low !== undefined &&
point.close !== undefined
) {
return point.high >= Math.max(point.open, point.close) && point.low <= Math.min(point.open, point.close);
}
return true;
});
}
public getTypeName(): string {
return 'Candlestick';
}
protected dataSourceSubscription = (dataToSet: Candle[]): void => {
if (!this.validateData(dataToSet)) {
console.error(`LightweightAPI: Invalid data format for ${this.getTypeName()} chart`);
return;
}
this.setData(this.formatData(dataToSet));
};
protected dataSourceRealtimeSubscription = (dataToSet: Candle): void => {
if (!this.validateData([dataToSet])) {
console.error(`LightweightAPI: Invalid data format for ${this.getTypeName()} chart`);
return;
}
const formattedData = this.formatData([dataToSet]);
this.update(formattedData[0], true);
};
protected formatMainSerie(inputData: Candle[]): SeriesDataItemTypeMap<Time>['Candlestick'][] {
return inputData.map((point) => ({
time: point.time as Time,
open: point.open,
high: point.high,
low: point.low,
close: point.close,
customValues: point as unknown as Record<string, unknown>,
}));
}
protected formatLegendValues(
currentBar: null | BarData | LineData | HistogramData | CustomData,
prevBar: null | BarData | LineData | HistogramData | CustomData,
): Partial<Record<keyof Ohlc, { value: number | string | Time; color: string; name: string }>> {
if (!currentBar || !isBarData(currentBar)) {
return {};
}
const { colors } = getThemeStore();
const color = removeAlphaFromHex(
currentBar.close < currentBar.open ? colors.chartCandleWickDown : colors.chartCandleWickUp,
);
const { absoluteChange, percentageChange, time } = ensureDefined(calcCandleChange(prevBar, currentBar));
return {
open: {
value: formatCompactNumber(currentBar.open) ?? '',
name: t('Open'),
color,
},
high: {
value: formatCompactNumber(currentBar.high) ?? '',
name: t('High'),
color,
},
low: {
value: formatCompactNumber(currentBar.low) ?? '',
name: t('Low'),
color,
},
close: {
value: formatCompactNumber(currentBar.close) ?? '',
name: t('Close'),
color,
},
absoluteChange: {
value: formatCompactNumber(absoluteChange ?? 0),
name: t('Change'),
color,
},
percentageChange: {
value: percentageChange !== undefined ? `${formatCompactNumber(percentageChange)}%` : '',
name: t('Change'),
color,
},
time: {
value: time,
name: t('Time'),
color,
},
};
}
}
import {
BarData,
CustomData,
HistogramData,
HistogramSeries,
LineData,
SeriesDataItemTypeMap,
SeriesDefinition,
SeriesPartialOptionsMap,
Time,
} from 'lightweight-charts';
import { Ohlc } from '@core/Legend';
import { BaseSeries, BaseSeriesParams, calcCandleChange } from '@core/Series/BaseSeries';
import { ISeries } from '@src/modules/series-strategies';
import { t } from '@src/translations';
import { Candle, LineCandle } from '@src/types';
import { ensureDefined, formatCompactNumber, isHistogramData } from '@src/utils';
import { removeAlphaFromHex } from '@src/utils/removeAlphaFromHex';
export class HistogramSeriesStrategy extends BaseSeries<'Histogram'> implements ISeries<'Histogram'> {
constructor(params: BaseSeriesParams<'Histogram'>) {
super(params);
this.subscribeDataSource(params.dataSource);
}
protected seriesDefinition(): SeriesDefinition<'Histogram'> {
return HistogramSeries;
}
protected getDefaultOptions(): SeriesPartialOptionsMap['Histogram'] {
return {};
}
public validateData(data: (Partial<Candle> & Partial<LineCandle>)[]): boolean {
if (!Array.isArray(data)) {
return false;
}
return data.every((point) => typeof point.time === 'number');
}
public getTypeName(): string {
return 'Histogram';
}
protected dataSourceSubscription = (dataToSet: Candle[]): void => {
if (!this.validateData(dataToSet)) {
console.error(`LightweightAPI: Invalid data format for ${this.getTypeName()} chart`);
return;
}
this.setData(this.formatData(dataToSet));
};
protected dataSourceRealtimeSubscription = (dataToSet: Candle): void => {
if (!this.validateData([dataToSet])) {
console.error(`LightweightAPI: Invalid data format for ${this.getTypeName()} chart`);
return;
}
const formattedData = this.formatData([dataToSet]);
this.update(formattedData[0], true);
};
protected formatMainSerie(inputData: Candle[]): SeriesDataItemTypeMap<Time>['Histogram'][] {
return inputData.map((point) => ({
time: point.time as Time,
value: point.close,
customValues: point as unknown as Record<string, unknown>,
}));
}
protected formatLegendValues(
currentBar: null | BarData | LineData | HistogramData | CustomData,
prevBar: null | BarData | LineData | HistogramData | CustomData,
): Partial<Record<keyof Ohlc, { value: number | string | Time; color: string; name: string }>> {
if (!currentBar || !isHistogramData(currentBar)) {
return {};
}
const { absoluteChange, percentageChange, time } = ensureDefined(calcCandleChange(prevBar, currentBar));
const color = currentBar.color ? removeAlphaFromHex(currentBar.color) : this.options().color;
return {
value: {
value: formatCompactNumber(currentBar.value) ?? '',
name: '',
color,
},
absoluteChange: {
value: formatCompactNumber(absoluteChange ?? 0),
name: t('Change'),
color,
},
percentageChange: {
value: percentageChange !== undefined ? `${formatCompactNumber(percentageChange)}%` : '',
name: t('Change'),
color,
},
time: {
value: time,
name: t('Time'),
color,
},
};
}
}
import {
BarData,
CustomData,
HistogramData,
LineData,
LineSeries,
LineStyle,
SeriesDataItemTypeMap,
SeriesDefinition,
SeriesPartialOptionsMap,
Time,
} from 'lightweight-charts';
import { Ohlc } from '@core/Legend';
import { BaseSeries, BaseSeriesParams, calcCandleChange } from '@core/Series/BaseSeries';
import { ISeries } from '@src/modules/series-strategies';
import { getThemeStore } from '@src/theme/store';
import { t } from '@src/translations';
import { Candle, LineCandle } from '@src/types';
import { ensureDefined, formatCompactNumber, isLineData } from '@src/utils';
import { removeAlphaFromHex } from '@src/utils/removeAlphaFromHex';
export class LineSeriesStrategy extends BaseSeries<'Line'> implements ISeries<'Line'> {
constructor(params: BaseSeriesParams<'Line'>) {
super(params);
this.subscribeDataSource(params.dataSource);
}
protected seriesDefinition(): SeriesDefinition<'Line'> {
return LineSeries;
}
protected getDefaultOptions(): SeriesPartialOptionsMap['Line'] {
const { colors } = getThemeStore();
return {
color: colors.chartLineColor,
lineWidth: 2,
lineStyle: LineStyle.Solid,
};
}
public validateData(data: (Partial<Candle> & Partial<LineCandle>)[]): boolean {
if (!Array.isArray(data)) {
return false;
}
return data.every((point) => typeof point.time === 'number');
}
public getTypeName(): string {
return 'Line';
}
protected dataSourceSubscription = (dataToSet: Candle[]): void => {
if (!this.validateData(dataToSet)) {
console.error(`LightweightAPI: Invalid data format for ${this.getTypeName()} chart`);
return;
}
this.setData(this.formatData(dataToSet));
};
protected dataSourceRealtimeSubscription = (dataToSet: Candle): void => {
if (!this.validateData([dataToSet])) {
console.error(`LightweightAPI: Invalid data format for ${this.getTypeName()} chart`);
return;
}
const formattedData = this.formatData([dataToSet]);
this.update(formattedData[0], true);
};
protected formatMainSerie(inputData: Candle[]): SeriesDataItemTypeMap<Time>['Line'][] {
return inputData.map((point) => ({
time: point.time as Time,
value: point.close, // Для line графика используем close как value
customValues: point as unknown as Record<string, unknown>,
}));
}
protected formatLegendValues(
currentBar: null | BarData | LineData | HistogramData | CustomData,
prevBar: null | BarData | LineData | HistogramData | CustomData,
): Partial<Record<keyof Ohlc, { value: number | string | Time; color: string; name: string }>> {
if (!currentBar || !isLineData(currentBar)) {
return {};
}
const { absoluteChange, percentageChange, time } = ensureDefined(calcCandleChange(prevBar, currentBar));
const color = currentBar.color ? removeAlphaFromHex(currentBar.color) : this.options().color;
return {
value: {
value: formatCompactNumber(currentBar.value) ?? '',
name: '',
color,
},
absoluteChange: {
value: formatCompactNumber(absoluteChange ?? 0),
name: t('Change'),
color,
},
percentageChange: {
value: percentageChange !== undefined ? `${formatCompactNumber(percentageChange)}%` : '',
name: t('Change'),
color,
},
time: {
value: time,
name: t('Time'),
color,
},
};
}
}