IB@stoqey/ib
@stoqey/ib (Low-Level SDK)Core Architecture

Connection & Options

How to configure IBApi instance, handle connection lifecycles, and process error codes.

Initializing IBApi

The IBApi constructor takes an options object specifying connection parameters:

import { IBApi } from "@stoqey/ib";

const ib = new IBApi({
  host: "127.0.0.1", // TWS or IB Gateway IP host (default: '127.0.0.1')
  port: 7497,        // Socket port (7497 for paper TWS, 4002 for paper Gateway)
  clientId: 0,       // Unique client ID (default: 0)
});

Connection Options Reference

PropertyTypeDefaultDescription
hoststring"127.0.0.1"IP address or hostname of TWS / IB Gateway.
portnumber7497TCP socket port.
clientIdnumber0Client ID identifying this connection. TWS allows multiple client connections (0, 1, 2, ...).
timeoutnumber0Socket connection timeout in milliseconds.

Connection Lifecycle

Establishing Connection

Call .connect() to start the socket handshake. TWS will respond by emitting nextValidId or connected event callbacks:

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

const ib = new IBApi({ port: 7497 });

ib.once(EventName.nextValidId, (orderId: number) => {
  console.log(`Connected! Next valid order ID: ${orderId}`);
});

ib.connect();

Disconnecting

Call .disconnect() to cleanly close the TCP socket connection:

ib.disconnect();

Error Handling

Errors from TWS or socket transport are dispatched via the error event:

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

ib.on(EventName.error, (err: Error, code: ErrorCode, reqId: number) => {
  console.error(`Error Code: ${code} | ReqId: ${reqId} | Message: ${err.message}`);
});

TWS Info Messages

Note that TWS uses the error event for informational messages and system notifications as well as hard errors (e.g., Code 2104 = "Market data farm connection is OK"). Check the code parameter to filter errors.

On this page