-
Notifications
You must be signed in to change notification settings - Fork 66
/
kline.ts
507 lines (417 loc) · 13 KB
/
kline.ts
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
/// <reference path="chart.ts" />
/// <reference path="utils.ts" />
module StockChart {
interface IKLineOptions extends IChartOptions {
ohlcPrices: CandleBar[]
volumes: number[]
dates: string[]
dataCount: number
riseColor: string
fallColor: string
period: Period,
maLists: MAList[]
}
type CandleBar = {
o: number
h: number
l: number
c: number
}
type AxisDate = {
text: string
index: number
}
type MAList = {
title: string,
color?: string | number,
prices: number[]
}
enum Period { Day, Week, Month }
enum MAColors {
Yellow,
Blue,
Pink,
Green
}
const COLOR = {
YELLOW: 'rgba(219,169,83,.5)',
BLUE: 'rgba(99,179,243,.5)',
PINK: 'rgba(223,140,201,.5)',
GREEN: 'rgba(151,192,57,.5)'
}
class KLine extends Chart {
ohlcPrices: CandleBar[]
volumes: number[]
dates: string[]
volumeTopHeight: number
fillColor: string
volumeColor: string
unitX: number
unitY: number
roofPrice: number
floorPrice: number
dataCount: number
riseColor: string
fallColor: string
period: Period
maLists: MAList[]
calcY: (price: number) => number
constructor(options?: IKLineOptions) {
super(options)
this.ohlcPrices = options.ohlcPrices
this.volumes = options.volumes
this.dates = options.dates
this.dataCount = options.dataCount
this.volumeTopHeight = this.height - this.volumeHeight + this.textOffsetY
this.unitX = this.figureWidth / this.dataCount
this.riseColor = options.riseColor
this.fallColor = options.fallColor
this.period = options.period
this.maLists = options.maLists
}
initialize() {
super.initialize()
this.drawGrid()
this.drawPriceBar()
this.drawMaLines()
this.drawVolumeBar()
this.drawAxisYText()
}
private drawGrid() {
const {ctx, grid, height, figureWidth, figureHeight, figureOffsetHeight, figureOffsetY, volumeTopHeight} = this
ctx.beginPath()
// 横轴基线
this.drawLine({
color: grid.color,
startPoint: [0, this.figureHeight],
points: [[figureWidth, figureHeight]]
}, false)
// 量图顶部线
this.drawLine({
color: grid.color,
startPoint: [0, volumeTopHeight],
points: [[figureWidth, volumeTopHeight]]
}, false)
// 图表顶部线
this.drawLine({
color: grid.color,
startPoint: [0, 0],
points: [[figureWidth, 0]]
}, false)
// 图表底部线
this.drawLine({
color: grid.color,
startPoint: [0, this.height],
points: [[figureWidth, height]]
})
// 横向网格
const gridY = figureOffsetHeight / grid.y
for (let i = 0; i < grid.y; i++) {
ctx.beginPath()
this.drawLine({
color: grid.color,
startPoint: [0, gridY * i + figureOffsetY],
points: [[figureWidth, gridY * i + figureOffsetY]]
})
}
this.drawGridX()
}
private drawPriceBar() {
const {ctx, ohlcPrices, dataCount, figureHeight, figureOffsetHeight} = this
const len = ohlcPrices.length
const count = Math.min(len, dataCount)
const highPrices = ohlcPrices.map((price: CandleBar) => {
return price.h
})
const lowPrices = ohlcPrices.map((price: CandleBar) => {
return price.l
})
let maxPrice = Math.max.apply(null, highPrices)
let minPrice = Math.min.apply(null, lowPrices)
// 横座标和纵座标的单位尺寸
const unitX = this.unitX
const unitY = this.unitY = (figureOffsetHeight - 10) / (maxPrice - minPrice)
// 纵座标顶部和底部的价格,这里一般是之前计算出的 maxPrice 和 minPrice
this.roofPrice = maxPrice
// this.floorPrice = (minPrice * unitY - 10) / unitY
this.floorPrice = minPrice
// 计算当前价所在纵轴坐标位置
const calcY = this.calcY = (price: number): number => {
return Math.round(figureHeight - Math.abs(price - minPrice) * unitY - 10)
}
// 绘制 K 线
for (let i = 0; i < count; i++) {
const openPrice = ohlcPrices[i].o
const highPrice = ohlcPrices[i].h
const lowPrice = ohlcPrices[i].l
const closePrice = ohlcPrices[i].c
const barX = unitX * i + unitX / 2
const barColor = this.getBarColor(ohlcPrices, i)
ctx.beginPath()
this.drawLine({
color: barColor,
size: 1,
startPoint: [barX, calcY(highPrice)],
points: [[barX, calcY(lowPrice)]]
})
ctx.beginPath()
if (calcY(openPrice) === calcY(closePrice)) {
this.drawLine({
color: barColor,
size: 1,
startPoint: [barX - 2, calcY(openPrice)],
points: [[barX + 2, calcY(closePrice)]]
})
} else {
this.drawLine({
color: barColor,
size: 4,
startPoint: [barX, calcY(openPrice)],
points: [[barX, calcY(closePrice)]]
})
}
}
}
private drawVolumeBar() {
const {ctx, volumes, ohlcPrices, dataCount, height, volumeHeight, textOffsetY, unitX} = this
const len = volumes.length
const count = Math.min(len, dataCount)
let maxVolume = Math.max.apply(null, volumes)
let minVolume = Math.min.apply(null, volumes)
// 如果最大交易量等于最小交易量,计算单位高度保证分母为 1
if (maxVolume === minVolume) {
minVolume = maxVolume - 1
}
// 单位高度
const volumeUnitY = (volumeHeight - textOffsetY) / (maxVolume - minVolume)
// 绘制量线
let currentVolumeHeight
for (let i = 0; i < count; i++) {
const barX = unitX * i + unitX / 2
currentVolumeHeight = Math.round(height - (volumes[i] - minVolume) * volumeUnitY)
if (currentVolumeHeight === height) {
currentVolumeHeight = height - 1
}
ctx.beginPath()
this.drawLine({
color: this.getBarColor(ohlcPrices, i),
size: 4,
startPoint: [barX, height],
points: [[barX, currentVolumeHeight]]
})
}
}
private drawMaLines() {
const {maLists} = this
if (!maLists.length) {
return
}
maLists.forEach((maList: MAList) => {
this.drawMaLine(maList)
})
// 绘制均线指示图
this.drawMaLegend()
}
private drawMaLine(maList: MAList) {
const {ctx, unitX, calcY, roofPrice} = this
const len = maList.prices.length
const count = Math.min(len, this.dataCount)
let points: Point[]
let maColor: string
if (count === 0) {
return
}
maColor = this.getMaColor(maList)
// 当当前价大于坐标顶部的最大价格,均线不显示,所以这里采用 NaN
points = maList.prices.map((price: number, index: number): Point => {
return [unitX * index, price > roofPrice ? NaN : calcY(price)]
})
ctx.beginPath()
this.drawLine({
color: maColor,
size: 1,
startPoint: points.splice(0, 1)[0],
points: points
})
}
private getMaColor(maList) {
let maColor
if (typeof maList.color === 'undefined') {
const index = arrayObjectIndexOf(this.maLists, 'title', maList.title)
maColor = COLOR[MAColors[index].toUpperCase()]
} else if (typeof maList.color === 'number') {
maColor = COLOR[MAColors[maList.color].toUpperCase()]
} else {
maColor = maList.color.toString()
}
return maColor
}
private drawMaLegend() {
const {ctx, dpr, maLists, figureWidth, figureOffsetY} = this
const len = maLists.length
const dot = {
radius: 3,
paddingLeft: 10,
paddingRight: 3
}
let text: string
let textWidth: number
let prices: number[]
let lastPrice: number
for (let i = len - 1, textWidth = 0; i >= 0; i--) {
const title = maLists[i].title
// 这里要重新初始化 canvas 字体,否则 drawText 中对字体的处理会对 measureText 造成影响
ctx.font = this.font
// 去除空数据,这里的空数据指的是 NaN
prices = maLists[i].prices.filter((price) => {
return Boolean(price)
})
if (!prices.length) {
continue
}
lastPrice = prices[prices.length - 1]
text = `${title} ${lastPrice}`
textWidth += ctx.measureText(text).width
this.drawText(text, [figureWidth - textWidth, figureOffsetY - 5])
this.drawRound({
point: [figureWidth - textWidth - dot.radius - dot.paddingRight, figureOffsetY - 5 - dot.radius],
radius: dot.radius,
isFill: true,
fillColor: this.getMaColor(maLists[i])
})
textWidth += dot.radius * 2 + dot.paddingLeft + dot.paddingRight
}
}
private drawAxisYText() {
this.drawText(this.roofPrice.toFixed(2), [0, this.figureOffsetY - this.textOffsetY])
this.drawText(this.floorPrice.toFixed(2), [0, this.figureHeight - this.textOffsetY])
}
private drawGridX() {
const {ctx, dataCount, period} = this
let {dates} = this
const len = dates.length
const count = Math.min(len, dataCount)
// 最前两点不显示横座标,因为显示不下
if (count <= 2) {
return
}
// 重新开辟绘画路径,避免横向网格线变粗
ctx.beginPath()
switch (Period[period]) {
// 周 K
case 'Week':
let uniqDates: AxisDate[] = []
let weekDates: AxisDate[] = []
for (let i = 2; i < count - 2; i++) {
if (dates[i] !== dates[i - 1]) {
uniqDates.push({
text: dates[i],
index: i
})
}
}
weekDates = uniqDates.filter((date, index) => {
return !(index % 3)
})
if (!weekDates.length) {
return
}
weekDates.forEach((date) => {
this.drawGridTextX(date.text, date.index)
})
break
// 月 K
case 'Month':
let monthDates: AxisDate[] = []
dates = dates.map((date) => {
return date.split('-')[0]
})
for (let i = 2; i < count - 2; i++) {
if (dates[i] !== dates[i - 1]) {
monthDates.push({
text: dates[i],
index: i
})
}
}
monthDates.forEach((date) => {
this.drawGridTextX(date.text, date.index)
})
break
// 默认 Period 为 'Day' 为日 K
default:
let dayDates: AxisDate[] = []
for (let i = 2; i < count - 2; i++) {
if (dates[i] !== dates[i - 1]) {
dayDates.push({
text: dates[i],
index: i
})
}
}
for (let j = 1; j < dayDates.length; j++) {
// 如果相隔太近(7个点内),也不显示横座标值,否则会产生文字重叠现象
if (dayDates[j].index - dayDates[j - 1].index < 7) {
dayDates.splice(j, 1)
j--;
}
}
dayDates.forEach((date) => {
this.drawGridTextX(date.text, date.index)
})
break
}
}
private drawGridTextX(date: string, index: number) {
const {grid, dataCount, height, volumeHeight, figureWidth, figureHeight, figureOffsetY} = this
const unitX = figureWidth / dataCount
const axisY = height - volumeHeight
const barX = unitX * index + unitX / 2
this.drawText(date, [unitX * index - 15, axisY])
this.drawLine({
color: grid.color,
startPoint: [barX, figureOffsetY],
points: [[barX, figureHeight]]
})
}
private getBarColor(bars: CandleBar[], index: number) {
const {riseColor, fallColor} = this
const openPrice = bars[index].o
const closePrice = bars[index].c
// 涨
if (closePrice > openPrice) {
return riseColor
}
// 跌
else if (closePrice < openPrice) {
return fallColor
}
// 不涨不跌
else {
if (index === 0) {
return 'black'
} else {
const preClosePrice = bars[index - 1].c
return closePrice > preClosePrice ? riseColor : fallColor
}
}
}
}
export function drawKLine(options) {
const defaultOptions = {
dataCount: 50,
grid: {
y: 4,
color: 'rgba(221,221,221,1)'
},
lineColor: 'rgba(94,168,199,1)',
volumeColor: 'rgba(130,152,200,1)',
riseColor: 'rgba(252,63,29,1)',
fallColor: 'rgba(85,170,48,1)',
period: 0
}
options = mixins({}, defaultOptions, options)
const kLine = new KLine(options)
kLine.initialize()
}
}