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