hedgequantx 2.9.20 → 2.9.22
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/app.js +64 -42
- package/src/menus/connect.js +17 -14
- package/src/menus/dashboard.js +76 -58
- package/src/pages/accounts.js +49 -38
- package/src/pages/ai-agents-ui.js +388 -0
- package/src/pages/ai-agents.js +494 -0
- package/src/pages/ai-models.js +389 -0
- package/src/pages/algo/algo-executor.js +307 -0
- package/src/pages/algo/copy-executor.js +331 -0
- package/src/pages/algo/copy-trading.js +178 -546
- package/src/pages/algo/custom-strategy.js +313 -0
- package/src/pages/algo/index.js +75 -18
- package/src/pages/algo/one-account.js +57 -322
- package/src/pages/algo/ui.js +15 -15
- package/src/pages/orders.js +22 -19
- package/src/pages/positions.js +22 -19
- package/src/pages/stats/index.js +16 -15
- package/src/pages/user.js +11 -7
- package/src/services/ai-supervision/consensus.js +284 -0
- package/src/services/ai-supervision/context.js +275 -0
- package/src/services/ai-supervision/directive.js +167 -0
- package/src/services/ai-supervision/health.js +47 -35
- package/src/services/ai-supervision/index.js +359 -0
- package/src/services/ai-supervision/parser.js +278 -0
- package/src/services/ai-supervision/symbols.js +259 -0
- package/src/services/cliproxy/index.js +256 -0
- package/src/services/cliproxy/installer.js +111 -0
- package/src/services/cliproxy/manager.js +387 -0
- package/src/services/index.js +9 -1
- package/src/services/llmproxy/index.js +166 -0
- package/src/services/llmproxy/manager.js +411 -0
- package/src/services/rithmic/accounts.js +6 -8
- package/src/ui/box.js +5 -9
- package/src/ui/index.js +18 -5
- package/src/ui/menu.js +4 -4
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copy Trading Executor - Execution engine for copy trading
|
|
3
|
+
* Handles signal processing, order placement, and AI supervision
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
const readline = require('readline');
|
|
7
|
+
const { connections } = require('../../services');
|
|
8
|
+
const { AlgoUI, renderSessionSummary } = require('./ui');
|
|
9
|
+
const { SupervisionEngine } = require('../../services/ai-supervision');
|
|
10
|
+
const { M1 } = require('../../lib/m/s1');
|
|
11
|
+
const { MarketDataFeed } = require('../../lib/data');
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Launch Copy Trading execution
|
|
15
|
+
*/
|
|
16
|
+
const launchCopyTrading = async (config) => {
|
|
17
|
+
const { lead, followers, contract, dailyTarget, maxRisk, showNames, supervisionConfig } = config;
|
|
18
|
+
|
|
19
|
+
// Initialize AI Supervision if configured
|
|
20
|
+
const supervisionEnabled = supervisionConfig?.supervisionEnabled && supervisionConfig?.agents?.length > 0;
|
|
21
|
+
const supervisionEngine = supervisionEnabled ? new SupervisionEngine(supervisionConfig) : null;
|
|
22
|
+
const aiContext = { recentTicks: [], recentSignals: [], maxTicks: 100 };
|
|
23
|
+
|
|
24
|
+
const leadAccount = lead.account;
|
|
25
|
+
const leadService = leadAccount.service || connections.getServiceForAccount(leadAccount.accountId);
|
|
26
|
+
const leadName = showNames
|
|
27
|
+
? (leadAccount.accountName || leadAccount.rithmicAccountId || leadAccount.accountId)
|
|
28
|
+
: 'HQX Lead *****';
|
|
29
|
+
const symbolName = contract.name;
|
|
30
|
+
const contractId = contract.id;
|
|
31
|
+
const tickSize = contract.tickSize || 0.25;
|
|
32
|
+
|
|
33
|
+
const followerNames = followers.map((f, i) =>
|
|
34
|
+
showNames ? (f.account.accountName || f.account.accountId) : `HQX Follower ${i + 1} *****`
|
|
35
|
+
);
|
|
36
|
+
|
|
37
|
+
const ui = new AlgoUI({
|
|
38
|
+
subtitle: supervisionEnabled ? 'HQX Copy + AI' : 'HQX Copy Trading',
|
|
39
|
+
mode: 'copy-trading'
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
const stats = {
|
|
43
|
+
accountName: leadName,
|
|
44
|
+
followerNames,
|
|
45
|
+
symbol: symbolName,
|
|
46
|
+
qty: lead.contracts,
|
|
47
|
+
followerQty: followers[0]?.contracts || lead.contracts,
|
|
48
|
+
target: dailyTarget,
|
|
49
|
+
risk: maxRisk,
|
|
50
|
+
propfirm: leadAccount.propfirm || 'Unknown',
|
|
51
|
+
platform: leadAccount.platform || 'Rithmic',
|
|
52
|
+
pnl: 0,
|
|
53
|
+
followerPnl: 0,
|
|
54
|
+
trades: 0,
|
|
55
|
+
wins: 0,
|
|
56
|
+
losses: 0,
|
|
57
|
+
latency: 0,
|
|
58
|
+
connected: false,
|
|
59
|
+
startTime: Date.now(),
|
|
60
|
+
followersCount: followers.length
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
let running = true;
|
|
64
|
+
let stopReason = null;
|
|
65
|
+
let startingPnL = null;
|
|
66
|
+
let currentPosition = 0;
|
|
67
|
+
let pendingOrder = false;
|
|
68
|
+
let tickCount = 0;
|
|
69
|
+
|
|
70
|
+
// Initialize Strategy
|
|
71
|
+
const strategy = new M1({ tickSize });
|
|
72
|
+
strategy.initialize(contractId, tickSize);
|
|
73
|
+
|
|
74
|
+
// Initialize Market Data Feed
|
|
75
|
+
const marketFeed = new MarketDataFeed({ propfirm: leadAccount.propfirm });
|
|
76
|
+
|
|
77
|
+
// Log startup
|
|
78
|
+
ui.addLog('info', `Lead: ${leadName} | Followers: ${followers.length}`);
|
|
79
|
+
ui.addLog('info', `Symbol: ${symbolName} | Qty: ${lead.contracts}/${followers[0]?.contracts}`);
|
|
80
|
+
ui.addLog('info', `Target: $${dailyTarget} | Risk: $${maxRisk}`);
|
|
81
|
+
if (supervisionEnabled) ui.addLog('info', `AI: ${supervisionEngine.getActiveCount()} agents`);
|
|
82
|
+
ui.addLog('info', 'Connecting...');
|
|
83
|
+
|
|
84
|
+
// Handle strategy signals
|
|
85
|
+
strategy.on('signal', async (signal) => {
|
|
86
|
+
if (!running || pendingOrder || currentPosition !== 0) return;
|
|
87
|
+
|
|
88
|
+
let { direction, entry, stopLoss, takeProfit, confidence } = signal;
|
|
89
|
+
|
|
90
|
+
aiContext.recentSignals.push({ ...signal, timestamp: Date.now() });
|
|
91
|
+
if (aiContext.recentSignals.length > 10) aiContext.recentSignals.shift();
|
|
92
|
+
|
|
93
|
+
ui.addLog('signal', `${direction.toUpperCase()} @ ${entry.toFixed(2)} (${(confidence * 100).toFixed(0)}%)`);
|
|
94
|
+
|
|
95
|
+
// AI Supervision
|
|
96
|
+
if (supervisionEnabled && supervisionEngine) {
|
|
97
|
+
const result = await supervisionEngine.supervise({
|
|
98
|
+
symbolId: symbolName,
|
|
99
|
+
signal: { direction, entry, stopLoss, takeProfit, confidence },
|
|
100
|
+
recentTicks: aiContext.recentTicks,
|
|
101
|
+
recentSignals: aiContext.recentSignals,
|
|
102
|
+
stats,
|
|
103
|
+
config: { dailyTarget, maxRisk }
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
if (result.decision === 'reject') {
|
|
107
|
+
ui.addLog('info', `AI rejected: ${result.reason}`);
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// Apply optimizations
|
|
112
|
+
if (result.optimizedSignal?.aiOptimized) {
|
|
113
|
+
const opt = result.optimizedSignal;
|
|
114
|
+
if (opt.entry) entry = opt.entry;
|
|
115
|
+
if (opt.stopLoss) stopLoss = opt.stopLoss;
|
|
116
|
+
if (opt.takeProfit) takeProfit = opt.takeProfit;
|
|
117
|
+
}
|
|
118
|
+
ui.addLog('info', `AI ${result.decision} (${result.confidence}%)`);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// Execute orders
|
|
122
|
+
pendingOrder = true;
|
|
123
|
+
try {
|
|
124
|
+
const orderSide = direction === 'long' ? 0 : 1;
|
|
125
|
+
|
|
126
|
+
// Place order on LEAD
|
|
127
|
+
const leadResult = await leadService.placeOrder({
|
|
128
|
+
accountId: leadAccount.accountId,
|
|
129
|
+
contractId,
|
|
130
|
+
type: 2,
|
|
131
|
+
side: orderSide,
|
|
132
|
+
size: lead.contracts
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
if (leadResult.success) {
|
|
136
|
+
currentPosition = direction === 'long' ? lead.contracts : -lead.contracts;
|
|
137
|
+
stats.trades++;
|
|
138
|
+
ui.addLog('trade', `LEAD: ${direction.toUpperCase()} ${lead.contracts}x`);
|
|
139
|
+
|
|
140
|
+
// Place orders on FOLLOWERS
|
|
141
|
+
await placeFollowerOrders(followers, contractId, orderSide, direction, ui);
|
|
142
|
+
|
|
143
|
+
// Bracket orders on lead
|
|
144
|
+
if (stopLoss && takeProfit) {
|
|
145
|
+
await placeBracketOrders(leadService, leadAccount, contractId, direction, lead.contracts, stopLoss, takeProfit);
|
|
146
|
+
ui.addLog('info', `SL: ${stopLoss.toFixed(2)} | TP: ${takeProfit.toFixed(2)}`);
|
|
147
|
+
}
|
|
148
|
+
} else {
|
|
149
|
+
ui.addLog('error', `Lead failed: ${leadResult.error}`);
|
|
150
|
+
}
|
|
151
|
+
} catch (e) {
|
|
152
|
+
ui.addLog('error', `Order error: ${e.message}`);
|
|
153
|
+
}
|
|
154
|
+
pendingOrder = false;
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
// Handle market data ticks
|
|
158
|
+
marketFeed.on('tick', (tick) => {
|
|
159
|
+
tickCount++;
|
|
160
|
+
const latencyStart = Date.now();
|
|
161
|
+
|
|
162
|
+
aiContext.recentTicks.push(tick);
|
|
163
|
+
if (aiContext.recentTicks.length > aiContext.maxTicks) aiContext.recentTicks.shift();
|
|
164
|
+
|
|
165
|
+
strategy.processTick({
|
|
166
|
+
contractId: tick.contractId || contractId,
|
|
167
|
+
price: tick.price,
|
|
168
|
+
bid: tick.bid,
|
|
169
|
+
ask: tick.ask,
|
|
170
|
+
volume: tick.volume || 1,
|
|
171
|
+
side: tick.lastTradeSide || 'unknown',
|
|
172
|
+
timestamp: tick.timestamp || Date.now()
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
stats.latency = Date.now() - latencyStart;
|
|
176
|
+
if (tickCount % 100 === 0) ui.addLog('info', `#${tickCount} @ ${tick.price?.toFixed(2) || 'N/A'}`);
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
marketFeed.on('connected', () => { stats.connected = true; ui.addLog('success', 'Connected!'); });
|
|
180
|
+
marketFeed.on('error', (err) => ui.addLog('error', `Market: ${err.message}`));
|
|
181
|
+
marketFeed.on('disconnected', () => { stats.connected = false; ui.addLog('error', 'Disconnected'); });
|
|
182
|
+
|
|
183
|
+
// Connect to market data
|
|
184
|
+
try {
|
|
185
|
+
const token = leadService.token || leadService.getToken?.();
|
|
186
|
+
const pk = (leadAccount.propfirm || 'topstep').toLowerCase().replace(/\s+/g, '_');
|
|
187
|
+
await marketFeed.connect(token, pk, contractId);
|
|
188
|
+
await marketFeed.subscribe(symbolName, contractId);
|
|
189
|
+
} catch (e) {
|
|
190
|
+
ui.addLog('error', `Connect failed: ${e.message}`);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// Poll P&L
|
|
194
|
+
const pollPnL = async () => {
|
|
195
|
+
try {
|
|
196
|
+
const res = await leadService.getTradingAccounts();
|
|
197
|
+
if (res.success && res.accounts) {
|
|
198
|
+
const acc = res.accounts.find(a => a.accountId === leadAccount.accountId);
|
|
199
|
+
if (acc?.profitAndLoss !== undefined) {
|
|
200
|
+
if (startingPnL === null) startingPnL = acc.profitAndLoss;
|
|
201
|
+
stats.pnl = acc.profitAndLoss - startingPnL;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
if (stats.pnl >= dailyTarget) {
|
|
205
|
+
stopReason = 'target';
|
|
206
|
+
running = false;
|
|
207
|
+
ui.addLog('success', `TARGET! +$${stats.pnl.toFixed(2)}`);
|
|
208
|
+
} else if (stats.pnl <= -maxRisk) {
|
|
209
|
+
stopReason = 'risk';
|
|
210
|
+
running = false;
|
|
211
|
+
ui.addLog('error', `RISK! -$${Math.abs(stats.pnl).toFixed(2)}`);
|
|
212
|
+
}
|
|
213
|
+
} catch (e) { /* silent */ }
|
|
214
|
+
};
|
|
215
|
+
|
|
216
|
+
// Start intervals
|
|
217
|
+
const refreshInterval = setInterval(() => { if (running) ui.render(stats); }, 250);
|
|
218
|
+
const pnlInterval = setInterval(() => { if (running) pollPnL(); }, 2000);
|
|
219
|
+
pollPnL();
|
|
220
|
+
|
|
221
|
+
// Keyboard handler
|
|
222
|
+
const cleanupKeys = setupKeyHandler(() => { running = false; stopReason = 'manual'; });
|
|
223
|
+
|
|
224
|
+
// Wait for stop
|
|
225
|
+
await new Promise(resolve => {
|
|
226
|
+
const check = setInterval(() => {
|
|
227
|
+
if (!running) { clearInterval(check); resolve(); }
|
|
228
|
+
}, 100);
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
// Cleanup
|
|
232
|
+
clearInterval(refreshInterval);
|
|
233
|
+
clearInterval(pnlInterval);
|
|
234
|
+
await marketFeed.disconnect();
|
|
235
|
+
if (cleanupKeys) cleanupKeys();
|
|
236
|
+
ui.cleanup();
|
|
237
|
+
|
|
238
|
+
if (process.stdin.isTTY) process.stdin.setRawMode(false);
|
|
239
|
+
process.stdin.resume();
|
|
240
|
+
|
|
241
|
+
// Duration
|
|
242
|
+
const durationMs = Date.now() - stats.startTime;
|
|
243
|
+
const hours = Math.floor(durationMs / 3600000);
|
|
244
|
+
const minutes = Math.floor((durationMs % 3600000) / 60000);
|
|
245
|
+
const seconds = Math.floor((durationMs % 60000) / 1000);
|
|
246
|
+
stats.duration = hours > 0 ? `${hours}h ${minutes}m ${seconds}s` : minutes > 0 ? `${minutes}m ${seconds}s` : `${seconds}s`;
|
|
247
|
+
|
|
248
|
+
renderSessionSummary(stats, stopReason);
|
|
249
|
+
|
|
250
|
+
console.log('\n Returning to menu in 3 seconds...');
|
|
251
|
+
await new Promise(resolve => setTimeout(resolve, 3000));
|
|
252
|
+
};
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* Place orders on all follower accounts
|
|
256
|
+
*/
|
|
257
|
+
const placeFollowerOrders = async (followers, contractId, orderSide, direction, ui) => {
|
|
258
|
+
for (let i = 0; i < followers.length; i++) {
|
|
259
|
+
const f = followers[i];
|
|
260
|
+
const fService = f.account.service || connections.getServiceForAccount(f.account.accountId);
|
|
261
|
+
|
|
262
|
+
try {
|
|
263
|
+
const fResult = await fService.placeOrder({
|
|
264
|
+
accountId: f.account.accountId,
|
|
265
|
+
contractId,
|
|
266
|
+
type: 2,
|
|
267
|
+
side: orderSide,
|
|
268
|
+
size: f.contracts
|
|
269
|
+
});
|
|
270
|
+
|
|
271
|
+
if (fResult.success) {
|
|
272
|
+
ui.addLog('trade', `F${i + 1}: ${direction.toUpperCase()} ${f.contracts}x`);
|
|
273
|
+
} else {
|
|
274
|
+
ui.addLog('error', `F${i + 1}: Failed`);
|
|
275
|
+
}
|
|
276
|
+
} catch (e) {
|
|
277
|
+
ui.addLog('error', `F${i + 1}: ${e.message}`);
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
};
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Place bracket orders (stop loss and take profit)
|
|
284
|
+
*/
|
|
285
|
+
const placeBracketOrders = async (service, account, contractId, direction, size, stopLoss, takeProfit) => {
|
|
286
|
+
const exitSide = direction === 'long' ? 1 : 0;
|
|
287
|
+
|
|
288
|
+
await service.placeOrder({
|
|
289
|
+
accountId: account.accountId,
|
|
290
|
+
contractId,
|
|
291
|
+
type: 4,
|
|
292
|
+
side: exitSide,
|
|
293
|
+
size,
|
|
294
|
+
stopPrice: stopLoss
|
|
295
|
+
});
|
|
296
|
+
|
|
297
|
+
await service.placeOrder({
|
|
298
|
+
accountId: account.accountId,
|
|
299
|
+
contractId,
|
|
300
|
+
type: 1,
|
|
301
|
+
side: exitSide,
|
|
302
|
+
size,
|
|
303
|
+
limitPrice: takeProfit
|
|
304
|
+
});
|
|
305
|
+
};
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* Setup keyboard handler for stopping
|
|
309
|
+
*/
|
|
310
|
+
const setupKeyHandler = (onStop) => {
|
|
311
|
+
if (!process.stdin.isTTY) return null;
|
|
312
|
+
|
|
313
|
+
readline.emitKeypressEvents(process.stdin);
|
|
314
|
+
process.stdin.setRawMode(true);
|
|
315
|
+
process.stdin.resume();
|
|
316
|
+
|
|
317
|
+
const onKey = (str, key) => {
|
|
318
|
+
if (key && (key.name === 'x' || key.name === 'X' || (key.ctrl && key.name === 'c'))) {
|
|
319
|
+
onStop();
|
|
320
|
+
}
|
|
321
|
+
};
|
|
322
|
+
|
|
323
|
+
process.stdin.on('keypress', onKey);
|
|
324
|
+
|
|
325
|
+
return () => {
|
|
326
|
+
process.stdin.removeListener('keypress', onKey);
|
|
327
|
+
if (process.stdin.isTTY) process.stdin.setRawMode(false);
|
|
328
|
+
};
|
|
329
|
+
};
|
|
330
|
+
|
|
331
|
+
module.exports = { launchCopyTrading };
|