forked from rDrayBen/Algohouse-fetchers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweex-fetcher.js
220 lines (185 loc) · 6.83 KB
/
weex-fetcher.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
import WebSocket from 'ws';
import fetch from 'node-fetch';
// define the websocket and REST URLs
const wsUrl = 'wss://stream-rest.qqkcs.com/v1/stream?compress=false';
const restUrl = "http://www.weex.com/v1/spot/public/coinChainList";
const response = await fetch(restUrl);
//extract JSON from the http response
const myJson = await response.json();
var currencies = [];
// extract symbols from JSON returned information
for(let i = 0; i < myJson['data'].length; ++i){
if(myJson['data'][i]['coinName'] === "USDT") continue;
currencies.push(myJson['data'][i]['coinName'].toLowerCase() + '_usdt');
}
// print metadata about pairs
async function Metadata(){
myJson['data'].forEach((item)=>{
if(item['coinName'] !== "USDT"){
let pair_data = '@MD ' + item['coinName'] + '-USDT spot ' + item['coinName'] + ' ' + 'USDT' + ' '
+ '-1' + ' 1 1 0 0';
console.log(pair_data);
}
})
console.log('@MDEND')
}
//function to get current time in unix format
function getUnixTime(){
return Math.floor(Date.now());
}
// func to print trades
async function getTrades(message){
message['data'].forEach((item)=>{
var name = message['id'].replace('histroyInit|', '');
name = name.split('_')[0].toUpperCase() + '-' + name.split('_')[1].toUpperCase();
var trade_output = '! ' + getUnixTime() + ' ' + name + ' ' +
(item['type'] === 1 ? 'S' : 'B') + ' ' + item['prize'] + ' ' + item['count'];
console.log(trade_output);
});
}
// func to print orderbooks and deltas
async function getSnapshot(message){
var name = message['id'].replace('depthInit|', '');
name = name.split('_')[0].toUpperCase() + '-' + name.split('_')[1].toUpperCase();
// check if bids array is not Null
if(message['data']['bids']){
var order_answer = '$ ' + getUnixTime() + ' ' + name + ' B ';
var pq = '';
for(let i = 0; i < message['data']['bids'].length; i++){
pq += message['data']['bids'][i]['count'] + '@' + message['data']['bids'][i]['prize'] + '|';
}
pq = pq.slice(0, -1);
console.log(order_answer + pq + ' R');
}
// check if asks array is not Null
if(message['data']['asks']){
var order_answer = '$ ' + getUnixTime() + ' ' + name + ' S '
var pq = '';
for(let i = 0; i < message['data']['asks'].length; i++){
pq += message['data']['asks'][i]['count'] + '@' + message['data']['asks'][i]['prize'] + '|';
}
pq = pq.slice(0, -1);
console.log(order_answer + pq + ' R');
}
}
async function ConnectTrades(pair){
// create a new websocket instance
var ws = new WebSocket(wsUrl);
ws.onopen = function(e) {
// create ping function to keep connection alive
// ws.ping();
setInterval(function() {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify(
{
"action": "requestTheheartbeat",
"id": `requestTheheartbeat|ping|${getUnixTime()}`
}
));
console.log('Ping request sent');
}
}, 15000);
// subscribe to trades and orders for all instruments
ws.send(JSON.stringify(
{
"id": `histroyInit|${pair}`,
"action": "histroyInit",
"count": 10,
"exchangeTypeCode": pair
}
));
};
// func to handle input messages
ws.onmessage = function(event) {
try{
// parse input data to JSON format
let dataJSON = JSON.parse(event.data);
if (dataJSON['action'] === 'histroyInit' && dataJSON['data'].length > 5){
// skip trades history
}else if(dataJSON['action'] === 'histroyInit' && dataJSON['data'].length <= 5){
getTrades(dataJSON);
}else{
console.log(dataJSON);
}
}catch(e){
// skip confirmation messages cause they can`t be parsed into JSON format without an error
}
};
// func to handle closing connection
ws.onclose = function(event) {
if (event.wasClean) {
console.log(`Connection closed with code ${event.code} and reason ${event.reason}`);
} else {
console.log('Connection lost');
setTimeout(async function() {
ConnectTrades(pair);
}, 500);
}
};
// func to handle errors
ws.onerror = function(error) {
console.log(`Error ${error} occurred`);
};
}
async function ConnectSnapshots(pair){
// create a new websocket instance
var ws = new WebSocket(wsUrl);
ws.onopen = function(e) {
// create ping function to keep connection alive
setInterval(function() {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify(
{
"action": "requestTheheartbeat",
"id": `requestTheheartbeat|ping|${getUnixTime()}`
}
));
console.log('Ping request sent');
}
}, 15000);
// subscribe to trades and orders for all instruments
ws.send(JSON.stringify(
{
"action": "depthInit",
"depthAccuracy": "0.00000001",
"exchangeTypeCode": pair,
"id": `depthInit|${pair}`
}
));
};
// func to handle input messages
ws.onmessage = function(event) {
try{
// parse input data to JSON format
let dataJSON = JSON.parse(event.data);
if (dataJSON['action'] === 'depthInit'){
getSnapshot(dataJSON);
}else{
console.log(dataJSON);
}
}catch(e){
// skip confirmation messages cause they can`t be parsed into JSON format without an error
}
};
// func to handle closing connection
ws.onclose = function(event) {
if (event.wasClean) {
console.log(`Connection closed with code ${event.code} and reason ${event.reason}`);
} else {
console.log('Connection lost');
setTimeout(async function() {
ConnectSnapshots(pair);
}, 500);
}
};
// func to handle errors
ws.onerror = function(error) {
console.log(`Error ${error} occurred`);
};
}
Metadata();
var connections = [];
for(let pair of currencies){
connections.push(ConnectTrades(pair));
connections.push(ConnectSnapshots(pair));
}