fixparser-plugin-mcp 9.1.7-57d70bb1 → 9.1.7-5d282a9e

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3232 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ MCPLocal: () => MCPLocal,
34
+ MCPRemote: () => MCPRemote
35
+ });
36
+ module.exports = __toCommonJS(index_exports);
37
+
38
+ // src/MCPLocal.ts
39
+ var import_server = require("@modelcontextprotocol/sdk/server/index.js");
40
+ var import_stdio = require("@modelcontextprotocol/sdk/server/stdio.js");
41
+ var import_zod = require("zod");
42
+
43
+ // src/MCPBase.ts
44
+ var MCPBase = class {
45
+ /**
46
+ * Optional logger instance for diagnostics and output.
47
+ * @protected
48
+ */
49
+ logger;
50
+ /**
51
+ * FIXParser instance, set during plugin register().
52
+ * @protected
53
+ */
54
+ parser;
55
+ /**
56
+ * Called when server is setup and listening.
57
+ * @protected
58
+ */
59
+ onReady = void 0;
60
+ /**
61
+ * Map to store verified orders before execution
62
+ * @protected
63
+ */
64
+ verifiedOrders = /* @__PURE__ */ new Map();
65
+ /**
66
+ * Map to store pending market data requests
67
+ * @protected
68
+ */
69
+ pendingRequests = /* @__PURE__ */ new Map();
70
+ /**
71
+ * Map to store market data prices
72
+ * @protected
73
+ */
74
+ marketDataPrices = /* @__PURE__ */ new Map();
75
+ /**
76
+ * Maximum number of price history entries to keep per symbol
77
+ * @protected
78
+ */
79
+ MAX_PRICE_HISTORY = 1e5;
80
+ constructor({ logger, onReady }) {
81
+ this.logger = logger;
82
+ this.onReady = onReady;
83
+ }
84
+ };
85
+
86
+ // src/schemas/schemas.ts
87
+ var toolSchemas = {
88
+ parse: {
89
+ description: "Parses a FIX message and describes it in plain language",
90
+ schema: {
91
+ type: "object",
92
+ properties: {
93
+ fixString: { type: "string" }
94
+ },
95
+ required: ["fixString"]
96
+ }
97
+ },
98
+ parseToJSON: {
99
+ description: "Parses a FIX message into JSON",
100
+ schema: {
101
+ type: "object",
102
+ properties: {
103
+ fixString: { type: "string" }
104
+ },
105
+ required: ["fixString"]
106
+ }
107
+ },
108
+ verifyOrder: {
109
+ description: "Verifies order parameters before execution. verifyOrder must be called before executeOrder.",
110
+ schema: {
111
+ type: "object",
112
+ properties: {
113
+ clOrdID: { type: "string" },
114
+ handlInst: {
115
+ type: "string",
116
+ enum: ["1", "2", "3"],
117
+ description: "Handling Instructions: 1=Automated Execution No Intervention, 2=Automated Execution Intervention OK, 3=Manual Order"
118
+ },
119
+ quantity: { type: "string" },
120
+ price: { type: "string" },
121
+ ordType: {
122
+ type: "string",
123
+ enum: [
124
+ "1",
125
+ "2",
126
+ "3",
127
+ "4",
128
+ "5",
129
+ "6",
130
+ "7",
131
+ "8",
132
+ "9",
133
+ "A",
134
+ "B",
135
+ "C",
136
+ "D",
137
+ "E",
138
+ "F",
139
+ "G",
140
+ "H",
141
+ "I",
142
+ "J",
143
+ "K",
144
+ "L",
145
+ "M",
146
+ "P",
147
+ "Q",
148
+ "R",
149
+ "S"
150
+ ],
151
+ description: "Order Type: 1=Market, 2=Limit, 3=Stop, 4=StopLimit, 5=MarketOnClose, 6=WithOrWithout, 7=LimitOrBetter, 8=LimitWithOrWithout, 9=OnBasis, A=OnClose, B=LimitOnClose, C=ForexMarket, D=PreviouslyQuoted, E=PreviouslyIndicated, F=ForexLimit, G=ForexSwap, H=ForexPreviouslyQuoted, I=Funari, J=MarketIfTouched, K=MarketWithLeftOverAsLimit, L=PreviousFundValuationPoint, M=NextFundValuationPoint, P=Pegged, Q=CounterOrderSelection, R=StopOnBidOrOffer, S=StopLimitOnBidOrOffer"
152
+ },
153
+ side: {
154
+ type: "string",
155
+ enum: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H"],
156
+ description: "Side: 1=Buy, 2=Sell, 3=BuyMinus, 4=SellPlus, 5=SellShort, 6=SellShortExempt, 7=Undisclosed, 8=Cross, 9=CrossShort, A=CrossShortExempt, B=AsDefined, C=Opposite, D=Subscribe, E=Redeem, F=Lend, G=Borrow, H=SellUndisclosed"
157
+ },
158
+ symbol: { type: "string" },
159
+ timeInForce: {
160
+ type: "string",
161
+ enum: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C"],
162
+ description: "Time In Force: 0=Day, 1=GoodTillCancel, 2=AtTheOpening, 3=ImmediateOrCancel, 4=FillOrKill, 5=GoodTillCrossing, 6=GoodTillDate, 7=AtTheClose, 8=GoodThroughCrossing, 9=AtCrossing, A=GoodForTime, B=GoodForAuction, C=GoodForMonth"
163
+ }
164
+ },
165
+ required: ["clOrdID", "handlInst", "quantity", "price", "ordType", "side", "symbol", "timeInForce"]
166
+ }
167
+ },
168
+ executeOrder: {
169
+ description: "Executes a verified order. verifyOrder must be called before executeOrder.",
170
+ schema: {
171
+ type: "object",
172
+ properties: {
173
+ clOrdID: { type: "string" },
174
+ handlInst: {
175
+ type: "string",
176
+ enum: ["1", "2", "3"],
177
+ description: "Handling Instructions: 1=Automated Execution No Intervention, 2=Automated Execution Intervention OK, 3=Manual Order"
178
+ },
179
+ quantity: { type: "string" },
180
+ price: { type: "string" },
181
+ ordType: {
182
+ type: "string",
183
+ enum: [
184
+ "1",
185
+ "2",
186
+ "3",
187
+ "4",
188
+ "5",
189
+ "6",
190
+ "7",
191
+ "8",
192
+ "9",
193
+ "A",
194
+ "B",
195
+ "C",
196
+ "D",
197
+ "E",
198
+ "F",
199
+ "G",
200
+ "H",
201
+ "I",
202
+ "J",
203
+ "K",
204
+ "L",
205
+ "M",
206
+ "P",
207
+ "Q",
208
+ "R",
209
+ "S"
210
+ ],
211
+ description: "Order Type: 1=Market, 2=Limit, 3=Stop, 4=StopLimit, 5=MarketOnClose, 6=WithOrWithout, 7=LimitOrBetter, 8=LimitWithOrWithout, 9=OnBasis, A=OnClose, B=LimitOnClose, C=ForexMarket, D=PreviouslyQuoted, E=PreviouslyIndicated, F=ForexLimit, G=ForexSwap, H=ForexPreviouslyQuoted, I=Funari, J=MarketIfTouched, K=MarketWithLeftOverAsLimit, L=PreviousFundValuationPoint, M=NextFundValuationPoint, P=Pegged, Q=CounterOrderSelection, R=StopOnBidOrOffer, S=StopLimitOnBidOrOffer"
212
+ },
213
+ side: {
214
+ type: "string",
215
+ enum: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H"],
216
+ description: "Side: 1=Buy, 2=Sell, 3=BuyMinus, 4=SellPlus, 5=SellShort, 6=SellShortExempt, 7=Undisclosed, 8=Cross, 9=CrossShort, A=CrossShortExempt, B=AsDefined, C=Opposite, D=Subscribe, E=Redeem, F=Lend, G=Borrow, H=SellUndisclosed"
217
+ },
218
+ symbol: { type: "string" },
219
+ timeInForce: {
220
+ type: "string",
221
+ enum: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C"],
222
+ description: "Time In Force: 0=Day, 1=GoodTillCancel, 2=AtTheOpening, 3=ImmediateOrCancel, 4=FillOrKill, 5=GoodTillCrossing, 6=GoodTillDate, 7=AtTheClose, 8=GoodThroughCrossing, 9=AtCrossing, A=GoodForTime, B=GoodForAuction, C=GoodForMonth"
223
+ }
224
+ },
225
+ required: ["clOrdID", "handlInst", "quantity", "price", "ordType", "side", "symbol", "timeInForce"]
226
+ }
227
+ },
228
+ marketDataRequest: {
229
+ description: "Requests market data for specified symbols",
230
+ schema: {
231
+ type: "object",
232
+ properties: {
233
+ mdUpdateType: {
234
+ type: "string",
235
+ enum: ["0", "1"],
236
+ description: "Market Data Update Type: 0=Full Refresh, 1=Incremental Refresh"
237
+ },
238
+ symbols: { type: "array", items: { type: "string" } },
239
+ mdReqID: { type: "string" },
240
+ subscriptionRequestType: {
241
+ type: "string",
242
+ enum: ["0", "1", "2"],
243
+ description: "Subscription Request Type: 0=Snapshot, 1=Snapshot + Updates, 2=Disable Previous Snapshot + Update Request"
244
+ },
245
+ mdEntryTypes: {
246
+ type: "array",
247
+ items: {
248
+ type: "string",
249
+ enum: [
250
+ "0",
251
+ "1",
252
+ "2",
253
+ "3",
254
+ "4",
255
+ "5",
256
+ "6",
257
+ "7",
258
+ "8",
259
+ "9",
260
+ "A",
261
+ "B",
262
+ "C",
263
+ "D",
264
+ "E",
265
+ "F",
266
+ "G",
267
+ "H",
268
+ "I",
269
+ "J",
270
+ "K",
271
+ "L",
272
+ "M",
273
+ "N",
274
+ "O",
275
+ "P",
276
+ "Q",
277
+ "R",
278
+ "S",
279
+ "T",
280
+ "U",
281
+ "V",
282
+ "W",
283
+ "X",
284
+ "Y",
285
+ "Z"
286
+ ]
287
+ },
288
+ description: "Market Data Entry Types: 0=Bid, 1=Offer, 2=Trade, 3=Index Value, 4=Opening Price, 5=Closing Price, 6=Settlement Price, 7=High Price, 8=Low Price, 9=Trade Volume, A=Open Interest, B=Simulated Sell Price, C=Simulated Buy Price, D=Empty Book, E=Session High Bid, F=Session Low Offer, G=Fixing Price, H=Electronic Volume, I=Threshold Limits and Price Band Variation, J=Clearing Price, K=Open Interest Change, L=Last Trade Price, M=Last Trade Volume, N=Last Trade Time, O=Last Trade Tick, P=Last Trade Exchange, Q=Last Trade ID, R=Last Trade Side, S=Last Trade Price Change, T=Last Trade Price Change Percent, U=Last Trade Price Change Basis Points, V=Last Trade Price Change Points, W=Last Trade Price Change Ticks, X=Last Trade Price Change Ticks Percent, Y=Last Trade Price Change Ticks Basis Points, Z=Last Trade Price Change Ticks Points"
289
+ }
290
+ },
291
+ required: ["mdUpdateType", "symbols", "mdReqID", "subscriptionRequestType"]
292
+ }
293
+ },
294
+ getStockGraph: {
295
+ description: "Generates a price chart for a given symbol",
296
+ schema: {
297
+ type: "object",
298
+ properties: {
299
+ symbol: { type: "string" }
300
+ },
301
+ required: ["symbol"]
302
+ }
303
+ },
304
+ getStockPriceHistory: {
305
+ description: "Returns price history for a given symbol",
306
+ schema: {
307
+ type: "object",
308
+ properties: {
309
+ symbol: { type: "string" }
310
+ },
311
+ required: ["symbol"]
312
+ }
313
+ },
314
+ technicalAnalysis: {
315
+ description: "Performs comprehensive technical analysis on market data for a given symbol, including indicators like SMA, EMA, RSI, Bollinger Bands, and trading signals",
316
+ schema: {
317
+ type: "object",
318
+ properties: {
319
+ symbol: {
320
+ type: "string",
321
+ description: "The trading symbol to analyze (e.g., AAPL, MSFT, EURUSD)"
322
+ }
323
+ },
324
+ required: ["symbol"]
325
+ }
326
+ }
327
+ };
328
+
329
+ // src/tools/analytics.ts
330
+ function sum(numbers) {
331
+ return numbers.reduce((acc, val) => acc + val, 0);
332
+ }
333
+ var TechnicalAnalyzer = class {
334
+ prices;
335
+ volumes;
336
+ highs;
337
+ lows;
338
+ constructor(data) {
339
+ this.prices = data.map((d) => d.trade > 0 ? d.trade : d.midPrice);
340
+ this.volumes = data.map((d) => d.volume);
341
+ this.highs = data.map((d) => d.tradingSessionHighPrice > 0 ? d.tradingSessionHighPrice : d.trade);
342
+ this.lows = data.map((d) => d.tradingSessionLowPrice > 0 ? d.tradingSessionLowPrice : d.trade);
343
+ }
344
+ // Calculate Simple Moving Average
345
+ calculateSMA(data, period) {
346
+ const sma = [];
347
+ for (let i = period - 1; i < data.length; i++) {
348
+ const sum2 = data.slice(i - period + 1, i + 1).reduce((a, b) => a + b, 0);
349
+ sma.push(sum2 / period);
350
+ }
351
+ return sma;
352
+ }
353
+ // Calculate Exponential Moving Average
354
+ calculateEMA(data, period) {
355
+ const multiplier = 2 / (period + 1);
356
+ const ema = [data[0]];
357
+ for (let i = 1; i < data.length; i++) {
358
+ ema.push(data[i] * multiplier + ema[i - 1] * (1 - multiplier));
359
+ }
360
+ return ema;
361
+ }
362
+ // Calculate RSI
363
+ calculateRSI(data, period = 14) {
364
+ if (data.length < period + 1) return [];
365
+ const changes = [];
366
+ for (let i = 1; i < data.length; i++) {
367
+ changes.push(data[i] - data[i - 1]);
368
+ }
369
+ const gains = changes.map((change) => change > 0 ? change : 0);
370
+ const losses = changes.map((change) => change < 0 ? Math.abs(change) : 0);
371
+ let avgGain = gains.slice(0, period).reduce((a, b) => a + b, 0) / period;
372
+ let avgLoss = losses.slice(0, period).reduce((a, b) => a + b, 0) / period;
373
+ const rsi = [];
374
+ for (let i = period; i < changes.length; i++) {
375
+ const rs = avgGain / avgLoss;
376
+ rsi.push(100 - 100 / (1 + rs));
377
+ avgGain = (avgGain * (period - 1) + gains[i]) / period;
378
+ avgLoss = (avgLoss * (period - 1) + losses[i]) / period;
379
+ }
380
+ return rsi;
381
+ }
382
+ // Calculate Bollinger Bands
383
+ calculateBollingerBands(data, period = 20, stdDev = 2) {
384
+ if (data.length < period) return [];
385
+ const sma = this.calculateSMA(data, period);
386
+ const bands = [];
387
+ for (let i = 0; i < sma.length; i++) {
388
+ const dataSlice = data.slice(i, i + period);
389
+ const mean = sma[i];
390
+ const variance = dataSlice.reduce((sum2, price) => sum2 + (price - mean) ** 2, 0) / period;
391
+ const standardDeviation = Math.sqrt(variance);
392
+ const upper = mean + standardDeviation * stdDev;
393
+ const lower = mean - standardDeviation * stdDev;
394
+ bands.push({
395
+ upper,
396
+ middle: mean,
397
+ lower,
398
+ bandwidth: (upper - lower) / mean * 100,
399
+ percentB: (data[i] - lower) / (upper - lower) * 100
400
+ });
401
+ }
402
+ return bands;
403
+ }
404
+ // Calculate maximum drawdown
405
+ calculateMaxDrawdown(prices) {
406
+ let maxPrice = prices[0];
407
+ let maxDrawdown = 0;
408
+ for (let i = 1; i < prices.length; i++) {
409
+ if (prices[i] > maxPrice) {
410
+ maxPrice = prices[i];
411
+ }
412
+ const drawdown = (maxPrice - prices[i]) / maxPrice;
413
+ if (drawdown > maxDrawdown) {
414
+ maxDrawdown = drawdown;
415
+ }
416
+ }
417
+ return maxDrawdown;
418
+ }
419
+ // Calculate Average True Range (ATR)
420
+ calculateAtr(prices, highs, lows) {
421
+ if (prices.length < 2) return [];
422
+ const trueRanges = [];
423
+ for (let i = 1; i < prices.length; i++) {
424
+ const high = highs[i] || prices[i];
425
+ const low = lows[i] || prices[i];
426
+ const prevClose = prices[i - 1];
427
+ const tr1 = high - low;
428
+ const tr2 = Math.abs(high - prevClose);
429
+ const tr3 = Math.abs(low - prevClose);
430
+ trueRanges.push(Math.max(tr1, tr2, tr3));
431
+ }
432
+ const atr = [];
433
+ if (trueRanges.length >= 14) {
434
+ let sum2 = trueRanges.slice(0, 14).reduce((a, b) => a + b, 0);
435
+ atr.push(sum2 / 14);
436
+ for (let i = 14; i < trueRanges.length; i++) {
437
+ sum2 = sum2 - trueRanges[i - 14] + trueRanges[i];
438
+ atr.push(sum2 / 14);
439
+ }
440
+ }
441
+ return atr;
442
+ }
443
+ // Calculate maximum consecutive losses
444
+ calculateMaxConsecutiveLosses(prices) {
445
+ let maxConsecutive = 0;
446
+ let currentConsecutive = 0;
447
+ for (let i = 1; i < prices.length; i++) {
448
+ if (prices[i] < prices[i - 1]) {
449
+ currentConsecutive++;
450
+ maxConsecutive = Math.max(maxConsecutive, currentConsecutive);
451
+ } else {
452
+ currentConsecutive = 0;
453
+ }
454
+ }
455
+ return maxConsecutive;
456
+ }
457
+ // Calculate win rate
458
+ calculateWinRate(prices) {
459
+ let wins = 0;
460
+ let total = 0;
461
+ for (let i = 1; i < prices.length; i++) {
462
+ if (prices[i] !== prices[i - 1]) {
463
+ total++;
464
+ if (prices[i] > prices[i - 1]) {
465
+ wins++;
466
+ }
467
+ }
468
+ }
469
+ return total > 0 ? wins / total : 0;
470
+ }
471
+ // Calculate profit factor
472
+ calculateProfitFactor(prices) {
473
+ let grossProfit = 0;
474
+ let grossLoss = 0;
475
+ for (let i = 1; i < prices.length; i++) {
476
+ const change = prices[i] - prices[i - 1];
477
+ if (change > 0) {
478
+ grossProfit += change;
479
+ } else {
480
+ grossLoss += Math.abs(change);
481
+ }
482
+ }
483
+ return grossLoss > 0 ? grossProfit / grossLoss : 0;
484
+ }
485
+ // Calculate Weighted Moving Average
486
+ calculateWma(data, period) {
487
+ const wma = [];
488
+ const weights = Array.from({ length: period }, (_, i) => i + 1);
489
+ const weightSum = weights.reduce((a, b) => a + b, 0);
490
+ for (let i = period - 1; i < data.length; i++) {
491
+ let weightedSum = 0;
492
+ for (let j = 0; j < period; j++) {
493
+ weightedSum += data[i - j] * weights[j];
494
+ }
495
+ wma.push(weightedSum / weightSum);
496
+ }
497
+ return wma;
498
+ }
499
+ // Calculate Volume Weighted Moving Average
500
+ calculateVwma(prices, period) {
501
+ const vwma = [];
502
+ for (let i = period - 1; i < prices.length; i++) {
503
+ let volumeSum = 0;
504
+ let priceVolumeSum = 0;
505
+ for (let j = 0; j < period; j++) {
506
+ const volume = this.volumes[i - j] || 1;
507
+ volumeSum += volume;
508
+ priceVolumeSum += prices[i - j] * volume;
509
+ }
510
+ vwma.push(priceVolumeSum / volumeSum);
511
+ }
512
+ return vwma;
513
+ }
514
+ // Calculate MACD
515
+ calculateMacd(prices) {
516
+ const ema12 = this.calculateEMA(prices, 12);
517
+ const ema26 = this.calculateEMA(prices, 26);
518
+ const macd = [];
519
+ const macdLine = [];
520
+ for (let i = 0; i < Math.min(ema12.length, ema26.length); i++) {
521
+ macdLine.push(ema12[i] - ema26[i]);
522
+ }
523
+ const signalLine = this.calculateEMA(macdLine, 9);
524
+ for (let i = 0; i < Math.min(macdLine.length, signalLine.length); i++) {
525
+ macd.push({
526
+ macd: macdLine[i],
527
+ signal: signalLine[i],
528
+ histogram: macdLine[i] - signalLine[i]
529
+ });
530
+ }
531
+ return macd;
532
+ }
533
+ // Calculate ADX (Average Directional Index)
534
+ calculateAdx(prices, highs, lows) {
535
+ if (prices.length < 14) return [];
536
+ const period = 14;
537
+ const adx = [];
538
+ const trueRanges = [];
539
+ const plusDM = [];
540
+ const minusDM = [];
541
+ trueRanges.push(highs[0] - lows[0]);
542
+ plusDM.push(0);
543
+ minusDM.push(0);
544
+ for (let i = 1; i < prices.length; i++) {
545
+ const high = highs[i] || prices[i];
546
+ const low = lows[i] || prices[i];
547
+ const prevHigh = highs[i - 1] || prices[i - 1];
548
+ const prevLow = lows[i - 1] || prices[i - 1];
549
+ const prevClose = prices[i - 1];
550
+ const tr1 = high - low;
551
+ const tr2 = Math.abs(high - prevClose);
552
+ const tr3 = Math.abs(low - prevClose);
553
+ trueRanges.push(Math.max(tr1, tr2, tr3));
554
+ const upMove = high - prevHigh;
555
+ const downMove = prevLow - low;
556
+ if (upMove > downMove && upMove > 0) {
557
+ plusDM.push(upMove);
558
+ minusDM.push(0);
559
+ } else if (downMove > upMove && downMove > 0) {
560
+ plusDM.push(0);
561
+ minusDM.push(downMove);
562
+ } else {
563
+ plusDM.push(0);
564
+ minusDM.push(0);
565
+ }
566
+ }
567
+ const smoothedTR = [];
568
+ const smoothedPlusDM = [];
569
+ const smoothedMinusDM = [];
570
+ let sumTR = 0;
571
+ let sumPlusDM = 0;
572
+ let sumMinusDM = 0;
573
+ for (let i = 0; i < period; i++) {
574
+ sumTR += trueRanges[i];
575
+ sumPlusDM += plusDM[i];
576
+ sumMinusDM += minusDM[i];
577
+ }
578
+ smoothedTR.push(sumTR);
579
+ smoothedPlusDM.push(sumPlusDM);
580
+ smoothedMinusDM.push(sumMinusDM);
581
+ for (let i = period; i < trueRanges.length; i++) {
582
+ const newTR = smoothedTR[smoothedTR.length - 1] - smoothedTR[smoothedTR.length - 1] / period + trueRanges[i];
583
+ const newPlusDM = smoothedPlusDM[smoothedPlusDM.length - 1] - smoothedPlusDM[smoothedPlusDM.length - 1] / period + plusDM[i];
584
+ const newMinusDM = smoothedMinusDM[smoothedMinusDM.length - 1] - smoothedMinusDM[smoothedMinusDM.length - 1] / period + minusDM[i];
585
+ smoothedTR.push(newTR);
586
+ smoothedPlusDM.push(newPlusDM);
587
+ smoothedMinusDM.push(newMinusDM);
588
+ }
589
+ const plusDI = [];
590
+ const minusDI = [];
591
+ for (let i = 0; i < smoothedTR.length; i++) {
592
+ plusDI.push(smoothedPlusDM[i] / smoothedTR[i] * 100);
593
+ minusDI.push(smoothedMinusDM[i] / smoothedTR[i] * 100);
594
+ }
595
+ const dx = [];
596
+ for (let i = 0; i < plusDI.length; i++) {
597
+ const diSum = plusDI[i] + minusDI[i];
598
+ const diDiff = Math.abs(plusDI[i] - minusDI[i]);
599
+ dx.push(diSum > 0 ? diDiff / diSum * 100 : 0);
600
+ }
601
+ if (dx.length < period) return [];
602
+ let sumDX = 0;
603
+ for (let i = 0; i < period; i++) {
604
+ sumDX += dx[i];
605
+ }
606
+ adx.push(sumDX / period);
607
+ for (let i = period; i < dx.length; i++) {
608
+ const newADX = adx[adx.length - 1] - adx[adx.length - 1] / period + dx[i];
609
+ adx.push(newADX);
610
+ }
611
+ return adx;
612
+ }
613
+ // Calculate DMI (Directional Movement Index)
614
+ calculateDmi(prices, highs, lows) {
615
+ if (prices.length < 14) return [];
616
+ const period = 14;
617
+ const dmi = [];
618
+ const trueRanges = [];
619
+ const plusDM = [];
620
+ const minusDM = [];
621
+ trueRanges.push(highs[0] - lows[0]);
622
+ plusDM.push(0);
623
+ minusDM.push(0);
624
+ for (let i = 1; i < prices.length; i++) {
625
+ const high = highs[i] || prices[i];
626
+ const low = lows[i] || prices[i];
627
+ const prevHigh = highs[i - 1] || prices[i - 1];
628
+ const prevLow = lows[i - 1] || prices[i - 1];
629
+ const prevClose = prices[i - 1];
630
+ const tr1 = high - low;
631
+ const tr2 = Math.abs(high - prevClose);
632
+ const tr3 = Math.abs(low - prevClose);
633
+ trueRanges.push(Math.max(tr1, tr2, tr3));
634
+ const upMove = high - prevHigh;
635
+ const downMove = prevLow - low;
636
+ if (upMove > downMove && upMove > 0) {
637
+ plusDM.push(upMove);
638
+ minusDM.push(0);
639
+ } else if (downMove > upMove && downMove > 0) {
640
+ plusDM.push(0);
641
+ minusDM.push(downMove);
642
+ } else {
643
+ plusDM.push(0);
644
+ minusDM.push(0);
645
+ }
646
+ }
647
+ const smoothedTR = [];
648
+ const smoothedPlusDM = [];
649
+ const smoothedMinusDM = [];
650
+ let sumTR = 0;
651
+ let sumPlusDM = 0;
652
+ let sumMinusDM = 0;
653
+ for (let i = 0; i < period; i++) {
654
+ sumTR += trueRanges[i];
655
+ sumPlusDM += plusDM[i];
656
+ sumMinusDM += minusDM[i];
657
+ }
658
+ smoothedTR.push(sumTR);
659
+ smoothedPlusDM.push(sumPlusDM);
660
+ smoothedMinusDM.push(sumMinusDM);
661
+ for (let i = period; i < trueRanges.length; i++) {
662
+ const newTR = smoothedTR[smoothedTR.length - 1] - smoothedTR[smoothedTR.length - 1] / period + trueRanges[i];
663
+ const newPlusDM = smoothedPlusDM[smoothedPlusDM.length - 1] - smoothedPlusDM[smoothedPlusDM.length - 1] / period + plusDM[i];
664
+ const newMinusDM = smoothedMinusDM[smoothedMinusDM.length - 1] - smoothedMinusDM[smoothedMinusDM.length - 1] / period + minusDM[i];
665
+ smoothedTR.push(newTR);
666
+ smoothedPlusDM.push(newPlusDM);
667
+ smoothedMinusDM.push(newMinusDM);
668
+ }
669
+ const plusDI = [];
670
+ const minusDI = [];
671
+ for (let i = 0; i < smoothedTR.length; i++) {
672
+ plusDI.push(smoothedPlusDM[i] / smoothedTR[i] * 100);
673
+ minusDI.push(smoothedMinusDM[i] / smoothedTR[i] * 100);
674
+ }
675
+ const dx = [];
676
+ for (let i = 0; i < plusDI.length; i++) {
677
+ const diSum = plusDI[i] + minusDI[i];
678
+ const diDiff = Math.abs(plusDI[i] - minusDI[i]);
679
+ dx.push(diSum > 0 ? diDiff / diSum * 100 : 0);
680
+ }
681
+ if (dx.length < period) return [];
682
+ const adx = [];
683
+ let sumDX = 0;
684
+ for (let i = 0; i < period; i++) {
685
+ sumDX += dx[i];
686
+ }
687
+ adx.push(sumDX / period);
688
+ for (let i = period; i < dx.length; i++) {
689
+ const newADX = adx[adx.length - 1] - adx[adx.length - 1] / period + dx[i];
690
+ adx.push(newADX);
691
+ }
692
+ for (let i = 0; i < adx.length; i++) {
693
+ dmi.push({
694
+ plusDI: plusDI[i + period - 1] || 0,
695
+ minusDI: minusDI[i + period - 1] || 0,
696
+ adx: adx[i]
697
+ });
698
+ }
699
+ return dmi;
700
+ }
701
+ // Calculate Ichimoku Cloud
702
+ calculateIchimoku(prices, highs, lows) {
703
+ if (prices.length < 52) return [];
704
+ const ichimoku = [];
705
+ const tenkanSen = [];
706
+ for (let i = 8; i < prices.length; i++) {
707
+ const periodHigh = Math.max(...highs.slice(i - 8, i + 1));
708
+ const periodLow = Math.min(...lows.slice(i - 8, i + 1));
709
+ tenkanSen.push((periodHigh + periodLow) / 2);
710
+ }
711
+ const kijunSen = [];
712
+ for (let i = 25; i < prices.length; i++) {
713
+ const periodHigh = Math.max(...highs.slice(i - 25, i + 1));
714
+ const periodLow = Math.min(...lows.slice(i - 25, i + 1));
715
+ kijunSen.push((periodHigh + periodLow) / 2);
716
+ }
717
+ const senkouSpanA = [];
718
+ for (let i = 0; i < Math.min(tenkanSen.length, kijunSen.length); i++) {
719
+ senkouSpanA.push((tenkanSen[i] + kijunSen[i]) / 2);
720
+ }
721
+ const senkouSpanB = [];
722
+ for (let i = 51; i < prices.length; i++) {
723
+ const periodHigh = Math.max(...highs.slice(i - 51, i + 1));
724
+ const periodLow = Math.min(...lows.slice(i - 51, i + 1));
725
+ senkouSpanB.push((periodHigh + periodLow) / 2);
726
+ }
727
+ const chikouSpan = [];
728
+ for (let i = 26; i < prices.length; i++) {
729
+ chikouSpan.push(prices[i - 26]);
730
+ }
731
+ const minLength = Math.min(
732
+ tenkanSen.length,
733
+ kijunSen.length,
734
+ senkouSpanA.length,
735
+ senkouSpanB.length,
736
+ chikouSpan.length
737
+ );
738
+ for (let i = 0; i < minLength; i++) {
739
+ ichimoku.push({
740
+ tenkan: tenkanSen[i],
741
+ kijun: kijunSen[i],
742
+ senkouA: senkouSpanA[i],
743
+ senkouB: senkouSpanB[i],
744
+ chikou: chikouSpan[i]
745
+ });
746
+ }
747
+ return ichimoku;
748
+ }
749
+ // Calculate Parabolic SAR
750
+ calculateParabolicSAR(prices, highs, lows) {
751
+ if (prices.length < 2) return [];
752
+ const sar = [];
753
+ const accelerationFactor = 0.02;
754
+ const maximumAcceleration = 0.2;
755
+ let currentSAR = lows[0];
756
+ let isLong = true;
757
+ let af = accelerationFactor;
758
+ let ep = highs[0];
759
+ sar.push(currentSAR);
760
+ for (let i = 1; i < prices.length; i++) {
761
+ const high = highs[i] || prices[i];
762
+ const low = lows[i] || prices[i];
763
+ if (isLong) {
764
+ if (low < currentSAR) {
765
+ isLong = false;
766
+ currentSAR = ep;
767
+ ep = low;
768
+ af = accelerationFactor;
769
+ } else {
770
+ if (high > ep) {
771
+ ep = high;
772
+ af = Math.min(af + accelerationFactor, maximumAcceleration);
773
+ }
774
+ currentSAR = currentSAR + af * (ep - currentSAR);
775
+ if (i > 0) {
776
+ const prevLow = lows[i - 1] || prices[i - 1];
777
+ currentSAR = Math.min(currentSAR, prevLow);
778
+ }
779
+ }
780
+ } else {
781
+ if (high > currentSAR) {
782
+ isLong = true;
783
+ currentSAR = ep;
784
+ ep = high;
785
+ af = accelerationFactor;
786
+ } else {
787
+ if (low < ep) {
788
+ ep = low;
789
+ af = Math.min(af + accelerationFactor, maximumAcceleration);
790
+ }
791
+ currentSAR = currentSAR + af * (ep - currentSAR);
792
+ if (i > 0) {
793
+ const prevHigh = highs[i - 1] || prices[i - 1];
794
+ currentSAR = Math.max(currentSAR, prevHigh);
795
+ }
796
+ }
797
+ }
798
+ sar.push(currentSAR);
799
+ }
800
+ return sar;
801
+ }
802
+ // Calculate Stochastic
803
+ calculateStochastic(prices, highs, lows) {
804
+ const stochastic = [];
805
+ const period = 14;
806
+ const smoothK = 3;
807
+ const smoothD = 3;
808
+ if (prices.length < period) return [];
809
+ const percentK = [];
810
+ for (let i = period - 1; i < prices.length; i++) {
811
+ const high = Math.max(...highs.slice(i - period + 1, i + 1));
812
+ const low = Math.min(...lows.slice(i - period + 1, i + 1));
813
+ const close = prices[i];
814
+ const k = (close - low) / (high - low) * 100;
815
+ percentK.push(k);
816
+ }
817
+ const smoothedK = [];
818
+ for (let i = smoothK - 1; i < percentK.length; i++) {
819
+ const sum2 = percentK.slice(i - smoothK + 1, i + 1).reduce((a, b) => a + b, 0);
820
+ smoothedK.push(sum2 / smoothK);
821
+ }
822
+ for (let i = smoothD - 1; i < smoothedK.length; i++) {
823
+ const sum2 = smoothedK.slice(i - smoothD + 1, i + 1).reduce((a, b) => a + b, 0);
824
+ const d = sum2 / smoothD;
825
+ stochastic.push({
826
+ k: smoothedK[i],
827
+ d
828
+ });
829
+ }
830
+ return stochastic;
831
+ }
832
+ // Calculate CCI
833
+ calculateCci(prices, highs, lows) {
834
+ const cci = [];
835
+ const period = 20;
836
+ if (prices.length < period) return [];
837
+ for (let i = period - 1; i < prices.length; i++) {
838
+ const slice = prices.slice(i - period + 1, i + 1);
839
+ const typicalPrices = slice.map((price, idx) => {
840
+ const high = highs[i - period + 1 + idx] || price;
841
+ const low = lows[i - period + 1 + idx] || price;
842
+ return (high + low + price) / 3;
843
+ });
844
+ const sma = typicalPrices.reduce((a, b) => a + b, 0) / period;
845
+ const meanDeviation = typicalPrices.reduce((sum2, tp) => sum2 + Math.abs(tp - sma), 0) / period;
846
+ const currentTP = (highs[i] + lows[i] + prices[i]) / 3;
847
+ const cciValue = meanDeviation !== 0 ? (currentTP - sma) / (0.015 * meanDeviation) : 0;
848
+ cci.push(cciValue);
849
+ }
850
+ return cci;
851
+ }
852
+ // Calculate Rate of Change
853
+ calculateRoc(prices) {
854
+ const roc = [];
855
+ for (let i = 10; i < prices.length; i++) {
856
+ roc.push((prices[i] - prices[i - 10]) / prices[i - 10] * 100);
857
+ }
858
+ return roc;
859
+ }
860
+ // Calculate Williams %R
861
+ calculateWilliamsR(prices) {
862
+ const williamsR = [];
863
+ const period = 14;
864
+ if (prices.length < period) return [];
865
+ for (let i = period - 1; i < prices.length; i++) {
866
+ const slice = prices.slice(i - period + 1, i + 1);
867
+ const high = Math.max(...slice);
868
+ const low = Math.min(...slice);
869
+ const close = prices[i];
870
+ const wr = (high - close) / (high - low) * -100;
871
+ williamsR.push(wr);
872
+ }
873
+ return williamsR;
874
+ }
875
+ // Calculate Momentum
876
+ calculateMomentum(prices) {
877
+ const momentum = [];
878
+ for (let i = 10; i < prices.length; i++) {
879
+ momentum.push(prices[i] - prices[i - 10]);
880
+ }
881
+ return momentum;
882
+ }
883
+ // Calculate Keltner Channels
884
+ calculateKeltnerChannels(prices, highs, lows) {
885
+ const keltner = [];
886
+ const period = 20;
887
+ const multiplier = 2;
888
+ if (prices.length < period) return [];
889
+ const ema = this.calculateEMA(prices, period);
890
+ const atr = this.calculateAtr(prices, highs, lows);
891
+ for (let i = 0; i < Math.min(ema.length, atr.length); i++) {
892
+ const middle = ema[i];
893
+ const atrValue = atr[i];
894
+ keltner.push({
895
+ upper: middle + multiplier * atrValue,
896
+ middle,
897
+ lower: middle - multiplier * atrValue
898
+ });
899
+ }
900
+ return keltner;
901
+ }
902
+ // Calculate Donchian Channels
903
+ calculateDonchianChannels(prices) {
904
+ const donchian = [];
905
+ for (let i = 20; i < prices.length; i++) {
906
+ const slice = prices.slice(i - 20, i);
907
+ donchian.push({
908
+ upper: Math.max(...slice),
909
+ middle: (Math.max(...slice) + Math.min(...slice)) / 2,
910
+ lower: Math.min(...slice)
911
+ });
912
+ }
913
+ return donchian;
914
+ }
915
+ // Calculate Chaikin Volatility
916
+ calculateChaikinVolatility(prices, highs, lows) {
917
+ const volatility = [];
918
+ const period = 10;
919
+ if (prices.length < period * 2) return [];
920
+ const highLowRange = [];
921
+ for (let i = 0; i < prices.length; i++) {
922
+ const high = highs[i] || prices[i];
923
+ const low = lows[i] || prices[i];
924
+ highLowRange.push(high - low);
925
+ }
926
+ const emaRange = this.calculateEMA(highLowRange, period);
927
+ for (let i = period; i < emaRange.length; i++) {
928
+ const currentEMA = emaRange[i];
929
+ const pastEMA = emaRange[i - period];
930
+ const volatilityValue = pastEMA !== 0 ? (currentEMA - pastEMA) / pastEMA * 100 : 0;
931
+ volatility.push(volatilityValue);
932
+ }
933
+ return volatility;
934
+ }
935
+ // Calculate On Balance Volume
936
+ calculateObv(volumes) {
937
+ const obv = [volumes[0]];
938
+ for (let i = 1; i < volumes.length; i++) {
939
+ obv.push(obv[i - 1] + volumes[i]);
940
+ }
941
+ return obv;
942
+ }
943
+ // Calculate Chaikin Money Flow
944
+ calculateCmf(prices, highs, lows, volumes) {
945
+ const cmf = [];
946
+ const period = 20;
947
+ if (prices.length < period) return [];
948
+ for (let i = period - 1; i < prices.length; i++) {
949
+ let totalMoneyFlowVolume = 0;
950
+ let totalVolume = 0;
951
+ for (let j = i - period + 1; j <= i; j++) {
952
+ const high = highs[j] || prices[j];
953
+ const low = lows[j] || prices[j];
954
+ const close = prices[j];
955
+ const volume = volumes[j] || 1;
956
+ const moneyFlowMultiplier = (close - low - (high - close)) / (high - low);
957
+ const moneyFlowVolume = moneyFlowMultiplier * volume;
958
+ totalMoneyFlowVolume += moneyFlowVolume;
959
+ totalVolume += volume;
960
+ }
961
+ const cmfValue = totalVolume !== 0 ? totalMoneyFlowVolume / totalVolume : 0;
962
+ cmf.push(cmfValue);
963
+ }
964
+ return cmf;
965
+ }
966
+ // Calculate Accumulation/Distribution Line
967
+ calculateAdl(prices) {
968
+ const adl = [0];
969
+ for (let i = 1; i < prices.length; i++) {
970
+ const high = this.highs[i] || prices[i];
971
+ const low = this.lows[i] || prices[i];
972
+ const close = prices[i];
973
+ const volume = this.volumes[i] || 1;
974
+ const moneyFlowMultiplier = (close - low - (high - close)) / (high - low);
975
+ const moneyFlowVolume = moneyFlowMultiplier * volume;
976
+ adl.push(adl[i - 1] + moneyFlowVolume);
977
+ }
978
+ return adl;
979
+ }
980
+ // Calculate Volume Rate of Change
981
+ calculateVolumeROC() {
982
+ const volumeROC = [];
983
+ for (let i = 10; i < this.volumes.length; i++) {
984
+ volumeROC.push((this.volumes[i] - this.volumes[i - 10]) / this.volumes[i - 10] * 100);
985
+ }
986
+ return volumeROC;
987
+ }
988
+ // Calculate Money Flow Index
989
+ calculateMfi(prices, highs, lows, volumes) {
990
+ const mfi = [];
991
+ const period = 14;
992
+ if (prices.length < period + 1) return [];
993
+ for (let i = period; i < prices.length; i++) {
994
+ let positiveMoneyFlow = 0;
995
+ let negativeMoneyFlow = 0;
996
+ for (let j = i - period + 1; j <= i; j++) {
997
+ const high = highs[j] || prices[j];
998
+ const low = lows[j] || prices[j];
999
+ const close = prices[j];
1000
+ const volume = volumes[j] || 1;
1001
+ const typicalPrice = (high + low + close) / 3;
1002
+ const moneyFlow = typicalPrice * volume;
1003
+ if (j > i - period + 1) {
1004
+ const prevHigh = highs[j - 1] || prices[j - 1];
1005
+ const prevLow = lows[j - 1] || prices[j - 1];
1006
+ const prevClose = prices[j - 1];
1007
+ const prevTypicalPrice = (prevHigh + prevLow + prevClose) / 3;
1008
+ if (typicalPrice > prevTypicalPrice) {
1009
+ positiveMoneyFlow += moneyFlow;
1010
+ } else if (typicalPrice < prevTypicalPrice) {
1011
+ negativeMoneyFlow += moneyFlow;
1012
+ }
1013
+ }
1014
+ }
1015
+ const moneyRatio = negativeMoneyFlow !== 0 ? positiveMoneyFlow / negativeMoneyFlow : 0;
1016
+ const mfiValue = 100 - 100 / (1 + moneyRatio);
1017
+ mfi.push(mfiValue);
1018
+ }
1019
+ return mfi;
1020
+ }
1021
+ // Calculate VWAP
1022
+ calculateVwap(prices, volumes) {
1023
+ const vwap = [];
1024
+ let cumulativePV = 0;
1025
+ let cumulativeVolume = 0;
1026
+ for (let i = 0; i < prices.length; i++) {
1027
+ cumulativePV += prices[i] * (volumes[i] || 1);
1028
+ cumulativeVolume += volumes[i] || 1;
1029
+ vwap.push(cumulativePV / cumulativeVolume);
1030
+ }
1031
+ return vwap;
1032
+ }
1033
+ // Calculate Pivot Points
1034
+ calculatePivotPoints(prices) {
1035
+ const pivotPoints = [];
1036
+ for (let i = 0; i < prices.length; i++) {
1037
+ const high = this.highs[i] || prices[i];
1038
+ const low = this.lows[i] || prices[i];
1039
+ const close = prices[i];
1040
+ const pp = (high + low + close) / 3;
1041
+ const r1 = 2 * pp - low;
1042
+ const s1 = 2 * pp - high;
1043
+ const r2 = pp + (high - low);
1044
+ const s2 = pp - (high - low);
1045
+ const r3 = high + 2 * (pp - low);
1046
+ const s3 = low - 2 * (high - pp);
1047
+ pivotPoints.push({
1048
+ pp,
1049
+ r1,
1050
+ r2,
1051
+ r3,
1052
+ s1,
1053
+ s2,
1054
+ s3
1055
+ });
1056
+ }
1057
+ return pivotPoints;
1058
+ }
1059
+ // Calculate Fibonacci Levels
1060
+ calculateFibonacciLevels(prices) {
1061
+ const fibonacci = [];
1062
+ for (let i = 0; i < prices.length; i++) {
1063
+ const price = prices[i];
1064
+ fibonacci.push({
1065
+ retracement: {
1066
+ level0: price,
1067
+ level236: price * 0.764,
1068
+ level382: price * 0.618,
1069
+ level500: price * 0.5,
1070
+ level618: price * 0.382,
1071
+ level786: price * 0.214,
1072
+ level100: price * 0
1073
+ },
1074
+ extension: {
1075
+ level1272: price * 1.272,
1076
+ level1618: price * 1.618,
1077
+ level2618: price * 2.618,
1078
+ level4236: price * 4.236
1079
+ }
1080
+ });
1081
+ }
1082
+ return fibonacci;
1083
+ }
1084
+ // Calculate Gann Levels
1085
+ calculateGannLevels(prices) {
1086
+ const gannLevels = [];
1087
+ for (let i = 0; i < prices.length; i++) {
1088
+ gannLevels.push(prices[i] * (1 + i * 0.01));
1089
+ }
1090
+ return gannLevels;
1091
+ }
1092
+ // Calculate Elliott Wave
1093
+ calculateElliottWave(prices) {
1094
+ const elliottWave = [];
1095
+ if (prices.length < 10) return [];
1096
+ for (let i = 0; i < prices.length; i++) {
1097
+ const waves = [];
1098
+ let currentWave = 1;
1099
+ let wavePosition = 0.5;
1100
+ if (i >= 4) {
1101
+ const recentPrices = prices.slice(i - 4, i + 1);
1102
+ const swings = this.detectPriceSwings(recentPrices);
1103
+ if (swings.length >= 3) {
1104
+ waves.push(...swings.slice(0, 3));
1105
+ currentWave = Math.min(swings.length, 5);
1106
+ wavePosition = this.calculateWavePosition(recentPrices);
1107
+ }
1108
+ }
1109
+ elliottWave.push({
1110
+ waves: waves.length > 0 ? waves : [prices[i]],
1111
+ currentWave,
1112
+ wavePosition
1113
+ });
1114
+ }
1115
+ return elliottWave;
1116
+ }
1117
+ // Helper method to detect price swings
1118
+ detectPriceSwings(prices) {
1119
+ const swings = [];
1120
+ for (let i = 1; i < prices.length - 1; i++) {
1121
+ const prev = prices[i - 1];
1122
+ const curr = prices[i];
1123
+ const next = prices[i + 1];
1124
+ if (curr > prev && curr > next) {
1125
+ swings.push(curr);
1126
+ } else if (curr < prev && curr < next) {
1127
+ swings.push(curr);
1128
+ }
1129
+ }
1130
+ return swings;
1131
+ }
1132
+ // Helper method to calculate wave position
1133
+ calculateWavePosition(prices) {
1134
+ if (prices.length < 2) return 0.5;
1135
+ const current = prices[prices.length - 1];
1136
+ const min = Math.min(...prices);
1137
+ const max = Math.max(...prices);
1138
+ return max !== min ? (current - min) / (max - min) : 0.5;
1139
+ }
1140
+ // Calculate Harmonic Patterns
1141
+ calculateHarmonicPatterns(prices) {
1142
+ const harmonicPatterns = [];
1143
+ if (prices.length < 5) return [];
1144
+ for (let i = 4; i < prices.length; i++) {
1145
+ const recentPrices = prices.slice(i - 4, i + 1);
1146
+ const pattern = this.detectHarmonicPattern(recentPrices);
1147
+ harmonicPatterns.push(pattern);
1148
+ }
1149
+ return harmonicPatterns;
1150
+ }
1151
+ // Helper method to detect harmonic patterns
1152
+ detectHarmonicPattern(prices) {
1153
+ if (prices.length < 5) {
1154
+ return {
1155
+ type: "Unknown",
1156
+ completion: 0,
1157
+ target: prices[prices.length - 1] * 1.1,
1158
+ stopLoss: prices[prices.length - 1] * 0.9
1159
+ };
1160
+ }
1161
+ const swings = this.detectPriceSwings(prices);
1162
+ if (swings.length < 4) {
1163
+ return {
1164
+ type: "Unknown",
1165
+ completion: 0,
1166
+ target: prices[prices.length - 1] * 1.1,
1167
+ stopLoss: prices[prices.length - 1] * 0.9
1168
+ };
1169
+ }
1170
+ const [A, B, C, D] = swings.slice(-4);
1171
+ const X = prices[0];
1172
+ const abRatio = Math.abs((B - A) / (X - A));
1173
+ const bcRatio = Math.abs((C - B) / (A - B));
1174
+ const cdRatio = Math.abs((D - C) / (B - C));
1175
+ const adRatio = Math.abs((D - A) / (X - A));
1176
+ 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;
1177
+ if (isGartley) {
1178
+ const completion = this.calculatePatternCompletion(prices);
1179
+ const target = D + (D - C) * 0.618;
1180
+ const stopLoss = D - (D - C) * 0.382;
1181
+ return {
1182
+ type: "Gartley",
1183
+ completion,
1184
+ target,
1185
+ stopLoss
1186
+ };
1187
+ }
1188
+ 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;
1189
+ if (isButterfly) {
1190
+ const completion = this.calculatePatternCompletion(prices);
1191
+ const target = D + (D - C) * 1.27;
1192
+ const stopLoss = D - (D - C) * 0.5;
1193
+ return {
1194
+ type: "Butterfly",
1195
+ completion,
1196
+ target,
1197
+ stopLoss
1198
+ };
1199
+ }
1200
+ return {
1201
+ type: "Unknown",
1202
+ completion: 0,
1203
+ target: prices[prices.length - 1] * 1.1,
1204
+ stopLoss: prices[prices.length - 1] * 0.9
1205
+ };
1206
+ }
1207
+ // Helper method to calculate pattern completion
1208
+ calculatePatternCompletion(prices) {
1209
+ if (prices.length < 2) return 0;
1210
+ const current = prices[prices.length - 1];
1211
+ const min = Math.min(...prices);
1212
+ const max = Math.max(...prices);
1213
+ return max !== min ? (current - min) / (max - min) : 0;
1214
+ }
1215
+ // Calculate Position Size
1216
+ calculatePositionSize(currentPrice, targetEntry, stopLoss) {
1217
+ void currentPrice;
1218
+ const riskPerShare = Math.abs(targetEntry - stopLoss);
1219
+ return riskPerShare > 0 ? 100 / riskPerShare : 1;
1220
+ }
1221
+ // Calculate Confidence
1222
+ calculateConfidence(signals) {
1223
+ return Math.min(signals.length * 10, 100);
1224
+ }
1225
+ // Calculate Risk Level
1226
+ calculateRiskLevel(volatility) {
1227
+ if (volatility < 20) return "LOW";
1228
+ if (volatility < 40) return "MEDIUM";
1229
+ return "HIGH";
1230
+ }
1231
+ // Calculate Z-Score
1232
+ calculateZScore(currentPrice, startPrice) {
1233
+ return (currentPrice - startPrice) / (startPrice * 0.1);
1234
+ }
1235
+ // Calculate Ornstein-Uhlenbeck
1236
+ calculateOrnsteinUhlenbeck(currentPrice, startPrice, avgVolume) {
1237
+ const priceChanges = this.calculatePriceChanges();
1238
+ const mean = startPrice;
1239
+ let speed = 0.1;
1240
+ if (priceChanges.length > 1) {
1241
+ const variance = priceChanges.reduce((sum2, change) => sum2 + change * change, 0) / priceChanges.length;
1242
+ speed = Math.max(0.01, Math.min(1, variance * 10));
1243
+ }
1244
+ const volatility = avgVolume * 0.01;
1245
+ return {
1246
+ mean,
1247
+ speed,
1248
+ volatility,
1249
+ currentValue: currentPrice
1250
+ };
1251
+ }
1252
+ // Calculate Kalman Filter
1253
+ calculateKalmanFilter(currentPrice, startPrice, avgVolume) {
1254
+ const measurementNoise = avgVolume * 1e-3;
1255
+ const processNoise = avgVolume * 1e-4;
1256
+ let state = startPrice;
1257
+ let covariance = measurementNoise;
1258
+ const priceChanges = this.calculatePriceChanges();
1259
+ if (priceChanges.length > 0) {
1260
+ const predictedState = state;
1261
+ const predictedCovariance = covariance + processNoise;
1262
+ const kalmanGain = predictedCovariance / (predictedCovariance + measurementNoise);
1263
+ state = predictedState + kalmanGain * (currentPrice - predictedState);
1264
+ covariance = (1 - kalmanGain) * predictedCovariance;
1265
+ return {
1266
+ state,
1267
+ covariance,
1268
+ gain: kalmanGain
1269
+ };
1270
+ }
1271
+ return {
1272
+ state: currentPrice,
1273
+ covariance,
1274
+ gain: 0.5
1275
+ };
1276
+ }
1277
+ // Calculate ARIMA
1278
+ calculateArima(currentPrice) {
1279
+ const priceChanges = this.calculatePriceChanges();
1280
+ if (priceChanges.length < 3) {
1281
+ return {
1282
+ forecast: [currentPrice * 1.01, currentPrice * 1.02],
1283
+ residuals: [0, 0],
1284
+ aic: 100
1285
+ };
1286
+ }
1287
+ const n = priceChanges.length;
1288
+ let sumY = 0;
1289
+ let sumY1 = 0;
1290
+ let sumYY1 = 0;
1291
+ let sumY1Sq = 0;
1292
+ for (let i = 1; i < n; i++) {
1293
+ const y = priceChanges[i];
1294
+ const y1 = priceChanges[i - 1];
1295
+ sumY += y;
1296
+ sumY1 += y1;
1297
+ sumYY1 += y * y1;
1298
+ sumY1Sq += y1 * y1;
1299
+ }
1300
+ const phi = (n * sumYY1 - sumY * sumY1) / (n * sumY1Sq - sumY1 * sumY1);
1301
+ const c = (sumY - phi * sumY1) / n;
1302
+ const residuals = [];
1303
+ for (let i = 1; i < n; i++) {
1304
+ const predicted = c + phi * priceChanges[i - 1];
1305
+ residuals.push(priceChanges[i] - predicted);
1306
+ }
1307
+ const rss = residuals.reduce((sum2, r) => sum2 + r * r, 0);
1308
+ const aic = n * Math.log(rss / n) + 2 * 2;
1309
+ const lastChange = priceChanges[priceChanges.length - 1];
1310
+ const forecast1 = currentPrice + (c + phi * lastChange);
1311
+ const forecast2 = forecast1 + (c + phi * (c + phi * lastChange));
1312
+ return {
1313
+ forecast: [forecast1, forecast2],
1314
+ residuals,
1315
+ aic
1316
+ };
1317
+ }
1318
+ // Calculate GARCH
1319
+ calculateGarch(avgVolume) {
1320
+ const priceChanges = this.calculatePriceChanges();
1321
+ if (priceChanges.length < 5) {
1322
+ return {
1323
+ volatility: avgVolume * 0.01,
1324
+ persistence: 0.9,
1325
+ meanReversion: 0.1
1326
+ };
1327
+ }
1328
+ const squaredReturns = priceChanges.map((change) => change * change);
1329
+ const meanSquaredReturn = squaredReturns.reduce((sum2, sq) => sum2 + sq, 0) / squaredReturns.length;
1330
+ let persistence = 0.9;
1331
+ if (squaredReturns.length > 1) {
1332
+ const variance = squaredReturns.reduce((sum2, sq) => sum2 + sq, 0) / squaredReturns.length;
1333
+ persistence = Math.min(0.99, Math.max(0.5, variance / meanSquaredReturn));
1334
+ }
1335
+ const meanReversion = meanSquaredReturn * (1 - persistence);
1336
+ const volatility = Math.sqrt(meanSquaredReturn);
1337
+ return {
1338
+ volatility,
1339
+ persistence,
1340
+ meanReversion
1341
+ };
1342
+ }
1343
+ // Calculate Hilbert Transform
1344
+ calculateHilbertTransform(currentPrice) {
1345
+ const priceChanges = this.calculatePriceChanges();
1346
+ if (priceChanges.length < 3) {
1347
+ return {
1348
+ analytic: [currentPrice],
1349
+ phase: [0],
1350
+ amplitude: [currentPrice]
1351
+ };
1352
+ }
1353
+ const n = priceChanges.length;
1354
+ const analytic = [];
1355
+ const phase = [];
1356
+ const amplitude = [];
1357
+ for (let i = 0; i < n; i++) {
1358
+ let hilbertValue = 0;
1359
+ for (let j = 0; j < n; j++) {
1360
+ if (i !== j) {
1361
+ hilbertValue += priceChanges[j] / (Math.PI * (i - j));
1362
+ }
1363
+ }
1364
+ const realPart = priceChanges[i];
1365
+ const imagPart = hilbertValue;
1366
+ const analyticValue = Math.sqrt(realPart * realPart + imagPart * imagPart);
1367
+ analytic.push(analyticValue);
1368
+ const phaseValue = Math.atan2(imagPart, realPart);
1369
+ phase.push(phaseValue);
1370
+ amplitude.push(analyticValue);
1371
+ }
1372
+ return {
1373
+ analytic,
1374
+ phase,
1375
+ amplitude
1376
+ };
1377
+ }
1378
+ // Calculate Wavelet Transform
1379
+ calculateWaveletTransform(currentPrice) {
1380
+ const priceChanges = this.calculatePriceChanges();
1381
+ if (priceChanges.length < 4) {
1382
+ return {
1383
+ coefficients: [currentPrice],
1384
+ scales: [1]
1385
+ };
1386
+ }
1387
+ const coefficients = [];
1388
+ const scales = [];
1389
+ const n = priceChanges.length;
1390
+ const maxLevel = Math.floor(Math.log2(n));
1391
+ for (let level = 1; level <= maxLevel; level++) {
1392
+ const step = 2 ** (level - 1);
1393
+ const scale = step;
1394
+ for (let i = 0; i < n - step; i += step * 2) {
1395
+ if (i + step < n) {
1396
+ const coefficient = (priceChanges[i] - priceChanges[i + step]) / Math.sqrt(2);
1397
+ coefficients.push(coefficient);
1398
+ scales.push(scale);
1399
+ }
1400
+ }
1401
+ }
1402
+ if (coefficients.length === 0) {
1403
+ coefficients.push(currentPrice);
1404
+ scales.push(1);
1405
+ }
1406
+ return {
1407
+ coefficients,
1408
+ scales
1409
+ };
1410
+ }
1411
+ // Calculate Black-Scholes
1412
+ calculateBlackScholes(currentPrice, startPrice, avgVolume) {
1413
+ const S = currentPrice;
1414
+ const K = startPrice;
1415
+ const T = 1;
1416
+ const r = 0.05;
1417
+ const sigma = avgVolume * 0.01;
1418
+ const d1 = (Math.log(S / K) + (r + sigma * sigma / 2) * T) / (sigma * Math.sqrt(T));
1419
+ const d2 = d1 - sigma * Math.sqrt(T);
1420
+ const callPrice = S * this.normalCDF(d1) - K * Math.exp(-r * T) * this.normalCDF(d2);
1421
+ const putPrice = K * Math.exp(-r * T) * this.normalCDF(-d2) - S * this.normalCDF(-d1);
1422
+ return {
1423
+ callPrice,
1424
+ putPrice,
1425
+ delta: this.normalCDF(d1),
1426
+ gamma: this.normalPDF(d1) / (S * sigma * Math.sqrt(T)),
1427
+ theta: -S * this.normalPDF(d1) * sigma / (2 * Math.sqrt(T)) - r * K * Math.exp(-r * T) * this.normalCDF(d2),
1428
+ vega: S * Math.sqrt(T) * this.normalPDF(d1),
1429
+ rho: K * T * Math.exp(-r * T) * this.normalCDF(d2)
1430
+ };
1431
+ }
1432
+ // Normal CDF approximation
1433
+ normalCDF(x) {
1434
+ return 0.5 * (1 + this.erf(x / Math.sqrt(2)));
1435
+ }
1436
+ // Normal PDF
1437
+ normalPDF(x) {
1438
+ return Math.exp(-x * x / 2) / Math.sqrt(2 * Math.PI);
1439
+ }
1440
+ // Error function approximation
1441
+ erf(x) {
1442
+ const a1 = 0.254829592;
1443
+ const a2 = -0.284496736;
1444
+ const a3 = 1.421413741;
1445
+ const a4 = -1.453152027;
1446
+ const a5 = 1.061405429;
1447
+ const p = 0.3275911;
1448
+ const sign = x >= 0 ? 1 : -1;
1449
+ const absX = Math.abs(x);
1450
+ const t = 1 / (1 + p * absX);
1451
+ const y = 1 - ((((a5 * t + a4) * t + a3) * t + a2) * t + a1) * t * Math.exp(-absX * absX);
1452
+ return sign * y;
1453
+ }
1454
+ // Calculate price changes for volatility
1455
+ calculatePriceChanges() {
1456
+ const changes = [];
1457
+ for (let i = 1; i < this.prices.length; i++) {
1458
+ changes.push((this.prices[i] - this.prices[i - 1]) / this.prices[i - 1]);
1459
+ }
1460
+ return changes;
1461
+ }
1462
+ // Generate comprehensive market analysis
1463
+ analyze() {
1464
+ const currentPrice = this.prices[this.prices.length - 1];
1465
+ const startPrice = this.prices[0];
1466
+ const sessionHigh = Math.max(...this.highs);
1467
+ const sessionLow = Math.min(...this.lows);
1468
+ const totalVolume = sum(this.volumes);
1469
+ const avgVolume = totalVolume / this.volumes.length;
1470
+ const priceChanges = this.calculatePriceChanges();
1471
+ const volatility = priceChanges.length > 0 ? Math.sqrt(
1472
+ priceChanges.reduce((sum2, change) => sum2 + change ** 2, 0) / priceChanges.length
1473
+ ) * Math.sqrt(252) * 100 : 0;
1474
+ const sessionReturn = (currentPrice - startPrice) / startPrice * 100;
1475
+ const pricePosition = (currentPrice - sessionLow) / (sessionHigh - sessionLow) * 100;
1476
+ const trueVWAP = this.prices.reduce((sum2, price, i) => sum2 + price * this.volumes[i], 0) / totalVolume;
1477
+ 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;
1478
+ 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;
1479
+ const maxDrawdown = this.calculateMaxDrawdown(this.prices);
1480
+ const atrValues = this.calculateAtr(this.prices, this.highs, this.lows);
1481
+ const atr = atrValues.length > 0 ? atrValues[atrValues.length - 1] : 0;
1482
+ const impliedVolatility = volatility;
1483
+ const realizedVolatility = volatility;
1484
+ const sharpeRatio = sessionReturn / volatility;
1485
+ const sortinoRatio = sessionReturn / realizedVolatility;
1486
+ const calmarRatio = sessionReturn / maxDrawdown;
1487
+ const maxConsecutiveLosses = this.calculateMaxConsecutiveLosses(this.prices);
1488
+ const winRate = this.calculateWinRate(this.prices);
1489
+ const profitFactor = this.calculateProfitFactor(this.prices);
1490
+ return {
1491
+ currentPrice,
1492
+ startPrice,
1493
+ sessionHigh,
1494
+ sessionLow,
1495
+ totalVolume,
1496
+ avgVolume,
1497
+ volatility,
1498
+ sessionReturn,
1499
+ pricePosition,
1500
+ trueVWAP,
1501
+ momentum5,
1502
+ momentum10,
1503
+ maxDrawdown,
1504
+ atr,
1505
+ impliedVolatility,
1506
+ realizedVolatility,
1507
+ sharpeRatio,
1508
+ sortinoRatio,
1509
+ calmarRatio,
1510
+ maxConsecutiveLosses,
1511
+ winRate,
1512
+ profitFactor
1513
+ };
1514
+ }
1515
+ // Generate technical indicators
1516
+ getTechnicalIndicators() {
1517
+ return {
1518
+ sma5: this.calculateSMA(this.prices, 5),
1519
+ sma10: this.calculateSMA(this.prices, 10),
1520
+ sma20: this.calculateSMA(this.prices, 20),
1521
+ sma50: this.calculateSMA(this.prices, 50),
1522
+ sma200: this.calculateSMA(this.prices, 200),
1523
+ ema8: this.calculateEMA(this.prices, 8),
1524
+ ema12: this.calculateEMA(this.prices, 12),
1525
+ ema21: this.calculateEMA(this.prices, 21),
1526
+ ema26: this.calculateEMA(this.prices, 26),
1527
+ wma20: this.calculateWma(this.prices, 20),
1528
+ vwma20: this.calculateVwma(this.prices, 20),
1529
+ macd: this.calculateMacd(this.prices),
1530
+ adx: this.calculateAdx(this.prices, this.highs, this.lows),
1531
+ dmi: this.calculateDmi(this.prices, this.highs, this.lows),
1532
+ ichimoku: this.calculateIchimoku(this.prices, this.highs, this.lows),
1533
+ parabolicSAR: this.calculateParabolicSAR(this.prices, this.highs, this.lows),
1534
+ rsi: this.calculateRSI(this.prices, 14),
1535
+ stochastic: this.calculateStochastic(this.prices, this.highs, this.lows),
1536
+ cci: this.calculateCci(this.prices, this.highs, this.lows),
1537
+ roc: this.calculateRoc(this.prices),
1538
+ williamsR: this.calculateWilliamsR(this.prices),
1539
+ momentum: this.calculateMomentum(this.prices),
1540
+ bollinger: this.calculateBollingerBands(this.prices, 20, 2),
1541
+ atr: this.calculateAtr(this.prices, this.highs, this.lows),
1542
+ keltner: this.calculateKeltnerChannels(this.prices, this.highs, this.lows),
1543
+ donchian: this.calculateDonchianChannels(this.prices),
1544
+ chaikinVolatility: this.calculateChaikinVolatility(this.prices, this.highs, this.lows),
1545
+ obv: this.calculateObv(this.volumes),
1546
+ cmf: this.calculateCmf(this.prices, this.highs, this.lows, this.volumes),
1547
+ adl: this.calculateAdl(this.prices),
1548
+ volumeROC: this.calculateVolumeROC(),
1549
+ mfi: this.calculateMfi(this.prices, this.highs, this.lows, this.volumes),
1550
+ vwap: this.calculateVwap(this.prices, this.volumes),
1551
+ pivotPoints: this.calculatePivotPoints(this.prices),
1552
+ fibonacci: this.calculateFibonacciLevels(this.prices),
1553
+ gannLevels: this.calculateGannLevels(this.prices),
1554
+ elliottWave: this.calculateElliottWave(this.prices),
1555
+ harmonicPatterns: this.calculateHarmonicPatterns(this.prices)
1556
+ };
1557
+ }
1558
+ // Generate trading signals
1559
+ generateSignals() {
1560
+ const analysis = this.analyze();
1561
+ let bullishSignals = 0;
1562
+ let bearishSignals = 0;
1563
+ const signals = [];
1564
+ if (analysis.currentPrice > analysis.trueVWAP) {
1565
+ signals.push(
1566
+ `\u2713 BULLISH: Price above VWAP (+${((analysis.currentPrice - analysis.trueVWAP) / analysis.trueVWAP * 100).toFixed(2)}%)`
1567
+ );
1568
+ bullishSignals++;
1569
+ } else {
1570
+ signals.push(
1571
+ `\u2717 BEARISH: Price below VWAP (${((analysis.currentPrice - analysis.trueVWAP) / analysis.trueVWAP * 100).toFixed(2)}%)`
1572
+ );
1573
+ bearishSignals++;
1574
+ }
1575
+ if (analysis.momentum5 > 0 && analysis.momentum10 > 0) {
1576
+ signals.push("\u2713 BULLISH: Positive momentum on both timeframes");
1577
+ bullishSignals++;
1578
+ } else if (analysis.momentum5 < 0 && analysis.momentum10 < 0) {
1579
+ signals.push("\u2717 BEARISH: Negative momentum on both timeframes");
1580
+ bearishSignals++;
1581
+ } else {
1582
+ signals.push("\u25D0 MIXED: Conflicting momentum signals");
1583
+ }
1584
+ const currentVolume = this.volumes[this.volumes.length - 1];
1585
+ const volumeRatio = currentVolume / analysis.avgVolume;
1586
+ if (volumeRatio > 1.2 && analysis.sessionReturn > 0) {
1587
+ signals.push("\u2713 BULLISH: Above-average volume supporting upward move");
1588
+ bullishSignals++;
1589
+ } else if (volumeRatio > 1.2 && analysis.sessionReturn < 0) {
1590
+ signals.push("\u2717 BEARISH: Above-average volume supporting downward move");
1591
+ bearishSignals++;
1592
+ } else {
1593
+ signals.push("\u25D0 NEUTRAL: Volume not providing clear direction");
1594
+ }
1595
+ if (analysis.pricePosition > 65 && analysis.volatility > 30) {
1596
+ signals.push("\u2717 BEARISH: High in range with elevated volatility - reversal risk");
1597
+ bearishSignals++;
1598
+ } else if (analysis.pricePosition < 35 && analysis.volatility > 30) {
1599
+ signals.push("\u2713 BULLISH: Low in range with volatility - potential bounce");
1600
+ bullishSignals++;
1601
+ } else {
1602
+ signals.push("\u25D0 NEUTRAL: Price position and volatility not extreme");
1603
+ }
1604
+ return { bullishSignals, bearishSignals, signals };
1605
+ }
1606
+ // Generate comprehensive JSON analysis
1607
+ generateJSONAnalysis(symbol) {
1608
+ const analysis = this.analyze();
1609
+ const indicators = this.getTechnicalIndicators();
1610
+ const signals = this.generateSignals();
1611
+ const currentSMA5 = indicators.sma5.length > 0 ? indicators.sma5[indicators.sma5.length - 1] : null;
1612
+ const currentSMA10 = indicators.sma10.length > 0 ? indicators.sma10[indicators.sma10.length - 1] : null;
1613
+ const currentSMA20 = indicators.sma20.length > 0 ? indicators.sma20[indicators.sma20.length - 1] : null;
1614
+ const currentSMA50 = indicators.sma50.length > 0 ? indicators.sma50[indicators.sma50.length - 1] : null;
1615
+ const currentSMA200 = indicators.sma200.length > 0 ? indicators.sma200[indicators.sma200.length - 1] : null;
1616
+ const currentEMA8 = indicators.ema8[indicators.ema8.length - 1];
1617
+ const currentEMA12 = indicators.ema12[indicators.ema12.length - 1];
1618
+ const currentEMA21 = indicators.ema21[indicators.ema21.length - 1];
1619
+ const currentEMA26 = indicators.ema26[indicators.ema26.length - 1];
1620
+ const currentWMA20 = indicators.wma20.length > 0 ? indicators.wma20[indicators.wma20.length - 1] : null;
1621
+ const currentVWMA20 = indicators.vwma20.length > 0 ? indicators.vwma20[indicators.vwma20.length - 1] : null;
1622
+ const currentMACD = indicators.macd.length > 0 ? indicators.macd[indicators.macd.length - 1] : null;
1623
+ const currentADX = indicators.adx.length > 0 ? indicators.adx[indicators.adx.length - 1] : null;
1624
+ const currentDMI = indicators.dmi.length > 0 ? indicators.dmi[indicators.dmi.length - 1] : null;
1625
+ const currentIchimoku = indicators.ichimoku.length > 0 ? indicators.ichimoku[indicators.ichimoku.length - 1] : null;
1626
+ const currentParabolicSAR = indicators.parabolicSAR.length > 0 ? indicators.parabolicSAR[indicators.parabolicSAR.length - 1] : null;
1627
+ const currentRSI = indicators.rsi.length > 0 ? indicators.rsi[indicators.rsi.length - 1] : null;
1628
+ const currentStochastic = indicators.stochastic.length > 0 ? indicators.stochastic[indicators.stochastic.length - 1] : null;
1629
+ const currentCCI = indicators.cci.length > 0 ? indicators.cci[indicators.cci.length - 1] : null;
1630
+ const currentROC = indicators.roc.length > 0 ? indicators.roc[indicators.roc.length - 1] : null;
1631
+ const currentWilliamsR = indicators.williamsR.length > 0 ? indicators.williamsR[indicators.williamsR.length - 1] : null;
1632
+ const currentMomentum = indicators.momentum.length > 0 ? indicators.momentum[indicators.momentum.length - 1] : null;
1633
+ const currentBB = indicators.bollinger.length > 0 ? indicators.bollinger[indicators.bollinger.length - 1] : null;
1634
+ const currentAtr = indicators.atr.length > 0 ? indicators.atr[indicators.atr.length - 1] : null;
1635
+ const currentKeltner = indicators.keltner.length > 0 ? indicators.keltner[indicators.keltner.length - 1] : null;
1636
+ const currentDonchian = indicators.donchian.length > 0 ? indicators.donchian[indicators.donchian.length - 1] : null;
1637
+ const currentChaikinVolatility = indicators.chaikinVolatility.length > 0 ? indicators.chaikinVolatility[indicators.chaikinVolatility.length - 1] : null;
1638
+ const currentObv = indicators.obv.length > 0 ? indicators.obv[indicators.obv.length - 1] : null;
1639
+ const currentCmf = indicators.cmf.length > 0 ? indicators.cmf[indicators.cmf.length - 1] : null;
1640
+ const currentAdl = indicators.adl.length > 0 ? indicators.adl[indicators.adl.length - 1] : null;
1641
+ const currentVolumeROC = indicators.volumeROC.length > 0 ? indicators.volumeROC[indicators.volumeROC.length - 1] : null;
1642
+ const currentMfi = indicators.mfi.length > 0 ? indicators.mfi[indicators.mfi.length - 1] : null;
1643
+ const currentVwap = indicators.vwap.length > 0 ? indicators.vwap[indicators.vwap.length - 1] : null;
1644
+ const currentPivotPoints = indicators.pivotPoints.length > 0 ? indicators.pivotPoints[indicators.pivotPoints.length - 1] : null;
1645
+ const currentFibonacci = indicators.fibonacci.length > 0 ? indicators.fibonacci[indicators.fibonacci.length - 1] : null;
1646
+ const currentGannLevels = indicators.gannLevels.length > 0 ? indicators.gannLevels : [];
1647
+ const currentElliottWave = indicators.elliottWave.length > 0 ? indicators.elliottWave[indicators.elliottWave.length - 1] : null;
1648
+ const currentHarmonicPatterns = indicators.harmonicPatterns.length > 0 ? indicators.harmonicPatterns : [];
1649
+ const currentVolume = this.volumes[this.volumes.length - 1];
1650
+ const volumeRatio = currentVolume / analysis.avgVolume;
1651
+ const currentDrawdown = (analysis.sessionHigh - analysis.currentPrice) / analysis.sessionHigh * 100;
1652
+ const rangeWidth = (analysis.sessionHigh - analysis.sessionLow) / analysis.sessionLow * 100;
1653
+ const priceVsVWAP = (analysis.currentPrice - analysis.trueVWAP) / analysis.trueVWAP * 100;
1654
+ const totalScore = signals.bullishSignals - signals.bearishSignals;
1655
+ const overallSignal = totalScore > 0 ? "BULLISH_BIAS" : totalScore < 0 ? "BEARISH_BIAS" : "NEUTRAL";
1656
+ const targetEntry = Math.max(analysis.sessionLow * 1.005, analysis.trueVWAP * 0.998);
1657
+ const stopLoss = analysis.sessionLow * 0.995;
1658
+ const profitTarget = analysis.sessionHigh * 0.995;
1659
+ const riskRewardRatio = (profitTarget - analysis.currentPrice) / (analysis.currentPrice - stopLoss);
1660
+ const positionSize = this.calculatePositionSize(analysis.currentPrice, targetEntry, stopLoss);
1661
+ const maxRisk = positionSize * (targetEntry - stopLoss);
1662
+ return {
1663
+ symbol,
1664
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1665
+ marketStructure: {
1666
+ currentPrice: analysis.currentPrice,
1667
+ startPrice: analysis.startPrice,
1668
+ sessionHigh: analysis.sessionHigh,
1669
+ sessionLow: analysis.sessionLow,
1670
+ rangeWidth,
1671
+ totalVolume: analysis.totalVolume,
1672
+ sessionPerformance: analysis.sessionReturn,
1673
+ positionInRange: analysis.pricePosition
1674
+ },
1675
+ volatility: {
1676
+ impliedVolatility: analysis.impliedVolatility,
1677
+ realizedVolatility: analysis.realizedVolatility,
1678
+ atr: analysis.atr,
1679
+ maxDrawdown: analysis.maxDrawdown * 100,
1680
+ currentDrawdown
1681
+ },
1682
+ technicalIndicators: {
1683
+ sma5: currentSMA5,
1684
+ sma10: currentSMA10,
1685
+ sma20: currentSMA20,
1686
+ sma50: currentSMA50,
1687
+ sma200: currentSMA200,
1688
+ ema8: currentEMA8,
1689
+ ema12: currentEMA12,
1690
+ ema21: currentEMA21,
1691
+ ema26: currentEMA26,
1692
+ wma20: currentWMA20,
1693
+ vwma20: currentVWMA20,
1694
+ macd: currentMACD,
1695
+ adx: currentADX,
1696
+ dmi: currentDMI,
1697
+ ichimoku: currentIchimoku,
1698
+ parabolicSAR: currentParabolicSAR,
1699
+ rsi: currentRSI,
1700
+ stochastic: currentStochastic,
1701
+ cci: currentCCI,
1702
+ roc: currentROC,
1703
+ williamsR: currentWilliamsR,
1704
+ momentum: currentMomentum,
1705
+ bollingerBands: currentBB ? {
1706
+ upper: currentBB.upper,
1707
+ middle: currentBB.middle,
1708
+ lower: currentBB.lower,
1709
+ bandwidth: currentBB.bandwidth,
1710
+ percentB: currentBB.percentB
1711
+ } : null,
1712
+ atr: currentAtr,
1713
+ keltnerChannels: currentKeltner ? {
1714
+ upper: currentKeltner.upper,
1715
+ middle: currentKeltner.middle,
1716
+ lower: currentKeltner.lower
1717
+ } : null,
1718
+ donchianChannels: currentDonchian ? {
1719
+ upper: currentDonchian.upper,
1720
+ middle: currentDonchian.middle,
1721
+ lower: currentDonchian.lower
1722
+ } : null,
1723
+ chaikinVolatility: currentChaikinVolatility,
1724
+ obv: currentObv,
1725
+ cmf: currentCmf,
1726
+ adl: currentAdl,
1727
+ volumeROC: currentVolumeROC,
1728
+ mfi: currentMfi,
1729
+ vwap: currentVwap
1730
+ },
1731
+ volumeAnalysis: {
1732
+ currentVolume,
1733
+ averageVolume: Math.round(analysis.avgVolume),
1734
+ volumeRatio,
1735
+ trueVWAP: analysis.trueVWAP,
1736
+ priceVsVWAP,
1737
+ obv: currentObv,
1738
+ cmf: currentCmf,
1739
+ mfi: currentMfi
1740
+ },
1741
+ momentum: {
1742
+ momentum5: analysis.momentum5,
1743
+ momentum10: analysis.momentum10,
1744
+ sessionROC: analysis.sessionReturn,
1745
+ rsi: currentRSI,
1746
+ stochastic: currentStochastic,
1747
+ cci: currentCCI
1748
+ },
1749
+ supportResistance: {
1750
+ pivotPoints: currentPivotPoints,
1751
+ fibonacci: currentFibonacci,
1752
+ gannLevels: currentGannLevels,
1753
+ elliottWave: currentElliottWave,
1754
+ harmonicPatterns: currentHarmonicPatterns
1755
+ },
1756
+ tradingSignals: {
1757
+ ...signals,
1758
+ overallSignal,
1759
+ signalScore: totalScore,
1760
+ confidence: this.calculateConfidence(signals.signals),
1761
+ riskLevel: this.calculateRiskLevel(analysis.volatility)
1762
+ },
1763
+ statisticalModels: {
1764
+ zScore: this.calculateZScore(analysis.currentPrice, analysis.startPrice),
1765
+ ornsteinUhlenbeck: this.calculateOrnsteinUhlenbeck(
1766
+ analysis.currentPrice,
1767
+ analysis.startPrice,
1768
+ analysis.avgVolume
1769
+ ),
1770
+ kalmanFilter: this.calculateKalmanFilter(
1771
+ analysis.currentPrice,
1772
+ analysis.startPrice,
1773
+ analysis.avgVolume
1774
+ ),
1775
+ arima: this.calculateArima(analysis.currentPrice),
1776
+ garch: this.calculateGarch(analysis.avgVolume),
1777
+ hilbertTransform: this.calculateHilbertTransform(analysis.currentPrice),
1778
+ waveletTransform: this.calculateWaveletTransform(analysis.currentPrice)
1779
+ },
1780
+ optionsAnalysis: (() => {
1781
+ const blackScholes = this.calculateBlackScholes(
1782
+ analysis.currentPrice,
1783
+ analysis.startPrice,
1784
+ analysis.avgVolume
1785
+ );
1786
+ if (!blackScholes) return null;
1787
+ return {
1788
+ blackScholes,
1789
+ impliedVolatility: analysis.impliedVolatility,
1790
+ delta: blackScholes.delta,
1791
+ gamma: blackScholes.gamma,
1792
+ theta: blackScholes.theta,
1793
+ vega: blackScholes.vega,
1794
+ rho: blackScholes.rho,
1795
+ greeks: {
1796
+ delta: blackScholes.delta,
1797
+ gamma: blackScholes.gamma,
1798
+ theta: blackScholes.theta,
1799
+ vega: blackScholes.vega,
1800
+ rho: blackScholes.rho
1801
+ }
1802
+ };
1803
+ })(),
1804
+ riskManagement: {
1805
+ targetEntry,
1806
+ stopLoss,
1807
+ profitTarget,
1808
+ riskRewardRatio,
1809
+ positionSize,
1810
+ maxRisk
1811
+ },
1812
+ performance: {
1813
+ sharpeRatio: analysis.sharpeRatio,
1814
+ sortinoRatio: analysis.sortinoRatio,
1815
+ calmarRatio: analysis.calmarRatio,
1816
+ maxDrawdown: analysis.maxDrawdown * 100,
1817
+ winRate: analysis.winRate,
1818
+ profitFactor: analysis.profitFactor,
1819
+ totalReturn: analysis.sessionReturn,
1820
+ volatility: analysis.volatility
1821
+ }
1822
+ };
1823
+ }
1824
+ };
1825
+ var createTechnicalAnalysisHandler = (marketDataPrices) => {
1826
+ return async (args) => {
1827
+ try {
1828
+ const symbol = args.symbol;
1829
+ const priceHistory = marketDataPrices.get(symbol) || [];
1830
+ if (priceHistory.length === 0) {
1831
+ return {
1832
+ content: [
1833
+ {
1834
+ type: "text",
1835
+ text: `No price data available for ${symbol}. Please request market data first.`,
1836
+ uri: "technicalAnalysis"
1837
+ }
1838
+ ]
1839
+ };
1840
+ }
1841
+ const hasValidData = priceHistory.every(
1842
+ (entry) => typeof entry.trade === "number" && !Number.isNaN(entry.trade) && typeof entry.midPrice === "number" && !Number.isNaN(entry.midPrice)
1843
+ );
1844
+ if (!hasValidData) {
1845
+ throw new Error("Invalid market data");
1846
+ }
1847
+ const analyzer = new TechnicalAnalyzer(priceHistory);
1848
+ const analysis = analyzer.generateJSONAnalysis(symbol);
1849
+ return {
1850
+ content: [
1851
+ {
1852
+ type: "text",
1853
+ text: `Technical Analysis for ${symbol}:
1854
+
1855
+ ${JSON.stringify(analysis, null, 2)}`,
1856
+ uri: "technicalAnalysis"
1857
+ }
1858
+ ]
1859
+ };
1860
+ } catch (error) {
1861
+ return {
1862
+ content: [
1863
+ {
1864
+ type: "text",
1865
+ text: `Error performing technical analysis: ${error instanceof Error ? error.message : "Unknown error"}`,
1866
+ uri: "technicalAnalysis"
1867
+ }
1868
+ ],
1869
+ isError: true
1870
+ };
1871
+ }
1872
+ };
1873
+ };
1874
+
1875
+ // src/tools/marketData.ts
1876
+ var import_fixparser = require("fixparser");
1877
+ var import_quickchart_js = __toESM(require("quickchart-js"), 1);
1878
+ var createMarketDataRequestHandler = (parser, pendingRequests) => {
1879
+ return async (args) => {
1880
+ try {
1881
+ parser.logger.log({
1882
+ level: "info",
1883
+ message: `Sending market data request for symbols: ${args.symbols.join(", ")}`
1884
+ });
1885
+ const response = new Promise((resolve) => {
1886
+ pendingRequests.set(args.mdReqID, resolve);
1887
+ parser.logger.log({
1888
+ level: "info",
1889
+ message: `Registered callback for market data request ID: ${args.mdReqID}`
1890
+ });
1891
+ });
1892
+ const entryTypes = args.mdEntryTypes || [
1893
+ import_fixparser.MDEntryType.Bid,
1894
+ import_fixparser.MDEntryType.Offer,
1895
+ import_fixparser.MDEntryType.Trade,
1896
+ import_fixparser.MDEntryType.IndexValue,
1897
+ import_fixparser.MDEntryType.OpeningPrice,
1898
+ import_fixparser.MDEntryType.ClosingPrice,
1899
+ import_fixparser.MDEntryType.SettlementPrice,
1900
+ import_fixparser.MDEntryType.TradingSessionHighPrice,
1901
+ import_fixparser.MDEntryType.TradingSessionLowPrice,
1902
+ import_fixparser.MDEntryType.VWAP,
1903
+ import_fixparser.MDEntryType.Imbalance,
1904
+ import_fixparser.MDEntryType.TradeVolume,
1905
+ import_fixparser.MDEntryType.OpenInterest,
1906
+ import_fixparser.MDEntryType.CompositeUnderlyingPrice,
1907
+ import_fixparser.MDEntryType.SimulatedSellPrice,
1908
+ import_fixparser.MDEntryType.SimulatedBuyPrice,
1909
+ import_fixparser.MDEntryType.MarginRate,
1910
+ import_fixparser.MDEntryType.MidPrice,
1911
+ import_fixparser.MDEntryType.EmptyBook,
1912
+ import_fixparser.MDEntryType.SettleHighPrice,
1913
+ import_fixparser.MDEntryType.SettleLowPrice,
1914
+ import_fixparser.MDEntryType.PriorSettlePrice,
1915
+ import_fixparser.MDEntryType.SessionHighBid,
1916
+ import_fixparser.MDEntryType.SessionLowOffer,
1917
+ import_fixparser.MDEntryType.EarlyPrices,
1918
+ import_fixparser.MDEntryType.AuctionClearingPrice,
1919
+ import_fixparser.MDEntryType.SwapValueFactor,
1920
+ import_fixparser.MDEntryType.DailyValueAdjustmentForLongPositions,
1921
+ import_fixparser.MDEntryType.CumulativeValueAdjustmentForLongPositions,
1922
+ import_fixparser.MDEntryType.DailyValueAdjustmentForShortPositions,
1923
+ import_fixparser.MDEntryType.CumulativeValueAdjustmentForShortPositions,
1924
+ import_fixparser.MDEntryType.FixingPrice,
1925
+ import_fixparser.MDEntryType.CashRate,
1926
+ import_fixparser.MDEntryType.RecoveryRate,
1927
+ import_fixparser.MDEntryType.RecoveryRateForLong,
1928
+ import_fixparser.MDEntryType.RecoveryRateForShort,
1929
+ import_fixparser.MDEntryType.MarketBid,
1930
+ import_fixparser.MDEntryType.MarketOffer,
1931
+ import_fixparser.MDEntryType.ShortSaleMinPrice,
1932
+ import_fixparser.MDEntryType.PreviousClosingPrice,
1933
+ import_fixparser.MDEntryType.ThresholdLimitPriceBanding,
1934
+ import_fixparser.MDEntryType.DailyFinancingValue,
1935
+ import_fixparser.MDEntryType.AccruedFinancingValue,
1936
+ import_fixparser.MDEntryType.TWAP
1937
+ ];
1938
+ const messageFields = [
1939
+ new import_fixparser.Field(import_fixparser.Fields.MsgType, import_fixparser.Messages.MarketDataRequest),
1940
+ new import_fixparser.Field(import_fixparser.Fields.SenderCompID, parser.sender),
1941
+ new import_fixparser.Field(import_fixparser.Fields.MsgSeqNum, parser.getNextTargetMsgSeqNum()),
1942
+ new import_fixparser.Field(import_fixparser.Fields.TargetCompID, parser.target),
1943
+ new import_fixparser.Field(import_fixparser.Fields.SendingTime, parser.getTimestamp()),
1944
+ new import_fixparser.Field(import_fixparser.Fields.MDReqID, args.mdReqID),
1945
+ new import_fixparser.Field(import_fixparser.Fields.SubscriptionRequestType, args.subscriptionRequestType),
1946
+ new import_fixparser.Field(import_fixparser.Fields.MarketDepth, 0),
1947
+ new import_fixparser.Field(import_fixparser.Fields.MDUpdateType, args.mdUpdateType)
1948
+ ];
1949
+ messageFields.push(new import_fixparser.Field(import_fixparser.Fields.NoRelatedSym, args.symbols.length));
1950
+ args.symbols.forEach((symbol) => {
1951
+ messageFields.push(new import_fixparser.Field(import_fixparser.Fields.Symbol, symbol));
1952
+ });
1953
+ messageFields.push(new import_fixparser.Field(import_fixparser.Fields.NoMDEntryTypes, entryTypes.length));
1954
+ entryTypes.forEach((entryType) => {
1955
+ messageFields.push(new import_fixparser.Field(import_fixparser.Fields.MDEntryType, entryType));
1956
+ });
1957
+ const mdr = parser.createMessage(...messageFields);
1958
+ if (!parser.connected) {
1959
+ parser.logger.log({
1960
+ level: "error",
1961
+ message: "Not connected. Cannot send market data request."
1962
+ });
1963
+ return {
1964
+ content: [
1965
+ {
1966
+ type: "text",
1967
+ text: "Error: Not connected. Ignoring message.",
1968
+ uri: "marketDataRequest"
1969
+ }
1970
+ ],
1971
+ isError: true
1972
+ };
1973
+ }
1974
+ parser.logger.log({
1975
+ level: "info",
1976
+ message: `Sending market data request message: ${JSON.stringify(mdr?.toFIXJSON())}`
1977
+ });
1978
+ parser.send(mdr);
1979
+ const fixData = await response;
1980
+ parser.logger.log({
1981
+ level: "info",
1982
+ message: `Received market data response for request ID: ${args.mdReqID}`
1983
+ });
1984
+ return {
1985
+ content: [
1986
+ {
1987
+ type: "text",
1988
+ text: `Market data for ${args.symbols.join(", ")}: ${JSON.stringify(fixData.toFIXJSON())}`,
1989
+ uri: "marketDataRequest"
1990
+ }
1991
+ ]
1992
+ };
1993
+ } catch (error) {
1994
+ return {
1995
+ content: [
1996
+ {
1997
+ type: "text",
1998
+ text: `Error: ${error instanceof Error ? error.message : "Failed to request market data"}`,
1999
+ uri: "marketDataRequest"
2000
+ }
2001
+ ],
2002
+ isError: true
2003
+ };
2004
+ }
2005
+ };
2006
+ };
2007
+ var aggregateMarketData = (priceHistory, maxPoints = 490) => {
2008
+ if (priceHistory.length <= maxPoints) {
2009
+ return priceHistory;
2010
+ }
2011
+ const result = [];
2012
+ const step = priceHistory.length / maxPoints;
2013
+ result.push(priceHistory[0]);
2014
+ for (let i = 1; i < maxPoints - 1; i++) {
2015
+ const startIndex = Math.floor(i * step);
2016
+ const endIndex = Math.floor((i + 1) * step);
2017
+ const segment = priceHistory.slice(startIndex, endIndex);
2018
+ if (segment.length === 0) continue;
2019
+ const aggregatedPoint = {
2020
+ timestamp: segment[0].timestamp,
2021
+ // Use timestamp of first point in segment
2022
+ bid: segment.reduce((sum2, p) => sum2 + p.bid, 0) / segment.length,
2023
+ offer: segment.reduce((sum2, p) => sum2 + p.offer, 0) / segment.length,
2024
+ spread: segment.reduce((sum2, p) => sum2 + p.spread, 0) / segment.length,
2025
+ volume: segment.reduce((sum2, p) => sum2 + p.volume, 0) / segment.length,
2026
+ trade: segment.reduce((sum2, p) => sum2 + p.trade, 0) / segment.length,
2027
+ indexValue: segment.reduce((sum2, p) => sum2 + p.indexValue, 0) / segment.length,
2028
+ openingPrice: segment.reduce((sum2, p) => sum2 + p.openingPrice, 0) / segment.length,
2029
+ closingPrice: segment.reduce((sum2, p) => sum2 + p.closingPrice, 0) / segment.length,
2030
+ settlementPrice: segment.reduce((sum2, p) => sum2 + p.settlementPrice, 0) / segment.length,
2031
+ tradingSessionHighPrice: segment.reduce((sum2, p) => sum2 + p.tradingSessionHighPrice, 0) / segment.length,
2032
+ tradingSessionLowPrice: segment.reduce((sum2, p) => sum2 + p.tradingSessionLowPrice, 0) / segment.length,
2033
+ vwap: segment.reduce((sum2, p) => sum2 + p.vwap, 0) / segment.length,
2034
+ imbalance: segment.reduce((sum2, p) => sum2 + p.imbalance, 0) / segment.length,
2035
+ openInterest: segment.reduce((sum2, p) => sum2 + p.openInterest, 0) / segment.length,
2036
+ compositeUnderlyingPrice: segment.reduce((sum2, p) => sum2 + p.compositeUnderlyingPrice, 0) / segment.length,
2037
+ simulatedSellPrice: segment.reduce((sum2, p) => sum2 + p.simulatedSellPrice, 0) / segment.length,
2038
+ simulatedBuyPrice: segment.reduce((sum2, p) => sum2 + p.simulatedBuyPrice, 0) / segment.length,
2039
+ marginRate: segment.reduce((sum2, p) => sum2 + p.marginRate, 0) / segment.length,
2040
+ midPrice: segment.reduce((sum2, p) => sum2 + p.midPrice, 0) / segment.length,
2041
+ emptyBook: segment.reduce((sum2, p) => sum2 + p.emptyBook, 0) / segment.length,
2042
+ settleHighPrice: segment.reduce((sum2, p) => sum2 + p.settleHighPrice, 0) / segment.length,
2043
+ settleLowPrice: segment.reduce((sum2, p) => sum2 + p.settleLowPrice, 0) / segment.length,
2044
+ priorSettlePrice: segment.reduce((sum2, p) => sum2 + p.priorSettlePrice, 0) / segment.length,
2045
+ sessionHighBid: segment.reduce((sum2, p) => sum2 + p.sessionHighBid, 0) / segment.length,
2046
+ sessionLowOffer: segment.reduce((sum2, p) => sum2 + p.sessionLowOffer, 0) / segment.length,
2047
+ earlyPrices: segment.reduce((sum2, p) => sum2 + p.earlyPrices, 0) / segment.length,
2048
+ auctionClearingPrice: segment.reduce((sum2, p) => sum2 + p.auctionClearingPrice, 0) / segment.length,
2049
+ swapValueFactor: segment.reduce((sum2, p) => sum2 + p.swapValueFactor, 0) / segment.length,
2050
+ dailyValueAdjustmentForLongPositions: segment.reduce((sum2, p) => sum2 + p.dailyValueAdjustmentForLongPositions, 0) / segment.length,
2051
+ cumulativeValueAdjustmentForLongPositions: segment.reduce((sum2, p) => sum2 + p.cumulativeValueAdjustmentForLongPositions, 0) / segment.length,
2052
+ dailyValueAdjustmentForShortPositions: segment.reduce((sum2, p) => sum2 + p.dailyValueAdjustmentForShortPositions, 0) / segment.length,
2053
+ cumulativeValueAdjustmentForShortPositions: segment.reduce((sum2, p) => sum2 + p.cumulativeValueAdjustmentForShortPositions, 0) / segment.length,
2054
+ fixingPrice: segment.reduce((sum2, p) => sum2 + p.fixingPrice, 0) / segment.length,
2055
+ cashRate: segment.reduce((sum2, p) => sum2 + p.cashRate, 0) / segment.length,
2056
+ recoveryRate: segment.reduce((sum2, p) => sum2 + p.recoveryRate, 0) / segment.length,
2057
+ recoveryRateForLong: segment.reduce((sum2, p) => sum2 + p.recoveryRateForLong, 0) / segment.length,
2058
+ recoveryRateForShort: segment.reduce((sum2, p) => sum2 + p.recoveryRateForShort, 0) / segment.length,
2059
+ marketBid: segment.reduce((sum2, p) => sum2 + p.marketBid, 0) / segment.length,
2060
+ marketOffer: segment.reduce((sum2, p) => sum2 + p.marketOffer, 0) / segment.length,
2061
+ shortSaleMinPrice: segment.reduce((sum2, p) => sum2 + p.shortSaleMinPrice, 0) / segment.length,
2062
+ previousClosingPrice: segment.reduce((sum2, p) => sum2 + p.previousClosingPrice, 0) / segment.length,
2063
+ thresholdLimitPriceBanding: segment.reduce((sum2, p) => sum2 + p.thresholdLimitPriceBanding, 0) / segment.length,
2064
+ dailyFinancingValue: segment.reduce((sum2, p) => sum2 + p.dailyFinancingValue, 0) / segment.length,
2065
+ accruedFinancingValue: segment.reduce((sum2, p) => sum2 + p.accruedFinancingValue, 0) / segment.length,
2066
+ twap: segment.reduce((sum2, p) => sum2 + p.twap, 0) / segment.length
2067
+ };
2068
+ result.push(aggregatedPoint);
2069
+ }
2070
+ result.push(priceHistory[priceHistory.length - 1]);
2071
+ return result;
2072
+ };
2073
+ var createGetStockGraphHandler = (marketDataPrices) => {
2074
+ return async (args) => {
2075
+ try {
2076
+ const symbol = args.symbol;
2077
+ const priceHistory = marketDataPrices.get(symbol) || [];
2078
+ if (priceHistory.length === 0) {
2079
+ return {
2080
+ content: [
2081
+ {
2082
+ type: "text",
2083
+ text: `No price data available for ${symbol}`,
2084
+ uri: "getStockGraph"
2085
+ }
2086
+ ]
2087
+ };
2088
+ }
2089
+ const aggregatedData = aggregateMarketData(priceHistory, 500);
2090
+ const chart = new import_quickchart_js.default();
2091
+ chart.setWidth(1200);
2092
+ chart.setHeight(600);
2093
+ chart.setBackgroundColor("transparent");
2094
+ const labels = aggregatedData.map((point) => new Date(point.timestamp).toLocaleTimeString());
2095
+ const bidData = aggregatedData.map((point) => point.bid);
2096
+ const offerData = aggregatedData.map((point) => point.offer);
2097
+ const spreadData = aggregatedData.map((point) => point.spread);
2098
+ const volumeData = aggregatedData.map((point) => point.volume);
2099
+ const tradeData = aggregatedData.map((point) => point.trade);
2100
+ const vwapData = aggregatedData.map((point) => point.vwap);
2101
+ const twapData = aggregatedData.map((point) => point.twap);
2102
+ const maxVolume = Math.max(...volumeData.filter((v) => v > 0));
2103
+ const maxPrice = Math.max(...bidData, ...offerData, ...tradeData, ...vwapData, ...twapData);
2104
+ const normalizedVolumeData = volumeData.map((v) => v / maxVolume * maxPrice * 0.3);
2105
+ const config = {
2106
+ type: "line",
2107
+ data: {
2108
+ labels,
2109
+ datasets: [
2110
+ {
2111
+ label: "Bid",
2112
+ data: bidData,
2113
+ borderColor: "#28a745",
2114
+ backgroundColor: "rgba(40, 167, 69, 0.1)",
2115
+ fill: false,
2116
+ tension: 0.4
2117
+ },
2118
+ {
2119
+ label: "Offer",
2120
+ data: offerData,
2121
+ borderColor: "#dc3545",
2122
+ backgroundColor: "rgba(220, 53, 69, 0.1)",
2123
+ fill: false,
2124
+ tension: 0.4
2125
+ },
2126
+ {
2127
+ label: "Spread",
2128
+ data: spreadData,
2129
+ borderColor: "#6c757d",
2130
+ backgroundColor: "rgba(108, 117, 125, 0.1)",
2131
+ fill: false,
2132
+ tension: 0.4
2133
+ },
2134
+ {
2135
+ label: "Trade",
2136
+ data: tradeData,
2137
+ borderColor: "#ffc107",
2138
+ backgroundColor: "rgba(255, 193, 7, 0.1)",
2139
+ fill: false,
2140
+ tension: 0.4
2141
+ },
2142
+ {
2143
+ label: "VWAP",
2144
+ data: vwapData,
2145
+ borderColor: "#17a2b8",
2146
+ backgroundColor: "rgba(23, 162, 184, 0.1)",
2147
+ fill: false,
2148
+ tension: 0.4
2149
+ },
2150
+ {
2151
+ label: "TWAP",
2152
+ data: twapData,
2153
+ borderColor: "#6610f2",
2154
+ backgroundColor: "rgba(102, 16, 242, 0.1)",
2155
+ fill: false,
2156
+ tension: 0.4
2157
+ },
2158
+ {
2159
+ label: "Volume (Normalized)",
2160
+ data: normalizedVolumeData,
2161
+ borderColor: "#007bff",
2162
+ backgroundColor: "rgba(0, 123, 255, 0.1)",
2163
+ fill: true,
2164
+ tension: 0.4
2165
+ }
2166
+ ]
2167
+ },
2168
+ options: {
2169
+ responsive: true,
2170
+ plugins: {
2171
+ title: {
2172
+ display: true,
2173
+ text: `${symbol} Market Data (Volume normalized to 30% of max price)`
2174
+ }
2175
+ },
2176
+ scales: {
2177
+ y: {
2178
+ beginAtZero: false,
2179
+ title: {
2180
+ display: true,
2181
+ text: "Price / Normalized Volume"
2182
+ }
2183
+ }
2184
+ }
2185
+ }
2186
+ };
2187
+ chart.setConfig(config);
2188
+ const imageBuffer = await chart.toBinary();
2189
+ const base64 = imageBuffer.toString("base64");
2190
+ return {
2191
+ content: [
2192
+ {
2193
+ type: "resource",
2194
+ resource: {
2195
+ uri: "resource://graph",
2196
+ mimeType: "image/png",
2197
+ blob: base64
2198
+ }
2199
+ }
2200
+ ]
2201
+ };
2202
+ } catch (error) {
2203
+ return {
2204
+ content: [
2205
+ {
2206
+ type: "text",
2207
+ text: `Error: ${error instanceof Error ? error.message : "Failed to generate graph"}`,
2208
+ uri: "getStockGraph"
2209
+ }
2210
+ ],
2211
+ isError: true
2212
+ };
2213
+ }
2214
+ };
2215
+ };
2216
+ var createGetStockPriceHistoryHandler = (marketDataPrices) => {
2217
+ return async (args) => {
2218
+ try {
2219
+ const symbol = args.symbol;
2220
+ const priceHistory = marketDataPrices.get(symbol) || [];
2221
+ if (priceHistory.length === 0) {
2222
+ return {
2223
+ content: [
2224
+ {
2225
+ type: "text",
2226
+ text: `No price data available for ${symbol}`,
2227
+ uri: "getStockPriceHistory"
2228
+ }
2229
+ ]
2230
+ };
2231
+ }
2232
+ const aggregatedData = aggregateMarketData(priceHistory, 500);
2233
+ return {
2234
+ content: [
2235
+ {
2236
+ type: "text",
2237
+ text: JSON.stringify(
2238
+ {
2239
+ symbol,
2240
+ count: aggregatedData.length,
2241
+ originalCount: priceHistory.length,
2242
+ data: aggregatedData.map((point) => ({
2243
+ timestamp: new Date(point.timestamp).toISOString(),
2244
+ bid: point.bid,
2245
+ offer: point.offer,
2246
+ spread: point.spread,
2247
+ volume: point.volume,
2248
+ trade: point.trade,
2249
+ indexValue: point.indexValue,
2250
+ openingPrice: point.openingPrice,
2251
+ closingPrice: point.closingPrice,
2252
+ settlementPrice: point.settlementPrice,
2253
+ tradingSessionHighPrice: point.tradingSessionHighPrice,
2254
+ tradingSessionLowPrice: point.tradingSessionLowPrice,
2255
+ vwap: point.vwap,
2256
+ imbalance: point.imbalance,
2257
+ openInterest: point.openInterest,
2258
+ compositeUnderlyingPrice: point.compositeUnderlyingPrice,
2259
+ simulatedSellPrice: point.simulatedSellPrice,
2260
+ simulatedBuyPrice: point.simulatedBuyPrice,
2261
+ marginRate: point.marginRate,
2262
+ midPrice: point.midPrice,
2263
+ emptyBook: point.emptyBook,
2264
+ settleHighPrice: point.settleHighPrice,
2265
+ settleLowPrice: point.settleLowPrice,
2266
+ priorSettlePrice: point.priorSettlePrice,
2267
+ sessionHighBid: point.sessionHighBid,
2268
+ sessionLowOffer: point.sessionLowOffer,
2269
+ earlyPrices: point.earlyPrices,
2270
+ auctionClearingPrice: point.auctionClearingPrice,
2271
+ swapValueFactor: point.swapValueFactor,
2272
+ dailyValueAdjustmentForLongPositions: point.dailyValueAdjustmentForLongPositions,
2273
+ cumulativeValueAdjustmentForLongPositions: point.cumulativeValueAdjustmentForLongPositions,
2274
+ dailyValueAdjustmentForShortPositions: point.dailyValueAdjustmentForShortPositions,
2275
+ cumulativeValueAdjustmentForShortPositions: point.cumulativeValueAdjustmentForShortPositions,
2276
+ fixingPrice: point.fixingPrice,
2277
+ cashRate: point.cashRate,
2278
+ recoveryRate: point.recoveryRate,
2279
+ recoveryRateForLong: point.recoveryRateForLong,
2280
+ recoveryRateForShort: point.recoveryRateForShort,
2281
+ marketBid: point.marketBid,
2282
+ marketOffer: point.marketOffer,
2283
+ shortSaleMinPrice: point.shortSaleMinPrice,
2284
+ previousClosingPrice: point.previousClosingPrice,
2285
+ thresholdLimitPriceBanding: point.thresholdLimitPriceBanding,
2286
+ dailyFinancingValue: point.dailyFinancingValue,
2287
+ accruedFinancingValue: point.accruedFinancingValue,
2288
+ twap: point.twap
2289
+ }))
2290
+ },
2291
+ null,
2292
+ 2
2293
+ ),
2294
+ uri: "getStockPriceHistory"
2295
+ }
2296
+ ]
2297
+ };
2298
+ } catch (error) {
2299
+ return {
2300
+ content: [
2301
+ {
2302
+ type: "text",
2303
+ text: `Error: ${error instanceof Error ? error.message : "Failed to get price history"}`,
2304
+ uri: "getStockPriceHistory"
2305
+ }
2306
+ ],
2307
+ isError: true
2308
+ };
2309
+ }
2310
+ };
2311
+ };
2312
+
2313
+ // src/tools/order.ts
2314
+ var import_fixparser2 = require("fixparser");
2315
+ var ordTypeNames = {
2316
+ "1": "Market",
2317
+ "2": "Limit",
2318
+ "3": "Stop",
2319
+ "4": "StopLimit",
2320
+ "5": "MarketOnClose",
2321
+ "6": "WithOrWithout",
2322
+ "7": "LimitOrBetter",
2323
+ "8": "LimitWithOrWithout",
2324
+ "9": "OnBasis",
2325
+ A: "OnClose",
2326
+ B: "LimitOnClose",
2327
+ C: "ForexMarket",
2328
+ D: "PreviouslyQuoted",
2329
+ E: "PreviouslyIndicated",
2330
+ F: "ForexLimit",
2331
+ G: "ForexSwap",
2332
+ H: "ForexPreviouslyQuoted",
2333
+ I: "Funari",
2334
+ J: "MarketIfTouched",
2335
+ K: "MarketWithLeftOverAsLimit",
2336
+ L: "PreviousFundValuationPoint",
2337
+ M: "NextFundValuationPoint",
2338
+ P: "Pegged",
2339
+ Q: "CounterOrderSelection",
2340
+ R: "StopOnBidOrOffer",
2341
+ S: "StopLimitOnBidOrOffer"
2342
+ };
2343
+ var sideNames = {
2344
+ "1": "Buy",
2345
+ "2": "Sell",
2346
+ "3": "BuyMinus",
2347
+ "4": "SellPlus",
2348
+ "5": "SellShort",
2349
+ "6": "SellShortExempt",
2350
+ "7": "Undisclosed",
2351
+ "8": "Cross",
2352
+ "9": "CrossShort",
2353
+ A: "CrossShortExempt",
2354
+ B: "AsDefined",
2355
+ C: "Opposite",
2356
+ D: "Subscribe",
2357
+ E: "Redeem",
2358
+ F: "Lend",
2359
+ G: "Borrow",
2360
+ H: "SellUndisclosed"
2361
+ };
2362
+ var timeInForceNames = {
2363
+ "0": "Day",
2364
+ "1": "GoodTillCancel",
2365
+ "2": "AtTheOpening",
2366
+ "3": "ImmediateOrCancel",
2367
+ "4": "FillOrKill",
2368
+ "5": "GoodTillCrossing",
2369
+ "6": "GoodTillDate",
2370
+ "7": "AtTheClose",
2371
+ "8": "GoodThroughCrossing",
2372
+ "9": "AtCrossing",
2373
+ A: "GoodForTime",
2374
+ B: "GoodForAuction",
2375
+ C: "GoodForMonth"
2376
+ };
2377
+ var handlInstNames = {
2378
+ "1": "AutomatedExecutionNoIntervention",
2379
+ "2": "AutomatedExecutionInterventionOK",
2380
+ "3": "ManualOrder"
2381
+ };
2382
+ var createVerifyOrderHandler = (parser, verifiedOrders) => {
2383
+ return async (args) => {
2384
+ void parser;
2385
+ try {
2386
+ verifiedOrders.set(args.clOrdID, {
2387
+ clOrdID: args.clOrdID,
2388
+ handlInst: args.handlInst,
2389
+ quantity: Number.parseFloat(String(args.quantity)),
2390
+ price: Number.parseFloat(String(args.price)),
2391
+ ordType: args.ordType,
2392
+ side: args.side,
2393
+ symbol: args.symbol,
2394
+ timeInForce: args.timeInForce
2395
+ });
2396
+ return {
2397
+ content: [
2398
+ {
2399
+ type: "text",
2400
+ text: `VERIFICATION: All parameters valid. Ready to proceed with order execution.
2401
+
2402
+ Parameters verified:
2403
+ - ClOrdID: ${args.clOrdID}
2404
+ - HandlInst: ${args.handlInst} (${handlInstNames[args.handlInst]})
2405
+ - Quantity: ${args.quantity}
2406
+ - Price: ${args.price}
2407
+ - OrdType: ${args.ordType} (${ordTypeNames[args.ordType]})
2408
+ - Side: ${args.side} (${sideNames[args.side]})
2409
+ - Symbol: ${args.symbol}
2410
+ - TimeInForce: ${args.timeInForce} (${timeInForceNames[args.timeInForce]})
2411
+
2412
+ To execute this order, call the executeOrder tool with these exact same parameters. Important: The user has to explicitly confirm before executeOrder is called!`,
2413
+ uri: "verifyOrder"
2414
+ }
2415
+ ]
2416
+ };
2417
+ } catch (error) {
2418
+ return {
2419
+ content: [
2420
+ {
2421
+ type: "text",
2422
+ text: `Error: ${error instanceof Error ? error.message : "Failed to verify order parameters"}`,
2423
+ uri: "verifyOrder"
2424
+ }
2425
+ ],
2426
+ isError: true
2427
+ };
2428
+ }
2429
+ };
2430
+ };
2431
+ var createExecuteOrderHandler = (parser, verifiedOrders, pendingRequests) => {
2432
+ return async (args) => {
2433
+ try {
2434
+ const verifiedOrder = verifiedOrders.get(args.clOrdID);
2435
+ if (!verifiedOrder) {
2436
+ return {
2437
+ content: [
2438
+ {
2439
+ type: "text",
2440
+ text: `Error: Order ${args.clOrdID} has not been verified. Please call verifyOrder first.`,
2441
+ uri: "executeOrder"
2442
+ }
2443
+ ],
2444
+ isError: true
2445
+ };
2446
+ }
2447
+ if (verifiedOrder.handlInst !== args.handlInst || verifiedOrder.quantity !== Number.parseFloat(String(args.quantity)) || verifiedOrder.price !== Number.parseFloat(String(args.price)) || verifiedOrder.ordType !== args.ordType || verifiedOrder.side !== args.side || verifiedOrder.symbol !== args.symbol || verifiedOrder.timeInForce !== args.timeInForce) {
2448
+ return {
2449
+ content: [
2450
+ {
2451
+ type: "text",
2452
+ text: "Error: Order parameters do not match the verified order. Please use the exact same parameters that were verified.",
2453
+ uri: "executeOrder"
2454
+ }
2455
+ ],
2456
+ isError: true
2457
+ };
2458
+ }
2459
+ const response = new Promise((resolve) => {
2460
+ pendingRequests.set(args.clOrdID, resolve);
2461
+ });
2462
+ const order = parser.createMessage(
2463
+ new import_fixparser2.Field(import_fixparser2.Fields.MsgType, import_fixparser2.Messages.NewOrderSingle),
2464
+ new import_fixparser2.Field(import_fixparser2.Fields.MsgSeqNum, parser.getNextTargetMsgSeqNum()),
2465
+ new import_fixparser2.Field(import_fixparser2.Fields.SenderCompID, parser.sender),
2466
+ new import_fixparser2.Field(import_fixparser2.Fields.TargetCompID, parser.target),
2467
+ new import_fixparser2.Field(import_fixparser2.Fields.SendingTime, parser.getTimestamp()),
2468
+ new import_fixparser2.Field(import_fixparser2.Fields.ClOrdID, args.clOrdID),
2469
+ new import_fixparser2.Field(import_fixparser2.Fields.Side, args.side),
2470
+ new import_fixparser2.Field(import_fixparser2.Fields.Symbol, args.symbol),
2471
+ new import_fixparser2.Field(import_fixparser2.Fields.OrderQty, Number.parseFloat(String(args.quantity))),
2472
+ new import_fixparser2.Field(import_fixparser2.Fields.Price, Number.parseFloat(String(args.price))),
2473
+ new import_fixparser2.Field(import_fixparser2.Fields.OrdType, args.ordType),
2474
+ new import_fixparser2.Field(import_fixparser2.Fields.HandlInst, args.handlInst),
2475
+ new import_fixparser2.Field(import_fixparser2.Fields.TimeInForce, args.timeInForce),
2476
+ new import_fixparser2.Field(import_fixparser2.Fields.TransactTime, parser.getTimestamp())
2477
+ );
2478
+ if (!parser.connected) {
2479
+ return {
2480
+ content: [
2481
+ {
2482
+ type: "text",
2483
+ text: "Error: Not connected. Ignoring message.",
2484
+ uri: "executeOrder"
2485
+ }
2486
+ ],
2487
+ isError: true
2488
+ };
2489
+ }
2490
+ parser.send(order);
2491
+ const fixData = await response;
2492
+ verifiedOrders.delete(args.clOrdID);
2493
+ return {
2494
+ content: [
2495
+ {
2496
+ type: "text",
2497
+ text: fixData.messageType === import_fixparser2.Messages.Reject ? `Reject message for order ${args.clOrdID}: ${JSON.stringify(fixData.toFIXJSON())}` : `Execution Report for order ${args.clOrdID}: ${JSON.stringify(fixData.toFIXJSON())}`,
2498
+ uri: "executeOrder"
2499
+ }
2500
+ ]
2501
+ };
2502
+ } catch (error) {
2503
+ return {
2504
+ content: [
2505
+ {
2506
+ type: "text",
2507
+ text: `Error: ${error instanceof Error ? error.message : "Failed to execute order"}`,
2508
+ uri: "executeOrder"
2509
+ }
2510
+ ],
2511
+ isError: true
2512
+ };
2513
+ }
2514
+ };
2515
+ };
2516
+
2517
+ // src/tools/parse.ts
2518
+ var createParseHandler = (parser) => {
2519
+ return async (args) => {
2520
+ try {
2521
+ const parsedMessage = parser.parse(args.fixString);
2522
+ if (!parsedMessage || parsedMessage.length === 0) {
2523
+ return {
2524
+ content: [
2525
+ {
2526
+ type: "text",
2527
+ text: "Error: Failed to parse FIX string",
2528
+ uri: "parse"
2529
+ }
2530
+ ],
2531
+ isError: true
2532
+ };
2533
+ }
2534
+ return {
2535
+ content: [
2536
+ {
2537
+ type: "text",
2538
+ text: `${parsedMessage[0].description}
2539
+ ${parsedMessage[0].messageTypeDescription}`,
2540
+ uri: "parse"
2541
+ }
2542
+ ]
2543
+ };
2544
+ } catch (error) {
2545
+ return {
2546
+ content: [
2547
+ {
2548
+ type: "text",
2549
+ text: `Error: ${error instanceof Error ? error.message : "Failed to parse FIX string"}`,
2550
+ uri: "parse"
2551
+ }
2552
+ ],
2553
+ isError: true
2554
+ };
2555
+ }
2556
+ };
2557
+ };
2558
+
2559
+ // src/tools/parseToJSON.ts
2560
+ var createParseToJSONHandler = (parser) => {
2561
+ return async (args) => {
2562
+ try {
2563
+ const parsedMessage = parser.parse(args.fixString);
2564
+ if (!parsedMessage || parsedMessage.length === 0) {
2565
+ return {
2566
+ content: [
2567
+ {
2568
+ type: "text",
2569
+ text: "Error: Failed to parse FIX string",
2570
+ uri: "parseToJSON"
2571
+ }
2572
+ ],
2573
+ isError: true
2574
+ };
2575
+ }
2576
+ return {
2577
+ content: [
2578
+ {
2579
+ type: "text",
2580
+ text: `${parsedMessage[0].toFIXJSON()}`,
2581
+ uri: "parseToJSON"
2582
+ }
2583
+ ]
2584
+ };
2585
+ } catch (error) {
2586
+ return {
2587
+ content: [
2588
+ {
2589
+ type: "text",
2590
+ text: `Error: ${error instanceof Error ? error.message : "Failed to parse FIX string"}`,
2591
+ uri: "parseToJSON"
2592
+ }
2593
+ ],
2594
+ isError: true
2595
+ };
2596
+ }
2597
+ };
2598
+ };
2599
+
2600
+ // src/tools/index.ts
2601
+ var createToolHandlers = (parser, verifiedOrders, pendingRequests, marketDataPrices) => ({
2602
+ parse: createParseHandler(parser),
2603
+ parseToJSON: createParseToJSONHandler(parser),
2604
+ verifyOrder: createVerifyOrderHandler(parser, verifiedOrders),
2605
+ executeOrder: createExecuteOrderHandler(parser, verifiedOrders, pendingRequests),
2606
+ marketDataRequest: createMarketDataRequestHandler(parser, pendingRequests),
2607
+ getStockGraph: createGetStockGraphHandler(marketDataPrices),
2608
+ getStockPriceHistory: createGetStockPriceHistoryHandler(marketDataPrices),
2609
+ technicalAnalysis: createTechnicalAnalysisHandler(marketDataPrices)
2610
+ });
2611
+
2612
+ // src/utils/messageHandler.ts
2613
+ var import_fixparser3 = require("fixparser");
2614
+ function getEnumValue(enumObj, name) {
2615
+ return enumObj[name] || name;
2616
+ }
2617
+ function handleMessage(message, parser, pendingRequests, marketDataPrices, maxPriceHistory, onPriceUpdate) {
2618
+ void parser;
2619
+ const msgType = message.messageType;
2620
+ if (msgType === import_fixparser3.Messages.MarketDataSnapshotFullRefresh || msgType === import_fixparser3.Messages.MarketDataIncrementalRefresh) {
2621
+ const symbol = message.getField(import_fixparser3.Fields.Symbol)?.value;
2622
+ const fixJson = message.toFIXJSON();
2623
+ const entries = fixJson.Body?.NoMDEntries || [];
2624
+ const data = {
2625
+ timestamp: Date.now(),
2626
+ bid: 0,
2627
+ offer: 0,
2628
+ spread: 0,
2629
+ volume: 0,
2630
+ trade: 0,
2631
+ indexValue: 0,
2632
+ openingPrice: 0,
2633
+ closingPrice: 0,
2634
+ settlementPrice: 0,
2635
+ tradingSessionHighPrice: 0,
2636
+ tradingSessionLowPrice: 0,
2637
+ vwap: 0,
2638
+ imbalance: 0,
2639
+ openInterest: 0,
2640
+ compositeUnderlyingPrice: 0,
2641
+ simulatedSellPrice: 0,
2642
+ simulatedBuyPrice: 0,
2643
+ marginRate: 0,
2644
+ midPrice: 0,
2645
+ emptyBook: 0,
2646
+ settleHighPrice: 0,
2647
+ settleLowPrice: 0,
2648
+ priorSettlePrice: 0,
2649
+ sessionHighBid: 0,
2650
+ sessionLowOffer: 0,
2651
+ earlyPrices: 0,
2652
+ auctionClearingPrice: 0,
2653
+ swapValueFactor: 0,
2654
+ dailyValueAdjustmentForLongPositions: 0,
2655
+ cumulativeValueAdjustmentForLongPositions: 0,
2656
+ dailyValueAdjustmentForShortPositions: 0,
2657
+ cumulativeValueAdjustmentForShortPositions: 0,
2658
+ fixingPrice: 0,
2659
+ cashRate: 0,
2660
+ recoveryRate: 0,
2661
+ recoveryRateForLong: 0,
2662
+ recoveryRateForShort: 0,
2663
+ marketBid: 0,
2664
+ marketOffer: 0,
2665
+ shortSaleMinPrice: 0,
2666
+ previousClosingPrice: 0,
2667
+ thresholdLimitPriceBanding: 0,
2668
+ dailyFinancingValue: 0,
2669
+ accruedFinancingValue: 0,
2670
+ twap: 0
2671
+ };
2672
+ for (const entry of entries) {
2673
+ const entryType = entry.MDEntryType;
2674
+ const price = entry.MDEntryPx ? Number.parseFloat(entry.MDEntryPx) : 0;
2675
+ const size = entry.MDEntrySize ? Number.parseFloat(entry.MDEntrySize) : 0;
2676
+ const enumValue = getEnumValue(import_fixparser3.MDEntryType, entryType);
2677
+ switch (enumValue) {
2678
+ case import_fixparser3.MDEntryType.Bid:
2679
+ data.bid = price;
2680
+ break;
2681
+ case import_fixparser3.MDEntryType.Offer:
2682
+ data.offer = price;
2683
+ break;
2684
+ case import_fixparser3.MDEntryType.Trade:
2685
+ data.trade = price;
2686
+ break;
2687
+ case import_fixparser3.MDEntryType.IndexValue:
2688
+ data.indexValue = price;
2689
+ break;
2690
+ case import_fixparser3.MDEntryType.OpeningPrice:
2691
+ data.openingPrice = price;
2692
+ break;
2693
+ case import_fixparser3.MDEntryType.ClosingPrice:
2694
+ data.closingPrice = price;
2695
+ break;
2696
+ case import_fixparser3.MDEntryType.SettlementPrice:
2697
+ data.settlementPrice = price;
2698
+ break;
2699
+ case import_fixparser3.MDEntryType.TradingSessionHighPrice:
2700
+ data.tradingSessionHighPrice = price;
2701
+ break;
2702
+ case import_fixparser3.MDEntryType.TradingSessionLowPrice:
2703
+ data.tradingSessionLowPrice = price;
2704
+ break;
2705
+ case import_fixparser3.MDEntryType.VWAP:
2706
+ data.vwap = price;
2707
+ break;
2708
+ case import_fixparser3.MDEntryType.Imbalance:
2709
+ data.imbalance = size;
2710
+ break;
2711
+ case import_fixparser3.MDEntryType.TradeVolume:
2712
+ data.volume = size;
2713
+ break;
2714
+ case import_fixparser3.MDEntryType.OpenInterest:
2715
+ data.openInterest = size;
2716
+ break;
2717
+ case import_fixparser3.MDEntryType.CompositeUnderlyingPrice:
2718
+ data.compositeUnderlyingPrice = price;
2719
+ break;
2720
+ case import_fixparser3.MDEntryType.SimulatedSellPrice:
2721
+ data.simulatedSellPrice = price;
2722
+ break;
2723
+ case import_fixparser3.MDEntryType.SimulatedBuyPrice:
2724
+ data.simulatedBuyPrice = price;
2725
+ break;
2726
+ case import_fixparser3.MDEntryType.MarginRate:
2727
+ data.marginRate = price;
2728
+ break;
2729
+ case import_fixparser3.MDEntryType.MidPrice:
2730
+ data.midPrice = price;
2731
+ break;
2732
+ case import_fixparser3.MDEntryType.EmptyBook:
2733
+ data.emptyBook = 1;
2734
+ break;
2735
+ case import_fixparser3.MDEntryType.SettleHighPrice:
2736
+ data.settleHighPrice = price;
2737
+ break;
2738
+ case import_fixparser3.MDEntryType.SettleLowPrice:
2739
+ data.settleLowPrice = price;
2740
+ break;
2741
+ case import_fixparser3.MDEntryType.PriorSettlePrice:
2742
+ data.priorSettlePrice = price;
2743
+ break;
2744
+ case import_fixparser3.MDEntryType.SessionHighBid:
2745
+ data.sessionHighBid = price;
2746
+ break;
2747
+ case import_fixparser3.MDEntryType.SessionLowOffer:
2748
+ data.sessionLowOffer = price;
2749
+ break;
2750
+ case import_fixparser3.MDEntryType.EarlyPrices:
2751
+ data.earlyPrices = price;
2752
+ break;
2753
+ case import_fixparser3.MDEntryType.AuctionClearingPrice:
2754
+ data.auctionClearingPrice = price;
2755
+ break;
2756
+ case import_fixparser3.MDEntryType.SwapValueFactor:
2757
+ data.swapValueFactor = price;
2758
+ break;
2759
+ case import_fixparser3.MDEntryType.DailyValueAdjustmentForLongPositions:
2760
+ data.dailyValueAdjustmentForLongPositions = price;
2761
+ break;
2762
+ case import_fixparser3.MDEntryType.CumulativeValueAdjustmentForLongPositions:
2763
+ data.cumulativeValueAdjustmentForLongPositions = price;
2764
+ break;
2765
+ case import_fixparser3.MDEntryType.DailyValueAdjustmentForShortPositions:
2766
+ data.dailyValueAdjustmentForShortPositions = price;
2767
+ break;
2768
+ case import_fixparser3.MDEntryType.CumulativeValueAdjustmentForShortPositions:
2769
+ data.cumulativeValueAdjustmentForShortPositions = price;
2770
+ break;
2771
+ case import_fixparser3.MDEntryType.FixingPrice:
2772
+ data.fixingPrice = price;
2773
+ break;
2774
+ case import_fixparser3.MDEntryType.CashRate:
2775
+ data.cashRate = price;
2776
+ break;
2777
+ case import_fixparser3.MDEntryType.RecoveryRate:
2778
+ data.recoveryRate = price;
2779
+ break;
2780
+ case import_fixparser3.MDEntryType.RecoveryRateForLong:
2781
+ data.recoveryRateForLong = price;
2782
+ break;
2783
+ case import_fixparser3.MDEntryType.RecoveryRateForShort:
2784
+ data.recoveryRateForShort = price;
2785
+ break;
2786
+ case import_fixparser3.MDEntryType.MarketBid:
2787
+ data.marketBid = price;
2788
+ break;
2789
+ case import_fixparser3.MDEntryType.MarketOffer:
2790
+ data.marketOffer = price;
2791
+ break;
2792
+ case import_fixparser3.MDEntryType.ShortSaleMinPrice:
2793
+ data.shortSaleMinPrice = price;
2794
+ break;
2795
+ case import_fixparser3.MDEntryType.PreviousClosingPrice:
2796
+ data.previousClosingPrice = price;
2797
+ break;
2798
+ case import_fixparser3.MDEntryType.ThresholdLimitPriceBanding:
2799
+ data.thresholdLimitPriceBanding = price;
2800
+ break;
2801
+ case import_fixparser3.MDEntryType.DailyFinancingValue:
2802
+ data.dailyFinancingValue = price;
2803
+ break;
2804
+ case import_fixparser3.MDEntryType.AccruedFinancingValue:
2805
+ data.accruedFinancingValue = price;
2806
+ break;
2807
+ case import_fixparser3.MDEntryType.TWAP:
2808
+ data.twap = price;
2809
+ break;
2810
+ }
2811
+ }
2812
+ data.spread = data.offer - data.bid;
2813
+ if (!marketDataPrices.has(symbol)) {
2814
+ marketDataPrices.set(symbol, []);
2815
+ }
2816
+ const prices = marketDataPrices.get(symbol);
2817
+ prices.push(data);
2818
+ if (prices.length > maxPriceHistory) {
2819
+ prices.splice(0, prices.length - maxPriceHistory);
2820
+ }
2821
+ onPriceUpdate?.(symbol, data);
2822
+ const mdReqID = message.getField(import_fixparser3.Fields.MDReqID)?.value;
2823
+ if (mdReqID) {
2824
+ const callback = pendingRequests.get(mdReqID);
2825
+ if (callback) {
2826
+ callback(message);
2827
+ pendingRequests.delete(mdReqID);
2828
+ }
2829
+ }
2830
+ } else if (msgType === import_fixparser3.Messages.ExecutionReport) {
2831
+ const reqId = message.getField(import_fixparser3.Fields.ClOrdID)?.value;
2832
+ const callback = pendingRequests.get(reqId);
2833
+ if (callback) {
2834
+ callback(message);
2835
+ pendingRequests.delete(reqId);
2836
+ }
2837
+ }
2838
+ }
2839
+
2840
+ // src/MCPLocal.ts
2841
+ var MCPLocal = class extends MCPBase {
2842
+ /**
2843
+ * Map to store verified orders before execution
2844
+ * @private
2845
+ */
2846
+ verifiedOrders = /* @__PURE__ */ new Map();
2847
+ /**
2848
+ * Map to store pending requests and their callbacks
2849
+ * @private
2850
+ */
2851
+ pendingRequests = /* @__PURE__ */ new Map();
2852
+ /**
2853
+ * Map to store market data prices for each symbol
2854
+ * @private
2855
+ */
2856
+ marketDataPrices = /* @__PURE__ */ new Map();
2857
+ /**
2858
+ * Maximum number of price history entries to keep per symbol
2859
+ * @private
2860
+ */
2861
+ MAX_PRICE_HISTORY = 1e5;
2862
+ server = new import_server.Server(
2863
+ {
2864
+ name: "fixparser",
2865
+ version: "1.0.0"
2866
+ },
2867
+ {
2868
+ capabilities: {
2869
+ tools: Object.entries(toolSchemas).reduce(
2870
+ (acc, [name, { description, schema }]) => {
2871
+ acc[name] = {
2872
+ description,
2873
+ parameters: schema
2874
+ };
2875
+ return acc;
2876
+ },
2877
+ {}
2878
+ )
2879
+ }
2880
+ }
2881
+ );
2882
+ transport = new import_stdio.StdioServerTransport();
2883
+ constructor({ logger, onReady }) {
2884
+ super({ logger, onReady });
2885
+ }
2886
+ async register(parser) {
2887
+ this.parser = parser;
2888
+ this.parser.addOnMessageCallback((message) => {
2889
+ handleMessage(message, this.parser, this.pendingRequests, this.marketDataPrices, this.MAX_PRICE_HISTORY);
2890
+ });
2891
+ this.addWorkflows();
2892
+ await this.server.connect(this.transport);
2893
+ if (this.onReady) {
2894
+ this.onReady();
2895
+ }
2896
+ }
2897
+ addWorkflows() {
2898
+ if (!this.parser) {
2899
+ return;
2900
+ }
2901
+ if (!this.server) {
2902
+ return;
2903
+ }
2904
+ this.server.setRequestHandler(import_zod.z.object({ method: import_zod.z.literal("tools/list") }), async () => {
2905
+ return {
2906
+ tools: Object.entries(toolSchemas).map(([name, { description, schema }]) => ({
2907
+ name,
2908
+ description,
2909
+ inputSchema: schema
2910
+ }))
2911
+ };
2912
+ });
2913
+ this.server.setRequestHandler(
2914
+ import_zod.z.object({
2915
+ method: import_zod.z.literal("tools/call"),
2916
+ params: import_zod.z.object({
2917
+ name: import_zod.z.string(),
2918
+ arguments: import_zod.z.any(),
2919
+ _meta: import_zod.z.object({
2920
+ progressToken: import_zod.z.number()
2921
+ }).optional()
2922
+ })
2923
+ }),
2924
+ async (request) => {
2925
+ const { name, arguments: args } = request.params;
2926
+ const toolHandlers = createToolHandlers(
2927
+ this.parser,
2928
+ this.verifiedOrders,
2929
+ this.pendingRequests,
2930
+ this.marketDataPrices
2931
+ );
2932
+ const handler = toolHandlers[name];
2933
+ if (!handler) {
2934
+ return {
2935
+ content: [
2936
+ {
2937
+ type: "text",
2938
+ text: `Tool not found: ${name}`,
2939
+ uri: name
2940
+ }
2941
+ ],
2942
+ isError: true
2943
+ };
2944
+ }
2945
+ const result = await handler(args);
2946
+ return {
2947
+ content: result.content,
2948
+ isError: result.isError
2949
+ };
2950
+ }
2951
+ );
2952
+ process.on("SIGINT", async () => {
2953
+ await this.server.close();
2954
+ process.exit(0);
2955
+ });
2956
+ }
2957
+ };
2958
+
2959
+ // src/MCPRemote.ts
2960
+ var import_node_crypto = require("node:crypto");
2961
+ var import_node_http = require("node:http");
2962
+ var import_mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
2963
+ var import_streamableHttp = require("@modelcontextprotocol/sdk/server/streamableHttp.js");
2964
+ var import_types = require("@modelcontextprotocol/sdk/types.js");
2965
+ var import_zod2 = require("zod");
2966
+ var transports = {};
2967
+ function jsonSchemaToZod(schema) {
2968
+ if (schema.type === "object") {
2969
+ const shape = {};
2970
+ for (const [key, prop] of Object.entries(schema.properties || {})) {
2971
+ const propSchema = prop;
2972
+ if (propSchema.type === "string") {
2973
+ if (propSchema.enum) {
2974
+ shape[key] = import_zod2.z.enum(propSchema.enum);
2975
+ } else {
2976
+ shape[key] = import_zod2.z.string();
2977
+ }
2978
+ } else if (propSchema.type === "number") {
2979
+ shape[key] = import_zod2.z.number();
2980
+ } else if (propSchema.type === "boolean") {
2981
+ shape[key] = import_zod2.z.boolean();
2982
+ } else if (propSchema.type === "array") {
2983
+ if (propSchema.items.type === "string") {
2984
+ shape[key] = import_zod2.z.array(import_zod2.z.string());
2985
+ } else if (propSchema.items.type === "number") {
2986
+ shape[key] = import_zod2.z.array(import_zod2.z.number());
2987
+ } else if (propSchema.items.type === "boolean") {
2988
+ shape[key] = import_zod2.z.array(import_zod2.z.boolean());
2989
+ } else {
2990
+ shape[key] = import_zod2.z.array(import_zod2.z.any());
2991
+ }
2992
+ } else {
2993
+ shape[key] = import_zod2.z.any();
2994
+ }
2995
+ }
2996
+ return shape;
2997
+ }
2998
+ return {};
2999
+ }
3000
+ var MCPRemote = class extends MCPBase {
3001
+ /**
3002
+ * Port number the server will listen on.
3003
+ * @private
3004
+ */
3005
+ port;
3006
+ /**
3007
+ * Node.js HTTP server instance created internally.
3008
+ * @private
3009
+ */
3010
+ httpServer;
3011
+ /**
3012
+ * MCP server instance handling MCP protocol logic.
3013
+ * @private
3014
+ */
3015
+ mcpServer;
3016
+ /**
3017
+ * Optional name of the plugin/server instance.
3018
+ * @private
3019
+ */
3020
+ serverName;
3021
+ /**
3022
+ * Optional version string of the plugin/server.
3023
+ * @private
3024
+ */
3025
+ serverVersion;
3026
+ /**
3027
+ * Map to store verified orders before execution
3028
+ * @private
3029
+ */
3030
+ verifiedOrders = /* @__PURE__ */ new Map();
3031
+ /**
3032
+ * Map to store pending requests and their callbacks
3033
+ * @private
3034
+ */
3035
+ pendingRequests = /* @__PURE__ */ new Map();
3036
+ /**
3037
+ * Map to store market data prices for each symbol
3038
+ * @private
3039
+ */
3040
+ marketDataPrices = /* @__PURE__ */ new Map();
3041
+ /**
3042
+ * Maximum number of price history entries to keep per symbol
3043
+ * @private
3044
+ */
3045
+ MAX_PRICE_HISTORY = 1e5;
3046
+ constructor({ port, logger, onReady }) {
3047
+ super({ logger, onReady });
3048
+ this.port = port;
3049
+ }
3050
+ async register(parser) {
3051
+ this.parser = parser;
3052
+ this.logger = parser.logger;
3053
+ this.logger?.log({
3054
+ level: "info",
3055
+ message: `FIXParser (MCP): -- Plugin registered. Creating MCP server on port ${this.port}...`
3056
+ });
3057
+ this.parser.addOnMessageCallback((message) => {
3058
+ if (this.parser) {
3059
+ handleMessage(
3060
+ message,
3061
+ this.parser,
3062
+ this.pendingRequests,
3063
+ this.marketDataPrices,
3064
+ this.MAX_PRICE_HISTORY
3065
+ );
3066
+ }
3067
+ });
3068
+ this.httpServer = (0, import_node_http.createServer)(async (req, res) => {
3069
+ if (!req.url || !req.method) {
3070
+ res.writeHead(400);
3071
+ res.end("Bad Request");
3072
+ return;
3073
+ }
3074
+ if (req.url === "/mcp") {
3075
+ const sessionId = req.headers["mcp-session-id"];
3076
+ if (req.method === "POST") {
3077
+ const bodyChunks = [];
3078
+ req.on("data", (chunk) => {
3079
+ bodyChunks.push(chunk);
3080
+ });
3081
+ req.on("end", async () => {
3082
+ let parsed;
3083
+ const body = Buffer.concat(bodyChunks).toString();
3084
+ try {
3085
+ parsed = JSON.parse(body);
3086
+ } catch (error) {
3087
+ void error;
3088
+ res.writeHead(400);
3089
+ res.end(JSON.stringify({ error: "Invalid JSON" }));
3090
+ return;
3091
+ }
3092
+ let transport;
3093
+ if (sessionId && transports[sessionId]) {
3094
+ transport = transports[sessionId];
3095
+ } else if (!sessionId && req.method === "POST" && (0, import_types.isInitializeRequest)(parsed)) {
3096
+ transport = new import_streamableHttp.StreamableHTTPServerTransport({
3097
+ sessionIdGenerator: () => (0, import_node_crypto.randomUUID)(),
3098
+ onsessioninitialized: (sessionId2) => {
3099
+ transports[sessionId2] = transport;
3100
+ }
3101
+ });
3102
+ transport.onclose = () => {
3103
+ if (transport.sessionId) {
3104
+ delete transports[transport.sessionId];
3105
+ }
3106
+ };
3107
+ this.mcpServer = new import_mcp.McpServer({
3108
+ name: this.serverName || "FIXParser",
3109
+ version: this.serverVersion || "1.0.0"
3110
+ });
3111
+ this.setupTools();
3112
+ await this.mcpServer.connect(transport);
3113
+ } else {
3114
+ res.writeHead(400, { "Content-Type": "application/json" });
3115
+ res.end(
3116
+ JSON.stringify({
3117
+ jsonrpc: "2.0",
3118
+ error: {
3119
+ code: -32e3,
3120
+ message: "Bad Request: No valid session ID provided"
3121
+ },
3122
+ id: null
3123
+ })
3124
+ );
3125
+ return;
3126
+ }
3127
+ try {
3128
+ await transport.handleRequest(req, res, parsed);
3129
+ } catch (error) {
3130
+ this.logger?.log({
3131
+ level: "error",
3132
+ message: `Error handling request: ${error}`
3133
+ });
3134
+ throw error;
3135
+ }
3136
+ });
3137
+ } else if (req.method === "GET" || req.method === "DELETE") {
3138
+ if (!sessionId || !transports[sessionId]) {
3139
+ res.writeHead(400);
3140
+ res.end("Invalid or missing session ID");
3141
+ return;
3142
+ }
3143
+ const transport = transports[sessionId];
3144
+ try {
3145
+ await transport.handleRequest(req, res);
3146
+ } catch (error) {
3147
+ this.logger?.log({
3148
+ level: "error",
3149
+ message: `Error handling ${req.method} request: ${error}`
3150
+ });
3151
+ throw error;
3152
+ }
3153
+ } else {
3154
+ this.logger?.log({
3155
+ level: "error",
3156
+ message: `Method not allowed: ${req.method}`
3157
+ });
3158
+ res.writeHead(405);
3159
+ res.end("Method Not Allowed");
3160
+ }
3161
+ } else {
3162
+ res.writeHead(404);
3163
+ res.end("Not Found");
3164
+ }
3165
+ });
3166
+ this.httpServer.listen(this.port, () => {
3167
+ this.logger?.log({
3168
+ level: "info",
3169
+ message: `FIXParser (MCP): -- Server listening on http://localhost:${this.port}...`
3170
+ });
3171
+ });
3172
+ if (this.onReady) {
3173
+ this.onReady();
3174
+ }
3175
+ }
3176
+ setupTools() {
3177
+ if (!this.parser) {
3178
+ this.logger?.log({
3179
+ level: "error",
3180
+ message: "FIXParser (MCP): -- FIXParser instance not initialized. Ignoring setup of tools..."
3181
+ });
3182
+ return;
3183
+ }
3184
+ if (!this.mcpServer) {
3185
+ this.logger?.log({
3186
+ level: "error",
3187
+ message: "FIXParser (MCP): -- MCP Server not initialized. Ignoring setup of tools..."
3188
+ });
3189
+ return;
3190
+ }
3191
+ const toolHandlers = createToolHandlers(
3192
+ this.parser,
3193
+ this.verifiedOrders,
3194
+ this.pendingRequests,
3195
+ this.marketDataPrices
3196
+ );
3197
+ Object.entries(toolSchemas).forEach(([name, { description, schema }]) => {
3198
+ this.mcpServer?.registerTool(
3199
+ name,
3200
+ {
3201
+ description,
3202
+ inputSchema: jsonSchemaToZod(schema)
3203
+ },
3204
+ async (args) => {
3205
+ const handler = toolHandlers[name];
3206
+ if (!handler) {
3207
+ return {
3208
+ content: [
3209
+ {
3210
+ type: "text",
3211
+ text: `Tool not found: ${name}`
3212
+ }
3213
+ ],
3214
+ isError: true
3215
+ };
3216
+ }
3217
+ const result = await handler(args);
3218
+ return {
3219
+ content: result.content,
3220
+ isError: result.isError
3221
+ };
3222
+ }
3223
+ );
3224
+ });
3225
+ }
3226
+ };
3227
+ // Annotate the CommonJS export names for ESM import in node:
3228
+ 0 && (module.exports = {
3229
+ MCPLocal,
3230
+ MCPRemote
3231
+ });
3232
+ //# sourceMappingURL=index.js.map