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

100% Statements 29/29
100% Branches 8/8
100% Functions 5/5
100% Lines 26/26

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 668x 8x 8x 8x 8x             8x   8x     8x         6x 1x   5x 1x     4x               4x   1x 1x   1x 1x   1x 1x   1x 1x     4x   4x         8x       15x      
import * as IB from "@stoqey/ib";
import {inject, service} from "@waytrade/microservice-core";
import {firstValueFrom, ReplaySubject} from "rxjs";
import {IBApiApp} from "../app";
import {IBApiLoggerProxy} from "../utils/ib-api-logger-proxy";
 
 
/**
 * IBApiNext factory service.
 */
@service()
export class IBApiFactoryService {
  @inject("IBApiApp")
  private app!: IBApiApp;
 
  /** The [[IBApiNext]] instance subject. */
  private _api = new ReplaySubject<IB.IBApiNext>(1);
 
 
  /** Start the service. */
  start(): void {
    if (!this.app.config.IB_GATEWAY_PORT) {
      throw Error("IB_GATEWAY_PORT not configured.");
    }
    if (!this.app.config.IB_GATEWAY_HOST) {
      throw Error("IB_GATEWAY_HOST not configured.");
    }
 
    const ibApi = new IB.IBApiNext({
      port: this.app.config.IB_GATEWAY_PORT,
      host: this.app.config.IB_GATEWAY_HOST,
      logger: new IBApiLoggerProxy(this.app),
      connectionWatchdogInterval: 30,
      reconnectInterval: 5000,
    });
 
    switch (this.app.config.LOG_LEVEL) {
      case "debug":
        ibApi.logLevel = IB.LogLevel.DETAIL;
        break;
      case "info":
        ibApi.logLevel = IB.LogLevel.INFO;
        break;
      case "warn":
        ibApi.logLevel = IB.LogLevel.WARN;
        break;
      case "error":
        ibApi.logLevel = IB.LogLevel.ERROR;
        break;
    }
 
    ibApi.connect(0);
 
    this._api.next(ibApi);
  }
 
  /** Stop the service. */
  stop(): void {
    this.api.then((p) => p.disconnect());
  }
 
  get api():  Promise<IB.IBApiNext> {
    return firstValueFrom(this._api);
  }
 }