fixparser-plugin-mcp 9.1.7-1736d80f → 9.1.7-1818bee7

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