-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
87 lines (77 loc) · 2.08 KB
/
index.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
const http = require('http');
const Websocket = require('websocket').server;
const redis = require('redis');
const client = redis.createClient();
const config = require('./config');
//Binance API
const { APIKEY, APISECRET } = config.Binance;
const { CURRENCY } = config.Currency;
const binance = require('node-binance-api')().options({
APIKEY,
APISECRET,
useServerTime: true,
});
const server = http.createServer((req, res) => {
res.writeHead(200);
res.end(index);
});
server.listen(8080, () => {
console.log('Listen port 8080');
});
const ws = new Websocket({
httpServer: server,
autoAcceptConnections: false
});
client.on('connect', function() {
console.log('Redis client connected');
});
const connections = [];
ws.on('request', req => {
const connection = req.accept('', req.origin);
connections.push(connection);
console.log('Connected ' + connection.remoteAddress);
connection.on('message', message => {
const dataName = message.type + 'Data';
const data = message[dataName];
console.log('Received: ' + data);
connections.forEach(client => {
//When new connection to socket
if (connection == client) {
//send information about previous day
binance.prevDay(CURRENCY, (error, prevDay, symbol) => {
client.send( prevDay);
});
}
});
});
connection.on('close', (reasonCode, description) => {
console.log('Disconnected ' + connection.remoteAddress);
console.dir({ reasonCode, description });
});
});
binance.websockets.candlesticks([CURRENCY], '1m', (candlesticks) => {
const {
e:eventType,
E:eventTime,
s:symbol,
k:ticks,
} = candlesticks;
const price = {
open: ticks.o,
high: ticks.h,
low: ticks.l,
close: ticks.c,
volume: ticks.v,
trades: ticks.n,
interval: ticks.i,
isFinal: ticks.x,
quoteVolume: ticks.q,
buyVolume: ticks.V,
quoteBuyVolume: ticks.Q,
};
const prices = JSON.stringify(price);
client.set('prices', prices, redis.print);
connections.forEach(client => {
client.send(prices);
});
});