-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMarketSocket.js
376 lines (323 loc) · 9.48 KB
/
MarketSocket.js
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
const EventEmitter = require('eventemitter3');
const WebSocket = require('ws');
const _ = require('lodash');
const { getDurationLabel, getDurationValue, randomStr, datetimeToNano } = require('./util');
const MARKET_URL = 'wss://openmd.shinnytech.com/t/md/front/mobile';
// const MARKET_URL = 'wss://api.shinnytech.com/t/nfmd/front/mobile'; // 行情备选wss地址
class MarketSocket extends EventEmitter {
constructor(url = MARKET_URL, options = {}) {
super();
if (typeof url === 'object') {
options = url;
url = MARKET_URL;
}
this.url = url;
this.ws = null;
this.queue = [];
// 自动重连开关
this.reconnect = true;
this.reconnectTask = null;
this.reconnectInterval = options.reconnectInterval || 3000;
this.reconnectMaxTimes = options.reconnectMaxTimes || 3;
this.reconnectTimes = 0;
this._init(false);
}
send (data) {
const objToJson = JSON.stringify(data);
if (this.isReady()) {
this.ws.send(objToJson);
}
else {
this.queue.push(objToJson);
}
}
isReady() {
return this.ws.readyState === WebSocket.OPEN
}
_init (isReconnection = true) {
this.ws = new WebSocket(this.url);
if (isReconnection) {
this.reconnectTimes += 1;
}
this.ws.onmessage = (message) => {
// eslint-disable-next-line no-eval
const data = JSON.parse(message.data);
this.emit('message', data);
this.ws.send('{"aid":"peek_message"}');
}
this.ws.onclose = (event) => {
this.emit('close', event);
// 清空 queue
this.queue = [];
// 自动重连
if (this.reconnect) {
if (this.reconnectMaxTimes <= this.reconnectTimes) {
clearTimeout(this.reconnectTask);
this.emit('death', {
msg: `超过重连次数 ${this.reconnectMaxTimes}`
});
}
else {
this.reconnectTask = setTimeout(() => {
if (this.ws.readyState === WebSocket.CLOSED) {
// 每次重连的时候设置 _this.reconnectUrlIndex
this._init(true)
this.emit('reconnect', {
msg: `发起第 ${this.reconnectTimes} 次重连`
});
}
}, this.reconnectInterval);
}
}
}
this.ws.onerror = error => {
this.emit('error', error);
this.ws.close();
}
this.ws.onopen = () => {
this.emit('open', {
msg: `建立与 ${this.url} 的连接成功`
});
if (this.reconnectTask) {
clearTimeout(this.reconnectTask)
}
while (this.queue.length > 0) {
if (this.ws.readyState === WebSocket.OPEN) {
this.ws.send(this.queue.shift());
}
else {
break;
}
}
}
}
close() {
this.ws.onclose = () => {};
this.ws.close();
}
getKlines({ data, symbol, duration, endId }) {
if (data.aid === 'rtn_data') {
const list = data.data;
let len = list.length;
let bars = {};
let charts;
for (let i = 0; i < len; i++) {
const tempCharts = list[i] && list[i].charts;
if (tempCharts) {
charts = tempCharts;
len = i;
break;
}
}
let leftId, rightId, hasMoreData = true;
if (charts) {
const chart = charts[this.klineChartId];
if (chart) {
leftId = chart.left_id;
rightId = chart.right_id;
hasMoreData = chart.more_data;
}
}
for (let i = 0; i < len; i++) {
const d = list[i];
if (Object.keys(d).length === 1 && d.klines) {
for (const symbol in d.klines) {
if (!bars[symbol]) {
bars[symbol] = {};
}
const barMap = bars[symbol];
const symbolKlineData = d.klines[symbol];
for (const durationValue in symbolKlineData) {
const durationKlineData = symbolKlineData[durationValue].data;
const durationLabel = getDurationLabel(Number(durationValue));
if (durationKlineData) {
for (let id in durationKlineData) {
id = Number(id);
if (endId && id === endId) {
continue;
}
const bar = durationKlineData[id];
bar.symbol = symbol;
bar.duration = durationLabel;
bar.id = id;
bar.datetime /= 1e6; // 转换成毫秒
barMap[id] = bar;
}
}
}
}
}
}
for (const symbol in bars) {
bars[symbol] = Object.values(bars[symbol]);
}
if (symbol) {
bars = bars[symbol];
if (bars && bars.length) {
if (duration) {
if (typeof duration === 'number') {
duration = getDurationLabel(duration);
}
bars = bars.filter(item => item.duration === duration);
}
}
}
return {
bars,
rightId,
hasMoreData
};
}
}
getTicks({ data, symbol, toArray = true }) {
if (data.aid === 'rtn_data') {
const list = data.data;
let len = list.length;
const ticks = {};
const endTicks = {}; // 落在leftId和rightId外的tick
let charts;
for (let i = 0; i < len; i++) {
const tempCharts = list[i] && list[i].charts;
if (tempCharts) {
charts = tempCharts;
len = i;
break;
}
}
if (!charts) {
return {
ticks,
endTicks
};
}
const chart = charts[this.tickChartId];
if (!chart) {
return {
ticks,
endTicks
};
}
const leftId = chart.left_id;
const rightId = chart.right_id;
if (!_.isNumber(leftId) || !_.isNumber(rightId)) {
return {
ticks,
endTicks
};
}
for (let i = 0; i < len; i++) {
const d = list[i];
if (Object.keys(d).length === 1 && d.ticks) {
for (const symbol in d.ticks) {
if (!ticks[symbol]) {
ticks[symbol] = {};
}
if (!endTicks[symbol]) {
endTicks[symbol] = {};
}
const tickMap = ticks[symbol];
const endTickMap = endTicks[symbol];
const symbolTickData = d.ticks[symbol].data;
for (let id in symbolTickData) {
id = Number(id);
const tick = symbolTickData[id];
tick.symbol = symbol;
tick.id = id;
tick.datetime /= 1e6; // 转换成毫秒
if (id < leftId || id > rightId) {
tick.leftId = leftId;
tick.rightId = rightId;
if (id > rightId) {
endTickMap[id] = tick;
}
continue;
}
tickMap[id] = tick;
}
}
}
}
for (const symbol in ticks) {
ticks[symbol] = Object.values(ticks[symbol]).sort((a, b) => a.id - b.id);
}
for (const symbol in endTicks) {
endTicks[symbol] = Object.values(endTicks[symbol]).sort((a, b) => a.id - b.id);;
}
if (symbol) {
ticks = ticks[symbol];
endTicks = endTicks[symbol];
}
return {
ticks,
endTicks
};
}
}
getQuotes({ data, symbol }) {
if (data.aid === 'rtn_data') {
let list = data.data;
for (let i = 0, l = list.length; i < l; i++) {
let d = list[i];
if (Object.keys(d).length === 1 && d.quotes) {
return symbol ? d.quotes[symbol] : d.quotes;
}
}
}
}
/**
* @param {String} symbol 合约 SHFE.rb2101
* @param {String} duration 周期 '1m', '5m', '15m', '30m'
*/
requestKlines({ symbol = '', duration = '1m' }) {
let symbols = symbol.split(',');
if (symbols && symbols.length > 1) {
// 实际上快期接口是支持一次订阅多个kline序列的, 但为了处理方便同时和requestTicks接口保持一致, 故这里默认也只支持单个合约订阅, 可通过multipleSymbols解锁多合约订阅功能
throw new Error('Kline序列不支持多合约订阅');
}
const params = {
aid: 'set_chart',
chart_id: 'kline_chart_' + randomStr(),
ins_list: symbol,
duration: getDurationValue(duration),
view_width: 10000,
// trading_day_start_id: 51540,
// trading_day_count: 1
// left_kline_id: 51685
// focus_datetime: datetimeToNano(startDatetime),
// focus_position: 0
};
this.klineChartId = params.chart_id;
this.send(params);
return params;
}
requestTicks({ symbol = '', startDatetime, count = 1998, chartId }) {
let symbols = symbol.split(',');
if (symbols && symbols.length > 1) {
throw new Error('Tick序列不支持多合约订阅');
}
const params = {
aid: 'set_chart',
chart_id: chartId || 'tick_chart_' + randomStr(),
ins_list: symbol,
duration: 0,
view_width: count,
focus_datetime: datetimeToNano(startDatetime),
focus_position: 0
};
this.tickChartId = params.chart_id;
this.send(params);
return params;
}
requestQuotes({ symbols = [] }) {
if (_.isString(symbols)) {
symbols = symbols.split(',');
}
const params = {
aid: 'subscribe_quote',
ins_list: symbols.join(',')
};
this.send(params);
return params;
}
}
module.exports = MarketSocket;