fixparser-plugin-mcp 9.1.7-5c2fdc7a → 9.1.7-5d282a9e

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,6 +1,18 @@
1
1
  #!/usr/bin/env node
2
- import{EncryptMethod as B,FIXParser as L,Field as c,Fields as l,LicenseManager as H,Messages as J,ResetSeqNumFlag as G}from"fixparser";import{Server as O}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as b}from"@modelcontextprotocol/sdk/server/stdio.js";import{CallToolRequestSchema as N,GetPromptRequestSchema as D,ListPromptsRequestSchema as E,ListResourcesRequestSchema as P,ListToolsRequestSchema as C}from"@modelcontextprotocol/sdk/types.js";import{Field as t,Fields as r,HandlInst as X,MDEntryType as A,Messages as f,OrdType as U,SubscriptionRequestType as k,TimeInForce as $}from"fixparser";var I={type:"object",properties:{fixString:{type:"string",description:"FIX message string to parse"}},required:["fixString"]},T={type:"object",properties:{fixString:{type:"string",description:"FIX message string to parse"}},required:["fixString"]},F={type:"object",properties:{clOrdID:{type:"string",description:"Client Order ID"},handlInst:{type:"string",enum:["1","2","3"],default:X.AutomatedExecutionNoIntervention,description:'Handling instruction (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use "1" for Manual, "2" for Automated, "3" for AutomatedNoIntervention)'},quantity:{type:"number",description:"Order quantity"},price:{type:"number",description:"Order price"},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"],default:U.Market,description:'Order type (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use "1" for Market, "2" for Limit, "3" for Stop)'},side:{type:"string",enum:["1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H"],description:'Order side (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use "1" for Buy, "2" for Sell, "3" for BuyMinus, "4" for SellPlus, "5" for SellShort, "6" for SellShortExempt, "7" for Undisclosed, "8" for Cross, "9" for CrossShort, "A" for CrossShortExempt, "B" for AsDefined, "C" for Opposite, "D" for Subscribe, "E" for Redeem, "F" for Lend, "G" for Borrow, "H" for SellUndisclosed)'},symbol:{type:"string",description:"Trading symbol"},timeInForce:{type:"string",enum:["0","1","2","3","4","5","6","7","8","9","A","B","C"],default:$.Day,description:'Time in force (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use "0" for Day, "1" for Good Till Cancel, "2" for At Opening, "3" for Immediate or Cancel, "4" for Fill or Kill, "5" for Good Till Crossing, "6" for Good Till Date)'}},required:["clOrdID","quantity","price","side","symbol"]},w={type:"object",properties:{mdUpdateType:{type:"string",enum:["0","1"],default:"0",description:'Market data update type (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use "0" for FullRefresh, "1" for IncrementalRefresh)'},symbol:{type:"string",description:"Trading symbol"},mdReqID:{type:"string",description:"Market data request ID"},subscriptionRequestType:{type:"string",enum:["0","1","2"],default:k.SnapshotAndUpdates,description:'Subscription request type (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use "0" for Snapshot + Updates, "1" for Snapshot, "2" for Unsubscribe)'},mdEntryType:{type:"string",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:A.Bid,description:'Market data entry type (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use "0" for Bid, "1" for Offer, "2" for Trade, "3" for Index Value, "4" for Opening Price)'}},required:["symbol","mdReqID"]},v=class{logger;parser;server=new O({name:"fixparser",version:"1.0.0"},{capabilities:{tools:{},prompts:{},resources:{}}});transport=new b;onReady=void 0;pendingRequests=new Map;constructor({logger:s,onReady:i}){s&&!s.silent&&(this.logger=s),i&&(this.onReady=i)}async register(s){this.parser=s,s.logger&&!s.logger.silent&&(this.logger=s.logger),this.parser.addOnMessageCallback(i=>{let a=i.messageType;if(a===f.MarketDataSnapshotFullRefresh||a===f.ExecutionReport){let o=a===f.MarketDataSnapshotFullRefresh?i.getField(r.MDReqID):i.getField(r.ClOrdID);if(o){let e=o.value;if(typeof e=="string"||typeof e=="number"){let n=this.pendingRequests.get(String(e));n&&(n(i),this.pendingRequests.delete(String(e)))}}}}),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}let s=(i,a)=>{let o={};for(let[e,n]of Object.entries(a.properties||{})){let p=n,d=i?.[e];if(p.required&&d==null)throw new Error(`Required property '${e}' is missing`);d!==void 0?o[e]=d:p.default!==void 0&&(o[e]=p.default)}return o};this.server.setRequestHandler(P,async()=>({resources:[]})),this.server.setRequestHandler(C,async()=>({tools:[{name:"parse",description:"Parses a FIX message and describes it in plain language",inputSchema:I},{name:"parseToJSON",description:"Parses a FIX message into JSON",inputSchema:T},{name:"newOrderSingle",description:"Creates and sends a New Order Single",inputSchema:F},{name:"marketDataRequest",description:"Sends a request for Market Data with the given symbol",inputSchema:w}]})),this.server.setRequestHandler(N,async i=>{let{name:a,arguments:o}=i.params;switch(a){case"parse":try{let{fixString:e}=s(o,I),n=this.parser?.parse(e);return!n||n.length===0?{isError:!0,content:[{type:"text",text:"Error: Failed to parse FIX string"}]}:{content:[{type:"text",text:`${n[0].description}
3
- ${n[0].messageTypeDescription}`}]}}catch(e){return{isError:!0,content:[{type:"text",text:`Error: ${e instanceof Error?e.message:"Failed to parse FIX string"}`}]}}case"parseToJSON":try{let{fixString:e}=s(o,T),n=this.parser?.parse(e);return!n||n.length===0?{isError:!0,content:[{type:"text",text:"Error: Failed to parse FIX string"}]}:{content:[{type:"text",text:`${n[0].toFIXJSON()}`}]}}catch(e){return{isError:!0,content:[{type:"text",text:`Error: ${e instanceof Error?e.message:"Failed to parse FIX string"}`}]}}case"newOrderSingle":try{let{clOrdID:e,handlInst:n,quantity:p,price:d,ordType:u,side:g,symbol:m,timeInForce:h}=s(o,F),y=new Promise(x=>{this.pendingRequests.set(e,x)}),S=this.parser?.createMessage(new t(r.MsgType,f.NewOrderSingle),new t(r.MsgSeqNum,this.parser?.getNextTargetMsgSeqNum()),new t(r.SenderCompID,this.parser?.sender),new t(r.TargetCompID,this.parser?.target),new t(r.SendingTime,this.parser?.getTimestamp()),new t(r.ClOrdID,e),new t(r.Side,g),new t(r.Symbol,m),new t(r.OrderQty,p),new t(r.Price,d),new t(r.OrdType,u),new t(r.HandlInst,n),new t(r.TimeInForce,h),new t(r.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(S),this.logger?.log({level:"info",message:`FIXParser (MCP): (${this.parser?.protocol?.toUpperCase()}): >> sent ${S?.description}`});let R=await y;return{content:[{type:"text",text:`Execution Report for order ${e}: ${JSON.stringify(R.toFIXJSON())}`}]}}catch(e){return{isError:!0,content:[{type:"text",text:`Error: ${e instanceof Error?e.message:"Failed to create order"}`}]}}case"marketDataRequest":try{let{mdUpdateType:e,symbol:n,mdReqID:p,subscriptionRequestType:d,mdEntryType:u}=s(o,w),g=new Promise(y=>{this.pendingRequests.set(p,y)}),m=this.parser?.createMessage(new t(r.MsgType,f.MarketDataRequest),new t(r.SenderCompID,this.parser?.sender),new t(r.MsgSeqNum,this.parser?.getNextTargetMsgSeqNum()),new t(r.TargetCompID,this.parser?.target),new t(r.SendingTime,this.parser?.getTimestamp()),new t(r.MarketDepth,0),new t(r.MDUpdateType,e),new t(r.NoRelatedSym,1),new t(r.Symbol,n),new t(r.MDReqID,p),new t(r.SubscriptionRequestType,d),new t(r.NoMDEntryTypes,1),new t(r.MDEntryType,u));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 h=await g;return{content:[{type:"text",text:`Market data for ${n}: ${JSON.stringify(h.toFIXJSON())}`}]}}catch(e){return{isError:!0,content:[{type:"text",text:`Error: ${e instanceof Error?e.message:"Failed to request market data"}`}]}}default:throw new Error(`Unknown tool: ${a}`)}}),this.server.setRequestHandler(E,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, 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)",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(D,async i=>{let{name:a,arguments:o}=i.params;switch(a){case"parse":return{messages:[{role:"user",content:{type:"text",text:`Please parse and explain this FIX message: ${o?.fixString||""}`}}]};case"parseToJSON":return{messages:[{role:"user",content:{type:"text",text:`Please parse the FIX message to JSON: ${o?.fixString||""}`}}]};case"newOrderSingle":{let{clOrdID:e,handlInst:n,quantity:p,price:d,ordType:u,side:g,symbol:m,timeInForce:h}=o||{};return{messages:[{role:"user",content:{type:"text",text:["Create a New Order Single FIX message with the following parameters:",`- ClOrdID: ${e}`,`- HandlInst: ${n??"3"} (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use '1' for Manual, '2' for Automated, '3' for AutomatedNoIntervention)`,`- Quantity: ${p}`,`- Price: ${d}`,`- OrdType: ${u??"1"} (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use '1' for Market, '2' for Limit, '3' for Stop)`,`- Side: ${g} (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use '1' for Buy, '2' for Sell)`,`- Symbol: ${m}`,`- TimeInForce: ${h??"0"} (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use '0' for Day, '1' for Good Till Cancel, '2' for At Opening, '3' for Immediate or Cancel, '4' for Fill or Kill, '5' for Good Till Crossing, '6' for Good Till Date)`,"","Format the response as a JSON object with FIX tag numbers as keys and their corresponding values.","",'Note: For the Side parameter, always use the numeric/alphabetic value (e.g., "1" for Buy, "2" for Sell) as defined in the FIX protocol, not the descriptive name.','Note: For the HandlInst parameter, always use the numeric/alphabetic value (e.g., "1" for Manual, "2" for Automated, "3" for AutomatedNoIntervention) as defined in the FIX protocol, not the descriptive name.','Note: For the OrdType parameter, always use the numeric/alphabetic value (e.g., "1" for Market, "2" for Limit, "3" for Stop) as defined in the FIX protocol, not the descriptive name.','Note: For the TimeInForce parameter, always use the numeric/alphabetic value (e.g., "0" for Day, "1" for Good Till Cancel, "2" for At Opening) as defined in the FIX protocol, not the descriptive name.'].join(`
4
- `)}}]}}case"marketDataRequest":{let{mdUpdateType:e,symbol:n,mdReqID:p,subscriptionRequestType:d,mdEntryType:u}=o||{};return{messages:[{role:"user",content:{type:"text",text:["Create a Market Data Request FIX message with the following parameters:",`- MDUpdateType: ${e??"0"} (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use '0' for FullRefresh, '1' for IncrementalRefresh)`,`- Symbol: ${n}`,`- MDReqID: ${p}`,`- SubscriptionRequestType: ${d??"0"} (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use '0' for Snapshot + Updates, '1' for Snapshot, '2' for Unsubscribe)`,`- MDEntryType: ${u??"0"} (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use '0' for Bid, '1' for Offer, '2' for Trade, '3' for Index Value, '4' for Opening Price)`,"","Format the response as a JSON object with FIX tag numbers as keys and their corresponding values.","",'Note: For the MDUpdateType parameter, always use the numeric/alphabetic value (e.g., "0" for FullRefresh, "1" for IncrementalRefresh) as defined in the FIX protocol, not the descriptive name.','Note: For the SubscriptionRequestType parameter, always use the numeric/alphabetic value (e.g., "0" for Snapshot + Updates, "1" for Snapshot, "2" for Unsubscribe) as defined in the FIX protocol, not the descriptive name.','Note: For the MDEntryType parameter, always use the numeric/alphabetic value (e.g., "0" for Bid, "1" for Offer, "2" for Trade, "3" for Index Value, "4" for Opening Price) as defined in the FIX protocol, not the descriptive name.'].join(`
5
- `)}}]}}default:throw new Error(`Unknown prompt: ${a}`)}}),process.on("SIGINT",async()=>{await this.server.close(),process.exit(0)})}};var M="CLIENT2",q="EXECUTOR",j=async()=>{await H.setLicenseKey(process.env.FIXPARSER_LICENSE_KEY);let s=new L({logging:!1,plugins:[new v({port:3099,onReady:()=>{}})]}),i=()=>{let o=s.createMessage(new c(l.MsgType,J.Logon),new c(l.MsgSeqNum,s.getNextTargetMsgSeqNum()),new c(l.SenderCompID,M),new c(l.SendingTime,s.getTimestamp()),new c(l.TargetCompID,q),new c(l.ResetSeqNumFlag,G.Yes),new c(l.EncryptMethod,B.None),new c(l.HeartBtInt,10));s.send(o)},a={host:"10.0.1.42",port:5001,protocol:"tcp",sender:M,target:q,fixVersion:"FIX.4.4",onOpen:()=>{i()},onMessage:o=>{},onClose:()=>{setTimeout(()=>{s.connect(a)},1e3)}};s.connect(a)};j().catch(s=>console.error("Error initializing server:",s));
2
+ import{EncryptMethod as je,FIXParser as qe,Field as H,Fields as N,LicenseManager as We,Messages as Ge,ResetSeqNumFlag as $e}from"fixparser";var Q=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,...n}=t,l={jsonrpc:"2.0",method:t.level,params:{message:e,...n},id:t.id||Date.now()};r(JSON.stringify(l))}else{let{name:e,id:n,message:l,level:o,...c}=t,i=Object.entries(c).map(([a,s])=>`${a}: ${s}`),u="";e&&(u+=`${e} `),u+=`${n}: ${l}`,r(u,i.join(", "))}}async flush(){}async close(){}status(){return"connected"}};import{Server as Pe}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as ve}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as V}from"zod";import{Field as O,Fields as I,MDEntryType as v,Messages as Re}from"fixparser";import Fe from"quickchart-js";import{Field as F,Fields as C,Messages as Z}from"fixparser";import{Fields as G,MDEntryType as P,Messages as $}from"fixparser";import{McpServer as rt}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as st}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{isInitializeRequest as ot}from"@modelcontextprotocol/sdk/types.js";import{z as lt}from"zod";var Se=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}},Y={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 Me(t){return t.reduce((r,e)=>r+e,0)}var we=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 n=r-1;n<t.length;n++){let l=t.slice(n-r+1,n+1).reduce((o,c)=>o+c,0);e.push(l/r)}return e}calculateEMA(t,r){let e=2/(r+1),n=[t[0]];for(let l=1;l<t.length;l++)n.push(t[l]*e+n[l-1]*(1-e));return n}calculateRSI(t,r=14){if(t.length<r+1)return[];let e=[];for(let u=1;u<t.length;u++)e.push(t[u]-t[u-1]);let n=e.map(u=>u>0?u:0),l=e.map(u=>u<0?Math.abs(u):0),o=n.slice(0,r).reduce((u,a)=>u+a,0)/r,c=l.slice(0,r).reduce((u,a)=>u+a,0)/r,i=[];for(let u=r;u<e.length;u++){let a=o/c;i.push(100-100/(1+a)),o=(o*(r-1)+n[u])/r,c=(c*(r-1)+l[u])/r}return i}calculateBollingerBands(t,r=20,e=2){if(t.length<r)return[];let n=this.calculateSMA(t,r),l=[];for(let o=0;o<n.length;o++){let c=t.slice(o,o+r),i=n[o],u=c.reduce((g,f)=>g+(f-i)**2,0)/r,a=Math.sqrt(u),s=i+a*e,m=i-a*e;l.push({upper:s,middle:i,lower:m,bandwidth:(s-m)/i*100,percentB:(t[o]-m)/(s-m)*100})}return l}calculateMaxDrawdown(t){let r=t[0],e=0;for(let n=1;n<t.length;n++){t[n]>r&&(r=t[n]);let l=(r-t[n])/r;l>e&&(e=l)}return e}calculateAtr(t,r,e){if(t.length<2)return[];let n=[];for(let o=1;o<t.length;o++){let c=r[o]||t[o],i=e[o]||t[o],u=t[o-1],a=c-i,s=Math.abs(c-u),m=Math.abs(i-u);n.push(Math.max(a,s,m))}let l=[];if(n.length>=14){let o=n.slice(0,14).reduce((c,i)=>c+i,0);l.push(o/14);for(let c=14;c<n.length;c++)o=o-n[c-14]+n[c],l.push(o/14)}return l}calculateMaxConsecutiveLosses(t){let r=0,e=0;for(let n=1;n<t.length;n++)t[n]<t[n-1]?(e++,r=Math.max(r,e)):e=0;return r}calculateWinRate(t){let r=0,e=0;for(let n=1;n<t.length;n++)t[n]!==t[n-1]&&(e++,t[n]>t[n-1]&&r++);return e>0?r/e:0}calculateProfitFactor(t){let r=0,e=0;for(let n=1;n<t.length;n++){let l=t[n]-t[n-1];l>0?r+=l:e+=Math.abs(l)}return e>0?r/e:0}calculateWma(t,r){let e=[],n=Array.from({length:r},(o,c)=>c+1),l=n.reduce((o,c)=>o+c,0);for(let o=r-1;o<t.length;o++){let c=0;for(let i=0;i<r;i++)c+=t[o-i]*n[i];e.push(c/l)}return e}calculateVwma(t,r){let e=[];for(let n=r-1;n<t.length;n++){let l=0,o=0;for(let c=0;c<r;c++){let i=this.volumes[n-c]||1;l+=i,o+=t[n-c]*i}e.push(o/l)}return e}calculateMacd(t){let r=this.calculateEMA(t,12),e=this.calculateEMA(t,26),n=[],l=[];for(let c=0;c<Math.min(r.length,e.length);c++)l.push(r[c]-e[c]);let o=this.calculateEMA(l,9);for(let c=0;c<Math.min(l.length,o.length);c++)n.push({macd:l[c],signal:o[c],histogram:l[c]-o[c]});return n}calculateAdx(t,r,e){if(t.length<14)return[];let n=14,l=[],o=[],c=[],i=[];o.push(r[0]-e[0]),c.push(0),i.push(0);for(let p=1;p<t.length;p++){let d=r[p]||t[p],y=e[p]||t[p],b=r[p-1]||t[p-1],A=e[p-1]||t[p-1],E=t[p-1],T=d-y,D=Math.abs(d-E),x=Math.abs(y-E);o.push(Math.max(T,D,x));let B=d-b,R=A-y;B>R&&B>0?(c.push(B),i.push(0)):R>B&&R>0?(c.push(0),i.push(R)):(c.push(0),i.push(0))}let u=[],a=[],s=[],m=0,g=0,f=0;for(let p=0;p<n;p++)m+=o[p],g+=c[p],f+=i[p];u.push(m),a.push(g),s.push(f);for(let p=n;p<o.length;p++){let d=u[u.length-1]-u[u.length-1]/n+o[p],y=a[a.length-1]-a[a.length-1]/n+c[p],b=s[s.length-1]-s[s.length-1]/n+i[p];u.push(d),a.push(y),s.push(b)}let M=[],h=[];for(let p=0;p<u.length;p++)M.push(a[p]/u[p]*100),h.push(s[p]/u[p]*100);let S=[];for(let p=0;p<M.length;p++){let d=M[p]+h[p],y=Math.abs(M[p]-h[p]);S.push(d>0?y/d*100:0)}if(S.length<n)return[];let w=0;for(let p=0;p<n;p++)w+=S[p];l.push(w/n);for(let p=n;p<S.length;p++){let d=l[l.length-1]-l[l.length-1]/n+S[p];l.push(d)}return l}calculateDmi(t,r,e){if(t.length<14)return[];let n=14,l=[],o=[],c=[],i=[];o.push(r[0]-e[0]),c.push(0),i.push(0);for(let d=1;d<t.length;d++){let y=r[d]||t[d],b=e[d]||t[d],A=r[d-1]||t[d-1],E=e[d-1]||t[d-1],T=t[d-1],D=y-b,x=Math.abs(y-T),B=Math.abs(b-T);o.push(Math.max(D,x,B));let R=y-A,L=E-b;R>L&&R>0?(c.push(R),i.push(0)):L>R&&L>0?(c.push(0),i.push(L)):(c.push(0),i.push(0))}let u=[],a=[],s=[],m=0,g=0,f=0;for(let d=0;d<n;d++)m+=o[d],g+=c[d],f+=i[d];u.push(m),a.push(g),s.push(f);for(let d=n;d<o.length;d++){let y=u[u.length-1]-u[u.length-1]/n+o[d],b=a[a.length-1]-a[a.length-1]/n+c[d],A=s[s.length-1]-s[s.length-1]/n+i[d];u.push(y),a.push(b),s.push(A)}let M=[],h=[];for(let d=0;d<u.length;d++)M.push(a[d]/u[d]*100),h.push(s[d]/u[d]*100);let S=[];for(let d=0;d<M.length;d++){let y=M[d]+h[d],b=Math.abs(M[d]-h[d]);S.push(y>0?b/y*100:0)}if(S.length<n)return[];let w=[],p=0;for(let d=0;d<n;d++)p+=S[d];w.push(p/n);for(let d=n;d<S.length;d++){let y=w[w.length-1]-w[w.length-1]/n+S[d];w.push(y)}for(let d=0;d<w.length;d++)l.push({plusDI:M[d+n-1]||0,minusDI:h[d+n-1]||0,adx:w[d]});return l}calculateIchimoku(t,r,e){if(t.length<52)return[];let n=[],l=[];for(let s=8;s<t.length;s++){let m=Math.max(...r.slice(s-8,s+1)),g=Math.min(...e.slice(s-8,s+1));l.push((m+g)/2)}let o=[];for(let s=25;s<t.length;s++){let m=Math.max(...r.slice(s-25,s+1)),g=Math.min(...e.slice(s-25,s+1));o.push((m+g)/2)}let c=[];for(let s=0;s<Math.min(l.length,o.length);s++)c.push((l[s]+o[s])/2);let i=[];for(let s=51;s<t.length;s++){let m=Math.max(...r.slice(s-51,s+1)),g=Math.min(...e.slice(s-51,s+1));i.push((m+g)/2)}let u=[];for(let s=26;s<t.length;s++)u.push(t[s-26]);let a=Math.min(l.length,o.length,c.length,i.length,u.length);for(let s=0;s<a;s++)n.push({tenkan:l[s],kijun:o[s],senkouA:c[s],senkouB:i[s],chikou:u[s]});return n}calculateParabolicSAR(t,r,e){if(t.length<2)return[];let n=[],l=.02,o=.2,c=e[0],i=!0,u=l,a=r[0];n.push(c);for(let s=1;s<t.length;s++){let m=r[s]||t[s],g=e[s]||t[s];if(i){if(g<c)i=!1,c=a,a=g,u=l;else if(m>a&&(a=m,u=Math.min(u+l,o)),c=c+u*(a-c),s>0){let f=e[s-1]||t[s-1];c=Math.min(c,f)}}else if(m>c)i=!0,c=a,a=m,u=l;else if(g<a&&(a=g,u=Math.min(u+l,o)),c=c+u*(a-c),s>0){let f=r[s-1]||t[s-1];c=Math.max(c,f)}n.push(c)}return n}calculateStochastic(t,r,e){let n=[];if(t.length<14)return[];let i=[];for(let a=13;a<t.length;a++){let s=Math.max(...r.slice(a-14+1,a+1)),m=Math.min(...e.slice(a-14+1,a+1)),f=(t[a]-m)/(s-m)*100;i.push(f)}let u=[];for(let a=2;a<i.length;a++){let s=i.slice(a-3+1,a+1).reduce((m,g)=>m+g,0);u.push(s/3)}for(let a=2;a<u.length;a++){let m=u.slice(a-3+1,a+1).reduce((g,f)=>g+f,0)/3;n.push({k:u[a],d:m})}return n}calculateCci(t,r,e){let n=[];if(t.length<20)return[];for(let o=19;o<t.length;o++){let i=t.slice(o-20+1,o+1).map((g,f)=>{let M=r[o-20+1+f]||g,h=e[o-20+1+f]||g;return(M+h+g)/3}),u=i.reduce((g,f)=>g+f,0)/20,a=i.reduce((g,f)=>g+Math.abs(f-u),0)/20,s=(r[o]+e[o]+t[o])/3,m=a!==0?(s-u)/(.015*a):0;n.push(m)}return n}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=[];if(t.length<14)return[];for(let n=13;n<t.length;n++){let l=t.slice(n-14+1,n+1),o=Math.max(...l),c=Math.min(...l),i=t[n],u=(o-i)/(o-c)*-100;r.push(u)}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 n=[];if(t.length<20)return[];let c=this.calculateEMA(t,20),i=this.calculateAtr(t,r,e);for(let u=0;u<Math.min(c.length,i.length);u++){let a=c[u],s=i[u];n.push({upper:a+2*s,middle:a,lower:a-2*s})}return n}calculateDonchianChannels(t){let r=[];for(let e=20;e<t.length;e++){let n=t.slice(e-20,e);r.push({upper:Math.max(...n),middle:(Math.max(...n)+Math.min(...n))/2,lower:Math.min(...n)})}return r}calculateChaikinVolatility(t,r,e){let n=[];if(t.length<10*2)return[];let o=[];for(let i=0;i<t.length;i++){let u=r[i]||t[i],a=e[i]||t[i];o.push(u-a)}let c=this.calculateEMA(o,10);for(let i=10;i<c.length;i++){let u=c[i],a=c[i-10],s=a!==0?(u-a)/a*100:0;n.push(s)}return n}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,n){let l=[];if(t.length<20)return[];for(let c=19;c<t.length;c++){let i=0,u=0;for(let s=c-20+1;s<=c;s++){let m=r[s]||t[s],g=e[s]||t[s],f=t[s],M=n[s]||1,S=(f-g-(m-f))/(m-g)*M;i+=S,u+=M}let a=u!==0?i/u:0;l.push(a)}return l}calculateAdl(t){let r=[0];for(let e=1;e<t.length;e++){let n=this.highs[e]||t[e],l=this.lows[e]||t[e],o=t[e],c=this.volumes[e]||1,u=(o-l-(n-o))/(n-l)*c;r.push(r[e-1]+u)}return r}calculateVolumeROC(){let t=[];for(let r=10;r<this.volumes.length;r++)t.push((this.volumes[r]-this.volumes[r-10])/this.volumes[r-10]*100);return t}calculateMfi(t,r,e,n){let l=[];if(t.length<15)return[];for(let c=14;c<t.length;c++){let i=0,u=0;for(let m=c-14+1;m<=c;m++){let g=r[m]||t[m],f=e[m]||t[m],M=t[m],h=n[m]||1,S=(g+f+M)/3,w=S*h;if(m>c-14+1){let p=r[m-1]||t[m-1],d=e[m-1]||t[m-1],y=t[m-1],b=(p+d+y)/3;S>b?i+=w:S<b&&(u+=w)}}let s=100-100/(1+(u!==0?i/u:0));l.push(s)}return l}calculateVwap(t,r){let e=[],n=0,l=0;for(let o=0;o<t.length;o++)n+=t[o]*(r[o]||1),l+=r[o]||1,e.push(n/l);return e}calculatePivotPoints(t){let r=[];for(let e=0;e<t.length;e++){let n=this.highs[e]||t[e],l=this.lows[e]||t[e],o=t[e],c=(n+l+o)/3,i=2*c-l,u=2*c-n,a=c+(n-l),s=c-(n-l),m=n+2*(c-l),g=l-2*(n-c);r.push({pp:c,r1:i,r2:a,r3:m,s1:u,s2:s,s3:g})}return r}calculateFibonacciLevels(t){let r=[];for(let e=0;e<t.length;e++){let n=t[e];r.push({retracement:{level0:n,level236:n*.764,level382:n*.618,level500:n*.5,level618:n*.382,level786:n*.214,level100:n*0},extension:{level1272:n*1.272,level1618:n*1.618,level2618:n*2.618,level4236:n*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=[];if(t.length<10)return[];for(let e=0;e<t.length;e++){let n=[],l=1,o=.5;if(e>=4){let c=t.slice(e-4,e+1),i=this.detectPriceSwings(c);i.length>=3&&(n.push(...i.slice(0,3)),l=Math.min(i.length,5),o=this.calculateWavePosition(c))}r.push({waves:n.length>0?n:[t[e]],currentWave:l,wavePosition:o})}return r}detectPriceSwings(t){let r=[];for(let e=1;e<t.length-1;e++){let n=t[e-1],l=t[e],o=t[e+1];(l>n&&l>o||l<n&&l<o)&&r.push(l)}return r}calculateWavePosition(t){if(t.length<2)return .5;let r=t[t.length-1],e=Math.min(...t),n=Math.max(...t);return n!==e?(r-e)/(n-e):.5}calculateHarmonicPatterns(t){let r=[];if(t.length<5)return[];for(let e=4;e<t.length;e++){let n=t.slice(e-4,e+1),l=this.detectHarmonicPattern(n);r.push(l)}return r}detectHarmonicPattern(t){if(t.length<5)return{type:"Unknown",completion:0,target:t[t.length-1]*1.1,stopLoss:t[t.length-1]*.9};let r=this.detectPriceSwings(t);if(r.length<4)return{type:"Unknown",completion:0,target:t[t.length-1]*1.1,stopLoss:t[t.length-1]*.9};let[e,n,l,o]=r.slice(-4),c=t[0],i=Math.abs((n-e)/(c-e)),u=Math.abs((l-n)/(e-n)),a=Math.abs((o-l)/(n-l)),s=Math.abs((o-e)/(c-e));if(Math.abs(i-.618)<.1&&u>=.382&&u<=.886&&a>=1.13&&a<=1.618&&Math.abs(s-.786)<.1){let f=this.calculatePatternCompletion(t),M=o+(o-l)*.618,h=o-(o-l)*.382;return{type:"Gartley",completion:f,target:M,stopLoss:h}}if(Math.abs(i-.786)<.1&&u>=.382&&u<=.886&&a>=1.618&&a<=2.618&&Math.abs(s-1.27)<.1){let f=this.calculatePatternCompletion(t),M=o+(o-l)*1.27,h=o-(o-l)*.5;return{type:"Butterfly",completion:f,target:M,stopLoss:h}}return{type:"Unknown",completion:0,target:t[t.length-1]*1.1,stopLoss:t[t.length-1]*.9}}calculatePatternCompletion(t){if(t.length<2)return 0;let r=t[t.length-1],e=Math.min(...t),n=Math.max(...t);return n!==e?(r-e)/(n-e):0}calculatePositionSize(t,r,e){let n=Math.abs(r-e);return n>0?100/n:1}calculateConfidence(t){return Math.min(t.length*10,100)}calculateRiskLevel(t){return t<20?"LOW":t<40?"MEDIUM":"HIGH"}calculateZScore(t,r){return(t-r)/(r*.1)}calculateOrnsteinUhlenbeck(t,r,e){let n=this.calculatePriceChanges(),l=r,o=.1;if(n.length>1){let i=n.reduce((u,a)=>u+a*a,0)/n.length;o=Math.max(.01,Math.min(1,i*10))}let c=e*.01;return{mean:l,speed:o,volatility:c,currentValue:t}}calculateKalmanFilter(t,r,e){let n=e*.001,l=e*1e-4,o=r,c=n;if(this.calculatePriceChanges().length>0){let u=o,a=c+l,s=a/(a+n);return o=u+s*(t-u),c=(1-s)*a,{state:o,covariance:c,gain:s}}return{state:t,covariance:c,gain:.5}}calculateArima(t){let r=this.calculatePriceChanges();if(r.length<3)return{forecast:[t*1.01,t*1.02],residuals:[0,0],aic:100};let e=r.length,n=0,l=0,o=0,c=0;for(let h=1;h<e;h++){let S=r[h],w=r[h-1];n+=S,l+=w,o+=S*w,c+=w*w}let i=(e*o-n*l)/(e*c-l*l),u=(n-i*l)/e,a=[];for(let h=1;h<e;h++){let S=u+i*r[h-1];a.push(r[h]-S)}let s=a.reduce((h,S)=>h+S*S,0),m=e*Math.log(s/e)+2*2,g=r[r.length-1],f=t+(u+i*g),M=f+(u+i*(u+i*g));return{forecast:[f,M],residuals:a,aic:m}}calculateGarch(t){let r=this.calculatePriceChanges();if(r.length<5)return{volatility:t*.01,persistence:.9,meanReversion:.1};let e=r.map(i=>i*i),n=e.reduce((i,u)=>i+u,0)/e.length,l=.9;if(e.length>1){let i=e.reduce((u,a)=>u+a,0)/e.length;l=Math.min(.99,Math.max(.5,i/n))}let o=n*(1-l);return{volatility:Math.sqrt(n),persistence:l,meanReversion:o}}calculateHilbertTransform(t){let r=this.calculatePriceChanges();if(r.length<3)return{analytic:[t],phase:[0],amplitude:[t]};let e=r.length,n=[],l=[],o=[];for(let c=0;c<e;c++){let i=0;for(let g=0;g<e;g++)c!==g&&(i+=r[g]/(Math.PI*(c-g)));let u=r[c],a=i,s=Math.sqrt(u*u+a*a);n.push(s);let m=Math.atan2(a,u);l.push(m),o.push(s)}return{analytic:n,phase:l,amplitude:o}}calculateWaveletTransform(t){let r=this.calculatePriceChanges();if(r.length<4)return{coefficients:[t],scales:[1]};let e=[],n=[],l=r.length,o=Math.floor(Math.log2(l));for(let c=1;c<=o;c++){let i=2**(c-1),u=i;for(let a=0;a<l-i;a+=i*2)if(a+i<l){let s=(r[a]-r[a+i])/Math.sqrt(2);e.push(s),n.push(u)}}return e.length===0&&(e.push(t),n.push(1)),{coefficients:e,scales:n}}calculateBlackScholes(t,r,e){let n=t,l=r,o=1,c=.05,i=e*.01,u=(Math.log(n/l)+(c+i*i/2)*o)/(i*Math.sqrt(o)),a=u-i*Math.sqrt(o),s=n*this.normalCDF(u)-l*Math.exp(-c*o)*this.normalCDF(a),m=l*Math.exp(-c*o)*this.normalCDF(-a)-n*this.normalCDF(-u);return{callPrice:s,putPrice:m,delta:this.normalCDF(u),gamma:this.normalPDF(u)/(n*i*Math.sqrt(o)),theta:-n*this.normalPDF(u)*i/(2*Math.sqrt(o))-c*l*Math.exp(-c*o)*this.normalCDF(a),vega:n*Math.sqrt(o)*this.normalPDF(u),rho:l*o*Math.exp(-c*o)*this.normalCDF(a)}}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,n=1.421413741,l=-1.453152027,o=1.061405429,c=.3275911,i=t>=0?1:-1,u=Math.abs(t),a=1/(1+c*u),s=1-((((o*a+l)*a+n)*a+e)*a+r)*a*Math.exp(-u*u);return i*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),n=Math.min(...this.lows),l=Me(this.volumes),o=l/this.volumes.length,c=this.calculatePriceChanges(),i=c.length>0?Math.sqrt(c.reduce((T,D)=>T+D**2,0)/c.length)*Math.sqrt(252)*100:0,u=(t-r)/r*100,a=(t-n)/(e-n)*100,s=this.prices.reduce((T,D,x)=>T+D*this.volumes[x],0)/l,m=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,g=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,f=this.calculateMaxDrawdown(this.prices),M=this.calculateAtr(this.prices,this.highs,this.lows),h=M.length>0?M[M.length-1]:0,S=i,w=i,p=u/i,d=u/w,y=u/f,b=this.calculateMaxConsecutiveLosses(this.prices),A=this.calculateWinRate(this.prices),E=this.calculateProfitFactor(this.prices);return{currentPrice:t,startPrice:r,sessionHigh:e,sessionLow:n,totalVolume:l,avgVolume:o,volatility:i,sessionReturn:u,pricePosition:a,trueVWAP:s,momentum5:m,momentum10:g,maxDrawdown:f,atr:h,impliedVolatility:S,realizedVolatility:w,sharpeRatio:p,sortinoRatio:d,calmarRatio:y,maxConsecutiveLosses:b,winRate:A,profitFactor:E}}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),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(),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,n=[];t.currentPrice>t.trueVWAP?(n.push(`\u2713 BULLISH: Price above VWAP (+${((t.currentPrice-t.trueVWAP)/t.trueVWAP*100).toFixed(2)}%)`),r++):(n.push(`\u2717 BEARISH: Price below VWAP (${((t.currentPrice-t.trueVWAP)/t.trueVWAP*100).toFixed(2)}%)`),e++),t.momentum5>0&&t.momentum10>0?(n.push("\u2713 BULLISH: Positive momentum on both timeframes"),r++):t.momentum5<0&&t.momentum10<0?(n.push("\u2717 BEARISH: Negative momentum on both timeframes"),e++):n.push("\u25D0 MIXED: Conflicting momentum signals");let o=this.volumes[this.volumes.length-1]/t.avgVolume;return o>1.2&&t.sessionReturn>0?(n.push("\u2713 BULLISH: Above-average volume supporting upward move"),r++):o>1.2&&t.sessionReturn<0?(n.push("\u2717 BEARISH: Above-average volume supporting downward move"),e++):n.push("\u25D0 NEUTRAL: Volume not providing clear direction"),t.pricePosition>65&&t.volatility>30?(n.push("\u2717 BEARISH: High in range with elevated volatility - reversal risk"),e++):t.pricePosition<35&&t.volatility>30?(n.push("\u2713 BULLISH: Low in range with volatility - potential bounce"),r++):n.push("\u25D0 NEUTRAL: Price position and volatility not extreme"),{bullishSignals:r,bearishSignals:e,signals:n}}generateJSONAnalysis(t){let r=this.analyze(),e=this.getTechnicalIndicators(),n=this.generateSignals(),l=e.sma5.length>0?e.sma5[e.sma5.length-1]:null,o=e.sma10.length>0?e.sma10[e.sma10.length-1]:null,c=e.sma20.length>0?e.sma20[e.sma20.length-1]:null,i=e.sma50.length>0?e.sma50[e.sma50.length-1]:null,u=e.sma200.length>0?e.sma200[e.sma200.length-1]:null,a=e.ema8[e.ema8.length-1],s=e.ema12[e.ema12.length-1],m=e.ema21[e.ema21.length-1],g=e.ema26[e.ema26.length-1],f=e.wma20.length>0?e.wma20[e.wma20.length-1]:null,M=e.vwma20.length>0?e.vwma20[e.vwma20.length-1]:null,h=e.macd.length>0?e.macd[e.macd.length-1]:null,S=e.adx.length>0?e.adx[e.adx.length-1]:null,w=e.dmi.length>0?e.dmi[e.dmi.length-1]:null,p=e.ichimoku.length>0?e.ichimoku[e.ichimoku.length-1]:null,d=e.parabolicSAR.length>0?e.parabolicSAR[e.parabolicSAR.length-1]:null,y=e.rsi.length>0?e.rsi[e.rsi.length-1]:null,b=e.stochastic.length>0?e.stochastic[e.stochastic.length-1]:null,A=e.cci.length>0?e.cci[e.cci.length-1]:null,E=e.roc.length>0?e.roc[e.roc.length-1]:null,T=e.williamsR.length>0?e.williamsR[e.williamsR.length-1]:null,D=e.momentum.length>0?e.momentum[e.momentum.length-1]:null,x=e.bollinger.length>0?e.bollinger[e.bollinger.length-1]:null,B=e.atr.length>0?e.atr[e.atr.length-1]:null,R=e.keltner.length>0?e.keltner[e.keltner.length-1]:null,L=e.donchian.length>0?e.donchian[e.donchian.length-1]:null,re=e.chaikinVolatility.length>0?e.chaikinVolatility[e.chaikinVolatility.length-1]:null,X=e.obv.length>0?e.obv[e.obv.length-1]:null,U=e.cmf.length>0?e.cmf[e.cmf.length-1]:null,ne=e.adl.length>0?e.adl[e.adl.length-1]:null,se=e.volumeROC.length>0?e.volumeROC[e.volumeROC.length-1]:null,J=e.mfi.length>0?e.mfi[e.mfi.length-1]:null,ie=e.vwap.length>0?e.vwap[e.vwap.length-1]:null,oe=e.pivotPoints.length>0?e.pivotPoints[e.pivotPoints.length-1]:null,ae=e.fibonacci.length>0?e.fibonacci[e.fibonacci.length-1]:null,le=e.gannLevels.length>0?e.gannLevels:[],ce=e.elliottWave.length>0?e.elliottWave[e.elliottWave.length-1]:null,ue=e.harmonicPatterns.length>0?e.harmonicPatterns:[],z=this.volumes[this.volumes.length-1],he=z/r.avgVolume,me=(r.sessionHigh-r.currentPrice)/r.sessionHigh*100,de=(r.sessionHigh-r.sessionLow)/r.sessionLow*100,ge=(r.currentPrice-r.trueVWAP)/r.trueVWAP*100,q=n.bullishSignals-n.bearishSignals,pe=q>0?"BULLISH_BIAS":q<0?"BEARISH_BIAS":"NEUTRAL",W=Math.max(r.sessionLow*1.005,r.trueVWAP*.998),j=r.sessionLow*.995,K=r.sessionHigh*.995,fe=(K-r.currentPrice)/(r.currentPrice-j),_=this.calculatePositionSize(r.currentPrice,W,j),ye=_*(W-j);return{symbol:t,timestamp:new Date().toISOString(),marketStructure:{currentPrice:r.currentPrice,startPrice:r.startPrice,sessionHigh:r.sessionHigh,sessionLow:r.sessionLow,rangeWidth:de,totalVolume:r.totalVolume,sessionPerformance:r.sessionReturn,positionInRange:r.pricePosition},volatility:{impliedVolatility:r.impliedVolatility,realizedVolatility:r.realizedVolatility,atr:r.atr,maxDrawdown:r.maxDrawdown*100,currentDrawdown:me},technicalIndicators:{sma5:l,sma10:o,sma20:c,sma50:i,sma200:u,ema8:a,ema12:s,ema21:m,ema26:g,wma20:f,vwma20:M,macd:h,adx:S,dmi:w,ichimoku:p,parabolicSAR:d,rsi:y,stochastic:b,cci:A,roc:E,williamsR:T,momentum:D,bollingerBands:x?{upper:x.upper,middle:x.middle,lower:x.lower,bandwidth:x.bandwidth,percentB:x.percentB}:null,atr:B,keltnerChannels:R?{upper:R.upper,middle:R.middle,lower:R.lower}:null,donchianChannels:L?{upper:L.upper,middle:L.middle,lower:L.lower}:null,chaikinVolatility:re,obv:X,cmf:U,adl:ne,volumeROC:se,mfi:J,vwap:ie},volumeAnalysis:{currentVolume:z,averageVolume:Math.round(r.avgVolume),volumeRatio:he,trueVWAP:r.trueVWAP,priceVsVWAP:ge,obv:X,cmf:U,mfi:J},momentum:{momentum5:r.momentum5,momentum10:r.momentum10,sessionROC:r.sessionReturn,rsi:y,stochastic:b,cci:A},supportResistance:{pivotPoints:oe,fibonacci:ae,gannLevels:le,elliottWave:ce,harmonicPatterns:ue},tradingSignals:{...n,overallSignal:pe,signalScore:q,confidence:this.calculateConfidence(n.signals),riskLevel:this.calculateRiskLevel(r.volatility)},statisticalModels:{zScore:this.calculateZScore(r.currentPrice,r.startPrice),ornsteinUhlenbeck:this.calculateOrnsteinUhlenbeck(r.currentPrice,r.startPrice,r.avgVolume),kalmanFilter:this.calculateKalmanFilter(r.currentPrice,r.startPrice,r.avgVolume),arima:this.calculateArima(r.currentPrice),garch:this.calculateGarch(r.avgVolume),hilbertTransform:this.calculateHilbertTransform(r.currentPrice),waveletTransform:this.calculateWaveletTransform(r.currentPrice)},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:W,stopLoss:j,profitTarget:K,riskRewardRatio:fe,positionSize:_,maxRisk:ye},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}}}},be=t=>async r=>{try{let e=r.symbol,n=t.get(e)||[];if(n.length===0)return{content:[{type:"text",text:`No price data available for ${e}. Please request market data first.`,uri:"technicalAnalysis"}]};if(!n.every(i=>typeof i.trade=="number"&&!Number.isNaN(i.trade)&&typeof i.midPrice=="number"&&!Number.isNaN(i.midPrice)))throw new Error("Invalid market data");let c=new we(n).generateJSONAnalysis(e);return{content:[{type:"text",text:`Technical Analysis for ${e}:
3
+
4
+ ${JSON.stringify(c,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}}},Ce=(t,r)=>async e=>{try{t.logger.log({level:"info",message:`Sending market data request for symbols: ${e.symbols.join(", ")}`});let n=new Promise(u=>{r.set(e.mdReqID,u),t.logger.log({level:"info",message:`Registered callback for market data request ID: ${e.mdReqID}`})}),l=e.mdEntryTypes||[v.Bid,v.Offer,v.Trade,v.IndexValue,v.OpeningPrice,v.ClosingPrice,v.SettlementPrice,v.TradingSessionHighPrice,v.TradingSessionLowPrice,v.VWAP,v.Imbalance,v.TradeVolume,v.OpenInterest,v.CompositeUnderlyingPrice,v.SimulatedSellPrice,v.SimulatedBuyPrice,v.MarginRate,v.MidPrice,v.EmptyBook,v.SettleHighPrice,v.SettleLowPrice,v.PriorSettlePrice,v.SessionHighBid,v.SessionLowOffer,v.EarlyPrices,v.AuctionClearingPrice,v.SwapValueFactor,v.DailyValueAdjustmentForLongPositions,v.CumulativeValueAdjustmentForLongPositions,v.DailyValueAdjustmentForShortPositions,v.CumulativeValueAdjustmentForShortPositions,v.FixingPrice,v.CashRate,v.RecoveryRate,v.RecoveryRateForLong,v.RecoveryRateForShort,v.MarketBid,v.MarketOffer,v.ShortSaleMinPrice,v.PreviousClosingPrice,v.ThresholdLimitPriceBanding,v.DailyFinancingValue,v.AccruedFinancingValue,v.TWAP],o=[new O(I.MsgType,Re.MarketDataRequest),new O(I.SenderCompID,t.sender),new O(I.MsgSeqNum,t.getNextTargetMsgSeqNum()),new O(I.TargetCompID,t.target),new O(I.SendingTime,t.getTimestamp()),new O(I.MDReqID,e.mdReqID),new O(I.SubscriptionRequestType,e.subscriptionRequestType),new O(I.MarketDepth,0),new O(I.MDUpdateType,e.mdUpdateType)];o.push(new O(I.NoRelatedSym,e.symbols.length)),e.symbols.forEach(u=>{o.push(new O(I.Symbol,u))}),o.push(new O(I.NoMDEntryTypes,l.length)),l.forEach(u=>{o.push(new O(I.MDEntryType,u))});let c=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(c?.toFIXJSON())}`}),t.send(c);let i=await n;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(i.toFIXJSON())}`,uri:"marketDataRequest"}]}}catch(n){return{content:[{type:"text",text:`Error: ${n instanceof Error?n.message:"Failed to request market data"}`,uri:"marketDataRequest"}],isError:!0}}},ee=(t,r=490)=>{if(t.length<=r)return t;let e=[],n=t.length/r;e.push(t[0]);for(let l=1;l<r-1;l++){let o=Math.floor(l*n),c=Math.floor((l+1)*n),i=t.slice(o,c);if(i.length===0)continue;let u={timestamp:i[0].timestamp,bid:i.reduce((a,s)=>a+s.bid,0)/i.length,offer:i.reduce((a,s)=>a+s.offer,0)/i.length,spread:i.reduce((a,s)=>a+s.spread,0)/i.length,volume:i.reduce((a,s)=>a+s.volume,0)/i.length,trade:i.reduce((a,s)=>a+s.trade,0)/i.length,indexValue:i.reduce((a,s)=>a+s.indexValue,0)/i.length,openingPrice:i.reduce((a,s)=>a+s.openingPrice,0)/i.length,closingPrice:i.reduce((a,s)=>a+s.closingPrice,0)/i.length,settlementPrice:i.reduce((a,s)=>a+s.settlementPrice,0)/i.length,tradingSessionHighPrice:i.reduce((a,s)=>a+s.tradingSessionHighPrice,0)/i.length,tradingSessionLowPrice:i.reduce((a,s)=>a+s.tradingSessionLowPrice,0)/i.length,vwap:i.reduce((a,s)=>a+s.vwap,0)/i.length,imbalance:i.reduce((a,s)=>a+s.imbalance,0)/i.length,openInterest:i.reduce((a,s)=>a+s.openInterest,0)/i.length,compositeUnderlyingPrice:i.reduce((a,s)=>a+s.compositeUnderlyingPrice,0)/i.length,simulatedSellPrice:i.reduce((a,s)=>a+s.simulatedSellPrice,0)/i.length,simulatedBuyPrice:i.reduce((a,s)=>a+s.simulatedBuyPrice,0)/i.length,marginRate:i.reduce((a,s)=>a+s.marginRate,0)/i.length,midPrice:i.reduce((a,s)=>a+s.midPrice,0)/i.length,emptyBook:i.reduce((a,s)=>a+s.emptyBook,0)/i.length,settleHighPrice:i.reduce((a,s)=>a+s.settleHighPrice,0)/i.length,settleLowPrice:i.reduce((a,s)=>a+s.settleLowPrice,0)/i.length,priorSettlePrice:i.reduce((a,s)=>a+s.priorSettlePrice,0)/i.length,sessionHighBid:i.reduce((a,s)=>a+s.sessionHighBid,0)/i.length,sessionLowOffer:i.reduce((a,s)=>a+s.sessionLowOffer,0)/i.length,earlyPrices:i.reduce((a,s)=>a+s.earlyPrices,0)/i.length,auctionClearingPrice:i.reduce((a,s)=>a+s.auctionClearingPrice,0)/i.length,swapValueFactor:i.reduce((a,s)=>a+s.swapValueFactor,0)/i.length,dailyValueAdjustmentForLongPositions:i.reduce((a,s)=>a+s.dailyValueAdjustmentForLongPositions,0)/i.length,cumulativeValueAdjustmentForLongPositions:i.reduce((a,s)=>a+s.cumulativeValueAdjustmentForLongPositions,0)/i.length,dailyValueAdjustmentForShortPositions:i.reduce((a,s)=>a+s.dailyValueAdjustmentForShortPositions,0)/i.length,cumulativeValueAdjustmentForShortPositions:i.reduce((a,s)=>a+s.cumulativeValueAdjustmentForShortPositions,0)/i.length,fixingPrice:i.reduce((a,s)=>a+s.fixingPrice,0)/i.length,cashRate:i.reduce((a,s)=>a+s.cashRate,0)/i.length,recoveryRate:i.reduce((a,s)=>a+s.recoveryRate,0)/i.length,recoveryRateForLong:i.reduce((a,s)=>a+s.recoveryRateForLong,0)/i.length,recoveryRateForShort:i.reduce((a,s)=>a+s.recoveryRateForShort,0)/i.length,marketBid:i.reduce((a,s)=>a+s.marketBid,0)/i.length,marketOffer:i.reduce((a,s)=>a+s.marketOffer,0)/i.length,shortSaleMinPrice:i.reduce((a,s)=>a+s.shortSaleMinPrice,0)/i.length,previousClosingPrice:i.reduce((a,s)=>a+s.previousClosingPrice,0)/i.length,thresholdLimitPriceBanding:i.reduce((a,s)=>a+s.thresholdLimitPriceBanding,0)/i.length,dailyFinancingValue:i.reduce((a,s)=>a+s.dailyFinancingValue,0)/i.length,accruedFinancingValue:i.reduce((a,s)=>a+s.accruedFinancingValue,0)/i.length,twap:i.reduce((a,s)=>a+s.twap,0)/i.length};e.push(u)}return e.push(t[t.length-1]),e},Oe=t=>async r=>{try{let e=r.symbol,n=t.get(e)||[];if(n.length===0)return{content:[{type:"text",text:`No price data available for ${e}`,uri:"getStockGraph"}]};let l=ee(n,500),o=new Fe;o.setWidth(1200),o.setHeight(600),o.setBackgroundColor("transparent");let c=l.map(y=>new Date(y.timestamp).toLocaleTimeString()),i=l.map(y=>y.bid),u=l.map(y=>y.offer),a=l.map(y=>y.spread),s=l.map(y=>y.volume),m=l.map(y=>y.trade),g=l.map(y=>y.vwap),f=l.map(y=>y.twap),M=Math.max(...s.filter(y=>y>0)),h=Math.max(...i,...u,...m,...g,...f),S=s.map(y=>y/M*h*.3),w={type:"line",data:{labels:c,datasets:[{label:"Bid",data:i,borderColor:"#28a745",backgroundColor:"rgba(40, 167, 69, 0.1)",fill:!1,tension:.4},{label:"Offer",data:u,borderColor:"#dc3545",backgroundColor:"rgba(220, 53, 69, 0.1)",fill:!1,tension:.4},{label:"Spread",data:a,borderColor:"#6c757d",backgroundColor:"rgba(108, 117, 125, 0.1)",fill:!1,tension:.4},{label:"Trade",data:m,borderColor:"#ffc107",backgroundColor:"rgba(255, 193, 7, 0.1)",fill:!1,tension:.4},{label:"VWAP",data:g,borderColor:"#17a2b8",backgroundColor:"rgba(23, 162, 184, 0.1)",fill:!1,tension:.4},{label:"TWAP",data:f,borderColor:"#6610f2",backgroundColor:"rgba(102, 16, 242, 0.1)",fill:!1,tension:.4},{label:"Volume (Normalized)",data:S,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(w),{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}}},Ie=t=>async r=>{try{let e=r.symbol,n=t.get(e)||[];if(n.length===0)return{content:[{type:"text",text:`No price data available for ${e}`,uri:"getStockPriceHistory"}]};let l=ee(n,500);return{content:[{type:"text",text:JSON.stringify({symbol:e,count:l.length,originalCount:n.length,data:l.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"},ke={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"},Ae={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} (${ke[e.side]})
13
+ - Symbol: ${e.symbol}
14
+ - TimeInForce: ${e.timeInForce} (${Ae[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(n){return{content:[{type:"text",text:`Error: ${n instanceof Error?n.message:"Failed to verify order parameters"}`,uri:"verifyOrder"}],isError:!0}}},Le=(t,r,e)=>async n=>{try{let l=r.get(n.clOrdID);if(!l)return{content:[{type:"text",text:`Error: Order ${n.clOrdID} has not been verified. Please call verifyOrder first.`,uri:"executeOrder"}],isError:!0};if(l.handlInst!==n.handlInst||l.quantity!==Number.parseFloat(String(n.quantity))||l.price!==Number.parseFloat(String(n.price))||l.ordType!==n.ordType||l.side!==n.side||l.symbol!==n.symbol||l.timeInForce!==n.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(u=>{e.set(n.clOrdID,u)}),c=t.createMessage(new F(C.MsgType,Z.NewOrderSingle),new F(C.MsgSeqNum,t.getNextTargetMsgSeqNum()),new F(C.SenderCompID,t.sender),new F(C.TargetCompID,t.target),new F(C.SendingTime,t.getTimestamp()),new F(C.ClOrdID,n.clOrdID),new F(C.Side,n.side),new F(C.Symbol,n.symbol),new F(C.OrderQty,Number.parseFloat(String(n.quantity))),new F(C.Price,Number.parseFloat(String(n.price))),new F(C.OrdType,n.ordType),new F(C.HandlInst,n.handlInst),new F(C.TimeInForce,n.timeInForce),new F(C.TransactTime,t.getTimestamp()));if(!t.connected)return{content:[{type:"text",text:"Error: Not connected. Ignoring message.",uri:"executeOrder"}],isError:!0};t.send(c);let i=await o;return r.delete(n.clOrdID),{content:[{type:"text",text:i.messageType===Z.Reject?`Reject message for order ${n.clOrdID}: ${JSON.stringify(i.toFIXJSON())}`:`Execution Report for order ${n.clOrdID}: ${JSON.stringify(i.toFIXJSON())}`,uri:"executeOrder"}]}}catch(l){return{content:[{type:"text",text:`Error: ${l instanceof Error?l.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,n)=>({parse:Ve(t),parseToJSON:Ee(t),verifyOrder:De(t,r),executeOrder:Le(t,r,e),marketDataRequest:Ce(t,e),getStockGraph:Oe(n),getStockPriceHistory:Ie(n),technicalAnalysis:be(n)});function He(t,r){return t[r]||r}function Ne(t,r,e,n,l,o){let c=t.messageType;if(c===$.MarketDataSnapshotFullRefresh||c===$.MarketDataIncrementalRefresh){let i=t.getField(G.Symbol)?.value,a=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 f of a){let M=f.MDEntryType,h=f.MDEntryPx?Number.parseFloat(f.MDEntryPx):0,S=f.MDEntrySize?Number.parseFloat(f.MDEntrySize):0;switch(He(P,M)){case P.Bid:s.bid=h;break;case P.Offer:s.offer=h;break;case P.Trade:s.trade=h;break;case P.IndexValue:s.indexValue=h;break;case P.OpeningPrice:s.openingPrice=h;break;case P.ClosingPrice:s.closingPrice=h;break;case P.SettlementPrice:s.settlementPrice=h;break;case P.TradingSessionHighPrice:s.tradingSessionHighPrice=h;break;case P.TradingSessionLowPrice:s.tradingSessionLowPrice=h;break;case P.VWAP:s.vwap=h;break;case P.Imbalance:s.imbalance=S;break;case P.TradeVolume:s.volume=S;break;case P.OpenInterest:s.openInterest=S;break;case P.CompositeUnderlyingPrice:s.compositeUnderlyingPrice=h;break;case P.SimulatedSellPrice:s.simulatedSellPrice=h;break;case P.SimulatedBuyPrice:s.simulatedBuyPrice=h;break;case P.MarginRate:s.marginRate=h;break;case P.MidPrice:s.midPrice=h;break;case P.EmptyBook:s.emptyBook=1;break;case P.SettleHighPrice:s.settleHighPrice=h;break;case P.SettleLowPrice:s.settleLowPrice=h;break;case P.PriorSettlePrice:s.priorSettlePrice=h;break;case P.SessionHighBid:s.sessionHighBid=h;break;case P.SessionLowOffer:s.sessionLowOffer=h;break;case P.EarlyPrices:s.earlyPrices=h;break;case P.AuctionClearingPrice:s.auctionClearingPrice=h;break;case P.SwapValueFactor:s.swapValueFactor=h;break;case P.DailyValueAdjustmentForLongPositions:s.dailyValueAdjustmentForLongPositions=h;break;case P.CumulativeValueAdjustmentForLongPositions:s.cumulativeValueAdjustmentForLongPositions=h;break;case P.DailyValueAdjustmentForShortPositions:s.dailyValueAdjustmentForShortPositions=h;break;case P.CumulativeValueAdjustmentForShortPositions:s.cumulativeValueAdjustmentForShortPositions=h;break;case P.FixingPrice:s.fixingPrice=h;break;case P.CashRate:s.cashRate=h;break;case P.RecoveryRate:s.recoveryRate=h;break;case P.RecoveryRateForLong:s.recoveryRateForLong=h;break;case P.RecoveryRateForShort:s.recoveryRateForShort=h;break;case P.MarketBid:s.marketBid=h;break;case P.MarketOffer:s.marketOffer=h;break;case P.ShortSaleMinPrice:s.shortSaleMinPrice=h;break;case P.PreviousClosingPrice:s.previousClosingPrice=h;break;case P.ThresholdLimitPriceBanding:s.thresholdLimitPriceBanding=h;break;case P.DailyFinancingValue:s.dailyFinancingValue=h;break;case P.AccruedFinancingValue:s.accruedFinancingValue=h;break;case P.TWAP:s.twap=h;break}}s.spread=s.offer-s.bid,n.has(i)||n.set(i,[]);let m=n.get(i);m.push(s),m.length>l&&m.splice(0,m.length-l),o?.(i,s);let g=t.getField(G.MDReqID)?.value;if(g){let f=e.get(g);f&&(f(t),e.delete(g))}}else if(c===$.ExecutionReport){let i=t.getField(G.ClOrdID)?.value,u=e.get(i);u&&(u(t),e.delete(i))}}var te=class extends Se{verifiedOrders=new Map;pendingRequests=new Map;marketDataPrices=new Map;MAX_PRICE_HISTORY=1e5;server=new Pe({name:"fixparser",version:"1.0.0"},{capabilities:{tools:Object.entries(Y).reduce((t,[r,{description:e,schema:n}])=>(t[r]={description:e,parameters:n},t),{})}});transport=new ve;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(V.object({method:V.literal("tools/list")}),async()=>({tools:Object.entries(Y).map(([t,{description:r,schema:e}])=>({name:t,description:r,inputSchema:e}))})),this.server.setRequestHandler(V.object({method:V.literal("tools/call"),params:V.object({name:V.string(),arguments:V.any(),_meta:V.object({progressToken:V.number()}).optional()})}),async t=>{let{name:r,arguments:e}=t.params,l=Be(this.parser,this.verifiedOrders,this.pendingRequests,this.marketDataPrices)[r];if(!l)return{content:[{type:"text",text:`Tool not found: ${r}`,uri:r}],isError:!0};let o=await l(e);return{content:o.content,isError:o.isError}}),process.on("SIGINT",async()=>{await this.server.close(),process.exit(0)}))}};var Xe=async()=>{await We.setLicenseKey(process.env.FIXPARSER_LICENSE_KEY);let t=process.env.FIXPARSER_SENDER||"SENDER",r=process.env.FIXPARSER_TARGET||"TARGET",e=new qe({logging:!0,logOptions:{level:"info",format:"jsonrpc",transport:new Q({format:"jsonrpc"})},plugins:[new te({port:3099,onReady:()=>{}})]}),n=()=>{let o=e.createMessage(new H(N.MsgType,Ge.Logon),new H(N.MsgSeqNum,e.getNextTargetMsgSeqNum()),new H(N.SenderCompID,t),new H(N.SendingTime,e.getTimestamp()),new H(N.TargetCompID,r),new H(N.ResetSeqNumFlag,$e.Yes),new H(N.EncryptMethod,je.None),new H(N.HeartBtInt,10));e.send(o)},l={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..."}),n()},onClose:()=>{e.logger.log({level:"info",message:"FIXParser disconnected. Reconnecting in 1 second..."}),setTimeout(()=>{e.connect(l)},1e3)}};e.connect(l)};Xe().catch(t=>console.error("Error initializing server:",t));
6
18
  //# sourceMappingURL=example_mcp_local.mjs.map