-
Notifications
You must be signed in to change notification settings - Fork 3
/
dcoin.js
213 lines (183 loc) · 7.38 KB
/
dcoin.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
import WebSocket from 'ws';
import fetch from 'node-fetch';
import zlib from 'zlib';
import getenv from 'getenv';
import * as commonFunctions from './CommonFunctions/CommonFunctions.js';
// define the websocket and REST URLs
const wsUrl = 'wss://ws.dcoinpro.com/kline-api/ws';
const restUrl = "https://openapi.dcoin.com/open/api/common/symbols";
const response = await fetch(restUrl);
//extract JSON from the http response
const myJson = await response.json();
var currencies = [];
var trades_count_5min = {};
var orders_count_5min = {};
// extract symbols from JSON returned information
for(let i = 0; i < myJson['data'].length; ++i){
currencies.push(myJson['data'][i]['symbol']);
}
// print metadata about pairs
async function Metadata(){
myJson['data'].forEach((item, index)=>{
trades_count_5min[item['symbol'].toUpperCase()] = 0;
orders_count_5min[item['symbol'].toUpperCase()] = 0;
let pair_data = '@MD ' + item['symbol'].toUpperCase() + ' spot ' + item['count_coin'].toUpperCase() + ' '
+ item['base_coin'].toUpperCase() + ' '
+ (item['price_precision']*-1) + ' 1 1 0 0';
console.log(pair_data);
})
console.log('@MDEND')
}
// func to print trades
async function getTrades(message){
message['tick']['data'].forEach((item)=>{
let pair_name = message['channel'];
pair_name = pair_name.replace('market_', '');
pair_name = pair_name.replace('_trade_ticker', '');
trades_count_5min[pair_name.toUpperCase()] += 1;
var trade_output = '! ' + commonFunctions.getUnixTime() + ' ' +
pair_name.toUpperCase() + ' ' +
item['side'][0] + ' ' + item['price'] + ' ' + item['vol'];
console.log(trade_output);
});
}
// func to print orderbooks and deltas
async function getOrders(message, update){
let pair_name = message['channel'];
pair_name = pair_name.replace('market_', '');
pair_name = pair_name.replace('_depth_step', '');
pair_name = pair_name.slice(0, -1);
// check if bids array is not Null
if(message['tick']['buys'].length > 0){
orders_count_5min[pair_name.toUpperCase()] += message['tick']['buys'].length;
var order_answer = '$ ' + commonFunctions.getUnixTime() + ' ' + pair_name.toUpperCase() + ' B '
var pq = '';
for(let i = 0; i < message['tick']['buys'].length; i++){
pq += message['tick']['buys'][i][1] + '@' + message['tick']['buys'][i][0] + '|';
}
pq = pq.slice(0, -1);
// check if the input data is full order book or just update
if (update){
console.log(order_answer + pq)
}
else{
console.log(order_answer + pq + ' R')
}
}
// check if asks array is not Null
if(message['tick']['asks'].length > 0){
orders_count_5min[pair_name.toUpperCase()] += message['tick']['asks'].length;
var order_answer = '$ ' + commonFunctions.getUnixTime() + ' ' + pair_name.toUpperCase() + ' S '
var pq = '';
for(let i = 0; i < message['tick']['asks'].length; i++){
pq += message['tick']['asks'][i][1] + '@' + message['tick']['asks'][i][0] + '|';
}
pq = pq.slice(0, -1);
// check if the input data is full order book or just update
if (update){
console.log(order_answer + pq)
}
else{
console.log(order_answer + pq + ' R')
}
}
}
async function sendStats(){
commonFunctions.stats(trades_count_5min, orders_count_5min);
setTimeout(sendStats, parseFloat(5 - ((Date.now() / 60000) % 5)) * 60000);
}
function Connect1(){
var ws1 = new WebSocket(wsUrl);
// call this func when first opening connection
ws1.onopen = function(e) {
// create ping function to keep connection alive
ws1.ping();
currencies.forEach((item)=>{
// sub for trades
ws1.send(JSON.stringify(
{
"event":"sub",
"params":{
"channel":`market_${item}_trade_ticker`,
"cb_id":""
}
}
))
if(getenv.string("SKIP_ORDERBOOKS", '') === '' || getenv.string("SKIP_ORDERBOOKS") === null){
// sub for snapshot
ws1.send(JSON.stringify(
{
"event":"sub",
"params":{
"channel":`market_${item}_depth_step0`,
"cb_id":"",
"asks":150,
"bids":150
}
}
))
// sub for delta
ws1.send(JSON.stringify(
{
"event":"sub",
"params":{
"channel":`market_${item}_depth_step2`,
"cb_id":"",
"asks":10,
"bids":10
}
}
))
}
})
};
// func to handle input messages
ws1.onmessage = function(event) {
const compressedData = Buffer.from(event.data, 'base64');
zlib.gunzip(compressedData, (err, uncompressedData) => {
// console.log(uncompressedData);
try{
//uncompressedData = uncompressedData.trim();
var dataJSON = JSON.parse(uncompressedData);
// console.log(dataJSON);
if (dataJSON['channel'].slice(-6) === 'ticker' && dataJSON['tick']['data'].length <= 3){
getTrades(dataJSON);
}else if (dataJSON['channel'].slice(-6) === 'ticker' && dataJSON['tick']['data'].length > 3){
// to skip trades history
}else if(dataJSON['channel'].slice(-5) === 'step0' && 'tick' in dataJSON){
getOrders(dataJSON, false);
}else if(dataJSON['channel'].slice(-5) === 'step2' && 'tick' in dataJSON){
getOrders(dataJSON, true);
}else{
console.log(dataJSON);
}
}catch(e){
(async () => {
await commonFunctions.sleep(1000); // commonFunctions.sleep for 1000 milliseconds (1 second)
})();
}
});
};
// func to handle closing connection
ws1.onclose = function(event) {
if (event.wasClean) {
console.log(`Connection 1 closed with code ${event.code} and reason ${event.reason}`);
} else {
console.log('Connection 1 lost');
setTimeout(function() {
Connect1();
}, 500);
}
};
// func to handle errors
ws1.onerror = function(error) {
console.log(`Error ${error} occurred in ws1`);
(async () => {
await commonFunctions.sleep(1000); // commonFunctions.sleep for 1000 milliseconds (1 second)
})();
};
}
// call metadata to execute
Metadata();
setTimeout(sendStats, parseFloat(5 - ((Date.now() / 60000) % 5)) * 60000);
Connect1();