fixparser-plugin-mcp 9.1.7-5d282a9e → 9.1.7-620b3399

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,18 +0,0 @@
1
- #!/usr/bin/env node
2
- "use strict";var Pe=Object.create;var X=Object.defineProperty;var ve=Object.getOwnPropertyDescriptor;var Se=Object.getOwnPropertyNames;var Me=Object.getPrototypeOf,we=Object.prototype.hasOwnProperty;var be=(t,r,e,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let l of Se(r))!we.call(t,l)&&l!==e&&X(t,l,{get:()=>r[l],enumerable:!(n=ve(r,l))||n.enumerable});return t};var Re=(t,r,e)=>(e=t!=null?Pe(Me(t)):{},be(r||!t||!t.__esModule?X(e,"default",{value:t,enumerable:!0}):e,t));var b=require("fixparser");var J=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,...n}=t,l={jsonrpc:"2.0",method:t.level,params:{message:e,...n},id:t.id||Date.now()};r(JSON.stringify(l))}else{let{name:e,id:n,message:l,level:o,...c}=t,i=Object.entries(c).map(([a,s])=>`${a}: ${s}`),u="";e&&(u+=`${e} `),u+=`${n}: ${l}`,r(u,i.join(", "))}}async flush(){}async close(){}status(){return"connected"}};var Fe=require("@modelcontextprotocol/sdk/server/index.js"),Ce=require("@modelcontextprotocol/sdk/server/stdio.js"),Oe=require("zod"),m=require("fixparser"),z=Re(require("quickchart-js"),1),w=require("fixparser"),y=require("fixparser"),_=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"),O=require("zod"),xe=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}},Ie={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 ke(t){return t.reduce((r,e)=>r+e,0)}var Ae=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 n=r-1;n<t.length;n++){let l=t.slice(n-r+1,n+1).reduce((o,c)=>o+c,0);e.push(l/r)}return e}calculateEMA(t,r){let e=2/(r+1),n=[t[0]];for(let l=1;l<t.length;l++)n.push(t[l]*e+n[l-1]*(1-e));return n}calculateRSI(t,r=14){if(t.length<r+1)return[];let e=[];for(let u=1;u<t.length;u++)e.push(t[u]-t[u-1]);let n=e.map(u=>u>0?u:0),l=e.map(u=>u<0?Math.abs(u):0),o=n.slice(0,r).reduce((u,a)=>u+a,0)/r,c=l.slice(0,r).reduce((u,a)=>u+a,0)/r,i=[];for(let u=r;u<e.length;u++){let a=o/c;i.push(100-100/(1+a)),o=(o*(r-1)+n[u])/r,c=(c*(r-1)+l[u])/r}return i}calculateBollingerBands(t,r=20,e=2){if(t.length<r)return[];let n=this.calculateSMA(t,r),l=[];for(let o=0;o<n.length;o++){let c=t.slice(o,o+r),i=n[o],u=c.reduce((p,P)=>p+(P-i)**2,0)/r,a=Math.sqrt(u),s=i+a*e,d=i-a*e;l.push({upper:s,middle:i,lower:d,bandwidth:(s-d)/i*100,percentB:(t[o]-d)/(s-d)*100})}return l}calculateMaxDrawdown(t){let r=t[0],e=0;for(let n=1;n<t.length;n++){t[n]>r&&(r=t[n]);let l=(r-t[n])/r;l>e&&(e=l)}return e}calculateAtr(t,r,e){if(t.length<2)return[];let n=[];for(let o=1;o<t.length;o++){let c=r[o]||t[o],i=e[o]||t[o],u=t[o-1],a=c-i,s=Math.abs(c-u),d=Math.abs(i-u);n.push(Math.max(a,s,d))}let l=[];if(n.length>=14){let o=n.slice(0,14).reduce((c,i)=>c+i,0);l.push(o/14);for(let c=14;c<n.length;c++)o=o-n[c-14]+n[c],l.push(o/14)}return l}calculateMaxConsecutiveLosses(t){let r=0,e=0;for(let n=1;n<t.length;n++)t[n]<t[n-1]?(e++,r=Math.max(r,e)):e=0;return r}calculateWinRate(t){let r=0,e=0;for(let n=1;n<t.length;n++)t[n]!==t[n-1]&&(e++,t[n]>t[n-1]&&r++);return e>0?r/e:0}calculateProfitFactor(t){let r=0,e=0;for(let n=1;n<t.length;n++){let l=t[n]-t[n-1];l>0?r+=l:e+=Math.abs(l)}return e>0?r/e:0}calculateWma(t,r){let e=[],n=Array.from({length:r},(o,c)=>c+1),l=n.reduce((o,c)=>o+c,0);for(let o=r-1;o<t.length;o++){let c=0;for(let i=0;i<r;i++)c+=t[o-i]*n[i];e.push(c/l)}return e}calculateVwma(t,r){let e=[];for(let n=r-1;n<t.length;n++){let l=0,o=0;for(let c=0;c<r;c++){let i=this.volumes[n-c]||1;l+=i,o+=t[n-c]*i}e.push(o/l)}return e}calculateMacd(t){let r=this.calculateEMA(t,12),e=this.calculateEMA(t,26),n=[],l=[];for(let c=0;c<Math.min(r.length,e.length);c++)l.push(r[c]-e[c]);let o=this.calculateEMA(l,9);for(let c=0;c<Math.min(l.length,o.length);c++)n.push({macd:l[c],signal:o[c],histogram:l[c]-o[c]});return n}calculateAdx(t,r,e){if(t.length<14)return[];let n=14,l=[],o=[],c=[],i=[];o.push(r[0]-e[0]),c.push(0),i.push(0);for(let f=1;f<t.length;f++){let g=r[f]||t[f],v=e[f]||t[f],F=r[f-1]||t[f-1],k=e[f-1]||t[f-1],L=t[f-1],A=g-v,T=Math.abs(g-L),x=Math.abs(v-L);o.push(Math.max(A,T,x));let V=g-F,C=k-v;V>C&&V>0?(c.push(V),i.push(0)):C>V&&C>0?(c.push(0),i.push(C)):(c.push(0),i.push(0))}let u=[],a=[],s=[],d=0,p=0,P=0;for(let f=0;f<n;f++)d+=o[f],p+=c[f],P+=i[f];u.push(d),a.push(p),s.push(P);for(let f=n;f<o.length;f++){let g=u[u.length-1]-u[u.length-1]/n+o[f],v=a[a.length-1]-a[a.length-1]/n+c[f],F=s[s.length-1]-s[s.length-1]/n+i[f];u.push(g),a.push(v),s.push(F)}let M=[],h=[];for(let f=0;f<u.length;f++)M.push(a[f]/u[f]*100),h.push(s[f]/u[f]*100);let S=[];for(let f=0;f<M.length;f++){let g=M[f]+h[f],v=Math.abs(M[f]-h[f]);S.push(g>0?v/g*100:0)}if(S.length<n)return[];let R=0;for(let f=0;f<n;f++)R+=S[f];l.push(R/n);for(let f=n;f<S.length;f++){let g=l[l.length-1]-l[l.length-1]/n+S[f];l.push(g)}return l}calculateDmi(t,r,e){if(t.length<14)return[];let n=14,l=[],o=[],c=[],i=[];o.push(r[0]-e[0]),c.push(0),i.push(0);for(let g=1;g<t.length;g++){let v=r[g]||t[g],F=e[g]||t[g],k=r[g-1]||t[g-1],L=e[g-1]||t[g-1],A=t[g-1],T=v-F,x=Math.abs(v-A),V=Math.abs(F-A);o.push(Math.max(T,x,V));let C=v-k,D=L-F;C>D&&C>0?(c.push(C),i.push(0)):D>C&&D>0?(c.push(0),i.push(D)):(c.push(0),i.push(0))}let u=[],a=[],s=[],d=0,p=0,P=0;for(let g=0;g<n;g++)d+=o[g],p+=c[g],P+=i[g];u.push(d),a.push(p),s.push(P);for(let g=n;g<o.length;g++){let v=u[u.length-1]-u[u.length-1]/n+o[g],F=a[a.length-1]-a[a.length-1]/n+c[g],k=s[s.length-1]-s[s.length-1]/n+i[g];u.push(v),a.push(F),s.push(k)}let M=[],h=[];for(let g=0;g<u.length;g++)M.push(a[g]/u[g]*100),h.push(s[g]/u[g]*100);let S=[];for(let g=0;g<M.length;g++){let v=M[g]+h[g],F=Math.abs(M[g]-h[g]);S.push(v>0?F/v*100:0)}if(S.length<n)return[];let R=[],f=0;for(let g=0;g<n;g++)f+=S[g];R.push(f/n);for(let g=n;g<S.length;g++){let v=R[R.length-1]-R[R.length-1]/n+S[g];R.push(v)}for(let g=0;g<R.length;g++)l.push({plusDI:M[g+n-1]||0,minusDI:h[g+n-1]||0,adx:R[g]});return l}calculateIchimoku(t,r,e){if(t.length<52)return[];let n=[],l=[];for(let s=8;s<t.length;s++){let d=Math.max(...r.slice(s-8,s+1)),p=Math.min(...e.slice(s-8,s+1));l.push((d+p)/2)}let o=[];for(let s=25;s<t.length;s++){let d=Math.max(...r.slice(s-25,s+1)),p=Math.min(...e.slice(s-25,s+1));o.push((d+p)/2)}let c=[];for(let s=0;s<Math.min(l.length,o.length);s++)c.push((l[s]+o[s])/2);let i=[];for(let s=51;s<t.length;s++){let d=Math.max(...r.slice(s-51,s+1)),p=Math.min(...e.slice(s-51,s+1));i.push((d+p)/2)}let u=[];for(let s=26;s<t.length;s++)u.push(t[s-26]);let a=Math.min(l.length,o.length,c.length,i.length,u.length);for(let s=0;s<a;s++)n.push({tenkan:l[s],kijun:o[s],senkouA:c[s],senkouB:i[s],chikou:u[s]});return n}calculateParabolicSAR(t,r,e){if(t.length<2)return[];let n=[],l=.02,o=.2,c=e[0],i=!0,u=l,a=r[0];n.push(c);for(let s=1;s<t.length;s++){let d=r[s]||t[s],p=e[s]||t[s];if(i){if(p<c)i=!1,c=a,a=p,u=l;else if(d>a&&(a=d,u=Math.min(u+l,o)),c=c+u*(a-c),s>0){let P=e[s-1]||t[s-1];c=Math.min(c,P)}}else if(d>c)i=!0,c=a,a=d,u=l;else if(p<a&&(a=p,u=Math.min(u+l,o)),c=c+u*(a-c),s>0){let P=r[s-1]||t[s-1];c=Math.max(c,P)}n.push(c)}return n}calculateStochastic(t,r,e){let n=[];if(t.length<14)return[];let i=[];for(let a=13;a<t.length;a++){let s=Math.max(...r.slice(a-14+1,a+1)),d=Math.min(...e.slice(a-14+1,a+1)),P=(t[a]-d)/(s-d)*100;i.push(P)}let u=[];for(let a=2;a<i.length;a++){let s=i.slice(a-3+1,a+1).reduce((d,p)=>d+p,0);u.push(s/3)}for(let a=2;a<u.length;a++){let d=u.slice(a-3+1,a+1).reduce((p,P)=>p+P,0)/3;n.push({k:u[a],d})}return n}calculateCci(t,r,e){let n=[];if(t.length<20)return[];for(let o=19;o<t.length;o++){let i=t.slice(o-20+1,o+1).map((p,P)=>{let M=r[o-20+1+P]||p,h=e[o-20+1+P]||p;return(M+h+p)/3}),u=i.reduce((p,P)=>p+P,0)/20,a=i.reduce((p,P)=>p+Math.abs(P-u),0)/20,s=(r[o]+e[o]+t[o])/3,d=a!==0?(s-u)/(.015*a):0;n.push(d)}return n}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=[];if(t.length<14)return[];for(let n=13;n<t.length;n++){let l=t.slice(n-14+1,n+1),o=Math.max(...l),c=Math.min(...l),i=t[n],u=(o-i)/(o-c)*-100;r.push(u)}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 n=[];if(t.length<20)return[];let c=this.calculateEMA(t,20),i=this.calculateAtr(t,r,e);for(let u=0;u<Math.min(c.length,i.length);u++){let a=c[u],s=i[u];n.push({upper:a+2*s,middle:a,lower:a-2*s})}return n}calculateDonchianChannels(t){let r=[];for(let e=20;e<t.length;e++){let n=t.slice(e-20,e);r.push({upper:Math.max(...n),middle:(Math.max(...n)+Math.min(...n))/2,lower:Math.min(...n)})}return r}calculateChaikinVolatility(t,r,e){let n=[];if(t.length<10*2)return[];let o=[];for(let i=0;i<t.length;i++){let u=r[i]||t[i],a=e[i]||t[i];o.push(u-a)}let c=this.calculateEMA(o,10);for(let i=10;i<c.length;i++){let u=c[i],a=c[i-10],s=a!==0?(u-a)/a*100:0;n.push(s)}return n}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,n){let l=[];if(t.length<20)return[];for(let c=19;c<t.length;c++){let i=0,u=0;for(let s=c-20+1;s<=c;s++){let d=r[s]||t[s],p=e[s]||t[s],P=t[s],M=n[s]||1,S=(P-p-(d-P))/(d-p)*M;i+=S,u+=M}let a=u!==0?i/u:0;l.push(a)}return l}calculateAdl(t){let r=[0];for(let e=1;e<t.length;e++){let n=this.highs[e]||t[e],l=this.lows[e]||t[e],o=t[e],c=this.volumes[e]||1,u=(o-l-(n-o))/(n-l)*c;r.push(r[e-1]+u)}return r}calculateVolumeROC(){let t=[];for(let r=10;r<this.volumes.length;r++)t.push((this.volumes[r]-this.volumes[r-10])/this.volumes[r-10]*100);return t}calculateMfi(t,r,e,n){let l=[];if(t.length<15)return[];for(let c=14;c<t.length;c++){let i=0,u=0;for(let d=c-14+1;d<=c;d++){let p=r[d]||t[d],P=e[d]||t[d],M=t[d],h=n[d]||1,S=(p+P+M)/3,R=S*h;if(d>c-14+1){let f=r[d-1]||t[d-1],g=e[d-1]||t[d-1],v=t[d-1],F=(f+g+v)/3;S>F?i+=R:S<F&&(u+=R)}}let s=100-100/(1+(u!==0?i/u:0));l.push(s)}return l}calculateVwap(t,r){let e=[],n=0,l=0;for(let o=0;o<t.length;o++)n+=t[o]*(r[o]||1),l+=r[o]||1,e.push(n/l);return e}calculatePivotPoints(t){let r=[];for(let e=0;e<t.length;e++){let n=this.highs[e]||t[e],l=this.lows[e]||t[e],o=t[e],c=(n+l+o)/3,i=2*c-l,u=2*c-n,a=c+(n-l),s=c-(n-l),d=n+2*(c-l),p=l-2*(n-c);r.push({pp:c,r1:i,r2:a,r3:d,s1:u,s2:s,s3:p})}return r}calculateFibonacciLevels(t){let r=[];for(let e=0;e<t.length;e++){let n=t[e];r.push({retracement:{level0:n,level236:n*.764,level382:n*.618,level500:n*.5,level618:n*.382,level786:n*.214,level100:n*0},extension:{level1272:n*1.272,level1618:n*1.618,level2618:n*2.618,level4236:n*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=[];if(t.length<10)return[];for(let e=0;e<t.length;e++){let n=[],l=1,o=.5;if(e>=4){let c=t.slice(e-4,e+1),i=this.detectPriceSwings(c);i.length>=3&&(n.push(...i.slice(0,3)),l=Math.min(i.length,5),o=this.calculateWavePosition(c))}r.push({waves:n.length>0?n:[t[e]],currentWave:l,wavePosition:o})}return r}detectPriceSwings(t){let r=[];for(let e=1;e<t.length-1;e++){let n=t[e-1],l=t[e],o=t[e+1];(l>n&&l>o||l<n&&l<o)&&r.push(l)}return r}calculateWavePosition(t){if(t.length<2)return .5;let r=t[t.length-1],e=Math.min(...t),n=Math.max(...t);return n!==e?(r-e)/(n-e):.5}calculateHarmonicPatterns(t){let r=[];if(t.length<5)return[];for(let e=4;e<t.length;e++){let n=t.slice(e-4,e+1),l=this.detectHarmonicPattern(n);r.push(l)}return r}detectHarmonicPattern(t){if(t.length<5)return{type:"Unknown",completion:0,target:t[t.length-1]*1.1,stopLoss:t[t.length-1]*.9};let r=this.detectPriceSwings(t);if(r.length<4)return{type:"Unknown",completion:0,target:t[t.length-1]*1.1,stopLoss:t[t.length-1]*.9};let[e,n,l,o]=r.slice(-4),c=t[0],i=Math.abs((n-e)/(c-e)),u=Math.abs((l-n)/(e-n)),a=Math.abs((o-l)/(n-l)),s=Math.abs((o-e)/(c-e));if(Math.abs(i-.618)<.1&&u>=.382&&u<=.886&&a>=1.13&&a<=1.618&&Math.abs(s-.786)<.1){let P=this.calculatePatternCompletion(t),M=o+(o-l)*.618,h=o-(o-l)*.382;return{type:"Gartley",completion:P,target:M,stopLoss:h}}if(Math.abs(i-.786)<.1&&u>=.382&&u<=.886&&a>=1.618&&a<=2.618&&Math.abs(s-1.27)<.1){let P=this.calculatePatternCompletion(t),M=o+(o-l)*1.27,h=o-(o-l)*.5;return{type:"Butterfly",completion:P,target:M,stopLoss:h}}return{type:"Unknown",completion:0,target:t[t.length-1]*1.1,stopLoss:t[t.length-1]*.9}}calculatePatternCompletion(t){if(t.length<2)return 0;let r=t[t.length-1],e=Math.min(...t),n=Math.max(...t);return n!==e?(r-e)/(n-e):0}calculatePositionSize(t,r,e){let n=Math.abs(r-e);return n>0?100/n:1}calculateConfidence(t){return Math.min(t.length*10,100)}calculateRiskLevel(t){return t<20?"LOW":t<40?"MEDIUM":"HIGH"}calculateZScore(t,r){return(t-r)/(r*.1)}calculateOrnsteinUhlenbeck(t,r,e){let n=this.calculatePriceChanges(),l=r,o=.1;if(n.length>1){let i=n.reduce((u,a)=>u+a*a,0)/n.length;o=Math.max(.01,Math.min(1,i*10))}let c=e*.01;return{mean:l,speed:o,volatility:c,currentValue:t}}calculateKalmanFilter(t,r,e){let n=e*.001,l=e*1e-4,o=r,c=n;if(this.calculatePriceChanges().length>0){let u=o,a=c+l,s=a/(a+n);return o=u+s*(t-u),c=(1-s)*a,{state:o,covariance:c,gain:s}}return{state:t,covariance:c,gain:.5}}calculateArima(t){let r=this.calculatePriceChanges();if(r.length<3)return{forecast:[t*1.01,t*1.02],residuals:[0,0],aic:100};let e=r.length,n=0,l=0,o=0,c=0;for(let h=1;h<e;h++){let S=r[h],R=r[h-1];n+=S,l+=R,o+=S*R,c+=R*R}let i=(e*o-n*l)/(e*c-l*l),u=(n-i*l)/e,a=[];for(let h=1;h<e;h++){let S=u+i*r[h-1];a.push(r[h]-S)}let s=a.reduce((h,S)=>h+S*S,0),d=e*Math.log(s/e)+2*2,p=r[r.length-1],P=t+(u+i*p),M=P+(u+i*(u+i*p));return{forecast:[P,M],residuals:a,aic:d}}calculateGarch(t){let r=this.calculatePriceChanges();if(r.length<5)return{volatility:t*.01,persistence:.9,meanReversion:.1};let e=r.map(i=>i*i),n=e.reduce((i,u)=>i+u,0)/e.length,l=.9;if(e.length>1){let i=e.reduce((u,a)=>u+a,0)/e.length;l=Math.min(.99,Math.max(.5,i/n))}let o=n*(1-l);return{volatility:Math.sqrt(n),persistence:l,meanReversion:o}}calculateHilbertTransform(t){let r=this.calculatePriceChanges();if(r.length<3)return{analytic:[t],phase:[0],amplitude:[t]};let e=r.length,n=[],l=[],o=[];for(let c=0;c<e;c++){let i=0;for(let p=0;p<e;p++)c!==p&&(i+=r[p]/(Math.PI*(c-p)));let u=r[c],a=i,s=Math.sqrt(u*u+a*a);n.push(s);let d=Math.atan2(a,u);l.push(d),o.push(s)}return{analytic:n,phase:l,amplitude:o}}calculateWaveletTransform(t){let r=this.calculatePriceChanges();if(r.length<4)return{coefficients:[t],scales:[1]};let e=[],n=[],l=r.length,o=Math.floor(Math.log2(l));for(let c=1;c<=o;c++){let i=2**(c-1),u=i;for(let a=0;a<l-i;a+=i*2)if(a+i<l){let s=(r[a]-r[a+i])/Math.sqrt(2);e.push(s),n.push(u)}}return e.length===0&&(e.push(t),n.push(1)),{coefficients:e,scales:n}}calculateBlackScholes(t,r,e){let n=t,l=r,o=1,c=.05,i=e*.01,u=(Math.log(n/l)+(c+i*i/2)*o)/(i*Math.sqrt(o)),a=u-i*Math.sqrt(o),s=n*this.normalCDF(u)-l*Math.exp(-c*o)*this.normalCDF(a),d=l*Math.exp(-c*o)*this.normalCDF(-a)-n*this.normalCDF(-u);return{callPrice:s,putPrice:d,delta:this.normalCDF(u),gamma:this.normalPDF(u)/(n*i*Math.sqrt(o)),theta:-n*this.normalPDF(u)*i/(2*Math.sqrt(o))-c*l*Math.exp(-c*o)*this.normalCDF(a),vega:n*Math.sqrt(o)*this.normalPDF(u),rho:l*o*Math.exp(-c*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,n=1.421413741,l=-1.453152027,o=1.061405429,c=.3275911,i=t>=0?1:-1,u=Math.abs(t),a=1/(1+c*u),s=1-((((o*a+l)*a+n)*a+e)*a+r)*a*Math.exp(-u*u);return i*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),n=Math.min(...this.lows),l=ke(this.volumes),o=l/this.volumes.length,c=this.calculatePriceChanges(),i=c.length>0?Math.sqrt(c.reduce((A,T)=>A+T**2,0)/c.length)*Math.sqrt(252)*100:0,u=(t-r)/r*100,a=(t-n)/(e-n)*100,s=this.prices.reduce((A,T,x)=>A+T*this.volumes[x],0)/l,d=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,P=this.calculateMaxDrawdown(this.prices),M=this.calculateAtr(this.prices,this.highs,this.lows),h=M.length>0?M[M.length-1]:0,S=i,R=i,f=u/i,g=u/R,v=u/P,F=this.calculateMaxConsecutiveLosses(this.prices),k=this.calculateWinRate(this.prices),L=this.calculateProfitFactor(this.prices);return{currentPrice:t,startPrice:r,sessionHigh:e,sessionLow:n,totalVolume:l,avgVolume:o,volatility:i,sessionReturn:u,pricePosition:a,trueVWAP:s,momentum5:d,momentum10:p,maxDrawdown:P,atr:h,impliedVolatility:S,realizedVolatility:R,sharpeRatio:f,sortinoRatio:g,calmarRatio:v,maxConsecutiveLosses:F,winRate:k,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),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(),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,n=[];t.currentPrice>t.trueVWAP?(n.push(`\u2713 BULLISH: Price above VWAP (+${((t.currentPrice-t.trueVWAP)/t.trueVWAP*100).toFixed(2)}%)`),r++):(n.push(`\u2717 BEARISH: Price below VWAP (${((t.currentPrice-t.trueVWAP)/t.trueVWAP*100).toFixed(2)}%)`),e++),t.momentum5>0&&t.momentum10>0?(n.push("\u2713 BULLISH: Positive momentum on both timeframes"),r++):t.momentum5<0&&t.momentum10<0?(n.push("\u2717 BEARISH: Negative momentum on both timeframes"),e++):n.push("\u25D0 MIXED: Conflicting momentum signals");let o=this.volumes[this.volumes.length-1]/t.avgVolume;return o>1.2&&t.sessionReturn>0?(n.push("\u2713 BULLISH: Above-average volume supporting upward move"),r++):o>1.2&&t.sessionReturn<0?(n.push("\u2717 BEARISH: Above-average volume supporting downward move"),e++):n.push("\u25D0 NEUTRAL: Volume not providing clear direction"),t.pricePosition>65&&t.volatility>30?(n.push("\u2717 BEARISH: High in range with elevated volatility - reversal risk"),e++):t.pricePosition<35&&t.volatility>30?(n.push("\u2713 BULLISH: Low in range with volatility - potential bounce"),r++):n.push("\u25D0 NEUTRAL: Price position and volatility not extreme"),{bullishSignals:r,bearishSignals:e,signals:n}}generateJSONAnalysis(t){let r=this.analyze(),e=this.getTechnicalIndicators(),n=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,c=e.sma20.length>0?e.sma20[e.sma20.length-1]:null,i=e.sma50.length>0?e.sma50[e.sma50.length-1]:null,u=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],d=e.ema21[e.ema21.length-1],p=e.ema26[e.ema26.length-1],P=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,S=e.adx.length>0?e.adx[e.adx.length-1]:null,R=e.dmi.length>0?e.dmi[e.dmi.length-1]:null,f=e.ichimoku.length>0?e.ichimoku[e.ichimoku.length-1]:null,g=e.parabolicSAR.length>0?e.parabolicSAR[e.parabolicSAR.length-1]:null,v=e.rsi.length>0?e.rsi[e.rsi.length-1]:null,F=e.stochastic.length>0?e.stochastic[e.stochastic.length-1]:null,k=e.cci.length>0?e.cci[e.cci.length-1]:null,L=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,x=e.bollinger.length>0?e.bollinger[e.bollinger.length-1]:null,V=e.atr.length>0?e.atr[e.atr.length-1]:null,C=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,ne=e.adl.length>0?e.adl[e.adl.length-1]:null,se=e.volumeROC.length>0?e.volumeROC[e.volumeROC.length-1]:null,W=e.mfi.length>0?e.mfi[e.mfi.length-1]:null,ie=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/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,H=n.bullishSignals-n.bearishSignals,pe=H>0?"BULLISH_BIAS":H<0?"BEARISH_BIAS":"NEUTRAL",N=Math.max(r.sessionLow*1.005,r.trueVWAP*.998),B=r.sessionLow*.995,$=r.sessionHigh*.995,fe=($-r.currentPrice)/(r.currentPrice-B),U=this.calculatePositionSize(r.currentPrice,N,B),ye=U*(N-B);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:c,sma50:i,sma200:u,ema8:a,ema12:s,ema21:d,ema26:p,wma20:P,vwma20:M,macd:h,adx:S,dmi:R,ichimoku:f,parabolicSAR:g,rsi:v,stochastic:F,cci:k,roc:L,williamsR:A,momentum:T,bollingerBands:x?{upper:x.upper,middle:x.middle,lower:x.lower,bandwidth:x.bandwidth,percentB:x.percentB}:null,atr:V,keltnerChannels:C?{upper:C.upper,middle:C.middle,lower:C.lower}:null,donchianChannels:D?{upper:D.upper,middle:D.middle,lower:D.lower}:null,chaikinVolatility:re,obv:j,cmf:q,adl:ne,volumeROC:se,mfi:W,vwap:ie},volumeAnalysis:{currentVolume:G,averageVolume:Math.round(r.avgVolume),volumeRatio:he,trueVWAP:r.trueVWAP,priceVsVWAP:ge,obv:j,cmf:q,mfi:W},momentum:{momentum5:r.momentum5,momentum10:r.momentum10,sessionROC:r.sessionReturn,rsi:v,stochastic:F,cci:k},supportResistance:{pivotPoints:oe,fibonacci:ae,gannLevels:le,elliottWave:ce,harmonicPatterns:ue},tradingSignals:{...n,overallSignal:pe,signalScore:H,confidence:this.calculateConfidence(n.signals),riskLevel:this.calculateRiskLevel(r.volatility)},statisticalModels:{zScore:this.calculateZScore(r.currentPrice,r.startPrice),ornsteinUhlenbeck:this.calculateOrnsteinUhlenbeck(r.currentPrice,r.startPrice,r.avgVolume),kalmanFilter:this.calculateKalmanFilter(r.currentPrice,r.startPrice,r.avgVolume),arima:this.calculateArima(r.currentPrice),garch:this.calculateGarch(r.avgVolume),hilbertTransform:this.calculateHilbertTransform(r.currentPrice),waveletTransform:this.calculateWaveletTransform(r.currentPrice)},optionsAnalysis:(()=>{let I=this.calculateBlackScholes(r.currentPrice,r.startPrice,r.avgVolume);return I?{blackScholes:I,impliedVolatility:r.impliedVolatility,delta:I.delta,gamma:I.gamma,theta:I.theta,vega:I.vega,rho:I.rho,greeks:{delta:I.delta,gamma:I.gamma,theta:I.theta,vega:I.vega,rho:I.rho}}:null})(),riskManagement:{targetEntry:N,stopLoss:B,profitTarget:$,riskRewardRatio:fe,positionSize:U,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}}}},Te=t=>async r=>{try{let e=r.symbol,n=t.get(e)||[];if(n.length===0)return{content:[{type:"text",text:`No price data available for ${e}. Please request market data first.`,uri:"technicalAnalysis"}]};if(!n.every(i=>typeof i.trade=="number"&&!Number.isNaN(i.trade)&&typeof i.midPrice=="number"&&!Number.isNaN(i.midPrice)))throw new Error("Invalid market data");let c=new Ae(n).generateJSONAnalysis(e);return{content:[{type:"text",text:`Technical Analysis for ${e}:
3
-
4
- ${JSON.stringify(c,null,2)}`,uri:"technicalAnalysis"}]}}catch(e){return{content:[{type:"text",text:`Error performing technical analysis: ${e instanceof Error?e.message:"Unknown error"}`,uri:"technicalAnalysis"}],isError:!0}}},De=(t,r)=>async e=>{try{t.logger.log({level:"info",message:`Sending market data request for symbols: ${e.symbols.join(", ")}`});let n=new Promise(u=>{r.set(e.mdReqID,u),t.logger.log({level:"info",message:`Registered callback for market data request ID: ${e.mdReqID}`})}),l=e.mdEntryTypes||[m.MDEntryType.Bid,m.MDEntryType.Offer,m.MDEntryType.Trade,m.MDEntryType.IndexValue,m.MDEntryType.OpeningPrice,m.MDEntryType.ClosingPrice,m.MDEntryType.SettlementPrice,m.MDEntryType.TradingSessionHighPrice,m.MDEntryType.TradingSessionLowPrice,m.MDEntryType.VWAP,m.MDEntryType.Imbalance,m.MDEntryType.TradeVolume,m.MDEntryType.OpenInterest,m.MDEntryType.CompositeUnderlyingPrice,m.MDEntryType.SimulatedSellPrice,m.MDEntryType.SimulatedBuyPrice,m.MDEntryType.MarginRate,m.MDEntryType.MidPrice,m.MDEntryType.EmptyBook,m.MDEntryType.SettleHighPrice,m.MDEntryType.SettleLowPrice,m.MDEntryType.PriorSettlePrice,m.MDEntryType.SessionHighBid,m.MDEntryType.SessionLowOffer,m.MDEntryType.EarlyPrices,m.MDEntryType.AuctionClearingPrice,m.MDEntryType.SwapValueFactor,m.MDEntryType.DailyValueAdjustmentForLongPositions,m.MDEntryType.CumulativeValueAdjustmentForLongPositions,m.MDEntryType.DailyValueAdjustmentForShortPositions,m.MDEntryType.CumulativeValueAdjustmentForShortPositions,m.MDEntryType.FixingPrice,m.MDEntryType.CashRate,m.MDEntryType.RecoveryRate,m.MDEntryType.RecoveryRateForLong,m.MDEntryType.RecoveryRateForShort,m.MDEntryType.MarketBid,m.MDEntryType.MarketOffer,m.MDEntryType.ShortSaleMinPrice,m.MDEntryType.PreviousClosingPrice,m.MDEntryType.ThresholdLimitPriceBanding,m.MDEntryType.DailyFinancingValue,m.MDEntryType.AccruedFinancingValue,m.MDEntryType.TWAP],o=[new m.Field(m.Fields.MsgType,m.Messages.MarketDataRequest),new m.Field(m.Fields.SenderCompID,t.sender),new m.Field(m.Fields.MsgSeqNum,t.getNextTargetMsgSeqNum()),new m.Field(m.Fields.TargetCompID,t.target),new m.Field(m.Fields.SendingTime,t.getTimestamp()),new m.Field(m.Fields.MDReqID,e.mdReqID),new m.Field(m.Fields.SubscriptionRequestType,e.subscriptionRequestType),new m.Field(m.Fields.MarketDepth,0),new m.Field(m.Fields.MDUpdateType,e.mdUpdateType)];o.push(new m.Field(m.Fields.NoRelatedSym,e.symbols.length)),e.symbols.forEach(u=>{o.push(new m.Field(m.Fields.Symbol,u))}),o.push(new m.Field(m.Fields.NoMDEntryTypes,l.length)),l.forEach(u=>{o.push(new m.Field(m.Fields.MDEntryType,u))});let c=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(c?.toFIXJSON())}`}),t.send(c);let i=await n;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(i.toFIXJSON())}`,uri:"marketDataRequest"}]}}catch(n){return{content:[{type:"text",text:`Error: ${n instanceof Error?n.message:"Failed to request market data"}`,uri:"marketDataRequest"}],isError:!0}}},K=(t,r=490)=>{if(t.length<=r)return t;let e=[],n=t.length/r;e.push(t[0]);for(let l=1;l<r-1;l++){let o=Math.floor(l*n),c=Math.floor((l+1)*n),i=t.slice(o,c);if(i.length===0)continue;let u={timestamp:i[0].timestamp,bid:i.reduce((a,s)=>a+s.bid,0)/i.length,offer:i.reduce((a,s)=>a+s.offer,0)/i.length,spread:i.reduce((a,s)=>a+s.spread,0)/i.length,volume:i.reduce((a,s)=>a+s.volume,0)/i.length,trade:i.reduce((a,s)=>a+s.trade,0)/i.length,indexValue:i.reduce((a,s)=>a+s.indexValue,0)/i.length,openingPrice:i.reduce((a,s)=>a+s.openingPrice,0)/i.length,closingPrice:i.reduce((a,s)=>a+s.closingPrice,0)/i.length,settlementPrice:i.reduce((a,s)=>a+s.settlementPrice,0)/i.length,tradingSessionHighPrice:i.reduce((a,s)=>a+s.tradingSessionHighPrice,0)/i.length,tradingSessionLowPrice:i.reduce((a,s)=>a+s.tradingSessionLowPrice,0)/i.length,vwap:i.reduce((a,s)=>a+s.vwap,0)/i.length,imbalance:i.reduce((a,s)=>a+s.imbalance,0)/i.length,openInterest:i.reduce((a,s)=>a+s.openInterest,0)/i.length,compositeUnderlyingPrice:i.reduce((a,s)=>a+s.compositeUnderlyingPrice,0)/i.length,simulatedSellPrice:i.reduce((a,s)=>a+s.simulatedSellPrice,0)/i.length,simulatedBuyPrice:i.reduce((a,s)=>a+s.simulatedBuyPrice,0)/i.length,marginRate:i.reduce((a,s)=>a+s.marginRate,0)/i.length,midPrice:i.reduce((a,s)=>a+s.midPrice,0)/i.length,emptyBook:i.reduce((a,s)=>a+s.emptyBook,0)/i.length,settleHighPrice:i.reduce((a,s)=>a+s.settleHighPrice,0)/i.length,settleLowPrice:i.reduce((a,s)=>a+s.settleLowPrice,0)/i.length,priorSettlePrice:i.reduce((a,s)=>a+s.priorSettlePrice,0)/i.length,sessionHighBid:i.reduce((a,s)=>a+s.sessionHighBid,0)/i.length,sessionLowOffer:i.reduce((a,s)=>a+s.sessionLowOffer,0)/i.length,earlyPrices:i.reduce((a,s)=>a+s.earlyPrices,0)/i.length,auctionClearingPrice:i.reduce((a,s)=>a+s.auctionClearingPrice,0)/i.length,swapValueFactor:i.reduce((a,s)=>a+s.swapValueFactor,0)/i.length,dailyValueAdjustmentForLongPositions:i.reduce((a,s)=>a+s.dailyValueAdjustmentForLongPositions,0)/i.length,cumulativeValueAdjustmentForLongPositions:i.reduce((a,s)=>a+s.cumulativeValueAdjustmentForLongPositions,0)/i.length,dailyValueAdjustmentForShortPositions:i.reduce((a,s)=>a+s.dailyValueAdjustmentForShortPositions,0)/i.length,cumulativeValueAdjustmentForShortPositions:i.reduce((a,s)=>a+s.cumulativeValueAdjustmentForShortPositions,0)/i.length,fixingPrice:i.reduce((a,s)=>a+s.fixingPrice,0)/i.length,cashRate:i.reduce((a,s)=>a+s.cashRate,0)/i.length,recoveryRate:i.reduce((a,s)=>a+s.recoveryRate,0)/i.length,recoveryRateForLong:i.reduce((a,s)=>a+s.recoveryRateForLong,0)/i.length,recoveryRateForShort:i.reduce((a,s)=>a+s.recoveryRateForShort,0)/i.length,marketBid:i.reduce((a,s)=>a+s.marketBid,0)/i.length,marketOffer:i.reduce((a,s)=>a+s.marketOffer,0)/i.length,shortSaleMinPrice:i.reduce((a,s)=>a+s.shortSaleMinPrice,0)/i.length,previousClosingPrice:i.reduce((a,s)=>a+s.previousClosingPrice,0)/i.length,thresholdLimitPriceBanding:i.reduce((a,s)=>a+s.thresholdLimitPriceBanding,0)/i.length,dailyFinancingValue:i.reduce((a,s)=>a+s.dailyFinancingValue,0)/i.length,accruedFinancingValue:i.reduce((a,s)=>a+s.accruedFinancingValue,0)/i.length,twap:i.reduce((a,s)=>a+s.twap,0)/i.length};e.push(u)}return e.push(t[t.length-1]),e},Le=t=>async r=>{try{let e=r.symbol,n=t.get(e)||[];if(n.length===0)return{content:[{type:"text",text:`No price data available for ${e}`,uri:"getStockGraph"}]};let l=K(n,500),o=new z.default;o.setWidth(1200),o.setHeight(600),o.setBackgroundColor("transparent");let c=l.map(v=>new Date(v.timestamp).toLocaleTimeString()),i=l.map(v=>v.bid),u=l.map(v=>v.offer),a=l.map(v=>v.spread),s=l.map(v=>v.volume),d=l.map(v=>v.trade),p=l.map(v=>v.vwap),P=l.map(v=>v.twap),M=Math.max(...s.filter(v=>v>0)),h=Math.max(...i,...u,...d,...p,...P),S=s.map(v=>v/M*h*.3),R={type:"line",data:{labels:c,datasets:[{label:"Bid",data:i,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:a,borderColor:"#6c757d",backgroundColor:"rgba(108, 117, 125, 0.1)",fill:!1,tension:.4},{label:"Trade",data:d,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:P,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(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=t=>async r=>{try{let e=r.symbol,n=t.get(e)||[];if(n.length===0)return{content:[{type:"text",text:`No price data available for ${e}`,uri:"getStockPriceHistory"}]};let l=K(n,500);return{content:[{type:"text",text:JSON.stringify({symbol:e,count:l.length,originalCount:n.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}}},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=(t,r)=>async e=>{try{return r.set(e.clOrdID,{clOrdID:e.clOrdID,handlInst:e.handlInst,quantity:Number.parseFloat(String(e.quantity)),price:Number.parseFloat(String(e.price)),ordType:e.ordType,side:e.side,symbol:e.symbol,timeInForce:e.timeInForce}),{content:[{type:"text",text:`VERIFICATION: All parameters valid. Ready to proceed with order execution.
5
-
6
- Parameters verified:
7
- - ClOrdID: ${e.clOrdID}
8
- - HandlInst: ${e.handlInst} (${Ne[e.handlInst]})
9
- - Quantity: ${e.quantity}
10
- - Price: ${e.price}
11
- - OrdType: ${e.ordType} (${Ee[e.ordType]})
12
- - Side: ${e.side} (${Be[e.side]})
13
- - Symbol: ${e.symbol}
14
- - TimeInForce: ${e.timeInForce} (${He[e.timeInForce]})
15
-
16
- To execute this order, call the executeOrder tool with these exact same parameters. Important: The user has to explicitly confirm before executeOrder is called!`,uri:"verifyOrder"}]}}catch(n){return{content:[{type:"text",text:`Error: ${n instanceof Error?n.message:"Failed to verify order parameters"}`,uri:"verifyOrder"}],isError:!0}}},qe=(t,r,e)=>async n=>{try{let l=r.get(n.clOrdID);if(!l)return{content:[{type:"text",text:`Error: Order ${n.clOrdID} has not been verified. Please call verifyOrder first.`,uri:"executeOrder"}],isError:!0};if(l.handlInst!==n.handlInst||l.quantity!==Number.parseFloat(String(n.quantity))||l.price!==Number.parseFloat(String(n.price))||l.ordType!==n.ordType||l.side!==n.side||l.symbol!==n.symbol||l.timeInForce!==n.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(n.clOrdID,u)}),c=t.createMessage(new w.Field(w.Fields.MsgType,w.Messages.NewOrderSingle),new w.Field(w.Fields.MsgSeqNum,t.getNextTargetMsgSeqNum()),new w.Field(w.Fields.SenderCompID,t.sender),new w.Field(w.Fields.TargetCompID,t.target),new w.Field(w.Fields.SendingTime,t.getTimestamp()),new w.Field(w.Fields.ClOrdID,n.clOrdID),new w.Field(w.Fields.Side,n.side),new w.Field(w.Fields.Symbol,n.symbol),new w.Field(w.Fields.OrderQty,Number.parseFloat(String(n.quantity))),new w.Field(w.Fields.Price,Number.parseFloat(String(n.price))),new w.Field(w.Fields.OrdType,n.ordType),new w.Field(w.Fields.HandlInst,n.handlInst),new w.Field(w.Fields.TimeInForce,n.timeInForce),new w.Field(w.Fields.TransactTime,t.getTimestamp()));if(!t.connected)return{content:[{type:"text",text:"Error: Not connected. Ignoring message.",uri:"executeOrder"}],isError:!0};t.send(c);let i=await o;return r.delete(n.clOrdID),{content:[{type:"text",text:i.messageType===w.Messages.Reject?`Reject message for order ${n.clOrdID}: ${JSON.stringify(i.toFIXJSON())}`:`Execution Report for order ${n.clOrdID}: ${JSON.stringify(i.toFIXJSON())}`,uri:"executeOrder"}]}}catch(l){return{content:[{type:"text",text:`Error: ${l instanceof Error?l.message:"Failed to execute order"}`,uri:"executeOrder"}],isError:!0}}},We=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}}},Ge=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}}},$e=(t,r,e,n)=>({parse:We(t),parseToJSON:Ge(t),verifyOrder:je(t,r),executeOrder:qe(t,r,e),marketDataRequest:De(t,e),getStockGraph:Le(n),getStockPriceHistory:Ve(n),technicalAnalysis:Te(n)});function Ue(t,r){return t[r]||r}function Xe(t,r,e,n,l,o){let c=t.messageType;if(c===y.Messages.MarketDataSnapshotFullRefresh||c===y.Messages.MarketDataIncrementalRefresh){let i=t.getField(y.Fields.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 P of a){let M=P.MDEntryType,h=P.MDEntryPx?Number.parseFloat(P.MDEntryPx):0,S=P.MDEntrySize?Number.parseFloat(P.MDEntrySize):0;switch(Ue(y.MDEntryType,M)){case y.MDEntryType.Bid:s.bid=h;break;case y.MDEntryType.Offer:s.offer=h;break;case y.MDEntryType.Trade:s.trade=h;break;case y.MDEntryType.IndexValue:s.indexValue=h;break;case y.MDEntryType.OpeningPrice:s.openingPrice=h;break;case y.MDEntryType.ClosingPrice:s.closingPrice=h;break;case y.MDEntryType.SettlementPrice:s.settlementPrice=h;break;case y.MDEntryType.TradingSessionHighPrice:s.tradingSessionHighPrice=h;break;case y.MDEntryType.TradingSessionLowPrice:s.tradingSessionLowPrice=h;break;case y.MDEntryType.VWAP:s.vwap=h;break;case y.MDEntryType.Imbalance:s.imbalance=S;break;case y.MDEntryType.TradeVolume:s.volume=S;break;case y.MDEntryType.OpenInterest:s.openInterest=S;break;case y.MDEntryType.CompositeUnderlyingPrice:s.compositeUnderlyingPrice=h;break;case y.MDEntryType.SimulatedSellPrice:s.simulatedSellPrice=h;break;case y.MDEntryType.SimulatedBuyPrice:s.simulatedBuyPrice=h;break;case y.MDEntryType.MarginRate:s.marginRate=h;break;case y.MDEntryType.MidPrice:s.midPrice=h;break;case y.MDEntryType.EmptyBook:s.emptyBook=1;break;case y.MDEntryType.SettleHighPrice:s.settleHighPrice=h;break;case y.MDEntryType.SettleLowPrice:s.settleLowPrice=h;break;case y.MDEntryType.PriorSettlePrice:s.priorSettlePrice=h;break;case y.MDEntryType.SessionHighBid:s.sessionHighBid=h;break;case y.MDEntryType.SessionLowOffer:s.sessionLowOffer=h;break;case y.MDEntryType.EarlyPrices:s.earlyPrices=h;break;case y.MDEntryType.AuctionClearingPrice:s.auctionClearingPrice=h;break;case y.MDEntryType.SwapValueFactor:s.swapValueFactor=h;break;case y.MDEntryType.DailyValueAdjustmentForLongPositions:s.dailyValueAdjustmentForLongPositions=h;break;case y.MDEntryType.CumulativeValueAdjustmentForLongPositions:s.cumulativeValueAdjustmentForLongPositions=h;break;case y.MDEntryType.DailyValueAdjustmentForShortPositions:s.dailyValueAdjustmentForShortPositions=h;break;case y.MDEntryType.CumulativeValueAdjustmentForShortPositions:s.cumulativeValueAdjustmentForShortPositions=h;break;case y.MDEntryType.FixingPrice:s.fixingPrice=h;break;case y.MDEntryType.CashRate:s.cashRate=h;break;case y.MDEntryType.RecoveryRate:s.recoveryRate=h;break;case y.MDEntryType.RecoveryRateForLong:s.recoveryRateForLong=h;break;case y.MDEntryType.RecoveryRateForShort:s.recoveryRateForShort=h;break;case y.MDEntryType.MarketBid:s.marketBid=h;break;case y.MDEntryType.MarketOffer:s.marketOffer=h;break;case y.MDEntryType.ShortSaleMinPrice:s.shortSaleMinPrice=h;break;case y.MDEntryType.PreviousClosingPrice:s.previousClosingPrice=h;break;case y.MDEntryType.ThresholdLimitPriceBanding:s.thresholdLimitPriceBanding=h;break;case y.MDEntryType.DailyFinancingValue:s.dailyFinancingValue=h;break;case y.MDEntryType.AccruedFinancingValue:s.accruedFinancingValue=h;break;case y.MDEntryType.TWAP:s.twap=h;break}}s.spread=s.offer-s.bid,n.has(i)||n.set(i,[]);let d=n.get(i);d.push(s),d.length>l&&d.splice(0,d.length-l),o?.(i,s);let p=t.getField(y.Fields.MDReqID)?.value;if(p){let P=e.get(p);P&&(P(t),e.delete(p))}}else if(c===y.Messages.ExecutionReport){let i=t.getField(y.Fields.ClOrdID)?.value,u=e.get(i);u&&(u(t),e.delete(i))}}var E={};function Je(t){if(t.type==="object"){let r={};for(let[e,n]of Object.entries(t.properties||{})){let l=n;l.type==="string"?l.enum?r[e]=O.z.enum(l.enum):r[e]=O.z.string():l.type==="number"?r[e]=O.z.number():l.type==="boolean"?r[e]=O.z.boolean():l.type==="array"?l.items.type==="string"?r[e]=O.z.array(O.z.string()):l.items.type==="number"?r[e]=O.z.array(O.z.number()):l.items.type==="boolean"?r[e]=O.z.array(O.z.boolean()):r[e]=O.z.array(O.z.any()):r[e]=O.z.any()}return r}return{}}var te=class extends xe{port;httpServer;mcpServer;serverName;serverVersion;verifiedOrders=new Map;pendingRequests=new Map;marketDataPrices=new Map;MAX_PRICE_HISTORY=1e5;constructor({port:t,logger:r,onReady:e}){super({logger:r,onReady:e}),this.port=t}async register(t){this.parser=t,this.logger=t.logger,this.logger?.log({level:"info",message:`FIXParser (MCP): -- Plugin registered. Creating MCP server on port ${this.port}...`}),this.parser.addOnMessageCallback(r=>{this.parser&&Xe(r,this.parser,this.pendingRequests,this.marketDataPrices,this.MAX_PRICE_HISTORY)}),this.httpServer=(0,Q.createServer)(async(r,e)=>{if(!r.url||!r.method){e.writeHead(400),e.end("Bad Request");return}if(r.url==="/mcp"){let n=r.headers["mcp-session-id"];if(r.method==="POST"){let l=[];r.on("data",o=>{l.push(o)}),r.on("end",async()=>{let o,c=Buffer.concat(l).toString();try{o=JSON.parse(c)}catch(u){e.writeHead(400),e.end(JSON.stringify({error:"Invalid JSON"}));return}let i;if(n&&E[n])i=E[n];else if(!n&&r.method==="POST"&&(0,ee.isInitializeRequest)(o))i=new Z.StreamableHTTPServerTransport({sessionIdGenerator:()=>(0,_.randomUUID)(),onsessioninitialized:u=>{E[u]=i}}),i.onclose=()=>{i.sessionId&&delete E[i.sessionId]},this.mcpServer=new Y.McpServer({name:this.serverName||"FIXParser",version:this.serverVersion||"1.0.0"}),this.setupTools(),await this.mcpServer.connect(i);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 i.handleRequest(r,e,o)}catch(u){throw this.logger?.log({level:"error",message:`Error handling request: ${u}`}),u}})}else if(r.method==="GET"||r.method==="DELETE"){if(!n||!E[n]){e.writeHead(400),e.end("Invalid or missing session ID");return}let l=E[n];try{await l.handleRequest(r,e)}catch(o){throw this.logger?.log({level:"error",message:`Error handling ${r.method} request: ${o}`}),o}}else this.logger?.log({level:"error",message:`Method not allowed: ${r.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 t=$e(this.parser,this.verifiedOrders,this.pendingRequests,this.marketDataPrices);Object.entries(Ie).forEach(([r,{description:e,schema:n}])=>{this.mcpServer?.registerTool(r,{description:e,inputSchema:Je(n)},async l=>{let o=t[r];if(!o)return{content:[{type:"text",text:`Tool not found: ${r}`}],isError:!0};let c=await o(l);return{content:c.content,isError:c.isError}})})}};var ze=async()=>{await b.LicenseManager.setLicenseKey(process.env.FIXPARSER_LICENSE_KEY);let t=process.env.FIXPARSER_SENDER||"SENDER",r=process.env.FIXPARSER_TARGET||"TARGET",e=new b.FIXParser({plugins:[new te({port:3099,onReady:()=>console.log("ready!")})]}),n=()=>{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,t),new b.Field(b.Fields.SendingTime,e.getTimestamp()),new b.Field(b.Fields.TargetCompID,r),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)},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",logging:!0,logOptions:{name:t,level:"info",format:"json",transport:new J({format:"console"})},onOpen:()=>{console.log("Open"),n()},onMessage:o=>console.log("received message",o.description,o.messageString.replace(/\x01/g,"|")),onClose:()=>{console.log("Disconnected")}};e.connect(l)};ze().catch(t=>console.error("Error initializing server:",t));
18
- //# sourceMappingURL=example_mcp_remote.js.map