nodegdax/app.js

103 lines
3.0 KiB
JavaScript

var bs = require('binarysearch');
var Gdax = require('gdax');
var orderBook = [];
orderBook['bids'] = [];
orderBook['bids']['price'] = [];
orderBook['bids']['size'] = [];
orderBook['asks'] = [];
orderBook['asks']['price'] = [];
orderBook['asks']['size'] = [];
var wsGdax = new Gdax.WebsocketClient(
['BTC-EUR'],
'wss://ws-feed.gdax.com',
null,
{channels: ['level2', 'heartbeat']}
);
function array_keys(input) {
var output = [];
var counter = 0;
for (i in input) {
output[counter++] = i;
}
return output;
}
wsGdax.on('message', function(data) {
if(data.type === 'snapshot') {
// save snapshot on orderBook object
for(var i=0; i<data.bids.length; i++) {
var bid = data.bids[i];
pos = bs.closest(orderBook['bids']['price'], bid[0]);
orderBook['bids']['price'].splice(pos, 0, bid[0]);
orderBook['bids']['size'].splice(pos, 0, bid[1]);
}
for(var i=0; i<data.asks.length; i++) {
var ask = data.asks[i];
pos = bs.closest(orderBook['asks']['price'], ask[0]);
orderBook['asks']['price'].splice(pos, 0, ask[0]);
orderBook['asks']['size'].splice(pos, 0, ask[1]);
}
return;
}
if(data.type === 'l2update') {
// apply the changes
var changes = data.changes;
for(var i=0; i<changes.length; i++) {
var change = changes[i];
if(change[0] === 'buy') {
if(change[2] === '0') {
pos = bs.closest(orderBook['bids']['price'], change[1]);
orderBook['bids']['price'].splice(pos, 1);
orderBook['bids']['size'].splice(pos, 1);
} else {
pos = bs.closest(orderBook['bids']['price'], change[1]);
orderBook['bids']['price'].splice(pos, 0, change[1]);
orderBook['bids']['size'].splice(pos, 0, change[2]);
}
} else if (change[0] === 'sell') {
if(change[2] === '0') {
pos = bs.closest(orderBook['asks']['price'], change[1]);
orderBook['asks']['price'].splice(pos, 1);
orderBook['asks']['size'].splice(pos, 1);
} else {
pos = bs.closest(orderBook['asks']['price'], change[1]);
orderBook['asks']['price'].splice(pos, 0, change[1]);
orderBook['asks']['size'].splice(pos, 0, change[2]);
}
}
}
console.log("bids " + orderBook['bids']['size'].length + "/" + orderBook['bids']['price'].length + " = " + orderBook['bids']['price'].slice(-1) + " -------- " + "asks " + orderBook['asks']['size'].length + "/" + orderBook['asks']['price'].length + " = " + orderBook['asks']['price'].slice(-1));
return;
}
});
wsGdax.on('close', function(data) {
console.log('wsGdax closed:', data);
});
wsGdax.on('error', function(data) {
console.log('wsGdax error:', data);
});
wsGdax.on('open', function() {
console.log('wsGdax opened');
});