fixparser-plugin-mcp 9.1.7-dde631c6 → 9.1.7-def37df3

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