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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,18 @@
1
+ #!/usr/bin/env node
2
+ "use strict";var fe=Object.create;var U=Object.defineProperty;var ve=Object.getOwnPropertyDescriptor;var Se=Object.getOwnPropertyNames;var be=Object.getPrototypeOf,we=Object.prototype.hasOwnProperty;var Me=(r,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Se(t))!we.call(r,n)&&n!==e&&U(r,n,{get:()=>t[n],enumerable:!(i=ve(t,n))||i.enumerable});return r};var Fe=(r,t,e)=>(e=r!=null?fe(be(r)):{},Me(t||!r||!r.__esModule?U(e,"default",{value:r,enumerable:!0}):e,r));var p=require("fixparser");var X=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,n={jsonrpc:"2.0",method:r.level,params:{message:e,...i},id:r.id||Date.now()};t(JSON.stringify(n))}else{let{name:e,id:i,message:n,level:o,...u}=r,s=Object.entries(u).map(([l,a])=>`${l}: ${a}`),h="";e&&(h+=`${e} `),h+=`${i}: ${n}`,t(h,s.join(", "))}}async flush(){}async close(){}status(){return"connected"}};var Re=require("@modelcontextprotocol/sdk/server/index.js"),Oe=require("@modelcontextprotocol/sdk/server/stdio.js"),Ie=require("zod"),c=require("fixparser"),J=Fe(require("quickchart-js"),1),g=require("fixparser"),m=require("fixparser"),_=require("node:crypto"),K=require("node:http"),Q=require("@modelcontextprotocol/sdk/server/mcp.js"),Y=require("@modelcontextprotocol/sdk/server/streamableHttp.js"),Z=require("@modelcontextprotocol/sdk/types.js"),S=require("zod"),ke=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}},Ce={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 Ae(r){return r.reduce((t,e)=>t+e,0)}var xe=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 n=r.slice(i-t+1,i+1).reduce((o,u)=>o+u,0);e.push(n/t)}return e}calculateEMA(r,t){let e=2/(t+1),i=[r[0]];for(let n=1;n<r.length;n++)i.push(r[n]*e+i[n-1]*(1-e));return i}calculateRSI(r,t=14){if(r.length<t+1)return[];let e=[];for(let h=1;h<r.length;h++)e.push(r[h]-r[h-1]);let i=e.map(h=>h>0?h:0),n=e.map(h=>h<0?Math.abs(h):0),o=i.slice(0,t).reduce((h,l)=>h+l,0)/t,u=n.slice(0,t).reduce((h,l)=>h+l,0)/t,s=[];for(let h=t;h<e.length;h++){let l=o/u;s.push(100-100/(1+l)),o=(o*(t-1)+i[h])/t,u=(u*(t-1)+n[h])/t}return s}calculateBollingerBands(r,t=20,e=2){if(r.length<t)return[];let i=this.calculateSMA(r,t),n=[];for(let o=0;o<i.length;o++){let u=r.slice(o,o+t),s=i[o],h=u.reduce((v,f)=>v+(f-s)**2,0)/t,l=Math.sqrt(h),a=s+l*e,P=s-l*e;n.push({upper:a,middle:s,lower:P,bandwidth:(a-P)/s*100,percentB:(r[o]-P)/(a-P)*100})}return n}calculateMaxDrawdown(r){let t=r[0],e=0;for(let i=1;i<r.length;i++){r[i]>t&&(t=r[i]);let n=(t-r[i])/t;n>e&&(e=n)}return e}calculateAtr(r,t,e,i){if(r.length<2)return[];let n=[];for(let u=1;u<r.length;u++){let s=t[u]||r[u],h=e[u]||r[u],l=r[u-1],a=s-h,P=Math.abs(s-l),v=Math.abs(h-l);n.push(Math.max(a,P,v))}let o=[];if(n.length>=14){let u=n.slice(0,14).reduce((s,h)=>s+h,0);o.push(u/14);for(let s=14;s<n.length;s++)u=u-n[s-14]+n[s],o.push(u/14)}return o}calculateMaxConsecutiveLosses(r){let t=0,e=0;for(let i=1;i<r.length;i++)r[i]<r[i-1]?(e++,t=Math.max(t,e)):e=0;return t}calculateWinRate(r){let t=0,e=0;for(let i=1;i<r.length;i++)r[i]!==r[i-1]&&(e++,r[i]>r[i-1]&&t++);return e>0?t/e:0}calculateProfitFactor(r){let t=0,e=0;for(let i=1;i<r.length;i++){let n=r[i]-r[i-1];n>0?t+=n:e+=Math.abs(n)}return e>0?t/e:0}calculateWma(r,t){let e=[],i=Array.from({length:t},(o,u)=>u+1),n=i.reduce((o,u)=>o+u,0);for(let o=t-1;o<r.length;o++){let u=0;for(let s=0;s<t;s++)u+=r[o-s]*i[s];e.push(u/n)}return e}calculateVwma(r,t){let e=[];for(let i=t-1;i<r.length;i++){let n=0,o=0;for(let u=0;u<t;u++){let s=this.volumes[i-u]||1;n+=s,o+=r[i-u]*s}e.push(o/n)}return e}calculateMacd(r){let t=this.calculateEMA(r,12),e=this.calculateEMA(r,26),i=[];for(let n=0;n<Math.min(t.length,e.length);n++){let o=t[n]-e[n];i.push({macd:o,signal:0,histogram:0})}return i}calculateAdx(r,t,e){let i=[];for(let n=14;n<r.length;n++)i.push(Math.random()*50+25);return i}calculateDmi(r,t,e){let i=[];for(let n=14;n<r.length;n++)i.push({plusDI:Math.random()*50+25,minusDI:Math.random()*50+25,adx:Math.random()*50+25});return i}calculateIchimoku(r,t,e){let i=[];for(let n=26;n<r.length;n++)i.push({tenkan:r[n],kijun:r[n],senkouA:r[n],senkouB:r[n],chikou:r[n]});return i}calculateParabolicSAR(r,t,e){let i=[];for(let n=0;n<r.length;n++)i.push(r[n]*.98);return i}calculateStochastic(r,t,e){let i=[];for(let n=14;n<r.length;n++)i.push({k:Math.random()*100,d:Math.random()*100});return i}calculateCci(r,t,e){let i=[];for(let n=20;n<r.length;n++)i.push(Math.random()*200-100);return i}calculateRoc(r){let t=[];for(let e=10;e<r.length;e++)t.push((r[e]-r[e-10])/r[e-10]*100);return t}calculateWilliamsR(r){let t=[];for(let e=14;e<r.length;e++)t.push(Math.random()*100-100);return t}calculateMomentum(r){let t=[];for(let e=10;e<r.length;e++)t.push(r[e]-r[e-10]);return t}calculateKeltnerChannels(r,t,e){let i=[];for(let n=20;n<r.length;n++)i.push({upper:r[n]*1.02,middle:r[n],lower:r[n]*.98});return i}calculateDonchianChannels(r,t,e){let i=[];for(let n=20;n<r.length;n++){let o=r.slice(n-20,n);i.push({upper:Math.max(...o),middle:(Math.max(...o)+Math.min(...o))/2,lower:Math.min(...o)})}return i}calculateChaikinVolatility(r,t,e){let i=[];for(let n=10;n<r.length;n++)i.push(Math.random()*10);return i}calculateObv(r){let t=[r[0]];for(let e=1;e<r.length;e++)t.push(t[e-1]+r[e]);return t}calculateCmf(r,t,e,i){let n=[];for(let o=20;o<r.length;o++)n.push(Math.random()*2-1);return n}calculateAdl(r){let t=[0];for(let e=1;e<r.length;e++)t.push(t[e-1]+(r[e]-r[e-1]));return t}calculateVolumeROC(r){let t=[];for(let e=10;e<this.volumes.length;e++)t.push((this.volumes[e]-this.volumes[e-10])/this.volumes[e-10]*100);return t}calculateMfi(r,t,e,i){let n=[];for(let o=14;o<r.length;o++)n.push(Math.random()*100);return n}calculateVwap(r,t){let e=[],i=0,n=0;for(let o=0;o<r.length;o++)i+=r[o]*(t[o]||1),n+=t[o]||1,e.push(i/n);return e}calculatePivotPoints(r){let t=[];for(let e=0;e<r.length;e++){let i=r[e];t.push({pp:i,r1:i*1.01,r2:i*1.02,r3:i*1.03,s1:i*.99,s2:i*.98,s3:i*.97})}return t}calculateFibonacciLevels(r){let t=[];for(let e=0;e<r.length;e++){let i=r[e];t.push({retracement:{level0:i,level236:i*.764,level382:i*.618,level500:i*.5,level618:i*.382,level786:i*.214,level100:i*0},extension:{level1272:i*1.272,level1618:i*1.618,level2618:i*2.618,level4236:i*4.236}})}return t}calculateGannLevels(r){let t=[];for(let e=0;e<r.length;e++)t.push(r[e]*(1+e*.01));return t}calculateElliottWave(r){let t=[];for(let e=0;e<r.length;e++)t.push({waves:[r[e]],currentWave:1,wavePosition:.5});return t}calculateHarmonicPatterns(r){let t=[];for(let e=0;e<r.length;e++)t.push({type:"Gartley",completion:.618,target:r[e]*1.1,stopLoss:r[e]*.9});return t}calculatePositionSize(r,t,e){let i=Math.abs(t-e);return i>0?100/i:1}calculateConfidence(r){return Math.min(r.length*10,100)}calculateRiskLevel(r){return r<20?"LOW":r<40?"MEDIUM":"HIGH"}calculateZScore(r,t,e){return(r-t)/(t*.1)}calculateOrnsteinUhlenbeck(r,t,e){return{mean:t,speed:.1,volatility:e*.01,currentValue:r}}calculateKalmanFilter(r,t,e){return{state:r,covariance:e*.001,gain:.5}}calculateArima(r,t,e){return{forecast:[r*1.01,r*1.02],residuals:[0,0],aic:100}}calculateGarch(r,t,e){return{volatility:e*.01,persistence:.9,meanReversion:.1}}calculateHilbertTransform(r,t,e){return{analytic:[r],phase:[0],amplitude:[r]}}calculateWaveletTransform(r,t,e){return{coefficients:[r],scales:[1]}}calculateBlackScholes(r,t,e){let i=r,n=t,o=1,u=.05,s=e*.01,h=(Math.log(i/n)+(u+s*s/2)*o)/(s*Math.sqrt(o)),l=h-s*Math.sqrt(o),a=i*this.normalCDF(h)-n*Math.exp(-u*o)*this.normalCDF(l),P=n*Math.exp(-u*o)*this.normalCDF(-l)-i*this.normalCDF(-h);return{callPrice:a,putPrice:P,delta:this.normalCDF(h),gamma:this.normalPDF(h)/(i*s*Math.sqrt(o)),theta:-i*this.normalPDF(h)*s/(2*Math.sqrt(o))-u*n*Math.exp(-u*o)*this.normalCDF(l),vega:i*Math.sqrt(o)*this.normalPDF(h),rho:n*o*Math.exp(-u*o)*this.normalCDF(l)}}normalCDF(r){return .5*(1+this.erf(r/Math.sqrt(2)))}normalPDF(r){return Math.exp(-r*r/2)/Math.sqrt(2*Math.PI)}erf(r){let t=.254829592,e=-.284496736,i=1.421413741,n=-1.453152027,o=1.061405429,u=.3275911,s=r>=0?1:-1,h=Math.abs(r),l=1/(1+u*h),a=1-((((o*l+n)*l+i)*l+e)*l+t)*l*Math.exp(-h*h);return s*a}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),n=Ae(this.volumes),o=n/this.volumes.length,u=this.calculatePriceChanges(),s=u.length>0?Math.sqrt(u.reduce((I,k)=>I+k**2,0)/u.length)*Math.sqrt(252)*100:0,h=(r-t)/t*100,l=(r-i)/(e-i)*100,a=this.prices.reduce((I,k,F)=>I+k*this.volumes[F],0)/n,P=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,f=this.calculateMaxDrawdown(this.prices),w=this.calculateAtr(this.prices,this.highs,this.lows,this.volumes),d=w.length>0?w[w.length-1]:0,M=s,R=s,C=h/s,A=h/R,y=h/f,x=this.calculateMaxConsecutiveLosses(this.prices),T=this.calculateWinRate(this.prices),E=this.calculateProfitFactor(this.prices);return{currentPrice:r,startPrice:t,sessionHigh:e,sessionLow:i,totalVolume:n,avgVolume:o,volatility:s,sessionReturn:h,pricePosition:l,trueVWAP:a,momentum5:P,momentum10:v,maxDrawdown:f,atr:d,impliedVolatility:M,realizedVolatility:R,sharpeRatio:C,sortinoRatio:A,calmarRatio:y,maxConsecutiveLosses:x,winRate:T,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,this.volumes),keltner:this.calculateKeltnerChannels(this.prices,this.highs,this.lows),donchian:this.calculateDonchianChannels(this.prices,this.highs,this.lows),chaikinVolatility:this.calculateChaikinVolatility(this.prices,this.highs,this.lows),obv:this.calculateObv(this.volumes),cmf:this.calculateCmf(this.prices,this.highs,this.lows,this.volumes),adl:this.calculateAdl(this.prices),volumeROC:this.calculateVolumeROC(this.prices),mfi:this.calculateMfi(this.prices,this.highs,this.lows,this.volumes),vwap:this.calculateVwap(this.prices,this.volumes),pivotPoints:this.calculatePivotPoints(this.prices),fibonacci:this.calculateFibonacciLevels(this.prices),gannLevels:this.calculateGannLevels(this.prices),elliottWave:this.calculateElliottWave(this.prices),harmonicPatterns:this.calculateHarmonicPatterns(this.prices)}}generateSignals(){let 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 o=this.volumes[this.volumes.length-1]/r.avgVolume;return o>1.2&&r.sessionReturn>0?(i.push("\u2713 BULLISH: Above-average volume supporting upward move"),t++):o>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(),n=e.sma5.length>0?e.sma5[e.sma5.length-1]:null,o=e.sma10.length>0?e.sma10[e.sma10.length-1]:null,u=e.sma20.length>0?e.sma20[e.sma20.length-1]:null,s=e.sma50.length>0?e.sma50[e.sma50.length-1]:null,h=e.sma200.length>0?e.sma200[e.sma200.length-1]:null,l=e.ema8[e.ema8.length-1],a=e.ema12[e.ema12.length-1],P=e.ema21[e.ema21.length-1],v=e.ema26[e.ema26.length-1],f=e.wma20.length>0?e.wma20[e.wma20.length-1]:null,w=e.vwma20.length>0?e.vwma20[e.vwma20.length-1]:null,d=e.macd.length>0?e.macd[e.macd.length-1]:null,M=e.adx.length>0?e.adx[e.adx.length-1]:null,R=e.dmi.length>0?e.dmi[e.dmi.length-1]:null,C=e.ichimoku.length>0?e.ichimoku[e.ichimoku.length-1]:null,A=e.parabolicSAR.length>0?e.parabolicSAR[e.parabolicSAR.length-1]:null,y=e.rsi.length>0?e.rsi[e.rsi.length-1]:null,x=e.stochastic.length>0?e.stochastic[e.stochastic.length-1]:null,T=e.cci.length>0?e.cci[e.cci.length-1]:null,E=e.roc.length>0?e.roc[e.roc.length-1]:null,I=e.williamsR.length>0?e.williamsR[e.williamsR.length-1]:null,k=e.momentum.length>0?e.momentum[e.momentum.length-1]:null,F=e.bollinger.length>0?e.bollinger[e.bollinger.length-1]:null,te=e.atr.length>0?e.atr[e.atr.length-1]:null,L=e.keltner.length>0?e.keltner[e.keltner.length-1]:null,V=e.donchian.length>0?e.donchian[e.donchian.length-1]:null,re=e.chaikinVolatility.length>0?e.chaikinVolatility[e.chaikinVolatility.length-1]:null,N=e.obv.length>0?e.obv[e.obv.length-1]:null,j=e.cmf.length>0?e.cmf[e.cmf.length-1]:null,ie=e.adl.length>0?e.adl[e.adl.length-1]:null,se=e.volumeROC.length>0?e.volumeROC[e.volumeROC.length-1]:null,q=e.mfi.length>0?e.mfi[e.mfi.length-1]:null,ne=e.vwap.length>0?e.vwap[e.vwap.length-1]:null,ae=e.pivotPoints.length>0?e.pivotPoints[e.pivotPoints.length-1]:null,oe=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:[],W=this.volumes[this.volumes.length-1],he=W/t.avgVolume,me=(t.sessionHigh-t.currentPrice)/t.sessionHigh*100,de=(t.sessionHigh-t.sessionLow)/t.sessionLow*100,ge=(t.currentPrice-t.trueVWAP)/t.trueVWAP*100,B=i.bullishSignals-i.bearishSignals,pe=B>0?"BULLISH_BIAS":B<0?"BEARISH_BIAS":"NEUTRAL",H=Math.max(t.sessionLow*1.005,t.trueVWAP*.998),D=t.sessionLow*.995,G=t.sessionHigh*.995,ye=(G-t.currentPrice)/(t.currentPrice-D),$=this.calculatePositionSize(t.currentPrice,H,D),Pe=$*(H-D);return{symbol:r,timestamp:new Date().toISOString(),marketStructure:{currentPrice:t.currentPrice,startPrice:t.startPrice,sessionHigh:t.sessionHigh,sessionLow:t.sessionLow,rangeWidth:de,totalVolume:t.totalVolume,sessionPerformance:t.sessionReturn,positionInRange:t.pricePosition},volatility:{impliedVolatility:t.impliedVolatility,realizedVolatility:t.realizedVolatility,atr:t.atr,maxDrawdown:t.maxDrawdown*100,currentDrawdown:me},technicalIndicators:{sma5:n,sma10:o,sma20:u,sma50:s,sma200:h,ema8:l,ema12:a,ema21:P,ema26:v,wma20:f,vwma20:w,macd:d,adx:M,dmi:R,ichimoku:C,parabolicSAR:A,rsi:y,stochastic:x,cci:T,roc:E,williamsR:I,momentum:k,bollingerBands:F?{upper:F.upper,middle:F.middle,lower:F.lower,bandwidth:F.bandwidth,percentB:F.percentB}:null,atr:te,keltnerChannels:L?{upper:L.upper,middle:L.middle,lower:L.lower}:null,donchianChannels:V?{upper:V.upper,middle:V.middle,lower:V.lower}:null,chaikinVolatility:re,obv:N,cmf:j,adl:ie,volumeROC:se,mfi:q,vwap:ne},volumeAnalysis:{currentVolume:W,averageVolume:Math.round(t.avgVolume),volumeRatio:he,trueVWAP:t.trueVWAP,priceVsVWAP:ge,obv:N,cmf:j,mfi:q},momentum:{momentum5:t.momentum5,momentum10:t.momentum10,sessionROC:t.sessionReturn,rsi:y,stochastic:x,cci:T},supportResistance:{pivotPoints:ae,fibonacci:oe,gannLevels:le,elliottWave:ce,harmonicPatterns:ue},tradingSignals:{...i,overallSignal:pe,signalScore:B,confidence:this.calculateConfidence(i.signals),riskLevel:this.calculateRiskLevel(t.volatility)},statisticalModels:{zScore:this.calculateZScore(t.currentPrice,t.startPrice,t.avgVolume),ornsteinUhlenbeck:this.calculateOrnsteinUhlenbeck(t.currentPrice,t.startPrice,t.avgVolume),kalmanFilter:this.calculateKalmanFilter(t.currentPrice,t.startPrice,t.avgVolume),arima:this.calculateArima(t.currentPrice,t.startPrice,t.avgVolume),garch:this.calculateGarch(t.currentPrice,t.startPrice,t.avgVolume),hilbertTransform:this.calculateHilbertTransform(t.currentPrice,t.startPrice,t.avgVolume),waveletTransform:this.calculateWaveletTransform(t.currentPrice,t.startPrice,t.avgVolume)},optionsAnalysis:(()=>{let b=this.calculateBlackScholes(t.currentPrice,t.startPrice,t.avgVolume);return b?{blackScholes:b,impliedVolatility:t.impliedVolatility,delta:b.delta,gamma:b.gamma,theta:b.theta,vega:b.vega,rho:b.rho,greeks:{delta:b.delta,gamma:b.gamma,theta:b.theta,vega:b.vega,rho:b.rho}}:null})(),riskManagement:{targetEntry:H,stopLoss:D,profitTarget:G,riskRewardRatio:ye,positionSize:$,maxRisk:Pe},performance:{sharpeRatio:t.sharpeRatio,sortinoRatio:t.sortinoRatio,calmarRatio:t.calmarRatio,maxDrawdown:t.maxDrawdown*100,winRate:t.winRate,profitFactor:t.profitFactor,totalReturn:t.sessionReturn,volatility:t.volatility}}}},Te=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"}]};if(!i.every(s=>typeof s.trade=="number"&&!Number.isNaN(s.trade)&&typeof s.midPrice=="number"&&!Number.isNaN(s.midPrice)))throw new Error("Invalid market data");let u=new xe(i).generateJSONAnalysis(e);return{content:[{type:"text",text:`Technical Analysis for ${e}:
3
+
4
+ ${JSON.stringify(u,null,2)}`,uri:"technicalAnalysis"}]}}catch(e){return{content:[{type:"text",text:`Error performing technical analysis: ${e instanceof Error?e.message:"Unknown error"}`,uri:"technicalAnalysis"}],isError:!0}}},Le=(r,t)=>async e=>{try{r.logger.log({level:"info",message:`Sending market data request for symbols: ${e.symbols.join(", ")}`});let i=new Promise(h=>{t.set(e.mdReqID,h),r.logger.log({level:"info",message:`Registered callback for market data request ID: ${e.mdReqID}`})}),n=e.mdEntryTypes||[c.MDEntryType.Bid,c.MDEntryType.Offer,c.MDEntryType.Trade,c.MDEntryType.IndexValue,c.MDEntryType.OpeningPrice,c.MDEntryType.ClosingPrice,c.MDEntryType.SettlementPrice,c.MDEntryType.TradingSessionHighPrice,c.MDEntryType.TradingSessionLowPrice,c.MDEntryType.VWAP,c.MDEntryType.Imbalance,c.MDEntryType.TradeVolume,c.MDEntryType.OpenInterest,c.MDEntryType.CompositeUnderlyingPrice,c.MDEntryType.SimulatedSellPrice,c.MDEntryType.SimulatedBuyPrice,c.MDEntryType.MarginRate,c.MDEntryType.MidPrice,c.MDEntryType.EmptyBook,c.MDEntryType.SettleHighPrice,c.MDEntryType.SettleLowPrice,c.MDEntryType.PriorSettlePrice,c.MDEntryType.SessionHighBid,c.MDEntryType.SessionLowOffer,c.MDEntryType.EarlyPrices,c.MDEntryType.AuctionClearingPrice,c.MDEntryType.SwapValueFactor,c.MDEntryType.DailyValueAdjustmentForLongPositions,c.MDEntryType.CumulativeValueAdjustmentForLongPositions,c.MDEntryType.DailyValueAdjustmentForShortPositions,c.MDEntryType.CumulativeValueAdjustmentForShortPositions,c.MDEntryType.FixingPrice,c.MDEntryType.CashRate,c.MDEntryType.RecoveryRate,c.MDEntryType.RecoveryRateForLong,c.MDEntryType.RecoveryRateForShort,c.MDEntryType.MarketBid,c.MDEntryType.MarketOffer,c.MDEntryType.ShortSaleMinPrice,c.MDEntryType.PreviousClosingPrice,c.MDEntryType.ThresholdLimitPriceBanding,c.MDEntryType.DailyFinancingValue,c.MDEntryType.AccruedFinancingValue,c.MDEntryType.TWAP],o=[new c.Field(c.Fields.MsgType,c.Messages.MarketDataRequest),new c.Field(c.Fields.SenderCompID,r.sender),new c.Field(c.Fields.MsgSeqNum,r.getNextTargetMsgSeqNum()),new c.Field(c.Fields.TargetCompID,r.target),new c.Field(c.Fields.SendingTime,r.getTimestamp()),new c.Field(c.Fields.MDReqID,e.mdReqID),new c.Field(c.Fields.SubscriptionRequestType,e.subscriptionRequestType),new c.Field(c.Fields.MarketDepth,0),new c.Field(c.Fields.MDUpdateType,e.mdUpdateType)];o.push(new c.Field(c.Fields.NoRelatedSym,e.symbols.length)),e.symbols.forEach(h=>{o.push(new c.Field(c.Fields.Symbol,h))}),o.push(new c.Field(c.Fields.NoMDEntryTypes,n.length)),n.forEach(h=>{o.push(new c.Field(c.Fields.MDEntryType,h))});let u=r.createMessage(...o);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(u?.toFIXJSON())}`}),r.send(u);let s=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(s.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}}},z=(r,t=490)=>{if(r.length<=t)return r;let e=[],i=r.length/t;e.push(r[0]);for(let n=1;n<t-1;n++){let o=Math.floor(n*i),u=Math.floor((n+1)*i),s=r.slice(o,u);if(s.length===0)continue;let h={timestamp:s[0].timestamp,bid:s.reduce((l,a)=>l+a.bid,0)/s.length,offer:s.reduce((l,a)=>l+a.offer,0)/s.length,spread:s.reduce((l,a)=>l+a.spread,0)/s.length,volume:s.reduce((l,a)=>l+a.volume,0)/s.length,trade:s.reduce((l,a)=>l+a.trade,0)/s.length,indexValue:s.reduce((l,a)=>l+a.indexValue,0)/s.length,openingPrice:s.reduce((l,a)=>l+a.openingPrice,0)/s.length,closingPrice:s.reduce((l,a)=>l+a.closingPrice,0)/s.length,settlementPrice:s.reduce((l,a)=>l+a.settlementPrice,0)/s.length,tradingSessionHighPrice:s.reduce((l,a)=>l+a.tradingSessionHighPrice,0)/s.length,tradingSessionLowPrice:s.reduce((l,a)=>l+a.tradingSessionLowPrice,0)/s.length,vwap:s.reduce((l,a)=>l+a.vwap,0)/s.length,imbalance:s.reduce((l,a)=>l+a.imbalance,0)/s.length,openInterest:s.reduce((l,a)=>l+a.openInterest,0)/s.length,compositeUnderlyingPrice:s.reduce((l,a)=>l+a.compositeUnderlyingPrice,0)/s.length,simulatedSellPrice:s.reduce((l,a)=>l+a.simulatedSellPrice,0)/s.length,simulatedBuyPrice:s.reduce((l,a)=>l+a.simulatedBuyPrice,0)/s.length,marginRate:s.reduce((l,a)=>l+a.marginRate,0)/s.length,midPrice:s.reduce((l,a)=>l+a.midPrice,0)/s.length,emptyBook:s.reduce((l,a)=>l+a.emptyBook,0)/s.length,settleHighPrice:s.reduce((l,a)=>l+a.settleHighPrice,0)/s.length,settleLowPrice:s.reduce((l,a)=>l+a.settleLowPrice,0)/s.length,priorSettlePrice:s.reduce((l,a)=>l+a.priorSettlePrice,0)/s.length,sessionHighBid:s.reduce((l,a)=>l+a.sessionHighBid,0)/s.length,sessionLowOffer:s.reduce((l,a)=>l+a.sessionLowOffer,0)/s.length,earlyPrices:s.reduce((l,a)=>l+a.earlyPrices,0)/s.length,auctionClearingPrice:s.reduce((l,a)=>l+a.auctionClearingPrice,0)/s.length,swapValueFactor:s.reduce((l,a)=>l+a.swapValueFactor,0)/s.length,dailyValueAdjustmentForLongPositions:s.reduce((l,a)=>l+a.dailyValueAdjustmentForLongPositions,0)/s.length,cumulativeValueAdjustmentForLongPositions:s.reduce((l,a)=>l+a.cumulativeValueAdjustmentForLongPositions,0)/s.length,dailyValueAdjustmentForShortPositions:s.reduce((l,a)=>l+a.dailyValueAdjustmentForShortPositions,0)/s.length,cumulativeValueAdjustmentForShortPositions:s.reduce((l,a)=>l+a.cumulativeValueAdjustmentForShortPositions,0)/s.length,fixingPrice:s.reduce((l,a)=>l+a.fixingPrice,0)/s.length,cashRate:s.reduce((l,a)=>l+a.cashRate,0)/s.length,recoveryRate:s.reduce((l,a)=>l+a.recoveryRate,0)/s.length,recoveryRateForLong:s.reduce((l,a)=>l+a.recoveryRateForLong,0)/s.length,recoveryRateForShort:s.reduce((l,a)=>l+a.recoveryRateForShort,0)/s.length,marketBid:s.reduce((l,a)=>l+a.marketBid,0)/s.length,marketOffer:s.reduce((l,a)=>l+a.marketOffer,0)/s.length,shortSaleMinPrice:s.reduce((l,a)=>l+a.shortSaleMinPrice,0)/s.length,previousClosingPrice:s.reduce((l,a)=>l+a.previousClosingPrice,0)/s.length,thresholdLimitPriceBanding:s.reduce((l,a)=>l+a.thresholdLimitPriceBanding,0)/s.length,dailyFinancingValue:s.reduce((l,a)=>l+a.dailyFinancingValue,0)/s.length,accruedFinancingValue:s.reduce((l,a)=>l+a.accruedFinancingValue,0)/s.length,twap:s.reduce((l,a)=>l+a.twap,0)/s.length};e.push(h)}return e.push(r[r.length-1]),e},Ve=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 n=z(i,500),o=new J.default;o.setWidth(1200),o.setHeight(600),o.setBackgroundColor("transparent");let u=n.map(y=>new Date(y.timestamp).toLocaleTimeString()),s=n.map(y=>y.bid),h=n.map(y=>y.offer),l=n.map(y=>y.spread),a=n.map(y=>y.volume),P=n.map(y=>y.trade),v=n.map(y=>y.vwap),f=n.map(y=>y.twap),w=Math.max(...a.filter(y=>y>0)),d=Math.max(...s,...h,...P,...v,...f),M=a.map(y=>y/w*d*.3),R={type:"line",data:{labels:u,datasets:[{label:"Bid",data:s,borderColor:"#28a745",backgroundColor:"rgba(40, 167, 69, 0.1)",fill:!1,tension:.4},{label:"Offer",data:h,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:P,borderColor:"#ffc107",backgroundColor:"rgba(255, 193, 7, 0.1)",fill:!1,tension:.4},{label:"VWAP",data:v,borderColor:"#17a2b8",backgroundColor:"rgba(23, 162, 184, 0.1)",fill:!1,tension:.4},{label:"TWAP",data:f,borderColor:"#6610f2",backgroundColor:"rgba(102, 16, 242, 0.1)",fill:!1,tension:.4},{label:"Volume (Normalized)",data:M,borderColor:"#007bff",backgroundColor:"rgba(0, 123, 255, 0.1)",fill:!0,tension:.4}]},options:{responsive:!0,plugins:{title:{display:!0,text:`${e} Market Data (Volume normalized to 30% of max price)`}},scales:{y:{beginAtZero:!1,title:{display:!0,text:"Price / Normalized Volume"}}}}};return o.setConfig(R),{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}}},De=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:"getStockPriceHistory"}]};let n=z(i,500);return{content:[{type:"text",text:JSON.stringify({symbol:e,count:n.length,originalCount:i.length,data:n.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}}},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"},Be={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"},He={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"},Ne={1:"AutomatedExecutionNoIntervention",2:"AutomatedExecutionInterventionOK",3:"ManualOrder"},je=(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.
5
+
6
+ Parameters verified:
7
+ - ClOrdID: ${e.clOrdID}
8
+ - HandlInst: ${e.handlInst} (${Ne[e.handlInst]})
9
+ - Quantity: ${e.quantity}
10
+ - Price: ${e.price}
11
+ - OrdType: ${e.ordType} (${Ee[e.ordType]})
12
+ - Side: ${e.side} (${Be[e.side]})
13
+ - Symbol: ${e.symbol}
14
+ - TimeInForce: ${e.timeInForce} (${He[e.timeInForce]})
15
+
16
+ To execute this order, call the executeOrder tool with these exact same parameters. Important: The user has to explicitly confirm before executeOrder is called!`,uri:"verifyOrder"}]}}catch(i){return{content:[{type:"text",text:`Error: ${i instanceof Error?i.message:"Failed to verify order parameters"}`,uri:"verifyOrder"}],isError:!0}}},qe=(r,t,e)=>async i=>{try{let n=t.get(i.clOrdID);if(!n)return{content:[{type:"text",text:`Error: Order ${i.clOrdID} has not been verified. Please call verifyOrder first.`,uri:"executeOrder"}],isError:!0};if(n.handlInst!==i.handlInst||n.quantity!==Number.parseFloat(String(i.quantity))||n.price!==Number.parseFloat(String(i.price))||n.ordType!==i.ordType||n.side!==i.side||n.symbol!==i.symbol||n.timeInForce!==i.timeInForce)return{content:[{type:"text",text:"Error: Order parameters do not match the verified order. Please use the exact same parameters that were verified.",uri:"executeOrder"}],isError:!0};let o=new Promise(h=>{e.set(i.clOrdID,h)}),u=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(u);let s=await o;return t.delete(i.clOrdID),{content:[{type:"text",text:s.messageType===g.Messages.Reject?`Reject message for order ${i.clOrdID}: ${JSON.stringify(s.toFIXJSON())}`:`Execution Report for order ${i.clOrdID}: ${JSON.stringify(s.toFIXJSON())}`,uri:"executeOrder"}]}}catch(n){return{content:[{type:"text",text:`Error: ${n instanceof Error?n.message:"Failed to execute order"}`,uri:"executeOrder"}],isError:!0}}},We=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}}},Ge=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}}},$e=(r,t,e,i)=>({parse:We(r),parseToJSON:Ge(r),verifyOrder:je(r,t),executeOrder:qe(r,t,e),marketDataRequest:Le(r,e),getStockGraph:Ve(i),getStockPriceHistory:De(i),technicalAnalysis:Te(i)});function Ue(r,t){return r[t]||t}function Xe(r,t,e,i,n,o){let u=r.messageType;if(u===m.Messages.MarketDataSnapshotFullRefresh||u===m.Messages.MarketDataIncrementalRefresh){let s=r.getField(m.Fields.Symbol)?.value,l=r.toFIXJSON().Body?.NoMDEntries||[],a={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 l){let w=f.MDEntryType,d=f.MDEntryPx?Number.parseFloat(f.MDEntryPx):0,M=f.MDEntrySize?Number.parseFloat(f.MDEntrySize):0;switch(Ue(m.MDEntryType,w)){case m.MDEntryType.Bid:a.bid=d;break;case m.MDEntryType.Offer:a.offer=d;break;case m.MDEntryType.Trade:a.trade=d;break;case m.MDEntryType.IndexValue:a.indexValue=d;break;case m.MDEntryType.OpeningPrice:a.openingPrice=d;break;case m.MDEntryType.ClosingPrice:a.closingPrice=d;break;case m.MDEntryType.SettlementPrice:a.settlementPrice=d;break;case m.MDEntryType.TradingSessionHighPrice:a.tradingSessionHighPrice=d;break;case m.MDEntryType.TradingSessionLowPrice:a.tradingSessionLowPrice=d;break;case m.MDEntryType.VWAP:a.vwap=d;break;case m.MDEntryType.Imbalance:a.imbalance=M;break;case m.MDEntryType.TradeVolume:a.volume=M;break;case m.MDEntryType.OpenInterest:a.openInterest=M;break;case m.MDEntryType.CompositeUnderlyingPrice:a.compositeUnderlyingPrice=d;break;case m.MDEntryType.SimulatedSellPrice:a.simulatedSellPrice=d;break;case m.MDEntryType.SimulatedBuyPrice:a.simulatedBuyPrice=d;break;case m.MDEntryType.MarginRate:a.marginRate=d;break;case m.MDEntryType.MidPrice:a.midPrice=d;break;case m.MDEntryType.EmptyBook:a.emptyBook=1;break;case m.MDEntryType.SettleHighPrice:a.settleHighPrice=d;break;case m.MDEntryType.SettleLowPrice:a.settleLowPrice=d;break;case m.MDEntryType.PriorSettlePrice:a.priorSettlePrice=d;break;case m.MDEntryType.SessionHighBid:a.sessionHighBid=d;break;case m.MDEntryType.SessionLowOffer:a.sessionLowOffer=d;break;case m.MDEntryType.EarlyPrices:a.earlyPrices=d;break;case m.MDEntryType.AuctionClearingPrice:a.auctionClearingPrice=d;break;case m.MDEntryType.SwapValueFactor:a.swapValueFactor=d;break;case m.MDEntryType.DailyValueAdjustmentForLongPositions:a.dailyValueAdjustmentForLongPositions=d;break;case m.MDEntryType.CumulativeValueAdjustmentForLongPositions:a.cumulativeValueAdjustmentForLongPositions=d;break;case m.MDEntryType.DailyValueAdjustmentForShortPositions:a.dailyValueAdjustmentForShortPositions=d;break;case m.MDEntryType.CumulativeValueAdjustmentForShortPositions:a.cumulativeValueAdjustmentForShortPositions=d;break;case m.MDEntryType.FixingPrice:a.fixingPrice=d;break;case m.MDEntryType.CashRate:a.cashRate=d;break;case m.MDEntryType.RecoveryRate:a.recoveryRate=d;break;case m.MDEntryType.RecoveryRateForLong:a.recoveryRateForLong=d;break;case m.MDEntryType.RecoveryRateForShort:a.recoveryRateForShort=d;break;case m.MDEntryType.MarketBid:a.marketBid=d;break;case m.MDEntryType.MarketOffer:a.marketOffer=d;break;case m.MDEntryType.ShortSaleMinPrice:a.shortSaleMinPrice=d;break;case m.MDEntryType.PreviousClosingPrice:a.previousClosingPrice=d;break;case m.MDEntryType.ThresholdLimitPriceBanding:a.thresholdLimitPriceBanding=d;break;case m.MDEntryType.DailyFinancingValue:a.dailyFinancingValue=d;break;case m.MDEntryType.AccruedFinancingValue:a.accruedFinancingValue=d;break;case m.MDEntryType.TWAP:a.twap=d;break}}a.spread=a.offer-a.bid,i.has(s)||i.set(s,[]);let P=i.get(s);P.push(a),P.length>n&&P.splice(0,P.length-n),o?.(s,a);let v=r.getField(m.Fields.MDReqID)?.value;if(v){let f=e.get(v);f&&(f(r),e.delete(v))}}else if(u===m.Messages.ExecutionReport){let s=r.getField(m.Fields.ClOrdID)?.value,h=e.get(s);h&&(h(r),e.delete(s))}}var O={};function Je(r){if(r.type==="object"){let t={};for(let[e,i]of Object.entries(r.properties||{})){let n=i;n.type==="string"?n.enum?t[e]=S.z.enum(n.enum):t[e]=S.z.string():n.type==="number"?t[e]=S.z.number():n.type==="boolean"?t[e]=S.z.boolean():n.type==="array"?n.items.type==="string"?t[e]=S.z.array(S.z.string()):n.items.type==="number"?t[e]=S.z.array(S.z.number()):n.items.type==="boolean"?t[e]=S.z.array(S.z.boolean()):t[e]=S.z.array(S.z.any()):t[e]=S.z.any()}return t}return{}}var ee=class extends ke{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&&Xe(t,this.parser,this.pendingRequests,this.marketDataPrices,this.MAX_PRICE_HISTORY)}),this.httpServer=(0,K.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 n=[];t.on("data",o=>{n.push(o)}),t.on("end",async()=>{let o,u=Buffer.concat(n).toString();try{o=JSON.parse(u)}catch{e.writeHead(400),e.end(JSON.stringify({error:"Invalid JSON"}));return}let s;if(i&&O[i])s=O[i];else if(!i&&t.method==="POST"&&(0,Z.isInitializeRequest)(o))s=new Y.StreamableHTTPServerTransport({sessionIdGenerator:()=>(0,_.randomUUID)(),onsessioninitialized:h=>{O[h]=s}}),s.onclose=()=>{s.sessionId&&delete O[s.sessionId]},this.mcpServer=new Q.McpServer({name:this.serverName||"FIXParser",version:this.serverVersion||"1.0.0"}),this.setupTools(),await this.mcpServer.connect(s);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 s.handleRequest(t,e,o)}catch(h){throw this.logger?.log({level:"error",message:`Error handling request: ${h}`}),h}})}else if(t.method==="GET"||t.method==="DELETE"){if(!i||!O[i]){e.writeHead(400),e.end("Invalid or missing session ID");return}let n=O[i];try{await n.handleRequest(t,e)}catch(o){throw this.logger?.log({level:"error",message:`Error handling ${t.method} request: ${o}`}),o}}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=$e(this.parser,this.verifiedOrders,this.pendingRequests,this.marketDataPrices);Object.entries(Ce).forEach(([t,{description:e,schema:i}])=>{this.mcpServer?.registerTool(t,{description:e,inputSchema:Je(i)},async n=>{let o=r[t];if(!o)return{content:[{type:"text",text:`Tool not found: ${t}`}],isError:!0};let u=await o(n);return{content:u.content,isError:u.isError}})})}};var ze=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 ee({port:3099,onReady:()=>console.log("ready!")})]}),i=()=>{let o=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)),u=e.parse(o.encode());console.log("sending message",u[0].description,u[0].messageString),e.send(o)},n={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 X({format:"console"})},onOpen:()=>{console.log("Open"),i()},onMessage:o=>console.log("received message",o.description,o.messageString.replace(/\x01/g,"|")),onClose:()=>{console.log("Disconnected")}};e.connect(n)};ze().catch(r=>console.error("Error initializing server:",r));
18
+ //# sourceMappingURL=example_mcp_remote.js.map