### Local Testing Setup with IB Gateway Docker Source: https://github.com/stoqey/ib/blob/master/README.md This section provides step-by-step instructions for setting up a local testing environment using an included IB Gateway Docker container. It covers copying environment files, installing dependencies, building TypeScript code, and managing the Docker container for testing Interactive Brokers API integrations. Users are warned to use a paper trading account. ```APIDOC ! 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. ``` -------------------------------- ### Install @stoqey/ib Node.js client library Source: https://github.com/stoqey/ib/blob/master/README.md Instructions to install the @stoqey/ib client library for Interactive Brokers TWS API using npm or yarn package managers. ```Shell npm install @stoqey/ib ``` ```Shell yarn add @stoqey/ib ``` -------------------------------- ### IBApi: Place a Limit Stock Order Source: https://github.com/stoqey/ib/blob/master/README.md This JavaScript example demonstrates how to place a limit order for a stock using the IBApi. It waits for a valid order ID, defines a contract for AMZN, sets up a BUY limit order, and then places it. Remember to replace 'YOUR_ACCOUNT_ID' with your actual account. ```javascript 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(); ``` -------------------------------- ### IB-Shell: Get Account Summary via CLI Source: https://github.com/stoqey/ib/blob/master/README.md This shell command demonstrates how to use the `account-summary.js` tool from the `src/tools` folder to retrieve account summary data. It specifies the account group, desired tags (NetLiquidation, MaintMarginReq), enables watch mode, includes ingress time, and sets the port. The output shows a JSON structure of the retrieved account data. ```shell 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": [ [ ... ``` -------------------------------- ### Using toMatchSchema Custom Jest Matcher Source: https://github.com/stoqey/ib/blob/master/src/tests/README.md This example demonstrates how to use the `toMatchSchema` custom matcher in a test file. It asserts that the `data` variable conforms to the provided object schema, leveraging the extended Jest `expect` functionality. ```typescript expect(data).toMatchSchema({ type: "object" }) ``` -------------------------------- ### Handle undefined values in @stoqey/ib event callbacks (v1.2.x update) Source: https://github.com/stoqey/ib/blob/master/README.md Demonstrates the breaking change introduced in @stoqey/ib versions 1.2.x, where Number.MAX_VALUE is replaced by undefined for unavailable values in event callbacks like pnlSingle. This example shows the type signature change for unrealizedPnL and realizedPnL parameters. ```TypeScript ib.on(EventName.pnlSingle, ( reqId: number, pos: number, dailyPnL: number, unrealizedPnL: number, realizedPnL: number, value: number ) => { ... } ); ``` ```TypeScript ib.on(EventName.pnlSingle, ( reqId: number, pos: number, dailyPnL: number, unrealizedPnL: number | undefined, realizedPnL: number | undefined, value: number ) => { ... } ); ``` -------------------------------- ### Run Jest Unit Tests Source: https://github.com/stoqey/ib/blob/master/README.md This section outlines how to execute unit tests using the Jest framework. It provides commands for running single test files, multiple tests by path, or all tests within the project. The `yarn test` command is provided as a convenient way to run all tests. ```shell jest src/test/unit/api/api.test.ts yarn test ``` -------------------------------- ### Running Jest Tests Source: https://github.com/stoqey/ib/blob/master/src/tests/README.md This command executes the test suite configured in `jest.config.js`, which uses `ts-jest` for TypeScript support and sets the default environment to Node. It runs both unit and integration tests. ```shell yarn test ``` -------------------------------- ### IBApi: Print All Portfolio Positions Source: https://github.com/stoqey/ib/blob/master/README.md This JavaScript snippet demonstrates how to connect to the Interactive Brokers TWS/Gateway, request all portfolio positions, and print them to the console. It registers event handlers for errors, position updates, and the end of the position stream, ensuring proper disconnection. ```javascript /* 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(); ``` -------------------------------- ### Interactive Brokers TWS/IB Gateway Socket Ports Source: https://github.com/stoqey/ib/blob/master/README.md Reference table listing the default socket port numbers for connecting to Interactive Brokers TWS (Trader Workstation) and IB Gateway for both live and paper trading accounts. ```APIDOC IB Gateway live account | 4001 IB Gateway paper account | 4002 TWS Live Account | 7496 TWS papertrading account | 7497 ``` -------------------------------- ### IBApiNext: RxJS Design Principles Source: https://github.com/stoqey/ib/blob/master/README.md This section explains the fundamental design differences between IBApi and IBApiNext. IBApiNext leverages RxJS 7, offering two primary function types: one-shot functions returning Promises for single results (e.g., `getCurrentTime`), and endless stream subscriptions returning Observables for continuous updates (e.g., `getAccountSummary`). It highlights that Observables will never complete, making Promise conversion unsuitable for streams. ```APIDOC 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!) ``` -------------------------------- ### API Deprecation Policy Source: https://github.com/stoqey/ib/blob/master/README.md This section details the deprecation process for public interfaces. Deprecated functions will be marked with `@deprecated` tags, including migration instructions. Users are advised to avoid new code using deprecated functions and to migrate existing code during cleanup sessions, noting that deprecated functions will continue to work for at least six months before removal. ```APIDOC 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. ``` -------------------------------- ### Extending Jest Expect Interface for toMatchSchema Source: https://github.com/stoqey/ib/blob/master/src/tests/README.md This TypeScript declaration extends the Jest `Expect` interface, making the `toMatchSchema` matcher recognized by TypeScript. It specifies the expected signature when used with `expect`, omitting the initial data parameter. ```typescript toMatchSchema(schema: any) ``` -------------------------------- ### Defining Custom Jest Matcher in matchers.ts Source: https://github.com/stoqey/ib/blob/master/src/tests/README.md This signature defines the `toMatchSchema` custom matcher within `matchers.ts`. It takes the data received from `expect` and a schema object as parameters, allowing for schema validation in tests. ```typescript toMatchSchema(data: any, schema: any) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.