fixparser-plugin-mcp 9.1.7-1736d80f → 9.1.7-1818bee7
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 +2319 -129
- package/build/cjs/MCPLocal.js.map +4 -4
- package/build/cjs/MCPRemote.js +3152 -437
- package/build/cjs/MCPRemote.js.map +4 -4
- package/build/cjs/index.js +3449 -0
- package/build/cjs/index.js.map +7 -0
- package/build/esm/MCPLocal.mjs +2319 -129
- package/build/esm/MCPLocal.mjs.map +4 -4
- package/build/esm/MCPRemote.mjs +3143 -447
- package/build/esm/MCPRemote.mjs.map +4 -4
- package/build/esm/index.mjs +3411 -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 +9 -9
- package/types/MCPLocal.d.ts +0 -16
- package/types/MCPRemote.d.ts +0 -60
- 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/build/cjs/MCPLocal.js
CHANGED
|
@@ -35,9 +35,51 @@ __export(MCPLocal_exports, {
|
|
|
35
35
|
module.exports = __toCommonJS(MCPLocal_exports);
|
|
36
36
|
var import_server = require("@modelcontextprotocol/sdk/server/index.js");
|
|
37
37
|
var import_stdio = require("@modelcontextprotocol/sdk/server/stdio.js");
|
|
38
|
-
var import_fixparser3 = require("fixparser");
|
|
39
38
|
var import_zod = require("zod");
|
|
40
39
|
|
|
40
|
+
// src/MCPBase.ts
|
|
41
|
+
var MCPBase = class {
|
|
42
|
+
/**
|
|
43
|
+
* Optional logger instance for diagnostics and output.
|
|
44
|
+
* @protected
|
|
45
|
+
*/
|
|
46
|
+
logger;
|
|
47
|
+
/**
|
|
48
|
+
* FIXParser instance, set during plugin register().
|
|
49
|
+
* @protected
|
|
50
|
+
*/
|
|
51
|
+
parser;
|
|
52
|
+
/**
|
|
53
|
+
* Called when server is setup and listening.
|
|
54
|
+
* @protected
|
|
55
|
+
*/
|
|
56
|
+
onReady = void 0;
|
|
57
|
+
/**
|
|
58
|
+
* Map to store verified orders before execution
|
|
59
|
+
* @protected
|
|
60
|
+
*/
|
|
61
|
+
verifiedOrders = /* @__PURE__ */ new Map();
|
|
62
|
+
/**
|
|
63
|
+
* Map to store pending market data requests
|
|
64
|
+
* @protected
|
|
65
|
+
*/
|
|
66
|
+
pendingRequests = /* @__PURE__ */ new Map();
|
|
67
|
+
/**
|
|
68
|
+
* Map to store market data prices
|
|
69
|
+
* @protected
|
|
70
|
+
*/
|
|
71
|
+
marketDataPrices = /* @__PURE__ */ new Map();
|
|
72
|
+
/**
|
|
73
|
+
* Maximum number of price history entries to keep per symbol
|
|
74
|
+
* @protected
|
|
75
|
+
*/
|
|
76
|
+
MAX_PRICE_HISTORY = 1e5;
|
|
77
|
+
constructor({ logger, onReady }) {
|
|
78
|
+
this.logger = logger;
|
|
79
|
+
this.onReady = onReady;
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
|
|
41
83
|
// src/schemas/schemas.ts
|
|
42
84
|
var toolSchemas = {
|
|
43
85
|
parse: {
|
|
@@ -121,7 +163,7 @@ var toolSchemas = {
|
|
|
121
163
|
}
|
|
122
164
|
},
|
|
123
165
|
executeOrder: {
|
|
124
|
-
description: "Executes a verified order. verifyOrder must be called before executeOrder.
|
|
166
|
+
description: "Executes a verified order. verifyOrder must be called before executeOrder.",
|
|
125
167
|
schema: {
|
|
126
168
|
type: "object",
|
|
127
169
|
properties: {
|
|
@@ -265,19 +307,1848 @@ var toolSchemas = {
|
|
|
265
307
|
},
|
|
266
308
|
required: ["symbol"]
|
|
267
309
|
}
|
|
310
|
+
},
|
|
311
|
+
technicalAnalysis: {
|
|
312
|
+
description: "Performs comprehensive technical analysis on market data for a given symbol, including indicators like SMA, EMA, RSI, Bollinger Bands, and trading signals",
|
|
313
|
+
schema: {
|
|
314
|
+
type: "object",
|
|
315
|
+
properties: {
|
|
316
|
+
symbol: {
|
|
317
|
+
type: "string",
|
|
318
|
+
description: "The trading symbol to analyze (e.g., AAPL, MSFT, EURUSD)"
|
|
319
|
+
}
|
|
320
|
+
},
|
|
321
|
+
required: ["symbol"]
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
};
|
|
325
|
+
|
|
326
|
+
// src/tools/indicators/momentum.ts
|
|
327
|
+
var MomentumIndicators = class {
|
|
328
|
+
/**
|
|
329
|
+
* Calculate RSI (Relative Strength Index)
|
|
330
|
+
*/
|
|
331
|
+
static calculateRSI(data, period = 14) {
|
|
332
|
+
if (data.length < period + 1) return [];
|
|
333
|
+
const changes = [];
|
|
334
|
+
for (let i = 1; i < data.length; i++) {
|
|
335
|
+
changes.push(data[i] - data[i - 1]);
|
|
336
|
+
}
|
|
337
|
+
const gains = changes.map((change) => change > 0 ? change : 0);
|
|
338
|
+
const losses = changes.map((change) => change < 0 ? Math.abs(change) : 0);
|
|
339
|
+
let avgGain = gains.slice(0, period).reduce((a, b) => a + b, 0) / period;
|
|
340
|
+
let avgLoss = losses.slice(0, period).reduce((a, b) => a + b, 0) / period;
|
|
341
|
+
const rsi = [];
|
|
342
|
+
for (let i = period; i < changes.length; i++) {
|
|
343
|
+
const rs = avgGain / avgLoss;
|
|
344
|
+
rsi.push(100 - 100 / (1 + rs));
|
|
345
|
+
avgGain = (avgGain * (period - 1) + gains[i]) / period;
|
|
346
|
+
avgLoss = (avgLoss * (period - 1) + losses[i]) / period;
|
|
347
|
+
}
|
|
348
|
+
return rsi;
|
|
349
|
+
}
|
|
350
|
+
/**
|
|
351
|
+
* Calculate Stochastic Oscillator
|
|
352
|
+
*/
|
|
353
|
+
static calculateStochastic(prices, highs, lows) {
|
|
354
|
+
const stochastic = [];
|
|
355
|
+
const period = 14;
|
|
356
|
+
const smoothK = 3;
|
|
357
|
+
const smoothD = 3;
|
|
358
|
+
if (prices.length < period) return [];
|
|
359
|
+
const percentK = [];
|
|
360
|
+
for (let i = period - 1; i < prices.length; i++) {
|
|
361
|
+
const high = Math.max(...highs.slice(i - period + 1, i + 1));
|
|
362
|
+
const low = Math.min(...lows.slice(i - period + 1, i + 1));
|
|
363
|
+
const close = prices[i];
|
|
364
|
+
const k = (close - low) / (high - low) * 100;
|
|
365
|
+
percentK.push(k);
|
|
366
|
+
}
|
|
367
|
+
const smoothedK = [];
|
|
368
|
+
for (let i = smoothK - 1; i < percentK.length; i++) {
|
|
369
|
+
const sum2 = percentK.slice(i - smoothK + 1, i + 1).reduce((a, b) => a + b, 0);
|
|
370
|
+
smoothedK.push(sum2 / smoothK);
|
|
371
|
+
}
|
|
372
|
+
for (let i = smoothD - 1; i < smoothedK.length; i++) {
|
|
373
|
+
const sum2 = smoothedK.slice(i - smoothD + 1, i + 1).reduce((a, b) => a + b, 0);
|
|
374
|
+
const d = sum2 / smoothD;
|
|
375
|
+
stochastic.push({
|
|
376
|
+
k: smoothedK[i],
|
|
377
|
+
d
|
|
378
|
+
});
|
|
379
|
+
}
|
|
380
|
+
return stochastic;
|
|
381
|
+
}
|
|
382
|
+
/**
|
|
383
|
+
* Calculate CCI (Commodity Channel Index)
|
|
384
|
+
*/
|
|
385
|
+
static calculateCCI(prices, highs, lows) {
|
|
386
|
+
const cci = [];
|
|
387
|
+
const period = 20;
|
|
388
|
+
if (prices.length < period) return [];
|
|
389
|
+
for (let i = period - 1; i < prices.length; i++) {
|
|
390
|
+
const slice = prices.slice(i - period + 1, i + 1);
|
|
391
|
+
const typicalPrices = slice.map((price, idx) => {
|
|
392
|
+
const high = highs[i - period + 1 + idx] || price;
|
|
393
|
+
const low = lows[i - period + 1 + idx] || price;
|
|
394
|
+
return (high + low + price) / 3;
|
|
395
|
+
});
|
|
396
|
+
const sma = typicalPrices.reduce((a, b) => a + b, 0) / period;
|
|
397
|
+
const meanDeviation = typicalPrices.reduce((sum2, tp) => sum2 + Math.abs(tp - sma), 0) / period;
|
|
398
|
+
const currentTP = (highs[i] + lows[i] + prices[i]) / 3;
|
|
399
|
+
const cciValue = meanDeviation !== 0 ? (currentTP - sma) / (0.015 * meanDeviation) : 0;
|
|
400
|
+
cci.push(cciValue);
|
|
401
|
+
}
|
|
402
|
+
return cci;
|
|
403
|
+
}
|
|
404
|
+
/**
|
|
405
|
+
* Calculate Rate of Change
|
|
406
|
+
*/
|
|
407
|
+
static calculateROC(prices) {
|
|
408
|
+
const roc = [];
|
|
409
|
+
for (let i = 10; i < prices.length; i++) {
|
|
410
|
+
roc.push((prices[i] - prices[i - 10]) / prices[i - 10] * 100);
|
|
411
|
+
}
|
|
412
|
+
return roc;
|
|
413
|
+
}
|
|
414
|
+
/**
|
|
415
|
+
* Calculate Williams %R
|
|
416
|
+
*/
|
|
417
|
+
static calculateWilliamsR(prices) {
|
|
418
|
+
const williamsR = [];
|
|
419
|
+
const period = 14;
|
|
420
|
+
if (prices.length < period) return [];
|
|
421
|
+
for (let i = period - 1; i < prices.length; i++) {
|
|
422
|
+
const slice = prices.slice(i - period + 1, i + 1);
|
|
423
|
+
const high = Math.max(...slice);
|
|
424
|
+
const low = Math.min(...slice);
|
|
425
|
+
const close = prices[i];
|
|
426
|
+
const wr = (high - close) / (high - low) * -100;
|
|
427
|
+
williamsR.push(wr);
|
|
428
|
+
}
|
|
429
|
+
return williamsR;
|
|
430
|
+
}
|
|
431
|
+
/**
|
|
432
|
+
* Calculate Momentum
|
|
433
|
+
*/
|
|
434
|
+
static calculateMomentum(prices) {
|
|
435
|
+
const momentum = [];
|
|
436
|
+
for (let i = 10; i < prices.length; i++) {
|
|
437
|
+
momentum.push(prices[i] - prices[i - 10]);
|
|
438
|
+
}
|
|
439
|
+
return momentum;
|
|
440
|
+
}
|
|
441
|
+
};
|
|
442
|
+
|
|
443
|
+
// src/tools/indicators/movingAverages.ts
|
|
444
|
+
var MovingAverages = class {
|
|
445
|
+
/**
|
|
446
|
+
* Calculate Simple Moving Average
|
|
447
|
+
*/
|
|
448
|
+
static calculateSMA(data, period) {
|
|
449
|
+
const sma = [];
|
|
450
|
+
for (let i = period - 1; i < data.length; i++) {
|
|
451
|
+
const sum2 = data.slice(i - period + 1, i + 1).reduce((a, b) => a + b, 0);
|
|
452
|
+
sma.push(sum2 / period);
|
|
453
|
+
}
|
|
454
|
+
return sma;
|
|
455
|
+
}
|
|
456
|
+
/**
|
|
457
|
+
* Calculate Exponential Moving Average
|
|
458
|
+
*/
|
|
459
|
+
static calculateEMA(data, period) {
|
|
460
|
+
const multiplier = 2 / (period + 1);
|
|
461
|
+
const ema = [data[0]];
|
|
462
|
+
for (let i = 1; i < data.length; i++) {
|
|
463
|
+
ema.push(data[i] * multiplier + ema[i - 1] * (1 - multiplier));
|
|
464
|
+
}
|
|
465
|
+
return ema;
|
|
466
|
+
}
|
|
467
|
+
/**
|
|
468
|
+
* Calculate Weighted Moving Average
|
|
469
|
+
*/
|
|
470
|
+
static calculateWMA(data, period) {
|
|
471
|
+
const wma = [];
|
|
472
|
+
const weights = Array.from({ length: period }, (_, i) => i + 1);
|
|
473
|
+
const weightSum = weights.reduce((a, b) => a + b, 0);
|
|
474
|
+
for (let i = period - 1; i < data.length; i++) {
|
|
475
|
+
let weightedSum = 0;
|
|
476
|
+
for (let j = 0; j < period; j++) {
|
|
477
|
+
weightedSum += data[i - j] * weights[j];
|
|
478
|
+
}
|
|
479
|
+
wma.push(weightedSum / weightSum);
|
|
480
|
+
}
|
|
481
|
+
return wma;
|
|
482
|
+
}
|
|
483
|
+
/**
|
|
484
|
+
* Calculate Volume Weighted Moving Average
|
|
485
|
+
*/
|
|
486
|
+
static calculateVWMA(prices, volumes, period) {
|
|
487
|
+
const vwma = [];
|
|
488
|
+
for (let i = period - 1; i < prices.length; i++) {
|
|
489
|
+
let volumeSum = 0;
|
|
490
|
+
let priceVolumeSum = 0;
|
|
491
|
+
for (let j = 0; j < period; j++) {
|
|
492
|
+
const volume = volumes[i - j] || 1;
|
|
493
|
+
volumeSum += volume;
|
|
494
|
+
priceVolumeSum += prices[i - j] * volume;
|
|
495
|
+
}
|
|
496
|
+
vwma.push(priceVolumeSum / volumeSum);
|
|
497
|
+
}
|
|
498
|
+
return vwma;
|
|
499
|
+
}
|
|
500
|
+
};
|
|
501
|
+
|
|
502
|
+
// src/tools/indicators/options.ts
|
|
503
|
+
var OptionsAnalysis = class _OptionsAnalysis {
|
|
504
|
+
/**
|
|
505
|
+
* Calculate Black-Scholes Option Pricing
|
|
506
|
+
*/
|
|
507
|
+
static calculateBlackScholes(currentPrice, startPrice, avgVolume) {
|
|
508
|
+
const S = currentPrice;
|
|
509
|
+
const K = startPrice;
|
|
510
|
+
const T = 1;
|
|
511
|
+
const r = 0.05;
|
|
512
|
+
const sigma = avgVolume * 0.01;
|
|
513
|
+
const d1 = (Math.log(S / K) + (r + sigma * sigma / 2) * T) / (sigma * Math.sqrt(T));
|
|
514
|
+
const d2 = d1 - sigma * Math.sqrt(T);
|
|
515
|
+
const callPrice = S * _OptionsAnalysis.normalCDF(d1) - K * Math.exp(-r * T) * _OptionsAnalysis.normalCDF(d2);
|
|
516
|
+
const putPrice = K * Math.exp(-r * T) * _OptionsAnalysis.normalCDF(-d2) - S * _OptionsAnalysis.normalCDF(-d1);
|
|
517
|
+
return {
|
|
518
|
+
callPrice,
|
|
519
|
+
putPrice,
|
|
520
|
+
delta: _OptionsAnalysis.normalCDF(d1),
|
|
521
|
+
gamma: _OptionsAnalysis.normalPDF(d1) / (S * sigma * Math.sqrt(T)),
|
|
522
|
+
theta: -S * _OptionsAnalysis.normalPDF(d1) * sigma / (2 * Math.sqrt(T)) - r * K * Math.exp(-r * T) * _OptionsAnalysis.normalCDF(d2),
|
|
523
|
+
vega: S * Math.sqrt(T) * _OptionsAnalysis.normalPDF(d1),
|
|
524
|
+
rho: K * T * Math.exp(-r * T) * _OptionsAnalysis.normalCDF(d2)
|
|
525
|
+
};
|
|
526
|
+
}
|
|
527
|
+
/**
|
|
528
|
+
* Normal CDF approximation
|
|
529
|
+
*/
|
|
530
|
+
static normalCDF(x) {
|
|
531
|
+
return 0.5 * (1 + _OptionsAnalysis.erf(x / Math.sqrt(2)));
|
|
532
|
+
}
|
|
533
|
+
/**
|
|
534
|
+
* Normal PDF
|
|
535
|
+
*/
|
|
536
|
+
static normalPDF(x) {
|
|
537
|
+
return Math.exp(-x * x / 2) / Math.sqrt(2 * Math.PI);
|
|
538
|
+
}
|
|
539
|
+
/**
|
|
540
|
+
* Error function approximation
|
|
541
|
+
*/
|
|
542
|
+
static erf(x) {
|
|
543
|
+
const a1 = 0.254829592;
|
|
544
|
+
const a2 = -0.284496736;
|
|
545
|
+
const a3 = 1.421413741;
|
|
546
|
+
const a4 = -1.453152027;
|
|
547
|
+
const a5 = 1.061405429;
|
|
548
|
+
const p = 0.3275911;
|
|
549
|
+
const sign = x >= 0 ? 1 : -1;
|
|
550
|
+
const absX = Math.abs(x);
|
|
551
|
+
const t = 1 / (1 + p * absX);
|
|
552
|
+
const y = 1 - ((((a5 * t + a4) * t + a3) * t + a2) * t + a1) * t * Math.exp(-absX * absX);
|
|
553
|
+
return sign * y;
|
|
554
|
+
}
|
|
555
|
+
};
|
|
556
|
+
|
|
557
|
+
// src/tools/indicators/performance.ts
|
|
558
|
+
var PerformanceAnalysis = class {
|
|
559
|
+
/**
|
|
560
|
+
* Calculate maximum drawdown
|
|
561
|
+
*/
|
|
562
|
+
static calculateMaxDrawdown(prices) {
|
|
563
|
+
let maxPrice = prices[0];
|
|
564
|
+
let maxDrawdown = 0;
|
|
565
|
+
for (let i = 1; i < prices.length; i++) {
|
|
566
|
+
if (prices[i] > maxPrice) {
|
|
567
|
+
maxPrice = prices[i];
|
|
568
|
+
}
|
|
569
|
+
const drawdown = (maxPrice - prices[i]) / maxPrice;
|
|
570
|
+
if (drawdown > maxDrawdown) {
|
|
571
|
+
maxDrawdown = drawdown;
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
return maxDrawdown;
|
|
575
|
+
}
|
|
576
|
+
/**
|
|
577
|
+
* Calculate maximum consecutive losses
|
|
578
|
+
*/
|
|
579
|
+
static calculateMaxConsecutiveLosses(prices) {
|
|
580
|
+
let maxConsecutive = 0;
|
|
581
|
+
let currentConsecutive = 0;
|
|
582
|
+
for (let i = 1; i < prices.length; i++) {
|
|
583
|
+
if (prices[i] < prices[i - 1]) {
|
|
584
|
+
currentConsecutive++;
|
|
585
|
+
maxConsecutive = Math.max(maxConsecutive, currentConsecutive);
|
|
586
|
+
} else {
|
|
587
|
+
currentConsecutive = 0;
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
return maxConsecutive;
|
|
591
|
+
}
|
|
592
|
+
/**
|
|
593
|
+
* Calculate win rate
|
|
594
|
+
*/
|
|
595
|
+
static calculateWinRate(prices) {
|
|
596
|
+
let wins = 0;
|
|
597
|
+
let total = 0;
|
|
598
|
+
for (let i = 1; i < prices.length; i++) {
|
|
599
|
+
if (prices[i] !== prices[i - 1]) {
|
|
600
|
+
total++;
|
|
601
|
+
if (prices[i] > prices[i - 1]) {
|
|
602
|
+
wins++;
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
return total > 0 ? wins / total : 0;
|
|
607
|
+
}
|
|
608
|
+
/**
|
|
609
|
+
* Calculate profit factor
|
|
610
|
+
*/
|
|
611
|
+
static calculateProfitFactor(prices) {
|
|
612
|
+
let grossProfit = 0;
|
|
613
|
+
let grossLoss = 0;
|
|
614
|
+
for (let i = 1; i < prices.length; i++) {
|
|
615
|
+
const change = prices[i] - prices[i - 1];
|
|
616
|
+
if (change > 0) {
|
|
617
|
+
grossProfit += change;
|
|
618
|
+
} else {
|
|
619
|
+
grossLoss += Math.abs(change);
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
return grossLoss > 0 ? grossProfit / grossLoss : 0;
|
|
623
|
+
}
|
|
624
|
+
/**
|
|
625
|
+
* Calculate Sharpe Ratio
|
|
626
|
+
*/
|
|
627
|
+
static calculateSharpeRatio(returns, riskFreeRate = 0.02) {
|
|
628
|
+
if (returns.length === 0) return 0;
|
|
629
|
+
const meanReturn = returns.reduce((sum2, ret) => sum2 + ret, 0) / returns.length;
|
|
630
|
+
const excessReturn = meanReturn - riskFreeRate;
|
|
631
|
+
const variance = returns.reduce((sum2, ret) => sum2 + (ret - meanReturn) ** 2, 0) / returns.length;
|
|
632
|
+
const volatility = Math.sqrt(variance);
|
|
633
|
+
return volatility > 0 ? excessReturn / volatility : 0;
|
|
634
|
+
}
|
|
635
|
+
/**
|
|
636
|
+
* Calculate Sortino Ratio
|
|
637
|
+
*/
|
|
638
|
+
static calculateSortinoRatio(returns, riskFreeRate = 0.02) {
|
|
639
|
+
if (returns.length === 0) return 0;
|
|
640
|
+
const meanReturn = returns.reduce((sum2, ret) => sum2 + ret, 0) / returns.length;
|
|
641
|
+
const excessReturn = meanReturn - riskFreeRate;
|
|
642
|
+
const negativeReturns = returns.filter((ret) => ret < meanReturn);
|
|
643
|
+
const downsideVariance = negativeReturns.reduce((sum2, ret) => sum2 + (ret - meanReturn) ** 2, 0) / returns.length;
|
|
644
|
+
const downsideDeviation = Math.sqrt(downsideVariance);
|
|
645
|
+
return downsideDeviation > 0 ? excessReturn / downsideDeviation : 0;
|
|
646
|
+
}
|
|
647
|
+
/**
|
|
648
|
+
* Calculate Calmar Ratio
|
|
649
|
+
*/
|
|
650
|
+
static calculateCalmarRatio(returns, maxDrawdown) {
|
|
651
|
+
if (maxDrawdown === 0) return 0;
|
|
652
|
+
const meanReturn = returns.reduce((sum2, ret) => sum2 + ret, 0) / returns.length;
|
|
653
|
+
return meanReturn / maxDrawdown;
|
|
654
|
+
}
|
|
655
|
+
/**
|
|
656
|
+
* Calculate Position Size
|
|
657
|
+
*/
|
|
658
|
+
static calculatePositionSize(targetEntry, stopLoss) {
|
|
659
|
+
const riskPerShare = Math.abs(targetEntry - stopLoss);
|
|
660
|
+
return riskPerShare > 0 ? 100 / riskPerShare : 1;
|
|
661
|
+
}
|
|
662
|
+
/**
|
|
663
|
+
* Calculate Confidence
|
|
664
|
+
*/
|
|
665
|
+
static calculateConfidence(signals) {
|
|
666
|
+
return Math.min(signals.length * 10, 100);
|
|
667
|
+
}
|
|
668
|
+
/**
|
|
669
|
+
* Calculate Risk Level
|
|
670
|
+
*/
|
|
671
|
+
static calculateRiskLevel(volatility) {
|
|
672
|
+
if (volatility < 20) return "LOW";
|
|
673
|
+
if (volatility < 40) return "MEDIUM";
|
|
674
|
+
return "HIGH";
|
|
675
|
+
}
|
|
676
|
+
};
|
|
677
|
+
|
|
678
|
+
// src/tools/indicators/signals.ts
|
|
679
|
+
var TradingSignalsGenerator = class _TradingSignalsGenerator {
|
|
680
|
+
/**
|
|
681
|
+
* Generate trading signals based on market analysis
|
|
682
|
+
*/
|
|
683
|
+
static generateSignals(currentPrice, trueVWAP, momentum5, momentum10, sessionReturn, currentVolume, avgVolume, pricePosition, volatility) {
|
|
684
|
+
let bullishSignals = 0;
|
|
685
|
+
let bearishSignals = 0;
|
|
686
|
+
const signals = [];
|
|
687
|
+
if (currentPrice > trueVWAP) {
|
|
688
|
+
signals.push(
|
|
689
|
+
`\u2713 BULLISH: Price above VWAP (+${((currentPrice - trueVWAP) / trueVWAP * 100).toFixed(2)}%)`
|
|
690
|
+
);
|
|
691
|
+
bullishSignals++;
|
|
692
|
+
} else {
|
|
693
|
+
signals.push(`\u2717 BEARISH: Price below VWAP (${((currentPrice - trueVWAP) / trueVWAP * 100).toFixed(2)}%)`);
|
|
694
|
+
bearishSignals++;
|
|
695
|
+
}
|
|
696
|
+
if (momentum5 > 0 && momentum10 > 0) {
|
|
697
|
+
signals.push("\u2713 BULLISH: Positive momentum on both timeframes");
|
|
698
|
+
bullishSignals++;
|
|
699
|
+
} else if (momentum5 < 0 && momentum10 < 0) {
|
|
700
|
+
signals.push("\u2717 BEARISH: Negative momentum on both timeframes");
|
|
701
|
+
bearishSignals++;
|
|
702
|
+
} else {
|
|
703
|
+
signals.push("\u25D0 MIXED: Conflicting momentum signals");
|
|
704
|
+
}
|
|
705
|
+
const volumeRatio = currentVolume / avgVolume;
|
|
706
|
+
if (volumeRatio > 1.2 && sessionReturn > 0) {
|
|
707
|
+
signals.push("\u2713 BULLISH: Above-average volume supporting upward move");
|
|
708
|
+
bullishSignals++;
|
|
709
|
+
} else if (volumeRatio > 1.2 && sessionReturn < 0) {
|
|
710
|
+
signals.push("\u2717 BEARISH: Above-average volume supporting downward move");
|
|
711
|
+
bearishSignals++;
|
|
712
|
+
} else {
|
|
713
|
+
signals.push("\u25D0 NEUTRAL: Volume not providing clear direction");
|
|
714
|
+
}
|
|
715
|
+
if (pricePosition > 65 && volatility > 30) {
|
|
716
|
+
signals.push("\u2717 BEARISH: High in range with elevated volatility - reversal risk");
|
|
717
|
+
bearishSignals++;
|
|
718
|
+
} else if (pricePosition < 35 && volatility > 30) {
|
|
719
|
+
signals.push("\u2713 BULLISH: Low in range with volatility - potential bounce");
|
|
720
|
+
bullishSignals++;
|
|
721
|
+
} else {
|
|
722
|
+
signals.push("\u25D0 NEUTRAL: Price position and volatility not extreme");
|
|
723
|
+
}
|
|
724
|
+
return { bullishSignals, bearishSignals, signals };
|
|
725
|
+
}
|
|
726
|
+
/**
|
|
727
|
+
* Calculate overall signal and confidence
|
|
728
|
+
*/
|
|
729
|
+
static calculateOverallSignal(bullishSignals, bearishSignals, signals, volatility) {
|
|
730
|
+
const totalScore = bullishSignals - bearishSignals;
|
|
731
|
+
const overallSignal = totalScore > 0 ? "BULLISH_BIAS" : totalScore < 0 ? "BEARISH_BIAS" : "NEUTRAL";
|
|
732
|
+
const confidence = _TradingSignalsGenerator.calculateConfidence(signals);
|
|
733
|
+
const riskLevel = _TradingSignalsGenerator.calculateRiskLevel(volatility);
|
|
734
|
+
return {
|
|
735
|
+
bullishSignals,
|
|
736
|
+
bearishSignals,
|
|
737
|
+
signals,
|
|
738
|
+
overallSignal,
|
|
739
|
+
signalScore: totalScore,
|
|
740
|
+
confidence,
|
|
741
|
+
riskLevel
|
|
742
|
+
};
|
|
743
|
+
}
|
|
744
|
+
/**
|
|
745
|
+
* Calculate confidence based on number of signals
|
|
746
|
+
*/
|
|
747
|
+
static calculateConfidence(signals) {
|
|
748
|
+
return Math.min(signals.length * 10, 100);
|
|
749
|
+
}
|
|
750
|
+
/**
|
|
751
|
+
* Calculate risk level based on volatility
|
|
752
|
+
*/
|
|
753
|
+
static calculateRiskLevel(volatility) {
|
|
754
|
+
if (volatility < 20) return "LOW";
|
|
755
|
+
if (volatility < 40) return "MEDIUM";
|
|
756
|
+
return "HIGH";
|
|
757
|
+
}
|
|
758
|
+
};
|
|
759
|
+
|
|
760
|
+
// src/tools/indicators/statistical.ts
|
|
761
|
+
var StatisticalModels = class {
|
|
762
|
+
/**
|
|
763
|
+
* Calculate Z-Score
|
|
764
|
+
*/
|
|
765
|
+
static calculateZScore(currentPrice, startPrice) {
|
|
766
|
+
return (currentPrice - startPrice) / (startPrice * 0.1);
|
|
767
|
+
}
|
|
768
|
+
/**
|
|
769
|
+
* Calculate Ornstein-Uhlenbeck
|
|
770
|
+
*/
|
|
771
|
+
static calculateOrnsteinUhlenbeck(currentPrice, startPrice, avgVolume, priceChanges) {
|
|
772
|
+
const mean = startPrice;
|
|
773
|
+
let speed = 0.1;
|
|
774
|
+
if (priceChanges.length > 1) {
|
|
775
|
+
const variance = priceChanges.reduce((sum2, change) => sum2 + change * change, 0) / priceChanges.length;
|
|
776
|
+
speed = Math.max(0.01, Math.min(1, variance * 10));
|
|
777
|
+
}
|
|
778
|
+
const volatility = avgVolume * 0.01;
|
|
779
|
+
return {
|
|
780
|
+
mean,
|
|
781
|
+
speed,
|
|
782
|
+
volatility,
|
|
783
|
+
currentValue: currentPrice
|
|
784
|
+
};
|
|
785
|
+
}
|
|
786
|
+
/**
|
|
787
|
+
* Calculate Kalman Filter
|
|
788
|
+
*/
|
|
789
|
+
static calculateKalmanFilter(currentPrice, startPrice, avgVolume, priceChanges) {
|
|
790
|
+
const measurementNoise = avgVolume * 1e-3;
|
|
791
|
+
const processNoise = avgVolume * 1e-4;
|
|
792
|
+
let state = startPrice;
|
|
793
|
+
let covariance = measurementNoise;
|
|
794
|
+
if (priceChanges.length > 0) {
|
|
795
|
+
const predictedState = state;
|
|
796
|
+
const predictedCovariance = covariance + processNoise;
|
|
797
|
+
const kalmanGain = predictedCovariance / (predictedCovariance + measurementNoise);
|
|
798
|
+
state = predictedState + kalmanGain * (currentPrice - predictedState);
|
|
799
|
+
covariance = (1 - kalmanGain) * predictedCovariance;
|
|
800
|
+
return {
|
|
801
|
+
state,
|
|
802
|
+
covariance,
|
|
803
|
+
gain: kalmanGain
|
|
804
|
+
};
|
|
805
|
+
}
|
|
806
|
+
return {
|
|
807
|
+
state: currentPrice,
|
|
808
|
+
covariance,
|
|
809
|
+
gain: 0.5
|
|
810
|
+
};
|
|
811
|
+
}
|
|
812
|
+
/**
|
|
813
|
+
* Calculate ARIMA
|
|
814
|
+
*/
|
|
815
|
+
static calculateARIMA(currentPrice, priceChanges) {
|
|
816
|
+
if (priceChanges.length < 3) {
|
|
817
|
+
return {
|
|
818
|
+
forecast: [currentPrice * 1.01, currentPrice * 1.02],
|
|
819
|
+
residuals: [0, 0],
|
|
820
|
+
aic: 100
|
|
821
|
+
};
|
|
822
|
+
}
|
|
823
|
+
const n = priceChanges.length;
|
|
824
|
+
let sumY = 0;
|
|
825
|
+
let sumY1 = 0;
|
|
826
|
+
let sumYY1 = 0;
|
|
827
|
+
let sumY1Sq = 0;
|
|
828
|
+
for (let i = 1; i < n; i++) {
|
|
829
|
+
const y = priceChanges[i];
|
|
830
|
+
const y1 = priceChanges[i - 1];
|
|
831
|
+
sumY += y;
|
|
832
|
+
sumY1 += y1;
|
|
833
|
+
sumYY1 += y * y1;
|
|
834
|
+
sumY1Sq += y1 * y1;
|
|
835
|
+
}
|
|
836
|
+
const phi = (n * sumYY1 - sumY * sumY1) / (n * sumY1Sq - sumY1 * sumY1);
|
|
837
|
+
const c = (sumY - phi * sumY1) / n;
|
|
838
|
+
const residuals = [];
|
|
839
|
+
for (let i = 1; i < n; i++) {
|
|
840
|
+
const predicted = c + phi * priceChanges[i - 1];
|
|
841
|
+
residuals.push(priceChanges[i] - predicted);
|
|
842
|
+
}
|
|
843
|
+
const rss = residuals.reduce((sum2, r) => sum2 + r * r, 0);
|
|
844
|
+
const aic = n * Math.log(rss / n) + 2 * 2;
|
|
845
|
+
const lastChange = priceChanges[priceChanges.length - 1];
|
|
846
|
+
const forecast1 = currentPrice + (c + phi * lastChange);
|
|
847
|
+
const forecast2 = forecast1 + (c + phi * (c + phi * lastChange));
|
|
848
|
+
return {
|
|
849
|
+
forecast: [forecast1, forecast2],
|
|
850
|
+
residuals,
|
|
851
|
+
aic
|
|
852
|
+
};
|
|
853
|
+
}
|
|
854
|
+
/**
|
|
855
|
+
* Calculate GARCH
|
|
856
|
+
*/
|
|
857
|
+
static calculateGARCH(avgVolume, priceChanges) {
|
|
858
|
+
if (priceChanges.length < 5) {
|
|
859
|
+
return {
|
|
860
|
+
volatility: avgVolume * 0.01,
|
|
861
|
+
persistence: 0.9,
|
|
862
|
+
meanReversion: 0.1
|
|
863
|
+
};
|
|
864
|
+
}
|
|
865
|
+
const squaredReturns = priceChanges.map((change) => change * change);
|
|
866
|
+
const meanSquaredReturn = squaredReturns.reduce((sum2, sq) => sum2 + sq, 0) / squaredReturns.length;
|
|
867
|
+
let persistence = 0.9;
|
|
868
|
+
if (squaredReturns.length > 1) {
|
|
869
|
+
const variance = squaredReturns.reduce((sum2, sq) => sum2 + sq, 0) / squaredReturns.length;
|
|
870
|
+
persistence = Math.min(0.99, Math.max(0.5, variance / meanSquaredReturn));
|
|
871
|
+
}
|
|
872
|
+
const meanReversion = meanSquaredReturn * (1 - persistence);
|
|
873
|
+
const volatility = Math.sqrt(meanSquaredReturn);
|
|
874
|
+
return {
|
|
875
|
+
volatility,
|
|
876
|
+
persistence,
|
|
877
|
+
meanReversion
|
|
878
|
+
};
|
|
879
|
+
}
|
|
880
|
+
/**
|
|
881
|
+
* Calculate Hilbert Transform
|
|
882
|
+
*/
|
|
883
|
+
static calculateHilbertTransform(currentPrice, priceChanges) {
|
|
884
|
+
if (priceChanges.length < 3) {
|
|
885
|
+
return {
|
|
886
|
+
analytic: [currentPrice],
|
|
887
|
+
phase: [0],
|
|
888
|
+
amplitude: [currentPrice]
|
|
889
|
+
};
|
|
890
|
+
}
|
|
891
|
+
const n = priceChanges.length;
|
|
892
|
+
const analytic = [];
|
|
893
|
+
const phase = [];
|
|
894
|
+
const amplitude = [];
|
|
895
|
+
for (let i = 0; i < n; i++) {
|
|
896
|
+
let hilbertValue = 0;
|
|
897
|
+
for (let j = 0; j < n; j++) {
|
|
898
|
+
if (i !== j) {
|
|
899
|
+
hilbertValue += priceChanges[j] / (Math.PI * (i - j));
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
const realPart = priceChanges[i];
|
|
903
|
+
const imagPart = hilbertValue;
|
|
904
|
+
const analyticValue = Math.sqrt(realPart * realPart + imagPart * imagPart);
|
|
905
|
+
analytic.push(analyticValue);
|
|
906
|
+
const phaseValue = Math.atan2(imagPart, realPart);
|
|
907
|
+
phase.push(phaseValue);
|
|
908
|
+
amplitude.push(analyticValue);
|
|
909
|
+
}
|
|
910
|
+
return {
|
|
911
|
+
analytic,
|
|
912
|
+
phase,
|
|
913
|
+
amplitude
|
|
914
|
+
};
|
|
915
|
+
}
|
|
916
|
+
/**
|
|
917
|
+
* Calculate Wavelet Transform
|
|
918
|
+
*/
|
|
919
|
+
static calculateWaveletTransform(currentPrice, priceChanges) {
|
|
920
|
+
if (priceChanges.length < 4) {
|
|
921
|
+
return {
|
|
922
|
+
coefficients: [currentPrice],
|
|
923
|
+
scales: [1]
|
|
924
|
+
};
|
|
925
|
+
}
|
|
926
|
+
const coefficients = [];
|
|
927
|
+
const scales = [];
|
|
928
|
+
const n = priceChanges.length;
|
|
929
|
+
const maxLevel = Math.floor(Math.log2(n));
|
|
930
|
+
for (let level = 1; level <= maxLevel; level++) {
|
|
931
|
+
const step = 2 ** (level - 1);
|
|
932
|
+
const scale = step;
|
|
933
|
+
for (let i = 0; i < n - step; i += step * 2) {
|
|
934
|
+
if (i + step < n) {
|
|
935
|
+
const coefficient = (priceChanges[i] - priceChanges[i + step]) / Math.sqrt(2);
|
|
936
|
+
coefficients.push(coefficient);
|
|
937
|
+
scales.push(scale);
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
}
|
|
941
|
+
if (coefficients.length === 0) {
|
|
942
|
+
coefficients.push(currentPrice);
|
|
943
|
+
scales.push(1);
|
|
944
|
+
}
|
|
945
|
+
return {
|
|
946
|
+
coefficients,
|
|
947
|
+
scales
|
|
948
|
+
};
|
|
949
|
+
}
|
|
950
|
+
};
|
|
951
|
+
|
|
952
|
+
// src/tools/indicators/supportResistance.ts
|
|
953
|
+
var SupportResistanceIndicators = class _SupportResistanceIndicators {
|
|
954
|
+
/**
|
|
955
|
+
* Calculate Pivot Points
|
|
956
|
+
*/
|
|
957
|
+
static calculatePivotPoints(prices, highs, lows) {
|
|
958
|
+
const pivotPoints = [];
|
|
959
|
+
for (let i = 0; i < prices.length; i++) {
|
|
960
|
+
const high = highs[i] || prices[i];
|
|
961
|
+
const low = lows[i] || prices[i];
|
|
962
|
+
const close = prices[i];
|
|
963
|
+
const pp = (high + low + close) / 3;
|
|
964
|
+
const r1 = 2 * pp - low;
|
|
965
|
+
const s1 = 2 * pp - high;
|
|
966
|
+
const r2 = pp + (high - low);
|
|
967
|
+
const s2 = pp - (high - low);
|
|
968
|
+
const r3 = high + 2 * (pp - low);
|
|
969
|
+
const s3 = low - 2 * (high - pp);
|
|
970
|
+
pivotPoints.push({
|
|
971
|
+
pp,
|
|
972
|
+
r1,
|
|
973
|
+
r2,
|
|
974
|
+
r3,
|
|
975
|
+
s1,
|
|
976
|
+
s2,
|
|
977
|
+
s3
|
|
978
|
+
});
|
|
979
|
+
}
|
|
980
|
+
return pivotPoints;
|
|
981
|
+
}
|
|
982
|
+
/**
|
|
983
|
+
* Calculate Fibonacci Levels
|
|
984
|
+
*/
|
|
985
|
+
static calculateFibonacciLevels(prices) {
|
|
986
|
+
const fibonacci = [];
|
|
987
|
+
for (let i = 0; i < prices.length; i++) {
|
|
988
|
+
const price = prices[i];
|
|
989
|
+
fibonacci.push({
|
|
990
|
+
retracement: {
|
|
991
|
+
level0: price,
|
|
992
|
+
level236: price * 0.764,
|
|
993
|
+
level382: price * 0.618,
|
|
994
|
+
level500: price * 0.5,
|
|
995
|
+
level618: price * 0.382,
|
|
996
|
+
level786: price * 0.214,
|
|
997
|
+
level100: price * 0
|
|
998
|
+
},
|
|
999
|
+
extension: {
|
|
1000
|
+
level1272: price * 1.272,
|
|
1001
|
+
level1618: price * 1.618,
|
|
1002
|
+
level2618: price * 2.618,
|
|
1003
|
+
level4236: price * 4.236
|
|
1004
|
+
}
|
|
1005
|
+
});
|
|
1006
|
+
}
|
|
1007
|
+
return fibonacci;
|
|
1008
|
+
}
|
|
1009
|
+
/**
|
|
1010
|
+
* Calculate Gann Levels
|
|
1011
|
+
*/
|
|
1012
|
+
static calculateGannLevels(prices) {
|
|
1013
|
+
const gannLevels = [];
|
|
1014
|
+
for (let i = 0; i < prices.length; i++) {
|
|
1015
|
+
gannLevels.push(prices[i] * (1 + i * 0.01));
|
|
1016
|
+
}
|
|
1017
|
+
return gannLevels;
|
|
1018
|
+
}
|
|
1019
|
+
/**
|
|
1020
|
+
* Calculate Elliott Wave
|
|
1021
|
+
*/
|
|
1022
|
+
static calculateElliottWave(prices) {
|
|
1023
|
+
const elliottWave = [];
|
|
1024
|
+
if (prices.length < 10) return [];
|
|
1025
|
+
for (let i = 0; i < prices.length; i++) {
|
|
1026
|
+
const waves = [];
|
|
1027
|
+
let currentWave = 1;
|
|
1028
|
+
let wavePosition = 0.5;
|
|
1029
|
+
if (i >= 4) {
|
|
1030
|
+
const recentPrices = prices.slice(i - 4, i + 1);
|
|
1031
|
+
const swings = _SupportResistanceIndicators.detectPriceSwings(recentPrices);
|
|
1032
|
+
if (swings.length >= 3) {
|
|
1033
|
+
waves.push(...swings.slice(0, 3));
|
|
1034
|
+
currentWave = Math.min(swings.length, 5);
|
|
1035
|
+
wavePosition = _SupportResistanceIndicators.calculateWavePosition(recentPrices);
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
elliottWave.push({
|
|
1039
|
+
waves: waves.length > 0 ? waves : [prices[i]],
|
|
1040
|
+
currentWave,
|
|
1041
|
+
wavePosition
|
|
1042
|
+
});
|
|
1043
|
+
}
|
|
1044
|
+
return elliottWave;
|
|
1045
|
+
}
|
|
1046
|
+
/**
|
|
1047
|
+
* Helper method to detect price swings
|
|
1048
|
+
*/
|
|
1049
|
+
static detectPriceSwings(prices) {
|
|
1050
|
+
const swings = [];
|
|
1051
|
+
for (let i = 1; i < prices.length - 1; i++) {
|
|
1052
|
+
const prev = prices[i - 1];
|
|
1053
|
+
const curr = prices[i];
|
|
1054
|
+
const next = prices[i + 1];
|
|
1055
|
+
if (curr > prev && curr > next) {
|
|
1056
|
+
swings.push(curr);
|
|
1057
|
+
} else if (curr < prev && curr < next) {
|
|
1058
|
+
swings.push(curr);
|
|
1059
|
+
}
|
|
1060
|
+
}
|
|
1061
|
+
return swings;
|
|
1062
|
+
}
|
|
1063
|
+
/**
|
|
1064
|
+
* Helper method to calculate wave position
|
|
1065
|
+
*/
|
|
1066
|
+
static calculateWavePosition(prices) {
|
|
1067
|
+
if (prices.length < 2) return 0.5;
|
|
1068
|
+
const current = prices[prices.length - 1];
|
|
1069
|
+
const min = Math.min(...prices);
|
|
1070
|
+
const max = Math.max(...prices);
|
|
1071
|
+
return max !== min ? (current - min) / (max - min) : 0.5;
|
|
1072
|
+
}
|
|
1073
|
+
/**
|
|
1074
|
+
* Calculate Harmonic Patterns
|
|
1075
|
+
*/
|
|
1076
|
+
static calculateHarmonicPatterns(prices) {
|
|
1077
|
+
const harmonicPatterns = [];
|
|
1078
|
+
if (prices.length < 5) return [];
|
|
1079
|
+
for (let i = 4; i < prices.length; i++) {
|
|
1080
|
+
const recentPrices = prices.slice(i - 4, i + 1);
|
|
1081
|
+
const pattern = _SupportResistanceIndicators.detectHarmonicPattern(recentPrices);
|
|
1082
|
+
harmonicPatterns.push(pattern);
|
|
1083
|
+
}
|
|
1084
|
+
return harmonicPatterns;
|
|
1085
|
+
}
|
|
1086
|
+
/**
|
|
1087
|
+
* Helper method to detect harmonic patterns
|
|
1088
|
+
*/
|
|
1089
|
+
static detectHarmonicPattern(prices) {
|
|
1090
|
+
if (prices.length < 5) {
|
|
1091
|
+
return {
|
|
1092
|
+
type: "Unknown",
|
|
1093
|
+
completion: 0,
|
|
1094
|
+
target: prices[prices.length - 1] * 1.1,
|
|
1095
|
+
stopLoss: prices[prices.length - 1] * 0.9
|
|
1096
|
+
};
|
|
1097
|
+
}
|
|
1098
|
+
const swings = _SupportResistanceIndicators.detectPriceSwings(prices);
|
|
1099
|
+
if (swings.length < 4) {
|
|
1100
|
+
return {
|
|
1101
|
+
type: "Unknown",
|
|
1102
|
+
completion: 0,
|
|
1103
|
+
target: prices[prices.length - 1] * 1.1,
|
|
1104
|
+
stopLoss: prices[prices.length - 1] * 0.9
|
|
1105
|
+
};
|
|
1106
|
+
}
|
|
1107
|
+
const [A, B, C, D] = swings.slice(-4);
|
|
1108
|
+
const X = prices[0];
|
|
1109
|
+
const abRatio = Math.abs((B - A) / (X - A));
|
|
1110
|
+
const bcRatio = Math.abs((C - B) / (A - B));
|
|
1111
|
+
const cdRatio = Math.abs((D - C) / (B - C));
|
|
1112
|
+
const adRatio = Math.abs((D - A) / (X - A));
|
|
1113
|
+
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;
|
|
1114
|
+
if (isGartley) {
|
|
1115
|
+
const completion = _SupportResistanceIndicators.calculatePatternCompletion(prices);
|
|
1116
|
+
const target = D + (D - C) * 0.618;
|
|
1117
|
+
const stopLoss = D - (D - C) * 0.382;
|
|
1118
|
+
return {
|
|
1119
|
+
type: "Gartley",
|
|
1120
|
+
completion,
|
|
1121
|
+
target,
|
|
1122
|
+
stopLoss
|
|
1123
|
+
};
|
|
1124
|
+
}
|
|
1125
|
+
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;
|
|
1126
|
+
if (isButterfly) {
|
|
1127
|
+
const completion = _SupportResistanceIndicators.calculatePatternCompletion(prices);
|
|
1128
|
+
const target = D + (D - C) * 1.27;
|
|
1129
|
+
const stopLoss = D - (D - C) * 0.5;
|
|
1130
|
+
return {
|
|
1131
|
+
type: "Butterfly",
|
|
1132
|
+
completion,
|
|
1133
|
+
target,
|
|
1134
|
+
stopLoss
|
|
1135
|
+
};
|
|
1136
|
+
}
|
|
1137
|
+
return {
|
|
1138
|
+
type: "Unknown",
|
|
1139
|
+
completion: 0,
|
|
1140
|
+
target: prices[prices.length - 1] * 1.1,
|
|
1141
|
+
stopLoss: prices[prices.length - 1] * 0.9
|
|
1142
|
+
};
|
|
1143
|
+
}
|
|
1144
|
+
/**
|
|
1145
|
+
* Helper method to calculate pattern completion
|
|
1146
|
+
*/
|
|
1147
|
+
static calculatePatternCompletion(prices) {
|
|
1148
|
+
if (prices.length < 2) return 0;
|
|
1149
|
+
const current = prices[prices.length - 1];
|
|
1150
|
+
const min = Math.min(...prices);
|
|
1151
|
+
const max = Math.max(...prices);
|
|
1152
|
+
return max !== min ? (current - min) / (max - min) : 0;
|
|
1153
|
+
}
|
|
1154
|
+
};
|
|
1155
|
+
|
|
1156
|
+
// src/tools/indicators/trend.ts
|
|
1157
|
+
var TrendIndicators = class {
|
|
1158
|
+
/**
|
|
1159
|
+
* Calculate MACD (Moving Average Convergence Divergence)
|
|
1160
|
+
*/
|
|
1161
|
+
static calculateMACD(prices) {
|
|
1162
|
+
const ema12 = MovingAverages.calculateEMA(prices, 12);
|
|
1163
|
+
const ema26 = MovingAverages.calculateEMA(prices, 26);
|
|
1164
|
+
const macd = [];
|
|
1165
|
+
const macdLine = [];
|
|
1166
|
+
for (let i = 0; i < Math.min(ema12.length, ema26.length); i++) {
|
|
1167
|
+
macdLine.push(ema12[i] - ema26[i]);
|
|
1168
|
+
}
|
|
1169
|
+
const signalLine = MovingAverages.calculateEMA(macdLine, 9);
|
|
1170
|
+
for (let i = 0; i < Math.min(macdLine.length, signalLine.length); i++) {
|
|
1171
|
+
macd.push({
|
|
1172
|
+
macd: macdLine[i],
|
|
1173
|
+
signal: signalLine[i],
|
|
1174
|
+
histogram: macdLine[i] - signalLine[i]
|
|
1175
|
+
});
|
|
1176
|
+
}
|
|
1177
|
+
return macd;
|
|
1178
|
+
}
|
|
1179
|
+
/**
|
|
1180
|
+
* Calculate ADX (Average Directional Index)
|
|
1181
|
+
*/
|
|
1182
|
+
static calculateADX(prices, highs, lows) {
|
|
1183
|
+
if (prices.length < 14) return [];
|
|
1184
|
+
const period = 14;
|
|
1185
|
+
const adx = [];
|
|
1186
|
+
const trueRanges = [];
|
|
1187
|
+
const plusDM = [];
|
|
1188
|
+
const minusDM = [];
|
|
1189
|
+
trueRanges.push(highs[0] - lows[0]);
|
|
1190
|
+
plusDM.push(0);
|
|
1191
|
+
minusDM.push(0);
|
|
1192
|
+
for (let i = 1; i < prices.length; i++) {
|
|
1193
|
+
const high = highs[i] || prices[i];
|
|
1194
|
+
const low = lows[i] || prices[i];
|
|
1195
|
+
const prevHigh = highs[i - 1] || prices[i - 1];
|
|
1196
|
+
const prevLow = lows[i - 1] || prices[i - 1];
|
|
1197
|
+
const prevClose = prices[i - 1];
|
|
1198
|
+
const tr1 = high - low;
|
|
1199
|
+
const tr2 = Math.abs(high - prevClose);
|
|
1200
|
+
const tr3 = Math.abs(low - prevClose);
|
|
1201
|
+
trueRanges.push(Math.max(tr1, tr2, tr3));
|
|
1202
|
+
const upMove = high - prevHigh;
|
|
1203
|
+
const downMove = prevLow - low;
|
|
1204
|
+
if (upMove > downMove && upMove > 0) {
|
|
1205
|
+
plusDM.push(upMove);
|
|
1206
|
+
minusDM.push(0);
|
|
1207
|
+
} else if (downMove > upMove && downMove > 0) {
|
|
1208
|
+
plusDM.push(0);
|
|
1209
|
+
minusDM.push(downMove);
|
|
1210
|
+
} else {
|
|
1211
|
+
plusDM.push(0);
|
|
1212
|
+
minusDM.push(0);
|
|
1213
|
+
}
|
|
1214
|
+
}
|
|
1215
|
+
const smoothedTR = [];
|
|
1216
|
+
const smoothedPlusDM = [];
|
|
1217
|
+
const smoothedMinusDM = [];
|
|
1218
|
+
let sumTR = 0;
|
|
1219
|
+
let sumPlusDM = 0;
|
|
1220
|
+
let sumMinusDM = 0;
|
|
1221
|
+
for (let i = 0; i < period; i++) {
|
|
1222
|
+
sumTR += trueRanges[i];
|
|
1223
|
+
sumPlusDM += plusDM[i];
|
|
1224
|
+
sumMinusDM += minusDM[i];
|
|
1225
|
+
}
|
|
1226
|
+
smoothedTR.push(sumTR);
|
|
1227
|
+
smoothedPlusDM.push(sumPlusDM);
|
|
1228
|
+
smoothedMinusDM.push(sumMinusDM);
|
|
1229
|
+
for (let i = period; i < trueRanges.length; i++) {
|
|
1230
|
+
const newTR = smoothedTR[smoothedTR.length - 1] - smoothedTR[smoothedTR.length - 1] / period + trueRanges[i];
|
|
1231
|
+
const newPlusDM = smoothedPlusDM[smoothedPlusDM.length - 1] - smoothedPlusDM[smoothedPlusDM.length - 1] / period + plusDM[i];
|
|
1232
|
+
const newMinusDM = smoothedMinusDM[smoothedMinusDM.length - 1] - smoothedMinusDM[smoothedMinusDM.length - 1] / period + minusDM[i];
|
|
1233
|
+
smoothedTR.push(newTR);
|
|
1234
|
+
smoothedPlusDM.push(newPlusDM);
|
|
1235
|
+
smoothedMinusDM.push(newMinusDM);
|
|
1236
|
+
}
|
|
1237
|
+
const plusDI = [];
|
|
1238
|
+
const minusDI = [];
|
|
1239
|
+
for (let i = 0; i < smoothedTR.length; i++) {
|
|
1240
|
+
plusDI.push(smoothedPlusDM[i] / smoothedTR[i] * 100);
|
|
1241
|
+
minusDI.push(smoothedMinusDM[i] / smoothedTR[i] * 100);
|
|
1242
|
+
}
|
|
1243
|
+
const dx = [];
|
|
1244
|
+
for (let i = 0; i < plusDI.length; i++) {
|
|
1245
|
+
const diSum = plusDI[i] + minusDI[i];
|
|
1246
|
+
const diDiff = Math.abs(plusDI[i] - minusDI[i]);
|
|
1247
|
+
dx.push(diSum > 0 ? diDiff / diSum * 100 : 0);
|
|
1248
|
+
}
|
|
1249
|
+
if (dx.length < period) return [];
|
|
1250
|
+
let sumDX = 0;
|
|
1251
|
+
for (let i = 0; i < period; i++) {
|
|
1252
|
+
sumDX += dx[i];
|
|
1253
|
+
}
|
|
1254
|
+
adx.push(sumDX / period);
|
|
1255
|
+
for (let i = period; i < dx.length; i++) {
|
|
1256
|
+
const newADX = adx[adx.length - 1] - adx[adx.length - 1] / period + dx[i];
|
|
1257
|
+
adx.push(newADX);
|
|
1258
|
+
}
|
|
1259
|
+
return adx;
|
|
1260
|
+
}
|
|
1261
|
+
/**
|
|
1262
|
+
* Calculate DMI (Directional Movement Index)
|
|
1263
|
+
*/
|
|
1264
|
+
static calculateDMI(prices, highs, lows) {
|
|
1265
|
+
if (prices.length < 14) return [];
|
|
1266
|
+
const period = 14;
|
|
1267
|
+
const dmi = [];
|
|
1268
|
+
const trueRanges = [];
|
|
1269
|
+
const plusDM = [];
|
|
1270
|
+
const minusDM = [];
|
|
1271
|
+
trueRanges.push(highs[0] - lows[0]);
|
|
1272
|
+
plusDM.push(0);
|
|
1273
|
+
minusDM.push(0);
|
|
1274
|
+
for (let i = 1; i < prices.length; i++) {
|
|
1275
|
+
const high = highs[i] || prices[i];
|
|
1276
|
+
const low = lows[i] || prices[i];
|
|
1277
|
+
const prevHigh = highs[i - 1] || prices[i - 1];
|
|
1278
|
+
const prevLow = lows[i - 1] || prices[i - 1];
|
|
1279
|
+
const prevClose = prices[i - 1];
|
|
1280
|
+
const tr1 = high - low;
|
|
1281
|
+
const tr2 = Math.abs(high - prevClose);
|
|
1282
|
+
const tr3 = Math.abs(low - prevClose);
|
|
1283
|
+
trueRanges.push(Math.max(tr1, tr2, tr3));
|
|
1284
|
+
const upMove = high - prevHigh;
|
|
1285
|
+
const downMove = prevLow - low;
|
|
1286
|
+
if (upMove > downMove && upMove > 0) {
|
|
1287
|
+
plusDM.push(upMove);
|
|
1288
|
+
minusDM.push(0);
|
|
1289
|
+
} else if (downMove > upMove && downMove > 0) {
|
|
1290
|
+
plusDM.push(0);
|
|
1291
|
+
minusDM.push(downMove);
|
|
1292
|
+
} else {
|
|
1293
|
+
plusDM.push(0);
|
|
1294
|
+
minusDM.push(0);
|
|
1295
|
+
}
|
|
1296
|
+
}
|
|
1297
|
+
const smoothedTR = [];
|
|
1298
|
+
const smoothedPlusDM = [];
|
|
1299
|
+
const smoothedMinusDM = [];
|
|
1300
|
+
let sumTR = 0;
|
|
1301
|
+
let sumPlusDM = 0;
|
|
1302
|
+
let sumMinusDM = 0;
|
|
1303
|
+
for (let i = 0; i < period; i++) {
|
|
1304
|
+
sumTR += trueRanges[i];
|
|
1305
|
+
sumPlusDM += plusDM[i];
|
|
1306
|
+
sumMinusDM += minusDM[i];
|
|
1307
|
+
}
|
|
1308
|
+
smoothedTR.push(sumTR);
|
|
1309
|
+
smoothedPlusDM.push(sumPlusDM);
|
|
1310
|
+
smoothedMinusDM.push(sumMinusDM);
|
|
1311
|
+
for (let i = period; i < trueRanges.length; i++) {
|
|
1312
|
+
const newTR = smoothedTR[smoothedTR.length - 1] - smoothedTR[smoothedTR.length - 1] / period + trueRanges[i];
|
|
1313
|
+
const newPlusDM = smoothedPlusDM[smoothedPlusDM.length - 1] - smoothedPlusDM[smoothedPlusDM.length - 1] / period + plusDM[i];
|
|
1314
|
+
const newMinusDM = smoothedMinusDM[smoothedMinusDM.length - 1] - smoothedMinusDM[smoothedMinusDM.length - 1] / period + minusDM[i];
|
|
1315
|
+
smoothedTR.push(newTR);
|
|
1316
|
+
smoothedPlusDM.push(newPlusDM);
|
|
1317
|
+
smoothedMinusDM.push(newMinusDM);
|
|
1318
|
+
}
|
|
1319
|
+
const plusDI = [];
|
|
1320
|
+
const minusDI = [];
|
|
1321
|
+
for (let i = 0; i < smoothedTR.length; i++) {
|
|
1322
|
+
plusDI.push(smoothedPlusDM[i] / smoothedTR[i] * 100);
|
|
1323
|
+
minusDI.push(smoothedMinusDM[i] / smoothedTR[i] * 100);
|
|
1324
|
+
}
|
|
1325
|
+
const dx = [];
|
|
1326
|
+
for (let i = 0; i < plusDI.length; i++) {
|
|
1327
|
+
const diSum = plusDI[i] + minusDI[i];
|
|
1328
|
+
const diDiff = Math.abs(plusDI[i] - minusDI[i]);
|
|
1329
|
+
dx.push(diSum > 0 ? diDiff / diSum * 100 : 0);
|
|
1330
|
+
}
|
|
1331
|
+
if (dx.length < period) return [];
|
|
1332
|
+
const adx = [];
|
|
1333
|
+
let sumDX = 0;
|
|
1334
|
+
for (let i = 0; i < period; i++) {
|
|
1335
|
+
sumDX += dx[i];
|
|
1336
|
+
}
|
|
1337
|
+
adx.push(sumDX / period);
|
|
1338
|
+
for (let i = period; i < dx.length; i++) {
|
|
1339
|
+
const newADX = adx[adx.length - 1] - adx[adx.length - 1] / period + dx[i];
|
|
1340
|
+
adx.push(newADX);
|
|
1341
|
+
}
|
|
1342
|
+
for (let i = 0; i < adx.length; i++) {
|
|
1343
|
+
dmi.push({
|
|
1344
|
+
plusDI: plusDI[i + period - 1] || 0,
|
|
1345
|
+
minusDI: minusDI[i + period - 1] || 0,
|
|
1346
|
+
adx: adx[i]
|
|
1347
|
+
});
|
|
1348
|
+
}
|
|
1349
|
+
return dmi;
|
|
1350
|
+
}
|
|
1351
|
+
/**
|
|
1352
|
+
* Calculate Ichimoku Cloud
|
|
1353
|
+
*/
|
|
1354
|
+
static calculateIchimoku(prices, highs, lows) {
|
|
1355
|
+
if (prices.length < 52) return [];
|
|
1356
|
+
const ichimoku = [];
|
|
1357
|
+
const tenkanSen = [];
|
|
1358
|
+
for (let i = 8; i < prices.length; i++) {
|
|
1359
|
+
const periodHigh = Math.max(...highs.slice(i - 8, i + 1));
|
|
1360
|
+
const periodLow = Math.min(...lows.slice(i - 8, i + 1));
|
|
1361
|
+
tenkanSen.push((periodHigh + periodLow) / 2);
|
|
1362
|
+
}
|
|
1363
|
+
const kijunSen = [];
|
|
1364
|
+
for (let i = 25; i < prices.length; i++) {
|
|
1365
|
+
const periodHigh = Math.max(...highs.slice(i - 25, i + 1));
|
|
1366
|
+
const periodLow = Math.min(...lows.slice(i - 25, i + 1));
|
|
1367
|
+
kijunSen.push((periodHigh + periodLow) / 2);
|
|
1368
|
+
}
|
|
1369
|
+
const senkouSpanA = [];
|
|
1370
|
+
for (let i = 0; i < Math.min(tenkanSen.length, kijunSen.length); i++) {
|
|
1371
|
+
senkouSpanA.push((tenkanSen[i] + kijunSen[i]) / 2);
|
|
1372
|
+
}
|
|
1373
|
+
const senkouSpanB = [];
|
|
1374
|
+
for (let i = 51; i < prices.length; i++) {
|
|
1375
|
+
const periodHigh = Math.max(...highs.slice(i - 51, i + 1));
|
|
1376
|
+
const periodLow = Math.min(...lows.slice(i - 51, i + 1));
|
|
1377
|
+
senkouSpanB.push((periodHigh + periodLow) / 2);
|
|
1378
|
+
}
|
|
1379
|
+
const chikouSpan = [];
|
|
1380
|
+
for (let i = 26; i < prices.length; i++) {
|
|
1381
|
+
chikouSpan.push(prices[i - 26]);
|
|
1382
|
+
}
|
|
1383
|
+
const minLength = Math.min(
|
|
1384
|
+
tenkanSen.length,
|
|
1385
|
+
kijunSen.length,
|
|
1386
|
+
senkouSpanA.length,
|
|
1387
|
+
senkouSpanB.length,
|
|
1388
|
+
chikouSpan.length
|
|
1389
|
+
);
|
|
1390
|
+
for (let i = 0; i < minLength; i++) {
|
|
1391
|
+
ichimoku.push({
|
|
1392
|
+
tenkan: tenkanSen[i],
|
|
1393
|
+
kijun: kijunSen[i],
|
|
1394
|
+
senkouA: senkouSpanA[i],
|
|
1395
|
+
senkouB: senkouSpanB[i],
|
|
1396
|
+
chikou: chikouSpan[i]
|
|
1397
|
+
});
|
|
1398
|
+
}
|
|
1399
|
+
return ichimoku;
|
|
1400
|
+
}
|
|
1401
|
+
/**
|
|
1402
|
+
* Calculate Parabolic SAR
|
|
1403
|
+
*/
|
|
1404
|
+
static calculateParabolicSAR(prices, highs, lows) {
|
|
1405
|
+
if (prices.length < 2) return [];
|
|
1406
|
+
const sar = [];
|
|
1407
|
+
const accelerationFactor = 0.02;
|
|
1408
|
+
const maximumAcceleration = 0.2;
|
|
1409
|
+
let currentSAR = lows[0];
|
|
1410
|
+
let isLong = true;
|
|
1411
|
+
let af = accelerationFactor;
|
|
1412
|
+
let ep = highs[0];
|
|
1413
|
+
sar.push(currentSAR);
|
|
1414
|
+
for (let i = 1; i < prices.length; i++) {
|
|
1415
|
+
const high = highs[i] || prices[i];
|
|
1416
|
+
const low = lows[i] || prices[i];
|
|
1417
|
+
if (isLong) {
|
|
1418
|
+
if (low < currentSAR) {
|
|
1419
|
+
isLong = false;
|
|
1420
|
+
currentSAR = ep;
|
|
1421
|
+
ep = low;
|
|
1422
|
+
af = accelerationFactor;
|
|
1423
|
+
} else {
|
|
1424
|
+
if (high > ep) {
|
|
1425
|
+
ep = high;
|
|
1426
|
+
af = Math.min(af + accelerationFactor, maximumAcceleration);
|
|
1427
|
+
}
|
|
1428
|
+
currentSAR = currentSAR + af * (ep - currentSAR);
|
|
1429
|
+
if (i > 0) {
|
|
1430
|
+
const prevLow = lows[i - 1] || prices[i - 1];
|
|
1431
|
+
currentSAR = Math.min(currentSAR, prevLow);
|
|
1432
|
+
}
|
|
1433
|
+
}
|
|
1434
|
+
} else {
|
|
1435
|
+
if (high > currentSAR) {
|
|
1436
|
+
isLong = true;
|
|
1437
|
+
currentSAR = ep;
|
|
1438
|
+
ep = high;
|
|
1439
|
+
af = accelerationFactor;
|
|
1440
|
+
} else {
|
|
1441
|
+
if (low < ep) {
|
|
1442
|
+
ep = low;
|
|
1443
|
+
af = Math.min(af + accelerationFactor, maximumAcceleration);
|
|
1444
|
+
}
|
|
1445
|
+
currentSAR = currentSAR + af * (ep - currentSAR);
|
|
1446
|
+
if (i > 0) {
|
|
1447
|
+
const prevHigh = highs[i - 1] || prices[i - 1];
|
|
1448
|
+
currentSAR = Math.max(currentSAR, prevHigh);
|
|
1449
|
+
}
|
|
1450
|
+
}
|
|
1451
|
+
}
|
|
1452
|
+
sar.push(currentSAR);
|
|
1453
|
+
}
|
|
1454
|
+
return sar;
|
|
268
1455
|
}
|
|
269
1456
|
};
|
|
270
1457
|
|
|
1458
|
+
// src/tools/indicators/volatility.ts
|
|
1459
|
+
var VolatilityIndicators = class _VolatilityIndicators {
|
|
1460
|
+
/**
|
|
1461
|
+
* Calculate Bollinger Bands
|
|
1462
|
+
*/
|
|
1463
|
+
static calculateBollingerBands(data, period = 20, stdDev = 2) {
|
|
1464
|
+
if (data.length < period) return [];
|
|
1465
|
+
const sma = MovingAverages.calculateSMA(data, period);
|
|
1466
|
+
const bands = [];
|
|
1467
|
+
for (let i = 0; i < sma.length; i++) {
|
|
1468
|
+
const dataSlice = data.slice(i, i + period);
|
|
1469
|
+
const mean = sma[i];
|
|
1470
|
+
const variance = dataSlice.reduce((sum2, price) => sum2 + (price - mean) ** 2, 0) / period;
|
|
1471
|
+
const standardDeviation = Math.sqrt(variance);
|
|
1472
|
+
const upper = mean + standardDeviation * stdDev;
|
|
1473
|
+
const lower = mean - standardDeviation * stdDev;
|
|
1474
|
+
bands.push({
|
|
1475
|
+
upper,
|
|
1476
|
+
middle: mean,
|
|
1477
|
+
lower,
|
|
1478
|
+
bandwidth: (upper - lower) / mean * 100,
|
|
1479
|
+
percentB: (data[i] - lower) / (upper - lower) * 100
|
|
1480
|
+
});
|
|
1481
|
+
}
|
|
1482
|
+
return bands;
|
|
1483
|
+
}
|
|
1484
|
+
/**
|
|
1485
|
+
* Calculate Average True Range (ATR)
|
|
1486
|
+
*/
|
|
1487
|
+
static calculateATR(prices, highs, lows) {
|
|
1488
|
+
if (prices.length < 2) return [];
|
|
1489
|
+
const trueRanges = [];
|
|
1490
|
+
for (let i = 1; i < prices.length; i++) {
|
|
1491
|
+
const high = highs[i] || prices[i];
|
|
1492
|
+
const low = lows[i] || prices[i];
|
|
1493
|
+
const prevClose = prices[i - 1];
|
|
1494
|
+
const tr1 = high - low;
|
|
1495
|
+
const tr2 = Math.abs(high - prevClose);
|
|
1496
|
+
const tr3 = Math.abs(low - prevClose);
|
|
1497
|
+
trueRanges.push(Math.max(tr1, tr2, tr3));
|
|
1498
|
+
}
|
|
1499
|
+
const atr = [];
|
|
1500
|
+
if (trueRanges.length >= 14) {
|
|
1501
|
+
let sum2 = trueRanges.slice(0, 14).reduce((a, b) => a + b, 0);
|
|
1502
|
+
atr.push(sum2 / 14);
|
|
1503
|
+
for (let i = 14; i < trueRanges.length; i++) {
|
|
1504
|
+
sum2 = sum2 - trueRanges[i - 14] + trueRanges[i];
|
|
1505
|
+
atr.push(sum2 / 14);
|
|
1506
|
+
}
|
|
1507
|
+
}
|
|
1508
|
+
return atr;
|
|
1509
|
+
}
|
|
1510
|
+
/**
|
|
1511
|
+
* Calculate Keltner Channels
|
|
1512
|
+
*/
|
|
1513
|
+
static calculateKeltnerChannels(prices, highs, lows) {
|
|
1514
|
+
const keltner = [];
|
|
1515
|
+
const period = 20;
|
|
1516
|
+
const multiplier = 2;
|
|
1517
|
+
if (prices.length < period) return [];
|
|
1518
|
+
const ema = MovingAverages.calculateEMA(prices, period);
|
|
1519
|
+
const atr = _VolatilityIndicators.calculateATR(prices, highs, lows);
|
|
1520
|
+
for (let i = 0; i < Math.min(ema.length, atr.length); i++) {
|
|
1521
|
+
const middle = ema[i];
|
|
1522
|
+
const atrValue = atr[i];
|
|
1523
|
+
keltner.push({
|
|
1524
|
+
upper: middle + multiplier * atrValue,
|
|
1525
|
+
middle,
|
|
1526
|
+
lower: middle - multiplier * atrValue
|
|
1527
|
+
});
|
|
1528
|
+
}
|
|
1529
|
+
return keltner;
|
|
1530
|
+
}
|
|
1531
|
+
/**
|
|
1532
|
+
* Calculate Donchian Channels
|
|
1533
|
+
*/
|
|
1534
|
+
static calculateDonchianChannels(prices) {
|
|
1535
|
+
const donchian = [];
|
|
1536
|
+
for (let i = 20; i < prices.length; i++) {
|
|
1537
|
+
const slice = prices.slice(i - 20, i);
|
|
1538
|
+
donchian.push({
|
|
1539
|
+
upper: Math.max(...slice),
|
|
1540
|
+
middle: (Math.max(...slice) + Math.min(...slice)) / 2,
|
|
1541
|
+
lower: Math.min(...slice)
|
|
1542
|
+
});
|
|
1543
|
+
}
|
|
1544
|
+
return donchian;
|
|
1545
|
+
}
|
|
1546
|
+
/**
|
|
1547
|
+
* Calculate Chaikin Volatility
|
|
1548
|
+
*/
|
|
1549
|
+
static calculateChaikinVolatility(prices, highs, lows) {
|
|
1550
|
+
const volatility = [];
|
|
1551
|
+
const period = 10;
|
|
1552
|
+
if (prices.length < period * 2) return [];
|
|
1553
|
+
const highLowRange = [];
|
|
1554
|
+
for (let i = 0; i < prices.length; i++) {
|
|
1555
|
+
const high = highs[i] || prices[i];
|
|
1556
|
+
const low = lows[i] || prices[i];
|
|
1557
|
+
highLowRange.push(high - low);
|
|
1558
|
+
}
|
|
1559
|
+
const emaRange = MovingAverages.calculateEMA(highLowRange, period);
|
|
1560
|
+
for (let i = period; i < emaRange.length; i++) {
|
|
1561
|
+
const currentEMA = emaRange[i];
|
|
1562
|
+
const pastEMA = emaRange[i - period];
|
|
1563
|
+
const volatilityValue = pastEMA !== 0 ? (currentEMA - pastEMA) / pastEMA * 100 : 0;
|
|
1564
|
+
volatility.push(volatilityValue);
|
|
1565
|
+
}
|
|
1566
|
+
return volatility;
|
|
1567
|
+
}
|
|
1568
|
+
};
|
|
1569
|
+
|
|
1570
|
+
// src/tools/indicators/volume.ts
|
|
1571
|
+
var VolumeIndicators = class {
|
|
1572
|
+
/**
|
|
1573
|
+
* Calculate On Balance Volume (OBV)
|
|
1574
|
+
*/
|
|
1575
|
+
static calculateOBV(prices, volumes) {
|
|
1576
|
+
const obv = [volumes[0]];
|
|
1577
|
+
for (let i = 1; i < prices.length; i++) {
|
|
1578
|
+
if (prices[i] > prices[i - 1]) {
|
|
1579
|
+
obv.push(obv[i - 1] + volumes[i]);
|
|
1580
|
+
} else if (prices[i] < prices[i - 1]) {
|
|
1581
|
+
obv.push(obv[i - 1] - volumes[i]);
|
|
1582
|
+
} else {
|
|
1583
|
+
obv.push(obv[i - 1]);
|
|
1584
|
+
}
|
|
1585
|
+
}
|
|
1586
|
+
return obv;
|
|
1587
|
+
}
|
|
1588
|
+
/**
|
|
1589
|
+
* Calculate Chaikin Money Flow (CMF)
|
|
1590
|
+
*/
|
|
1591
|
+
static calculateCMF(prices, highs, lows, volumes) {
|
|
1592
|
+
const cmf = [];
|
|
1593
|
+
const period = 20;
|
|
1594
|
+
if (prices.length < period) return [];
|
|
1595
|
+
for (let i = period - 1; i < prices.length; i++) {
|
|
1596
|
+
let totalMoneyFlowVolume = 0;
|
|
1597
|
+
let totalVolume = 0;
|
|
1598
|
+
for (let j = i - period + 1; j <= i; j++) {
|
|
1599
|
+
const high = highs[j] || prices[j];
|
|
1600
|
+
const low = lows[j] || prices[j];
|
|
1601
|
+
const close = prices[j];
|
|
1602
|
+
const volume = volumes[j] || 1;
|
|
1603
|
+
const moneyFlowMultiplier = (close - low - (high - close)) / (high - low);
|
|
1604
|
+
const moneyFlowVolume = moneyFlowMultiplier * volume;
|
|
1605
|
+
totalMoneyFlowVolume += moneyFlowVolume;
|
|
1606
|
+
totalVolume += volume;
|
|
1607
|
+
}
|
|
1608
|
+
const cmfValue = totalVolume !== 0 ? totalMoneyFlowVolume / totalVolume : 0;
|
|
1609
|
+
cmf.push(cmfValue);
|
|
1610
|
+
}
|
|
1611
|
+
return cmf;
|
|
1612
|
+
}
|
|
1613
|
+
/**
|
|
1614
|
+
* Calculate Accumulation/Distribution Line (ADL)
|
|
1615
|
+
*/
|
|
1616
|
+
static calculateADL(prices, highs, lows, volumes) {
|
|
1617
|
+
const adl = [0];
|
|
1618
|
+
for (let i = 1; i < prices.length; i++) {
|
|
1619
|
+
const high = highs[i] || prices[i];
|
|
1620
|
+
const low = lows[i] || prices[i];
|
|
1621
|
+
const close = prices[i];
|
|
1622
|
+
const volume = volumes[i] || 1;
|
|
1623
|
+
const moneyFlowMultiplier = (close - low - (high - close)) / (high - low);
|
|
1624
|
+
const moneyFlowVolume = moneyFlowMultiplier * volume;
|
|
1625
|
+
adl.push(adl[i - 1] + moneyFlowVolume);
|
|
1626
|
+
}
|
|
1627
|
+
return adl;
|
|
1628
|
+
}
|
|
1629
|
+
/**
|
|
1630
|
+
* Calculate Volume Rate of Change
|
|
1631
|
+
*/
|
|
1632
|
+
static calculateVolumeROC(volumes) {
|
|
1633
|
+
const volumeROC = [];
|
|
1634
|
+
for (let i = 10; i < volumes.length; i++) {
|
|
1635
|
+
volumeROC.push((volumes[i] - volumes[i - 10]) / volumes[i - 10] * 100);
|
|
1636
|
+
}
|
|
1637
|
+
return volumeROC;
|
|
1638
|
+
}
|
|
1639
|
+
/**
|
|
1640
|
+
* Calculate Money Flow Index (MFI)
|
|
1641
|
+
*/
|
|
1642
|
+
static calculateMFI(prices, highs, lows, volumes) {
|
|
1643
|
+
const mfi = [];
|
|
1644
|
+
const period = 14;
|
|
1645
|
+
if (prices.length < period + 1) return [];
|
|
1646
|
+
for (let i = period; i < prices.length; i++) {
|
|
1647
|
+
let positiveMoneyFlow = 0;
|
|
1648
|
+
let negativeMoneyFlow = 0;
|
|
1649
|
+
for (let j = i - period + 1; j <= i; j++) {
|
|
1650
|
+
const high = highs[j] || prices[j];
|
|
1651
|
+
const low = lows[j] || prices[j];
|
|
1652
|
+
const close = prices[j];
|
|
1653
|
+
const volume = volumes[j] || 1;
|
|
1654
|
+
const typicalPrice = (high + low + close) / 3;
|
|
1655
|
+
const moneyFlow = typicalPrice * volume;
|
|
1656
|
+
if (j > i - period + 1) {
|
|
1657
|
+
const prevHigh = highs[j - 1] || prices[j - 1];
|
|
1658
|
+
const prevLow = lows[j - 1] || prices[j - 1];
|
|
1659
|
+
const prevClose = prices[j - 1];
|
|
1660
|
+
const prevTypicalPrice = (prevHigh + prevLow + prevClose) / 3;
|
|
1661
|
+
if (typicalPrice > prevTypicalPrice) {
|
|
1662
|
+
positiveMoneyFlow += moneyFlow;
|
|
1663
|
+
} else if (typicalPrice < prevTypicalPrice) {
|
|
1664
|
+
negativeMoneyFlow += moneyFlow;
|
|
1665
|
+
}
|
|
1666
|
+
}
|
|
1667
|
+
}
|
|
1668
|
+
const moneyRatio = negativeMoneyFlow !== 0 ? positiveMoneyFlow / negativeMoneyFlow : 0;
|
|
1669
|
+
const mfiValue = 100 - 100 / (1 + moneyRatio);
|
|
1670
|
+
mfi.push(mfiValue);
|
|
1671
|
+
}
|
|
1672
|
+
return mfi;
|
|
1673
|
+
}
|
|
1674
|
+
/**
|
|
1675
|
+
* Calculate Volume Weighted Average Price (VWAP)
|
|
1676
|
+
*/
|
|
1677
|
+
static calculateVWAP(prices, volumes) {
|
|
1678
|
+
const vwap = [];
|
|
1679
|
+
let cumulativePV = 0;
|
|
1680
|
+
let cumulativeVolume = 0;
|
|
1681
|
+
for (let i = 0; i < prices.length; i++) {
|
|
1682
|
+
cumulativePV += prices[i] * (volumes[i] || 1);
|
|
1683
|
+
cumulativeVolume += volumes[i] || 1;
|
|
1684
|
+
vwap.push(cumulativePV / cumulativeVolume);
|
|
1685
|
+
}
|
|
1686
|
+
return vwap;
|
|
1687
|
+
}
|
|
1688
|
+
};
|
|
1689
|
+
|
|
1690
|
+
// src/tools/analytics.ts
|
|
1691
|
+
function sum(numbers) {
|
|
1692
|
+
return numbers.reduce((acc, val) => acc + val, 0);
|
|
1693
|
+
}
|
|
1694
|
+
var TechnicalAnalyzer = class {
|
|
1695
|
+
prices;
|
|
1696
|
+
volumes;
|
|
1697
|
+
highs;
|
|
1698
|
+
lows;
|
|
1699
|
+
constructor(data) {
|
|
1700
|
+
this.prices = data.map((d) => d.trade > 0 ? d.trade : d.midPrice);
|
|
1701
|
+
this.volumes = data.map((d) => d.volume);
|
|
1702
|
+
this.highs = data.map((d) => d.tradingSessionHighPrice > 0 ? d.tradingSessionHighPrice : d.trade);
|
|
1703
|
+
this.lows = data.map((d) => d.tradingSessionLowPrice > 0 ? d.tradingSessionLowPrice : d.trade);
|
|
1704
|
+
}
|
|
1705
|
+
// Calculate price changes for volatility
|
|
1706
|
+
calculatePriceChanges() {
|
|
1707
|
+
const changes = [];
|
|
1708
|
+
for (let i = 1; i < this.prices.length; i++) {
|
|
1709
|
+
changes.push((this.prices[i] - this.prices[i - 1]) / this.prices[i - 1]);
|
|
1710
|
+
}
|
|
1711
|
+
return changes;
|
|
1712
|
+
}
|
|
1713
|
+
// Generate comprehensive market analysis
|
|
1714
|
+
analyze() {
|
|
1715
|
+
const currentPrice = this.prices[this.prices.length - 1];
|
|
1716
|
+
const startPrice = this.prices[0];
|
|
1717
|
+
const sessionHigh = Math.max(...this.highs);
|
|
1718
|
+
const sessionLow = Math.min(...this.lows);
|
|
1719
|
+
const totalVolume = sum(this.volumes);
|
|
1720
|
+
const avgVolume = totalVolume / this.volumes.length;
|
|
1721
|
+
const priceChanges = this.calculatePriceChanges();
|
|
1722
|
+
const volatility = priceChanges.length > 0 ? Math.sqrt(
|
|
1723
|
+
priceChanges.reduce((sum2, change) => sum2 + change ** 2, 0) / priceChanges.length
|
|
1724
|
+
) * Math.sqrt(252) * 100 : 0;
|
|
1725
|
+
const sessionReturn = (currentPrice - startPrice) / startPrice * 100;
|
|
1726
|
+
const pricePosition = (currentPrice - sessionLow) / (sessionHigh - sessionLow) * 100;
|
|
1727
|
+
const trueVWAP = this.prices.reduce((sum2, price, i) => sum2 + price * this.volumes[i], 0) / totalVolume;
|
|
1728
|
+
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;
|
|
1729
|
+
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;
|
|
1730
|
+
const maxDrawdown = PerformanceAnalysis.calculateMaxDrawdown(this.prices);
|
|
1731
|
+
const atrValues = VolatilityIndicators.calculateATR(this.prices, this.highs, this.lows);
|
|
1732
|
+
const atr = atrValues.length > 0 ? atrValues[atrValues.length - 1] : 0;
|
|
1733
|
+
const impliedVolatility = volatility;
|
|
1734
|
+
const realizedVolatility = volatility;
|
|
1735
|
+
const sharpeRatio = sessionReturn / volatility;
|
|
1736
|
+
const sortinoRatio = sessionReturn / realizedVolatility;
|
|
1737
|
+
const calmarRatio = sessionReturn / maxDrawdown;
|
|
1738
|
+
const maxConsecutiveLosses = PerformanceAnalysis.calculateMaxConsecutiveLosses(this.prices);
|
|
1739
|
+
const winRate = PerformanceAnalysis.calculateWinRate(this.prices);
|
|
1740
|
+
const profitFactor = PerformanceAnalysis.calculateProfitFactor(this.prices);
|
|
1741
|
+
return {
|
|
1742
|
+
currentPrice,
|
|
1743
|
+
startPrice,
|
|
1744
|
+
sessionHigh,
|
|
1745
|
+
sessionLow,
|
|
1746
|
+
totalVolume,
|
|
1747
|
+
avgVolume,
|
|
1748
|
+
volatility,
|
|
1749
|
+
sessionReturn,
|
|
1750
|
+
pricePosition,
|
|
1751
|
+
trueVWAP,
|
|
1752
|
+
momentum5,
|
|
1753
|
+
momentum10,
|
|
1754
|
+
maxDrawdown,
|
|
1755
|
+
atr,
|
|
1756
|
+
impliedVolatility,
|
|
1757
|
+
realizedVolatility,
|
|
1758
|
+
sharpeRatio,
|
|
1759
|
+
sortinoRatio,
|
|
1760
|
+
calmarRatio,
|
|
1761
|
+
maxConsecutiveLosses,
|
|
1762
|
+
winRate,
|
|
1763
|
+
profitFactor
|
|
1764
|
+
};
|
|
1765
|
+
}
|
|
1766
|
+
// Generate technical indicators
|
|
1767
|
+
getTechnicalIndicators() {
|
|
1768
|
+
return {
|
|
1769
|
+
sma5: MovingAverages.calculateSMA(this.prices, 5),
|
|
1770
|
+
sma10: MovingAverages.calculateSMA(this.prices, 10),
|
|
1771
|
+
sma20: MovingAverages.calculateSMA(this.prices, 20),
|
|
1772
|
+
sma50: MovingAverages.calculateSMA(this.prices, 50),
|
|
1773
|
+
sma200: MovingAverages.calculateSMA(this.prices, 200),
|
|
1774
|
+
ema8: MovingAverages.calculateEMA(this.prices, 8),
|
|
1775
|
+
ema12: MovingAverages.calculateEMA(this.prices, 12),
|
|
1776
|
+
ema21: MovingAverages.calculateEMA(this.prices, 21),
|
|
1777
|
+
ema26: MovingAverages.calculateEMA(this.prices, 26),
|
|
1778
|
+
wma20: MovingAverages.calculateWMA(this.prices, 20),
|
|
1779
|
+
vwma20: MovingAverages.calculateVWMA(this.prices, this.volumes, 20),
|
|
1780
|
+
macd: TrendIndicators.calculateMACD(this.prices),
|
|
1781
|
+
adx: TrendIndicators.calculateADX(this.prices, this.highs, this.lows),
|
|
1782
|
+
dmi: TrendIndicators.calculateDMI(this.prices, this.highs, this.lows),
|
|
1783
|
+
ichimoku: TrendIndicators.calculateIchimoku(this.prices, this.highs, this.lows),
|
|
1784
|
+
parabolicSAR: TrendIndicators.calculateParabolicSAR(this.prices, this.highs, this.lows),
|
|
1785
|
+
rsi: MomentumIndicators.calculateRSI(this.prices, 14),
|
|
1786
|
+
stochastic: MomentumIndicators.calculateStochastic(this.prices, this.highs, this.lows),
|
|
1787
|
+
cci: MomentumIndicators.calculateCCI(this.prices, this.highs, this.lows),
|
|
1788
|
+
roc: MomentumIndicators.calculateROC(this.prices),
|
|
1789
|
+
williamsR: MomentumIndicators.calculateWilliamsR(this.prices),
|
|
1790
|
+
momentum: MomentumIndicators.calculateMomentum(this.prices),
|
|
1791
|
+
bollinger: VolatilityIndicators.calculateBollingerBands(this.prices, 20, 2),
|
|
1792
|
+
atr: VolatilityIndicators.calculateATR(this.prices, this.highs, this.lows),
|
|
1793
|
+
keltner: VolatilityIndicators.calculateKeltnerChannels(this.prices, this.highs, this.lows),
|
|
1794
|
+
donchian: VolatilityIndicators.calculateDonchianChannels(this.prices),
|
|
1795
|
+
chaikinVolatility: VolatilityIndicators.calculateChaikinVolatility(this.prices, this.highs, this.lows),
|
|
1796
|
+
obv: VolumeIndicators.calculateOBV(this.prices, this.volumes),
|
|
1797
|
+
cmf: VolumeIndicators.calculateCMF(this.prices, this.highs, this.lows, this.volumes),
|
|
1798
|
+
adl: VolumeIndicators.calculateADL(this.prices, this.highs, this.lows, this.volumes),
|
|
1799
|
+
volumeROC: VolumeIndicators.calculateVolumeROC(this.volumes),
|
|
1800
|
+
mfi: VolumeIndicators.calculateMFI(this.prices, this.highs, this.lows, this.volumes),
|
|
1801
|
+
vwap: VolumeIndicators.calculateVWAP(this.prices, this.volumes),
|
|
1802
|
+
pivotPoints: SupportResistanceIndicators.calculatePivotPoints(this.prices, this.highs, this.lows),
|
|
1803
|
+
fibonacci: SupportResistanceIndicators.calculateFibonacciLevels(this.prices),
|
|
1804
|
+
gannLevels: SupportResistanceIndicators.calculateGannLevels(this.prices),
|
|
1805
|
+
elliottWave: SupportResistanceIndicators.calculateElliottWave(this.prices),
|
|
1806
|
+
harmonicPatterns: SupportResistanceIndicators.calculateHarmonicPatterns(this.prices)
|
|
1807
|
+
};
|
|
1808
|
+
}
|
|
1809
|
+
// Generate comprehensive JSON analysis
|
|
1810
|
+
generateJSONAnalysis(symbol) {
|
|
1811
|
+
const analysis = this.analyze();
|
|
1812
|
+
const indicators = this.getTechnicalIndicators();
|
|
1813
|
+
const priceChanges = this.calculatePriceChanges();
|
|
1814
|
+
const currentSMA5 = indicators.sma5.length > 0 ? indicators.sma5[indicators.sma5.length - 1] : null;
|
|
1815
|
+
const currentSMA10 = indicators.sma10.length > 0 ? indicators.sma10[indicators.sma10.length - 1] : null;
|
|
1816
|
+
const currentSMA20 = indicators.sma20.length > 0 ? indicators.sma20[indicators.sma20.length - 1] : null;
|
|
1817
|
+
const currentSMA50 = indicators.sma50.length > 0 ? indicators.sma50[indicators.sma50.length - 1] : null;
|
|
1818
|
+
const currentSMA200 = indicators.sma200.length > 0 ? indicators.sma200[indicators.sma200.length - 1] : null;
|
|
1819
|
+
const currentEMA8 = indicators.ema8[indicators.ema8.length - 1];
|
|
1820
|
+
const currentEMA12 = indicators.ema12[indicators.ema12.length - 1];
|
|
1821
|
+
const currentEMA21 = indicators.ema21[indicators.ema21.length - 1];
|
|
1822
|
+
const currentEMA26 = indicators.ema26[indicators.ema26.length - 1];
|
|
1823
|
+
const currentWMA20 = indicators.wma20.length > 0 ? indicators.wma20[indicators.wma20.length - 1] : null;
|
|
1824
|
+
const currentVWMA20 = indicators.vwma20.length > 0 ? indicators.vwma20[indicators.vwma20.length - 1] : null;
|
|
1825
|
+
const currentMACD = indicators.macd.length > 0 ? indicators.macd[indicators.macd.length - 1] : null;
|
|
1826
|
+
const currentADX = indicators.adx.length > 0 ? indicators.adx[indicators.adx.length - 1] : null;
|
|
1827
|
+
const currentDMI = indicators.dmi.length > 0 ? indicators.dmi[indicators.dmi.length - 1] : null;
|
|
1828
|
+
const currentIchimoku = indicators.ichimoku.length > 0 ? indicators.ichimoku[indicators.ichimoku.length - 1] : null;
|
|
1829
|
+
const currentParabolicSAR = indicators.parabolicSAR.length > 0 ? indicators.parabolicSAR[indicators.parabolicSAR.length - 1] : null;
|
|
1830
|
+
const currentRSI = indicators.rsi.length > 0 ? indicators.rsi[indicators.rsi.length - 1] : null;
|
|
1831
|
+
const currentStochastic = indicators.stochastic.length > 0 ? indicators.stochastic[indicators.stochastic.length - 1] : null;
|
|
1832
|
+
const currentCCI = indicators.cci.length > 0 ? indicators.cci[indicators.cci.length - 1] : null;
|
|
1833
|
+
const currentROC = indicators.roc.length > 0 ? indicators.roc[indicators.roc.length - 1] : null;
|
|
1834
|
+
const currentWilliamsR = indicators.williamsR.length > 0 ? indicators.williamsR[indicators.williamsR.length - 1] : null;
|
|
1835
|
+
const currentMomentum = indicators.momentum.length > 0 ? indicators.momentum[indicators.momentum.length - 1] : null;
|
|
1836
|
+
const currentBB = indicators.bollinger.length > 0 ? indicators.bollinger[indicators.bollinger.length - 1] : null;
|
|
1837
|
+
const currentAtr = indicators.atr.length > 0 ? indicators.atr[indicators.atr.length - 1] : null;
|
|
1838
|
+
const currentKeltner = indicators.keltner.length > 0 ? indicators.keltner[indicators.keltner.length - 1] : null;
|
|
1839
|
+
const currentDonchian = indicators.donchian.length > 0 ? indicators.donchian[indicators.donchian.length - 1] : null;
|
|
1840
|
+
const currentChaikinVolatility = indicators.chaikinVolatility.length > 0 ? indicators.chaikinVolatility[indicators.chaikinVolatility.length - 1] : null;
|
|
1841
|
+
const currentObv = indicators.obv.length > 0 ? indicators.obv[indicators.obv.length - 1] : null;
|
|
1842
|
+
const currentCmf = indicators.cmf.length > 0 ? indicators.cmf[indicators.cmf.length - 1] : null;
|
|
1843
|
+
const currentAdl = indicators.adl.length > 0 ? indicators.adl[indicators.adl.length - 1] : null;
|
|
1844
|
+
const currentVolumeROC = indicators.volumeROC.length > 0 ? indicators.volumeROC[indicators.volumeROC.length - 1] : null;
|
|
1845
|
+
const currentMfi = indicators.mfi.length > 0 ? indicators.mfi[indicators.mfi.length - 1] : null;
|
|
1846
|
+
const currentVwap = indicators.vwap.length > 0 ? indicators.vwap[indicators.vwap.length - 1] : null;
|
|
1847
|
+
const currentPivotPoints = indicators.pivotPoints.length > 0 ? indicators.pivotPoints[indicators.pivotPoints.length - 1] : null;
|
|
1848
|
+
const currentFibonacci = indicators.fibonacci.length > 0 ? indicators.fibonacci[indicators.fibonacci.length - 1] : null;
|
|
1849
|
+
const currentGannLevels = indicators.gannLevels.length > 0 ? indicators.gannLevels : [];
|
|
1850
|
+
const currentElliottWave = indicators.elliottWave.length > 0 ? indicators.elliottWave[indicators.elliottWave.length - 1] : null;
|
|
1851
|
+
const currentHarmonicPatterns = indicators.harmonicPatterns.length > 0 ? indicators.harmonicPatterns : [];
|
|
1852
|
+
const currentVolume = this.volumes[this.volumes.length - 1];
|
|
1853
|
+
const volumeRatio = currentVolume / analysis.avgVolume;
|
|
1854
|
+
const currentDrawdown = (analysis.sessionHigh - analysis.currentPrice) / analysis.sessionHigh * 100;
|
|
1855
|
+
const rangeWidth = (analysis.sessionHigh - analysis.sessionLow) / analysis.sessionLow * 100;
|
|
1856
|
+
const priceVsVWAP = (analysis.currentPrice - analysis.trueVWAP) / analysis.trueVWAP * 100;
|
|
1857
|
+
const signalData = TradingSignalsGenerator.generateSignals(
|
|
1858
|
+
analysis.currentPrice,
|
|
1859
|
+
analysis.trueVWAP,
|
|
1860
|
+
analysis.momentum5,
|
|
1861
|
+
analysis.momentum10,
|
|
1862
|
+
analysis.sessionReturn,
|
|
1863
|
+
currentVolume,
|
|
1864
|
+
analysis.avgVolume,
|
|
1865
|
+
analysis.pricePosition,
|
|
1866
|
+
analysis.volatility
|
|
1867
|
+
);
|
|
1868
|
+
const tradingSignals = TradingSignalsGenerator.calculateOverallSignal(
|
|
1869
|
+
signalData.bullishSignals,
|
|
1870
|
+
signalData.bearishSignals,
|
|
1871
|
+
signalData.signals,
|
|
1872
|
+
analysis.volatility
|
|
1873
|
+
);
|
|
1874
|
+
const targetEntry = Math.max(analysis.sessionLow * 1.005, analysis.trueVWAP * 0.998);
|
|
1875
|
+
const stopLoss = analysis.sessionLow * 0.995;
|
|
1876
|
+
const profitTarget = analysis.sessionHigh * 0.995;
|
|
1877
|
+
const riskRewardRatio = (profitTarget - analysis.currentPrice) / (analysis.currentPrice - stopLoss);
|
|
1878
|
+
const positionSize = PerformanceAnalysis.calculatePositionSize(targetEntry, stopLoss);
|
|
1879
|
+
const maxRisk = positionSize * (targetEntry - stopLoss);
|
|
1880
|
+
return {
|
|
1881
|
+
symbol,
|
|
1882
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1883
|
+
marketStructure: {
|
|
1884
|
+
currentPrice: analysis.currentPrice,
|
|
1885
|
+
startPrice: analysis.startPrice,
|
|
1886
|
+
sessionHigh: analysis.sessionHigh,
|
|
1887
|
+
sessionLow: analysis.sessionLow,
|
|
1888
|
+
rangeWidth,
|
|
1889
|
+
totalVolume: analysis.totalVolume,
|
|
1890
|
+
sessionPerformance: analysis.sessionReturn,
|
|
1891
|
+
positionInRange: analysis.pricePosition
|
|
1892
|
+
},
|
|
1893
|
+
volatility: {
|
|
1894
|
+
impliedVolatility: analysis.impliedVolatility,
|
|
1895
|
+
realizedVolatility: analysis.realizedVolatility,
|
|
1896
|
+
atr: analysis.atr,
|
|
1897
|
+
maxDrawdown: analysis.maxDrawdown * 100,
|
|
1898
|
+
currentDrawdown
|
|
1899
|
+
},
|
|
1900
|
+
technicalIndicators: {
|
|
1901
|
+
sma5: currentSMA5,
|
|
1902
|
+
sma10: currentSMA10,
|
|
1903
|
+
sma20: currentSMA20,
|
|
1904
|
+
sma50: currentSMA50,
|
|
1905
|
+
sma200: currentSMA200,
|
|
1906
|
+
ema8: currentEMA8,
|
|
1907
|
+
ema12: currentEMA12,
|
|
1908
|
+
ema21: currentEMA21,
|
|
1909
|
+
ema26: currentEMA26,
|
|
1910
|
+
wma20: currentWMA20,
|
|
1911
|
+
vwma20: currentVWMA20,
|
|
1912
|
+
macd: currentMACD,
|
|
1913
|
+
adx: currentADX,
|
|
1914
|
+
dmi: currentDMI,
|
|
1915
|
+
ichimoku: currentIchimoku,
|
|
1916
|
+
parabolicSAR: currentParabolicSAR,
|
|
1917
|
+
rsi: currentRSI,
|
|
1918
|
+
stochastic: currentStochastic,
|
|
1919
|
+
cci: currentCCI,
|
|
1920
|
+
roc: currentROC,
|
|
1921
|
+
williamsR: currentWilliamsR,
|
|
1922
|
+
momentum: currentMomentum,
|
|
1923
|
+
bollingerBands: currentBB ? {
|
|
1924
|
+
upper: currentBB.upper,
|
|
1925
|
+
middle: currentBB.middle,
|
|
1926
|
+
lower: currentBB.lower,
|
|
1927
|
+
bandwidth: currentBB.bandwidth,
|
|
1928
|
+
percentB: currentBB.percentB
|
|
1929
|
+
} : null,
|
|
1930
|
+
atr: currentAtr,
|
|
1931
|
+
keltnerChannels: currentKeltner ? {
|
|
1932
|
+
upper: currentKeltner.upper,
|
|
1933
|
+
middle: currentKeltner.middle,
|
|
1934
|
+
lower: currentKeltner.lower
|
|
1935
|
+
} : null,
|
|
1936
|
+
donchianChannels: currentDonchian ? {
|
|
1937
|
+
upper: currentDonchian.upper,
|
|
1938
|
+
middle: currentDonchian.middle,
|
|
1939
|
+
lower: currentDonchian.lower
|
|
1940
|
+
} : null,
|
|
1941
|
+
chaikinVolatility: currentChaikinVolatility,
|
|
1942
|
+
obv: currentObv,
|
|
1943
|
+
cmf: currentCmf,
|
|
1944
|
+
adl: currentAdl,
|
|
1945
|
+
volumeROC: currentVolumeROC,
|
|
1946
|
+
mfi: currentMfi,
|
|
1947
|
+
vwap: currentVwap
|
|
1948
|
+
},
|
|
1949
|
+
volumeAnalysis: {
|
|
1950
|
+
currentVolume,
|
|
1951
|
+
averageVolume: Math.round(analysis.avgVolume),
|
|
1952
|
+
volumeRatio,
|
|
1953
|
+
trueVWAP: analysis.trueVWAP,
|
|
1954
|
+
priceVsVWAP,
|
|
1955
|
+
obv: currentObv,
|
|
1956
|
+
cmf: currentCmf,
|
|
1957
|
+
mfi: currentMfi
|
|
1958
|
+
},
|
|
1959
|
+
momentum: {
|
|
1960
|
+
momentum5: analysis.momentum5,
|
|
1961
|
+
momentum10: analysis.momentum10,
|
|
1962
|
+
sessionROC: analysis.sessionReturn,
|
|
1963
|
+
rsi: currentRSI,
|
|
1964
|
+
stochastic: currentStochastic,
|
|
1965
|
+
cci: currentCCI
|
|
1966
|
+
},
|
|
1967
|
+
supportResistance: {
|
|
1968
|
+
pivotPoints: currentPivotPoints,
|
|
1969
|
+
fibonacci: currentFibonacci,
|
|
1970
|
+
gannLevels: currentGannLevels,
|
|
1971
|
+
elliottWave: currentElliottWave,
|
|
1972
|
+
harmonicPatterns: currentHarmonicPatterns
|
|
1973
|
+
},
|
|
1974
|
+
tradingSignals,
|
|
1975
|
+
statisticalModels: {
|
|
1976
|
+
zScore: StatisticalModels.calculateZScore(analysis.currentPrice, analysis.startPrice),
|
|
1977
|
+
ornsteinUhlenbeck: StatisticalModels.calculateOrnsteinUhlenbeck(
|
|
1978
|
+
analysis.currentPrice,
|
|
1979
|
+
analysis.startPrice,
|
|
1980
|
+
analysis.avgVolume,
|
|
1981
|
+
priceChanges
|
|
1982
|
+
),
|
|
1983
|
+
kalmanFilter: StatisticalModels.calculateKalmanFilter(
|
|
1984
|
+
analysis.currentPrice,
|
|
1985
|
+
analysis.startPrice,
|
|
1986
|
+
analysis.avgVolume,
|
|
1987
|
+
priceChanges
|
|
1988
|
+
),
|
|
1989
|
+
arima: StatisticalModels.calculateARIMA(analysis.currentPrice, priceChanges),
|
|
1990
|
+
garch: StatisticalModels.calculateGARCH(analysis.avgVolume, priceChanges),
|
|
1991
|
+
hilbertTransform: StatisticalModels.calculateHilbertTransform(analysis.currentPrice, priceChanges),
|
|
1992
|
+
waveletTransform: StatisticalModels.calculateWaveletTransform(analysis.currentPrice, priceChanges)
|
|
1993
|
+
},
|
|
1994
|
+
optionsAnalysis: (() => {
|
|
1995
|
+
const blackScholes = OptionsAnalysis.calculateBlackScholes(
|
|
1996
|
+
analysis.currentPrice,
|
|
1997
|
+
analysis.startPrice,
|
|
1998
|
+
analysis.avgVolume
|
|
1999
|
+
);
|
|
2000
|
+
if (!blackScholes) return null;
|
|
2001
|
+
return {
|
|
2002
|
+
blackScholes,
|
|
2003
|
+
impliedVolatility: analysis.impliedVolatility,
|
|
2004
|
+
delta: blackScholes.delta,
|
|
2005
|
+
gamma: blackScholes.gamma,
|
|
2006
|
+
theta: blackScholes.theta,
|
|
2007
|
+
vega: blackScholes.vega,
|
|
2008
|
+
rho: blackScholes.rho,
|
|
2009
|
+
greeks: {
|
|
2010
|
+
delta: blackScholes.delta,
|
|
2011
|
+
gamma: blackScholes.gamma,
|
|
2012
|
+
theta: blackScholes.theta,
|
|
2013
|
+
vega: blackScholes.vega,
|
|
2014
|
+
rho: blackScholes.rho
|
|
2015
|
+
}
|
|
2016
|
+
};
|
|
2017
|
+
})(),
|
|
2018
|
+
riskManagement: {
|
|
2019
|
+
targetEntry,
|
|
2020
|
+
stopLoss,
|
|
2021
|
+
profitTarget,
|
|
2022
|
+
riskRewardRatio,
|
|
2023
|
+
positionSize,
|
|
2024
|
+
maxRisk
|
|
2025
|
+
},
|
|
2026
|
+
performance: {
|
|
2027
|
+
sharpeRatio: analysis.sharpeRatio,
|
|
2028
|
+
sortinoRatio: analysis.sortinoRatio,
|
|
2029
|
+
calmarRatio: analysis.calmarRatio,
|
|
2030
|
+
maxDrawdown: analysis.maxDrawdown * 100,
|
|
2031
|
+
winRate: analysis.winRate,
|
|
2032
|
+
profitFactor: analysis.profitFactor,
|
|
2033
|
+
totalReturn: analysis.sessionReturn,
|
|
2034
|
+
volatility: analysis.volatility
|
|
2035
|
+
}
|
|
2036
|
+
};
|
|
2037
|
+
}
|
|
2038
|
+
};
|
|
2039
|
+
var createTechnicalAnalysisHandler = (marketDataPrices) => {
|
|
2040
|
+
return async (args) => {
|
|
2041
|
+
try {
|
|
2042
|
+
const symbol = args.symbol;
|
|
2043
|
+
const priceHistory = marketDataPrices.get(symbol) || [];
|
|
2044
|
+
if (priceHistory.length === 0) {
|
|
2045
|
+
return {
|
|
2046
|
+
content: [
|
|
2047
|
+
{
|
|
2048
|
+
type: "text",
|
|
2049
|
+
text: `No price data available for ${symbol}. Please request market data first.`,
|
|
2050
|
+
uri: "technicalAnalysis"
|
|
2051
|
+
}
|
|
2052
|
+
]
|
|
2053
|
+
};
|
|
2054
|
+
}
|
|
2055
|
+
const hasValidData = priceHistory.every(
|
|
2056
|
+
(entry) => typeof entry.trade === "number" && !Number.isNaN(entry.trade) && typeof entry.midPrice === "number" && !Number.isNaN(entry.midPrice)
|
|
2057
|
+
);
|
|
2058
|
+
if (!hasValidData) {
|
|
2059
|
+
throw new Error("Invalid market data");
|
|
2060
|
+
}
|
|
2061
|
+
const analyzer = new TechnicalAnalyzer(priceHistory);
|
|
2062
|
+
const analysis = analyzer.generateJSONAnalysis(symbol);
|
|
2063
|
+
return {
|
|
2064
|
+
content: [
|
|
2065
|
+
{
|
|
2066
|
+
type: "text",
|
|
2067
|
+
text: `Technical Analysis for ${symbol}:
|
|
2068
|
+
|
|
2069
|
+
${JSON.stringify(analysis, null, 2)}`,
|
|
2070
|
+
uri: "technicalAnalysis"
|
|
2071
|
+
}
|
|
2072
|
+
]
|
|
2073
|
+
};
|
|
2074
|
+
} catch (error) {
|
|
2075
|
+
return {
|
|
2076
|
+
content: [
|
|
2077
|
+
{
|
|
2078
|
+
type: "text",
|
|
2079
|
+
text: `Error performing technical analysis: ${error instanceof Error ? error.message : "Unknown error"}`,
|
|
2080
|
+
uri: "technicalAnalysis"
|
|
2081
|
+
}
|
|
2082
|
+
],
|
|
2083
|
+
isError: true
|
|
2084
|
+
};
|
|
2085
|
+
}
|
|
2086
|
+
};
|
|
2087
|
+
};
|
|
2088
|
+
|
|
271
2089
|
// src/tools/marketData.ts
|
|
272
2090
|
var import_fixparser = require("fixparser");
|
|
273
2091
|
var import_quickchart_js = __toESM(require("quickchart-js"), 1);
|
|
274
2092
|
var createMarketDataRequestHandler = (parser, pendingRequests) => {
|
|
275
2093
|
return async (args) => {
|
|
276
2094
|
try {
|
|
2095
|
+
parser.logger.log({
|
|
2096
|
+
level: "info",
|
|
2097
|
+
message: `Sending market data request for symbols: ${args.symbols.join(", ")}`
|
|
2098
|
+
});
|
|
277
2099
|
const response = new Promise((resolve) => {
|
|
278
2100
|
pendingRequests.set(args.mdReqID, resolve);
|
|
2101
|
+
parser.logger.log({
|
|
2102
|
+
level: "info",
|
|
2103
|
+
message: `Registered callback for market data request ID: ${args.mdReqID}`
|
|
2104
|
+
});
|
|
279
2105
|
});
|
|
280
|
-
const entryTypes = args.mdEntryTypes || [
|
|
2106
|
+
const entryTypes = args.mdEntryTypes || [
|
|
2107
|
+
import_fixparser.MDEntryType.Bid,
|
|
2108
|
+
import_fixparser.MDEntryType.Offer,
|
|
2109
|
+
import_fixparser.MDEntryType.Trade,
|
|
2110
|
+
import_fixparser.MDEntryType.IndexValue,
|
|
2111
|
+
import_fixparser.MDEntryType.OpeningPrice,
|
|
2112
|
+
import_fixparser.MDEntryType.ClosingPrice,
|
|
2113
|
+
import_fixparser.MDEntryType.SettlementPrice,
|
|
2114
|
+
import_fixparser.MDEntryType.TradingSessionHighPrice,
|
|
2115
|
+
import_fixparser.MDEntryType.TradingSessionLowPrice,
|
|
2116
|
+
import_fixparser.MDEntryType.VWAP,
|
|
2117
|
+
import_fixparser.MDEntryType.Imbalance,
|
|
2118
|
+
import_fixparser.MDEntryType.TradeVolume,
|
|
2119
|
+
import_fixparser.MDEntryType.OpenInterest,
|
|
2120
|
+
import_fixparser.MDEntryType.CompositeUnderlyingPrice,
|
|
2121
|
+
import_fixparser.MDEntryType.SimulatedSellPrice,
|
|
2122
|
+
import_fixparser.MDEntryType.SimulatedBuyPrice,
|
|
2123
|
+
import_fixparser.MDEntryType.MarginRate,
|
|
2124
|
+
import_fixparser.MDEntryType.MidPrice,
|
|
2125
|
+
import_fixparser.MDEntryType.EmptyBook,
|
|
2126
|
+
import_fixparser.MDEntryType.SettleHighPrice,
|
|
2127
|
+
import_fixparser.MDEntryType.SettleLowPrice,
|
|
2128
|
+
import_fixparser.MDEntryType.PriorSettlePrice,
|
|
2129
|
+
import_fixparser.MDEntryType.SessionHighBid,
|
|
2130
|
+
import_fixparser.MDEntryType.SessionLowOffer,
|
|
2131
|
+
import_fixparser.MDEntryType.EarlyPrices,
|
|
2132
|
+
import_fixparser.MDEntryType.AuctionClearingPrice,
|
|
2133
|
+
import_fixparser.MDEntryType.SwapValueFactor,
|
|
2134
|
+
import_fixparser.MDEntryType.DailyValueAdjustmentForLongPositions,
|
|
2135
|
+
import_fixparser.MDEntryType.CumulativeValueAdjustmentForLongPositions,
|
|
2136
|
+
import_fixparser.MDEntryType.DailyValueAdjustmentForShortPositions,
|
|
2137
|
+
import_fixparser.MDEntryType.CumulativeValueAdjustmentForShortPositions,
|
|
2138
|
+
import_fixparser.MDEntryType.FixingPrice,
|
|
2139
|
+
import_fixparser.MDEntryType.CashRate,
|
|
2140
|
+
import_fixparser.MDEntryType.RecoveryRate,
|
|
2141
|
+
import_fixparser.MDEntryType.RecoveryRateForLong,
|
|
2142
|
+
import_fixparser.MDEntryType.RecoveryRateForShort,
|
|
2143
|
+
import_fixparser.MDEntryType.MarketBid,
|
|
2144
|
+
import_fixparser.MDEntryType.MarketOffer,
|
|
2145
|
+
import_fixparser.MDEntryType.ShortSaleMinPrice,
|
|
2146
|
+
import_fixparser.MDEntryType.PreviousClosingPrice,
|
|
2147
|
+
import_fixparser.MDEntryType.ThresholdLimitPriceBanding,
|
|
2148
|
+
import_fixparser.MDEntryType.DailyFinancingValue,
|
|
2149
|
+
import_fixparser.MDEntryType.AccruedFinancingValue,
|
|
2150
|
+
import_fixparser.MDEntryType.TWAP
|
|
2151
|
+
];
|
|
281
2152
|
const messageFields = [
|
|
282
2153
|
new import_fixparser.Field(import_fixparser.Fields.MsgType, import_fixparser.Messages.MarketDataRequest),
|
|
283
2154
|
new import_fixparser.Field(import_fixparser.Fields.SenderCompID, parser.sender),
|
|
@@ -299,6 +2170,10 @@ var createMarketDataRequestHandler = (parser, pendingRequests) => {
|
|
|
299
2170
|
});
|
|
300
2171
|
const mdr = parser.createMessage(...messageFields);
|
|
301
2172
|
if (!parser.connected) {
|
|
2173
|
+
parser.logger.log({
|
|
2174
|
+
level: "error",
|
|
2175
|
+
message: "Not connected. Cannot send market data request."
|
|
2176
|
+
});
|
|
302
2177
|
return {
|
|
303
2178
|
content: [
|
|
304
2179
|
{
|
|
@@ -310,8 +2185,16 @@ var createMarketDataRequestHandler = (parser, pendingRequests) => {
|
|
|
310
2185
|
isError: true
|
|
311
2186
|
};
|
|
312
2187
|
}
|
|
2188
|
+
parser.logger.log({
|
|
2189
|
+
level: "info",
|
|
2190
|
+
message: `Sending market data request message: ${JSON.stringify(mdr?.toFIXJSON())}`
|
|
2191
|
+
});
|
|
313
2192
|
parser.send(mdr);
|
|
314
2193
|
const fixData = await response;
|
|
2194
|
+
parser.logger.log({
|
|
2195
|
+
level: "info",
|
|
2196
|
+
message: `Received market data response for request ID: ${args.mdReqID}`
|
|
2197
|
+
});
|
|
315
2198
|
return {
|
|
316
2199
|
content: [
|
|
317
2200
|
{
|
|
@@ -335,6 +2218,72 @@ var createMarketDataRequestHandler = (parser, pendingRequests) => {
|
|
|
335
2218
|
}
|
|
336
2219
|
};
|
|
337
2220
|
};
|
|
2221
|
+
var aggregateMarketData = (priceHistory, maxPoints = 490) => {
|
|
2222
|
+
if (priceHistory.length <= maxPoints) {
|
|
2223
|
+
return priceHistory;
|
|
2224
|
+
}
|
|
2225
|
+
const result = [];
|
|
2226
|
+
const step = priceHistory.length / maxPoints;
|
|
2227
|
+
result.push(priceHistory[0]);
|
|
2228
|
+
for (let i = 1; i < maxPoints - 1; i++) {
|
|
2229
|
+
const startIndex = Math.floor(i * step);
|
|
2230
|
+
const endIndex = Math.floor((i + 1) * step);
|
|
2231
|
+
const segment = priceHistory.slice(startIndex, endIndex);
|
|
2232
|
+
if (segment.length === 0) continue;
|
|
2233
|
+
const aggregatedPoint = {
|
|
2234
|
+
timestamp: segment[0].timestamp,
|
|
2235
|
+
// Use timestamp of first point in segment
|
|
2236
|
+
bid: segment.reduce((sum2, p) => sum2 + p.bid, 0) / segment.length,
|
|
2237
|
+
offer: segment.reduce((sum2, p) => sum2 + p.offer, 0) / segment.length,
|
|
2238
|
+
spread: segment.reduce((sum2, p) => sum2 + p.spread, 0) / segment.length,
|
|
2239
|
+
volume: segment.reduce((sum2, p) => sum2 + p.volume, 0) / segment.length,
|
|
2240
|
+
trade: segment.reduce((sum2, p) => sum2 + p.trade, 0) / segment.length,
|
|
2241
|
+
indexValue: segment.reduce((sum2, p) => sum2 + p.indexValue, 0) / segment.length,
|
|
2242
|
+
openingPrice: segment.reduce((sum2, p) => sum2 + p.openingPrice, 0) / segment.length,
|
|
2243
|
+
closingPrice: segment.reduce((sum2, p) => sum2 + p.closingPrice, 0) / segment.length,
|
|
2244
|
+
settlementPrice: segment.reduce((sum2, p) => sum2 + p.settlementPrice, 0) / segment.length,
|
|
2245
|
+
tradingSessionHighPrice: segment.reduce((sum2, p) => sum2 + p.tradingSessionHighPrice, 0) / segment.length,
|
|
2246
|
+
tradingSessionLowPrice: segment.reduce((sum2, p) => sum2 + p.tradingSessionLowPrice, 0) / segment.length,
|
|
2247
|
+
vwap: segment.reduce((sum2, p) => sum2 + p.vwap, 0) / segment.length,
|
|
2248
|
+
imbalance: segment.reduce((sum2, p) => sum2 + p.imbalance, 0) / segment.length,
|
|
2249
|
+
openInterest: segment.reduce((sum2, p) => sum2 + p.openInterest, 0) / segment.length,
|
|
2250
|
+
compositeUnderlyingPrice: segment.reduce((sum2, p) => sum2 + p.compositeUnderlyingPrice, 0) / segment.length,
|
|
2251
|
+
simulatedSellPrice: segment.reduce((sum2, p) => sum2 + p.simulatedSellPrice, 0) / segment.length,
|
|
2252
|
+
simulatedBuyPrice: segment.reduce((sum2, p) => sum2 + p.simulatedBuyPrice, 0) / segment.length,
|
|
2253
|
+
marginRate: segment.reduce((sum2, p) => sum2 + p.marginRate, 0) / segment.length,
|
|
2254
|
+
midPrice: segment.reduce((sum2, p) => sum2 + p.midPrice, 0) / segment.length,
|
|
2255
|
+
emptyBook: segment.reduce((sum2, p) => sum2 + p.emptyBook, 0) / segment.length,
|
|
2256
|
+
settleHighPrice: segment.reduce((sum2, p) => sum2 + p.settleHighPrice, 0) / segment.length,
|
|
2257
|
+
settleLowPrice: segment.reduce((sum2, p) => sum2 + p.settleLowPrice, 0) / segment.length,
|
|
2258
|
+
priorSettlePrice: segment.reduce((sum2, p) => sum2 + p.priorSettlePrice, 0) / segment.length,
|
|
2259
|
+
sessionHighBid: segment.reduce((sum2, p) => sum2 + p.sessionHighBid, 0) / segment.length,
|
|
2260
|
+
sessionLowOffer: segment.reduce((sum2, p) => sum2 + p.sessionLowOffer, 0) / segment.length,
|
|
2261
|
+
earlyPrices: segment.reduce((sum2, p) => sum2 + p.earlyPrices, 0) / segment.length,
|
|
2262
|
+
auctionClearingPrice: segment.reduce((sum2, p) => sum2 + p.auctionClearingPrice, 0) / segment.length,
|
|
2263
|
+
swapValueFactor: segment.reduce((sum2, p) => sum2 + p.swapValueFactor, 0) / segment.length,
|
|
2264
|
+
dailyValueAdjustmentForLongPositions: segment.reduce((sum2, p) => sum2 + p.dailyValueAdjustmentForLongPositions, 0) / segment.length,
|
|
2265
|
+
cumulativeValueAdjustmentForLongPositions: segment.reduce((sum2, p) => sum2 + p.cumulativeValueAdjustmentForLongPositions, 0) / segment.length,
|
|
2266
|
+
dailyValueAdjustmentForShortPositions: segment.reduce((sum2, p) => sum2 + p.dailyValueAdjustmentForShortPositions, 0) / segment.length,
|
|
2267
|
+
cumulativeValueAdjustmentForShortPositions: segment.reduce((sum2, p) => sum2 + p.cumulativeValueAdjustmentForShortPositions, 0) / segment.length,
|
|
2268
|
+
fixingPrice: segment.reduce((sum2, p) => sum2 + p.fixingPrice, 0) / segment.length,
|
|
2269
|
+
cashRate: segment.reduce((sum2, p) => sum2 + p.cashRate, 0) / segment.length,
|
|
2270
|
+
recoveryRate: segment.reduce((sum2, p) => sum2 + p.recoveryRate, 0) / segment.length,
|
|
2271
|
+
recoveryRateForLong: segment.reduce((sum2, p) => sum2 + p.recoveryRateForLong, 0) / segment.length,
|
|
2272
|
+
recoveryRateForShort: segment.reduce((sum2, p) => sum2 + p.recoveryRateForShort, 0) / segment.length,
|
|
2273
|
+
marketBid: segment.reduce((sum2, p) => sum2 + p.marketBid, 0) / segment.length,
|
|
2274
|
+
marketOffer: segment.reduce((sum2, p) => sum2 + p.marketOffer, 0) / segment.length,
|
|
2275
|
+
shortSaleMinPrice: segment.reduce((sum2, p) => sum2 + p.shortSaleMinPrice, 0) / segment.length,
|
|
2276
|
+
previousClosingPrice: segment.reduce((sum2, p) => sum2 + p.previousClosingPrice, 0) / segment.length,
|
|
2277
|
+
thresholdLimitPriceBanding: segment.reduce((sum2, p) => sum2 + p.thresholdLimitPriceBanding, 0) / segment.length,
|
|
2278
|
+
dailyFinancingValue: segment.reduce((sum2, p) => sum2 + p.dailyFinancingValue, 0) / segment.length,
|
|
2279
|
+
accruedFinancingValue: segment.reduce((sum2, p) => sum2 + p.accruedFinancingValue, 0) / segment.length,
|
|
2280
|
+
twap: segment.reduce((sum2, p) => sum2 + p.twap, 0) / segment.length
|
|
2281
|
+
};
|
|
2282
|
+
result.push(aggregatedPoint);
|
|
2283
|
+
}
|
|
2284
|
+
result.push(priceHistory[priceHistory.length - 1]);
|
|
2285
|
+
return result;
|
|
2286
|
+
};
|
|
338
2287
|
var createGetStockGraphHandler = (marketDataPrices) => {
|
|
339
2288
|
return async (args) => {
|
|
340
2289
|
try {
|
|
@@ -351,14 +2300,22 @@ var createGetStockGraphHandler = (marketDataPrices) => {
|
|
|
351
2300
|
]
|
|
352
2301
|
};
|
|
353
2302
|
}
|
|
2303
|
+
const aggregatedData = aggregateMarketData(priceHistory, 500);
|
|
354
2304
|
const chart = new import_quickchart_js.default();
|
|
355
|
-
chart.setWidth(
|
|
356
|
-
chart.setHeight(
|
|
357
|
-
|
|
358
|
-
const
|
|
359
|
-
const
|
|
360
|
-
const
|
|
361
|
-
const
|
|
2305
|
+
chart.setWidth(1200);
|
|
2306
|
+
chart.setHeight(600);
|
|
2307
|
+
chart.setBackgroundColor("transparent");
|
|
2308
|
+
const labels = aggregatedData.map((point) => new Date(point.timestamp).toLocaleTimeString());
|
|
2309
|
+
const bidData = aggregatedData.map((point) => point.bid);
|
|
2310
|
+
const offerData = aggregatedData.map((point) => point.offer);
|
|
2311
|
+
const spreadData = aggregatedData.map((point) => point.spread);
|
|
2312
|
+
const volumeData = aggregatedData.map((point) => point.volume);
|
|
2313
|
+
const tradeData = aggregatedData.map((point) => point.trade);
|
|
2314
|
+
const vwapData = aggregatedData.map((point) => point.vwap);
|
|
2315
|
+
const twapData = aggregatedData.map((point) => point.twap);
|
|
2316
|
+
const maxVolume = Math.max(...volumeData.filter((v) => v > 0));
|
|
2317
|
+
const maxPrice = Math.max(...bidData, ...offerData, ...tradeData, ...vwapData, ...twapData);
|
|
2318
|
+
const normalizedVolumeData = volumeData.map((v) => v / maxVolume * maxPrice * 0.3);
|
|
362
2319
|
const config = {
|
|
363
2320
|
type: "line",
|
|
364
2321
|
data: {
|
|
@@ -389,8 +2346,32 @@ var createGetStockGraphHandler = (marketDataPrices) => {
|
|
|
389
2346
|
tension: 0.4
|
|
390
2347
|
},
|
|
391
2348
|
{
|
|
392
|
-
label: "
|
|
393
|
-
data:
|
|
2349
|
+
label: "Trade",
|
|
2350
|
+
data: tradeData,
|
|
2351
|
+
borderColor: "#ffc107",
|
|
2352
|
+
backgroundColor: "rgba(255, 193, 7, 0.1)",
|
|
2353
|
+
fill: false,
|
|
2354
|
+
tension: 0.4
|
|
2355
|
+
},
|
|
2356
|
+
{
|
|
2357
|
+
label: "VWAP",
|
|
2358
|
+
data: vwapData,
|
|
2359
|
+
borderColor: "#17a2b8",
|
|
2360
|
+
backgroundColor: "rgba(23, 162, 184, 0.1)",
|
|
2361
|
+
fill: false,
|
|
2362
|
+
tension: 0.4
|
|
2363
|
+
},
|
|
2364
|
+
{
|
|
2365
|
+
label: "TWAP",
|
|
2366
|
+
data: twapData,
|
|
2367
|
+
borderColor: "#6610f2",
|
|
2368
|
+
backgroundColor: "rgba(102, 16, 242, 0.1)",
|
|
2369
|
+
fill: false,
|
|
2370
|
+
tension: 0.4
|
|
2371
|
+
},
|
|
2372
|
+
{
|
|
2373
|
+
label: "Volume (Normalized)",
|
|
2374
|
+
data: normalizedVolumeData,
|
|
394
2375
|
borderColor: "#007bff",
|
|
395
2376
|
backgroundColor: "rgba(0, 123, 255, 0.1)",
|
|
396
2377
|
fill: true,
|
|
@@ -403,36 +2384,33 @@ var createGetStockGraphHandler = (marketDataPrices) => {
|
|
|
403
2384
|
plugins: {
|
|
404
2385
|
title: {
|
|
405
2386
|
display: true,
|
|
406
|
-
text: `${symbol} Market Data`
|
|
2387
|
+
text: `${symbol} Market Data (Volume normalized to 30% of max price)`
|
|
407
2388
|
}
|
|
408
2389
|
},
|
|
409
2390
|
scales: {
|
|
410
2391
|
y: {
|
|
411
|
-
beginAtZero: false
|
|
2392
|
+
beginAtZero: false,
|
|
2393
|
+
title: {
|
|
2394
|
+
display: true,
|
|
2395
|
+
text: "Price / Normalized Volume"
|
|
2396
|
+
}
|
|
412
2397
|
}
|
|
413
2398
|
}
|
|
414
2399
|
}
|
|
415
2400
|
};
|
|
416
2401
|
chart.setConfig(config);
|
|
417
2402
|
const imageBuffer = await chart.toBinary();
|
|
418
|
-
const
|
|
2403
|
+
const base64 = imageBuffer.toString("base64");
|
|
419
2404
|
return {
|
|
420
2405
|
content: [
|
|
421
2406
|
{
|
|
422
|
-
type: "
|
|
423
|
-
|
|
424
|
-
|
|
2407
|
+
type: "resource",
|
|
2408
|
+
resource: {
|
|
2409
|
+
uri: "resource://graph",
|
|
2410
|
+
mimeType: "image/png",
|
|
2411
|
+
blob: base64
|
|
2412
|
+
}
|
|
425
2413
|
}
|
|
426
|
-
// {
|
|
427
|
-
// type: 'image',
|
|
428
|
-
// image: {
|
|
429
|
-
// source: {
|
|
430
|
-
// filename: 'graph.png',
|
|
431
|
-
// data: `data:image/png;base64,${base64Image}`,
|
|
432
|
-
// },
|
|
433
|
-
// },
|
|
434
|
-
// mimeType: 'image/png',
|
|
435
|
-
// },
|
|
436
2414
|
]
|
|
437
2415
|
};
|
|
438
2416
|
} catch (error) {
|
|
@@ -440,7 +2418,7 @@ var createGetStockGraphHandler = (marketDataPrices) => {
|
|
|
440
2418
|
content: [
|
|
441
2419
|
{
|
|
442
2420
|
type: "text",
|
|
443
|
-
text: `Error: ${error instanceof Error ? error.message : "Failed to generate
|
|
2421
|
+
text: `Error: ${error instanceof Error ? error.message : "Failed to generate graph"}`,
|
|
444
2422
|
uri: "getStockGraph"
|
|
445
2423
|
}
|
|
446
2424
|
],
|
|
@@ -465,6 +2443,7 @@ var createGetStockPriceHistoryHandler = (marketDataPrices) => {
|
|
|
465
2443
|
]
|
|
466
2444
|
};
|
|
467
2445
|
}
|
|
2446
|
+
const aggregatedData = aggregateMarketData(priceHistory, 500);
|
|
468
2447
|
return {
|
|
469
2448
|
content: [
|
|
470
2449
|
{
|
|
@@ -472,13 +2451,55 @@ var createGetStockPriceHistoryHandler = (marketDataPrices) => {
|
|
|
472
2451
|
text: JSON.stringify(
|
|
473
2452
|
{
|
|
474
2453
|
symbol,
|
|
475
|
-
count:
|
|
476
|
-
|
|
2454
|
+
count: aggregatedData.length,
|
|
2455
|
+
originalCount: priceHistory.length,
|
|
2456
|
+
data: aggregatedData.map((point) => ({
|
|
477
2457
|
timestamp: new Date(point.timestamp).toISOString(),
|
|
478
2458
|
bid: point.bid,
|
|
479
2459
|
offer: point.offer,
|
|
480
2460
|
spread: point.spread,
|
|
481
|
-
volume: point.volume
|
|
2461
|
+
volume: point.volume,
|
|
2462
|
+
trade: point.trade,
|
|
2463
|
+
indexValue: point.indexValue,
|
|
2464
|
+
openingPrice: point.openingPrice,
|
|
2465
|
+
closingPrice: point.closingPrice,
|
|
2466
|
+
settlementPrice: point.settlementPrice,
|
|
2467
|
+
tradingSessionHighPrice: point.tradingSessionHighPrice,
|
|
2468
|
+
tradingSessionLowPrice: point.tradingSessionLowPrice,
|
|
2469
|
+
vwap: point.vwap,
|
|
2470
|
+
imbalance: point.imbalance,
|
|
2471
|
+
openInterest: point.openInterest,
|
|
2472
|
+
compositeUnderlyingPrice: point.compositeUnderlyingPrice,
|
|
2473
|
+
simulatedSellPrice: point.simulatedSellPrice,
|
|
2474
|
+
simulatedBuyPrice: point.simulatedBuyPrice,
|
|
2475
|
+
marginRate: point.marginRate,
|
|
2476
|
+
midPrice: point.midPrice,
|
|
2477
|
+
emptyBook: point.emptyBook,
|
|
2478
|
+
settleHighPrice: point.settleHighPrice,
|
|
2479
|
+
settleLowPrice: point.settleLowPrice,
|
|
2480
|
+
priorSettlePrice: point.priorSettlePrice,
|
|
2481
|
+
sessionHighBid: point.sessionHighBid,
|
|
2482
|
+
sessionLowOffer: point.sessionLowOffer,
|
|
2483
|
+
earlyPrices: point.earlyPrices,
|
|
2484
|
+
auctionClearingPrice: point.auctionClearingPrice,
|
|
2485
|
+
swapValueFactor: point.swapValueFactor,
|
|
2486
|
+
dailyValueAdjustmentForLongPositions: point.dailyValueAdjustmentForLongPositions,
|
|
2487
|
+
cumulativeValueAdjustmentForLongPositions: point.cumulativeValueAdjustmentForLongPositions,
|
|
2488
|
+
dailyValueAdjustmentForShortPositions: point.dailyValueAdjustmentForShortPositions,
|
|
2489
|
+
cumulativeValueAdjustmentForShortPositions: point.cumulativeValueAdjustmentForShortPositions,
|
|
2490
|
+
fixingPrice: point.fixingPrice,
|
|
2491
|
+
cashRate: point.cashRate,
|
|
2492
|
+
recoveryRate: point.recoveryRate,
|
|
2493
|
+
recoveryRateForLong: point.recoveryRateForLong,
|
|
2494
|
+
recoveryRateForShort: point.recoveryRateForShort,
|
|
2495
|
+
marketBid: point.marketBid,
|
|
2496
|
+
marketOffer: point.marketOffer,
|
|
2497
|
+
shortSaleMinPrice: point.shortSaleMinPrice,
|
|
2498
|
+
previousClosingPrice: point.previousClosingPrice,
|
|
2499
|
+
thresholdLimitPriceBanding: point.thresholdLimitPriceBanding,
|
|
2500
|
+
dailyFinancingValue: point.dailyFinancingValue,
|
|
2501
|
+
accruedFinancingValue: point.accruedFinancingValue,
|
|
2502
|
+
twap: point.twap
|
|
482
2503
|
}))
|
|
483
2504
|
},
|
|
484
2505
|
null,
|
|
@@ -493,7 +2514,7 @@ var createGetStockPriceHistoryHandler = (marketDataPrices) => {
|
|
|
493
2514
|
content: [
|
|
494
2515
|
{
|
|
495
2516
|
type: "text",
|
|
496
|
-
text: `Error: ${error instanceof Error ? error.message : "Failed to get
|
|
2517
|
+
text: `Error: ${error instanceof Error ? error.message : "Failed to get price history"}`,
|
|
497
2518
|
uri: "getStockPriceHistory"
|
|
498
2519
|
}
|
|
499
2520
|
],
|
|
@@ -574,6 +2595,7 @@ var handlInstNames = {
|
|
|
574
2595
|
};
|
|
575
2596
|
var createVerifyOrderHandler = (parser, verifiedOrders) => {
|
|
576
2597
|
return async (args) => {
|
|
2598
|
+
void parser;
|
|
577
2599
|
try {
|
|
578
2600
|
verifiedOrders.set(args.clOrdID, {
|
|
579
2601
|
clOrdID: args.clOrdID,
|
|
@@ -601,7 +2623,7 @@ Parameters verified:
|
|
|
601
2623
|
- Symbol: ${args.symbol}
|
|
602
2624
|
- TimeInForce: ${args.timeInForce} (${timeInForceNames[args.timeInForce]})
|
|
603
2625
|
|
|
604
|
-
To execute this order, call the executeOrder tool with these exact same parameters
|
|
2626
|
+
To execute this order, call the executeOrder tool with these exact same parameters. Important: The user has to explicitly confirm before executeOrder is called!`,
|
|
605
2627
|
uri: "verifyOrder"
|
|
606
2628
|
}
|
|
607
2629
|
]
|
|
@@ -797,12 +2819,260 @@ var createToolHandlers = (parser, verifiedOrders, pendingRequests, marketDataPri
|
|
|
797
2819
|
executeOrder: createExecuteOrderHandler(parser, verifiedOrders, pendingRequests),
|
|
798
2820
|
marketDataRequest: createMarketDataRequestHandler(parser, pendingRequests),
|
|
799
2821
|
getStockGraph: createGetStockGraphHandler(marketDataPrices),
|
|
800
|
-
getStockPriceHistory: createGetStockPriceHistoryHandler(marketDataPrices)
|
|
2822
|
+
getStockPriceHistory: createGetStockPriceHistoryHandler(marketDataPrices),
|
|
2823
|
+
technicalAnalysis: createTechnicalAnalysisHandler(marketDataPrices)
|
|
801
2824
|
});
|
|
802
2825
|
|
|
2826
|
+
// src/utils/messageHandler.ts
|
|
2827
|
+
var import_fixparser3 = require("fixparser");
|
|
2828
|
+
function getEnumValue(enumObj, name) {
|
|
2829
|
+
return enumObj[name] || name;
|
|
2830
|
+
}
|
|
2831
|
+
function handleMessage(message, parser, pendingRequests, marketDataPrices, maxPriceHistory, onPriceUpdate) {
|
|
2832
|
+
void parser;
|
|
2833
|
+
const msgType = message.messageType;
|
|
2834
|
+
if (msgType === import_fixparser3.Messages.MarketDataSnapshotFullRefresh || msgType === import_fixparser3.Messages.MarketDataIncrementalRefresh) {
|
|
2835
|
+
const symbol = message.getField(import_fixparser3.Fields.Symbol)?.value;
|
|
2836
|
+
const fixJson = message.toFIXJSON();
|
|
2837
|
+
const entries = fixJson.Body?.NoMDEntries || [];
|
|
2838
|
+
const data = {
|
|
2839
|
+
timestamp: Date.now(),
|
|
2840
|
+
bid: 0,
|
|
2841
|
+
offer: 0,
|
|
2842
|
+
spread: 0,
|
|
2843
|
+
volume: 0,
|
|
2844
|
+
trade: 0,
|
|
2845
|
+
indexValue: 0,
|
|
2846
|
+
openingPrice: 0,
|
|
2847
|
+
closingPrice: 0,
|
|
2848
|
+
settlementPrice: 0,
|
|
2849
|
+
tradingSessionHighPrice: 0,
|
|
2850
|
+
tradingSessionLowPrice: 0,
|
|
2851
|
+
vwap: 0,
|
|
2852
|
+
imbalance: 0,
|
|
2853
|
+
openInterest: 0,
|
|
2854
|
+
compositeUnderlyingPrice: 0,
|
|
2855
|
+
simulatedSellPrice: 0,
|
|
2856
|
+
simulatedBuyPrice: 0,
|
|
2857
|
+
marginRate: 0,
|
|
2858
|
+
midPrice: 0,
|
|
2859
|
+
emptyBook: 0,
|
|
2860
|
+
settleHighPrice: 0,
|
|
2861
|
+
settleLowPrice: 0,
|
|
2862
|
+
priorSettlePrice: 0,
|
|
2863
|
+
sessionHighBid: 0,
|
|
2864
|
+
sessionLowOffer: 0,
|
|
2865
|
+
earlyPrices: 0,
|
|
2866
|
+
auctionClearingPrice: 0,
|
|
2867
|
+
swapValueFactor: 0,
|
|
2868
|
+
dailyValueAdjustmentForLongPositions: 0,
|
|
2869
|
+
cumulativeValueAdjustmentForLongPositions: 0,
|
|
2870
|
+
dailyValueAdjustmentForShortPositions: 0,
|
|
2871
|
+
cumulativeValueAdjustmentForShortPositions: 0,
|
|
2872
|
+
fixingPrice: 0,
|
|
2873
|
+
cashRate: 0,
|
|
2874
|
+
recoveryRate: 0,
|
|
2875
|
+
recoveryRateForLong: 0,
|
|
2876
|
+
recoveryRateForShort: 0,
|
|
2877
|
+
marketBid: 0,
|
|
2878
|
+
marketOffer: 0,
|
|
2879
|
+
shortSaleMinPrice: 0,
|
|
2880
|
+
previousClosingPrice: 0,
|
|
2881
|
+
thresholdLimitPriceBanding: 0,
|
|
2882
|
+
dailyFinancingValue: 0,
|
|
2883
|
+
accruedFinancingValue: 0,
|
|
2884
|
+
twap: 0
|
|
2885
|
+
};
|
|
2886
|
+
for (const entry of entries) {
|
|
2887
|
+
const entryType = entry.MDEntryType;
|
|
2888
|
+
const price = entry.MDEntryPx ? Number.parseFloat(entry.MDEntryPx) : 0;
|
|
2889
|
+
const size = entry.MDEntrySize ? Number.parseFloat(entry.MDEntrySize) : 0;
|
|
2890
|
+
const enumValue = getEnumValue(import_fixparser3.MDEntryType, entryType);
|
|
2891
|
+
switch (enumValue) {
|
|
2892
|
+
case import_fixparser3.MDEntryType.Bid:
|
|
2893
|
+
data.bid = price;
|
|
2894
|
+
break;
|
|
2895
|
+
case import_fixparser3.MDEntryType.Offer:
|
|
2896
|
+
data.offer = price;
|
|
2897
|
+
break;
|
|
2898
|
+
case import_fixparser3.MDEntryType.Trade:
|
|
2899
|
+
data.trade = price;
|
|
2900
|
+
break;
|
|
2901
|
+
case import_fixparser3.MDEntryType.IndexValue:
|
|
2902
|
+
data.indexValue = price;
|
|
2903
|
+
break;
|
|
2904
|
+
case import_fixparser3.MDEntryType.OpeningPrice:
|
|
2905
|
+
data.openingPrice = price;
|
|
2906
|
+
break;
|
|
2907
|
+
case import_fixparser3.MDEntryType.ClosingPrice:
|
|
2908
|
+
data.closingPrice = price;
|
|
2909
|
+
break;
|
|
2910
|
+
case import_fixparser3.MDEntryType.SettlementPrice:
|
|
2911
|
+
data.settlementPrice = price;
|
|
2912
|
+
break;
|
|
2913
|
+
case import_fixparser3.MDEntryType.TradingSessionHighPrice:
|
|
2914
|
+
data.tradingSessionHighPrice = price;
|
|
2915
|
+
break;
|
|
2916
|
+
case import_fixparser3.MDEntryType.TradingSessionLowPrice:
|
|
2917
|
+
data.tradingSessionLowPrice = price;
|
|
2918
|
+
break;
|
|
2919
|
+
case import_fixparser3.MDEntryType.VWAP:
|
|
2920
|
+
data.vwap = price;
|
|
2921
|
+
break;
|
|
2922
|
+
case import_fixparser3.MDEntryType.Imbalance:
|
|
2923
|
+
data.imbalance = size;
|
|
2924
|
+
break;
|
|
2925
|
+
case import_fixparser3.MDEntryType.TradeVolume:
|
|
2926
|
+
data.volume = size;
|
|
2927
|
+
break;
|
|
2928
|
+
case import_fixparser3.MDEntryType.OpenInterest:
|
|
2929
|
+
data.openInterest = size;
|
|
2930
|
+
break;
|
|
2931
|
+
case import_fixparser3.MDEntryType.CompositeUnderlyingPrice:
|
|
2932
|
+
data.compositeUnderlyingPrice = price;
|
|
2933
|
+
break;
|
|
2934
|
+
case import_fixparser3.MDEntryType.SimulatedSellPrice:
|
|
2935
|
+
data.simulatedSellPrice = price;
|
|
2936
|
+
break;
|
|
2937
|
+
case import_fixparser3.MDEntryType.SimulatedBuyPrice:
|
|
2938
|
+
data.simulatedBuyPrice = price;
|
|
2939
|
+
break;
|
|
2940
|
+
case import_fixparser3.MDEntryType.MarginRate:
|
|
2941
|
+
data.marginRate = price;
|
|
2942
|
+
break;
|
|
2943
|
+
case import_fixparser3.MDEntryType.MidPrice:
|
|
2944
|
+
data.midPrice = price;
|
|
2945
|
+
break;
|
|
2946
|
+
case import_fixparser3.MDEntryType.EmptyBook:
|
|
2947
|
+
data.emptyBook = 1;
|
|
2948
|
+
break;
|
|
2949
|
+
case import_fixparser3.MDEntryType.SettleHighPrice:
|
|
2950
|
+
data.settleHighPrice = price;
|
|
2951
|
+
break;
|
|
2952
|
+
case import_fixparser3.MDEntryType.SettleLowPrice:
|
|
2953
|
+
data.settleLowPrice = price;
|
|
2954
|
+
break;
|
|
2955
|
+
case import_fixparser3.MDEntryType.PriorSettlePrice:
|
|
2956
|
+
data.priorSettlePrice = price;
|
|
2957
|
+
break;
|
|
2958
|
+
case import_fixparser3.MDEntryType.SessionHighBid:
|
|
2959
|
+
data.sessionHighBid = price;
|
|
2960
|
+
break;
|
|
2961
|
+
case import_fixparser3.MDEntryType.SessionLowOffer:
|
|
2962
|
+
data.sessionLowOffer = price;
|
|
2963
|
+
break;
|
|
2964
|
+
case import_fixparser3.MDEntryType.EarlyPrices:
|
|
2965
|
+
data.earlyPrices = price;
|
|
2966
|
+
break;
|
|
2967
|
+
case import_fixparser3.MDEntryType.AuctionClearingPrice:
|
|
2968
|
+
data.auctionClearingPrice = price;
|
|
2969
|
+
break;
|
|
2970
|
+
case import_fixparser3.MDEntryType.SwapValueFactor:
|
|
2971
|
+
data.swapValueFactor = price;
|
|
2972
|
+
break;
|
|
2973
|
+
case import_fixparser3.MDEntryType.DailyValueAdjustmentForLongPositions:
|
|
2974
|
+
data.dailyValueAdjustmentForLongPositions = price;
|
|
2975
|
+
break;
|
|
2976
|
+
case import_fixparser3.MDEntryType.CumulativeValueAdjustmentForLongPositions:
|
|
2977
|
+
data.cumulativeValueAdjustmentForLongPositions = price;
|
|
2978
|
+
break;
|
|
2979
|
+
case import_fixparser3.MDEntryType.DailyValueAdjustmentForShortPositions:
|
|
2980
|
+
data.dailyValueAdjustmentForShortPositions = price;
|
|
2981
|
+
break;
|
|
2982
|
+
case import_fixparser3.MDEntryType.CumulativeValueAdjustmentForShortPositions:
|
|
2983
|
+
data.cumulativeValueAdjustmentForShortPositions = price;
|
|
2984
|
+
break;
|
|
2985
|
+
case import_fixparser3.MDEntryType.FixingPrice:
|
|
2986
|
+
data.fixingPrice = price;
|
|
2987
|
+
break;
|
|
2988
|
+
case import_fixparser3.MDEntryType.CashRate:
|
|
2989
|
+
data.cashRate = price;
|
|
2990
|
+
break;
|
|
2991
|
+
case import_fixparser3.MDEntryType.RecoveryRate:
|
|
2992
|
+
data.recoveryRate = price;
|
|
2993
|
+
break;
|
|
2994
|
+
case import_fixparser3.MDEntryType.RecoveryRateForLong:
|
|
2995
|
+
data.recoveryRateForLong = price;
|
|
2996
|
+
break;
|
|
2997
|
+
case import_fixparser3.MDEntryType.RecoveryRateForShort:
|
|
2998
|
+
data.recoveryRateForShort = price;
|
|
2999
|
+
break;
|
|
3000
|
+
case import_fixparser3.MDEntryType.MarketBid:
|
|
3001
|
+
data.marketBid = price;
|
|
3002
|
+
break;
|
|
3003
|
+
case import_fixparser3.MDEntryType.MarketOffer:
|
|
3004
|
+
data.marketOffer = price;
|
|
3005
|
+
break;
|
|
3006
|
+
case import_fixparser3.MDEntryType.ShortSaleMinPrice:
|
|
3007
|
+
data.shortSaleMinPrice = price;
|
|
3008
|
+
break;
|
|
3009
|
+
case import_fixparser3.MDEntryType.PreviousClosingPrice:
|
|
3010
|
+
data.previousClosingPrice = price;
|
|
3011
|
+
break;
|
|
3012
|
+
case import_fixparser3.MDEntryType.ThresholdLimitPriceBanding:
|
|
3013
|
+
data.thresholdLimitPriceBanding = price;
|
|
3014
|
+
break;
|
|
3015
|
+
case import_fixparser3.MDEntryType.DailyFinancingValue:
|
|
3016
|
+
data.dailyFinancingValue = price;
|
|
3017
|
+
break;
|
|
3018
|
+
case import_fixparser3.MDEntryType.AccruedFinancingValue:
|
|
3019
|
+
data.accruedFinancingValue = price;
|
|
3020
|
+
break;
|
|
3021
|
+
case import_fixparser3.MDEntryType.TWAP:
|
|
3022
|
+
data.twap = price;
|
|
3023
|
+
break;
|
|
3024
|
+
}
|
|
3025
|
+
}
|
|
3026
|
+
data.spread = data.offer - data.bid;
|
|
3027
|
+
if (!marketDataPrices.has(symbol)) {
|
|
3028
|
+
marketDataPrices.set(symbol, []);
|
|
3029
|
+
}
|
|
3030
|
+
const prices = marketDataPrices.get(symbol);
|
|
3031
|
+
prices.push(data);
|
|
3032
|
+
if (prices.length > maxPriceHistory) {
|
|
3033
|
+
prices.splice(0, prices.length - maxPriceHistory);
|
|
3034
|
+
}
|
|
3035
|
+
onPriceUpdate?.(symbol, data);
|
|
3036
|
+
const mdReqID = message.getField(import_fixparser3.Fields.MDReqID)?.value;
|
|
3037
|
+
if (mdReqID) {
|
|
3038
|
+
const callback = pendingRequests.get(mdReqID);
|
|
3039
|
+
if (callback) {
|
|
3040
|
+
callback(message);
|
|
3041
|
+
pendingRequests.delete(mdReqID);
|
|
3042
|
+
}
|
|
3043
|
+
}
|
|
3044
|
+
} else if (msgType === import_fixparser3.Messages.ExecutionReport) {
|
|
3045
|
+
const reqId = message.getField(import_fixparser3.Fields.ClOrdID)?.value;
|
|
3046
|
+
const callback = pendingRequests.get(reqId);
|
|
3047
|
+
if (callback) {
|
|
3048
|
+
callback(message);
|
|
3049
|
+
pendingRequests.delete(reqId);
|
|
3050
|
+
}
|
|
3051
|
+
}
|
|
3052
|
+
}
|
|
3053
|
+
|
|
803
3054
|
// src/MCPLocal.ts
|
|
804
|
-
var MCPLocal = class {
|
|
805
|
-
|
|
3055
|
+
var MCPLocal = class extends MCPBase {
|
|
3056
|
+
/**
|
|
3057
|
+
* Map to store verified orders before execution
|
|
3058
|
+
* @private
|
|
3059
|
+
*/
|
|
3060
|
+
verifiedOrders = /* @__PURE__ */ new Map();
|
|
3061
|
+
/**
|
|
3062
|
+
* Map to store pending requests and their callbacks
|
|
3063
|
+
* @private
|
|
3064
|
+
*/
|
|
3065
|
+
pendingRequests = /* @__PURE__ */ new Map();
|
|
3066
|
+
/**
|
|
3067
|
+
* Map to store market data prices for each symbol
|
|
3068
|
+
* @private
|
|
3069
|
+
*/
|
|
3070
|
+
marketDataPrices = /* @__PURE__ */ new Map();
|
|
3071
|
+
/**
|
|
3072
|
+
* Maximum number of price history entries to keep per symbol
|
|
3073
|
+
* @private
|
|
3074
|
+
*/
|
|
3075
|
+
MAX_PRICE_HISTORY = 1e5;
|
|
806
3076
|
server = new import_server.Server(
|
|
807
3077
|
{
|
|
808
3078
|
name: "fixparser",
|
|
@@ -824,90 +3094,13 @@ var MCPLocal = class {
|
|
|
824
3094
|
}
|
|
825
3095
|
);
|
|
826
3096
|
transport = new import_stdio.StdioServerTransport();
|
|
827
|
-
onReady = void 0;
|
|
828
|
-
pendingRequests = /* @__PURE__ */ new Map();
|
|
829
|
-
verifiedOrders = /* @__PURE__ */ new Map();
|
|
830
|
-
marketDataPrices = /* @__PURE__ */ new Map();
|
|
831
|
-
MAX_PRICE_HISTORY = 1e5;
|
|
832
|
-
// Maximum number of price points to store per symbol
|
|
833
3097
|
constructor({ logger, onReady }) {
|
|
834
|
-
|
|
3098
|
+
super({ logger, onReady });
|
|
835
3099
|
}
|
|
836
3100
|
async register(parser) {
|
|
837
3101
|
this.parser = parser;
|
|
838
3102
|
this.parser.addOnMessageCallback((message) => {
|
|
839
|
-
this.parser
|
|
840
|
-
level: "info",
|
|
841
|
-
message: `MCP Server received message: ${message.messageType}: ${message.description}`
|
|
842
|
-
});
|
|
843
|
-
const msgType = message.messageType;
|
|
844
|
-
if (msgType === import_fixparser3.Messages.MarketDataSnapshotFullRefresh || msgType === import_fixparser3.Messages.ExecutionReport || msgType === import_fixparser3.Messages.Reject || msgType === import_fixparser3.Messages.MarketDataIncrementalRefresh) {
|
|
845
|
-
this.parser?.logger.log({
|
|
846
|
-
level: "info",
|
|
847
|
-
message: `MCP Server handling message type: ${msgType}`
|
|
848
|
-
});
|
|
849
|
-
let id;
|
|
850
|
-
if (msgType === import_fixparser3.Messages.MarketDataIncrementalRefresh || msgType === import_fixparser3.Messages.MarketDataSnapshotFullRefresh) {
|
|
851
|
-
const symbol = message.getField(import_fixparser3.Fields.Symbol);
|
|
852
|
-
const entryType = message.getField(import_fixparser3.Fields.MDEntryType);
|
|
853
|
-
const price = message.getField(import_fixparser3.Fields.MDEntryPx);
|
|
854
|
-
const size = message.getField(import_fixparser3.Fields.MDEntrySize);
|
|
855
|
-
const timestamp = message.getField(import_fixparser3.Fields.MDEntryTime)?.value || Date.now();
|
|
856
|
-
if (symbol?.value && price?.value) {
|
|
857
|
-
const symbolStr = String(symbol.value);
|
|
858
|
-
const priceNum = Number(price.value);
|
|
859
|
-
const sizeNum = size?.value ? Number(size.value) : 0;
|
|
860
|
-
const priceHistory = this.marketDataPrices.get(symbolStr) || [];
|
|
861
|
-
const lastEntry = priceHistory[priceHistory.length - 1] || {
|
|
862
|
-
timestamp: 0,
|
|
863
|
-
bid: 0,
|
|
864
|
-
offer: 0,
|
|
865
|
-
spread: 0,
|
|
866
|
-
volume: 0
|
|
867
|
-
};
|
|
868
|
-
const newEntry = {
|
|
869
|
-
timestamp: Number(timestamp),
|
|
870
|
-
bid: entryType?.value === import_fixparser3.MDEntryType.Bid ? priceNum : lastEntry.bid,
|
|
871
|
-
offer: entryType?.value === import_fixparser3.MDEntryType.Offer ? priceNum : lastEntry.offer,
|
|
872
|
-
spread: entryType?.value === import_fixparser3.MDEntryType.Offer ? priceNum - lastEntry.bid : entryType?.value === import_fixparser3.MDEntryType.Bid ? lastEntry.offer - priceNum : lastEntry.spread,
|
|
873
|
-
volume: entryType?.value === import_fixparser3.MDEntryType.TradeVolume ? sizeNum : lastEntry.volume
|
|
874
|
-
};
|
|
875
|
-
priceHistory.push(newEntry);
|
|
876
|
-
if (priceHistory.length > this.MAX_PRICE_HISTORY) {
|
|
877
|
-
priceHistory.shift();
|
|
878
|
-
}
|
|
879
|
-
this.marketDataPrices.set(symbolStr, priceHistory);
|
|
880
|
-
this.parser?.logger.log({
|
|
881
|
-
level: "info",
|
|
882
|
-
message: `MCP Server added ${symbol}: ${JSON.stringify(newEntry)}`
|
|
883
|
-
});
|
|
884
|
-
this.server.notification({
|
|
885
|
-
method: "priceUpdate",
|
|
886
|
-
params: {
|
|
887
|
-
symbol: symbolStr,
|
|
888
|
-
...newEntry
|
|
889
|
-
}
|
|
890
|
-
});
|
|
891
|
-
}
|
|
892
|
-
}
|
|
893
|
-
if (msgType === import_fixparser3.Messages.MarketDataSnapshotFullRefresh) {
|
|
894
|
-
const mdReqID = message.getField(import_fixparser3.Fields.MDReqID);
|
|
895
|
-
if (mdReqID) id = String(mdReqID.value);
|
|
896
|
-
} else if (msgType === import_fixparser3.Messages.ExecutionReport) {
|
|
897
|
-
const clOrdID = message.getField(import_fixparser3.Fields.ClOrdID);
|
|
898
|
-
if (clOrdID) id = String(clOrdID.value);
|
|
899
|
-
} else if (msgType === import_fixparser3.Messages.Reject) {
|
|
900
|
-
const refSeqNum = message.getField(import_fixparser3.Fields.RefSeqNum);
|
|
901
|
-
if (refSeqNum) id = String(refSeqNum.value);
|
|
902
|
-
}
|
|
903
|
-
if (id) {
|
|
904
|
-
const callback = this.pendingRequests.get(id);
|
|
905
|
-
if (callback) {
|
|
906
|
-
callback(message);
|
|
907
|
-
this.pendingRequests.delete(id);
|
|
908
|
-
}
|
|
909
|
-
}
|
|
910
|
-
}
|
|
3103
|
+
handleMessage(message, this.parser, this.pendingRequests, this.marketDataPrices, this.MAX_PRICE_HISTORY);
|
|
911
3104
|
});
|
|
912
3105
|
this.addWorkflows();
|
|
913
3106
|
await this.server.connect(this.transport);
|
|
@@ -922,18 +3115,15 @@ var MCPLocal = class {
|
|
|
922
3115
|
if (!this.server) {
|
|
923
3116
|
return;
|
|
924
3117
|
}
|
|
925
|
-
this.server.setRequestHandler(
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
};
|
|
935
|
-
}
|
|
936
|
-
);
|
|
3118
|
+
this.server.setRequestHandler(import_zod.z.object({ method: import_zod.z.literal("tools/list") }), async () => {
|
|
3119
|
+
return {
|
|
3120
|
+
tools: Object.entries(toolSchemas).map(([name, { description, schema }]) => ({
|
|
3121
|
+
name,
|
|
3122
|
+
description,
|
|
3123
|
+
inputSchema: schema
|
|
3124
|
+
}))
|
|
3125
|
+
};
|
|
3126
|
+
});
|
|
937
3127
|
this.server.setRequestHandler(
|
|
938
3128
|
import_zod.z.object({
|
|
939
3129
|
method: import_zod.z.literal("tools/call"),
|
|
@@ -945,7 +3135,7 @@ var MCPLocal = class {
|
|
|
945
3135
|
}).optional()
|
|
946
3136
|
})
|
|
947
3137
|
}),
|
|
948
|
-
async (request
|
|
3138
|
+
async (request) => {
|
|
949
3139
|
const { name, arguments: args } = request.params;
|
|
950
3140
|
const toolHandlers = createToolHandlers(
|
|
951
3141
|
this.parser,
|