Загрузка данных
import type { ChartViewType } from './chartView';
import type { PriceScaleMode } from 'lightweight-charts';
export type SeasonalityScale = PriceScaleMode.Normal | PriceScaleMode.Percentage;
export enum SeasonalityViewType {
Chart = 'chart',
Table = 'table',
}
export interface SeasonalityRange {
fromYear: number;
toYear: number;
}
export interface SeasonalityState extends SeasonalityRange {
view: ChartViewType;
displayMode: SeasonalityViewType;
status: 'idle' | 'loading' | 'ready' | 'empty' | 'error';
scale: SeasonalityScale;
symbolId: string;
minYear: number;
maxYear: number;
error: string | null;
tableRows: SeasonalityTableRow[];
}
export interface SeasonalityPoint {
date: string;
chartDate: string;
price: number;
percentage: number | null;
}
export interface SeasonalityYear {
year: number;
baselineDate: string;
baselinePrice: number;
points: SeasonalityPoint[];
}
export interface DailyClose {
date: string;
close: number;
}
export interface SeasonalityChange {
absolute: number;
percentage: number | null;
}
export interface SeasonalityTableRow {
year: number;
months: (SeasonalityChange | null)[];
total: SeasonalityChange | null;
}
import { PriceScaleMode } from 'lightweight-charts';
import { ChartViewType, SeasonalityViewType } from '@src/types';
import type { SeasonalityState } from '@src/types';
export const DEFAULT_SEASONALITY_YEARS = 5;
export function createInitialSeasonalityState(): SeasonalityState {
const year = new Date().getUTCFullYear();
const fromYear = year - DEFAULT_SEASONALITY_YEARS + 1;
return {
view: ChartViewType.Chart,
displayMode: SeasonalityViewType.Chart,
status: 'idle',
scale: PriceScaleMode.Normal,
symbolId: '',
error: null,
minYear: fromYear,
maxYear: year,
fromYear,
toYear: year,
tableRows: [],
};
}
import { type LineData, PriceScaleMode, type WhitespaceData } from 'lightweight-charts';
import type {
DailyClose,
SeasonalityChange,
SeasonalityRange,
SeasonalityScale,
SeasonalityTableRow,
SeasonalityYear,
} from '@src/types';
type SeriesDatum = LineData | WhitespaceData;
const CALENDAR = Array.from({ length: 366 }, (_, day) =>
new Date(Date.UTC(2000, 0, day + 1)).toISOString().slice(0, 10),
);
export function normalizeRange(
range: SeasonalityRange,
minYear: number,
maxYear: number,
): SeasonalityRange {
if (!Number.isFinite(range.fromYear) || !Number.isFinite(range.toYear)) {
throw new Error('Invalid year range');
}
const fromYear = Math.max(minYear, Math.min(maxYear, Math.round(range.fromYear)));
const toYear = Math.max(fromYear, Math.min(maxYear, Math.round(range.toYear)));
return { fromYear, toYear };
}
export function buildSeasonality(rows: readonly DailyClose[]): SeasonalityYear[] {
const years: SeasonalityYear[] = [];
const sorted = [...rows].sort((a, b) => a.date.localeCompare(b.date));
for (const row of sorted) {
const year = Number(row.date.slice(0, 4));
let current = years[years.length - 1];
if (!current || current.year !== year) {
current = {
year,
baselineDate: row.date,
baselinePrice: row.close,
points: [],
};
years.push(current);
}
if (current.points[current.points.length - 1]?.date === row.date) {
throw new Error(`Multiple daily candles on ${row.date}`);
}
const percentage = current.baselinePrice > 0
? (row.close / current.baselinePrice - 1) * 100
: null;
if (percentage !== null && !Number.isFinite(percentage)) {
throw new Error('Invalid percentage');
}
current.points.push({
date: row.date,
chartDate: `2000-${row.date.slice(5)}`,
price: row.close,
percentage,
});
}
return years;
}
export function toSeriesData(
year: SeasonalityYear,
scale: SeasonalityScale,
): SeriesDatum[] {
const isPercentage = scale === PriceScaleMode.Percentage;
let index = 0;
return CALENDAR.map((time) => {
const point = year.points[index];
if (point?.chartDate !== time) {
return { time };
}
index += 1;
const value = isPercentage ? point.percentage : point.price;
return value === null ? { time } : { time, value };
});
}
export function buildSeasonalityTable(
years: readonly SeasonalityYear[],
): SeasonalityTableRow[] {
const closes = new Map<number, number>();
for (const year of years) {
for (const point of year.points) {
const month = Number(point.date.slice(5, 7)) - 1;
closes.set(year.year * 12 + month, point.price);
}
}
return years
.map((year) => {
const firstMonth = year.year * 12;
const lastPoint = year.points[year.points.length - 1];
return {
year: year.year,
months: Array.from({ length: 12 }, (_, month) => {
const key = firstMonth + month;
return calculateChange(closes.get(key - 1), closes.get(key));
}),
total: calculateChange(closes.get(firstMonth - 1), lastPoint.price),
};
})
.reverse();
}
function calculateChange(
from: number | undefined,
to: number | undefined,
): SeasonalityChange | null {
if (from === undefined || to === undefined) {
return null;
}
return {
absolute: to - from,
percentage: from > 0 ? (to / from - 1) * 100 : null,
};
}
import { PriceScaleMode } from 'lightweight-charts';
import { Button } from '@src/components/Button';
import { Dropdown } from '@src/components/Dropdown';
import { RangeField } from '@src/components/FormFields';
import { SeasonalityScaleMenu } from '@src/components/Menu/SeasonalityScaleMenu';
import { t } from '@src/translations';
import { ChartViewType, SeasonalityViewType } from '@src/types';
import { useObservable } from '@src/utils';
import styles from './index.module.scss';
import type {
SeasonalityRange,
SeasonalityScale,
SeasonalityState,
} from '@src/types';
import type { Observable } from 'rxjs';
interface SeasonalityControlsProps {
stateObs: Observable<SeasonalityState>;
setDisplayMode: (displayMode: SeasonalityViewType) => void;
setScale: (scale: SeasonalityScale) => void;
setRange: (range: SeasonalityRange) => void;
}
export function SeasonalityControls({
stateObs,
setDisplayMode,
setScale,
setRange,
}: SeasonalityControlsProps) {
const state = useObservable(stateObs);
if (!state || state.view !== ChartViewType.Seasonality) {
return null;
}
const handleRangeChange = ([fromYear, toYear]: [number, number]) => {
setRange({ fromYear, toYear });
};
return (
<div className={styles.controls}>
<div className={styles.controls_header}>
<div className={styles.controls_views}>
<Button
label={t('Chart')}
pressed={state.displayMode === SeasonalityViewType.Chart}
onClick={() => setDisplayMode(SeasonalityViewType.Chart)}
/>
<Button
label={t('Table')}
pressed={state.displayMode === SeasonalityViewType.Table}
onClick={() => setDisplayMode(SeasonalityViewType.Table)}
/>
</div>
<Dropdown selectedValue={state.scale === PriceScaleMode.Normal ? t('Price') : t('Percent')}>
<SeasonalityScaleMenu
selectedScale={state.scale}
onClick={setScale}
/>
</Dropdown>
</div>
<div className={styles.controls_range}>
<RangeField
mode="range"
value={[state.fromYear, state.toYear]}
min={state.minYear}
max={state.maxYear}
step={1}
suffix=""
size="sm"
disabled={state.status === 'loading' || state.status === 'error'}
onRangeChange={handleRangeChange}
/>
</div>
</div>
);
}
.controls {
display: flex;
flex-direction: column;
width: 100%;
gap: var(--space-0500);
&_header {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-0500);
}
&_views {
display: flex;
align-items: center;
gap: var(--space-0125);
}
&_range {
min-width: 0;
}
}
import { PriceScaleMode } from 'lightweight-charts';
import { useMemo } from 'react';
import { getLocale, t } from '@src/translations';
import { ChartViewType, SeasonalityViewType } from '@src/types';
import { useObservable } from '@src/utils';
import styles from './index.module.scss';
import type { SeasonalityChange, SeasonalityState } from '@src/types';
import type { Observable } from 'rxjs';
const MONTHS = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December',
] as const;
interface SeasonalityTableProps {
stateObs: Observable<SeasonalityState>;
}
export function SeasonalityTable({ stateObs }: SeasonalityTableProps) {
const state = useObservable(stateObs);
const locale = getLocale();
const formatter = useMemo(
() => new Intl.NumberFormat(locale, {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
}),
[locale],
);
if (
!state ||
state.view !== ChartViewType.Seasonality ||
state.displayMode !== SeasonalityViewType.Table ||
state.status !== 'ready'
) {
return null;
}
const isPercentage = state.scale === PriceScaleMode.Percentage;
const renderCell = (
change: SeasonalityChange | null,
key: string | number,
) => {
const value = change?.[isPercentage ? 'percentage' : 'absolute'] ?? null;
let className = styles.table_cell;
if (value !== null && value > 0) {
className += ` ${styles.table_cell_positive}`;
}
if (value !== null && value < 0) {
className += ` ${styles.table_cell_negative}`;
}
const text = value === null
? '—'
: `${formatter.format(value)}${isPercentage ? '%' : ''}`;
return (
<td
key={key}
className={className}
>
{text}
</td>
);
};
return (
<div className={styles.table}>
<table className={styles.table_content}>
<thead>
<tr>
<th scope="col">{t('Date')}</th>
{MONTHS.map((month) => (
<th
key={month}
scope="col"
>
{t(month)}
</th>
))}
<th scope="col">{t('Year')}</th>
</tr>
</thead>
<tbody>
{state.tableRows.map((row) => (
<tr key={row.year}>
<th scope="row">{row.year}</th>
{row.months.map((change, month) => renderCell(change, month))}
{renderCell(row.total, 'total')}
</tr>
))}
</tbody>
</table>
</div>
);
}
.table {
position: absolute;
inset: 0;
overflow: auto;
color: var(--seasonality-text);
background: var(--seasonality-background);
font-variant-numeric: tabular-nums;
&_content {
width: 100%;
border-collapse: separate;
border-spacing: 0;
white-space: nowrap;
th,
td {
padding: var(--space-0750) var(--space-1000);
border-right: 1px solid var(--seasonality-border);
border-bottom: 1px solid var(--seasonality-border);
text-align: right;
font-weight: 400;
}
th {
background: var(--seasonality-background);
}
thead th {
position: sticky;
top: 0;
z-index: 2;
border-top: 1px solid var(--seasonality-border);
}
th:first-child {
position: sticky;
left: 0;
z-index: 1;
text-align: left;
}
thead th:first-child {
z-index: 3;
}
th:last-child,
td:last-child {
border-right: 0;
font-weight: 600;
}
}
&_cell {
background: transparent;
&_positive {
background: color-mix(
in srgb,
#089981 25%,
var(--seasonality-background)
);
}
&_negative {
background: color-mix(
in srgb,
#f23645 35%,
var(--seasonality-background)
);
}
}
}
import { createPortal } from 'react-dom';
import { SeasonalityControls } from '@src/components/SeasonalityControls';
import { SeasonalityTable } from '@src/components/SeasonalityTable';
import type {
SeasonalityRange,
SeasonalityScale,
SeasonalityState,
SeasonalityViewType,
} from '@src/types';
import type { Observable } from 'rxjs';
interface SeasonalityPanelProps {
stateObs: Observable<SeasonalityState>;
contentContainer: HTMLElement;
setDisplayMode: (displayMode: SeasonalityViewType) => void;
setScale: (scale: SeasonalityScale) => void;
setRange: (range: SeasonalityRange) => void;
}
export function SeasonalityPanel({
contentContainer,
...controlsProps
}: SeasonalityPanelProps) {
return (
<>
<SeasonalityControls {...controlsProps} />
{createPortal(
<SeasonalityTable stateObs={controlsProps.stateObs} />,
contentContainer,
)}
</>
);
}
import dayjs from 'dayjs';
import {
ColorType,
createChart,
createSeriesMarkers,
CrosshairMode,
type IChartApi,
type ISeriesApi,
type ISeriesMarkersPluginApi,
LineSeries,
LineStyle,
type MouseEventParams,
PriceScaleMode,
type Time,
} from 'lightweight-charts';
import { BehaviorSubject } from 'rxjs';
import { createInitialSeasonalityState } from '@src/constants';
import { ZIndex } from '@src/core/ContainerManager';
import { COMPARE_COLOR_PALETTE } from '@src/theme';
import { getThemeStore } from '@src/theme/store';
import { getLocale, t } from '@src/translations';
import { ChartViewType, SeasonalityViewType } from '@src/types';
import { Timeframes } from '@src/types/timeframes';
import {
buildSeasonality,
buildSeasonalityTable,
canvasToBlob,
drawTextLayer,
formatCompactNumber,
normalizeRange,
toSeriesData,
} from '@src/utils';
import type { DataSourceParams } from '@src/core/DataSource';
import type {
Candle,
DailyClose,
SeasonalityRange,
SeasonalityScale,
SeasonalityTableRow,
SeasonalityYear,
} from '@src/types';
interface SeasonalityManagerParams {
container: HTMLElement;
getData: DataSourceParams['getData'];
precision?: number;
onOpen: () => void;
onBack: () => void;
}
interface SeasonalityPlot {
year: SeasonalityYear;
series: ISeriesApi<'Line'>;
legend: HTMLSpanElement;
legendValue: HTMLSpanElement;
markers?: ISeriesMarkersPluginApi<Time>;
}
const DEFAULT_YEARS = 5;
export class SeasonalityManager {
private readonly currentYear = dayjs().year();
private readonly state = new BehaviorSubject(createInitialSeasonalityState());
private readonly chartContainer = document.createElement('div');
private readonly legend = document.createElement('div');
private readonly statusElement = document.createElement('div');
private readonly plots = new Map<number, SeasonalityPlot>();
private chart: IChartApi | null = null;
private allYears: SeasonalityYear[] = [];
private allTableRows: SeasonalityTableRow[] = [];
private requestId = 0;
private renderFrame: number | null = null;
private destroyed = false;
constructor(private readonly params: SeasonalityManagerParams) {
Object.assign(this.chartContainer.style, {
position: 'absolute',
inset: 0,
});
Object.assign(this.legend.style, {
width: 'max-content',
position: 'absolute',
top: 0,
left: 0,
display: 'grid',
gridTemplateColumns: 'max-content max-content',
justifyContent: 'start',
alignItems: 'center',
gap: 'var(--space-0125) var(--space-0500)',
fontSize: 'var(--space-0750)',
lineHeight: 'var(--space-1000)',
fontVariantNumeric: 'tabular-nums',
pointerEvents: 'none',
zIndex: ZIndex.Legend,
});
Object.assign(this.statusElement.style, {
position: 'absolute',
inset: 0,
display: 'none',
alignItems: 'center',
justifyContent: 'center',
textAlign: 'center',
pointerEvents: 'none',
});
params.container.append(this.chartContainer, this.legend, this.statusElement);
this.updateTheme();
}
public getState() {
return this.state.asObservable();
}
public isActive(): boolean {
return this.state.value.view === ChartViewType.Seasonality;
}
public async show(symbolId: string, range?: SeasonalityRange): Promise<void> {
if (this.destroyed || this.reuseHistory(symbolId, range)) {
return;
}
const requestId = ++this.requestId;
this.reset();
if (!this.isActive()) {
this.params.onOpen();
}
this.showStatus(t('Loading seasonality'));
this.state.next({
...this.state.value,
symbolId,
view: ChartViewType.Seasonality,
status: 'loading',
error: null,
tableRows: [],
});
try {
if (!symbolId) {
throw new Error('Select an instrument');
}
const rows = await this.loadHistory(symbolId, requestId);
if (!this.isCurrent(requestId)) {
return;
}
this.allYears = buildSeasonality(rows);
this.allTableRows = buildSeasonalityTable(this.allYears);
this.setInitialRange(range);
} catch (error) {
if (!this.isCurrent(requestId)) {
return;
}
this.reset();
this.showStatus(t('Unable to load seasonality'));
this.state.next({
...this.state.value,
status: 'error',
error: String(error),
tableRows: [],
});
console.error('[Seasonality] History loading failed:', error);
}
}
public setRange = (range: SeasonalityRange): void => {
if (this.destroyed || !this.isActive() || this.allYears.length === 0) {
return;
}
const state = this.state.value;
const next = normalizeRange(range, state.minYear, state.maxYear);
if (next.fromYear === state.fromYear && next.toYear === state.toYear) {
return;
}
this.state.next({ ...state, ...next });
if (this.renderFrame !== null) {
return;
}
this.renderFrame = requestAnimationFrame(() => {
this.renderFrame = null;
if (!this.destroyed && this.isActive()) {
this.renderRange();
}
});
};
public setScale = (scale: SeasonalityScale): void => {
if (this.destroyed || !this.isActive() || this.state.value.scale === scale) {
return;
}
this.state.next({ ...this.state.value, scale });
if (!this.chart) {
return;
}
this.plots.forEach((plot) => this.updateSeries(plot));
this.fitCalendar();
this.updateStatus();
this.updateLegend();
};
public setDisplayMode = (displayMode: SeasonalityViewType): void => {
if (
this.destroyed ||
!this.isActive() ||
this.state.value.displayMode === displayMode
) {
return;
}
this.state.next({ ...this.state.value, displayMode });
this.updateVisibility();
if (
this.state.value.status === 'ready' ||
this.state.value.status === 'empty'
) {
this.updateStatus();
}
};
public back = (): void => {
if (this.destroyed || !this.isActive()) {
return;
}
this.requestId += 1;
this.reset();
this.state.next({
...this.state.value,
view: ChartViewType.Chart,
status: 'idle',
error: null,
tableRows: [],
});
this.params.onBack();
};
public updateTheme(): void {
const { colors } = getThemeStore();
Object.assign(this.params.container.style, {
backgroundColor: colors.chartBackground,
});
this.params.container.style.setProperty(
'--seasonality-background',
colors.chartBackground,
);
this.params.container.style.setProperty(
'--seasonality-text',
colors.chartTextPrimary,
);
this.params.container.style.setProperty(
'--seasonality-border',
colors.chartGridLine,
);
Object.assign(this.statusElement.style, {
color: colors.chartTextPrimary,
});
this.legend.style.color = colors.chartTextPrimary;
this.chart?.applyOptions(getThemeOptions());
}
public async copyImage(): Promise<void> {
if (
!this.chart ||
this.state.value.status !== 'ready' ||
this.state.value.displayMode !== SeasonalityViewType.Chart
) {
return;
}
const canvas = this.chart.takeScreenshot(true, false);
drawTextLayer(canvas, this.legend, this.chart.chartElement());
const blob = await canvasToBlob(canvas);
await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]);
}
public destroy(): void {
if (this.destroyed) {
return;
}
this.destroyed = true;
this.requestId += 1;
this.reset();
this.chartContainer.remove();
this.legend.remove();
this.statusElement.remove();
this.state.complete();
}
private isCurrent(requestId: number): boolean {
return !this.destroyed && requestId === this.requestId;
}
private reuseHistory(
symbolId: string,
range?: SeasonalityRange,
): boolean {
const state = this.state.value;
if (!this.isActive() || state.symbolId !== symbolId) {
return false;
}
if (state.status === 'loading') {
return true;
}
if (this.allYears.length === 0) {
return false;
}
if (range) {
this.setRange(range);
}
return true;
}
private async loadHistory(
symbolId: string,
requestId: number,
): Promise<DailyClose[]> {
const candles = new Map<number, Candle>();
const loadPage = async (cursor?: Candle): Promise<void> => {
if (!this.isCurrent(requestId)) {
return;
}
const loaded = await this.params.getData(
Timeframes['1d'],
symbolId,
cursor,
);
if (!this.isCurrent(requestId) || !loaded?.length) {
return;
}
const { oldest, newestTime } = mergeHistoryPage(loaded, candles);
if (cursor && oldest.time >= cursor.time) {
const isBoundaryOnly =
oldest.time === cursor.time && newestTime === cursor.time;
if (isBoundaryOnly) {
return;
}
throw new Error(
`History pagination made no progress: cursor=${cursor.time}, ` +
`oldest=${oldest.time}, newest=${newestTime}, count=${loaded.length}`,
);
}
return loadPage(oldest);
};
await loadPage();
if (!this.isCurrent(requestId)) {
return [];
}
return Array.from(candles.values(), (candle) => ({
date: dayjs.unix(candle.time).format('YYYY-MM-DD'),
close: candle.close,
}));
}
private setInitialRange(range?: SeasonalityRange): void {
if (this.allYears.length === 0) {
this.showStatus(t('No seasonality data'));
this.state.next({
...this.state.value,
status: 'empty',
});
return;
}
const minYear = this.allYears[0].year;
const maxYear = this.allYears[this.allYears.length - 1].year;
const selected = normalizeRange(
range ?? {
fromYear: maxYear - DEFAULT_YEARS + 1,
toYear: maxYear,
},
minYear,
maxYear,
);
this.state.next({
...this.state.value,
...selected,
minYear,
maxYear,
});
this.renderRange();
}
private createChart(): IChartApi {
const chart = createChart(this.chartContainer, {
...getThemeOptions(),
autoSize: true,
handleScroll: false,
handleScale: false,
kineticScroll: {
mouse: false,
touch: false,
},
rightPriceScale: {
mode: PriceScaleMode.Normal,
autoScale: true,
alignLabels: true,
visible: true,
borderVisible: false,
},
leftPriceScale: {
visible: false,
},
timeScale: {
timeVisible: false,
secondsVisible: false,
borderVisible: false,
allowBoldLabels: false,
rightOffset: 0,
tickMarkFormatter: formatSeasonDate,
lockVisibleTimeRangeOnResize: true,
},
localization: {
locale: getLocale(),
timeFormatter: formatSeasonDate,
},
});
chart.subscribeCrosshairMove(this.onCrosshairMove);
this.chart = chart;
return chart;
}
private renderRange(): void {
const chart = this.chart ?? this.createChart();
const { fromYear, toYear } = this.state.value;
const years = this.allYears.filter(
(year) => year.year >= fromYear && year.year <= toYear,
);
this.plots.forEach((plot, year) => {
if (year < fromYear || year > toYear) {
plot.markers?.detach();
chart.removeSeries(plot.series);
this.plots.delete(year);
}
});
const plots = years.map((year) => {
const existing = this.plots.get(year.year);
if (existing) {
return existing;
}
const plot = this.createPlot(chart, year);
this.plots.set(year.year, plot);
return plot;
});
this.legend.replaceChildren(
...plots.flatMap((plot) => [plot.legend, plot.legendValue]),
);
if (plots.length > 0) {
this.fitCalendar();
}
this.state.next({
...this.state.value,
status: plots.length > 0 ? 'ready' : 'empty',
tableRows: this.allTableRows.filter(
(row) => row.year >= fromYear && row.year <= toYear,
),
});
this.updateVisibility();
this.updateStatus();
this.updateLegend();
}
private fitCalendar(): void {
this.chart?.timeScale().setVisibleRange({
from: '2000-01-01',
to: '2000-12-31',
});
}
private createPlot(
chart: IChartApi,
year: SeasonalityYear,
): SeasonalityPlot {
const color = getYearColor(year.year);
const legend = document.createElement('span');
const legendValue = document.createElement('span');
legend.textContent = String(year.year);
Object.assign(legendValue.style, {
color,
textAlign: 'right',
});
const plot: SeasonalityPlot = {
year,
legend,
legendValue,
series: chart.addSeries(LineSeries, {
title: String(year.year),
color,
priceLineVisible: false,
lastValueVisible: true,
lineWidth: year.year === this.currentYear ? 3 : 1,
pointMarkersVisible: false,
crosshairMarkerVisible: true,
}),
};
if (year.year === this.currentYear) {
plot.markers = createSeriesMarkers(plot.series, [], {
autoScale: false,
});
}
this.updateSeries(plot);
return plot;
}
private updateSeries({
series,
year,
markers,
}: SeasonalityPlot): void {
const { scale } = this.state.value;
const isPercentage = scale === PriceScaleMode.Percentage;
series.applyOptions({
priceFormat: {
type: 'custom',
minMove: isPercentage ? 0.01 : 10 ** -(this.params.precision ?? 2),
formatter: (value: number) => (
isPercentage ? `${value.toFixed(2)}%` : formatCompactNumber(value)
),
},
});
series.setData(toSeriesData(year, scale));
if (markers) {
const lastPoint = year.points[year.points.length - 1];
const value = isPercentage ? lastPoint.percentage : lastPoint.price;
markers.setMarkers(
value === null
? []
: [
{
time: lastPoint.chartDate,
position: 'inBar',
shape: 'circle',
color: getYearColor(year.year),
size: 1,
},
],
);
}
}
private updateStatus(): void {
if (this.state.value.displayMode === SeasonalityViewType.Table) {
if (this.state.value.tableRows.length === 0) {
this.showStatus(t('No seasonality data'));
} else {
this.statusElement.style.display = 'none';
}
return;
}
if (this.plots.size === 0) {
this.showStatus(t('No seasonality data'));
return;
}
const isPercentage = this.state.value.scale === PriceScaleMode.Percentage;
const hasBaseline = Array.from(this.plots.values()).some(
(plot) => plot.year.baselinePrice > 0,
);
if (isPercentage && !hasBaseline) {
this.showStatus(t('Percentage requires a positive baseline'));
return;
}
this.statusElement.style.display = 'none';
}
private onCrosshairMove = (event: MouseEventParams): void => {
this.updateLegend(event);
};
private updateLegend(event?: MouseEventParams): void {
const isPercentage = this.state.value.scale === PriceScaleMode.Percentage;
this.plots.forEach(({ year, series, legendValue }) => {
const lastPoint = year.points[year.points.length - 1];
let value = isPercentage ? lastPoint.percentage : lastPoint.price;
if (event?.time !== undefined) {
const point = event.seriesData.get(series);
value = point && 'value' in point && typeof point.value === 'number'
? point.value
: null;
}
legendValue.textContent = value === null
? '—'
: series.priceFormatter().format(value);
});
}
private updateVisibility(): void {
const isChart = this.state.value.displayMode === SeasonalityViewType.Chart;
const visibility = isChart ? 'visible' : 'hidden';
this.chartContainer.style.visibility = visibility;
this.chartContainer.inert = !isChart;
this.legend.style.visibility = visibility;
}
private showStatus(message: string): void {
this.statusElement.textContent = message;
this.statusElement.style.display = 'flex';
}
private reset(): void {
if (this.renderFrame !== null) {
cancelAnimationFrame(this.renderFrame);
this.renderFrame = null;
}
this.chart?.unsubscribeCrosshairMove(this.onCrosshairMove);
this.plots.forEach((plot) => plot.markers?.detach());
this.chart?.remove();
this.chart = null;
this.allYears = [];
this.allTableRows = [];
this.plots.clear();
this.legend.replaceChildren();
this.statusElement.style.display = 'none';
}
}
function mergeHistoryPage(
loaded: Candle[],
candles: Map<number, Candle>,
): { oldest: Candle; newestTime: number } {
let oldest = loaded[0];
let oldestTime = Infinity;
let newestTime = -Infinity;
for (let index = loaded.length - 1; index >= 0; index -= 1) {
const candle = loaded[index];
if (!Number.isFinite(candle.time) || !Number.isFinite(candle.close)) {
throw new Error('Invalid daily candle');
}
const time = Math.floor(
candle.time > 1e10 ? candle.time / 1000 : candle.time,
);
const normalized = time === candle.time ? candle : { ...candle, time };
newestTime = Math.max(newestTime, time);
if (time < oldestTime) {
oldest = normalized;
oldestTime = time;
}
if (!candles.has(time)) {
candles.set(time, normalized);
}
}
return { oldest, newestTime };
}
function getThemeOptions() {
const { colors } = getThemeStore();
return {
layout: {
background: {
type: ColorType.Solid,
color: colors.chartBackground,
},
textColor: colors.chartTextPrimary,
panes: {
separatorColor: colors.chartPaneSeparator,
separatorHoverColor: colors.chartPaneSeparator,
enableResize: false,
},
},
grid: {
vertLines: {
color: colors.chartGridLine,
},
horzLines: {
color: colors.chartGridLine,
},
},
crosshair: {
mode: CrosshairMode.Normal,
vertLine: {
color: colors.chartCrosshairLine,
labelBackgroundColor: colors.chartCrosshairLabel,
style: LineStyle.Solid,
},
horzLine: {
color: colors.chartCrosshairLine,
labelBackgroundColor: colors.chartCrosshairLabel,
style: LineStyle.Dashed,
},
},
};
}
function formatSeasonDate(time: Time): string {
if (typeof time === 'object') {
const day = String(time.day).padStart(2, '0');
const month = String(time.month).padStart(2, '0');
return `${day}.${month}`;
}
const date = typeof time === 'number'
? new Date(time * 1000).toISOString()
: time;
return `${date.slice(8, 10)}.${date.slice(5, 7)}`;
}
function getYearColor(year: number): string {
return COMPARE_COLOR_PALETTE[year % COMPARE_COLOR_PALETTE.length];
}
this.seasonalityControlsRenderer.renderComponent(
<SeasonalityPanel
stateObs={this.seasonalityManager.getState()}
contentContainer={seasonalityPlotContainer}
setDisplayMode={this.seasonalityManager.setDisplayMode}
setScale={this.seasonalityManager.setScale}
setRange={this.seasonalityManager.setRange}
/>,
);
const canCopyImage = Boolean(
copyImage &&
(!isSeasonality ||
(seasonalityState.status === 'ready' &&
seasonalityState.displayMode === SeasonalityViewType.Chart)),
);
{(canCopyImage || (!isSeasonality && showFullscreenButton)) && (
<>
<Divider
direction="vertical"
pt={{ divider: { className: styles.divider } }}
/>
<div className={styles.group}>
{copyImage && canCopyImage && (
<Tooltip
location="bottom"
label={t('Snapshot')}
>
<Dropdown
menuClassName={styles.menu}
selectedValue={<CameraIcon />}
>
<SnapshotMenu onCopyImage={copyImage} />
</Dropdown>
</Tooltip>
)}
{showFullscreenButton && !isSeasonality && (
<Tooltip
location="bottom"
label={t(isFullscreen ? 'Exit fullscreen' : 'Fullscreen')}
>
<Button
pressed={isFullscreen}
onClick={() => fullscreen.toggle()}
label={<FullscreenIcon />}
/>
</Tooltip>
)}
</div>
</>
)}
{
"Table": "Таблица",
"Date": "Дата",
"Year": "Год",
"January": "январь",
"February": "февраль",
"March": "март",
"April": "апрель",
"May": "май",
"June": "июнь",
"July": "июль",
"August": "август",
"September": "сентябрь",
"October": "октябрь",
"November": "ноябрь",
"December": "декабрь"
}