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