fixparser-plugin-mcp 9.1.7-5d282a9e → 9.1.7-620b3399

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.
@@ -307,1568 +307,9 @@ 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
- }
323
310
  }
324
311
  };
325
312
 
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
-
1872
313
  // src/tools/marketData.ts
1873
314
  var import_fixparser = require("fixparser");
1874
315
  var import_quickchart_js = __toESM(require("quickchart-js"), 1);
@@ -2001,72 +442,6 @@ var createMarketDataRequestHandler = (parser, pendingRequests) => {
2001
442
  }
2002
443
  };
2003
444
  };
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
- };
2070
445
  var createGetStockGraphHandler = (marketDataPrices) => {
2071
446
  return async (args) => {
2072
447
  try {
@@ -2083,22 +458,18 @@ var createGetStockGraphHandler = (marketDataPrices) => {
2083
458
  ]
2084
459
  };
2085
460
  }
2086
- const aggregatedData = aggregateMarketData(priceHistory, 500);
2087
461
  const chart = new import_quickchart_js.default();
2088
462
  chart.setWidth(1200);
2089
463
  chart.setHeight(600);
2090
464
  chart.setBackgroundColor("transparent");
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);
465
+ const labels = priceHistory.map((point) => new Date(point.timestamp).toLocaleTimeString());
466
+ const bidData = priceHistory.map((point) => point.bid);
467
+ const offerData = priceHistory.map((point) => point.offer);
468
+ const spreadData = priceHistory.map((point) => point.spread);
469
+ const volumeData = priceHistory.map((point) => point.volume);
470
+ const tradeData = priceHistory.map((point) => point.trade);
471
+ const vwapData = priceHistory.map((point) => point.vwap);
472
+ const twapData = priceHistory.map((point) => point.twap);
2102
473
  const config = {
2103
474
  type: "line",
2104
475
  data: {
@@ -2153,8 +524,8 @@ var createGetStockGraphHandler = (marketDataPrices) => {
2153
524
  tension: 0.4
2154
525
  },
2155
526
  {
2156
- label: "Volume (Normalized)",
2157
- data: normalizedVolumeData,
527
+ label: "Volume",
528
+ data: volumeData,
2158
529
  borderColor: "#007bff",
2159
530
  backgroundColor: "rgba(0, 123, 255, 0.1)",
2160
531
  fill: true,
@@ -2167,16 +538,12 @@ var createGetStockGraphHandler = (marketDataPrices) => {
2167
538
  plugins: {
2168
539
  title: {
2169
540
  display: true,
2170
- text: `${symbol} Market Data (Volume normalized to 30% of max price)`
541
+ text: `${symbol} Market Data`
2171
542
  }
2172
543
  },
2173
544
  scales: {
2174
545
  y: {
2175
- beginAtZero: false,
2176
- title: {
2177
- display: true,
2178
- text: "Price / Normalized Volume"
2179
- }
546
+ beginAtZero: false
2180
547
  }
2181
548
  }
2182
549
  }
@@ -2226,7 +593,6 @@ var createGetStockPriceHistoryHandler = (marketDataPrices) => {
2226
593
  ]
2227
594
  };
2228
595
  }
2229
- const aggregatedData = aggregateMarketData(priceHistory, 500);
2230
596
  return {
2231
597
  content: [
2232
598
  {
@@ -2234,9 +600,8 @@ var createGetStockPriceHistoryHandler = (marketDataPrices) => {
2234
600
  text: JSON.stringify(
2235
601
  {
2236
602
  symbol,
2237
- count: aggregatedData.length,
2238
- originalCount: priceHistory.length,
2239
- data: aggregatedData.map((point) => ({
603
+ count: priceHistory.length,
604
+ data: priceHistory.map((point) => ({
2240
605
  timestamp: new Date(point.timestamp).toISOString(),
2241
606
  bid: point.bid,
2242
607
  offer: point.offer,
@@ -2378,7 +743,6 @@ var handlInstNames = {
2378
743
  };
2379
744
  var createVerifyOrderHandler = (parser, verifiedOrders) => {
2380
745
  return async (args) => {
2381
- void parser;
2382
746
  try {
2383
747
  verifiedOrders.set(args.clOrdID, {
2384
748
  clOrdID: args.clOrdID,
@@ -2602,22 +966,29 @@ var createToolHandlers = (parser, verifiedOrders, pendingRequests, marketDataPri
2602
966
  executeOrder: createExecuteOrderHandler(parser, verifiedOrders, pendingRequests),
2603
967
  marketDataRequest: createMarketDataRequestHandler(parser, pendingRequests),
2604
968
  getStockGraph: createGetStockGraphHandler(marketDataPrices),
2605
- getStockPriceHistory: createGetStockPriceHistoryHandler(marketDataPrices),
2606
- technicalAnalysis: createTechnicalAnalysisHandler(marketDataPrices)
969
+ getStockPriceHistory: createGetStockPriceHistoryHandler(marketDataPrices)
2607
970
  });
2608
971
 
2609
972
  // src/utils/messageHandler.ts
2610
973
  var import_fixparser3 = require("fixparser");
2611
- function getEnumValue(enumObj, name) {
2612
- return enumObj[name] || name;
2613
- }
2614
974
  function handleMessage(message, parser, pendingRequests, marketDataPrices, maxPriceHistory, onPriceUpdate) {
2615
- void parser;
975
+ parser.logger.log({
976
+ level: "info",
977
+ message: `MCP Server received message: ${message.messageType}: ${message.description}`
978
+ });
2616
979
  const msgType = message.messageType;
2617
980
  if (msgType === import_fixparser3.Messages.MarketDataSnapshotFullRefresh || msgType === import_fixparser3.Messages.MarketDataIncrementalRefresh) {
2618
981
  const symbol = message.getField(import_fixparser3.Fields.Symbol)?.value;
982
+ parser.logger.log({
983
+ level: "info",
984
+ message: `Processing market data for symbol: ${symbol}`
985
+ });
2619
986
  const fixJson = message.toFIXJSON();
2620
987
  const entries = fixJson.Body?.NoMDEntries || [];
988
+ parser.logger.log({
989
+ level: "info",
990
+ message: `Found ${entries.length} market data entries`
991
+ });
2621
992
  const data = {
2622
993
  timestamp: Date.now(),
2623
994
  bid: 0,
@@ -2670,8 +1041,13 @@ function handleMessage(message, parser, pendingRequests, marketDataPrices, maxPr
2670
1041
  const entryType = entry.MDEntryType;
2671
1042
  const price = entry.MDEntryPx ? Number.parseFloat(entry.MDEntryPx) : 0;
2672
1043
  const size = entry.MDEntrySize ? Number.parseFloat(entry.MDEntrySize) : 0;
2673
- const enumValue = getEnumValue(import_fixparser3.MDEntryType, entryType);
2674
- switch (enumValue) {
1044
+ if (entryType === import_fixparser3.MDEntryType.Bid || entryType === import_fixparser3.MDEntryType.Offer || entryType === import_fixparser3.MDEntryType.TradeVolume) {
1045
+ parser.logger.log({
1046
+ level: "info",
1047
+ message: `Market Data Entry - Type: ${entryType}, Price: ${price}, Size: ${size}`
1048
+ });
1049
+ }
1050
+ switch (entryType) {
2675
1051
  case import_fixparser3.MDEntryType.Bid:
2676
1052
  data.bid = price;
2677
1053
  break;
@@ -2808,12 +1184,24 @@ function handleMessage(message, parser, pendingRequests, marketDataPrices, maxPr
2808
1184
  }
2809
1185
  data.spread = data.offer - data.bid;
2810
1186
  if (!marketDataPrices.has(symbol)) {
1187
+ parser.logger.log({
1188
+ level: "info",
1189
+ message: `Creating new price history array for symbol: ${symbol}`
1190
+ });
2811
1191
  marketDataPrices.set(symbol, []);
2812
1192
  }
2813
1193
  const prices = marketDataPrices.get(symbol);
2814
1194
  prices.push(data);
1195
+ parser.logger.log({
1196
+ level: "info",
1197
+ message: `Updated price history for ${symbol}. Current size: ${prices.length}`
1198
+ });
2815
1199
  if (prices.length > maxPriceHistory) {
2816
1200
  prices.splice(0, prices.length - maxPriceHistory);
1201
+ parser.logger.log({
1202
+ level: "info",
1203
+ message: `Trimmed price history for ${symbol} to ${maxPriceHistory} entries`
1204
+ });
2817
1205
  }
2818
1206
  onPriceUpdate?.(symbol, data);
2819
1207
  const mdReqID = message.getField(import_fixparser3.Fields.MDReqID)?.value;
@@ -2822,6 +1210,10 @@ function handleMessage(message, parser, pendingRequests, marketDataPrices, maxPr
2822
1210
  if (callback) {
2823
1211
  callback(message);
2824
1212
  pendingRequests.delete(mdReqID);
1213
+ parser.logger.log({
1214
+ level: "info",
1215
+ message: `Resolved market data request for ID: ${mdReqID}`
1216
+ });
2825
1217
  }
2826
1218
  }
2827
1219
  } else if (msgType === import_fixparser3.Messages.ExecutionReport) {