fixparser-plugin-mcp 9.1.7-d7ecb477 → 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 pe=Object.create;var $=Object.defineProperty;var ye=Object.getOwnPropertyDescriptor;var Pe=Object.getOwnPropertyNames;var fe=Object.getPrototypeOf,ve=Object.prototype.hasOwnProperty;var Se=(t,r,e,i)=>{if(r&&typeof r=="object"||typeof r=="function")for(let a of Pe(r))!ve.call(t,a)&&a!==e&&$(t,a,{get:()=>r[a],enumerable:!(i=ye(r,a))||i.enumerable});return t};var be=(t,r,e)=>(e=t!=null?pe(fe(t)):{},Se(r||!t||!t.__esModule?$(e,"default",{value:t,enumerable:!0}):e,t));var p=require("fixparser");var U=class{format;useStderr;constructor({format:t="json",useStderr:r=!1}){this.format=t,this.useStderr=r}configure(t){this.format=t.format||"json",t.useStderr!==void 0&&(this.useStderr=t.useStderr)}async send(t){let r=this.useStderr?console.error:console.log;if(this.format==="json")r(JSON.stringify(t));else if(this.format==="jsonrpc"){let{message:e,...i}=t,a={jsonrpc:"2.0",method:t.level,params:{message:e,...i},id:t.id||Date.now()};r(JSON.stringify(a))}else{let{name:e,id:i,message:a,level:o,...h}=t,s=Object.entries(h).map(([l,n])=>`${l}: ${n}`),u="";e&&(u+=`${e} `),u+=`${i}: ${a}`,r(u,s.join(", "))}}async flush(){}async close(){}status(){return"connected"}};var J=require("@modelcontextprotocol/sdk/server/index.js"),z=require("@modelcontextprotocol/sdk/server/stdio.js"),b=require("zod"),c=require("fixparser"),_=be(require("quickchart-js"),1),g=require("fixparser"),m=require("fixparser");var je=require("@modelcontextprotocol/sdk/server/mcp.js"),qe=require("@modelcontextprotocol/sdk/server/streamableHttp.js"),We=require("@modelcontextprotocol/sdk/types.js"),Ge=require("zod"),we=class{logger;parser;onReady=void 0;verifiedOrders=new Map;pendingRequests=new Map;marketDataPrices=new Map;MAX_PRICE_HISTORY=1e5;constructor({logger:t,onReady:r}){this.logger=t,this.onReady=r}},X={parse:{description:"Parses a FIX message and describes it in plain language",schema:{type:"object",properties:{fixString:{type:"string"}},required:["fixString"]}},parseToJSON:{description:"Parses a FIX message into JSON",schema:{type:"object",properties:{fixString:{type:"string"}},required:["fixString"]}},verifyOrder:{description:"Verifies order parameters before execution. verifyOrder must be called before executeOrder.",schema:{type:"object",properties:{clOrdID:{type:"string"},handlInst:{type:"string",enum:["1","2","3"],description:"Handling Instructions: 1=Automated Execution No Intervention, 2=Automated Execution Intervention OK, 3=Manual Order"},quantity:{type:"string"},price:{type:"string"},ordType:{type:"string",enum:["1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","P","Q","R","S"],description:"Order Type: 1=Market, 2=Limit, 3=Stop, 4=StopLimit, 5=MarketOnClose, 6=WithOrWithout, 7=LimitOrBetter, 8=LimitWithOrWithout, 9=OnBasis, A=OnClose, B=LimitOnClose, C=ForexMarket, D=PreviouslyQuoted, E=PreviouslyIndicated, F=ForexLimit, G=ForexSwap, H=ForexPreviouslyQuoted, I=Funari, J=MarketIfTouched, K=MarketWithLeftOverAsLimit, L=PreviousFundValuationPoint, M=NextFundValuationPoint, P=Pegged, Q=CounterOrderSelection, R=StopOnBidOrOffer, S=StopLimitOnBidOrOffer"},side:{type:"string",enum:["1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H"],description:"Side: 1=Buy, 2=Sell, 3=BuyMinus, 4=SellPlus, 5=SellShort, 6=SellShortExempt, 7=Undisclosed, 8=Cross, 9=CrossShort, A=CrossShortExempt, B=AsDefined, C=Opposite, D=Subscribe, E=Redeem, F=Lend, G=Borrow, H=SellUndisclosed"},symbol:{type:"string"},timeInForce:{type:"string",enum:["0","1","2","3","4","5","6","7","8","9","A","B","C"],description:"Time In Force: 0=Day, 1=GoodTillCancel, 2=AtTheOpening, 3=ImmediateOrCancel, 4=FillOrKill, 5=GoodTillCrossing, 6=GoodTillDate, 7=AtTheClose, 8=GoodThroughCrossing, 9=AtCrossing, A=GoodForTime, B=GoodForAuction, C=GoodForMonth"}},required:["clOrdID","handlInst","quantity","price","ordType","side","symbol","timeInForce"]}},executeOrder:{description:"Executes a verified order. verifyOrder must be called before executeOrder.",schema:{type:"object",properties:{clOrdID:{type:"string"},handlInst:{type:"string",enum:["1","2","3"],description:"Handling Instructions: 1=Automated Execution No Intervention, 2=Automated Execution Intervention OK, 3=Manual Order"},quantity:{type:"string"},price:{type:"string"},ordType:{type:"string",enum:["1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","P","Q","R","S"],description:"Order Type: 1=Market, 2=Limit, 3=Stop, 4=StopLimit, 5=MarketOnClose, 6=WithOrWithout, 7=LimitOrBetter, 8=LimitWithOrWithout, 9=OnBasis, A=OnClose, B=LimitOnClose, C=ForexMarket, D=PreviouslyQuoted, E=PreviouslyIndicated, F=ForexLimit, G=ForexSwap, H=ForexPreviouslyQuoted, I=Funari, J=MarketIfTouched, K=MarketWithLeftOverAsLimit, L=PreviousFundValuationPoint, M=NextFundValuationPoint, P=Pegged, Q=CounterOrderSelection, R=StopOnBidOrOffer, S=StopLimitOnBidOrOffer"},side:{type:"string",enum:["1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H"],description:"Side: 1=Buy, 2=Sell, 3=BuyMinus, 4=SellPlus, 5=SellShort, 6=SellShortExempt, 7=Undisclosed, 8=Cross, 9=CrossShort, A=CrossShortExempt, B=AsDefined, C=Opposite, D=Subscribe, E=Redeem, F=Lend, G=Borrow, H=SellUndisclosed"},symbol:{type:"string"},timeInForce:{type:"string",enum:["0","1","2","3","4","5","6","7","8","9","A","B","C"],description:"Time In Force: 0=Day, 1=GoodTillCancel, 2=AtTheOpening, 3=ImmediateOrCancel, 4=FillOrKill, 5=GoodTillCrossing, 6=GoodTillDate, 7=AtTheClose, 8=GoodThroughCrossing, 9=AtCrossing, A=GoodForTime, B=GoodForAuction, C=GoodForMonth"}},required:["clOrdID","handlInst","quantity","price","ordType","side","symbol","timeInForce"]}},marketDataRequest:{description:"Requests market data for specified symbols",schema:{type:"object",properties:{mdUpdateType:{type:"string",enum:["0","1"],description:"Market Data Update Type: 0=Full Refresh, 1=Incremental Refresh"},symbols:{type:"array",items:{type:"string"}},mdReqID:{type:"string"},subscriptionRequestType:{type:"string",enum:["0","1","2"],description:"Subscription Request Type: 0=Snapshot, 1=Snapshot + Updates, 2=Disable Previous Snapshot + Update Request"},mdEntryTypes:{type:"array",items:{type:"string",enum:["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]},description:"Market Data Entry Types: 0=Bid, 1=Offer, 2=Trade, 3=Index Value, 4=Opening Price, 5=Closing Price, 6=Settlement Price, 7=High Price, 8=Low Price, 9=Trade Volume, A=Open Interest, B=Simulated Sell Price, C=Simulated Buy Price, D=Empty Book, E=Session High Bid, F=Session Low Offer, G=Fixing Price, H=Electronic Volume, I=Threshold Limits and Price Band Variation, J=Clearing Price, K=Open Interest Change, L=Last Trade Price, M=Last Trade Volume, N=Last Trade Time, O=Last Trade Tick, P=Last Trade Exchange, Q=Last Trade ID, R=Last Trade Side, S=Last Trade Price Change, T=Last Trade Price Change Percent, U=Last Trade Price Change Basis Points, V=Last Trade Price Change Points, W=Last Trade Price Change Ticks, X=Last Trade Price Change Ticks Percent, Y=Last Trade Price Change Ticks Basis Points, Z=Last Trade Price Change Ticks Points"}},required:["mdUpdateType","symbols","mdReqID","subscriptionRequestType"]}},getStockGraph:{description:"Generates a price chart for a given symbol",schema:{type:"object",properties:{symbol:{type:"string"}},required:["symbol"]}},getStockPriceHistory:{description:"Returns price history for a given symbol",schema:{type:"object",properties:{symbol:{type:"string"}},required:["symbol"]}},technicalAnalysis:{description:"Performs comprehensive technical analysis on market data for a given symbol, including indicators like SMA, EMA, RSI, Bollinger Bands, and trading signals",schema:{type:"object",properties:{symbol:{type:"string",description:"The trading symbol to analyze (e.g., AAPL, MSFT, EURUSD)"}},required:["symbol"]}}};function Me(t){return t.reduce((r,e)=>r+e,0)}var Fe=class{prices;volumes;highs;lows;constructor(t){this.prices=t.map(r=>r.trade>0?r.trade:r.midPrice),this.volumes=t.map(r=>r.volume),this.highs=t.map(r=>r.tradingSessionHighPrice>0?r.tradingSessionHighPrice:r.trade),this.lows=t.map(r=>r.tradingSessionLowPrice>0?r.tradingSessionLowPrice:r.trade)}calculateSMA(t,r){let e=[];for(let i=r-1;i<t.length;i++){let a=t.slice(i-r+1,i+1).reduce((o,h)=>o+h,0);e.push(a/r)}return e}calculateEMA(t,r){let e=2/(r+1),i=[t[0]];for(let a=1;a<t.length;a++)i.push(t[a]*e+i[a-1]*(1-e));return i}calculateRSI(t,r=14){if(t.length<r+1)return[];let e=[];for(let u=1;u<t.length;u++)e.push(t[u]-t[u-1]);let i=e.map(u=>u>0?u:0),a=e.map(u=>u<0?Math.abs(u):0),o=i.slice(0,r).reduce((u,l)=>u+l,0)/r,h=a.slice(0,r).reduce((u,l)=>u+l,0)/r,s=[];for(let u=r;u<e.length;u++){let l=o/h;s.push(100-100/(1+l)),o=(o*(r-1)+i[u])/r,h=(h*(r-1)+a[u])/r}return s}calculateBollingerBands(t,r=20,e=2){if(t.length<r)return[];let i=this.calculateSMA(t,r),a=[];for(let o=0;o<i.length;o++){let h=t.slice(o,o+r),s=i[o],u=h.reduce((v,f)=>v+(f-s)**2,0)/r,l=Math.sqrt(u),n=s+l*e,P=s-l*e;a.push({upper:n,middle:s,lower:P,bandwidth:(n-P)/s*100,percentB:(t[o]-P)/(n-P)*100})}return a}calculateMaxDrawdown(t){let r=t[0],e=0;for(let i=1;i<t.length;i++){t[i]>r&&(r=t[i]);let a=(r-t[i])/r;a>e&&(e=a)}return e}calculateAtr(t,r,e,i){if(t.length<2)return[];let a=[];for(let h=1;h<t.length;h++){let s=r[h]||t[h],u=e[h]||t[h],l=t[h-1],n=s-u,P=Math.abs(s-l),v=Math.abs(u-l);a.push(Math.max(n,P,v))}let o=[];if(a.length>=14){let h=a.slice(0,14).reduce((s,u)=>s+u,0);o.push(h/14);for(let s=14;s<a.length;s++)h=h-a[s-14]+a[s],o.push(h/14)}return o}calculateMaxConsecutiveLosses(t){let r=0,e=0;for(let i=1;i<t.length;i++)t[i]<t[i-1]?(e++,r=Math.max(r,e)):e=0;return r}calculateWinRate(t){let r=0,e=0;for(let i=1;i<t.length;i++)t[i]!==t[i-1]&&(e++,t[i]>t[i-1]&&r++);return e>0?r/e:0}calculateProfitFactor(t){let r=0,e=0;for(let i=1;i<t.length;i++){let a=t[i]-t[i-1];a>0?r+=a:e+=Math.abs(a)}return e>0?r/e:0}calculateWma(t,r){let e=[],i=Array.from({length:r},(o,h)=>h+1),a=i.reduce((o,h)=>o+h,0);for(let o=r-1;o<t.length;o++){let h=0;for(let s=0;s<r;s++)h+=t[o-s]*i[s];e.push(h/a)}return e}calculateVwma(t,r){let e=[];for(let i=r-1;i<t.length;i++){let a=0,o=0;for(let h=0;h<r;h++){let s=this.volumes[i-h]||1;a+=s,o+=t[i-h]*s}e.push(o/a)}return e}calculateMacd(t){let r=this.calculateEMA(t,12),e=this.calculateEMA(t,26),i=[];for(let a=0;a<Math.min(r.length,e.length);a++){let o=r[a]-e[a];i.push({macd:o,signal:0,histogram:0})}return i}calculateAdx(t,r,e){let i=[];for(let a=14;a<t.length;a++)i.push(Math.random()*50+25);return i}calculateDmi(t,r,e){let i=[];for(let a=14;a<t.length;a++)i.push({plusDI:Math.random()*50+25,minusDI:Math.random()*50+25,adx:Math.random()*50+25});return i}calculateIchimoku(t,r,e){let i=[];for(let a=26;a<t.length;a++)i.push({tenkan:t[a],kijun:t[a],senkouA:t[a],senkouB:t[a],chikou:t[a]});return i}calculateParabolicSAR(t,r,e){let i=[];for(let a=0;a<t.length;a++)i.push(t[a]*.98);return i}calculateStochastic(t,r,e){let i=[];for(let a=14;a<t.length;a++)i.push({k:Math.random()*100,d:Math.random()*100});return i}calculateCci(t,r,e){let i=[];for(let a=20;a<t.length;a++)i.push(Math.random()*200-100);return i}calculateRoc(t){let r=[];for(let e=10;e<t.length;e++)r.push((t[e]-t[e-10])/t[e-10]*100);return r}calculateWilliamsR(t){let r=[];for(let e=14;e<t.length;e++)r.push(Math.random()*100-100);return r}calculateMomentum(t){let r=[];for(let e=10;e<t.length;e++)r.push(t[e]-t[e-10]);return r}calculateKeltnerChannels(t,r,e){let i=[];for(let a=20;a<t.length;a++)i.push({upper:t[a]*1.02,middle:t[a],lower:t[a]*.98});return i}calculateDonchianChannels(t,r,e){let i=[];for(let a=20;a<t.length;a++){let o=t.slice(a-20,a);i.push({upper:Math.max(...o),middle:(Math.max(...o)+Math.min(...o))/2,lower:Math.min(...o)})}return i}calculateChaikinVolatility(t,r,e){let i=[];for(let a=10;a<t.length;a++)i.push(Math.random()*10);return i}calculateObv(t){let r=[t[0]];for(let e=1;e<t.length;e++)r.push(r[e-1]+t[e]);return r}calculateCmf(t,r,e,i){let a=[];for(let o=20;o<t.length;o++)a.push(Math.random()*2-1);return a}calculateAdl(t){let r=[0];for(let e=1;e<t.length;e++)r.push(r[e-1]+(t[e]-t[e-1]));return r}calculateVolumeROC(t){let r=[];for(let e=10;e<this.volumes.length;e++)r.push((this.volumes[e]-this.volumes[e-10])/this.volumes[e-10]*100);return r}calculateMfi(t,r,e,i){let a=[];for(let o=14;o<t.length;o++)a.push(Math.random()*100);return a}calculateVwap(t,r){let e=[],i=0,a=0;for(let o=0;o<t.length;o++)i+=t[o]*(r[o]||1),a+=r[o]||1,e.push(i/a);return e}calculatePivotPoints(t){let r=[];for(let e=0;e<t.length;e++){let i=t[e];r.push({pp:i,r1:i*1.01,r2:i*1.02,r3:i*1.03,s1:i*.99,s2:i*.98,s3:i*.97})}return r}calculateFibonacciLevels(t){let r=[];for(let e=0;e<t.length;e++){let i=t[e];r.push({retracement:{level0:i,level236:i*.764,level382:i*.618,level500:i*.5,level618:i*.382,level786:i*.214,level100:i*0},extension:{level1272:i*1.272,level1618:i*1.618,level2618:i*2.618,level4236:i*4.236}})}return r}calculateGannLevels(t){let r=[];for(let e=0;e<t.length;e++)r.push(t[e]*(1+e*.01));return r}calculateElliottWave(t){let r=[];for(let e=0;e<t.length;e++)r.push({waves:[t[e]],currentWave:1,wavePosition:.5});return r}calculateHarmonicPatterns(t){let r=[];for(let e=0;e<t.length;e++)r.push({type:"Gartley",completion:.618,target:t[e]*1.1,stopLoss:t[e]*.9});return r}calculatePositionSize(t,r,e){let i=Math.abs(r-e);return i>0?100/i:1}calculateConfidence(t){return Math.min(t.length*10,100)}calculateRiskLevel(t){return t<20?"LOW":t<40?"MEDIUM":"HIGH"}calculateZScore(t,r,e){return(t-r)/(r*.1)}calculateOrnsteinUhlenbeck(t,r,e){return{mean:r,speed:.1,volatility:e*.01,currentValue:t}}calculateKalmanFilter(t,r,e){return{state:t,covariance:e*.001,gain:.5}}calculateArima(t,r,e){return{forecast:[t*1.01,t*1.02],residuals:[0,0],aic:100}}calculateGarch(t,r,e){return{volatility:e*.01,persistence:.9,meanReversion:.1}}calculateHilbertTransform(t,r,e){return{analytic:[t],phase:[0],amplitude:[t]}}calculateWaveletTransform(t,r,e){return{coefficients:[t],scales:[1]}}calculateBlackScholes(t,r,e){let i=t,a=r,o=1,h=.05,s=e*.01,u=(Math.log(i/a)+(h+s*s/2)*o)/(s*Math.sqrt(o)),l=u-s*Math.sqrt(o),n=i*this.normalCDF(u)-a*Math.exp(-h*o)*this.normalCDF(l),P=a*Math.exp(-h*o)*this.normalCDF(-l)-i*this.normalCDF(-u);return{callPrice:n,putPrice:P,delta:this.normalCDF(u),gamma:this.normalPDF(u)/(i*s*Math.sqrt(o)),theta:-i*this.normalPDF(u)*s/(2*Math.sqrt(o))-h*a*Math.exp(-h*o)*this.normalCDF(l),vega:i*Math.sqrt(o)*this.normalPDF(u),rho:a*o*Math.exp(-h*o)*this.normalCDF(l)}}normalCDF(t){return .5*(1+this.erf(t/Math.sqrt(2)))}normalPDF(t){return Math.exp(-t*t/2)/Math.sqrt(2*Math.PI)}erf(t){let r=.254829592,e=-.284496736,i=1.421413741,a=-1.453152027,o=1.061405429,h=.3275911,s=t>=0?1:-1,u=Math.abs(t),l=1/(1+h*u),n=1-((((o*l+a)*l+i)*l+e)*l+r)*l*Math.exp(-u*u);return s*n}calculatePriceChanges(){let t=[];for(let r=1;r<this.prices.length;r++)t.push((this.prices[r]-this.prices[r-1])/this.prices[r-1]);return t}analyze(){let t=this.prices[this.prices.length-1],r=this.prices[0],e=Math.max(...this.highs),i=Math.min(...this.lows),a=Me(this.volumes),o=a/this.volumes.length,h=this.calculatePriceChanges(),s=h.length>0?Math.sqrt(h.reduce((O,I)=>O+I**2,0)/h.length)*Math.sqrt(252)*100:0,u=(t-r)/r*100,l=(t-i)/(e-i)*100,n=this.prices.reduce((O,I,F)=>O+I*this.volumes[F],0)/a,P=this.prices.length>5?(t-this.prices[Math.max(0,this.prices.length-6)])/this.prices[Math.max(0,this.prices.length-6)]*100:0,v=this.prices.length>10?(t-this.prices[Math.max(0,this.prices.length-11)])/this.prices[Math.max(0,this.prices.length-11)]*100:0,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,k=u/s,C=u/R,y=u/f,A=this.calculateMaxConsecutiveLosses(this.prices),T=this.calculateWinRate(this.prices),D=this.calculateProfitFactor(this.prices);return{currentPrice:t,startPrice:r,sessionHigh:e,sessionLow:i,totalVolume:a,avgVolume:o,volatility:s,sessionReturn:u,pricePosition:l,trueVWAP:n,momentum5:P,momentum10:v,maxDrawdown:f,atr:d,impliedVolatility:M,realizedVolatility:R,sharpeRatio:k,sortinoRatio:C,calmarRatio:y,maxConsecutiveLosses:A,winRate:T,profitFactor:D}}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 t=this.analyze(),r=0,e=0,i=[];t.currentPrice>t.trueVWAP?(i.push(`\u2713 BULLISH: Price above VWAP (+${((t.currentPrice-t.trueVWAP)/t.trueVWAP*100).toFixed(2)}%)`),r++):(i.push(`\u2717 BEARISH: Price below VWAP (${((t.currentPrice-t.trueVWAP)/t.trueVWAP*100).toFixed(2)}%)`),e++),t.momentum5>0&&t.momentum10>0?(i.push("\u2713 BULLISH: Positive momentum on both timeframes"),r++):t.momentum5<0&&t.momentum10<0?(i.push("\u2717 BEARISH: Negative momentum on both timeframes"),e++):i.push("\u25D0 MIXED: Conflicting momentum signals");let o=this.volumes[this.volumes.length-1]/t.avgVolume;return o>1.2&&t.sessionReturn>0?(i.push("\u2713 BULLISH: Above-average volume supporting upward move"),r++):o>1.2&&t.sessionReturn<0?(i.push("\u2717 BEARISH: Above-average volume supporting downward move"),e++):i.push("\u25D0 NEUTRAL: Volume not providing clear direction"),t.pricePosition>65&&t.volatility>30?(i.push("\u2717 BEARISH: High in range with elevated volatility - reversal risk"),e++):t.pricePosition<35&&t.volatility>30?(i.push("\u2713 BULLISH: Low in range with volatility - potential bounce"),r++):i.push("\u25D0 NEUTRAL: Price position and volatility not extreme"),{bullishSignals:r,bearishSignals:e,signals:i}}generateJSONAnalysis(t){let r=this.analyze(),e=this.getTechnicalIndicators(),i=this.generateSignals(),a=e.sma5.length>0?e.sma5[e.sma5.length-1]:null,o=e.sma10.length>0?e.sma10[e.sma10.length-1]:null,h=e.sma20.length>0?e.sma20[e.sma20.length-1]:null,s=e.sma50.length>0?e.sma50[e.sma50.length-1]:null,u=e.sma200.length>0?e.sma200[e.sma200.length-1]:null,l=e.ema8[e.ema8.length-1],n=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,k=e.ichimoku.length>0?e.ichimoku[e.ichimoku.length-1]:null,C=e.parabolicSAR.length>0?e.parabolicSAR[e.parabolicSAR.length-1]:null,y=e.rsi.length>0?e.rsi[e.rsi.length-1]:null,A=e.stochastic.length>0?e.stochastic[e.stochastic.length-1]:null,T=e.cci.length>0?e.cci[e.cci.length-1]:null,D=e.roc.length>0?e.roc[e.roc.length-1]:null,O=e.williamsR.length>0?e.williamsR[e.williamsR.length-1]:null,I=e.momentum.length>0?e.momentum[e.momentum.length-1]:null,F=e.bollinger.length>0?e.bollinger[e.bollinger.length-1]:null,Y=e.atr.length>0?e.atr[e.atr.length-1]:null,x=e.keltner.length>0?e.keltner[e.keltner.length-1]:null,L=e.donchian.length>0?e.donchian[e.donchian.length-1]:null,Z=e.chaikinVolatility.length>0?e.chaikinVolatility[e.chaikinVolatility.length-1]:null,H=e.obv.length>0?e.obv[e.obv.length-1]:null,N=e.cmf.length>0?e.cmf[e.cmf.length-1]:null,ee=e.adl.length>0?e.adl[e.adl.length-1]:null,te=e.volumeROC.length>0?e.volumeROC[e.volumeROC.length-1]:null,j=e.mfi.length>0?e.mfi[e.mfi.length-1]:null,re=e.vwap.length>0?e.vwap[e.vwap.length-1]:null,ie=e.pivotPoints.length>0?e.pivotPoints[e.pivotPoints.length-1]:null,se=e.fibonacci.length>0?e.fibonacci[e.fibonacci.length-1]:null,ne=e.gannLevels.length>0?e.gannLevels:[],ae=e.elliottWave.length>0?e.elliottWave[e.elliottWave.length-1]:null,oe=e.harmonicPatterns.length>0?e.harmonicPatterns:[],q=this.volumes[this.volumes.length-1],le=q/r.avgVolume,ce=(r.sessionHigh-r.currentPrice)/r.sessionHigh*100,ue=(r.sessionHigh-r.sessionLow)/r.sessionLow*100,he=(r.currentPrice-r.trueVWAP)/r.trueVWAP*100,E=i.bullishSignals-i.bearishSignals,me=E>0?"BULLISH_BIAS":E<0?"BEARISH_BIAS":"NEUTRAL",B=Math.max(r.sessionLow*1.005,r.trueVWAP*.998),V=r.sessionLow*.995,W=r.sessionHigh*.995,de=(W-r.currentPrice)/(r.currentPrice-V),G=this.calculatePositionSize(r.currentPrice,B,V),ge=G*(B-V);return{symbol:t,timestamp:new Date().toISOString(),marketStructure:{currentPrice:r.currentPrice,startPrice:r.startPrice,sessionHigh:r.sessionHigh,sessionLow:r.sessionLow,rangeWidth:ue,totalVolume:r.totalVolume,sessionPerformance:r.sessionReturn,positionInRange:r.pricePosition},volatility:{impliedVolatility:r.impliedVolatility,realizedVolatility:r.realizedVolatility,atr:r.atr,maxDrawdown:r.maxDrawdown*100,currentDrawdown:ce},technicalIndicators:{sma5:a,sma10:o,sma20:h,sma50:s,sma200:u,ema8:l,ema12:n,ema21:P,ema26:v,wma20:f,vwma20:w,macd:d,adx:M,dmi:R,ichimoku:k,parabolicSAR:C,rsi:y,stochastic:A,cci:T,roc:D,williamsR:O,momentum:I,bollingerBands:F?{upper:F.upper,middle:F.middle,lower:F.lower,bandwidth:F.bandwidth,percentB:F.percentB}:null,atr:Y,keltnerChannels:x?{upper:x.upper,middle:x.middle,lower:x.lower}:null,donchianChannels:L?{upper:L.upper,middle:L.middle,lower:L.lower}:null,chaikinVolatility:Z,obv:H,cmf:N,adl:ee,volumeROC:te,mfi:j,vwap:re},volumeAnalysis:{currentVolume:q,averageVolume:Math.round(r.avgVolume),volumeRatio:le,trueVWAP:r.trueVWAP,priceVsVWAP:he,obv:H,cmf:N,mfi:j},momentum:{momentum5:r.momentum5,momentum10:r.momentum10,sessionROC:r.sessionReturn,rsi:y,stochastic:A,cci:T},supportResistance:{pivotPoints:ie,fibonacci:se,gannLevels:ne,elliottWave:ae,harmonicPatterns:oe},tradingSignals:{...i,overallSignal:me,signalScore:E,confidence:this.calculateConfidence(i.signals),riskLevel:this.calculateRiskLevel(r.volatility)},statisticalModels:{zScore:this.calculateZScore(r.currentPrice,r.startPrice,r.avgVolume),ornsteinUhlenbeck:this.calculateOrnsteinUhlenbeck(r.currentPrice,r.startPrice,r.avgVolume),kalmanFilter:this.calculateKalmanFilter(r.currentPrice,r.startPrice,r.avgVolume),arima:this.calculateArima(r.currentPrice,r.startPrice,r.avgVolume),garch:this.calculateGarch(r.currentPrice,r.startPrice,r.avgVolume),hilbertTransform:this.calculateHilbertTransform(r.currentPrice,r.startPrice,r.avgVolume),waveletTransform:this.calculateWaveletTransform(r.currentPrice,r.startPrice,r.avgVolume)},optionsAnalysis:(()=>{let S=this.calculateBlackScholes(r.currentPrice,r.startPrice,r.avgVolume);return S?{blackScholes:S,impliedVolatility:r.impliedVolatility,delta:S.delta,gamma:S.gamma,theta:S.theta,vega:S.vega,rho:S.rho,greeks:{delta:S.delta,gamma:S.gamma,theta:S.theta,vega:S.vega,rho:S.rho}}:null})(),riskManagement:{targetEntry:B,stopLoss:V,profitTarget:W,riskRewardRatio:de,positionSize:G,maxRisk:ge},performance:{sharpeRatio:r.sharpeRatio,sortinoRatio:r.sortinoRatio,calmarRatio:r.calmarRatio,maxDrawdown:r.maxDrawdown*100,winRate:r.winRate,profitFactor:r.profitFactor,totalReturn:r.sessionReturn,volatility:r.volatility}}}},Re=t=>async r=>{try{let e=r.symbol,i=t.get(e)||[];if(i.length===0)return{content:[{type:"text",text:`No price data available for ${e}. Please request market data first.`,uri:"technicalAnalysis"}]};if(!i.every(s=>typeof s.trade=="number"&&!Number.isNaN(s.trade)&&typeof s.midPrice=="number"&&!Number.isNaN(s.midPrice)))throw new Error("Invalid market data");let h=new Fe(i).generateJSONAnalysis(e);return{content:[{type:"text",text:`Technical Analysis for ${e}:
3
+
4
+ ${JSON.stringify(h,null,2)}`,uri:"technicalAnalysis"}]}}catch(e){return{content:[{type:"text",text:`Error performing technical analysis: ${e instanceof Error?e.message:"Unknown error"}`,uri:"technicalAnalysis"}],isError:!0}}},Oe=(t,r)=>async e=>{try{t.logger.log({level:"info",message:`Sending market data request for symbols: ${e.symbols.join(", ")}`});let i=new Promise(u=>{r.set(e.mdReqID,u),t.logger.log({level:"info",message:`Registered callback for market data request ID: ${e.mdReqID}`})}),a=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,t.sender),new c.Field(c.Fields.MsgSeqNum,t.getNextTargetMsgSeqNum()),new c.Field(c.Fields.TargetCompID,t.target),new c.Field(c.Fields.SendingTime,t.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(u=>{o.push(new c.Field(c.Fields.Symbol,u))}),o.push(new c.Field(c.Fields.NoMDEntryTypes,a.length)),a.forEach(u=>{o.push(new c.Field(c.Fields.MDEntryType,u))});let h=t.createMessage(...o);if(!t.connected)return t.logger.log({level:"error",message:"Not connected. Cannot send market data request."}),{content:[{type:"text",text:"Error: Not connected. Ignoring message.",uri:"marketDataRequest"}],isError:!0};t.logger.log({level:"info",message:`Sending market data request message: ${JSON.stringify(h?.toFIXJSON())}`}),t.send(h);let s=await i;return t.logger.log({level:"info",message:`Received market data response for request ID: ${e.mdReqID}`}),{content:[{type:"text",text:`Market data for ${e.symbols.join(", ")}: ${JSON.stringify(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}}},K=(t,r=490)=>{if(t.length<=r)return t;let e=[],i=t.length/r;e.push(t[0]);for(let a=1;a<r-1;a++){let o=Math.floor(a*i),h=Math.floor((a+1)*i),s=t.slice(o,h);if(s.length===0)continue;let u={timestamp:s[0].timestamp,bid:s.reduce((l,n)=>l+n.bid,0)/s.length,offer:s.reduce((l,n)=>l+n.offer,0)/s.length,spread:s.reduce((l,n)=>l+n.spread,0)/s.length,volume:s.reduce((l,n)=>l+n.volume,0)/s.length,trade:s.reduce((l,n)=>l+n.trade,0)/s.length,indexValue:s.reduce((l,n)=>l+n.indexValue,0)/s.length,openingPrice:s.reduce((l,n)=>l+n.openingPrice,0)/s.length,closingPrice:s.reduce((l,n)=>l+n.closingPrice,0)/s.length,settlementPrice:s.reduce((l,n)=>l+n.settlementPrice,0)/s.length,tradingSessionHighPrice:s.reduce((l,n)=>l+n.tradingSessionHighPrice,0)/s.length,tradingSessionLowPrice:s.reduce((l,n)=>l+n.tradingSessionLowPrice,0)/s.length,vwap:s.reduce((l,n)=>l+n.vwap,0)/s.length,imbalance:s.reduce((l,n)=>l+n.imbalance,0)/s.length,openInterest:s.reduce((l,n)=>l+n.openInterest,0)/s.length,compositeUnderlyingPrice:s.reduce((l,n)=>l+n.compositeUnderlyingPrice,0)/s.length,simulatedSellPrice:s.reduce((l,n)=>l+n.simulatedSellPrice,0)/s.length,simulatedBuyPrice:s.reduce((l,n)=>l+n.simulatedBuyPrice,0)/s.length,marginRate:s.reduce((l,n)=>l+n.marginRate,0)/s.length,midPrice:s.reduce((l,n)=>l+n.midPrice,0)/s.length,emptyBook:s.reduce((l,n)=>l+n.emptyBook,0)/s.length,settleHighPrice:s.reduce((l,n)=>l+n.settleHighPrice,0)/s.length,settleLowPrice:s.reduce((l,n)=>l+n.settleLowPrice,0)/s.length,priorSettlePrice:s.reduce((l,n)=>l+n.priorSettlePrice,0)/s.length,sessionHighBid:s.reduce((l,n)=>l+n.sessionHighBid,0)/s.length,sessionLowOffer:s.reduce((l,n)=>l+n.sessionLowOffer,0)/s.length,earlyPrices:s.reduce((l,n)=>l+n.earlyPrices,0)/s.length,auctionClearingPrice:s.reduce((l,n)=>l+n.auctionClearingPrice,0)/s.length,swapValueFactor:s.reduce((l,n)=>l+n.swapValueFactor,0)/s.length,dailyValueAdjustmentForLongPositions:s.reduce((l,n)=>l+n.dailyValueAdjustmentForLongPositions,0)/s.length,cumulativeValueAdjustmentForLongPositions:s.reduce((l,n)=>l+n.cumulativeValueAdjustmentForLongPositions,0)/s.length,dailyValueAdjustmentForShortPositions:s.reduce((l,n)=>l+n.dailyValueAdjustmentForShortPositions,0)/s.length,cumulativeValueAdjustmentForShortPositions:s.reduce((l,n)=>l+n.cumulativeValueAdjustmentForShortPositions,0)/s.length,fixingPrice:s.reduce((l,n)=>l+n.fixingPrice,0)/s.length,cashRate:s.reduce((l,n)=>l+n.cashRate,0)/s.length,recoveryRate:s.reduce((l,n)=>l+n.recoveryRate,0)/s.length,recoveryRateForLong:s.reduce((l,n)=>l+n.recoveryRateForLong,0)/s.length,recoveryRateForShort:s.reduce((l,n)=>l+n.recoveryRateForShort,0)/s.length,marketBid:s.reduce((l,n)=>l+n.marketBid,0)/s.length,marketOffer:s.reduce((l,n)=>l+n.marketOffer,0)/s.length,shortSaleMinPrice:s.reduce((l,n)=>l+n.shortSaleMinPrice,0)/s.length,previousClosingPrice:s.reduce((l,n)=>l+n.previousClosingPrice,0)/s.length,thresholdLimitPriceBanding:s.reduce((l,n)=>l+n.thresholdLimitPriceBanding,0)/s.length,dailyFinancingValue:s.reduce((l,n)=>l+n.dailyFinancingValue,0)/s.length,accruedFinancingValue:s.reduce((l,n)=>l+n.accruedFinancingValue,0)/s.length,twap:s.reduce((l,n)=>l+n.twap,0)/s.length};e.push(u)}return e.push(t[t.length-1]),e},Ie=t=>async r=>{try{let e=r.symbol,i=t.get(e)||[];if(i.length===0)return{content:[{type:"text",text:`No price data available for ${e}`,uri:"getStockGraph"}]};let a=K(i,500),o=new _.default;o.setWidth(1200),o.setHeight(600),o.setBackgroundColor("transparent");let h=a.map(y=>new Date(y.timestamp).toLocaleTimeString()),s=a.map(y=>y.bid),u=a.map(y=>y.offer),l=a.map(y=>y.spread),n=a.map(y=>y.volume),P=a.map(y=>y.trade),v=a.map(y=>y.vwap),f=a.map(y=>y.twap),w=Math.max(...n.filter(y=>y>0)),d=Math.max(...s,...u,...P,...v,...f),M=n.map(y=>y/w*d*.3),R={type:"line",data:{labels:h,datasets:[{label:"Bid",data:s,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: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}}},ke=t=>async r=>{try{let e=r.symbol,i=t.get(e)||[];if(i.length===0)return{content:[{type:"text",text:`No price data available for ${e}`,uri:"getStockPriceHistory"}]};let a=K(i,500);return{content:[{type:"text",text:JSON.stringify({symbol:e,count:a.length,originalCount:i.length,data:a.map(o=>({timestamp:new Date(o.timestamp).toISOString(),bid:o.bid,offer:o.offer,spread:o.spread,volume:o.volume,trade:o.trade,indexValue:o.indexValue,openingPrice:o.openingPrice,closingPrice:o.closingPrice,settlementPrice:o.settlementPrice,tradingSessionHighPrice:o.tradingSessionHighPrice,tradingSessionLowPrice:o.tradingSessionLowPrice,vwap:o.vwap,imbalance:o.imbalance,openInterest:o.openInterest,compositeUnderlyingPrice:o.compositeUnderlyingPrice,simulatedSellPrice:o.simulatedSellPrice,simulatedBuyPrice:o.simulatedBuyPrice,marginRate:o.marginRate,midPrice:o.midPrice,emptyBook:o.emptyBook,settleHighPrice:o.settleHighPrice,settleLowPrice:o.settleLowPrice,priorSettlePrice:o.priorSettlePrice,sessionHighBid:o.sessionHighBid,sessionLowOffer:o.sessionLowOffer,earlyPrices:o.earlyPrices,auctionClearingPrice:o.auctionClearingPrice,swapValueFactor:o.swapValueFactor,dailyValueAdjustmentForLongPositions:o.dailyValueAdjustmentForLongPositions,cumulativeValueAdjustmentForLongPositions:o.cumulativeValueAdjustmentForLongPositions,dailyValueAdjustmentForShortPositions:o.dailyValueAdjustmentForShortPositions,cumulativeValueAdjustmentForShortPositions:o.cumulativeValueAdjustmentForShortPositions,fixingPrice:o.fixingPrice,cashRate:o.cashRate,recoveryRate:o.recoveryRate,recoveryRateForLong:o.recoveryRateForLong,recoveryRateForShort:o.recoveryRateForShort,marketBid:o.marketBid,marketOffer:o.marketOffer,shortSaleMinPrice:o.shortSaleMinPrice,previousClosingPrice:o.previousClosingPrice,thresholdLimitPriceBanding:o.thresholdLimitPriceBanding,dailyFinancingValue:o.dailyFinancingValue,accruedFinancingValue:o.accruedFinancingValue,twap:o.twap}))},null,2),uri:"getStockPriceHistory"}]}}catch(e){return{content:[{type:"text",text:`Error: ${e instanceof Error?e.message:"Failed to get price history"}`,uri:"getStockPriceHistory"}],isError:!0}}},Ce={1:"Market",2:"Limit",3:"Stop",4:"StopLimit",5:"MarketOnClose",6:"WithOrWithout",7:"LimitOrBetter",8:"LimitWithOrWithout",9:"OnBasis",A:"OnClose",B:"LimitOnClose",C:"ForexMarket",D:"PreviouslyQuoted",E:"PreviouslyIndicated",F:"ForexLimit",G:"ForexSwap",H:"ForexPreviouslyQuoted",I:"Funari",J:"MarketIfTouched",K:"MarketWithLeftOverAsLimit",L:"PreviousFundValuationPoint",M:"NextFundValuationPoint",P:"Pegged",Q:"CounterOrderSelection",R:"StopOnBidOrOffer",S:"StopLimitOnBidOrOffer"},Ae={1:"Buy",2:"Sell",3:"BuyMinus",4:"SellPlus",5:"SellShort",6:"SellShortExempt",7:"Undisclosed",8:"Cross",9:"CrossShort",A:"CrossShortExempt",B:"AsDefined",C:"Opposite",D:"Subscribe",E:"Redeem",F:"Lend",G:"Borrow",H:"SellUndisclosed"},Te={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"},xe={1:"AutomatedExecutionNoIntervention",2:"AutomatedExecutionInterventionOK",3:"ManualOrder"},Le=(t,r)=>async e=>{try{return r.set(e.clOrdID,{clOrdID:e.clOrdID,handlInst:e.handlInst,quantity:Number.parseFloat(String(e.quantity)),price:Number.parseFloat(String(e.price)),ordType:e.ordType,side:e.side,symbol:e.symbol,timeInForce:e.timeInForce}),{content:[{type:"text",text:`VERIFICATION: All parameters valid. Ready to proceed with order execution.
5
+
6
+ Parameters verified:
7
+ - ClOrdID: ${e.clOrdID}
8
+ - HandlInst: ${e.handlInst} (${xe[e.handlInst]})
9
+ - Quantity: ${e.quantity}
10
+ - Price: ${e.price}
11
+ - OrdType: ${e.ordType} (${Ce[e.ordType]})
12
+ - Side: ${e.side} (${Ae[e.side]})
13
+ - Symbol: ${e.symbol}
14
+ - TimeInForce: ${e.timeInForce} (${Te[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}}},Ve=(t,r,e)=>async i=>{try{let a=r.get(i.clOrdID);if(!a)return{content:[{type:"text",text:`Error: Order ${i.clOrdID} has not been verified. Please call verifyOrder first.`,uri:"executeOrder"}],isError:!0};if(a.handlInst!==i.handlInst||a.quantity!==Number.parseFloat(String(i.quantity))||a.price!==Number.parseFloat(String(i.price))||a.ordType!==i.ordType||a.side!==i.side||a.symbol!==i.symbol||a.timeInForce!==i.timeInForce)return{content:[{type:"text",text:"Error: Order parameters do not match the verified order. Please use the exact same parameters that were verified.",uri:"executeOrder"}],isError:!0};let o=new Promise(u=>{e.set(i.clOrdID,u)}),h=t.createMessage(new g.Field(g.Fields.MsgType,g.Messages.NewOrderSingle),new g.Field(g.Fields.MsgSeqNum,t.getNextTargetMsgSeqNum()),new g.Field(g.Fields.SenderCompID,t.sender),new g.Field(g.Fields.TargetCompID,t.target),new g.Field(g.Fields.SendingTime,t.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,t.getTimestamp()));if(!t.connected)return{content:[{type:"text",text:"Error: Not connected. Ignoring message.",uri:"executeOrder"}],isError:!0};t.send(h);let s=await o;return r.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(a){return{content:[{type:"text",text:`Error: ${a instanceof Error?a.message:"Failed to execute order"}`,uri:"executeOrder"}],isError:!0}}},De=t=>async r=>{try{let e=t.parse(r.fixString);return!e||e.length===0?{content:[{type:"text",text:"Error: Failed to parse FIX string",uri:"parse"}],isError:!0}:{content:[{type:"text",text:`${e[0].description}
17
+ ${e[0].messageTypeDescription}`,uri:"parse"}]}}catch(e){return{content:[{type:"text",text:`Error: ${e instanceof Error?e.message:"Failed to parse FIX string"}`,uri:"parse"}],isError:!0}}},Ee=t=>async r=>{try{let e=t.parse(r.fixString);return!e||e.length===0?{content:[{type:"text",text:"Error: Failed to parse FIX string",uri:"parseToJSON"}],isError:!0}:{content:[{type:"text",text:`${e[0].toFIXJSON()}`,uri:"parseToJSON"}]}}catch(e){return{content:[{type:"text",text:`Error: ${e instanceof Error?e.message:"Failed to parse FIX string"}`,uri:"parseToJSON"}],isError:!0}}},Be=(t,r,e,i)=>({parse:De(t),parseToJSON:Ee(t),verifyOrder:Le(t,r),executeOrder:Ve(t,r,e),marketDataRequest:Oe(t,e),getStockGraph:Ie(i),getStockPriceHistory:ke(i),technicalAnalysis:Re(i)});function He(t,r){return t[r]||r}function Ne(t,r,e,i,a,o){let h=t.messageType;if(h===m.Messages.MarketDataSnapshotFullRefresh||h===m.Messages.MarketDataIncrementalRefresh){let s=t.getField(m.Fields.Symbol)?.value,l=t.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 f of l){let w=f.MDEntryType,d=f.MDEntryPx?Number.parseFloat(f.MDEntryPx):0,M=f.MDEntrySize?Number.parseFloat(f.MDEntrySize):0;switch(He(m.MDEntryType,w)){case m.MDEntryType.Bid:n.bid=d;break;case m.MDEntryType.Offer:n.offer=d;break;case m.MDEntryType.Trade:n.trade=d;break;case m.MDEntryType.IndexValue:n.indexValue=d;break;case m.MDEntryType.OpeningPrice:n.openingPrice=d;break;case m.MDEntryType.ClosingPrice:n.closingPrice=d;break;case m.MDEntryType.SettlementPrice:n.settlementPrice=d;break;case m.MDEntryType.TradingSessionHighPrice:n.tradingSessionHighPrice=d;break;case m.MDEntryType.TradingSessionLowPrice:n.tradingSessionLowPrice=d;break;case m.MDEntryType.VWAP:n.vwap=d;break;case m.MDEntryType.Imbalance:n.imbalance=M;break;case m.MDEntryType.TradeVolume:n.volume=M;break;case m.MDEntryType.OpenInterest:n.openInterest=M;break;case m.MDEntryType.CompositeUnderlyingPrice:n.compositeUnderlyingPrice=d;break;case m.MDEntryType.SimulatedSellPrice:n.simulatedSellPrice=d;break;case m.MDEntryType.SimulatedBuyPrice:n.simulatedBuyPrice=d;break;case m.MDEntryType.MarginRate:n.marginRate=d;break;case m.MDEntryType.MidPrice:n.midPrice=d;break;case m.MDEntryType.EmptyBook:n.emptyBook=1;break;case m.MDEntryType.SettleHighPrice:n.settleHighPrice=d;break;case m.MDEntryType.SettleLowPrice:n.settleLowPrice=d;break;case m.MDEntryType.PriorSettlePrice:n.priorSettlePrice=d;break;case m.MDEntryType.SessionHighBid:n.sessionHighBid=d;break;case m.MDEntryType.SessionLowOffer:n.sessionLowOffer=d;break;case m.MDEntryType.EarlyPrices:n.earlyPrices=d;break;case m.MDEntryType.AuctionClearingPrice:n.auctionClearingPrice=d;break;case m.MDEntryType.SwapValueFactor:n.swapValueFactor=d;break;case m.MDEntryType.DailyValueAdjustmentForLongPositions:n.dailyValueAdjustmentForLongPositions=d;break;case m.MDEntryType.CumulativeValueAdjustmentForLongPositions:n.cumulativeValueAdjustmentForLongPositions=d;break;case m.MDEntryType.DailyValueAdjustmentForShortPositions:n.dailyValueAdjustmentForShortPositions=d;break;case m.MDEntryType.CumulativeValueAdjustmentForShortPositions:n.cumulativeValueAdjustmentForShortPositions=d;break;case m.MDEntryType.FixingPrice:n.fixingPrice=d;break;case m.MDEntryType.CashRate:n.cashRate=d;break;case m.MDEntryType.RecoveryRate:n.recoveryRate=d;break;case m.MDEntryType.RecoveryRateForLong:n.recoveryRateForLong=d;break;case m.MDEntryType.RecoveryRateForShort:n.recoveryRateForShort=d;break;case m.MDEntryType.MarketBid:n.marketBid=d;break;case m.MDEntryType.MarketOffer:n.marketOffer=d;break;case m.MDEntryType.ShortSaleMinPrice:n.shortSaleMinPrice=d;break;case m.MDEntryType.PreviousClosingPrice:n.previousClosingPrice=d;break;case m.MDEntryType.ThresholdLimitPriceBanding:n.thresholdLimitPriceBanding=d;break;case m.MDEntryType.DailyFinancingValue:n.dailyFinancingValue=d;break;case m.MDEntryType.AccruedFinancingValue:n.accruedFinancingValue=d;break;case m.MDEntryType.TWAP:n.twap=d;break}}n.spread=n.offer-n.bid,i.has(s)||i.set(s,[]);let P=i.get(s);P.push(n),P.length>a&&P.splice(0,P.length-a),o?.(s,n);let v=t.getField(m.Fields.MDReqID)?.value;if(v){let f=e.get(v);f&&(f(t),e.delete(v))}}else if(h===m.Messages.ExecutionReport){let s=t.getField(m.Fields.ClOrdID)?.value,u=e.get(s);u&&(u(t),e.delete(s))}}var Q=class extends we{verifiedOrders=new Map;pendingRequests=new Map;marketDataPrices=new Map;MAX_PRICE_HISTORY=1e5;server=new J.Server({name:"fixparser",version:"1.0.0"},{capabilities:{tools:Object.entries(X).reduce((t,[r,{description:e,schema:i}])=>(t[r]={description:e,parameters:i},t),{})}});transport=new z.StdioServerTransport;constructor({logger:t,onReady:r}){super({logger:t,onReady:r})}async register(t){this.parser=t,this.parser.addOnMessageCallback(r=>{Ne(r,this.parser,this.pendingRequests,this.marketDataPrices,this.MAX_PRICE_HISTORY)}),this.addWorkflows(),await this.server.connect(this.transport),this.onReady&&this.onReady()}addWorkflows(){this.parser&&this.server&&(this.server.setRequestHandler(b.z.object({method:b.z.literal("tools/list")}),async()=>({tools:Object.entries(X).map(([t,{description:r,schema:e}])=>({name:t,description:r,inputSchema:e}))})),this.server.setRequestHandler(b.z.object({method:b.z.literal("tools/call"),params:b.z.object({name:b.z.string(),arguments:b.z.any(),_meta:b.z.object({progressToken:b.z.number()}).optional()})}),async t=>{let{name:r,arguments:e}=t.params,a=Be(this.parser,this.verifiedOrders,this.pendingRequests,this.marketDataPrices)[r];if(!a)return{content:[{type:"text",text:`Tool not found: ${r}`,uri:r}],isError:!0};let o=await a(e);return{content:o.content,isError:o.isError}}),process.on("SIGINT",async()=>{await this.server.close(),process.exit(0)}))}};var $e=async()=>{await p.LicenseManager.setLicenseKey(process.env.FIXPARSER_LICENSE_KEY);let t=process.env.FIXPARSER_SENDER||"SENDER",r=process.env.FIXPARSER_TARGET||"TARGET",e=new p.FIXParser({logging:!0,logOptions:{level:"info",format:"jsonrpc",transport:new U({format:"jsonrpc"})},plugins:[new Q({port:3099,onReady:()=>{}})]}),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,t),new p.Field(p.Fields.SendingTime,e.getTimestamp()),new p.Field(p.Fields.TargetCompID,r),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));e.send(o)},a={host:process.env.FIXPARSER_HOST||"10.0.1.42",port:process.env.FIXPARSER_PORT?Number.parseInt(process.env.FIXPARSER_PORT,10):5001,protocol:"tcp",sender:t,target:r,fixVersion:"FIX.4.4",onOpen:()=>{e.logger.log({level:"info",message:"FIXParser logging in..."}),i()},onClose:()=>{e.logger.log({level:"info",message:"FIXParser disconnected. Reconnecting in 1 second..."}),setTimeout(()=>{e.connect(a)},1e3)}};e.connect(a)};$e().catch(t=>console.error("Error initializing server:",t));
18
+ //# sourceMappingURL=example_mcp_local.js.map