fixparser-plugin-mcp 9.1.7-d7ecb477 → 9.1.7-def37df3

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