IBApiNext Overview & RxJS
Next-generation reactive Interactive Brokers client built on RxJS 7 Observables and Promises.
What is IBApiNext?
IBApiNext is a modern, high-level reactive client built on top of IBApi.
While IBApi relies on manual request IDs and event callback routing via EventEmitter, IBApiNext leverages RxJS 7 to streamline data subscriptions and state management.
Two Function Patterns in IBApiNext
-
One-Shot Functions (Promises): Returns a single result asynchronously or throws an error.
- Example:
api.getCurrentTime(),api.getContractDetails(contract)
- Example:
-
Endless Stream Subscriptions (Observables): Returns an RxJS
Observabledelivering continuous real-time updates.- Example:
api.getAccountSummary(),api.getMarketData(contract)
- Example:
Do NOT convert Streaming Observables to Promises
Functions that stream data (such as getMarketData or getAccountSummary) return infinite Observables that never complete. Calling .toPromise() or firstValueFrom() on them will wait forever!
Basic Example
import { IBApiNext, Contract, SecType } from "@stoqey/ib";
// Instantiate IBApiNext
const api = new IBApiNext({ port: 7497 });
// 1. One-shot Promise method
async function printCurrentTime() {
const time = await api.getCurrentTime();
console.log("TWS Current Time:", new Date(time * 1000).toLocaleString());
}
// 2. Observable streaming method
const contract: Contract = {
symbol: "AAPL",
secType: SecType.STK,
currency: "USD",
exchange: "SMART",
};
const subscription = api.getMarketData(contract, "", false, false).subscribe({
next: (marketData) => {
console.log("Market Data Tick:", marketData);
},
error: (err) => {
console.error("Market Data Error:", err);
},
});
// Connect to TWS / Gateway
api.connect();
printCurrentTime();
// Later, to stop receiving market data:
// subscription.unsubscribe();