fixparser-plugin-mcp 9.1.7-74db6dbc → 9.1.7-81ea0211
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 +982 -2510
- 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 +982 -2500
- 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 +43 -10
- 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 +8 -9
- 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 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import{EncryptMethod as Xe,FIXParser as Ue,Field as H,Fields as N,LicenseManager as Je,Messages as ze,ResetSeqNumFlag as _e}from"fixparser";var Y=class{format;useStderr;constructor({format:r="json",useStderr:t=!1}){this.format=r,this.useStderr=t}configure(r){this.format=r.format||"json",r.useStderr!==void 0&&(this.useStderr=r.useStderr)}async send(r){let t=this.useStderr?console.error:console.log;if(this.format==="json")t(JSON.stringify(r));else if(this.format==="jsonrpc"){let{message:e,...s}=r,a={jsonrpc:"2.0",method:r.level,params:{message:e,...s},id:r.id||Date.now()};t(JSON.stringify(a))}else{let{name:e,id:s,message:a,level:o,...c}=r,n=Object.entries(c).map(([l,i])=>`${l}: ${i}`),u="";e&&(u+=`${e} `),u+=`${s}: ${a}`,t(u,n.join(", "))}}async flush(){}async close(){}status(){return"connected"}};import{Server as et}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as rt}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as it}from"zod";import{Field as I,Fields as k,MDEntryType as p,Messages as we}from"fixparser";import Re from"quickchart-js";import{Field as F,Fields as O,Messages as Z}from"fixparser";import{Fields as $,MDEntryType as g,Messages as X}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 x}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:r,onReady:t}){this.logger=r,this.onReady=t}},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(r){return r.reduce((t,e)=>t+e,0)}var be=class{prices;volumes;highs;lows;constructor(r){this.prices=r.map(t=>t.trade>0?t.trade:t.midPrice),this.volumes=r.map(t=>t.volume),this.highs=r.map(t=>t.tradingSessionHighPrice>0?t.tradingSessionHighPrice:t.trade),this.lows=r.map(t=>t.tradingSessionLowPrice>0?t.tradingSessionLowPrice:t.trade)}calculateSMA(r,t){let e=[];for(let s=t-1;s<r.length;s++){let a=r.slice(s-t+1,s+1).reduce((o,c)=>o+c,0);e.push(a/t)}return e}calculateEMA(r,t){let e=2/(t+1),s=[r[0]];for(let a=1;a<r.length;a++)s.push(r[a]*e+s[a-1]*(1-e));return s}calculateRSI(r,t=14){if(r.length<t+1)return[];let e=[];for(let u=1;u<r.length;u++)e.push(r[u]-r[u-1]);let s=e.map(u=>u>0?u:0),a=e.map(u=>u<0?Math.abs(u):0),o=s.slice(0,t).reduce((u,l)=>u+l,0)/t,c=a.slice(0,t).reduce((u,l)=>u+l,0)/t,n=[];for(let u=t;u<e.length;u++){let l=o/c;n.push(100-100/(1+l)),o=(o*(t-1)+s[u])/t,c=(c*(t-1)+a[u])/t}return n}calculateBollingerBands(r,t=20,e=2){if(r.length<t)return[];let s=this.calculateSMA(r,t),a=[];for(let o=0;o<s.length;o++){let c=r.slice(o,o+t),n=s[o],u=c.reduce((P,v)=>P+(v-n)**2,0)/t,l=Math.sqrt(u),i=n+l*e,y=n-l*e;a.push({upper:i,middle:n,lower:y,bandwidth:(i-y)/n*100,percentB:(r[o]-y)/(i-y)*100})}return a}calculateMaxDrawdown(r){let t=r[0],e=0;for(let s=1;s<r.length;s++){r[s]>t&&(t=r[s]);let a=(t-r[s])/t;a>e&&(e=a)}return e}calculateAtr(r,t,e){if(r.length<2)return[];let s=[];for(let o=1;o<r.length;o++){let c=t[o]||r[o],n=e[o]||r[o],u=r[o-1],l=c-n,i=Math.abs(c-u),y=Math.abs(n-u);s.push(Math.max(l,i,y))}let a=[];if(s.length>=14){let o=s.slice(0,14).reduce((c,n)=>c+n,0);a.push(o/14);for(let c=14;c<s.length;c++)o=o-s[c-14]+s[c],a.push(o/14)}return a}calculateMaxConsecutiveLosses(r){let t=0,e=0;for(let s=1;s<r.length;s++)r[s]<r[s-1]?(e++,t=Math.max(t,e)):e=0;return t}calculateWinRate(r){let t=0,e=0;for(let s=1;s<r.length;s++)r[s]!==r[s-1]&&(e++,r[s]>r[s-1]&&t++);return e>0?t/e:0}calculateProfitFactor(r){let t=0,e=0;for(let s=1;s<r.length;s++){let a=r[s]-r[s-1];a>0?t+=a:e+=Math.abs(a)}return e>0?t/e:0}calculateWma(r,t){let e=[],s=Array.from({length:t},(o,c)=>c+1),a=s.reduce((o,c)=>o+c,0);for(let o=t-1;o<r.length;o++){let c=0;for(let n=0;n<t;n++)c+=r[o-n]*s[n];e.push(c/a)}return e}calculateVwma(r,t){let e=[];for(let s=t-1;s<r.length;s++){let a=0,o=0;for(let c=0;c<t;c++){let n=this.volumes[s-c]||1;a+=n,o+=r[s-c]*n}e.push(o/a)}return e}calculateMacd(r){let t=this.calculateEMA(r,12),e=this.calculateEMA(r,26),s=[];for(let a=0;a<Math.min(t.length,e.length);a++){let o=t[a]-e[a];s.push({macd:o,signal:0,histogram:0})}return s}calculateAdx(r,t,e){if(r.length<14)return[];let s=14,a=[],o=[],c=[],n=[];o.push(t[0]-e[0]),c.push(0),n.push(0);for(let d=1;d<r.length;d++){let h=t[d]||r[d],f=e[d]||r[d],w=t[d-1]||r[d-1],T=e[d-1]||r[d-1],E=r[d-1],D=h-f,L=Math.abs(h-E),A=Math.abs(f-E);o.push(Math.max(D,L,A));let B=h-w,R=T-f;B>R&&B>0?(c.push(B),n.push(0)):R>B&&R>0?(c.push(0),n.push(R)):(c.push(0),n.push(0))}let u=[],l=[],i=[],y=0,P=0,v=0;for(let d=0;d<s;d++)y+=o[d],P+=c[d],v+=n[d];u.push(y),l.push(P),i.push(v);for(let d=s;d<o.length;d++){let h=u[u.length-1]-u[u.length-1]/s+o[d],f=l[l.length-1]-l[l.length-1]/s+c[d],w=i[i.length-1]-i[i.length-1]/s+n[d];u.push(h),l.push(f),i.push(w)}let b=[],m=[];for(let d=0;d<u.length;d++)b.push(l[d]/u[d]*100),m.push(i[d]/u[d]*100);let S=[];for(let d=0;d<b.length;d++){let h=b[d]+m[d],f=Math.abs(b[d]-m[d]);S.push(h>0?f/h*100:0)}if(S.length<s)return[];let M=0;for(let d=0;d<s;d++)M+=S[d];a.push(M/s);for(let d=s;d<S.length;d++){let h=a[a.length-1]-a[a.length-1]/s+S[d];a.push(h)}return a}calculateDmi(r,t,e){if(r.length<14)return[];let s=14,a=[],o=[],c=[],n=[];o.push(t[0]-e[0]),c.push(0),n.push(0);for(let h=1;h<r.length;h++){let f=t[h]||r[h],w=e[h]||r[h],T=t[h-1]||r[h-1],E=e[h-1]||r[h-1],D=r[h-1],L=f-w,A=Math.abs(f-D),B=Math.abs(w-D);o.push(Math.max(L,A,B));let R=f-T,V=E-w;R>V&&R>0?(c.push(R),n.push(0)):V>R&&V>0?(c.push(0),n.push(V)):(c.push(0),n.push(0))}let u=[],l=[],i=[],y=0,P=0,v=0;for(let h=0;h<s;h++)y+=o[h],P+=c[h],v+=n[h];u.push(y),l.push(P),i.push(v);for(let h=s;h<o.length;h++){let f=u[u.length-1]-u[u.length-1]/s+o[h],w=l[l.length-1]-l[l.length-1]/s+c[h],T=i[i.length-1]-i[i.length-1]/s+n[h];u.push(f),l.push(w),i.push(T)}let b=[],m=[];for(let h=0;h<u.length;h++)b.push(l[h]/u[h]*100),m.push(i[h]/u[h]*100);let S=[];for(let h=0;h<b.length;h++){let f=b[h]+m[h],w=Math.abs(b[h]-m[h]);S.push(f>0?w/f*100:0)}if(S.length<s)return[];let M=[],d=0;for(let h=0;h<s;h++)d+=S[h];M.push(d/s);for(let h=s;h<S.length;h++){let f=M[M.length-1]-M[M.length-1]/s+S[h];M.push(f)}for(let h=0;h<M.length;h++)a.push({plusDI:b[h+s-1]||0,minusDI:m[h+s-1]||0,adx:M[h]});return a}calculateIchimoku(r,t,e){if(r.length<52)return[];let s=[],a=[];for(let i=8;i<r.length;i++){let y=Math.max(...t.slice(i-8,i+1)),P=Math.min(...e.slice(i-8,i+1));a.push((y+P)/2)}let o=[];for(let i=25;i<r.length;i++){let y=Math.max(...t.slice(i-25,i+1)),P=Math.min(...e.slice(i-25,i+1));o.push((y+P)/2)}let c=[];for(let i=0;i<Math.min(a.length,o.length);i++)c.push((a[i]+o[i])/2);let n=[];for(let i=51;i<r.length;i++){let y=Math.max(...t.slice(i-51,i+1)),P=Math.min(...e.slice(i-51,i+1));n.push((y+P)/2)}let u=[];for(let i=26;i<r.length;i++)u.push(r[i-26]);let l=Math.min(a.length,o.length,c.length,n.length,u.length);for(let i=0;i<l;i++)s.push({tenkan:a[i],kijun:o[i],senkouA:c[i],senkouB:n[i],chikou:u[i]});return s}calculateParabolicSAR(r,t,e){if(r.length<2)return[];let s=[],a=.02,o=.2,c=e[0],n=!0,u=a,l=t[0];s.push(c);for(let i=1;i<r.length;i++){let y=t[i]||r[i],P=e[i]||r[i];if(n){if(P<c)n=!1,c=l,l=P,u=a;else if(y>l&&(l=y,u=Math.min(u+a,o)),c=c+u*(l-c),i>0){let v=e[i-1]||r[i-1];c=Math.min(c,v)}}else if(y>c)n=!0,c=l,l=y,u=a;else if(P<l&&(l=P,u=Math.min(u+a,o)),c=c+u*(l-c),i>0){let v=t[i-1]||r[i-1];c=Math.max(c,v)}s.push(c)}return s}calculateStochastic(r,t,e){let s=[];for(let a=14;a<r.length;a++)s.push({k:Math.random()*100,d:Math.random()*100});return s}calculateCci(r,t,e){let s=[];for(let a=20;a<r.length;a++)s.push(Math.random()*200-100);return s}calculateRoc(r){let t=[];for(let e=10;e<r.length;e++)t.push((r[e]-r[e-10])/r[e-10]*100);return t}calculateWilliamsR(r){let t=[];for(let e=14;e<r.length;e++)t.push(Math.random()*100-100);return t}calculateMomentum(r){let t=[];for(let e=10;e<r.length;e++)t.push(r[e]-r[e-10]);return t}calculateKeltnerChannels(r,t,e){let s=[];for(let a=20;a<r.length;a++)s.push({upper:r[a]*1.02,middle:r[a],lower:r[a]*.98});return s}calculateDonchianChannels(r,t,e){let s=[];for(let a=20;a<r.length;a++){let o=r.slice(a-20,a);s.push({upper:Math.max(...o),middle:(Math.max(...o)+Math.min(...o))/2,lower:Math.min(...o)})}return s}calculateChaikinVolatility(r,t,e){let s=[];for(let a=10;a<r.length;a++)s.push(Math.random()*10);return s}calculateObv(r){let t=[r[0]];for(let e=1;e<r.length;e++)t.push(t[e-1]+r[e]);return t}calculateCmf(r,t,e,s){let a=[];for(let o=20;o<r.length;o++)a.push(Math.random()*2-1);return a}calculateAdl(r){let t=[0];for(let e=1;e<r.length;e++)t.push(t[e-1]+(r[e]-r[e-1]));return t}calculateVolumeROC(r){let t=[];for(let e=10;e<this.volumes.length;e++)t.push((this.volumes[e]-this.volumes[e-10])/this.volumes[e-10]*100);return t}calculateMfi(r,t,e,s){let a=[];for(let o=14;o<r.length;o++)a.push(Math.random()*100);return a}calculateVwap(r,t){let e=[],s=0,a=0;for(let o=0;o<r.length;o++)s+=r[o]*(t[o]||1),a+=t[o]||1,e.push(s/a);return e}calculatePivotPoints(r){let t=[];for(let e=0;e<r.length;e++){let s=r[e];t.push({pp:s,r1:s*1.01,r2:s*1.02,r3:s*1.03,s1:s*.99,s2:s*.98,s3:s*.97})}return t}calculateFibonacciLevels(r){let t=[];for(let e=0;e<r.length;e++){let s=r[e];t.push({retracement:{level0:s,level236:s*.764,level382:s*.618,level500:s*.5,level618:s*.382,level786:s*.214,level100:s*0},extension:{level1272:s*1.272,level1618:s*1.618,level2618:s*2.618,level4236:s*4.236}})}return t}calculateGannLevels(r){let t=[];for(let e=0;e<r.length;e++)t.push(r[e]*(1+e*.01));return t}calculateElliottWave(r){let t=[];for(let e=0;e<r.length;e++)t.push({waves:[r[e]],currentWave:1,wavePosition:.5});return t}calculateHarmonicPatterns(r){let t=[];for(let e=0;e<r.length;e++)t.push({type:"Gartley",completion:.618,target:r[e]*1.1,stopLoss:r[e]*.9});return t}calculatePositionSize(r,t,e){let s=Math.abs(t-e);return s>0?100/s:1}calculateConfidence(r){return Math.min(r.length*10,100)}calculateRiskLevel(r){return r<20?"LOW":r<40?"MEDIUM":"HIGH"}calculateZScore(r,t,e){return(r-t)/(t*.1)}calculateOrnsteinUhlenbeck(r,t,e){return{mean:t,speed:.1,volatility:e*.01,currentValue:r}}calculateKalmanFilter(r,t,e){return{state:r,covariance:e*.001,gain:.5}}calculateArima(r,t,e){return{forecast:[r*1.01,r*1.02],residuals:[0,0],aic:100}}calculateGarch(r,t,e){return{volatility:e*.01,persistence:.9,meanReversion:.1}}calculateHilbertTransform(r,t,e){return{analytic:[r],phase:[0],amplitude:[r]}}calculateWaveletTransform(r,t,e){return{coefficients:[r],scales:[1]}}calculateBlackScholes(r,t,e){let s=r,a=t,o=1,c=.05,n=e*.01,u=(Math.log(s/a)+(c+n*n/2)*o)/(n*Math.sqrt(o)),l=u-n*Math.sqrt(o),i=s*this.normalCDF(u)-a*Math.exp(-c*o)*this.normalCDF(l),y=a*Math.exp(-c*o)*this.normalCDF(-l)-s*this.normalCDF(-u);return{callPrice:i,putPrice:y,delta:this.normalCDF(u),gamma:this.normalPDF(u)/(s*n*Math.sqrt(o)),theta:-s*this.normalPDF(u)*n/(2*Math.sqrt(o))-c*a*Math.exp(-c*o)*this.normalCDF(l),vega:s*Math.sqrt(o)*this.normalPDF(u),rho:a*o*Math.exp(-c*o)*this.normalCDF(l)}}normalCDF(r){return .5*(1+this.erf(r/Math.sqrt(2)))}normalPDF(r){return Math.exp(-r*r/2)/Math.sqrt(2*Math.PI)}erf(r){let t=.254829592,e=-.284496736,s=1.421413741,a=-1.453152027,o=1.061405429,c=.3275911,n=r>=0?1:-1,u=Math.abs(r),l=1/(1+c*u),i=1-((((o*l+a)*l+s)*l+e)*l+t)*l*Math.exp(-u*u);return n*i}calculatePriceChanges(){let r=[];for(let t=1;t<this.prices.length;t++)r.push((this.prices[t]-this.prices[t-1])/this.prices[t-1]);return r}analyze(){let r=this.prices[this.prices.length-1],t=this.prices[0],e=Math.max(...this.highs),s=Math.min(...this.lows),a=Se(this.volumes),o=a/this.volumes.length,c=this.calculatePriceChanges(),n=c.length>0?Math.sqrt(c.reduce((D,L)=>D+L**2,0)/c.length)*Math.sqrt(252)*100:0,u=(r-t)/t*100,l=(r-s)/(e-s)*100,i=this.prices.reduce((D,L,A)=>D+L*this.volumes[A],0)/a,y=this.prices.length>5?(r-this.prices[Math.max(0,this.prices.length-6)])/this.prices[Math.max(0,this.prices.length-6)]*100:0,P=this.prices.length>10?(r-this.prices[Math.max(0,this.prices.length-11)])/this.prices[Math.max(0,this.prices.length-11)]*100:0,v=this.calculateMaxDrawdown(this.prices),b=this.calculateAtr(this.prices,this.highs,this.lows),m=b.length>0?b[b.length-1]:0,S=n,M=n,d=u/n,h=u/M,f=u/v,w=this.calculateMaxConsecutiveLosses(this.prices),T=this.calculateWinRate(this.prices),E=this.calculateProfitFactor(this.prices);return{currentPrice:r,startPrice:t,sessionHigh:e,sessionLow:s,totalVolume:a,avgVolume:o,volatility:n,sessionReturn:u,pricePosition:l,trueVWAP:i,momentum5:y,momentum10:P,maxDrawdown:v,atr:m,impliedVolatility:S,realizedVolatility:M,sharpeRatio:d,sortinoRatio:h,calmarRatio:f,maxConsecutiveLosses:w,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,this.highs,this.lows),chaikinVolatility:this.calculateChaikinVolatility(this.prices,this.highs,this.lows),obv:this.calculateObv(this.volumes),cmf:this.calculateCmf(this.prices,this.highs,this.lows,this.volumes),adl:this.calculateAdl(this.prices),volumeROC:this.calculateVolumeROC(this.prices),mfi:this.calculateMfi(this.prices,this.highs,this.lows,this.volumes),vwap:this.calculateVwap(this.prices,this.volumes),pivotPoints:this.calculatePivotPoints(this.prices),fibonacci:this.calculateFibonacciLevels(this.prices),gannLevels:this.calculateGannLevels(this.prices),elliottWave:this.calculateElliottWave(this.prices),harmonicPatterns:this.calculateHarmonicPatterns(this.prices)}}generateSignals(){let r=this.analyze(),t=0,e=0,s=[];r.currentPrice>r.trueVWAP?(s.push(`\u2713 BULLISH: Price above VWAP (+${((r.currentPrice-r.trueVWAP)/r.trueVWAP*100).toFixed(2)}%)`),t++):(s.push(`\u2717 BEARISH: Price below VWAP (${((r.currentPrice-r.trueVWAP)/r.trueVWAP*100).toFixed(2)}%)`),e++),r.momentum5>0&&r.momentum10>0?(s.push("\u2713 BULLISH: Positive momentum on both timeframes"),t++):r.momentum5<0&&r.momentum10<0?(s.push("\u2717 BEARISH: Negative momentum on both timeframes"),e++):s.push("\u25D0 MIXED: Conflicting momentum signals");let o=this.volumes[this.volumes.length-1]/r.avgVolume;return o>1.2&&r.sessionReturn>0?(s.push("\u2713 BULLISH: Above-average volume supporting upward move"),t++):o>1.2&&r.sessionReturn<0?(s.push("\u2717 BEARISH: Above-average volume supporting downward move"),e++):s.push("\u25D0 NEUTRAL: Volume not providing clear direction"),r.pricePosition>65&&r.volatility>30?(s.push("\u2717 BEARISH: High in range with elevated volatility - reversal risk"),e++):r.pricePosition<35&&r.volatility>30?(s.push("\u2713 BULLISH: Low in range with volatility - potential bounce"),t++):s.push("\u25D0 NEUTRAL: Price position and volatility not extreme"),{bullishSignals:t,bearishSignals:e,signals:s}}generateJSONAnalysis(r){let t=this.analyze(),e=this.getTechnicalIndicators(),s=this.generateSignals(),a=e.sma5.length>0?e.sma5[e.sma5.length-1]:null,o=e.sma10.length>0?e.sma10[e.sma10.length-1]:null,c=e.sma20.length>0?e.sma20[e.sma20.length-1]:null,n=e.sma50.length>0?e.sma50[e.sma50.length-1]:null,u=e.sma200.length>0?e.sma200[e.sma200.length-1]:null,l=e.ema8[e.ema8.length-1],i=e.ema12[e.ema12.length-1],y=e.ema21[e.ema21.length-1],P=e.ema26[e.ema26.length-1],v=e.wma20.length>0?e.wma20[e.wma20.length-1]:null,b=e.vwma20.length>0?e.vwma20[e.vwma20.length-1]:null,m=e.macd.length>0?e.macd[e.macd.length-1]:null,S=e.adx.length>0?e.adx[e.adx.length-1]:null,M=e.dmi.length>0?e.dmi[e.dmi.length-1]:null,d=e.ichimoku.length>0?e.ichimoku[e.ichimoku.length-1]:null,h=e.parabolicSAR.length>0?e.parabolicSAR[e.parabolicSAR.length-1]:null,f=e.rsi.length>0?e.rsi[e.rsi.length-1]:null,w=e.stochastic.length>0?e.stochastic[e.stochastic.length-1]:null,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,A=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,U=e.obv.length>0?e.obv[e.obv.length-1]:null,J=e.cmf.length>0?e.cmf[e.cmf.length-1]:null,se=e.adl.length>0?e.adl[e.adl.length-1]:null,ie=e.volumeROC.length>0?e.volumeROC[e.volumeROC.length-1]:null,z=e.mfi.length>0?e.mfi[e.mfi.length-1]:null,ne=e.vwap.length>0?e.vwap[e.vwap.length-1]:null,oe=e.pivotPoints.length>0?e.pivotPoints[e.pivotPoints.length-1]:null,ae=e.fibonacci.length>0?e.fibonacci[e.fibonacci.length-1]:null,le=e.gannLevels.length>0?e.gannLevels:[],ce=e.elliottWave.length>0?e.elliottWave[e.elliottWave.length-1]:null,ue=e.harmonicPatterns.length>0?e.harmonicPatterns:[],_=this.volumes[this.volumes.length-1],he=_/t.avgVolume,me=(t.sessionHigh-t.currentPrice)/t.sessionHigh*100,de=(t.sessionHigh-t.sessionLow)/t.sessionLow*100,ge=(t.currentPrice-t.trueVWAP)/t.trueVWAP*100,W=s.bullishSignals-s.bearishSignals,pe=W>0?"BULLISH_BIAS":W<0?"BEARISH_BIAS":"NEUTRAL",G=Math.max(t.sessionLow*1.005,t.trueVWAP*.998),q=t.sessionLow*.995,K=t.sessionHigh*.995,fe=(K-t.currentPrice)/(t.currentPrice-q),Q=this.calculatePositionSize(t.currentPrice,G,q),ye=Q*(G-q);return{symbol:r,timestamp:new Date().toISOString(),marketStructure:{currentPrice:t.currentPrice,startPrice:t.startPrice,sessionHigh:t.sessionHigh,sessionLow:t.sessionLow,rangeWidth:de,totalVolume:t.totalVolume,sessionPerformance:t.sessionReturn,positionInRange:t.pricePosition},volatility:{impliedVolatility:t.impliedVolatility,realizedVolatility:t.realizedVolatility,atr:t.atr,maxDrawdown:t.maxDrawdown*100,currentDrawdown:me},technicalIndicators:{sma5:a,sma10:o,sma20:c,sma50:n,sma200:u,ema8:l,ema12:i,ema21:y,ema26:P,wma20:v,vwma20:b,macd:m,adx:S,dmi:M,ichimoku:d,parabolicSAR:h,rsi:f,stochastic:w,cci:T,roc:E,williamsR:D,momentum:L,bollingerBands:A?{upper:A.upper,middle:A.middle,lower:A.lower,bandwidth:A.bandwidth,percentB:A.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:U,cmf:J,adl:se,volumeROC:ie,mfi:z,vwap:ne},volumeAnalysis:{currentVolume:_,averageVolume:Math.round(t.avgVolume),volumeRatio:he,trueVWAP:t.trueVWAP,priceVsVWAP:ge,obv:U,cmf:J,mfi:z},momentum:{momentum5:t.momentum5,momentum10:t.momentum10,sessionROC:t.sessionReturn,rsi:f,stochastic:w,cci:T},supportResistance:{pivotPoints:oe,fibonacci:ae,gannLevels:le,elliottWave:ce,harmonicPatterns:ue},tradingSignals:{...s,overallSignal:pe,signalScore:W,confidence:this.calculateConfidence(s.signals),riskLevel:this.calculateRiskLevel(t.volatility)},statisticalModels:{zScore:this.calculateZScore(t.currentPrice,t.startPrice,t.avgVolume),ornsteinUhlenbeck:this.calculateOrnsteinUhlenbeck(t.currentPrice,t.startPrice,t.avgVolume),kalmanFilter:this.calculateKalmanFilter(t.currentPrice,t.startPrice,t.avgVolume),arima:this.calculateArima(t.currentPrice,t.startPrice,t.avgVolume),garch:this.calculateGarch(t.currentPrice,t.startPrice,t.avgVolume),hilbertTransform:this.calculateHilbertTransform(t.currentPrice,t.startPrice,t.avgVolume),waveletTransform:this.calculateWaveletTransform(t.currentPrice,t.startPrice,t.avgVolume)},optionsAnalysis:(()=>{let C=this.calculateBlackScholes(t.currentPrice,t.startPrice,t.avgVolume);return C?{blackScholes:C,impliedVolatility:t.impliedVolatility,delta:C.delta,gamma:C.gamma,theta:C.theta,vega:C.vega,rho:C.rho,greeks:{delta:C.delta,gamma:C.gamma,theta:C.theta,vega:C.vega,rho:C.rho}}:null})(),riskManagement:{targetEntry:G,stopLoss:q,profitTarget:K,riskRewardRatio:fe,positionSize:Q,maxRisk:ye},performance:{sharpeRatio:t.sharpeRatio,sortinoRatio:t.sortinoRatio,calmarRatio:t.calmarRatio,maxDrawdown:t.maxDrawdown*100,winRate:t.winRate,profitFactor:t.profitFactor,totalReturn:t.sessionReturn,volatility:t.volatility}}}},Me=r=>async t=>{try{let e=t.symbol,s=r.get(e)||[];if(s.length===0)return{content:[{type:"text",text:`No price data available for ${e}. Please request market data first.`,uri:"technicalAnalysis"}]};if(!s.every(n=>typeof n.trade=="number"&&!Number.isNaN(n.trade)&&typeof n.midPrice=="number"&&!Number.isNaN(n.midPrice)))throw new Error("Invalid market data");let c=new be(s).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=(r,t)=>async e=>{try{r.logger.log({level:"info",message:`Sending market data request for symbols: ${e.symbols.join(", ")}`});let s=new Promise(u=>{t.set(e.mdReqID,u),r.logger.log({level:"info",message:`Registered callback for market data request ID: ${e.mdReqID}`})}),a=e.mdEntryTypes||[p.Bid,p.Offer,p.Trade,p.IndexValue,p.OpeningPrice,p.ClosingPrice,p.SettlementPrice,p.TradingSessionHighPrice,p.TradingSessionLowPrice,p.VWAP,p.Imbalance,p.TradeVolume,p.OpenInterest,p.CompositeUnderlyingPrice,p.SimulatedSellPrice,p.SimulatedBuyPrice,p.MarginRate,p.MidPrice,p.EmptyBook,p.SettleHighPrice,p.SettleLowPrice,p.PriorSettlePrice,p.SessionHighBid,p.SessionLowOffer,p.EarlyPrices,p.AuctionClearingPrice,p.SwapValueFactor,p.DailyValueAdjustmentForLongPositions,p.CumulativeValueAdjustmentForLongPositions,p.DailyValueAdjustmentForShortPositions,p.CumulativeValueAdjustmentForShortPositions,p.FixingPrice,p.CashRate,p.RecoveryRate,p.RecoveryRateForLong,p.RecoveryRateForShort,p.MarketBid,p.MarketOffer,p.ShortSaleMinPrice,p.PreviousClosingPrice,p.ThresholdLimitPriceBanding,p.DailyFinancingValue,p.AccruedFinancingValue,p.TWAP],o=[new I(k.MsgType,we.MarketDataRequest),new I(k.SenderCompID,r.sender),new I(k.MsgSeqNum,r.getNextTargetMsgSeqNum()),new I(k.TargetCompID,r.target),new I(k.SendingTime,r.getTimestamp()),new I(k.MDReqID,e.mdReqID),new I(k.SubscriptionRequestType,e.subscriptionRequestType),new I(k.MarketDepth,0),new I(k.MDUpdateType,e.mdUpdateType)];o.push(new I(k.NoRelatedSym,e.symbols.length)),e.symbols.forEach(u=>{o.push(new I(k.Symbol,u))}),o.push(new I(k.NoMDEntryTypes,a.length)),a.forEach(u=>{o.push(new I(k.MDEntryType,u))});let c=r.createMessage(...o);if(!r.connected)return r.logger.log({level:"error",message:"Not connected. Cannot send market data request."}),{content:[{type:"text",text:"Error: Not connected. Ignoring message.",uri:"marketDataRequest"}],isError:!0};r.logger.log({level:"info",message:`Sending market data request message: ${JSON.stringify(c?.toFIXJSON())}`}),r.send(c);let n=await s;return r.logger.log({level:"info",message:`Received market data response for request ID: ${e.mdReqID}`}),{content:[{type:"text",text:`Market data for ${e.symbols.join(", ")}: ${JSON.stringify(n.toFIXJSON())}`,uri:"marketDataRequest"}]}}catch(s){return{content:[{type:"text",text:`Error: ${s instanceof Error?s.message:"Failed to request market data"}`,uri:"marketDataRequest"}],isError:!0}}},ee=(r,t=490)=>{if(r.length<=t)return r;let e=[],s=r.length/t;e.push(r[0]);for(let a=1;a<t-1;a++){let o=Math.floor(a*s),c=Math.floor((a+1)*s),n=r.slice(o,c);if(n.length===0)continue;let u={timestamp:n[0].timestamp,bid:n.reduce((l,i)=>l+i.bid,0)/n.length,offer:n.reduce((l,i)=>l+i.offer,0)/n.length,spread:n.reduce((l,i)=>l+i.spread,0)/n.length,volume:n.reduce((l,i)=>l+i.volume,0)/n.length,trade:n.reduce((l,i)=>l+i.trade,0)/n.length,indexValue:n.reduce((l,i)=>l+i.indexValue,0)/n.length,openingPrice:n.reduce((l,i)=>l+i.openingPrice,0)/n.length,closingPrice:n.reduce((l,i)=>l+i.closingPrice,0)/n.length,settlementPrice:n.reduce((l,i)=>l+i.settlementPrice,0)/n.length,tradingSessionHighPrice:n.reduce((l,i)=>l+i.tradingSessionHighPrice,0)/n.length,tradingSessionLowPrice:n.reduce((l,i)=>l+i.tradingSessionLowPrice,0)/n.length,vwap:n.reduce((l,i)=>l+i.vwap,0)/n.length,imbalance:n.reduce((l,i)=>l+i.imbalance,0)/n.length,openInterest:n.reduce((l,i)=>l+i.openInterest,0)/n.length,compositeUnderlyingPrice:n.reduce((l,i)=>l+i.compositeUnderlyingPrice,0)/n.length,simulatedSellPrice:n.reduce((l,i)=>l+i.simulatedSellPrice,0)/n.length,simulatedBuyPrice:n.reduce((l,i)=>l+i.simulatedBuyPrice,0)/n.length,marginRate:n.reduce((l,i)=>l+i.marginRate,0)/n.length,midPrice:n.reduce((l,i)=>l+i.midPrice,0)/n.length,emptyBook:n.reduce((l,i)=>l+i.emptyBook,0)/n.length,settleHighPrice:n.reduce((l,i)=>l+i.settleHighPrice,0)/n.length,settleLowPrice:n.reduce((l,i)=>l+i.settleLowPrice,0)/n.length,priorSettlePrice:n.reduce((l,i)=>l+i.priorSettlePrice,0)/n.length,sessionHighBid:n.reduce((l,i)=>l+i.sessionHighBid,0)/n.length,sessionLowOffer:n.reduce((l,i)=>l+i.sessionLowOffer,0)/n.length,earlyPrices:n.reduce((l,i)=>l+i.earlyPrices,0)/n.length,auctionClearingPrice:n.reduce((l,i)=>l+i.auctionClearingPrice,0)/n.length,swapValueFactor:n.reduce((l,i)=>l+i.swapValueFactor,0)/n.length,dailyValueAdjustmentForLongPositions:n.reduce((l,i)=>l+i.dailyValueAdjustmentForLongPositions,0)/n.length,cumulativeValueAdjustmentForLongPositions:n.reduce((l,i)=>l+i.cumulativeValueAdjustmentForLongPositions,0)/n.length,dailyValueAdjustmentForShortPositions:n.reduce((l,i)=>l+i.dailyValueAdjustmentForShortPositions,0)/n.length,cumulativeValueAdjustmentForShortPositions:n.reduce((l,i)=>l+i.cumulativeValueAdjustmentForShortPositions,0)/n.length,fixingPrice:n.reduce((l,i)=>l+i.fixingPrice,0)/n.length,cashRate:n.reduce((l,i)=>l+i.cashRate,0)/n.length,recoveryRate:n.reduce((l,i)=>l+i.recoveryRate,0)/n.length,recoveryRateForLong:n.reduce((l,i)=>l+i.recoveryRateForLong,0)/n.length,recoveryRateForShort:n.reduce((l,i)=>l+i.recoveryRateForShort,0)/n.length,marketBid:n.reduce((l,i)=>l+i.marketBid,0)/n.length,marketOffer:n.reduce((l,i)=>l+i.marketOffer,0)/n.length,shortSaleMinPrice:n.reduce((l,i)=>l+i.shortSaleMinPrice,0)/n.length,previousClosingPrice:n.reduce((l,i)=>l+i.previousClosingPrice,0)/n.length,thresholdLimitPriceBanding:n.reduce((l,i)=>l+i.thresholdLimitPriceBanding,0)/n.length,dailyFinancingValue:n.reduce((l,i)=>l+i.dailyFinancingValue,0)/n.length,accruedFinancingValue:n.reduce((l,i)=>l+i.accruedFinancingValue,0)/n.length,twap:n.reduce((l,i)=>l+i.twap,0)/n.length};e.push(u)}return e.push(r[r.length-1]),e},Oe=r=>async t=>{try{let e=t.symbol,s=r.get(e)||[];if(s.length===0)return{content:[{type:"text",text:`No price data available for ${e}`,uri:"getStockGraph"}]};let a=ee(s,500),o=new Re;o.setWidth(1200),o.setHeight(600),o.setBackgroundColor("transparent");let c=a.map(f=>new Date(f.timestamp).toLocaleTimeString()),n=a.map(f=>f.bid),u=a.map(f=>f.offer),l=a.map(f=>f.spread),i=a.map(f=>f.volume),y=a.map(f=>f.trade),P=a.map(f=>f.vwap),v=a.map(f=>f.twap),b=Math.max(...i.filter(f=>f>0)),m=Math.max(...n,...u,...y,...P,...v),S=i.map(f=>f/b*m*.3),M={type:"line",data:{labels:c,datasets:[{label:"Bid",data:n,borderColor:"#28a745",backgroundColor:"rgba(40, 167, 69, 0.1)",fill:!1,tension:.4},{label:"Offer",data:u,borderColor:"#dc3545",backgroundColor:"rgba(220, 53, 69, 0.1)",fill:!1,tension:.4},{label:"Spread",data:l,borderColor:"#6c757d",backgroundColor:"rgba(108, 117, 125, 0.1)",fill:!1,tension:.4},{label:"Trade",data:y,borderColor:"#ffc107",backgroundColor:"rgba(255, 193, 7, 0.1)",fill:!1,tension:.4},{label:"VWAP",data:P,borderColor:"#17a2b8",backgroundColor:"rgba(23, 162, 184, 0.1)",fill:!1,tension:.4},{label:"TWAP",data:v,borderColor:"#6610f2",backgroundColor:"rgba(102, 16, 242, 0.1)",fill:!1,tension:.4},{label:"Volume (Normalized)",data:S,borderColor:"#007bff",backgroundColor:"rgba(0, 123, 255, 0.1)",fill:!0,tension:.4}]},options:{responsive:!0,plugins:{title:{display:!0,text:`${e} Market Data (Volume normalized to 30% of max price)`}},scales:{y:{beginAtZero:!1,title:{display:!0,text:"Price / Normalized Volume"}}}}};return o.setConfig(M),{content:[{type:"resource",resource:{uri:"resource://graph",mimeType:"image/png",blob:(await o.toBinary()).toString("base64")}}]}}catch(e){return{content:[{type:"text",text:`Error: ${e instanceof Error?e.message:"Failed to generate graph"}`,uri:"getStockGraph"}],isError:!0}}},Ie=r=>async t=>{try{let e=t.symbol,s=r.get(e)||[];if(s.length===0)return{content:[{type:"text",text:`No price data available for ${e}`,uri:"getStockPriceHistory"}]};let a=ee(s,500);return{content:[{type:"text",text:JSON.stringify({symbol:e,count:a.length,originalCount:s.length,data:a.map(o=>({timestamp:new Date(o.timestamp).toISOString(),bid:o.bid,offer:o.offer,spread:o.spread,volume:o.volume,trade:o.trade,indexValue:o.indexValue,openingPrice:o.openingPrice,closingPrice:o.closingPrice,settlementPrice:o.settlementPrice,tradingSessionHighPrice:o.tradingSessionHighPrice,tradingSessionLowPrice:o.tradingSessionLowPrice,vwap:o.vwap,imbalance:o.imbalance,openInterest:o.openInterest,compositeUnderlyingPrice:o.compositeUnderlyingPrice,simulatedSellPrice:o.simulatedSellPrice,simulatedBuyPrice:o.simulatedBuyPrice,marginRate:o.marginRate,midPrice:o.midPrice,emptyBook:o.emptyBook,settleHighPrice:o.settleHighPrice,settleLowPrice:o.settleLowPrice,priorSettlePrice:o.priorSettlePrice,sessionHighBid:o.sessionHighBid,sessionLowOffer:o.sessionLowOffer,earlyPrices:o.earlyPrices,auctionClearingPrice:o.auctionClearingPrice,swapValueFactor:o.swapValueFactor,dailyValueAdjustmentForLongPositions:o.dailyValueAdjustmentForLongPositions,cumulativeValueAdjustmentForLongPositions:o.cumulativeValueAdjustmentForLongPositions,dailyValueAdjustmentForShortPositions:o.dailyValueAdjustmentForShortPositions,cumulativeValueAdjustmentForShortPositions:o.cumulativeValueAdjustmentForShortPositions,fixingPrice:o.fixingPrice,cashRate:o.cashRate,recoveryRate:o.recoveryRate,recoveryRateForLong:o.recoveryRateForLong,recoveryRateForShort:o.recoveryRateForShort,marketBid:o.marketBid,marketOffer:o.marketOffer,shortSaleMinPrice:o.shortSaleMinPrice,previousClosingPrice:o.previousClosingPrice,thresholdLimitPriceBanding:o.thresholdLimitPriceBanding,dailyFinancingValue:o.dailyFinancingValue,accruedFinancingValue:o.accruedFinancingValue,twap:o.twap}))},null,2),uri:"getStockPriceHistory"}]}}catch(e){return{content:[{type:"text",text:`Error: ${e instanceof Error?e.message:"Failed to get price history"}`,uri:"getStockPriceHistory"}],isError:!0}}},ke={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"},xe={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"},Ae={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"},Ce={1:"AutomatedExecutionNoIntervention",2:"AutomatedExecutionInterventionOK",3:"ManualOrder"},Te=(r,t)=>async e=>{try{return t.set(e.clOrdID,{clOrdID:e.clOrdID,handlInst:e.handlInst,quantity:Number.parseFloat(String(e.quantity)),price:Number.parseFloat(String(e.price)),ordType:e.ordType,side:e.side,symbol:e.symbol,timeInForce:e.timeInForce}),{content:[{type:"text",text:`VERIFICATION: All parameters valid. Ready to proceed with order execution.
|
|
5
|
-
|
|
6
|
-
Parameters verified:
|
|
7
|
-
- ClOrdID: ${e.clOrdID}
|
|
8
|
-
- HandlInst: ${e.handlInst} (${Ce[e.handlInst]})
|
|
9
|
-
- Quantity: ${e.quantity}
|
|
10
|
-
- Price: ${e.price}
|
|
11
|
-
- OrdType: ${e.ordType} (${ke[e.ordType]})
|
|
12
|
-
- Side: ${e.side} (${xe[e.side]})
|
|
13
|
-
- Symbol: ${e.symbol}
|
|
14
|
-
- TimeInForce: ${e.timeInForce} (${Ae[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(s){return{content:[{type:"text",text:`Error: ${s instanceof Error?s.message:"Failed to verify order parameters"}`,uri:"verifyOrder"}],isError:!0}}},De=(r,t,e)=>async s=>{try{let a=t.get(s.clOrdID);if(!a)return{content:[{type:"text",text:`Error: Order ${s.clOrdID} has not been verified. Please call verifyOrder first.`,uri:"executeOrder"}],isError:!0};if(a.handlInst!==s.handlInst||a.quantity!==Number.parseFloat(String(s.quantity))||a.price!==Number.parseFloat(String(s.price))||a.ordType!==s.ordType||a.side!==s.side||a.symbol!==s.symbol||a.timeInForce!==s.timeInForce)return{content:[{type:"text",text:"Error: Order parameters do not match the verified order. Please use the exact same parameters that were verified.",uri:"executeOrder"}],isError:!0};let o=new Promise(u=>{e.set(s.clOrdID,u)}),c=r.createMessage(new F(O.MsgType,Z.NewOrderSingle),new F(O.MsgSeqNum,r.getNextTargetMsgSeqNum()),new F(O.SenderCompID,r.sender),new F(O.TargetCompID,r.target),new F(O.SendingTime,r.getTimestamp()),new F(O.ClOrdID,s.clOrdID),new F(O.Side,s.side),new F(O.Symbol,s.symbol),new F(O.OrderQty,Number.parseFloat(String(s.quantity))),new F(O.Price,Number.parseFloat(String(s.price))),new F(O.OrdType,s.ordType),new F(O.HandlInst,s.handlInst),new F(O.TimeInForce,s.timeInForce),new F(O.TransactTime,r.getTimestamp()));if(!r.connected)return{content:[{type:"text",text:"Error: Not connected. Ignoring message.",uri:"executeOrder"}],isError:!0};r.send(c);let n=await o;return t.delete(s.clOrdID),{content:[{type:"text",text:n.messageType===Z.Reject?`Reject message for order ${s.clOrdID}: ${JSON.stringify(n.toFIXJSON())}`:`Execution Report for order ${s.clOrdID}: ${JSON.stringify(n.toFIXJSON())}`,uri:"executeOrder"}]}}catch(a){return{content:[{type:"text",text:`Error: ${a instanceof Error?a.message:"Failed to execute order"}`,uri:"executeOrder"}],isError:!0}}},Le=r=>async t=>{try{let e=r.parse(t.fixString);return!e||e.length===0?{content:[{type:"text",text:"Error: Failed to parse FIX string",uri:"parse"}],isError:!0}:{content:[{type:"text",text:`${e[0].description}
|
|
17
|
-
${e[0].messageTypeDescription}`,uri:"parse"}]}}catch(e){return{content:[{type:"text",text:`Error: ${e instanceof Error?e.message:"Failed to parse FIX string"}`,uri:"parse"}],isError:!0}}},Ve=r=>async t=>{try{let e=r.parse(t.fixString);return!e||e.length===0?{content:[{type:"text",text:"Error: Failed to parse FIX string",uri:"parseToJSON"}],isError:!0}:{content:[{type:"text",text:`${e[0].toFIXJSON()}`,uri:"parseToJSON"}]}}catch(e){return{content:[{type:"text",text:`Error: ${e instanceof Error?e.message:"Failed to parse FIX string"}`,uri:"parseToJSON"}],isError:!0}}},Ee=(r,t,e,s)=>({parse:Le(r),parseToJSON:Ve(r),verifyOrder:Te(r,t),executeOrder:De(r,t,e),marketDataRequest:Fe(r,e),getStockGraph:Oe(s),getStockPriceHistory:Ie(s),technicalAnalysis:Me(s)});function Be(r,t){return r[t]||t}function He(r,t,e,s,a,o){let c=r.messageType;if(c===X.MarketDataSnapshotFullRefresh||c===X.MarketDataIncrementalRefresh){let n=r.getField($.Symbol)?.value,l=r.toFIXJSON().Body?.NoMDEntries||[],i={timestamp:Date.now(),bid:0,offer:0,spread:0,volume:0,trade:0,indexValue:0,openingPrice:0,closingPrice:0,settlementPrice:0,tradingSessionHighPrice:0,tradingSessionLowPrice:0,vwap:0,imbalance:0,openInterest:0,compositeUnderlyingPrice:0,simulatedSellPrice:0,simulatedBuyPrice:0,marginRate:0,midPrice:0,emptyBook:0,settleHighPrice:0,settleLowPrice:0,priorSettlePrice:0,sessionHighBid:0,sessionLowOffer:0,earlyPrices:0,auctionClearingPrice:0,swapValueFactor:0,dailyValueAdjustmentForLongPositions:0,cumulativeValueAdjustmentForLongPositions:0,dailyValueAdjustmentForShortPositions:0,cumulativeValueAdjustmentForShortPositions:0,fixingPrice:0,cashRate:0,recoveryRate:0,recoveryRateForLong:0,recoveryRateForShort:0,marketBid:0,marketOffer:0,shortSaleMinPrice:0,previousClosingPrice:0,thresholdLimitPriceBanding:0,dailyFinancingValue:0,accruedFinancingValue:0,twap:0};for(let v of l){let b=v.MDEntryType,m=v.MDEntryPx?Number.parseFloat(v.MDEntryPx):0,S=v.MDEntrySize?Number.parseFloat(v.MDEntrySize):0;switch(Be(g,b)){case g.Bid:i.bid=m;break;case g.Offer:i.offer=m;break;case g.Trade:i.trade=m;break;case g.IndexValue:i.indexValue=m;break;case g.OpeningPrice:i.openingPrice=m;break;case g.ClosingPrice:i.closingPrice=m;break;case g.SettlementPrice:i.settlementPrice=m;break;case g.TradingSessionHighPrice:i.tradingSessionHighPrice=m;break;case g.TradingSessionLowPrice:i.tradingSessionLowPrice=m;break;case g.VWAP:i.vwap=m;break;case g.Imbalance:i.imbalance=S;break;case g.TradeVolume:i.volume=S;break;case g.OpenInterest:i.openInterest=S;break;case g.CompositeUnderlyingPrice:i.compositeUnderlyingPrice=m;break;case g.SimulatedSellPrice:i.simulatedSellPrice=m;break;case g.SimulatedBuyPrice:i.simulatedBuyPrice=m;break;case g.MarginRate:i.marginRate=m;break;case g.MidPrice:i.midPrice=m;break;case g.EmptyBook:i.emptyBook=1;break;case g.SettleHighPrice:i.settleHighPrice=m;break;case g.SettleLowPrice:i.settleLowPrice=m;break;case g.PriorSettlePrice:i.priorSettlePrice=m;break;case g.SessionHighBid:i.sessionHighBid=m;break;case g.SessionLowOffer:i.sessionLowOffer=m;break;case g.EarlyPrices:i.earlyPrices=m;break;case g.AuctionClearingPrice:i.auctionClearingPrice=m;break;case g.SwapValueFactor:i.swapValueFactor=m;break;case g.DailyValueAdjustmentForLongPositions:i.dailyValueAdjustmentForLongPositions=m;break;case g.CumulativeValueAdjustmentForLongPositions:i.cumulativeValueAdjustmentForLongPositions=m;break;case g.DailyValueAdjustmentForShortPositions:i.dailyValueAdjustmentForShortPositions=m;break;case g.CumulativeValueAdjustmentForShortPositions:i.cumulativeValueAdjustmentForShortPositions=m;break;case g.FixingPrice:i.fixingPrice=m;break;case g.CashRate:i.cashRate=m;break;case g.RecoveryRate:i.recoveryRate=m;break;case g.RecoveryRateForLong:i.recoveryRateForLong=m;break;case g.RecoveryRateForShort:i.recoveryRateForShort=m;break;case g.MarketBid:i.marketBid=m;break;case g.MarketOffer:i.marketOffer=m;break;case g.ShortSaleMinPrice:i.shortSaleMinPrice=m;break;case g.PreviousClosingPrice:i.previousClosingPrice=m;break;case g.ThresholdLimitPriceBanding:i.thresholdLimitPriceBanding=m;break;case g.DailyFinancingValue:i.dailyFinancingValue=m;break;case g.AccruedFinancingValue:i.accruedFinancingValue=m;break;case g.TWAP:i.twap=m;break}}i.spread=i.offer-i.bid,s.has(n)||s.set(n,[]);let y=s.get(n);y.push(i),y.length>a&&y.splice(0,y.length-a),o?.(n,i);let P=r.getField($.MDReqID)?.value;if(P){let v=e.get(P);v&&(v(r),e.delete(P))}}else if(c===X.ExecutionReport){let n=r.getField($.ClOrdID)?.value,u=e.get(n);u&&(u(r),e.delete(n))}}var j={};function $e(r){if(r.type==="object"){let t={};for(let[e,s]of Object.entries(r.properties||{})){let a=s;a.type==="string"?a.enum?t[e]=x.enum(a.enum):t[e]=x.string():a.type==="number"?t[e]=x.number():a.type==="boolean"?t[e]=x.boolean():a.type==="array"?a.items.type==="string"?t[e]=x.array(x.string()):a.items.type==="number"?t[e]=x.array(x.number()):a.items.type==="boolean"?t[e]=x.array(x.boolean()):t[e]=x.array(x.any()):t[e]=x.any()}return t}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:r,logger:t,onReady:e}){super({logger:t,onReady:e}),this.port=r}async register(r){this.parser=r,this.logger=r.logger,this.logger?.log({level:"info",message:`FIXParser (MCP): -- Plugin registered. Creating MCP server on port ${this.port}...`}),this.parser.addOnMessageCallback(t=>{this.parser&&He(t,this.parser,this.pendingRequests,this.marketDataPrices,this.MAX_PRICE_HISTORY)}),this.httpServer=je(async(t,e)=>{if(!t.url||!t.method){e.writeHead(400),e.end("Bad Request");return}if(t.url==="/mcp"){let s=t.headers["mcp-session-id"];if(t.method==="POST"){let a=[];t.on("data",o=>{a.push(o)}),t.on("end",async()=>{let o,c=Buffer.concat(a).toString();try{o=JSON.parse(c)}catch{e.writeHead(400),e.end(JSON.stringify({error:"Invalid JSON"}));return}let n;if(s&&j[s])n=j[s];else if(!s&&t.method==="POST"&&Ge(o))n=new We({sessionIdGenerator:()=>Ne(),onsessioninitialized:u=>{j[u]=n}}),n.onclose=()=>{n.sessionId&&delete j[n.sessionId]},this.mcpServer=new qe({name:this.serverName||"FIXParser",version:this.serverVersion||"1.0.0"}),this.setupTools(),await this.mcpServer.connect(n);else{e.writeHead(400,{"Content-Type":"application/json"}),e.end(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Bad Request: No valid session ID provided"},id:null}));return}try{await n.handleRequest(t,e,o)}catch(u){throw this.logger?.log({level:"error",message:`Error handling request: ${u}`}),u}})}else if(t.method==="GET"||t.method==="DELETE"){if(!s||!j[s]){e.writeHead(400),e.end("Invalid or missing session ID");return}let a=j[s];try{await a.handleRequest(t,e)}catch(o){throw this.logger?.log({level:"error",message:`Error handling ${t.method} request: ${o}`}),o}}else this.logger?.log({level:"error",message:`Method not allowed: ${t.method}`}),e.writeHead(405),e.end("Method Not Allowed")}else e.writeHead(404),e.end("Not Found")}),this.httpServer.listen(this.port,()=>{this.logger?.log({level:"info",message:`FIXParser (MCP): -- Server listening on http://localhost:${this.port}...`})}),this.onReady&&this.onReady()}setupTools(){if(!this.parser){this.logger?.log({level:"error",message:"FIXParser (MCP): -- FIXParser instance not initialized. Ignoring setup of tools..."});return}if(!this.mcpServer){this.logger?.log({level:"error",message:"FIXParser (MCP): -- MCP Server not initialized. Ignoring setup of tools..."});return}let r=Ee(this.parser,this.verifiedOrders,this.pendingRequests,this.marketDataPrices);Object.entries(ve).forEach(([t,{description:e,schema:s}])=>{this.mcpServer?.registerTool(t,{description:e,inputSchema:$e(s)},async a=>{let o=r[t];if(!o)return{content:[{type:"text",text:`Tool not found: ${t}`}],isError:!0};let c=await o(a);return{content:c.content,isError:c.isError}})})}};var Ke=async()=>{await Je.setLicenseKey(process.env.FIXPARSER_LICENSE_KEY);let r=process.env.FIXPARSER_SENDER||"SENDER",t=process.env.FIXPARSER_TARGET||"TARGET",e=new Ue({plugins:[new te({port:3099,onReady:()=>console.log("ready!")})]}),s=()=>{let o=e.createMessage(new H(N.MsgType,ze.Logon),new H(N.MsgSeqNum,e.getNextTargetMsgSeqNum()),new H(N.SenderCompID,r),new H(N.SendingTime,e.getTimestamp()),new H(N.TargetCompID,t),new H(N.ResetSeqNumFlag,_e.Yes),new H(N.EncryptMethod,Xe.None),new H(N.HeartBtInt,10)),c=e.parse(o.encode());console.log("sending message",c[0].description,c[0].messageString),e.send(o)},a={host:process.env.FIXPARSER_HOST||"10.0.1.42",port:process.env.FIXPARSER_PORT?Number.parseInt(process.env.FIXPARSER_PORT,10):5001,protocol:"tcp",sender:r,target:t,fixVersion:"FIX.4.4",logging:!0,logOptions:{name:r,level:"info",format:"json",transport:new Y({format:"console"})},onOpen:()=>{console.log("Open"),s()},onMessage:o=>console.log("received message",o.description,o.messageString.replace(/\x01/g,"|")),onClose:()=>{console.log("Disconnected")}};e.connect(a)};Ke().catch(r=>console.error("Error initializing server:",r));
|
|
18
|
-
//# sourceMappingURL=example_mcp_remote.mjs.map
|