-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathwebsocketAPI.ts
76 lines (70 loc) · 2.69 KB
/
websocketAPI.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
import * as crypto from 'crypto';
import { buildQueryString, removeEmptyValue, randomString, sortObject, ObjectType } from './helpers/utils';
import { WebsocketFeaturesBase } from './setters/mixinBase';
import { WebsocketAPIOptions, sendMessageOptions } from './setters/types';
export class WebsocketAPI extends WebsocketFeaturesBase {
wsURL: string;
apiKey: string;
apiSecret: string;
constructor(apiKey = '', apiSecret = '', options: WebsocketAPIOptions = {}) {
super(apiKey, apiSecret, options);
this.wsURL = options.wsURL || 'wss://ws-api.binance.com:443/ws-api/v3';
this.initConnect(this.wsURL);
this.apiKey = apiKey;
this.apiSecret = apiSecret;
}
sendMessageWithAPIKey(method: string, options: Omit<sendMessageOptions, 'timestamp' | 'signature'> = {}) {
if (!this.isConnected()) {
this.logger.error('Not connected');
return;
}
const id = options.id || randomString();
options.apiKey = this.apiKey;
delete options.id;
const payload = {
id,
method,
params: removeEmptyValue(options)
};
this.logger.debug('Send message to Binance Websocket API Server:', payload);
this.send(JSON.stringify(payload));
}
sendMessage(method: string, options: Omit<sendMessageOptions, 'apiKey' | 'timestamp' | 'signature'> = {}) {
if (!this.isConnected()) {
this.logger.error('Not connected');
return;
}
const id = options.id && /^[0-9a-f]{32}$/.test(options.id) ? options.id : randomString();
delete options.id;
const payload = {
id,
method,
params: removeEmptyValue(options)
};
this.logger.debug('Send message to Binance Websocket API Server:', payload);
this.send(JSON.stringify(payload));
}
sendSignatureMessage(method: string, options: sendMessageOptions = {}) {
if (!this.isConnected()) {
this.logger.error('Not connected');
return;
}
const id = options.id || randomString();
delete options.id;
options = removeEmptyValue(options);
options.apiKey = this.apiKey;
options.timestamp = Date.now();
options = sortObject(options as ObjectType);
options.signature = crypto
.createHmac('sha256', this.apiSecret)
.update(buildQueryString(options))
.digest('hex');
const payload = {
id,
method,
params: options
};
this.logger.debug('Send message to Binance Websocket API Server:', payload);
this.send(JSON.stringify(payload));
}
}