crypto-nodes
Version:
307 lines (205 loc) • 7.79 kB
JavaScript
var per_second = 0;
var bittrex_obj = {
init_ws: function (node, symbols) {
//console.log('Starting BITTREX WS');
var that = this;
function tick(data) {
per_second++;
if (data.M === 'updateExchangeState') {
data.A.forEach(function(data_for) {
//console.log(data_for);
var tmp = data_for.MarketName.split('-');
node.send({ payload: { 'exchange' : 'bittrex', fees: that.fees, sym_from: tmp[0], sym_to: tmp[1], 'data' : data } });
});
}
}
function reconnect() {
var websocketsclient = that.bittrex.websockets.client(function () {
//console.log('Connected!!');
that.bittrex.websockets.subscribe(symbols, tick);
});
//bittrex.websockets.serviceHandlers.connectFailed = function(error) { console.log("Websocket connectFailed: ", error); reconnect(); };
//bittrex.websockets.serviceHandlers.disconnected = function () { console.log("Websocket disconnected"); reconnect(); };
//bittrex.websockets.serviceHandlers.bindingError = function (error) { console.log("Websocket bindingError: ", error); reconnect(); };
//bittrex.websockets.serviceHandlers.connectionLost = function (error) { console.log("Connection Lost: ", error); reconnect(); };
}
reconnect();
/**
* the messages received must be parsed as json first e.g. via jsonic(message.utf8Data)
*/
//websocketsclient.serviceHandlers.messageReceived = function (message) {
// console.log(message);
// }
/**
* all possible serviceHandlers:
*
* bound: function() { console.log("Websocket bound"); },
* connectFailed: function(error) { console.log("Websocket connectFailed: ", error); },
* connected: function(connection) { console.log("Websocket connected"); },
* disconnected: function() { console.log("Websocket disconnected"); },
* onerror: function (error) { console.log("Websocket onerror: ", error); },
* messageReceived: function (message) { console.log("Websocket messageReceived: ", message); return false; },
* bindingError: function (error) { console.log("Websocket bindingError: ", error); },
* connectionLost: function (error) { console.log("Connection Lost: ", error); },
* reconnecting: function (retry { inital: true/false, count: 0} ) {
* console.log("Websocket Retrying: ", retry);
* //return retry.count >= 3; // cancel retry true
* return true;
* }
*/
/*websocketsclient.serviceHandlers.onerror = function (error) {
console.log('some error occured', error);
}
*/
},
fees: {},
interval: false,
connected: false,
exchange_symbols: [],
configured_symbols: [],
enabled_symbols: [],
get_exchange_symbols: function(callback) {
//console.log('CALLING');
this.bittrex.getmarketsummaries( function( data, err ) {
var symbols = [];
if (err) {
console.error(err);
} else {
for( var i in data.result ) {
symbols.push(data.result[i].MarketName);
}
}
//console.log('BACK..');
callback(symbols);
});
},
get_enabled_symbols: function() {
var out = [];
for(x in this.exchange_symbols) {
var pass = false;
var exc_tmp = this.exchange_symbols[x].toUpperCase().split('-');
for(y in this.configured_symbols) {
var cfg_tmp = this.configured_symbols[y].split('/');
// If its matching or inverted variant matches its enabled symbol
if((exc_tmp[0] == cfg_tmp[0] && exc_tmp[1] == cfg_tmp[1]) ||
(exc_tmp[0] == cfg_tmp[1] && exc_tmp[1] == cfg_tmp[0])
) {
pass = true;
}
}
if(pass) {
out.push(this.exchange_symbols[x]);
}
}
return out;
},
init: function(config, node, symbols, callback) {
var that = this;
this.configured_symbols = symbols;
//console.log(symbols);
try { this.fees = JSON.parse(config.fees); } catch (e) {}
if (!this.interval) {
this.interval = setInterval(function() {
var color = per_second > 0 ? 'green' : 'red';
node.status({ fill: color, shape: 'ring', text: per_second + ' requests per second' });
per_second = 0;
}, 1000);
}
this.bittrex = require('node-bittrex-api');
var opts = { verbose: false }
if(config.api_key && config.api_secret) {
opts.apikey = config.api_key;
opts.apisecret = config.apisecret;
}
this.bittrex.options(opts);
this.get_exchange_symbols(function (exchange_symbols) {
that.exchange_symbols = exchange_symbols;
var enabled_symbols = that.get_enabled_symbols();
//console.log(exchange_symbols);
//console.log(enabled_symbols);
that.init_ws(node, enabled_symbols);
});
},
}
module.exports = function(RED) {
function bittrexConnector(config) {
RED.nodes.createNode(this,config);
var node = this;
var per_second = 0;
node.on('input', function(msg) {
if(config.disabled) {
// Disable UI Updates
if(bittrex_obj.interval) {
clearInterval(bittrex_obj.interval);
}
// Set node status
node.status({ fill: 'red',shape:'ring', text: 'Disabled' });
// Emit flush orderbook
node.send({payload: { exchange: 'bittrex', op: 'flush' }});
return;
}
if(msg.payload && msg.payload.op == 'subscribe') {
bittrex_obj.init(config, node, msg.payload.symbols);
}
});
node.on('close', function() {
// tidy up any async code here - shutdown connections and so on.
node.status({ fill: 'red',shape:'ring', text: 'Offline' });
node.send({payload: { exchange: 'bittrex', op: 'flush' }});
});
/*
var success = false;
var lock = false;
setInterval(function () {
if(lock || success) {
return;
}
console.log('BITTREX :: Trying connection');
lock = true;
bittrex.websockets.client(function(c) {
//console.log(c);
console.log('Websocket connected');
/*
0 – new order entries at matching price, you need to add it to the orderbook
1 – cancelled / filled order entries at matching price, you need to delete it from the orderbook
2 – changed order entries at matching price (partial fills, cancellations), you need to edit it in the orderbook
Buys: [ { Type: 1, Rate: 0.46148244, Quantity: 0 } ],
Sells:
[ { Type: 1, Rate: 0.46993515, Quantity: 0 },
{ Type: 1, Rate: 0.46993984, Quantity: 0 },
{ Type: 0, Rate: 0.49368263, Quantity: 0.88017017 },
{ Type: 1, Rate: 0.49799999, Quantity: 0 } ],
..
Fills: []...
..
success = true;
bittrex.websockets.subscribe(all_markets, function(data) {
// console.log(data);
if (data.M === 'updateExchangeState') {
data.A.forEach(function(data_for) {
console.log(data_for);
process(data_for);
});
}
});
});
setTimeout(function () {
lock = false;
}, 5000);
}, 1000);
});
setInterval(function () {
var color = per_second > 0 ? 'green' : 'red';
// onsole.log('BITTREX :: ' + per_second + ' requests per second');
//console.log('BITTREX :: LATEST ' + JSON.stringify(latest));
node.status({ fill: color,shape:'ring', text: per_second + ' requests per second' });
per_second = 0;
}, 1000);
/*
request('https://api.bitfinex.com/v1/symbols', function (error, response, body) {
});
*/
// node.on('input', function(msg) { console.log(msg); });
}
RED.nodes.registerType("bittrexConnector", bittrexConnector);
}