fixparser-plugin-mcp 9.1.7-71fc8a2b → 9.1.7-74db6dbc
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.
- package/build/cjs/MCPLocal.js +2446 -1804
- package/build/cjs/MCPLocal.js.map +4 -4
- package/build/cjs/MCPRemote.js +2600 -436
- package/build/cjs/MCPRemote.js.map +4 -4
- package/build/cjs/index.js +2898 -0
- package/build/cjs/index.js.map +7 -0
- package/build/esm/MCPLocal.mjs +2433 -1816
- package/build/esm/MCPLocal.mjs.map +4 -4
- package/build/esm/MCPRemote.mjs +2591 -446
- package/build/esm/MCPRemote.mjs.map +4 -4
- package/build/esm/index.mjs +2860 -0
- package/build/esm/index.mjs.map +7 -0
- package/build-examples/cjs/example_mcp_local.js +16 -7
- package/build-examples/cjs/example_mcp_local.js.map +4 -4
- package/build-examples/cjs/example_mcp_remote.js +18 -0
- package/build-examples/cjs/example_mcp_remote.js.map +7 -0
- package/build-examples/esm/example_mcp_local.mjs +16 -7
- package/build-examples/esm/example_mcp_local.mjs.map +4 -4
- package/build-examples/esm/example_mcp_remote.mjs +18 -0
- package/build-examples/esm/example_mcp_remote.mjs.map +7 -0
- package/package.json +17 -16
- package/types/MCPLocal.d.ts +0 -14
- package/types/MCPRemote.d.ts +0 -60
- package/types/PluginOptions.d.ts +0 -6
- package/types/index.d.ts +0 -3
|
@@ -1,9 +1,18 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var g=require("fixparser");var F=require("@modelcontextprotocol/sdk/server/index.js"),N=require("@modelcontextprotocol/sdk/server/stdio.js"),S=require("@modelcontextprotocol/sdk/types.js"),c=require("zod"),l=require("zod"),q=require("zod"),P=require("zod"),C=require("zod"),i=require("fixparser"),z=Symbol("Let zodToJsonSchema decide on which parser to use"),D={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},U=t=>typeof t=="string"?{...D,name:t}:{...D,...t},B=t=>{let e=U(t),n=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([r,a])=>[a._def,{def:a._def,path:[...e.basePath,e.definitionPath,r],jsonSchema:void 0}]))}};function _(t,e,n,r){r?.errorMessages&&n&&(t.errorMessage={...t.errorMessage,[e]:n})}function m(t,e,n,r,a){t[e]=n,_(t,e,r,a)}function J(){return{}}function H(t,e){let n={type:"array"};return t.type?._def&&t.type?._def?.typeName!==q.ZodFirstPartyTypeKind.ZodAny&&(n.items=d(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&m(n,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&m(n,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(m(n,"minItems",t.exactLength.value,t.exactLength.message,e),m(n,"maxItems",t.exactLength.value,t.exactLength.message,e)),n}function K(t,e){let n={type:"integer",format:"int64"};if(!t.checks)return n;for(let r of t.checks)switch(r.kind){case"min":e.target==="jsonSchema7"?r.inclusive?m(n,"minimum",r.value,r.message,e):m(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),m(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?m(n,"maximum",r.value,r.message,e):m(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),m(n,"maximum",r.value,r.message,e));break;case"multipleOf":m(n,"multipleOf",r.value,r.message,e);break}return n}function G(){return{type:"boolean"}}function R(t,e){return d(t.type._def,e)}var V=(t,e)=>d(t.innerType._def,e);function Z(t,e,n){let r=n??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((a,s)=>Z(t,e,a))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return W(t,e)}}var W=(t,e)=>{let n={type:"integer",format:"unix-time"};if(e.target==="openApi3")return n;for(let r of t.checks)switch(r.kind){case"min":m(n,"minimum",r.value,r.message,e);break;case"max":m(n,"maximum",r.value,r.message,e);break}return n};function Q(t,e){return{...d(t.innerType._def,e),default:t.defaultValue()}}function Y(t,e){return e.effectStrategy==="input"?d(t.schema._def,e):{}}function ee(t){return{type:"string",enum:Array.from(t.values)}}var te=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function re(t,e){let n=[d(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),d(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),r=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,a=[];return n.forEach(s=>{if(te(s))a.push(...s.allOf),s.unevaluatedProperties===void 0&&(r=void 0);else{let u=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:p,...o}=s;u=o}else r=void 0;a.push(u)}}),a.length?{allOf:a,...r}:void 0}function ne(t,e){let n=typeof t.value;return n!=="bigint"&&n!=="number"&&n!=="boolean"&&n!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:n==="bigint"?"integer":n,enum:[t.value]}:{type:n==="bigint"?"integer":n,const:t.value}}var O=void 0,h={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(O===void 0&&(O=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),O),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}$/,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])$/,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])$/,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})))$/,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])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function E(t,e){let n={type:"string"};if(t.checks)for(let r of t.checks)switch(r.kind){case"min":m(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e);break;case"max":m(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"email":switch(e.emailStrategy){case"format:email":b(n,"email",r.message,e);break;case"format:idn-email":b(n,"idn-email",r.message,e);break;case"pattern:zod":y(n,h.email,r.message,e);break}break;case"url":b(n,"uri",r.message,e);break;case"uuid":b(n,"uuid",r.message,e);break;case"regex":y(n,r.regex,r.message,e);break;case"cuid":y(n,h.cuid,r.message,e);break;case"cuid2":y(n,h.cuid2,r.message,e);break;case"startsWith":y(n,RegExp(`^${w(r.value,e)}`),r.message,e);break;case"endsWith":y(n,RegExp(`${w(r.value,e)}$`),r.message,e);break;case"datetime":b(n,"date-time",r.message,e);break;case"date":b(n,"date",r.message,e);break;case"time":b(n,"time",r.message,e);break;case"duration":b(n,"duration",r.message,e);break;case"length":m(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e),m(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"includes":{y(n,RegExp(w(r.value,e)),r.message,e);break}case"ip":{r.version!=="v6"&&b(n,"ipv4",r.message,e),r.version!=="v4"&&b(n,"ipv6",r.message,e);break}case"base64url":y(n,h.base64url,r.message,e);break;case"jwt":y(n,h.jwt,r.message,e);break;case"cidr":{r.version!=="v6"&&y(n,h.ipv4Cidr,r.message,e),r.version!=="v4"&&y(n,h.ipv6Cidr,r.message,e);break}case"emoji":y(n,h.emoji(),r.message,e);break;case"ulid":{y(n,h.ulid,r.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{b(n,"binary",r.message,e);break}case"contentEncoding:base64":{m(n,"contentEncoding","base64",r.message,e);break}case"pattern:zod":{y(n,h.base64,r.message,e);break}}break}case"nanoid":y(n,h.nanoid,r.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return n}function w(t,e){return e.patternStrategy==="escape"?ie(t):t}var ae=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function ie(t){let e="";for(let n=0;n<t.length;n++)ae.has(t[n])||(e+="\\"),e+=t[n];return e}function b(t,e,n,r){t.format||t.anyOf?.some(a=>a.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&r.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...n&&r.errorMessages&&{errorMessage:{format:n}}})):m(t,"format",e,n,r)}function y(t,e,n,r){t.pattern||t.allOf?.some(a=>a.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&r.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:x(e,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):m(t,"pattern",x(e,r),n,r)}function x(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let n={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},r=n.i?t.source.toLowerCase():t.source,a="",s=!1,u=!1,p=!1;for(let o=0;o<r.length;o++){if(s){a+=r[o],s=!1;continue}if(n.i){if(u){if(r[o].match(/[a-z]/)){p?(a+=r[o],a+=`${r[o-2]}-${r[o]}`.toUpperCase(),p=!1):r[o+1]==="-"&&r[o+2]?.match(/[a-z]/)?(a+=r[o],p=!0):a+=`${r[o]}${r[o].toUpperCase()}`;continue}}else if(r[o].match(/[a-z]/)){a+=`[${r[o]}${r[o].toUpperCase()}]`;continue}}if(n.m){if(r[o]==="^"){a+=`(^|(?<=[\r
|
|
3
|
-
|
|
4
|
-
]))`;continue}}if(n.s&&r[o]==="."){a+=u?`${r[o]}\r
|
|
5
|
-
|
|
6
|
-
]`;continue}a+=r[o],r[o]==="\\"?s=!0:u&&r[o]==="]"?u=!1:!u&&r[o]==="["&&(u=!0)}try{new RegExp(a)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return a}function $(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===P.ZodFirstPartyTypeKind.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((r,a)=>({...r,[a]:d(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",a]})??{}}),{}),additionalProperties:e.rejectedAdditionalProperties};let n={type:"object",additionalProperties:d(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return n;if(t.keyType?._def.typeName===P.ZodFirstPartyTypeKind.ZodString&&t.keyType._def.checks?.length){let{type:r,...a}=E(t.keyType._def,e);return{...n,propertyNames:a}}else{if(t.keyType?._def.typeName===P.ZodFirstPartyTypeKind.ZodEnum)return{...n,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===P.ZodFirstPartyTypeKind.ZodBranded&&t.keyType._def.type._def.typeName===P.ZodFirstPartyTypeKind.ZodString&&t.keyType._def.type._def.checks?.length){let{type:r,...a}=R(t.keyType._def,e);return{...n,propertyNames:a}}}return n}function se(t,e){if(e.mapStrategy==="record")return $(t,e);let n=d(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},r=d(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}function oe(t){let e=t.values,r=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),a=Array.from(new Set(r.map(s=>typeof s)));return{type:a.length===1?a[0]==="string"?"string":"number":["string","number"],enum:r}}function ue(){return{not:{}}}function ce(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var I={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function pe(t,e){if(e.target==="openApi3")return A(t,e);let n=t.options instanceof Map?Array.from(t.options.values()):t.options;if(n.every(r=>r._def.typeName in I&&(!r._def.checks||!r._def.checks.length))){let r=n.reduce((a,s)=>{let u=I[s._def.typeName];return u&&!a.includes(u)?[...a,u]:a},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){let r=n.reduce((a,s)=>{let u=typeof s._def.value;switch(u){case"string":case"number":case"boolean":return[...a,u];case"bigint":return[...a,"integer"];case"object":if(s._def.value===null)return[...a,"null"];case"symbol":case"undefined":case"function":default:return a}},[]);if(r.length===n.length){let a=r.filter((s,u,p)=>p.indexOf(s)===u);return{type:a.length>1?a:a[0],enum:n.reduce((s,u)=>s.includes(u._def.value)?s:[...s,u._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,a)=>[...r,...a._def.values.filter(s=>!r.includes(s))],[])};return A(t,e)}var A=(t,e)=>{let n=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((r,a)=>d(r._def,{...e,currentPath:[...e.currentPath,"anyOf",`${a}`]})).filter(r=>!!r&&(!e.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0};function le(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:I[t.innerType._def.typeName],nullable:!0}:{type:[I[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let r=d(t.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let n=d(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function de(t,e){let n={type:"number"};if(!t.checks)return n;for(let r of t.checks)switch(r.kind){case"int":n.type="integer",_(n,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?m(n,"minimum",r.value,r.message,e):m(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),m(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?m(n,"maximum",r.value,r.message,e):m(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),m(n,"maximum",r.value,r.message,e));break;case"multipleOf":m(n,"multipleOf",r.value,r.message,e);break}return n}function me(t,e){let n=e.target==="openAi",r={type:"object",properties:{}},a=[],s=t.shape();for(let p in s){let o=s[p];if(o===void 0||o._def===void 0)continue;let f=ye(o);f&&n&&(o instanceof C.ZodOptional&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),f=!1);let v=d(o._def,{...e,currentPath:[...e.currentPath,"properties",p],propertyPath:[...e.currentPath,"properties",p]});v!==void 0&&(r.properties[p]=v,f||a.push(p))}a.length&&(r.required=a);let u=ge(t,e);return u!==void 0&&(r.additionalProperties=u),r}function ge(t,e){if(t.catchall._def.typeName!=="ZodNever")return d(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function ye(t){try{return t.isOptional()}catch{return!0}}var fe=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return d(t.innerType._def,e);let n=d(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:{}},n]}:{}},he=(t,e)=>{if(e.pipeStrategy==="input")return d(t.in._def,e);if(e.pipeStrategy==="output")return d(t.out._def,e);let n=d(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),r=d(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(a=>a!==void 0)}};function be(t,e){return d(t.type._def,e)}function ve(t,e){let r={type:"array",uniqueItems:!0,items:d(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&m(r,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&m(r,"maxItems",t.maxSize.value,t.maxSize.message,e),r}function Se(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((n,r)=>d(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:d(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((n,r)=>d(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}function Pe(){return{not:{}}}function Te(){return{}}var Ie=(t,e)=>d(t.innerType._def,e),ke=(t,e,n)=>{switch(e){case l.ZodFirstPartyTypeKind.ZodString:return E(t,n);case l.ZodFirstPartyTypeKind.ZodNumber:return de(t,n);case l.ZodFirstPartyTypeKind.ZodObject:return me(t,n);case l.ZodFirstPartyTypeKind.ZodBigInt:return K(t,n);case l.ZodFirstPartyTypeKind.ZodBoolean:return G();case l.ZodFirstPartyTypeKind.ZodDate:return Z(t,n);case l.ZodFirstPartyTypeKind.ZodUndefined:return Pe();case l.ZodFirstPartyTypeKind.ZodNull:return ce(n);case l.ZodFirstPartyTypeKind.ZodArray:return H(t,n);case l.ZodFirstPartyTypeKind.ZodUnion:case l.ZodFirstPartyTypeKind.ZodDiscriminatedUnion:return pe(t,n);case l.ZodFirstPartyTypeKind.ZodIntersection:return re(t,n);case l.ZodFirstPartyTypeKind.ZodTuple:return Se(t,n);case l.ZodFirstPartyTypeKind.ZodRecord:return $(t,n);case l.ZodFirstPartyTypeKind.ZodLiteral:return ne(t,n);case l.ZodFirstPartyTypeKind.ZodEnum:return ee(t);case l.ZodFirstPartyTypeKind.ZodNativeEnum:return oe(t);case l.ZodFirstPartyTypeKind.ZodNullable:return le(t,n);case l.ZodFirstPartyTypeKind.ZodOptional:return fe(t,n);case l.ZodFirstPartyTypeKind.ZodMap:return se(t,n);case l.ZodFirstPartyTypeKind.ZodSet:return ve(t,n);case l.ZodFirstPartyTypeKind.ZodLazy:return()=>t.getter()._def;case l.ZodFirstPartyTypeKind.ZodPromise:return be(t,n);case l.ZodFirstPartyTypeKind.ZodNaN:case l.ZodFirstPartyTypeKind.ZodNever:return ue();case l.ZodFirstPartyTypeKind.ZodEffects:return Y(t,n);case l.ZodFirstPartyTypeKind.ZodAny:return J();case l.ZodFirstPartyTypeKind.ZodUnknown:return Te();case l.ZodFirstPartyTypeKind.ZodDefault:return Q(t,n);case l.ZodFirstPartyTypeKind.ZodBranded:return R(t,n);case l.ZodFirstPartyTypeKind.ZodReadonly:return Ie(t,n);case l.ZodFirstPartyTypeKind.ZodCatch:return V(t,n);case l.ZodFirstPartyTypeKind.ZodPipeline:return he(t,n);case l.ZodFirstPartyTypeKind.ZodFunction:case l.ZodFirstPartyTypeKind.ZodVoid:case l.ZodFirstPartyTypeKind.ZodSymbol:return;default:return(r=>{})(e)}};function d(t,e,n=!1){let r=e.seen.get(t);if(e.override){let p=e.override?.(t,e,r,n);if(p!==z)return p}if(r&&!n){let p=Oe(r,e);if(p!==void 0)return p}let a={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,a);let s=ke(t,t.typeName,e),u=typeof s=="function"?d(s(),e):s;if(u&&Me(t,e,u),e.postProcess){let p=e.postProcess(u,t,e);return a.jsonSchema=u,p}return a.jsonSchema=u,u}var Oe=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:we(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((n,r)=>e.currentPath[r]===n)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},we=(t,e)=>{let n=0;for(;n<t.length&&n<e.length&&t[n]===e[n];n++);return[(t.length-n).toString(),...e.slice(n)].join("/")},Me=(t,e,n)=>(t.description&&(n.description=t.description,e.markdownDescription&&(n.markdownDescription=t.description)),n),T=(t,e)=>{let n=B(e),r=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((o,[f,v])=>({...o,[f]:d(v._def,{...n,currentPath:[...n.basePath,n.definitionPath,f]},!0)??{}}),{}):void 0,a=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=d(t._def,a===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,a]},!1)??{},u=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;u!==void 0&&(s.title=u);let p=a===void 0?r?{...s,[n.definitionPath]:r}:s:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,a].join("/"),[n.definitionPath]:{...r,[a]:s}};return n.target==="jsonSchema7"?p.$schema="http://json-schema.org/draft-07/schema#":(n.target==="jsonSchema2019-09"||n.target==="openAi")&&(p.$schema="https://json-schema.org/draft/2019-09/schema#"),n.target==="openAi"&&("anyOf"in p||"oneOf"in p||"allOf"in p||"type"in p&&Array.isArray(p.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),p},j=class{logger;parser;server=new F.Server({name:"fixparser",version:"1.0.0"},{capabilities:{tools:{},prompts:{},resources:{}}});transport=new N.StdioServerTransport;onReady=void 0;pendingRequests=new Map;constructor({logger:t,onReady:e}){t&&(this.logger=t),e&&(this.onReady=e)}async register(t){this.parser=t,this.parser.addOnMessageCallback(e=>{this.logger?.log({level:"info",message:`FIXParser (MCP): (${t.protocol?.toUpperCase()}): << received ${e.description}`});let n=e.messageType;if(n===i.Messages.MarketDataSnapshotFullRefresh||n===i.Messages.ExecutionReport){let r=n===i.Messages.MarketDataSnapshotFullRefresh?e.getField(i.Fields.MDReqID):e.getField(i.Fields.ClOrdID);if(r){let a=r.value;if(typeof a=="string"||typeof a=="number"){let s=this.pendingRequests.get(String(a));s&&(s(e),this.pendingRequests.delete(String(a)))}}}}),this.logger=t.logger,this.addWorkflows(),await this.server.connect(this.transport),this.onReady&&this.onReady()}addWorkflows(){if(!this.parser){this.logger?.log({level:"error",message:"FIXParser (MCP): -- FIXParser instance not initialized. Ignoring setup of workflows..."});return}if(!this.server){this.logger?.log({level:"error",message:"FIXParser (MCP): -- MCP Server not initialized. Ignoring setup of workflows..."});return}this.server.setRequestHandler(S.ListResourcesRequestSchema,async()=>({resources:[]})),this.server.setRequestHandler(S.ListToolsRequestSchema,async()=>({tools:[{name:"parse",description:"Parses a FIX message and describes it in plain language",inputSchema:T(c.z.object({fixString:c.z.string().describe("FIX message string to parse")}),{name:"ParseInput"})},{name:"parseToJSON",description:"Parses a FIX message into JSON",inputSchema:T(c.z.object({fixString:c.z.string().describe("FIX message string to parse")}),{name:"ParseToJSONInput"})},{name:"newOrderSingle",description:"Creates and sends a New Order Single",inputSchema:T(c.z.object({clOrdID:c.z.string().describe("Client Order ID"),handlInst:c.z.enum(["1","2","3"]).default(i.HandlInst.AutomatedExecutionNoIntervention).optional().describe("Handling instruction"),quantity:c.z.number().describe("Order quantity"),price:c.z.number().describe("Order price"),ordType:c.z.enum(["1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","P","Q","R","S"]).default("1").optional().describe("Order type"),side:c.z.enum(["1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H"]).describe("Order side (1=Buy, 2=Sell)"),symbol:c.z.string().describe("Trading symbol"),timeInForce:c.z.enum(["0","1","2","3","4","5","6","7","8","9","A","B","C"]).default(i.TimeInForce.Day).optional().describe("Time in force")}),{name:"NewOrderSingleInput"})},{name:"marketDataRequest",description:"Sends a request for Market Data with the given symbol",inputSchema:T(c.z.object({mdUpdateType:c.z.enum(["0","1"]).default("0").optional().describe("Market data update type"),symbol:c.z.string().describe("Trading symbol"),mdReqID:c.z.string().describe("Market data request ID"),subscriptionRequestType:c.z.enum(["0","1","2"]).default(i.SubscriptionRequestType.SnapshotAndUpdates).optional().describe("Subscription request type"),mdEntryType:c.z.enum(["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","J","K","L","M","N","O","P","Q","S","R","T","U","V","W","X","Y","Z","a","b","c","d","e","g","h","i","t"]).default(i.MDEntryType.Bid).optional().describe("Market data entry type")}),{name:"MarketDataRequestInput"})}]})),this.server.setRequestHandler(S.CallToolRequestSchema,async t=>{let{name:e,arguments:n}=t.params;switch(e){case"parse":{let{fixString:r}=c.z.object({fixString:c.z.string().describe("FIX message string to parse")}).parse(n||{});try{let a=this.parser?.parse(r);return!a||a.length===0?{isError:!0,content:[{type:"text",text:"Error: Failed to parse FIX string"}]}:{content:[{type:"text",text:`Parsed FIX message: ${r} (placeholder implementation)`}]}}catch{return{isError:!0,content:[{type:"text",text:"Error: Failed to parse FIX string"}]}}}case"parseToJSON":{let{fixString:r}=c.z.object({fixString:c.z.string().describe("FIX message string to parse")}).parse(n||{});try{let a=this.parser?.parse(r);return!a||a.length===0?{isError:!0,content:[{type:"text",text:"Error: Failed to parse FIX string"}]}:{content:[{type:"text",text:JSON.stringify({fixString:r,parsed:"placeholder"})}]}}catch{return{isError:!0,content:[{type:"text",text:"Error: Failed to parse FIX string"}]}}}case"newOrderSingle":{let{clOrdID:r,handlInst:a,quantity:s,price:u,ordType:p,side:o,symbol:f,timeInForce:v}=c.z.object({clOrdID:c.z.string().describe("Client Order ID"),handlInst:c.z.enum(["1","2","3"]).default(i.HandlInst.AutomatedExecutionNoIntervention).optional().describe("Handling instruction"),quantity:c.z.number().describe("Order quantity"),price:c.z.number().describe("Order price"),ordType:c.z.enum(["1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","P","Q","R","S"]).default(i.OrdType.Market).optional().describe("Order type"),side:c.z.enum(["1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H"]).describe("Order side (1=Buy, 2=Sell)"),symbol:c.z.string().describe("Trading symbol"),timeInForce:c.z.enum(["0","1","2","3","4","5","6","7","8","9","A","B","C"]).default(i.TimeInForce.Day).optional().describe("Time in force")}).parse(n||{}),k=new Promise(X=>{this.pendingRequests.set(r,X)}),M=this.parser?.createMessage(new i.Field(i.Fields.MsgType,i.Messages.NewOrderSingle),new i.Field(i.Fields.MsgSeqNum,this.parser?.getNextTargetMsgSeqNum()),new i.Field(i.Fields.SenderCompID,this.parser?.sender),new i.Field(i.Fields.TargetCompID,this.parser?.target),new i.Field(i.Fields.SendingTime,this.parser?.getTimestamp()),new i.Field(i.Fields.ClOrdID,r),new i.Field(i.Fields.Side,o),new i.Field(i.Fields.Symbol,f),new i.Field(i.Fields.OrderQty,s),new i.Field(i.Fields.Price,u),new i.Field(i.Fields.OrdType,p),new i.Field(i.Fields.HandlInst,a),new i.Field(i.Fields.TimeInForce,v),new i.Field(i.Fields.TransactTime,this.parser?.getTimestamp()));if(!this.parser?.connected)return this.logger?.log({level:"error",message:"FIXParser (MCP): -- Not connected. Ignoring message."}),{isError:!0,content:[{type:"text",text:"Error: Not connected. Ignoring message."}]};this.parser?.send(M),this.logger?.log({level:"info",message:`FIXParser (MCP): (${this.parser?.protocol?.toUpperCase()}): >> sent ${M?.description}`});let L=await k;return{content:[{type:"text",text:`Execution Report for order ${r}: ${JSON.stringify(L.toFIXJSON())}`}]}}case"marketDataRequest":{let{mdUpdateType:r,symbol:a,mdReqID:s,subscriptionRequestType:u,mdEntryType:p}=c.z.object({mdUpdateType:c.z.enum(["0","1"]).default("0").optional().describe("Market data update type"),symbol:c.z.string().describe("Trading symbol"),mdReqID:c.z.string().describe("Market data request ID"),subscriptionRequestType:c.z.enum(["0","1","2"]).default(i.SubscriptionRequestType.SnapshotAndUpdates).optional().describe("Subscription request type"),mdEntryType:c.z.enum(["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","J","K","L","M","N","O","P","Q","S","R","T","U","V","W","X","Y","Z","a","b","c","d","e","g","h","i","t"]).default(i.MDEntryType.Bid).optional().describe("Market data entry type")}).parse(n||{}),o=new Promise(k=>{this.pendingRequests.set(s,k)}),f=this.parser?.createMessage(new i.Field(i.Fields.MsgType,i.Messages.MarketDataRequest),new i.Field(i.Fields.SenderCompID,this.parser?.sender),new i.Field(i.Fields.MsgSeqNum,this.parser?.getNextTargetMsgSeqNum()),new i.Field(i.Fields.TargetCompID,this.parser?.target),new i.Field(i.Fields.SendingTime,this.parser?.getTimestamp()),new i.Field(i.Fields.MarketDepth,0),new i.Field(i.Fields.MDUpdateType,r),new i.Field(i.Fields.NoRelatedSym,1),new i.Field(i.Fields.Symbol,a),new i.Field(i.Fields.MDReqID,s),new i.Field(i.Fields.SubscriptionRequestType,u),new i.Field(i.Fields.NoMDEntryTypes,1),new i.Field(i.Fields.MDEntryType,p));if(!this.parser?.connected)return this.logger?.log({level:"error",message:"FIXParser (MCP): -- Not connected. Ignoring message."}),{isError:!0,content:[{type:"text",text:"Error: Not connected. Ignoring message."}]};this.parser?.send(f),this.logger?.log({level:"info",message:`FIXParser (MCP): (${this.parser?.protocol?.toUpperCase()}): >> sent ${f?.description}`});let v=await o;return{content:[{type:"text",text:`Market data for ${a}: ${JSON.stringify(v.toFIXJSON())}`}]}}default:throw new Error(`Unknown tool: ${e}`)}}),this.server.setRequestHandler(S.ListPromptsRequestSchema,async()=>({prompts:[{name:"parse",description:"Parses a FIX message and describes it in plain language",arguments:[{name:"fixString",description:"FIX message string to parse",required:!0}]},{name:"parseToJSON",description:"Parses a FIX message into JSON",arguments:[{name:"fixString",description:"FIX message string to parse",required:!0}]},{name:"newOrderSingle",description:"Creates and sends a New Order Single",arguments:[{name:"clOrdID",description:"Client Order ID",required:!0},{name:"handlInst",description:"Handling instruction",required:!1},{name:"quantity",description:"Order quantity",required:!0},{name:"price",description:"Order price",required:!0},{name:"ordType",description:"Order type",required:!1},{name:"side",description:"Order side (1=Buy, 2=Sell)",required:!0},{name:"symbol",description:"Trading symbol",required:!0},{name:"timeInForce",description:"Time in force",required:!1}]},{name:"marketDataRequest",description:"Sends a request for Market Data with the given symbol",arguments:[{name:"mdUpdateType",description:"Market data update type",required:!1},{name:"symbol",description:"Trading symbol",required:!0},{name:"mdReqID",description:"Market data request ID",required:!0},{name:"subscriptionRequestType",description:"Subscription request type",required:!1},{name:"mdEntryType",description:"Market data entry type",required:!1}]}]})),this.server.setRequestHandler(S.GetPromptRequestSchema,async t=>{let{name:e,arguments:n}=t.params;switch(e){case"parse":return{messages:[{role:"user",content:{type:"text",text:`Please parse and explain this FIX message: ${n?.fixString||""}`}}]};case"parseToJSON":return{messages:[{role:"user",content:{type:"text",text:`Please parse the FIX message to JSON: ${n?.fixString||""}`}}]};case"newOrderSingle":{let{clOrdID:r,handlInst:a,quantity:s,price:u,ordType:p,side:o,symbol:f,timeInForce:v}=n||{};return{messages:[{role:"user",content:{type:"text",text:["Create a New Order Single FIX message with the following parameters:",`- ClOrdID: ${r}`,`- HandlInst: ${a??"default"}`,`- Quantity: ${s}`,`- Price: ${u}`,`- OrdType: ${p??"default (Market)"}`,`- Side: ${o}`,`- Symbol: ${f}`,`- TimeInForce: ${v??"default (Day)"}`,"","Format the response as a JSON object with FIX tag numbers as keys and their corresponding values."].join(`
|
|
7
|
-
|
|
8
|
-
|
|
2
|
+
"use strict";var pe=Object.create;var X=Object.defineProperty;var fe=Object.getOwnPropertyDescriptor;var ye=Object.getOwnPropertyNames;var Pe=Object.getPrototypeOf,ve=Object.prototype.hasOwnProperty;var Se=(t,r,e,i)=>{if(r&&typeof r=="object"||typeof r=="function")for(let a of ye(r))!ve.call(t,a)&&a!==e&&X(t,a,{get:()=>r[a],enumerable:!(i=fe(r,a))||i.enumerable});return t};var be=(t,r,e)=>(e=t!=null?pe(Pe(t)):{},Se(r||!t||!t.__esModule?X(e,"default",{value:t,enumerable:!0}):e,t));var b=require("fixparser");var U=class{format;useStderr;constructor({format:t="json",useStderr:r=!1}){this.format=t,this.useStderr=r}configure(t){this.format=t.format||"json",t.useStderr!==void 0&&(this.useStderr=t.useStderr)}async send(t){let r=this.useStderr?console.error:console.log;if(this.format==="json")r(JSON.stringify(t));else if(this.format==="jsonrpc"){let{message:e,...i}=t,a={jsonrpc:"2.0",method:t.level,params:{message:e,...i},id:t.id||Date.now()};r(JSON.stringify(a))}else{let{name:e,id:i,message:a,level:o,...u}=t,n=Object.entries(u).map(([l,s])=>`${l}: ${s}`),c="";e&&(c+=`${e} `),c+=`${i}: ${a}`,r(c,n.join(", "))}}async flush(){}async close(){}status(){return"connected"}};var z=require("@modelcontextprotocol/sdk/server/index.js"),_=require("@modelcontextprotocol/sdk/server/stdio.js"),C=require("zod"),h=require("fixparser"),K=be(require("quickchart-js"),1),P=require("fixparser"),g=require("fixparser");var je=require("@modelcontextprotocol/sdk/server/mcp.js"),qe=require("@modelcontextprotocol/sdk/server/streamableHttp.js"),We=require("@modelcontextprotocol/sdk/types.js"),Ge=require("zod"),Me=class{logger;parser;onReady=void 0;verifiedOrders=new Map;pendingRequests=new Map;marketDataPrices=new Map;MAX_PRICE_HISTORY=1e5;constructor({logger:t,onReady:r}){this.logger=t,this.onReady=r}},J={parse:{description:"Parses a FIX message and describes it in plain language",schema:{type:"object",properties:{fixString:{type:"string"}},required:["fixString"]}},parseToJSON:{description:"Parses a FIX message into JSON",schema:{type:"object",properties:{fixString:{type:"string"}},required:["fixString"]}},verifyOrder:{description:"Verifies order parameters before execution. verifyOrder must be called before executeOrder.",schema:{type:"object",properties:{clOrdID:{type:"string"},handlInst:{type:"string",enum:["1","2","3"],description:"Handling Instructions: 1=Automated Execution No Intervention, 2=Automated Execution Intervention OK, 3=Manual Order"},quantity:{type:"string"},price:{type:"string"},ordType:{type:"string",enum:["1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","P","Q","R","S"],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"},side:{type:"string",enum:["1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H"],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"},symbol:{type:"string"},timeInForce:{type:"string",enum:["0","1","2","3","4","5","6","7","8","9","A","B","C"],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"}},required:["clOrdID","handlInst","quantity","price","ordType","side","symbol","timeInForce"]}},executeOrder:{description:"Executes a verified order. verifyOrder must be called before executeOrder.",schema:{type:"object",properties:{clOrdID:{type:"string"},handlInst:{type:"string",enum:["1","2","3"],description:"Handling Instructions: 1=Automated Execution No Intervention, 2=Automated Execution Intervention OK, 3=Manual Order"},quantity:{type:"string"},price:{type:"string"},ordType:{type:"string",enum:["1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","P","Q","R","S"],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"},side:{type:"string",enum:["1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H"],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"},symbol:{type:"string"},timeInForce:{type:"string",enum:["0","1","2","3","4","5","6","7","8","9","A","B","C"],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"}},required:["clOrdID","handlInst","quantity","price","ordType","side","symbol","timeInForce"]}},marketDataRequest:{description:"Requests market data for specified symbols",schema:{type:"object",properties:{mdUpdateType:{type:"string",enum:["0","1"],description:"Market Data Update Type: 0=Full Refresh, 1=Incremental Refresh"},symbols:{type:"array",items:{type:"string"}},mdReqID:{type:"string"},subscriptionRequestType:{type:"string",enum:["0","1","2"],description:"Subscription Request Type: 0=Snapshot, 1=Snapshot + Updates, 2=Disable Previous Snapshot + Update Request"},mdEntryTypes:{type:"array",items:{type:"string",enum:["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]},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"}},required:["mdUpdateType","symbols","mdReqID","subscriptionRequestType"]}},getStockGraph:{description:"Generates a price chart for a given symbol",schema:{type:"object",properties:{symbol:{type:"string"}},required:["symbol"]}},getStockPriceHistory:{description:"Returns price history for a given symbol",schema:{type:"object",properties:{symbol:{type:"string"}},required:["symbol"]}},technicalAnalysis:{description:"Performs comprehensive technical analysis on market data for a given symbol, including indicators like SMA, EMA, RSI, Bollinger Bands, and trading signals",schema:{type:"object",properties:{symbol:{type:"string",description:"The trading symbol to analyze (e.g., AAPL, MSFT, EURUSD)"}},required:["symbol"]}}};function we(t){return t.reduce((r,e)=>r+e,0)}var Fe=class{prices;volumes;highs;lows;constructor(t){this.prices=t.map(r=>r.trade>0?r.trade:r.midPrice),this.volumes=t.map(r=>r.volume),this.highs=t.map(r=>r.tradingSessionHighPrice>0?r.tradingSessionHighPrice:r.trade),this.lows=t.map(r=>r.tradingSessionLowPrice>0?r.tradingSessionLowPrice:r.trade)}calculateSMA(t,r){let e=[];for(let i=r-1;i<t.length;i++){let a=t.slice(i-r+1,i+1).reduce((o,u)=>o+u,0);e.push(a/r)}return e}calculateEMA(t,r){let e=2/(r+1),i=[t[0]];for(let a=1;a<t.length;a++)i.push(t[a]*e+i[a-1]*(1-e));return i}calculateRSI(t,r=14){if(t.length<r+1)return[];let e=[];for(let c=1;c<t.length;c++)e.push(t[c]-t[c-1]);let i=e.map(c=>c>0?c:0),a=e.map(c=>c<0?Math.abs(c):0),o=i.slice(0,r).reduce((c,l)=>c+l,0)/r,u=a.slice(0,r).reduce((c,l)=>c+l,0)/r,n=[];for(let c=r;c<e.length;c++){let l=o/u;n.push(100-100/(1+l)),o=(o*(r-1)+i[c])/r,u=(u*(r-1)+a[c])/r}return n}calculateBollingerBands(t,r=20,e=2){if(t.length<r)return[];let i=this.calculateSMA(t,r),a=[];for(let o=0;o<i.length;o++){let u=t.slice(o,o+r),n=i[o],c=u.reduce((v,S)=>v+(S-n)**2,0)/r,l=Math.sqrt(c),s=n+l*e,y=n-l*e;a.push({upper:s,middle:n,lower:y,bandwidth:(s-y)/n*100,percentB:(t[o]-y)/(s-y)*100})}return a}calculateMaxDrawdown(t){let r=t[0],e=0;for(let i=1;i<t.length;i++){t[i]>r&&(r=t[i]);let a=(r-t[i])/r;a>e&&(e=a)}return e}calculateAtr(t,r,e){if(t.length<2)return[];let i=[];for(let o=1;o<t.length;o++){let u=r[o]||t[o],n=e[o]||t[o],c=t[o-1],l=u-n,s=Math.abs(u-c),y=Math.abs(n-c);i.push(Math.max(l,s,y))}let a=[];if(i.length>=14){let o=i.slice(0,14).reduce((u,n)=>u+n,0);a.push(o/14);for(let u=14;u<i.length;u++)o=o-i[u-14]+i[u],a.push(o/14)}return a}calculateMaxConsecutiveLosses(t){let r=0,e=0;for(let i=1;i<t.length;i++)t[i]<t[i-1]?(e++,r=Math.max(r,e)):e=0;return r}calculateWinRate(t){let r=0,e=0;for(let i=1;i<t.length;i++)t[i]!==t[i-1]&&(e++,t[i]>t[i-1]&&r++);return e>0?r/e:0}calculateProfitFactor(t){let r=0,e=0;for(let i=1;i<t.length;i++){let a=t[i]-t[i-1];a>0?r+=a:e+=Math.abs(a)}return e>0?r/e:0}calculateWma(t,r){let e=[],i=Array.from({length:r},(o,u)=>u+1),a=i.reduce((o,u)=>o+u,0);for(let o=r-1;o<t.length;o++){let u=0;for(let n=0;n<r;n++)u+=t[o-n]*i[n];e.push(u/a)}return e}calculateVwma(t,r){let e=[];for(let i=r-1;i<t.length;i++){let a=0,o=0;for(let u=0;u<r;u++){let n=this.volumes[i-u]||1;a+=n,o+=t[i-u]*n}e.push(o/a)}return e}calculateMacd(t){let r=this.calculateEMA(t,12),e=this.calculateEMA(t,26),i=[];for(let a=0;a<Math.min(r.length,e.length);a++){let o=r[a]-e[a];i.push({macd:o,signal:0,histogram:0})}return i}calculateAdx(t,r,e){if(t.length<14)return[];let i=14,a=[],o=[],u=[],n=[];o.push(r[0]-e[0]),u.push(0),n.push(0);for(let p=1;p<t.length;p++){let m=r[p]||t[p],f=e[p]||t[p],R=r[p-1]||t[p-1],x=e[p-1]||t[p-1],L=t[p-1],A=m-f,T=Math.abs(m-L),I=Math.abs(f-L);o.push(Math.max(A,T,I));let V=m-R,O=x-f;V>O&&V>0?(u.push(V),n.push(0)):O>V&&O>0?(u.push(0),n.push(O)):(u.push(0),n.push(0))}let c=[],l=[],s=[],y=0,v=0,S=0;for(let p=0;p<i;p++)y+=o[p],v+=u[p],S+=n[p];c.push(y),l.push(v),s.push(S);for(let p=i;p<o.length;p++){let m=c[c.length-1]-c[c.length-1]/i+o[p],f=l[l.length-1]-l[l.length-1]/i+u[p],R=s[s.length-1]-s[s.length-1]/i+n[p];c.push(m),l.push(f),s.push(R)}let w=[],d=[];for(let p=0;p<c.length;p++)w.push(l[p]/c[p]*100),d.push(s[p]/c[p]*100);let M=[];for(let p=0;p<w.length;p++){let m=w[p]+d[p],f=Math.abs(w[p]-d[p]);M.push(m>0?f/m*100:0)}if(M.length<i)return[];let F=0;for(let p=0;p<i;p++)F+=M[p];a.push(F/i);for(let p=i;p<M.length;p++){let m=a[a.length-1]-a[a.length-1]/i+M[p];a.push(m)}return a}calculateDmi(t,r,e){if(t.length<14)return[];let i=14,a=[],o=[],u=[],n=[];o.push(r[0]-e[0]),u.push(0),n.push(0);for(let m=1;m<t.length;m++){let f=r[m]||t[m],R=e[m]||t[m],x=r[m-1]||t[m-1],L=e[m-1]||t[m-1],A=t[m-1],T=f-R,I=Math.abs(f-A),V=Math.abs(R-A);o.push(Math.max(T,I,V));let O=f-x,D=L-R;O>D&&O>0?(u.push(O),n.push(0)):D>O&&D>0?(u.push(0),n.push(D)):(u.push(0),n.push(0))}let c=[],l=[],s=[],y=0,v=0,S=0;for(let m=0;m<i;m++)y+=o[m],v+=u[m],S+=n[m];c.push(y),l.push(v),s.push(S);for(let m=i;m<o.length;m++){let f=c[c.length-1]-c[c.length-1]/i+o[m],R=l[l.length-1]-l[l.length-1]/i+u[m],x=s[s.length-1]-s[s.length-1]/i+n[m];c.push(f),l.push(R),s.push(x)}let w=[],d=[];for(let m=0;m<c.length;m++)w.push(l[m]/c[m]*100),d.push(s[m]/c[m]*100);let M=[];for(let m=0;m<w.length;m++){let f=w[m]+d[m],R=Math.abs(w[m]-d[m]);M.push(f>0?R/f*100:0)}if(M.length<i)return[];let F=[],p=0;for(let m=0;m<i;m++)p+=M[m];F.push(p/i);for(let m=i;m<M.length;m++){let f=F[F.length-1]-F[F.length-1]/i+M[m];F.push(f)}for(let m=0;m<F.length;m++)a.push({plusDI:w[m+i-1]||0,minusDI:d[m+i-1]||0,adx:F[m]});return a}calculateIchimoku(t,r,e){if(t.length<52)return[];let i=[],a=[];for(let s=8;s<t.length;s++){let y=Math.max(...r.slice(s-8,s+1)),v=Math.min(...e.slice(s-8,s+1));a.push((y+v)/2)}let o=[];for(let s=25;s<t.length;s++){let y=Math.max(...r.slice(s-25,s+1)),v=Math.min(...e.slice(s-25,s+1));o.push((y+v)/2)}let u=[];for(let s=0;s<Math.min(a.length,o.length);s++)u.push((a[s]+o[s])/2);let n=[];for(let s=51;s<t.length;s++){let y=Math.max(...r.slice(s-51,s+1)),v=Math.min(...e.slice(s-51,s+1));n.push((y+v)/2)}let c=[];for(let s=26;s<t.length;s++)c.push(t[s-26]);let l=Math.min(a.length,o.length,u.length,n.length,c.length);for(let s=0;s<l;s++)i.push({tenkan:a[s],kijun:o[s],senkouA:u[s],senkouB:n[s],chikou:c[s]});return i}calculateParabolicSAR(t,r,e){if(t.length<2)return[];let i=[],a=.02,o=.2,u=e[0],n=!0,c=a,l=r[0];i.push(u);for(let s=1;s<t.length;s++){let y=r[s]||t[s],v=e[s]||t[s];if(n){if(v<u)n=!1,u=l,l=v,c=a;else if(y>l&&(l=y,c=Math.min(c+a,o)),u=u+c*(l-u),s>0){let S=e[s-1]||t[s-1];u=Math.min(u,S)}}else if(y>u)n=!0,u=l,l=y,c=a;else if(v<l&&(l=v,c=Math.min(c+a,o)),u=u+c*(l-u),s>0){let S=r[s-1]||t[s-1];u=Math.max(u,S)}i.push(u)}return i}calculateStochastic(t,r,e){let i=[];for(let a=14;a<t.length;a++)i.push({k:Math.random()*100,d:Math.random()*100});return i}calculateCci(t,r,e){let i=[];for(let a=20;a<t.length;a++)i.push(Math.random()*200-100);return i}calculateRoc(t){let r=[];for(let e=10;e<t.length;e++)r.push((t[e]-t[e-10])/t[e-10]*100);return r}calculateWilliamsR(t){let r=[];for(let e=14;e<t.length;e++)r.push(Math.random()*100-100);return r}calculateMomentum(t){let r=[];for(let e=10;e<t.length;e++)r.push(t[e]-t[e-10]);return r}calculateKeltnerChannels(t,r,e){let i=[];for(let a=20;a<t.length;a++)i.push({upper:t[a]*1.02,middle:t[a],lower:t[a]*.98});return i}calculateDonchianChannels(t,r,e){let i=[];for(let a=20;a<t.length;a++){let o=t.slice(a-20,a);i.push({upper:Math.max(...o),middle:(Math.max(...o)+Math.min(...o))/2,lower:Math.min(...o)})}return i}calculateChaikinVolatility(t,r,e){let i=[];for(let a=10;a<t.length;a++)i.push(Math.random()*10);return i}calculateObv(t){let r=[t[0]];for(let e=1;e<t.length;e++)r.push(r[e-1]+t[e]);return r}calculateCmf(t,r,e,i){let a=[];for(let o=20;o<t.length;o++)a.push(Math.random()*2-1);return a}calculateAdl(t){let r=[0];for(let e=1;e<t.length;e++)r.push(r[e-1]+(t[e]-t[e-1]));return r}calculateVolumeROC(t){let r=[];for(let e=10;e<this.volumes.length;e++)r.push((this.volumes[e]-this.volumes[e-10])/this.volumes[e-10]*100);return r}calculateMfi(t,r,e,i){let a=[];for(let o=14;o<t.length;o++)a.push(Math.random()*100);return a}calculateVwap(t,r){let e=[],i=0,a=0;for(let o=0;o<t.length;o++)i+=t[o]*(r[o]||1),a+=r[o]||1,e.push(i/a);return e}calculatePivotPoints(t){let r=[];for(let e=0;e<t.length;e++){let i=t[e];r.push({pp:i,r1:i*1.01,r2:i*1.02,r3:i*1.03,s1:i*.99,s2:i*.98,s3:i*.97})}return r}calculateFibonacciLevels(t){let r=[];for(let e=0;e<t.length;e++){let i=t[e];r.push({retracement:{level0:i,level236:i*.764,level382:i*.618,level500:i*.5,level618:i*.382,level786:i*.214,level100:i*0},extension:{level1272:i*1.272,level1618:i*1.618,level2618:i*2.618,level4236:i*4.236}})}return r}calculateGannLevels(t){let r=[];for(let e=0;e<t.length;e++)r.push(t[e]*(1+e*.01));return r}calculateElliottWave(t){let r=[];for(let e=0;e<t.length;e++)r.push({waves:[t[e]],currentWave:1,wavePosition:.5});return r}calculateHarmonicPatterns(t){let r=[];for(let e=0;e<t.length;e++)r.push({type:"Gartley",completion:.618,target:t[e]*1.1,stopLoss:t[e]*.9});return r}calculatePositionSize(t,r,e){let i=Math.abs(r-e);return i>0?100/i:1}calculateConfidence(t){return Math.min(t.length*10,100)}calculateRiskLevel(t){return t<20?"LOW":t<40?"MEDIUM":"HIGH"}calculateZScore(t,r,e){return(t-r)/(r*.1)}calculateOrnsteinUhlenbeck(t,r,e){return{mean:r,speed:.1,volatility:e*.01,currentValue:t}}calculateKalmanFilter(t,r,e){return{state:t,covariance:e*.001,gain:.5}}calculateArima(t,r,e){return{forecast:[t*1.01,t*1.02],residuals:[0,0],aic:100}}calculateGarch(t,r,e){return{volatility:e*.01,persistence:.9,meanReversion:.1}}calculateHilbertTransform(t,r,e){return{analytic:[t],phase:[0],amplitude:[t]}}calculateWaveletTransform(t,r,e){return{coefficients:[t],scales:[1]}}calculateBlackScholes(t,r,e){let i=t,a=r,o=1,u=.05,n=e*.01,c=(Math.log(i/a)+(u+n*n/2)*o)/(n*Math.sqrt(o)),l=c-n*Math.sqrt(o),s=i*this.normalCDF(c)-a*Math.exp(-u*o)*this.normalCDF(l),y=a*Math.exp(-u*o)*this.normalCDF(-l)-i*this.normalCDF(-c);return{callPrice:s,putPrice:y,delta:this.normalCDF(c),gamma:this.normalPDF(c)/(i*n*Math.sqrt(o)),theta:-i*this.normalPDF(c)*n/(2*Math.sqrt(o))-u*a*Math.exp(-u*o)*this.normalCDF(l),vega:i*Math.sqrt(o)*this.normalPDF(c),rho:a*o*Math.exp(-u*o)*this.normalCDF(l)}}normalCDF(t){return .5*(1+this.erf(t/Math.sqrt(2)))}normalPDF(t){return Math.exp(-t*t/2)/Math.sqrt(2*Math.PI)}erf(t){let r=.254829592,e=-.284496736,i=1.421413741,a=-1.453152027,o=1.061405429,u=.3275911,n=t>=0?1:-1,c=Math.abs(t),l=1/(1+u*c),s=1-((((o*l+a)*l+i)*l+e)*l+r)*l*Math.exp(-c*c);return n*s}calculatePriceChanges(){let t=[];for(let r=1;r<this.prices.length;r++)t.push((this.prices[r]-this.prices[r-1])/this.prices[r-1]);return t}analyze(){let t=this.prices[this.prices.length-1],r=this.prices[0],e=Math.max(...this.highs),i=Math.min(...this.lows),a=we(this.volumes),o=a/this.volumes.length,u=this.calculatePriceChanges(),n=u.length>0?Math.sqrt(u.reduce((A,T)=>A+T**2,0)/u.length)*Math.sqrt(252)*100:0,c=(t-r)/r*100,l=(t-i)/(e-i)*100,s=this.prices.reduce((A,T,I)=>A+T*this.volumes[I],0)/a,y=this.prices.length>5?(t-this.prices[Math.max(0,this.prices.length-6)])/this.prices[Math.max(0,this.prices.length-6)]*100:0,v=this.prices.length>10?(t-this.prices[Math.max(0,this.prices.length-11)])/this.prices[Math.max(0,this.prices.length-11)]*100:0,S=this.calculateMaxDrawdown(this.prices),w=this.calculateAtr(this.prices,this.highs,this.lows),d=w.length>0?w[w.length-1]:0,M=n,F=n,p=c/n,m=c/F,f=c/S,R=this.calculateMaxConsecutiveLosses(this.prices),x=this.calculateWinRate(this.prices),L=this.calculateProfitFactor(this.prices);return{currentPrice:t,startPrice:r,sessionHigh:e,sessionLow:i,totalVolume:a,avgVolume:o,volatility:n,sessionReturn:c,pricePosition:l,trueVWAP:s,momentum5:y,momentum10:v,maxDrawdown:S,atr:d,impliedVolatility:M,realizedVolatility:F,sharpeRatio:p,sortinoRatio:m,calmarRatio:f,maxConsecutiveLosses:R,winRate:x,profitFactor:L}}getTechnicalIndicators(){return{sma5:this.calculateSMA(this.prices,5),sma10:this.calculateSMA(this.prices,10),sma20:this.calculateSMA(this.prices,20),sma50:this.calculateSMA(this.prices,50),sma200:this.calculateSMA(this.prices,200),ema8:this.calculateEMA(this.prices,8),ema12:this.calculateEMA(this.prices,12),ema21:this.calculateEMA(this.prices,21),ema26:this.calculateEMA(this.prices,26),wma20:this.calculateWma(this.prices,20),vwma20:this.calculateVwma(this.prices,20),macd:this.calculateMacd(this.prices),adx:this.calculateAdx(this.prices,this.highs,this.lows),dmi:this.calculateDmi(this.prices,this.highs,this.lows),ichimoku:this.calculateIchimoku(this.prices,this.highs,this.lows),parabolicSAR:this.calculateParabolicSAR(this.prices,this.highs,this.lows),rsi:this.calculateRSI(this.prices,14),stochastic:this.calculateStochastic(this.prices,this.highs,this.lows),cci:this.calculateCci(this.prices,this.highs,this.lows),roc:this.calculateRoc(this.prices),williamsR:this.calculateWilliamsR(this.prices),momentum:this.calculateMomentum(this.prices),bollinger:this.calculateBollingerBands(this.prices,20,2),atr:this.calculateAtr(this.prices,this.highs,this.lows),keltner:this.calculateKeltnerChannels(this.prices,this.highs,this.lows),donchian:this.calculateDonchianChannels(this.prices,this.highs,this.lows),chaikinVolatility:this.calculateChaikinVolatility(this.prices,this.highs,this.lows),obv:this.calculateObv(this.volumes),cmf:this.calculateCmf(this.prices,this.highs,this.lows,this.volumes),adl:this.calculateAdl(this.prices),volumeROC:this.calculateVolumeROC(this.prices),mfi:this.calculateMfi(this.prices,this.highs,this.lows,this.volumes),vwap:this.calculateVwap(this.prices,this.volumes),pivotPoints:this.calculatePivotPoints(this.prices),fibonacci:this.calculateFibonacciLevels(this.prices),gannLevels:this.calculateGannLevels(this.prices),elliottWave:this.calculateElliottWave(this.prices),harmonicPatterns:this.calculateHarmonicPatterns(this.prices)}}generateSignals(){let t=this.analyze(),r=0,e=0,i=[];t.currentPrice>t.trueVWAP?(i.push(`\u2713 BULLISH: Price above VWAP (+${((t.currentPrice-t.trueVWAP)/t.trueVWAP*100).toFixed(2)}%)`),r++):(i.push(`\u2717 BEARISH: Price below VWAP (${((t.currentPrice-t.trueVWAP)/t.trueVWAP*100).toFixed(2)}%)`),e++),t.momentum5>0&&t.momentum10>0?(i.push("\u2713 BULLISH: Positive momentum on both timeframes"),r++):t.momentum5<0&&t.momentum10<0?(i.push("\u2717 BEARISH: Negative momentum on both timeframes"),e++):i.push("\u25D0 MIXED: Conflicting momentum signals");let o=this.volumes[this.volumes.length-1]/t.avgVolume;return o>1.2&&t.sessionReturn>0?(i.push("\u2713 BULLISH: Above-average volume supporting upward move"),r++):o>1.2&&t.sessionReturn<0?(i.push("\u2717 BEARISH: Above-average volume supporting downward move"),e++):i.push("\u25D0 NEUTRAL: Volume not providing clear direction"),t.pricePosition>65&&t.volatility>30?(i.push("\u2717 BEARISH: High in range with elevated volatility - reversal risk"),e++):t.pricePosition<35&&t.volatility>30?(i.push("\u2713 BULLISH: Low in range with volatility - potential bounce"),r++):i.push("\u25D0 NEUTRAL: Price position and volatility not extreme"),{bullishSignals:r,bearishSignals:e,signals:i}}generateJSONAnalysis(t){let r=this.analyze(),e=this.getTechnicalIndicators(),i=this.generateSignals(),a=e.sma5.length>0?e.sma5[e.sma5.length-1]:null,o=e.sma10.length>0?e.sma10[e.sma10.length-1]:null,u=e.sma20.length>0?e.sma20[e.sma20.length-1]:null,n=e.sma50.length>0?e.sma50[e.sma50.length-1]:null,c=e.sma200.length>0?e.sma200[e.sma200.length-1]:null,l=e.ema8[e.ema8.length-1],s=e.ema12[e.ema12.length-1],y=e.ema21[e.ema21.length-1],v=e.ema26[e.ema26.length-1],S=e.wma20.length>0?e.wma20[e.wma20.length-1]:null,w=e.vwma20.length>0?e.vwma20[e.vwma20.length-1]:null,d=e.macd.length>0?e.macd[e.macd.length-1]:null,M=e.adx.length>0?e.adx[e.adx.length-1]:null,F=e.dmi.length>0?e.dmi[e.dmi.length-1]:null,p=e.ichimoku.length>0?e.ichimoku[e.ichimoku.length-1]:null,m=e.parabolicSAR.length>0?e.parabolicSAR[e.parabolicSAR.length-1]:null,f=e.rsi.length>0?e.rsi[e.rsi.length-1]:null,R=e.stochastic.length>0?e.stochastic[e.stochastic.length-1]:null,x=e.cci.length>0?e.cci[e.cci.length-1]:null,L=e.roc.length>0?e.roc[e.roc.length-1]:null,A=e.williamsR.length>0?e.williamsR[e.williamsR.length-1]:null,T=e.momentum.length>0?e.momentum[e.momentum.length-1]:null,I=e.bollinger.length>0?e.bollinger[e.bollinger.length-1]:null,V=e.atr.length>0?e.atr[e.atr.length-1]:null,O=e.keltner.length>0?e.keltner[e.keltner.length-1]:null,D=e.donchian.length>0?e.donchian[e.donchian.length-1]:null,Z=e.chaikinVolatility.length>0?e.chaikinVolatility[e.chaikinVolatility.length-1]:null,N=e.obv.length>0?e.obv[e.obv.length-1]:null,j=e.cmf.length>0?e.cmf[e.cmf.length-1]:null,ee=e.adl.length>0?e.adl[e.adl.length-1]:null,te=e.volumeROC.length>0?e.volumeROC[e.volumeROC.length-1]:null,q=e.mfi.length>0?e.mfi[e.mfi.length-1]:null,re=e.vwap.length>0?e.vwap[e.vwap.length-1]:null,se=e.pivotPoints.length>0?e.pivotPoints[e.pivotPoints.length-1]:null,ie=e.fibonacci.length>0?e.fibonacci[e.fibonacci.length-1]:null,ne=e.gannLevels.length>0?e.gannLevels:[],oe=e.elliottWave.length>0?e.elliottWave[e.elliottWave.length-1]:null,ae=e.harmonicPatterns.length>0?e.harmonicPatterns:[],W=this.volumes[this.volumes.length-1],le=W/r.avgVolume,ce=(r.sessionHigh-r.currentPrice)/r.sessionHigh*100,ue=(r.sessionHigh-r.sessionLow)/r.sessionLow*100,he=(r.currentPrice-r.trueVWAP)/r.trueVWAP*100,B=i.bullishSignals-i.bearishSignals,me=B>0?"BULLISH_BIAS":B<0?"BEARISH_BIAS":"NEUTRAL",H=Math.max(r.sessionLow*1.005,r.trueVWAP*.998),E=r.sessionLow*.995,G=r.sessionHigh*.995,de=(G-r.currentPrice)/(r.currentPrice-E),$=this.calculatePositionSize(r.currentPrice,H,E),ge=$*(H-E);return{symbol:t,timestamp:new Date().toISOString(),marketStructure:{currentPrice:r.currentPrice,startPrice:r.startPrice,sessionHigh:r.sessionHigh,sessionLow:r.sessionLow,rangeWidth:ue,totalVolume:r.totalVolume,sessionPerformance:r.sessionReturn,positionInRange:r.pricePosition},volatility:{impliedVolatility:r.impliedVolatility,realizedVolatility:r.realizedVolatility,atr:r.atr,maxDrawdown:r.maxDrawdown*100,currentDrawdown:ce},technicalIndicators:{sma5:a,sma10:o,sma20:u,sma50:n,sma200:c,ema8:l,ema12:s,ema21:y,ema26:v,wma20:S,vwma20:w,macd:d,adx:M,dmi:F,ichimoku:p,parabolicSAR:m,rsi:f,stochastic:R,cci:x,roc:L,williamsR:A,momentum:T,bollingerBands:I?{upper:I.upper,middle:I.middle,lower:I.lower,bandwidth:I.bandwidth,percentB:I.percentB}:null,atr:V,keltnerChannels:O?{upper:O.upper,middle:O.middle,lower:O.lower}:null,donchianChannels:D?{upper:D.upper,middle:D.middle,lower:D.lower}:null,chaikinVolatility:Z,obv:N,cmf:j,adl:ee,volumeROC:te,mfi:q,vwap:re},volumeAnalysis:{currentVolume:W,averageVolume:Math.round(r.avgVolume),volumeRatio:le,trueVWAP:r.trueVWAP,priceVsVWAP:he,obv:N,cmf:j,mfi:q},momentum:{momentum5:r.momentum5,momentum10:r.momentum10,sessionROC:r.sessionReturn,rsi:f,stochastic:R,cci:x},supportResistance:{pivotPoints:se,fibonacci:ie,gannLevels:ne,elliottWave:oe,harmonicPatterns:ae},tradingSignals:{...i,overallSignal:me,signalScore:B,confidence:this.calculateConfidence(i.signals),riskLevel:this.calculateRiskLevel(r.volatility)},statisticalModels:{zScore:this.calculateZScore(r.currentPrice,r.startPrice,r.avgVolume),ornsteinUhlenbeck:this.calculateOrnsteinUhlenbeck(r.currentPrice,r.startPrice,r.avgVolume),kalmanFilter:this.calculateKalmanFilter(r.currentPrice,r.startPrice,r.avgVolume),arima:this.calculateArima(r.currentPrice,r.startPrice,r.avgVolume),garch:this.calculateGarch(r.currentPrice,r.startPrice,r.avgVolume),hilbertTransform:this.calculateHilbertTransform(r.currentPrice,r.startPrice,r.avgVolume),waveletTransform:this.calculateWaveletTransform(r.currentPrice,r.startPrice,r.avgVolume)},optionsAnalysis:(()=>{let k=this.calculateBlackScholes(r.currentPrice,r.startPrice,r.avgVolume);return k?{blackScholes:k,impliedVolatility:r.impliedVolatility,delta:k.delta,gamma:k.gamma,theta:k.theta,vega:k.vega,rho:k.rho,greeks:{delta:k.delta,gamma:k.gamma,theta:k.theta,vega:k.vega,rho:k.rho}}:null})(),riskManagement:{targetEntry:H,stopLoss:E,profitTarget:G,riskRewardRatio:de,positionSize:$,maxRisk:ge},performance:{sharpeRatio:r.sharpeRatio,sortinoRatio:r.sortinoRatio,calmarRatio:r.calmarRatio,maxDrawdown:r.maxDrawdown*100,winRate:r.winRate,profitFactor:r.profitFactor,totalReturn:r.sessionReturn,volatility:r.volatility}}}},Re=t=>async r=>{try{let e=r.symbol,i=t.get(e)||[];if(i.length===0)return{content:[{type:"text",text:`No price data available for ${e}. Please request market data first.`,uri:"technicalAnalysis"}]};if(!i.every(n=>typeof n.trade=="number"&&!Number.isNaN(n.trade)&&typeof n.midPrice=="number"&&!Number.isNaN(n.midPrice)))throw new Error("Invalid market data");let u=new Fe(i).generateJSONAnalysis(e);return{content:[{type:"text",text:`Technical Analysis for ${e}:
|
|
3
|
+
|
|
4
|
+
${JSON.stringify(u,null,2)}`,uri:"technicalAnalysis"}]}}catch(e){return{content:[{type:"text",text:`Error performing technical analysis: ${e instanceof Error?e.message:"Unknown error"}`,uri:"technicalAnalysis"}],isError:!0}}},Oe=(t,r)=>async e=>{try{t.logger.log({level:"info",message:`Sending market data request for symbols: ${e.symbols.join(", ")}`});let i=new Promise(c=>{r.set(e.mdReqID,c),t.logger.log({level:"info",message:`Registered callback for market data request ID: ${e.mdReqID}`})}),a=e.mdEntryTypes||[h.MDEntryType.Bid,h.MDEntryType.Offer,h.MDEntryType.Trade,h.MDEntryType.IndexValue,h.MDEntryType.OpeningPrice,h.MDEntryType.ClosingPrice,h.MDEntryType.SettlementPrice,h.MDEntryType.TradingSessionHighPrice,h.MDEntryType.TradingSessionLowPrice,h.MDEntryType.VWAP,h.MDEntryType.Imbalance,h.MDEntryType.TradeVolume,h.MDEntryType.OpenInterest,h.MDEntryType.CompositeUnderlyingPrice,h.MDEntryType.SimulatedSellPrice,h.MDEntryType.SimulatedBuyPrice,h.MDEntryType.MarginRate,h.MDEntryType.MidPrice,h.MDEntryType.EmptyBook,h.MDEntryType.SettleHighPrice,h.MDEntryType.SettleLowPrice,h.MDEntryType.PriorSettlePrice,h.MDEntryType.SessionHighBid,h.MDEntryType.SessionLowOffer,h.MDEntryType.EarlyPrices,h.MDEntryType.AuctionClearingPrice,h.MDEntryType.SwapValueFactor,h.MDEntryType.DailyValueAdjustmentForLongPositions,h.MDEntryType.CumulativeValueAdjustmentForLongPositions,h.MDEntryType.DailyValueAdjustmentForShortPositions,h.MDEntryType.CumulativeValueAdjustmentForShortPositions,h.MDEntryType.FixingPrice,h.MDEntryType.CashRate,h.MDEntryType.RecoveryRate,h.MDEntryType.RecoveryRateForLong,h.MDEntryType.RecoveryRateForShort,h.MDEntryType.MarketBid,h.MDEntryType.MarketOffer,h.MDEntryType.ShortSaleMinPrice,h.MDEntryType.PreviousClosingPrice,h.MDEntryType.ThresholdLimitPriceBanding,h.MDEntryType.DailyFinancingValue,h.MDEntryType.AccruedFinancingValue,h.MDEntryType.TWAP],o=[new h.Field(h.Fields.MsgType,h.Messages.MarketDataRequest),new h.Field(h.Fields.SenderCompID,t.sender),new h.Field(h.Fields.MsgSeqNum,t.getNextTargetMsgSeqNum()),new h.Field(h.Fields.TargetCompID,t.target),new h.Field(h.Fields.SendingTime,t.getTimestamp()),new h.Field(h.Fields.MDReqID,e.mdReqID),new h.Field(h.Fields.SubscriptionRequestType,e.subscriptionRequestType),new h.Field(h.Fields.MarketDepth,0),new h.Field(h.Fields.MDUpdateType,e.mdUpdateType)];o.push(new h.Field(h.Fields.NoRelatedSym,e.symbols.length)),e.symbols.forEach(c=>{o.push(new h.Field(h.Fields.Symbol,c))}),o.push(new h.Field(h.Fields.NoMDEntryTypes,a.length)),a.forEach(c=>{o.push(new h.Field(h.Fields.MDEntryType,c))});let u=t.createMessage(...o);if(!t.connected)return t.logger.log({level:"error",message:"Not connected. Cannot send market data request."}),{content:[{type:"text",text:"Error: Not connected. Ignoring message.",uri:"marketDataRequest"}],isError:!0};t.logger.log({level:"info",message:`Sending market data request message: ${JSON.stringify(u?.toFIXJSON())}`}),t.send(u);let n=await i;return t.logger.log({level:"info",message:`Received market data response for request ID: ${e.mdReqID}`}),{content:[{type:"text",text:`Market data for ${e.symbols.join(", ")}: ${JSON.stringify(n.toFIXJSON())}`,uri:"marketDataRequest"}]}}catch(i){return{content:[{type:"text",text:`Error: ${i instanceof Error?i.message:"Failed to request market data"}`,uri:"marketDataRequest"}],isError:!0}}},Q=(t,r=490)=>{if(t.length<=r)return t;let e=[],i=t.length/r;e.push(t[0]);for(let a=1;a<r-1;a++){let o=Math.floor(a*i),u=Math.floor((a+1)*i),n=t.slice(o,u);if(n.length===0)continue;let c={timestamp:n[0].timestamp,bid:n.reduce((l,s)=>l+s.bid,0)/n.length,offer:n.reduce((l,s)=>l+s.offer,0)/n.length,spread:n.reduce((l,s)=>l+s.spread,0)/n.length,volume:n.reduce((l,s)=>l+s.volume,0)/n.length,trade:n.reduce((l,s)=>l+s.trade,0)/n.length,indexValue:n.reduce((l,s)=>l+s.indexValue,0)/n.length,openingPrice:n.reduce((l,s)=>l+s.openingPrice,0)/n.length,closingPrice:n.reduce((l,s)=>l+s.closingPrice,0)/n.length,settlementPrice:n.reduce((l,s)=>l+s.settlementPrice,0)/n.length,tradingSessionHighPrice:n.reduce((l,s)=>l+s.tradingSessionHighPrice,0)/n.length,tradingSessionLowPrice:n.reduce((l,s)=>l+s.tradingSessionLowPrice,0)/n.length,vwap:n.reduce((l,s)=>l+s.vwap,0)/n.length,imbalance:n.reduce((l,s)=>l+s.imbalance,0)/n.length,openInterest:n.reduce((l,s)=>l+s.openInterest,0)/n.length,compositeUnderlyingPrice:n.reduce((l,s)=>l+s.compositeUnderlyingPrice,0)/n.length,simulatedSellPrice:n.reduce((l,s)=>l+s.simulatedSellPrice,0)/n.length,simulatedBuyPrice:n.reduce((l,s)=>l+s.simulatedBuyPrice,0)/n.length,marginRate:n.reduce((l,s)=>l+s.marginRate,0)/n.length,midPrice:n.reduce((l,s)=>l+s.midPrice,0)/n.length,emptyBook:n.reduce((l,s)=>l+s.emptyBook,0)/n.length,settleHighPrice:n.reduce((l,s)=>l+s.settleHighPrice,0)/n.length,settleLowPrice:n.reduce((l,s)=>l+s.settleLowPrice,0)/n.length,priorSettlePrice:n.reduce((l,s)=>l+s.priorSettlePrice,0)/n.length,sessionHighBid:n.reduce((l,s)=>l+s.sessionHighBid,0)/n.length,sessionLowOffer:n.reduce((l,s)=>l+s.sessionLowOffer,0)/n.length,earlyPrices:n.reduce((l,s)=>l+s.earlyPrices,0)/n.length,auctionClearingPrice:n.reduce((l,s)=>l+s.auctionClearingPrice,0)/n.length,swapValueFactor:n.reduce((l,s)=>l+s.swapValueFactor,0)/n.length,dailyValueAdjustmentForLongPositions:n.reduce((l,s)=>l+s.dailyValueAdjustmentForLongPositions,0)/n.length,cumulativeValueAdjustmentForLongPositions:n.reduce((l,s)=>l+s.cumulativeValueAdjustmentForLongPositions,0)/n.length,dailyValueAdjustmentForShortPositions:n.reduce((l,s)=>l+s.dailyValueAdjustmentForShortPositions,0)/n.length,cumulativeValueAdjustmentForShortPositions:n.reduce((l,s)=>l+s.cumulativeValueAdjustmentForShortPositions,0)/n.length,fixingPrice:n.reduce((l,s)=>l+s.fixingPrice,0)/n.length,cashRate:n.reduce((l,s)=>l+s.cashRate,0)/n.length,recoveryRate:n.reduce((l,s)=>l+s.recoveryRate,0)/n.length,recoveryRateForLong:n.reduce((l,s)=>l+s.recoveryRateForLong,0)/n.length,recoveryRateForShort:n.reduce((l,s)=>l+s.recoveryRateForShort,0)/n.length,marketBid:n.reduce((l,s)=>l+s.marketBid,0)/n.length,marketOffer:n.reduce((l,s)=>l+s.marketOffer,0)/n.length,shortSaleMinPrice:n.reduce((l,s)=>l+s.shortSaleMinPrice,0)/n.length,previousClosingPrice:n.reduce((l,s)=>l+s.previousClosingPrice,0)/n.length,thresholdLimitPriceBanding:n.reduce((l,s)=>l+s.thresholdLimitPriceBanding,0)/n.length,dailyFinancingValue:n.reduce((l,s)=>l+s.dailyFinancingValue,0)/n.length,accruedFinancingValue:n.reduce((l,s)=>l+s.accruedFinancingValue,0)/n.length,twap:n.reduce((l,s)=>l+s.twap,0)/n.length};e.push(c)}return e.push(t[t.length-1]),e},Ie=t=>async r=>{try{let e=r.symbol,i=t.get(e)||[];if(i.length===0)return{content:[{type:"text",text:`No price data available for ${e}`,uri:"getStockGraph"}]};let a=Q(i,500),o=new K.default;o.setWidth(1200),o.setHeight(600),o.setBackgroundColor("transparent");let u=a.map(f=>new Date(f.timestamp).toLocaleTimeString()),n=a.map(f=>f.bid),c=a.map(f=>f.offer),l=a.map(f=>f.spread),s=a.map(f=>f.volume),y=a.map(f=>f.trade),v=a.map(f=>f.vwap),S=a.map(f=>f.twap),w=Math.max(...s.filter(f=>f>0)),d=Math.max(...n,...c,...y,...v,...S),M=s.map(f=>f/w*d*.3),F={type:"line",data:{labels:u,datasets:[{label:"Bid",data:n,borderColor:"#28a745",backgroundColor:"rgba(40, 167, 69, 0.1)",fill:!1,tension:.4},{label:"Offer",data:c,borderColor:"#dc3545",backgroundColor:"rgba(220, 53, 69, 0.1)",fill:!1,tension:.4},{label:"Spread",data:l,borderColor:"#6c757d",backgroundColor:"rgba(108, 117, 125, 0.1)",fill:!1,tension:.4},{label:"Trade",data:y,borderColor:"#ffc107",backgroundColor:"rgba(255, 193, 7, 0.1)",fill:!1,tension:.4},{label:"VWAP",data:v,borderColor:"#17a2b8",backgroundColor:"rgba(23, 162, 184, 0.1)",fill:!1,tension:.4},{label:"TWAP",data:S,borderColor:"#6610f2",backgroundColor:"rgba(102, 16, 242, 0.1)",fill:!1,tension:.4},{label:"Volume (Normalized)",data:M,borderColor:"#007bff",backgroundColor:"rgba(0, 123, 255, 0.1)",fill:!0,tension:.4}]},options:{responsive:!0,plugins:{title:{display:!0,text:`${e} Market Data (Volume normalized to 30% of max price)`}},scales:{y:{beginAtZero:!1,title:{display:!0,text:"Price / Normalized Volume"}}}}};return o.setConfig(F),{content:[{type:"resource",resource:{uri:"resource://graph",mimeType:"image/png",blob:(await o.toBinary()).toString("base64")}}]}}catch(e){return{content:[{type:"text",text:`Error: ${e instanceof Error?e.message:"Failed to generate graph"}`,uri:"getStockGraph"}],isError:!0}}},ke=t=>async r=>{try{let e=r.symbol,i=t.get(e)||[];if(i.length===0)return{content:[{type:"text",text:`No price data available for ${e}`,uri:"getStockPriceHistory"}]};let a=Q(i,500);return{content:[{type:"text",text:JSON.stringify({symbol:e,count:a.length,originalCount:i.length,data:a.map(o=>({timestamp:new Date(o.timestamp).toISOString(),bid:o.bid,offer:o.offer,spread:o.spread,volume:o.volume,trade:o.trade,indexValue:o.indexValue,openingPrice:o.openingPrice,closingPrice:o.closingPrice,settlementPrice:o.settlementPrice,tradingSessionHighPrice:o.tradingSessionHighPrice,tradingSessionLowPrice:o.tradingSessionLowPrice,vwap:o.vwap,imbalance:o.imbalance,openInterest:o.openInterest,compositeUnderlyingPrice:o.compositeUnderlyingPrice,simulatedSellPrice:o.simulatedSellPrice,simulatedBuyPrice:o.simulatedBuyPrice,marginRate:o.marginRate,midPrice:o.midPrice,emptyBook:o.emptyBook,settleHighPrice:o.settleHighPrice,settleLowPrice:o.settleLowPrice,priorSettlePrice:o.priorSettlePrice,sessionHighBid:o.sessionHighBid,sessionLowOffer:o.sessionLowOffer,earlyPrices:o.earlyPrices,auctionClearingPrice:o.auctionClearingPrice,swapValueFactor:o.swapValueFactor,dailyValueAdjustmentForLongPositions:o.dailyValueAdjustmentForLongPositions,cumulativeValueAdjustmentForLongPositions:o.cumulativeValueAdjustmentForLongPositions,dailyValueAdjustmentForShortPositions:o.dailyValueAdjustmentForShortPositions,cumulativeValueAdjustmentForShortPositions:o.cumulativeValueAdjustmentForShortPositions,fixingPrice:o.fixingPrice,cashRate:o.cashRate,recoveryRate:o.recoveryRate,recoveryRateForLong:o.recoveryRateForLong,recoveryRateForShort:o.recoveryRateForShort,marketBid:o.marketBid,marketOffer:o.marketOffer,shortSaleMinPrice:o.shortSaleMinPrice,previousClosingPrice:o.previousClosingPrice,thresholdLimitPriceBanding:o.thresholdLimitPriceBanding,dailyFinancingValue:o.dailyFinancingValue,accruedFinancingValue:o.accruedFinancingValue,twap:o.twap}))},null,2),uri:"getStockPriceHistory"}]}}catch(e){return{content:[{type:"text",text:`Error: ${e instanceof Error?e.message:"Failed to get price history"}`,uri:"getStockPriceHistory"}],isError:!0}}},xe={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"},Ae={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"},Ce={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"},Te={1:"AutomatedExecutionNoIntervention",2:"AutomatedExecutionInterventionOK",3:"ManualOrder"},De=(t,r)=>async e=>{try{return r.set(e.clOrdID,{clOrdID:e.clOrdID,handlInst:e.handlInst,quantity:Number.parseFloat(String(e.quantity)),price:Number.parseFloat(String(e.price)),ordType:e.ordType,side:e.side,symbol:e.symbol,timeInForce:e.timeInForce}),{content:[{type:"text",text:`VERIFICATION: All parameters valid. Ready to proceed with order execution.
|
|
5
|
+
|
|
6
|
+
Parameters verified:
|
|
7
|
+
- ClOrdID: ${e.clOrdID}
|
|
8
|
+
- HandlInst: ${e.handlInst} (${Te[e.handlInst]})
|
|
9
|
+
- Quantity: ${e.quantity}
|
|
10
|
+
- Price: ${e.price}
|
|
11
|
+
- OrdType: ${e.ordType} (${xe[e.ordType]})
|
|
12
|
+
- Side: ${e.side} (${Ae[e.side]})
|
|
13
|
+
- Symbol: ${e.symbol}
|
|
14
|
+
- TimeInForce: ${e.timeInForce} (${Ce[e.timeInForce]})
|
|
15
|
+
|
|
16
|
+
To execute this order, call the executeOrder tool with these exact same parameters. Important: The user has to explicitly confirm before executeOrder is called!`,uri:"verifyOrder"}]}}catch(i){return{content:[{type:"text",text:`Error: ${i instanceof Error?i.message:"Failed to verify order parameters"}`,uri:"verifyOrder"}],isError:!0}}},Le=(t,r,e)=>async i=>{try{let a=r.get(i.clOrdID);if(!a)return{content:[{type:"text",text:`Error: Order ${i.clOrdID} has not been verified. Please call verifyOrder first.`,uri:"executeOrder"}],isError:!0};if(a.handlInst!==i.handlInst||a.quantity!==Number.parseFloat(String(i.quantity))||a.price!==Number.parseFloat(String(i.price))||a.ordType!==i.ordType||a.side!==i.side||a.symbol!==i.symbol||a.timeInForce!==i.timeInForce)return{content:[{type:"text",text:"Error: Order parameters do not match the verified order. Please use the exact same parameters that were verified.",uri:"executeOrder"}],isError:!0};let o=new Promise(c=>{e.set(i.clOrdID,c)}),u=t.createMessage(new P.Field(P.Fields.MsgType,P.Messages.NewOrderSingle),new P.Field(P.Fields.MsgSeqNum,t.getNextTargetMsgSeqNum()),new P.Field(P.Fields.SenderCompID,t.sender),new P.Field(P.Fields.TargetCompID,t.target),new P.Field(P.Fields.SendingTime,t.getTimestamp()),new P.Field(P.Fields.ClOrdID,i.clOrdID),new P.Field(P.Fields.Side,i.side),new P.Field(P.Fields.Symbol,i.symbol),new P.Field(P.Fields.OrderQty,Number.parseFloat(String(i.quantity))),new P.Field(P.Fields.Price,Number.parseFloat(String(i.price))),new P.Field(P.Fields.OrdType,i.ordType),new P.Field(P.Fields.HandlInst,i.handlInst),new P.Field(P.Fields.TimeInForce,i.timeInForce),new P.Field(P.Fields.TransactTime,t.getTimestamp()));if(!t.connected)return{content:[{type:"text",text:"Error: Not connected. Ignoring message.",uri:"executeOrder"}],isError:!0};t.send(u);let n=await o;return r.delete(i.clOrdID),{content:[{type:"text",text:n.messageType===P.Messages.Reject?`Reject message for order ${i.clOrdID}: ${JSON.stringify(n.toFIXJSON())}`:`Execution Report for order ${i.clOrdID}: ${JSON.stringify(n.toFIXJSON())}`,uri:"executeOrder"}]}}catch(a){return{content:[{type:"text",text:`Error: ${a instanceof Error?a.message:"Failed to execute order"}`,uri:"executeOrder"}],isError:!0}}},Ve=t=>async r=>{try{let e=t.parse(r.fixString);return!e||e.length===0?{content:[{type:"text",text:"Error: Failed to parse FIX string",uri:"parse"}],isError:!0}:{content:[{type:"text",text:`${e[0].description}
|
|
17
|
+
${e[0].messageTypeDescription}`,uri:"parse"}]}}catch(e){return{content:[{type:"text",text:`Error: ${e instanceof Error?e.message:"Failed to parse FIX string"}`,uri:"parse"}],isError:!0}}},Ee=t=>async r=>{try{let e=t.parse(r.fixString);return!e||e.length===0?{content:[{type:"text",text:"Error: Failed to parse FIX string",uri:"parseToJSON"}],isError:!0}:{content:[{type:"text",text:`${e[0].toFIXJSON()}`,uri:"parseToJSON"}]}}catch(e){return{content:[{type:"text",text:`Error: ${e instanceof Error?e.message:"Failed to parse FIX string"}`,uri:"parseToJSON"}],isError:!0}}},Be=(t,r,e,i)=>({parse:Ve(t),parseToJSON:Ee(t),verifyOrder:De(t,r),executeOrder:Le(t,r,e),marketDataRequest:Oe(t,e),getStockGraph:Ie(i),getStockPriceHistory:ke(i),technicalAnalysis:Re(i)});function He(t,r){return t[r]||r}function Ne(t,r,e,i,a,o){let u=t.messageType;if(u===g.Messages.MarketDataSnapshotFullRefresh||u===g.Messages.MarketDataIncrementalRefresh){let n=t.getField(g.Fields.Symbol)?.value,l=t.toFIXJSON().Body?.NoMDEntries||[],s={timestamp:Date.now(),bid:0,offer:0,spread:0,volume:0,trade:0,indexValue:0,openingPrice:0,closingPrice:0,settlementPrice:0,tradingSessionHighPrice:0,tradingSessionLowPrice:0,vwap:0,imbalance:0,openInterest:0,compositeUnderlyingPrice:0,simulatedSellPrice:0,simulatedBuyPrice:0,marginRate:0,midPrice:0,emptyBook:0,settleHighPrice:0,settleLowPrice:0,priorSettlePrice:0,sessionHighBid:0,sessionLowOffer:0,earlyPrices:0,auctionClearingPrice:0,swapValueFactor:0,dailyValueAdjustmentForLongPositions:0,cumulativeValueAdjustmentForLongPositions:0,dailyValueAdjustmentForShortPositions:0,cumulativeValueAdjustmentForShortPositions:0,fixingPrice:0,cashRate:0,recoveryRate:0,recoveryRateForLong:0,recoveryRateForShort:0,marketBid:0,marketOffer:0,shortSaleMinPrice:0,previousClosingPrice:0,thresholdLimitPriceBanding:0,dailyFinancingValue:0,accruedFinancingValue:0,twap:0};for(let S of l){let w=S.MDEntryType,d=S.MDEntryPx?Number.parseFloat(S.MDEntryPx):0,M=S.MDEntrySize?Number.parseFloat(S.MDEntrySize):0;switch(He(g.MDEntryType,w)){case g.MDEntryType.Bid:s.bid=d;break;case g.MDEntryType.Offer:s.offer=d;break;case g.MDEntryType.Trade:s.trade=d;break;case g.MDEntryType.IndexValue:s.indexValue=d;break;case g.MDEntryType.OpeningPrice:s.openingPrice=d;break;case g.MDEntryType.ClosingPrice:s.closingPrice=d;break;case g.MDEntryType.SettlementPrice:s.settlementPrice=d;break;case g.MDEntryType.TradingSessionHighPrice:s.tradingSessionHighPrice=d;break;case g.MDEntryType.TradingSessionLowPrice:s.tradingSessionLowPrice=d;break;case g.MDEntryType.VWAP:s.vwap=d;break;case g.MDEntryType.Imbalance:s.imbalance=M;break;case g.MDEntryType.TradeVolume:s.volume=M;break;case g.MDEntryType.OpenInterest:s.openInterest=M;break;case g.MDEntryType.CompositeUnderlyingPrice:s.compositeUnderlyingPrice=d;break;case g.MDEntryType.SimulatedSellPrice:s.simulatedSellPrice=d;break;case g.MDEntryType.SimulatedBuyPrice:s.simulatedBuyPrice=d;break;case g.MDEntryType.MarginRate:s.marginRate=d;break;case g.MDEntryType.MidPrice:s.midPrice=d;break;case g.MDEntryType.EmptyBook:s.emptyBook=1;break;case g.MDEntryType.SettleHighPrice:s.settleHighPrice=d;break;case g.MDEntryType.SettleLowPrice:s.settleLowPrice=d;break;case g.MDEntryType.PriorSettlePrice:s.priorSettlePrice=d;break;case g.MDEntryType.SessionHighBid:s.sessionHighBid=d;break;case g.MDEntryType.SessionLowOffer:s.sessionLowOffer=d;break;case g.MDEntryType.EarlyPrices:s.earlyPrices=d;break;case g.MDEntryType.AuctionClearingPrice:s.auctionClearingPrice=d;break;case g.MDEntryType.SwapValueFactor:s.swapValueFactor=d;break;case g.MDEntryType.DailyValueAdjustmentForLongPositions:s.dailyValueAdjustmentForLongPositions=d;break;case g.MDEntryType.CumulativeValueAdjustmentForLongPositions:s.cumulativeValueAdjustmentForLongPositions=d;break;case g.MDEntryType.DailyValueAdjustmentForShortPositions:s.dailyValueAdjustmentForShortPositions=d;break;case g.MDEntryType.CumulativeValueAdjustmentForShortPositions:s.cumulativeValueAdjustmentForShortPositions=d;break;case g.MDEntryType.FixingPrice:s.fixingPrice=d;break;case g.MDEntryType.CashRate:s.cashRate=d;break;case g.MDEntryType.RecoveryRate:s.recoveryRate=d;break;case g.MDEntryType.RecoveryRateForLong:s.recoveryRateForLong=d;break;case g.MDEntryType.RecoveryRateForShort:s.recoveryRateForShort=d;break;case g.MDEntryType.MarketBid:s.marketBid=d;break;case g.MDEntryType.MarketOffer:s.marketOffer=d;break;case g.MDEntryType.ShortSaleMinPrice:s.shortSaleMinPrice=d;break;case g.MDEntryType.PreviousClosingPrice:s.previousClosingPrice=d;break;case g.MDEntryType.ThresholdLimitPriceBanding:s.thresholdLimitPriceBanding=d;break;case g.MDEntryType.DailyFinancingValue:s.dailyFinancingValue=d;break;case g.MDEntryType.AccruedFinancingValue:s.accruedFinancingValue=d;break;case g.MDEntryType.TWAP:s.twap=d;break}}s.spread=s.offer-s.bid,i.has(n)||i.set(n,[]);let y=i.get(n);y.push(s),y.length>a&&y.splice(0,y.length-a),o?.(n,s);let v=t.getField(g.Fields.MDReqID)?.value;if(v){let S=e.get(v);S&&(S(t),e.delete(v))}}else if(u===g.Messages.ExecutionReport){let n=t.getField(g.Fields.ClOrdID)?.value,c=e.get(n);c&&(c(t),e.delete(n))}}var Y=class extends Me{verifiedOrders=new Map;pendingRequests=new Map;marketDataPrices=new Map;MAX_PRICE_HISTORY=1e5;server=new z.Server({name:"fixparser",version:"1.0.0"},{capabilities:{tools:Object.entries(J).reduce((t,[r,{description:e,schema:i}])=>(t[r]={description:e,parameters:i},t),{})}});transport=new _.StdioServerTransport;constructor({logger:t,onReady:r}){super({logger:t,onReady:r})}async register(t){this.parser=t,this.parser.addOnMessageCallback(r=>{Ne(r,this.parser,this.pendingRequests,this.marketDataPrices,this.MAX_PRICE_HISTORY)}),this.addWorkflows(),await this.server.connect(this.transport),this.onReady&&this.onReady()}addWorkflows(){this.parser&&this.server&&(this.server.setRequestHandler(C.z.object({method:C.z.literal("tools/list")}),async()=>({tools:Object.entries(J).map(([t,{description:r,schema:e}])=>({name:t,description:r,inputSchema:e}))})),this.server.setRequestHandler(C.z.object({method:C.z.literal("tools/call"),params:C.z.object({name:C.z.string(),arguments:C.z.any(),_meta:C.z.object({progressToken:C.z.number()}).optional()})}),async t=>{let{name:r,arguments:e}=t.params,a=Be(this.parser,this.verifiedOrders,this.pendingRequests,this.marketDataPrices)[r];if(!a)return{content:[{type:"text",text:`Tool not found: ${r}`,uri:r}],isError:!0};let o=await a(e);return{content:o.content,isError:o.isError}}),process.on("SIGINT",async()=>{await this.server.close(),process.exit(0)}))}};var $e=async()=>{await b.LicenseManager.setLicenseKey(process.env.FIXPARSER_LICENSE_KEY);let t=process.env.FIXPARSER_SENDER||"SENDER",r=process.env.FIXPARSER_TARGET||"TARGET",e=new b.FIXParser({logging:!0,logOptions:{level:"info",format:"jsonrpc",transport:new U({format:"jsonrpc"})},plugins:[new Y({port:3099,onReady:()=>{}})]}),i=()=>{let o=e.createMessage(new b.Field(b.Fields.MsgType,b.Messages.Logon),new b.Field(b.Fields.MsgSeqNum,e.getNextTargetMsgSeqNum()),new b.Field(b.Fields.SenderCompID,t),new b.Field(b.Fields.SendingTime,e.getTimestamp()),new b.Field(b.Fields.TargetCompID,r),new b.Field(b.Fields.ResetSeqNumFlag,b.ResetSeqNumFlag.Yes),new b.Field(b.Fields.EncryptMethod,b.EncryptMethod.None),new b.Field(b.Fields.HeartBtInt,10));e.send(o)},a={host:process.env.FIXPARSER_HOST||"10.0.1.42",port:process.env.FIXPARSER_PORT?Number.parseInt(process.env.FIXPARSER_PORT,10):5001,protocol:"tcp",sender:t,target:r,fixVersion:"FIX.4.4",onOpen:()=>{e.logger.log({level:"info",message:"FIXParser logging in..."}),i()},onClose:()=>{e.logger.log({level:"info",message:"FIXParser disconnected. Reconnecting in 1 second..."}),setTimeout(()=>{e.connect(a)},1e3)}};e.connect(a)};$e().catch(t=>console.error("Error initializing server:",t));
|
|
9
18
|
//# sourceMappingURL=example_mcp_local.js.map
|