fixparser-plugin-mcp 9.1.7-57d70bb1 → 9.1.7-5d282a9e
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/build/cjs/MCPLocal.js +1991 -51
- package/build/cjs/MCPLocal.js.map +4 -4
- package/build/cjs/MCPRemote.js +2079 -138
- package/build/cjs/MCPRemote.js.map +4 -4
- package/build/cjs/index.js +3232 -0
- package/build/cjs/index.js.map +7 -0
- package/build/esm/MCPLocal.mjs +1991 -51
- package/build/esm/MCPLocal.mjs.map +4 -4
- package/build/esm/MCPRemote.mjs +2079 -138
- package/build/esm/MCPRemote.mjs.map +4 -4
- package/build/esm/index.mjs +3194 -0
- package/build/esm/index.mjs.map +7 -0
- package/build-examples/cjs/example_mcp_local.js +9 -7
- package/build-examples/cjs/example_mcp_local.js.map +4 -4
- package/build-examples/cjs/example_mcp_remote.js +18 -0
- package/build-examples/cjs/example_mcp_remote.js.map +7 -0
- package/build-examples/esm/example_mcp_local.mjs +9 -7
- package/build-examples/esm/example_mcp_local.mjs.map +4 -4
- package/build-examples/esm/example_mcp_remote.mjs +18 -0
- package/build-examples/esm/example_mcp_remote.mjs.map +7 -0
- package/package.json +7 -7
- package/types/MCPBase.d.ts +0 -49
- package/types/MCPLocal.d.ts +0 -40
- package/types/MCPRemote.d.ts +0 -66
- package/types/PluginOptions.d.ts +0 -6
- package/types/index.d.ts +0 -3
- package/types/schemas/index.d.ts +0 -15
- package/types/schemas/schemas.d.ts +0 -168
- package/types/tools/index.d.ts +0 -17
- package/types/tools/marketData.d.ts +0 -40
- package/types/tools/order.d.ts +0 -12
- package/types/tools/parse.d.ts +0 -5
- package/types/tools/parseToJSON.d.ts +0 -5
- package/types/utils/messageHandler.d.ts +0 -18
package/build/cjs/MCPLocal.js
CHANGED
|
@@ -163,7 +163,7 @@ var toolSchemas = {
|
|
|
163
163
|
}
|
|
164
164
|
},
|
|
165
165
|
executeOrder: {
|
|
166
|
-
description: "Executes a verified order. verifyOrder must be called before executeOrder.
|
|
166
|
+
description: "Executes a verified order. verifyOrder must be called before executeOrder.",
|
|
167
167
|
schema: {
|
|
168
168
|
type: "object",
|
|
169
169
|
properties: {
|
|
@@ -307,19 +307,1631 @@ var toolSchemas = {
|
|
|
307
307
|
},
|
|
308
308
|
required: ["symbol"]
|
|
309
309
|
}
|
|
310
|
+
},
|
|
311
|
+
technicalAnalysis: {
|
|
312
|
+
description: "Performs comprehensive technical analysis on market data for a given symbol, including indicators like SMA, EMA, RSI, Bollinger Bands, and trading signals",
|
|
313
|
+
schema: {
|
|
314
|
+
type: "object",
|
|
315
|
+
properties: {
|
|
316
|
+
symbol: {
|
|
317
|
+
type: "string",
|
|
318
|
+
description: "The trading symbol to analyze (e.g., AAPL, MSFT, EURUSD)"
|
|
319
|
+
}
|
|
320
|
+
},
|
|
321
|
+
required: ["symbol"]
|
|
322
|
+
}
|
|
310
323
|
}
|
|
311
324
|
};
|
|
312
325
|
|
|
326
|
+
// src/tools/analytics.ts
|
|
327
|
+
function sum(numbers) {
|
|
328
|
+
return numbers.reduce((acc, val) => acc + val, 0);
|
|
329
|
+
}
|
|
330
|
+
var TechnicalAnalyzer = class {
|
|
331
|
+
prices;
|
|
332
|
+
volumes;
|
|
333
|
+
highs;
|
|
334
|
+
lows;
|
|
335
|
+
constructor(data) {
|
|
336
|
+
this.prices = data.map((d) => d.trade > 0 ? d.trade : d.midPrice);
|
|
337
|
+
this.volumes = data.map((d) => d.volume);
|
|
338
|
+
this.highs = data.map((d) => d.tradingSessionHighPrice > 0 ? d.tradingSessionHighPrice : d.trade);
|
|
339
|
+
this.lows = data.map((d) => d.tradingSessionLowPrice > 0 ? d.tradingSessionLowPrice : d.trade);
|
|
340
|
+
}
|
|
341
|
+
// Calculate Simple Moving Average
|
|
342
|
+
calculateSMA(data, period) {
|
|
343
|
+
const sma = [];
|
|
344
|
+
for (let i = period - 1; i < data.length; i++) {
|
|
345
|
+
const sum2 = data.slice(i - period + 1, i + 1).reduce((a, b) => a + b, 0);
|
|
346
|
+
sma.push(sum2 / period);
|
|
347
|
+
}
|
|
348
|
+
return sma;
|
|
349
|
+
}
|
|
350
|
+
// Calculate Exponential Moving Average
|
|
351
|
+
calculateEMA(data, period) {
|
|
352
|
+
const multiplier = 2 / (period + 1);
|
|
353
|
+
const ema = [data[0]];
|
|
354
|
+
for (let i = 1; i < data.length; i++) {
|
|
355
|
+
ema.push(data[i] * multiplier + ema[i - 1] * (1 - multiplier));
|
|
356
|
+
}
|
|
357
|
+
return ema;
|
|
358
|
+
}
|
|
359
|
+
// Calculate RSI
|
|
360
|
+
calculateRSI(data, period = 14) {
|
|
361
|
+
if (data.length < period + 1) return [];
|
|
362
|
+
const changes = [];
|
|
363
|
+
for (let i = 1; i < data.length; i++) {
|
|
364
|
+
changes.push(data[i] - data[i - 1]);
|
|
365
|
+
}
|
|
366
|
+
const gains = changes.map((change) => change > 0 ? change : 0);
|
|
367
|
+
const losses = changes.map((change) => change < 0 ? Math.abs(change) : 0);
|
|
368
|
+
let avgGain = gains.slice(0, period).reduce((a, b) => a + b, 0) / period;
|
|
369
|
+
let avgLoss = losses.slice(0, period).reduce((a, b) => a + b, 0) / period;
|
|
370
|
+
const rsi = [];
|
|
371
|
+
for (let i = period; i < changes.length; i++) {
|
|
372
|
+
const rs = avgGain / avgLoss;
|
|
373
|
+
rsi.push(100 - 100 / (1 + rs));
|
|
374
|
+
avgGain = (avgGain * (period - 1) + gains[i]) / period;
|
|
375
|
+
avgLoss = (avgLoss * (period - 1) + losses[i]) / period;
|
|
376
|
+
}
|
|
377
|
+
return rsi;
|
|
378
|
+
}
|
|
379
|
+
// Calculate Bollinger Bands
|
|
380
|
+
calculateBollingerBands(data, period = 20, stdDev = 2) {
|
|
381
|
+
if (data.length < period) return [];
|
|
382
|
+
const sma = this.calculateSMA(data, period);
|
|
383
|
+
const bands = [];
|
|
384
|
+
for (let i = 0; i < sma.length; i++) {
|
|
385
|
+
const dataSlice = data.slice(i, i + period);
|
|
386
|
+
const mean = sma[i];
|
|
387
|
+
const variance = dataSlice.reduce((sum2, price) => sum2 + (price - mean) ** 2, 0) / period;
|
|
388
|
+
const standardDeviation = Math.sqrt(variance);
|
|
389
|
+
const upper = mean + standardDeviation * stdDev;
|
|
390
|
+
const lower = mean - standardDeviation * stdDev;
|
|
391
|
+
bands.push({
|
|
392
|
+
upper,
|
|
393
|
+
middle: mean,
|
|
394
|
+
lower,
|
|
395
|
+
bandwidth: (upper - lower) / mean * 100,
|
|
396
|
+
percentB: (data[i] - lower) / (upper - lower) * 100
|
|
397
|
+
});
|
|
398
|
+
}
|
|
399
|
+
return bands;
|
|
400
|
+
}
|
|
401
|
+
// Calculate maximum drawdown
|
|
402
|
+
calculateMaxDrawdown(prices) {
|
|
403
|
+
let maxPrice = prices[0];
|
|
404
|
+
let maxDrawdown = 0;
|
|
405
|
+
for (let i = 1; i < prices.length; i++) {
|
|
406
|
+
if (prices[i] > maxPrice) {
|
|
407
|
+
maxPrice = prices[i];
|
|
408
|
+
}
|
|
409
|
+
const drawdown = (maxPrice - prices[i]) / maxPrice;
|
|
410
|
+
if (drawdown > maxDrawdown) {
|
|
411
|
+
maxDrawdown = drawdown;
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
return maxDrawdown;
|
|
415
|
+
}
|
|
416
|
+
// Calculate Average True Range (ATR)
|
|
417
|
+
calculateAtr(prices, highs, lows) {
|
|
418
|
+
if (prices.length < 2) return [];
|
|
419
|
+
const trueRanges = [];
|
|
420
|
+
for (let i = 1; i < prices.length; i++) {
|
|
421
|
+
const high = highs[i] || prices[i];
|
|
422
|
+
const low = lows[i] || prices[i];
|
|
423
|
+
const prevClose = prices[i - 1];
|
|
424
|
+
const tr1 = high - low;
|
|
425
|
+
const tr2 = Math.abs(high - prevClose);
|
|
426
|
+
const tr3 = Math.abs(low - prevClose);
|
|
427
|
+
trueRanges.push(Math.max(tr1, tr2, tr3));
|
|
428
|
+
}
|
|
429
|
+
const atr = [];
|
|
430
|
+
if (trueRanges.length >= 14) {
|
|
431
|
+
let sum2 = trueRanges.slice(0, 14).reduce((a, b) => a + b, 0);
|
|
432
|
+
atr.push(sum2 / 14);
|
|
433
|
+
for (let i = 14; i < trueRanges.length; i++) {
|
|
434
|
+
sum2 = sum2 - trueRanges[i - 14] + trueRanges[i];
|
|
435
|
+
atr.push(sum2 / 14);
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
return atr;
|
|
439
|
+
}
|
|
440
|
+
// Calculate maximum consecutive losses
|
|
441
|
+
calculateMaxConsecutiveLosses(prices) {
|
|
442
|
+
let maxConsecutive = 0;
|
|
443
|
+
let currentConsecutive = 0;
|
|
444
|
+
for (let i = 1; i < prices.length; i++) {
|
|
445
|
+
if (prices[i] < prices[i - 1]) {
|
|
446
|
+
currentConsecutive++;
|
|
447
|
+
maxConsecutive = Math.max(maxConsecutive, currentConsecutive);
|
|
448
|
+
} else {
|
|
449
|
+
currentConsecutive = 0;
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
return maxConsecutive;
|
|
453
|
+
}
|
|
454
|
+
// Calculate win rate
|
|
455
|
+
calculateWinRate(prices) {
|
|
456
|
+
let wins = 0;
|
|
457
|
+
let total = 0;
|
|
458
|
+
for (let i = 1; i < prices.length; i++) {
|
|
459
|
+
if (prices[i] !== prices[i - 1]) {
|
|
460
|
+
total++;
|
|
461
|
+
if (prices[i] > prices[i - 1]) {
|
|
462
|
+
wins++;
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
return total > 0 ? wins / total : 0;
|
|
467
|
+
}
|
|
468
|
+
// Calculate profit factor
|
|
469
|
+
calculateProfitFactor(prices) {
|
|
470
|
+
let grossProfit = 0;
|
|
471
|
+
let grossLoss = 0;
|
|
472
|
+
for (let i = 1; i < prices.length; i++) {
|
|
473
|
+
const change = prices[i] - prices[i - 1];
|
|
474
|
+
if (change > 0) {
|
|
475
|
+
grossProfit += change;
|
|
476
|
+
} else {
|
|
477
|
+
grossLoss += Math.abs(change);
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
return grossLoss > 0 ? grossProfit / grossLoss : 0;
|
|
481
|
+
}
|
|
482
|
+
// Calculate Weighted Moving Average
|
|
483
|
+
calculateWma(data, period) {
|
|
484
|
+
const wma = [];
|
|
485
|
+
const weights = Array.from({ length: period }, (_, i) => i + 1);
|
|
486
|
+
const weightSum = weights.reduce((a, b) => a + b, 0);
|
|
487
|
+
for (let i = period - 1; i < data.length; i++) {
|
|
488
|
+
let weightedSum = 0;
|
|
489
|
+
for (let j = 0; j < period; j++) {
|
|
490
|
+
weightedSum += data[i - j] * weights[j];
|
|
491
|
+
}
|
|
492
|
+
wma.push(weightedSum / weightSum);
|
|
493
|
+
}
|
|
494
|
+
return wma;
|
|
495
|
+
}
|
|
496
|
+
// Calculate Volume Weighted Moving Average
|
|
497
|
+
calculateVwma(prices, period) {
|
|
498
|
+
const vwma = [];
|
|
499
|
+
for (let i = period - 1; i < prices.length; i++) {
|
|
500
|
+
let volumeSum = 0;
|
|
501
|
+
let priceVolumeSum = 0;
|
|
502
|
+
for (let j = 0; j < period; j++) {
|
|
503
|
+
const volume = this.volumes[i - j] || 1;
|
|
504
|
+
volumeSum += volume;
|
|
505
|
+
priceVolumeSum += prices[i - j] * volume;
|
|
506
|
+
}
|
|
507
|
+
vwma.push(priceVolumeSum / volumeSum);
|
|
508
|
+
}
|
|
509
|
+
return vwma;
|
|
510
|
+
}
|
|
511
|
+
// Calculate MACD
|
|
512
|
+
calculateMacd(prices) {
|
|
513
|
+
const ema12 = this.calculateEMA(prices, 12);
|
|
514
|
+
const ema26 = this.calculateEMA(prices, 26);
|
|
515
|
+
const macd = [];
|
|
516
|
+
const macdLine = [];
|
|
517
|
+
for (let i = 0; i < Math.min(ema12.length, ema26.length); i++) {
|
|
518
|
+
macdLine.push(ema12[i] - ema26[i]);
|
|
519
|
+
}
|
|
520
|
+
const signalLine = this.calculateEMA(macdLine, 9);
|
|
521
|
+
for (let i = 0; i < Math.min(macdLine.length, signalLine.length); i++) {
|
|
522
|
+
macd.push({
|
|
523
|
+
macd: macdLine[i],
|
|
524
|
+
signal: signalLine[i],
|
|
525
|
+
histogram: macdLine[i] - signalLine[i]
|
|
526
|
+
});
|
|
527
|
+
}
|
|
528
|
+
return macd;
|
|
529
|
+
}
|
|
530
|
+
// Calculate ADX (Average Directional Index)
|
|
531
|
+
calculateAdx(prices, highs, lows) {
|
|
532
|
+
if (prices.length < 14) return [];
|
|
533
|
+
const period = 14;
|
|
534
|
+
const adx = [];
|
|
535
|
+
const trueRanges = [];
|
|
536
|
+
const plusDM = [];
|
|
537
|
+
const minusDM = [];
|
|
538
|
+
trueRanges.push(highs[0] - lows[0]);
|
|
539
|
+
plusDM.push(0);
|
|
540
|
+
minusDM.push(0);
|
|
541
|
+
for (let i = 1; i < prices.length; i++) {
|
|
542
|
+
const high = highs[i] || prices[i];
|
|
543
|
+
const low = lows[i] || prices[i];
|
|
544
|
+
const prevHigh = highs[i - 1] || prices[i - 1];
|
|
545
|
+
const prevLow = lows[i - 1] || prices[i - 1];
|
|
546
|
+
const prevClose = prices[i - 1];
|
|
547
|
+
const tr1 = high - low;
|
|
548
|
+
const tr2 = Math.abs(high - prevClose);
|
|
549
|
+
const tr3 = Math.abs(low - prevClose);
|
|
550
|
+
trueRanges.push(Math.max(tr1, tr2, tr3));
|
|
551
|
+
const upMove = high - prevHigh;
|
|
552
|
+
const downMove = prevLow - low;
|
|
553
|
+
if (upMove > downMove && upMove > 0) {
|
|
554
|
+
plusDM.push(upMove);
|
|
555
|
+
minusDM.push(0);
|
|
556
|
+
} else if (downMove > upMove && downMove > 0) {
|
|
557
|
+
plusDM.push(0);
|
|
558
|
+
minusDM.push(downMove);
|
|
559
|
+
} else {
|
|
560
|
+
plusDM.push(0);
|
|
561
|
+
minusDM.push(0);
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
const smoothedTR = [];
|
|
565
|
+
const smoothedPlusDM = [];
|
|
566
|
+
const smoothedMinusDM = [];
|
|
567
|
+
let sumTR = 0;
|
|
568
|
+
let sumPlusDM = 0;
|
|
569
|
+
let sumMinusDM = 0;
|
|
570
|
+
for (let i = 0; i < period; i++) {
|
|
571
|
+
sumTR += trueRanges[i];
|
|
572
|
+
sumPlusDM += plusDM[i];
|
|
573
|
+
sumMinusDM += minusDM[i];
|
|
574
|
+
}
|
|
575
|
+
smoothedTR.push(sumTR);
|
|
576
|
+
smoothedPlusDM.push(sumPlusDM);
|
|
577
|
+
smoothedMinusDM.push(sumMinusDM);
|
|
578
|
+
for (let i = period; i < trueRanges.length; i++) {
|
|
579
|
+
const newTR = smoothedTR[smoothedTR.length - 1] - smoothedTR[smoothedTR.length - 1] / period + trueRanges[i];
|
|
580
|
+
const newPlusDM = smoothedPlusDM[smoothedPlusDM.length - 1] - smoothedPlusDM[smoothedPlusDM.length - 1] / period + plusDM[i];
|
|
581
|
+
const newMinusDM = smoothedMinusDM[smoothedMinusDM.length - 1] - smoothedMinusDM[smoothedMinusDM.length - 1] / period + minusDM[i];
|
|
582
|
+
smoothedTR.push(newTR);
|
|
583
|
+
smoothedPlusDM.push(newPlusDM);
|
|
584
|
+
smoothedMinusDM.push(newMinusDM);
|
|
585
|
+
}
|
|
586
|
+
const plusDI = [];
|
|
587
|
+
const minusDI = [];
|
|
588
|
+
for (let i = 0; i < smoothedTR.length; i++) {
|
|
589
|
+
plusDI.push(smoothedPlusDM[i] / smoothedTR[i] * 100);
|
|
590
|
+
minusDI.push(smoothedMinusDM[i] / smoothedTR[i] * 100);
|
|
591
|
+
}
|
|
592
|
+
const dx = [];
|
|
593
|
+
for (let i = 0; i < plusDI.length; i++) {
|
|
594
|
+
const diSum = plusDI[i] + minusDI[i];
|
|
595
|
+
const diDiff = Math.abs(plusDI[i] - minusDI[i]);
|
|
596
|
+
dx.push(diSum > 0 ? diDiff / diSum * 100 : 0);
|
|
597
|
+
}
|
|
598
|
+
if (dx.length < period) return [];
|
|
599
|
+
let sumDX = 0;
|
|
600
|
+
for (let i = 0; i < period; i++) {
|
|
601
|
+
sumDX += dx[i];
|
|
602
|
+
}
|
|
603
|
+
adx.push(sumDX / period);
|
|
604
|
+
for (let i = period; i < dx.length; i++) {
|
|
605
|
+
const newADX = adx[adx.length - 1] - adx[adx.length - 1] / period + dx[i];
|
|
606
|
+
adx.push(newADX);
|
|
607
|
+
}
|
|
608
|
+
return adx;
|
|
609
|
+
}
|
|
610
|
+
// Calculate DMI (Directional Movement Index)
|
|
611
|
+
calculateDmi(prices, highs, lows) {
|
|
612
|
+
if (prices.length < 14) return [];
|
|
613
|
+
const period = 14;
|
|
614
|
+
const dmi = [];
|
|
615
|
+
const trueRanges = [];
|
|
616
|
+
const plusDM = [];
|
|
617
|
+
const minusDM = [];
|
|
618
|
+
trueRanges.push(highs[0] - lows[0]);
|
|
619
|
+
plusDM.push(0);
|
|
620
|
+
minusDM.push(0);
|
|
621
|
+
for (let i = 1; i < prices.length; i++) {
|
|
622
|
+
const high = highs[i] || prices[i];
|
|
623
|
+
const low = lows[i] || prices[i];
|
|
624
|
+
const prevHigh = highs[i - 1] || prices[i - 1];
|
|
625
|
+
const prevLow = lows[i - 1] || prices[i - 1];
|
|
626
|
+
const prevClose = prices[i - 1];
|
|
627
|
+
const tr1 = high - low;
|
|
628
|
+
const tr2 = Math.abs(high - prevClose);
|
|
629
|
+
const tr3 = Math.abs(low - prevClose);
|
|
630
|
+
trueRanges.push(Math.max(tr1, tr2, tr3));
|
|
631
|
+
const upMove = high - prevHigh;
|
|
632
|
+
const downMove = prevLow - low;
|
|
633
|
+
if (upMove > downMove && upMove > 0) {
|
|
634
|
+
plusDM.push(upMove);
|
|
635
|
+
minusDM.push(0);
|
|
636
|
+
} else if (downMove > upMove && downMove > 0) {
|
|
637
|
+
plusDM.push(0);
|
|
638
|
+
minusDM.push(downMove);
|
|
639
|
+
} else {
|
|
640
|
+
plusDM.push(0);
|
|
641
|
+
minusDM.push(0);
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
const smoothedTR = [];
|
|
645
|
+
const smoothedPlusDM = [];
|
|
646
|
+
const smoothedMinusDM = [];
|
|
647
|
+
let sumTR = 0;
|
|
648
|
+
let sumPlusDM = 0;
|
|
649
|
+
let sumMinusDM = 0;
|
|
650
|
+
for (let i = 0; i < period; i++) {
|
|
651
|
+
sumTR += trueRanges[i];
|
|
652
|
+
sumPlusDM += plusDM[i];
|
|
653
|
+
sumMinusDM += minusDM[i];
|
|
654
|
+
}
|
|
655
|
+
smoothedTR.push(sumTR);
|
|
656
|
+
smoothedPlusDM.push(sumPlusDM);
|
|
657
|
+
smoothedMinusDM.push(sumMinusDM);
|
|
658
|
+
for (let i = period; i < trueRanges.length; i++) {
|
|
659
|
+
const newTR = smoothedTR[smoothedTR.length - 1] - smoothedTR[smoothedTR.length - 1] / period + trueRanges[i];
|
|
660
|
+
const newPlusDM = smoothedPlusDM[smoothedPlusDM.length - 1] - smoothedPlusDM[smoothedPlusDM.length - 1] / period + plusDM[i];
|
|
661
|
+
const newMinusDM = smoothedMinusDM[smoothedMinusDM.length - 1] - smoothedMinusDM[smoothedMinusDM.length - 1] / period + minusDM[i];
|
|
662
|
+
smoothedTR.push(newTR);
|
|
663
|
+
smoothedPlusDM.push(newPlusDM);
|
|
664
|
+
smoothedMinusDM.push(newMinusDM);
|
|
665
|
+
}
|
|
666
|
+
const plusDI = [];
|
|
667
|
+
const minusDI = [];
|
|
668
|
+
for (let i = 0; i < smoothedTR.length; i++) {
|
|
669
|
+
plusDI.push(smoothedPlusDM[i] / smoothedTR[i] * 100);
|
|
670
|
+
minusDI.push(smoothedMinusDM[i] / smoothedTR[i] * 100);
|
|
671
|
+
}
|
|
672
|
+
const dx = [];
|
|
673
|
+
for (let i = 0; i < plusDI.length; i++) {
|
|
674
|
+
const diSum = plusDI[i] + minusDI[i];
|
|
675
|
+
const diDiff = Math.abs(plusDI[i] - minusDI[i]);
|
|
676
|
+
dx.push(diSum > 0 ? diDiff / diSum * 100 : 0);
|
|
677
|
+
}
|
|
678
|
+
if (dx.length < period) return [];
|
|
679
|
+
const adx = [];
|
|
680
|
+
let sumDX = 0;
|
|
681
|
+
for (let i = 0; i < period; i++) {
|
|
682
|
+
sumDX += dx[i];
|
|
683
|
+
}
|
|
684
|
+
adx.push(sumDX / period);
|
|
685
|
+
for (let i = period; i < dx.length; i++) {
|
|
686
|
+
const newADX = adx[adx.length - 1] - adx[adx.length - 1] / period + dx[i];
|
|
687
|
+
adx.push(newADX);
|
|
688
|
+
}
|
|
689
|
+
for (let i = 0; i < adx.length; i++) {
|
|
690
|
+
dmi.push({
|
|
691
|
+
plusDI: plusDI[i + period - 1] || 0,
|
|
692
|
+
minusDI: minusDI[i + period - 1] || 0,
|
|
693
|
+
adx: adx[i]
|
|
694
|
+
});
|
|
695
|
+
}
|
|
696
|
+
return dmi;
|
|
697
|
+
}
|
|
698
|
+
// Calculate Ichimoku Cloud
|
|
699
|
+
calculateIchimoku(prices, highs, lows) {
|
|
700
|
+
if (prices.length < 52) return [];
|
|
701
|
+
const ichimoku = [];
|
|
702
|
+
const tenkanSen = [];
|
|
703
|
+
for (let i = 8; i < prices.length; i++) {
|
|
704
|
+
const periodHigh = Math.max(...highs.slice(i - 8, i + 1));
|
|
705
|
+
const periodLow = Math.min(...lows.slice(i - 8, i + 1));
|
|
706
|
+
tenkanSen.push((periodHigh + periodLow) / 2);
|
|
707
|
+
}
|
|
708
|
+
const kijunSen = [];
|
|
709
|
+
for (let i = 25; i < prices.length; i++) {
|
|
710
|
+
const periodHigh = Math.max(...highs.slice(i - 25, i + 1));
|
|
711
|
+
const periodLow = Math.min(...lows.slice(i - 25, i + 1));
|
|
712
|
+
kijunSen.push((periodHigh + periodLow) / 2);
|
|
713
|
+
}
|
|
714
|
+
const senkouSpanA = [];
|
|
715
|
+
for (let i = 0; i < Math.min(tenkanSen.length, kijunSen.length); i++) {
|
|
716
|
+
senkouSpanA.push((tenkanSen[i] + kijunSen[i]) / 2);
|
|
717
|
+
}
|
|
718
|
+
const senkouSpanB = [];
|
|
719
|
+
for (let i = 51; i < prices.length; i++) {
|
|
720
|
+
const periodHigh = Math.max(...highs.slice(i - 51, i + 1));
|
|
721
|
+
const periodLow = Math.min(...lows.slice(i - 51, i + 1));
|
|
722
|
+
senkouSpanB.push((periodHigh + periodLow) / 2);
|
|
723
|
+
}
|
|
724
|
+
const chikouSpan = [];
|
|
725
|
+
for (let i = 26; i < prices.length; i++) {
|
|
726
|
+
chikouSpan.push(prices[i - 26]);
|
|
727
|
+
}
|
|
728
|
+
const minLength = Math.min(
|
|
729
|
+
tenkanSen.length,
|
|
730
|
+
kijunSen.length,
|
|
731
|
+
senkouSpanA.length,
|
|
732
|
+
senkouSpanB.length,
|
|
733
|
+
chikouSpan.length
|
|
734
|
+
);
|
|
735
|
+
for (let i = 0; i < minLength; i++) {
|
|
736
|
+
ichimoku.push({
|
|
737
|
+
tenkan: tenkanSen[i],
|
|
738
|
+
kijun: kijunSen[i],
|
|
739
|
+
senkouA: senkouSpanA[i],
|
|
740
|
+
senkouB: senkouSpanB[i],
|
|
741
|
+
chikou: chikouSpan[i]
|
|
742
|
+
});
|
|
743
|
+
}
|
|
744
|
+
return ichimoku;
|
|
745
|
+
}
|
|
746
|
+
// Calculate Parabolic SAR
|
|
747
|
+
calculateParabolicSAR(prices, highs, lows) {
|
|
748
|
+
if (prices.length < 2) return [];
|
|
749
|
+
const sar = [];
|
|
750
|
+
const accelerationFactor = 0.02;
|
|
751
|
+
const maximumAcceleration = 0.2;
|
|
752
|
+
let currentSAR = lows[0];
|
|
753
|
+
let isLong = true;
|
|
754
|
+
let af = accelerationFactor;
|
|
755
|
+
let ep = highs[0];
|
|
756
|
+
sar.push(currentSAR);
|
|
757
|
+
for (let i = 1; i < prices.length; i++) {
|
|
758
|
+
const high = highs[i] || prices[i];
|
|
759
|
+
const low = lows[i] || prices[i];
|
|
760
|
+
if (isLong) {
|
|
761
|
+
if (low < currentSAR) {
|
|
762
|
+
isLong = false;
|
|
763
|
+
currentSAR = ep;
|
|
764
|
+
ep = low;
|
|
765
|
+
af = accelerationFactor;
|
|
766
|
+
} else {
|
|
767
|
+
if (high > ep) {
|
|
768
|
+
ep = high;
|
|
769
|
+
af = Math.min(af + accelerationFactor, maximumAcceleration);
|
|
770
|
+
}
|
|
771
|
+
currentSAR = currentSAR + af * (ep - currentSAR);
|
|
772
|
+
if (i > 0) {
|
|
773
|
+
const prevLow = lows[i - 1] || prices[i - 1];
|
|
774
|
+
currentSAR = Math.min(currentSAR, prevLow);
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
} else {
|
|
778
|
+
if (high > currentSAR) {
|
|
779
|
+
isLong = true;
|
|
780
|
+
currentSAR = ep;
|
|
781
|
+
ep = high;
|
|
782
|
+
af = accelerationFactor;
|
|
783
|
+
} else {
|
|
784
|
+
if (low < ep) {
|
|
785
|
+
ep = low;
|
|
786
|
+
af = Math.min(af + accelerationFactor, maximumAcceleration);
|
|
787
|
+
}
|
|
788
|
+
currentSAR = currentSAR + af * (ep - currentSAR);
|
|
789
|
+
if (i > 0) {
|
|
790
|
+
const prevHigh = highs[i - 1] || prices[i - 1];
|
|
791
|
+
currentSAR = Math.max(currentSAR, prevHigh);
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
sar.push(currentSAR);
|
|
796
|
+
}
|
|
797
|
+
return sar;
|
|
798
|
+
}
|
|
799
|
+
// Calculate Stochastic
|
|
800
|
+
calculateStochastic(prices, highs, lows) {
|
|
801
|
+
const stochastic = [];
|
|
802
|
+
const period = 14;
|
|
803
|
+
const smoothK = 3;
|
|
804
|
+
const smoothD = 3;
|
|
805
|
+
if (prices.length < period) return [];
|
|
806
|
+
const percentK = [];
|
|
807
|
+
for (let i = period - 1; i < prices.length; i++) {
|
|
808
|
+
const high = Math.max(...highs.slice(i - period + 1, i + 1));
|
|
809
|
+
const low = Math.min(...lows.slice(i - period + 1, i + 1));
|
|
810
|
+
const close = prices[i];
|
|
811
|
+
const k = (close - low) / (high - low) * 100;
|
|
812
|
+
percentK.push(k);
|
|
813
|
+
}
|
|
814
|
+
const smoothedK = [];
|
|
815
|
+
for (let i = smoothK - 1; i < percentK.length; i++) {
|
|
816
|
+
const sum2 = percentK.slice(i - smoothK + 1, i + 1).reduce((a, b) => a + b, 0);
|
|
817
|
+
smoothedK.push(sum2 / smoothK);
|
|
818
|
+
}
|
|
819
|
+
for (let i = smoothD - 1; i < smoothedK.length; i++) {
|
|
820
|
+
const sum2 = smoothedK.slice(i - smoothD + 1, i + 1).reduce((a, b) => a + b, 0);
|
|
821
|
+
const d = sum2 / smoothD;
|
|
822
|
+
stochastic.push({
|
|
823
|
+
k: smoothedK[i],
|
|
824
|
+
d
|
|
825
|
+
});
|
|
826
|
+
}
|
|
827
|
+
return stochastic;
|
|
828
|
+
}
|
|
829
|
+
// Calculate CCI
|
|
830
|
+
calculateCci(prices, highs, lows) {
|
|
831
|
+
const cci = [];
|
|
832
|
+
const period = 20;
|
|
833
|
+
if (prices.length < period) return [];
|
|
834
|
+
for (let i = period - 1; i < prices.length; i++) {
|
|
835
|
+
const slice = prices.slice(i - period + 1, i + 1);
|
|
836
|
+
const typicalPrices = slice.map((price, idx) => {
|
|
837
|
+
const high = highs[i - period + 1 + idx] || price;
|
|
838
|
+
const low = lows[i - period + 1 + idx] || price;
|
|
839
|
+
return (high + low + price) / 3;
|
|
840
|
+
});
|
|
841
|
+
const sma = typicalPrices.reduce((a, b) => a + b, 0) / period;
|
|
842
|
+
const meanDeviation = typicalPrices.reduce((sum2, tp) => sum2 + Math.abs(tp - sma), 0) / period;
|
|
843
|
+
const currentTP = (highs[i] + lows[i] + prices[i]) / 3;
|
|
844
|
+
const cciValue = meanDeviation !== 0 ? (currentTP - sma) / (0.015 * meanDeviation) : 0;
|
|
845
|
+
cci.push(cciValue);
|
|
846
|
+
}
|
|
847
|
+
return cci;
|
|
848
|
+
}
|
|
849
|
+
// Calculate Rate of Change
|
|
850
|
+
calculateRoc(prices) {
|
|
851
|
+
const roc = [];
|
|
852
|
+
for (let i = 10; i < prices.length; i++) {
|
|
853
|
+
roc.push((prices[i] - prices[i - 10]) / prices[i - 10] * 100);
|
|
854
|
+
}
|
|
855
|
+
return roc;
|
|
856
|
+
}
|
|
857
|
+
// Calculate Williams %R
|
|
858
|
+
calculateWilliamsR(prices) {
|
|
859
|
+
const williamsR = [];
|
|
860
|
+
const period = 14;
|
|
861
|
+
if (prices.length < period) return [];
|
|
862
|
+
for (let i = period - 1; i < prices.length; i++) {
|
|
863
|
+
const slice = prices.slice(i - period + 1, i + 1);
|
|
864
|
+
const high = Math.max(...slice);
|
|
865
|
+
const low = Math.min(...slice);
|
|
866
|
+
const close = prices[i];
|
|
867
|
+
const wr = (high - close) / (high - low) * -100;
|
|
868
|
+
williamsR.push(wr);
|
|
869
|
+
}
|
|
870
|
+
return williamsR;
|
|
871
|
+
}
|
|
872
|
+
// Calculate Momentum
|
|
873
|
+
calculateMomentum(prices) {
|
|
874
|
+
const momentum = [];
|
|
875
|
+
for (let i = 10; i < prices.length; i++) {
|
|
876
|
+
momentum.push(prices[i] - prices[i - 10]);
|
|
877
|
+
}
|
|
878
|
+
return momentum;
|
|
879
|
+
}
|
|
880
|
+
// Calculate Keltner Channels
|
|
881
|
+
calculateKeltnerChannels(prices, highs, lows) {
|
|
882
|
+
const keltner = [];
|
|
883
|
+
const period = 20;
|
|
884
|
+
const multiplier = 2;
|
|
885
|
+
if (prices.length < period) return [];
|
|
886
|
+
const ema = this.calculateEMA(prices, period);
|
|
887
|
+
const atr = this.calculateAtr(prices, highs, lows);
|
|
888
|
+
for (let i = 0; i < Math.min(ema.length, atr.length); i++) {
|
|
889
|
+
const middle = ema[i];
|
|
890
|
+
const atrValue = atr[i];
|
|
891
|
+
keltner.push({
|
|
892
|
+
upper: middle + multiplier * atrValue,
|
|
893
|
+
middle,
|
|
894
|
+
lower: middle - multiplier * atrValue
|
|
895
|
+
});
|
|
896
|
+
}
|
|
897
|
+
return keltner;
|
|
898
|
+
}
|
|
899
|
+
// Calculate Donchian Channels
|
|
900
|
+
calculateDonchianChannels(prices) {
|
|
901
|
+
const donchian = [];
|
|
902
|
+
for (let i = 20; i < prices.length; i++) {
|
|
903
|
+
const slice = prices.slice(i - 20, i);
|
|
904
|
+
donchian.push({
|
|
905
|
+
upper: Math.max(...slice),
|
|
906
|
+
middle: (Math.max(...slice) + Math.min(...slice)) / 2,
|
|
907
|
+
lower: Math.min(...slice)
|
|
908
|
+
});
|
|
909
|
+
}
|
|
910
|
+
return donchian;
|
|
911
|
+
}
|
|
912
|
+
// Calculate Chaikin Volatility
|
|
913
|
+
calculateChaikinVolatility(prices, highs, lows) {
|
|
914
|
+
const volatility = [];
|
|
915
|
+
const period = 10;
|
|
916
|
+
if (prices.length < period * 2) return [];
|
|
917
|
+
const highLowRange = [];
|
|
918
|
+
for (let i = 0; i < prices.length; i++) {
|
|
919
|
+
const high = highs[i] || prices[i];
|
|
920
|
+
const low = lows[i] || prices[i];
|
|
921
|
+
highLowRange.push(high - low);
|
|
922
|
+
}
|
|
923
|
+
const emaRange = this.calculateEMA(highLowRange, period);
|
|
924
|
+
for (let i = period; i < emaRange.length; i++) {
|
|
925
|
+
const currentEMA = emaRange[i];
|
|
926
|
+
const pastEMA = emaRange[i - period];
|
|
927
|
+
const volatilityValue = pastEMA !== 0 ? (currentEMA - pastEMA) / pastEMA * 100 : 0;
|
|
928
|
+
volatility.push(volatilityValue);
|
|
929
|
+
}
|
|
930
|
+
return volatility;
|
|
931
|
+
}
|
|
932
|
+
// Calculate On Balance Volume
|
|
933
|
+
calculateObv(volumes) {
|
|
934
|
+
const obv = [volumes[0]];
|
|
935
|
+
for (let i = 1; i < volumes.length; i++) {
|
|
936
|
+
obv.push(obv[i - 1] + volumes[i]);
|
|
937
|
+
}
|
|
938
|
+
return obv;
|
|
939
|
+
}
|
|
940
|
+
// Calculate Chaikin Money Flow
|
|
941
|
+
calculateCmf(prices, highs, lows, volumes) {
|
|
942
|
+
const cmf = [];
|
|
943
|
+
const period = 20;
|
|
944
|
+
if (prices.length < period) return [];
|
|
945
|
+
for (let i = period - 1; i < prices.length; i++) {
|
|
946
|
+
let totalMoneyFlowVolume = 0;
|
|
947
|
+
let totalVolume = 0;
|
|
948
|
+
for (let j = i - period + 1; j <= i; j++) {
|
|
949
|
+
const high = highs[j] || prices[j];
|
|
950
|
+
const low = lows[j] || prices[j];
|
|
951
|
+
const close = prices[j];
|
|
952
|
+
const volume = volumes[j] || 1;
|
|
953
|
+
const moneyFlowMultiplier = (close - low - (high - close)) / (high - low);
|
|
954
|
+
const moneyFlowVolume = moneyFlowMultiplier * volume;
|
|
955
|
+
totalMoneyFlowVolume += moneyFlowVolume;
|
|
956
|
+
totalVolume += volume;
|
|
957
|
+
}
|
|
958
|
+
const cmfValue = totalVolume !== 0 ? totalMoneyFlowVolume / totalVolume : 0;
|
|
959
|
+
cmf.push(cmfValue);
|
|
960
|
+
}
|
|
961
|
+
return cmf;
|
|
962
|
+
}
|
|
963
|
+
// Calculate Accumulation/Distribution Line
|
|
964
|
+
calculateAdl(prices) {
|
|
965
|
+
const adl = [0];
|
|
966
|
+
for (let i = 1; i < prices.length; i++) {
|
|
967
|
+
const high = this.highs[i] || prices[i];
|
|
968
|
+
const low = this.lows[i] || prices[i];
|
|
969
|
+
const close = prices[i];
|
|
970
|
+
const volume = this.volumes[i] || 1;
|
|
971
|
+
const moneyFlowMultiplier = (close - low - (high - close)) / (high - low);
|
|
972
|
+
const moneyFlowVolume = moneyFlowMultiplier * volume;
|
|
973
|
+
adl.push(adl[i - 1] + moneyFlowVolume);
|
|
974
|
+
}
|
|
975
|
+
return adl;
|
|
976
|
+
}
|
|
977
|
+
// Calculate Volume Rate of Change
|
|
978
|
+
calculateVolumeROC() {
|
|
979
|
+
const volumeROC = [];
|
|
980
|
+
for (let i = 10; i < this.volumes.length; i++) {
|
|
981
|
+
volumeROC.push((this.volumes[i] - this.volumes[i - 10]) / this.volumes[i - 10] * 100);
|
|
982
|
+
}
|
|
983
|
+
return volumeROC;
|
|
984
|
+
}
|
|
985
|
+
// Calculate Money Flow Index
|
|
986
|
+
calculateMfi(prices, highs, lows, volumes) {
|
|
987
|
+
const mfi = [];
|
|
988
|
+
const period = 14;
|
|
989
|
+
if (prices.length < period + 1) return [];
|
|
990
|
+
for (let i = period; i < prices.length; i++) {
|
|
991
|
+
let positiveMoneyFlow = 0;
|
|
992
|
+
let negativeMoneyFlow = 0;
|
|
993
|
+
for (let j = i - period + 1; j <= i; j++) {
|
|
994
|
+
const high = highs[j] || prices[j];
|
|
995
|
+
const low = lows[j] || prices[j];
|
|
996
|
+
const close = prices[j];
|
|
997
|
+
const volume = volumes[j] || 1;
|
|
998
|
+
const typicalPrice = (high + low + close) / 3;
|
|
999
|
+
const moneyFlow = typicalPrice * volume;
|
|
1000
|
+
if (j > i - period + 1) {
|
|
1001
|
+
const prevHigh = highs[j - 1] || prices[j - 1];
|
|
1002
|
+
const prevLow = lows[j - 1] || prices[j - 1];
|
|
1003
|
+
const prevClose = prices[j - 1];
|
|
1004
|
+
const prevTypicalPrice = (prevHigh + prevLow + prevClose) / 3;
|
|
1005
|
+
if (typicalPrice > prevTypicalPrice) {
|
|
1006
|
+
positiveMoneyFlow += moneyFlow;
|
|
1007
|
+
} else if (typicalPrice < prevTypicalPrice) {
|
|
1008
|
+
negativeMoneyFlow += moneyFlow;
|
|
1009
|
+
}
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
const moneyRatio = negativeMoneyFlow !== 0 ? positiveMoneyFlow / negativeMoneyFlow : 0;
|
|
1013
|
+
const mfiValue = 100 - 100 / (1 + moneyRatio);
|
|
1014
|
+
mfi.push(mfiValue);
|
|
1015
|
+
}
|
|
1016
|
+
return mfi;
|
|
1017
|
+
}
|
|
1018
|
+
// Calculate VWAP
|
|
1019
|
+
calculateVwap(prices, volumes) {
|
|
1020
|
+
const vwap = [];
|
|
1021
|
+
let cumulativePV = 0;
|
|
1022
|
+
let cumulativeVolume = 0;
|
|
1023
|
+
for (let i = 0; i < prices.length; i++) {
|
|
1024
|
+
cumulativePV += prices[i] * (volumes[i] || 1);
|
|
1025
|
+
cumulativeVolume += volumes[i] || 1;
|
|
1026
|
+
vwap.push(cumulativePV / cumulativeVolume);
|
|
1027
|
+
}
|
|
1028
|
+
return vwap;
|
|
1029
|
+
}
|
|
1030
|
+
// Calculate Pivot Points
|
|
1031
|
+
calculatePivotPoints(prices) {
|
|
1032
|
+
const pivotPoints = [];
|
|
1033
|
+
for (let i = 0; i < prices.length; i++) {
|
|
1034
|
+
const high = this.highs[i] || prices[i];
|
|
1035
|
+
const low = this.lows[i] || prices[i];
|
|
1036
|
+
const close = prices[i];
|
|
1037
|
+
const pp = (high + low + close) / 3;
|
|
1038
|
+
const r1 = 2 * pp - low;
|
|
1039
|
+
const s1 = 2 * pp - high;
|
|
1040
|
+
const r2 = pp + (high - low);
|
|
1041
|
+
const s2 = pp - (high - low);
|
|
1042
|
+
const r3 = high + 2 * (pp - low);
|
|
1043
|
+
const s3 = low - 2 * (high - pp);
|
|
1044
|
+
pivotPoints.push({
|
|
1045
|
+
pp,
|
|
1046
|
+
r1,
|
|
1047
|
+
r2,
|
|
1048
|
+
r3,
|
|
1049
|
+
s1,
|
|
1050
|
+
s2,
|
|
1051
|
+
s3
|
|
1052
|
+
});
|
|
1053
|
+
}
|
|
1054
|
+
return pivotPoints;
|
|
1055
|
+
}
|
|
1056
|
+
// Calculate Fibonacci Levels
|
|
1057
|
+
calculateFibonacciLevels(prices) {
|
|
1058
|
+
const fibonacci = [];
|
|
1059
|
+
for (let i = 0; i < prices.length; i++) {
|
|
1060
|
+
const price = prices[i];
|
|
1061
|
+
fibonacci.push({
|
|
1062
|
+
retracement: {
|
|
1063
|
+
level0: price,
|
|
1064
|
+
level236: price * 0.764,
|
|
1065
|
+
level382: price * 0.618,
|
|
1066
|
+
level500: price * 0.5,
|
|
1067
|
+
level618: price * 0.382,
|
|
1068
|
+
level786: price * 0.214,
|
|
1069
|
+
level100: price * 0
|
|
1070
|
+
},
|
|
1071
|
+
extension: {
|
|
1072
|
+
level1272: price * 1.272,
|
|
1073
|
+
level1618: price * 1.618,
|
|
1074
|
+
level2618: price * 2.618,
|
|
1075
|
+
level4236: price * 4.236
|
|
1076
|
+
}
|
|
1077
|
+
});
|
|
1078
|
+
}
|
|
1079
|
+
return fibonacci;
|
|
1080
|
+
}
|
|
1081
|
+
// Calculate Gann Levels
|
|
1082
|
+
calculateGannLevels(prices) {
|
|
1083
|
+
const gannLevels = [];
|
|
1084
|
+
for (let i = 0; i < prices.length; i++) {
|
|
1085
|
+
gannLevels.push(prices[i] * (1 + i * 0.01));
|
|
1086
|
+
}
|
|
1087
|
+
return gannLevels;
|
|
1088
|
+
}
|
|
1089
|
+
// Calculate Elliott Wave
|
|
1090
|
+
calculateElliottWave(prices) {
|
|
1091
|
+
const elliottWave = [];
|
|
1092
|
+
if (prices.length < 10) return [];
|
|
1093
|
+
for (let i = 0; i < prices.length; i++) {
|
|
1094
|
+
const waves = [];
|
|
1095
|
+
let currentWave = 1;
|
|
1096
|
+
let wavePosition = 0.5;
|
|
1097
|
+
if (i >= 4) {
|
|
1098
|
+
const recentPrices = prices.slice(i - 4, i + 1);
|
|
1099
|
+
const swings = this.detectPriceSwings(recentPrices);
|
|
1100
|
+
if (swings.length >= 3) {
|
|
1101
|
+
waves.push(...swings.slice(0, 3));
|
|
1102
|
+
currentWave = Math.min(swings.length, 5);
|
|
1103
|
+
wavePosition = this.calculateWavePosition(recentPrices);
|
|
1104
|
+
}
|
|
1105
|
+
}
|
|
1106
|
+
elliottWave.push({
|
|
1107
|
+
waves: waves.length > 0 ? waves : [prices[i]],
|
|
1108
|
+
currentWave,
|
|
1109
|
+
wavePosition
|
|
1110
|
+
});
|
|
1111
|
+
}
|
|
1112
|
+
return elliottWave;
|
|
1113
|
+
}
|
|
1114
|
+
// Helper method to detect price swings
|
|
1115
|
+
detectPriceSwings(prices) {
|
|
1116
|
+
const swings = [];
|
|
1117
|
+
for (let i = 1; i < prices.length - 1; i++) {
|
|
1118
|
+
const prev = prices[i - 1];
|
|
1119
|
+
const curr = prices[i];
|
|
1120
|
+
const next = prices[i + 1];
|
|
1121
|
+
if (curr > prev && curr > next) {
|
|
1122
|
+
swings.push(curr);
|
|
1123
|
+
} else if (curr < prev && curr < next) {
|
|
1124
|
+
swings.push(curr);
|
|
1125
|
+
}
|
|
1126
|
+
}
|
|
1127
|
+
return swings;
|
|
1128
|
+
}
|
|
1129
|
+
// Helper method to calculate wave position
|
|
1130
|
+
calculateWavePosition(prices) {
|
|
1131
|
+
if (prices.length < 2) return 0.5;
|
|
1132
|
+
const current = prices[prices.length - 1];
|
|
1133
|
+
const min = Math.min(...prices);
|
|
1134
|
+
const max = Math.max(...prices);
|
|
1135
|
+
return max !== min ? (current - min) / (max - min) : 0.5;
|
|
1136
|
+
}
|
|
1137
|
+
// Calculate Harmonic Patterns
|
|
1138
|
+
calculateHarmonicPatterns(prices) {
|
|
1139
|
+
const harmonicPatterns = [];
|
|
1140
|
+
if (prices.length < 5) return [];
|
|
1141
|
+
for (let i = 4; i < prices.length; i++) {
|
|
1142
|
+
const recentPrices = prices.slice(i - 4, i + 1);
|
|
1143
|
+
const pattern = this.detectHarmonicPattern(recentPrices);
|
|
1144
|
+
harmonicPatterns.push(pattern);
|
|
1145
|
+
}
|
|
1146
|
+
return harmonicPatterns;
|
|
1147
|
+
}
|
|
1148
|
+
// Helper method to detect harmonic patterns
|
|
1149
|
+
detectHarmonicPattern(prices) {
|
|
1150
|
+
if (prices.length < 5) {
|
|
1151
|
+
return {
|
|
1152
|
+
type: "Unknown",
|
|
1153
|
+
completion: 0,
|
|
1154
|
+
target: prices[prices.length - 1] * 1.1,
|
|
1155
|
+
stopLoss: prices[prices.length - 1] * 0.9
|
|
1156
|
+
};
|
|
1157
|
+
}
|
|
1158
|
+
const swings = this.detectPriceSwings(prices);
|
|
1159
|
+
if (swings.length < 4) {
|
|
1160
|
+
return {
|
|
1161
|
+
type: "Unknown",
|
|
1162
|
+
completion: 0,
|
|
1163
|
+
target: prices[prices.length - 1] * 1.1,
|
|
1164
|
+
stopLoss: prices[prices.length - 1] * 0.9
|
|
1165
|
+
};
|
|
1166
|
+
}
|
|
1167
|
+
const [A, B, C, D] = swings.slice(-4);
|
|
1168
|
+
const X = prices[0];
|
|
1169
|
+
const abRatio = Math.abs((B - A) / (X - A));
|
|
1170
|
+
const bcRatio = Math.abs((C - B) / (A - B));
|
|
1171
|
+
const cdRatio = Math.abs((D - C) / (B - C));
|
|
1172
|
+
const adRatio = Math.abs((D - A) / (X - A));
|
|
1173
|
+
const isGartley = Math.abs(abRatio - 0.618) < 0.1 && bcRatio >= 0.382 && bcRatio <= 0.886 && cdRatio >= 1.13 && cdRatio <= 1.618 && Math.abs(adRatio - 0.786) < 0.1;
|
|
1174
|
+
if (isGartley) {
|
|
1175
|
+
const completion = this.calculatePatternCompletion(prices);
|
|
1176
|
+
const target = D + (D - C) * 0.618;
|
|
1177
|
+
const stopLoss = D - (D - C) * 0.382;
|
|
1178
|
+
return {
|
|
1179
|
+
type: "Gartley",
|
|
1180
|
+
completion,
|
|
1181
|
+
target,
|
|
1182
|
+
stopLoss
|
|
1183
|
+
};
|
|
1184
|
+
}
|
|
1185
|
+
const isButterfly = Math.abs(abRatio - 0.786) < 0.1 && bcRatio >= 0.382 && bcRatio <= 0.886 && cdRatio >= 1.618 && cdRatio <= 2.618 && Math.abs(adRatio - 1.27) < 0.1;
|
|
1186
|
+
if (isButterfly) {
|
|
1187
|
+
const completion = this.calculatePatternCompletion(prices);
|
|
1188
|
+
const target = D + (D - C) * 1.27;
|
|
1189
|
+
const stopLoss = D - (D - C) * 0.5;
|
|
1190
|
+
return {
|
|
1191
|
+
type: "Butterfly",
|
|
1192
|
+
completion,
|
|
1193
|
+
target,
|
|
1194
|
+
stopLoss
|
|
1195
|
+
};
|
|
1196
|
+
}
|
|
1197
|
+
return {
|
|
1198
|
+
type: "Unknown",
|
|
1199
|
+
completion: 0,
|
|
1200
|
+
target: prices[prices.length - 1] * 1.1,
|
|
1201
|
+
stopLoss: prices[prices.length - 1] * 0.9
|
|
1202
|
+
};
|
|
1203
|
+
}
|
|
1204
|
+
// Helper method to calculate pattern completion
|
|
1205
|
+
calculatePatternCompletion(prices) {
|
|
1206
|
+
if (prices.length < 2) return 0;
|
|
1207
|
+
const current = prices[prices.length - 1];
|
|
1208
|
+
const min = Math.min(...prices);
|
|
1209
|
+
const max = Math.max(...prices);
|
|
1210
|
+
return max !== min ? (current - min) / (max - min) : 0;
|
|
1211
|
+
}
|
|
1212
|
+
// Calculate Position Size
|
|
1213
|
+
calculatePositionSize(currentPrice, targetEntry, stopLoss) {
|
|
1214
|
+
void currentPrice;
|
|
1215
|
+
const riskPerShare = Math.abs(targetEntry - stopLoss);
|
|
1216
|
+
return riskPerShare > 0 ? 100 / riskPerShare : 1;
|
|
1217
|
+
}
|
|
1218
|
+
// Calculate Confidence
|
|
1219
|
+
calculateConfidence(signals) {
|
|
1220
|
+
return Math.min(signals.length * 10, 100);
|
|
1221
|
+
}
|
|
1222
|
+
// Calculate Risk Level
|
|
1223
|
+
calculateRiskLevel(volatility) {
|
|
1224
|
+
if (volatility < 20) return "LOW";
|
|
1225
|
+
if (volatility < 40) return "MEDIUM";
|
|
1226
|
+
return "HIGH";
|
|
1227
|
+
}
|
|
1228
|
+
// Calculate Z-Score
|
|
1229
|
+
calculateZScore(currentPrice, startPrice) {
|
|
1230
|
+
return (currentPrice - startPrice) / (startPrice * 0.1);
|
|
1231
|
+
}
|
|
1232
|
+
// Calculate Ornstein-Uhlenbeck
|
|
1233
|
+
calculateOrnsteinUhlenbeck(currentPrice, startPrice, avgVolume) {
|
|
1234
|
+
const priceChanges = this.calculatePriceChanges();
|
|
1235
|
+
const mean = startPrice;
|
|
1236
|
+
let speed = 0.1;
|
|
1237
|
+
if (priceChanges.length > 1) {
|
|
1238
|
+
const variance = priceChanges.reduce((sum2, change) => sum2 + change * change, 0) / priceChanges.length;
|
|
1239
|
+
speed = Math.max(0.01, Math.min(1, variance * 10));
|
|
1240
|
+
}
|
|
1241
|
+
const volatility = avgVolume * 0.01;
|
|
1242
|
+
return {
|
|
1243
|
+
mean,
|
|
1244
|
+
speed,
|
|
1245
|
+
volatility,
|
|
1246
|
+
currentValue: currentPrice
|
|
1247
|
+
};
|
|
1248
|
+
}
|
|
1249
|
+
// Calculate Kalman Filter
|
|
1250
|
+
calculateKalmanFilter(currentPrice, startPrice, avgVolume) {
|
|
1251
|
+
const measurementNoise = avgVolume * 1e-3;
|
|
1252
|
+
const processNoise = avgVolume * 1e-4;
|
|
1253
|
+
let state = startPrice;
|
|
1254
|
+
let covariance = measurementNoise;
|
|
1255
|
+
const priceChanges = this.calculatePriceChanges();
|
|
1256
|
+
if (priceChanges.length > 0) {
|
|
1257
|
+
const predictedState = state;
|
|
1258
|
+
const predictedCovariance = covariance + processNoise;
|
|
1259
|
+
const kalmanGain = predictedCovariance / (predictedCovariance + measurementNoise);
|
|
1260
|
+
state = predictedState + kalmanGain * (currentPrice - predictedState);
|
|
1261
|
+
covariance = (1 - kalmanGain) * predictedCovariance;
|
|
1262
|
+
return {
|
|
1263
|
+
state,
|
|
1264
|
+
covariance,
|
|
1265
|
+
gain: kalmanGain
|
|
1266
|
+
};
|
|
1267
|
+
}
|
|
1268
|
+
return {
|
|
1269
|
+
state: currentPrice,
|
|
1270
|
+
covariance,
|
|
1271
|
+
gain: 0.5
|
|
1272
|
+
};
|
|
1273
|
+
}
|
|
1274
|
+
// Calculate ARIMA
|
|
1275
|
+
calculateArima(currentPrice) {
|
|
1276
|
+
const priceChanges = this.calculatePriceChanges();
|
|
1277
|
+
if (priceChanges.length < 3) {
|
|
1278
|
+
return {
|
|
1279
|
+
forecast: [currentPrice * 1.01, currentPrice * 1.02],
|
|
1280
|
+
residuals: [0, 0],
|
|
1281
|
+
aic: 100
|
|
1282
|
+
};
|
|
1283
|
+
}
|
|
1284
|
+
const n = priceChanges.length;
|
|
1285
|
+
let sumY = 0;
|
|
1286
|
+
let sumY1 = 0;
|
|
1287
|
+
let sumYY1 = 0;
|
|
1288
|
+
let sumY1Sq = 0;
|
|
1289
|
+
for (let i = 1; i < n; i++) {
|
|
1290
|
+
const y = priceChanges[i];
|
|
1291
|
+
const y1 = priceChanges[i - 1];
|
|
1292
|
+
sumY += y;
|
|
1293
|
+
sumY1 += y1;
|
|
1294
|
+
sumYY1 += y * y1;
|
|
1295
|
+
sumY1Sq += y1 * y1;
|
|
1296
|
+
}
|
|
1297
|
+
const phi = (n * sumYY1 - sumY * sumY1) / (n * sumY1Sq - sumY1 * sumY1);
|
|
1298
|
+
const c = (sumY - phi * sumY1) / n;
|
|
1299
|
+
const residuals = [];
|
|
1300
|
+
for (let i = 1; i < n; i++) {
|
|
1301
|
+
const predicted = c + phi * priceChanges[i - 1];
|
|
1302
|
+
residuals.push(priceChanges[i] - predicted);
|
|
1303
|
+
}
|
|
1304
|
+
const rss = residuals.reduce((sum2, r) => sum2 + r * r, 0);
|
|
1305
|
+
const aic = n * Math.log(rss / n) + 2 * 2;
|
|
1306
|
+
const lastChange = priceChanges[priceChanges.length - 1];
|
|
1307
|
+
const forecast1 = currentPrice + (c + phi * lastChange);
|
|
1308
|
+
const forecast2 = forecast1 + (c + phi * (c + phi * lastChange));
|
|
1309
|
+
return {
|
|
1310
|
+
forecast: [forecast1, forecast2],
|
|
1311
|
+
residuals,
|
|
1312
|
+
aic
|
|
1313
|
+
};
|
|
1314
|
+
}
|
|
1315
|
+
// Calculate GARCH
|
|
1316
|
+
calculateGarch(avgVolume) {
|
|
1317
|
+
const priceChanges = this.calculatePriceChanges();
|
|
1318
|
+
if (priceChanges.length < 5) {
|
|
1319
|
+
return {
|
|
1320
|
+
volatility: avgVolume * 0.01,
|
|
1321
|
+
persistence: 0.9,
|
|
1322
|
+
meanReversion: 0.1
|
|
1323
|
+
};
|
|
1324
|
+
}
|
|
1325
|
+
const squaredReturns = priceChanges.map((change) => change * change);
|
|
1326
|
+
const meanSquaredReturn = squaredReturns.reduce((sum2, sq) => sum2 + sq, 0) / squaredReturns.length;
|
|
1327
|
+
let persistence = 0.9;
|
|
1328
|
+
if (squaredReturns.length > 1) {
|
|
1329
|
+
const variance = squaredReturns.reduce((sum2, sq) => sum2 + sq, 0) / squaredReturns.length;
|
|
1330
|
+
persistence = Math.min(0.99, Math.max(0.5, variance / meanSquaredReturn));
|
|
1331
|
+
}
|
|
1332
|
+
const meanReversion = meanSquaredReturn * (1 - persistence);
|
|
1333
|
+
const volatility = Math.sqrt(meanSquaredReturn);
|
|
1334
|
+
return {
|
|
1335
|
+
volatility,
|
|
1336
|
+
persistence,
|
|
1337
|
+
meanReversion
|
|
1338
|
+
};
|
|
1339
|
+
}
|
|
1340
|
+
// Calculate Hilbert Transform
|
|
1341
|
+
calculateHilbertTransform(currentPrice) {
|
|
1342
|
+
const priceChanges = this.calculatePriceChanges();
|
|
1343
|
+
if (priceChanges.length < 3) {
|
|
1344
|
+
return {
|
|
1345
|
+
analytic: [currentPrice],
|
|
1346
|
+
phase: [0],
|
|
1347
|
+
amplitude: [currentPrice]
|
|
1348
|
+
};
|
|
1349
|
+
}
|
|
1350
|
+
const n = priceChanges.length;
|
|
1351
|
+
const analytic = [];
|
|
1352
|
+
const phase = [];
|
|
1353
|
+
const amplitude = [];
|
|
1354
|
+
for (let i = 0; i < n; i++) {
|
|
1355
|
+
let hilbertValue = 0;
|
|
1356
|
+
for (let j = 0; j < n; j++) {
|
|
1357
|
+
if (i !== j) {
|
|
1358
|
+
hilbertValue += priceChanges[j] / (Math.PI * (i - j));
|
|
1359
|
+
}
|
|
1360
|
+
}
|
|
1361
|
+
const realPart = priceChanges[i];
|
|
1362
|
+
const imagPart = hilbertValue;
|
|
1363
|
+
const analyticValue = Math.sqrt(realPart * realPart + imagPart * imagPart);
|
|
1364
|
+
analytic.push(analyticValue);
|
|
1365
|
+
const phaseValue = Math.atan2(imagPart, realPart);
|
|
1366
|
+
phase.push(phaseValue);
|
|
1367
|
+
amplitude.push(analyticValue);
|
|
1368
|
+
}
|
|
1369
|
+
return {
|
|
1370
|
+
analytic,
|
|
1371
|
+
phase,
|
|
1372
|
+
amplitude
|
|
1373
|
+
};
|
|
1374
|
+
}
|
|
1375
|
+
// Calculate Wavelet Transform
|
|
1376
|
+
calculateWaveletTransform(currentPrice) {
|
|
1377
|
+
const priceChanges = this.calculatePriceChanges();
|
|
1378
|
+
if (priceChanges.length < 4) {
|
|
1379
|
+
return {
|
|
1380
|
+
coefficients: [currentPrice],
|
|
1381
|
+
scales: [1]
|
|
1382
|
+
};
|
|
1383
|
+
}
|
|
1384
|
+
const coefficients = [];
|
|
1385
|
+
const scales = [];
|
|
1386
|
+
const n = priceChanges.length;
|
|
1387
|
+
const maxLevel = Math.floor(Math.log2(n));
|
|
1388
|
+
for (let level = 1; level <= maxLevel; level++) {
|
|
1389
|
+
const step = 2 ** (level - 1);
|
|
1390
|
+
const scale = step;
|
|
1391
|
+
for (let i = 0; i < n - step; i += step * 2) {
|
|
1392
|
+
if (i + step < n) {
|
|
1393
|
+
const coefficient = (priceChanges[i] - priceChanges[i + step]) / Math.sqrt(2);
|
|
1394
|
+
coefficients.push(coefficient);
|
|
1395
|
+
scales.push(scale);
|
|
1396
|
+
}
|
|
1397
|
+
}
|
|
1398
|
+
}
|
|
1399
|
+
if (coefficients.length === 0) {
|
|
1400
|
+
coefficients.push(currentPrice);
|
|
1401
|
+
scales.push(1);
|
|
1402
|
+
}
|
|
1403
|
+
return {
|
|
1404
|
+
coefficients,
|
|
1405
|
+
scales
|
|
1406
|
+
};
|
|
1407
|
+
}
|
|
1408
|
+
// Calculate Black-Scholes
|
|
1409
|
+
calculateBlackScholes(currentPrice, startPrice, avgVolume) {
|
|
1410
|
+
const S = currentPrice;
|
|
1411
|
+
const K = startPrice;
|
|
1412
|
+
const T = 1;
|
|
1413
|
+
const r = 0.05;
|
|
1414
|
+
const sigma = avgVolume * 0.01;
|
|
1415
|
+
const d1 = (Math.log(S / K) + (r + sigma * sigma / 2) * T) / (sigma * Math.sqrt(T));
|
|
1416
|
+
const d2 = d1 - sigma * Math.sqrt(T);
|
|
1417
|
+
const callPrice = S * this.normalCDF(d1) - K * Math.exp(-r * T) * this.normalCDF(d2);
|
|
1418
|
+
const putPrice = K * Math.exp(-r * T) * this.normalCDF(-d2) - S * this.normalCDF(-d1);
|
|
1419
|
+
return {
|
|
1420
|
+
callPrice,
|
|
1421
|
+
putPrice,
|
|
1422
|
+
delta: this.normalCDF(d1),
|
|
1423
|
+
gamma: this.normalPDF(d1) / (S * sigma * Math.sqrt(T)),
|
|
1424
|
+
theta: -S * this.normalPDF(d1) * sigma / (2 * Math.sqrt(T)) - r * K * Math.exp(-r * T) * this.normalCDF(d2),
|
|
1425
|
+
vega: S * Math.sqrt(T) * this.normalPDF(d1),
|
|
1426
|
+
rho: K * T * Math.exp(-r * T) * this.normalCDF(d2)
|
|
1427
|
+
};
|
|
1428
|
+
}
|
|
1429
|
+
// Normal CDF approximation
|
|
1430
|
+
normalCDF(x) {
|
|
1431
|
+
return 0.5 * (1 + this.erf(x / Math.sqrt(2)));
|
|
1432
|
+
}
|
|
1433
|
+
// Normal PDF
|
|
1434
|
+
normalPDF(x) {
|
|
1435
|
+
return Math.exp(-x * x / 2) / Math.sqrt(2 * Math.PI);
|
|
1436
|
+
}
|
|
1437
|
+
// Error function approximation
|
|
1438
|
+
erf(x) {
|
|
1439
|
+
const a1 = 0.254829592;
|
|
1440
|
+
const a2 = -0.284496736;
|
|
1441
|
+
const a3 = 1.421413741;
|
|
1442
|
+
const a4 = -1.453152027;
|
|
1443
|
+
const a5 = 1.061405429;
|
|
1444
|
+
const p = 0.3275911;
|
|
1445
|
+
const sign = x >= 0 ? 1 : -1;
|
|
1446
|
+
const absX = Math.abs(x);
|
|
1447
|
+
const t = 1 / (1 + p * absX);
|
|
1448
|
+
const y = 1 - ((((a5 * t + a4) * t + a3) * t + a2) * t + a1) * t * Math.exp(-absX * absX);
|
|
1449
|
+
return sign * y;
|
|
1450
|
+
}
|
|
1451
|
+
// Calculate price changes for volatility
|
|
1452
|
+
calculatePriceChanges() {
|
|
1453
|
+
const changes = [];
|
|
1454
|
+
for (let i = 1; i < this.prices.length; i++) {
|
|
1455
|
+
changes.push((this.prices[i] - this.prices[i - 1]) / this.prices[i - 1]);
|
|
1456
|
+
}
|
|
1457
|
+
return changes;
|
|
1458
|
+
}
|
|
1459
|
+
// Generate comprehensive market analysis
|
|
1460
|
+
analyze() {
|
|
1461
|
+
const currentPrice = this.prices[this.prices.length - 1];
|
|
1462
|
+
const startPrice = this.prices[0];
|
|
1463
|
+
const sessionHigh = Math.max(...this.highs);
|
|
1464
|
+
const sessionLow = Math.min(...this.lows);
|
|
1465
|
+
const totalVolume = sum(this.volumes);
|
|
1466
|
+
const avgVolume = totalVolume / this.volumes.length;
|
|
1467
|
+
const priceChanges = this.calculatePriceChanges();
|
|
1468
|
+
const volatility = priceChanges.length > 0 ? Math.sqrt(
|
|
1469
|
+
priceChanges.reduce((sum2, change) => sum2 + change ** 2, 0) / priceChanges.length
|
|
1470
|
+
) * Math.sqrt(252) * 100 : 0;
|
|
1471
|
+
const sessionReturn = (currentPrice - startPrice) / startPrice * 100;
|
|
1472
|
+
const pricePosition = (currentPrice - sessionLow) / (sessionHigh - sessionLow) * 100;
|
|
1473
|
+
const trueVWAP = this.prices.reduce((sum2, price, i) => sum2 + price * this.volumes[i], 0) / totalVolume;
|
|
1474
|
+
const momentum5 = this.prices.length > 5 ? (currentPrice - this.prices[Math.max(0, this.prices.length - 6)]) / this.prices[Math.max(0, this.prices.length - 6)] * 100 : 0;
|
|
1475
|
+
const momentum10 = this.prices.length > 10 ? (currentPrice - this.prices[Math.max(0, this.prices.length - 11)]) / this.prices[Math.max(0, this.prices.length - 11)] * 100 : 0;
|
|
1476
|
+
const maxDrawdown = this.calculateMaxDrawdown(this.prices);
|
|
1477
|
+
const atrValues = this.calculateAtr(this.prices, this.highs, this.lows);
|
|
1478
|
+
const atr = atrValues.length > 0 ? atrValues[atrValues.length - 1] : 0;
|
|
1479
|
+
const impliedVolatility = volatility;
|
|
1480
|
+
const realizedVolatility = volatility;
|
|
1481
|
+
const sharpeRatio = sessionReturn / volatility;
|
|
1482
|
+
const sortinoRatio = sessionReturn / realizedVolatility;
|
|
1483
|
+
const calmarRatio = sessionReturn / maxDrawdown;
|
|
1484
|
+
const maxConsecutiveLosses = this.calculateMaxConsecutiveLosses(this.prices);
|
|
1485
|
+
const winRate = this.calculateWinRate(this.prices);
|
|
1486
|
+
const profitFactor = this.calculateProfitFactor(this.prices);
|
|
1487
|
+
return {
|
|
1488
|
+
currentPrice,
|
|
1489
|
+
startPrice,
|
|
1490
|
+
sessionHigh,
|
|
1491
|
+
sessionLow,
|
|
1492
|
+
totalVolume,
|
|
1493
|
+
avgVolume,
|
|
1494
|
+
volatility,
|
|
1495
|
+
sessionReturn,
|
|
1496
|
+
pricePosition,
|
|
1497
|
+
trueVWAP,
|
|
1498
|
+
momentum5,
|
|
1499
|
+
momentum10,
|
|
1500
|
+
maxDrawdown,
|
|
1501
|
+
atr,
|
|
1502
|
+
impliedVolatility,
|
|
1503
|
+
realizedVolatility,
|
|
1504
|
+
sharpeRatio,
|
|
1505
|
+
sortinoRatio,
|
|
1506
|
+
calmarRatio,
|
|
1507
|
+
maxConsecutiveLosses,
|
|
1508
|
+
winRate,
|
|
1509
|
+
profitFactor
|
|
1510
|
+
};
|
|
1511
|
+
}
|
|
1512
|
+
// Generate technical indicators
|
|
1513
|
+
getTechnicalIndicators() {
|
|
1514
|
+
return {
|
|
1515
|
+
sma5: this.calculateSMA(this.prices, 5),
|
|
1516
|
+
sma10: this.calculateSMA(this.prices, 10),
|
|
1517
|
+
sma20: this.calculateSMA(this.prices, 20),
|
|
1518
|
+
sma50: this.calculateSMA(this.prices, 50),
|
|
1519
|
+
sma200: this.calculateSMA(this.prices, 200),
|
|
1520
|
+
ema8: this.calculateEMA(this.prices, 8),
|
|
1521
|
+
ema12: this.calculateEMA(this.prices, 12),
|
|
1522
|
+
ema21: this.calculateEMA(this.prices, 21),
|
|
1523
|
+
ema26: this.calculateEMA(this.prices, 26),
|
|
1524
|
+
wma20: this.calculateWma(this.prices, 20),
|
|
1525
|
+
vwma20: this.calculateVwma(this.prices, 20),
|
|
1526
|
+
macd: this.calculateMacd(this.prices),
|
|
1527
|
+
adx: this.calculateAdx(this.prices, this.highs, this.lows),
|
|
1528
|
+
dmi: this.calculateDmi(this.prices, this.highs, this.lows),
|
|
1529
|
+
ichimoku: this.calculateIchimoku(this.prices, this.highs, this.lows),
|
|
1530
|
+
parabolicSAR: this.calculateParabolicSAR(this.prices, this.highs, this.lows),
|
|
1531
|
+
rsi: this.calculateRSI(this.prices, 14),
|
|
1532
|
+
stochastic: this.calculateStochastic(this.prices, this.highs, this.lows),
|
|
1533
|
+
cci: this.calculateCci(this.prices, this.highs, this.lows),
|
|
1534
|
+
roc: this.calculateRoc(this.prices),
|
|
1535
|
+
williamsR: this.calculateWilliamsR(this.prices),
|
|
1536
|
+
momentum: this.calculateMomentum(this.prices),
|
|
1537
|
+
bollinger: this.calculateBollingerBands(this.prices, 20, 2),
|
|
1538
|
+
atr: this.calculateAtr(this.prices, this.highs, this.lows),
|
|
1539
|
+
keltner: this.calculateKeltnerChannels(this.prices, this.highs, this.lows),
|
|
1540
|
+
donchian: this.calculateDonchianChannels(this.prices),
|
|
1541
|
+
chaikinVolatility: this.calculateChaikinVolatility(this.prices, this.highs, this.lows),
|
|
1542
|
+
obv: this.calculateObv(this.volumes),
|
|
1543
|
+
cmf: this.calculateCmf(this.prices, this.highs, this.lows, this.volumes),
|
|
1544
|
+
adl: this.calculateAdl(this.prices),
|
|
1545
|
+
volumeROC: this.calculateVolumeROC(),
|
|
1546
|
+
mfi: this.calculateMfi(this.prices, this.highs, this.lows, this.volumes),
|
|
1547
|
+
vwap: this.calculateVwap(this.prices, this.volumes),
|
|
1548
|
+
pivotPoints: this.calculatePivotPoints(this.prices),
|
|
1549
|
+
fibonacci: this.calculateFibonacciLevels(this.prices),
|
|
1550
|
+
gannLevels: this.calculateGannLevels(this.prices),
|
|
1551
|
+
elliottWave: this.calculateElliottWave(this.prices),
|
|
1552
|
+
harmonicPatterns: this.calculateHarmonicPatterns(this.prices)
|
|
1553
|
+
};
|
|
1554
|
+
}
|
|
1555
|
+
// Generate trading signals
|
|
1556
|
+
generateSignals() {
|
|
1557
|
+
const analysis = this.analyze();
|
|
1558
|
+
let bullishSignals = 0;
|
|
1559
|
+
let bearishSignals = 0;
|
|
1560
|
+
const signals = [];
|
|
1561
|
+
if (analysis.currentPrice > analysis.trueVWAP) {
|
|
1562
|
+
signals.push(
|
|
1563
|
+
`\u2713 BULLISH: Price above VWAP (+${((analysis.currentPrice - analysis.trueVWAP) / analysis.trueVWAP * 100).toFixed(2)}%)`
|
|
1564
|
+
);
|
|
1565
|
+
bullishSignals++;
|
|
1566
|
+
} else {
|
|
1567
|
+
signals.push(
|
|
1568
|
+
`\u2717 BEARISH: Price below VWAP (${((analysis.currentPrice - analysis.trueVWAP) / analysis.trueVWAP * 100).toFixed(2)}%)`
|
|
1569
|
+
);
|
|
1570
|
+
bearishSignals++;
|
|
1571
|
+
}
|
|
1572
|
+
if (analysis.momentum5 > 0 && analysis.momentum10 > 0) {
|
|
1573
|
+
signals.push("\u2713 BULLISH: Positive momentum on both timeframes");
|
|
1574
|
+
bullishSignals++;
|
|
1575
|
+
} else if (analysis.momentum5 < 0 && analysis.momentum10 < 0) {
|
|
1576
|
+
signals.push("\u2717 BEARISH: Negative momentum on both timeframes");
|
|
1577
|
+
bearishSignals++;
|
|
1578
|
+
} else {
|
|
1579
|
+
signals.push("\u25D0 MIXED: Conflicting momentum signals");
|
|
1580
|
+
}
|
|
1581
|
+
const currentVolume = this.volumes[this.volumes.length - 1];
|
|
1582
|
+
const volumeRatio = currentVolume / analysis.avgVolume;
|
|
1583
|
+
if (volumeRatio > 1.2 && analysis.sessionReturn > 0) {
|
|
1584
|
+
signals.push("\u2713 BULLISH: Above-average volume supporting upward move");
|
|
1585
|
+
bullishSignals++;
|
|
1586
|
+
} else if (volumeRatio > 1.2 && analysis.sessionReturn < 0) {
|
|
1587
|
+
signals.push("\u2717 BEARISH: Above-average volume supporting downward move");
|
|
1588
|
+
bearishSignals++;
|
|
1589
|
+
} else {
|
|
1590
|
+
signals.push("\u25D0 NEUTRAL: Volume not providing clear direction");
|
|
1591
|
+
}
|
|
1592
|
+
if (analysis.pricePosition > 65 && analysis.volatility > 30) {
|
|
1593
|
+
signals.push("\u2717 BEARISH: High in range with elevated volatility - reversal risk");
|
|
1594
|
+
bearishSignals++;
|
|
1595
|
+
} else if (analysis.pricePosition < 35 && analysis.volatility > 30) {
|
|
1596
|
+
signals.push("\u2713 BULLISH: Low in range with volatility - potential bounce");
|
|
1597
|
+
bullishSignals++;
|
|
1598
|
+
} else {
|
|
1599
|
+
signals.push("\u25D0 NEUTRAL: Price position and volatility not extreme");
|
|
1600
|
+
}
|
|
1601
|
+
return { bullishSignals, bearishSignals, signals };
|
|
1602
|
+
}
|
|
1603
|
+
// Generate comprehensive JSON analysis
|
|
1604
|
+
generateJSONAnalysis(symbol) {
|
|
1605
|
+
const analysis = this.analyze();
|
|
1606
|
+
const indicators = this.getTechnicalIndicators();
|
|
1607
|
+
const signals = this.generateSignals();
|
|
1608
|
+
const currentSMA5 = indicators.sma5.length > 0 ? indicators.sma5[indicators.sma5.length - 1] : null;
|
|
1609
|
+
const currentSMA10 = indicators.sma10.length > 0 ? indicators.sma10[indicators.sma10.length - 1] : null;
|
|
1610
|
+
const currentSMA20 = indicators.sma20.length > 0 ? indicators.sma20[indicators.sma20.length - 1] : null;
|
|
1611
|
+
const currentSMA50 = indicators.sma50.length > 0 ? indicators.sma50[indicators.sma50.length - 1] : null;
|
|
1612
|
+
const currentSMA200 = indicators.sma200.length > 0 ? indicators.sma200[indicators.sma200.length - 1] : null;
|
|
1613
|
+
const currentEMA8 = indicators.ema8[indicators.ema8.length - 1];
|
|
1614
|
+
const currentEMA12 = indicators.ema12[indicators.ema12.length - 1];
|
|
1615
|
+
const currentEMA21 = indicators.ema21[indicators.ema21.length - 1];
|
|
1616
|
+
const currentEMA26 = indicators.ema26[indicators.ema26.length - 1];
|
|
1617
|
+
const currentWMA20 = indicators.wma20.length > 0 ? indicators.wma20[indicators.wma20.length - 1] : null;
|
|
1618
|
+
const currentVWMA20 = indicators.vwma20.length > 0 ? indicators.vwma20[indicators.vwma20.length - 1] : null;
|
|
1619
|
+
const currentMACD = indicators.macd.length > 0 ? indicators.macd[indicators.macd.length - 1] : null;
|
|
1620
|
+
const currentADX = indicators.adx.length > 0 ? indicators.adx[indicators.adx.length - 1] : null;
|
|
1621
|
+
const currentDMI = indicators.dmi.length > 0 ? indicators.dmi[indicators.dmi.length - 1] : null;
|
|
1622
|
+
const currentIchimoku = indicators.ichimoku.length > 0 ? indicators.ichimoku[indicators.ichimoku.length - 1] : null;
|
|
1623
|
+
const currentParabolicSAR = indicators.parabolicSAR.length > 0 ? indicators.parabolicSAR[indicators.parabolicSAR.length - 1] : null;
|
|
1624
|
+
const currentRSI = indicators.rsi.length > 0 ? indicators.rsi[indicators.rsi.length - 1] : null;
|
|
1625
|
+
const currentStochastic = indicators.stochastic.length > 0 ? indicators.stochastic[indicators.stochastic.length - 1] : null;
|
|
1626
|
+
const currentCCI = indicators.cci.length > 0 ? indicators.cci[indicators.cci.length - 1] : null;
|
|
1627
|
+
const currentROC = indicators.roc.length > 0 ? indicators.roc[indicators.roc.length - 1] : null;
|
|
1628
|
+
const currentWilliamsR = indicators.williamsR.length > 0 ? indicators.williamsR[indicators.williamsR.length - 1] : null;
|
|
1629
|
+
const currentMomentum = indicators.momentum.length > 0 ? indicators.momentum[indicators.momentum.length - 1] : null;
|
|
1630
|
+
const currentBB = indicators.bollinger.length > 0 ? indicators.bollinger[indicators.bollinger.length - 1] : null;
|
|
1631
|
+
const currentAtr = indicators.atr.length > 0 ? indicators.atr[indicators.atr.length - 1] : null;
|
|
1632
|
+
const currentKeltner = indicators.keltner.length > 0 ? indicators.keltner[indicators.keltner.length - 1] : null;
|
|
1633
|
+
const currentDonchian = indicators.donchian.length > 0 ? indicators.donchian[indicators.donchian.length - 1] : null;
|
|
1634
|
+
const currentChaikinVolatility = indicators.chaikinVolatility.length > 0 ? indicators.chaikinVolatility[indicators.chaikinVolatility.length - 1] : null;
|
|
1635
|
+
const currentObv = indicators.obv.length > 0 ? indicators.obv[indicators.obv.length - 1] : null;
|
|
1636
|
+
const currentCmf = indicators.cmf.length > 0 ? indicators.cmf[indicators.cmf.length - 1] : null;
|
|
1637
|
+
const currentAdl = indicators.adl.length > 0 ? indicators.adl[indicators.adl.length - 1] : null;
|
|
1638
|
+
const currentVolumeROC = indicators.volumeROC.length > 0 ? indicators.volumeROC[indicators.volumeROC.length - 1] : null;
|
|
1639
|
+
const currentMfi = indicators.mfi.length > 0 ? indicators.mfi[indicators.mfi.length - 1] : null;
|
|
1640
|
+
const currentVwap = indicators.vwap.length > 0 ? indicators.vwap[indicators.vwap.length - 1] : null;
|
|
1641
|
+
const currentPivotPoints = indicators.pivotPoints.length > 0 ? indicators.pivotPoints[indicators.pivotPoints.length - 1] : null;
|
|
1642
|
+
const currentFibonacci = indicators.fibonacci.length > 0 ? indicators.fibonacci[indicators.fibonacci.length - 1] : null;
|
|
1643
|
+
const currentGannLevels = indicators.gannLevels.length > 0 ? indicators.gannLevels : [];
|
|
1644
|
+
const currentElliottWave = indicators.elliottWave.length > 0 ? indicators.elliottWave[indicators.elliottWave.length - 1] : null;
|
|
1645
|
+
const currentHarmonicPatterns = indicators.harmonicPatterns.length > 0 ? indicators.harmonicPatterns : [];
|
|
1646
|
+
const currentVolume = this.volumes[this.volumes.length - 1];
|
|
1647
|
+
const volumeRatio = currentVolume / analysis.avgVolume;
|
|
1648
|
+
const currentDrawdown = (analysis.sessionHigh - analysis.currentPrice) / analysis.sessionHigh * 100;
|
|
1649
|
+
const rangeWidth = (analysis.sessionHigh - analysis.sessionLow) / analysis.sessionLow * 100;
|
|
1650
|
+
const priceVsVWAP = (analysis.currentPrice - analysis.trueVWAP) / analysis.trueVWAP * 100;
|
|
1651
|
+
const totalScore = signals.bullishSignals - signals.bearishSignals;
|
|
1652
|
+
const overallSignal = totalScore > 0 ? "BULLISH_BIAS" : totalScore < 0 ? "BEARISH_BIAS" : "NEUTRAL";
|
|
1653
|
+
const targetEntry = Math.max(analysis.sessionLow * 1.005, analysis.trueVWAP * 0.998);
|
|
1654
|
+
const stopLoss = analysis.sessionLow * 0.995;
|
|
1655
|
+
const profitTarget = analysis.sessionHigh * 0.995;
|
|
1656
|
+
const riskRewardRatio = (profitTarget - analysis.currentPrice) / (analysis.currentPrice - stopLoss);
|
|
1657
|
+
const positionSize = this.calculatePositionSize(analysis.currentPrice, targetEntry, stopLoss);
|
|
1658
|
+
const maxRisk = positionSize * (targetEntry - stopLoss);
|
|
1659
|
+
return {
|
|
1660
|
+
symbol,
|
|
1661
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1662
|
+
marketStructure: {
|
|
1663
|
+
currentPrice: analysis.currentPrice,
|
|
1664
|
+
startPrice: analysis.startPrice,
|
|
1665
|
+
sessionHigh: analysis.sessionHigh,
|
|
1666
|
+
sessionLow: analysis.sessionLow,
|
|
1667
|
+
rangeWidth,
|
|
1668
|
+
totalVolume: analysis.totalVolume,
|
|
1669
|
+
sessionPerformance: analysis.sessionReturn,
|
|
1670
|
+
positionInRange: analysis.pricePosition
|
|
1671
|
+
},
|
|
1672
|
+
volatility: {
|
|
1673
|
+
impliedVolatility: analysis.impliedVolatility,
|
|
1674
|
+
realizedVolatility: analysis.realizedVolatility,
|
|
1675
|
+
atr: analysis.atr,
|
|
1676
|
+
maxDrawdown: analysis.maxDrawdown * 100,
|
|
1677
|
+
currentDrawdown
|
|
1678
|
+
},
|
|
1679
|
+
technicalIndicators: {
|
|
1680
|
+
sma5: currentSMA5,
|
|
1681
|
+
sma10: currentSMA10,
|
|
1682
|
+
sma20: currentSMA20,
|
|
1683
|
+
sma50: currentSMA50,
|
|
1684
|
+
sma200: currentSMA200,
|
|
1685
|
+
ema8: currentEMA8,
|
|
1686
|
+
ema12: currentEMA12,
|
|
1687
|
+
ema21: currentEMA21,
|
|
1688
|
+
ema26: currentEMA26,
|
|
1689
|
+
wma20: currentWMA20,
|
|
1690
|
+
vwma20: currentVWMA20,
|
|
1691
|
+
macd: currentMACD,
|
|
1692
|
+
adx: currentADX,
|
|
1693
|
+
dmi: currentDMI,
|
|
1694
|
+
ichimoku: currentIchimoku,
|
|
1695
|
+
parabolicSAR: currentParabolicSAR,
|
|
1696
|
+
rsi: currentRSI,
|
|
1697
|
+
stochastic: currentStochastic,
|
|
1698
|
+
cci: currentCCI,
|
|
1699
|
+
roc: currentROC,
|
|
1700
|
+
williamsR: currentWilliamsR,
|
|
1701
|
+
momentum: currentMomentum,
|
|
1702
|
+
bollingerBands: currentBB ? {
|
|
1703
|
+
upper: currentBB.upper,
|
|
1704
|
+
middle: currentBB.middle,
|
|
1705
|
+
lower: currentBB.lower,
|
|
1706
|
+
bandwidth: currentBB.bandwidth,
|
|
1707
|
+
percentB: currentBB.percentB
|
|
1708
|
+
} : null,
|
|
1709
|
+
atr: currentAtr,
|
|
1710
|
+
keltnerChannels: currentKeltner ? {
|
|
1711
|
+
upper: currentKeltner.upper,
|
|
1712
|
+
middle: currentKeltner.middle,
|
|
1713
|
+
lower: currentKeltner.lower
|
|
1714
|
+
} : null,
|
|
1715
|
+
donchianChannels: currentDonchian ? {
|
|
1716
|
+
upper: currentDonchian.upper,
|
|
1717
|
+
middle: currentDonchian.middle,
|
|
1718
|
+
lower: currentDonchian.lower
|
|
1719
|
+
} : null,
|
|
1720
|
+
chaikinVolatility: currentChaikinVolatility,
|
|
1721
|
+
obv: currentObv,
|
|
1722
|
+
cmf: currentCmf,
|
|
1723
|
+
adl: currentAdl,
|
|
1724
|
+
volumeROC: currentVolumeROC,
|
|
1725
|
+
mfi: currentMfi,
|
|
1726
|
+
vwap: currentVwap
|
|
1727
|
+
},
|
|
1728
|
+
volumeAnalysis: {
|
|
1729
|
+
currentVolume,
|
|
1730
|
+
averageVolume: Math.round(analysis.avgVolume),
|
|
1731
|
+
volumeRatio,
|
|
1732
|
+
trueVWAP: analysis.trueVWAP,
|
|
1733
|
+
priceVsVWAP,
|
|
1734
|
+
obv: currentObv,
|
|
1735
|
+
cmf: currentCmf,
|
|
1736
|
+
mfi: currentMfi
|
|
1737
|
+
},
|
|
1738
|
+
momentum: {
|
|
1739
|
+
momentum5: analysis.momentum5,
|
|
1740
|
+
momentum10: analysis.momentum10,
|
|
1741
|
+
sessionROC: analysis.sessionReturn,
|
|
1742
|
+
rsi: currentRSI,
|
|
1743
|
+
stochastic: currentStochastic,
|
|
1744
|
+
cci: currentCCI
|
|
1745
|
+
},
|
|
1746
|
+
supportResistance: {
|
|
1747
|
+
pivotPoints: currentPivotPoints,
|
|
1748
|
+
fibonacci: currentFibonacci,
|
|
1749
|
+
gannLevels: currentGannLevels,
|
|
1750
|
+
elliottWave: currentElliottWave,
|
|
1751
|
+
harmonicPatterns: currentHarmonicPatterns
|
|
1752
|
+
},
|
|
1753
|
+
tradingSignals: {
|
|
1754
|
+
...signals,
|
|
1755
|
+
overallSignal,
|
|
1756
|
+
signalScore: totalScore,
|
|
1757
|
+
confidence: this.calculateConfidence(signals.signals),
|
|
1758
|
+
riskLevel: this.calculateRiskLevel(analysis.volatility)
|
|
1759
|
+
},
|
|
1760
|
+
statisticalModels: {
|
|
1761
|
+
zScore: this.calculateZScore(analysis.currentPrice, analysis.startPrice),
|
|
1762
|
+
ornsteinUhlenbeck: this.calculateOrnsteinUhlenbeck(
|
|
1763
|
+
analysis.currentPrice,
|
|
1764
|
+
analysis.startPrice,
|
|
1765
|
+
analysis.avgVolume
|
|
1766
|
+
),
|
|
1767
|
+
kalmanFilter: this.calculateKalmanFilter(
|
|
1768
|
+
analysis.currentPrice,
|
|
1769
|
+
analysis.startPrice,
|
|
1770
|
+
analysis.avgVolume
|
|
1771
|
+
),
|
|
1772
|
+
arima: this.calculateArima(analysis.currentPrice),
|
|
1773
|
+
garch: this.calculateGarch(analysis.avgVolume),
|
|
1774
|
+
hilbertTransform: this.calculateHilbertTransform(analysis.currentPrice),
|
|
1775
|
+
waveletTransform: this.calculateWaveletTransform(analysis.currentPrice)
|
|
1776
|
+
},
|
|
1777
|
+
optionsAnalysis: (() => {
|
|
1778
|
+
const blackScholes = this.calculateBlackScholes(
|
|
1779
|
+
analysis.currentPrice,
|
|
1780
|
+
analysis.startPrice,
|
|
1781
|
+
analysis.avgVolume
|
|
1782
|
+
);
|
|
1783
|
+
if (!blackScholes) return null;
|
|
1784
|
+
return {
|
|
1785
|
+
blackScholes,
|
|
1786
|
+
impliedVolatility: analysis.impliedVolatility,
|
|
1787
|
+
delta: blackScholes.delta,
|
|
1788
|
+
gamma: blackScholes.gamma,
|
|
1789
|
+
theta: blackScholes.theta,
|
|
1790
|
+
vega: blackScholes.vega,
|
|
1791
|
+
rho: blackScholes.rho,
|
|
1792
|
+
greeks: {
|
|
1793
|
+
delta: blackScholes.delta,
|
|
1794
|
+
gamma: blackScholes.gamma,
|
|
1795
|
+
theta: blackScholes.theta,
|
|
1796
|
+
vega: blackScholes.vega,
|
|
1797
|
+
rho: blackScholes.rho
|
|
1798
|
+
}
|
|
1799
|
+
};
|
|
1800
|
+
})(),
|
|
1801
|
+
riskManagement: {
|
|
1802
|
+
targetEntry,
|
|
1803
|
+
stopLoss,
|
|
1804
|
+
profitTarget,
|
|
1805
|
+
riskRewardRatio,
|
|
1806
|
+
positionSize,
|
|
1807
|
+
maxRisk
|
|
1808
|
+
},
|
|
1809
|
+
performance: {
|
|
1810
|
+
sharpeRatio: analysis.sharpeRatio,
|
|
1811
|
+
sortinoRatio: analysis.sortinoRatio,
|
|
1812
|
+
calmarRatio: analysis.calmarRatio,
|
|
1813
|
+
maxDrawdown: analysis.maxDrawdown * 100,
|
|
1814
|
+
winRate: analysis.winRate,
|
|
1815
|
+
profitFactor: analysis.profitFactor,
|
|
1816
|
+
totalReturn: analysis.sessionReturn,
|
|
1817
|
+
volatility: analysis.volatility
|
|
1818
|
+
}
|
|
1819
|
+
};
|
|
1820
|
+
}
|
|
1821
|
+
};
|
|
1822
|
+
var createTechnicalAnalysisHandler = (marketDataPrices) => {
|
|
1823
|
+
return async (args) => {
|
|
1824
|
+
try {
|
|
1825
|
+
const symbol = args.symbol;
|
|
1826
|
+
const priceHistory = marketDataPrices.get(symbol) || [];
|
|
1827
|
+
if (priceHistory.length === 0) {
|
|
1828
|
+
return {
|
|
1829
|
+
content: [
|
|
1830
|
+
{
|
|
1831
|
+
type: "text",
|
|
1832
|
+
text: `No price data available for ${symbol}. Please request market data first.`,
|
|
1833
|
+
uri: "technicalAnalysis"
|
|
1834
|
+
}
|
|
1835
|
+
]
|
|
1836
|
+
};
|
|
1837
|
+
}
|
|
1838
|
+
const hasValidData = priceHistory.every(
|
|
1839
|
+
(entry) => typeof entry.trade === "number" && !Number.isNaN(entry.trade) && typeof entry.midPrice === "number" && !Number.isNaN(entry.midPrice)
|
|
1840
|
+
);
|
|
1841
|
+
if (!hasValidData) {
|
|
1842
|
+
throw new Error("Invalid market data");
|
|
1843
|
+
}
|
|
1844
|
+
const analyzer = new TechnicalAnalyzer(priceHistory);
|
|
1845
|
+
const analysis = analyzer.generateJSONAnalysis(symbol);
|
|
1846
|
+
return {
|
|
1847
|
+
content: [
|
|
1848
|
+
{
|
|
1849
|
+
type: "text",
|
|
1850
|
+
text: `Technical Analysis for ${symbol}:
|
|
1851
|
+
|
|
1852
|
+
${JSON.stringify(analysis, null, 2)}`,
|
|
1853
|
+
uri: "technicalAnalysis"
|
|
1854
|
+
}
|
|
1855
|
+
]
|
|
1856
|
+
};
|
|
1857
|
+
} catch (error) {
|
|
1858
|
+
return {
|
|
1859
|
+
content: [
|
|
1860
|
+
{
|
|
1861
|
+
type: "text",
|
|
1862
|
+
text: `Error performing technical analysis: ${error instanceof Error ? error.message : "Unknown error"}`,
|
|
1863
|
+
uri: "technicalAnalysis"
|
|
1864
|
+
}
|
|
1865
|
+
],
|
|
1866
|
+
isError: true
|
|
1867
|
+
};
|
|
1868
|
+
}
|
|
1869
|
+
};
|
|
1870
|
+
};
|
|
1871
|
+
|
|
313
1872
|
// src/tools/marketData.ts
|
|
314
1873
|
var import_fixparser = require("fixparser");
|
|
315
1874
|
var import_quickchart_js = __toESM(require("quickchart-js"), 1);
|
|
316
1875
|
var createMarketDataRequestHandler = (parser, pendingRequests) => {
|
|
317
1876
|
return async (args) => {
|
|
318
1877
|
try {
|
|
1878
|
+
parser.logger.log({
|
|
1879
|
+
level: "info",
|
|
1880
|
+
message: `Sending market data request for symbols: ${args.symbols.join(", ")}`
|
|
1881
|
+
});
|
|
319
1882
|
const response = new Promise((resolve) => {
|
|
320
1883
|
pendingRequests.set(args.mdReqID, resolve);
|
|
1884
|
+
parser.logger.log({
|
|
1885
|
+
level: "info",
|
|
1886
|
+
message: `Registered callback for market data request ID: ${args.mdReqID}`
|
|
1887
|
+
});
|
|
321
1888
|
});
|
|
322
|
-
const entryTypes = args.mdEntryTypes || [
|
|
1889
|
+
const entryTypes = args.mdEntryTypes || [
|
|
1890
|
+
import_fixparser.MDEntryType.Bid,
|
|
1891
|
+
import_fixparser.MDEntryType.Offer,
|
|
1892
|
+
import_fixparser.MDEntryType.Trade,
|
|
1893
|
+
import_fixparser.MDEntryType.IndexValue,
|
|
1894
|
+
import_fixparser.MDEntryType.OpeningPrice,
|
|
1895
|
+
import_fixparser.MDEntryType.ClosingPrice,
|
|
1896
|
+
import_fixparser.MDEntryType.SettlementPrice,
|
|
1897
|
+
import_fixparser.MDEntryType.TradingSessionHighPrice,
|
|
1898
|
+
import_fixparser.MDEntryType.TradingSessionLowPrice,
|
|
1899
|
+
import_fixparser.MDEntryType.VWAP,
|
|
1900
|
+
import_fixparser.MDEntryType.Imbalance,
|
|
1901
|
+
import_fixparser.MDEntryType.TradeVolume,
|
|
1902
|
+
import_fixparser.MDEntryType.OpenInterest,
|
|
1903
|
+
import_fixparser.MDEntryType.CompositeUnderlyingPrice,
|
|
1904
|
+
import_fixparser.MDEntryType.SimulatedSellPrice,
|
|
1905
|
+
import_fixparser.MDEntryType.SimulatedBuyPrice,
|
|
1906
|
+
import_fixparser.MDEntryType.MarginRate,
|
|
1907
|
+
import_fixparser.MDEntryType.MidPrice,
|
|
1908
|
+
import_fixparser.MDEntryType.EmptyBook,
|
|
1909
|
+
import_fixparser.MDEntryType.SettleHighPrice,
|
|
1910
|
+
import_fixparser.MDEntryType.SettleLowPrice,
|
|
1911
|
+
import_fixparser.MDEntryType.PriorSettlePrice,
|
|
1912
|
+
import_fixparser.MDEntryType.SessionHighBid,
|
|
1913
|
+
import_fixparser.MDEntryType.SessionLowOffer,
|
|
1914
|
+
import_fixparser.MDEntryType.EarlyPrices,
|
|
1915
|
+
import_fixparser.MDEntryType.AuctionClearingPrice,
|
|
1916
|
+
import_fixparser.MDEntryType.SwapValueFactor,
|
|
1917
|
+
import_fixparser.MDEntryType.DailyValueAdjustmentForLongPositions,
|
|
1918
|
+
import_fixparser.MDEntryType.CumulativeValueAdjustmentForLongPositions,
|
|
1919
|
+
import_fixparser.MDEntryType.DailyValueAdjustmentForShortPositions,
|
|
1920
|
+
import_fixparser.MDEntryType.CumulativeValueAdjustmentForShortPositions,
|
|
1921
|
+
import_fixparser.MDEntryType.FixingPrice,
|
|
1922
|
+
import_fixparser.MDEntryType.CashRate,
|
|
1923
|
+
import_fixparser.MDEntryType.RecoveryRate,
|
|
1924
|
+
import_fixparser.MDEntryType.RecoveryRateForLong,
|
|
1925
|
+
import_fixparser.MDEntryType.RecoveryRateForShort,
|
|
1926
|
+
import_fixparser.MDEntryType.MarketBid,
|
|
1927
|
+
import_fixparser.MDEntryType.MarketOffer,
|
|
1928
|
+
import_fixparser.MDEntryType.ShortSaleMinPrice,
|
|
1929
|
+
import_fixparser.MDEntryType.PreviousClosingPrice,
|
|
1930
|
+
import_fixparser.MDEntryType.ThresholdLimitPriceBanding,
|
|
1931
|
+
import_fixparser.MDEntryType.DailyFinancingValue,
|
|
1932
|
+
import_fixparser.MDEntryType.AccruedFinancingValue,
|
|
1933
|
+
import_fixparser.MDEntryType.TWAP
|
|
1934
|
+
];
|
|
323
1935
|
const messageFields = [
|
|
324
1936
|
new import_fixparser.Field(import_fixparser.Fields.MsgType, import_fixparser.Messages.MarketDataRequest),
|
|
325
1937
|
new import_fixparser.Field(import_fixparser.Fields.SenderCompID, parser.sender),
|
|
@@ -341,6 +1953,10 @@ var createMarketDataRequestHandler = (parser, pendingRequests) => {
|
|
|
341
1953
|
});
|
|
342
1954
|
const mdr = parser.createMessage(...messageFields);
|
|
343
1955
|
if (!parser.connected) {
|
|
1956
|
+
parser.logger.log({
|
|
1957
|
+
level: "error",
|
|
1958
|
+
message: "Not connected. Cannot send market data request."
|
|
1959
|
+
});
|
|
344
1960
|
return {
|
|
345
1961
|
content: [
|
|
346
1962
|
{
|
|
@@ -352,8 +1968,16 @@ var createMarketDataRequestHandler = (parser, pendingRequests) => {
|
|
|
352
1968
|
isError: true
|
|
353
1969
|
};
|
|
354
1970
|
}
|
|
1971
|
+
parser.logger.log({
|
|
1972
|
+
level: "info",
|
|
1973
|
+
message: `Sending market data request message: ${JSON.stringify(mdr?.toFIXJSON())}`
|
|
1974
|
+
});
|
|
355
1975
|
parser.send(mdr);
|
|
356
1976
|
const fixData = await response;
|
|
1977
|
+
parser.logger.log({
|
|
1978
|
+
level: "info",
|
|
1979
|
+
message: `Received market data response for request ID: ${args.mdReqID}`
|
|
1980
|
+
});
|
|
357
1981
|
return {
|
|
358
1982
|
content: [
|
|
359
1983
|
{
|
|
@@ -377,6 +2001,72 @@ var createMarketDataRequestHandler = (parser, pendingRequests) => {
|
|
|
377
2001
|
}
|
|
378
2002
|
};
|
|
379
2003
|
};
|
|
2004
|
+
var aggregateMarketData = (priceHistory, maxPoints = 490) => {
|
|
2005
|
+
if (priceHistory.length <= maxPoints) {
|
|
2006
|
+
return priceHistory;
|
|
2007
|
+
}
|
|
2008
|
+
const result = [];
|
|
2009
|
+
const step = priceHistory.length / maxPoints;
|
|
2010
|
+
result.push(priceHistory[0]);
|
|
2011
|
+
for (let i = 1; i < maxPoints - 1; i++) {
|
|
2012
|
+
const startIndex = Math.floor(i * step);
|
|
2013
|
+
const endIndex = Math.floor((i + 1) * step);
|
|
2014
|
+
const segment = priceHistory.slice(startIndex, endIndex);
|
|
2015
|
+
if (segment.length === 0) continue;
|
|
2016
|
+
const aggregatedPoint = {
|
|
2017
|
+
timestamp: segment[0].timestamp,
|
|
2018
|
+
// Use timestamp of first point in segment
|
|
2019
|
+
bid: segment.reduce((sum2, p) => sum2 + p.bid, 0) / segment.length,
|
|
2020
|
+
offer: segment.reduce((sum2, p) => sum2 + p.offer, 0) / segment.length,
|
|
2021
|
+
spread: segment.reduce((sum2, p) => sum2 + p.spread, 0) / segment.length,
|
|
2022
|
+
volume: segment.reduce((sum2, p) => sum2 + p.volume, 0) / segment.length,
|
|
2023
|
+
trade: segment.reduce((sum2, p) => sum2 + p.trade, 0) / segment.length,
|
|
2024
|
+
indexValue: segment.reduce((sum2, p) => sum2 + p.indexValue, 0) / segment.length,
|
|
2025
|
+
openingPrice: segment.reduce((sum2, p) => sum2 + p.openingPrice, 0) / segment.length,
|
|
2026
|
+
closingPrice: segment.reduce((sum2, p) => sum2 + p.closingPrice, 0) / segment.length,
|
|
2027
|
+
settlementPrice: segment.reduce((sum2, p) => sum2 + p.settlementPrice, 0) / segment.length,
|
|
2028
|
+
tradingSessionHighPrice: segment.reduce((sum2, p) => sum2 + p.tradingSessionHighPrice, 0) / segment.length,
|
|
2029
|
+
tradingSessionLowPrice: segment.reduce((sum2, p) => sum2 + p.tradingSessionLowPrice, 0) / segment.length,
|
|
2030
|
+
vwap: segment.reduce((sum2, p) => sum2 + p.vwap, 0) / segment.length,
|
|
2031
|
+
imbalance: segment.reduce((sum2, p) => sum2 + p.imbalance, 0) / segment.length,
|
|
2032
|
+
openInterest: segment.reduce((sum2, p) => sum2 + p.openInterest, 0) / segment.length,
|
|
2033
|
+
compositeUnderlyingPrice: segment.reduce((sum2, p) => sum2 + p.compositeUnderlyingPrice, 0) / segment.length,
|
|
2034
|
+
simulatedSellPrice: segment.reduce((sum2, p) => sum2 + p.simulatedSellPrice, 0) / segment.length,
|
|
2035
|
+
simulatedBuyPrice: segment.reduce((sum2, p) => sum2 + p.simulatedBuyPrice, 0) / segment.length,
|
|
2036
|
+
marginRate: segment.reduce((sum2, p) => sum2 + p.marginRate, 0) / segment.length,
|
|
2037
|
+
midPrice: segment.reduce((sum2, p) => sum2 + p.midPrice, 0) / segment.length,
|
|
2038
|
+
emptyBook: segment.reduce((sum2, p) => sum2 + p.emptyBook, 0) / segment.length,
|
|
2039
|
+
settleHighPrice: segment.reduce((sum2, p) => sum2 + p.settleHighPrice, 0) / segment.length,
|
|
2040
|
+
settleLowPrice: segment.reduce((sum2, p) => sum2 + p.settleLowPrice, 0) / segment.length,
|
|
2041
|
+
priorSettlePrice: segment.reduce((sum2, p) => sum2 + p.priorSettlePrice, 0) / segment.length,
|
|
2042
|
+
sessionHighBid: segment.reduce((sum2, p) => sum2 + p.sessionHighBid, 0) / segment.length,
|
|
2043
|
+
sessionLowOffer: segment.reduce((sum2, p) => sum2 + p.sessionLowOffer, 0) / segment.length,
|
|
2044
|
+
earlyPrices: segment.reduce((sum2, p) => sum2 + p.earlyPrices, 0) / segment.length,
|
|
2045
|
+
auctionClearingPrice: segment.reduce((sum2, p) => sum2 + p.auctionClearingPrice, 0) / segment.length,
|
|
2046
|
+
swapValueFactor: segment.reduce((sum2, p) => sum2 + p.swapValueFactor, 0) / segment.length,
|
|
2047
|
+
dailyValueAdjustmentForLongPositions: segment.reduce((sum2, p) => sum2 + p.dailyValueAdjustmentForLongPositions, 0) / segment.length,
|
|
2048
|
+
cumulativeValueAdjustmentForLongPositions: segment.reduce((sum2, p) => sum2 + p.cumulativeValueAdjustmentForLongPositions, 0) / segment.length,
|
|
2049
|
+
dailyValueAdjustmentForShortPositions: segment.reduce((sum2, p) => sum2 + p.dailyValueAdjustmentForShortPositions, 0) / segment.length,
|
|
2050
|
+
cumulativeValueAdjustmentForShortPositions: segment.reduce((sum2, p) => sum2 + p.cumulativeValueAdjustmentForShortPositions, 0) / segment.length,
|
|
2051
|
+
fixingPrice: segment.reduce((sum2, p) => sum2 + p.fixingPrice, 0) / segment.length,
|
|
2052
|
+
cashRate: segment.reduce((sum2, p) => sum2 + p.cashRate, 0) / segment.length,
|
|
2053
|
+
recoveryRate: segment.reduce((sum2, p) => sum2 + p.recoveryRate, 0) / segment.length,
|
|
2054
|
+
recoveryRateForLong: segment.reduce((sum2, p) => sum2 + p.recoveryRateForLong, 0) / segment.length,
|
|
2055
|
+
recoveryRateForShort: segment.reduce((sum2, p) => sum2 + p.recoveryRateForShort, 0) / segment.length,
|
|
2056
|
+
marketBid: segment.reduce((sum2, p) => sum2 + p.marketBid, 0) / segment.length,
|
|
2057
|
+
marketOffer: segment.reduce((sum2, p) => sum2 + p.marketOffer, 0) / segment.length,
|
|
2058
|
+
shortSaleMinPrice: segment.reduce((sum2, p) => sum2 + p.shortSaleMinPrice, 0) / segment.length,
|
|
2059
|
+
previousClosingPrice: segment.reduce((sum2, p) => sum2 + p.previousClosingPrice, 0) / segment.length,
|
|
2060
|
+
thresholdLimitPriceBanding: segment.reduce((sum2, p) => sum2 + p.thresholdLimitPriceBanding, 0) / segment.length,
|
|
2061
|
+
dailyFinancingValue: segment.reduce((sum2, p) => sum2 + p.dailyFinancingValue, 0) / segment.length,
|
|
2062
|
+
accruedFinancingValue: segment.reduce((sum2, p) => sum2 + p.accruedFinancingValue, 0) / segment.length,
|
|
2063
|
+
twap: segment.reduce((sum2, p) => sum2 + p.twap, 0) / segment.length
|
|
2064
|
+
};
|
|
2065
|
+
result.push(aggregatedPoint);
|
|
2066
|
+
}
|
|
2067
|
+
result.push(priceHistory[priceHistory.length - 1]);
|
|
2068
|
+
return result;
|
|
2069
|
+
};
|
|
380
2070
|
var createGetStockGraphHandler = (marketDataPrices) => {
|
|
381
2071
|
return async (args) => {
|
|
382
2072
|
try {
|
|
@@ -393,15 +2083,22 @@ var createGetStockGraphHandler = (marketDataPrices) => {
|
|
|
393
2083
|
]
|
|
394
2084
|
};
|
|
395
2085
|
}
|
|
2086
|
+
const aggregatedData = aggregateMarketData(priceHistory, 500);
|
|
396
2087
|
const chart = new import_quickchart_js.default();
|
|
397
2088
|
chart.setWidth(1200);
|
|
398
2089
|
chart.setHeight(600);
|
|
399
2090
|
chart.setBackgroundColor("transparent");
|
|
400
|
-
const labels =
|
|
401
|
-
const bidData =
|
|
402
|
-
const offerData =
|
|
403
|
-
const spreadData =
|
|
404
|
-
const volumeData =
|
|
2091
|
+
const labels = aggregatedData.map((point) => new Date(point.timestamp).toLocaleTimeString());
|
|
2092
|
+
const bidData = aggregatedData.map((point) => point.bid);
|
|
2093
|
+
const offerData = aggregatedData.map((point) => point.offer);
|
|
2094
|
+
const spreadData = aggregatedData.map((point) => point.spread);
|
|
2095
|
+
const volumeData = aggregatedData.map((point) => point.volume);
|
|
2096
|
+
const tradeData = aggregatedData.map((point) => point.trade);
|
|
2097
|
+
const vwapData = aggregatedData.map((point) => point.vwap);
|
|
2098
|
+
const twapData = aggregatedData.map((point) => point.twap);
|
|
2099
|
+
const maxVolume = Math.max(...volumeData.filter((v) => v > 0));
|
|
2100
|
+
const maxPrice = Math.max(...bidData, ...offerData, ...tradeData, ...vwapData, ...twapData);
|
|
2101
|
+
const normalizedVolumeData = volumeData.map((v) => v / maxVolume * maxPrice * 0.3);
|
|
405
2102
|
const config = {
|
|
406
2103
|
type: "line",
|
|
407
2104
|
data: {
|
|
@@ -432,8 +2129,32 @@ var createGetStockGraphHandler = (marketDataPrices) => {
|
|
|
432
2129
|
tension: 0.4
|
|
433
2130
|
},
|
|
434
2131
|
{
|
|
435
|
-
label: "
|
|
436
|
-
data:
|
|
2132
|
+
label: "Trade",
|
|
2133
|
+
data: tradeData,
|
|
2134
|
+
borderColor: "#ffc107",
|
|
2135
|
+
backgroundColor: "rgba(255, 193, 7, 0.1)",
|
|
2136
|
+
fill: false,
|
|
2137
|
+
tension: 0.4
|
|
2138
|
+
},
|
|
2139
|
+
{
|
|
2140
|
+
label: "VWAP",
|
|
2141
|
+
data: vwapData,
|
|
2142
|
+
borderColor: "#17a2b8",
|
|
2143
|
+
backgroundColor: "rgba(23, 162, 184, 0.1)",
|
|
2144
|
+
fill: false,
|
|
2145
|
+
tension: 0.4
|
|
2146
|
+
},
|
|
2147
|
+
{
|
|
2148
|
+
label: "TWAP",
|
|
2149
|
+
data: twapData,
|
|
2150
|
+
borderColor: "#6610f2",
|
|
2151
|
+
backgroundColor: "rgba(102, 16, 242, 0.1)",
|
|
2152
|
+
fill: false,
|
|
2153
|
+
tension: 0.4
|
|
2154
|
+
},
|
|
2155
|
+
{
|
|
2156
|
+
label: "Volume (Normalized)",
|
|
2157
|
+
data: normalizedVolumeData,
|
|
437
2158
|
borderColor: "#007bff",
|
|
438
2159
|
backgroundColor: "rgba(0, 123, 255, 0.1)",
|
|
439
2160
|
fill: true,
|
|
@@ -446,12 +2167,16 @@ var createGetStockGraphHandler = (marketDataPrices) => {
|
|
|
446
2167
|
plugins: {
|
|
447
2168
|
title: {
|
|
448
2169
|
display: true,
|
|
449
|
-
text: `${symbol} Market Data`
|
|
2170
|
+
text: `${symbol} Market Data (Volume normalized to 30% of max price)`
|
|
450
2171
|
}
|
|
451
2172
|
},
|
|
452
2173
|
scales: {
|
|
453
2174
|
y: {
|
|
454
|
-
beginAtZero: false
|
|
2175
|
+
beginAtZero: false,
|
|
2176
|
+
title: {
|
|
2177
|
+
display: true,
|
|
2178
|
+
text: "Price / Normalized Volume"
|
|
2179
|
+
}
|
|
455
2180
|
}
|
|
456
2181
|
}
|
|
457
2182
|
}
|
|
@@ -476,7 +2201,7 @@ var createGetStockGraphHandler = (marketDataPrices) => {
|
|
|
476
2201
|
content: [
|
|
477
2202
|
{
|
|
478
2203
|
type: "text",
|
|
479
|
-
text: `Error: ${error instanceof Error ? error.message : "Failed to generate
|
|
2204
|
+
text: `Error: ${error instanceof Error ? error.message : "Failed to generate graph"}`,
|
|
480
2205
|
uri: "getStockGraph"
|
|
481
2206
|
}
|
|
482
2207
|
],
|
|
@@ -501,6 +2226,7 @@ var createGetStockPriceHistoryHandler = (marketDataPrices) => {
|
|
|
501
2226
|
]
|
|
502
2227
|
};
|
|
503
2228
|
}
|
|
2229
|
+
const aggregatedData = aggregateMarketData(priceHistory, 500);
|
|
504
2230
|
return {
|
|
505
2231
|
content: [
|
|
506
2232
|
{
|
|
@@ -508,13 +2234,55 @@ var createGetStockPriceHistoryHandler = (marketDataPrices) => {
|
|
|
508
2234
|
text: JSON.stringify(
|
|
509
2235
|
{
|
|
510
2236
|
symbol,
|
|
511
|
-
count:
|
|
512
|
-
|
|
2237
|
+
count: aggregatedData.length,
|
|
2238
|
+
originalCount: priceHistory.length,
|
|
2239
|
+
data: aggregatedData.map((point) => ({
|
|
513
2240
|
timestamp: new Date(point.timestamp).toISOString(),
|
|
514
2241
|
bid: point.bid,
|
|
515
2242
|
offer: point.offer,
|
|
516
2243
|
spread: point.spread,
|
|
517
|
-
volume: point.volume
|
|
2244
|
+
volume: point.volume,
|
|
2245
|
+
trade: point.trade,
|
|
2246
|
+
indexValue: point.indexValue,
|
|
2247
|
+
openingPrice: point.openingPrice,
|
|
2248
|
+
closingPrice: point.closingPrice,
|
|
2249
|
+
settlementPrice: point.settlementPrice,
|
|
2250
|
+
tradingSessionHighPrice: point.tradingSessionHighPrice,
|
|
2251
|
+
tradingSessionLowPrice: point.tradingSessionLowPrice,
|
|
2252
|
+
vwap: point.vwap,
|
|
2253
|
+
imbalance: point.imbalance,
|
|
2254
|
+
openInterest: point.openInterest,
|
|
2255
|
+
compositeUnderlyingPrice: point.compositeUnderlyingPrice,
|
|
2256
|
+
simulatedSellPrice: point.simulatedSellPrice,
|
|
2257
|
+
simulatedBuyPrice: point.simulatedBuyPrice,
|
|
2258
|
+
marginRate: point.marginRate,
|
|
2259
|
+
midPrice: point.midPrice,
|
|
2260
|
+
emptyBook: point.emptyBook,
|
|
2261
|
+
settleHighPrice: point.settleHighPrice,
|
|
2262
|
+
settleLowPrice: point.settleLowPrice,
|
|
2263
|
+
priorSettlePrice: point.priorSettlePrice,
|
|
2264
|
+
sessionHighBid: point.sessionHighBid,
|
|
2265
|
+
sessionLowOffer: point.sessionLowOffer,
|
|
2266
|
+
earlyPrices: point.earlyPrices,
|
|
2267
|
+
auctionClearingPrice: point.auctionClearingPrice,
|
|
2268
|
+
swapValueFactor: point.swapValueFactor,
|
|
2269
|
+
dailyValueAdjustmentForLongPositions: point.dailyValueAdjustmentForLongPositions,
|
|
2270
|
+
cumulativeValueAdjustmentForLongPositions: point.cumulativeValueAdjustmentForLongPositions,
|
|
2271
|
+
dailyValueAdjustmentForShortPositions: point.dailyValueAdjustmentForShortPositions,
|
|
2272
|
+
cumulativeValueAdjustmentForShortPositions: point.cumulativeValueAdjustmentForShortPositions,
|
|
2273
|
+
fixingPrice: point.fixingPrice,
|
|
2274
|
+
cashRate: point.cashRate,
|
|
2275
|
+
recoveryRate: point.recoveryRate,
|
|
2276
|
+
recoveryRateForLong: point.recoveryRateForLong,
|
|
2277
|
+
recoveryRateForShort: point.recoveryRateForShort,
|
|
2278
|
+
marketBid: point.marketBid,
|
|
2279
|
+
marketOffer: point.marketOffer,
|
|
2280
|
+
shortSaleMinPrice: point.shortSaleMinPrice,
|
|
2281
|
+
previousClosingPrice: point.previousClosingPrice,
|
|
2282
|
+
thresholdLimitPriceBanding: point.thresholdLimitPriceBanding,
|
|
2283
|
+
dailyFinancingValue: point.dailyFinancingValue,
|
|
2284
|
+
accruedFinancingValue: point.accruedFinancingValue,
|
|
2285
|
+
twap: point.twap
|
|
518
2286
|
}))
|
|
519
2287
|
},
|
|
520
2288
|
null,
|
|
@@ -529,7 +2297,7 @@ var createGetStockPriceHistoryHandler = (marketDataPrices) => {
|
|
|
529
2297
|
content: [
|
|
530
2298
|
{
|
|
531
2299
|
type: "text",
|
|
532
|
-
text: `Error: ${error instanceof Error ? error.message : "Failed to get
|
|
2300
|
+
text: `Error: ${error instanceof Error ? error.message : "Failed to get price history"}`,
|
|
533
2301
|
uri: "getStockPriceHistory"
|
|
534
2302
|
}
|
|
535
2303
|
],
|
|
@@ -610,6 +2378,7 @@ var handlInstNames = {
|
|
|
610
2378
|
};
|
|
611
2379
|
var createVerifyOrderHandler = (parser, verifiedOrders) => {
|
|
612
2380
|
return async (args) => {
|
|
2381
|
+
void parser;
|
|
613
2382
|
try {
|
|
614
2383
|
verifiedOrders.set(args.clOrdID, {
|
|
615
2384
|
clOrdID: args.clOrdID,
|
|
@@ -637,7 +2406,7 @@ Parameters verified:
|
|
|
637
2406
|
- Symbol: ${args.symbol}
|
|
638
2407
|
- TimeInForce: ${args.timeInForce} (${timeInForceNames[args.timeInForce]})
|
|
639
2408
|
|
|
640
|
-
To execute this order, call the executeOrder tool with these exact same parameters
|
|
2409
|
+
To execute this order, call the executeOrder tool with these exact same parameters. Important: The user has to explicitly confirm before executeOrder is called!`,
|
|
641
2410
|
uri: "verifyOrder"
|
|
642
2411
|
}
|
|
643
2412
|
]
|
|
@@ -833,48 +2602,211 @@ var createToolHandlers = (parser, verifiedOrders, pendingRequests, marketDataPri
|
|
|
833
2602
|
executeOrder: createExecuteOrderHandler(parser, verifiedOrders, pendingRequests),
|
|
834
2603
|
marketDataRequest: createMarketDataRequestHandler(parser, pendingRequests),
|
|
835
2604
|
getStockGraph: createGetStockGraphHandler(marketDataPrices),
|
|
836
|
-
getStockPriceHistory: createGetStockPriceHistoryHandler(marketDataPrices)
|
|
2605
|
+
getStockPriceHistory: createGetStockPriceHistoryHandler(marketDataPrices),
|
|
2606
|
+
technicalAnalysis: createTechnicalAnalysisHandler(marketDataPrices)
|
|
837
2607
|
});
|
|
838
2608
|
|
|
839
2609
|
// src/utils/messageHandler.ts
|
|
840
2610
|
var import_fixparser3 = require("fixparser");
|
|
2611
|
+
function getEnumValue(enumObj, name) {
|
|
2612
|
+
return enumObj[name] || name;
|
|
2613
|
+
}
|
|
841
2614
|
function handleMessage(message, parser, pendingRequests, marketDataPrices, maxPriceHistory, onPriceUpdate) {
|
|
842
|
-
parser
|
|
843
|
-
level: "info",
|
|
844
|
-
message: `MCP Server received message: ${message.messageType}: ${message.description}`
|
|
845
|
-
});
|
|
2615
|
+
void parser;
|
|
846
2616
|
const msgType = message.messageType;
|
|
847
|
-
if (msgType === import_fixparser3.Messages.MarketDataSnapshotFullRefresh) {
|
|
2617
|
+
if (msgType === import_fixparser3.Messages.MarketDataSnapshotFullRefresh || msgType === import_fixparser3.Messages.MarketDataIncrementalRefresh) {
|
|
848
2618
|
const symbol = message.getField(import_fixparser3.Fields.Symbol)?.value;
|
|
849
|
-
const
|
|
850
|
-
|
|
851
|
-
let offer = 0;
|
|
852
|
-
let volume = 0;
|
|
853
|
-
const entryTypes = message.getFields(import_fixparser3.Fields.MDEntryType);
|
|
854
|
-
const entryPrices = message.getFields(import_fixparser3.Fields.MDEntryPx);
|
|
855
|
-
const entrySizes = message.getFields(import_fixparser3.Fields.MDEntrySize);
|
|
856
|
-
if (entryTypes && entryPrices && entrySizes) {
|
|
857
|
-
for (let i = 0; i < entries; i++) {
|
|
858
|
-
const entryType = entryTypes[i]?.value;
|
|
859
|
-
const entryPrice = Number.parseFloat(entryPrices[i]?.value);
|
|
860
|
-
const entrySize = Number.parseFloat(entrySizes[i]?.value);
|
|
861
|
-
if (entryType === import_fixparser3.MDEntryType.Bid) {
|
|
862
|
-
bid = entryPrice;
|
|
863
|
-
} else if (entryType === import_fixparser3.MDEntryType.Offer) {
|
|
864
|
-
offer = entryPrice;
|
|
865
|
-
}
|
|
866
|
-
volume += entrySize;
|
|
867
|
-
}
|
|
868
|
-
}
|
|
869
|
-
const spread = offer - bid;
|
|
870
|
-
const timestamp = Date.now();
|
|
2619
|
+
const fixJson = message.toFIXJSON();
|
|
2620
|
+
const entries = fixJson.Body?.NoMDEntries || [];
|
|
871
2621
|
const data = {
|
|
872
|
-
timestamp,
|
|
873
|
-
bid,
|
|
874
|
-
offer,
|
|
875
|
-
spread,
|
|
876
|
-
volume
|
|
2622
|
+
timestamp: Date.now(),
|
|
2623
|
+
bid: 0,
|
|
2624
|
+
offer: 0,
|
|
2625
|
+
spread: 0,
|
|
2626
|
+
volume: 0,
|
|
2627
|
+
trade: 0,
|
|
2628
|
+
indexValue: 0,
|
|
2629
|
+
openingPrice: 0,
|
|
2630
|
+
closingPrice: 0,
|
|
2631
|
+
settlementPrice: 0,
|
|
2632
|
+
tradingSessionHighPrice: 0,
|
|
2633
|
+
tradingSessionLowPrice: 0,
|
|
2634
|
+
vwap: 0,
|
|
2635
|
+
imbalance: 0,
|
|
2636
|
+
openInterest: 0,
|
|
2637
|
+
compositeUnderlyingPrice: 0,
|
|
2638
|
+
simulatedSellPrice: 0,
|
|
2639
|
+
simulatedBuyPrice: 0,
|
|
2640
|
+
marginRate: 0,
|
|
2641
|
+
midPrice: 0,
|
|
2642
|
+
emptyBook: 0,
|
|
2643
|
+
settleHighPrice: 0,
|
|
2644
|
+
settleLowPrice: 0,
|
|
2645
|
+
priorSettlePrice: 0,
|
|
2646
|
+
sessionHighBid: 0,
|
|
2647
|
+
sessionLowOffer: 0,
|
|
2648
|
+
earlyPrices: 0,
|
|
2649
|
+
auctionClearingPrice: 0,
|
|
2650
|
+
swapValueFactor: 0,
|
|
2651
|
+
dailyValueAdjustmentForLongPositions: 0,
|
|
2652
|
+
cumulativeValueAdjustmentForLongPositions: 0,
|
|
2653
|
+
dailyValueAdjustmentForShortPositions: 0,
|
|
2654
|
+
cumulativeValueAdjustmentForShortPositions: 0,
|
|
2655
|
+
fixingPrice: 0,
|
|
2656
|
+
cashRate: 0,
|
|
2657
|
+
recoveryRate: 0,
|
|
2658
|
+
recoveryRateForLong: 0,
|
|
2659
|
+
recoveryRateForShort: 0,
|
|
2660
|
+
marketBid: 0,
|
|
2661
|
+
marketOffer: 0,
|
|
2662
|
+
shortSaleMinPrice: 0,
|
|
2663
|
+
previousClosingPrice: 0,
|
|
2664
|
+
thresholdLimitPriceBanding: 0,
|
|
2665
|
+
dailyFinancingValue: 0,
|
|
2666
|
+
accruedFinancingValue: 0,
|
|
2667
|
+
twap: 0
|
|
877
2668
|
};
|
|
2669
|
+
for (const entry of entries) {
|
|
2670
|
+
const entryType = entry.MDEntryType;
|
|
2671
|
+
const price = entry.MDEntryPx ? Number.parseFloat(entry.MDEntryPx) : 0;
|
|
2672
|
+
const size = entry.MDEntrySize ? Number.parseFloat(entry.MDEntrySize) : 0;
|
|
2673
|
+
const enumValue = getEnumValue(import_fixparser3.MDEntryType, entryType);
|
|
2674
|
+
switch (enumValue) {
|
|
2675
|
+
case import_fixparser3.MDEntryType.Bid:
|
|
2676
|
+
data.bid = price;
|
|
2677
|
+
break;
|
|
2678
|
+
case import_fixparser3.MDEntryType.Offer:
|
|
2679
|
+
data.offer = price;
|
|
2680
|
+
break;
|
|
2681
|
+
case import_fixparser3.MDEntryType.Trade:
|
|
2682
|
+
data.trade = price;
|
|
2683
|
+
break;
|
|
2684
|
+
case import_fixparser3.MDEntryType.IndexValue:
|
|
2685
|
+
data.indexValue = price;
|
|
2686
|
+
break;
|
|
2687
|
+
case import_fixparser3.MDEntryType.OpeningPrice:
|
|
2688
|
+
data.openingPrice = price;
|
|
2689
|
+
break;
|
|
2690
|
+
case import_fixparser3.MDEntryType.ClosingPrice:
|
|
2691
|
+
data.closingPrice = price;
|
|
2692
|
+
break;
|
|
2693
|
+
case import_fixparser3.MDEntryType.SettlementPrice:
|
|
2694
|
+
data.settlementPrice = price;
|
|
2695
|
+
break;
|
|
2696
|
+
case import_fixparser3.MDEntryType.TradingSessionHighPrice:
|
|
2697
|
+
data.tradingSessionHighPrice = price;
|
|
2698
|
+
break;
|
|
2699
|
+
case import_fixparser3.MDEntryType.TradingSessionLowPrice:
|
|
2700
|
+
data.tradingSessionLowPrice = price;
|
|
2701
|
+
break;
|
|
2702
|
+
case import_fixparser3.MDEntryType.VWAP:
|
|
2703
|
+
data.vwap = price;
|
|
2704
|
+
break;
|
|
2705
|
+
case import_fixparser3.MDEntryType.Imbalance:
|
|
2706
|
+
data.imbalance = size;
|
|
2707
|
+
break;
|
|
2708
|
+
case import_fixparser3.MDEntryType.TradeVolume:
|
|
2709
|
+
data.volume = size;
|
|
2710
|
+
break;
|
|
2711
|
+
case import_fixparser3.MDEntryType.OpenInterest:
|
|
2712
|
+
data.openInterest = size;
|
|
2713
|
+
break;
|
|
2714
|
+
case import_fixparser3.MDEntryType.CompositeUnderlyingPrice:
|
|
2715
|
+
data.compositeUnderlyingPrice = price;
|
|
2716
|
+
break;
|
|
2717
|
+
case import_fixparser3.MDEntryType.SimulatedSellPrice:
|
|
2718
|
+
data.simulatedSellPrice = price;
|
|
2719
|
+
break;
|
|
2720
|
+
case import_fixparser3.MDEntryType.SimulatedBuyPrice:
|
|
2721
|
+
data.simulatedBuyPrice = price;
|
|
2722
|
+
break;
|
|
2723
|
+
case import_fixparser3.MDEntryType.MarginRate:
|
|
2724
|
+
data.marginRate = price;
|
|
2725
|
+
break;
|
|
2726
|
+
case import_fixparser3.MDEntryType.MidPrice:
|
|
2727
|
+
data.midPrice = price;
|
|
2728
|
+
break;
|
|
2729
|
+
case import_fixparser3.MDEntryType.EmptyBook:
|
|
2730
|
+
data.emptyBook = 1;
|
|
2731
|
+
break;
|
|
2732
|
+
case import_fixparser3.MDEntryType.SettleHighPrice:
|
|
2733
|
+
data.settleHighPrice = price;
|
|
2734
|
+
break;
|
|
2735
|
+
case import_fixparser3.MDEntryType.SettleLowPrice:
|
|
2736
|
+
data.settleLowPrice = price;
|
|
2737
|
+
break;
|
|
2738
|
+
case import_fixparser3.MDEntryType.PriorSettlePrice:
|
|
2739
|
+
data.priorSettlePrice = price;
|
|
2740
|
+
break;
|
|
2741
|
+
case import_fixparser3.MDEntryType.SessionHighBid:
|
|
2742
|
+
data.sessionHighBid = price;
|
|
2743
|
+
break;
|
|
2744
|
+
case import_fixparser3.MDEntryType.SessionLowOffer:
|
|
2745
|
+
data.sessionLowOffer = price;
|
|
2746
|
+
break;
|
|
2747
|
+
case import_fixparser3.MDEntryType.EarlyPrices:
|
|
2748
|
+
data.earlyPrices = price;
|
|
2749
|
+
break;
|
|
2750
|
+
case import_fixparser3.MDEntryType.AuctionClearingPrice:
|
|
2751
|
+
data.auctionClearingPrice = price;
|
|
2752
|
+
break;
|
|
2753
|
+
case import_fixparser3.MDEntryType.SwapValueFactor:
|
|
2754
|
+
data.swapValueFactor = price;
|
|
2755
|
+
break;
|
|
2756
|
+
case import_fixparser3.MDEntryType.DailyValueAdjustmentForLongPositions:
|
|
2757
|
+
data.dailyValueAdjustmentForLongPositions = price;
|
|
2758
|
+
break;
|
|
2759
|
+
case import_fixparser3.MDEntryType.CumulativeValueAdjustmentForLongPositions:
|
|
2760
|
+
data.cumulativeValueAdjustmentForLongPositions = price;
|
|
2761
|
+
break;
|
|
2762
|
+
case import_fixparser3.MDEntryType.DailyValueAdjustmentForShortPositions:
|
|
2763
|
+
data.dailyValueAdjustmentForShortPositions = price;
|
|
2764
|
+
break;
|
|
2765
|
+
case import_fixparser3.MDEntryType.CumulativeValueAdjustmentForShortPositions:
|
|
2766
|
+
data.cumulativeValueAdjustmentForShortPositions = price;
|
|
2767
|
+
break;
|
|
2768
|
+
case import_fixparser3.MDEntryType.FixingPrice:
|
|
2769
|
+
data.fixingPrice = price;
|
|
2770
|
+
break;
|
|
2771
|
+
case import_fixparser3.MDEntryType.CashRate:
|
|
2772
|
+
data.cashRate = price;
|
|
2773
|
+
break;
|
|
2774
|
+
case import_fixparser3.MDEntryType.RecoveryRate:
|
|
2775
|
+
data.recoveryRate = price;
|
|
2776
|
+
break;
|
|
2777
|
+
case import_fixparser3.MDEntryType.RecoveryRateForLong:
|
|
2778
|
+
data.recoveryRateForLong = price;
|
|
2779
|
+
break;
|
|
2780
|
+
case import_fixparser3.MDEntryType.RecoveryRateForShort:
|
|
2781
|
+
data.recoveryRateForShort = price;
|
|
2782
|
+
break;
|
|
2783
|
+
case import_fixparser3.MDEntryType.MarketBid:
|
|
2784
|
+
data.marketBid = price;
|
|
2785
|
+
break;
|
|
2786
|
+
case import_fixparser3.MDEntryType.MarketOffer:
|
|
2787
|
+
data.marketOffer = price;
|
|
2788
|
+
break;
|
|
2789
|
+
case import_fixparser3.MDEntryType.ShortSaleMinPrice:
|
|
2790
|
+
data.shortSaleMinPrice = price;
|
|
2791
|
+
break;
|
|
2792
|
+
case import_fixparser3.MDEntryType.PreviousClosingPrice:
|
|
2793
|
+
data.previousClosingPrice = price;
|
|
2794
|
+
break;
|
|
2795
|
+
case import_fixparser3.MDEntryType.ThresholdLimitPriceBanding:
|
|
2796
|
+
data.thresholdLimitPriceBanding = price;
|
|
2797
|
+
break;
|
|
2798
|
+
case import_fixparser3.MDEntryType.DailyFinancingValue:
|
|
2799
|
+
data.dailyFinancingValue = price;
|
|
2800
|
+
break;
|
|
2801
|
+
case import_fixparser3.MDEntryType.AccruedFinancingValue:
|
|
2802
|
+
data.accruedFinancingValue = price;
|
|
2803
|
+
break;
|
|
2804
|
+
case import_fixparser3.MDEntryType.TWAP:
|
|
2805
|
+
data.twap = price;
|
|
2806
|
+
break;
|
|
2807
|
+
}
|
|
2808
|
+
}
|
|
2809
|
+
data.spread = data.offer - data.bid;
|
|
878
2810
|
if (!marketDataPrices.has(symbol)) {
|
|
879
2811
|
marketDataPrices.set(symbol, []);
|
|
880
2812
|
}
|
|
@@ -884,6 +2816,14 @@ function handleMessage(message, parser, pendingRequests, marketDataPrices, maxPr
|
|
|
884
2816
|
prices.splice(0, prices.length - maxPriceHistory);
|
|
885
2817
|
}
|
|
886
2818
|
onPriceUpdate?.(symbol, data);
|
|
2819
|
+
const mdReqID = message.getField(import_fixparser3.Fields.MDReqID)?.value;
|
|
2820
|
+
if (mdReqID) {
|
|
2821
|
+
const callback = pendingRequests.get(mdReqID);
|
|
2822
|
+
if (callback) {
|
|
2823
|
+
callback(message);
|
|
2824
|
+
pendingRequests.delete(mdReqID);
|
|
2825
|
+
}
|
|
2826
|
+
}
|
|
887
2827
|
} else if (msgType === import_fixparser3.Messages.ExecutionReport) {
|
|
888
2828
|
const reqId = message.getField(import_fixparser3.Fields.ClOrdID)?.value;
|
|
889
2829
|
const callback = pendingRequests.get(reqId);
|
|
@@ -912,7 +2852,7 @@ var MCPLocal = class extends MCPBase {
|
|
|
912
2852
|
*/
|
|
913
2853
|
marketDataPrices = /* @__PURE__ */ new Map();
|
|
914
2854
|
/**
|
|
915
|
-
* Maximum number of price
|
|
2855
|
+
* Maximum number of price history entries to keep per symbol
|
|
916
2856
|
* @private
|
|
917
2857
|
*/
|
|
918
2858
|
MAX_PRICE_HISTORY = 1e5;
|