fixparser-plugin-mcp 9.1.7-c415bb75 → 9.1.7-c6228661

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.
Files changed (35) hide show
  1. package/build/cjs/MCPLocal.js +422 -10
  2. package/build/cjs/MCPLocal.js.map +4 -4
  3. package/build/cjs/MCPRemote.js +422 -66
  4. package/build/cjs/MCPRemote.js.map +4 -4
  5. package/build/cjs/index.js +422 -66
  6. package/build/cjs/index.js.map +4 -4
  7. package/build/esm/MCPLocal.mjs +422 -10
  8. package/build/esm/MCPLocal.mjs.map +4 -4
  9. package/build/esm/MCPRemote.mjs +422 -66
  10. package/build/esm/MCPRemote.mjs.map +4 -4
  11. package/build/esm/index.mjs +422 -66
  12. package/build/esm/index.mjs.map +4 -4
  13. package/build-examples/cjs/example_mcp_local.js +9 -7
  14. package/build-examples/cjs/example_mcp_local.js.map +4 -4
  15. package/build-examples/cjs/example_mcp_remote.js +9 -7
  16. package/build-examples/cjs/example_mcp_remote.js.map +4 -4
  17. package/build-examples/esm/example_mcp_local.mjs +9 -7
  18. package/build-examples/esm/example_mcp_local.mjs.map +4 -4
  19. package/build-examples/esm/example_mcp_remote.mjs +9 -7
  20. package/build-examples/esm/example_mcp_remote.mjs.map +4 -4
  21. package/package.json +2 -2
  22. package/types/MCPBase.d.ts +0 -49
  23. package/types/MCPLocal.d.ts +0 -32
  24. package/types/MCPRemote.d.ts +0 -58
  25. package/types/PluginOptions.d.ts +0 -6
  26. package/types/index.d.ts +0 -3
  27. package/types/schemas/index.d.ts +0 -15
  28. package/types/schemas/marketData.d.ts +0 -48
  29. package/types/schemas/schemas.d.ts +0 -168
  30. package/types/tools/index.d.ts +0 -17
  31. package/types/tools/marketData.d.ts +0 -40
  32. package/types/tools/order.d.ts +0 -12
  33. package/types/tools/parse.d.ts +0 -5
  34. package/types/tools/parseToJSON.d.ts +0 -5
  35. package/types/utils/messageHandler.d.ts +0 -12
@@ -1,16 +1,18 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var w=Object.create;var v=Object.defineProperty;var D=Object.getOwnPropertyDescriptor;var L=Object.getOwnPropertyNames;var A=Object.getPrototypeOf,N=Object.prototype.hasOwnProperty;var B=(r,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of L(t))!N.call(r,s)&&s!==e&&v(r,s,{get:()=>t[s],enumerable:!(i=D(t,s))||i.enumerable});return r};var H=(r,t,e)=>(e=r!=null?w(A(r)):{},B(t||!r||!r.__esModule?v(e,"default",{value:r,enumerable:!0}):e,r));var p=require("fixparser");var T=class{format;useStderr;constructor({format:r="json",useStderr:t=!1}){this.format=r,this.useStderr=t}configure(r){this.format=r.format||"json",r.useStderr!==void 0&&(this.useStderr=r.useStderr)}async send(r){let t=this.useStderr?console.error:console.log;if(this.format==="json")t(JSON.stringify(r));else if(this.format==="jsonrpc"){let{message:e,...i}=r,s={jsonrpc:"2.0",method:r.level,params:{message:e,...i},id:r.id||Date.now()};t(JSON.stringify(s))}else{let{name:e,id:i,message:s,level:d,...g}=r,u=Object.entries(g).map(([S,n])=>`${S}: ${n}`),m="";e&&(m+=`${e} `),m+=`${i}: ${s}`,t(m,u.join(", "))}}async flush(){}async close(){}status(){return"connected"}};var $=require("@modelcontextprotocol/sdk/server/index.js"),V=require("@modelcontextprotocol/sdk/server/stdio.js"),q=require("zod"),o=require("fixparser"),I=H(require("quickchart-js"),1),c=require("fixparser"),a=require("fixparser"),F=require("node:crypto"),C=require("node:http"),x=require("@modelcontextprotocol/sdk/server/mcp.js"),M=require("@modelcontextprotocol/sdk/server/streamableHttp.js"),k=require("@modelcontextprotocol/sdk/types.js"),h=require("zod"),j=class{logger;parser;onReady=void 0;verifiedOrders=new Map;pendingRequests=new Map;marketDataPrices=new Map;MAX_PRICE_HISTORY=1e5;constructor({logger:r,onReady:t}){this.logger=r,this.onReady=t}},G={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"]}}},J=(r,t)=>async e=>{try{let i=new Promise(m=>{t.set(e.mdReqID,m)}),s=e.mdEntryTypes||[o.MDEntryType.Bid,o.MDEntryType.Offer,o.MDEntryType.Trade,o.MDEntryType.IndexValue,o.MDEntryType.OpeningPrice,o.MDEntryType.ClosingPrice,o.MDEntryType.SettlementPrice,o.MDEntryType.TradingSessionHighPrice,o.MDEntryType.TradingSessionLowPrice,o.MDEntryType.VWAP,o.MDEntryType.Imbalance,o.MDEntryType.TradeVolume,o.MDEntryType.OpenInterest,o.MDEntryType.CompositeUnderlyingPrice,o.MDEntryType.SimulatedSellPrice,o.MDEntryType.SimulatedBuyPrice,o.MDEntryType.MarginRate,o.MDEntryType.MidPrice,o.MDEntryType.EmptyBook,o.MDEntryType.SettleHighPrice,o.MDEntryType.SettleLowPrice,o.MDEntryType.PriorSettlePrice,o.MDEntryType.SessionHighBid,o.MDEntryType.SessionLowOffer,o.MDEntryType.EarlyPrices,o.MDEntryType.AuctionClearingPrice,o.MDEntryType.SwapValueFactor,o.MDEntryType.DailyValueAdjustmentForLongPositions,o.MDEntryType.CumulativeValueAdjustmentForLongPositions,o.MDEntryType.DailyValueAdjustmentForShortPositions,o.MDEntryType.CumulativeValueAdjustmentForShortPositions,o.MDEntryType.FixingPrice,o.MDEntryType.CashRate,o.MDEntryType.RecoveryRate,o.MDEntryType.RecoveryRateForLong,o.MDEntryType.RecoveryRateForShort,o.MDEntryType.MarketBid,o.MDEntryType.MarketOffer,o.MDEntryType.ShortSaleMinPrice,o.MDEntryType.PreviousClosingPrice,o.MDEntryType.ThresholdLimitPriceBanding,o.MDEntryType.DailyFinancingValue,o.MDEntryType.AccruedFinancingValue,o.MDEntryType.TWAP],d=[new o.Field(o.Fields.MsgType,o.Messages.MarketDataRequest),new o.Field(o.Fields.SenderCompID,r.sender),new o.Field(o.Fields.MsgSeqNum,r.getNextTargetMsgSeqNum()),new o.Field(o.Fields.TargetCompID,r.target),new o.Field(o.Fields.SendingTime,r.getTimestamp()),new o.Field(o.Fields.MDReqID,e.mdReqID),new o.Field(o.Fields.SubscriptionRequestType,e.subscriptionRequestType),new o.Field(o.Fields.MarketDepth,0),new o.Field(o.Fields.MDUpdateType,e.mdUpdateType)];d.push(new o.Field(o.Fields.NoRelatedSym,e.symbols.length)),e.symbols.forEach(m=>{d.push(new o.Field(o.Fields.Symbol,m))}),d.push(new o.Field(o.Fields.NoMDEntryTypes,s.length)),s.forEach(m=>{d.push(new o.Field(o.Fields.MDEntryType,m))});let g=r.createMessage(...d);if(!r.connected)return{content:[{type:"text",text:"Error: Not connected. Ignoring message.",uri:"marketDataRequest"}],isError:!0};r.send(g);let u=await i;return{content:[{type:"text",text:`Market data for ${e.symbols.join(", ")}: ${JSON.stringify(u.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}}},X=r=>async t=>{try{let e=t.symbol,i=r.get(e)||[];if(i.length===0)return{content:[{type:"text",text:`No price data available for ${e}`,uri:"getStockGraph"}]};let s=new I.default;s.setWidth(1200),s.setHeight(600),s.setBackgroundColor("transparent");let d=i.map(y=>new Date(y.timestamp).toLocaleTimeString()),g=i.map(y=>y.bid),u=i.map(y=>y.offer),m=i.map(y=>y.spread),S=i.map(y=>y.volume),n={type:"line",data:{labels:d,datasets:[{label:"Bid",data:g,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:m,borderColor:"#6c757d",backgroundColor:"rgba(108, 117, 125, 0.1)",fill:!1,tension:.4},{label:"Volume",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`}},scales:{y:{beginAtZero:!1}}}};return s.setConfig(n),{content:[{type:"resource",resource:{uri:"resource://graph",mimeType:"image/png",blob:(await s.toBinary()).toString("base64")}}]}}catch(e){return{content:[{type:"text",text:`Error: ${e instanceof Error?e.message:"Failed to generate chart"}`,uri:"getStockGraph"}],isError:!0}}},W=r=>async t=>{try{let e=t.symbol,i=r.get(e)||[];return i.length===0?{content:[{type:"text",text:`No price data available for ${e}`,uri:"getStockPriceHistory"}]}:{content:[{type:"text",text:JSON.stringify({symbol:e,count:i.length,data:i.map(s=>({timestamp:new Date(s.timestamp).toISOString(),bid:s.bid,offer:s.offer,spread:s.spread,volume:s.volume}))},null,2),uri:"getStockPriceHistory"}]}}catch(e){return{content:[{type:"text",text:`Error: ${e instanceof Error?e.message:"Failed to get stock price history"}`,uri:"getStockPriceHistory"}],isError:!0}}},U={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"},_={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"},Q={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"},K={1:"AutomatedExecutionNoIntervention",2:"AutomatedExecutionInterventionOK",3:"ManualOrder"},z=(r,t)=>async e=>{try{return t.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.
2
+ "use strict";var B=Object.create;var w=Object.defineProperty;var V=Object.getOwnPropertyDescriptor;var H=Object.getOwnPropertyNames;var N=Object.getPrototypeOf,q=Object.prototype.hasOwnProperty;var j=(r,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of H(t))!q.call(r,s)&&s!==e&&w(r,s,{get:()=>t[s],enumerable:!(i=V(t,s))||i.enumerable});return r};var $=(r,t,e)=>(e=r!=null?B(N(r)):{},j(t||!r||!r.__esModule?w(e,"default",{value:r,enumerable:!0}):e,r));var p=require("fixparser");var R=class{format;useStderr;constructor({format:r="json",useStderr:t=!1}){this.format=r,this.useStderr=t}configure(r){this.format=r.format||"json",r.useStderr!==void 0&&(this.useStderr=r.useStderr)}async send(r){let t=this.useStderr?console.error:console.log;if(this.format==="json")t(JSON.stringify(r));else if(this.format==="jsonrpc"){let{message:e,...i}=r,s={jsonrpc:"2.0",method:r.level,params:{message:e,...i},id:r.id||Date.now()};t(JSON.stringify(s))}else{let{name:e,id:i,message:s,level:c,...m}=r,d=Object.entries(m).map(([h,n])=>`${h}: ${n}`),l="";e&&(l+=`${e} `),l+=`${i}: ${s}`,t(l,d.join(", "))}}async flush(){}async close(){}status(){return"connected"}};var G=require("@modelcontextprotocol/sdk/server/index.js"),W=require("@modelcontextprotocol/sdk/server/stdio.js"),J=require("zod"),o=require("fixparser"),M=$(require("quickchart-js"),1),g=require("fixparser"),a=require("fixparser"),x=require("node:crypto"),C=require("node:http"),A=require("@modelcontextprotocol/sdk/server/mcp.js"),k=require("@modelcontextprotocol/sdk/server/streamableHttp.js"),E=require("@modelcontextprotocol/sdk/types.js"),P=require("zod"),X=class{logger;parser;onReady=void 0;verifiedOrders=new Map;pendingRequests=new Map;marketDataPrices=new Map;MAX_PRICE_HISTORY=1e5;constructor({logger:r,onReady:t}){this.logger=r,this.onReady=t}},U={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 _(r){return r.reduce((t,e)=>t+e,0)}var z=class{prices;volumes;highs;lows;constructor(r){this.prices=r.map(t=>t.trade>0?t.trade:t.midPrice),this.volumes=r.map(t=>t.volume),this.highs=r.map(t=>t.tradingSessionHighPrice>0?t.tradingSessionHighPrice:t.trade),this.lows=r.map(t=>t.tradingSessionLowPrice>0?t.tradingSessionLowPrice:t.trade)}calculateSMA(r,t){let e=[];for(let i=t-1;i<r.length;i++){let s=r.slice(i-t+1,i+1).reduce((c,m)=>c+m,0);e.push(s/t)}return e}calculateEMA(r,t){let e=2/(t+1),i=[r[0]];for(let s=1;s<r.length;s++)i.push(r[s]*e+i[s-1]*(1-e));return i}calculateRSI(r,t=14){if(r.length<t+1)return[];let e=[];for(let l=1;l<r.length;l++)e.push(r[l]-r[l-1]);let i=e.map(l=>l>0?l:0),s=e.map(l=>l<0?Math.abs(l):0),c=i.slice(0,t).reduce((l,h)=>l+h,0)/t,m=s.slice(0,t).reduce((l,h)=>l+h,0)/t,d=[];for(let l=t;l<e.length;l++){let h=c/m;d.push(100-100/(1+h)),c=(c*(t-1)+i[l])/t,m=(m*(t-1)+s[l])/t}return d}calculateBollingerBands(r,t=20,e=2){if(r.length<t)return[];let i=this.calculateSMA(r,t),s=[];for(let c=0;c<i.length;c++){let m=r.slice(c,c+t),d=i[c],l=m.reduce((n,f)=>n+(f-d)**2,0)/t,h=Math.sqrt(l);s.push({upper:d+h*e,middle:d,lower:d-h*e})}return s}calculateMaxDrawdown(r){let t=r[0],e=0;for(let i=1;i<r.length;i++){r[i]>t&&(t=r[i]);let s=(t-r[i])/t;s>e&&(e=s)}return e}calculatePriceChanges(){let r=[];for(let t=1;t<this.prices.length;t++)r.push((this.prices[t]-this.prices[t-1])/this.prices[t-1]);return r}analyze(){let r=this.prices[this.prices.length-1],t=this.prices[0],e=Math.max(...this.highs),i=Math.min(...this.lows),s=_(this.volumes),c=s/this.volumes.length,m=this.calculatePriceChanges(),d=m.length>0?Math.sqrt(m.reduce((b,u)=>b+u**2,0)/m.length)*Math.sqrt(252)*100:0,l=(r-t)/t*100,h=(r-i)/(e-i)*100,n=this.prices.reduce((b,u,y)=>b+u*this.volumes[y],0)/s,f=this.prices.length>5?(r-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?(r-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);return{currentPrice:r,startPrice:t,sessionHigh:e,sessionLow:i,totalVolume:s,avgVolume:c,volatility:d,sessionReturn:l,pricePosition:h,trueVWAP:n,momentum5:f,momentum10:v,maxDrawdown:S}}getTechnicalIndicators(){return{sma5:this.calculateSMA(this.prices,5),sma10:this.calculateSMA(this.prices,10),ema8:this.calculateEMA(this.prices,8),ema21:this.calculateEMA(this.prices,21),rsi:this.calculateRSI(this.prices,14),bollinger:this.calculateBollingerBands(this.prices,20,2)}}generateSignals(){let r=this.analyze(),t=0,e=0,i=[];r.currentPrice>r.trueVWAP?(i.push(`\u2713 BULLISH: Price above VWAP (+${((r.currentPrice-r.trueVWAP)/r.trueVWAP*100).toFixed(2)}%)`),t++):(i.push(`\u2717 BEARISH: Price below VWAP (${((r.currentPrice-r.trueVWAP)/r.trueVWAP*100).toFixed(2)}%)`),e++),r.momentum5>0&&r.momentum10>0?(i.push("\u2713 BULLISH: Positive momentum on both timeframes"),t++):r.momentum5<0&&r.momentum10<0?(i.push("\u2717 BEARISH: Negative momentum on both timeframes"),e++):i.push("\u25D0 MIXED: Conflicting momentum signals");let c=this.volumes[this.volumes.length-1]/r.avgVolume;return c>1.2&&r.sessionReturn>0?(i.push("\u2713 BULLISH: Above-average volume supporting upward move"),t++):c>1.2&&r.sessionReturn<0?(i.push("\u2717 BEARISH: Above-average volume supporting downward move"),e++):i.push("\u25D0 NEUTRAL: Volume not providing clear direction"),r.pricePosition>65&&r.volatility>30?(i.push("\u2717 BEARISH: High in range with elevated volatility - reversal risk"),e++):r.pricePosition<35&&r.volatility>30?(i.push("\u2713 BULLISH: Low in range with volatility - potential bounce"),t++):i.push("\u25D0 NEUTRAL: Price position and volatility not extreme"),{bullishSignals:t,bearishSignals:e,signals:i}}generateJSONAnalysis(r){let t=this.analyze(),e=this.getTechnicalIndicators(),i=this.generateSignals(),s=e.sma5.length>0?e.sma5[e.sma5.length-1]:null,c=e.sma10.length>0?e.sma10[e.sma10.length-1]:null,m=e.ema8[e.ema8.length-1],d=e.ema21[e.ema21.length-1],l=e.rsi.length>0?e.rsi[e.rsi.length-1]:null,h=e.bollinger.length>0?e.bollinger[e.bollinger.length-1]:null,n=this.volumes[this.volumes.length-1],f=n/t.avgVolume,v=(t.sessionHigh-t.currentPrice)/t.sessionHigh*100,S=(t.sessionHigh-t.sessionLow)/t.sessionLow*100,b=(t.currentPrice-t.trueVWAP)/t.trueVWAP*100,u=i.bullishSignals-i.bearishSignals,y=u>0?"BULLISH_BIAS":u<0?"BEARISH_BIAS":"NEUTRAL",I=Math.max(t.sessionLow*1.005,t.trueVWAP*.998),F=t.sessionLow*.995,T=t.sessionHigh*.995,D=(T-t.currentPrice)/(t.currentPrice-F);return{symbol:r,timestamp:new Date().toISOString(),marketStructure:{currentPrice:t.currentPrice,startPrice:t.startPrice,sessionHigh:t.sessionHigh,sessionLow:t.sessionLow,rangeWidth:S,totalVolume:t.totalVolume,sessionPerformance:t.sessionReturn,positionInRange:t.pricePosition},volatility:{impliedVolatility:t.volatility,maxDrawdown:t.maxDrawdown*100,currentDrawdown:v},technicalIndicators:{sma5:s,sma10:c,ema8:m,ema21:d,rsi:l,bollingerBands:h?{upper:h.upper,middle:h.middle,lower:h.lower,position:(t.currentPrice-h.lower)/(h.upper-h.lower)*100}:null},volumeAnalysis:{currentVolume:n,averageVolume:Math.round(t.avgVolume),volumeRatio:f,trueVWAP:t.trueVWAP,priceVsVWAP:b},momentum:{momentum5:t.momentum5,momentum10:t.momentum10,sessionROC:t.sessionReturn},tradingSignals:{...i,overallSignal:y,signalScore:u},riskManagement:{targetEntry:I,stopLoss:F,profitTarget:T,riskRewardRatio:D}}}},Q=r=>async t=>{try{let e=t.symbol,i=r.get(e)||[];if(i.length===0)return{content:[{type:"text",text:`No price data available for ${e}. Please request market data first.`,uri:"technicalAnalysis"}]};let c=new z(i).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}}},K=(r,t)=>async e=>{try{r.logger.log({level:"info",message:`Sending market data request for symbols: ${e.symbols.join(", ")}`});let i=new Promise(l=>{t.set(e.mdReqID,l),r.logger.log({level:"info",message:`Registered callback for market data request ID: ${e.mdReqID}`})}),s=e.mdEntryTypes||[o.MDEntryType.Bid,o.MDEntryType.Offer,o.MDEntryType.Trade,o.MDEntryType.IndexValue,o.MDEntryType.OpeningPrice,o.MDEntryType.ClosingPrice,o.MDEntryType.SettlementPrice,o.MDEntryType.TradingSessionHighPrice,o.MDEntryType.TradingSessionLowPrice,o.MDEntryType.VWAP,o.MDEntryType.Imbalance,o.MDEntryType.TradeVolume,o.MDEntryType.OpenInterest,o.MDEntryType.CompositeUnderlyingPrice,o.MDEntryType.SimulatedSellPrice,o.MDEntryType.SimulatedBuyPrice,o.MDEntryType.MarginRate,o.MDEntryType.MidPrice,o.MDEntryType.EmptyBook,o.MDEntryType.SettleHighPrice,o.MDEntryType.SettleLowPrice,o.MDEntryType.PriorSettlePrice,o.MDEntryType.SessionHighBid,o.MDEntryType.SessionLowOffer,o.MDEntryType.EarlyPrices,o.MDEntryType.AuctionClearingPrice,o.MDEntryType.SwapValueFactor,o.MDEntryType.DailyValueAdjustmentForLongPositions,o.MDEntryType.CumulativeValueAdjustmentForLongPositions,o.MDEntryType.DailyValueAdjustmentForShortPositions,o.MDEntryType.CumulativeValueAdjustmentForShortPositions,o.MDEntryType.FixingPrice,o.MDEntryType.CashRate,o.MDEntryType.RecoveryRate,o.MDEntryType.RecoveryRateForLong,o.MDEntryType.RecoveryRateForShort,o.MDEntryType.MarketBid,o.MDEntryType.MarketOffer,o.MDEntryType.ShortSaleMinPrice,o.MDEntryType.PreviousClosingPrice,o.MDEntryType.ThresholdLimitPriceBanding,o.MDEntryType.DailyFinancingValue,o.MDEntryType.AccruedFinancingValue,o.MDEntryType.TWAP],c=[new o.Field(o.Fields.MsgType,o.Messages.MarketDataRequest),new o.Field(o.Fields.SenderCompID,r.sender),new o.Field(o.Fields.MsgSeqNum,r.getNextTargetMsgSeqNum()),new o.Field(o.Fields.TargetCompID,r.target),new o.Field(o.Fields.SendingTime,r.getTimestamp()),new o.Field(o.Fields.MDReqID,e.mdReqID),new o.Field(o.Fields.SubscriptionRequestType,e.subscriptionRequestType),new o.Field(o.Fields.MarketDepth,0),new o.Field(o.Fields.MDUpdateType,e.mdUpdateType)];c.push(new o.Field(o.Fields.NoRelatedSym,e.symbols.length)),e.symbols.forEach(l=>{c.push(new o.Field(o.Fields.Symbol,l))}),c.push(new o.Field(o.Fields.NoMDEntryTypes,s.length)),s.forEach(l=>{c.push(new o.Field(o.Fields.MDEntryType,l))});let m=r.createMessage(...c);if(!r.connected)return r.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};r.logger.log({level:"info",message:`Sending market data request message: ${JSON.stringify(m?.toFIXJSON())}`}),r.send(m);let d=await i;return r.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(d.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}}},Y=r=>async t=>{try{let e=t.symbol,i=r.get(e)||[];if(i.length===0)return{content:[{type:"text",text:`No price data available for ${e}`,uri:"getStockGraph"}]};let s=new M.default;s.setWidth(1200),s.setHeight(600),s.setBackgroundColor("transparent");let c=i.map(y=>new Date(y.timestamp).toLocaleTimeString()),m=i.map(y=>y.bid),d=i.map(y=>y.offer),l=i.map(y=>y.spread),h=i.map(y=>y.volume),n=i.map(y=>y.trade),f=i.map(y=>y.vwap),v=i.map(y=>y.twap),S={type:"line",data:{labels:c,datasets:[{label:"Bid",data:m,borderColor:"#28a745",backgroundColor:"rgba(40, 167, 69, 0.1)",fill:!1,tension:.4},{label:"Offer",data:d,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:n,borderColor:"#ffc107",backgroundColor:"rgba(255, 193, 7, 0.1)",fill:!1,tension:.4},{label:"VWAP",data:f,borderColor:"#17a2b8",backgroundColor:"rgba(23, 162, 184, 0.1)",fill:!1,tension:.4},{label:"TWAP",data:v,borderColor:"#6610f2",backgroundColor:"rgba(102, 16, 242, 0.1)",fill:!1,tension:.4},{label:"Volume",data:h,borderColor:"#007bff",backgroundColor:"rgba(0, 123, 255, 0.1)",fill:!0,tension:.4}]},options:{responsive:!0,plugins:{title:{display:!0,text:`${e} Market Data`}},scales:{y:{beginAtZero:!1}}}};return s.setConfig(S),{content:[{type:"resource",resource:{uri:"resource://graph",mimeType:"image/png",blob:(await s.toBinary()).toString("base64")}}]}}catch(e){return{content:[{type:"text",text:`Error: ${e instanceof Error?e.message:"Failed to generate graph"}`,uri:"getStockGraph"}],isError:!0}}},Z=r=>async t=>{try{let e=t.symbol,i=r.get(e)||[];return i.length===0?{content:[{type:"text",text:`No price data available for ${e}`,uri:"getStockPriceHistory"}]}:{content:[{type:"text",text:JSON.stringify({symbol:e,count:i.length,data:i.map(s=>({timestamp:new Date(s.timestamp).toISOString(),bid:s.bid,offer:s.offer,spread:s.spread,volume:s.volume,trade:s.trade,indexValue:s.indexValue,openingPrice:s.openingPrice,closingPrice:s.closingPrice,settlementPrice:s.settlementPrice,tradingSessionHighPrice:s.tradingSessionHighPrice,tradingSessionLowPrice:s.tradingSessionLowPrice,vwap:s.vwap,imbalance:s.imbalance,openInterest:s.openInterest,compositeUnderlyingPrice:s.compositeUnderlyingPrice,simulatedSellPrice:s.simulatedSellPrice,simulatedBuyPrice:s.simulatedBuyPrice,marginRate:s.marginRate,midPrice:s.midPrice,emptyBook:s.emptyBook,settleHighPrice:s.settleHighPrice,settleLowPrice:s.settleLowPrice,priorSettlePrice:s.priorSettlePrice,sessionHighBid:s.sessionHighBid,sessionLowOffer:s.sessionLowOffer,earlyPrices:s.earlyPrices,auctionClearingPrice:s.auctionClearingPrice,swapValueFactor:s.swapValueFactor,dailyValueAdjustmentForLongPositions:s.dailyValueAdjustmentForLongPositions,cumulativeValueAdjustmentForLongPositions:s.cumulativeValueAdjustmentForLongPositions,dailyValueAdjustmentForShortPositions:s.dailyValueAdjustmentForShortPositions,cumulativeValueAdjustmentForShortPositions:s.cumulativeValueAdjustmentForShortPositions,fixingPrice:s.fixingPrice,cashRate:s.cashRate,recoveryRate:s.recoveryRate,recoveryRateForLong:s.recoveryRateForLong,recoveryRateForShort:s.recoveryRateForShort,marketBid:s.marketBid,marketOffer:s.marketOffer,shortSaleMinPrice:s.shortSaleMinPrice,previousClosingPrice:s.previousClosingPrice,thresholdLimitPriceBanding:s.thresholdLimitPriceBanding,dailyFinancingValue:s.dailyFinancingValue,accruedFinancingValue:s.accruedFinancingValue,twap:s.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}}},ee={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"},te={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"},re={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"},se={1:"AutomatedExecutionNoIntervention",2:"AutomatedExecutionInterventionOK",3:"ManualOrder"},ie=(r,t)=>async e=>{try{return t.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.
3
5
 
4
6
  Parameters verified:
5
7
  - ClOrdID: ${e.clOrdID}
6
- - HandlInst: ${e.handlInst} (${K[e.handlInst]})
8
+ - HandlInst: ${e.handlInst} (${se[e.handlInst]})
7
9
  - Quantity: ${e.quantity}
8
10
  - Price: ${e.price}
9
- - OrdType: ${e.ordType} (${U[e.ordType]})
10
- - Side: ${e.side} (${_[e.side]})
11
+ - OrdType: ${e.ordType} (${ee[e.ordType]})
12
+ - Side: ${e.side} (${te[e.side]})
11
13
  - Symbol: ${e.symbol}
12
- - TimeInForce: ${e.timeInForce} (${Q[e.timeInForce]})
14
+ - TimeInForce: ${e.timeInForce} (${re[e.timeInForce]})
13
15
 
14
- To execute this order, call the executeOrder tool with these exact same parameters.`,uri:"verifyOrder"}]}}catch(i){return{content:[{type:"text",text:`Error: ${i instanceof Error?i.message:"Failed to verify order parameters"}`,uri:"verifyOrder"}],isError:!0}}},Y=(r,t,e)=>async i=>{try{let s=t.get(i.clOrdID);if(!s)return{content:[{type:"text",text:`Error: Order ${i.clOrdID} has not been verified. Please call verifyOrder first.`,uri:"executeOrder"}],isError:!0};if(s.handlInst!==i.handlInst||s.quantity!==Number.parseFloat(String(i.quantity))||s.price!==Number.parseFloat(String(i.price))||s.ordType!==i.ordType||s.side!==i.side||s.symbol!==i.symbol||s.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 d=new Promise(m=>{e.set(i.clOrdID,m)}),g=r.createMessage(new c.Field(c.Fields.MsgType,c.Messages.NewOrderSingle),new c.Field(c.Fields.MsgSeqNum,r.getNextTargetMsgSeqNum()),new c.Field(c.Fields.SenderCompID,r.sender),new c.Field(c.Fields.TargetCompID,r.target),new c.Field(c.Fields.SendingTime,r.getTimestamp()),new c.Field(c.Fields.ClOrdID,i.clOrdID),new c.Field(c.Fields.Side,i.side),new c.Field(c.Fields.Symbol,i.symbol),new c.Field(c.Fields.OrderQty,Number.parseFloat(String(i.quantity))),new c.Field(c.Fields.Price,Number.parseFloat(String(i.price))),new c.Field(c.Fields.OrdType,i.ordType),new c.Field(c.Fields.HandlInst,i.handlInst),new c.Field(c.Fields.TimeInForce,i.timeInForce),new c.Field(c.Fields.TransactTime,r.getTimestamp()));if(!r.connected)return{content:[{type:"text",text:"Error: Not connected. Ignoring message.",uri:"executeOrder"}],isError:!0};r.send(g);let u=await d;return t.delete(i.clOrdID),{content:[{type:"text",text:u.messageType===c.Messages.Reject?`Reject message for order ${i.clOrdID}: ${JSON.stringify(u.toFIXJSON())}`:`Execution Report for order ${i.clOrdID}: ${JSON.stringify(u.toFIXJSON())}`,uri:"executeOrder"}]}}catch(s){return{content:[{type:"text",text:`Error: ${s instanceof Error?s.message:"Failed to execute order"}`,uri:"executeOrder"}],isError:!0}}},Z=r=>async t=>{try{let e=r.parse(t.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}
15
- ${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=r=>async t=>{try{let e=r.parse(t.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}}},re=(r,t,e,i)=>({parse:Z(r),parseToJSON:ee(r),verifyOrder:z(r,t),executeOrder:Y(r,t,e),marketDataRequest:J(r,e),getStockGraph:X(i),getStockPriceHistory:W(i)});function te(r,t,e,i,s,d){t.logger.log({level:"info",message:`MCP Server received message: ${r.messageType}: ${r.description}`});let g=r.messageType;if(g===a.Messages.MarketDataSnapshotFullRefresh||g===a.Messages.MarketDataIncrementalRefresh){let u=r.getField(a.Fields.Symbol)?.value,S=r.toFIXJSON().Body?.NoMDEntries||[],n={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 y of S){let R=y.MDEntryType,l=y.MDEntryPx?Number.parseFloat(y.MDEntryPx):0,b=y.MDEntrySize?Number.parseFloat(y.MDEntrySize):0;switch(R){case a.MDEntryType.Bid:n.bid=l;break;case a.MDEntryType.Offer:n.offer=l;break;case a.MDEntryType.Trade:n.trade=l;break;case a.MDEntryType.IndexValue:n.indexValue=l;break;case a.MDEntryType.OpeningPrice:n.openingPrice=l;break;case a.MDEntryType.ClosingPrice:n.closingPrice=l;break;case a.MDEntryType.SettlementPrice:n.settlementPrice=l;break;case a.MDEntryType.TradingSessionHighPrice:n.tradingSessionHighPrice=l;break;case a.MDEntryType.TradingSessionLowPrice:n.tradingSessionLowPrice=l;break;case a.MDEntryType.VWAP:n.vwap=l;break;case a.MDEntryType.Imbalance:n.imbalance=b;break;case a.MDEntryType.TradeVolume:n.volume=b;break;case a.MDEntryType.OpenInterest:n.openInterest=b;break;case a.MDEntryType.CompositeUnderlyingPrice:n.compositeUnderlyingPrice=l;break;case a.MDEntryType.SimulatedSellPrice:n.simulatedSellPrice=l;break;case a.MDEntryType.SimulatedBuyPrice:n.simulatedBuyPrice=l;break;case a.MDEntryType.MarginRate:n.marginRate=l;break;case a.MDEntryType.MidPrice:n.midPrice=l;break;case a.MDEntryType.EmptyBook:n.emptyBook=1;break;case a.MDEntryType.SettleHighPrice:n.settleHighPrice=l;break;case a.MDEntryType.SettleLowPrice:n.settleLowPrice=l;break;case a.MDEntryType.PriorSettlePrice:n.priorSettlePrice=l;break;case a.MDEntryType.SessionHighBid:n.sessionHighBid=l;break;case a.MDEntryType.SessionLowOffer:n.sessionLowOffer=l;break;case a.MDEntryType.EarlyPrices:n.earlyPrices=l;break;case a.MDEntryType.AuctionClearingPrice:n.auctionClearingPrice=l;break;case a.MDEntryType.SwapValueFactor:n.swapValueFactor=l;break;case a.MDEntryType.DailyValueAdjustmentForLongPositions:n.dailyValueAdjustmentForLongPositions=l;break;case a.MDEntryType.CumulativeValueAdjustmentForLongPositions:n.cumulativeValueAdjustmentForLongPositions=l;break;case a.MDEntryType.DailyValueAdjustmentForShortPositions:n.dailyValueAdjustmentForShortPositions=l;break;case a.MDEntryType.CumulativeValueAdjustmentForShortPositions:n.cumulativeValueAdjustmentForShortPositions=l;break;case a.MDEntryType.FixingPrice:n.fixingPrice=l;break;case a.MDEntryType.CashRate:n.cashRate=l;break;case a.MDEntryType.RecoveryRate:n.recoveryRate=l;break;case a.MDEntryType.RecoveryRateForLong:n.recoveryRateForLong=l;break;case a.MDEntryType.RecoveryRateForShort:n.recoveryRateForShort=l;break;case a.MDEntryType.MarketBid:n.marketBid=l;break;case a.MDEntryType.MarketOffer:n.marketOffer=l;break;case a.MDEntryType.ShortSaleMinPrice:n.shortSaleMinPrice=l;break;case a.MDEntryType.PreviousClosingPrice:n.previousClosingPrice=l;break;case a.MDEntryType.ThresholdLimitPriceBanding:n.thresholdLimitPriceBanding=l;break;case a.MDEntryType.DailyFinancingValue:n.dailyFinancingValue=l;break;case a.MDEntryType.AccruedFinancingValue:n.accruedFinancingValue=l;break;case a.MDEntryType.TWAP:n.twap=l;break}}n.spread=n.offer-n.bid,i.has(u)||i.set(u,[]);let P=i.get(u);P.push(n),P.length>s&&P.splice(0,P.length-s),d?.(u,n);let O=r.getField(a.Fields.MDReqID)?.value;if(O){let y=e.get(O);y&&(y(r),e.delete(O))}}else if(g===a.Messages.ExecutionReport){let u=r.getField(a.Fields.ClOrdID)?.value,m=e.get(u);m&&(m(r),e.delete(u))}}var f={};function oe(r){if(r.type==="object"){let t={};for(let[e,i]of Object.entries(r.properties||{})){let s=i;s.type==="string"?s.enum?t[e]=h.z.enum(s.enum):t[e]=h.z.string():s.type==="number"?t[e]=h.z.number():s.type==="boolean"?t[e]=h.z.boolean():s.type==="array"?s.items.type==="string"?t[e]=h.z.array(h.z.string()):s.items.type==="number"?t[e]=h.z.array(h.z.number()):s.items.type==="boolean"?t[e]=h.z.array(h.z.boolean()):t[e]=h.z.array(h.z.any()):t[e]=h.z.any()}return t}return{}}var E=class extends j{port;httpServer;mcpServer;serverName;serverVersion;verifiedOrders=new Map;pendingRequests=new Map;marketDataPrices=new Map;MAX_PRICE_HISTORY=1e5;constructor({port:r,logger:t,onReady:e}){super({logger:t,onReady:e}),this.port=r}async register(r){this.parser=r,this.logger=r.logger,this.logger?.log({level:"info",message:`FIXParser (MCP): -- Plugin registered. Creating MCP server on port ${this.port}...`}),this.parser.addOnMessageCallback(t=>{this.parser&&te(t,this.parser,this.pendingRequests,this.marketDataPrices,this.MAX_PRICE_HISTORY)}),this.httpServer=(0,C.createServer)(async(t,e)=>{if(this.logger?.log({level:"info",message:`Incoming request: ${t.method} ${t.url}`}),!t.url||!t.method){this.logger?.log({level:"error",message:"Invalid request: missing URL or method"}),e.writeHead(400),e.end("Bad Request");return}if(t.url==="/mcp"){let i=t.headers["mcp-session-id"];if(this.logger?.log({level:"info",message:`MCP request received. Session ID: ${i||"none"}, headers: ${t.headers}`}),t.method==="POST"){let s=[];t.on("data",d=>{s.push(d)}),t.on("end",async()=>{let d,g=Buffer.concat(s).toString();try{d=JSON.parse(g),this.logger?.log({level:"info",message:`Parsed request body: ${JSON.stringify(d)}`})}catch(m){this.logger?.log({level:"error",message:`Failed to parse JSON body: ${m}`}),e.writeHead(400),e.end(JSON.stringify({error:"Invalid JSON"}));return}let u;if(i&&f[i])this.logger?.log({level:"info",message:`Using existing transport for session: ${i}`}),u=f[i];else if(!i&&t.method==="POST"&&(0,k.isInitializeRequest)(d))this.logger?.log({level:"info",message:"Creating new transport for initialization request"}),u=new M.StreamableHTTPServerTransport({sessionIdGenerator:()=>(0,F.randomUUID)(),onsessioninitialized:m=>{this.logger?.log({level:"info",message:`New session initialized: ${m}`}),f[m]=u}}),u.onclose=()=>{u.sessionId&&(this.logger?.log({level:"info",message:`Session closed: ${u.sessionId}`}),delete f[u.sessionId])},this.mcpServer=new x.McpServer({name:this.serverName||"FIXParser",version:this.serverVersion||"1.0.0"}),this.setupTools(),await this.mcpServer.connect(u);else{this.logger?.log({level:"error",message:"Invalid request: No valid session ID provided"}),e.writeHead(400,{"Content-Type":"application/json"}),e.end(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Bad Request: No valid session ID provided"},id:null}));return}try{await u.handleRequest(t,e,d),this.logger?.log({level:"info",message:"Request handled successfully"})}catch(m){throw this.logger?.log({level:"error",message:`Error handling request: ${m}`}),m}})}else if(t.method==="GET"||t.method==="DELETE"){if(!i||!f[i]){this.logger?.log({level:"error",message:`Invalid session ID for ${t.method} request: ${i}`}),e.writeHead(400),e.end("Invalid or missing session ID");return}let s=f[i];try{await s.handleRequest(t,e),this.logger?.log({level:"info",message:`${t.method} request handled successfully for session: ${i}`})}catch(d){throw this.logger?.log({level:"error",message:`Error handling ${t.method} request: ${d}`}),d}}else this.logger?.log({level:"error",message:`Method not allowed: ${t.method}`}),e.writeHead(405),e.end("Method Not Allowed")}else this.logger?.log({level:"error",message:`Not found: ${t.url}`}),e.writeHead(404),e.end("Not Found")}),this.httpServer.listen(this.port,()=>{this.logger?.log({level:"info",message:`FIXParser (MCP): -- Server listening on http://localhost:${this.port}...`})}),this.onReady&&this.onReady()}setupTools(){if(!this.parser){this.logger?.log({level:"error",message:"FIXParser (MCP): -- FIXParser instance not initialized. Ignoring setup of tools..."});return}if(!this.mcpServer){this.logger?.log({level:"error",message:"FIXParser (MCP): -- MCP Server not initialized. Ignoring setup of tools..."});return}let r=re(this.parser,this.verifiedOrders,this.pendingRequests,this.marketDataPrices);Object.entries(G).forEach(([t,{description:e,schema:i}])=>{this.mcpServer?.registerTool(t,{description:e,inputSchema:oe(i)},async s=>{let d=r[t];if(!d)return{content:[{type:"text",text:`Tool not found: ${t}`}],isError:!0};let g=await d(s);return{content:g.content,isError:g.isError}})})}};var ie=async()=>{await p.LicenseManager.setLicenseKey(process.env.FIXPARSER_LICENSE_KEY);let r=process.env.FIXPARSER_SENDER||"SENDER",t=process.env.FIXPARSER_TARGET||"TARGET",e=new p.FIXParser({plugins:[new E({port:3099,onReady:()=>console.log("ready!")})]}),i=()=>{let d=e.createMessage(new p.Field(p.Fields.MsgType,p.Messages.Logon),new p.Field(p.Fields.MsgSeqNum,e.getNextTargetMsgSeqNum()),new p.Field(p.Fields.SenderCompID,r),new p.Field(p.Fields.SendingTime,e.getTimestamp()),new p.Field(p.Fields.TargetCompID,t),new p.Field(p.Fields.ResetSeqNumFlag,p.ResetSeqNumFlag.Yes),new p.Field(p.Fields.EncryptMethod,p.EncryptMethod.None),new p.Field(p.Fields.HeartBtInt,10)),g=e.parse(d.encode());console.log("sending message",g[0].description,g[0].messageString),e.send(d)},s={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:r,target:t,fixVersion:"FIX.4.4",logging:!0,logOptions:{name:r,level:"info",format:"json",transport:new T({format:"console"})},onOpen:()=>{console.log("Open"),i()},onMessage:d=>console.log("received message",d.description,d.messageString.replace(/\x01/g,"|")),onClose:()=>{console.log("Disconnected")}};e.connect(s)};ie().catch(r=>console.error("Error initializing server:",r));
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}}},oe=(r,t,e)=>async i=>{try{let s=t.get(i.clOrdID);if(!s)return{content:[{type:"text",text:`Error: Order ${i.clOrdID} has not been verified. Please call verifyOrder first.`,uri:"executeOrder"}],isError:!0};if(s.handlInst!==i.handlInst||s.quantity!==Number.parseFloat(String(i.quantity))||s.price!==Number.parseFloat(String(i.price))||s.ordType!==i.ordType||s.side!==i.side||s.symbol!==i.symbol||s.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 c=new Promise(l=>{e.set(i.clOrdID,l)}),m=r.createMessage(new g.Field(g.Fields.MsgType,g.Messages.NewOrderSingle),new g.Field(g.Fields.MsgSeqNum,r.getNextTargetMsgSeqNum()),new g.Field(g.Fields.SenderCompID,r.sender),new g.Field(g.Fields.TargetCompID,r.target),new g.Field(g.Fields.SendingTime,r.getTimestamp()),new g.Field(g.Fields.ClOrdID,i.clOrdID),new g.Field(g.Fields.Side,i.side),new g.Field(g.Fields.Symbol,i.symbol),new g.Field(g.Fields.OrderQty,Number.parseFloat(String(i.quantity))),new g.Field(g.Fields.Price,Number.parseFloat(String(i.price))),new g.Field(g.Fields.OrdType,i.ordType),new g.Field(g.Fields.HandlInst,i.handlInst),new g.Field(g.Fields.TimeInForce,i.timeInForce),new g.Field(g.Fields.TransactTime,r.getTimestamp()));if(!r.connected)return{content:[{type:"text",text:"Error: Not connected. Ignoring message.",uri:"executeOrder"}],isError:!0};r.send(m);let d=await c;return t.delete(i.clOrdID),{content:[{type:"text",text:d.messageType===g.Messages.Reject?`Reject message for order ${i.clOrdID}: ${JSON.stringify(d.toFIXJSON())}`:`Execution Report for order ${i.clOrdID}: ${JSON.stringify(d.toFIXJSON())}`,uri:"executeOrder"}]}}catch(s){return{content:[{type:"text",text:`Error: ${s instanceof Error?s.message:"Failed to execute order"}`,uri:"executeOrder"}],isError:!0}}},ne=r=>async t=>{try{let e=r.parse(t.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}}},ae=r=>async t=>{try{let e=r.parse(t.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}}},ce=(r,t,e,i)=>({parse:ne(r),parseToJSON:ae(r),verifyOrder:ie(r,t),executeOrder:oe(r,t,e),marketDataRequest:K(r,e),getStockGraph:Y(i),getStockPriceHistory:Z(i),technicalAnalysis:Q(i)});function le(r,t){return r[t]||t}function ue(r,t,e,i,s,c){let m=r.messageType;if(m===a.Messages.MarketDataSnapshotFullRefresh||m===a.Messages.MarketDataIncrementalRefresh){let d=r.getField(a.Fields.Symbol)?.value,h=r.toFIXJSON().Body?.NoMDEntries||[],n={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 h){let b=S.MDEntryType,u=S.MDEntryPx?Number.parseFloat(S.MDEntryPx):0,y=S.MDEntrySize?Number.parseFloat(S.MDEntrySize):0;switch(le(a.MDEntryType,b)){case a.MDEntryType.Bid:n.bid=u;break;case a.MDEntryType.Offer:n.offer=u;break;case a.MDEntryType.Trade:n.trade=u;break;case a.MDEntryType.IndexValue:n.indexValue=u;break;case a.MDEntryType.OpeningPrice:n.openingPrice=u;break;case a.MDEntryType.ClosingPrice:n.closingPrice=u;break;case a.MDEntryType.SettlementPrice:n.settlementPrice=u;break;case a.MDEntryType.TradingSessionHighPrice:n.tradingSessionHighPrice=u;break;case a.MDEntryType.TradingSessionLowPrice:n.tradingSessionLowPrice=u;break;case a.MDEntryType.VWAP:n.vwap=u;break;case a.MDEntryType.Imbalance:n.imbalance=y;break;case a.MDEntryType.TradeVolume:n.volume=y;break;case a.MDEntryType.OpenInterest:n.openInterest=y;break;case a.MDEntryType.CompositeUnderlyingPrice:n.compositeUnderlyingPrice=u;break;case a.MDEntryType.SimulatedSellPrice:n.simulatedSellPrice=u;break;case a.MDEntryType.SimulatedBuyPrice:n.simulatedBuyPrice=u;break;case a.MDEntryType.MarginRate:n.marginRate=u;break;case a.MDEntryType.MidPrice:n.midPrice=u;break;case a.MDEntryType.EmptyBook:n.emptyBook=1;break;case a.MDEntryType.SettleHighPrice:n.settleHighPrice=u;break;case a.MDEntryType.SettleLowPrice:n.settleLowPrice=u;break;case a.MDEntryType.PriorSettlePrice:n.priorSettlePrice=u;break;case a.MDEntryType.SessionHighBid:n.sessionHighBid=u;break;case a.MDEntryType.SessionLowOffer:n.sessionLowOffer=u;break;case a.MDEntryType.EarlyPrices:n.earlyPrices=u;break;case a.MDEntryType.AuctionClearingPrice:n.auctionClearingPrice=u;break;case a.MDEntryType.SwapValueFactor:n.swapValueFactor=u;break;case a.MDEntryType.DailyValueAdjustmentForLongPositions:n.dailyValueAdjustmentForLongPositions=u;break;case a.MDEntryType.CumulativeValueAdjustmentForLongPositions:n.cumulativeValueAdjustmentForLongPositions=u;break;case a.MDEntryType.DailyValueAdjustmentForShortPositions:n.dailyValueAdjustmentForShortPositions=u;break;case a.MDEntryType.CumulativeValueAdjustmentForShortPositions:n.cumulativeValueAdjustmentForShortPositions=u;break;case a.MDEntryType.FixingPrice:n.fixingPrice=u;break;case a.MDEntryType.CashRate:n.cashRate=u;break;case a.MDEntryType.RecoveryRate:n.recoveryRate=u;break;case a.MDEntryType.RecoveryRateForLong:n.recoveryRateForLong=u;break;case a.MDEntryType.RecoveryRateForShort:n.recoveryRateForShort=u;break;case a.MDEntryType.MarketBid:n.marketBid=u;break;case a.MDEntryType.MarketOffer:n.marketOffer=u;break;case a.MDEntryType.ShortSaleMinPrice:n.shortSaleMinPrice=u;break;case a.MDEntryType.PreviousClosingPrice:n.previousClosingPrice=u;break;case a.MDEntryType.ThresholdLimitPriceBanding:n.thresholdLimitPriceBanding=u;break;case a.MDEntryType.DailyFinancingValue:n.dailyFinancingValue=u;break;case a.MDEntryType.AccruedFinancingValue:n.accruedFinancingValue=u;break;case a.MDEntryType.TWAP:n.twap=u;break}}n.spread=n.offer-n.bid,i.has(d)||i.set(d,[]);let f=i.get(d);f.push(n),f.length>s&&f.splice(0,f.length-s),c?.(d,n);let v=r.getField(a.Fields.MDReqID)?.value;if(v){let S=e.get(v);S&&(S(r),e.delete(v))}}else if(m===a.Messages.ExecutionReport){let d=r.getField(a.Fields.ClOrdID)?.value,l=e.get(d);l&&(l(r),e.delete(d))}}var O={};function de(r){if(r.type==="object"){let t={};for(let[e,i]of Object.entries(r.properties||{})){let s=i;s.type==="string"?s.enum?t[e]=P.z.enum(s.enum):t[e]=P.z.string():s.type==="number"?t[e]=P.z.number():s.type==="boolean"?t[e]=P.z.boolean():s.type==="array"?s.items.type==="string"?t[e]=P.z.array(P.z.string()):s.items.type==="number"?t[e]=P.z.array(P.z.number()):s.items.type==="boolean"?t[e]=P.z.array(P.z.boolean()):t[e]=P.z.array(P.z.any()):t[e]=P.z.any()}return t}return{}}var L=class extends X{port;httpServer;mcpServer;serverName;serverVersion;verifiedOrders=new Map;pendingRequests=new Map;marketDataPrices=new Map;MAX_PRICE_HISTORY=1e5;constructor({port:r,logger:t,onReady:e}){super({logger:t,onReady:e}),this.port=r}async register(r){this.parser=r,this.logger=r.logger,this.logger?.log({level:"info",message:`FIXParser (MCP): -- Plugin registered. Creating MCP server on port ${this.port}...`}),this.parser.addOnMessageCallback(t=>{this.parser&&ue(t,this.parser,this.pendingRequests,this.marketDataPrices,this.MAX_PRICE_HISTORY)}),this.httpServer=(0,C.createServer)(async(t,e)=>{if(!t.url||!t.method){e.writeHead(400),e.end("Bad Request");return}if(t.url==="/mcp"){let i=t.headers["mcp-session-id"];if(t.method==="POST"){let s=[];t.on("data",c=>{s.push(c)}),t.on("end",async()=>{let c,m=Buffer.concat(s).toString();try{c=JSON.parse(m)}catch{e.writeHead(400),e.end(JSON.stringify({error:"Invalid JSON"}));return}let d;if(i&&O[i])d=O[i];else if(!i&&t.method==="POST"&&(0,E.isInitializeRequest)(c))d=new k.StreamableHTTPServerTransport({sessionIdGenerator:()=>(0,x.randomUUID)(),onsessioninitialized:l=>{O[l]=d}}),d.onclose=()=>{d.sessionId&&delete O[d.sessionId]},this.mcpServer=new A.McpServer({name:this.serverName||"FIXParser",version:this.serverVersion||"1.0.0"}),this.setupTools(),await this.mcpServer.connect(d);else{e.writeHead(400,{"Content-Type":"application/json"}),e.end(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Bad Request: No valid session ID provided"},id:null}));return}try{await d.handleRequest(t,e,c)}catch(l){throw this.logger?.log({level:"error",message:`Error handling request: ${l}`}),l}})}else if(t.method==="GET"||t.method==="DELETE"){if(!i||!O[i]){e.writeHead(400),e.end("Invalid or missing session ID");return}let s=O[i];try{await s.handleRequest(t,e)}catch(c){throw this.logger?.log({level:"error",message:`Error handling ${t.method} request: ${c}`}),c}}else this.logger?.log({level:"error",message:`Method not allowed: ${t.method}`}),e.writeHead(405),e.end("Method Not Allowed")}else e.writeHead(404),e.end("Not Found")}),this.httpServer.listen(this.port,()=>{this.logger?.log({level:"info",message:`FIXParser (MCP): -- Server listening on http://localhost:${this.port}...`})}),this.onReady&&this.onReady()}setupTools(){if(!this.parser){this.logger?.log({level:"error",message:"FIXParser (MCP): -- FIXParser instance not initialized. Ignoring setup of tools..."});return}if(!this.mcpServer){this.logger?.log({level:"error",message:"FIXParser (MCP): -- MCP Server not initialized. Ignoring setup of tools..."});return}let r=ce(this.parser,this.verifiedOrders,this.pendingRequests,this.marketDataPrices);Object.entries(U).forEach(([t,{description:e,schema:i}])=>{this.mcpServer?.registerTool(t,{description:e,inputSchema:de(i)},async s=>{let c=r[t];if(!c)return{content:[{type:"text",text:`Tool not found: ${t}`}],isError:!0};let m=await c(s);return{content:m.content,isError:m.isError}})})}};var me=async()=>{await p.LicenseManager.setLicenseKey(process.env.FIXPARSER_LICENSE_KEY);let r=process.env.FIXPARSER_SENDER||"SENDER",t=process.env.FIXPARSER_TARGET||"TARGET",e=new p.FIXParser({plugins:[new L({port:3099,onReady:()=>console.log("ready!")})]}),i=()=>{let c=e.createMessage(new p.Field(p.Fields.MsgType,p.Messages.Logon),new p.Field(p.Fields.MsgSeqNum,e.getNextTargetMsgSeqNum()),new p.Field(p.Fields.SenderCompID,r),new p.Field(p.Fields.SendingTime,e.getTimestamp()),new p.Field(p.Fields.TargetCompID,t),new p.Field(p.Fields.ResetSeqNumFlag,p.ResetSeqNumFlag.Yes),new p.Field(p.Fields.EncryptMethod,p.EncryptMethod.None),new p.Field(p.Fields.HeartBtInt,10)),m=e.parse(c.encode());console.log("sending message",m[0].description,m[0].messageString),e.send(c)},s={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:r,target:t,fixVersion:"FIX.4.4",logging:!0,logOptions:{name:r,level:"info",format:"json",transport:new R({format:"console"})},onOpen:()=>{console.log("Open"),i()},onMessage:c=>console.log("received message",c.description,c.messageString.replace(/\x01/g,"|")),onClose:()=>{console.log("Disconnected")}};e.connect(s)};me().catch(r=>console.error("Error initializing server:",r));
16
18
  //# sourceMappingURL=example_mcp_remote.js.map