Code Monkey home page Code Monkey logo

node-ib's Introduction

Logo

NPM NPM

ib is an Interactive Brokers TWS (or IB Gateway) API client library for Node.js. Refer to the official Trader Workstation API documentation for details.

This is a direct port of Interactive Brokers' official Java client. There is no C++/Java library dependency. It makes a socket connection to TWS (or IB Gateway) using the net module, and all messages are entirely processed in JavaScript. It uses EventEmitter to pass the result back to user.

MAINTAINERS NEEDED

The libary is lagging behind the official Java reference and no updates have been made after v9.70 (~2017). This means that some newer features aren't implemented:

Installation

$ npm install ib

Usage

var ib = new (require('ib'))({
  // clientId: 0,
  // host: '127.0.0.1',
  // port: 7496
}).on('error', function (err) {
  console.error('error --- %s', err.message);
}).on('result', function (event, args) {
  console.log('%s --- %s', event, JSON.stringify(args));
}).once('nextValidId', function (orderId) {
  ib.placeOrder(
    orderId,
    ib.contract.stock('AAPL'),
    ib.order.limit('BUY', 1, 0.01)  // safe, unreal value used for demo
  );
  ib.reqOpenOrders();
}).once('openOrderEnd', function () {
  ib.disconnect();
})

ib.connect()
  .reqIds(1);

API

Connection

.connect()
.disconnect()

Methods

.calculateImpliedVolatility(reqId, contract, optionPrice, underPrice)
.calculateOptionPrice(reqId, contract, volatility, underPrice)
.cancelAccountSummary(reqId)
.cancelAccountUpdatesMulti(requestId)
.cancelCalculateImpliedVolatility(reqId)
.cancelCalculateOptionPrice(reqId)
.cancelFundamentalData(reqId)
.cancelHistoricalData(tickerId)
.cancelMktData(tickerId)
.cancelMktDepth(tickerId)
.cancelNewsBulletins()
.cancelOrder(id)
.cancelPositions()
.cancelPositionsMulti(requestId)
.cancelRealTimeBars(tickerId)
.cancelScannerSubscription(tickerId)
.cancelTickByTickData(tickerId)
.exerciseOptions(tickerId, contract, exerciseAction, exerciseQuantity, account, override)
.placeOrder(id, contract, order)
.replaceFA(faDataType, xml)
.reqAccountSummary(reqId, group, tags)
.reqAccountUpdates(subscribe, acctCode)
.reqAccountUpdatesMulti(requestId, account, modelCode, ledgerAndNLV)
.reqAllOpenOrders()
.reqAutoOpenOrders(bAutoBind)
.reqContractDetails(reqId, contract)
.reqCurrentTime()
.reqExecutions(reqId, filter)
.reqFundamentalData(reqId, contract, reportType)
.reqGlobalCancel()
.reqHistoricalData(tickerId, contract, endDateTime, durationStr, barSizeSetting, whatToShow, useRTH, formatDate, keepUpToDate)
.reqHistoricalTicks(tickerId, contract, startDateTime, endDateTime, numberOfTicks, whatToShow, useRTH, ignoreSize)
.reqTickByTickData(tickerId, contract, tickType, numberOfTicks, ignoreSize)
.reqIds(numIds)
.reqManagedAccts()
.reqMarketDataType(marketDataType)
.reqMatchingSymbols(tickerId, pattern)
.reqMktData(tickerId, contract, genericTickList, snapshot, regulatorySnapshot)
.reqMktDepth(tickerId, contract, numRows)
.reqNewsBulletins(allMsgs)
.reqOpenOrders()
.reqPositions()
.reqPositionsMulti(requestId, account, modelCode)
.reqRealTimeBars(tickerId, contract, barSize, whatToShow, useRTH)
.reqScannerParameters()
.reqScannerSubscription(tickerId, subscription)
.requestFA(faDataType)
.queryDisplayGroups(reqId)
.subscribeToGroupEvents(reqId, group)
.unsubscribeToGroupEvents(reqId)
.updateDisplayGroup(reqId, contract)
.setServerLogLevel(logLevel)

Note that .reqContractDetails doesn't respect the official format of the ContractDetails class. For example, the Contract field is replaced with a summary field that contains some of the attributes in the contract.

Events

// General
.on('error', function (err, data))
.on('result', function (event, args))  // exclude connection
.on('all', function (event, args))  // error + connection + result

// Connection
.on('connected', function ())
.on('disconnected', function ())
.on('received', function (tokens, data))
.on('sent', function (tokens, data))
.on('server', function (version, connectionTime))

// Result
.on('accountDownloadEnd', function (accountName))
.on('accountUpdateMulti', function (reqId, account, modelCode, key, value, currency))
.on('accountUpdateMultiEnd', function (reqId))
.on('accountSummary', function (reqId, account, tag, value, currency))
.on('accountSummaryEnd', function (reqId))
.on('bondContractDetails', function (reqId, contract))
.on('commissionReport', function (commissionReport))
.on('contractDetails', function (reqId, contract))
.on('contractDetailsEnd', function (reqId))
.on('currentTime', function (time))
.on('deltaNeutralValidation', function (reqId, underComp))
.on('execDetails', function (reqId, contract, exec))
.on('execDetailsEnd', function (reqId))
.on('fundamentalData', function (reqId, data))
.on('historicalData', function (reqId, date, open, high, low, close, volume, count, WAP, hasGaps))
.on('historicalTickTradeData', (reqId, timestamp, mask, price, size, exchange, specialConditions))
.on('historicalTickBidAskData', (reqId, timestamp, mask, priceBid, priceAsk, sizeBid, sizeAsk))
.on('historicalTickMidPointData', (reqId, timestamp, price, size))
.on('tickByTickAllLast', reqId, tickType, time, price, size, { pastLimit, unreported }, exchange, specialConditions)
.on('tickByTickBidAsk', reqId, time, bidPrice, askPrice, bidSize, askSize, { bidPastLow, askPastHigh })
.on('tickByTickMidPoint', reqId, time, midPoint))
.on('managedAccounts', function (accountsList))
.on('marketDataType', function (reqId, marketDataType))
.on('nextValidId', function (orderId))
.on('openOrder', function (orderId, contract, order, orderState))
.on('openOrderEnd', function ())
.on('orderStatus', function (id, status, filled, remaining, avgFillPrice, permId, parentId, lastFillPrice, clientId, whyHeld))
.on('position', function (account, contract, pos, avgCost))
.on('positionEnd', function ())
.on('positionMulti', function (reqId, account, modelCode, contract, pos, avgCost))
.on('positionMultiEnd', function (reqId))
.on('realtimeBar', function (reqId, time, open, high, low, close, volume, wap, count))
.on('receiveFA', function (faDataType, xml))
.on('scannerData', function (tickerId, rank, contract, distance, benchmark, projection, legsStr))
.on('scannerDataEnd', function (tickerId))
.on('scannerParameters', function (xml))
.on('symbolSamples', function (contractDescriptions))
.on('tickEFP', function (tickerId, tickType, basisPoints, formattedBasisPoints, impliedFuturesPrice, holdDays, futureExpiry, dividendImpact, dividendsToExpiry))
.on('tickGeneric', function (tickerId, tickType, value))
.on('tickOptionComputation', function (tickerId, tickType, impliedVol, delta, optPrice, pvDividend, gamma, vega, theta, undPrice))
.on('tickPrice', function (tickerId, tickType, price, canAutoExecute))
.on('tickSize', function (tickerId, sizeTickType, size))
.on('tickSnapshotEnd', function (reqId))
.on('tickString', function (tickerId, tickType, value))
.on('updateAccountTime', function (timeStamp))
.on('updateAccountValue', function (key, value, currency, accountName))
.on('updateMktDepth', function (id, position, operation, side, price, size))
.on('updateMktDepthL2', function (id, position, marketMaker, operation, side, price, size))
.on('updateNewsBulletin', function (newsMsgId, newsMsgType, newsMessage, originatingExch))
.on('updatePortfolio', function (contract, position, marketPrice, marketValue, averageCost, unrealizedPNL, realizedPNL, accountName))
.on('displayGroupList', function(id, list))
.on('displayGroupUpdated', function(id, contract))

Builders

// Contract
.contract.combo(symbol, currency, exchange)
.contract.forex(symbol, currency)
.contract.future(symbol, expiry, currency, exchange)
.contract.option(symbol, expiry, strike, right, exchange, currency)
.contract.stock(symbol, exchange, currency)

// Order
.order.limit(action, quantity, price, transmitOrder)
.order.market(action, quantity, transmitOrder, goodAfterTime, goodTillDate)
.order.marketClose(action, quantity, price, transmitOrder)
.order.stop(action, quantity, price, transmitOrder, parentId, tif)
.order.stopLimit(action, quantity, limitPrice, stopPrice, transmitOrder, parentId, tif)
.order.trailingStop(action, quantity, auxPrice, tif, transmitOrder, parentId)

Util

.incomingToString(incoming)
.numberToString(number)
.outgoingToString(outgoing)
.tickTypeToString(tickType)

Credits

See the contributors.

License

The MIT License (MIT)

Copyright (c) 2013-2021 Pilwon Huh

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

Analytics

node-ib's People

Contributors

ajpierce avatar andrewjdmartin avatar andrewlim1984 avatar athena123 avatar bfreis avatar buzzcloudau avatar caedmon avatar catch-point avatar claude2 avatar conanak99 avatar dependabot[bot] avatar guidov avatar hhamilto avatar jajuanm2 avatar jfyuen avatar julienbiau avatar lewisdawson avatar mfrener avatar mvberg avatar okonovalenko avatar pgodel avatar pilwon avatar sblackstone avatar tredondo avatar uberscientist avatar vorandrew avatar yuanzhanghu avatar zgsrc avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-ib's Issues

when i run sample, i got the error output, i don't know is there really some error or just log

when i run sample, i got the log from console as below

managedAccounts --- ["DU363248"]
nextValidId --- [1]
error --- Market data farm connection is OK:hfarm
error --- Market data farm connection is OK:cashfarm
error --- Market data farm connection is OK:usfarm.us
error --- Market data farm connection is OK:usfarm
error --- HMDS data farm connection is OK:hthmds
error --- HMDS data farm connection is OK:cashhmds
error --- HMDS data farm connection is OK:ushmds
nextValidId --- [1]
error --- Error validating request:-'ie' : cause - You must specify an account.
openOrderEnd --- []

i noticed that there are many errors, I do not know what goes wrong
thank you

CSCO,INTC,MSFT - Requested market data is not subscribed

For next generation:
I was reading/streaming realtime tick data using ib.reqMktData(uniqueId, {ticker: "CSCO", market: "ISLAND"}, '', false); function and I was getting errors for three tickers CSCO, INTC, MSFT. I also have standard data subscription on Interactive Brokers.
I was getting these errors:

Error: Part of requested market data is not subscribed. Subscription-independent ticks are still active.CSCO NASDAQ.NMS/TOP/BID_ASK
Error: Requested market data is not subscribed.Error&ISLAND/STK/Top

Reason for this is (as far as I know), that these tickers are traded on multiple exchanges (ISLAND and BATS) which may not be available on given subscription. I was able to fix it by setting market to BATS like this:
ib.reqMktData(uniqueId, {ticker: "CSCO", market: "BATS"}, '', false);

Bracket Orders

Is there a way to create bracket orders? Currently there's no parentId field on orders to associate child orders to parents. I'm not sure if there's another way or if this functionality is missing all together?

reqFundamentalData: Missing reportType

Hi,

I'm getting the following error when using reqFundamentalData(), this also happens in the examples/all.js:

Error:

We are sorry, but fundamentals data for the security specified is not available.Missing reportType

ib.reqFundamentalData(201, {
  currency: 'USD',
  exchange: 'SMART',
  primaryExch: 'NASDAQ',
  secType: 'STK',
  symbol: 'AMZN'
}, 'Estimates');  // reqId, contract, reportType

Using TWS 956

TIme In Force (tif) question

Where do I enter tif (time in force) when I place order,
I modified the stock.js like the following:

module.exports = function (symbol, exchange, currency, tif) {
  assert(_.isString(symbol), 'Symbol must be a string.');

  return {
    currency: currency || 'USD',
    exchange: exchange || 'SMART',
    secType: 'STK',
    symbol: symbol,
    tif: tif
  };
};

Is this going to work?
Thanks

historicalData event not emitted and with high CPU usage

I suspect that this is related to the buffer underrun problem (fixed in #8) because:

  1. no problem when I run the request with the same duration and time unit in a slower machine with some network distance to IB gateway;
  2. no problem when reducing the duration from 10 D to 5 D (for 1 min time unit);
  3. I have util.log for every 1000 historical data being received;
  4. IB gateway shows that there was request and returned data;

Here is the tick file generated by node-tick-processor after running node --prof hist.js:

tick.txt

node-ib version: 0.1.10
node version: 6.3.1

Requested market data is not subscribed.

When I call reqMktData I get an error "Requested market data is not subscribed.Error&BEST/STK/Top&BEST/STK/Top". The account definitely has a market data subscription (Nasdaq and NYSE). I'm trying AAPL... still that error message. Have tried other stocks too. The gateway is running, connection OK. I am running the reqMktData.js example as is. Then tried just one stock, AAPL, still does not work.

The FAQ on IB's web page says:

Q: Why do I receive an error 200 - No security definition has been found for the request when I call reqContractDetails, reqMktData, or addOrder() for a stock contract?

A: When using these methods for a stock contract, leave Global Symbol and Trading Class blank.

Am I supposed to change these? (if so, how) Or does the reqMktData call in node-ib handle that?

the way to close an existing forex(cash) position instead of opening a new one?

From examples, I have not managed to find out how to close an existing forex(cash) position, say a short position of USD.JPY. If I place an order of 'BUY' then it will cause a new long position to be opened while the old short position remains untouched.
There's no problem with stocks, anyway.
Thanks for any suggestions

Option: No security definition has been found for the request

Hello,

I'm trying to place orders for options, but the following error returns when I send the order.

version v0.1.7 API (TWS Build 955.2g)

joelpinheiro at joelpinheiros-MacBook-Pro in ~/Dropbox/iTrading/node-ib/examples on master [+!?$]
$ node placeOrderAll.js
option
AAPL
20170118
40
C
SMART
USD
BUY
1
0.01
managedAccounts: ["DU226956"]
[nextValidId] orderId=49
Placing orders...
Market data farm connection is OK:usfarm
HMDS data farm connection is OK:ushmds
[nextValidId] orderId=49
[orderStatus] id=49 status=ApiPending filled=0 remaining=1 avgFillPrice=NaN permId=0 parentId=0 lastFillPrice=NaN clientId=0 whyHeld=
[openOrderEnd]
[nextValidId] orderId=50
No security definition has been found for the request
Cancelling orders...
Can't find order with id =49
Can't find order with id =50
Can't find order with id =51
[openOrderEnd]
Disconnecting...

I'm using limit contract. My parameters are the follow:

option
AAPL
20170118
40
C
SMART
USD
BUY
1
0.01

Am I missing something?

Regards

Combo / BAG example

Could you supply a combo example please?

contract/combo.js only takes a symbol, but how do you define the legs?

placeOrder not working version v0.1.7 API (TWS Build 955.2g)

Hi,

First, congrats for this API.

I'm trying to call placeOrder and I have this output:

$ node placeOrder.js managedAccounts: ["DU317663"] [nextValidId] orderId=1 Placing orders... Market data farm connection is OK:cashfarm Market data farm connection is OK:usfarm.us Market data farm connection is OK:usfarm HMDS data farm connection is OK:fundfarm HMDS data farm connection is OK:ushmds [nextValidId] orderId=1 Error validating request:-'ke' : cause - You must specify an account. Error validating request:-'ke' : cause - You must specify an account. Error validating request:-'ke' : cause - You must specify an account. [openOrderEnd] [nextValidId] orderId=1 Cancelling orders... Can't find order with id =1 Can't find order with id =2 Can't find order with id =3 [openOrderEnd] Disconnecting...

When I call placeOrder there is no response from the server.

Should I specify which account I want to placeOrder?
How can I do that?

Regards

Buying on margin

Hello guys.. It is maybe lame question but .. how can I buy something on margin?

For example if I want to buy 3x leveraged AAPL CFD..

Can i browserify this api (this is not an issue)

Am completely new to the nodejs and javascript. My goal is to connect to the client side TWS/IB gateway through the web appp. Previously we used JNLP to connect to the client side TWS. Now you have given this wonderful library. And i try to browserify this to work on the client side. failed with some exception regarding net package. Is ther any way we can port this lib to browser side scripting.
Thanks in advance

incoming buffer underrun

Incoming.process can dispatch a message before all the data for the message has been received. The message in this case handler ends up reading past the end of this._dataQueue. The current message is corrupted and what's worse, when the rest of the message is received Incoming tries to start reading a new message from the middle of the last message.

I saw this frequently when using reqHistoricalData.

Use ES6 modules

Tried to use node-ib with Webpack (disabled net temporarily), still getting this error:

Uncaught (in promise) Error: Cannot find module './contract'.

It is caused by this line.

This patch seems to work:

IB.prototype.contract = require('./contract/index');
IB.prototype.order = require('./order/index');
IB.prototype.util = require('./util');

But, any plans to use modern ES6 modules?

Missing error fields in error event

The err parameter for the error event only has the error message but no other useful error object fields like the (order) id, and the errorCode.

Was there a reason for this? The id is very useful to match the error and the order that generated it.

some incorrect property types in orderState

Hi
I am getting equityWithLoan, initMargin, maintMargin as string type instead of Number (Number.MAX_VALUE) on openOrder event in orderStatus object.

equityWithLoan: "1.7976931348623157E308"
initMargin: "1.7976931348623157E308"
maintMargin: "1.7976931348623157E308"
maxCommission:1.7976931348623157e+308

scanning

Is is possible to scan for stocks and options with the API ?

thanks!

Examples does not work

I used first example from examples/all.js and it does not work.
I see next error:

@@@ ERROR: connect ECONNREFUSED @@@

Also I can not understand what are parameters in ib constructor. Can you explain it to me? And what is reqId in calculateImpliedVolatility?


'use strict';

var util = require('util');

require('colors');

var _ = require('lodash');

var ib = new (require('..'))({
// clientId: 0,
// host: '127.0.0.1',
// port: 7496
}).on('connected', function () {
console.log('CONNECTED'.rainbow);
}).on('diconnected', function () {
console.log('DISCONNECTED'.rainbow);
}).on('received', function (tokens) {
console.info('%s %s', '<<< RECV <<<'.cyan, JSON.stringify(tokens));
}).on('sent', function (tokens) {
console.info('%s %s', '>>> SENT >>>'.yellow, JSON.stringify(tokens));
}).on('server', function (version, connectionTime) {
console.log(util.format('Server Version: %s', version).rainbow);
console.log(util.format('Server Connection Time: %s', connectionTime).rainbow);
}).on('error', function (err) {
console.error(util.format('@@@ ERROR: %s @@@', err.message).red);
}).on('result', function (event, args) {
console.log(util.format('======= %s =======', event).green);
args.forEach(function (arg, i) {
console.log('%s %s',
util.format('[%d]', i + 1).green,
JSON.stringify(arg)
);
});
});

ib.connect();

ib.calculateImpliedVolatility(12345, {
currency: 'USD',
exchange: 'SMART',
expiry: '20140118',
right: 'C',
secType: 'OPT',
strike: 40.00,
symbol: 'QQQQ'
}, 12.34, 56.78); // reqId, contract, optionPrice, underPrice

How to handle multiple clients?

Hi,
How does server handle multiple clients? Do I have to install multiple IB gateways in server? If I have thousands of clients, each client have their own account. How do I handel this case with node-ib? Is node-ib running without IB gateway?
Thanks

Why Number.MAX_VALUE vs. "null" for missing commission, margins, prices etc.

In the output of the placeOrder example I see the same value for initial margin, maintenance margin commissions and many other properties: 1.7976931348623157E308. This is the default Number.MAX_VALUE.

Is the data really not available, or does the package not have the algorithm to decode it? In many places, a better value would be "null".

Search for "1.7976931348623157" below:

[openOrder] orderId=144 contract={"conId":107113386,"symbol":"FB","secType":"STK","expiry":"","strike":0,"right":"?","multiplier":"","exchange":"SMART","currency":"USD","localSymbol":"FB","tradingClass":"NMS","comboLegsDescrip":""} order={"orderId":144,"action":"BUY","totalQuantity":1,"orderType":"LMT","lmtPrice":0.01,"auxPrice":1.7976931348623157e+308,"tif":"GTC","ocaGroup":"","account":"U327195","openClose":"C","origin":0,"orderRef":"","clientId":0,"permId":1534811360,"outsideRth":false,"hidden":false,"discretionaryAmt":0,"goodAfterTime":"","faGroup":"","faMethod":"","faPercentage":"","faProfile":"","goodTillDate":"","rule80A":"","percentOffset":1.7976931348623157e+308,"settlingFirm":"","shortSaleSlot":0,"designatedLocation":"","exemptCode":-1,"auctionStrategy":0,"startingPrice":1.7976931348623157e+308,"stockRefPrice":1.7976931348623157e+308,"delta":1.7976931348623157e+308,"stockRangeLower":1.7976931348623157e+308,"stockRangeUpper":1.7976931348623157e+308,"displaySize":null,"blockOrder":false,"sweepToFill":false,"allOrNone":false,"minQty":1.7976931348623157e+308,"ocaType":3,"eTradeOnly":false,"firmQuoteOnly":false,"nbboPriceCap":1.7976931348623157e+308,"parentId":0,"triggerMethod":0,"volatility":1.7976931348623157e+308,"volatilityType":0,"deltaNeutralOrderType":"None","deltaNeutralAuxPrice":1.7976931348623157e+308,"deltaNeutralConId":0,"deltaNeutralSettlingFirm":"","deltaNeutralClearingAccount":"","deltaNeutralClearingIntent":"","deltaNeutralOpenClose":"?","deltaNeutralShortSale":false,"deltaNeutralShortSaleSlot":0,"deltaNeutralDesignatedLocation":"","continuousUpdate":0,"referencePriceType":0,"trailStopPrice":1.7976931348623157e+308,"trailingPercent":1.7976931348623157e+308,"basisPoints":1.7976931348623157e+308,"basisPointsType":1.7976931348623157e+308,"scaleInitLevelSize":1.7976931348623157e+308,"scaleSubsLevelSize":1.7976931348623157e+308,"scalePriceIncrement":1.7976931348623157e+308,"hedgeType":"","optOutSmartRouting":false,"clearingAccount":"","clearingIntent":"IB","notHeld":false,"algoStrategy":"","whatIf":false} orderState={"status":"PendingCancel","initMargin":"1.7976931348623157E308","maintMargin":"1.7976931348623157E308","equityWithLoan":"1.7976931348623157E308","commission":1.7976931348623157e+308,"minCommission":1.7976931348623157e+308,"maxCommission":1.7976931348623157e+308,"commissionCurrency":"","warningText":""}

on('connected') only happens once even after TWS restart

Situation:

  1. Connect to the TWS API with script using ib.connect()
  2. on('connected') handler is called
  3. TWS exits, e.g. because of the daily logout or crash
  4. User restarts TWS and logs in

The on('connected') handler will not be called again.

on('disconnected') is called correctly but I called ib.connect() from it on a 10 second interval and on('connected') was never called again.

How can we detect when TWS API is available again after disconnect?

market data slow after certain amount of request

I have a issue that when client request market data, at the beginning the data response very quick, but after more than 200 ticker request, the response for market data update became very slow, this was monitored in the callback print out. Does anybody have this issue?

placeOrder not working with v9.71 API

Hi, great library first of all, I will be the first one to raise an issue.
When I call placeOrder there is no response from the server at all in the logs, doesn't even reply with correct format error.

Regards

Does not support position requests.

Hi,

Here is my run-time issue:

$ node reqPositions.js 
managedAccounts: ["XX188971"]
nextValidId: [9]
Market data farm connection is OK:usfarm
HMDS data farm connection is OK:ushmds
It does not support position requests.

Please advice,
Thomas Ku

Uncaught Exception RangeError in Socket

Once in a great while, I get these, which is impossible to catch

RangeError: Invalid array length
    at Incoming.process (node_modules/ib/lib/incoming.js:1229:41)
    at Socket._onData (node_modules/ib/lib/socket.js:48:30)
    at Socket.<anonymous> (node_modules/ib/lib/socket.js:87:18)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:188:7)
    at readableAddChunk (_stream_readable.js:176:18)
    at Socket.Readable.push (_stream_readable.js:134:10)
    at TCP.onread (net.js:543:20)

clientId single digit issue

When I try using different single digit clientIds, IB gateway refuses connection because of duplicate clientIds. So trying 0, 1, 2 at the same time gets an error because IB sees them all as 0.

However, if I start with 10, 11, 12, etc., it works ok since IB gateway sees them as 0, 1, 2 and so on.

So there is a work around but thought I would let you know about this.

thanks!!

Error creating NQ future

Try to create NQ future like 'NQ', '20160916'. You'll get the error that the contract is ambiguous and needs trading class or multiplier. I'll submit a PR for multiplier.

Always connects with Client ID 0 regardless of setting

var ib = new ( require('ib') ) ({
    clientId: 1,
    host: '127.0.0.1',
    port: 7496
})

...will still connect with Client ID 0, per IB Gateway. Changing the host and port properties does have an effect. Noticed that line 78 of lib/socket.js doesn't specify the clientId:

  this._client = net.connect({
    host: this._controller.options.host,
    port: this._controller.options.port
  }, function () {
    self._onConnect.apply(self, arguments);
    self._controller.resume();
  });

...but adding it also had no effect. Any ideas? Thanks

Process out of Memory

When I have multiple clients connect to ib server, I have fatal error "process out of memory" it is in the line 84 of controller.js. "this._ib.emit.apply(this._ib, arguments);"
Is there anyway to solve this problem? I can't find where is the memory leak.
Thanks
The error is as following:

<--- Last few GCs --->

14452083 ms: Mark-sweep 1394.5 (1457.4) -> 1398.1 (1457.4) MB, 2424.1 / 0 ms [al
location failure] [GC in old space requested].
14454442 ms: Mark-sweep 1398.1 (1457.4) -> 1398.1 (1457.4) MB, 2358.6 / 0 ms [al
location failure] [GC in old space requested].
14456756 ms: Mark-sweep 1398.1 (1457.4) -> 1392.2 (1457.4) MB, 2318.7 / 0 ms [la
st resort gc].
14459021 ms: Mark-sweep 1392.2 (1457.4) -> 1394.3 (1457.4) MB, 2259.1 / 0 ms [la
st resort gc].

<--- JS stacktrace --->

==== JS stack trace =========================================

Security context: 000001356F0B4639
1: emit [events.js:~117] [pc=000003297D6EC572](this=000003216CF86369 <an IB
with map 000002295660DB01>,type=0000024C696565E9 <String[8]: tickSize)
2: arguments adaptor frame: 4->1
4: emit [D:\nodejs\node_modules\npm_IB??????\IB_nodejs_mtrader\node_modules
\lib\controller.js:84] [pc=000003297DC81B73](this=000000DCF770EEA1 <a Controlle
r with map 0000004C4A3EEEE1)
5: argument...

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory

reqRealTimeBars not working

I was trying to get the premarket/aftermarket bar, with useRTH=false, and in following the example

var requestId=1000;
ib.reqRealTimeBars(requestId, ib.contract.stock('AAPL'), 5, 'TRADES', false);

The request happens to go through without an error or server message, and there is no response to the function

 ib.on('realtimeBar', function (reqId, time, open, high, low, close, volume, wap, count) {
      console.log(reqId, time, open, high, low, close, volume, wap, count);
}

According to the docs at
interactive brokers api reference guide

Regular Trading Hours only. Valid values include:

0 = all data available during the time span requested is returned, including time intervals when the market in question was outside of regular trading hours.
1 = only data within the regular trading hours for the product requested is returned, even if the time time span falls partially or completely outside.

However in the code, useRTH it is a boolean...
Relevant code https://github.com/pilwon/node-ib/blob/master/lib/index.js#L336

When it maybe should be integer? Could this be why it is not working (similar to reqHistoricalData)?

  assert(_.isNumber(useRTH), '"useRTH" must be an integer - ' + useRTH);

Thanks!

Contract unique security identifier missing

Currently only the symbol of the underlying asset is usable when querying contract details or when placing orders.

This symbols are not unique and may vary on different exchanges and/or currencies. For example "FB" references Facebook Inc. (ISIN: US30303M1027) when currency is set to "USD". But it also references Fromageries Bel, a French cheese marketer (ISIN: FR0000121857) if currency set to "EUR".

The Interactive Broker API provides input parameters for solving this: m_secId and m_secIdType. Unfortunately this parameters are not yet supported by the IB API client library for Node.js.

Can you change that please?
Thank you!

Doesn't work with Webpack

Basic Webpack config, getting this error:

ERROR in ../~/ib/lib/socket.js
Module not found: Error: Can't resolve 'net' in './node_modules/ib/lib'

Applying the "fix" suggested here doesn't work because ib.connect() actually needs net.

Must this be used locally?

Thought that either TWS or the API Gateway must be logged in to use IB's API. So can this package NOT be used locally?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.