fixparser-plugin-mcp 9.1.7-74db6dbc → 9.1.7-75ded9c1
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 +923 -2519
- package/build/cjs/MCPLocal.js.map +4 -4
- package/build/cjs/MCPRemote.js +437 -2601
- package/build/cjs/MCPRemote.js.map +4 -4
- package/build/esm/MCPLocal.mjs +923 -2509
- package/build/esm/MCPLocal.mjs.map +4 -4
- package/build/esm/MCPRemote.mjs +446 -2591
- package/build/esm/MCPRemote.mjs.map +4 -4
- package/build-examples/cjs/example_mcp_local.js +47 -14
- package/build-examples/cjs/example_mcp_local.js.map +4 -4
- package/build-examples/esm/example_mcp_local.mjs +43 -10
- package/build-examples/esm/example_mcp_local.mjs.map +4 -4
- package/package.json +9 -10
- package/types/MCPLocal.d.ts +16 -0
- package/types/MCPRemote.d.ts +60 -0
- package/types/PluginOptions.d.ts +6 -0
- package/types/index.d.ts +3 -0
- package/build/cjs/index.js +0 -2898
- package/build/cjs/index.js.map +0 -7
- package/build/esm/index.mjs +0 -2860
- package/build/esm/index.mjs.map +0 -7
- package/build-examples/cjs/example_mcp_remote.js +0 -18
- package/build-examples/cjs/example_mcp_remote.js.map +0 -7
- package/build-examples/esm/example_mcp_remote.mjs +0 -18
- package/build-examples/esm/example_mcp_remote.mjs.map +0 -7
|
@@ -1,18 +1,51 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var pe=Object.create;var X=Object.defineProperty;var fe=Object.getOwnPropertyDescriptor;var ye=Object.getOwnPropertyNames;var Pe=Object.getPrototypeOf,ve=Object.prototype.hasOwnProperty;var Se=(t,r,e,i)=>{if(r&&typeof r=="object"||typeof r=="function")for(let a of ye(r))!ve.call(t,a)&&a!==e&&X(t,a,{get:()=>r[a],enumerable:!(i=fe(r,a))||i.enumerable});return t};var be=(t,r,e)=>(e=t!=null?pe(Pe(t)):{},Se(r||!t||!t.__esModule?X(e,"default",{value:t,enumerable:!0}):e,t));var b=require("fixparser");var U=class{format;useStderr;constructor({format:t="json",useStderr:r=!1}){this.format=t,this.useStderr=r}configure(t){this.format=t.format||"json",t.useStderr!==void 0&&(this.useStderr=t.useStderr)}async send(t){let r=this.useStderr?console.error:console.log;if(this.format==="json")r(JSON.stringify(t));else if(this.format==="jsonrpc"){let{message:e,...i}=t,a={jsonrpc:"2.0",method:t.level,params:{message:e,...i},id:t.id||Date.now()};r(JSON.stringify(a))}else{let{name:e,id:i,message:a,level:o,...u}=t,n=Object.entries(u).map(([l,s])=>`${l}: ${s}`),c="";e&&(c+=`${e} `),c+=`${i}: ${a}`,r(c,n.join(", "))}}async flush(){}async close(){}status(){return"connected"}};var z=require("@modelcontextprotocol/sdk/server/index.js"),_=require("@modelcontextprotocol/sdk/server/stdio.js"),C=require("zod"),h=require("fixparser"),K=be(require("quickchart-js"),1),P=require("fixparser"),g=require("fixparser");var je=require("@modelcontextprotocol/sdk/server/mcp.js"),qe=require("@modelcontextprotocol/sdk/server/streamableHttp.js"),We=require("@modelcontextprotocol/sdk/types.js"),Ge=require("zod"),Me=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}},J={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 we(t){return t.reduce((r,e)=>r+e,0)}var Fe=class{prices;volumes;highs;lows;constructor(t){this.prices=t.map(r=>r.trade>0?r.trade:r.midPrice),this.volumes=t.map(r=>r.volume),this.highs=t.map(r=>r.tradingSessionHighPrice>0?r.tradingSessionHighPrice:r.trade),this.lows=t.map(r=>r.tradingSessionLowPrice>0?r.tradingSessionLowPrice:r.trade)}calculateSMA(t,r){let e=[];for(let i=r-1;i<t.length;i++){let a=t.slice(i-r+1,i+1).reduce((o,u)=>o+u,0);e.push(a/r)}return e}calculateEMA(t,r){let e=2/(r+1),i=[t[0]];for(let a=1;a<t.length;a++)i.push(t[a]*e+i[a-1]*(1-e));return i}calculateRSI(t,r=14){if(t.length<r+1)return[];let e=[];for(let c=1;c<t.length;c++)e.push(t[c]-t[c-1]);let i=e.map(c=>c>0?c:0),a=e.map(c=>c<0?Math.abs(c):0),o=i.slice(0,r).reduce((c,l)=>c+l,0)/r,u=a.slice(0,r).reduce((c,l)=>c+l,0)/r,n=[];for(let c=r;c<e.length;c++){let l=o/u;n.push(100-100/(1+l)),o=(o*(r-1)+i[c])/r,u=(u*(r-1)+a[c])/r}return n}calculateBollingerBands(t,r=20,e=2){if(t.length<r)return[];let i=this.calculateSMA(t,r),a=[];for(let o=0;o<i.length;o++){let u=t.slice(o,o+r),n=i[o],c=u.reduce((v,S)=>v+(S-n)**2,0)/r,l=Math.sqrt(c),s=n+l*e,y=n-l*e;a.push({upper:s,middle:n,lower:y,bandwidth:(s-y)/n*100,percentB:(t[o]-y)/(s-y)*100})}return a}calculateMaxDrawdown(t){let r=t[0],e=0;for(let i=1;i<t.length;i++){t[i]>r&&(r=t[i]);let a=(r-t[i])/r;a>e&&(e=a)}return e}calculateAtr(t,r,e){if(t.length<2)return[];let i=[];for(let o=1;o<t.length;o++){let u=r[o]||t[o],n=e[o]||t[o],c=t[o-1],l=u-n,s=Math.abs(u-c),y=Math.abs(n-c);i.push(Math.max(l,s,y))}let a=[];if(i.length>=14){let o=i.slice(0,14).reduce((u,n)=>u+n,0);a.push(o/14);for(let u=14;u<i.length;u++)o=o-i[u-14]+i[u],a.push(o/14)}return a}calculateMaxConsecutiveLosses(t){let r=0,e=0;for(let i=1;i<t.length;i++)t[i]<t[i-1]?(e++,r=Math.max(r,e)):e=0;return r}calculateWinRate(t){let r=0,e=0;for(let i=1;i<t.length;i++)t[i]!==t[i-1]&&(e++,t[i]>t[i-1]&&r++);return e>0?r/e:0}calculateProfitFactor(t){let r=0,e=0;for(let i=1;i<t.length;i++){let a=t[i]-t[i-1];a>0?r+=a:e+=Math.abs(a)}return e>0?r/e:0}calculateWma(t,r){let e=[],i=Array.from({length:r},(o,u)=>u+1),a=i.reduce((o,u)=>o+u,0);for(let o=r-1;o<t.length;o++){let u=0;for(let n=0;n<r;n++)u+=t[o-n]*i[n];e.push(u/a)}return e}calculateVwma(t,r){let e=[];for(let i=r-1;i<t.length;i++){let a=0,o=0;for(let u=0;u<r;u++){let n=this.volumes[i-u]||1;a+=n,o+=t[i-u]*n}e.push(o/a)}return e}calculateMacd(t){let r=this.calculateEMA(t,12),e=this.calculateEMA(t,26),i=[];for(let a=0;a<Math.min(r.length,e.length);a++){let o=r[a]-e[a];i.push({macd:o,signal:0,histogram:0})}return i}calculateAdx(t,r,e){if(t.length<14)return[];let i=14,a=[],o=[],u=[],n=[];o.push(r[0]-e[0]),u.push(0),n.push(0);for(let p=1;p<t.length;p++){let m=r[p]||t[p],f=e[p]||t[p],R=r[p-1]||t[p-1],x=e[p-1]||t[p-1],L=t[p-1],A=m-f,T=Math.abs(m-L),I=Math.abs(f-L);o.push(Math.max(A,T,I));let V=m-R,O=x-f;V>O&&V>0?(u.push(V),n.push(0)):O>V&&O>0?(u.push(0),n.push(O)):(u.push(0),n.push(0))}let c=[],l=[],s=[],y=0,v=0,S=0;for(let p=0;p<i;p++)y+=o[p],v+=u[p],S+=n[p];c.push(y),l.push(v),s.push(S);for(let p=i;p<o.length;p++){let m=c[c.length-1]-c[c.length-1]/i+o[p],f=l[l.length-1]-l[l.length-1]/i+u[p],R=s[s.length-1]-s[s.length-1]/i+n[p];c.push(m),l.push(f),s.push(R)}let w=[],d=[];for(let p=0;p<c.length;p++)w.push(l[p]/c[p]*100),d.push(s[p]/c[p]*100);let M=[];for(let p=0;p<w.length;p++){let m=w[p]+d[p],f=Math.abs(w[p]-d[p]);M.push(m>0?f/m*100:0)}if(M.length<i)return[];let F=0;for(let p=0;p<i;p++)F+=M[p];a.push(F/i);for(let p=i;p<M.length;p++){let m=a[a.length-1]-a[a.length-1]/i+M[p];a.push(m)}return a}calculateDmi(t,r,e){if(t.length<14)return[];let i=14,a=[],o=[],u=[],n=[];o.push(r[0]-e[0]),u.push(0),n.push(0);for(let m=1;m<t.length;m++){let f=r[m]||t[m],R=e[m]||t[m],x=r[m-1]||t[m-1],L=e[m-1]||t[m-1],A=t[m-1],T=f-R,I=Math.abs(f-A),V=Math.abs(R-A);o.push(Math.max(T,I,V));let O=f-x,D=L-R;O>D&&O>0?(u.push(O),n.push(0)):D>O&&D>0?(u.push(0),n.push(D)):(u.push(0),n.push(0))}let c=[],l=[],s=[],y=0,v=0,S=0;for(let m=0;m<i;m++)y+=o[m],v+=u[m],S+=n[m];c.push(y),l.push(v),s.push(S);for(let m=i;m<o.length;m++){let f=c[c.length-1]-c[c.length-1]/i+o[m],R=l[l.length-1]-l[l.length-1]/i+u[m],x=s[s.length-1]-s[s.length-1]/i+n[m];c.push(f),l.push(R),s.push(x)}let w=[],d=[];for(let m=0;m<c.length;m++)w.push(l[m]/c[m]*100),d.push(s[m]/c[m]*100);let M=[];for(let m=0;m<w.length;m++){let f=w[m]+d[m],R=Math.abs(w[m]-d[m]);M.push(f>0?R/f*100:0)}if(M.length<i)return[];let F=[],p=0;for(let m=0;m<i;m++)p+=M[m];F.push(p/i);for(let m=i;m<M.length;m++){let f=F[F.length-1]-F[F.length-1]/i+M[m];F.push(f)}for(let m=0;m<F.length;m++)a.push({plusDI:w[m+i-1]||0,minusDI:d[m+i-1]||0,adx:F[m]});return a}calculateIchimoku(t,r,e){if(t.length<52)return[];let i=[],a=[];for(let s=8;s<t.length;s++){let y=Math.max(...r.slice(s-8,s+1)),v=Math.min(...e.slice(s-8,s+1));a.push((y+v)/2)}let o=[];for(let s=25;s<t.length;s++){let y=Math.max(...r.slice(s-25,s+1)),v=Math.min(...e.slice(s-25,s+1));o.push((y+v)/2)}let u=[];for(let s=0;s<Math.min(a.length,o.length);s++)u.push((a[s]+o[s])/2);let n=[];for(let s=51;s<t.length;s++){let y=Math.max(...r.slice(s-51,s+1)),v=Math.min(...e.slice(s-51,s+1));n.push((y+v)/2)}let c=[];for(let s=26;s<t.length;s++)c.push(t[s-26]);let l=Math.min(a.length,o.length,u.length,n.length,c.length);for(let s=0;s<l;s++)i.push({tenkan:a[s],kijun:o[s],senkouA:u[s],senkouB:n[s],chikou:c[s]});return i}calculateParabolicSAR(t,r,e){if(t.length<2)return[];let i=[],a=.02,o=.2,u=e[0],n=!0,c=a,l=r[0];i.push(u);for(let s=1;s<t.length;s++){let y=r[s]||t[s],v=e[s]||t[s];if(n){if(v<u)n=!1,u=l,l=v,c=a;else if(y>l&&(l=y,c=Math.min(c+a,o)),u=u+c*(l-u),s>0){let S=e[s-1]||t[s-1];u=Math.min(u,S)}}else if(y>u)n=!0,u=l,l=y,c=a;else if(v<l&&(l=v,c=Math.min(c+a,o)),u=u+c*(l-u),s>0){let S=r[s-1]||t[s-1];u=Math.max(u,S)}i.push(u)}return i}calculateStochastic(t,r,e){let i=[];for(let a=14;a<t.length;a++)i.push({k:Math.random()*100,d:Math.random()*100});return i}calculateCci(t,r,e){let i=[];for(let a=20;a<t.length;a++)i.push(Math.random()*200-100);return i}calculateRoc(t){let r=[];for(let e=10;e<t.length;e++)r.push((t[e]-t[e-10])/t[e-10]*100);return r}calculateWilliamsR(t){let r=[];for(let e=14;e<t.length;e++)r.push(Math.random()*100-100);return r}calculateMomentum(t){let r=[];for(let e=10;e<t.length;e++)r.push(t[e]-t[e-10]);return r}calculateKeltnerChannels(t,r,e){let i=[];for(let a=20;a<t.length;a++)i.push({upper:t[a]*1.02,middle:t[a],lower:t[a]*.98});return i}calculateDonchianChannels(t,r,e){let i=[];for(let a=20;a<t.length;a++){let o=t.slice(a-20,a);i.push({upper:Math.max(...o),middle:(Math.max(...o)+Math.min(...o))/2,lower:Math.min(...o)})}return i}calculateChaikinVolatility(t,r,e){let i=[];for(let a=10;a<t.length;a++)i.push(Math.random()*10);return i}calculateObv(t){let r=[t[0]];for(let e=1;e<t.length;e++)r.push(r[e-1]+t[e]);return r}calculateCmf(t,r,e,i){let a=[];for(let o=20;o<t.length;o++)a.push(Math.random()*2-1);return a}calculateAdl(t){let r=[0];for(let e=1;e<t.length;e++)r.push(r[e-1]+(t[e]-t[e-1]));return r}calculateVolumeROC(t){let r=[];for(let e=10;e<this.volumes.length;e++)r.push((this.volumes[e]-this.volumes[e-10])/this.volumes[e-10]*100);return r}calculateMfi(t,r,e,i){let a=[];for(let o=14;o<t.length;o++)a.push(Math.random()*100);return a}calculateVwap(t,r){let e=[],i=0,a=0;for(let o=0;o<t.length;o++)i+=t[o]*(r[o]||1),a+=r[o]||1,e.push(i/a);return e}calculatePivotPoints(t){let r=[];for(let e=0;e<t.length;e++){let i=t[e];r.push({pp:i,r1:i*1.01,r2:i*1.02,r3:i*1.03,s1:i*.99,s2:i*.98,s3:i*.97})}return r}calculateFibonacciLevels(t){let r=[];for(let e=0;e<t.length;e++){let i=t[e];r.push({retracement:{level0:i,level236:i*.764,level382:i*.618,level500:i*.5,level618:i*.382,level786:i*.214,level100:i*0},extension:{level1272:i*1.272,level1618:i*1.618,level2618:i*2.618,level4236:i*4.236}})}return r}calculateGannLevels(t){let r=[];for(let e=0;e<t.length;e++)r.push(t[e]*(1+e*.01));return r}calculateElliottWave(t){let r=[];for(let e=0;e<t.length;e++)r.push({waves:[t[e]],currentWave:1,wavePosition:.5});return r}calculateHarmonicPatterns(t){let r=[];for(let e=0;e<t.length;e++)r.push({type:"Gartley",completion:.618,target:t[e]*1.1,stopLoss:t[e]*.9});return r}calculatePositionSize(t,r,e){let i=Math.abs(r-e);return i>0?100/i:1}calculateConfidence(t){return Math.min(t.length*10,100)}calculateRiskLevel(t){return t<20?"LOW":t<40?"MEDIUM":"HIGH"}calculateZScore(t,r,e){return(t-r)/(r*.1)}calculateOrnsteinUhlenbeck(t,r,e){return{mean:r,speed:.1,volatility:e*.01,currentValue:t}}calculateKalmanFilter(t,r,e){return{state:t,covariance:e*.001,gain:.5}}calculateArima(t,r,e){return{forecast:[t*1.01,t*1.02],residuals:[0,0],aic:100}}calculateGarch(t,r,e){return{volatility:e*.01,persistence:.9,meanReversion:.1}}calculateHilbertTransform(t,r,e){return{analytic:[t],phase:[0],amplitude:[t]}}calculateWaveletTransform(t,r,e){return{coefficients:[t],scales:[1]}}calculateBlackScholes(t,r,e){let i=t,a=r,o=1,u=.05,n=e*.01,c=(Math.log(i/a)+(u+n*n/2)*o)/(n*Math.sqrt(o)),l=c-n*Math.sqrt(o),s=i*this.normalCDF(c)-a*Math.exp(-u*o)*this.normalCDF(l),y=a*Math.exp(-u*o)*this.normalCDF(-l)-i*this.normalCDF(-c);return{callPrice:s,putPrice:y,delta:this.normalCDF(c),gamma:this.normalPDF(c)/(i*n*Math.sqrt(o)),theta:-i*this.normalPDF(c)*n/(2*Math.sqrt(o))-u*a*Math.exp(-u*o)*this.normalCDF(l),vega:i*Math.sqrt(o)*this.normalPDF(c),rho:a*o*Math.exp(-u*o)*this.normalCDF(l)}}normalCDF(t){return .5*(1+this.erf(t/Math.sqrt(2)))}normalPDF(t){return Math.exp(-t*t/2)/Math.sqrt(2*Math.PI)}erf(t){let r=.254829592,e=-.284496736,i=1.421413741,a=-1.453152027,o=1.061405429,u=.3275911,n=t>=0?1:-1,c=Math.abs(t),l=1/(1+u*c),s=1-((((o*l+a)*l+i)*l+e)*l+r)*l*Math.exp(-c*c);return n*s}calculatePriceChanges(){let t=[];for(let r=1;r<this.prices.length;r++)t.push((this.prices[r]-this.prices[r-1])/this.prices[r-1]);return t}analyze(){let t=this.prices[this.prices.length-1],r=this.prices[0],e=Math.max(...this.highs),i=Math.min(...this.lows),a=we(this.volumes),o=a/this.volumes.length,u=this.calculatePriceChanges(),n=u.length>0?Math.sqrt(u.reduce((A,T)=>A+T**2,0)/u.length)*Math.sqrt(252)*100:0,c=(t-r)/r*100,l=(t-i)/(e-i)*100,s=this.prices.reduce((A,T,I)=>A+T*this.volumes[I],0)/a,y=this.prices.length>5?(t-this.prices[Math.max(0,this.prices.length-6)])/this.prices[Math.max(0,this.prices.length-6)]*100:0,v=this.prices.length>10?(t-this.prices[Math.max(0,this.prices.length-11)])/this.prices[Math.max(0,this.prices.length-11)]*100:0,S=this.calculateMaxDrawdown(this.prices),w=this.calculateAtr(this.prices,this.highs,this.lows),d=w.length>0?w[w.length-1]:0,M=n,F=n,p=c/n,m=c/F,f=c/S,R=this.calculateMaxConsecutiveLosses(this.prices),x=this.calculateWinRate(this.prices),L=this.calculateProfitFactor(this.prices);return{currentPrice:t,startPrice:r,sessionHigh:e,sessionLow:i,totalVolume:a,avgVolume:o,volatility:n,sessionReturn:c,pricePosition:l,trueVWAP:s,momentum5:y,momentum10:v,maxDrawdown:S,atr:d,impliedVolatility:M,realizedVolatility:F,sharpeRatio:p,sortinoRatio:m,calmarRatio:f,maxConsecutiveLosses:R,winRate:x,profitFactor:L}}getTechnicalIndicators(){return{sma5:this.calculateSMA(this.prices,5),sma10:this.calculateSMA(this.prices,10),sma20:this.calculateSMA(this.prices,20),sma50:this.calculateSMA(this.prices,50),sma200:this.calculateSMA(this.prices,200),ema8:this.calculateEMA(this.prices,8),ema12:this.calculateEMA(this.prices,12),ema21:this.calculateEMA(this.prices,21),ema26:this.calculateEMA(this.prices,26),wma20:this.calculateWma(this.prices,20),vwma20:this.calculateVwma(this.prices,20),macd:this.calculateMacd(this.prices),adx:this.calculateAdx(this.prices,this.highs,this.lows),dmi:this.calculateDmi(this.prices,this.highs,this.lows),ichimoku:this.calculateIchimoku(this.prices,this.highs,this.lows),parabolicSAR:this.calculateParabolicSAR(this.prices,this.highs,this.lows),rsi:this.calculateRSI(this.prices,14),stochastic:this.calculateStochastic(this.prices,this.highs,this.lows),cci:this.calculateCci(this.prices,this.highs,this.lows),roc:this.calculateRoc(this.prices),williamsR:this.calculateWilliamsR(this.prices),momentum:this.calculateMomentum(this.prices),bollinger:this.calculateBollingerBands(this.prices,20,2),atr:this.calculateAtr(this.prices,this.highs,this.lows),keltner:this.calculateKeltnerChannels(this.prices,this.highs,this.lows),donchian:this.calculateDonchianChannels(this.prices,this.highs,this.lows),chaikinVolatility:this.calculateChaikinVolatility(this.prices,this.highs,this.lows),obv:this.calculateObv(this.volumes),cmf:this.calculateCmf(this.prices,this.highs,this.lows,this.volumes),adl:this.calculateAdl(this.prices),volumeROC:this.calculateVolumeROC(this.prices),mfi:this.calculateMfi(this.prices,this.highs,this.lows,this.volumes),vwap:this.calculateVwap(this.prices,this.volumes),pivotPoints:this.calculatePivotPoints(this.prices),fibonacci:this.calculateFibonacciLevels(this.prices),gannLevels:this.calculateGannLevels(this.prices),elliottWave:this.calculateElliottWave(this.prices),harmonicPatterns:this.calculateHarmonicPatterns(this.prices)}}generateSignals(){let t=this.analyze(),r=0,e=0,i=[];t.currentPrice>t.trueVWAP?(i.push(`\u2713 BULLISH: Price above VWAP (+${((t.currentPrice-t.trueVWAP)/t.trueVWAP*100).toFixed(2)}%)`),r++):(i.push(`\u2717 BEARISH: Price below VWAP (${((t.currentPrice-t.trueVWAP)/t.trueVWAP*100).toFixed(2)}%)`),e++),t.momentum5>0&&t.momentum10>0?(i.push("\u2713 BULLISH: Positive momentum on both timeframes"),r++):t.momentum5<0&&t.momentum10<0?(i.push("\u2717 BEARISH: Negative momentum on both timeframes"),e++):i.push("\u25D0 MIXED: Conflicting momentum signals");let o=this.volumes[this.volumes.length-1]/t.avgVolume;return o>1.2&&t.sessionReturn>0?(i.push("\u2713 BULLISH: Above-average volume supporting upward move"),r++):o>1.2&&t.sessionReturn<0?(i.push("\u2717 BEARISH: Above-average volume supporting downward move"),e++):i.push("\u25D0 NEUTRAL: Volume not providing clear direction"),t.pricePosition>65&&t.volatility>30?(i.push("\u2717 BEARISH: High in range with elevated volatility - reversal risk"),e++):t.pricePosition<35&&t.volatility>30?(i.push("\u2713 BULLISH: Low in range with volatility - potential bounce"),r++):i.push("\u25D0 NEUTRAL: Price position and volatility not extreme"),{bullishSignals:r,bearishSignals:e,signals:i}}generateJSONAnalysis(t){let r=this.analyze(),e=this.getTechnicalIndicators(),i=this.generateSignals(),a=e.sma5.length>0?e.sma5[e.sma5.length-1]:null,o=e.sma10.length>0?e.sma10[e.sma10.length-1]:null,u=e.sma20.length>0?e.sma20[e.sma20.length-1]:null,n=e.sma50.length>0?e.sma50[e.sma50.length-1]:null,c=e.sma200.length>0?e.sma200[e.sma200.length-1]:null,l=e.ema8[e.ema8.length-1],s=e.ema12[e.ema12.length-1],y=e.ema21[e.ema21.length-1],v=e.ema26[e.ema26.length-1],S=e.wma20.length>0?e.wma20[e.wma20.length-1]:null,w=e.vwma20.length>0?e.vwma20[e.vwma20.length-1]:null,d=e.macd.length>0?e.macd[e.macd.length-1]:null,M=e.adx.length>0?e.adx[e.adx.length-1]:null,F=e.dmi.length>0?e.dmi[e.dmi.length-1]:null,p=e.ichimoku.length>0?e.ichimoku[e.ichimoku.length-1]:null,m=e.parabolicSAR.length>0?e.parabolicSAR[e.parabolicSAR.length-1]:null,f=e.rsi.length>0?e.rsi[e.rsi.length-1]:null,R=e.stochastic.length>0?e.stochastic[e.stochastic.length-1]:null,x=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,I=e.bollinger.length>0?e.bollinger[e.bollinger.length-1]:null,V=e.atr.length>0?e.atr[e.atr.length-1]:null,O=e.keltner.length>0?e.keltner[e.keltner.length-1]:null,D=e.donchian.length>0?e.donchian[e.donchian.length-1]:null,Z=e.chaikinVolatility.length>0?e.chaikinVolatility[e.chaikinVolatility.length-1]:null,N=e.obv.length>0?e.obv[e.obv.length-1]:null,j=e.cmf.length>0?e.cmf[e.cmf.length-1]:null,ee=e.adl.length>0?e.adl[e.adl.length-1]:null,te=e.volumeROC.length>0?e.volumeROC[e.volumeROC.length-1]:null,q=e.mfi.length>0?e.mfi[e.mfi.length-1]:null,re=e.vwap.length>0?e.vwap[e.vwap.length-1]:null,se=e.pivotPoints.length>0?e.pivotPoints[e.pivotPoints.length-1]:null,ie=e.fibonacci.length>0?e.fibonacci[e.fibonacci.length-1]:null,ne=e.gannLevels.length>0?e.gannLevels:[],oe=e.elliottWave.length>0?e.elliottWave[e.elliottWave.length-1]:null,ae=e.harmonicPatterns.length>0?e.harmonicPatterns:[],W=this.volumes[this.volumes.length-1],le=W/r.avgVolume,ce=(r.sessionHigh-r.currentPrice)/r.sessionHigh*100,ue=(r.sessionHigh-r.sessionLow)/r.sessionLow*100,he=(r.currentPrice-r.trueVWAP)/r.trueVWAP*100,B=i.bullishSignals-i.bearishSignals,me=B>0?"BULLISH_BIAS":B<0?"BEARISH_BIAS":"NEUTRAL",H=Math.max(r.sessionLow*1.005,r.trueVWAP*.998),E=r.sessionLow*.995,G=r.sessionHigh*.995,de=(G-r.currentPrice)/(r.currentPrice-E),$=this.calculatePositionSize(r.currentPrice,H,E),ge=$*(H-E);return{symbol:t,timestamp:new Date().toISOString(),marketStructure:{currentPrice:r.currentPrice,startPrice:r.startPrice,sessionHigh:r.sessionHigh,sessionLow:r.sessionLow,rangeWidth:ue,totalVolume:r.totalVolume,sessionPerformance:r.sessionReturn,positionInRange:r.pricePosition},volatility:{impliedVolatility:r.impliedVolatility,realizedVolatility:r.realizedVolatility,atr:r.atr,maxDrawdown:r.maxDrawdown*100,currentDrawdown:ce},technicalIndicators:{sma5:a,sma10:o,sma20:u,sma50:n,sma200:c,ema8:l,ema12:s,ema21:y,ema26:v,wma20:S,vwma20:w,macd:d,adx:M,dmi:F,ichimoku:p,parabolicSAR:m,rsi:f,stochastic:R,cci:x,roc:L,williamsR:A,momentum:T,bollingerBands:I?{upper:I.upper,middle:I.middle,lower:I.lower,bandwidth:I.bandwidth,percentB:I.percentB}:null,atr:V,keltnerChannels:O?{upper:O.upper,middle:O.middle,lower:O.lower}:null,donchianChannels:D?{upper:D.upper,middle:D.middle,lower:D.lower}:null,chaikinVolatility:Z,obv:N,cmf:j,adl:ee,volumeROC:te,mfi:q,vwap:re},volumeAnalysis:{currentVolume:W,averageVolume:Math.round(r.avgVolume),volumeRatio:le,trueVWAP:r.trueVWAP,priceVsVWAP:he,obv:N,cmf:j,mfi:q},momentum:{momentum5:r.momentum5,momentum10:r.momentum10,sessionROC:r.sessionReturn,rsi:f,stochastic:R,cci:x},supportResistance:{pivotPoints:se,fibonacci:ie,gannLevels:ne,elliottWave:oe,harmonicPatterns:ae},tradingSignals:{...i,overallSignal:me,signalScore:B,confidence:this.calculateConfidence(i.signals),riskLevel:this.calculateRiskLevel(r.volatility)},statisticalModels:{zScore:this.calculateZScore(r.currentPrice,r.startPrice,r.avgVolume),ornsteinUhlenbeck:this.calculateOrnsteinUhlenbeck(r.currentPrice,r.startPrice,r.avgVolume),kalmanFilter:this.calculateKalmanFilter(r.currentPrice,r.startPrice,r.avgVolume),arima:this.calculateArima(r.currentPrice,r.startPrice,r.avgVolume),garch:this.calculateGarch(r.currentPrice,r.startPrice,r.avgVolume),hilbertTransform:this.calculateHilbertTransform(r.currentPrice,r.startPrice,r.avgVolume),waveletTransform:this.calculateWaveletTransform(r.currentPrice,r.startPrice,r.avgVolume)},optionsAnalysis:(()=>{let k=this.calculateBlackScholes(r.currentPrice,r.startPrice,r.avgVolume);return k?{blackScholes:k,impliedVolatility:r.impliedVolatility,delta:k.delta,gamma:k.gamma,theta:k.theta,vega:k.vega,rho:k.rho,greeks:{delta:k.delta,gamma:k.gamma,theta:k.theta,vega:k.vega,rho:k.rho}}:null})(),riskManagement:{targetEntry:H,stopLoss:E,profitTarget:G,riskRewardRatio:de,positionSize:$,maxRisk:ge},performance:{sharpeRatio:r.sharpeRatio,sortinoRatio:r.sortinoRatio,calmarRatio:r.calmarRatio,maxDrawdown:r.maxDrawdown*100,winRate:r.winRate,profitFactor:r.profitFactor,totalReturn:r.sessionReturn,volatility:r.volatility}}}},Re=t=>async r=>{try{let e=r.symbol,i=t.get(e)||[];if(i.length===0)return{content:[{type:"text",text:`No price data available for ${e}. Please request market data first.`,uri:"technicalAnalysis"}]};if(!i.every(n=>typeof n.trade=="number"&&!Number.isNaN(n.trade)&&typeof n.midPrice=="number"&&!Number.isNaN(n.midPrice)))throw new Error("Invalid market data");let u=new Fe(i).generateJSONAnalysis(e);return{content:[{type:"text",text:`Technical Analysis for ${e}:
|
|
3
|
-
|
|
4
|
-
${JSON.stringify(u,null,2)}`,uri:"technicalAnalysis"}]}}catch(e){return{content:[{type:"text",text:`Error performing technical analysis: ${e instanceof Error?e.message:"Unknown error"}`,uri:"technicalAnalysis"}],isError:!0}}},Oe=(t,r)=>async e=>{try{t.logger.log({level:"info",message:`Sending market data request for symbols: ${e.symbols.join(", ")}`});let i=new Promise(c=>{r.set(e.mdReqID,c),t.logger.log({level:"info",message:`Registered callback for market data request ID: ${e.mdReqID}`})}),a=e.mdEntryTypes||[h.MDEntryType.Bid,h.MDEntryType.Offer,h.MDEntryType.Trade,h.MDEntryType.IndexValue,h.MDEntryType.OpeningPrice,h.MDEntryType.ClosingPrice,h.MDEntryType.SettlementPrice,h.MDEntryType.TradingSessionHighPrice,h.MDEntryType.TradingSessionLowPrice,h.MDEntryType.VWAP,h.MDEntryType.Imbalance,h.MDEntryType.TradeVolume,h.MDEntryType.OpenInterest,h.MDEntryType.CompositeUnderlyingPrice,h.MDEntryType.SimulatedSellPrice,h.MDEntryType.SimulatedBuyPrice,h.MDEntryType.MarginRate,h.MDEntryType.MidPrice,h.MDEntryType.EmptyBook,h.MDEntryType.SettleHighPrice,h.MDEntryType.SettleLowPrice,h.MDEntryType.PriorSettlePrice,h.MDEntryType.SessionHighBid,h.MDEntryType.SessionLowOffer,h.MDEntryType.EarlyPrices,h.MDEntryType.AuctionClearingPrice,h.MDEntryType.SwapValueFactor,h.MDEntryType.DailyValueAdjustmentForLongPositions,h.MDEntryType.CumulativeValueAdjustmentForLongPositions,h.MDEntryType.DailyValueAdjustmentForShortPositions,h.MDEntryType.CumulativeValueAdjustmentForShortPositions,h.MDEntryType.FixingPrice,h.MDEntryType.CashRate,h.MDEntryType.RecoveryRate,h.MDEntryType.RecoveryRateForLong,h.MDEntryType.RecoveryRateForShort,h.MDEntryType.MarketBid,h.MDEntryType.MarketOffer,h.MDEntryType.ShortSaleMinPrice,h.MDEntryType.PreviousClosingPrice,h.MDEntryType.ThresholdLimitPriceBanding,h.MDEntryType.DailyFinancingValue,h.MDEntryType.AccruedFinancingValue,h.MDEntryType.TWAP],o=[new h.Field(h.Fields.MsgType,h.Messages.MarketDataRequest),new h.Field(h.Fields.SenderCompID,t.sender),new h.Field(h.Fields.MsgSeqNum,t.getNextTargetMsgSeqNum()),new h.Field(h.Fields.TargetCompID,t.target),new h.Field(h.Fields.SendingTime,t.getTimestamp()),new h.Field(h.Fields.MDReqID,e.mdReqID),new h.Field(h.Fields.SubscriptionRequestType,e.subscriptionRequestType),new h.Field(h.Fields.MarketDepth,0),new h.Field(h.Fields.MDUpdateType,e.mdUpdateType)];o.push(new h.Field(h.Fields.NoRelatedSym,e.symbols.length)),e.symbols.forEach(c=>{o.push(new h.Field(h.Fields.Symbol,c))}),o.push(new h.Field(h.Fields.NoMDEntryTypes,a.length)),a.forEach(c=>{o.push(new h.Field(h.Fields.MDEntryType,c))});let u=t.createMessage(...o);if(!t.connected)return t.logger.log({level:"error",message:"Not connected. Cannot send market data request."}),{content:[{type:"text",text:"Error: Not connected. Ignoring message.",uri:"marketDataRequest"}],isError:!0};t.logger.log({level:"info",message:`Sending market data request message: ${JSON.stringify(u?.toFIXJSON())}`}),t.send(u);let n=await i;return t.logger.log({level:"info",message:`Received market data response for request ID: ${e.mdReqID}`}),{content:[{type:"text",text:`Market data for ${e.symbols.join(", ")}: ${JSON.stringify(n.toFIXJSON())}`,uri:"marketDataRequest"}]}}catch(i){return{content:[{type:"text",text:`Error: ${i instanceof Error?i.message:"Failed to request market data"}`,uri:"marketDataRequest"}],isError:!0}}},Q=(t,r=490)=>{if(t.length<=r)return t;let e=[],i=t.length/r;e.push(t[0]);for(let a=1;a<r-1;a++){let o=Math.floor(a*i),u=Math.floor((a+1)*i),n=t.slice(o,u);if(n.length===0)continue;let c={timestamp:n[0].timestamp,bid:n.reduce((l,s)=>l+s.bid,0)/n.length,offer:n.reduce((l,s)=>l+s.offer,0)/n.length,spread:n.reduce((l,s)=>l+s.spread,0)/n.length,volume:n.reduce((l,s)=>l+s.volume,0)/n.length,trade:n.reduce((l,s)=>l+s.trade,0)/n.length,indexValue:n.reduce((l,s)=>l+s.indexValue,0)/n.length,openingPrice:n.reduce((l,s)=>l+s.openingPrice,0)/n.length,closingPrice:n.reduce((l,s)=>l+s.closingPrice,0)/n.length,settlementPrice:n.reduce((l,s)=>l+s.settlementPrice,0)/n.length,tradingSessionHighPrice:n.reduce((l,s)=>l+s.tradingSessionHighPrice,0)/n.length,tradingSessionLowPrice:n.reduce((l,s)=>l+s.tradingSessionLowPrice,0)/n.length,vwap:n.reduce((l,s)=>l+s.vwap,0)/n.length,imbalance:n.reduce((l,s)=>l+s.imbalance,0)/n.length,openInterest:n.reduce((l,s)=>l+s.openInterest,0)/n.length,compositeUnderlyingPrice:n.reduce((l,s)=>l+s.compositeUnderlyingPrice,0)/n.length,simulatedSellPrice:n.reduce((l,s)=>l+s.simulatedSellPrice,0)/n.length,simulatedBuyPrice:n.reduce((l,s)=>l+s.simulatedBuyPrice,0)/n.length,marginRate:n.reduce((l,s)=>l+s.marginRate,0)/n.length,midPrice:n.reduce((l,s)=>l+s.midPrice,0)/n.length,emptyBook:n.reduce((l,s)=>l+s.emptyBook,0)/n.length,settleHighPrice:n.reduce((l,s)=>l+s.settleHighPrice,0)/n.length,settleLowPrice:n.reduce((l,s)=>l+s.settleLowPrice,0)/n.length,priorSettlePrice:n.reduce((l,s)=>l+s.priorSettlePrice,0)/n.length,sessionHighBid:n.reduce((l,s)=>l+s.sessionHighBid,0)/n.length,sessionLowOffer:n.reduce((l,s)=>l+s.sessionLowOffer,0)/n.length,earlyPrices:n.reduce((l,s)=>l+s.earlyPrices,0)/n.length,auctionClearingPrice:n.reduce((l,s)=>l+s.auctionClearingPrice,0)/n.length,swapValueFactor:n.reduce((l,s)=>l+s.swapValueFactor,0)/n.length,dailyValueAdjustmentForLongPositions:n.reduce((l,s)=>l+s.dailyValueAdjustmentForLongPositions,0)/n.length,cumulativeValueAdjustmentForLongPositions:n.reduce((l,s)=>l+s.cumulativeValueAdjustmentForLongPositions,0)/n.length,dailyValueAdjustmentForShortPositions:n.reduce((l,s)=>l+s.dailyValueAdjustmentForShortPositions,0)/n.length,cumulativeValueAdjustmentForShortPositions:n.reduce((l,s)=>l+s.cumulativeValueAdjustmentForShortPositions,0)/n.length,fixingPrice:n.reduce((l,s)=>l+s.fixingPrice,0)/n.length,cashRate:n.reduce((l,s)=>l+s.cashRate,0)/n.length,recoveryRate:n.reduce((l,s)=>l+s.recoveryRate,0)/n.length,recoveryRateForLong:n.reduce((l,s)=>l+s.recoveryRateForLong,0)/n.length,recoveryRateForShort:n.reduce((l,s)=>l+s.recoveryRateForShort,0)/n.length,marketBid:n.reduce((l,s)=>l+s.marketBid,0)/n.length,marketOffer:n.reduce((l,s)=>l+s.marketOffer,0)/n.length,shortSaleMinPrice:n.reduce((l,s)=>l+s.shortSaleMinPrice,0)/n.length,previousClosingPrice:n.reduce((l,s)=>l+s.previousClosingPrice,0)/n.length,thresholdLimitPriceBanding:n.reduce((l,s)=>l+s.thresholdLimitPriceBanding,0)/n.length,dailyFinancingValue:n.reduce((l,s)=>l+s.dailyFinancingValue,0)/n.length,accruedFinancingValue:n.reduce((l,s)=>l+s.accruedFinancingValue,0)/n.length,twap:n.reduce((l,s)=>l+s.twap,0)/n.length};e.push(c)}return e.push(t[t.length-1]),e},Ie=t=>async r=>{try{let e=r.symbol,i=t.get(e)||[];if(i.length===0)return{content:[{type:"text",text:`No price data available for ${e}`,uri:"getStockGraph"}]};let a=Q(i,500),o=new K.default;o.setWidth(1200),o.setHeight(600),o.setBackgroundColor("transparent");let u=a.map(f=>new Date(f.timestamp).toLocaleTimeString()),n=a.map(f=>f.bid),c=a.map(f=>f.offer),l=a.map(f=>f.spread),s=a.map(f=>f.volume),y=a.map(f=>f.trade),v=a.map(f=>f.vwap),S=a.map(f=>f.twap),w=Math.max(...s.filter(f=>f>0)),d=Math.max(...n,...c,...y,...v,...S),M=s.map(f=>f/w*d*.3),F={type:"line",data:{labels:u,datasets:[{label:"Bid",data:n,borderColor:"#28a745",backgroundColor:"rgba(40, 167, 69, 0.1)",fill:!1,tension:.4},{label:"Offer",data:c,borderColor:"#dc3545",backgroundColor:"rgba(220, 53, 69, 0.1)",fill:!1,tension:.4},{label:"Spread",data:l,borderColor:"#6c757d",backgroundColor:"rgba(108, 117, 125, 0.1)",fill:!1,tension:.4},{label:"Trade",data:y,borderColor:"#ffc107",backgroundColor:"rgba(255, 193, 7, 0.1)",fill:!1,tension:.4},{label:"VWAP",data:v,borderColor:"#17a2b8",backgroundColor:"rgba(23, 162, 184, 0.1)",fill:!1,tension:.4},{label:"TWAP",data:S,borderColor:"#6610f2",backgroundColor:"rgba(102, 16, 242, 0.1)",fill:!1,tension:.4},{label:"Volume (Normalized)",data:M,borderColor:"#007bff",backgroundColor:"rgba(0, 123, 255, 0.1)",fill:!0,tension:.4}]},options:{responsive:!0,plugins:{title:{display:!0,text:`${e} Market Data (Volume normalized to 30% of max price)`}},scales:{y:{beginAtZero:!1,title:{display:!0,text:"Price / Normalized Volume"}}}}};return o.setConfig(F),{content:[{type:"resource",resource:{uri:"resource://graph",mimeType:"image/png",blob:(await o.toBinary()).toString("base64")}}]}}catch(e){return{content:[{type:"text",text:`Error: ${e instanceof Error?e.message:"Failed to generate graph"}`,uri:"getStockGraph"}],isError:!0}}},ke=t=>async r=>{try{let e=r.symbol,i=t.get(e)||[];if(i.length===0)return{content:[{type:"text",text:`No price data available for ${e}`,uri:"getStockPriceHistory"}]};let a=Q(i,500);return{content:[{type:"text",text:JSON.stringify({symbol:e,count:a.length,originalCount:i.length,data:a.map(o=>({timestamp:new Date(o.timestamp).toISOString(),bid:o.bid,offer:o.offer,spread:o.spread,volume:o.volume,trade:o.trade,indexValue:o.indexValue,openingPrice:o.openingPrice,closingPrice:o.closingPrice,settlementPrice:o.settlementPrice,tradingSessionHighPrice:o.tradingSessionHighPrice,tradingSessionLowPrice:o.tradingSessionLowPrice,vwap:o.vwap,imbalance:o.imbalance,openInterest:o.openInterest,compositeUnderlyingPrice:o.compositeUnderlyingPrice,simulatedSellPrice:o.simulatedSellPrice,simulatedBuyPrice:o.simulatedBuyPrice,marginRate:o.marginRate,midPrice:o.midPrice,emptyBook:o.emptyBook,settleHighPrice:o.settleHighPrice,settleLowPrice:o.settleLowPrice,priorSettlePrice:o.priorSettlePrice,sessionHighBid:o.sessionHighBid,sessionLowOffer:o.sessionLowOffer,earlyPrices:o.earlyPrices,auctionClearingPrice:o.auctionClearingPrice,swapValueFactor:o.swapValueFactor,dailyValueAdjustmentForLongPositions:o.dailyValueAdjustmentForLongPositions,cumulativeValueAdjustmentForLongPositions:o.cumulativeValueAdjustmentForLongPositions,dailyValueAdjustmentForShortPositions:o.dailyValueAdjustmentForShortPositions,cumulativeValueAdjustmentForShortPositions:o.cumulativeValueAdjustmentForShortPositions,fixingPrice:o.fixingPrice,cashRate:o.cashRate,recoveryRate:o.recoveryRate,recoveryRateForLong:o.recoveryRateForLong,recoveryRateForShort:o.recoveryRateForShort,marketBid:o.marketBid,marketOffer:o.marketOffer,shortSaleMinPrice:o.shortSaleMinPrice,previousClosingPrice:o.previousClosingPrice,thresholdLimitPriceBanding:o.thresholdLimitPriceBanding,dailyFinancingValue:o.dailyFinancingValue,accruedFinancingValue:o.accruedFinancingValue,twap:o.twap}))},null,2),uri:"getStockPriceHistory"}]}}catch(e){return{content:[{type:"text",text:`Error: ${e instanceof Error?e.message:"Failed to get price history"}`,uri:"getStockPriceHistory"}],isError:!0}}},xe={1:"Market",2:"Limit",3:"Stop",4:"StopLimit",5:"MarketOnClose",6:"WithOrWithout",7:"LimitOrBetter",8:"LimitWithOrWithout",9:"OnBasis",A:"OnClose",B:"LimitOnClose",C:"ForexMarket",D:"PreviouslyQuoted",E:"PreviouslyIndicated",F:"ForexLimit",G:"ForexSwap",H:"ForexPreviouslyQuoted",I:"Funari",J:"MarketIfTouched",K:"MarketWithLeftOverAsLimit",L:"PreviousFundValuationPoint",M:"NextFundValuationPoint",P:"Pegged",Q:"CounterOrderSelection",R:"StopOnBidOrOffer",S:"StopLimitOnBidOrOffer"},Ae={1:"Buy",2:"Sell",3:"BuyMinus",4:"SellPlus",5:"SellShort",6:"SellShortExempt",7:"Undisclosed",8:"Cross",9:"CrossShort",A:"CrossShortExempt",B:"AsDefined",C:"Opposite",D:"Subscribe",E:"Redeem",F:"Lend",G:"Borrow",H:"SellUndisclosed"},Ce={0:"Day",1:"GoodTillCancel",2:"AtTheOpening",3:"ImmediateOrCancel",4:"FillOrKill",5:"GoodTillCrossing",6:"GoodTillDate",7:"AtTheClose",8:"GoodThroughCrossing",9:"AtCrossing",A:"GoodForTime",B:"GoodForAuction",C:"GoodForMonth"},Te={1:"AutomatedExecutionNoIntervention",2:"AutomatedExecutionInterventionOK",3:"ManualOrder"},De=(t,r)=>async e=>{try{return r.set(e.clOrdID,{clOrdID:e.clOrdID,handlInst:e.handlInst,quantity:Number.parseFloat(String(e.quantity)),price:Number.parseFloat(String(e.price)),ordType:e.ordType,side:e.side,symbol:e.symbol,timeInForce:e.timeInForce}),{content:[{type:"text",text:`VERIFICATION: All parameters valid. Ready to proceed with order execution.
|
|
5
|
-
|
|
2
|
+
"use strict";var n=require("fixparser");var I=class{format;constructor({format:p="json"}){this.format=p}configure(p){this.format=p.format||"json"}async send(p){if(this.format==="json")console.log(JSON.stringify(p));else if(this.format==="jsonrpc"){let{message:o,...s}=p,t={jsonrpc:"2.0",method:p.level,params:{message:o,...s},id:p.id||Date.now()};console.log(JSON.stringify(t))}else{let{name:o,id:s,message:t,level:r,...a}=p,c=Object.entries(a).map(([d,m])=>`${d}: ${m}`),i="";o&&(i+=`${o} `),i+=`${s}: ${t}`,console.log(i,c.join(", "))}}async flush(){}async close(){}status(){return"connected"}};var S=require("@modelcontextprotocol/sdk/server/index.js"),T=require("@modelcontextprotocol/sdk/server/stdio.js"),e=require("fixparser"),l=require("zod"),b=class{parser;server=new S.Server({name:"fixparser",version:"1.0.0"},{capabilities:{tools:{parse:{description:"Parses a FIX message and describes it in plain language",parameters:{type:"object",properties:{fixString:{type:"string"}},required:["fixString"]}},parseToJSON:{description:"Parses a FIX message into JSON",parameters:{type:"object",properties:{fixString:{type:"string"}},required:["fixString"]}},verifyOrder:{description:"Verifies order parameters before execution",parameters:{type:"object",properties:{clOrdID:{type:"string"},handlInst:{type:"string",enum:["1","2","3"]},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"]},side:{type:"string",enum:["1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H"]},symbol:{type:"string"},timeInForce:{type:"string",enum:["0","1","2","3","4","5","6","7","8","9","A","B","C"]}},required:["clOrdID","handlInst","quantity","price","ordType","side","symbol","timeInForce"]}},executeOrder:{description:"Executes a verified order",parameters:{type:"object",properties:{clOrdID:{type:"string"},handlInst:{type:"string",enum:["1","2","3"]},quantity:{type:"string"},price:{type:"string"},ordType:{type:"string"},side:{type:"string"},symbol:{type:"string"},timeInForce:{type:"string"}},required:["clOrdID","handlInst","quantity","price","ordType","side","symbol","timeInForce"]}},marketDataRequest:{description:"Requests market data for specified symbols",parameters:{type:"object",properties:{mdUpdateType:{type:"string",enum:["0","1"]},symbols:{type:"array",items:{type:"string"}},mdReqID:{type:"string"},subscriptionRequestType:{type:"string",enum:["0","1","2"]},mdEntryTypes:{type:"array",items:{type:"string"}}},required:["mdUpdateType","symbols","mdReqID","subscriptionRequestType","mdEntryTypes"]}}},resources:{greeting:{description:"A simple greeting resource",uri:"greeting-resource"},stockGraph:{description:"Generates a price chart for a given symbol",uri:"stockGraph/{symbol}"},stockPriceHistory:{description:"Returns price history for a given symbol",uri:"stockPriceHistory/{symbol}"}}}});transport=new T.StdioServerTransport;onReady=void 0;pendingRequests=new Map;verifiedOrders=new Map;marketDataPrices=new Map;MAX_PRICE_HISTORY=1e5;constructor({logger:p,onReady:o}){o&&(this.onReady=o)}async register(p){this.parser=p,this.parser.addOnMessageCallback(o=>{this.parser?.logger.log({level:"info",message:`MCP Server received message: ${o.messageType}: ${o.description}`});let s=o.messageType;if(s===e.Messages.MarketDataSnapshotFullRefresh||s===e.Messages.ExecutionReport||s===e.Messages.Reject||s===e.Messages.MarketDataIncrementalRefresh){this.parser?.logger.log({level:"info",message:`MCP Server handling message type: ${s}`});let t;if(s===e.Messages.MarketDataIncrementalRefresh||s===e.Messages.MarketDataSnapshotFullRefresh){let r=o.getField(e.Fields.Symbol),a=o.getField(e.Fields.MDEntryPx),c=o.getField(e.Fields.MDEntryTime)?.value||Date.now();if(r?.value&&a?.value){let i=String(r.value),d=Number(a.value),m=this.marketDataPrices.get(i)||[];m.push({timestamp:Number(c),price:d}),m.length>this.MAX_PRICE_HISTORY&&m.shift(),this.marketDataPrices.set(i,m),this.parser?.logger.log({level:"info",message:`MCP Server added ${r}: ${d}`}),this.server.notification({method:"priceUpdate",params:{symbol:i,price:d,timestamp:Number(c)}})}}if(s===e.Messages.MarketDataSnapshotFullRefresh){let r=o.getField(e.Fields.MDReqID);r&&(t=String(r.value))}else if(s===e.Messages.ExecutionReport){let r=o.getField(e.Fields.ClOrdID);r&&(t=String(r.value))}else if(s===e.Messages.Reject){let r=o.getField(e.Fields.RefSeqNum);r&&(t=String(r.value))}if(t){let r=this.pendingRequests.get(t);r&&(r(o),this.pendingRequests.delete(t))}}}),this.addWorkflows(),await this.server.connect(this.transport),this.onReady&&this.onReady()}addWorkflows(){this.parser&&this.server&&(this.server.setRequestHandler(l.z.object({method:l.z.literal("resources/list")}),async(p,o)=>({resources:[{name:"greeting",description:"A simple greeting resource",uri:"greeting-resource"}]})),this.server.setRequestHandler(l.z.object({method:l.z.literal("resources/templates/list")}),async(p,o)=>({resourceTemplates:[{name:"stockGraph",description:"Generates a price chart for a given symbol",uriTemplate:"stockGraph/{symbol}",parameters:{type:"object",properties:{symbol:{type:"string"}},required:["symbol"]}},{name:"stockPriceHistory",description:"Returns price history for a given symbol",uriTemplate:"stockPriceHistory/{symbol}",parameters:{type:"object",properties:{symbol:{type:"string"}},required:["symbol"]}}]})),this.server.setRequestHandler(l.z.object({method:l.z.literal("tools/list")}),async(p,o)=>({tools:[{name:"parse",description:"Parses a FIX message and describes it in plain language",inputSchema:{type:"object",properties:{fixString:{type:"string"}},required:["fixString"]}},{name:"parseToJSON",description:"Parses a FIX message into JSON",inputSchema:{type:"object",properties:{fixString:{type:"string"}},required:["fixString"]}},{name:"verifyOrder",description:"Verifies order parameters before execution",inputSchema:{type:"object",properties:{clOrdID:{type:"string"},handlInst:{type:"string",enum:["1","2","3"]},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"]},side:{type:"string",enum:["1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H"]},symbol:{type:"string"},timeInForce:{type:"string",enum:["0","1","2","3","4","5","6","7","8","9","A","B","C"]}},required:["clOrdID","handlInst","quantity","price","ordType","side","symbol","timeInForce"]}},{name:"executeOrder",description:"Executes a verified order",inputSchema:{type:"object",properties:{clOrdID:{type:"string"},handlInst:{type:"string",enum:["1","2","3"]},quantity:{type:"string"},price:{type:"string"},ordType:{type:"string"},side:{type:"string"},symbol:{type:"string"},timeInForce:{type:"string"}},required:["clOrdID","handlInst","quantity","price","ordType","side","symbol","timeInForce"]}},{name:"marketDataRequest",description:"Requests market data for specified symbols",inputSchema:{type:"object",properties:{mdUpdateType:{type:"string",enum:["0","1"]},symbols:{type:"array",items:{type:"string"}},mdReqID:{type:"string"},subscriptionRequestType:{type:"string",enum:["0","1","2"]},mdEntryTypes:{type:"array",items:{type:"string"}}},required:["mdUpdateType","symbols","mdReqID","subscriptionRequestType","mdEntryTypes"]}}]})),this.server.setRequestHandler(l.z.object({method:l.z.literal("tools/call"),params:l.z.object({name:l.z.string(),arguments:l.z.any(),_meta:l.z.object({progressToken:l.z.number()}).optional()})}),async(p,o)=>{let{name:s,arguments:t}=p.params;switch(s){case"parse":try{let r=this.parser?.parse(t.fixString);return!r||r.length===0?{contents:[{type:"text",text:"Error: Failed to parse FIX string",uri:"parse"}],isError:!0}:{contents:[{type:"text",text:`${r[0].description}
|
|
3
|
+
${r[0].messageTypeDescription}`,uri:"parse"}]}}catch(r){return{contents:[{type:"text",text:`Error: ${r instanceof Error?r.message:"Failed to parse FIX string"}`,uri:"parse"}],isError:!0}}case"parseToJSON":try{let r=this.parser?.parse(t.fixString);return!r||r.length===0?{contents:[{type:"text",text:"Error: Failed to parse FIX string",uri:"parseToJSON"}],isError:!0}:{contents:[{type:"text",text:`${r[0].toFIXJSON()}`,uri:"parseToJSON"}]}}catch(r){return{contents:[{type:"text",text:`Error: ${r instanceof Error?r.message:"Failed to parse FIX string"}`,uri:"parseToJSON"}],isError:!0}}case"verifyOrder":try{this.verifiedOrders.set(t.clOrdID,{clOrdID:t.clOrdID,handlInst:t.handlInst,quantity:Number.parseFloat(t.quantity),price:Number.parseFloat(t.price),ordType:t.ordType,side:t.side,symbol:t.symbol,timeInForce:t.timeInForce});let r={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"},a={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"},c={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"},i={1:"AutomatedExecutionNoIntervention",2:"AutomatedExecutionInterventionOK",3:"ManualOrder"};return{contents:[{type:"text",text:`VERIFICATION: All parameters valid. Ready to proceed with order execution.
|
|
4
|
+
|
|
6
5
|
Parameters verified:
|
|
7
|
-
- ClOrdID: ${
|
|
8
|
-
- HandlInst: ${
|
|
9
|
-
- Quantity: ${
|
|
10
|
-
- Price: ${
|
|
11
|
-
- OrdType: ${
|
|
12
|
-
- Side: ${
|
|
13
|
-
- Symbol: ${
|
|
14
|
-
- TimeInForce: ${
|
|
6
|
+
- ClOrdID: ${t.clOrdID}
|
|
7
|
+
- HandlInst: ${t.handlInst} (${i[t.handlInst]})
|
|
8
|
+
- Quantity: ${t.quantity}
|
|
9
|
+
- Price: ${t.price}
|
|
10
|
+
- OrdType: ${t.ordType} (${r[t.ordType]})
|
|
11
|
+
- Side: ${t.side} (${a[t.side]})
|
|
12
|
+
- Symbol: ${t.symbol}
|
|
13
|
+
- TimeInForce: ${t.timeInForce} (${c[t.timeInForce]})
|
|
15
14
|
|
|
16
|
-
To execute this order, call the executeOrder tool with these exact same parameters
|
|
17
|
-
|
|
15
|
+
To execute this order, call the executeOrder tool with these exact same parameters.`,uri:"verifyOrder"}]}}catch(r){return{contents:[{type:"text",text:`Error: ${r instanceof Error?r.message:"Failed to verify order parameters"}`,uri:"verifyOrder"}],isError:!0}}case"executeOrder":try{let r=this.verifiedOrders.get(t.clOrdID);if(!r)return{contents:[{type:"text",text:`Error: Order ${t.clOrdID} has not been verified. Please call verifyOrder first.`,uri:"executeOrder"}],isError:!0};if(r.handlInst!==t.handlInst||r.quantity!==Number.parseFloat(t.quantity)||r.price!==Number.parseFloat(t.price)||r.ordType!==t.ordType||r.side!==t.side||r.symbol!==t.symbol||r.timeInForce!==t.timeInForce)return{contents:[{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 a=new Promise(d=>{this.pendingRequests.set(t.clOrdID,d)}),c=this.parser?.createMessage(new e.Field(e.Fields.MsgType,e.Messages.NewOrderSingle),new e.Field(e.Fields.MsgSeqNum,this.parser?.getNextTargetMsgSeqNum()),new e.Field(e.Fields.SenderCompID,this.parser?.sender),new e.Field(e.Fields.TargetCompID,this.parser?.target),new e.Field(e.Fields.SendingTime,this.parser?.getTimestamp()),new e.Field(e.Fields.ClOrdID,t.clOrdID),new e.Field(e.Fields.Side,t.side),new e.Field(e.Fields.Symbol,t.symbol),new e.Field(e.Fields.OrderQty,Number.parseFloat(t.quantity)),new e.Field(e.Fields.Price,Number.parseFloat(t.price)),new e.Field(e.Fields.OrdType,t.ordType),new e.Field(e.Fields.HandlInst,t.handlInst),new e.Field(e.Fields.TimeInForce,t.timeInForce),new e.Field(e.Fields.TransactTime,this.parser?.getTimestamp()));if(!this.parser?.connected)return{contents:[{type:"text",text:"Error: Not connected. Ignoring message.",uri:"executeOrder"}],isError:!0};this.parser?.send(c);let i=await a;return this.verifiedOrders.delete(t.clOrdID),{contents:[{type:"text",text:i.messageType===e.Messages.Reject?`Reject message for order ${t.clOrdID}: ${JSON.stringify(i.toFIXJSON())}`:`Execution Report for order ${t.clOrdID}: ${JSON.stringify(i.toFIXJSON())}`,uri:"executeOrder"}]}}catch(r){return{contents:[{type:"text",text:`Error: ${r instanceof Error?r.message:"Failed to execute order"}`,uri:"executeOrder"}],isError:!0}}case"marketDataRequest":try{let r=new Promise(d=>{this.pendingRequests.set(t.mdReqID,d)}),a=[new e.Field(e.Fields.MsgType,e.Messages.MarketDataRequest),new e.Field(e.Fields.SenderCompID,this.parser?.sender),new e.Field(e.Fields.MsgSeqNum,this.parser?.getNextTargetMsgSeqNum()),new e.Field(e.Fields.TargetCompID,this.parser?.target),new e.Field(e.Fields.SendingTime,this.parser?.getTimestamp()),new e.Field(e.Fields.MDReqID,t.mdReqID),new e.Field(e.Fields.SubscriptionRequestType,t.subscriptionRequestType),new e.Field(e.Fields.MarketDepth,0),new e.Field(e.Fields.MDUpdateType,t.mdUpdateType)];a.push(new e.Field(e.Fields.NoRelatedSym,t.symbols.length)),t.symbols.forEach(d=>{a.push(new e.Field(e.Fields.Symbol,d))}),a.push(new e.Field(e.Fields.NoMDEntryTypes,t.mdEntryTypes.length)),t.mdEntryTypes.forEach(d=>{a.push(new e.Field(e.Fields.MDEntryType,d))});let c=this.parser?.createMessage(...a);if(!this.parser?.connected)return{contents:[{type:"text",text:"Error: Not connected. Ignoring message.",uri:"marketDataRequest"}],isError:!0};this.parser?.send(c);let i=await r;return{contents:[{type:"text",text:`Market data for ${t.symbols.join(", ")}: ${JSON.stringify(i.toFIXJSON())}`,uri:"marketDataRequest"}]}}catch(r){return{contents:[{type:"text",text:`Error: ${r instanceof Error?r.message:"Failed to request market data"}`,uri:"marketDataRequest"}],isError:!0}}default:return{contents:[{type:"text",text:`Tool not found: ${s}`,uri:s}],isError:!0}}}),this.server.setRequestHandler(l.z.object({method:l.z.literal("resources/read"),params:l.z.object({uri:l.z.string()})}),async(p,o)=>{let{uri:s}=p.params;switch(s){case"greeting-resource":return{contents:[{type:"text",text:"Hello, world!",uri:"greeting-resource"}]};case"stockGraph":return{contents:[{type:"text",text:"This resource requires a symbol parameter. Please use the stockGraph/{symbol} resource.",uri:"stockGraph"}]};case"stockPriceHistory":return{contents:[{type:"text",text:"This resource requires a symbol parameter. Please use the stockPriceHistory/{symbol} resource.",uri:"stockPriceHistory"}]};default:if(s.startsWith("stockGraph/")){let t=s.split("/")[1],r=this.marketDataPrices.get(t)||[];if(r.length===0)return{contents:[{type:"text",text:`No price data available for ${t}`,uri:s}]};let a=600,c=300,i=40,d=(a-2*i)/(r.length-1),m=Math.min(...r.map(u=>u.price)),f=Math.max(...r.map(u=>u.price)),x=(c-2*i)/(f-m),O=r.map((u,y)=>{let g=i+y*d,h=c-i-(u.price-m)*x;return`${g},${h}`}).join(" L ");return{contents:[{type:"text",text:`<?xml version="1.0" encoding="UTF-8"?>
|
|
16
|
+
<svg width="${a}" height="${c}" xmlns="http://www.w3.org/2000/svg">
|
|
17
|
+
<!-- Background -->
|
|
18
|
+
<rect width="100%" height="100%" fill="#f8f9fa"/>
|
|
19
|
+
|
|
20
|
+
<!-- Grid lines -->
|
|
21
|
+
<g stroke="#e9ecef" stroke-width="1">
|
|
22
|
+
${Array.from({length:5},(u,y)=>{let g=i+(c-2*i)*y/4;return`<line x1="${i}" y1="${g}" x2="${a-i}" y2="${g}"/>`}).join(`
|
|
23
|
+
`)}
|
|
24
|
+
</g>
|
|
25
|
+
|
|
26
|
+
<!-- Price line -->
|
|
27
|
+
<path d="M ${O}"
|
|
28
|
+
fill="none"
|
|
29
|
+
stroke="#007bff"
|
|
30
|
+
stroke-width="2"/>
|
|
31
|
+
|
|
32
|
+
<!-- Data points -->
|
|
33
|
+
${r.map((u,y)=>{let g=i+y*d,h=c-i-(u.price-m)*x;return`<circle cx="${g}" cy="${h}" r="3" fill="#007bff"/>`}).join(`
|
|
34
|
+
`)}
|
|
35
|
+
|
|
36
|
+
<!-- Labels -->
|
|
37
|
+
<g font-family="Arial" font-size="12" fill="#495057">
|
|
38
|
+
${Array.from({length:5},(u,y)=>{let g=i+(a-2*i)*y/4,h=Math.floor((r.length-1)*y/4),F=new Date(r[h].timestamp).toLocaleTimeString();return`<text x="${g+i}" y="${c-i+20}" text-anchor="middle">${F}</text>`}).join(`
|
|
39
|
+
`)}
|
|
40
|
+
${Array.from({length:5},(u,y)=>{let g=i+(c-2*i)*y/4,h=f-(f-m)*y/4;return`<text x="${i-5}" y="${g+4}" text-anchor="end">$${h.toFixed(2)}</text>`}).join(`
|
|
41
|
+
`)}
|
|
42
|
+
</g>
|
|
43
|
+
|
|
44
|
+
<!-- Title -->
|
|
45
|
+
<text x="${a/2}" y="${i/2}"
|
|
46
|
+
font-family="Arial" font-size="16" font-weight="bold"
|
|
47
|
+
text-anchor="middle" fill="#212529">
|
|
48
|
+
${t} - Price Chart (${r.length} points)
|
|
49
|
+
</text>
|
|
50
|
+
</svg>`,uri:s}]}}if(s.startsWith("stockPriceHistory/")){let t=s.split("/")[1],r=this.marketDataPrices.get(t)||[];return r.length===0?{contents:[{type:"text",text:`No price data available for ${t}`,uri:s}]}:{contents:[{type:"text",text:JSON.stringify({symbol:t,count:r.length,prices:r.map(a=>({timestamp:new Date(a.timestamp).toISOString(),price:a.price}))},null,2),uri:s}]}}return{contents:[{type:"text",text:`Resource not found: ${s}`,uri:s}],isError:!0}}}),process.on("SIGINT",async()=>{await this.server.close(),process.exit(0)}))}};var R=async()=>{await n.LicenseManager.setLicenseKey(process.env.FIXPARSER_LICENSE_KEY);let p=process.env.FIXPARSER_SENDER||"SENDER",o=process.env.FIXPARSER_TARGET||"TARGET",s=new n.FIXParser({logging:!0,logOptions:{level:"info",format:"jsonrpc",transport:new I({format:"jsonrpc"})},plugins:[new b({port:3099,onReady:()=>{}})]}),t=()=>{let a=s.createMessage(new n.Field(n.Fields.MsgType,n.Messages.Logon),new n.Field(n.Fields.MsgSeqNum,s.getNextTargetMsgSeqNum()),new n.Field(n.Fields.SenderCompID,p),new n.Field(n.Fields.SendingTime,s.getTimestamp()),new n.Field(n.Fields.TargetCompID,o),new n.Field(n.Fields.ResetSeqNumFlag,n.ResetSeqNumFlag.Yes),new n.Field(n.Fields.EncryptMethod,n.EncryptMethod.None),new n.Field(n.Fields.HeartBtInt,10));s.send(a)},r={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:p,target:o,fixVersion:"FIX.4.4",onOpen:()=>{s.logger.log({level:"info",message:"FIXParser logging in..."}),t()},onClose:()=>{s.logger.log({level:"info",message:"FIXParser disconnected. Reconnecting in 1 second..."}),setTimeout(()=>{s.connect(r)},1e3)}};s.connect(r)};R().catch(p=>console.error("Error initializing server:",p));
|
|
18
51
|
//# sourceMappingURL=example_mcp_local.js.map
|