109 lines
2.7 KiB
JavaScript
109 lines
2.7 KiB
JavaScript
var bs = require('binarysearch');
|
|
var Gdax = require('gdax');
|
|
|
|
|
|
var orderBook = {
|
|
bids: {},
|
|
asks: {}
|
|
};
|
|
|
|
|
|
var wsGdax = new Gdax.WebsocketClient(
|
|
['BTC-EUR'],
|
|
'wss://ws-feed.gdax.com',
|
|
null,
|
|
{channels: ['level2', 'heartbeat']}
|
|
);
|
|
|
|
|
|
function array_keys(input) {
|
|
var output = new Array();
|
|
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];
|
|
orderBook.bids[bid[0]] = bid[1];
|
|
}
|
|
for(var i=0; i<data.asks.length; i++) {
|
|
var ask = data.asks[i];
|
|
orderBook.asks[ask[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') {
|
|
delete orderBook.bids[change[1]];
|
|
} else {
|
|
pos = bs.closest(array_keys(orderBook.bids), change[2]);
|
|
tmp = new array();
|
|
tmp[change[1]] = change[2];
|
|
|
|
orderBook.bids = orderBook.bids.splice(pos, 0, tmp);
|
|
console.log(orderBook.bids);
|
|
|
|
delete tmp;
|
|
//orderBook.bids[change[1]] = change[2];
|
|
}
|
|
} else if (change[0] === 'sell') {
|
|
if(change[2] === '0') {
|
|
delete orderBook.asks[change[1]];
|
|
} else {
|
|
orderBook.asks[change[1]] = change[2];
|
|
}
|
|
}
|
|
}
|
|
|
|
// crate arrays then sort
|
|
var bids = [];
|
|
var asks = [];
|
|
for(var price in orderBook.bids) {
|
|
bids.push([parseFloat(price), parseFloat(orderBook.bids[price])]);
|
|
}
|
|
for(var price in orderBook.asks) {
|
|
asks.push([parseFloat(price), parseFloat(orderBook.asks[price])]);
|
|
}
|
|
|
|
// sort asc
|
|
asks.sort(function (a, b) {
|
|
return a[0] - b[0];
|
|
});
|
|
|
|
// sort desc
|
|
bids.sort(function (a, b) {
|
|
return b[0] - a[0];
|
|
});
|
|
|
|
if( asks[0][0] < bids[0][0] ) {
|
|
console.log('order book out of sync', asks[0], bids[0]);
|
|
}
|
|
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');
|
|
});
|