fixparser-plugin-mcp 9.1.7-74db6dbc → 9.1.7-75ded9c1

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