Skip to content

Commit

Permalink
Unit tests updated
Browse files Browse the repository at this point in the history
  • Loading branch information
rylorin committed Jul 21, 2024
1 parent 0017046 commit f186803
Show file tree
Hide file tree
Showing 8 changed files with 125 additions and 90 deletions.
4 changes: 4 additions & 0 deletions src/common/errorCode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export enum ErrorCode {

/** No trading permissions. */
NO_TRADING_PERMISSIONS = 460,

/**
* Couldn't connect to TWS.
*
Expand Down Expand Up @@ -282,6 +283,9 @@ export enum ErrorCode {
/** FA Profile is not supported anymore, use FA Group instead */
FA_PROFILE_NOT_SUPPORTED = 585,

/** Invalid position trade derived value */
INVALID_POSITION_TRADE_DERIVATED_VALUE = 2150,

/** Part of requested market data is not subscribed. */
PART_OF_REQUESTED_DATA_NOT_SUBSCRIBED = 10090,

Expand Down
2 changes: 1 addition & 1 deletion src/tests/unit/api-next-live/subscription-registry.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ describe("Subscription registry Tests", () => {
// Two active subscriptions for the same Event issue #193
subscription$ = api.getOpenOrders().subscribe({
next: (data) => {

Check warning on line 47 in src/tests/unit/api-next-live/subscription-registry.test.ts

View workflow job for this annotation

GitHub Actions / job

'data' is defined but never used. Allowed unused args must match /^_/u
console.log(data);
// console.log(data);
},
complete: () => {
console.log("getOpenOrders completed.");
Expand Down
84 changes: 38 additions & 46 deletions src/tests/unit/api/historical-data.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,60 +113,52 @@ describe("IBApi Historical data Tests", () => {
ib.reqHistoricalData(
refId,
contract,
"20240508-17:00:00",
"20240719-17:00:00",
"30 S",
BarSizeSetting.SECONDS_FIFTEEN,
WhatToShow.BID_ASK,
0,
2,
false,
);
})
.on(
EventName.historicalData,
(
reqId: number,
time: string,
open: number,
high: number,
low: number,
close: number,
volume: number,
count: number | undefined,
WAP: number,
) => {
// console.log(
// counter,
// time,
// open,
// high,
// low,
// close,
// volume,
// count,
// WAP,
// );
expect(reqId).toEqual(refId);
if (time.startsWith("finished")) {
expect(counter).toEqual(2);
done();
} else if (counter++ == 1) {
expect(time).toEqual("1715187585");
expect(open).toEqual(25.35);
expect(high).toEqual(25.35);
expect(low).toEqual(25.35);
expect(close).toEqual(25.35);
expect(volume).toEqual(-1);
expect(count).toEqual(-1);
expect(WAP).toEqual(-1);
}
},
)
.on(EventName.error, (err, code, reqId) => {
if (reqId == refId) done(`[${reqId}] ${err.message} (#${code})`);
});
}).on(
EventName.historicalData,
(
reqId: number,
time: string,
open: number,
high: number,
low: number,
close: number,
volume: number,
count: number | undefined,
WAP: number,
) => {
// console.log(counter, time, open, high, low, close, volume, count, WAP);
expect(reqId).toEqual(refId);
if (time.startsWith("finished")) {
expect(counter).toEqual(2);
done();
} else if (counter++ == 1) {
expect(time).toEqual("1721408385");
expect(open).toEqual(11.95);
expect(high).toEqual(11.95);
expect(low).toEqual(11.9);
expect(close).toEqual(11.95);
expect(volume).toEqual(-1);
expect(count).toEqual(-1);
expect(WAP).toEqual(-1);
}
},
);

ib.connect();
ib.on(EventName.disconnected, () => done())
.on(EventName.info, (msg, code) => console.info("INFO", code, msg))
.on(EventName.error, (err, code, reqId) => {
if (reqId > 0) done(`[${reqId}] ${err.message} (#${code})`);
else console.error("ERROR", err.message, code, reqId);
})
.connect();
});

it("Weekly market data", (done) => {
Expand Down
22 changes: 20 additions & 2 deletions src/tests/unit/api/order/placeConditionalOrder.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ const sample_percent_condition: OrderCondition = new PercentChangeCondition(
ConjunctionConnection.OR,
);
const sample_time_condition: OrderCondition = new TimeCondition(
"20250101-12:00:00",
"20250102-17:00:00",
true,
ConjunctionConnection.OR,
);
Expand Down Expand Up @@ -369,7 +369,25 @@ describe("Place Conditional Orders", () => {
},
);

ib.connect();
ib.connect()
.on(EventName.error, (error, code, reqId) => {
if (reqId > 0) {
const msg = `[${reqId}] ${error.message} (Error #${code})`;
if (
error.message.includes("Warning:") ||
error.message.includes("Order Message:")
) {
logger.warn(msg);
} else {
ib.disconnect();
done(msg);
}
} else {
console.error("ERROR", error.message, code, reqId);
}
})
.on(EventName.info, (msg, code) => console.info("INFO", code, msg))
.on(EventName.disconnected, () => done());
});

test("placeOrder with VolumeCondition", (done) => {
Expand Down
7 changes: 2 additions & 5 deletions src/tests/unit/api/order/placeOrder.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import logger from "../../../../common/logger";
import {
sample_crypto,
sample_etf,
sample_future,
sample_option,
sample_stock,
} from "../../sample-data/contracts";
Expand Down Expand Up @@ -284,11 +285,7 @@ describe("Place Orders", () => {
test("Issue #203", (done) => {
let refId: number;

const refContract: Contract = {
conId: 708846212,
exchange: "CME",
symbol: "MES",
};
const refContract: Contract = sample_future;
const refOrder: Order = {
action: OrderAction.BUY,
lmtPrice: 1,
Expand Down
40 changes: 32 additions & 8 deletions src/tests/unit/api/api.test.ts → src/tests/unit/api/pnl.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ describe("IBApi Tests", () => {
}
if (_conId === undefined && pos) {
_conId = contract.conId;
// console.info(JSON.stringify(contract));
}
expect(account).toBeTruthy();
expect(contract).toBeTruthy();
Expand Down Expand Up @@ -90,19 +91,31 @@ describe("IBApi Tests", () => {
const refId = 44;
let received = false;

ib.on(
ib.once(EventName.connected, () => {
console.log("reqPnLSingle", refId);
ib.reqPnLSingle(refId, _account, "", _conId);
}).on(
EventName.pnlSingle,
(
reqId: number,
pos: number,
dailyPnL: number,
_dailyPnL: number,
unrealizedPnL: number,
realizedPnL: number,
_realizedPnL: number,
value: number,
) => {
console.log(
"pnlSingle",
reqId,
pos,
_dailyPnL,
unrealizedPnL,
_realizedPnL,
value,
);
expect(reqId).toEqual(refId);
expect(pos).toBeTruthy();
expect(dailyPnL).toBeTruthy();
// expect(dailyPnL).toBeTruthy(); We may have no daily PnL (on week-ends)
expect(unrealizedPnL).toBeTruthy();
// expect(realizedPnL).toBeTruthy(); We may have no realized PnL today
expect(value).toBeTruthy();
Expand All @@ -113,10 +126,21 @@ describe("IBApi Tests", () => {
}
received = true;
},
).on(EventName.error, (err, code, reqId) => {
if (reqId == refId) done(`[${reqId}] ${err.message} (#${code})`);
});
);

ib.connect().reqPnLSingle(refId, _account, null, _conId);
ib.on(EventName.disconnected, () => done())
.on(EventName.info, (msg, code) => console.info("INFO", code, msg))
.on(EventName.error, (err, code, reqId) => {
const msg = `[${reqId}] ${err.message} (#${code})`;
if (
reqId > 0 &&
code != ErrorCode.INVALID_POSITION_TRADE_DERIVATED_VALUE
) {
done(msg);
} else {
console.error("ERROR", msg);
}
})
.connect();
});
});
52 changes: 26 additions & 26 deletions src/tests/unit/api/positions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,6 @@ describe("IBApi Tests", () => {
return res;
}

let _account: string; // maintain account name for further tests
let _conId: number; // maintain for conId for further tests

it("Test reqPositions / cancelPositions", (done) => {
let positionsCount = 0;

Expand All @@ -47,12 +44,6 @@ describe("IBApi Tests", () => {
.on(
EventName.position,
(account: string, contract: Contract, pos: number, avgCost: number) => {
if (_account === undefined) {
_account = account;
}
if (_conId === undefined && pos) {
_conId = contract.conId;
}
expect(account).toBeTruthy();
expect(contract).toBeTruthy();
// expect(pos).toBeTruthy(); pos can be 0 when it has been closed today
Expand All @@ -74,40 +65,49 @@ describe("IBApi Tests", () => {

it("Test reqPositionsMulti / cancelPositionsMulti", (done) => {
let refId = 45;
let count = 0;

ib.once(EventName.connected, () => {
ib.reqPositionsMulti(refId, "", "");
})
.on(
EventName.positionMulti,
(reqId, account, modelCode, contract, pos, avgCost) => {

Check warning on line 75 in src/tests/unit/api/positions.test.ts

View workflow job for this annotation

GitHub Actions / job

'pos' is defined but never used. Allowed unused args must match /^_/u

Check warning on line 75 in src/tests/unit/api/positions.test.ts

View workflow job for this annotation

GitHub Actions / job

'avgCost' is defined but never used. Allowed unused args must match /^_/u
console.log(
"positionMulti",
reqId,
account,
modelCode,
JSON.stringify(contract),
pos,
avgCost,
);
// console.log(
// "positionMulti",
// reqId,
// account,
// modelCode,
// JSON.stringify(contract),
// pos,
// avgCost,
// );
expect(account).toBeTruthy();
expect(contract).toBeTruthy();
},
)
.on(EventName.positionMultiEnd, (reqId) => {
console.log("positionMultiEnd", reqId);
count += 1;
// console.log("positionMultiEnd", reqId);
refId = reqId + 1;
ib.cancelPositionsMulti(refId);
console.log("cancelPositionsMulti sent", refId);
refId = refId + 1;
ib.reqPositionsMulti(refId, "", "");
console.log("reqPositionsMulti sent", refId);
// console.log("cancelPositionsMulti sent", refId);
if (count < 3) {
// console.log("count", count);
refId = refId + 1;
ib.reqPositionsMulti(refId, "", "");
// console.log("reqPositionsMulti sent", refId);
} else {
done();
}
});

ib.connect()
ib.on(EventName.disconnected, () => done())
.on(EventName.info, (msg, code) => console.info("INFO", code, msg))
.on(EventName.error, (err, code, reqId) => {
if (reqId > 0) done(`[${reqId}] ${err.message} (#${code})`);
else console.error("ERROR", err.message, code, reqId);
})
.on(EventName.info, (msg, code) => console.info("INFO", code, msg))
.on(EventName.disconnected, () => done());
.connect();
});
});
4 changes: 2 additions & 2 deletions src/tests/unit/sample-data/contracts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ export const sample_crypto: Contract = new Crypto("ETH");
// This one will need to be updated sometimes
export const sample_future: Contract = new Future(
"ES",
"ESM4",
"202406",
"ESH5",
"202503",
"CME",
50,
);
Expand Down

0 comments on commit f186803

Please sign in to comment.