All files / src/services ib-api.service.ts

97.58% Statements 242/248
91.15% Branches 103/113
95.59% Functions 65/68
97.5% Lines 234/240

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 6568x   8x             8x 8x           8x 8x       8x 8x       8x             8x     8x     8x       8x                       8x   8x       8x                 17x     17x               17x           17x     17x           17x       15x 13x 13x 13x 13x       13x     13x   19x   6x 6x   2x 1x   2x     2x   11x 2x   11x     1x 1x 1x   11x                 17x 17x         3x 3x   1x               13x 10x 10x 4x       9x 9x 6x 2x   6x   3x                     2x 2x 1x   1x 1x                       15x         3x   3x 3x 3x 3x 2x 2x 2x   3x     3x 3x     3x 3x 3x     3x       3x           2x 2x 2x 2x 1x 1x   2x 2x   1x 1x 1x 1x     1x     2x         2x 2x     2x   11x     2x           4x 4x       4x   3x 2x   3x 1x 1x     2x 2x       2x 6x         6x 2x 2x 2x         2x       2x       3x     1x     1x 1x           2x 2x 2x       1x     1x     4x 4x 4x             14x                   1x 1x 1x               5x         5x 5x 5x               5x 5x   2x   5x         5x 5x                 14x 10x 3x         1x 1x 1x           3x         1x             1x       1x   1x                     14x 14x 14x 14x     14x       3x 1x 1x 1x 1x           7x       7x         7x   7x 6x 13x         13x 3x 1x   3x     10x 10x 5x 5x                 10x 10x   2x   10x   2x     10x 5x 5x 2x             7x 7x 1x 1x 1x           7x 6x 6x 2x 2x     6x                   7x 6x 13x 3x     10x         10x 2x     8x                           15x   15x         2x 2x     2x     13x 13x 2x   13x   5x   13x   5x   13x   5x   13x   5x   13x   5x     13x 2x 2x 2x   11x     13x 10x             8x       7x 2x              
import * as IB from "@stoqey/ib";
import {IBApiNextError} from "@stoqey/ib";
import {
  DiffTools,
  inject,
  MapExt,
  service,
  subscribeUntil
} from "@waytrade/microservice-core";
import LruCache from "lru-cache";
import {
  firstValueFrom, map,
  Observable, Subject,
  Subscription,
  takeUntil
} from "rxjs";
import {IBApiApp} from "../app";
import {AccountSummary} from "../models/account-summary.model";
import {BarSize} from "../models/historic-data-request.model";
import {MarketData} from "../models/market-data.model";
import {OHLCBars} from "../models/ohlc-bar.model";
import {Position} from "../models/position.model";
import {
  ACCOUNT_SUMMARY_TAGS,
  IBApiServiceHelper as Helper
} from "../utils/ib.helper";
import {IBApiFactoryService} from "./ib-api-factory.service";
 
/**
 * Send interval on market data ticks in milliseconds.
 * TWS sends market data value changes one-by-one which can cause a lot of
 * overhead donwstream. Use this setting to reduce update frequency.
 */
const MARKET_DATA_SEND_INTERVAL_MS = 10;
 
/** Re-try intervall when an IB function has reported an error */
const IB_ERROR_RETRY_INTERVAL = 1000 * 30; // 30sec
 
/** Re-try intervall when an IB function has reported an error for tests */
const IB_ERROR_RETRY_INTERVAL_TEST = 1000; // 1sec
 
 
/** An update the positions.  */
export class PositionsUpdate {
  /** List of positions added or changed since last update. */
  changed?: Position[];
 
  /** List of positions closed since last update. */
  closed?: Position[];
}
 
/**
 * The Interactive Brokers TWS API Service
 */
@service()
export class IBApiService {
  @inject("IBApiApp")
  private app!: IBApiApp;
 
  /** The [[IBApiNext]] factory instance. */
  @inject("IBApiFactoryService")
  private factory!: IBApiFactoryService;
 
  /** The [[IBApiNext]] instance. */
  private api!: IB.IBApiNext;
 
  /** Subscription on IBApiNext connection date. */
  private connectionState$?: Subscription;
 
  /** The service shutdown signal. */
  private shutdownSignal = new Subject<void>();
 
  /** Cache of a requested contract details, with conId as key. */
  private readonly contractDetailsCache = new LruCache<
    number,
    IB.ContractDetails[]
  >({
    max: 128,
  });
 
  /** All current account summary values. */
  private readonly currentAccountSummaries = new MapExt<
    string,
    AccountSummary
  >();
 
  /** Account summary change subject. */
  private readonly accountSummariesChange = new Subject<AccountSummary[]>();
 
  /** All current positions. */
  private readonly currentPositions = new MapExt<
    string,
    Position
  >();
 
  /** Position change subject. */
  private readonly positionsChange = new Subject<PositionsUpdate>();
 
  /** Start the service. */
  async start(): Promise<void> {
    this.factory.api.then(api => {
      this.api = api;
      this.subscribeAccountSummaries();
      this.subscribeAccountPnL();
      this.subscribePositions();
 
      // exit on connection loss
 
      let connectionTries = 0;
      let connectedTimer: NodeJS.Timeout;
 
      this.connectionState$ = api.connectionState.subscribe({
        next: state => {
          switch (state) {
            case IB.ConnectionState.Connecting:
              connectionTries++;
              break;
            case IB.ConnectionState.Connected:
              if (connectedTimer) {
                clearTimeout(connectedTimer);
              }
              connectedTimer = global.setTimeout(() => {
                connectionTries = 0;
              }, 2000); // wait 2s to ensure a stable connection before resetting connectionTries
              break;
            case IB.ConnectionState.Disconnected:
              if (connectedTimer) {
                clearTimeout(connectedTimer);
              }
              if (
                connectionTries >= (this.app.config.IB_GATEWAY_RECONNECT_TRIES ?? 0)
              ) {
                this.app.error("Lost connection to IB Gateway, shutown app...");
                api.disconnect();
                this.app.stop();
              }
              break;
          }
        },
      });
    });
  }
 
  /** Stop the service. */
  stop(): void {
    this.connectionState$?.unsubscribe();
    this.shutdownSignal.next();
  }
 
  /** Search contracts where name or symbol matches the given text pattern. */
  async searchContracts(pattern: string): Promise<IB.ContractDescription[]> {
    try {
      return await this.api.searchContracts(pattern);
    } catch(e) {
      throw (<IBApiNextError>e).error;
    }
  }
 
  /** Get the contract details for contract that match the given criteria. */
  async getContractDetails(
    contract: IB.Contract,
  ): Promise<IB.ContractDetails[]> {
    if (contract.conId) {
      const cache = this.contractDetailsCache.get(contract.conId);
      if (cache) {
        return cache;
      }
    }
 
    try {
      const details = await this.api?.getContractDetails(contract);
      if (contract.conId && details.length) {
        this.contractDetailsCache.set(contract.conId, details);
      }
      return details;
    } catch(e) {
      throw (<IBApiNextError>e).error;
    }
  }
 
  /** Get historic OHLC data of a contract of a given contract ID. */
  async getHistoricData(
    conId: number,
    end: string | undefined,
    duration: string,
    barSize: BarSize,
    whatToShow: string): Promise<OHLCBars> {
    const contractDetails = (await this.getContractDetails({conId}));
    if (!contractDetails.length) {
      throw Error("Contract to found.");
    }
    try {
      return {
        bars: await this.api.getHistoricalData(
          contractDetails[0].contract, end, duration,
          <unknown>barSize as IB.BarSizeSetting, whatToShow, 1, 1)
      };
    } catch(e) {
      throw (<IBApiNextError>e).error;
    }
  }
 
  /** Get the accounts to which the logged user has access to. */
  get managedAccounts(): Promise<string[]> {
    return this.api.getManagedAccounts();
  }
 
  /** Get the account summary of the given account */
  getAccountSummary(account: string): Observable<AccountSummary> {
    return new Observable(res => {
      // initial event
      const current = this.currentAccountSummaries.get(account);
      const firstEvent: AccountSummary = {account};
      let baseCurrencySent = false;
      if (current) {
        Object.assign(firstEvent, current);
        firstEvent.baseCurrency = this.app.config.BASE_CURRENCY;
        baseCurrencySent = true;
      }
      res.next(firstEvent);
 
      // dispatch changes
      const sub$ = this.accountSummariesChange
        .pipe(map(v => v.find(v => v.account === account)))
        .subscribe({
          next: update => {
            const current: AccountSummary = {account};
            Object.assign(current, update);
            Iif (!baseCurrencySent) {
              current.baseCurrency = this.app.config.BASE_CURRENCY;
            }
            res.next(update);
          }
        });
 
      return (): void => sub$.unsubscribe();
    });
  }
 
  /** Get the account summaries of all accounts */
  get accountSummaries(): Observable<AccountSummary[]> {
    return new Observable(res => {
      const baseCurrencytSent = new Set<string>();
      const current = Array.from(this.currentAccountSummaries.values());
      current.forEach(v => {
        v.baseCurrency = this.app.config.BASE_CURRENCY;
        baseCurrencytSent.add(v.account);
      });
      res.next(current);
      const sub$ = this.accountSummariesChange.subscribe({
        next: update => {
          update.forEach(v => {
            Eif (!baseCurrencytSent.has(v.account)) {
              baseCurrencytSent.add(v.account);
              v.baseCurrency = this.app.config.BASE_CURRENCY;
            }
          });
          res.next(update);
        }
      });
      return (): void => sub$.unsubscribe();
    });
  }
 
  get positions(): Observable<PositionsUpdate> {
    return new Observable(res => {
      res.next({
        changed: Array.from(this.currentPositions.values())
      });
      const sub$ = this.positionsChange.subscribe({
        next: update => {
          res.next(update);
        }
      });
      return (): void => sub$.unsubscribe();
    });
  }
 
  /** Get market data updates for the given conId.*/
  getMarketData(conId: number): Observable<MarketData> {
    return new Observable<MarketData>(subscriber => {
      const cancel = new Subject();
 
      // lookup contract details from conId
 
      this.getContractDetails({conId})
        .then(details => {
          const contract = details.find(
            v => v.contract.conId === conId,
          )?.contract;
          if (!contract) {
            subscriber.error(new Error("conId not found"));
            return;
          }
 
          const lastSentMarketData: MarketData = {};
          let currentMarketData: MarketData = {};
 
          // donwstream send timer
 
          const sendTimer = setInterval(() => {
            const changedMarketData = DiffTools.diff(
              lastSentMarketData,
              currentMarketData,
            ).changed;
 
            if (changedMarketData) {
              Object.assign(currentMarketData, changedMarketData);
              Object.assign(lastSentMarketData, currentMarketData);
              subscriber.next(changedMarketData);
            }
          }, MARKET_DATA_SEND_INTERVAL_MS);
 
          // do not display delayed market data at all:
          this.api.setMarketDataType(IB.MarketDataType.FROZEN);
 
          // subscribe on market data
 
          const sub$ = this.api
            .getMarketData(contract, "104,105,106,165,411", false, false)
            .subscribe({
              next: update => {
                currentMarketData = Helper.marketDataTicksToModel(update.all);
              },
              error: (error: IB.IBApiNextError) => {
                this.app.error(
                  `getMarketData(${conId} / ${contract.symbol}) failed with ${error.error.message}`,
                );
                subscriber.error(new Error(error.error.message));
                clearInterval(sendTimer);
              },
            });
 
          // handle cancel signal
 
          firstValueFrom(cancel).then(() => {
            clearInterval(sendTimer);
            sub$.unsubscribe();
          });
        })
        .catch(e => {
          this.app.error(
            `getContractDetails(${conId}) failed with: ${e.message}`,
          );
          subscriber.error(e);
        });
 
      return (): void => {
        cancel.next(true);
        cancel.complete();
      };
    });
  }
 
  /** Subscribe on account summaries */
  private subscribeAccountSummaries(): void {
    subscribeUntil(
      this.shutdownSignal,
      this.api
        .getAccountSummary(
          "All",
          ACCOUNT_SUMMARY_TAGS.join(",") +
            `$LEDGER:${this.app.config.BASE_CURRENCY}`,
        ),
      {
        error: err => {
          setTimeout(() => {
            this.app.error("getAccountSummary: " + err.error.message);
            this.subscribeAccountSummaries();
          }, this.app.config.isTest ?
            IB_ERROR_RETRY_INTERVAL_TEST : IB_ERROR_RETRY_INTERVAL
          );
        },
        next: update => {
          // collect updated
 
          const updated = new Map([
            ...(update.changed?.entries() ?? []),
            ...(update.added?.entries() ?? []),
          ]);
 
          const changed = new MapExt<string, AccountSummary>();
          updated.forEach((tagValues, accountId) => {
            Helper.colllectAccountSummaryTagValues(
              accountId,
              tagValues,
              this.app.config.BASE_CURRENCY ?? "",
              changed,
            );
          });
 
          changed.forEach(changedSummary => {
            const currentSummary = this.currentAccountSummaries.getOrAdd(
              changedSummary.account,
              () => new AccountSummary({account: changedSummary.account}),
            );
            Object.assign(currentSummary, changedSummary);
          });
 
          // emit update event
 
          Eif (changed.size) {
            this.accountSummariesChange.next(Array.from(changed.values()));
          }
        },
      },
    );
  }
 
  /** Subscribe on account PnLs */
  private subscribeAccountPnL(): void {
    this.managedAccounts.then(managedAccount => {
      managedAccount?.forEach(accountId => {
        subscribeUntil(
          this.shutdownSignal,
          this.api.getPnL(accountId),
          {
            error: (err: IB.IBApiNextError) => {
              this.app.error(`getPnL(${accountId}): ${err.error.message}`);
              setTimeout(() => {
                this.subscribeAccountPnL();
              }, this.app.config.isTest ?
                IB_ERROR_RETRY_INTERVAL_TEST : IB_ERROR_RETRY_INTERVAL
              );
            },
            next: pnl => {
              if (
                pnl.dailyPnL !== undefined ||
                pnl.realizedPnL !== undefined ||
                pnl.unrealizedPnL !== undefined
              ) {
                const changedSummary: AccountSummary = {
                  account: accountId,
                  dailyPnL: pnl.dailyPnL,
                  realizedPnL: pnl.realizedPnL,
                  unrealizedPnL: pnl.unrealizedPnL,
                };
 
                const currentSummary = this.currentAccountSummaries.getOrAdd(
                  changedSummary.account,
                  () => new AccountSummary({account: changedSummary.account}),
                );
                Object.assign(currentSummary, changedSummary);
 
                this.accountSummariesChange.next([changedSummary]);
              }
            },
          },
        );
      });
    });
  }
 
  /** Subscribe on all account positions. */
  private subscribePositions(): void {
    const pnlSubscriptions = new Map<string, Subscription>();
    firstValueFrom(this.shutdownSignal).then(() => {
      pnlSubscriptions.forEach(p => p.unsubscribe());
      pnlSubscriptions.clear();
    });
 
    subscribeUntil(
      this.shutdownSignal,
      this.api.getPositions(), {
        error: (error: IB.IBApiNextError) => {
          pnlSubscriptions.forEach(p => p.unsubscribe());
          pnlSubscriptions.clear();
          this.app.error("getPositions(): " + error.error.message);
          setTimeout(() => {
            this.subscribePositions();
          }, this.app.config.isTest ?
            IB_ERROR_RETRY_INTERVAL_TEST : IB_ERROR_RETRY_INTERVAL
          );
        },
        next: update => {
          const changed = new MapExt<string, Position>();
 
          // collect updated
 
          const updated = new Map([
            ...(update.changed?.entries() ?? []),
            ...(update.added?.entries() ?? []),
          ]);
 
          const zeroSizedIds: string[] = [];
 
          updated.forEach((positions, accountId) => {
            positions.forEach(ibPosition => {
              const posId = Helper.formatPositionId(
                accountId,
                ibPosition.contract.conId,
              );
 
              if (!ibPosition.pos) {
                if (this.currentPositions.has(posId)) {
                  zeroSizedIds.push(posId);
                }
                return;
              }
 
              let newPosition = false;
              const prevPositions = this.currentPositions.getOrAdd(posId, () => {
                newPosition = true;
                return new Position({
                  id: posId,
                  avgCost: ibPosition.avgCost,
                  account: accountId,
                  conId: ibPosition.contract.conId,
                  pos: ibPosition.pos,
                });
              });
 
              const changedPos: Position = {id: posId};
              if (ibPosition.avgCost != undefined &&
                prevPositions.avgCost !== ibPosition.avgCost) {
                  changedPos.avgCost = ibPosition.avgCost;
              }
              if (ibPosition.pos != undefined &&
                prevPositions.pos !== ibPosition.pos) {
                  changedPos.pos = ibPosition.pos;
              }
 
              if (newPosition) {
                changed.set(posId, prevPositions);
              } else if (Object.keys(changedPos).length > 1) {
                changed.set(posId, changedPos);
              }
            });
          });
 
          // collect closed
 
          const removedIds = new Set(zeroSizedIds);
          update.removed?.forEach((positions, account) => {
            positions.forEach(pos => {
              const id = Helper.formatPositionId(account, pos.contract.conId);
              removedIds.add(id);
            });
          });
 
          // update
 
          if (changed.size || removedIds.size) {
            const closedPositions: Position[] = [];
            removedIds.forEach(id => {
              this.currentPositions.delete(id);
              closedPositions.push(new Position({id}));
            });
 
            this.positionsChange.next({
              changed: changed.size
                ? Array.from(changed.values())
                : undefined,
              closed: closedPositions,
            });
          }
 
          // subscribe on PnL
 
          updated.forEach((positions, accountId) => {
            positions.forEach(ibPosition => {
              if (!ibPosition.pos) {
                return;
              }
 
              const posId = Helper.formatPositionId(
                accountId,
                ibPosition.contract.conId,
              );
 
              if (pnlSubscriptions.has(posId)) {
                return;
              }
 
              const sub = this.api.getPnLSingle(
                  ibPosition.account,
                  "",
                  ibPosition.contract.conId ?? 0,
                )
                .pipe(takeUntil(this.shutdownSignal))
                .subscribe({
                  error: (error: IB.IBApiNextError) => {
                    pnlSubscriptions.delete(posId);
                    this.app.error(
                      `getPnLSingle(${ibPosition.contract.symbol}): ${error.error.message}`,
                    );
                  },
                  next: pnl => {
                    let prePos = this.currentPositions.get(posId);
 
                    if (
                      prePos &&
                      pnl.position !== undefined &&
                      !pnl.position
                    ) {
                      this.currentPositions.delete(posId);
                      this.positionsChange.next({
                        closed: [new Position({id: posId})],
                      });
                      return;
                    }
 
                    const changedPos: Position = {id: posId};
                    if (prePos?.account !== accountId) {
                      changedPos.account = accountId;
                    }
                    if (pnl.dailyPnL != undefined &&
                      prePos?.dailyPnL !== pnl.dailyPnL) {
                      changedPos.dailyPnL = pnl.dailyPnL;
                    }
                    if (pnl.marketValue != undefined &&
                      prePos?.marketValue !== pnl.marketValue) {
                      changedPos.marketValue = pnl.marketValue;
                    }
                    if (pnl.position != undefined &&
                      prePos?.pos !== pnl.position) {
                      changedPos.pos = pnl.position;
                    }
                    if (pnl.realizedPnL != undefined &&
                      prePos?.realizedPnL !== pnl.realizedPnL) {
                      changedPos.realizedPnL = pnl.realizedPnL;
                    }
                    if (pnl.unrealizedPnL != undefined &&
                      prePos?.unrealizedPnL !== pnl.unrealizedPnL) {
                      changedPos.unrealizedPnL = pnl.unrealizedPnL;
                    }
 
                    if (!prePos) {
                      prePos = {id: posId};
                      Object.assign(prePos, changedPos);
                      this.currentPositions.set(posId, prePos);
                    } else {
                      Object.assign(prePos, changedPos);
                    }
 
                    if (Object.keys(changedPos).length > 1) {
                      this.positionsChange.next({
                        changed: [changedPos],
                      });
                    }
                  },
                });
 
              pnlSubscriptions.set(posId, sub);
            });
          });
 
          removedIds.forEach(id => {
            pnlSubscriptions.get(id)?.unsubscribe();
          });
        }
      }
    );
  }
}