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