hedgequantx 2.6.161 → 2.6.162

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 (42) hide show
  1. package/package.json +1 -1
  2. package/src/menus/ai-agent-connect.js +181 -0
  3. package/src/menus/ai-agent-models.js +219 -0
  4. package/src/menus/ai-agent-oauth.js +292 -0
  5. package/src/menus/ai-agent-ui.js +141 -0
  6. package/src/menus/ai-agent.js +88 -1489
  7. package/src/pages/algo/copy-engine.js +449 -0
  8. package/src/pages/algo/copy-trading.js +11 -543
  9. package/src/pages/algo/smart-logs-data.js +218 -0
  10. package/src/pages/algo/smart-logs.js +9 -214
  11. package/src/pages/algo/ui-constants.js +144 -0
  12. package/src/pages/algo/ui-summary.js +184 -0
  13. package/src/pages/algo/ui.js +42 -526
  14. package/src/pages/stats-calculations.js +191 -0
  15. package/src/pages/stats-ui.js +381 -0
  16. package/src/pages/stats.js +14 -507
  17. package/src/services/ai/client-analysis.js +194 -0
  18. package/src/services/ai/client-models.js +333 -0
  19. package/src/services/ai/client.js +6 -489
  20. package/src/services/ai/index.js +2 -257
  21. package/src/services/ai/proxy-install.js +249 -0
  22. package/src/services/ai/proxy-manager.js +29 -411
  23. package/src/services/ai/proxy-remote.js +161 -0
  24. package/src/services/ai/supervisor-optimize.js +215 -0
  25. package/src/services/ai/supervisor-sync.js +178 -0
  26. package/src/services/ai/supervisor.js +50 -515
  27. package/src/services/ai/validation.js +250 -0
  28. package/src/services/hqx-server-events.js +110 -0
  29. package/src/services/hqx-server-handlers.js +217 -0
  30. package/src/services/hqx-server-latency.js +136 -0
  31. package/src/services/hqx-server.js +51 -403
  32. package/src/services/position-constants.js +28 -0
  33. package/src/services/position-manager.js +105 -554
  34. package/src/services/position-momentum.js +206 -0
  35. package/src/services/projectx/accounts.js +142 -0
  36. package/src/services/projectx/index.js +40 -289
  37. package/src/services/projectx/trading.js +180 -0
  38. package/src/services/rithmic/handlers.js +2 -208
  39. package/src/services/rithmic/index.js +32 -542
  40. package/src/services/rithmic/latency-tracker.js +182 -0
  41. package/src/services/rithmic/specs.js +146 -0
  42. package/src/services/rithmic/trade-history.js +254 -0
@@ -0,0 +1,161 @@
1
+ /**
2
+ * @fileoverview Remote OAuth for CLIProxyAPI
3
+ *
4
+ * For VPS/Server users without browser access
5
+ * Uses cli.hedgequantx.com as OAuth relay
6
+ */
7
+
8
+ const https = require('https');
9
+
10
+ const REMOTE_OAUTH_URL = 'https://cli.hedgequantx.com';
11
+
12
+ /**
13
+ * Make HTTPS request
14
+ */
15
+ const httpsRequest = (url, options, body = null) => {
16
+ return new Promise((resolve, reject) => {
17
+ const parsedUrl = new URL(url);
18
+ const req = https.request({
19
+ hostname: parsedUrl.hostname,
20
+ port: 443,
21
+ path: parsedUrl.pathname + parsedUrl.search,
22
+ method: options.method || 'GET',
23
+ headers: options.headers || {}
24
+ }, (res) => {
25
+ let data = '';
26
+ res.on('data', chunk => data += chunk);
27
+ res.on('end', () => {
28
+ try {
29
+ resolve(JSON.parse(data));
30
+ } catch (e) {
31
+ resolve(data);
32
+ }
33
+ });
34
+ });
35
+
36
+ req.on('error', reject);
37
+ req.on('timeout', () => {
38
+ req.destroy();
39
+ reject(new Error('Request timeout'));
40
+ });
41
+
42
+ if (body) {
43
+ req.write(typeof body === 'string' ? body : JSON.stringify(body));
44
+ }
45
+ req.end();
46
+ });
47
+ };
48
+
49
+ /**
50
+ * Create Remote OAuth session
51
+ * @param {string} provider - Provider ID (anthropic, openai, gemini)
52
+ * @returns {Promise<{sessionId: string, authUrl: string}>}
53
+ */
54
+ const createRemoteSession = async (provider) => {
55
+ const response = await httpsRequest(
56
+ `${REMOTE_OAUTH_URL}/oauth/session/create`,
57
+ {
58
+ method: 'POST',
59
+ headers: { 'Content-Type': 'application/json' }
60
+ },
61
+ JSON.stringify({ provider })
62
+ );
63
+
64
+ if (response.error) {
65
+ throw new Error(response.error);
66
+ }
67
+
68
+ return {
69
+ sessionId: response.sessionId,
70
+ authUrl: response.authUrl
71
+ };
72
+ };
73
+
74
+ /**
75
+ * Poll Remote OAuth session status
76
+ * @param {string} sessionId - Session ID from createRemoteSession
77
+ * @returns {Promise<{status: string, error?: string}>}
78
+ */
79
+ const pollRemoteSession = async (sessionId) => {
80
+ const response = await httpsRequest(
81
+ `${REMOTE_OAUTH_URL}/oauth/session/${sessionId}/status`,
82
+ { method: 'GET' }
83
+ );
84
+ return response;
85
+ };
86
+
87
+ /**
88
+ * Get tokens from Remote OAuth session
89
+ * @param {string} sessionId - Session ID
90
+ * @returns {Promise<{provider: string, tokens: Object}>}
91
+ */
92
+ const getRemoteTokens = async (sessionId) => {
93
+ const response = await httpsRequest(
94
+ `${REMOTE_OAUTH_URL}/oauth/session/${sessionId}/tokens`,
95
+ { method: 'GET' }
96
+ );
97
+
98
+ if (response.error) {
99
+ throw new Error(response.error);
100
+ }
101
+
102
+ return response;
103
+ };
104
+
105
+ /**
106
+ * Wait for Remote OAuth to complete
107
+ * @param {string} sessionId - Session ID
108
+ * @param {number} timeoutMs - Timeout in milliseconds
109
+ * @param {Function} onStatus - Status callback
110
+ * @returns {Promise<{provider: string, tokens: Object}>}
111
+ */
112
+ const waitForRemoteAuth = async (sessionId, timeoutMs = 300000, onStatus = () => {}) => {
113
+ const startTime = Date.now();
114
+
115
+ while (Date.now() - startTime < timeoutMs) {
116
+ const status = await pollRemoteSession(sessionId);
117
+
118
+ if (status.status === 'success') {
119
+ return await getRemoteTokens(sessionId);
120
+ } else if (status.status === 'error') {
121
+ throw new Error(status.error || 'Authentication failed');
122
+ }
123
+
124
+ onStatus('Waiting for authorization...');
125
+ await new Promise(resolve => setTimeout(resolve, 2000));
126
+ }
127
+
128
+ throw new Error('Authentication timeout');
129
+ };
130
+
131
+ /**
132
+ * Detect if we're running on a server (no display/browser)
133
+ * @returns {boolean}
134
+ */
135
+ const isServerEnvironment = () => {
136
+ if (process.env.SSH_CONNECTION || process.env.SSH_CLIENT) return true;
137
+ if (process.env.DISPLAY === undefined && process.platform === 'linux') return true;
138
+ if (process.env.TERM === 'dumb') return true;
139
+ if (process.env.HQX_REMOTE_OAUTH === '1') return true;
140
+ return false;
141
+ };
142
+
143
+ /**
144
+ * Detect if browser can be opened
145
+ * @returns {boolean}
146
+ */
147
+ const canOpenBrowser = () => {
148
+ if (process.platform === 'darwin' || process.platform === 'win32') return true;
149
+ if (process.env.DISPLAY) return true;
150
+ return false;
151
+ };
152
+
153
+ module.exports = {
154
+ createRemoteSession,
155
+ pollRemoteSession,
156
+ getRemoteTokens,
157
+ waitForRemoteAuth,
158
+ isServerEnvironment,
159
+ canOpenBrowser,
160
+ REMOTE_OAUTH_URL
161
+ };
@@ -0,0 +1,215 @@
1
+ /**
2
+ * @fileoverview AI Supervisor - Optimization & Market Advice
3
+ *
4
+ * Methods for AI-driven strategy optimization and market analysis
5
+ * In CONSENSUS mode, only unanimous suggestions are applied
6
+ */
7
+
8
+ const { analyzePerformance, getMarketAdvice: getMarketAdviceFromClient } = require('./client');
9
+
10
+ /**
11
+ * Request strategy optimization from all agents
12
+ * @param {Map} supervisionSessions - Sessions map
13
+ * @param {Object} performanceData - Strategy performance data
14
+ * @returns {Promise<Object|null>} Optimization suggestions
15
+ */
16
+ const requestOptimization = async (supervisionSessions, performanceData) => {
17
+ if (supervisionSessions.size === 0) return null;
18
+
19
+ const allSessions = Array.from(supervisionSessions.values());
20
+ const suggestions = [];
21
+
22
+ // Get optimization suggestions from each agent
23
+ for (const session of allSessions) {
24
+ try {
25
+ const suggestion = await analyzePerformance(session.agent, performanceData);
26
+ if (suggestion) {
27
+ suggestions.push({
28
+ agentId: session.agentId,
29
+ agentName: session.agent.name,
30
+ ...suggestion
31
+ });
32
+ }
33
+ } catch (e) {
34
+ // Silent fail for individual agent
35
+ }
36
+ }
37
+
38
+ if (suggestions.length === 0) return null;
39
+
40
+ // If single agent, return its suggestion
41
+ if (suggestions.length === 1) {
42
+ return {
43
+ mode: 'INDIVIDUAL',
44
+ ...suggestions[0]
45
+ };
46
+ }
47
+
48
+ // CONSENSUS MODE: Find common optimizations
49
+ const consensusOptimizations = [];
50
+ const allOptimizations = suggestions.flatMap(s => s.optimizations || []);
51
+
52
+ // Group by parameter name
53
+ const paramGroups = {};
54
+ for (const opt of allOptimizations) {
55
+ if (!opt.param) continue;
56
+ if (!paramGroups[opt.param]) {
57
+ paramGroups[opt.param] = [];
58
+ }
59
+ paramGroups[opt.param].push(opt);
60
+ }
61
+
62
+ // Find unanimous suggestions (all agents agree on direction)
63
+ for (const [param, opts] of Object.entries(paramGroups)) {
64
+ if (opts.length === suggestions.length) {
65
+ // All agents suggested this param - check if they agree on direction
66
+ const directions = opts.map(o => {
67
+ const current = parseFloat(o.current) || 0;
68
+ const suggested = parseFloat(o.suggested) || 0;
69
+ return suggested > current ? 'increase' : suggested < current ? 'decrease' : 'same';
70
+ });
71
+
72
+ const allSame = directions.every(d => d === directions[0]);
73
+ if (allSame && directions[0] !== 'same') {
74
+ // Unanimous - use average of suggested values
75
+ const avgSuggested = opts.reduce((sum, o) => sum + (parseFloat(o.suggested) || 0), 0) / opts.length;
76
+ consensusOptimizations.push({
77
+ param,
78
+ current: opts[0].current,
79
+ suggested: avgSuggested.toFixed(2),
80
+ reason: `Unanimous (${suggestions.length} agents agree)`,
81
+ direction: directions[0]
82
+ });
83
+ }
84
+ }
85
+ }
86
+
87
+ // Calculate average confidence
88
+ const avgConfidence = Math.round(
89
+ suggestions.reduce((sum, s) => sum + (s.confidence || 0), 0) / suggestions.length
90
+ );
91
+
92
+ // Determine consensus market condition
93
+ const conditions = suggestions.map(s => s.marketCondition).filter(Boolean);
94
+ const conditionCounts = {};
95
+ for (const c of conditions) {
96
+ conditionCounts[c] = (conditionCounts[c] || 0) + 1;
97
+ }
98
+ const consensusCondition = Object.entries(conditionCounts)
99
+ .sort((a, b) => b[1] - a[1])[0]?.[0] || 'unknown';
100
+
101
+ return {
102
+ mode: 'CONSENSUS',
103
+ agentCount: suggestions.length,
104
+ isUnanimous: consensusOptimizations.length > 0,
105
+ optimizations: consensusOptimizations,
106
+ marketCondition: consensusCondition,
107
+ confidence: avgConfidence,
108
+ individualSuggestions: suggestions
109
+ };
110
+ };
111
+
112
+ /**
113
+ * Get real-time market advice from all agents
114
+ * @param {Map} supervisionSessions - Sessions map
115
+ * @param {Object} marketData - Current market data
116
+ * @returns {Promise<Object|null>} Market advice (consensus)
117
+ */
118
+ const getMarketAdvice = async (supervisionSessions, marketData) => {
119
+ if (supervisionSessions.size === 0) return null;
120
+
121
+ const allSessions = Array.from(supervisionSessions.values());
122
+ const advices = [];
123
+
124
+ // Get advice from each agent
125
+ for (const session of allSessions) {
126
+ try {
127
+ const advice = await getMarketAdviceFromClient(session.agent, marketData);
128
+ if (advice) {
129
+ advices.push({
130
+ agentId: session.agentId,
131
+ agentName: session.agent.name,
132
+ ...advice
133
+ });
134
+ }
135
+ } catch (e) {
136
+ // Silent fail
137
+ }
138
+ }
139
+
140
+ if (advices.length === 0) return null;
141
+
142
+ // Single agent
143
+ if (advices.length === 1) {
144
+ return {
145
+ mode: 'INDIVIDUAL',
146
+ ...advices[0]
147
+ };
148
+ }
149
+
150
+ // CONSENSUS: All agents must agree on action
151
+ const actions = advices.map(a => a.action);
152
+ const allSameAction = actions.every(a => a === actions[0]);
153
+
154
+ if (allSameAction) {
155
+ // Unanimous action - average the size multiplier
156
+ const avgMultiplier = advices.reduce((sum, a) => sum + (a.sizeMultiplier || 1), 0) / advices.length;
157
+ const avgConfidence = Math.round(advices.reduce((sum, a) => sum + (a.confidence || 0), 0) / advices.length);
158
+
159
+ return {
160
+ mode: 'CONSENSUS',
161
+ isUnanimous: true,
162
+ action: actions[0],
163
+ sizeMultiplier: Math.round(avgMultiplier * 100) / 100,
164
+ confidence: avgConfidence,
165
+ reason: `${advices.length} agents unanimous`,
166
+ agentCount: advices.length
167
+ };
168
+ } else {
169
+ // Agents disagree - be conservative
170
+ return {
171
+ mode: 'CONSENSUS',
172
+ isUnanimous: false,
173
+ action: 'CAUTIOUS',
174
+ sizeMultiplier: 0.5,
175
+ confidence: 0,
176
+ reason: 'Agents disagree - reducing exposure',
177
+ agentCount: advices.length,
178
+ votes: actions.reduce((acc, a) => { acc[a] = (acc[a] || 0) + 1; return acc; }, {})
179
+ };
180
+ }
181
+ };
182
+
183
+ /**
184
+ * Apply optimization to strategy
185
+ * @param {Object} strategy - Strategy instance
186
+ * @param {Object} optimization - Optimization to apply
187
+ * @returns {boolean} Success
188
+ */
189
+ const applyOptimization = (strategy, optimization) => {
190
+ if (!strategy || !optimization) return false;
191
+
192
+ try {
193
+ // Check if strategy has optimization method
194
+ if (typeof strategy.applyOptimization === 'function') {
195
+ strategy.applyOptimization(optimization);
196
+ return true;
197
+ }
198
+
199
+ // Fallback: try to set individual parameters
200
+ if (typeof strategy.setParameter === 'function' && optimization.param) {
201
+ strategy.setParameter(optimization.param, optimization.suggested);
202
+ return true;
203
+ }
204
+
205
+ return false;
206
+ } catch (e) {
207
+ return false;
208
+ }
209
+ };
210
+
211
+ module.exports = {
212
+ requestOptimization,
213
+ getMarketAdvice,
214
+ applyOptimization,
215
+ };
@@ -0,0 +1,178 @@
1
+ /**
2
+ * @fileoverview AI Supervisor - Strategy Sync
3
+ *
4
+ * Methods to sync AI supervision with trading strategy in real-time
5
+ * Agents receive the same data as the strategy
6
+ */
7
+
8
+ /**
9
+ * Feed market tick to all sessions
10
+ * @param {Map} supervisionSessions - Sessions map
11
+ * @param {Object} tick - Market tick { price, bid, ask, volume, timestamp }
12
+ */
13
+ const feedTick = (supervisionSessions, tick) => {
14
+ if (supervisionSessions.size === 0) return;
15
+
16
+ for (const [agentId, session] of supervisionSessions.entries()) {
17
+ if (!session.marketData) {
18
+ session.marketData = { ticks: [], lastTick: null };
19
+ }
20
+ session.marketData.lastTick = tick;
21
+ session.marketData.ticks.push(tick);
22
+
23
+ // Keep only last 1000 ticks to prevent memory bloat
24
+ if (session.marketData.ticks.length > 1000) {
25
+ session.marketData.ticks = session.marketData.ticks.slice(-1000);
26
+ }
27
+ }
28
+ };
29
+
30
+ /**
31
+ * Feed strategy signal to all sessions
32
+ * @param {Map} supervisionSessions - Sessions map
33
+ * @param {Object} signal - Strategy signal
34
+ */
35
+ const feedSignal = (supervisionSessions, signal) => {
36
+ if (supervisionSessions.size === 0) return;
37
+
38
+ const signalData = {
39
+ timestamp: Date.now(),
40
+ direction: signal.direction,
41
+ entry: signal.entry,
42
+ stopLoss: signal.stopLoss,
43
+ takeProfit: signal.takeProfit,
44
+ confidence: signal.confidence
45
+ };
46
+
47
+ for (const [agentId, session] of supervisionSessions.entries()) {
48
+ if (!session.signals) {
49
+ session.signals = [];
50
+ }
51
+ session.signals.push(signalData);
52
+
53
+ // Keep only last 100 signals
54
+ if (session.signals.length > 100) {
55
+ session.signals = session.signals.slice(-100);
56
+ }
57
+ }
58
+ };
59
+
60
+ /**
61
+ * Feed trade execution to all sessions
62
+ * @param {Map} supervisionSessions - Sessions map
63
+ * @param {Object} trade - Trade data
64
+ */
65
+ const feedTrade = (supervisionSessions, trade) => {
66
+ if (supervisionSessions.size === 0) return;
67
+
68
+ const tradeData = {
69
+ timestamp: Date.now(),
70
+ side: trade.side,
71
+ qty: trade.qty,
72
+ price: trade.price,
73
+ pnl: trade.pnl,
74
+ symbol: trade.symbol
75
+ };
76
+
77
+ for (const [agentId, session] of supervisionSessions.entries()) {
78
+ if (!session.trades) {
79
+ session.trades = [];
80
+ }
81
+ session.trades.push(tradeData);
82
+ }
83
+ };
84
+
85
+ /**
86
+ * Update current position for all sessions
87
+ * @param {Map} supervisionSessions - Sessions map
88
+ * @param {Object} position - Position data
89
+ */
90
+ const updatePosition = (supervisionSessions, position) => {
91
+ if (supervisionSessions.size === 0) return;
92
+
93
+ for (const [agentId, session] of supervisionSessions.entries()) {
94
+ session.currentPosition = {
95
+ timestamp: Date.now(),
96
+ qty: position.qty,
97
+ side: position.side,
98
+ entryPrice: position.entryPrice,
99
+ pnl: position.pnl
100
+ };
101
+ }
102
+ };
103
+
104
+ /**
105
+ * Update P&L for all sessions
106
+ * @param {Map} supervisionSessions - Sessions map
107
+ * @param {number} pnl - Current session P&L
108
+ * @param {number} balance - Account balance
109
+ */
110
+ const updatePnL = (supervisionSessions, pnl, balance) => {
111
+ if (supervisionSessions.size === 0) return;
112
+
113
+ for (const [agentId, session] of supervisionSessions.entries()) {
114
+ session.currentPnL = pnl;
115
+ session.currentBalance = balance;
116
+ }
117
+ };
118
+
119
+ /**
120
+ * Check if agents recommend intervention
121
+ * @param {Map} supervisionSessions - Sessions map
122
+ * @param {Function} getConsensus - Function to get consensus
123
+ * @returns {Object} Intervention check result
124
+ */
125
+ const checkIntervention = (supervisionSessions, getConsensus) => {
126
+ if (supervisionSessions.size === 0) {
127
+ return { shouldContinue: true, action: 'CONTINUE', reason: 'No AI supervision active' };
128
+ }
129
+
130
+ const consensus = getConsensus();
131
+
132
+ if (consensus && consensus.isUnanimous) {
133
+ if (consensus.action === 'PAUSE' || consensus.action === 'STOP') {
134
+ return { shouldContinue: false, action: consensus.action, reason: 'AI agents recommend pause' };
135
+ }
136
+ if (consensus.action === 'REDUCE_SIZE') {
137
+ return { shouldContinue: true, action: 'REDUCE_SIZE', reason: 'AI agents recommend reducing size' };
138
+ }
139
+ } else if (consensus && !consensus.isUnanimous) {
140
+ return { shouldContinue: false, action: 'HOLD', reason: 'AI agents disagree - waiting for consensus' };
141
+ }
142
+
143
+ return { shouldContinue: true, action: 'CONTINUE', reason: 'AI supervision active' };
144
+ };
145
+
146
+ /**
147
+ * Get real-time sync status
148
+ * @param {Map} supervisionSessions - Sessions map
149
+ * @returns {Object} Sync status
150
+ */
151
+ const getSyncStatus = (supervisionSessions) => {
152
+ if (supervisionSessions.size === 0) {
153
+ return { synced: false, agents: 0 };
154
+ }
155
+
156
+ const firstSession = supervisionSessions.values().next().value;
157
+
158
+ return {
159
+ synced: true,
160
+ agents: supervisionSessions.size,
161
+ lastTick: firstSession?.marketData?.lastTick?.timestamp || null,
162
+ tickCount: firstSession?.marketData?.ticks?.length || 0,
163
+ signalCount: firstSession?.signals?.length || 0,
164
+ tradeCount: firstSession?.trades?.length || 0,
165
+ currentPnL: firstSession?.currentPnL || 0,
166
+ currentPosition: firstSession?.currentPosition || null
167
+ };
168
+ };
169
+
170
+ module.exports = {
171
+ feedTick,
172
+ feedSignal,
173
+ feedTrade,
174
+ updatePosition,
175
+ updatePnL,
176
+ checkIntervention,
177
+ getSyncStatus,
178
+ };