All Projects → stoqey → ib

stoqey / ib

Licence: MIT license
Interactive Brokers TWS/IB Gateway API client library for Node.js (TS)

Programming Languages

typescript
32286 projects

Projects that are alternatives of or similar to ib

ibkr
Interactive Brokers wrapper 🚩
Stars: ✭ 34 (-63.83%)
Mutual labels:  market-data, interactive-brokers, twsapi, stocks-api, forex-api
InterReact
Interactive Brokers reactive C# API.
Stars: ✭ 28 (-70.21%)
Mutual labels:  tws, interactive-brokers, ibapi
ib-historical-data
Interactive Brokers TWS API -- Historical data downloader
Stars: ✭ 40 (-57.45%)
Mutual labels:  tws, interactive-brokers, ibapi
Finance-Robinhood
Trade stocks and ETFs with free brokerage Robinhood and Perl
Stars: ✭ 42 (-55.32%)
Mutual labels:  options-trading, stocks-api
PT.MarketDataService
Market Data collector for Interactive Brokers
Stars: ✭ 16 (-82.98%)
Mutual labels:  market-data, interactive-brokers
ib dl
Historical market data downloader using Interactive Brokers TWS
Stars: ✭ 43 (-54.26%)
Mutual labels:  market-data, interactive-brokers
coinbash
💰 A bash script (CLI) for displaying crypto currencies market data in a terminal 🖥
Stars: ✭ 110 (+17.02%)
Mutual labels:  market-data, price-ticker
QuantStageApi Python
PT_QuantBaseApi python version
Stars: ✭ 13 (-86.17%)
Mutual labels:  market-data
iextrading4j-hist
IEX Trading library to parse TOPS and DEEP multicast packets
Stars: ✭ 20 (-78.72%)
Mutual labels:  market-data
Ta Rs
Technical analysis library for Rust language
Stars: ✭ 248 (+163.83%)
Mutual labels:  market-data
Tosdatabridge
A collection of resources for pulling real-time streaming data off of TDAmeritrade's ThinkOrSwim(TOS) platform; providing C, C++, Java and Python interfaces.
Stars: ✭ 229 (+143.62%)
Mutual labels:  market-data
pr-www
Portfolio Report Website - the data source for Portfolio Performance
Stars: ✭ 50 (-46.81%)
Mutual labels:  market-data
binaryapi
Binary.com & Deriv.com API for Python
Stars: ✭ 32 (-65.96%)
Mutual labels:  options-trading
intrinio-realtime-java-sdk
Intrinio Java SDK for Real-Time Stock Prices
Stars: ✭ 22 (-76.6%)
Mutual labels:  market-data
NasdaqCloudDataService-SDK-Java
Nasdaq Data Link provides a modern and efficient method of delivery for real-time exchange data and other financial information. This repository provides a Java SDK for developing applications using Nasdaq Data Link's real-time data.
Stars: ✭ 70 (-25.53%)
Mutual labels:  market-data
Coinapi Sdk
SDKs for CoinAPI
Stars: ✭ 238 (+153.19%)
Mutual labels:  market-data
IB.CSharpApiClient
Interactive Brokers - TWS API simplified client
Stars: ✭ 41 (-56.38%)
Mutual labels:  interactive-brokers
optionmatrix
Financial Derivatives Calculator with 168+ Models (Options Calculator)
Stars: ✭ 121 (+28.72%)
Mutual labels:  options-trading
IQFeed.CSharpApiClient
IQFeed.CSharpApiClient is fastest and the most well-designed C# DTN IQFeed socket API connector available
Stars: ✭ 103 (+9.57%)
Mutual labels:  market-data
dukascopy-tools
✨ Download historical price tick data for Crypto, Stocks, ETFs, CFDs, Forex via CLI and Node.js ✨
Stars: ✭ 128 (+36.17%)
Mutual labels:  market-data

Typescript API

Language grade: JavaScript

@stoqey/ib is an Interactive Brokers TWS (or IB Gateway) Typescript API client library for Node.js. It is a direct port of Interactive Brokers' Java Client Version 9.76 from May 08 2019.

Refer to the Trader Workstation API for the official documentation and the C#/Java/VB/C++/Python client.

The module makes a socket connection to TWS (or IB Gateway) using the net module and all messages are entirely processed in Typescript. It uses EventEmitter to pass the result back to user.

Installation

$ npm install @stoqey/ib

or

$ yarn add @stoqey/ib

Update from 1.1.x to 1.2.x

If you currently use version 1.1.x and want to upgrade to 1.2.x please note that there is a breaking change that might affect your code:

Versions up to 1.1.x did return Number.MAX_VALUE on values that are not available. This was to be in-sync with the official TWS API Java interfaces. Since the usage of Number.MAX_VALUE is very uncommon in JScript/TS and caused / causes lot of confusion, all versions starting from 1.2.1 will return undefined instead.

If you have checked for Number.MAX_VALUE up to now, you can drop this check. If you have not checked for undefined yet, you should add it.

Example:

ib.on(EventName.pnlSingle, (
      reqId: number,
      pos: number,
      dailyPnL: number,
      unrealizedPnL: number,
      realizedPnL: number,
      value: number
    ) => {
      ...
    }
  );

now is (look at unrealizedPnL and realizedPnL)

ib.on(EventName.pnlSingle, (
      reqId: number,
      pos: number,
      dailyPnL: number,
      unrealizedPnL: number | undefined,
      realizedPnL: number | undefined,
      value: number
    ) => {
      ...
    }
  );

API Documenation

See API documentation here.

IBApi vs IBApiNext

There are two APIs on this package, IBApi and IBApiNext.

IBApi replicates the official TWS API as close as possible, making it easy to migrate or port existing code. It implements all functions and provides same event callbacks as the official TWS API does.

IBApiNext is a preview of a new API that is currently in development. The goal of IBApiNext is it, to provide same functionality as IBApi, but focus on usability rather than replicating the official interface. It is not based on a request/event design anymore, but it does use RxJS instead. IBApiNext still is in preview stage. Not all functions are available yet, and we cannot guarantee stable interfaces (although are we confident that public signatures of already existing functions won't change anymore).

IB socket ports

Platform Port
IB Gateway live account  4001
IB Gateway paper account  4002
TWS Live Account 7496
TWS papertrading account 7497 

IBApi Examples

/* Example: Print all portfolio positions to console. */

import { IBApi, EventName, ErrorCode, Contract } from "@stoqey/ib";

// create IBApi object

const ib = new IBApi({
  // clientId: 0,
  // host: '127.0.0.1',
  port: 7497,
});

// register event handler

let positionsCount = 0;

ib.on(EventName.error, (err: Error, code: ErrorCode, reqId: number) => {
  console.error(`${err.message} - code: ${code} - reqId: ${reqId}`);
})
  .on(
    EventName.position,
    (account: string, contract: Contract, pos: number, avgCost?: number) => {
      console.log(`${account}: ${pos} x ${contract.symbol} @ ${avgCost}`);
      positionsCount++;
    }
  )
  .once(EventName.positionEnd, () => {
    console.log(`Total: ${positionsCount} positions.`);
    ib.disconnect();
  });

// call API functions

ib.connect();
ib.reqPositions();

Sending first order

ib.once(EventName.nextValidId, (orderId: number) => {
  const contract: Contract = {
    symbol: "AMZN",
    exchange: "SMART",
    currency: "USD",
    secType: SecType.STK,
  };

  const order: Order = {
    orderType: OrderType.LMT,
    action: OrderAction.BUY,
    lmtPrice: 1,
    orderId,
    totalQuantity: 1,
    account: "YOUR_ACCOUNT_ID",
  };

  ib.placeOrder(orderId, contract, order);
});

ib.connect();
ib.reqIds();

IBApiNext and RxJS

While IBApi uses a request function / event callback design where subscriptions are managed by the user, IBApiNext does use RxJS 7 to manage subscriptions.
In general, there are two types of functions on IBApiNext:

  • One-shot functions, returning a Promise, such as IBApiNext.getCurrentTime or IBApiNext.getContractDetails. Such functions will send a request to TWS and return the result (or error) on the Promise.

  • Endless stream subscriptions, returning an Observable, such as IBApiNext.getAccountSummary or IBApiNext.getMarketData. Such functions will deliver an endless stream of update events. The complete callback will NEVER be invoked (do not try to convert to a Promise - it will never resolve!)

IB-Shell / IBApiNext Examples

The src/tools folder contains a collection of command line tools to run IBApiNext from command line. Have look on it if you search for IBApiNext sample code.

Example:

node ./dist/tools/account-summary.js -group=All -tags="NetLiquidation,MaintMarginReq" -watch -inc -port=4002
{
  "all": [
    [
      "DU******",
      [
        [
          "MaintMarginReq",
          [
            [
              "EUR",
              {
                "value": "37688.07",
                "ingressTm": 1616849611611
              }
            ]
          ]
        ]
      ]
    ]
  ],
  "added": [
    [
...

Testing

Locally

! WARNING ! - Make sure to test on papertrading account as tests could contain actions that result in selling and buying financial instruments.

The easiest way to start testing and playing around with the code is to run included IB Gateway docker container. To set it up use following steps.

Copy sample.env to file .env

  1. run yarn to install dependencies
  2. cp sample.env .env
  3. fill in the account info
  4. you might need to change the value of IB_PORT from 4002 to 4004 if using IB Gateway from docker-compose (Step 6)
  5. run command yarn build to compile TypeScript code
  6. run command docker-compose up (use flag -d to run de-attached mode in background). Now the docker instance of IB Gateway should be running.
  7. to take the container down just run docker-compose down

Once docker is up and running with correct credentials it should be ready to accept connections.

Running jest test

Tests can be run from CLI with jest tool. Either a single one or multiple tests at once.

Running single/multiple tests

jest src/test/unit/api/api.test.ts

To run multiple, just use path instead of specific file.

To run all tests run the following command.

yarn test

CI

Will be added later once it's stable

Deprecation process

Public interfaces, that are planned to be removed, will be marked with a @deprecated.
The @deprecated tag will contain a description or link on how migrate to new API (example: IBApiCreationOptions.clientId).
VSCode will explicitly mark deprecated functions and attributes, so you cannot miss it.

If you write new code, don't use deprecated functions.
If you already use deprecated functions on existing code, migrate to new function on your next code-clean up session. There is no need for immediate change, the deprecated function will continue to work for a least a half more year, but at some point it will be removed.

How to contribute

IB does regularly release new API versions, so this library will need permanent maintenance in order to stay up-to-date with latest TWS features.
Also, there is not much testing code yet. Ideally there should be at least one test-case for each public function.
In addition to that, a little demo / example app would be nice, to demonstrate API usage (something like a little live-portoflio-viewer app for node.js console?).
Any kind of bugfixes are welcome as well.

If you want to contribute, read the Developer Guide and start coding.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].