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.
@@ -276,1568 +276,9 @@ var toolSchemas = {
276
276
  },
277
277
  required: ["symbol"]
278
278
  }
279
- },
280
- technicalAnalysis: {
281
- description: "Performs comprehensive technical analysis on market data for a given symbol, including indicators like SMA, EMA, RSI, Bollinger Bands, and trading signals",
282
- schema: {
283
- type: "object",
284
- properties: {
285
- symbol: {
286
- type: "string",
287
- description: "The trading symbol to analyze (e.g., AAPL, MSFT, EURUSD)"
288
- }
289
- },
290
- required: ["symbol"]
291
- }
292
279
  }
293
280
  };
294
281
 
295
- // src/tools/analytics.ts
296
- function sum(numbers) {
297
- return numbers.reduce((acc, val) => acc + val, 0);
298
- }
299
- var TechnicalAnalyzer = class {
300
- prices;
301
- volumes;
302
- highs;
303
- lows;
304
- constructor(data) {
305
- this.prices = data.map((d) => d.trade > 0 ? d.trade : d.midPrice);
306
- this.volumes = data.map((d) => d.volume);
307
- this.highs = data.map((d) => d.tradingSessionHighPrice > 0 ? d.tradingSessionHighPrice : d.trade);
308
- this.lows = data.map((d) => d.tradingSessionLowPrice > 0 ? d.tradingSessionLowPrice : d.trade);
309
- }
310
- // Calculate Simple Moving Average
311
- calculateSMA(data, period) {
312
- const sma = [];
313
- for (let i = period - 1; i < data.length; i++) {
314
- const sum2 = data.slice(i - period + 1, i + 1).reduce((a, b) => a + b, 0);
315
- sma.push(sum2 / period);
316
- }
317
- return sma;
318
- }
319
- // Calculate Exponential Moving Average
320
- calculateEMA(data, period) {
321
- const multiplier = 2 / (period + 1);
322
- const ema = [data[0]];
323
- for (let i = 1; i < data.length; i++) {
324
- ema.push(data[i] * multiplier + ema[i - 1] * (1 - multiplier));
325
- }
326
- return ema;
327
- }
328
- // Calculate RSI
329
- calculateRSI(data, period = 14) {
330
- if (data.length < period + 1) return [];
331
- const changes = [];
332
- for (let i = 1; i < data.length; i++) {
333
- changes.push(data[i] - data[i - 1]);
334
- }
335
- const gains = changes.map((change) => change > 0 ? change : 0);
336
- const losses = changes.map((change) => change < 0 ? Math.abs(change) : 0);
337
- let avgGain = gains.slice(0, period).reduce((a, b) => a + b, 0) / period;
338
- let avgLoss = losses.slice(0, period).reduce((a, b) => a + b, 0) / period;
339
- const rsi = [];
340
- for (let i = period; i < changes.length; i++) {
341
- const rs = avgGain / avgLoss;
342
- rsi.push(100 - 100 / (1 + rs));
343
- avgGain = (avgGain * (period - 1) + gains[i]) / period;
344
- avgLoss = (avgLoss * (period - 1) + losses[i]) / period;
345
- }
346
- return rsi;
347
- }
348
- // Calculate Bollinger Bands
349
- calculateBollingerBands(data, period = 20, stdDev = 2) {
350
- if (data.length < period) return [];
351
- const sma = this.calculateSMA(data, period);
352
- const bands = [];
353
- for (let i = 0; i < sma.length; i++) {
354
- const dataSlice = data.slice(i, i + period);
355
- const mean = sma[i];
356
- const variance = dataSlice.reduce((sum2, price) => sum2 + (price - mean) ** 2, 0) / period;
357
- const standardDeviation = Math.sqrt(variance);
358
- const upper = mean + standardDeviation * stdDev;
359
- const lower = mean - standardDeviation * stdDev;
360
- bands.push({
361
- upper,
362
- middle: mean,
363
- lower,
364
- bandwidth: (upper - lower) / mean * 100,
365
- percentB: (data[i] - lower) / (upper - lower) * 100
366
- });
367
- }
368
- return bands;
369
- }
370
- // Calculate maximum drawdown
371
- calculateMaxDrawdown(prices) {
372
- let maxPrice = prices[0];
373
- let maxDrawdown = 0;
374
- for (let i = 1; i < prices.length; i++) {
375
- if (prices[i] > maxPrice) {
376
- maxPrice = prices[i];
377
- }
378
- const drawdown = (maxPrice - prices[i]) / maxPrice;
379
- if (drawdown > maxDrawdown) {
380
- maxDrawdown = drawdown;
381
- }
382
- }
383
- return maxDrawdown;
384
- }
385
- // Calculate Average True Range (ATR)
386
- calculateAtr(prices, highs, lows) {
387
- if (prices.length < 2) return [];
388
- const trueRanges = [];
389
- for (let i = 1; i < prices.length; i++) {
390
- const high = highs[i] || prices[i];
391
- const low = lows[i] || prices[i];
392
- const prevClose = prices[i - 1];
393
- const tr1 = high - low;
394
- const tr2 = Math.abs(high - prevClose);
395
- const tr3 = Math.abs(low - prevClose);
396
- trueRanges.push(Math.max(tr1, tr2, tr3));
397
- }
398
- const atr = [];
399
- if (trueRanges.length >= 14) {
400
- let sum2 = trueRanges.slice(0, 14).reduce((a, b) => a + b, 0);
401
- atr.push(sum2 / 14);
402
- for (let i = 14; i < trueRanges.length; i++) {
403
- sum2 = sum2 - trueRanges[i - 14] + trueRanges[i];
404
- atr.push(sum2 / 14);
405
- }
406
- }
407
- return atr;
408
- }
409
- // Calculate maximum consecutive losses
410
- calculateMaxConsecutiveLosses(prices) {
411
- let maxConsecutive = 0;
412
- let currentConsecutive = 0;
413
- for (let i = 1; i < prices.length; i++) {
414
- if (prices[i] < prices[i - 1]) {
415
- currentConsecutive++;
416
- maxConsecutive = Math.max(maxConsecutive, currentConsecutive);
417
- } else {
418
- currentConsecutive = 0;
419
- }
420
- }
421
- return maxConsecutive;
422
- }
423
- // Calculate win rate
424
- calculateWinRate(prices) {
425
- let wins = 0;
426
- let total = 0;
427
- for (let i = 1; i < prices.length; i++) {
428
- if (prices[i] !== prices[i - 1]) {
429
- total++;
430
- if (prices[i] > prices[i - 1]) {
431
- wins++;
432
- }
433
- }
434
- }
435
- return total > 0 ? wins / total : 0;
436
- }
437
- // Calculate profit factor
438
- calculateProfitFactor(prices) {
439
- let grossProfit = 0;
440
- let grossLoss = 0;
441
- for (let i = 1; i < prices.length; i++) {
442
- const change = prices[i] - prices[i - 1];
443
- if (change > 0) {
444
- grossProfit += change;
445
- } else {
446
- grossLoss += Math.abs(change);
447
- }
448
- }
449
- return grossLoss > 0 ? grossProfit / grossLoss : 0;
450
- }
451
- // Calculate Weighted Moving Average
452
- calculateWma(data, period) {
453
- const wma = [];
454
- const weights = Array.from({ length: period }, (_, i) => i + 1);
455
- const weightSum = weights.reduce((a, b) => a + b, 0);
456
- for (let i = period - 1; i < data.length; i++) {
457
- let weightedSum = 0;
458
- for (let j = 0; j < period; j++) {
459
- weightedSum += data[i - j] * weights[j];
460
- }
461
- wma.push(weightedSum / weightSum);
462
- }
463
- return wma;
464
- }
465
- // Calculate Volume Weighted Moving Average
466
- calculateVwma(prices, period) {
467
- const vwma = [];
468
- for (let i = period - 1; i < prices.length; i++) {
469
- let volumeSum = 0;
470
- let priceVolumeSum = 0;
471
- for (let j = 0; j < period; j++) {
472
- const volume = this.volumes[i - j] || 1;
473
- volumeSum += volume;
474
- priceVolumeSum += prices[i - j] * volume;
475
- }
476
- vwma.push(priceVolumeSum / volumeSum);
477
- }
478
- return vwma;
479
- }
480
- // Calculate MACD
481
- calculateMacd(prices) {
482
- const ema12 = this.calculateEMA(prices, 12);
483
- const ema26 = this.calculateEMA(prices, 26);
484
- const macd = [];
485
- const macdLine = [];
486
- for (let i = 0; i < Math.min(ema12.length, ema26.length); i++) {
487
- macdLine.push(ema12[i] - ema26[i]);
488
- }
489
- const signalLine = this.calculateEMA(macdLine, 9);
490
- for (let i = 0; i < Math.min(macdLine.length, signalLine.length); i++) {
491
- macd.push({
492
- macd: macdLine[i],
493
- signal: signalLine[i],
494
- histogram: macdLine[i] - signalLine[i]
495
- });
496
- }
497
- return macd;
498
- }
499
- // Calculate ADX (Average Directional Index)
500
- calculateAdx(prices, highs, lows) {
501
- if (prices.length < 14) return [];
502
- const period = 14;
503
- const adx = [];
504
- const trueRanges = [];
505
- const plusDM = [];
506
- const minusDM = [];
507
- trueRanges.push(highs[0] - lows[0]);
508
- plusDM.push(0);
509
- minusDM.push(0);
510
- for (let i = 1; i < prices.length; i++) {
511
- const high = highs[i] || prices[i];
512
- const low = lows[i] || prices[i];
513
- const prevHigh = highs[i - 1] || prices[i - 1];
514
- const prevLow = lows[i - 1] || prices[i - 1];
515
- const prevClose = prices[i - 1];
516
- const tr1 = high - low;
517
- const tr2 = Math.abs(high - prevClose);
518
- const tr3 = Math.abs(low - prevClose);
519
- trueRanges.push(Math.max(tr1, tr2, tr3));
520
- const upMove = high - prevHigh;
521
- const downMove = prevLow - low;
522
- if (upMove > downMove && upMove > 0) {
523
- plusDM.push(upMove);
524
- minusDM.push(0);
525
- } else if (downMove > upMove && downMove > 0) {
526
- plusDM.push(0);
527
- minusDM.push(downMove);
528
- } else {
529
- plusDM.push(0);
530
- minusDM.push(0);
531
- }
532
- }
533
- const smoothedTR = [];
534
- const smoothedPlusDM = [];
535
- const smoothedMinusDM = [];
536
- let sumTR = 0;
537
- let sumPlusDM = 0;
538
- let sumMinusDM = 0;
539
- for (let i = 0; i < period; i++) {
540
- sumTR += trueRanges[i];
541
- sumPlusDM += plusDM[i];
542
- sumMinusDM += minusDM[i];
543
- }
544
- smoothedTR.push(sumTR);
545
- smoothedPlusDM.push(sumPlusDM);
546
- smoothedMinusDM.push(sumMinusDM);
547
- for (let i = period; i < trueRanges.length; i++) {
548
- const newTR = smoothedTR[smoothedTR.length - 1] - smoothedTR[smoothedTR.length - 1] / period + trueRanges[i];
549
- const newPlusDM = smoothedPlusDM[smoothedPlusDM.length - 1] - smoothedPlusDM[smoothedPlusDM.length - 1] / period + plusDM[i];
550
- const newMinusDM = smoothedMinusDM[smoothedMinusDM.length - 1] - smoothedMinusDM[smoothedMinusDM.length - 1] / period + minusDM[i];
551
- smoothedTR.push(newTR);
552
- smoothedPlusDM.push(newPlusDM);
553
- smoothedMinusDM.push(newMinusDM);
554
- }
555
- const plusDI = [];
556
- const minusDI = [];
557
- for (let i = 0; i < smoothedTR.length; i++) {
558
- plusDI.push(smoothedPlusDM[i] / smoothedTR[i] * 100);
559
- minusDI.push(smoothedMinusDM[i] / smoothedTR[i] * 100);
560
- }
561
- const dx = [];
562
- for (let i = 0; i < plusDI.length; i++) {
563
- const diSum = plusDI[i] + minusDI[i];
564
- const diDiff = Math.abs(plusDI[i] - minusDI[i]);
565
- dx.push(diSum > 0 ? diDiff / diSum * 100 : 0);
566
- }
567
- if (dx.length < period) return [];
568
- let sumDX = 0;
569
- for (let i = 0; i < period; i++) {
570
- sumDX += dx[i];
571
- }
572
- adx.push(sumDX / period);
573
- for (let i = period; i < dx.length; i++) {
574
- const newADX = adx[adx.length - 1] - adx[adx.length - 1] / period + dx[i];
575
- adx.push(newADX);
576
- }
577
- return adx;
578
- }
579
- // Calculate DMI (Directional Movement Index)
580
- calculateDmi(prices, highs, lows) {
581
- if (prices.length < 14) return [];
582
- const period = 14;
583
- const dmi = [];
584
- const trueRanges = [];
585
- const plusDM = [];
586
- const minusDM = [];
587
- trueRanges.push(highs[0] - lows[0]);
588
- plusDM.push(0);
589
- minusDM.push(0);
590
- for (let i = 1; i < prices.length; i++) {
591
- const high = highs[i] || prices[i];
592
- const low = lows[i] || prices[i];
593
- const prevHigh = highs[i - 1] || prices[i - 1];
594
- const prevLow = lows[i - 1] || prices[i - 1];
595
- const prevClose = prices[i - 1];
596
- const tr1 = high - low;
597
- const tr2 = Math.abs(high - prevClose);
598
- const tr3 = Math.abs(low - prevClose);
599
- trueRanges.push(Math.max(tr1, tr2, tr3));
600
- const upMove = high - prevHigh;
601
- const downMove = prevLow - low;
602
- if (upMove > downMove && upMove > 0) {
603
- plusDM.push(upMove);
604
- minusDM.push(0);
605
- } else if (downMove > upMove && downMove > 0) {
606
- plusDM.push(0);
607
- minusDM.push(downMove);
608
- } else {
609
- plusDM.push(0);
610
- minusDM.push(0);
611
- }
612
- }
613
- const smoothedTR = [];
614
- const smoothedPlusDM = [];
615
- const smoothedMinusDM = [];
616
- let sumTR = 0;
617
- let sumPlusDM = 0;
618
- let sumMinusDM = 0;
619
- for (let i = 0; i < period; i++) {
620
- sumTR += trueRanges[i];
621
- sumPlusDM += plusDM[i];
622
- sumMinusDM += minusDM[i];
623
- }
624
- smoothedTR.push(sumTR);
625
- smoothedPlusDM.push(sumPlusDM);
626
- smoothedMinusDM.push(sumMinusDM);
627
- for (let i = period; i < trueRanges.length; i++) {
628
- const newTR = smoothedTR[smoothedTR.length - 1] - smoothedTR[smoothedTR.length - 1] / period + trueRanges[i];
629
- const newPlusDM = smoothedPlusDM[smoothedPlusDM.length - 1] - smoothedPlusDM[smoothedPlusDM.length - 1] / period + plusDM[i];
630
- const newMinusDM = smoothedMinusDM[smoothedMinusDM.length - 1] - smoothedMinusDM[smoothedMinusDM.length - 1] / period + minusDM[i];
631
- smoothedTR.push(newTR);
632
- smoothedPlusDM.push(newPlusDM);
633
- smoothedMinusDM.push(newMinusDM);
634
- }
635
- const plusDI = [];
636
- const minusDI = [];
637
- for (let i = 0; i < smoothedTR.length; i++) {
638
- plusDI.push(smoothedPlusDM[i] / smoothedTR[i] * 100);
639
- minusDI.push(smoothedMinusDM[i] / smoothedTR[i] * 100);
640
- }
641
- const dx = [];
642
- for (let i = 0; i < plusDI.length; i++) {
643
- const diSum = plusDI[i] + minusDI[i];
644
- const diDiff = Math.abs(plusDI[i] - minusDI[i]);
645
- dx.push(diSum > 0 ? diDiff / diSum * 100 : 0);
646
- }
647
- if (dx.length < period) return [];
648
- const adx = [];
649
- let sumDX = 0;
650
- for (let i = 0; i < period; i++) {
651
- sumDX += dx[i];
652
- }
653
- adx.push(sumDX / period);
654
- for (let i = period; i < dx.length; i++) {
655
- const newADX = adx[adx.length - 1] - adx[adx.length - 1] / period + dx[i];
656
- adx.push(newADX);
657
- }
658
- for (let i = 0; i < adx.length; i++) {
659
- dmi.push({
660
- plusDI: plusDI[i + period - 1] || 0,
661
- minusDI: minusDI[i + period - 1] || 0,
662
- adx: adx[i]
663
- });
664
- }
665
- return dmi;
666
- }
667
- // Calculate Ichimoku Cloud
668
- calculateIchimoku(prices, highs, lows) {
669
- if (prices.length < 52) return [];
670
- const ichimoku = [];
671
- const tenkanSen = [];
672
- for (let i = 8; i < prices.length; i++) {
673
- const periodHigh = Math.max(...highs.slice(i - 8, i + 1));
674
- const periodLow = Math.min(...lows.slice(i - 8, i + 1));
675
- tenkanSen.push((periodHigh + periodLow) / 2);
676
- }
677
- const kijunSen = [];
678
- for (let i = 25; i < prices.length; i++) {
679
- const periodHigh = Math.max(...highs.slice(i - 25, i + 1));
680
- const periodLow = Math.min(...lows.slice(i - 25, i + 1));
681
- kijunSen.push((periodHigh + periodLow) / 2);
682
- }
683
- const senkouSpanA = [];
684
- for (let i = 0; i < Math.min(tenkanSen.length, kijunSen.length); i++) {
685
- senkouSpanA.push((tenkanSen[i] + kijunSen[i]) / 2);
686
- }
687
- const senkouSpanB = [];
688
- for (let i = 51; i < prices.length; i++) {
689
- const periodHigh = Math.max(...highs.slice(i - 51, i + 1));
690
- const periodLow = Math.min(...lows.slice(i - 51, i + 1));
691
- senkouSpanB.push((periodHigh + periodLow) / 2);
692
- }
693
- const chikouSpan = [];
694
- for (let i = 26; i < prices.length; i++) {
695
- chikouSpan.push(prices[i - 26]);
696
- }
697
- const minLength = Math.min(
698
- tenkanSen.length,
699
- kijunSen.length,
700
- senkouSpanA.length,
701
- senkouSpanB.length,
702
- chikouSpan.length
703
- );
704
- for (let i = 0; i < minLength; i++) {
705
- ichimoku.push({
706
- tenkan: tenkanSen[i],
707
- kijun: kijunSen[i],
708
- senkouA: senkouSpanA[i],
709
- senkouB: senkouSpanB[i],
710
- chikou: chikouSpan[i]
711
- });
712
- }
713
- return ichimoku;
714
- }
715
- // Calculate Parabolic SAR
716
- calculateParabolicSAR(prices, highs, lows) {
717
- if (prices.length < 2) return [];
718
- const sar = [];
719
- const accelerationFactor = 0.02;
720
- const maximumAcceleration = 0.2;
721
- let currentSAR = lows[0];
722
- let isLong = true;
723
- let af = accelerationFactor;
724
- let ep = highs[0];
725
- sar.push(currentSAR);
726
- for (let i = 1; i < prices.length; i++) {
727
- const high = highs[i] || prices[i];
728
- const low = lows[i] || prices[i];
729
- if (isLong) {
730
- if (low < currentSAR) {
731
- isLong = false;
732
- currentSAR = ep;
733
- ep = low;
734
- af = accelerationFactor;
735
- } else {
736
- if (high > ep) {
737
- ep = high;
738
- af = Math.min(af + accelerationFactor, maximumAcceleration);
739
- }
740
- currentSAR = currentSAR + af * (ep - currentSAR);
741
- if (i > 0) {
742
- const prevLow = lows[i - 1] || prices[i - 1];
743
- currentSAR = Math.min(currentSAR, prevLow);
744
- }
745
- }
746
- } else {
747
- if (high > currentSAR) {
748
- isLong = true;
749
- currentSAR = ep;
750
- ep = high;
751
- af = accelerationFactor;
752
- } else {
753
- if (low < ep) {
754
- ep = low;
755
- af = Math.min(af + accelerationFactor, maximumAcceleration);
756
- }
757
- currentSAR = currentSAR + af * (ep - currentSAR);
758
- if (i > 0) {
759
- const prevHigh = highs[i - 1] || prices[i - 1];
760
- currentSAR = Math.max(currentSAR, prevHigh);
761
- }
762
- }
763
- }
764
- sar.push(currentSAR);
765
- }
766
- return sar;
767
- }
768
- // Calculate Stochastic
769
- calculateStochastic(prices, highs, lows) {
770
- const stochastic = [];
771
- const period = 14;
772
- const smoothK = 3;
773
- const smoothD = 3;
774
- if (prices.length < period) return [];
775
- const percentK = [];
776
- for (let i = period - 1; i < prices.length; i++) {
777
- const high = Math.max(...highs.slice(i - period + 1, i + 1));
778
- const low = Math.min(...lows.slice(i - period + 1, i + 1));
779
- const close = prices[i];
780
- const k = (close - low) / (high - low) * 100;
781
- percentK.push(k);
782
- }
783
- const smoothedK = [];
784
- for (let i = smoothK - 1; i < percentK.length; i++) {
785
- const sum2 = percentK.slice(i - smoothK + 1, i + 1).reduce((a, b) => a + b, 0);
786
- smoothedK.push(sum2 / smoothK);
787
- }
788
- for (let i = smoothD - 1; i < smoothedK.length; i++) {
789
- const sum2 = smoothedK.slice(i - smoothD + 1, i + 1).reduce((a, b) => a + b, 0);
790
- const d = sum2 / smoothD;
791
- stochastic.push({
792
- k: smoothedK[i],
793
- d
794
- });
795
- }
796
- return stochastic;
797
- }
798
- // Calculate CCI
799
- calculateCci(prices, highs, lows) {
800
- const cci = [];
801
- const period = 20;
802
- if (prices.length < period) return [];
803
- for (let i = period - 1; i < prices.length; i++) {
804
- const slice = prices.slice(i - period + 1, i + 1);
805
- const typicalPrices = slice.map((price, idx) => {
806
- const high = highs[i - period + 1 + idx] || price;
807
- const low = lows[i - period + 1 + idx] || price;
808
- return (high + low + price) / 3;
809
- });
810
- const sma = typicalPrices.reduce((a, b) => a + b, 0) / period;
811
- const meanDeviation = typicalPrices.reduce((sum2, tp) => sum2 + Math.abs(tp - sma), 0) / period;
812
- const currentTP = (highs[i] + lows[i] + prices[i]) / 3;
813
- const cciValue = meanDeviation !== 0 ? (currentTP - sma) / (0.015 * meanDeviation) : 0;
814
- cci.push(cciValue);
815
- }
816
- return cci;
817
- }
818
- // Calculate Rate of Change
819
- calculateRoc(prices) {
820
- const roc = [];
821
- for (let i = 10; i < prices.length; i++) {
822
- roc.push((prices[i] - prices[i - 10]) / prices[i - 10] * 100);
823
- }
824
- return roc;
825
- }
826
- // Calculate Williams %R
827
- calculateWilliamsR(prices) {
828
- const williamsR = [];
829
- const period = 14;
830
- if (prices.length < period) return [];
831
- for (let i = period - 1; i < prices.length; i++) {
832
- const slice = prices.slice(i - period + 1, i + 1);
833
- const high = Math.max(...slice);
834
- const low = Math.min(...slice);
835
- const close = prices[i];
836
- const wr = (high - close) / (high - low) * -100;
837
- williamsR.push(wr);
838
- }
839
- return williamsR;
840
- }
841
- // Calculate Momentum
842
- calculateMomentum(prices) {
843
- const momentum = [];
844
- for (let i = 10; i < prices.length; i++) {
845
- momentum.push(prices[i] - prices[i - 10]);
846
- }
847
- return momentum;
848
- }
849
- // Calculate Keltner Channels
850
- calculateKeltnerChannels(prices, highs, lows) {
851
- const keltner = [];
852
- const period = 20;
853
- const multiplier = 2;
854
- if (prices.length < period) return [];
855
- const ema = this.calculateEMA(prices, period);
856
- const atr = this.calculateAtr(prices, highs, lows);
857
- for (let i = 0; i < Math.min(ema.length, atr.length); i++) {
858
- const middle = ema[i];
859
- const atrValue = atr[i];
860
- keltner.push({
861
- upper: middle + multiplier * atrValue,
862
- middle,
863
- lower: middle - multiplier * atrValue
864
- });
865
- }
866
- return keltner;
867
- }
868
- // Calculate Donchian Channels
869
- calculateDonchianChannels(prices) {
870
- const donchian = [];
871
- for (let i = 20; i < prices.length; i++) {
872
- const slice = prices.slice(i - 20, i);
873
- donchian.push({
874
- upper: Math.max(...slice),
875
- middle: (Math.max(...slice) + Math.min(...slice)) / 2,
876
- lower: Math.min(...slice)
877
- });
878
- }
879
- return donchian;
880
- }
881
- // Calculate Chaikin Volatility
882
- calculateChaikinVolatility(prices, highs, lows) {
883
- const volatility = [];
884
- const period = 10;
885
- if (prices.length < period * 2) return [];
886
- const highLowRange = [];
887
- for (let i = 0; i < prices.length; i++) {
888
- const high = highs[i] || prices[i];
889
- const low = lows[i] || prices[i];
890
- highLowRange.push(high - low);
891
- }
892
- const emaRange = this.calculateEMA(highLowRange, period);
893
- for (let i = period; i < emaRange.length; i++) {
894
- const currentEMA = emaRange[i];
895
- const pastEMA = emaRange[i - period];
896
- const volatilityValue = pastEMA !== 0 ? (currentEMA - pastEMA) / pastEMA * 100 : 0;
897
- volatility.push(volatilityValue);
898
- }
899
- return volatility;
900
- }
901
- // Calculate On Balance Volume
902
- calculateObv(volumes) {
903
- const obv = [volumes[0]];
904
- for (let i = 1; i < volumes.length; i++) {
905
- obv.push(obv[i - 1] + volumes[i]);
906
- }
907
- return obv;
908
- }
909
- // Calculate Chaikin Money Flow
910
- calculateCmf(prices, highs, lows, volumes) {
911
- const cmf = [];
912
- const period = 20;
913
- if (prices.length < period) return [];
914
- for (let i = period - 1; i < prices.length; i++) {
915
- let totalMoneyFlowVolume = 0;
916
- let totalVolume = 0;
917
- for (let j = i - period + 1; j <= i; j++) {
918
- const high = highs[j] || prices[j];
919
- const low = lows[j] || prices[j];
920
- const close = prices[j];
921
- const volume = volumes[j] || 1;
922
- const moneyFlowMultiplier = (close - low - (high - close)) / (high - low);
923
- const moneyFlowVolume = moneyFlowMultiplier * volume;
924
- totalMoneyFlowVolume += moneyFlowVolume;
925
- totalVolume += volume;
926
- }
927
- const cmfValue = totalVolume !== 0 ? totalMoneyFlowVolume / totalVolume : 0;
928
- cmf.push(cmfValue);
929
- }
930
- return cmf;
931
- }
932
- // Calculate Accumulation/Distribution Line
933
- calculateAdl(prices) {
934
- const adl = [0];
935
- for (let i = 1; i < prices.length; i++) {
936
- const high = this.highs[i] || prices[i];
937
- const low = this.lows[i] || prices[i];
938
- const close = prices[i];
939
- const volume = this.volumes[i] || 1;
940
- const moneyFlowMultiplier = (close - low - (high - close)) / (high - low);
941
- const moneyFlowVolume = moneyFlowMultiplier * volume;
942
- adl.push(adl[i - 1] + moneyFlowVolume);
943
- }
944
- return adl;
945
- }
946
- // Calculate Volume Rate of Change
947
- calculateVolumeROC() {
948
- const volumeROC = [];
949
- for (let i = 10; i < this.volumes.length; i++) {
950
- volumeROC.push((this.volumes[i] - this.volumes[i - 10]) / this.volumes[i - 10] * 100);
951
- }
952
- return volumeROC;
953
- }
954
- // Calculate Money Flow Index
955
- calculateMfi(prices, highs, lows, volumes) {
956
- const mfi = [];
957
- const period = 14;
958
- if (prices.length < period + 1) return [];
959
- for (let i = period; i < prices.length; i++) {
960
- let positiveMoneyFlow = 0;
961
- let negativeMoneyFlow = 0;
962
- for (let j = i - period + 1; j <= i; j++) {
963
- const high = highs[j] || prices[j];
964
- const low = lows[j] || prices[j];
965
- const close = prices[j];
966
- const volume = volumes[j] || 1;
967
- const typicalPrice = (high + low + close) / 3;
968
- const moneyFlow = typicalPrice * volume;
969
- if (j > i - period + 1) {
970
- const prevHigh = highs[j - 1] || prices[j - 1];
971
- const prevLow = lows[j - 1] || prices[j - 1];
972
- const prevClose = prices[j - 1];
973
- const prevTypicalPrice = (prevHigh + prevLow + prevClose) / 3;
974
- if (typicalPrice > prevTypicalPrice) {
975
- positiveMoneyFlow += moneyFlow;
976
- } else if (typicalPrice < prevTypicalPrice) {
977
- negativeMoneyFlow += moneyFlow;
978
- }
979
- }
980
- }
981
- const moneyRatio = negativeMoneyFlow !== 0 ? positiveMoneyFlow / negativeMoneyFlow : 0;
982
- const mfiValue = 100 - 100 / (1 + moneyRatio);
983
- mfi.push(mfiValue);
984
- }
985
- return mfi;
986
- }
987
- // Calculate VWAP
988
- calculateVwap(prices, volumes) {
989
- const vwap = [];
990
- let cumulativePV = 0;
991
- let cumulativeVolume = 0;
992
- for (let i = 0; i < prices.length; i++) {
993
- cumulativePV += prices[i] * (volumes[i] || 1);
994
- cumulativeVolume += volumes[i] || 1;
995
- vwap.push(cumulativePV / cumulativeVolume);
996
- }
997
- return vwap;
998
- }
999
- // Calculate Pivot Points
1000
- calculatePivotPoints(prices) {
1001
- const pivotPoints = [];
1002
- for (let i = 0; i < prices.length; i++) {
1003
- const high = this.highs[i] || prices[i];
1004
- const low = this.lows[i] || prices[i];
1005
- const close = prices[i];
1006
- const pp = (high + low + close) / 3;
1007
- const r1 = 2 * pp - low;
1008
- const s1 = 2 * pp - high;
1009
- const r2 = pp + (high - low);
1010
- const s2 = pp - (high - low);
1011
- const r3 = high + 2 * (pp - low);
1012
- const s3 = low - 2 * (high - pp);
1013
- pivotPoints.push({
1014
- pp,
1015
- r1,
1016
- r2,
1017
- r3,
1018
- s1,
1019
- s2,
1020
- s3
1021
- });
1022
- }
1023
- return pivotPoints;
1024
- }
1025
- // Calculate Fibonacci Levels
1026
- calculateFibonacciLevels(prices) {
1027
- const fibonacci = [];
1028
- for (let i = 0; i < prices.length; i++) {
1029
- const price = prices[i];
1030
- fibonacci.push({
1031
- retracement: {
1032
- level0: price,
1033
- level236: price * 0.764,
1034
- level382: price * 0.618,
1035
- level500: price * 0.5,
1036
- level618: price * 0.382,
1037
- level786: price * 0.214,
1038
- level100: price * 0
1039
- },
1040
- extension: {
1041
- level1272: price * 1.272,
1042
- level1618: price * 1.618,
1043
- level2618: price * 2.618,
1044
- level4236: price * 4.236
1045
- }
1046
- });
1047
- }
1048
- return fibonacci;
1049
- }
1050
- // Calculate Gann Levels
1051
- calculateGannLevels(prices) {
1052
- const gannLevels = [];
1053
- for (let i = 0; i < prices.length; i++) {
1054
- gannLevels.push(prices[i] * (1 + i * 0.01));
1055
- }
1056
- return gannLevels;
1057
- }
1058
- // Calculate Elliott Wave
1059
- calculateElliottWave(prices) {
1060
- const elliottWave = [];
1061
- if (prices.length < 10) return [];
1062
- for (let i = 0; i < prices.length; i++) {
1063
- const waves = [];
1064
- let currentWave = 1;
1065
- let wavePosition = 0.5;
1066
- if (i >= 4) {
1067
- const recentPrices = prices.slice(i - 4, i + 1);
1068
- const swings = this.detectPriceSwings(recentPrices);
1069
- if (swings.length >= 3) {
1070
- waves.push(...swings.slice(0, 3));
1071
- currentWave = Math.min(swings.length, 5);
1072
- wavePosition = this.calculateWavePosition(recentPrices);
1073
- }
1074
- }
1075
- elliottWave.push({
1076
- waves: waves.length > 0 ? waves : [prices[i]],
1077
- currentWave,
1078
- wavePosition
1079
- });
1080
- }
1081
- return elliottWave;
1082
- }
1083
- // Helper method to detect price swings
1084
- detectPriceSwings(prices) {
1085
- const swings = [];
1086
- for (let i = 1; i < prices.length - 1; i++) {
1087
- const prev = prices[i - 1];
1088
- const curr = prices[i];
1089
- const next = prices[i + 1];
1090
- if (curr > prev && curr > next) {
1091
- swings.push(curr);
1092
- } else if (curr < prev && curr < next) {
1093
- swings.push(curr);
1094
- }
1095
- }
1096
- return swings;
1097
- }
1098
- // Helper method to calculate wave position
1099
- calculateWavePosition(prices) {
1100
- if (prices.length < 2) return 0.5;
1101
- const current = prices[prices.length - 1];
1102
- const min = Math.min(...prices);
1103
- const max = Math.max(...prices);
1104
- return max !== min ? (current - min) / (max - min) : 0.5;
1105
- }
1106
- // Calculate Harmonic Patterns
1107
- calculateHarmonicPatterns(prices) {
1108
- const harmonicPatterns = [];
1109
- if (prices.length < 5) return [];
1110
- for (let i = 4; i < prices.length; i++) {
1111
- const recentPrices = prices.slice(i - 4, i + 1);
1112
- const pattern = this.detectHarmonicPattern(recentPrices);
1113
- harmonicPatterns.push(pattern);
1114
- }
1115
- return harmonicPatterns;
1116
- }
1117
- // Helper method to detect harmonic patterns
1118
- detectHarmonicPattern(prices) {
1119
- if (prices.length < 5) {
1120
- return {
1121
- type: "Unknown",
1122
- completion: 0,
1123
- target: prices[prices.length - 1] * 1.1,
1124
- stopLoss: prices[prices.length - 1] * 0.9
1125
- };
1126
- }
1127
- const swings = this.detectPriceSwings(prices);
1128
- if (swings.length < 4) {
1129
- return {
1130
- type: "Unknown",
1131
- completion: 0,
1132
- target: prices[prices.length - 1] * 1.1,
1133
- stopLoss: prices[prices.length - 1] * 0.9
1134
- };
1135
- }
1136
- const [A, B, C, D] = swings.slice(-4);
1137
- const X = prices[0];
1138
- const abRatio = Math.abs((B - A) / (X - A));
1139
- const bcRatio = Math.abs((C - B) / (A - B));
1140
- const cdRatio = Math.abs((D - C) / (B - C));
1141
- const adRatio = Math.abs((D - A) / (X - A));
1142
- 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;
1143
- if (isGartley) {
1144
- const completion = this.calculatePatternCompletion(prices);
1145
- const target = D + (D - C) * 0.618;
1146
- const stopLoss = D - (D - C) * 0.382;
1147
- return {
1148
- type: "Gartley",
1149
- completion,
1150
- target,
1151
- stopLoss
1152
- };
1153
- }
1154
- 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;
1155
- if (isButterfly) {
1156
- const completion = this.calculatePatternCompletion(prices);
1157
- const target = D + (D - C) * 1.27;
1158
- const stopLoss = D - (D - C) * 0.5;
1159
- return {
1160
- type: "Butterfly",
1161
- completion,
1162
- target,
1163
- stopLoss
1164
- };
1165
- }
1166
- return {
1167
- type: "Unknown",
1168
- completion: 0,
1169
- target: prices[prices.length - 1] * 1.1,
1170
- stopLoss: prices[prices.length - 1] * 0.9
1171
- };
1172
- }
1173
- // Helper method to calculate pattern completion
1174
- calculatePatternCompletion(prices) {
1175
- if (prices.length < 2) return 0;
1176
- const current = prices[prices.length - 1];
1177
- const min = Math.min(...prices);
1178
- const max = Math.max(...prices);
1179
- return max !== min ? (current - min) / (max - min) : 0;
1180
- }
1181
- // Calculate Position Size
1182
- calculatePositionSize(currentPrice, targetEntry, stopLoss) {
1183
- void currentPrice;
1184
- const riskPerShare = Math.abs(targetEntry - stopLoss);
1185
- return riskPerShare > 0 ? 100 / riskPerShare : 1;
1186
- }
1187
- // Calculate Confidence
1188
- calculateConfidence(signals) {
1189
- return Math.min(signals.length * 10, 100);
1190
- }
1191
- // Calculate Risk Level
1192
- calculateRiskLevel(volatility) {
1193
- if (volatility < 20) return "LOW";
1194
- if (volatility < 40) return "MEDIUM";
1195
- return "HIGH";
1196
- }
1197
- // Calculate Z-Score
1198
- calculateZScore(currentPrice, startPrice) {
1199
- return (currentPrice - startPrice) / (startPrice * 0.1);
1200
- }
1201
- // Calculate Ornstein-Uhlenbeck
1202
- calculateOrnsteinUhlenbeck(currentPrice, startPrice, avgVolume) {
1203
- const priceChanges = this.calculatePriceChanges();
1204
- const mean = startPrice;
1205
- let speed = 0.1;
1206
- if (priceChanges.length > 1) {
1207
- const variance = priceChanges.reduce((sum2, change) => sum2 + change * change, 0) / priceChanges.length;
1208
- speed = Math.max(0.01, Math.min(1, variance * 10));
1209
- }
1210
- const volatility = avgVolume * 0.01;
1211
- return {
1212
- mean,
1213
- speed,
1214
- volatility,
1215
- currentValue: currentPrice
1216
- };
1217
- }
1218
- // Calculate Kalman Filter
1219
- calculateKalmanFilter(currentPrice, startPrice, avgVolume) {
1220
- const measurementNoise = avgVolume * 1e-3;
1221
- const processNoise = avgVolume * 1e-4;
1222
- let state = startPrice;
1223
- let covariance = measurementNoise;
1224
- const priceChanges = this.calculatePriceChanges();
1225
- if (priceChanges.length > 0) {
1226
- const predictedState = state;
1227
- const predictedCovariance = covariance + processNoise;
1228
- const kalmanGain = predictedCovariance / (predictedCovariance + measurementNoise);
1229
- state = predictedState + kalmanGain * (currentPrice - predictedState);
1230
- covariance = (1 - kalmanGain) * predictedCovariance;
1231
- return {
1232
- state,
1233
- covariance,
1234
- gain: kalmanGain
1235
- };
1236
- }
1237
- return {
1238
- state: currentPrice,
1239
- covariance,
1240
- gain: 0.5
1241
- };
1242
- }
1243
- // Calculate ARIMA
1244
- calculateArima(currentPrice) {
1245
- const priceChanges = this.calculatePriceChanges();
1246
- if (priceChanges.length < 3) {
1247
- return {
1248
- forecast: [currentPrice * 1.01, currentPrice * 1.02],
1249
- residuals: [0, 0],
1250
- aic: 100
1251
- };
1252
- }
1253
- const n = priceChanges.length;
1254
- let sumY = 0;
1255
- let sumY1 = 0;
1256
- let sumYY1 = 0;
1257
- let sumY1Sq = 0;
1258
- for (let i = 1; i < n; i++) {
1259
- const y = priceChanges[i];
1260
- const y1 = priceChanges[i - 1];
1261
- sumY += y;
1262
- sumY1 += y1;
1263
- sumYY1 += y * y1;
1264
- sumY1Sq += y1 * y1;
1265
- }
1266
- const phi = (n * sumYY1 - sumY * sumY1) / (n * sumY1Sq - sumY1 * sumY1);
1267
- const c = (sumY - phi * sumY1) / n;
1268
- const residuals = [];
1269
- for (let i = 1; i < n; i++) {
1270
- const predicted = c + phi * priceChanges[i - 1];
1271
- residuals.push(priceChanges[i] - predicted);
1272
- }
1273
- const rss = residuals.reduce((sum2, r) => sum2 + r * r, 0);
1274
- const aic = n * Math.log(rss / n) + 2 * 2;
1275
- const lastChange = priceChanges[priceChanges.length - 1];
1276
- const forecast1 = currentPrice + (c + phi * lastChange);
1277
- const forecast2 = forecast1 + (c + phi * (c + phi * lastChange));
1278
- return {
1279
- forecast: [forecast1, forecast2],
1280
- residuals,
1281
- aic
1282
- };
1283
- }
1284
- // Calculate GARCH
1285
- calculateGarch(avgVolume) {
1286
- const priceChanges = this.calculatePriceChanges();
1287
- if (priceChanges.length < 5) {
1288
- return {
1289
- volatility: avgVolume * 0.01,
1290
- persistence: 0.9,
1291
- meanReversion: 0.1
1292
- };
1293
- }
1294
- const squaredReturns = priceChanges.map((change) => change * change);
1295
- const meanSquaredReturn = squaredReturns.reduce((sum2, sq) => sum2 + sq, 0) / squaredReturns.length;
1296
- let persistence = 0.9;
1297
- if (squaredReturns.length > 1) {
1298
- const variance = squaredReturns.reduce((sum2, sq) => sum2 + sq, 0) / squaredReturns.length;
1299
- persistence = Math.min(0.99, Math.max(0.5, variance / meanSquaredReturn));
1300
- }
1301
- const meanReversion = meanSquaredReturn * (1 - persistence);
1302
- const volatility = Math.sqrt(meanSquaredReturn);
1303
- return {
1304
- volatility,
1305
- persistence,
1306
- meanReversion
1307
- };
1308
- }
1309
- // Calculate Hilbert Transform
1310
- calculateHilbertTransform(currentPrice) {
1311
- const priceChanges = this.calculatePriceChanges();
1312
- if (priceChanges.length < 3) {
1313
- return {
1314
- analytic: [currentPrice],
1315
- phase: [0],
1316
- amplitude: [currentPrice]
1317
- };
1318
- }
1319
- const n = priceChanges.length;
1320
- const analytic = [];
1321
- const phase = [];
1322
- const amplitude = [];
1323
- for (let i = 0; i < n; i++) {
1324
- let hilbertValue = 0;
1325
- for (let j = 0; j < n; j++) {
1326
- if (i !== j) {
1327
- hilbertValue += priceChanges[j] / (Math.PI * (i - j));
1328
- }
1329
- }
1330
- const realPart = priceChanges[i];
1331
- const imagPart = hilbertValue;
1332
- const analyticValue = Math.sqrt(realPart * realPart + imagPart * imagPart);
1333
- analytic.push(analyticValue);
1334
- const phaseValue = Math.atan2(imagPart, realPart);
1335
- phase.push(phaseValue);
1336
- amplitude.push(analyticValue);
1337
- }
1338
- return {
1339
- analytic,
1340
- phase,
1341
- amplitude
1342
- };
1343
- }
1344
- // Calculate Wavelet Transform
1345
- calculateWaveletTransform(currentPrice) {
1346
- const priceChanges = this.calculatePriceChanges();
1347
- if (priceChanges.length < 4) {
1348
- return {
1349
- coefficients: [currentPrice],
1350
- scales: [1]
1351
- };
1352
- }
1353
- const coefficients = [];
1354
- const scales = [];
1355
- const n = priceChanges.length;
1356
- const maxLevel = Math.floor(Math.log2(n));
1357
- for (let level = 1; level <= maxLevel; level++) {
1358
- const step = 2 ** (level - 1);
1359
- const scale = step;
1360
- for (let i = 0; i < n - step; i += step * 2) {
1361
- if (i + step < n) {
1362
- const coefficient = (priceChanges[i] - priceChanges[i + step]) / Math.sqrt(2);
1363
- coefficients.push(coefficient);
1364
- scales.push(scale);
1365
- }
1366
- }
1367
- }
1368
- if (coefficients.length === 0) {
1369
- coefficients.push(currentPrice);
1370
- scales.push(1);
1371
- }
1372
- return {
1373
- coefficients,
1374
- scales
1375
- };
1376
- }
1377
- // Calculate Black-Scholes
1378
- calculateBlackScholes(currentPrice, startPrice, avgVolume) {
1379
- const S = currentPrice;
1380
- const K = startPrice;
1381
- const T = 1;
1382
- const r = 0.05;
1383
- const sigma = avgVolume * 0.01;
1384
- const d1 = (Math.log(S / K) + (r + sigma * sigma / 2) * T) / (sigma * Math.sqrt(T));
1385
- const d2 = d1 - sigma * Math.sqrt(T);
1386
- const callPrice = S * this.normalCDF(d1) - K * Math.exp(-r * T) * this.normalCDF(d2);
1387
- const putPrice = K * Math.exp(-r * T) * this.normalCDF(-d2) - S * this.normalCDF(-d1);
1388
- return {
1389
- callPrice,
1390
- putPrice,
1391
- delta: this.normalCDF(d1),
1392
- gamma: this.normalPDF(d1) / (S * sigma * Math.sqrt(T)),
1393
- theta: -S * this.normalPDF(d1) * sigma / (2 * Math.sqrt(T)) - r * K * Math.exp(-r * T) * this.normalCDF(d2),
1394
- vega: S * Math.sqrt(T) * this.normalPDF(d1),
1395
- rho: K * T * Math.exp(-r * T) * this.normalCDF(d2)
1396
- };
1397
- }
1398
- // Normal CDF approximation
1399
- normalCDF(x) {
1400
- return 0.5 * (1 + this.erf(x / Math.sqrt(2)));
1401
- }
1402
- // Normal PDF
1403
- normalPDF(x) {
1404
- return Math.exp(-x * x / 2) / Math.sqrt(2 * Math.PI);
1405
- }
1406
- // Error function approximation
1407
- erf(x) {
1408
- const a1 = 0.254829592;
1409
- const a2 = -0.284496736;
1410
- const a3 = 1.421413741;
1411
- const a4 = -1.453152027;
1412
- const a5 = 1.061405429;
1413
- const p = 0.3275911;
1414
- const sign = x >= 0 ? 1 : -1;
1415
- const absX = Math.abs(x);
1416
- const t = 1 / (1 + p * absX);
1417
- const y = 1 - ((((a5 * t + a4) * t + a3) * t + a2) * t + a1) * t * Math.exp(-absX * absX);
1418
- return sign * y;
1419
- }
1420
- // Calculate price changes for volatility
1421
- calculatePriceChanges() {
1422
- const changes = [];
1423
- for (let i = 1; i < this.prices.length; i++) {
1424
- changes.push((this.prices[i] - this.prices[i - 1]) / this.prices[i - 1]);
1425
- }
1426
- return changes;
1427
- }
1428
- // Generate comprehensive market analysis
1429
- analyze() {
1430
- const currentPrice = this.prices[this.prices.length - 1];
1431
- const startPrice = this.prices[0];
1432
- const sessionHigh = Math.max(...this.highs);
1433
- const sessionLow = Math.min(...this.lows);
1434
- const totalVolume = sum(this.volumes);
1435
- const avgVolume = totalVolume / this.volumes.length;
1436
- const priceChanges = this.calculatePriceChanges();
1437
- const volatility = priceChanges.length > 0 ? Math.sqrt(
1438
- priceChanges.reduce((sum2, change) => sum2 + change ** 2, 0) / priceChanges.length
1439
- ) * Math.sqrt(252) * 100 : 0;
1440
- const sessionReturn = (currentPrice - startPrice) / startPrice * 100;
1441
- const pricePosition = (currentPrice - sessionLow) / (sessionHigh - sessionLow) * 100;
1442
- const trueVWAP = this.prices.reduce((sum2, price, i) => sum2 + price * this.volumes[i], 0) / totalVolume;
1443
- 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;
1444
- 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;
1445
- const maxDrawdown = this.calculateMaxDrawdown(this.prices);
1446
- const atrValues = this.calculateAtr(this.prices, this.highs, this.lows);
1447
- const atr = atrValues.length > 0 ? atrValues[atrValues.length - 1] : 0;
1448
- const impliedVolatility = volatility;
1449
- const realizedVolatility = volatility;
1450
- const sharpeRatio = sessionReturn / volatility;
1451
- const sortinoRatio = sessionReturn / realizedVolatility;
1452
- const calmarRatio = sessionReturn / maxDrawdown;
1453
- const maxConsecutiveLosses = this.calculateMaxConsecutiveLosses(this.prices);
1454
- const winRate = this.calculateWinRate(this.prices);
1455
- const profitFactor = this.calculateProfitFactor(this.prices);
1456
- return {
1457
- currentPrice,
1458
- startPrice,
1459
- sessionHigh,
1460
- sessionLow,
1461
- totalVolume,
1462
- avgVolume,
1463
- volatility,
1464
- sessionReturn,
1465
- pricePosition,
1466
- trueVWAP,
1467
- momentum5,
1468
- momentum10,
1469
- maxDrawdown,
1470
- atr,
1471
- impliedVolatility,
1472
- realizedVolatility,
1473
- sharpeRatio,
1474
- sortinoRatio,
1475
- calmarRatio,
1476
- maxConsecutiveLosses,
1477
- winRate,
1478
- profitFactor
1479
- };
1480
- }
1481
- // Generate technical indicators
1482
- getTechnicalIndicators() {
1483
- return {
1484
- sma5: this.calculateSMA(this.prices, 5),
1485
- sma10: this.calculateSMA(this.prices, 10),
1486
- sma20: this.calculateSMA(this.prices, 20),
1487
- sma50: this.calculateSMA(this.prices, 50),
1488
- sma200: this.calculateSMA(this.prices, 200),
1489
- ema8: this.calculateEMA(this.prices, 8),
1490
- ema12: this.calculateEMA(this.prices, 12),
1491
- ema21: this.calculateEMA(this.prices, 21),
1492
- ema26: this.calculateEMA(this.prices, 26),
1493
- wma20: this.calculateWma(this.prices, 20),
1494
- vwma20: this.calculateVwma(this.prices, 20),
1495
- macd: this.calculateMacd(this.prices),
1496
- adx: this.calculateAdx(this.prices, this.highs, this.lows),
1497
- dmi: this.calculateDmi(this.prices, this.highs, this.lows),
1498
- ichimoku: this.calculateIchimoku(this.prices, this.highs, this.lows),
1499
- parabolicSAR: this.calculateParabolicSAR(this.prices, this.highs, this.lows),
1500
- rsi: this.calculateRSI(this.prices, 14),
1501
- stochastic: this.calculateStochastic(this.prices, this.highs, this.lows),
1502
- cci: this.calculateCci(this.prices, this.highs, this.lows),
1503
- roc: this.calculateRoc(this.prices),
1504
- williamsR: this.calculateWilliamsR(this.prices),
1505
- momentum: this.calculateMomentum(this.prices),
1506
- bollinger: this.calculateBollingerBands(this.prices, 20, 2),
1507
- atr: this.calculateAtr(this.prices, this.highs, this.lows),
1508
- keltner: this.calculateKeltnerChannels(this.prices, this.highs, this.lows),
1509
- donchian: this.calculateDonchianChannels(this.prices),
1510
- chaikinVolatility: this.calculateChaikinVolatility(this.prices, this.highs, this.lows),
1511
- obv: this.calculateObv(this.volumes),
1512
- cmf: this.calculateCmf(this.prices, this.highs, this.lows, this.volumes),
1513
- adl: this.calculateAdl(this.prices),
1514
- volumeROC: this.calculateVolumeROC(),
1515
- mfi: this.calculateMfi(this.prices, this.highs, this.lows, this.volumes),
1516
- vwap: this.calculateVwap(this.prices, this.volumes),
1517
- pivotPoints: this.calculatePivotPoints(this.prices),
1518
- fibonacci: this.calculateFibonacciLevels(this.prices),
1519
- gannLevels: this.calculateGannLevels(this.prices),
1520
- elliottWave: this.calculateElliottWave(this.prices),
1521
- harmonicPatterns: this.calculateHarmonicPatterns(this.prices)
1522
- };
1523
- }
1524
- // Generate trading signals
1525
- generateSignals() {
1526
- const analysis = this.analyze();
1527
- let bullishSignals = 0;
1528
- let bearishSignals = 0;
1529
- const signals = [];
1530
- if (analysis.currentPrice > analysis.trueVWAP) {
1531
- signals.push(
1532
- `\u2713 BULLISH: Price above VWAP (+${((analysis.currentPrice - analysis.trueVWAP) / analysis.trueVWAP * 100).toFixed(2)}%)`
1533
- );
1534
- bullishSignals++;
1535
- } else {
1536
- signals.push(
1537
- `\u2717 BEARISH: Price below VWAP (${((analysis.currentPrice - analysis.trueVWAP) / analysis.trueVWAP * 100).toFixed(2)}%)`
1538
- );
1539
- bearishSignals++;
1540
- }
1541
- if (analysis.momentum5 > 0 && analysis.momentum10 > 0) {
1542
- signals.push("\u2713 BULLISH: Positive momentum on both timeframes");
1543
- bullishSignals++;
1544
- } else if (analysis.momentum5 < 0 && analysis.momentum10 < 0) {
1545
- signals.push("\u2717 BEARISH: Negative momentum on both timeframes");
1546
- bearishSignals++;
1547
- } else {
1548
- signals.push("\u25D0 MIXED: Conflicting momentum signals");
1549
- }
1550
- const currentVolume = this.volumes[this.volumes.length - 1];
1551
- const volumeRatio = currentVolume / analysis.avgVolume;
1552
- if (volumeRatio > 1.2 && analysis.sessionReturn > 0) {
1553
- signals.push("\u2713 BULLISH: Above-average volume supporting upward move");
1554
- bullishSignals++;
1555
- } else if (volumeRatio > 1.2 && analysis.sessionReturn < 0) {
1556
- signals.push("\u2717 BEARISH: Above-average volume supporting downward move");
1557
- bearishSignals++;
1558
- } else {
1559
- signals.push("\u25D0 NEUTRAL: Volume not providing clear direction");
1560
- }
1561
- if (analysis.pricePosition > 65 && analysis.volatility > 30) {
1562
- signals.push("\u2717 BEARISH: High in range with elevated volatility - reversal risk");
1563
- bearishSignals++;
1564
- } else if (analysis.pricePosition < 35 && analysis.volatility > 30) {
1565
- signals.push("\u2713 BULLISH: Low in range with volatility - potential bounce");
1566
- bullishSignals++;
1567
- } else {
1568
- signals.push("\u25D0 NEUTRAL: Price position and volatility not extreme");
1569
- }
1570
- return { bullishSignals, bearishSignals, signals };
1571
- }
1572
- // Generate comprehensive JSON analysis
1573
- generateJSONAnalysis(symbol) {
1574
- const analysis = this.analyze();
1575
- const indicators = this.getTechnicalIndicators();
1576
- const signals = this.generateSignals();
1577
- const currentSMA5 = indicators.sma5.length > 0 ? indicators.sma5[indicators.sma5.length - 1] : null;
1578
- const currentSMA10 = indicators.sma10.length > 0 ? indicators.sma10[indicators.sma10.length - 1] : null;
1579
- const currentSMA20 = indicators.sma20.length > 0 ? indicators.sma20[indicators.sma20.length - 1] : null;
1580
- const currentSMA50 = indicators.sma50.length > 0 ? indicators.sma50[indicators.sma50.length - 1] : null;
1581
- const currentSMA200 = indicators.sma200.length > 0 ? indicators.sma200[indicators.sma200.length - 1] : null;
1582
- const currentEMA8 = indicators.ema8[indicators.ema8.length - 1];
1583
- const currentEMA12 = indicators.ema12[indicators.ema12.length - 1];
1584
- const currentEMA21 = indicators.ema21[indicators.ema21.length - 1];
1585
- const currentEMA26 = indicators.ema26[indicators.ema26.length - 1];
1586
- const currentWMA20 = indicators.wma20.length > 0 ? indicators.wma20[indicators.wma20.length - 1] : null;
1587
- const currentVWMA20 = indicators.vwma20.length > 0 ? indicators.vwma20[indicators.vwma20.length - 1] : null;
1588
- const currentMACD = indicators.macd.length > 0 ? indicators.macd[indicators.macd.length - 1] : null;
1589
- const currentADX = indicators.adx.length > 0 ? indicators.adx[indicators.adx.length - 1] : null;
1590
- const currentDMI = indicators.dmi.length > 0 ? indicators.dmi[indicators.dmi.length - 1] : null;
1591
- const currentIchimoku = indicators.ichimoku.length > 0 ? indicators.ichimoku[indicators.ichimoku.length - 1] : null;
1592
- const currentParabolicSAR = indicators.parabolicSAR.length > 0 ? indicators.parabolicSAR[indicators.parabolicSAR.length - 1] : null;
1593
- const currentRSI = indicators.rsi.length > 0 ? indicators.rsi[indicators.rsi.length - 1] : null;
1594
- const currentStochastic = indicators.stochastic.length > 0 ? indicators.stochastic[indicators.stochastic.length - 1] : null;
1595
- const currentCCI = indicators.cci.length > 0 ? indicators.cci[indicators.cci.length - 1] : null;
1596
- const currentROC = indicators.roc.length > 0 ? indicators.roc[indicators.roc.length - 1] : null;
1597
- const currentWilliamsR = indicators.williamsR.length > 0 ? indicators.williamsR[indicators.williamsR.length - 1] : null;
1598
- const currentMomentum = indicators.momentum.length > 0 ? indicators.momentum[indicators.momentum.length - 1] : null;
1599
- const currentBB = indicators.bollinger.length > 0 ? indicators.bollinger[indicators.bollinger.length - 1] : null;
1600
- const currentAtr = indicators.atr.length > 0 ? indicators.atr[indicators.atr.length - 1] : null;
1601
- const currentKeltner = indicators.keltner.length > 0 ? indicators.keltner[indicators.keltner.length - 1] : null;
1602
- const currentDonchian = indicators.donchian.length > 0 ? indicators.donchian[indicators.donchian.length - 1] : null;
1603
- const currentChaikinVolatility = indicators.chaikinVolatility.length > 0 ? indicators.chaikinVolatility[indicators.chaikinVolatility.length - 1] : null;
1604
- const currentObv = indicators.obv.length > 0 ? indicators.obv[indicators.obv.length - 1] : null;
1605
- const currentCmf = indicators.cmf.length > 0 ? indicators.cmf[indicators.cmf.length - 1] : null;
1606
- const currentAdl = indicators.adl.length > 0 ? indicators.adl[indicators.adl.length - 1] : null;
1607
- const currentVolumeROC = indicators.volumeROC.length > 0 ? indicators.volumeROC[indicators.volumeROC.length - 1] : null;
1608
- const currentMfi = indicators.mfi.length > 0 ? indicators.mfi[indicators.mfi.length - 1] : null;
1609
- const currentVwap = indicators.vwap.length > 0 ? indicators.vwap[indicators.vwap.length - 1] : null;
1610
- const currentPivotPoints = indicators.pivotPoints.length > 0 ? indicators.pivotPoints[indicators.pivotPoints.length - 1] : null;
1611
- const currentFibonacci = indicators.fibonacci.length > 0 ? indicators.fibonacci[indicators.fibonacci.length - 1] : null;
1612
- const currentGannLevels = indicators.gannLevels.length > 0 ? indicators.gannLevels : [];
1613
- const currentElliottWave = indicators.elliottWave.length > 0 ? indicators.elliottWave[indicators.elliottWave.length - 1] : null;
1614
- const currentHarmonicPatterns = indicators.harmonicPatterns.length > 0 ? indicators.harmonicPatterns : [];
1615
- const currentVolume = this.volumes[this.volumes.length - 1];
1616
- const volumeRatio = currentVolume / analysis.avgVolume;
1617
- const currentDrawdown = (analysis.sessionHigh - analysis.currentPrice) / analysis.sessionHigh * 100;
1618
- const rangeWidth = (analysis.sessionHigh - analysis.sessionLow) / analysis.sessionLow * 100;
1619
- const priceVsVWAP = (analysis.currentPrice - analysis.trueVWAP) / analysis.trueVWAP * 100;
1620
- const totalScore = signals.bullishSignals - signals.bearishSignals;
1621
- const overallSignal = totalScore > 0 ? "BULLISH_BIAS" : totalScore < 0 ? "BEARISH_BIAS" : "NEUTRAL";
1622
- const targetEntry = Math.max(analysis.sessionLow * 1.005, analysis.trueVWAP * 0.998);
1623
- const stopLoss = analysis.sessionLow * 0.995;
1624
- const profitTarget = analysis.sessionHigh * 0.995;
1625
- const riskRewardRatio = (profitTarget - analysis.currentPrice) / (analysis.currentPrice - stopLoss);
1626
- const positionSize = this.calculatePositionSize(analysis.currentPrice, targetEntry, stopLoss);
1627
- const maxRisk = positionSize * (targetEntry - stopLoss);
1628
- return {
1629
- symbol,
1630
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1631
- marketStructure: {
1632
- currentPrice: analysis.currentPrice,
1633
- startPrice: analysis.startPrice,
1634
- sessionHigh: analysis.sessionHigh,
1635
- sessionLow: analysis.sessionLow,
1636
- rangeWidth,
1637
- totalVolume: analysis.totalVolume,
1638
- sessionPerformance: analysis.sessionReturn,
1639
- positionInRange: analysis.pricePosition
1640
- },
1641
- volatility: {
1642
- impliedVolatility: analysis.impliedVolatility,
1643
- realizedVolatility: analysis.realizedVolatility,
1644
- atr: analysis.atr,
1645
- maxDrawdown: analysis.maxDrawdown * 100,
1646
- currentDrawdown
1647
- },
1648
- technicalIndicators: {
1649
- sma5: currentSMA5,
1650
- sma10: currentSMA10,
1651
- sma20: currentSMA20,
1652
- sma50: currentSMA50,
1653
- sma200: currentSMA200,
1654
- ema8: currentEMA8,
1655
- ema12: currentEMA12,
1656
- ema21: currentEMA21,
1657
- ema26: currentEMA26,
1658
- wma20: currentWMA20,
1659
- vwma20: currentVWMA20,
1660
- macd: currentMACD,
1661
- adx: currentADX,
1662
- dmi: currentDMI,
1663
- ichimoku: currentIchimoku,
1664
- parabolicSAR: currentParabolicSAR,
1665
- rsi: currentRSI,
1666
- stochastic: currentStochastic,
1667
- cci: currentCCI,
1668
- roc: currentROC,
1669
- williamsR: currentWilliamsR,
1670
- momentum: currentMomentum,
1671
- bollingerBands: currentBB ? {
1672
- upper: currentBB.upper,
1673
- middle: currentBB.middle,
1674
- lower: currentBB.lower,
1675
- bandwidth: currentBB.bandwidth,
1676
- percentB: currentBB.percentB
1677
- } : null,
1678
- atr: currentAtr,
1679
- keltnerChannels: currentKeltner ? {
1680
- upper: currentKeltner.upper,
1681
- middle: currentKeltner.middle,
1682
- lower: currentKeltner.lower
1683
- } : null,
1684
- donchianChannels: currentDonchian ? {
1685
- upper: currentDonchian.upper,
1686
- middle: currentDonchian.middle,
1687
- lower: currentDonchian.lower
1688
- } : null,
1689
- chaikinVolatility: currentChaikinVolatility,
1690
- obv: currentObv,
1691
- cmf: currentCmf,
1692
- adl: currentAdl,
1693
- volumeROC: currentVolumeROC,
1694
- mfi: currentMfi,
1695
- vwap: currentVwap
1696
- },
1697
- volumeAnalysis: {
1698
- currentVolume,
1699
- averageVolume: Math.round(analysis.avgVolume),
1700
- volumeRatio,
1701
- trueVWAP: analysis.trueVWAP,
1702
- priceVsVWAP,
1703
- obv: currentObv,
1704
- cmf: currentCmf,
1705
- mfi: currentMfi
1706
- },
1707
- momentum: {
1708
- momentum5: analysis.momentum5,
1709
- momentum10: analysis.momentum10,
1710
- sessionROC: analysis.sessionReturn,
1711
- rsi: currentRSI,
1712
- stochastic: currentStochastic,
1713
- cci: currentCCI
1714
- },
1715
- supportResistance: {
1716
- pivotPoints: currentPivotPoints,
1717
- fibonacci: currentFibonacci,
1718
- gannLevels: currentGannLevels,
1719
- elliottWave: currentElliottWave,
1720
- harmonicPatterns: currentHarmonicPatterns
1721
- },
1722
- tradingSignals: {
1723
- ...signals,
1724
- overallSignal,
1725
- signalScore: totalScore,
1726
- confidence: this.calculateConfidence(signals.signals),
1727
- riskLevel: this.calculateRiskLevel(analysis.volatility)
1728
- },
1729
- statisticalModels: {
1730
- zScore: this.calculateZScore(analysis.currentPrice, analysis.startPrice),
1731
- ornsteinUhlenbeck: this.calculateOrnsteinUhlenbeck(
1732
- analysis.currentPrice,
1733
- analysis.startPrice,
1734
- analysis.avgVolume
1735
- ),
1736
- kalmanFilter: this.calculateKalmanFilter(
1737
- analysis.currentPrice,
1738
- analysis.startPrice,
1739
- analysis.avgVolume
1740
- ),
1741
- arima: this.calculateArima(analysis.currentPrice),
1742
- garch: this.calculateGarch(analysis.avgVolume),
1743
- hilbertTransform: this.calculateHilbertTransform(analysis.currentPrice),
1744
- waveletTransform: this.calculateWaveletTransform(analysis.currentPrice)
1745
- },
1746
- optionsAnalysis: (() => {
1747
- const blackScholes = this.calculateBlackScholes(
1748
- analysis.currentPrice,
1749
- analysis.startPrice,
1750
- analysis.avgVolume
1751
- );
1752
- if (!blackScholes) return null;
1753
- return {
1754
- blackScholes,
1755
- impliedVolatility: analysis.impliedVolatility,
1756
- delta: blackScholes.delta,
1757
- gamma: blackScholes.gamma,
1758
- theta: blackScholes.theta,
1759
- vega: blackScholes.vega,
1760
- rho: blackScholes.rho,
1761
- greeks: {
1762
- delta: blackScholes.delta,
1763
- gamma: blackScholes.gamma,
1764
- theta: blackScholes.theta,
1765
- vega: blackScholes.vega,
1766
- rho: blackScholes.rho
1767
- }
1768
- };
1769
- })(),
1770
- riskManagement: {
1771
- targetEntry,
1772
- stopLoss,
1773
- profitTarget,
1774
- riskRewardRatio,
1775
- positionSize,
1776
- maxRisk
1777
- },
1778
- performance: {
1779
- sharpeRatio: analysis.sharpeRatio,
1780
- sortinoRatio: analysis.sortinoRatio,
1781
- calmarRatio: analysis.calmarRatio,
1782
- maxDrawdown: analysis.maxDrawdown * 100,
1783
- winRate: analysis.winRate,
1784
- profitFactor: analysis.profitFactor,
1785
- totalReturn: analysis.sessionReturn,
1786
- volatility: analysis.volatility
1787
- }
1788
- };
1789
- }
1790
- };
1791
- var createTechnicalAnalysisHandler = (marketDataPrices) => {
1792
- return async (args) => {
1793
- try {
1794
- const symbol = args.symbol;
1795
- const priceHistory = marketDataPrices.get(symbol) || [];
1796
- if (priceHistory.length === 0) {
1797
- return {
1798
- content: [
1799
- {
1800
- type: "text",
1801
- text: `No price data available for ${symbol}. Please request market data first.`,
1802
- uri: "technicalAnalysis"
1803
- }
1804
- ]
1805
- };
1806
- }
1807
- const hasValidData = priceHistory.every(
1808
- (entry) => typeof entry.trade === "number" && !Number.isNaN(entry.trade) && typeof entry.midPrice === "number" && !Number.isNaN(entry.midPrice)
1809
- );
1810
- if (!hasValidData) {
1811
- throw new Error("Invalid market data");
1812
- }
1813
- const analyzer = new TechnicalAnalyzer(priceHistory);
1814
- const analysis = analyzer.generateJSONAnalysis(symbol);
1815
- return {
1816
- content: [
1817
- {
1818
- type: "text",
1819
- text: `Technical Analysis for ${symbol}:
1820
-
1821
- ${JSON.stringify(analysis, null, 2)}`,
1822
- uri: "technicalAnalysis"
1823
- }
1824
- ]
1825
- };
1826
- } catch (error) {
1827
- return {
1828
- content: [
1829
- {
1830
- type: "text",
1831
- text: `Error performing technical analysis: ${error instanceof Error ? error.message : "Unknown error"}`,
1832
- uri: "technicalAnalysis"
1833
- }
1834
- ],
1835
- isError: true
1836
- };
1837
- }
1838
- };
1839
- };
1840
-
1841
282
  // src/tools/marketData.ts
1842
283
  import { Field, Fields, MDEntryType, Messages } from "fixparser";
1843
284
  import QuickChart from "quickchart-js";
@@ -1970,72 +411,6 @@ var createMarketDataRequestHandler = (parser, pendingRequests) => {
1970
411
  }
1971
412
  };
1972
413
  };
1973
- var aggregateMarketData = (priceHistory, maxPoints = 490) => {
1974
- if (priceHistory.length <= maxPoints) {
1975
- return priceHistory;
1976
- }
1977
- const result = [];
1978
- const step = priceHistory.length / maxPoints;
1979
- result.push(priceHistory[0]);
1980
- for (let i = 1; i < maxPoints - 1; i++) {
1981
- const startIndex = Math.floor(i * step);
1982
- const endIndex = Math.floor((i + 1) * step);
1983
- const segment = priceHistory.slice(startIndex, endIndex);
1984
- if (segment.length === 0) continue;
1985
- const aggregatedPoint = {
1986
- timestamp: segment[0].timestamp,
1987
- // Use timestamp of first point in segment
1988
- bid: segment.reduce((sum2, p) => sum2 + p.bid, 0) / segment.length,
1989
- offer: segment.reduce((sum2, p) => sum2 + p.offer, 0) / segment.length,
1990
- spread: segment.reduce((sum2, p) => sum2 + p.spread, 0) / segment.length,
1991
- volume: segment.reduce((sum2, p) => sum2 + p.volume, 0) / segment.length,
1992
- trade: segment.reduce((sum2, p) => sum2 + p.trade, 0) / segment.length,
1993
- indexValue: segment.reduce((sum2, p) => sum2 + p.indexValue, 0) / segment.length,
1994
- openingPrice: segment.reduce((sum2, p) => sum2 + p.openingPrice, 0) / segment.length,
1995
- closingPrice: segment.reduce((sum2, p) => sum2 + p.closingPrice, 0) / segment.length,
1996
- settlementPrice: segment.reduce((sum2, p) => sum2 + p.settlementPrice, 0) / segment.length,
1997
- tradingSessionHighPrice: segment.reduce((sum2, p) => sum2 + p.tradingSessionHighPrice, 0) / segment.length,
1998
- tradingSessionLowPrice: segment.reduce((sum2, p) => sum2 + p.tradingSessionLowPrice, 0) / segment.length,
1999
- vwap: segment.reduce((sum2, p) => sum2 + p.vwap, 0) / segment.length,
2000
- imbalance: segment.reduce((sum2, p) => sum2 + p.imbalance, 0) / segment.length,
2001
- openInterest: segment.reduce((sum2, p) => sum2 + p.openInterest, 0) / segment.length,
2002
- compositeUnderlyingPrice: segment.reduce((sum2, p) => sum2 + p.compositeUnderlyingPrice, 0) / segment.length,
2003
- simulatedSellPrice: segment.reduce((sum2, p) => sum2 + p.simulatedSellPrice, 0) / segment.length,
2004
- simulatedBuyPrice: segment.reduce((sum2, p) => sum2 + p.simulatedBuyPrice, 0) / segment.length,
2005
- marginRate: segment.reduce((sum2, p) => sum2 + p.marginRate, 0) / segment.length,
2006
- midPrice: segment.reduce((sum2, p) => sum2 + p.midPrice, 0) / segment.length,
2007
- emptyBook: segment.reduce((sum2, p) => sum2 + p.emptyBook, 0) / segment.length,
2008
- settleHighPrice: segment.reduce((sum2, p) => sum2 + p.settleHighPrice, 0) / segment.length,
2009
- settleLowPrice: segment.reduce((sum2, p) => sum2 + p.settleLowPrice, 0) / segment.length,
2010
- priorSettlePrice: segment.reduce((sum2, p) => sum2 + p.priorSettlePrice, 0) / segment.length,
2011
- sessionHighBid: segment.reduce((sum2, p) => sum2 + p.sessionHighBid, 0) / segment.length,
2012
- sessionLowOffer: segment.reduce((sum2, p) => sum2 + p.sessionLowOffer, 0) / segment.length,
2013
- earlyPrices: segment.reduce((sum2, p) => sum2 + p.earlyPrices, 0) / segment.length,
2014
- auctionClearingPrice: segment.reduce((sum2, p) => sum2 + p.auctionClearingPrice, 0) / segment.length,
2015
- swapValueFactor: segment.reduce((sum2, p) => sum2 + p.swapValueFactor, 0) / segment.length,
2016
- dailyValueAdjustmentForLongPositions: segment.reduce((sum2, p) => sum2 + p.dailyValueAdjustmentForLongPositions, 0) / segment.length,
2017
- cumulativeValueAdjustmentForLongPositions: segment.reduce((sum2, p) => sum2 + p.cumulativeValueAdjustmentForLongPositions, 0) / segment.length,
2018
- dailyValueAdjustmentForShortPositions: segment.reduce((sum2, p) => sum2 + p.dailyValueAdjustmentForShortPositions, 0) / segment.length,
2019
- cumulativeValueAdjustmentForShortPositions: segment.reduce((sum2, p) => sum2 + p.cumulativeValueAdjustmentForShortPositions, 0) / segment.length,
2020
- fixingPrice: segment.reduce((sum2, p) => sum2 + p.fixingPrice, 0) / segment.length,
2021
- cashRate: segment.reduce((sum2, p) => sum2 + p.cashRate, 0) / segment.length,
2022
- recoveryRate: segment.reduce((sum2, p) => sum2 + p.recoveryRate, 0) / segment.length,
2023
- recoveryRateForLong: segment.reduce((sum2, p) => sum2 + p.recoveryRateForLong, 0) / segment.length,
2024
- recoveryRateForShort: segment.reduce((sum2, p) => sum2 + p.recoveryRateForShort, 0) / segment.length,
2025
- marketBid: segment.reduce((sum2, p) => sum2 + p.marketBid, 0) / segment.length,
2026
- marketOffer: segment.reduce((sum2, p) => sum2 + p.marketOffer, 0) / segment.length,
2027
- shortSaleMinPrice: segment.reduce((sum2, p) => sum2 + p.shortSaleMinPrice, 0) / segment.length,
2028
- previousClosingPrice: segment.reduce((sum2, p) => sum2 + p.previousClosingPrice, 0) / segment.length,
2029
- thresholdLimitPriceBanding: segment.reduce((sum2, p) => sum2 + p.thresholdLimitPriceBanding, 0) / segment.length,
2030
- dailyFinancingValue: segment.reduce((sum2, p) => sum2 + p.dailyFinancingValue, 0) / segment.length,
2031
- accruedFinancingValue: segment.reduce((sum2, p) => sum2 + p.accruedFinancingValue, 0) / segment.length,
2032
- twap: segment.reduce((sum2, p) => sum2 + p.twap, 0) / segment.length
2033
- };
2034
- result.push(aggregatedPoint);
2035
- }
2036
- result.push(priceHistory[priceHistory.length - 1]);
2037
- return result;
2038
- };
2039
414
  var createGetStockGraphHandler = (marketDataPrices) => {
2040
415
  return async (args) => {
2041
416
  try {
@@ -2052,22 +427,18 @@ var createGetStockGraphHandler = (marketDataPrices) => {
2052
427
  ]
2053
428
  };
2054
429
  }
2055
- const aggregatedData = aggregateMarketData(priceHistory, 500);
2056
430
  const chart = new QuickChart();
2057
431
  chart.setWidth(1200);
2058
432
  chart.setHeight(600);
2059
433
  chart.setBackgroundColor("transparent");
2060
- const labels = aggregatedData.map((point) => new Date(point.timestamp).toLocaleTimeString());
2061
- const bidData = aggregatedData.map((point) => point.bid);
2062
- const offerData = aggregatedData.map((point) => point.offer);
2063
- const spreadData = aggregatedData.map((point) => point.spread);
2064
- const volumeData = aggregatedData.map((point) => point.volume);
2065
- const tradeData = aggregatedData.map((point) => point.trade);
2066
- const vwapData = aggregatedData.map((point) => point.vwap);
2067
- const twapData = aggregatedData.map((point) => point.twap);
2068
- const maxVolume = Math.max(...volumeData.filter((v) => v > 0));
2069
- const maxPrice = Math.max(...bidData, ...offerData, ...tradeData, ...vwapData, ...twapData);
2070
- const normalizedVolumeData = volumeData.map((v) => v / maxVolume * maxPrice * 0.3);
434
+ const labels = priceHistory.map((point) => new Date(point.timestamp).toLocaleTimeString());
435
+ const bidData = priceHistory.map((point) => point.bid);
436
+ const offerData = priceHistory.map((point) => point.offer);
437
+ const spreadData = priceHistory.map((point) => point.spread);
438
+ const volumeData = priceHistory.map((point) => point.volume);
439
+ const tradeData = priceHistory.map((point) => point.trade);
440
+ const vwapData = priceHistory.map((point) => point.vwap);
441
+ const twapData = priceHistory.map((point) => point.twap);
2071
442
  const config = {
2072
443
  type: "line",
2073
444
  data: {
@@ -2122,8 +493,8 @@ var createGetStockGraphHandler = (marketDataPrices) => {
2122
493
  tension: 0.4
2123
494
  },
2124
495
  {
2125
- label: "Volume (Normalized)",
2126
- data: normalizedVolumeData,
496
+ label: "Volume",
497
+ data: volumeData,
2127
498
  borderColor: "#007bff",
2128
499
  backgroundColor: "rgba(0, 123, 255, 0.1)",
2129
500
  fill: true,
@@ -2136,16 +507,12 @@ var createGetStockGraphHandler = (marketDataPrices) => {
2136
507
  plugins: {
2137
508
  title: {
2138
509
  display: true,
2139
- text: `${symbol} Market Data (Volume normalized to 30% of max price)`
510
+ text: `${symbol} Market Data`
2140
511
  }
2141
512
  },
2142
513
  scales: {
2143
514
  y: {
2144
- beginAtZero: false,
2145
- title: {
2146
- display: true,
2147
- text: "Price / Normalized Volume"
2148
- }
515
+ beginAtZero: false
2149
516
  }
2150
517
  }
2151
518
  }
@@ -2195,7 +562,6 @@ var createGetStockPriceHistoryHandler = (marketDataPrices) => {
2195
562
  ]
2196
563
  };
2197
564
  }
2198
- const aggregatedData = aggregateMarketData(priceHistory, 500);
2199
565
  return {
2200
566
  content: [
2201
567
  {
@@ -2203,9 +569,8 @@ var createGetStockPriceHistoryHandler = (marketDataPrices) => {
2203
569
  text: JSON.stringify(
2204
570
  {
2205
571
  symbol,
2206
- count: aggregatedData.length,
2207
- originalCount: priceHistory.length,
2208
- data: aggregatedData.map((point) => ({
572
+ count: priceHistory.length,
573
+ data: priceHistory.map((point) => ({
2209
574
  timestamp: new Date(point.timestamp).toISOString(),
2210
575
  bid: point.bid,
2211
576
  offer: point.offer,
@@ -2347,7 +712,6 @@ var handlInstNames = {
2347
712
  };
2348
713
  var createVerifyOrderHandler = (parser, verifiedOrders) => {
2349
714
  return async (args) => {
2350
- void parser;
2351
715
  try {
2352
716
  verifiedOrders.set(args.clOrdID, {
2353
717
  clOrdID: args.clOrdID,
@@ -2571,22 +935,29 @@ var createToolHandlers = (parser, verifiedOrders, pendingRequests, marketDataPri
2571
935
  executeOrder: createExecuteOrderHandler(parser, verifiedOrders, pendingRequests),
2572
936
  marketDataRequest: createMarketDataRequestHandler(parser, pendingRequests),
2573
937
  getStockGraph: createGetStockGraphHandler(marketDataPrices),
2574
- getStockPriceHistory: createGetStockPriceHistoryHandler(marketDataPrices),
2575
- technicalAnalysis: createTechnicalAnalysisHandler(marketDataPrices)
938
+ getStockPriceHistory: createGetStockPriceHistoryHandler(marketDataPrices)
2576
939
  });
2577
940
 
2578
941
  // src/utils/messageHandler.ts
2579
942
  import { Fields as Fields3, MDEntryType as MDEntryType2, Messages as Messages3 } from "fixparser";
2580
- function getEnumValue(enumObj, name) {
2581
- return enumObj[name] || name;
2582
- }
2583
943
  function handleMessage(message, parser, pendingRequests, marketDataPrices, maxPriceHistory, onPriceUpdate) {
2584
- void parser;
944
+ parser.logger.log({
945
+ level: "info",
946
+ message: `MCP Server received message: ${message.messageType}: ${message.description}`
947
+ });
2585
948
  const msgType = message.messageType;
2586
949
  if (msgType === Messages3.MarketDataSnapshotFullRefresh || msgType === Messages3.MarketDataIncrementalRefresh) {
2587
950
  const symbol = message.getField(Fields3.Symbol)?.value;
951
+ parser.logger.log({
952
+ level: "info",
953
+ message: `Processing market data for symbol: ${symbol}`
954
+ });
2588
955
  const fixJson = message.toFIXJSON();
2589
956
  const entries = fixJson.Body?.NoMDEntries || [];
957
+ parser.logger.log({
958
+ level: "info",
959
+ message: `Found ${entries.length} market data entries`
960
+ });
2590
961
  const data = {
2591
962
  timestamp: Date.now(),
2592
963
  bid: 0,
@@ -2639,8 +1010,13 @@ function handleMessage(message, parser, pendingRequests, marketDataPrices, maxPr
2639
1010
  const entryType = entry.MDEntryType;
2640
1011
  const price = entry.MDEntryPx ? Number.parseFloat(entry.MDEntryPx) : 0;
2641
1012
  const size = entry.MDEntrySize ? Number.parseFloat(entry.MDEntrySize) : 0;
2642
- const enumValue = getEnumValue(MDEntryType2, entryType);
2643
- switch (enumValue) {
1013
+ if (entryType === MDEntryType2.Bid || entryType === MDEntryType2.Offer || entryType === MDEntryType2.TradeVolume) {
1014
+ parser.logger.log({
1015
+ level: "info",
1016
+ message: `Market Data Entry - Type: ${entryType}, Price: ${price}, Size: ${size}`
1017
+ });
1018
+ }
1019
+ switch (entryType) {
2644
1020
  case MDEntryType2.Bid:
2645
1021
  data.bid = price;
2646
1022
  break;
@@ -2777,12 +1153,24 @@ function handleMessage(message, parser, pendingRequests, marketDataPrices, maxPr
2777
1153
  }
2778
1154
  data.spread = data.offer - data.bid;
2779
1155
  if (!marketDataPrices.has(symbol)) {
1156
+ parser.logger.log({
1157
+ level: "info",
1158
+ message: `Creating new price history array for symbol: ${symbol}`
1159
+ });
2780
1160
  marketDataPrices.set(symbol, []);
2781
1161
  }
2782
1162
  const prices = marketDataPrices.get(symbol);
2783
1163
  prices.push(data);
1164
+ parser.logger.log({
1165
+ level: "info",
1166
+ message: `Updated price history for ${symbol}. Current size: ${prices.length}`
1167
+ });
2784
1168
  if (prices.length > maxPriceHistory) {
2785
1169
  prices.splice(0, prices.length - maxPriceHistory);
1170
+ parser.logger.log({
1171
+ level: "info",
1172
+ message: `Trimmed price history for ${symbol} to ${maxPriceHistory} entries`
1173
+ });
2786
1174
  }
2787
1175
  onPriceUpdate?.(symbol, data);
2788
1176
  const mdReqID = message.getField(Fields3.MDReqID)?.value;
@@ -2791,6 +1179,10 @@ function handleMessage(message, parser, pendingRequests, marketDataPrices, maxPr
2791
1179
  if (callback) {
2792
1180
  callback(message);
2793
1181
  pendingRequests.delete(mdReqID);
1182
+ parser.logger.log({
1183
+ level: "info",
1184
+ message: `Resolved market data request for ID: ${mdReqID}`
1185
+ });
2794
1186
  }
2795
1187
  }
2796
1188
  } else if (msgType === Messages3.ExecutionReport) {
@@ -2904,6 +1296,10 @@ var MCPRemote = class extends MCPBase {
2904
1296
  this.marketDataPrices,
2905
1297
  this.MAX_PRICE_HISTORY
2906
1298
  );
1299
+ this.logger?.log({
1300
+ level: "info",
1301
+ message: `Market Data Prices TEST: ${JSON.stringify(this.marketDataPrices)}`
1302
+ });
2907
1303
  }
2908
1304
  });
2909
1305
  this.httpServer = createServer(async (req, res) => {
@@ -2924,8 +1320,7 @@ var MCPRemote = class extends MCPBase {
2924
1320
  const body = Buffer.concat(bodyChunks).toString();
2925
1321
  try {
2926
1322
  parsed = JSON.parse(body);
2927
- } catch (error) {
2928
- void error;
1323
+ } catch (err) {
2929
1324
  res.writeHead(400);
2930
1325
  res.end(JSON.stringify({ error: "Invalid JSON" }));
2931
1326
  return;