fixparser-plugin-mcp 9.1.7-70d519a1 → 9.1.7-74db6dbc

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