-
Notifications
You must be signed in to change notification settings - Fork 11.7k
/
CandlestickPanel.tsx
337 lines (291 loc) · 10.9 KB
/
CandlestickPanel.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
// this file is pretty much a copy-paste of TimeSeriesPanel.tsx :(
// with some extra renderers passed to the <TimeSeries> component
import React, { useMemo } from 'react';
import uPlot from 'uplot';
import { Field, getDisplayProcessor, getLinksSupplier, PanelProps } from '@grafana/data';
import { PanelDataErrorView } from '@grafana/runtime';
import { TooltipDisplayMode } from '@grafana/schema';
import { TimeSeries, TooltipPlugin, UPlotConfigBuilder, usePanelContext, useTheme2, ZoomPlugin } from '@grafana/ui';
import { AxisProps } from '@grafana/ui/src/components/uPlot/config/UPlotAxisBuilder';
import { ScaleProps } from '@grafana/ui/src/components/uPlot/config/UPlotScaleBuilder';
import { config } from 'app/core/config';
import { getFieldLinksForExplore } from 'app/features/explore/utils/links';
import { AnnotationEditorPlugin } from '../timeseries/plugins/AnnotationEditorPlugin';
import { AnnotationsPlugin } from '../timeseries/plugins/AnnotationsPlugin';
import { ContextMenuPlugin } from '../timeseries/plugins/ContextMenuPlugin';
import { ExemplarsPlugin } from '../timeseries/plugins/ExemplarsPlugin';
import { OutsideRangePlugin } from '../timeseries/plugins/OutsideRangePlugin';
import { ThresholdControlsPlugin } from '../timeseries/plugins/ThresholdControlsPlugin';
import { prepareCandlestickFields } from './fields';
import { CandlestickOptions, defaultColors, VizDisplayMode } from './models.gen';
import { drawMarkers, FieldIndices } from './utils';
interface CandlestickPanelProps extends PanelProps<CandlestickOptions> {}
export const CandlestickPanel: React.FC<CandlestickPanelProps> = ({
data,
id,
timeRange,
timeZone,
width,
height,
options,
fieldConfig,
onChangeTimeRange,
replaceVariables,
}) => {
const { sync, canAddAnnotations, onThresholdsChange, canEditThresholds, onSplitOpen } = usePanelContext();
const getFieldLinks = (field: Field, rowIndex: number) => {
return getFieldLinksForExplore({ field, rowIndex, splitOpenFn: onSplitOpen, range: timeRange });
};
const theme = useTheme2();
const info = useMemo(() => {
return prepareCandlestickFields(data.series, options, theme, timeRange);
}, [data, options, theme, timeRange]);
const { renderers, tweakScale, tweakAxis } = useMemo(() => {
let tweakScale = (opts: ScaleProps, forField: Field) => opts;
let tweakAxis = (opts: AxisProps, forField: Field) => opts;
let doNothing = {
renderers: [],
tweakScale,
tweakAxis,
};
if (!info) {
return doNothing;
}
// Un-encoding the already parsed special fields
// This takes currently matched fields and saves the name so they can be looked up by name later
// ¯\_(ツ)_/¯ someday this can make more sense!
const fieldMap = info.names;
if (!Object.keys(fieldMap).length) {
return doNothing;
}
const { mode, candleStyle, colorStrategy } = options;
const colors = { ...defaultColors, ...options.colors };
let { open, high, low, close, volume } = fieldMap; // names from matched fields
if (open == null || close == null) {
return doNothing;
}
let volumeAlpha = 0.5;
let volumeIdx = -1;
let shouldRenderVolume = false;
// find volume field and set overrides
if (volume != null && mode !== VizDisplayMode.Candles) {
let volumeField = info.volume!;
if (volumeField != null) {
shouldRenderVolume = true;
let { fillOpacity } = volumeField.config.custom;
if (fillOpacity) {
volumeAlpha = fillOpacity / 100;
}
// we only want to put volume on own shorter axis when rendered with price
if (mode !== VizDisplayMode.Volume) {
volumeField.config = { ...volumeField.config };
volumeField.config.unit = 'short';
volumeField.display = getDisplayProcessor({
field: volumeField,
theme: config.theme2,
});
tweakAxis = (opts: AxisProps, forField: Field) => {
// we can't do forField === info.volume because of copies :(
if (forField.name === info.volume?.name) {
let filter = (u: uPlot, splits: number[]) => {
let _splits = [];
let max = u.series[volumeIdx].max as number;
for (let i = 0; i < splits.length; i++) {
_splits.push(splits[i]);
if (splits[i] > max) {
break;
}
}
return _splits;
};
opts.space = 20; // reduce tick spacing
opts.filter = filter; // hide tick labels
opts.ticks = { ...opts.ticks, filter }; // hide tick marks
}
return opts;
};
tweakScale = (opts: ScaleProps, forField: Field) => {
// we can't do forField === info.volume because of copies :(
if (forField.name === info.volume?.name) {
opts.range = (u: uPlot, min: number, max: number) => [0, max * 7];
}
return opts;
};
}
}
}
let shouldRenderPrice = mode !== VizDisplayMode.Volume && high != null && low != null;
if (!shouldRenderPrice && !shouldRenderVolume) {
return doNothing;
}
let fields: Record<string, string> = {};
let indicesOnly = [];
if (shouldRenderPrice) {
fields = { open, high: high!, low: low!, close };
// hide series from legend that are rendered as composite markers
for (let key in fields) {
let field = (info as any)[key] as Field;
field.config = {
...field.config,
custom: {
...field.config.custom,
hideFrom: { legend: true, tooltip: false, viz: false },
},
};
}
} else {
// these fields should not be omitted from normal rendering if they arent rendered
// as part of price markers. they're only here so we can get back their indicies in the
// init callback below. TODO: remove this when field mapping happens in the panel instead of deep
indicesOnly.push(open, close);
}
if (shouldRenderVolume) {
fields.volume = volume!;
fields.open = open;
fields.close = close;
}
return {
renderers: [
{
fieldMap: fields,
indicesOnly,
init: (builder: UPlotConfigBuilder, fieldIndices: FieldIndices) => {
volumeIdx = fieldIndices.volume!;
builder.addHook(
'drawAxes',
drawMarkers({
mode,
fields: fieldIndices,
upColor: config.theme2.visualization.getColorByName(colors.up),
downColor: config.theme2.visualization.getColorByName(colors.down),
flatColor: config.theme2.visualization.getColorByName(colors.flat),
volumeAlpha,
colorStrategy,
candleStyle,
flatAsUp: true,
})
);
},
},
],
tweakScale,
tweakAxis,
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [options, data.structureRev, data.series.length]);
if (!info) {
return (
<PanelDataErrorView
panelId={id}
fieldConfig={fieldConfig}
data={data}
needsTimeField={true}
needsNumberField={true}
/>
);
}
const enableAnnotationCreation = Boolean(canAddAnnotations && canAddAnnotations());
return (
<TimeSeries
frames={[info.frame]}
structureRev={data.structureRev}
timeRange={timeRange}
timeZone={timeZone}
width={width}
height={height}
legend={options.legend}
renderers={renderers}
tweakAxis={tweakAxis}
tweakScale={tweakScale}
options={options}
>
{(config, alignedDataFrame) => {
alignedDataFrame.fields.forEach((field) => {
field.getLinks = getLinksSupplier(
alignedDataFrame,
field,
field.state!.scopedVars!,
replaceVariables,
timeZone
);
});
return (
<>
<ZoomPlugin config={config} onZoom={onChangeTimeRange} />
<TooltipPlugin
data={alignedDataFrame}
config={config}
mode={TooltipDisplayMode.Multi}
sync={sync}
timeZone={timeZone}
/>
{/* Renders annotation markers*/}
{data.annotations && (
<AnnotationsPlugin annotations={data.annotations} config={config} timeZone={timeZone} />
)}
{/* Enables annotations creation*/}
{enableAnnotationCreation ? (
<AnnotationEditorPlugin data={alignedDataFrame} timeZone={timeZone} config={config}>
{({ startAnnotating }) => {
return (
<ContextMenuPlugin
data={alignedDataFrame}
config={config}
timeZone={timeZone}
replaceVariables={replaceVariables}
defaultItems={
enableAnnotationCreation
? [
{
items: [
{
label: 'Add annotation',
ariaLabel: 'Add annotation',
icon: 'comment-alt',
onClick: (e, p) => {
if (!p) {
return;
}
startAnnotating({ coords: p.coords });
},
},
],
},
]
: []
}
/>
);
}}
</AnnotationEditorPlugin>
) : (
<ContextMenuPlugin
data={alignedDataFrame}
config={config}
timeZone={timeZone}
replaceVariables={replaceVariables}
defaultItems={[]}
/>
)}
{data.annotations && (
<ExemplarsPlugin
config={config}
exemplars={data.annotations}
timeZone={timeZone}
getFieldLinks={getFieldLinks}
/>
)}
{canEditThresholds && onThresholdsChange && (
<ThresholdControlsPlugin
config={config}
fieldConfig={fieldConfig}
onThresholdsChange={onThresholdsChange}
/>
)}
<OutsideRangePlugin config={config} onChangeTimeRange={onChangeTimeRange} />
</>
);
}}
</TimeSeries>
);
};