ibkr-client
v1.0.4
Published
IBKR (Interactive Brokers) Web API Client with OAuth support
Downloads
29
Maintainers
Readme
IBKR (Interactive Brokers) Web API Client with OAuth support
This TypeScript module is a client for IBKR modern REST Web API: Official Docs & API Reference.
It connects both via IB Gateway and directly using OAuth protocol.
It supports both REST API (via Fetch) and WebSocket (via RxJS client with exponential back-off).
It does not work with legacy TWS API, so please don't get confused.
It is highly recommended to read the official documentation and get familiar with IBKR API and connection concepts before using this module and integrating it into a trading system.
Install
npm i ibkr-client
It contains both ESM modern version and CommonJS version for NodeJS legacy.
Configuration
There are 2 options of connecting to IBKR Web API:
- Via their intermediate layer called IB Gateway (standard option).
- Directly using OAuth protocol (available only to institutional users).
IB Gateway
import { IbkrClient } from 'ibkr-client';
const client = new IbkrClient('http://url_to_ib_gateway_instance');OAuth
OAuth access allows for direct connection, but it's available only for institutional users.
At the moment only OAuth1.0a method is supported.
OAuth2.0 should be available later. Feel free to fund this package to speed the work up.
In order to use OAuth1.0a method one first needs to obtain configuration files and generate oauth1.json file using node configure script bundled with this module.
- Getting configuration files can be done on this page.
- That page contains instructions on how to manually generate Access Token and Secret.
- Please note that
opensslhas to be installed to complete this process. - After successfully completing OAuth setup process there should be 3 files and 3 strings:
- File
dhparam.pem - File
private_encryption.pem - File
private_signature.pem - String
Consumer Key - String
Access Token - String
Access Token Secret
- File
- Having all those 6 key things one can generate
oauth1.jsonconfiguration file. - Go to the module directory:
cd node_modules/ibkr-client. - Put 3 above-mentioned files into that directory.
- Run generation script:
node configure. - Use 3 above-mentioned strings when requested by the script.
- As result, file
oauth1.jsonwill be generated and ready to use by the client. - Put
oauth1.jsonin some secure location that is not available from outside as it contains secure information that can be used to perform trades on behalf of IBKR account owner.
import { IbkrClient } from 'ibkr-client';
const config = JSON.parse(fs.readFileSync('path_to_oauth1.json', 'utf8'));
const client = new IbkrClient(config);Without oauth1.json file
It's possible to pass all required parameters directly to IbkrClient during instantiation:
import { IbkrClient } from 'ibkr-client';
const config = {
accessTokenSecret: string;
accessToken: string;
consumerKey: string;
encryption: string;
signature: string;
dhPrime: string;
realm: string;
}
const client = new IbkrClient(config);Usage
Initialization
Before making REST API calls or connect to the WebSocket it's needed to initialize a session:
await client.init();This method supports 2 optional arguments, both are true by default: init(compete = true, publish = true).
Please refer to the documentation in order to clarify those parameters meaning.
In case of using OAuth1.0a, live session token will be obtained automatically by calling init().
Tickle
In order to keep the session alive it's needed to periodically call the tickle endpoint:
const res = await client.request({ path: 'tickle', method: 'POST' });
// it will return the session token that can be shown like this:
console.log('session token', res.session);
// the token may be re-generated after some time, so it's required to update it to the client:
client.session = res.session;
// IBKR API is known to be a bit slow during initialization,
// which may cause unexpected issues when API calls are made shortly after the first tickle(),
// so it's a good idea to wait for 1 second before making API requests, for example:
new Promise((r) => setTimeout(r, 1000));REST API calls
In order to make calls to IBKR REST API use universal request method:
async request(input: {
path: string;
method?: string; // GET by default
data?: object;
params?: Record<string, string | number | boolean | null | undefined>;
headers?: Record<string, string>;
})For example, request to get portfolio accounts will look like this:
const res = await client.request({ path: 'portfolio/accounts' });And stocks search will look like this:
const symbols = ['AAPL', 'AMZN'];
const res = await client.request({
path: 'trsrv/stocks',
params: { symbols: symbols.join(',') },
});WebSocket
A lot of data can be received via IBKR WebSocket, for example live order updates:
const socket = client.socket();
socket.multiplex(
() => {
return 'sor+{}';
},
() => {
return 'uor+{}';
},
(data) => {
return data.topic === 'sor';
},
);For debugging purposes one may want to watch the data being sent and received through WebSocket, it can be done with the oprional debug argument of client.socket():
const socket = client.socket(['send', 'receive']);All available values for debug string array are: open, close, send, receive, error.
socket() method returns RxWebSocketSubject that uses rxwebsocket module under the hood, which is a wrapper around standard RxJS WebSocketSubject with advanced capabilities, check it out.
