fixparser-plugin-mcp 9.1.7-c6228661 → 9.1.7-d47799ff

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,1917 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/index.ts
31
- var index_exports = {};
32
- __export(index_exports, {
33
- MCPLocal: () => MCPLocal,
34
- MCPRemote: () => MCPRemote
35
- });
36
- module.exports = __toCommonJS(index_exports);
37
-
38
- // src/MCPLocal.ts
39
- var import_server = require("@modelcontextprotocol/sdk/server/index.js");
40
- var import_stdio = require("@modelcontextprotocol/sdk/server/stdio.js");
41
- var import_zod = require("zod");
42
-
43
- // src/MCPBase.ts
44
- var MCPBase = class {
45
- /**
46
- * Optional logger instance for diagnostics and output.
47
- * @protected
48
- */
49
- logger;
50
- /**
51
- * FIXParser instance, set during plugin register().
52
- * @protected
53
- */
54
- parser;
55
- /**
56
- * Called when server is setup and listening.
57
- * @protected
58
- */
59
- onReady = void 0;
60
- /**
61
- * Map to store verified orders before execution
62
- * @protected
63
- */
64
- verifiedOrders = /* @__PURE__ */ new Map();
65
- /**
66
- * Map to store pending market data requests
67
- * @protected
68
- */
69
- pendingRequests = /* @__PURE__ */ new Map();
70
- /**
71
- * Map to store market data prices
72
- * @protected
73
- */
74
- marketDataPrices = /* @__PURE__ */ new Map();
75
- /**
76
- * Maximum number of price history entries to keep per symbol
77
- * @protected
78
- */
79
- MAX_PRICE_HISTORY = 1e5;
80
- constructor({ logger, onReady }) {
81
- this.logger = logger;
82
- this.onReady = onReady;
83
- }
84
- };
85
-
86
- // src/schemas/schemas.ts
87
- var toolSchemas = {
88
- parse: {
89
- description: "Parses a FIX message and describes it in plain language",
90
- schema: {
91
- type: "object",
92
- properties: {
93
- fixString: { type: "string" }
94
- },
95
- required: ["fixString"]
96
- }
97
- },
98
- parseToJSON: {
99
- description: "Parses a FIX message into JSON",
100
- schema: {
101
- type: "object",
102
- properties: {
103
- fixString: { type: "string" }
104
- },
105
- required: ["fixString"]
106
- }
107
- },
108
- verifyOrder: {
109
- description: "Verifies order parameters before execution. verifyOrder must be called before executeOrder.",
110
- schema: {
111
- type: "object",
112
- properties: {
113
- clOrdID: { type: "string" },
114
- handlInst: {
115
- type: "string",
116
- enum: ["1", "2", "3"],
117
- description: "Handling Instructions: 1=Automated Execution No Intervention, 2=Automated Execution Intervention OK, 3=Manual Order"
118
- },
119
- quantity: { type: "string" },
120
- price: { type: "string" },
121
- ordType: {
122
- type: "string",
123
- enum: [
124
- "1",
125
- "2",
126
- "3",
127
- "4",
128
- "5",
129
- "6",
130
- "7",
131
- "8",
132
- "9",
133
- "A",
134
- "B",
135
- "C",
136
- "D",
137
- "E",
138
- "F",
139
- "G",
140
- "H",
141
- "I",
142
- "J",
143
- "K",
144
- "L",
145
- "M",
146
- "P",
147
- "Q",
148
- "R",
149
- "S"
150
- ],
151
- description: "Order Type: 1=Market, 2=Limit, 3=Stop, 4=StopLimit, 5=MarketOnClose, 6=WithOrWithout, 7=LimitOrBetter, 8=LimitWithOrWithout, 9=OnBasis, A=OnClose, B=LimitOnClose, C=ForexMarket, D=PreviouslyQuoted, E=PreviouslyIndicated, F=ForexLimit, G=ForexSwap, H=ForexPreviouslyQuoted, I=Funari, J=MarketIfTouched, K=MarketWithLeftOverAsLimit, L=PreviousFundValuationPoint, M=NextFundValuationPoint, P=Pegged, Q=CounterOrderSelection, R=StopOnBidOrOffer, S=StopLimitOnBidOrOffer"
152
- },
153
- side: {
154
- type: "string",
155
- enum: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H"],
156
- description: "Side: 1=Buy, 2=Sell, 3=BuyMinus, 4=SellPlus, 5=SellShort, 6=SellShortExempt, 7=Undisclosed, 8=Cross, 9=CrossShort, A=CrossShortExempt, B=AsDefined, C=Opposite, D=Subscribe, E=Redeem, F=Lend, G=Borrow, H=SellUndisclosed"
157
- },
158
- symbol: { type: "string" },
159
- timeInForce: {
160
- type: "string",
161
- enum: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C"],
162
- description: "Time In Force: 0=Day, 1=GoodTillCancel, 2=AtTheOpening, 3=ImmediateOrCancel, 4=FillOrKill, 5=GoodTillCrossing, 6=GoodTillDate, 7=AtTheClose, 8=GoodThroughCrossing, 9=AtCrossing, A=GoodForTime, B=GoodForAuction, C=GoodForMonth"
163
- }
164
- },
165
- required: ["clOrdID", "handlInst", "quantity", "price", "ordType", "side", "symbol", "timeInForce"]
166
- }
167
- },
168
- executeOrder: {
169
- description: "Executes a verified order. verifyOrder must be called before executeOrder.",
170
- schema: {
171
- type: "object",
172
- properties: {
173
- clOrdID: { type: "string" },
174
- handlInst: {
175
- type: "string",
176
- enum: ["1", "2", "3"],
177
- description: "Handling Instructions: 1=Automated Execution No Intervention, 2=Automated Execution Intervention OK, 3=Manual Order"
178
- },
179
- quantity: { type: "string" },
180
- price: { type: "string" },
181
- ordType: {
182
- type: "string",
183
- enum: [
184
- "1",
185
- "2",
186
- "3",
187
- "4",
188
- "5",
189
- "6",
190
- "7",
191
- "8",
192
- "9",
193
- "A",
194
- "B",
195
- "C",
196
- "D",
197
- "E",
198
- "F",
199
- "G",
200
- "H",
201
- "I",
202
- "J",
203
- "K",
204
- "L",
205
- "M",
206
- "P",
207
- "Q",
208
- "R",
209
- "S"
210
- ],
211
- description: "Order Type: 1=Market, 2=Limit, 3=Stop, 4=StopLimit, 5=MarketOnClose, 6=WithOrWithout, 7=LimitOrBetter, 8=LimitWithOrWithout, 9=OnBasis, A=OnClose, B=LimitOnClose, C=ForexMarket, D=PreviouslyQuoted, E=PreviouslyIndicated, F=ForexLimit, G=ForexSwap, H=ForexPreviouslyQuoted, I=Funari, J=MarketIfTouched, K=MarketWithLeftOverAsLimit, L=PreviousFundValuationPoint, M=NextFundValuationPoint, P=Pegged, Q=CounterOrderSelection, R=StopOnBidOrOffer, S=StopLimitOnBidOrOffer"
212
- },
213
- side: {
214
- type: "string",
215
- enum: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H"],
216
- description: "Side: 1=Buy, 2=Sell, 3=BuyMinus, 4=SellPlus, 5=SellShort, 6=SellShortExempt, 7=Undisclosed, 8=Cross, 9=CrossShort, A=CrossShortExempt, B=AsDefined, C=Opposite, D=Subscribe, E=Redeem, F=Lend, G=Borrow, H=SellUndisclosed"
217
- },
218
- symbol: { type: "string" },
219
- timeInForce: {
220
- type: "string",
221
- enum: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C"],
222
- description: "Time In Force: 0=Day, 1=GoodTillCancel, 2=AtTheOpening, 3=ImmediateOrCancel, 4=FillOrKill, 5=GoodTillCrossing, 6=GoodTillDate, 7=AtTheClose, 8=GoodThroughCrossing, 9=AtCrossing, A=GoodForTime, B=GoodForAuction, C=GoodForMonth"
223
- }
224
- },
225
- required: ["clOrdID", "handlInst", "quantity", "price", "ordType", "side", "symbol", "timeInForce"]
226
- }
227
- },
228
- marketDataRequest: {
229
- description: "Requests market data for specified symbols",
230
- schema: {
231
- type: "object",
232
- properties: {
233
- mdUpdateType: {
234
- type: "string",
235
- enum: ["0", "1"],
236
- description: "Market Data Update Type: 0=Full Refresh, 1=Incremental Refresh"
237
- },
238
- symbols: { type: "array", items: { type: "string" } },
239
- mdReqID: { type: "string" },
240
- subscriptionRequestType: {
241
- type: "string",
242
- enum: ["0", "1", "2"],
243
- description: "Subscription Request Type: 0=Snapshot, 1=Snapshot + Updates, 2=Disable Previous Snapshot + Update Request"
244
- },
245
- mdEntryTypes: {
246
- type: "array",
247
- items: {
248
- type: "string",
249
- enum: [
250
- "0",
251
- "1",
252
- "2",
253
- "3",
254
- "4",
255
- "5",
256
- "6",
257
- "7",
258
- "8",
259
- "9",
260
- "A",
261
- "B",
262
- "C",
263
- "D",
264
- "E",
265
- "F",
266
- "G",
267
- "H",
268
- "I",
269
- "J",
270
- "K",
271
- "L",
272
- "M",
273
- "N",
274
- "O",
275
- "P",
276
- "Q",
277
- "R",
278
- "S",
279
- "T",
280
- "U",
281
- "V",
282
- "W",
283
- "X",
284
- "Y",
285
- "Z"
286
- ]
287
- },
288
- description: "Market Data Entry Types: 0=Bid, 1=Offer, 2=Trade, 3=Index Value, 4=Opening Price, 5=Closing Price, 6=Settlement Price, 7=High Price, 8=Low Price, 9=Trade Volume, A=Open Interest, B=Simulated Sell Price, C=Simulated Buy Price, D=Empty Book, E=Session High Bid, F=Session Low Offer, G=Fixing Price, H=Electronic Volume, I=Threshold Limits and Price Band Variation, J=Clearing Price, K=Open Interest Change, L=Last Trade Price, M=Last Trade Volume, N=Last Trade Time, O=Last Trade Tick, P=Last Trade Exchange, Q=Last Trade ID, R=Last Trade Side, S=Last Trade Price Change, T=Last Trade Price Change Percent, U=Last Trade Price Change Basis Points, V=Last Trade Price Change Points, W=Last Trade Price Change Ticks, X=Last Trade Price Change Ticks Percent, Y=Last Trade Price Change Ticks Basis Points, Z=Last Trade Price Change Ticks Points"
289
- }
290
- },
291
- required: ["mdUpdateType", "symbols", "mdReqID", "subscriptionRequestType"]
292
- }
293
- },
294
- getStockGraph: {
295
- description: "Generates a price chart for a given symbol",
296
- schema: {
297
- type: "object",
298
- properties: {
299
- symbol: { type: "string" }
300
- },
301
- required: ["symbol"]
302
- }
303
- },
304
- getStockPriceHistory: {
305
- description: "Returns price history for a given symbol",
306
- schema: {
307
- type: "object",
308
- properties: {
309
- symbol: { type: "string" }
310
- },
311
- required: ["symbol"]
312
- }
313
- },
314
- technicalAnalysis: {
315
- description: "Performs comprehensive technical analysis on market data for a given symbol, including indicators like SMA, EMA, RSI, Bollinger Bands, and trading signals",
316
- schema: {
317
- type: "object",
318
- properties: {
319
- symbol: {
320
- type: "string",
321
- description: "The trading symbol to analyze (e.g., AAPL, MSFT, EURUSD)"
322
- }
323
- },
324
- required: ["symbol"]
325
- }
326
- }
327
- };
328
-
329
- // src/tools/analytics.ts
330
- function sum(numbers) {
331
- return numbers.reduce((acc, val) => acc + val, 0);
332
- }
333
- var TechnicalAnalyzer = class {
334
- prices;
335
- volumes;
336
- highs;
337
- lows;
338
- constructor(data) {
339
- this.prices = data.map((d) => d.trade > 0 ? d.trade : d.midPrice);
340
- this.volumes = data.map((d) => d.volume);
341
- this.highs = data.map((d) => d.tradingSessionHighPrice > 0 ? d.tradingSessionHighPrice : d.trade);
342
- this.lows = data.map((d) => d.tradingSessionLowPrice > 0 ? d.tradingSessionLowPrice : d.trade);
343
- }
344
- // Calculate Simple Moving Average
345
- calculateSMA(data, period) {
346
- const sma = [];
347
- for (let i = period - 1; i < data.length; i++) {
348
- const sum2 = data.slice(i - period + 1, i + 1).reduce((a, b) => a + b, 0);
349
- sma.push(sum2 / period);
350
- }
351
- return sma;
352
- }
353
- // Calculate Exponential Moving Average
354
- calculateEMA(data, period) {
355
- const multiplier = 2 / (period + 1);
356
- const ema = [data[0]];
357
- for (let i = 1; i < data.length; i++) {
358
- ema.push(data[i] * multiplier + ema[i - 1] * (1 - multiplier));
359
- }
360
- return ema;
361
- }
362
- // Calculate RSI
363
- calculateRSI(data, period = 14) {
364
- if (data.length < period + 1) return [];
365
- const changes = [];
366
- for (let i = 1; i < data.length; i++) {
367
- changes.push(data[i] - data[i - 1]);
368
- }
369
- const gains = changes.map((change) => change > 0 ? change : 0);
370
- const losses = changes.map((change) => change < 0 ? Math.abs(change) : 0);
371
- let avgGain = gains.slice(0, period).reduce((a, b) => a + b, 0) / period;
372
- let avgLoss = losses.slice(0, period).reduce((a, b) => a + b, 0) / period;
373
- const rsi = [];
374
- for (let i = period; i < changes.length; i++) {
375
- const rs = avgGain / avgLoss;
376
- rsi.push(100 - 100 / (1 + rs));
377
- avgGain = (avgGain * (period - 1) + gains[i]) / period;
378
- avgLoss = (avgLoss * (period - 1) + losses[i]) / period;
379
- }
380
- return rsi;
381
- }
382
- // Calculate Bollinger Bands
383
- calculateBollingerBands(data, period = 20, stdDev = 2) {
384
- if (data.length < period) return [];
385
- const sma = this.calculateSMA(data, period);
386
- const bands = [];
387
- for (let i = 0; i < sma.length; i++) {
388
- const dataSlice = data.slice(i, i + period);
389
- const mean = sma[i];
390
- const variance = dataSlice.reduce((sum2, price) => sum2 + (price - mean) ** 2, 0) / period;
391
- const standardDeviation = Math.sqrt(variance);
392
- bands.push({
393
- upper: mean + standardDeviation * stdDev,
394
- middle: mean,
395
- lower: mean - standardDeviation * stdDev
396
- });
397
- }
398
- return bands;
399
- }
400
- // Calculate maximum drawdown
401
- calculateMaxDrawdown(prices) {
402
- let maxPrice = prices[0];
403
- let maxDrawdown = 0;
404
- for (let i = 1; i < prices.length; i++) {
405
- if (prices[i] > maxPrice) {
406
- maxPrice = prices[i];
407
- }
408
- const drawdown = (maxPrice - prices[i]) / maxPrice;
409
- if (drawdown > maxDrawdown) {
410
- maxDrawdown = drawdown;
411
- }
412
- }
413
- return maxDrawdown;
414
- }
415
- // Calculate price changes for volatility
416
- calculatePriceChanges() {
417
- const changes = [];
418
- for (let i = 1; i < this.prices.length; i++) {
419
- changes.push((this.prices[i] - this.prices[i - 1]) / this.prices[i - 1]);
420
- }
421
- return changes;
422
- }
423
- // Generate comprehensive market analysis
424
- analyze() {
425
- const currentPrice = this.prices[this.prices.length - 1];
426
- const startPrice = this.prices[0];
427
- const sessionHigh = Math.max(...this.highs);
428
- const sessionLow = Math.min(...this.lows);
429
- const totalVolume = sum(this.volumes);
430
- const avgVolume = totalVolume / this.volumes.length;
431
- const priceChanges = this.calculatePriceChanges();
432
- const volatility = priceChanges.length > 0 ? Math.sqrt(
433
- priceChanges.reduce((sum2, change) => sum2 + change ** 2, 0) / priceChanges.length
434
- ) * Math.sqrt(252) * 100 : 0;
435
- const sessionReturn = (currentPrice - startPrice) / startPrice * 100;
436
- const pricePosition = (currentPrice - sessionLow) / (sessionHigh - sessionLow) * 100;
437
- const trueVWAP = this.prices.reduce((sum2, price, i) => sum2 + price * this.volumes[i], 0) / totalVolume;
438
- 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;
439
- 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;
440
- const maxDrawdown = this.calculateMaxDrawdown(this.prices);
441
- return {
442
- currentPrice,
443
- startPrice,
444
- sessionHigh,
445
- sessionLow,
446
- totalVolume,
447
- avgVolume,
448
- volatility,
449
- sessionReturn,
450
- pricePosition,
451
- trueVWAP,
452
- momentum5,
453
- momentum10,
454
- maxDrawdown
455
- };
456
- }
457
- // Generate technical indicators
458
- getTechnicalIndicators() {
459
- return {
460
- sma5: this.calculateSMA(this.prices, 5),
461
- sma10: this.calculateSMA(this.prices, 10),
462
- ema8: this.calculateEMA(this.prices, 8),
463
- ema21: this.calculateEMA(this.prices, 21),
464
- rsi: this.calculateRSI(this.prices, 14),
465
- bollinger: this.calculateBollingerBands(this.prices, 20, 2)
466
- };
467
- }
468
- // Generate trading signals
469
- generateSignals() {
470
- const analysis = this.analyze();
471
- let bullishSignals = 0;
472
- let bearishSignals = 0;
473
- const signals = [];
474
- if (analysis.currentPrice > analysis.trueVWAP) {
475
- signals.push(
476
- `\u2713 BULLISH: Price above VWAP (+${((analysis.currentPrice - analysis.trueVWAP) / analysis.trueVWAP * 100).toFixed(2)}%)`
477
- );
478
- bullishSignals++;
479
- } else {
480
- signals.push(
481
- `\u2717 BEARISH: Price below VWAP (${((analysis.currentPrice - analysis.trueVWAP) / analysis.trueVWAP * 100).toFixed(2)}%)`
482
- );
483
- bearishSignals++;
484
- }
485
- if (analysis.momentum5 > 0 && analysis.momentum10 > 0) {
486
- signals.push("\u2713 BULLISH: Positive momentum on both timeframes");
487
- bullishSignals++;
488
- } else if (analysis.momentum5 < 0 && analysis.momentum10 < 0) {
489
- signals.push("\u2717 BEARISH: Negative momentum on both timeframes");
490
- bearishSignals++;
491
- } else {
492
- signals.push("\u25D0 MIXED: Conflicting momentum signals");
493
- }
494
- const currentVolume = this.volumes[this.volumes.length - 1];
495
- const volumeRatio = currentVolume / analysis.avgVolume;
496
- if (volumeRatio > 1.2 && analysis.sessionReturn > 0) {
497
- signals.push("\u2713 BULLISH: Above-average volume supporting upward move");
498
- bullishSignals++;
499
- } else if (volumeRatio > 1.2 && analysis.sessionReturn < 0) {
500
- signals.push("\u2717 BEARISH: Above-average volume supporting downward move");
501
- bearishSignals++;
502
- } else {
503
- signals.push("\u25D0 NEUTRAL: Volume not providing clear direction");
504
- }
505
- if (analysis.pricePosition > 65 && analysis.volatility > 30) {
506
- signals.push("\u2717 BEARISH: High in range with elevated volatility - reversal risk");
507
- bearishSignals++;
508
- } else if (analysis.pricePosition < 35 && analysis.volatility > 30) {
509
- signals.push("\u2713 BULLISH: Low in range with volatility - potential bounce");
510
- bullishSignals++;
511
- } else {
512
- signals.push("\u25D0 NEUTRAL: Price position and volatility not extreme");
513
- }
514
- return { bullishSignals, bearishSignals, signals };
515
- }
516
- // Generate comprehensive JSON analysis
517
- generateJSONAnalysis(symbol) {
518
- const analysis = this.analyze();
519
- const indicators = this.getTechnicalIndicators();
520
- const signals = this.generateSignals();
521
- const currentSMA5 = indicators.sma5.length > 0 ? indicators.sma5[indicators.sma5.length - 1] : null;
522
- const currentSMA10 = indicators.sma10.length > 0 ? indicators.sma10[indicators.sma10.length - 1] : null;
523
- const currentEMA8 = indicators.ema8[indicators.ema8.length - 1];
524
- const currentEMA21 = indicators.ema21[indicators.ema21.length - 1];
525
- const currentRSI = indicators.rsi.length > 0 ? indicators.rsi[indicators.rsi.length - 1] : null;
526
- const currentBB = indicators.bollinger.length > 0 ? indicators.bollinger[indicators.bollinger.length - 1] : null;
527
- const currentVolume = this.volumes[this.volumes.length - 1];
528
- const volumeRatio = currentVolume / analysis.avgVolume;
529
- const currentDrawdown = (analysis.sessionHigh - analysis.currentPrice) / analysis.sessionHigh * 100;
530
- const rangeWidth = (analysis.sessionHigh - analysis.sessionLow) / analysis.sessionLow * 100;
531
- const priceVsVWAP = (analysis.currentPrice - analysis.trueVWAP) / analysis.trueVWAP * 100;
532
- const totalScore = signals.bullishSignals - signals.bearishSignals;
533
- const overallSignal = totalScore > 0 ? "BULLISH_BIAS" : totalScore < 0 ? "BEARISH_BIAS" : "NEUTRAL";
534
- const targetEntry = Math.max(analysis.sessionLow * 1.005, analysis.trueVWAP * 0.998);
535
- const stopLoss = analysis.sessionLow * 0.995;
536
- const profitTarget = analysis.sessionHigh * 0.995;
537
- const riskRewardRatio = (profitTarget - analysis.currentPrice) / (analysis.currentPrice - stopLoss);
538
- return {
539
- symbol,
540
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
541
- marketStructure: {
542
- currentPrice: analysis.currentPrice,
543
- startPrice: analysis.startPrice,
544
- sessionHigh: analysis.sessionHigh,
545
- sessionLow: analysis.sessionLow,
546
- rangeWidth,
547
- totalVolume: analysis.totalVolume,
548
- sessionPerformance: analysis.sessionReturn,
549
- positionInRange: analysis.pricePosition
550
- },
551
- volatility: {
552
- impliedVolatility: analysis.volatility,
553
- maxDrawdown: analysis.maxDrawdown * 100,
554
- currentDrawdown
555
- },
556
- technicalIndicators: {
557
- sma5: currentSMA5,
558
- sma10: currentSMA10,
559
- ema8: currentEMA8,
560
- ema21: currentEMA21,
561
- rsi: currentRSI,
562
- bollingerBands: currentBB ? {
563
- upper: currentBB.upper,
564
- middle: currentBB.middle,
565
- lower: currentBB.lower,
566
- position: (analysis.currentPrice - currentBB.lower) / (currentBB.upper - currentBB.lower) * 100
567
- } : null
568
- },
569
- volumeAnalysis: {
570
- currentVolume,
571
- averageVolume: Math.round(analysis.avgVolume),
572
- volumeRatio,
573
- trueVWAP: analysis.trueVWAP,
574
- priceVsVWAP
575
- },
576
- momentum: {
577
- momentum5: analysis.momentum5,
578
- momentum10: analysis.momentum10,
579
- sessionROC: analysis.sessionReturn
580
- },
581
- tradingSignals: {
582
- ...signals,
583
- overallSignal,
584
- signalScore: totalScore
585
- },
586
- riskManagement: {
587
- targetEntry,
588
- stopLoss,
589
- profitTarget,
590
- riskRewardRatio
591
- }
592
- };
593
- }
594
- };
595
- var createTechnicalAnalysisHandler = (marketDataPrices) => {
596
- return async (args) => {
597
- try {
598
- const symbol = args.symbol;
599
- const priceHistory = marketDataPrices.get(symbol) || [];
600
- if (priceHistory.length === 0) {
601
- return {
602
- content: [
603
- {
604
- type: "text",
605
- text: `No price data available for ${symbol}. Please request market data first.`,
606
- uri: "technicalAnalysis"
607
- }
608
- ]
609
- };
610
- }
611
- const analyzer = new TechnicalAnalyzer(priceHistory);
612
- const analysis = analyzer.generateJSONAnalysis(symbol);
613
- return {
614
- content: [
615
- {
616
- type: "text",
617
- text: `Technical Analysis for ${symbol}:
618
-
619
- ${JSON.stringify(analysis, null, 2)}`,
620
- uri: "technicalAnalysis"
621
- }
622
- ]
623
- };
624
- } catch (error) {
625
- return {
626
- content: [
627
- {
628
- type: "text",
629
- text: `Error performing technical analysis: ${error instanceof Error ? error.message : "Unknown error"}`,
630
- uri: "technicalAnalysis"
631
- }
632
- ],
633
- isError: true
634
- };
635
- }
636
- };
637
- };
638
-
639
- // src/tools/marketData.ts
640
- var import_fixparser = require("fixparser");
641
- var import_quickchart_js = __toESM(require("quickchart-js"), 1);
642
- var createMarketDataRequestHandler = (parser, pendingRequests) => {
643
- return async (args) => {
644
- try {
645
- parser.logger.log({
646
- level: "info",
647
- message: `Sending market data request for symbols: ${args.symbols.join(", ")}`
648
- });
649
- const response = new Promise((resolve) => {
650
- pendingRequests.set(args.mdReqID, resolve);
651
- parser.logger.log({
652
- level: "info",
653
- message: `Registered callback for market data request ID: ${args.mdReqID}`
654
- });
655
- });
656
- const entryTypes = args.mdEntryTypes || [
657
- import_fixparser.MDEntryType.Bid,
658
- import_fixparser.MDEntryType.Offer,
659
- import_fixparser.MDEntryType.Trade,
660
- import_fixparser.MDEntryType.IndexValue,
661
- import_fixparser.MDEntryType.OpeningPrice,
662
- import_fixparser.MDEntryType.ClosingPrice,
663
- import_fixparser.MDEntryType.SettlementPrice,
664
- import_fixparser.MDEntryType.TradingSessionHighPrice,
665
- import_fixparser.MDEntryType.TradingSessionLowPrice,
666
- import_fixparser.MDEntryType.VWAP,
667
- import_fixparser.MDEntryType.Imbalance,
668
- import_fixparser.MDEntryType.TradeVolume,
669
- import_fixparser.MDEntryType.OpenInterest,
670
- import_fixparser.MDEntryType.CompositeUnderlyingPrice,
671
- import_fixparser.MDEntryType.SimulatedSellPrice,
672
- import_fixparser.MDEntryType.SimulatedBuyPrice,
673
- import_fixparser.MDEntryType.MarginRate,
674
- import_fixparser.MDEntryType.MidPrice,
675
- import_fixparser.MDEntryType.EmptyBook,
676
- import_fixparser.MDEntryType.SettleHighPrice,
677
- import_fixparser.MDEntryType.SettleLowPrice,
678
- import_fixparser.MDEntryType.PriorSettlePrice,
679
- import_fixparser.MDEntryType.SessionHighBid,
680
- import_fixparser.MDEntryType.SessionLowOffer,
681
- import_fixparser.MDEntryType.EarlyPrices,
682
- import_fixparser.MDEntryType.AuctionClearingPrice,
683
- import_fixparser.MDEntryType.SwapValueFactor,
684
- import_fixparser.MDEntryType.DailyValueAdjustmentForLongPositions,
685
- import_fixparser.MDEntryType.CumulativeValueAdjustmentForLongPositions,
686
- import_fixparser.MDEntryType.DailyValueAdjustmentForShortPositions,
687
- import_fixparser.MDEntryType.CumulativeValueAdjustmentForShortPositions,
688
- import_fixparser.MDEntryType.FixingPrice,
689
- import_fixparser.MDEntryType.CashRate,
690
- import_fixparser.MDEntryType.RecoveryRate,
691
- import_fixparser.MDEntryType.RecoveryRateForLong,
692
- import_fixparser.MDEntryType.RecoveryRateForShort,
693
- import_fixparser.MDEntryType.MarketBid,
694
- import_fixparser.MDEntryType.MarketOffer,
695
- import_fixparser.MDEntryType.ShortSaleMinPrice,
696
- import_fixparser.MDEntryType.PreviousClosingPrice,
697
- import_fixparser.MDEntryType.ThresholdLimitPriceBanding,
698
- import_fixparser.MDEntryType.DailyFinancingValue,
699
- import_fixparser.MDEntryType.AccruedFinancingValue,
700
- import_fixparser.MDEntryType.TWAP
701
- ];
702
- const messageFields = [
703
- new import_fixparser.Field(import_fixparser.Fields.MsgType, import_fixparser.Messages.MarketDataRequest),
704
- new import_fixparser.Field(import_fixparser.Fields.SenderCompID, parser.sender),
705
- new import_fixparser.Field(import_fixparser.Fields.MsgSeqNum, parser.getNextTargetMsgSeqNum()),
706
- new import_fixparser.Field(import_fixparser.Fields.TargetCompID, parser.target),
707
- new import_fixparser.Field(import_fixparser.Fields.SendingTime, parser.getTimestamp()),
708
- new import_fixparser.Field(import_fixparser.Fields.MDReqID, args.mdReqID),
709
- new import_fixparser.Field(import_fixparser.Fields.SubscriptionRequestType, args.subscriptionRequestType),
710
- new import_fixparser.Field(import_fixparser.Fields.MarketDepth, 0),
711
- new import_fixparser.Field(import_fixparser.Fields.MDUpdateType, args.mdUpdateType)
712
- ];
713
- messageFields.push(new import_fixparser.Field(import_fixparser.Fields.NoRelatedSym, args.symbols.length));
714
- args.symbols.forEach((symbol) => {
715
- messageFields.push(new import_fixparser.Field(import_fixparser.Fields.Symbol, symbol));
716
- });
717
- messageFields.push(new import_fixparser.Field(import_fixparser.Fields.NoMDEntryTypes, entryTypes.length));
718
- entryTypes.forEach((entryType) => {
719
- messageFields.push(new import_fixparser.Field(import_fixparser.Fields.MDEntryType, entryType));
720
- });
721
- const mdr = parser.createMessage(...messageFields);
722
- if (!parser.connected) {
723
- parser.logger.log({
724
- level: "error",
725
- message: "Not connected. Cannot send market data request."
726
- });
727
- return {
728
- content: [
729
- {
730
- type: "text",
731
- text: "Error: Not connected. Ignoring message.",
732
- uri: "marketDataRequest"
733
- }
734
- ],
735
- isError: true
736
- };
737
- }
738
- parser.logger.log({
739
- level: "info",
740
- message: `Sending market data request message: ${JSON.stringify(mdr?.toFIXJSON())}`
741
- });
742
- parser.send(mdr);
743
- const fixData = await response;
744
- parser.logger.log({
745
- level: "info",
746
- message: `Received market data response for request ID: ${args.mdReqID}`
747
- });
748
- return {
749
- content: [
750
- {
751
- type: "text",
752
- text: `Market data for ${args.symbols.join(", ")}: ${JSON.stringify(fixData.toFIXJSON())}`,
753
- uri: "marketDataRequest"
754
- }
755
- ]
756
- };
757
- } catch (error) {
758
- return {
759
- content: [
760
- {
761
- type: "text",
762
- text: `Error: ${error instanceof Error ? error.message : "Failed to request market data"}`,
763
- uri: "marketDataRequest"
764
- }
765
- ],
766
- isError: true
767
- };
768
- }
769
- };
770
- };
771
- var createGetStockGraphHandler = (marketDataPrices) => {
772
- return async (args) => {
773
- try {
774
- const symbol = args.symbol;
775
- const priceHistory = marketDataPrices.get(symbol) || [];
776
- if (priceHistory.length === 0) {
777
- return {
778
- content: [
779
- {
780
- type: "text",
781
- text: `No price data available for ${symbol}`,
782
- uri: "getStockGraph"
783
- }
784
- ]
785
- };
786
- }
787
- const chart = new import_quickchart_js.default();
788
- chart.setWidth(1200);
789
- chart.setHeight(600);
790
- chart.setBackgroundColor("transparent");
791
- const labels = priceHistory.map((point) => new Date(point.timestamp).toLocaleTimeString());
792
- const bidData = priceHistory.map((point) => point.bid);
793
- const offerData = priceHistory.map((point) => point.offer);
794
- const spreadData = priceHistory.map((point) => point.spread);
795
- const volumeData = priceHistory.map((point) => point.volume);
796
- const tradeData = priceHistory.map((point) => point.trade);
797
- const vwapData = priceHistory.map((point) => point.vwap);
798
- const twapData = priceHistory.map((point) => point.twap);
799
- const config = {
800
- type: "line",
801
- data: {
802
- labels,
803
- datasets: [
804
- {
805
- label: "Bid",
806
- data: bidData,
807
- borderColor: "#28a745",
808
- backgroundColor: "rgba(40, 167, 69, 0.1)",
809
- fill: false,
810
- tension: 0.4
811
- },
812
- {
813
- label: "Offer",
814
- data: offerData,
815
- borderColor: "#dc3545",
816
- backgroundColor: "rgba(220, 53, 69, 0.1)",
817
- fill: false,
818
- tension: 0.4
819
- },
820
- {
821
- label: "Spread",
822
- data: spreadData,
823
- borderColor: "#6c757d",
824
- backgroundColor: "rgba(108, 117, 125, 0.1)",
825
- fill: false,
826
- tension: 0.4
827
- },
828
- {
829
- label: "Trade",
830
- data: tradeData,
831
- borderColor: "#ffc107",
832
- backgroundColor: "rgba(255, 193, 7, 0.1)",
833
- fill: false,
834
- tension: 0.4
835
- },
836
- {
837
- label: "VWAP",
838
- data: vwapData,
839
- borderColor: "#17a2b8",
840
- backgroundColor: "rgba(23, 162, 184, 0.1)",
841
- fill: false,
842
- tension: 0.4
843
- },
844
- {
845
- label: "TWAP",
846
- data: twapData,
847
- borderColor: "#6610f2",
848
- backgroundColor: "rgba(102, 16, 242, 0.1)",
849
- fill: false,
850
- tension: 0.4
851
- },
852
- {
853
- label: "Volume",
854
- data: volumeData,
855
- borderColor: "#007bff",
856
- backgroundColor: "rgba(0, 123, 255, 0.1)",
857
- fill: true,
858
- tension: 0.4
859
- }
860
- ]
861
- },
862
- options: {
863
- responsive: true,
864
- plugins: {
865
- title: {
866
- display: true,
867
- text: `${symbol} Market Data`
868
- }
869
- },
870
- scales: {
871
- y: {
872
- beginAtZero: false
873
- }
874
- }
875
- }
876
- };
877
- chart.setConfig(config);
878
- const imageBuffer = await chart.toBinary();
879
- const base64 = imageBuffer.toString("base64");
880
- return {
881
- content: [
882
- {
883
- type: "resource",
884
- resource: {
885
- uri: "resource://graph",
886
- mimeType: "image/png",
887
- blob: base64
888
- }
889
- }
890
- ]
891
- };
892
- } catch (error) {
893
- return {
894
- content: [
895
- {
896
- type: "text",
897
- text: `Error: ${error instanceof Error ? error.message : "Failed to generate graph"}`,
898
- uri: "getStockGraph"
899
- }
900
- ],
901
- isError: true
902
- };
903
- }
904
- };
905
- };
906
- var createGetStockPriceHistoryHandler = (marketDataPrices) => {
907
- return async (args) => {
908
- try {
909
- const symbol = args.symbol;
910
- const priceHistory = marketDataPrices.get(symbol) || [];
911
- if (priceHistory.length === 0) {
912
- return {
913
- content: [
914
- {
915
- type: "text",
916
- text: `No price data available for ${symbol}`,
917
- uri: "getStockPriceHistory"
918
- }
919
- ]
920
- };
921
- }
922
- return {
923
- content: [
924
- {
925
- type: "text",
926
- text: JSON.stringify(
927
- {
928
- symbol,
929
- count: priceHistory.length,
930
- data: priceHistory.map((point) => ({
931
- timestamp: new Date(point.timestamp).toISOString(),
932
- bid: point.bid,
933
- offer: point.offer,
934
- spread: point.spread,
935
- volume: point.volume,
936
- trade: point.trade,
937
- indexValue: point.indexValue,
938
- openingPrice: point.openingPrice,
939
- closingPrice: point.closingPrice,
940
- settlementPrice: point.settlementPrice,
941
- tradingSessionHighPrice: point.tradingSessionHighPrice,
942
- tradingSessionLowPrice: point.tradingSessionLowPrice,
943
- vwap: point.vwap,
944
- imbalance: point.imbalance,
945
- openInterest: point.openInterest,
946
- compositeUnderlyingPrice: point.compositeUnderlyingPrice,
947
- simulatedSellPrice: point.simulatedSellPrice,
948
- simulatedBuyPrice: point.simulatedBuyPrice,
949
- marginRate: point.marginRate,
950
- midPrice: point.midPrice,
951
- emptyBook: point.emptyBook,
952
- settleHighPrice: point.settleHighPrice,
953
- settleLowPrice: point.settleLowPrice,
954
- priorSettlePrice: point.priorSettlePrice,
955
- sessionHighBid: point.sessionHighBid,
956
- sessionLowOffer: point.sessionLowOffer,
957
- earlyPrices: point.earlyPrices,
958
- auctionClearingPrice: point.auctionClearingPrice,
959
- swapValueFactor: point.swapValueFactor,
960
- dailyValueAdjustmentForLongPositions: point.dailyValueAdjustmentForLongPositions,
961
- cumulativeValueAdjustmentForLongPositions: point.cumulativeValueAdjustmentForLongPositions,
962
- dailyValueAdjustmentForShortPositions: point.dailyValueAdjustmentForShortPositions,
963
- cumulativeValueAdjustmentForShortPositions: point.cumulativeValueAdjustmentForShortPositions,
964
- fixingPrice: point.fixingPrice,
965
- cashRate: point.cashRate,
966
- recoveryRate: point.recoveryRate,
967
- recoveryRateForLong: point.recoveryRateForLong,
968
- recoveryRateForShort: point.recoveryRateForShort,
969
- marketBid: point.marketBid,
970
- marketOffer: point.marketOffer,
971
- shortSaleMinPrice: point.shortSaleMinPrice,
972
- previousClosingPrice: point.previousClosingPrice,
973
- thresholdLimitPriceBanding: point.thresholdLimitPriceBanding,
974
- dailyFinancingValue: point.dailyFinancingValue,
975
- accruedFinancingValue: point.accruedFinancingValue,
976
- twap: point.twap
977
- }))
978
- },
979
- null,
980
- 2
981
- ),
982
- uri: "getStockPriceHistory"
983
- }
984
- ]
985
- };
986
- } catch (error) {
987
- return {
988
- content: [
989
- {
990
- type: "text",
991
- text: `Error: ${error instanceof Error ? error.message : "Failed to get price history"}`,
992
- uri: "getStockPriceHistory"
993
- }
994
- ],
995
- isError: true
996
- };
997
- }
998
- };
999
- };
1000
-
1001
- // src/tools/order.ts
1002
- var import_fixparser2 = require("fixparser");
1003
- var ordTypeNames = {
1004
- "1": "Market",
1005
- "2": "Limit",
1006
- "3": "Stop",
1007
- "4": "StopLimit",
1008
- "5": "MarketOnClose",
1009
- "6": "WithOrWithout",
1010
- "7": "LimitOrBetter",
1011
- "8": "LimitWithOrWithout",
1012
- "9": "OnBasis",
1013
- A: "OnClose",
1014
- B: "LimitOnClose",
1015
- C: "ForexMarket",
1016
- D: "PreviouslyQuoted",
1017
- E: "PreviouslyIndicated",
1018
- F: "ForexLimit",
1019
- G: "ForexSwap",
1020
- H: "ForexPreviouslyQuoted",
1021
- I: "Funari",
1022
- J: "MarketIfTouched",
1023
- K: "MarketWithLeftOverAsLimit",
1024
- L: "PreviousFundValuationPoint",
1025
- M: "NextFundValuationPoint",
1026
- P: "Pegged",
1027
- Q: "CounterOrderSelection",
1028
- R: "StopOnBidOrOffer",
1029
- S: "StopLimitOnBidOrOffer"
1030
- };
1031
- var sideNames = {
1032
- "1": "Buy",
1033
- "2": "Sell",
1034
- "3": "BuyMinus",
1035
- "4": "SellPlus",
1036
- "5": "SellShort",
1037
- "6": "SellShortExempt",
1038
- "7": "Undisclosed",
1039
- "8": "Cross",
1040
- "9": "CrossShort",
1041
- A: "CrossShortExempt",
1042
- B: "AsDefined",
1043
- C: "Opposite",
1044
- D: "Subscribe",
1045
- E: "Redeem",
1046
- F: "Lend",
1047
- G: "Borrow",
1048
- H: "SellUndisclosed"
1049
- };
1050
- var timeInForceNames = {
1051
- "0": "Day",
1052
- "1": "GoodTillCancel",
1053
- "2": "AtTheOpening",
1054
- "3": "ImmediateOrCancel",
1055
- "4": "FillOrKill",
1056
- "5": "GoodTillCrossing",
1057
- "6": "GoodTillDate",
1058
- "7": "AtTheClose",
1059
- "8": "GoodThroughCrossing",
1060
- "9": "AtCrossing",
1061
- A: "GoodForTime",
1062
- B: "GoodForAuction",
1063
- C: "GoodForMonth"
1064
- };
1065
- var handlInstNames = {
1066
- "1": "AutomatedExecutionNoIntervention",
1067
- "2": "AutomatedExecutionInterventionOK",
1068
- "3": "ManualOrder"
1069
- };
1070
- var createVerifyOrderHandler = (parser, verifiedOrders) => {
1071
- return async (args) => {
1072
- try {
1073
- verifiedOrders.set(args.clOrdID, {
1074
- clOrdID: args.clOrdID,
1075
- handlInst: args.handlInst,
1076
- quantity: Number.parseFloat(String(args.quantity)),
1077
- price: Number.parseFloat(String(args.price)),
1078
- ordType: args.ordType,
1079
- side: args.side,
1080
- symbol: args.symbol,
1081
- timeInForce: args.timeInForce
1082
- });
1083
- return {
1084
- content: [
1085
- {
1086
- type: "text",
1087
- text: `VERIFICATION: All parameters valid. Ready to proceed with order execution.
1088
-
1089
- Parameters verified:
1090
- - ClOrdID: ${args.clOrdID}
1091
- - HandlInst: ${args.handlInst} (${handlInstNames[args.handlInst]})
1092
- - Quantity: ${args.quantity}
1093
- - Price: ${args.price}
1094
- - OrdType: ${args.ordType} (${ordTypeNames[args.ordType]})
1095
- - Side: ${args.side} (${sideNames[args.side]})
1096
- - Symbol: ${args.symbol}
1097
- - TimeInForce: ${args.timeInForce} (${timeInForceNames[args.timeInForce]})
1098
-
1099
- To execute this order, call the executeOrder tool with these exact same parameters. Important: The user has to explicitly confirm before executeOrder is called!`,
1100
- uri: "verifyOrder"
1101
- }
1102
- ]
1103
- };
1104
- } catch (error) {
1105
- return {
1106
- content: [
1107
- {
1108
- type: "text",
1109
- text: `Error: ${error instanceof Error ? error.message : "Failed to verify order parameters"}`,
1110
- uri: "verifyOrder"
1111
- }
1112
- ],
1113
- isError: true
1114
- };
1115
- }
1116
- };
1117
- };
1118
- var createExecuteOrderHandler = (parser, verifiedOrders, pendingRequests) => {
1119
- return async (args) => {
1120
- try {
1121
- const verifiedOrder = verifiedOrders.get(args.clOrdID);
1122
- if (!verifiedOrder) {
1123
- return {
1124
- content: [
1125
- {
1126
- type: "text",
1127
- text: `Error: Order ${args.clOrdID} has not been verified. Please call verifyOrder first.`,
1128
- uri: "executeOrder"
1129
- }
1130
- ],
1131
- isError: true
1132
- };
1133
- }
1134
- 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) {
1135
- return {
1136
- content: [
1137
- {
1138
- type: "text",
1139
- text: "Error: Order parameters do not match the verified order. Please use the exact same parameters that were verified.",
1140
- uri: "executeOrder"
1141
- }
1142
- ],
1143
- isError: true
1144
- };
1145
- }
1146
- const response = new Promise((resolve) => {
1147
- pendingRequests.set(args.clOrdID, resolve);
1148
- });
1149
- const order = parser.createMessage(
1150
- new import_fixparser2.Field(import_fixparser2.Fields.MsgType, import_fixparser2.Messages.NewOrderSingle),
1151
- new import_fixparser2.Field(import_fixparser2.Fields.MsgSeqNum, parser.getNextTargetMsgSeqNum()),
1152
- new import_fixparser2.Field(import_fixparser2.Fields.SenderCompID, parser.sender),
1153
- new import_fixparser2.Field(import_fixparser2.Fields.TargetCompID, parser.target),
1154
- new import_fixparser2.Field(import_fixparser2.Fields.SendingTime, parser.getTimestamp()),
1155
- new import_fixparser2.Field(import_fixparser2.Fields.ClOrdID, args.clOrdID),
1156
- new import_fixparser2.Field(import_fixparser2.Fields.Side, args.side),
1157
- new import_fixparser2.Field(import_fixparser2.Fields.Symbol, args.symbol),
1158
- new import_fixparser2.Field(import_fixparser2.Fields.OrderQty, Number.parseFloat(String(args.quantity))),
1159
- new import_fixparser2.Field(import_fixparser2.Fields.Price, Number.parseFloat(String(args.price))),
1160
- new import_fixparser2.Field(import_fixparser2.Fields.OrdType, args.ordType),
1161
- new import_fixparser2.Field(import_fixparser2.Fields.HandlInst, args.handlInst),
1162
- new import_fixparser2.Field(import_fixparser2.Fields.TimeInForce, args.timeInForce),
1163
- new import_fixparser2.Field(import_fixparser2.Fields.TransactTime, parser.getTimestamp())
1164
- );
1165
- if (!parser.connected) {
1166
- return {
1167
- content: [
1168
- {
1169
- type: "text",
1170
- text: "Error: Not connected. Ignoring message.",
1171
- uri: "executeOrder"
1172
- }
1173
- ],
1174
- isError: true
1175
- };
1176
- }
1177
- parser.send(order);
1178
- const fixData = await response;
1179
- verifiedOrders.delete(args.clOrdID);
1180
- return {
1181
- content: [
1182
- {
1183
- type: "text",
1184
- 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())}`,
1185
- uri: "executeOrder"
1186
- }
1187
- ]
1188
- };
1189
- } catch (error) {
1190
- return {
1191
- content: [
1192
- {
1193
- type: "text",
1194
- text: `Error: ${error instanceof Error ? error.message : "Failed to execute order"}`,
1195
- uri: "executeOrder"
1196
- }
1197
- ],
1198
- isError: true
1199
- };
1200
- }
1201
- };
1202
- };
1203
-
1204
- // src/tools/parse.ts
1205
- var createParseHandler = (parser) => {
1206
- return async (args) => {
1207
- try {
1208
- const parsedMessage = parser.parse(args.fixString);
1209
- if (!parsedMessage || parsedMessage.length === 0) {
1210
- return {
1211
- content: [
1212
- {
1213
- type: "text",
1214
- text: "Error: Failed to parse FIX string",
1215
- uri: "parse"
1216
- }
1217
- ],
1218
- isError: true
1219
- };
1220
- }
1221
- return {
1222
- content: [
1223
- {
1224
- type: "text",
1225
- text: `${parsedMessage[0].description}
1226
- ${parsedMessage[0].messageTypeDescription}`,
1227
- uri: "parse"
1228
- }
1229
- ]
1230
- };
1231
- } catch (error) {
1232
- return {
1233
- content: [
1234
- {
1235
- type: "text",
1236
- text: `Error: ${error instanceof Error ? error.message : "Failed to parse FIX string"}`,
1237
- uri: "parse"
1238
- }
1239
- ],
1240
- isError: true
1241
- };
1242
- }
1243
- };
1244
- };
1245
-
1246
- // src/tools/parseToJSON.ts
1247
- var createParseToJSONHandler = (parser) => {
1248
- return async (args) => {
1249
- try {
1250
- const parsedMessage = parser.parse(args.fixString);
1251
- if (!parsedMessage || parsedMessage.length === 0) {
1252
- return {
1253
- content: [
1254
- {
1255
- type: "text",
1256
- text: "Error: Failed to parse FIX string",
1257
- uri: "parseToJSON"
1258
- }
1259
- ],
1260
- isError: true
1261
- };
1262
- }
1263
- return {
1264
- content: [
1265
- {
1266
- type: "text",
1267
- text: `${parsedMessage[0].toFIXJSON()}`,
1268
- uri: "parseToJSON"
1269
- }
1270
- ]
1271
- };
1272
- } catch (error) {
1273
- return {
1274
- content: [
1275
- {
1276
- type: "text",
1277
- text: `Error: ${error instanceof Error ? error.message : "Failed to parse FIX string"}`,
1278
- uri: "parseToJSON"
1279
- }
1280
- ],
1281
- isError: true
1282
- };
1283
- }
1284
- };
1285
- };
1286
-
1287
- // src/tools/index.ts
1288
- var createToolHandlers = (parser, verifiedOrders, pendingRequests, marketDataPrices) => ({
1289
- parse: createParseHandler(parser),
1290
- parseToJSON: createParseToJSONHandler(parser),
1291
- verifyOrder: createVerifyOrderHandler(parser, verifiedOrders),
1292
- executeOrder: createExecuteOrderHandler(parser, verifiedOrders, pendingRequests),
1293
- marketDataRequest: createMarketDataRequestHandler(parser, pendingRequests),
1294
- getStockGraph: createGetStockGraphHandler(marketDataPrices),
1295
- getStockPriceHistory: createGetStockPriceHistoryHandler(marketDataPrices),
1296
- technicalAnalysis: createTechnicalAnalysisHandler(marketDataPrices)
1297
- });
1298
-
1299
- // src/utils/messageHandler.ts
1300
- var import_fixparser3 = require("fixparser");
1301
- function getEnumValue(enumObj, name) {
1302
- return enumObj[name] || name;
1303
- }
1304
- function handleMessage(message, parser, pendingRequests, marketDataPrices, maxPriceHistory, onPriceUpdate) {
1305
- const msgType = message.messageType;
1306
- if (msgType === import_fixparser3.Messages.MarketDataSnapshotFullRefresh || msgType === import_fixparser3.Messages.MarketDataIncrementalRefresh) {
1307
- const symbol = message.getField(import_fixparser3.Fields.Symbol)?.value;
1308
- const fixJson = message.toFIXJSON();
1309
- const entries = fixJson.Body?.NoMDEntries || [];
1310
- const data = {
1311
- timestamp: Date.now(),
1312
- bid: 0,
1313
- offer: 0,
1314
- spread: 0,
1315
- volume: 0,
1316
- trade: 0,
1317
- indexValue: 0,
1318
- openingPrice: 0,
1319
- closingPrice: 0,
1320
- settlementPrice: 0,
1321
- tradingSessionHighPrice: 0,
1322
- tradingSessionLowPrice: 0,
1323
- vwap: 0,
1324
- imbalance: 0,
1325
- openInterest: 0,
1326
- compositeUnderlyingPrice: 0,
1327
- simulatedSellPrice: 0,
1328
- simulatedBuyPrice: 0,
1329
- marginRate: 0,
1330
- midPrice: 0,
1331
- emptyBook: 0,
1332
- settleHighPrice: 0,
1333
- settleLowPrice: 0,
1334
- priorSettlePrice: 0,
1335
- sessionHighBid: 0,
1336
- sessionLowOffer: 0,
1337
- earlyPrices: 0,
1338
- auctionClearingPrice: 0,
1339
- swapValueFactor: 0,
1340
- dailyValueAdjustmentForLongPositions: 0,
1341
- cumulativeValueAdjustmentForLongPositions: 0,
1342
- dailyValueAdjustmentForShortPositions: 0,
1343
- cumulativeValueAdjustmentForShortPositions: 0,
1344
- fixingPrice: 0,
1345
- cashRate: 0,
1346
- recoveryRate: 0,
1347
- recoveryRateForLong: 0,
1348
- recoveryRateForShort: 0,
1349
- marketBid: 0,
1350
- marketOffer: 0,
1351
- shortSaleMinPrice: 0,
1352
- previousClosingPrice: 0,
1353
- thresholdLimitPriceBanding: 0,
1354
- dailyFinancingValue: 0,
1355
- accruedFinancingValue: 0,
1356
- twap: 0
1357
- };
1358
- for (const entry of entries) {
1359
- const entryType = entry.MDEntryType;
1360
- const price = entry.MDEntryPx ? Number.parseFloat(entry.MDEntryPx) : 0;
1361
- const size = entry.MDEntrySize ? Number.parseFloat(entry.MDEntrySize) : 0;
1362
- const enumValue = getEnumValue(import_fixparser3.MDEntryType, entryType);
1363
- switch (enumValue) {
1364
- case import_fixparser3.MDEntryType.Bid:
1365
- data.bid = price;
1366
- break;
1367
- case import_fixparser3.MDEntryType.Offer:
1368
- data.offer = price;
1369
- break;
1370
- case import_fixparser3.MDEntryType.Trade:
1371
- data.trade = price;
1372
- break;
1373
- case import_fixparser3.MDEntryType.IndexValue:
1374
- data.indexValue = price;
1375
- break;
1376
- case import_fixparser3.MDEntryType.OpeningPrice:
1377
- data.openingPrice = price;
1378
- break;
1379
- case import_fixparser3.MDEntryType.ClosingPrice:
1380
- data.closingPrice = price;
1381
- break;
1382
- case import_fixparser3.MDEntryType.SettlementPrice:
1383
- data.settlementPrice = price;
1384
- break;
1385
- case import_fixparser3.MDEntryType.TradingSessionHighPrice:
1386
- data.tradingSessionHighPrice = price;
1387
- break;
1388
- case import_fixparser3.MDEntryType.TradingSessionLowPrice:
1389
- data.tradingSessionLowPrice = price;
1390
- break;
1391
- case import_fixparser3.MDEntryType.VWAP:
1392
- data.vwap = price;
1393
- break;
1394
- case import_fixparser3.MDEntryType.Imbalance:
1395
- data.imbalance = size;
1396
- break;
1397
- case import_fixparser3.MDEntryType.TradeVolume:
1398
- data.volume = size;
1399
- break;
1400
- case import_fixparser3.MDEntryType.OpenInterest:
1401
- data.openInterest = size;
1402
- break;
1403
- case import_fixparser3.MDEntryType.CompositeUnderlyingPrice:
1404
- data.compositeUnderlyingPrice = price;
1405
- break;
1406
- case import_fixparser3.MDEntryType.SimulatedSellPrice:
1407
- data.simulatedSellPrice = price;
1408
- break;
1409
- case import_fixparser3.MDEntryType.SimulatedBuyPrice:
1410
- data.simulatedBuyPrice = price;
1411
- break;
1412
- case import_fixparser3.MDEntryType.MarginRate:
1413
- data.marginRate = price;
1414
- break;
1415
- case import_fixparser3.MDEntryType.MidPrice:
1416
- data.midPrice = price;
1417
- break;
1418
- case import_fixparser3.MDEntryType.EmptyBook:
1419
- data.emptyBook = 1;
1420
- break;
1421
- case import_fixparser3.MDEntryType.SettleHighPrice:
1422
- data.settleHighPrice = price;
1423
- break;
1424
- case import_fixparser3.MDEntryType.SettleLowPrice:
1425
- data.settleLowPrice = price;
1426
- break;
1427
- case import_fixparser3.MDEntryType.PriorSettlePrice:
1428
- data.priorSettlePrice = price;
1429
- break;
1430
- case import_fixparser3.MDEntryType.SessionHighBid:
1431
- data.sessionHighBid = price;
1432
- break;
1433
- case import_fixparser3.MDEntryType.SessionLowOffer:
1434
- data.sessionLowOffer = price;
1435
- break;
1436
- case import_fixparser3.MDEntryType.EarlyPrices:
1437
- data.earlyPrices = price;
1438
- break;
1439
- case import_fixparser3.MDEntryType.AuctionClearingPrice:
1440
- data.auctionClearingPrice = price;
1441
- break;
1442
- case import_fixparser3.MDEntryType.SwapValueFactor:
1443
- data.swapValueFactor = price;
1444
- break;
1445
- case import_fixparser3.MDEntryType.DailyValueAdjustmentForLongPositions:
1446
- data.dailyValueAdjustmentForLongPositions = price;
1447
- break;
1448
- case import_fixparser3.MDEntryType.CumulativeValueAdjustmentForLongPositions:
1449
- data.cumulativeValueAdjustmentForLongPositions = price;
1450
- break;
1451
- case import_fixparser3.MDEntryType.DailyValueAdjustmentForShortPositions:
1452
- data.dailyValueAdjustmentForShortPositions = price;
1453
- break;
1454
- case import_fixparser3.MDEntryType.CumulativeValueAdjustmentForShortPositions:
1455
- data.cumulativeValueAdjustmentForShortPositions = price;
1456
- break;
1457
- case import_fixparser3.MDEntryType.FixingPrice:
1458
- data.fixingPrice = price;
1459
- break;
1460
- case import_fixparser3.MDEntryType.CashRate:
1461
- data.cashRate = price;
1462
- break;
1463
- case import_fixparser3.MDEntryType.RecoveryRate:
1464
- data.recoveryRate = price;
1465
- break;
1466
- case import_fixparser3.MDEntryType.RecoveryRateForLong:
1467
- data.recoveryRateForLong = price;
1468
- break;
1469
- case import_fixparser3.MDEntryType.RecoveryRateForShort:
1470
- data.recoveryRateForShort = price;
1471
- break;
1472
- case import_fixparser3.MDEntryType.MarketBid:
1473
- data.marketBid = price;
1474
- break;
1475
- case import_fixparser3.MDEntryType.MarketOffer:
1476
- data.marketOffer = price;
1477
- break;
1478
- case import_fixparser3.MDEntryType.ShortSaleMinPrice:
1479
- data.shortSaleMinPrice = price;
1480
- break;
1481
- case import_fixparser3.MDEntryType.PreviousClosingPrice:
1482
- data.previousClosingPrice = price;
1483
- break;
1484
- case import_fixparser3.MDEntryType.ThresholdLimitPriceBanding:
1485
- data.thresholdLimitPriceBanding = price;
1486
- break;
1487
- case import_fixparser3.MDEntryType.DailyFinancingValue:
1488
- data.dailyFinancingValue = price;
1489
- break;
1490
- case import_fixparser3.MDEntryType.AccruedFinancingValue:
1491
- data.accruedFinancingValue = price;
1492
- break;
1493
- case import_fixparser3.MDEntryType.TWAP:
1494
- data.twap = price;
1495
- break;
1496
- }
1497
- }
1498
- data.spread = data.offer - data.bid;
1499
- if (!marketDataPrices.has(symbol)) {
1500
- marketDataPrices.set(symbol, []);
1501
- }
1502
- const prices = marketDataPrices.get(symbol);
1503
- prices.push(data);
1504
- if (prices.length > maxPriceHistory) {
1505
- prices.splice(0, prices.length - maxPriceHistory);
1506
- }
1507
- onPriceUpdate?.(symbol, data);
1508
- const mdReqID = message.getField(import_fixparser3.Fields.MDReqID)?.value;
1509
- if (mdReqID) {
1510
- const callback = pendingRequests.get(mdReqID);
1511
- if (callback) {
1512
- callback(message);
1513
- pendingRequests.delete(mdReqID);
1514
- }
1515
- }
1516
- } else if (msgType === import_fixparser3.Messages.ExecutionReport) {
1517
- const reqId = message.getField(import_fixparser3.Fields.ClOrdID)?.value;
1518
- const callback = pendingRequests.get(reqId);
1519
- if (callback) {
1520
- callback(message);
1521
- pendingRequests.delete(reqId);
1522
- }
1523
- }
1524
- }
1525
-
1526
- // src/MCPLocal.ts
1527
- var MCPLocal = class extends MCPBase {
1528
- /**
1529
- * Map to store verified orders before execution
1530
- * @private
1531
- */
1532
- verifiedOrders = /* @__PURE__ */ new Map();
1533
- /**
1534
- * Map to store pending requests and their callbacks
1535
- * @private
1536
- */
1537
- pendingRequests = /* @__PURE__ */ new Map();
1538
- /**
1539
- * Map to store market data prices for each symbol
1540
- * @private
1541
- */
1542
- marketDataPrices = /* @__PURE__ */ new Map();
1543
- /**
1544
- * Maximum number of price history entries to keep per symbol
1545
- * @private
1546
- */
1547
- MAX_PRICE_HISTORY = 1e5;
1548
- server = new import_server.Server(
1549
- {
1550
- name: "fixparser",
1551
- version: "1.0.0"
1552
- },
1553
- {
1554
- capabilities: {
1555
- tools: Object.entries(toolSchemas).reduce(
1556
- (acc, [name, { description, schema }]) => {
1557
- acc[name] = {
1558
- description,
1559
- parameters: schema
1560
- };
1561
- return acc;
1562
- },
1563
- {}
1564
- )
1565
- }
1566
- }
1567
- );
1568
- transport = new import_stdio.StdioServerTransport();
1569
- constructor({ logger, onReady }) {
1570
- super({ logger, onReady });
1571
- }
1572
- async register(parser) {
1573
- this.parser = parser;
1574
- this.parser.addOnMessageCallback((message) => {
1575
- handleMessage(message, this.parser, this.pendingRequests, this.marketDataPrices, this.MAX_PRICE_HISTORY);
1576
- });
1577
- this.addWorkflows();
1578
- await this.server.connect(this.transport);
1579
- if (this.onReady) {
1580
- this.onReady();
1581
- }
1582
- }
1583
- addWorkflows() {
1584
- if (!this.parser) {
1585
- return;
1586
- }
1587
- if (!this.server) {
1588
- return;
1589
- }
1590
- this.server.setRequestHandler(import_zod.z.object({ method: import_zod.z.literal("tools/list") }), async () => {
1591
- return {
1592
- tools: Object.entries(toolSchemas).map(([name, { description, schema }]) => ({
1593
- name,
1594
- description,
1595
- inputSchema: schema
1596
- }))
1597
- };
1598
- });
1599
- this.server.setRequestHandler(
1600
- import_zod.z.object({
1601
- method: import_zod.z.literal("tools/call"),
1602
- params: import_zod.z.object({
1603
- name: import_zod.z.string(),
1604
- arguments: import_zod.z.any(),
1605
- _meta: import_zod.z.object({
1606
- progressToken: import_zod.z.number()
1607
- }).optional()
1608
- })
1609
- }),
1610
- async (request) => {
1611
- const { name, arguments: args } = request.params;
1612
- const toolHandlers = createToolHandlers(
1613
- this.parser,
1614
- this.verifiedOrders,
1615
- this.pendingRequests,
1616
- this.marketDataPrices
1617
- );
1618
- const handler = toolHandlers[name];
1619
- if (!handler) {
1620
- return {
1621
- content: [
1622
- {
1623
- type: "text",
1624
- text: `Tool not found: ${name}`,
1625
- uri: name
1626
- }
1627
- ],
1628
- isError: true
1629
- };
1630
- }
1631
- const result = await handler(args);
1632
- return {
1633
- content: result.content,
1634
- isError: result.isError
1635
- };
1636
- }
1637
- );
1638
- process.on("SIGINT", async () => {
1639
- await this.server.close();
1640
- process.exit(0);
1641
- });
1642
- }
1643
- };
1644
-
1645
- // src/MCPRemote.ts
1646
- var import_node_crypto = require("node:crypto");
1647
- var import_node_http = require("node:http");
1648
- var import_mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
1649
- var import_streamableHttp = require("@modelcontextprotocol/sdk/server/streamableHttp.js");
1650
- var import_types = require("@modelcontextprotocol/sdk/types.js");
1651
- var import_zod2 = require("zod");
1652
- var transports = {};
1653
- function jsonSchemaToZod(schema) {
1654
- if (schema.type === "object") {
1655
- const shape = {};
1656
- for (const [key, prop] of Object.entries(schema.properties || {})) {
1657
- const propSchema = prop;
1658
- if (propSchema.type === "string") {
1659
- if (propSchema.enum) {
1660
- shape[key] = import_zod2.z.enum(propSchema.enum);
1661
- } else {
1662
- shape[key] = import_zod2.z.string();
1663
- }
1664
- } else if (propSchema.type === "number") {
1665
- shape[key] = import_zod2.z.number();
1666
- } else if (propSchema.type === "boolean") {
1667
- shape[key] = import_zod2.z.boolean();
1668
- } else if (propSchema.type === "array") {
1669
- if (propSchema.items.type === "string") {
1670
- shape[key] = import_zod2.z.array(import_zod2.z.string());
1671
- } else if (propSchema.items.type === "number") {
1672
- shape[key] = import_zod2.z.array(import_zod2.z.number());
1673
- } else if (propSchema.items.type === "boolean") {
1674
- shape[key] = import_zod2.z.array(import_zod2.z.boolean());
1675
- } else {
1676
- shape[key] = import_zod2.z.array(import_zod2.z.any());
1677
- }
1678
- } else {
1679
- shape[key] = import_zod2.z.any();
1680
- }
1681
- }
1682
- return shape;
1683
- }
1684
- return {};
1685
- }
1686
- var MCPRemote = class extends MCPBase {
1687
- /**
1688
- * Port number the server will listen on.
1689
- * @private
1690
- */
1691
- port;
1692
- /**
1693
- * Node.js HTTP server instance created internally.
1694
- * @private
1695
- */
1696
- httpServer;
1697
- /**
1698
- * MCP server instance handling MCP protocol logic.
1699
- * @private
1700
- */
1701
- mcpServer;
1702
- /**
1703
- * Optional name of the plugin/server instance.
1704
- * @private
1705
- */
1706
- serverName;
1707
- /**
1708
- * Optional version string of the plugin/server.
1709
- * @private
1710
- */
1711
- serverVersion;
1712
- /**
1713
- * Map to store verified orders before execution
1714
- * @private
1715
- */
1716
- verifiedOrders = /* @__PURE__ */ new Map();
1717
- /**
1718
- * Map to store pending requests and their callbacks
1719
- * @private
1720
- */
1721
- pendingRequests = /* @__PURE__ */ new Map();
1722
- /**
1723
- * Map to store market data prices for each symbol
1724
- * @private
1725
- */
1726
- marketDataPrices = /* @__PURE__ */ new Map();
1727
- /**
1728
- * Maximum number of price history entries to keep per symbol
1729
- * @private
1730
- */
1731
- MAX_PRICE_HISTORY = 1e5;
1732
- constructor({ port, logger, onReady }) {
1733
- super({ logger, onReady });
1734
- this.port = port;
1735
- }
1736
- async register(parser) {
1737
- this.parser = parser;
1738
- this.logger = parser.logger;
1739
- this.logger?.log({
1740
- level: "info",
1741
- message: `FIXParser (MCP): -- Plugin registered. Creating MCP server on port ${this.port}...`
1742
- });
1743
- this.parser.addOnMessageCallback((message) => {
1744
- if (this.parser) {
1745
- handleMessage(
1746
- message,
1747
- this.parser,
1748
- this.pendingRequests,
1749
- this.marketDataPrices,
1750
- this.MAX_PRICE_HISTORY
1751
- );
1752
- }
1753
- });
1754
- this.httpServer = (0, import_node_http.createServer)(async (req, res) => {
1755
- if (!req.url || !req.method) {
1756
- res.writeHead(400);
1757
- res.end("Bad Request");
1758
- return;
1759
- }
1760
- if (req.url === "/mcp") {
1761
- const sessionId = req.headers["mcp-session-id"];
1762
- if (req.method === "POST") {
1763
- const bodyChunks = [];
1764
- req.on("data", (chunk) => {
1765
- bodyChunks.push(chunk);
1766
- });
1767
- req.on("end", async () => {
1768
- let parsed;
1769
- const body = Buffer.concat(bodyChunks).toString();
1770
- try {
1771
- parsed = JSON.parse(body);
1772
- } catch (err) {
1773
- res.writeHead(400);
1774
- res.end(JSON.stringify({ error: "Invalid JSON" }));
1775
- return;
1776
- }
1777
- let transport;
1778
- if (sessionId && transports[sessionId]) {
1779
- transport = transports[sessionId];
1780
- } else if (!sessionId && req.method === "POST" && (0, import_types.isInitializeRequest)(parsed)) {
1781
- transport = new import_streamableHttp.StreamableHTTPServerTransport({
1782
- sessionIdGenerator: () => (0, import_node_crypto.randomUUID)(),
1783
- onsessioninitialized: (sessionId2) => {
1784
- transports[sessionId2] = transport;
1785
- }
1786
- });
1787
- transport.onclose = () => {
1788
- if (transport.sessionId) {
1789
- delete transports[transport.sessionId];
1790
- }
1791
- };
1792
- this.mcpServer = new import_mcp.McpServer({
1793
- name: this.serverName || "FIXParser",
1794
- version: this.serverVersion || "1.0.0"
1795
- });
1796
- this.setupTools();
1797
- await this.mcpServer.connect(transport);
1798
- } else {
1799
- res.writeHead(400, { "Content-Type": "application/json" });
1800
- res.end(
1801
- JSON.stringify({
1802
- jsonrpc: "2.0",
1803
- error: {
1804
- code: -32e3,
1805
- message: "Bad Request: No valid session ID provided"
1806
- },
1807
- id: null
1808
- })
1809
- );
1810
- return;
1811
- }
1812
- try {
1813
- await transport.handleRequest(req, res, parsed);
1814
- } catch (error) {
1815
- this.logger?.log({
1816
- level: "error",
1817
- message: `Error handling request: ${error}`
1818
- });
1819
- throw error;
1820
- }
1821
- });
1822
- } else if (req.method === "GET" || req.method === "DELETE") {
1823
- if (!sessionId || !transports[sessionId]) {
1824
- res.writeHead(400);
1825
- res.end("Invalid or missing session ID");
1826
- return;
1827
- }
1828
- const transport = transports[sessionId];
1829
- try {
1830
- await transport.handleRequest(req, res);
1831
- } catch (error) {
1832
- this.logger?.log({
1833
- level: "error",
1834
- message: `Error handling ${req.method} request: ${error}`
1835
- });
1836
- throw error;
1837
- }
1838
- } else {
1839
- this.logger?.log({
1840
- level: "error",
1841
- message: `Method not allowed: ${req.method}`
1842
- });
1843
- res.writeHead(405);
1844
- res.end("Method Not Allowed");
1845
- }
1846
- } else {
1847
- res.writeHead(404);
1848
- res.end("Not Found");
1849
- }
1850
- });
1851
- this.httpServer.listen(this.port, () => {
1852
- this.logger?.log({
1853
- level: "info",
1854
- message: `FIXParser (MCP): -- Server listening on http://localhost:${this.port}...`
1855
- });
1856
- });
1857
- if (this.onReady) {
1858
- this.onReady();
1859
- }
1860
- }
1861
- setupTools() {
1862
- if (!this.parser) {
1863
- this.logger?.log({
1864
- level: "error",
1865
- message: "FIXParser (MCP): -- FIXParser instance not initialized. Ignoring setup of tools..."
1866
- });
1867
- return;
1868
- }
1869
- if (!this.mcpServer) {
1870
- this.logger?.log({
1871
- level: "error",
1872
- message: "FIXParser (MCP): -- MCP Server not initialized. Ignoring setup of tools..."
1873
- });
1874
- return;
1875
- }
1876
- const toolHandlers = createToolHandlers(
1877
- this.parser,
1878
- this.verifiedOrders,
1879
- this.pendingRequests,
1880
- this.marketDataPrices
1881
- );
1882
- Object.entries(toolSchemas).forEach(([name, { description, schema }]) => {
1883
- this.mcpServer?.registerTool(
1884
- name,
1885
- {
1886
- description,
1887
- inputSchema: jsonSchemaToZod(schema)
1888
- },
1889
- async (args) => {
1890
- const handler = toolHandlers[name];
1891
- if (!handler) {
1892
- return {
1893
- content: [
1894
- {
1895
- type: "text",
1896
- text: `Tool not found: ${name}`
1897
- }
1898
- ],
1899
- isError: true
1900
- };
1901
- }
1902
- const result = await handler(args);
1903
- return {
1904
- content: result.content,
1905
- isError: result.isError
1906
- };
1907
- }
1908
- );
1909
- });
1910
- }
1911
- };
1912
- // Annotate the CommonJS export names for ESM import in node:
1913
- 0 && (module.exports = {
1914
- MCPLocal,
1915
- MCPRemote
1916
- });
1917
- //# sourceMappingURL=index.js.map