Expand types, add type guards, flesh out futures position example

This commit is contained in:
Tiago Siebler
2022-11-22 12:32:26 +00:00
parent b3c4c43f63
commit 99a24e6982
9 changed files with 276 additions and 10 deletions

73
src/util/type-guards.ts Normal file
View File

@@ -0,0 +1,73 @@
import {
WsAccountSnapshotUMCBL,
WsBaseEvent,
WSPositionSnapshotUMCBL,
WsSnapshotAccountEvent,
WsSnapshotChannelEvent,
WsSnapshotPositionsEvent,
} from '../types';
/** TypeGuard: event has a string "action" property */
function isWsEvent(event: unknown): event is WsBaseEvent {
return (
typeof event === 'object' &&
event &&
typeof event['action'] === 'string' &&
event['data']
);
}
/** TypeGuard: event has "action === snapshot" */
function isWsSnapshotEvent(event: unknown): event is WsBaseEvent<'snapshot'> {
return isWsEvent(event) && event.action === 'snapshot';
}
/** TypeGuard: event has a string channel name */
function isWsChannelEvent(event: WsBaseEvent): event is WsSnapshotChannelEvent {
if (
typeof event['arg'] === 'object' &&
event.arg &&
typeof event?.arg['channel'] === 'string'
) {
return true;
}
return false;
}
/** TypeGuard: event is an account update (balance) */
export function isWsAccountSnapshotEvent(
event: unknown
): event is WsSnapshotAccountEvent {
return (
isWsSnapshotEvent(event) &&
isWsChannelEvent(event) &&
event.arg.channel === 'account' &&
Array.isArray(event.data)
);
}
/** TypeGuard: event is a positions update */
export function isWsPositionsSnapshotEvent(
event: unknown
): event is WsSnapshotPositionsEvent {
return (
isWsSnapshotEvent(event) &&
isWsChannelEvent(event) &&
event.arg.channel === 'positions' &&
Array.isArray(event.data)
);
}
/** TypeGuard: event is a UMCBL account update (balance) */
export function isWsFuturesAccountSnapshotEvent(
event: unknown
): event is WsAccountSnapshotUMCBL {
return isWsAccountSnapshotEvent(event) && event.arg.instType === 'umcbl';
}
/** TypeGuard: event is a UMCBL positions update */
export function isWsFuturesPositionsSnapshotEvent(
event: unknown
): event is WSPositionSnapshotUMCBL {
return isWsPositionsSnapshotEvent(event) && event.arg.instType === 'umcbl';
}