Initial Commit
This commit is contained in:
@@ -0,0 +1,45 @@
|
||||
import { TradovateClient } from './tradovate-class';
|
||||
import { getFirms } from './db';
|
||||
|
||||
// Use global to persist the client pool across HMR reloads in dev mode
|
||||
const g = global as typeof globalThis & {
|
||||
__tradovateClients?: Map<number, TradovateClient>;
|
||||
__tradovateClientsInitialized?: boolean;
|
||||
};
|
||||
|
||||
function ensureMap(): Map<number, TradovateClient> {
|
||||
if (!g.__tradovateClients) {
|
||||
g.__tradovateClients = new Map();
|
||||
}
|
||||
return g.__tradovateClients;
|
||||
}
|
||||
|
||||
export function initClient(id: number, username: string, password: string, firmName: string): TradovateClient {
|
||||
const map = ensureMap();
|
||||
const client = new TradovateClient(username, password, async () => {
|
||||
console.log(`[${firmName}] sync complete — ${client.accountList.length} account(s)`);
|
||||
});
|
||||
map.set(id, client);
|
||||
return client;
|
||||
}
|
||||
|
||||
export function removeClient(id: number): void {
|
||||
ensureMap().delete(id);
|
||||
}
|
||||
|
||||
export function getClients(): Map<number, TradovateClient> {
|
||||
const map = ensureMap();
|
||||
if (!g.__tradovateClientsInitialized) {
|
||||
g.__tradovateClientsInitialized = true;
|
||||
try {
|
||||
const firms = getFirms();
|
||||
for (const firm of firms) {
|
||||
initClient(firm.id, firm.username, firm.password, firm.name);
|
||||
}
|
||||
console.log(`[clients] Initialized ${firms.length} Tradovate client(s)`);
|
||||
} catch (err) {
|
||||
console.error('[clients] Failed to initialize clients', err);
|
||||
}
|
||||
}
|
||||
return map;
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import Database from 'better-sqlite3';
|
||||
import path from 'path';
|
||||
|
||||
const db = new Database(path.join(process.cwd(), 'autotrader.sqlite'));
|
||||
|
||||
db.pragma('foreign_keys = ON');
|
||||
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS firms (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL UNIQUE,
|
||||
username TEXT NOT NULL,
|
||||
password TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS account_configs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
firm_id INTEGER NOT NULL REFERENCES firms(id) ON DELETE CASCADE,
|
||||
prefix TEXT NOT NULL,
|
||||
profit_target REAL NOT NULL DEFAULT 3000,
|
||||
consistency REAL NOT NULL DEFAULT 0.5,
|
||||
min_day_pnl REAL NOT NULL DEFAULT -999,
|
||||
min_trading_days INTEGER NOT NULL DEFAULT 5
|
||||
);
|
||||
`);
|
||||
|
||||
// Seed default data if empty
|
||||
const firmCount = (db.prepare('SELECT COUNT(*) as count FROM firms').get() as { count: number }).count;
|
||||
if (firmCount === 0) {
|
||||
const insertFirm = db.prepare('INSERT INTO firms (name, username, password) VALUES (?, ?, ?)');
|
||||
const insertAccount = db.prepare(
|
||||
'INSERT INTO account_configs (firm_id, prefix, profit_target, consistency, min_day_pnl, min_trading_days) VALUES (?, ?, ?, ?, ?, ?)'
|
||||
);
|
||||
|
||||
const alpha = insertFirm.run('Alpha', 'brandonsenoli72786', '-Z2kPm7nBg');
|
||||
insertAccount.run(alpha.lastInsertRowid, 'AFSTDEV', 9000, 0.51, -999, 5);
|
||||
insertAccount.run(alpha.lastInsertRowid, 'AFSTDQA', 4500, 0.40, -999, 7);
|
||||
insertAccount.run(alpha.lastInsertRowid, 'AFZEROEV', 3000, 0.50, -999, 5);
|
||||
insertAccount.run(alpha.lastInsertRowid, 'AFZEROQA', 3000, 0.50, -999, 5);
|
||||
insertAccount.run(alpha.lastInsertRowid, 'AF', 3000, 0.50, -999, 5);
|
||||
|
||||
const tpt = insertFirm.run('TakeProfitTrader', 'BRANDONLI1', 'W4592F5512U2817tv=');
|
||||
insertAccount.run(tpt.lastInsertRowid, 'TAKEPROFIT', 9000, 0.50, -999, 5);
|
||||
|
||||
console.log('[db] Seeded default firms.');
|
||||
}
|
||||
|
||||
export interface AccountConfigRow {
|
||||
id: number;
|
||||
firm_id: number;
|
||||
prefix: string;
|
||||
profit_target: number;
|
||||
consistency: number;
|
||||
min_day_pnl: number;
|
||||
min_trading_days: number;
|
||||
}
|
||||
|
||||
export interface FirmRow {
|
||||
id: number;
|
||||
name: string;
|
||||
username: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
export interface FirmWithAccounts extends FirmRow {
|
||||
accounts: AccountConfigRow[];
|
||||
}
|
||||
|
||||
export function getFirms(): FirmWithAccounts[] {
|
||||
const firms = db.prepare('SELECT * FROM firms ORDER BY id').all() as FirmRow[];
|
||||
const getAccounts = db.prepare('SELECT * FROM account_configs WHERE firm_id = ? ORDER BY id');
|
||||
return firms.map((firm) => ({
|
||||
...firm,
|
||||
accounts: getAccounts.all(firm.id) as AccountConfigRow[],
|
||||
}));
|
||||
}
|
||||
|
||||
export function createFirm(name: string, username: string, password: string): FirmRow {
|
||||
const stmt = db.prepare('INSERT INTO firms (name, username, password) VALUES (?, ?, ?)');
|
||||
const result = stmt.run(name, username, password);
|
||||
return db.prepare('SELECT * FROM firms WHERE id = ?').get(result.lastInsertRowid) as FirmRow;
|
||||
}
|
||||
|
||||
export function deleteFirm(id: number): boolean {
|
||||
const result = db.prepare('DELETE FROM firms WHERE id = ?').run(id);
|
||||
return result.changes > 0;
|
||||
}
|
||||
@@ -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',
|
||||
})}`
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import crypto from 'crypto';
|
||||
|
||||
export interface AuthLoginResponse {
|
||||
accessToken: string;
|
||||
mdAccessToken: string;
|
||||
expirationTime: string;
|
||||
userStatus: string;
|
||||
userId: number;
|
||||
name: string;
|
||||
hasLive: boolean;
|
||||
hasSimPlus: boolean;
|
||||
hasFunded: boolean;
|
||||
hasMarketData: boolean;
|
||||
requiredNonProCertification: boolean;
|
||||
outdatedSentimentPolicy: boolean;
|
||||
orgName: string;
|
||||
}
|
||||
|
||||
export interface AccountItem {
|
||||
id: number;
|
||||
name: string;
|
||||
userId: number;
|
||||
accountType: string;
|
||||
restricted: boolean;
|
||||
closed: boolean;
|
||||
clearingHouseId: number;
|
||||
riskCategoryId: number;
|
||||
autoLiqProfileId: number;
|
||||
marginAccountType: string;
|
||||
legalStatus: string;
|
||||
archived: boolean;
|
||||
timestamp: string;
|
||||
active: boolean;
|
||||
}
|
||||
|
||||
export interface Contract {
|
||||
id: number;
|
||||
name: string;
|
||||
contractMaturityId: number;
|
||||
timestamp: string;
|
||||
status: string;
|
||||
providerTickSize: number;
|
||||
}
|
||||
|
||||
export const randomUUIDV4 = () => {
|
||||
return crypto.randomUUID();
|
||||
};
|
||||
|
||||
export const computeSec = (user: string, password: string, deviceId: string, chl: string) => {
|
||||
const key = '035a1259-11e7-485a-aeae-9b6016579351';
|
||||
const Ct = ['chl', 'deviceId', 'name', 'password', 'appId'];
|
||||
const body = {
|
||||
chl: chl,
|
||||
deviceId: deviceId,
|
||||
name: user,
|
||||
password: password,
|
||||
appId: 'tradovate_trader(web)',
|
||||
};
|
||||
const msg = Ct.map((k) => body[k] ?? '').join('');
|
||||
return crypto.createHmac('sha256', key).update(msg, 'utf8').digest('hex');
|
||||
};
|
||||
Reference in New Issue
Block a user