hedgequantx 2.9.18 → 2.9.20

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.
Files changed (39) hide show
  1. package/package.json +1 -1
  2. package/src/app.js +42 -64
  3. package/src/lib/m/hqx-2b.js +7 -0
  4. package/src/lib/m/index.js +138 -0
  5. package/src/lib/m/ultra-scalping.js +7 -0
  6. package/src/menus/connect.js +14 -17
  7. package/src/menus/dashboard.js +58 -76
  8. package/src/pages/accounts.js +38 -49
  9. package/src/pages/algo/copy-trading.js +546 -178
  10. package/src/pages/algo/index.js +18 -75
  11. package/src/pages/algo/one-account.js +322 -57
  12. package/src/pages/algo/ui.js +15 -15
  13. package/src/pages/orders.js +19 -22
  14. package/src/pages/positions.js +19 -22
  15. package/src/pages/stats/index.js +15 -16
  16. package/src/pages/user.js +7 -11
  17. package/src/services/ai-supervision/health.js +35 -47
  18. package/src/services/index.js +1 -9
  19. package/src/services/rithmic/accounts.js +8 -6
  20. package/src/ui/box.js +9 -5
  21. package/src/ui/index.js +5 -18
  22. package/src/ui/menu.js +4 -4
  23. package/src/pages/ai-agents-ui.js +0 -388
  24. package/src/pages/ai-agents.js +0 -494
  25. package/src/pages/ai-models.js +0 -389
  26. package/src/pages/algo/algo-executor.js +0 -307
  27. package/src/pages/algo/copy-executor.js +0 -331
  28. package/src/pages/algo/custom-strategy.js +0 -313
  29. package/src/services/ai-supervision/consensus.js +0 -284
  30. package/src/services/ai-supervision/context.js +0 -275
  31. package/src/services/ai-supervision/directive.js +0 -167
  32. package/src/services/ai-supervision/index.js +0 -309
  33. package/src/services/ai-supervision/parser.js +0 -278
  34. package/src/services/ai-supervision/symbols.js +0 -259
  35. package/src/services/cliproxy/index.js +0 -256
  36. package/src/services/cliproxy/installer.js +0 -111
  37. package/src/services/cliproxy/manager.js +0 -387
  38. package/src/services/llmproxy/index.js +0 -166
  39. package/src/services/llmproxy/manager.js +0 -411
@@ -1,167 +0,0 @@
1
- /**
2
- * AI Supervision Directive - The 7 Phases
3
- *
4
- * This directive is sent to ALL AI agents for trading supervision.
5
- * Each agent receives the same instructions and analyzes signals in parallel.
6
- */
7
-
8
- const DIRECTIVE_PHASES = {
9
- phase1_strategy: `
10
- ## PHASE 1: MAÎTRISER LA STRATÉGIE
11
- Tu connais cette stratégie par coeur. Tu sais exactement:
12
- - Les conditions d'entrée (setup patterns, confirmations requises)
13
- - Les règles de sortie (targets, stops, trailing)
14
- - La gestion du risque (sizing, max loss, drawdown limits)
15
- - Les filtres de marché (sessions, volatilité, corrélations)
16
- Tu ne devines jamais. Tu appliques la stratégie avec précision chirurgicale.
17
- `,
18
-
19
- phase2_role: `
20
- ## PHASE 2: TON RÔLE
21
- Tu es une arme de précision intégrée à l'algo de trading.
22
- Tu n'es PAS un conseiller - tu es un avantage décisif.
23
- Ton job: optimiser chaque signal pour maximiser le edge.
24
- Tu travailles EN TEMPS RÉEL avec latence minimale.
25
- Chaque milliseconde compte. Chaque tick compte.
26
- `,
27
-
28
- phase3_analysis: `
29
- ## PHASE 3: CE QUE TU ANALYSES
30
- Pour chaque signal reçu, tu analyses:
31
- - DOM (Depth of Market): déséquilibres bid/ask, absorption, spoofing
32
- - Order Flow: delta, CVD, volume profile, footprint
33
- - Manipulations: stop hunts, fakeouts, liquidity grabs
34
- - Patterns: structure de marché, S/R, pivots, VWAP
35
- - Historique: trades récents, winrate par setup, performance horaire
36
- - Corrélations: autres symboles liés (ES/NQ, GC/SI, etc.)
37
- `,
38
-
39
- phase4_output: `
40
- ## PHASE 4: CE QUE TU FOURNIS
41
- Pour chaque signal, tu retournes:
42
- 1. DECISION: approve/reject/modify
43
- 2. CONFIDENCE: score 0-100
44
- 3. OPTIMIZATIONS (si approve/modify):
45
- - entry: prix d'entrée optimisé (ou null)
46
- - stopLoss: stop optimisé (ou null)
47
- - takeProfit: target optimisé (ou null)
48
- - size: ajustement de taille (-50% à +50%)
49
- - timing: "now" | "wait" | "cancel"
50
- 4. REASON: explication courte (max 50 chars)
51
- 5. ALERTS: warnings importants (optionnel)
52
- `,
53
-
54
- phase5_restrictions: `
55
- ## PHASE 5: CE QUE TU NE FAIS JAMAIS
56
- - Tu ne BLOQUES jamais l'algo sans raison valide
57
- - Tu ne RALENTIS jamais l'exécution (réponse < 2 secondes)
58
- - Tu ne fais pas de VAGUE - décision claire et directe
59
- - Tu n'INVENTES pas de données - utilise uniquement ce qui est fourni
60
- - Tu ne CHANGES pas la stratégie - tu l'optimises dans ses règles
61
- `,
62
-
63
- phase6_symbols: `
64
- ## PHASE 6: CONNAISSANCE DES SYMBOLES
65
- Tu trades ces symboles avec leurs caractéristiques:
66
- - NQ (Nasdaq): volatile, tech-driven, corrélé ES
67
- - ES (S&P500): référence, plus stable, leader
68
- - YM (Dow): value stocks, moins volatile
69
- - RTY (Russell): small caps, plus volatile que ES
70
- - GC (Gold): safe haven, inverse USD, sessions Asia/London
71
- - SI (Silver): suit GC avec plus de volatilité
72
- - CL (Crude): news-driven, inventories, géopolitique
73
-
74
- Sessions importantes:
75
- - Asia: 18:00-03:00 ET (GC/SI actifs)
76
- - London: 03:00-08:00 ET (préparation US)
77
- - US Open: 09:30-11:30 ET (max volatilité)
78
- - US Close: 15:00-16:00 ET (rebalancing)
79
- `,
80
-
81
- phase7_mindset: `
82
- ## PHASE 7: TA MENTALITÉ
83
- - OBJECTIF: Gagner. Pas "essayer". Gagner.
84
- - PRÉCISION: Chaque décision compte
85
- - RAPIDITÉ: Temps = argent. Sois rapide.
86
- - RESPONSABILITÉ: Tu assumes tes recommandations
87
- - ADAPTATION: Le marché change, tu t'adaptes
88
- - DISCIPLINE: Les règles sont les règles
89
- `
90
- };
91
-
92
- /**
93
- * Build the complete directive string
94
- */
95
- const buildDirective = () => {
96
- return Object.values(DIRECTIVE_PHASES).join('\n');
97
- };
98
-
99
- /**
100
- * Expected output format from AI agents
101
- */
102
- const OUTPUT_FORMAT = {
103
- schema: {
104
- decision: 'approve | reject | modify',
105
- confidence: 'number 0-100',
106
- optimizations: {
107
- entry: 'number | null',
108
- stopLoss: 'number | null',
109
- takeProfit: 'number | null',
110
- size: 'number (-0.5 to 0.5) | null',
111
- timing: 'now | wait | cancel'
112
- },
113
- reason: 'string (max 50 chars)',
114
- alerts: 'string[] | null'
115
- },
116
- example: {
117
- decision: 'modify',
118
- confidence: 85,
119
- optimizations: {
120
- entry: 21450.25,
121
- stopLoss: 21445.00,
122
- takeProfit: 21462.50,
123
- size: 0,
124
- timing: 'now'
125
- },
126
- reason: 'Strong bid stack, tighten stop',
127
- alerts: null
128
- }
129
- };
130
-
131
- /**
132
- * Build the output format instructions
133
- */
134
- const buildOutputInstructions = () => {
135
- return `
136
- ## OUTPUT FORMAT (JSON STRICT)
137
- Tu dois TOUJOURS répondre en JSON valide avec ce format exact:
138
-
139
- \`\`\`json
140
- ${JSON.stringify(OUTPUT_FORMAT.example, null, 2)}
141
- \`\`\`
142
-
143
- IMPORTANT:
144
- - decision: "approve" (exécuter tel quel), "reject" (ne pas exécuter), "modify" (exécuter avec optimisations)
145
- - confidence: 0-100, ton niveau de confiance dans la décision
146
- - optimizations: null si decision="reject", sinon les ajustements
147
- - size: 0 = garder la taille, -0.5 = réduire de 50%, +0.5 = augmenter de 50%
148
- - timing: "now" = exécuter immédiatement, "wait" = attendre meilleur prix, "cancel" = annuler
149
- - reason: TOUJOURS fournir une raison courte
150
- - Pas de texte avant ou après le JSON
151
- `;
152
- };
153
-
154
- /**
155
- * Get the complete directive with output format
156
- */
157
- const getFullDirective = () => {
158
- return buildDirective() + '\n' + buildOutputInstructions();
159
- };
160
-
161
- module.exports = {
162
- DIRECTIVE_PHASES,
163
- OUTPUT_FORMAT,
164
- buildDirective,
165
- buildOutputInstructions,
166
- getFullDirective
167
- };
@@ -1,309 +0,0 @@
1
- /**
2
- * AI Supervision Engine - Main Entry Point
3
- *
4
- * Orchestrates multi-agent AI supervision for trading signals.
5
- * Sends signals to all active agents in parallel and calculates
6
- * weighted consensus for final decision.
7
- */
8
-
9
- const { getFullDirective } = require('./directive');
10
- const { buildMarketContext, formatContextForPrompt } = require('./context');
11
- const { parseAgentResponse } = require('./parser');
12
- const { calculateConsensus, isApproved, applyOptimizations } = require('./consensus');
13
- const { runPreflightCheck, formatPreflightResults, getPreflightSummary } = require('./health');
14
- const cliproxy = require('../cliproxy');
15
-
16
- /**
17
- * SupervisionEngine class - manages multi-agent supervision
18
- */
19
- class SupervisionEngine {
20
- constructor(config = {}) {
21
- this.agents = config.agents || [];
22
- this.timeout = config.timeout || 30000;
23
- this.minAgents = config.minAgents || 1;
24
- this.directive = getFullDirective();
25
- this.activeAgents = new Map();
26
- this.rateLimitedAgents = new Set();
27
-
28
- // Initialize active agents
29
- for (const agent of this.agents) {
30
- if (agent.active) {
31
- this.activeAgents.set(agent.id, agent);
32
- }
33
- }
34
- }
35
-
36
- /**
37
- * Get count of active (non-rate-limited) agents
38
- */
39
- getActiveCount() {
40
- return this.activeAgents.size - this.rateLimitedAgents.size;
41
- }
42
-
43
- /**
44
- * Check if supervision is available
45
- */
46
- isAvailable() {
47
- return this.getActiveCount() >= this.minAgents;
48
- }
49
-
50
- /**
51
- * Mark agent as rate limited
52
- */
53
- markRateLimited(agentId) {
54
- this.rateLimitedAgents.add(agentId);
55
- }
56
-
57
- /**
58
- * Reset rate limited agents (call periodically)
59
- */
60
- resetRateLimits() {
61
- this.rateLimitedAgents.clear();
62
- }
63
-
64
- /**
65
- * Build prompt for AI agent
66
- */
67
- buildPrompt(context) {
68
- const contextStr = formatContextForPrompt(context);
69
- return `${this.directive}\n\n${contextStr}\n\nAnalyze this signal and respond with JSON only.`;
70
- }
71
-
72
- /**
73
- * Query a single agent
74
- */
75
- async queryAgent(agent, prompt) {
76
- const startTime = Date.now();
77
-
78
- try {
79
- let response;
80
-
81
- if (agent.connectionType === 'cliproxy') {
82
- // Use CLIProxy API
83
- response = await cliproxy.chat(agent.provider, agent.modelId, prompt, this.timeout);
84
- } else if (agent.connectionType === 'apikey' && agent.apiKey) {
85
- // Direct API call (implement per provider)
86
- response = await this.callDirectAPI(agent, prompt);
87
- } else {
88
- throw new Error('Invalid agent configuration');
89
- }
90
-
91
- const latency = Date.now() - startTime;
92
-
93
- if (!response.success) {
94
- // Check for rate limit
95
- if (response.error?.includes('rate') || response.error?.includes('limit')) {
96
- this.markRateLimited(agent.id);
97
- }
98
- return { success: false, error: response.error, latency };
99
- }
100
-
101
- const parsed = parseAgentResponse(response.content || response.text);
102
-
103
- return {
104
- success: true,
105
- response: parsed,
106
- latency,
107
- raw: response
108
- };
109
-
110
- } catch (error) {
111
- const latency = Date.now() - startTime;
112
-
113
- // Check for rate limit errors
114
- if (error.message?.includes('429') || error.message?.includes('rate')) {
115
- this.markRateLimited(agent.id);
116
- }
117
-
118
- return {
119
- success: false,
120
- error: error.message,
121
- latency
122
- };
123
- }
124
- }
125
-
126
- /**
127
- * Direct API call for API key connections
128
- */
129
- async callDirectAPI(agent, prompt) {
130
- // This would be implemented per provider
131
- // For now, return error to use CLIProxy instead
132
- return {
133
- success: false,
134
- error: 'Direct API not implemented - use CLIProxy'
135
- };
136
- }
137
-
138
- /**
139
- * Query all agents in parallel
140
- */
141
- async queryAllAgents(prompt) {
142
- const availableAgents = Array.from(this.activeAgents.values())
143
- .filter(agent => !this.rateLimitedAgents.has(agent.id));
144
-
145
- if (availableAgents.length === 0) {
146
- return [];
147
- }
148
-
149
- // Query all agents in parallel with timeout
150
- const queries = availableAgents.map(agent =>
151
- Promise.race([
152
- this.queryAgent(agent, prompt),
153
- new Promise((_, reject) =>
154
- setTimeout(() => reject(new Error('Timeout')), this.timeout)
155
- )
156
- ]).then(result => ({
157
- agentId: agent.id,
158
- agentName: agent.name,
159
- weight: agent.weight || 100,
160
- ...result
161
- })).catch(error => ({
162
- agentId: agent.id,
163
- agentName: agent.name,
164
- weight: agent.weight || 100,
165
- success: false,
166
- error: error.message
167
- }))
168
- );
169
-
170
- return Promise.all(queries);
171
- }
172
-
173
- /**
174
- * Main supervision method - analyze a signal
175
- */
176
- async supervise(params) {
177
- const {
178
- symbolId,
179
- signal,
180
- recentTicks = [],
181
- recentSignals = [],
182
- recentTrades = [],
183
- domData = null,
184
- position = null,
185
- stats = {},
186
- config = {}
187
- } = params;
188
-
189
- // Check availability
190
- if (!this.isAvailable()) {
191
- return {
192
- success: false,
193
- error: 'No agents available',
194
- decision: 'approve',
195
- reason: 'No AI supervision - passing through'
196
- };
197
- }
198
-
199
- // Build context and prompt
200
- const context = buildMarketContext({
201
- symbolId,
202
- signal,
203
- recentTicks,
204
- recentSignals,
205
- recentTrades,
206
- domData,
207
- position,
208
- stats,
209
- config
210
- });
211
-
212
- const prompt = this.buildPrompt(context);
213
-
214
- // Query all agents
215
- const results = await this.queryAllAgents(prompt);
216
-
217
- // Filter successful responses
218
- const successfulResults = results.filter(r => r.success);
219
-
220
- if (successfulResults.length === 0) {
221
- return {
222
- success: false,
223
- error: 'All agents failed',
224
- decision: 'approve',
225
- reason: 'Agent errors - passing through',
226
- agentResults: results
227
- };
228
- }
229
-
230
- // Calculate consensus
231
- const consensus = calculateConsensus(
232
- successfulResults.map(r => ({
233
- agentId: r.agentId,
234
- response: r.response,
235
- weight: r.weight
236
- })),
237
- { minAgents: this.minAgents }
238
- );
239
-
240
- // Apply optimizations if approved
241
- const optimizedSignal = isApproved(consensus)
242
- ? applyOptimizations(signal, consensus)
243
- : signal;
244
-
245
- return {
246
- success: true,
247
- decision: consensus.decision,
248
- confidence: consensus.confidence,
249
- reason: consensus.reason,
250
- optimizedSignal,
251
- consensus,
252
- agentResults: results,
253
- context
254
- };
255
- }
256
-
257
- /**
258
- * Get engine status
259
- */
260
- getStatus() {
261
- return {
262
- totalAgents: this.agents.length,
263
- activeAgents: this.activeAgents.size,
264
- rateLimitedAgents: this.rateLimitedAgents.size,
265
- availableAgents: this.getActiveCount(),
266
- isAvailable: this.isAvailable(),
267
- agents: Array.from(this.activeAgents.values()).map(a => ({
268
- id: a.id,
269
- name: a.name,
270
- provider: a.provider,
271
- weight: a.weight,
272
- rateLimited: this.rateLimitedAgents.has(a.id)
273
- }))
274
- };
275
- }
276
-
277
- /**
278
- * Run pre-flight check on all agents
279
- * Verifies CLIProxy is running and all agents respond correctly
280
- * @returns {Promise<Object>} Pre-flight results
281
- */
282
- async preflightCheck() {
283
- const agents = Array.from(this.activeAgents.values());
284
- return runPreflightCheck(agents);
285
- }
286
- }
287
-
288
- /**
289
- * Create supervision engine from config
290
- */
291
- const createSupervisionEngine = (config) => {
292
- return new SupervisionEngine(config);
293
- };
294
-
295
- module.exports = {
296
- SupervisionEngine,
297
- createSupervisionEngine,
298
- // Re-export utilities
299
- buildMarketContext,
300
- formatContextForPrompt,
301
- parseAgentResponse,
302
- calculateConsensus,
303
- isApproved,
304
- applyOptimizations,
305
- // Health check
306
- runPreflightCheck,
307
- formatPreflightResults,
308
- getPreflightSummary
309
- };