fixparser-plugin-mcp 9.1.7-5c2fdc7a → 9.1.7-5d282a9e
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 +2861 -619
- package/build/cjs/MCPLocal.js.map +4 -4
- package/build/cjs/MCPRemote.js +2935 -437
- package/build/cjs/MCPRemote.js.map +4 -4
- package/build/cjs/index.js +3232 -0
- package/build/cjs/index.js.map +7 -0
- package/build/esm/MCPLocal.mjs +2851 -634
- package/build/esm/MCPLocal.mjs.map +4 -4
- package/build/esm/MCPRemote.mjs +2926 -447
- package/build/esm/MCPRemote.mjs.map +4 -4
- package/build/esm/index.mjs +3194 -0
- package/build/esm/index.mjs.map +7 -0
- package/build-examples/cjs/example_mcp_local.js +16 -4
- package/build-examples/cjs/example_mcp_local.js.map +4 -4
- package/build-examples/cjs/example_mcp_remote.js +18 -0
- package/build-examples/cjs/example_mcp_remote.js.map +7 -0
- package/build-examples/esm/example_mcp_local.mjs +16 -4
- package/build-examples/esm/example_mcp_local.mjs.map +4 -4
- package/build-examples/esm/example_mcp_remote.mjs +18 -0
- package/build-examples/esm/example_mcp_remote.mjs.map +7 -0
- package/package.json +11 -11
- package/types/MCPLocal.d.ts +0 -14
- package/types/MCPRemote.d.ts +0 -60
- package/types/PluginOptions.d.ts +0 -6
- package/types/index.d.ts +0 -3
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{EncryptMethod as Ue,FIXParser as Xe,Field as H,Fields as N,LicenseManager as Je,Messages as ze,ResetSeqNumFlag as Ke}from"fixparser";var Y=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"}};import{Server as et}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as rt}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as st}from"zod";import{Field as O,Fields as x,MDEntryType as v,Messages as be}from"fixparser";import Re from"quickchart-js";import{Field as F,Fields as C,Messages as Z}from"fixparser";import{Fields as $,MDEntryType as P,Messages as U}from"fixparser";import{randomUUID as Ne}from"node:crypto";import{createServer as je}from"node:http";import{McpServer as qe}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as We}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{isInitializeRequest as Ge}from"@modelcontextprotocol/sdk/types.js";import{z as I}from"zod";var Pe=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}},ve={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 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 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((g,f)=>g+(f-i)**2,0)/r,a=Math.sqrt(u),s=i+a*e,m=i-a*e;l.push({upper:s,middle:i,lower:m,bandwidth:(s-m)/i*100,percentB:(t[o]-m)/(s-m)*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),m=Math.abs(i-u);n.push(Math.max(a,s,m))}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 p=1;p<t.length;p++){let d=r[p]||t[p],y=e[p]||t[p],b=r[p-1]||t[p-1],T=e[p-1]||t[p-1],E=t[p-1],D=d-y,L=Math.abs(d-E),k=Math.abs(y-E);o.push(Math.max(D,L,k));let B=d-b,R=T-y;B>R&&B>0?(c.push(B),i.push(0)):R>B&&R>0?(c.push(0),i.push(R)):(c.push(0),i.push(0))}let u=[],a=[],s=[],m=0,g=0,f=0;for(let p=0;p<n;p++)m+=o[p],g+=c[p],f+=i[p];u.push(m),a.push(g),s.push(f);for(let p=n;p<o.length;p++){let d=u[u.length-1]-u[u.length-1]/n+o[p],y=a[a.length-1]-a[a.length-1]/n+c[p],b=s[s.length-1]-s[s.length-1]/n+i[p];u.push(d),a.push(y),s.push(b)}let M=[],h=[];for(let p=0;p<u.length;p++)M.push(a[p]/u[p]*100),h.push(s[p]/u[p]*100);let S=[];for(let p=0;p<M.length;p++){let d=M[p]+h[p],y=Math.abs(M[p]-h[p]);S.push(d>0?y/d*100:0)}if(S.length<n)return[];let w=0;for(let p=0;p<n;p++)w+=S[p];l.push(w/n);for(let p=n;p<S.length;p++){let d=l[l.length-1]-l[l.length-1]/n+S[p];l.push(d)}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 d=1;d<t.length;d++){let y=r[d]||t[d],b=e[d]||t[d],T=r[d-1]||t[d-1],E=e[d-1]||t[d-1],D=t[d-1],L=y-b,k=Math.abs(y-D),B=Math.abs(b-D);o.push(Math.max(L,k,B));let R=y-T,V=E-b;R>V&&R>0?(c.push(R),i.push(0)):V>R&&V>0?(c.push(0),i.push(V)):(c.push(0),i.push(0))}let u=[],a=[],s=[],m=0,g=0,f=0;for(let d=0;d<n;d++)m+=o[d],g+=c[d],f+=i[d];u.push(m),a.push(g),s.push(f);for(let d=n;d<o.length;d++){let y=u[u.length-1]-u[u.length-1]/n+o[d],b=a[a.length-1]-a[a.length-1]/n+c[d],T=s[s.length-1]-s[s.length-1]/n+i[d];u.push(y),a.push(b),s.push(T)}let M=[],h=[];for(let d=0;d<u.length;d++)M.push(a[d]/u[d]*100),h.push(s[d]/u[d]*100);let S=[];for(let d=0;d<M.length;d++){let y=M[d]+h[d],b=Math.abs(M[d]-h[d]);S.push(y>0?b/y*100:0)}if(S.length<n)return[];let w=[],p=0;for(let d=0;d<n;d++)p+=S[d];w.push(p/n);for(let d=n;d<S.length;d++){let y=w[w.length-1]-w[w.length-1]/n+S[d];w.push(y)}for(let d=0;d<w.length;d++)l.push({plusDI:M[d+n-1]||0,minusDI:h[d+n-1]||0,adx:w[d]});return l}calculateIchimoku(t,r,e){if(t.length<52)return[];let n=[],l=[];for(let s=8;s<t.length;s++){let m=Math.max(...r.slice(s-8,s+1)),g=Math.min(...e.slice(s-8,s+1));l.push((m+g)/2)}let o=[];for(let s=25;s<t.length;s++){let m=Math.max(...r.slice(s-25,s+1)),g=Math.min(...e.slice(s-25,s+1));o.push((m+g)/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 m=Math.max(...r.slice(s-51,s+1)),g=Math.min(...e.slice(s-51,s+1));i.push((m+g)/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 m=r[s]||t[s],g=e[s]||t[s];if(i){if(g<c)i=!1,c=a,a=g,u=l;else if(m>a&&(a=m,u=Math.min(u+l,o)),c=c+u*(a-c),s>0){let f=e[s-1]||t[s-1];c=Math.min(c,f)}}else if(m>c)i=!0,c=a,a=m,u=l;else if(g<a&&(a=g,u=Math.min(u+l,o)),c=c+u*(a-c),s>0){let f=r[s-1]||t[s-1];c=Math.max(c,f)}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)),m=Math.min(...e.slice(a-14+1,a+1)),f=(t[a]-m)/(s-m)*100;i.push(f)}let u=[];for(let a=2;a<i.length;a++){let s=i.slice(a-3+1,a+1).reduce((m,g)=>m+g,0);u.push(s/3)}for(let a=2;a<u.length;a++){let m=u.slice(a-3+1,a+1).reduce((g,f)=>g+f,0)/3;n.push({k:u[a],d:m})}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((g,f)=>{let M=r[o-20+1+f]||g,h=e[o-20+1+f]||g;return(M+h+g)/3}),u=i.reduce((g,f)=>g+f,0)/20,a=i.reduce((g,f)=>g+Math.abs(f-u),0)/20,s=(r[o]+e[o]+t[o])/3,m=a!==0?(s-u)/(.015*a):0;n.push(m)}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 m=r[s]||t[s],g=e[s]||t[s],f=t[s],M=n[s]||1,S=(f-g-(m-f))/(m-g)*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 m=c-14+1;m<=c;m++){let g=r[m]||t[m],f=e[m]||t[m],M=t[m],h=n[m]||1,S=(g+f+M)/3,w=S*h;if(m>c-14+1){let p=r[m-1]||t[m-1],d=e[m-1]||t[m-1],y=t[m-1],b=(p+d+y)/3;S>b?i+=w:S<b&&(u+=w)}}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),m=n+2*(c-l),g=l-2*(n-c);r.push({pp:c,r1:i,r2:a,r3:m,s1:u,s2:s,s3:g})}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 f=this.calculatePatternCompletion(t),M=o+(o-l)*.618,h=o-(o-l)*.382;return{type:"Gartley",completion:f,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 f=this.calculatePatternCompletion(t),M=o+(o-l)*1.27,h=o-(o-l)*.5;return{type:"Butterfly",completion:f,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],w=r[h-1];n+=S,l+=w,o+=S*w,c+=w*w}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),m=e*Math.log(s/e)+2*2,g=r[r.length-1],f=t+(u+i*g),M=f+(u+i*(u+i*g));return{forecast:[f,M],residuals:a,aic:m}}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 g=0;g<e;g++)c!==g&&(i+=r[g]/(Math.PI*(c-g)));let u=r[c],a=i,s=Math.sqrt(u*u+a*a);n.push(s);let m=Math.atan2(a,u);l.push(m),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),m=l*Math.exp(-c*o)*this.normalCDF(-a)-n*this.normalCDF(-u);return{callPrice:s,putPrice:m,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=Se(this.volumes),o=l/this.volumes.length,c=this.calculatePriceChanges(),i=c.length>0?Math.sqrt(c.reduce((D,L)=>D+L**2,0)/c.length)*Math.sqrt(252)*100:0,u=(t-r)/r*100,a=(t-n)/(e-n)*100,s=this.prices.reduce((D,L,k)=>D+L*this.volumes[k],0)/l,m=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,g=this.prices.length>10?(t-this.prices[Math.max(0,this.prices.length-11)])/this.prices[Math.max(0,this.prices.length-11)]*100:0,f=this.calculateMaxDrawdown(this.prices),M=this.calculateAtr(this.prices,this.highs,this.lows),h=M.length>0?M[M.length-1]:0,S=i,w=i,p=u/i,d=u/w,y=u/f,b=this.calculateMaxConsecutiveLosses(this.prices),T=this.calculateWinRate(this.prices),E=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:m,momentum10:g,maxDrawdown:f,atr:h,impliedVolatility:S,realizedVolatility:w,sharpeRatio:p,sortinoRatio:d,calmarRatio:y,maxConsecutiveLosses:b,winRate:T,profitFactor:E}}getTechnicalIndicators(){return{sma5:this.calculateSMA(this.prices,5),sma10:this.calculateSMA(this.prices,10),sma20:this.calculateSMA(this.prices,20),sma50:this.calculateSMA(this.prices,50),sma200:this.calculateSMA(this.prices,200),ema8:this.calculateEMA(this.prices,8),ema12:this.calculateEMA(this.prices,12),ema21:this.calculateEMA(this.prices,21),ema26:this.calculateEMA(this.prices,26),wma20:this.calculateWma(this.prices,20),vwma20:this.calculateVwma(this.prices,20),macd:this.calculateMacd(this.prices),adx:this.calculateAdx(this.prices,this.highs,this.lows),dmi:this.calculateDmi(this.prices,this.highs,this.lows),ichimoku:this.calculateIchimoku(this.prices,this.highs,this.lows),parabolicSAR:this.calculateParabolicSAR(this.prices,this.highs,this.lows),rsi:this.calculateRSI(this.prices,14),stochastic:this.calculateStochastic(this.prices,this.highs,this.lows),cci:this.calculateCci(this.prices,this.highs,this.lows),roc:this.calculateRoc(this.prices),williamsR:this.calculateWilliamsR(this.prices),momentum:this.calculateMomentum(this.prices),bollinger:this.calculateBollingerBands(this.prices,20,2),atr:this.calculateAtr(this.prices,this.highs,this.lows),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],m=e.ema21[e.ema21.length-1],g=e.ema26[e.ema26.length-1],f=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,w=e.dmi.length>0?e.dmi[e.dmi.length-1]:null,p=e.ichimoku.length>0?e.ichimoku[e.ichimoku.length-1]:null,d=e.parabolicSAR.length>0?e.parabolicSAR[e.parabolicSAR.length-1]:null,y=e.rsi.length>0?e.rsi[e.rsi.length-1]:null,b=e.stochastic.length>0?e.stochastic[e.stochastic.length-1]:null,T=e.cci.length>0?e.cci[e.cci.length-1]:null,E=e.roc.length>0?e.roc[e.roc.length-1]:null,D=e.williamsR.length>0?e.williamsR[e.williamsR.length-1]:null,L=e.momentum.length>0?e.momentum[e.momentum.length-1]:null,k=e.bollinger.length>0?e.bollinger[e.bollinger.length-1]:null,B=e.atr.length>0?e.atr[e.atr.length-1]:null,R=e.keltner.length>0?e.keltner[e.keltner.length-1]:null,V=e.donchian.length>0?e.donchian[e.donchian.length-1]:null,re=e.chaikinVolatility.length>0?e.chaikinVolatility[e.chaikinVolatility.length-1]:null,X=e.obv.length>0?e.obv[e.obv.length-1]:null,J=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,z=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:[],K=this.volumes[this.volumes.length-1],he=K/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,W=n.bullishSignals-n.bearishSignals,pe=W>0?"BULLISH_BIAS":W<0?"BEARISH_BIAS":"NEUTRAL",G=Math.max(r.sessionLow*1.005,r.trueVWAP*.998),q=r.sessionLow*.995,_=r.sessionHigh*.995,fe=(_-r.currentPrice)/(r.currentPrice-q),Q=this.calculatePositionSize(r.currentPrice,G,q),ye=Q*(G-q);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:m,ema26:g,wma20:f,vwma20:M,macd:h,adx:S,dmi:w,ichimoku:p,parabolicSAR:d,rsi:y,stochastic:b,cci:T,roc:E,williamsR:D,momentum:L,bollingerBands:k?{upper:k.upper,middle:k.middle,lower:k.lower,bandwidth:k.bandwidth,percentB:k.percentB}:null,atr:B,keltnerChannels:R?{upper:R.upper,middle:R.middle,lower:R.lower}:null,donchianChannels:V?{upper:V.upper,middle:V.middle,lower:V.lower}:null,chaikinVolatility:re,obv:X,cmf:J,adl:ne,volumeROC:se,mfi:z,vwap:ie},volumeAnalysis:{currentVolume:K,averageVolume:Math.round(r.avgVolume),volumeRatio:he,trueVWAP:r.trueVWAP,priceVsVWAP:ge,obv:X,cmf:J,mfi:z},momentum:{momentum5:r.momentum5,momentum10:r.momentum10,sessionROC:r.sessionReturn,rsi:y,stochastic:b,cci:T},supportResistance:{pivotPoints:oe,fibonacci:ae,gannLevels:le,elliottWave:ce,harmonicPatterns:ue},tradingSignals:{...n,overallSignal:pe,signalScore:W,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 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:G,stopLoss:q,profitTarget:_,riskRewardRatio:fe,positionSize:Q,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,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 Me(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}}},Fe=(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||[v.Bid,v.Offer,v.Trade,v.IndexValue,v.OpeningPrice,v.ClosingPrice,v.SettlementPrice,v.TradingSessionHighPrice,v.TradingSessionLowPrice,v.VWAP,v.Imbalance,v.TradeVolume,v.OpenInterest,v.CompositeUnderlyingPrice,v.SimulatedSellPrice,v.SimulatedBuyPrice,v.MarginRate,v.MidPrice,v.EmptyBook,v.SettleHighPrice,v.SettleLowPrice,v.PriorSettlePrice,v.SessionHighBid,v.SessionLowOffer,v.EarlyPrices,v.AuctionClearingPrice,v.SwapValueFactor,v.DailyValueAdjustmentForLongPositions,v.CumulativeValueAdjustmentForLongPositions,v.DailyValueAdjustmentForShortPositions,v.CumulativeValueAdjustmentForShortPositions,v.FixingPrice,v.CashRate,v.RecoveryRate,v.RecoveryRateForLong,v.RecoveryRateForShort,v.MarketBid,v.MarketOffer,v.ShortSaleMinPrice,v.PreviousClosingPrice,v.ThresholdLimitPriceBanding,v.DailyFinancingValue,v.AccruedFinancingValue,v.TWAP],o=[new O(x.MsgType,be.MarketDataRequest),new O(x.SenderCompID,t.sender),new O(x.MsgSeqNum,t.getNextTargetMsgSeqNum()),new O(x.TargetCompID,t.target),new O(x.SendingTime,t.getTimestamp()),new O(x.MDReqID,e.mdReqID),new O(x.SubscriptionRequestType,e.subscriptionRequestType),new O(x.MarketDepth,0),new O(x.MDUpdateType,e.mdUpdateType)];o.push(new O(x.NoRelatedSym,e.symbols.length)),e.symbols.forEach(u=>{o.push(new O(x.Symbol,u))}),o.push(new O(x.NoMDEntryTypes,l.length)),l.forEach(u=>{o.push(new O(x.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}}},ee=(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},Ce=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=ee(n,500),o=new Re;o.setWidth(1200),o.setHeight(600),o.setBackgroundColor("transparent");let c=l.map(y=>new Date(y.timestamp).toLocaleTimeString()),i=l.map(y=>y.bid),u=l.map(y=>y.offer),a=l.map(y=>y.spread),s=l.map(y=>y.volume),m=l.map(y=>y.trade),g=l.map(y=>y.vwap),f=l.map(y=>y.twap),M=Math.max(...s.filter(y=>y>0)),h=Math.max(...i,...u,...m,...g,...f),S=s.map(y=>y/M*h*.3),w={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:m,borderColor:"#ffc107",backgroundColor:"rgba(255, 193, 7, 0.1)",fill:!1,tension:.4},{label:"VWAP",data:g,borderColor:"#17a2b8",backgroundColor:"rgba(23, 162, 184, 0.1)",fill:!1,tension:.4},{label:"TWAP",data:f,borderColor:"#6610f2",backgroundColor:"rgba(102, 16, 242, 0.1)",fill:!1,tension:.4},{label:"Volume (Normalized)",data: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(w),{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}}},Oe=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=ee(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}}},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"},Ie={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"},ke={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"},Ae={1:"AutomatedExecutionNoIntervention",2:"AutomatedExecutionInterventionOK",3:"ManualOrder"},Te=(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} (${Ae[e.handlInst]})
|
|
9
|
+
- Quantity: ${e.quantity}
|
|
10
|
+
- Price: ${e.price}
|
|
11
|
+
- OrdType: ${e.ordType} (${xe[e.ordType]})
|
|
12
|
+
- Side: ${e.side} (${Ie[e.side]})
|
|
13
|
+
- Symbol: ${e.symbol}
|
|
14
|
+
- TimeInForce: ${e.timeInForce} (${ke[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}}},De=(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 F(C.MsgType,Z.NewOrderSingle),new F(C.MsgSeqNum,t.getNextTargetMsgSeqNum()),new F(C.SenderCompID,t.sender),new F(C.TargetCompID,t.target),new F(C.SendingTime,t.getTimestamp()),new F(C.ClOrdID,n.clOrdID),new F(C.Side,n.side),new F(C.Symbol,n.symbol),new F(C.OrderQty,Number.parseFloat(String(n.quantity))),new F(C.Price,Number.parseFloat(String(n.price))),new F(C.OrdType,n.ordType),new F(C.HandlInst,n.handlInst),new F(C.TimeInForce,n.timeInForce),new F(C.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===Z.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}}},Le=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}}},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:"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}}},Ee=(t,r,e,n)=>({parse:Le(t),parseToJSON:Ve(t),verifyOrder:Te(t,r),executeOrder:De(t,r,e),marketDataRequest:Fe(t,e),getStockGraph:Ce(n),getStockPriceHistory:Oe(n),technicalAnalysis:we(n)});function Be(t,r){return t[r]||r}function He(t,r,e,n,l,o){let c=t.messageType;if(c===U.MarketDataSnapshotFullRefresh||c===U.MarketDataIncrementalRefresh){let i=t.getField($.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 f of a){let M=f.MDEntryType,h=f.MDEntryPx?Number.parseFloat(f.MDEntryPx):0,S=f.MDEntrySize?Number.parseFloat(f.MDEntrySize):0;switch(Be(P,M)){case P.Bid:s.bid=h;break;case P.Offer:s.offer=h;break;case P.Trade:s.trade=h;break;case P.IndexValue:s.indexValue=h;break;case P.OpeningPrice:s.openingPrice=h;break;case P.ClosingPrice:s.closingPrice=h;break;case P.SettlementPrice:s.settlementPrice=h;break;case P.TradingSessionHighPrice:s.tradingSessionHighPrice=h;break;case P.TradingSessionLowPrice:s.tradingSessionLowPrice=h;break;case P.VWAP:s.vwap=h;break;case P.Imbalance:s.imbalance=S;break;case P.TradeVolume:s.volume=S;break;case P.OpenInterest:s.openInterest=S;break;case P.CompositeUnderlyingPrice:s.compositeUnderlyingPrice=h;break;case P.SimulatedSellPrice:s.simulatedSellPrice=h;break;case P.SimulatedBuyPrice:s.simulatedBuyPrice=h;break;case P.MarginRate:s.marginRate=h;break;case P.MidPrice:s.midPrice=h;break;case P.EmptyBook:s.emptyBook=1;break;case P.SettleHighPrice:s.settleHighPrice=h;break;case P.SettleLowPrice:s.settleLowPrice=h;break;case P.PriorSettlePrice:s.priorSettlePrice=h;break;case P.SessionHighBid:s.sessionHighBid=h;break;case P.SessionLowOffer:s.sessionLowOffer=h;break;case P.EarlyPrices:s.earlyPrices=h;break;case P.AuctionClearingPrice:s.auctionClearingPrice=h;break;case P.SwapValueFactor:s.swapValueFactor=h;break;case P.DailyValueAdjustmentForLongPositions:s.dailyValueAdjustmentForLongPositions=h;break;case P.CumulativeValueAdjustmentForLongPositions:s.cumulativeValueAdjustmentForLongPositions=h;break;case P.DailyValueAdjustmentForShortPositions:s.dailyValueAdjustmentForShortPositions=h;break;case P.CumulativeValueAdjustmentForShortPositions:s.cumulativeValueAdjustmentForShortPositions=h;break;case P.FixingPrice:s.fixingPrice=h;break;case P.CashRate:s.cashRate=h;break;case P.RecoveryRate:s.recoveryRate=h;break;case P.RecoveryRateForLong:s.recoveryRateForLong=h;break;case P.RecoveryRateForShort:s.recoveryRateForShort=h;break;case P.MarketBid:s.marketBid=h;break;case P.MarketOffer:s.marketOffer=h;break;case P.ShortSaleMinPrice:s.shortSaleMinPrice=h;break;case P.PreviousClosingPrice:s.previousClosingPrice=h;break;case P.ThresholdLimitPriceBanding:s.thresholdLimitPriceBanding=h;break;case P.DailyFinancingValue:s.dailyFinancingValue=h;break;case P.AccruedFinancingValue:s.accruedFinancingValue=h;break;case P.TWAP:s.twap=h;break}}s.spread=s.offer-s.bid,n.has(i)||n.set(i,[]);let m=n.get(i);m.push(s),m.length>l&&m.splice(0,m.length-l),o?.(i,s);let g=t.getField($.MDReqID)?.value;if(g){let f=e.get(g);f&&(f(t),e.delete(g))}}else if(c===U.ExecutionReport){let i=t.getField($.ClOrdID)?.value,u=e.get(i);u&&(u(t),e.delete(i))}}var j={};function $e(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]=I.enum(l.enum):r[e]=I.string():l.type==="number"?r[e]=I.number():l.type==="boolean"?r[e]=I.boolean():l.type==="array"?l.items.type==="string"?r[e]=I.array(I.string()):l.items.type==="number"?r[e]=I.array(I.number()):l.items.type==="boolean"?r[e]=I.array(I.boolean()):r[e]=I.array(I.any()):r[e]=I.any()}return r}return{}}var te=class extends Pe{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&&He(r,this.parser,this.pendingRequests,this.marketDataPrices,this.MAX_PRICE_HISTORY)}),this.httpServer=je(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&&j[n])i=j[n];else if(!n&&r.method==="POST"&&Ge(o))i=new We({sessionIdGenerator:()=>Ne(),onsessioninitialized:u=>{j[u]=i}}),i.onclose=()=>{i.sessionId&&delete j[i.sessionId]},this.mcpServer=new qe({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||!j[n]){e.writeHead(400),e.end("Invalid or missing session ID");return}let l=j[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=Ee(this.parser,this.verifiedOrders,this.pendingRequests,this.marketDataPrices);Object.entries(ve).forEach(([r,{description:e,schema:n}])=>{this.mcpServer?.registerTool(r,{description:e,inputSchema:$e(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 _e=async()=>{await Je.setLicenseKey(process.env.FIXPARSER_LICENSE_KEY);let t=process.env.FIXPARSER_SENDER||"SENDER",r=process.env.FIXPARSER_TARGET||"TARGET",e=new Xe({plugins:[new te({port:3099,onReady:()=>console.log("ready!")})]}),n=()=>{let o=e.createMessage(new H(N.MsgType,ze.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,Ke.Yes),new H(N.EncryptMethod,Ue.None),new H(N.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 Y({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)};_e().catch(t=>console.error("Error initializing server:",t));
|
|
18
|
+
//# sourceMappingURL=example_mcp_remote.mjs.map
|