fixparser-plugin-mcp 9.1.7-2924f547 → 9.1.7-2cd4ac1b

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