{"id":13876199,"url":"https://github.com/stoqey/ib","last_synced_at":"2025-05-15T11:07:50.320Z","repository":{"id":37092163,"uuid":"264361665","full_name":"stoqey/ib","owner":"stoqey","description":"Interactive Brokers TWS/IB Gateway API client library for Node.js (TS)","archived":false,"fork":false,"pushed_at":"2025-03-23T21:09:56.000Z","size":2238,"stargazers_count":244,"open_issues_count":1,"forks_count":50,"subscribers_count":17,"default_branch":"master","last_synced_at":"2025-04-15T00:53:14.854Z","etag":null,"topics":["forex-api","ib-gateway","ibapi","interactive-brokers","market-data","options-trading","price-ticker","stocks-api","tws","twsapi","typescript"],"latest_commit_sha":null,"homepage":"https://stoqey.github.io/ib-doc/","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/stoqey.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"github":"stoqey","patreon":null,"open_collective":null,"ko_fi":null,"tidelift":null,"community_bridge":null,"liberapay":null,"issuehunt":null,"otechie":null,"custom":null}},"created_at":"2020-05-16T04:52:26.000Z","updated_at":"2025-04-13T05:54:38.000Z","dependencies_parsed_at":"2023-11-29T18:30:19.041Z","dependency_job_id":"ce771d71-b2d0-481d-a2d9-4f0cd708b995","html_url":"https://github.com/stoqey/ib","commit_stats":{"total_commits":363,"total_committers":23,"mean_commits":"15.782608695652174","dds":0.6831955922865014,"last_synced_commit":"b16b9596401a2ae728a64f3b36d8665c6854ca8e"},"previous_names":[],"tags_count":159,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/stoqey%2Fib","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/stoqey%2Fib/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/stoqey%2Fib/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/stoqey%2Fib/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/stoqey","download_url":"https://codeload.github.com/stoqey/ib/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254328384,"owners_count":22052632,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["forex-api","ib-gateway","ibapi","interactive-brokers","market-data","options-trading","price-ticker","stocks-api","tws","twsapi","typescript"],"created_at":"2024-08-06T06:01:08.325Z","updated_at":"2025-05-15T11:07:50.299Z","avatar_url":"https://github.com/stoqey.png","language":"TypeScript","funding_links":["https://github.com/sponsors/stoqey"],"categories":["TypeScript","typescript"],"sub_categories":[],"readme":"\u003cdiv align=\"center\"\u003e\n  \u003cimg src=\"https://www.interactivebrokers.com/images/web/logos/ib-logo-text-black.svg\"\u003e\u003c/img\u003e\n  \u003cp align=\"center\"\u003e\n    \u003ch1 align=\"center\"\u003eTypescript API\u003c/h1\u003e\n  \u003c/p\u003e\n  \u003cdiv style=\"display: flex;justify-content:center;\"\u003e\n    \u003ca href=\"https://discord.gg/T4VjBrqGtK\" aria-label=\"Join Stoqey #welcome\"\u003e\u003cimg src=\"https://img.shields.io/badge/discord-join%20chat-blue.svg\" alt=\"Join Stoqey #welcome\"\u003e\u003c/a\u003e\n    \u003cimg src=\"https://img.shields.io/github/package-json/v/stoqey/ib\"\u003e\u003c/img\u003e\n    \u003cimg src=\"https://circleci.com/gh/stoqey/ib.svg?style=svg\"\u003e\u003c/img\u003e\n    \u003cimg src=\"https://img.shields.io/badge/License-MIT-blue.svg\"/\u003e \n    \u003cimg src=\"https://img.shields.io/npm/dt/@stoqey/ib.svg\"\u003e\u003c/img\u003e\n\n  \u003c/div\u003e\n\u003c/div\u003e\n\n`@stoqey/ib` is an [Interactive Brokers](http://interactivebrokers.com/) TWS (or IB Gateway) Typescript API client library for [Node.js](http://nodejs.org/). It is a port of Interactive Brokers' Java Client Version 10.32.01 (\"latest\" relased on Oct 9, 2024).\n\nRefer to [IBKRCampus](https://ibkrcampus.com/campus/ibkr-api-page/twsapi-doc/) for the official documentation and the C#/Java/VB/C++/Python client.\n\nThe module makes a socket connection to TWS (or IB Gateway) using the [net](http://nodejs.org/api/net.html) module and all messages are entirely processed in Typescript. It uses [EventEmitter](http://nodejs.org/api/events.html) to pass the result back to user.\n\n## Simpler Alternative\n\nIf you're looking for a more straightforward implementation with ready-to-use examples, check out [@stoqey/ibkr](https://github.com/stoqey/ibkr). This wrapper library provides:\n\n- 🚀 Simplified API interface\n- 📝 Full working examples for common operations\n- 🔄 Built-in connection management\n- 📊 Easy market data handling\n- 💼 Streamlined portfolio management\n- 🤖 Trading automation helpers\n\nThe wrapper is built on top of this library but offers a more developer-friendly experience for common use cases.\n\n## Installation\n\n    $ npm install @stoqey/ib\n\nor\n\n    $ yarn add @stoqey/ib\n\n## Update from 1.1.x to 1.2.x\n\nIf 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:\n\nVersions 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.\n\nIf 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.\n\nExample:\n\n```js\nib.on(EventName.pnlSingle, (\n      reqId: number,\n      pos: number,\n      dailyPnL: number,\n      unrealizedPnL: number,\n      realizedPnL: number,\n      value: number\n    ) =\u003e {\n      ...\n    }\n  );\n```\n\nnow is (look at `unrealizedPnL` and `realizedPnL`)\n\n```js\nib.on(EventName.pnlSingle, (\n      reqId: number,\n      pos: number,\n      dailyPnL: number,\n      unrealizedPnL: number | undefined,\n      realizedPnL: number | undefined,\n      value: number\n    ) =\u003e {\n      ...\n    }\n  );\n```\n\n## API Documentation\n\n\u003cb\u003e[See API documentation here.](https://stoqey.github.io/ib-doc/)\u003c/b\u003e\n\n## IBApi vs IBApiNext\n\nThere are two APIs on this package, IBApi and IBApiNext.\n\nIBApi replicates the official TWS API as close as possible, making it easy to migrate or port existing code.\nIt implements all functions and provides same event callbacks as the official TWS API does.\n\nIBApiNext is a **preview** of a new API that is currently in development.\nThe goal of IBApiNext is it, to provide same functionality as IBApi, but focus on usability rather than replicating the official interface.\nIt is not based on a request/event design anymore, but it does use RxJS instead.\nIBApiNext 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).\n\n## IB socket ports\n\n| Platform                 | Port  |\n| ------------------------ | ----- |\n| IB Gateway live account  |  4001 |\n| IB Gateway paper account |  4002 |\n| TWS Live Account         | 7496  |\n| TWS papertrading account | 7497  |\n\n## IBApi Examples\n\n```js\n/* Example: Print all portfolio positions to console. */\n\nimport { IBApi, EventName, ErrorCode, Contract } from \"@stoqey/ib\";\n\n// create IBApi object\n\nconst ib = new IBApi({\n  // clientId: 0,\n  // host: '127.0.0.1',\n  port: 7497,\n});\n\n// register event handler\n\nlet positionsCount = 0;\n\nib.on(EventName.error, (err: Error, code: ErrorCode, reqId: number) =\u003e {\n  console.error(`${err.message} - code: ${code} - reqId: ${reqId}`);\n})\n  .on(\n    EventName.position,\n    (account: string, contract: Contract, pos: number, avgCost?: number) =\u003e {\n      console.log(`${account}: ${pos} x ${contract.symbol} @ ${avgCost}`);\n      positionsCount++;\n    },\n  )\n  .once(EventName.positionEnd, () =\u003e {\n    console.log(`Total: ${positionsCount} positions.`);\n    ib.disconnect();\n  });\n\n// call API functions\n\nib.connect();\nib.reqPositions();\n```\n\n### Sending first order\n\n```js\nib.once(EventName.nextValidId, (orderId: number) =\u003e {\n  const contract: Contract = {\n    symbol: \"AMZN\",\n    exchange: \"SMART\",\n    currency: \"USD\",\n    secType: SecType.STK,\n  };\n\n  const order: Order = {\n    orderType: OrderType.LMT,\n    action: OrderAction.BUY,\n    lmtPrice: 1,\n    orderId,\n    totalQuantity: 1,\n    account: \"YOUR_ACCOUNT_ID\",\n  };\n\n  ib.placeOrder(orderId, contract, order);\n});\n\nib.connect();\nib.reqIds();\n```\n\n## IBApiNext and RxJS\n\nWhile IBApi uses a request function / event callback design where subscriptions are managed by the user, IBApiNext does use RxJS 7 to manage subscriptions.\\\nIn general, there are two types of functions on IBApiNext:\n\n- 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.\n\n- Endless stream subscriptions, returning an Observable, such as `IBApiNext.getAccountSummary` or `IBApiNext.getMarketData`.\n  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!)\n\n## IB-Shell / IBApiNext Examples\n\nThe src/tools folder contains a collection of command line tools to run IBApiNext from command line.\nHave look on it if you search for IBApiNext sample code.\n\nExample:\n\n```\nnode ./dist/tools/account-summary.js -group=All -tags=\"NetLiquidation,MaintMarginReq\" -watch -inc -port=4002\n{\n  \"all\": [\n    [\n      \"DU******\",\n      [\n        [\n          \"MaintMarginReq\",\n          [\n            [\n              \"EUR\",\n              {\n                \"value\": \"37688.07\",\n                \"ingressTm\": 1616849611611\n              }\n            ]\n          ]\n        ]\n      ]\n    ]\n  ],\n  \"added\": [\n    [\n...\n```\n\n## Testing\n\n### Locally\n\n! WARNING ! - Make sure to test on papertrading account as tests could contain actions that result in selling and buying financial instruments.\n\nThe 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.\n\nCopy `sample.env` to file `.env`\n\n1. run `yarn` to install dependencies\n2. `cp sample.env .env`\n3. fill in the account info\n4. you might need to change the value of `IB_PORT` from `4002` to `4004` if using IB Gateway from `docker-compose` (Step 6)\n5. run command `yarn build` to compile TypeScript code\n6. 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.\n7. to take the container down just run `docker-compose down`\n\nOnce docker is up and running with correct credentials it should be ready to accept connections.\n\n### Running jest test\n\nTests can be run from CLI with `jest` tool. Either a single one or multiple tests at once.\n\nRunning single/multiple tests\n\n`jest src/test/unit/api/api.test.ts`\n\nTo run multiple, just use path instead of specific file.\n\nTo run all tests run the following command.\n\n`yarn test`\n\n### CI\n\nWill be added later once it's stable\n\n## Deprecation process\n\nPublic interfaces, that are planned to be removed, will be marked with a @deprecated. \u003cbr/\u003e\nThe @deprecated tag will contain a description or link on how migrate to new API (example: IBApiCreationOptions.clientId).\u003cbr/\u003e\nVSCode will explicitly mark deprecated functions and attributes, so you cannot miss it.\u003cbr/\u003e\n\nIf you write new code, don't use deprecated functions.\u003cbr/\u003e\nIf 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\ncontinue to work for a least a half more year, but at some point it will be removed.\u003cbr/\u003e\n\n## How to contribute\n\nIB does regularly release new API versions, so this library will need permanent maintenance in order to stay up-to-date with latest TWS features.\u003cbr/\u003e\nAlso, there is not much testing code yet. Ideally there should be at least one test-case for each public function.\u003cbr/\u003e\nIn 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?).\u003cbr/\u003e\nAny kind of bugfixes are welcome as well.\n\nIf you want to contribute, read the [Developer Guide](https://github.com/stoqey/ib/wiki/Developer-Guide) and start coding.\n\n## Community\n\nJoin our Discord community to get help, share ideas, and connect with other developers:\n\n[![Join our Discord server](https://img.shields.io/badge/discord-join%20chat-blue.svg)](https://discord.gg/T4VjBrqGtK)\n\n- Get help with implementation\n- Share your projects\n- Connect with other developers\n- Stay updated on new releases\n- Contribute to discussions\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fstoqey%2Fib","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fstoqey%2Fib","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fstoqey%2Fib/lists"}