-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmarket-analyzer.js
More file actions
529 lines (448 loc) Β· 17.5 KB
/
Copy pathmarket-analyzer.js
File metadata and controls
529 lines (448 loc) Β· 17.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
#!/usr/bin/env node
import { config } from './src/config/config.js';
import { KalshiAPI } from './src/api/kalshiApi.js';
import { KalshiWebSocket } from './src/websocket/kalshiWebSocket.js';
import logger from './src/utils/logger.js';
/**
* Market Data Analyzer
* Analyzes live market data to determine the best trading strategy
*/
class MarketAnalyzer {
constructor() {
this.api = new KalshiAPI();
this.websocket = new KalshiWebSocket();
// Data collection
this.marketData = new Map(); // marketId -> price history
this.analysisResults = new Map(); // marketId -> analysis
this.collectionTime = 300000; // 5 minutes of data collection
this.startTime = Date.now();
// Strategy recommendations
this.strategyScores = {
meanReversion: 0,
momentum: 0,
arbitrage: 0,
volatility: 0,
trendFollowing: 0
};
// Connect to WebSocket for live data
this.websocket.on('ticker', (tickerData) => {
this.processTicker(tickerData);
});
}
/**
* Process incoming ticker data
*/
processTicker(tickerData) {
try {
const { marketId, marketTicker, price, yesBid, yesAsk } = tickerData;
if (!price || !yesBid || !yesAsk) return;
// Initialize market data collection
if (!this.marketData.has(marketId)) {
this.marketData.set(marketId, {
ticker: marketTicker,
prices: [],
bids: [],
asks: [],
spreads: [],
timestamps: []
});
}
const market = this.marketData.get(marketId);
// Add new data point
market.prices.push(parseFloat(price));
market.bids.push(parseFloat(yesBid));
market.asks.push(parseFloat(yesAsk));
market.spreads.push(parseFloat(yesAsk) - parseFloat(yesBid));
market.timestamps.push(Date.now());
// Keep only last 100 data points
if (market.prices.length > 100) {
market.prices.shift();
market.bids.shift();
market.asks.shift();
market.spreads.shift();
market.timestamps.shift();
}
// Analyze when we have enough data
if (market.prices.length >= 20) {
this.analyzeMarket(marketId);
}
} catch (error) {
logger.error('Error processing ticker in analyzer', { error: error.message });
}
}
/**
* Analyze a specific market
*/
analyzeMarket(marketId) {
const market = this.marketData.get(marketId);
if (!market || market.prices.length < 20) return;
const analysis = {
ticker: market.ticker,
dataPoints: market.prices.length,
priceStats: this.calculatePriceStats(market.prices),
volatilityStats: this.calculateVolatilityStats(market.prices),
trendStats: this.calculateTrendStats(market.prices),
spreadStats: this.calculateSpreadStats(market.spreads),
strategyRecommendations: []
};
// Generate strategy recommendations
analysis.strategyRecommendations = this.generateStrategyRecommendations(analysis);
// Store analysis
this.analysisResults.set(marketId, analysis);
// Update global strategy scores
this.updateStrategyScores(analysis);
}
/**
* Calculate price statistics
*/
calculatePriceStats(prices) {
const sorted = [...prices].sort((a, b) => a - b);
const mean = prices.reduce((sum, p) => sum + p, 0) / prices.length;
const variance = prices.reduce((sum, p) => sum + Math.pow(p - mean, 2), 0) / prices.length;
const stdDev = Math.sqrt(variance);
return {
current: prices[prices.length - 1],
mean,
median: sorted[Math.floor(sorted.length / 2)],
min: sorted[0],
max: sorted[sorted.length - 1],
stdDev,
range: sorted[sorted.length - 1] - sorted[0],
coefficientOfVariation: stdDev / mean
};
}
/**
* Calculate volatility statistics
*/
calculateVolatilityStats(prices) {
if (prices.length < 2) return {};
const returns = [];
for (let i = 1; i < prices.length; i++) {
returns.push((prices[i] - prices[i-1]) / prices[i-1]);
}
const meanReturn = returns.reduce((sum, r) => sum + r, 0) / returns.length;
const returnVariance = returns.reduce((sum, r) => sum + Math.pow(r - meanReturn, 2), 0) / returns.length;
const returnStdDev = Math.sqrt(returnVariance);
// Calculate realized volatility (annualized)
const realizedVol = returnStdDev * Math.sqrt(252 * 24 * 60); // Assuming minute data
return {
returns,
meanReturn,
returnStdDev,
realizedVol,
maxGain: Math.max(...returns),
maxLoss: Math.min(...returns),
volatilityRegime: this.classifyVolatilityRegime(realizedVol)
};
}
/**
* Calculate trend statistics
*/
calculateTrendStats(prices) {
if (prices.length < 10) return {};
// Linear regression
const n = prices.length;
const x = Array.from({length: n}, (_, i) => i);
const y = prices;
const sumX = x.reduce((sum, xi) => sum + xi, 0);
const sumY = y.reduce((sum, yi) => sum + yi, 0);
const sumXY = x.reduce((sum, xi, i) => sum + xi * y[i], 0);
const sumX2 = x.reduce((sum, xi) => sum + xi * xi, 0);
const slope = (n * sumXY - sumX * sumY) / (n * sumX2 - sumX * sumX);
const intercept = (sumY - slope * sumX) / n;
// R-squared
const yMean = sumY / n;
const ssRes = y.reduce((sum, yi, i) => sum + Math.pow(yi - (slope * i + intercept), 2), 0);
const ssTot = y.reduce((sum, yi) => sum + Math.pow(yi - yMean, 2), 0);
const rSquared = 1 - (ssRes / ssTot);
// Trend strength classification
let trendStrength = 'weak';
if (rSquared > 0.7) trendStrength = 'strong';
else if (rSquared > 0.4) trendStrength = 'moderate';
// Trend direction
let trendDirection = 'sideways';
if (Math.abs(slope) > 0.001) {
trendDirection = slope > 0 ? 'uptrend' : 'downtrend';
}
return {
slope,
intercept,
rSquared,
trendStrength,
trendDirection,
priceChange: prices[prices.length - 1] - prices[0],
priceChangePercent: ((prices[prices.length - 1] - prices[0]) / prices[0]) * 100
};
}
/**
* Calculate spread statistics
*/
calculateSpreadStats(spreads) {
if (spreads.length === 0) return {};
const mean = spreads.reduce((sum, s) => sum + s, 0) / spreads.length;
const variance = spreads.reduce((sum, s) => sum + Math.pow(s - mean, 2), 0) / spreads.length;
const stdDev = Math.sqrt(variance);
return {
current: spreads[spreads.length - 1],
mean,
stdDev,
min: Math.min(...spreads),
max: Math.max(...spreads),
spreadVolatility: stdDev / mean
};
}
/**
* Classify volatility regime
*/
classifyVolatilityRegime(volatility) {
if (volatility < 0.1) return 'low';
if (volatility < 0.3) return 'medium';
if (volatility < 0.5) return 'high';
return 'extreme';
}
/**
* Generate strategy recommendations
*/
generateStrategyRecommendations(analysis) {
const recommendations = [];
const { priceStats, volatilityStats, trendStats, spreadStats } = analysis;
// Mean Reversion Strategy
let meanReversionScore = 0;
if (priceStats.coefficientOfVariation > 0.1) meanReversionScore += 2;
if (Math.abs(priceStats.current - priceStats.mean) > priceStats.stdDev) meanReversionScore += 2;
if (volatilityStats.volatilityRegime === 'medium') meanReversionScore += 1;
if (meanReversionScore > 0) {
recommendations.push({
strategy: 'Mean Reversion',
score: meanReversionScore,
reasoning: `Price ${priceStats.current > priceStats.mean ? 'above' : 'below'} mean by ${Math.abs(priceStats.current - priceStats.mean).toFixed(4)} (${(Math.abs(priceStats.current - priceStats.mean) / priceStats.stdDev).toFixed(2)} std dev)`,
action: priceStats.current > priceStats.mean ? 'SELL' : 'BUY'
});
}
// Momentum Strategy
let momentumScore = 0;
if (trendStats.trendStrength === 'strong') momentumScore += 3;
if (trendStats.rSquared > 0.6) momentumScore += 2;
if (Math.abs(trendStats.slope) > 0.001) momentumScore += 1;
if (momentumScore > 0) {
recommendations.push({
strategy: 'Momentum',
score: momentumScore,
reasoning: `${trendStats.trendDirection} with ${trendStats.trendStrength} trend (RΒ² = ${trendStats.rSquared.toFixed(3)})`,
action: trendStats.trendDirection === 'uptrend' ? 'BUY' : 'SELL'
});
}
// Volatility Strategy
let volatilityScore = 0;
if (volatilityStats.volatilityRegime === 'high' || volatilityStats.volatilityRegime === 'extreme') volatilityScore += 3;
if (priceStats.range > priceStats.mean * 0.1) volatilityScore += 2;
if (volatilityScore > 0) {
recommendations.push({
strategy: 'Volatility',
score: volatilityScore,
reasoning: `${volatilityStats.volatilityRegime} volatility regime with ${(priceStats.range / priceStats.mean * 100).toFixed(1)}% price range`,
action: 'BUY_STRADDLE' // Buy both sides for volatility
});
}
// Arbitrage Strategy
let arbitrageScore = 0;
if (spreadStats.spreadVolatility > 0.5) arbitrageScore += 2;
if (spreadStats.current > spreadStats.mean + spreadStats.stdDev) arbitrageScore += 1;
if (arbitrageScore > 0) {
recommendations.push({
strategy: 'Arbitrage',
score: arbitrageScore,
reasoning: `Wide spreads with ${spreadStats.spreadVolatility.toFixed(2)} spread volatility`,
action: 'EXPLOIT_SPREADS'
});
}
// Sort by score
recommendations.sort((a, b) => b.score - a.score);
return recommendations;
}
/**
* Update global strategy scores
*/
updateStrategyScores(analysis) {
analysis.strategyRecommendations.forEach(rec => {
switch (rec.strategy) {
case 'Mean Reversion':
this.strategyScores.meanReversion += rec.score;
break;
case 'Momentum':
this.strategyScores.momentum += rec.score;
break;
case 'Volatility':
this.strategyScores.volatility += rec.score;
break;
case 'Arbitrage':
this.strategyScores.arbitrage += rec.score;
break;
}
});
}
/**
* Start the market analysis
*/
async start() {
try {
console.log('π Starting Market Data Analysis...\n');
// Test API connection
console.log('π‘ Connecting to Kalshi API...');
await this.api.testConnection();
console.log('β
API connected successfully\n');
// Connect WebSocket with retry logic
console.log('π Connecting to Kalshi WebSocket...');
let websocketConnected = false;
let retryCount = 0;
const maxRetries = 3;
while (!websocketConnected && retryCount < maxRetries) {
try {
// Set a longer timeout for WebSocket connection
const connectionPromise = this.websocket.connect();
const timeoutPromise = new Promise((_, reject) =>
setTimeout(() => reject(new Error('Connection timeout')), 15000)
);
await Promise.race([connectionPromise, timeoutPromise]);
websocketConnected = true;
console.log('β
WebSocket connected successfully\n');
} catch (error) {
retryCount++;
console.log(`β οΈ WebSocket connection attempt ${retryCount} failed: ${error.message}`);
if (retryCount < maxRetries) {
console.log(`π Retrying in 2 seconds... (${retryCount}/${maxRetries})`);
await new Promise(resolve => setTimeout(resolve, 2000));
}
}
}
if (!websocketConnected) {
throw new Error(`WebSocket connection failed after ${maxRetries} attempts`);
}
// Subscribe to markets
console.log('π Discovering and subscribing to markets...');
await this.subscribeToMarkets();
console.log('β
Subscribed to market data\n');
console.log(`β±οΈ Collecting market data for ${this.collectionTime / 1000 / 60} minutes...`);
console.log('π Analyzing price patterns, volatility, and trends...');
console.log('π‘ Will recommend the best trading strategy based on data\n');
// Set up data collection timer
setTimeout(() => {
this.generateAnalysisReport();
this.stop();
}, this.collectionTime);
// Set up progress updates
const progressInterval = setInterval(() => {
const elapsed = Date.now() - this.startTime;
const remaining = this.collectionTime - elapsed;
const marketsAnalyzed = this.analysisResults.size;
console.log(`β³ Progress: ${(elapsed / this.collectionTime * 100).toFixed(1)}% | Markets Analyzed: ${marketsAnalyzed} | Time Remaining: ${Math.floor(remaining / 1000 / 60)}m ${Math.floor((remaining / 1000) % 60)}s`);
if (remaining <= 0) {
clearInterval(progressInterval);
}
}, 30000); // Every 30 seconds
} catch (error) {
console.error('β Failed to start market analysis:', error.message);
process.exit(1);
}
}
/**
* Subscribe to markets for analysis
*/
async subscribeToMarkets() {
try {
const markets = await this.api.getMarkets(1000);
if (markets.markets) {
const activeMarkets = markets.markets.filter(market =>
market.status === 'active'
).slice(0, 100); // Analyze top 100 active markets
console.log(`π Found ${activeMarkets.length} active markets for analysis`);
console.log(`π Football markets: ${activeMarkets.filter(m => m.ticker.includes('NFL')).length}`);
console.log(`π° Crypto markets: ${activeMarkets.filter(m => m.ticker.includes('BTC') || m.ticker.includes('ETH')).length}`);
console.log(`π Financial markets: ${activeMarkets.filter(m => m.ticker.includes('FED') || m.ticker.includes('NASDAQ')).length}\n`);
// Subscribe to general ticker feed
this.websocket.subscribe('ticker', {});
}
} catch (error) {
console.error('Failed to subscribe to markets:', error.message);
}
}
/**
* Generate comprehensive analysis report
*/
generateAnalysisReport() {
console.log('\nπ === MARKET ANALYSIS REPORT ===\n');
// Overall strategy recommendations
console.log('π― OVERALL STRATEGY RECOMMENDATIONS:');
const sortedStrategies = Object.entries(this.strategyScores)
.sort(([,a], [,b]) => b - a)
.map(([strategy, score]) => ({ strategy, score }));
sortedStrategies.forEach((strategy, index) => {
const emoji = index === 0 ? 'π₯' : index === 1 ? 'π₯' : index === 2 ? 'π₯' : 'π';
console.log(` ${emoji} ${strategy.strategy}: ${strategy.score} points`);
});
console.log(`\nπ RECOMMENDED STRATEGY: ${sortedStrategies[0].strategy.toUpperCase()}`);
// Market-specific insights
console.log('\nπ MARKET-SPECIFIC INSIGHTS:');
const topMarkets = Array.from(this.analysisResults.values())
.sort((a, b) => {
const aScore = a.strategyRecommendations[0]?.score || 0;
const bScore = b.strategyRecommendations[0]?.score || 0;
return bScore - aScore;
})
.slice(0, 10);
topMarkets.forEach((market, index) => {
if (market.strategyRecommendations.length > 0) {
const topRec = market.strategyRecommendations[0];
console.log(` ${index + 1}. ${market.ticker}: ${topRec.strategy} (${topRec.score} pts) - ${topRec.reasoning}`);
}
});
// Detailed statistics
console.log('\nπ MARKET STATISTICS:');
const totalMarkets = this.analysisResults.size;
const marketsWithSignals = Array.from(this.analysisResults.values())
.filter(m => m.strategyRecommendations.length > 0).length;
console.log(` Total Markets Analyzed: ${totalMarkets}`);
console.log(` Markets with Trading Signals: ${marketsWithSignals}`);
console.log(` Signal Rate: ${(marketsWithSignals / totalMarkets * 100).toFixed(1)}%`);
// Strategy breakdown
console.log('\nπ STRATEGY BREAKDOWN:');
const strategyCounts = {};
this.analysisResults.forEach(market => {
market.strategyRecommendations.forEach(rec => {
strategyCounts[rec.strategy] = (strategyCounts[rec.strategy] || 0) + 1;
});
});
Object.entries(strategyCounts)
.sort(([,a], [,b]) => b - a)
.forEach(([strategy, count]) => {
console.log(` ${strategy}: ${count} opportunities`);
});
console.log('\nπ‘ NEXT STEPS:');
console.log(` 1. Focus on ${sortedStrategies[0].strategy} strategy`);
console.log(` 2. Target markets with highest signal scores`);
console.log(` 3. Adjust parameters based on volatility analysis`);
console.log(` 4. Consider market-specific conditions`);
console.log('\nβββββββββββββββββββββββββββββββββββββββββββ\n');
}
/**
* Stop the analysis
*/
stop() {
console.log('π Stopping Market Analysis...\n');
if (this.websocket) {
this.websocket.disconnect();
}
console.log('π Market analysis completed. Goodbye!');
process.exit(0);
}
}
// Run the market analyzer
const analyzer = new MarketAnalyzer();
// Handle graceful shutdown
process.on('SIGINT', () => {
analyzer.stop();
});
analyzer.start().catch((error) => {
console.error('β Market analysis failed:', error.message);
process.exit(1);
});