TradingView + websocket 实现 k线图

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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
function TVApi() {
let _time = String(+new Date());
// 随机id生成
let userID = window.btoa(
_time.substr(_time.length - 6) + parseInt(Math.random() * 1e6)
);
let defaultData = {
urls: "wss://" + userID, // 测试
maOrBollObj: {
ma: [
{
title: "MA5",
value: "",
day: 5,
color: "#ECD58F",
linewidth: 3
},
{
title: "MA10",
value: "",
day: 10,
color: "#B8D8DB",
linewidth: 3
},
{
title: "MA20",
value: "",
day: 20,
color: "#4BA8FF",
linewidth: 3
},
{
title: "MA60",
value: "",
day: 60,
color: "#F8335E",
linewidth: 3
}
],
boll: [
{
title: "BOLL",
value: "",
color: "#DFC987"
},
{
title: "UB",
value: "",
color: "#749A9E"
},
{
title: "LB",
value: "",
color: "#158EFE"
}
]
},
widgets: null,
datafeeds: new datafeeds(this),
socket: null,
symbol: "SEAUSDT",
interval: null,
cacheData: {},
remarks: [], // MA返回的ID
// 指标线
studyObj: {
MA: "Moving Average",
BOLL: "Bollinger Bands",
MACD: "MACD",
KDJ: "KDJ",
RSI: "Relative Strength Index",
OBV: "On Balance Volume"
},
topStudyName: "", // 主图参考线简称
bottomStudyName: "", // 副图参考线简称
intervalType: null //APP传参标志
};
for (const k in defaultData) {
if (defaultData.hasOwnProperty(k)) {
this[k] = defaultData[k];
}
}
}
/**
* 初始化 socket
*/
TVApi.prototype.initSocket = function () {
let intervalType = this.intervalType === "hm" ? "1min" : this.intervalType;
this.socket = new socket(this.urls, {
interval: intervalType
});
this.socket.doOpen();
this.socket.on("open", () => {
this.sendMessage({
klineType: intervalType // k线时间类型
});
});
this.socket.on("message", this.onMessage.bind(this));
};
/**
* 初始化 TradingView
*/
TVApi.prototype.initTradingView = function () {
// console.log(this.intervalType, 'intervalType');
//设置默认symbol,interval的默认值
if (!this.widgets) {
this.widgets = window.tvWidget = new TradingView.widget({
symbol: this.symbol, //默认商品设置
interval: this.interval, //默认请求间隔
fullscreen: true, //默认是否全屏
autosize: false, //默认是否自适应
container_id: "trade-view", //设置容器
widgetbar: {
details: false,
watchlist: false
},
datafeed: this.datafeeds,
library_path: "/plugins/charting_library/",
timezone: "Asia/Shanghai",
locale: "zh",
debug: false,
has_empty_bars: false,
theme: "Light",
// preset: "mobile",
// custom_css_url: "/css/custom.css",
//设置默认不显示组件
disabled_features: [
"legend_context_menu",
"fix_left_edge", // 阻止滚动到第一个历史 K 线的左侧
"left_toolbar", //隐藏左边工具栏
"timeframes_toolbar", //隐藏底部刻度栏
"header_widget", // 隐藏头部组件
// "header_undo_redo", //左右箭头
// "header_compare", // compare
// "header_chart_type", // 图表类型
// "header_screenshot",
// "header_resolutions", // 分辨率
// "header_settings", // 设置按钮
// "header_indicators", // 技术指标线
// "header_symbol_search", // 搜索
// "header_saveload", // 上传下载按钮
// "header_fullscreen_button", // 全屏
"source_selection_markers", // 禁用系列和指示器的选择标记
"border_around_the_chart", // 周围边框
"constraint_dialogs_movement",
"show_interval_dialog_on_key_press",
"symbol_search_hot_key",
"volume_force_overlay", // 防止他们重叠
"property_pages", // 禁用所有属性页
"main_series_scale_menu",
"star_some_intervals_by_default",
"datasource_copypaste",
"right_bar_stays_on_scroll",
"context_menus",
"go_to_date",
"compare_symbol",
"timezone_menu",
"edit_buttons_in_legend",
"save_chart_properties_to_local_storage",
"pane_context_menu",
"control_bar", //与图表底部的导航按钮相关联
"collapsible_header",
"countdown", // 在价格标尺上显示倒计时标签
"show_dialog_on_snapshot_ready",
"study_dialog_search_control",
"show_hide_button_in_legend",
"legend_widget",
"widget_logo",

"charting_library_debug_mode",
"hide_left_toolbar_by_default",
"scales_context_menu",
"format_button_in_legend",
"side_toolbar_in_fullscreen_mode",
"study_buttons_in_legend",
"move_logo_to_main_pane",
"dont_show_boolean_study_arguments", //是否隐藏指标参数
"use_localstorage_for_settings",
"disable_resolution_rebuild",
"display_market_status",
"symbol_info"
],
enabled_features: [
"chart_zoom",
"study_templates",
"seconds_resolution",
"hide_last_na_study_output",
"adaptive_logo",
"same_data_requery",
"chart_scroll",
// "study_buttons_in_legend",
// "chart_scroll",
// "chart_zoom",
// "keep_left_toolbar_visible_on_small_screens", //防止左侧工具栏在小屏幕上消失
"show_animated_logo", //隐藏logo的动画
"logo_without_link" //去除logo的链接
// "adaptive_logo", // 在小屏幕设备上隐藏 logo 的TradingView文字
// "remove_library_container_border",
// "move_logo_to_main_pane", // 将 logo 放在主数据列窗格上而不是底部窗格
// "hide_last_na_study_output", //隐藏最后一次指标输出
// "hide_left_toolbar_by_default",
// "study_templates",
// "seconds_resolution",
// "same_data_requery",
],
//设置初始化加载条样式
loading_screen: {
backgroundColor: "#EDEDED",
foregroundColor: "#578BFF"
},
customFormatters: {
timeFormatter: {
format: function (date) {
var _format_str = "%h:%m";
return _format_str
.replace("%h", (date.getUTCHours() + "").padStart(2, 0), 2)
.replace("%m", (date.getUTCMinutes() + "").padStart(2, 0), 2)
.replace("%s", (date.getUTCSeconds() + "").padStart(2, 0), 2);
}
},
dateFormatter: {
format: function (date) {
return (
date.getUTCFullYear() +
"-" +
(date.getUTCMonth() + 1 + "").padStart(2, 0) +
"-" +
(date.getUTCDate() + "").padStart(2, 0)
);
}
}
},
//设置初始化样式配置
overrides: this.getOverrides(
"white",
this.changeInterval(this.intervalType).lineType
),
studies_overrides: this.getStudiesOverrides("white"),
hide_top_toolbar: false, //是否隐藏顶部工具栏
hide_legend: false, // 是否隐藏商品代码描述
save_image: false, // 获取图像按键(右上角照相机)
withdateranges: true, // 是否显示底部工具栏
allow_symbol_change: false, // 是否允许修改商品名称
hide_side_toolbar: false, // 显示绘图工具栏(左侧工具栏)
show_popup_button: false, // 在弹出窗口显示(右上角分享)
no_referral_id: false, // 激活引荐计划
details: false, // 显示详细资料
logo: {
// image: "https://www.seaio.cc/logo.png",
// link: "https://www.seaio.cc"
}
});
TVjsApi.tradingViewReady();
}
};

/**
* TradingView 初始化后的操作
*/
TVApi.prototype.tradingViewReady = function () {
var widget = this.widgets;
widget.onChartReady(() => {
var c = widget.activeChart();
setTimeout(() => {
this.setMaStudyLegend();
}, 500);
widget.subscribe("mouse_down", () => {
setTimeout(() => {
this.setValueLegend(), this.setMaStudyLegend();
}, 50);
});
widget.subscribe("mouse_up", () => {
c.resetData();
setTimeout(() => {
this.setMaStudyLegend();
// 去除高开低收
document.getElementById("tv-legend-value").innerHTML = "";
}, 50);
});
widget.subscribe("study", t => {
setTimeout(() => {
this.setMaStudyLegend();
}, 50);
});
widget.subscribe("onTick", t => {
setTimeout(() => {
this.setMaStudyLegend();
}, 50);
});
});
};

/**
* 根据指标线名称显示指标线
* @param {*String} newTop 主图指标线简称
* @param {*String} newBottom 副图指标线简称
*/
TVApi.prototype.setStudyByName = function (newTop = "", newBottom = "") {
this.widgets.onChartReady(() => {
var t = this.widgets.activeChart(),
topFullName = this.studyObj[newTop],
bottomFullName = this.studyObj[newBottom];
if (newTop != this.topStudyName && topFullName) {
console.log("top增加", topFullName);
switch (newTop) {
case "MA":
this.maOrBollObj.ma.forEach(function (e) {
t.createStudy(topFullName, !1, !1, [e.day], function () {}, {
"plot.color": e.color,
"plot.linewidth": e.linewidth
});
});
this.topStudyName = newTop;
break;
case "BOLL":
t.createStudy(topFullName, !1, !1, [20, 2], function () {}, {
"plot.linewidth": 3
});
this.topStudyName = newTop;
break;
default:
this.removeStudyByName(this.topStudyName);
break;
}
}
if (newBottom != this.bottomStudyName && bottomFullName) {
console.log("bottom增加", bottomFullName);
switch (newBottom) {
case "MACD":
t.createStudy(bottomFullName, !1, !1, [12, 26, "close", 9]);
this.bottomStudyName = newBottom;
break;
case "KDJ":
case "RSI":
t.createStudy(bottomFullName, !1, !1);
this.bottomStudyName = newBottom;
break;
case "OBV":
t.createStudy(bottomFullName, !1, !1, [], function () {}, {
"plot.color": "green",
"plot.linewidth": 3
});
this.bottomStudyName = newBottom;
break;
default:
this.removeStudyByName(this.bottomStudyName);
break;
}
}
});
};

/**
* 移除指标线
* @param {*String} name 要删除的指标线简称
* @param {*Boolean} posBool 是不是主图
*/
TVApi.prototype.removeStudyByName = function (name, posBool) {
var t = this;
var fullname = t.studyObj[name] || "";
var c = this.widgets.activeChart();
c.getAllStudies()
.filter(function (r) {
if (r.name === fullname) {
posBool
? ((t.topStudyName = ""),
(document.getElementById("tv-legend-study").innerHTML = ""))
: (t.bottomStudyName = "");
}
return r.name === fullname;
})
.forEach(function (e) {
c.removeEntity(e.id);
});
};

/**
* 设置高开低收 信息框
*/
TVApi.prototype.setValueLegend = function () {
let chart = TVjsApi.widgets.chart();
let _items =
chart._chartWidget._paneWidgets[0].legendWidget._itemsBinding || [];
this.setValueDom(_items[0].last);
};

/**
* 设置高开低收 DOM
* @param {*Array} data 数据信息
*/

TVApi.prototype.setValueDom = function (data) {
let html = "<div class='value-box'>";
let titles = ["开", "高", "低", "收"];
for (let i = 0; i < 4; i++) {
html += `<div class="item"><span class="title">${titles[i]}</span><span>${data[i]["text"]}</span></div>`;
}
html += "</div>";
document.getElementById("tv-legend-value").innerHTML = html;
};

/**
* 设置指标线 图例
*/
TVApi.prototype.setMaStudyLegend = function () {
this.widgets.onChartReady(() => {
let chart = TVjsApi.widgets.chart();
let _items =
chart._chartWidget._paneWidgets[0].legendWidget._itemsBinding || [];
if (1 < _items.length) {
if (4 <= _items.length) {
for (let i = 0; i < 4; i++) {
this.maOrBollObj.ma[i].value = _items[i + 1].last[0].text;
}
this.setMaStudyDom(this.maOrBollObj.ma);
} else {
for (let i = 0; i < 3; i++) {
this.maOrBollObj.boll[i].value = _items[1].last[i].text;
}
this.setMaStudyDom(this.maOrBollObj.boll);
}
}
});
};

/**
* 设置指标线 DOM
* @param {*Array} data 数据信息
*/
TVApi.prototype.setMaStudyDom = function (data) {
let html = "";
for (let i = 0; i < data.length; i++) {
let a = data[i];
html += `<span style='color:${a["color"]}'>${a["title"]}${a["value"]}</span>`;
}
document.getElementById("tv-legend-study").innerHTML = html;
};

TVApi.prototype.sendMessage = function (data) {
var that = this;
if (this.socket.checkOpen()) {
this.socket.send(data);
} else {
this.socket.on("open", function () {
that.socket.send(data);
});
}
};

// 初始化时获取url中的参数
TVApi.prototype.getUrlParams = function () {
var url = location.search; // 获取url中"?"符后的字串
var theParams = {}; // 初始化空对象接受url中的所有参数
if (url.indexOf("?") != -1) {
var str = url.substr(1),
strs = str.split("&"); // 各个参数放到数组里
for (var i = 0; i < strs.length; i++) {
theParams[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
}
}
return theParams;
};

// 设置覆盖默认样式
TVApi.prototype.getOverrides = function (theme, intervalType) {
var themes = {
white: {
up: "#1aad19",
down: "#d00218",
bg: "#ffffff",
grid: "#e3edf5",
cross: "#23283D",
border: "#9194a4",
text: "#9194a4",
areatop: "rgba(122, 152, 247, .1)",
areadown: "rgba(122, 152, 247, .02)",
line: "#737375"
},
black: {
down: "rgb(250,82,82)",
up: "rgb(18,184,134)",
bg: "#181B2A",
grid: "#1f2943",
cross: "#9194A3",
text: "#61688A",
areatop: "#1782d2",
areadown: "transparent",
line: "#737375"
},
mobile: {
up: "#03C087",
down: "#E76D42",
bg: "#ffffff",
grid: "#f7f8fa",
cross: "#23283D",
border: "#C5CFD5",
text: "#8C9FAD",
areatop: "rgba(71, 78, 112, 0.1)",
areadown: "rgba(71, 78, 112, 0.02)",
showLegend: !0
}
};
var t = themes[theme];
return {
volumePaneSize: "medium", // 成交量高度(支持的值: large, medium, small, tiny)
"paneProperties.topMargin": 15, //K线面板属性,
"paneProperties.bottomMargin": 7, //K线面板属性,
"scalesProperties.fontSize": 9, // 设置坐标轴字体大小
// 坐标轴和刻度标签颜色
"scalesProperties.lineColor": t.text,
"scalesProperties.textColor": t.text,
"paneProperties.background": t.bg, // 画布白色背景颜色
// 网格线
"paneProperties.vertGridProperties.color": t.grid,
"paneProperties.horzGridProperties.color": t.grid,
"paneProperties.crossHairProperties.color": t.cross, // 十字线
"paneProperties.crossHairProperties.style": 2, // 十字线样式
"paneProperties.crossHairProperties.transparency": 0, // 十字线
"paneProperties.legendProperties.showLegend": true, // 隐藏左上角标题
"paneProperties.legendProperties.showStudyArguments": !1,
"paneProperties.legendProperties.showStudyTitles": !1,
"paneProperties.legendProperties.showStudyValues": !0,
"paneProperties.legendProperties.showSeriesTitle": !1, // 是否显示大标题
"paneProperties.legendProperties.showSeriesOHLC": !0,
// "paneProperties.legendProperties.showBarChange": !1,
// "paneProperties.legendProperties.showOnlyPriceSource": !1,

// K线图样式
"mainSeriesProperties.candleStyle.upColor": t.up,
"mainSeriesProperties.candleStyle.downColor": t.down,
"mainSeriesProperties.candleStyle.drawWick": !0,
"mainSeriesProperties.candleStyle.drawBorder": !0,
"mainSeriesProperties.candleStyle.borderColor": t.border,
"mainSeriesProperties.candleStyle.borderUpColor": t.up,
"mainSeriesProperties.candleStyle.borderDownColor": t.down,
"mainSeriesProperties.candleStyle.wickUpColor": t.up,
"mainSeriesProperties.candleStyle.wickDownColor": t.down,
"mainSeriesProperties.candleStyle.barColorsOnPrevClose": !1,
// 空心K线图样式
"mainSeriesProperties.hollowCandleStyle.upColor": t.up,
"mainSeriesProperties.hollowCandleStyle.downColor": t.down,
"mainSeriesProperties.hollowCandleStyle.drawWick": !0,
"mainSeriesProperties.hollowCandleStyle.drawBorder": !0,
"mainSeriesProperties.hollowCandleStyle.borderColor": t.border,
"mainSeriesProperties.hollowCandleStyle.borderUpColor": t.up,
"mainSeriesProperties.hollowCandleStyle.borderDownColor": t.down,
"mainSeriesProperties.hollowCandleStyle.wickColor": t.line,
// 平均K线图样式
"mainSeriesProperties.haStyle.upColor": t.up,
"mainSeriesProperties.haStyle.downColor": t.down,
"mainSeriesProperties.haStyle.drawWick": !0,
"mainSeriesProperties.haStyle.drawBorder": !0,
"mainSeriesProperties.haStyle.borderColor": t.border,
"mainSeriesProperties.haStyle.borderUpColor": t.up,
"mainSeriesProperties.haStyle.borderDownColor": t.down,
"mainSeriesProperties.haStyle.wickColor": t.border,
"mainSeriesProperties.haStyle.barColorsOnPrevClose": !1,
// 美国线样式
"mainSeriesProperties.barStyle.upColor": t.up,
"mainSeriesProperties.barStyle.downColor": t.down,
"mainSeriesProperties.barStyle.barColorsOnPrevClose": !1,
"mainSeriesProperties.barStyle.dontDrawOpen": !1,
// 线形图样式
"mainSeriesProperties.lineStyle.color": t.border,
"mainSeriesProperties.lineStyle.linewidth": 1,
"mainSeriesProperties.lineStyle.priceSource": "close",
// 面积图样式
"mainSeriesProperties.areaStyle.color1": t.areatop,
"mainSeriesProperties.areaStyle.color2": t.areadown,
"mainSeriesProperties.areaStyle.linecolor": t.border,
"mainSeriesProperties.areaStyle.linewidth": 2,
"mainSeriesProperties.areaStyle.priceSource": "close",
/*
数据列风格。 请参阅下面的支持的值
Bars = 0 #美国线 Candles = 1 #K线图 Line = 2 #线形图
Area = 3 #面积图 Heiken Ashi = 8 #平均K线 Hollow Candles = 9 #空心K线
Renko = 4 #转形图 Kagi = 5 #卡吉图 Point&Figure = 6 #点数图
Line Break = 7 #新
*/
"mainSeriesProperties.style": intervalType,
// 基准线样式
"mainSeriesProperties.baselineStyle.baselineColor":
"rgba( 117, 134, 150, 1)",
"mainSeriesProperties.baselineStyle.topFillColor1":
"rgba( 83, 185, 135, 0.1)",
"mainSeriesProperties.baselineStyle.topFillColor2":
"rgba( 83, 185, 135, 0.1)",
"mainSeriesProperties.baselineStyle.bottomFillColor1":
"rgba( 235, 77, 92, 0.1)",
"mainSeriesProperties.baselineStyle.bottomFillColor2":
"rgba( 235, 77, 92, 0.1)",
"mainSeriesProperties.baselineStyle.topLineColor": "rgba( 83, 185, 135, 1)",
"mainSeriesProperties.baselineStyle.bottomLineColor":
"rgba( 235, 77, 92, 1)",
"mainSeriesProperties.baselineStyle.topLineWidth": 1,
"mainSeriesProperties.baselineStyle.bottomLineWidth": 1,
"mainSeriesProperties.baselineStyle.priceSource": "close",
"mainSeriesProperties.baselineStyle.transparency": 50,
"mainSeriesProperties.baselineStyle.baseLevelPercentage": 50
};
};
//设置成交量默认样式
TVApi.prototype.getStudiesOverrides = function (theme) {
var themes = {
white: {
c0: "rgb(213, 79, 60)",
c1: "rgb(77, 179, 106)",
t: 60,
v: !1
},
black: {
c0: "#fa5252",
c1: "#12b886",
t: 90,
v: !1
}
};
var t = themes[theme];
return {
"volume.volume.color.0": t.c0,
"volume.volume.color.1": t.c1,
"volume.volume.transparency": 100,
"volume.volume.linewidth": 1,
"volume.volume ma.linewidth": 3,
"volume.volume ma.plottype": "line",
"volume.show ma": true,
"volume.options.showStudyArguments": !0,
"volume.ma length": 5,
"bollinger bands.length": 10,
"bollinger bands.upper.color": "#DFC987",
"bollinger bands.median.color": "#749A9E",
"bollinger bands.lower.color": "#158EFE",
"bollinger bands.upper.linewidth": 3,
"bollinger bands.median.linewidth": 3,
"bollinger bands.lower.linewidth": 3,
"bollinger bands.plots background": "rgba(0,0,0,0)",
"macd.macd.color": "#DFC987",
"macd.signal.color": "#158EFE",
"macd.macd.linewidth": 3,
"macd.signal.linewidth": 3,
"macd.histogram.linewidth": 3,
"macd.histogram.plottype": "histogram",
"rsi.length": 14,
"rsi.source": "close",
"rsi.plot.linewidth": 3,
"rsi.plot.color": "rgba(10,115,255,1)",
"stoch.length": 14,
"stoch.smoothk": 1,
"stoch.smoothd": 3,
"stoch.%k.linewidth": 3,
"stoch.%d.linewidth": 3,
"stoch.show upperlimit": !1,
"stoch.show lowerlimit": !1,
"stoch.hlines background": !1
};
};
// 转换intervalType(1min/15min/day/week/1hour/4hour)为interval(1/15/1D/week/60/240)
TVApi.prototype.changeInterval = function (intervalType) {
let intervalObj = {
hm: "1",
"1min": "1",
"5min": "5",
"15min": "15",
"30min": "30",
"1hour": "60",
day: "1D",
week: "1W",
month: "1M"
};
return {
interval: intervalObj[intervalType] || "",
lineType: intervalType == "hm" ? 3 : 1
};
};
/**
* 转换数据格式
* @param {*Array} arr 数据信息
*/
TVApi.prototype.changeData = function (arr = []) {
return {
time: parseInt((arr[0] + "").length == 13 ? +arr[0] : +arr[0] * 1000),
open: +arr[1],
high: +arr[2],
low: +arr[3],
close: +arr[4],
volume: +arr[5]
};
};

/**
* 处理websocket返回的数据
* @param {*Array} data 数据信息
*/
// 数据模式 klines: [[1610613060000, "0.3471", "0.3471", "0.3469", "0.3469", "14765.4", 0, "5122.79336", 4, "0", "0"]]
TVApi.prototype.onMessage = function (data) {
var t = this,
ticker = t.interval;
// 历史数据
if ((data && data.length > 1) || (data && this.intervalType == "month")) {
console.log(ticker, data);

var _callback = t.cacheData[ticker + "_callback"],
_data = data.map(i => {
return t.changeData(i);
});
if (_callback) {
console.log(
"-------{callback} 调用 onMessage-------",
t.intervalType,
_data.length
);
t.cacheData = {};
_callback(_data, {
noData: 0 === _data.length
});
Window._hasGetBars = true;
errorTimer(true);
} else {
console.log(_callback);
console.log("-------{data} 缓存 onMessage-------");
t.cacheData[ticker + "_data"] = _data;
}
setTimeout(() => {
t.setMaStudyLegend();
}, 30);
}
// 递增数据
if (data && data.length === 1 && !TV_TIMER) {
t.datafeeds.updateData(t.changeData(data[0]));
}
};
TVApi.prototype.getBars = function (
symbolInfo,
resolution,
rangeStartDate,
rangeEndDate,
onDataCallback,
onErrorCallback
) {
var ticker = this.interval;
console.log("resolution", resolution);
console.log("ticker", ticker);
if (Window._hasGetBars || ticker !== resolution) {
onDataCallback([], {
noData: !0
});
return !0;
} else {
let _data = this.cacheData[ticker + "_data"];
console.log("typeof", typeof _data);
if (_data) {
console.log(
this.intervalType,
_data.length,
"-------{data} 调用 getBars-------"
);
this.cacheData = {};
onDataCallback(_data, {
noData: 0 === _data.length
});
Window._hasGetBars = true;
errorTimer(true);
} else {
console.log(_data);
console.log("-------{callback} 缓存 getBars-------");
this.cacheData[ticker + "_callback"] = onDataCallback;
}
}
};

var TVjsApi = new TVApi();
setTimeout(() => {
var params = TVjsApi.getUrlParams();
TVjsApi.intervalType = params["intervalType"] || "1min";
TVjsApi.interval =
TVjsApi.changeInterval(TVjsApi.intervalType)["interval"] || "1";
TVjsApi.initTradingView();
}, 10);
setTimeout(() => {
TVjsApi.initSocket();
var params = TVjsApi.getUrlParams();
var topStudyName = !params.hasOwnProperty("study_top")
? "MA"
: params["study_top"] || "";
var bottomStudyName = params.study_bottom || "";
TVjsApi.setStudyByName(topStudyName, bottomStudyName);
}, 50);