Skip to content

Commit

Permalink
Better consistency of tools code and args
Browse files Browse the repository at this point in the history
  • Loading branch information
rylorin committed Sep 14, 2023
1 parent 508a085 commit a994d3e
Show file tree
Hide file tree
Showing 32 changed files with 257 additions and 282 deletions.
11 changes: 8 additions & 3 deletions src/core/api-next/subscription.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ import { IBApiNext, IBApiNextError, ItemListUpdate } from "../../api-next";
import { ConnectionState } from "../../api-next/common/connection-state";
import { IBApiNextItemListUpdate } from "./item-list-update";

export type IBApiNextItemListUpdateMinimal<T> = Omit<
IBApiNextItemListUpdate<T>,
"added" | "changed" | "removed"
>;

/**
* @internal
*
Expand Down Expand Up @@ -43,7 +48,7 @@ export class IBApiNextSubscription<T> {
private subject = new ReplaySubject<IBApiNextItemListUpdate<T>>(1);

/** The last 'all' value as send to subscribers. */
private _lastValue?: IBApiNextItemListUpdate<T>;
private _lastValue?: IBApiNextItemListUpdateMinimal<T>;

/** The [[Subscription]] on the connection state. */
private connectionState$?: Subscription;
Expand All @@ -57,12 +62,12 @@ export class IBApiNextSubscription<T> {
}

/** Get the last value as previouly saved or send to subscribers. */
get lastValue(): IBApiNextItemListUpdate<T> | undefined {
get lastValue(): IBApiNextItemListUpdateMinimal<T> | undefined {
return this._lastValue;
}

/** Set the last value without publishing it to subscribers. For internal use only. */
set lastValue(value: IBApiNextItemListUpdate<T>) {
set lastValue(value: IBApiNextItemListUpdateMinimal<T>) {
this._lastValue = { all: value.all, allset: value.allset };
}

Expand Down
9 changes: 4 additions & 5 deletions src/tools/account-summary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import path from "path";
import { Subscription } from "rxjs";

import { IBApiNextError } from "../api-next";
import logger from "../common/logger";
import { IBApiNextApp } from "./common/ib-api-next-app";

/////////////////////////////////////////////////////////////////////////////////
Expand Down Expand Up @@ -37,7 +36,7 @@ const OPTION_ARGUMENTS: [string, string][] = [
[
"watch",
"Watch for changes. If specified, the app will keep running and print account summary updates to console as received from TWS. " +
"If not specified, the app will print a one-time snapshot and than exit.",
"If not specified, the app will print a one-time snapshot and than exit.",
],
];
const EXAMPLE_TEXT =
Expand All @@ -60,13 +59,13 @@ class PrintAccountSummaryApp extends IBApiNextApp {
*/
start(): void {
const scriptName = path.basename(__filename);
logger.debug(`Starting ${scriptName} script`);
this.info(`Starting ${scriptName} script`);
this.connect();

this.connect(this.cmdLineArgs.watch ? 10000 : 0);
this.subscription$ = this.api
.getAccountSummary(
(this.cmdLineArgs.group as string) ?? DEFAULT_GROUP,
(this.cmdLineArgs.tags as string) ?? DEFAULT_TAGS
(this.cmdLineArgs.tags as string) ?? DEFAULT_TAGS,
)
.subscribe({
next: (summaries) => {
Expand Down
12 changes: 4 additions & 8 deletions src/tools/commission-reports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import path from "path";

import { ExecutionFilter } from "..";
import logger from "../common/logger";
import { IBApiNextApp } from "./common/ib-api-next-app";

/////////////////////////////////////////////////////////////////////////////////
Expand All @@ -13,9 +12,7 @@ import { IBApiNextApp } from "./common/ib-api-next-app";

const DESCRIPTION_TEXT = "Get commission report.";
const USAGE_TEXT = "Usage: commission-reports.js <options>";
const OPTION_ARGUMENTS: [string, string][] = [
["clientId=<number>", "Client id of current ib connection. Default is 0"],
];
const OPTION_ARGUMENTS: [string, string][] = [];
const EXAMPLE_TEXT = "commission-reports.js -clientId=0";

//////////////////////////////////////////////////////////////////////////////
Expand All @@ -31,9 +28,8 @@ class CommissionReportApp extends IBApiNextApp {
*/
start(): void {
const scriptName = path.basename(__filename);
logger.debug(`Starting ${scriptName} script`);

this.connect(this.cmdLineArgs.watch ? 10000 : 0);
this.info(`Starting ${scriptName} script`);
this.connect();

const executionFilter: ExecutionFilter = {
clientId: "0",
Expand All @@ -45,7 +41,7 @@ class CommissionReportApp extends IBApiNextApp {
},
(error) => {
this.printObject(error);
}
},
);
}

Expand Down
94 changes: 64 additions & 30 deletions src/tools/common/ib-api-next-app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ export class IBApiNextApp {
["right=<P|C>", " The option type. Valid values are P, PUT, C, CALL."],
];

protected logLevel: LogLevel;

constructor(
appDescription: string,
usageDescription: string,
Expand All @@ -65,6 +67,29 @@ export class IBApiNextApp {
[...this.COMMON_OPTION_ARGUMENTS, ...optionArgumentDescriptions],
usageExample,
);
if (this.cmdLineArgs.log) {
switch (this.cmdLineArgs.log) {
case "error":
this.logLevel = LogLevel.ERROR;
break;
case "warn":
this.logLevel = LogLevel.WARN;
break;
case "info":
this.logLevel = LogLevel.INFO;
break;
case "debug":
this.logLevel = LogLevel.DETAIL;
break;
default:
this.error(
`Unknown value '${this.cmdLineArgs.log}' on -log argument.`,
);
break;
}
} else {
this.logLevel = LogLevel.ERROR;
}
}

/** Common command line options of all [[IBApiNext]] apps. */
Expand All @@ -76,10 +101,14 @@ export class IBApiNextApp {
"IP or hostname of the TWS or IB Gateway. Default is 127.0.0.1.",
],
["port=<number>", "Post number of the TWS or IB Gateway. Default is 4002."],
[
"clientId=<number>",
"Client id of current ib connection. Default is random",
],
[
"watch",
"Watch for changes. If specified, the app will keep running and print positions updates to console as received from TWS. " +
"If not specified, the app will print a one-time snapshot and than exit.",
"Watch for changes. If specified, the app will keep running and print updates as received from TWS. " +
"If not specified, the app will print a one-time snapshot and then exit.",
],
];

Expand All @@ -98,44 +127,28 @@ export class IBApiNextApp {

const port = (this.cmdLineArgs.port as number) ?? configuration.ib_port;
const host = (this.cmdLineArgs.host as string) ?? configuration.ib_host;
if (reconnectInterval === undefined && this.cmdLineArgs.watch)
reconnectInterval = 10000;
if (clientId === undefined && this.cmdLineArgs.clientId)
clientId = +this.cmdLineArgs.clientId;

logger.debug(`Logging into server: ${host}:${port}`);
this.info(`Logging into server: ${host}:${port}`);
if (!this.api) {
this.api = new IBApiNext({
reconnectInterval,
host,
port,
logger,
});
if (this.cmdLineArgs.log) {
switch (this.cmdLineArgs.log) {
case "error":
this.api.logLevel = LogLevel.ERROR;
break;
case "warn":
this.api.logLevel = LogLevel.WARN;
break;
case "info":
this.api.logLevel = LogLevel.INFO;
break;
case "debug":
this.api.logLevel = LogLevel.DETAIL;
break;
default:
this.error(
`Unknown value '${this.cmdLineArgs.log}' on -log argument.`,
);
break;
}
}
this.api.logLevel = this.logLevel;
}

// log generic errors (reqId = -1) and exit with failure code

if (!this.error$) {
this.error$ = this.api.errorSubject.subscribe((error) => {
if (error.reqId === -1) {
logger.warn(error.error.message, `(Error #${error.code})`);
this.warn(`${error.error.message} (Error #${error.code})`);
} else {
this.error(
`${error.error.message} (Error #${error.code}) ${
Expand All @@ -149,8 +162,7 @@ export class IBApiNextApp {
try {
this.api.connect(clientId);
} catch (error) {
logger.error("Connection error", error.message);
logger.debug(`IB host: ${host} - IB port: ${port}`);
this.error(error.message);
}
}

Expand All @@ -169,7 +181,7 @@ export class IBApiNextApp {
}

/**
* Print and error to console and exit the app with error code, unless -watch argument is present.
* Print an error message and exit the app with error code, unless -watch argument is present.
*/
error(text: string): void {
logger.error(text);
Expand All @@ -178,6 +190,27 @@ export class IBApiNextApp {
}
}

/**
* Print a warning message
*/
warn(text: string): void {
if (this.logLevel >= LogLevel.WARN) logger.warn(text);
}

/**
* Print an wainformation message
*/
info(text: string): void {
if (this.logLevel >= LogLevel.INFO) logger.info(text);
}

/**
* Print an wainformation message
*/
debug(text: string): void {
if (this.logLevel >= LogLevel.DETAIL) logger.debug(text);
}

/**
* Exit the app.
*/
Expand All @@ -199,7 +232,7 @@ export class IBApiNextApp {
const pair = arg.split("=");
const name = pair[0].substr(1);
if (!optionArguments.find((v) => v[0].split("=")[0] == name)) {
console.error("ERROR: Unknown argument -" + pair[0]);
console.error("ERROR: Unknown argument " + pair[0]);
this.exit(1);
}
this.cmdLineArgs[name] = pair.length > 1 ? pair[1] ?? "1" : "1";
Expand Down Expand Up @@ -227,7 +260,8 @@ export class IBApiNextApp {
return result + "Example: " + example;
}

getContractParameter(): Contract {
/** get contract from command line args */
getContractArg(): Contract {
return {
conId: (this.cmdLineArgs.conid as number) ?? undefined,
secType: this.cmdLineArgs.sectype as SecType,
Expand Down
5 changes: 2 additions & 3 deletions src/tools/contract-details.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
import path from "path";

import { IBApiNextError } from "../api-next";
import logger from "../common/logger";
import { IBApiNextApp } from "./common/ib-api-next-app";

/////////////////////////////////////////////////////////////////////////////////
Expand Down Expand Up @@ -35,11 +34,11 @@ class PrintContractDetailsApp extends IBApiNextApp {
*/
start(): void {
const scriptName = path.basename(__filename);
logger.debug(`Starting ${scriptName} script`);
this.info(`Starting ${scriptName} script`);
this.connect();

this.api
.getContractDetails(this.getContractParameter())
.getContractDetails(this.getContractArg())
.then((details) => {
this.printObject(details);
this.stop();
Expand Down
5 changes: 2 additions & 3 deletions src/tools/current-time.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
import path from "path";

import { IBApiNextError } from "../api-next";
import logger from "../common/logger";
import { IBApiNextApp } from "./common/ib-api-next-app";

/////////////////////////////////////////////////////////////////////////////////
Expand All @@ -31,8 +30,8 @@ class PrintCurrentTimeApp extends IBApiNextApp {
*/
start(): void {
const scriptName = path.basename(__filename);
logger.debug(`Starting ${scriptName} script`);
this.connect(0);
this.info(`Starting ${scriptName} script`);
this.connect();

// print current time

Expand Down
12 changes: 4 additions & 8 deletions src/tools/execution-details.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import path from "path";

import { ExecutionFilter } from "..";
import logger from "../common/logger";
import { IBApiNextApp } from "./common/ib-api-next-app";

/////////////////////////////////////////////////////////////////////////////////
Expand All @@ -13,9 +12,7 @@ import { IBApiNextApp } from "./common/ib-api-next-app";

const DESCRIPTION_TEXT = "Get close orders.";
const USAGE_TEXT = "Usage: close-order.js <options>";
const OPTION_ARGUMENTS: [string, string][] = [
["clientId=<number>", "Client id of current ib connection. Default is 0"],
];
const OPTION_ARGUMENTS: [string, string][] = [];
const EXAMPLE_TEXT = "close-order.js -clientId=0";

//////////////////////////////////////////////////////////////////////////////
Expand All @@ -31,9 +28,8 @@ class CloseOrdersApp extends IBApiNextApp {
*/
start(): void {
const scriptName = path.basename(__filename);
logger.debug(`Starting ${scriptName} script`);

this.connect(this.cmdLineArgs.watch ? 10000 : 0);
this.info(`Starting ${scriptName} script`);
this.connect();

const executionFilter: ExecutionFilter = {
clientId: "0",
Expand All @@ -45,7 +41,7 @@ class CloseOrdersApp extends IBApiNextApp {
},
(error) => {
this.printObject(error);
}
},
);
}

Expand Down
Loading

0 comments on commit a994d3e

Please sign in to comment.