hedgequantx 2.6.159 → 2.6.161
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.
|
@@ -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,158 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Supervisor Utility Functions
|
|
3
|
+
* Pure functions for market analysis - no state dependencies
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
'use strict';
|
|
7
|
+
|
|
8
|
+
const calculateTrendStrength = (ticks) => {
|
|
9
|
+
if (!ticks || ticks.length < 20) return { strength: 0, direction: 'unknown' };
|
|
10
|
+
const prices = ticks.map(t => t.price).filter(Boolean);
|
|
11
|
+
if (prices.length < 20) return { strength: 0, direction: 'unknown' };
|
|
12
|
+
const shortTerm = prices.slice(-20);
|
|
13
|
+
const shortChange = shortTerm[shortTerm.length - 1] - shortTerm[0];
|
|
14
|
+
const mediumTerm = prices.slice(-50);
|
|
15
|
+
const mediumChange = mediumTerm[mediumTerm.length - 1] - mediumTerm[0];
|
|
16
|
+
const aligned = (shortChange > 0 && mediumChange > 0) || (shortChange < 0 && mediumChange < 0);
|
|
17
|
+
const avgRange = Math.abs(Math.max(...prices) - Math.min(...prices)) || 1;
|
|
18
|
+
return {
|
|
19
|
+
strength: aligned ? Math.min(1, (Math.abs(shortChange) + Math.abs(mediumChange)) / avgRange) : 0,
|
|
20
|
+
direction: mediumChange > 0 ? 'bullish' : mediumChange < 0 ? 'bearish' : 'neutral',
|
|
21
|
+
shortTermDirection: shortChange > 0 ? 'up' : shortChange < 0 ? 'down' : 'flat',
|
|
22
|
+
aligned
|
|
23
|
+
};
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
const calculateRecentRange = (ticks, count) => {
|
|
27
|
+
if (!ticks || ticks.length === 0) return { high: 0, low: 0, range: 0 };
|
|
28
|
+
const prices = ticks.slice(-count).map(t => t.price).filter(Boolean);
|
|
29
|
+
if (prices.length === 0) return { high: 0, low: 0, range: 0 };
|
|
30
|
+
const high = Math.max(...prices);
|
|
31
|
+
const low = Math.min(...prices);
|
|
32
|
+
return { high, low, range: high - low };
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
const calculatePriceVelocity = (ticks, count) => {
|
|
36
|
+
if (!ticks || ticks.length < 2) return { velocity: 0, acceleration: 0 };
|
|
37
|
+
const recentTicks = ticks.slice(-count);
|
|
38
|
+
if (recentTicks.length < 2) return { velocity: 0, acceleration: 0 };
|
|
39
|
+
const prices = recentTicks.map(t => t.price).filter(Boolean);
|
|
40
|
+
if (prices.length < 2) return { velocity: 0, acceleration: 0 };
|
|
41
|
+
const totalChange = prices[prices.length - 1] - prices[0];
|
|
42
|
+
const velocity = totalChange / prices.length;
|
|
43
|
+
const midPoint = Math.floor(prices.length / 2);
|
|
44
|
+
const firstHalfVelocity = (prices[midPoint] - prices[0]) / midPoint;
|
|
45
|
+
const secondHalfVelocity = (prices[prices.length - 1] - prices[midPoint]) / (prices.length - midPoint);
|
|
46
|
+
const acceleration = secondHalfVelocity - firstHalfVelocity;
|
|
47
|
+
return { velocity, acceleration };
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
const getMarketSession = (hour) => {
|
|
51
|
+
if (hour >= 9 && hour < 12) return 'morning';
|
|
52
|
+
if (hour >= 12 && hour < 14) return 'midday';
|
|
53
|
+
if (hour >= 14 && hour < 16) return 'afternoon';
|
|
54
|
+
if (hour >= 16 && hour < 18) return 'close';
|
|
55
|
+
if (hour >= 18 || hour < 9) return 'overnight';
|
|
56
|
+
return 'unknown';
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
const getMinutesSinceOpen = (hour) => {
|
|
60
|
+
const now = new Date();
|
|
61
|
+
const currentMinutes = hour * 60 + now.getMinutes();
|
|
62
|
+
const openMinutes = 9 * 60 + 30;
|
|
63
|
+
return Math.max(0, currentMinutes - openMinutes);
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
const analyzePriceLevelInteraction = (entryPrice, ticks) => {
|
|
67
|
+
if (!ticks || ticks.length < 20) return null;
|
|
68
|
+
const prices = ticks.map(t => t.price).filter(Boolean);
|
|
69
|
+
if (prices.length < 20) return null;
|
|
70
|
+
const high = Math.max(...prices);
|
|
71
|
+
const low = Math.min(...prices);
|
|
72
|
+
const range = high - low || 1;
|
|
73
|
+
const positionInRange = (entryPrice - low) / range;
|
|
74
|
+
let levelType = 'middle';
|
|
75
|
+
if (positionInRange > 0.8) levelType = 'near_high';
|
|
76
|
+
else if (positionInRange < 0.2) levelType = 'near_low';
|
|
77
|
+
else if (positionInRange > 0.6) levelType = 'upper_middle';
|
|
78
|
+
else if (positionInRange < 0.4) levelType = 'lower_middle';
|
|
79
|
+
return {
|
|
80
|
+
positionInRange: Math.round(positionInRange * 100) / 100,
|
|
81
|
+
distanceToHigh: high - entryPrice,
|
|
82
|
+
distanceToLow: entryPrice - low,
|
|
83
|
+
recentHigh: high,
|
|
84
|
+
recentLow: low,
|
|
85
|
+
levelType
|
|
86
|
+
};
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
const determineLevelType = (price, ticks) => {
|
|
90
|
+
if (!ticks || ticks.length < 10) return 'unknown';
|
|
91
|
+
const prices = ticks.map(t => t.price).filter(Boolean);
|
|
92
|
+
if (prices.length < 10) return 'unknown';
|
|
93
|
+
const high = Math.max(...prices);
|
|
94
|
+
const low = Math.min(...prices);
|
|
95
|
+
const tickSize = 0.25;
|
|
96
|
+
if (Math.abs(price - high) <= tickSize * 4) return 'resistance';
|
|
97
|
+
if (Math.abs(price - low) <= tickSize * 4) return 'support';
|
|
98
|
+
if (price > high) return 'breakout_high';
|
|
99
|
+
if (price < low) return 'breakout_low';
|
|
100
|
+
return 'middle';
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
const analyzePriceAction = (ticks) => {
|
|
104
|
+
if (!ticks || ticks.length < 2) return { trend: 'unknown', strength: 0 };
|
|
105
|
+
const prices = ticks.map(t => t.price).filter(Boolean);
|
|
106
|
+
if (prices.length < 2) return { trend: 'unknown', strength: 0 };
|
|
107
|
+
const first = prices[0];
|
|
108
|
+
const last = prices[prices.length - 1];
|
|
109
|
+
const change = last - first;
|
|
110
|
+
const range = Math.max(...prices) - Math.min(...prices);
|
|
111
|
+
return {
|
|
112
|
+
trend: change > 0 ? 'up' : change < 0 ? 'down' : 'flat',
|
|
113
|
+
strength: range > 0 ? Math.abs(change) / range : 0,
|
|
114
|
+
range,
|
|
115
|
+
change
|
|
116
|
+
};
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
const analyzeVolume = (ticks) => {
|
|
120
|
+
if (!ticks || ticks.length === 0) return { total: 0, avg: 0, trend: 'unknown' };
|
|
121
|
+
const volumes = ticks.map(t => t.volume || 0);
|
|
122
|
+
const total = volumes.reduce((a, b) => a + b, 0);
|
|
123
|
+
const avg = total / volumes.length;
|
|
124
|
+
const mid = Math.floor(volumes.length / 2);
|
|
125
|
+
const firstHalf = volumes.slice(0, mid).reduce((a, b) => a + b, 0);
|
|
126
|
+
const secondHalf = volumes.slice(mid).reduce((a, b) => a + b, 0);
|
|
127
|
+
return {
|
|
128
|
+
total,
|
|
129
|
+
avg,
|
|
130
|
+
trend: secondHalf > firstHalf * 1.2 ? 'increasing' : secondHalf < firstHalf * 0.8 ? 'decreasing' : 'stable'
|
|
131
|
+
};
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
const calculateVolatility = (ticks) => {
|
|
135
|
+
if (!ticks || ticks.length < 2) return 0;
|
|
136
|
+
const prices = ticks.map(t => t.price).filter(Boolean);
|
|
137
|
+
if (prices.length < 2) return 0;
|
|
138
|
+
const returns = [];
|
|
139
|
+
for (let i = 1; i < prices.length; i++) {
|
|
140
|
+
returns.push((prices[i] - prices[i-1]) / prices[i-1]);
|
|
141
|
+
}
|
|
142
|
+
const mean = returns.reduce((a, b) => a + b, 0) / returns.length;
|
|
143
|
+
const variance = returns.reduce((sum, r) => sum + Math.pow(r - mean, 2), 0) / returns.length;
|
|
144
|
+
return Math.sqrt(variance);
|
|
145
|
+
};
|
|
146
|
+
|
|
147
|
+
module.exports = {
|
|
148
|
+
calculateTrendStrength,
|
|
149
|
+
calculateRecentRange,
|
|
150
|
+
calculatePriceVelocity,
|
|
151
|
+
getMarketSession,
|
|
152
|
+
getMinutesSinceOpen,
|
|
153
|
+
analyzePriceLevelInteraction,
|
|
154
|
+
determineLevelType,
|
|
155
|
+
analyzePriceAction,
|
|
156
|
+
analyzeVolume,
|
|
157
|
+
calculateVolatility
|
|
158
|
+
};
|