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