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