Skip to content

Instantly share code, notes, and snippets.

@ajpierce
Created December 10, 2015 02:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ajpierce/60f216142143b34764cf to your computer and use it in GitHub Desktop.
Save ajpierce/60f216142143b34764cf to your computer and use it in GitHub Desktop.
Script to replicate issue seen in https://github.com/pilwon/node-ib/issues/8
'use strict';
// Third party libs -- install via npm
var IBAPI = new require('./node-ib');
var _ = require('lodash');
var moment = require('moment');
// Config vars
var config = {
barSize: 60,
durationString: '2 D',
barSizeSetting: '1 min',
ibHost: 'tws', // set this to localhost; I'm using Docker
ibPort: 4001,
ibClientId: 1,
reconnectInterval: 10000
};
var pairs = [
'AUDUSD',
'EURUSD',
'GBPUSD',
'USDCAD',
'USDCHF',
'USDJPY'
];
// TWS/IB helper functions
var requestId = parseInt(('' + Date.now()).substr(4));
function getNextRequestId() {
requestId = requestId + 1;
return _.clone(requestId);
}
function getIBDate() {
return moment().format('YYYYMMDD HH:mm:ss');
}
function getRequestInfo(ib, pairs) {
/**
* Returns an object whose keys are tickerIds and whose values
* are contracts representing each of the pairs passed in
**/
var tickerIds = _.times(pairs.length, getNextRequestId);
var contracts = _.map(pairs, function(pair) {
var symbol = pair.substr(0, 3);
var currency = pair.substr(3, 6);
return ib.contract.forex(symbol, currency);
});
return _.zipObject(tickerIds, contracts);
}
// Connect to IB
var reconnectCodes = [
'ECONNREFUSED', // API server not yet connected
'ECONNRESET' // IB shut down partway through
];
function connectToIb() {
var ib = new IBAPI({
clientId: config.ibClientId,
host: config.ibHost,
port: config.ibPort
}).on('connected', function() {
// Request all currencies at once, watch it barf
var requestInfo = getRequestInfo(ib, pairs);
_.forEach(requestInfo, function(contract, tickerId) {
var endDateTime = getIBDate();
console.log('Requesting bars for %s%s', contract.symbol, contract.currency);
ib.reqHistoricalData(parseInt(tickerId), contract, endDateTime,
config.durationString, config.barSizeSetting, 'BID', 0, 1);
});
}).on('result', function (event, args) {
console.log('%s --- %s', event, JSON.stringify(args));
}).on('error', function (err) {
if (err.code && _.contains(reconnectCodes, err.code)) {
console.log('Not connected to IB (%s); attempting a reconnect in %s seconds',
err.code, config.reconnectInterval / 1000);
return setTimeout(connectToIb, config.reconnectInterval);
} else {
console.error(err);
}
}).connect();
}
connectToIb();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment