fixparser-plugin-mcp 9.1.7-74db6dbc → 9.1.7-81ea0211

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