Initial Commit
This commit is contained in:
@@ -0,0 +1,403 @@
|
||||
// Create a class with a constructor that takes a username and password and sets the credentials
|
||||
|
||||
import axios from 'axios';
|
||||
import type { AccountItem, AuthLoginResponse, Contract } from './tradovate-helpers';
|
||||
import { computeSec, randomUUIDV4 } from './tradovate-helpers';
|
||||
|
||||
export class TradovateClient {
|
||||
private name: string;
|
||||
private password: string;
|
||||
private accessInfo: AuthLoginResponse;
|
||||
private deviceId = randomUUIDV4();
|
||||
|
||||
public accountList: AccountItem[] = [];
|
||||
public accountCashBalances: {
|
||||
[accountId: number]: {
|
||||
amount: number;
|
||||
realizedPnL: number;
|
||||
};
|
||||
} = {};
|
||||
public positions: {
|
||||
[accountId: number]: {
|
||||
contractId: number;
|
||||
netPos: number;
|
||||
netPrice: number;
|
||||
timestamp: Date;
|
||||
};
|
||||
} = {};
|
||||
|
||||
public daysTraded: { [accountId: number]: number } = {};
|
||||
|
||||
private ws: WebSocket;
|
||||
private callbackOnSyncRequest: () => Promise<void>;
|
||||
|
||||
// Events that we sent out, and tradovate gives us a response for the id we sent out
|
||||
private directEventCallbacks: {
|
||||
[id: number]: (response: any) => void;
|
||||
} = {};
|
||||
private indirectEventCallbacks: {
|
||||
entityType:
|
||||
| 'order'
|
||||
| 'orderVersion'
|
||||
| 'auditUserAction'
|
||||
| 'command'
|
||||
| 'commandReport'
|
||||
| 'fill'
|
||||
| 'fillFee'
|
||||
| 'executionReport'
|
||||
| 'cashBalance';
|
||||
eventType: 'Created' | 'Updated';
|
||||
// Since the entity is not always the same, we need a validator to check if the response is the one we are looking for
|
||||
validator: (response: any) => boolean;
|
||||
callback: (response: any) => void;
|
||||
}[] = [];
|
||||
|
||||
constructor(name: string, password: string, callbackOnSyncRequest: () => Promise<void>) {
|
||||
this.name = name;
|
||||
this.password = password;
|
||||
this.callbackOnSyncRequest = callbackOnSyncRequest;
|
||||
|
||||
this.login().then((res) => {
|
||||
if (!res?.accessToken) {
|
||||
console.log('Failed to login', res);
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('Logged in', res);
|
||||
|
||||
// check every 2 minutes if the access token is expired
|
||||
setInterval(() => {
|
||||
// If we are within 15 minutes of the expiration time, renew the access token
|
||||
if (
|
||||
new Date(res.expirationTime).getTime() <
|
||||
new Date().getTime() + 15 * 60 * 1000
|
||||
) {
|
||||
this.renewAccessToken();
|
||||
}
|
||||
}, 2 * 60 * 1000);
|
||||
|
||||
this.accessInfo = res;
|
||||
|
||||
const randomnumber = Math.random().toString(36).substring(2, 15);
|
||||
this.ws = new WebSocket(`wss://demo.tradovateapi.com/v1/websocket?r=${randomnumber}`);
|
||||
|
||||
this.ws.onopen = () => {
|
||||
console.log('Connected to websocket');
|
||||
this.ws.send('authorize\n2\n\n' + this.accessInfo.accessToken);
|
||||
this.directEventCallbacks[2] = (response: any) => {
|
||||
// Once authorize, start syncing every 60 seconds
|
||||
this.requestAccountUpdates();
|
||||
setInterval(() => this.requestAccountUpdates(), 60000);
|
||||
|
||||
// Every 2.5 seconds send a heartbeat
|
||||
setInterval(() => {
|
||||
this.ws.send('[]');
|
||||
}, 2500);
|
||||
};
|
||||
};
|
||||
|
||||
this.ws.onmessage = (event) => {
|
||||
if (event.data[0] === 'a') {
|
||||
const dataString = event.data.slice(1);
|
||||
|
||||
const data: (
|
||||
| {
|
||||
i?: number; // Id
|
||||
s?: number; // Status
|
||||
d?: any; // Data
|
||||
}
|
||||
| {
|
||||
e?: string;
|
||||
d?: {
|
||||
entityType:
|
||||
| 'order'
|
||||
| 'orderVersion'
|
||||
| 'auditUserAction'
|
||||
| 'command'
|
||||
| 'commandReport';
|
||||
eventType: 'Created' | 'Updated';
|
||||
entity: any;
|
||||
};
|
||||
}
|
||||
)[] = JSON.parse(dataString);
|
||||
|
||||
for (const response of data) {
|
||||
if (
|
||||
'i' in response &&
|
||||
response.i &&
|
||||
this.directEventCallbacks[response.i]
|
||||
) {
|
||||
this.directEventCallbacks[response.i](response.d);
|
||||
}
|
||||
|
||||
if ('e' in response && response.e) {
|
||||
// Handle callbacks
|
||||
for (const info of this.indirectEventCallbacks) {
|
||||
if (
|
||||
response.d?.entityType === info?.entityType &&
|
||||
response.d?.eventType === info?.eventType &&
|
||||
info?.validator(response.d.entity)
|
||||
) {
|
||||
info?.callback(response.d.entity);
|
||||
}
|
||||
}
|
||||
|
||||
// console.log('No callback found', response.d);
|
||||
}
|
||||
}
|
||||
} else if (event.data[0] === 'h') {
|
||||
// Heartbeat response
|
||||
}
|
||||
};
|
||||
|
||||
this.ws.onerror = (event) => {
|
||||
console.error('Error on websocket', event);
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
private async requestAccountUpdates(): Promise<void> {
|
||||
this.directEventCallbacks[3] = (response: any) => {
|
||||
|
||||
// Syncing DLL or MLL hit
|
||||
const riskStatusById: { [id: number]: { liquidateOnly?: string } } = (
|
||||
response.accountRiskStatuses || []
|
||||
).reduce((acc: any, item: any) => {
|
||||
acc[item.id] = item;
|
||||
return acc;
|
||||
}, {});
|
||||
|
||||
this.accountList = (response.accounts as AccountItem[]).map((account) => {
|
||||
if (riskStatusById[account.id]?.liquidateOnly) {
|
||||
return { ...account, active: false };
|
||||
}
|
||||
return account;
|
||||
});
|
||||
|
||||
this.accountCashBalances = response.cashBalances.reduce(
|
||||
(
|
||||
acc: {
|
||||
[accountId: number]: { amount: number; realizedPnL: number };
|
||||
},
|
||||
item: { accountId: number; amount: number; realizedPnL: number }
|
||||
) => {
|
||||
acc[item.accountId] = {
|
||||
amount: item.amount,
|
||||
realizedPnL: item.realizedPnL,
|
||||
};
|
||||
return acc;
|
||||
},
|
||||
{} as { [accountId: number]: { amount: number; realizedPnL: number } }
|
||||
);
|
||||
this.positions = response.positions
|
||||
.filter((item) => item.netPos !== 0)
|
||||
.reduce(
|
||||
(
|
||||
acc: {
|
||||
[accountId: number]: {
|
||||
contractId: number;
|
||||
netPos: number;
|
||||
netPrice: number;
|
||||
timestamp: Date;
|
||||
};
|
||||
},
|
||||
item: {
|
||||
accountId: number;
|
||||
contractId: number;
|
||||
netPos: number;
|
||||
netPrice: number;
|
||||
timestamp: Date;
|
||||
}
|
||||
) => {
|
||||
acc[item.accountId] = {
|
||||
contractId: item.contractId,
|
||||
netPos: item.netPos,
|
||||
netPrice: item.netPrice,
|
||||
timestamp: new Date(item.timestamp),
|
||||
};
|
||||
return acc;
|
||||
},
|
||||
{} as {
|
||||
[accountId: number]: {
|
||||
contractId: number;
|
||||
netPos: number;
|
||||
netPrice: number;
|
||||
timestamp: Date;
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
this.callbackOnSyncRequest();
|
||||
this.fetchDaysTraded();
|
||||
};
|
||||
|
||||
this.ws.send('user/syncrequest\n3\n\n{"splitResponses":false}');
|
||||
}
|
||||
|
||||
private async fetchDaysTraded(): Promise<void> {
|
||||
if (!this.accessInfo?.accessToken) return;
|
||||
|
||||
const cutoff = new Date();
|
||||
cutoff.setDate(cutoff.getDate() - 28);
|
||||
|
||||
for (const account of this.accountList) {
|
||||
try {
|
||||
const res = await axios.get(
|
||||
`https://demo.tradovateapi.com/v1/fill/ldeps?masterid=${account.id}`,
|
||||
{ headers: { Authorization: `Bearer ${this.accessInfo.accessToken}` } }
|
||||
);
|
||||
const fills: { timestamp: string }[] = res.data ?? [];
|
||||
const tradingDays = new Set(
|
||||
fills
|
||||
.filter((f) => new Date(f.timestamp) >= cutoff)
|
||||
.map((f) => new Date(f.timestamp).toDateString())
|
||||
);
|
||||
this.daysTraded[account.id] = tradingDays.size;
|
||||
} catch (err) {
|
||||
console.error(`[fetchDaysTraded] account ${account.id}`, err);
|
||||
this.daysTraded[account.id] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async login(): Promise<AuthLoginResponse> {
|
||||
const chl = '' + (Date.now() - 1581e9);
|
||||
const sec = computeSec(this.name, this.password, this.deviceId, chl);
|
||||
|
||||
const generateEncodedPassword = (e) => {
|
||||
const { name: t, password: n } = e,
|
||||
o = t.length % n.length,
|
||||
r = (n.slice(o) + n.slice(0, o)).split('').reverse().join('');
|
||||
return btoa(r);
|
||||
};
|
||||
|
||||
const res = await axios.post('https://live.tradovateapi.com/v1/auth/accesstokenrequest', {
|
||||
name: this.name,
|
||||
password: generateEncodedPassword({ name: this.name, password: this.password }),
|
||||
environment: 'demo',
|
||||
appId: 'tradovate_trader(web)',
|
||||
appVersion: '3.251205.0',
|
||||
deviceId: this.deviceId,
|
||||
cid: '1',
|
||||
chl: chl,
|
||||
sec: sec,
|
||||
enc: true,
|
||||
});
|
||||
|
||||
if (res.status !== 200) {
|
||||
console.error('Failed to login', res.data);
|
||||
}
|
||||
|
||||
return res.data;
|
||||
}
|
||||
|
||||
private async renewAccessToken(): Promise<void> {
|
||||
const res = await axios.get('https://live.tradovateapi.com/v1/auth/renewAccessToken', {
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.accessInfo.accessToken}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (res.status !== 200) {
|
||||
console.error('Failed to renew access token', res.data);
|
||||
}
|
||||
|
||||
console.log('Renewed access token');
|
||||
this.accessInfo = res.data;
|
||||
}
|
||||
|
||||
async getAccountList(): Promise<AccountItem[]> {
|
||||
if (!this.accessInfo?.accessToken) {
|
||||
console.log('Not authenticated');
|
||||
return [];
|
||||
}
|
||||
|
||||
const res = await axios.get('https://demo.tradovateapi.com/v1/account/list', {
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.accessInfo.accessToken}`,
|
||||
},
|
||||
});
|
||||
|
||||
return res.data;
|
||||
}
|
||||
|
||||
async requestContractsFromSocket(names: string[]): Promise<{
|
||||
[name: string]: Contract;
|
||||
}> {
|
||||
if (!this.ws) {
|
||||
console.log('Websocket not connected');
|
||||
return {};
|
||||
}
|
||||
|
||||
return new Promise((resolve) => {
|
||||
this.directEventCallbacks[10] = (response: any) => {
|
||||
resolve(
|
||||
(response || []).reduce((acc: { [name: string]: Contract }, item: Contract) => {
|
||||
return { ...acc, [item.name]: item };
|
||||
}, {} as { [name: string]: Contract })
|
||||
);
|
||||
};
|
||||
this.ws.send(`contract/finds\n10\nnames=${names.join(',')}`);
|
||||
});
|
||||
}
|
||||
|
||||
async sendOrder(
|
||||
accountId: number,
|
||||
contractId: number,
|
||||
quantity: number,
|
||||
action: 'Buy' | 'Sell',
|
||||
orderType: 'Market' | 'Limit',
|
||||
price?: number
|
||||
): Promise<any> {
|
||||
if (!this.ws) {
|
||||
console.log('Websocket not connected');
|
||||
return;
|
||||
}
|
||||
|
||||
this.ws.send(
|
||||
`user/registeraudituseraction\n25\n\n${JSON.stringify({
|
||||
accountId: accountId,
|
||||
actionType: action + orderType,
|
||||
details: `DOM MESZ5: Buy ${orderType}, Buy ${quantity} ${orderType}${
|
||||
price ? ` ${price}` : ''
|
||||
}, TIF Day`,
|
||||
})}`
|
||||
);
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.directEventCallbacks[26] = (response: any) => {
|
||||
// console.log('Order id', response?.orderId);
|
||||
console.log('Order placed, order id: ', response);
|
||||
|
||||
// TODO: Implement for limit orders and rejected market orders
|
||||
|
||||
// If we don't get a response within 5 seconds, reject the promise
|
||||
setTimeout(() => {
|
||||
reject(new Error('No response from order placement'));
|
||||
}, 5000);
|
||||
|
||||
this.indirectEventCallbacks.push({
|
||||
entityType: 'fill',
|
||||
eventType: 'Created',
|
||||
validator: (item: any) => item?.orderId === response?.orderId,
|
||||
callback: (response: any) => {
|
||||
resolve(response);
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
this.ws.send(
|
||||
`order/placeorder\n26\n\n${JSON.stringify({
|
||||
accountId: accountId,
|
||||
action: action,
|
||||
symbol: contractId,
|
||||
orderQty: quantity,
|
||||
orderType: orderType,
|
||||
price: price,
|
||||
timeInForce: 'Day',
|
||||
text: 'DOM',
|
||||
})}`
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user