hedgequantx 2.6.160 → 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.
- package/package.json +1 -1
- package/src/menus/ai-agent-connect.js +181 -0
- package/src/menus/ai-agent-models.js +219 -0
- package/src/menus/ai-agent-oauth.js +292 -0
- package/src/menus/ai-agent-ui.js +141 -0
- package/src/menus/ai-agent.js +88 -1489
- package/src/pages/algo/copy-engine.js +449 -0
- package/src/pages/algo/copy-trading.js +11 -543
- package/src/pages/algo/smart-logs-data.js +218 -0
- package/src/pages/algo/smart-logs.js +9 -214
- package/src/pages/algo/ui-constants.js +144 -0
- package/src/pages/algo/ui-summary.js +184 -0
- package/src/pages/algo/ui.js +42 -526
- package/src/pages/stats-calculations.js +191 -0
- package/src/pages/stats-ui.js +381 -0
- package/src/pages/stats.js +14 -507
- package/src/services/ai/client-analysis.js +194 -0
- package/src/services/ai/client-models.js +333 -0
- package/src/services/ai/client.js +6 -489
- package/src/services/ai/index.js +2 -257
- package/src/services/ai/proxy-install.js +249 -0
- package/src/services/ai/proxy-manager.js +29 -411
- package/src/services/ai/proxy-remote.js +161 -0
- package/src/services/ai/strategy-supervisor.js +10 -765
- package/src/services/ai/supervisor-data.js +195 -0
- package/src/services/ai/supervisor-optimize.js +215 -0
- package/src/services/ai/supervisor-sync.js +178 -0
- package/src/services/ai/supervisor-utils.js +158 -0
- package/src/services/ai/supervisor.js +50 -515
- package/src/services/ai/validation.js +250 -0
- package/src/services/hqx-server-events.js +110 -0
- package/src/services/hqx-server-handlers.js +217 -0
- package/src/services/hqx-server-latency.js +136 -0
- package/src/services/hqx-server.js +51 -403
- package/src/services/position-constants.js +28 -0
- package/src/services/position-manager.js +105 -554
- package/src/services/position-momentum.js +206 -0
- package/src/services/projectx/accounts.js +142 -0
- package/src/services/projectx/index.js +40 -289
- package/src/services/projectx/trading.js +180 -0
- package/src/services/rithmic/handlers.js +2 -208
- package/src/services/rithmic/index.js +32 -542
- package/src/services/rithmic/latency-tracker.js +182 -0
- package/src/services/rithmic/specs.js +146 -0
- package/src/services/rithmic/trade-history.js +254 -0
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Supervisor Data Management
|
|
3
|
+
* Handles persistence and data operations for AI learning
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
'use strict';
|
|
7
|
+
|
|
8
|
+
const fs = require('fs');
|
|
9
|
+
const path = require('path');
|
|
10
|
+
const os = require('os');
|
|
11
|
+
|
|
12
|
+
const DATA_DIR = path.join(os.homedir(), '.hqx');
|
|
13
|
+
const LEARNING_FILE = path.join(DATA_DIR, 'ai-learning.json');
|
|
14
|
+
|
|
15
|
+
const loadLearningData = () => {
|
|
16
|
+
try {
|
|
17
|
+
if (!fs.existsSync(DATA_DIR)) {
|
|
18
|
+
fs.mkdirSync(DATA_DIR, { recursive: true });
|
|
19
|
+
}
|
|
20
|
+
if (fs.existsSync(LEARNING_FILE)) {
|
|
21
|
+
const data = JSON.parse(fs.readFileSync(LEARNING_FILE, 'utf8'));
|
|
22
|
+
const oneMonthAgo = Date.now() - (31 * 24 * 60 * 60 * 1000);
|
|
23
|
+
const sessions = (data.sessions || []).filter(s =>
|
|
24
|
+
new Date(s.date).getTime() > oneMonthAgo
|
|
25
|
+
);
|
|
26
|
+
return {
|
|
27
|
+
winningPatterns: data.winningPatterns || [],
|
|
28
|
+
losingPatterns: data.losingPatterns || [],
|
|
29
|
+
optimizations: data.optimizations || [],
|
|
30
|
+
symbols: data.symbols || {},
|
|
31
|
+
sessions,
|
|
32
|
+
hourlyStats: data.hourlyStats || {},
|
|
33
|
+
dayOfWeekStats: data.dayOfWeekStats || {},
|
|
34
|
+
strategyProfile: data.strategyProfile || {
|
|
35
|
+
bestHours: [], worstHours: [], avgWinStreak: 0, avgLossStreak: 0, preferredConditions: null
|
|
36
|
+
},
|
|
37
|
+
totalSessions: data.totalSessions || 0,
|
|
38
|
+
totalTrades: data.totalTrades || 0,
|
|
39
|
+
totalWins: data.totalWins || 0,
|
|
40
|
+
totalLosses: data.totalLosses || 0,
|
|
41
|
+
lifetimePnL: data.lifetimePnL || 0,
|
|
42
|
+
lastUpdated: data.lastUpdated || null,
|
|
43
|
+
firstSession: data.firstSession || null
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
} catch (e) { /* Silent fail */ }
|
|
47
|
+
return {
|
|
48
|
+
winningPatterns: [], losingPatterns: [], optimizations: [], symbols: {}, sessions: [],
|
|
49
|
+
hourlyStats: {}, dayOfWeekStats: {},
|
|
50
|
+
strategyProfile: { bestHours: [], worstHours: [], avgWinStreak: 0, avgLossStreak: 0, preferredConditions: null },
|
|
51
|
+
totalSessions: 0, totalTrades: 0, totalWins: 0, totalLosses: 0, lifetimePnL: 0,
|
|
52
|
+
lastUpdated: null, firstSession: null
|
|
53
|
+
};
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
const getSymbolData = (symbolName) => {
|
|
57
|
+
const data = loadLearningData();
|
|
58
|
+
if (!data.symbols[symbolName]) {
|
|
59
|
+
return {
|
|
60
|
+
name: symbolName, levels: { support: [], resistance: [] },
|
|
61
|
+
patterns: { winning: [], losing: [] }, stats: { trades: 0, wins: 0, avgWin: 0, avgLoss: 0 }
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
return data.symbols[symbolName];
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
const recordPriceLevel = (symbolName, price, type, outcome) => {
|
|
68
|
+
const data = loadLearningData();
|
|
69
|
+
if (!data.symbols[symbolName]) {
|
|
70
|
+
data.symbols[symbolName] = {
|
|
71
|
+
name: symbolName, levels: { support: [], resistance: [] },
|
|
72
|
+
patterns: { winning: [], losing: [] }, stats: { trades: 0, wins: 0, avgWin: 0, avgLoss: 0 }
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
const symbol = data.symbols[symbolName];
|
|
76
|
+
const levelKey = type === 'support' ? 'support' : 'resistance';
|
|
77
|
+
const existingLevel = symbol.levels[levelKey].find(l => Math.abs(l.price - price) <= 0.5);
|
|
78
|
+
if (existingLevel) {
|
|
79
|
+
existingLevel.touches++;
|
|
80
|
+
existingLevel.lastTouched = Date.now();
|
|
81
|
+
if (outcome === 'held') existingLevel.held++;
|
|
82
|
+
else existingLevel.broken++;
|
|
83
|
+
} else {
|
|
84
|
+
symbol.levels[levelKey].push({
|
|
85
|
+
price, touches: 1, held: outcome === 'held' ? 1 : 0,
|
|
86
|
+
broken: outcome === 'broken' ? 1 : 0, firstSeen: Date.now(), lastTouched: Date.now()
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
symbol.levels[levelKey].sort((a, b) => b.touches - a.touches);
|
|
90
|
+
if (symbol.levels[levelKey].length > 20) {
|
|
91
|
+
symbol.levels[levelKey] = symbol.levels[levelKey].slice(0, 20);
|
|
92
|
+
}
|
|
93
|
+
saveLearningData(data);
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
const analyzeNearbyLevels = (symbolName, currentPrice) => {
|
|
97
|
+
const symbolData = getSymbolData(symbolName);
|
|
98
|
+
const nearby = { support: [], resistance: [] };
|
|
99
|
+
const range = 10;
|
|
100
|
+
symbolData.levels.support.forEach(level => {
|
|
101
|
+
if (Math.abs(level.price - currentPrice) <= range) {
|
|
102
|
+
nearby.support.push({ ...level, distance: currentPrice - level.price });
|
|
103
|
+
}
|
|
104
|
+
});
|
|
105
|
+
symbolData.levels.resistance.forEach(level => {
|
|
106
|
+
if (Math.abs(level.price - currentPrice) <= range) {
|
|
107
|
+
nearby.resistance.push({ ...level, distance: level.price - currentPrice });
|
|
108
|
+
}
|
|
109
|
+
});
|
|
110
|
+
nearby.support.sort((a, b) => a.distance - b.distance);
|
|
111
|
+
nearby.resistance.sort((a, b) => a.distance - b.distance);
|
|
112
|
+
return nearby;
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
const saveLearningData = (data) => {
|
|
116
|
+
try {
|
|
117
|
+
if (!fs.existsSync(DATA_DIR)) {
|
|
118
|
+
fs.mkdirSync(DATA_DIR, { recursive: true });
|
|
119
|
+
}
|
|
120
|
+
data.lastUpdated = new Date().toISOString();
|
|
121
|
+
fs.writeFileSync(LEARNING_FILE, JSON.stringify(data, null, 2));
|
|
122
|
+
return true;
|
|
123
|
+
} catch (e) {
|
|
124
|
+
return false;
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
const buildStrategyProfile = (hourlyStats, dayOfWeekStats, sessions) => {
|
|
129
|
+
const profile = { bestHours: [], worstHours: [], avgWinStreak: 0, avgLossStreak: 0, preferredConditions: null };
|
|
130
|
+
const hourlyArray = Object.entries(hourlyStats)
|
|
131
|
+
.filter(([_, stats]) => stats.trades >= 5)
|
|
132
|
+
.map(([hour, stats]) => ({ hour: parseInt(hour), winRate: stats.wins / stats.trades, trades: stats.trades, pnl: stats.pnl }));
|
|
133
|
+
hourlyArray.sort((a, b) => b.winRate - a.winRate);
|
|
134
|
+
profile.bestHours = hourlyArray.slice(0, 3).map(h => ({ hour: h.hour, winRate: Math.round(h.winRate * 100) }));
|
|
135
|
+
profile.worstHours = hourlyArray.slice(-3).reverse().map(h => ({ hour: h.hour, winRate: Math.round(h.winRate * 100) }));
|
|
136
|
+
if (sessions.length >= 5) {
|
|
137
|
+
const winStreaks = sessions.map(s => s.maxWinStreak || 0).filter(Boolean);
|
|
138
|
+
const lossStreaks = sessions.map(s => s.maxLossStreak || 0).filter(Boolean);
|
|
139
|
+
profile.avgWinStreak = winStreaks.length > 0 ? winStreaks.reduce((a, b) => a + b, 0) / winStreaks.length : 0;
|
|
140
|
+
profile.avgLossStreak = lossStreaks.length > 0 ? lossStreaks.reduce((a, b) => a + b, 0) / lossStreaks.length : 0;
|
|
141
|
+
}
|
|
142
|
+
return profile;
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
const mergePatterns = (existing, current, maxCount) => {
|
|
146
|
+
const merged = [...existing];
|
|
147
|
+
current.forEach(pattern => {
|
|
148
|
+
const similar = merged.find(p => p.timeContext?.hour === pattern.timeContext?.hour && p.direction === pattern.direction);
|
|
149
|
+
if (!similar) merged.push(pattern);
|
|
150
|
+
});
|
|
151
|
+
merged.sort((a, b) => (b.timestamp || 0) - (a.timestamp || 0));
|
|
152
|
+
return merged.slice(0, maxCount);
|
|
153
|
+
};
|
|
154
|
+
|
|
155
|
+
const mergeLevels = (existing, current, maxCount) => {
|
|
156
|
+
const merged = [...existing];
|
|
157
|
+
current.forEach(level => {
|
|
158
|
+
const similar = merged.find(l => Math.abs(l.price - level.price) <= 0.5);
|
|
159
|
+
if (similar) {
|
|
160
|
+
similar.touches += level.touches || 1;
|
|
161
|
+
similar.held += level.held || 0;
|
|
162
|
+
similar.broken += level.broken || 0;
|
|
163
|
+
similar.lastTouched = Math.max(similar.lastTouched || 0, level.lastTouched || Date.now());
|
|
164
|
+
} else {
|
|
165
|
+
merged.push(level);
|
|
166
|
+
}
|
|
167
|
+
});
|
|
168
|
+
merged.sort((a, b) => b.touches - a.touches);
|
|
169
|
+
return merged.slice(0, maxCount);
|
|
170
|
+
};
|
|
171
|
+
|
|
172
|
+
const clearLearningData = () => {
|
|
173
|
+
try {
|
|
174
|
+
if (fs.existsSync(LEARNING_FILE)) {
|
|
175
|
+
fs.unlinkSync(LEARNING_FILE);
|
|
176
|
+
}
|
|
177
|
+
return true;
|
|
178
|
+
} catch (e) {
|
|
179
|
+
return false;
|
|
180
|
+
}
|
|
181
|
+
};
|
|
182
|
+
|
|
183
|
+
module.exports = {
|
|
184
|
+
DATA_DIR,
|
|
185
|
+
LEARNING_FILE,
|
|
186
|
+
loadLearningData,
|
|
187
|
+
getSymbolData,
|
|
188
|
+
recordPriceLevel,
|
|
189
|
+
analyzeNearbyLevels,
|
|
190
|
+
saveLearningData,
|
|
191
|
+
buildStrategyProfile,
|
|
192
|
+
mergePatterns,
|
|
193
|
+
mergeLevels,
|
|
194
|
+
clearLearningData
|
|
195
|
+
};
|
|
@@ -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
|
+
};
|