-
Notifications
You must be signed in to change notification settings - Fork 29
/
websocketStream.ts
57 lines (51 loc) · 1.8 KB
/
websocketStream.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
import { WebsocketStreamFeaturesBase } from './setters/mixinBase';
import { WebsocketStreamAPIOptions } from './setters/types';
export class WebsocketStream extends WebsocketStreamFeaturesBase {
combinedStreams: boolean;
constructor(options?: WebsocketStreamAPIOptions) {
super(options);
this.wsURL = options && options.wsURL ? options.wsURL : 'wss://stream.binance.com:9443';
this.combinedStreams = options && options.combinedStreams ? options.combinedStreams : false;
}
_prepareURL(stream: string | string[]) {
let url = `${this.wsURL}/ws/${stream}`;
if (this.combinedStreams) {
url = `${this.wsURL}/stream?streams=${stream}`;
}
return url;
}
subscribe(stream: string | string[]) {
if (!this.isConnected()) {
if (Array.isArray(stream)) stream = stream.join('/');
const url = this._prepareURL(stream);
this.initConnect(url);
} else {
if (!Array.isArray(stream)) {
stream = [stream];
}
const payload = {
method: 'SUBSCRIBE',
params: stream,
id: Date.now()
};
this.logger.info('SUBSCRIBE', payload);
this.send(JSON.stringify(payload));
}
}
unsubscribe(stream: string | string[]) {
if (!this.isConnected()) {
this.logger.warn('Not connected');
} else {
if (!Array.isArray(stream)) {
stream = [stream];
}
const payload = {
method: 'UNSUBSCRIBE',
params: stream,
id: Date.now()
};
this.logger.info('UNSUBSCRIBE', payload);
this.send(JSON.stringify(payload));
}
}
}