@oracle-agent/oracle 0.22.12 → 0.22.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,3 @@
1
1
  import{createHash as to}from"node:crypto";import{createHash as Dr}from"node:crypto";var zr=new Set([408,425,429,500,502,503,504]),zt=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),Vr=2,Vt=4e3,Kt=["authorization","x-api-key","x-tensor-api-key","0x-api-key","api-key","cookie","proxy-authorization"],Jr=new Set([301,302,303,307,308]),Jt=3;function Kr(e){let t=String(e||"").toLowerCase();return Kt.includes(t)||/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(t)}function Yr(e){let t={};for(let[r,n]of Object.entries(e||{}))Kr(r)||(t[r]=n);return t}function Gr(e,t){if(!e)throw new Error(`HTTP redirect from ${t} missing Location`);let r=new URL(String(e),String(t));if(r.protocol!=="http:"&&r.protocol!=="https:")throw new Error(`HTTP redirect from ${t} used unsupported protocol ${r.protocol}`);return r.toString()}function Xr(e,t){return new URL(String(e)).origin===new URL(String(t)).origin}var We=new Map;function Zr(e,t,r){let n={};for(let[l,u]of Object.entries(r||{}))n[l.toLowerCase()]=u;let o=Object.keys(n).filter(l=>/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(l)),i=[...new Set([...Kt,...o])].sort().map(l=>`${l}=${n[l]??""}`).join(`
2
- `),s=Dr("sha256").update(i).digest("hex").slice(0,32);return`${e} ${t} ${s}`}function Wr(e,t){let r=Number(t);return Number.isFinite(r)&&r>0?Math.min(r*1e3,Vt):Math.min(250*2**e,Vt)+Math.floor(Math.random()*100)}var Qr=e=>new Promise(t=>setTimeout(t,e));async function en(e,{fetchImpl:t,method:r,headers:n,body:o,timeoutMs:a}){let i=new AbortController,s=setTimeout(()=>i.abort(),a);try{let l=String(e),u={...n||{}};for(let f=0;f<=Jt;f+=1){let c=await t(l,{method:r,headers:u,body:o,signal:i.signal,redirect:"manual"}),d=await c.text(),m=null;if(d)try{m=JSON.parse(d)}catch{m=null}if(Jr.has(c.status)){if(r!=="GET"&&r!=="HEAD"){let h=new Error(`HTTP ${c.status} ${r} ${l} redirected non-idempotent request`);throw h.status=c.status,h.body=m??d.slice(0,300),h}if(f===Jt)throw new Error(`HTTP redirect loop for ${e}`);let p=Gr(c.headers?.get?.("location"),l);Xr(p,l)||(u=Yr(u)),l=p;continue}if(!c.ok){let p=new Error(`HTTP ${c.status} ${r} ${l}`);throw p.status=c.status,p.retryAfter=c.headers?.get?.("retry-after")??null,p.body=m??d.slice(0,300),p}return m??d}throw new Error(`HTTP redirect loop for ${e}`)}finally{clearTimeout(s)}}async function Yt(e,t={}){let r=t.fetchImpl||globalThis.fetch;if(typeof r!="function")throw new Error("fetch unavailable \u2014 pass opts.fetchImpl");let n=t.timeoutMs??12e3,o=(t.method||"GET").toUpperCase(),a={Accept:"application/json",...t.headers||{}},i=t.body;i!=null&&typeof i!="string"&&(a["Content-Type"]=a["Content-Type"]||"application/json",i=JSON.stringify(i));let s=Number.isInteger(t.retries)?Math.max(t.retries,0):Vr,l=async()=>{let m;for(let p=0;p<=s;p++)try{return await en(e,{fetchImpl:r,method:o,headers:a,body:i,timeoutMs:n})}catch(h){m=h;let E=h?.status,k=h?.name==="AbortError",P=new Set([408,425,429]),T=E!=null?P.has(E)||zr.has(E)&&zt.has(o):!k&&zt.has(o);if(p===s||!T)throw h;await Qr(Wr(p,h?.retryAfter))}throw m};if(!(t.dedupe!==!1&&o==="GET"&&i==null))return l();let f=Zr(o,e,a),c=We.get(f);if(c)return c;let d=l().finally(()=>We.delete(f));return We.set(f,d),d}var tn="https://api.hyperliquid.xyz/info",rn="https://api.hyperliquid-testnet.xyz/info";function nn({testnet:e,baseUrl:t}={}){if(t)return t.replace(/\/$/,"").endsWith("/info")?t:`${t.replace(/\/$/,"")}/info`;if(process.env.HL_INFO_URL)return process.env.HL_INFO_URL;if(process.env.HL_API_URL){let r=process.env.HL_API_URL.replace(/\/$/,"");return r.endsWith("/info")?r:`${r}/info`}return e||process.env.HL_TESTNET==="1"?rn:tn}async function Qe(e,t={}){if(!e||!e.type)throw new Error("hlInfo requires body.type");let r=nn(t);return Yt(r,{method:"POST",body:e,fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs})}async function Gt(e={}){return Qe({type:"meta"},e)}async function Xt({coin:e,interval:t="1h",startTime:r,endTime:n},o={}){if(!e)throw new Error("hlCandleSnapshot requires coin");let a={type:"candleSnapshot",req:{coin:String(e),interval:t,startTime:r??Date.now()-24*3600*1e3,endTime:n??Date.now()}};return Qe(a,o)}async function Zt({coin:e,startTime:t,endTime:r},n={}){if(!e)throw new Error("hlFundingHistory requires coin");return Qe({type:"fundingHistory",coin:String(e),startTime:t??Date.now()-24*3600*1e3,endTime:r??Date.now()},n)}function Pe(e){if(!Array.isArray(e))throw new TypeError("values must be an array");for(let t=0;t<e.length;t++){let r=e[t];if(typeof r!="number"||!Number.isFinite(r))throw new TypeError(`values[${t}] must be a finite number`)}}function ae(e){if(!Number.isInteger(e)||e<=0)throw new TypeError("period must be a positive integer")}function on(e){if(!Array.isArray(e))throw new TypeError("bars must be an array");for(let t=0;t<e.length;t++){let r=e[t];if(r==null||typeof r!="object")throw new TypeError(`bars[${t}] must be an object`);for(let n of["o","h","l","c"]){let o=r[n];if(typeof o!="number"||!Number.isFinite(o))throw new TypeError(`bars[${t}].${n} must be a finite number`)}if(r.h<r.l)throw new TypeError(`bars[${t}] high must be >= low`)}}function et(e,t){Pe(e),ae(t);let r=new Array(e.length).fill(null);if(e.length<t)return r;let n=0;for(let o=0;o<e.length;o++)n+=e[o],o>=t&&(n-=e[o-t]),o>=t-1&&(r[o]=n/t);return r}function Ae(e,t){Pe(e),ae(t);let r=new Array(e.length).fill(null);if(e.length<t)return r;let n=0;for(let i=0;i<t;i++)n+=e[i];let o=n/t;r[t-1]=o;let a=2/(t+1);for(let i=t;i<e.length;i++)o=a*e[i]+(1-a)*o,r[i]=o;return r}function tt(e,t){Pe(e),ae(t);let r=new Array(e.length).fill(null);if(e.length<=t)return r;let n=0,o=0;for(let s=1;s<=t;s++){let l=e[s]-e[s-1];l>=0?n+=l:o-=l}let a=n/t,i=o/t;r[t]=Wt(a,i);for(let s=t+1;s<e.length;s++){let l=e[s]-e[s-1],u=l>0?l:0,f=l<0?-l:0;a=(a*(t-1)+u)/t,i=(i*(t-1)+f)/t,r[s]=Wt(a,i)}return r}function Wt(e,t){return e===0&&t===0?50:t===0?100:e===0?0:100-100/(1+e/t)}function rt(e,t={}){Pe(e);let r=t.fastPeriod,n=t.slowPeriod,o=t.signalPeriod;if(ae(r),ae(n),ae(o),r>=n)throw new TypeError("fastPeriod must be < slowPeriod");let a=Ae(e,r),i=Ae(e,n),s=new Array(e.length).fill(null);for(let c=0;c<e.length;c++)a[c]!=null&&i[c]!=null&&(s[c]=a[c]-i[c]);let l=new Array(e.length).fill(null),u=new Array(e.length).fill(null),f=[];for(let c=0;c<s.length;c++)s[c]!=null&&f.push(c);if(f.length>=o){let c=0;for(let h=0;h<o;h++)c+=s[f[h]];let d=c/o,m=f[o-1];l[m]=d,u[m]=s[m]-d;let p=2/(o+1);for(let h=o;h<f.length;h++){let E=f[h];d=p*s[E]+(1-p)*d,l[E]=d,u[E]=s[E]-d}}return{line:s,signal:l,histogram:u}}function nt(e,t={}){Pe(e);let r=t.period,n=t.stdDev;if(ae(r),typeof n!="number"||!Number.isFinite(n)||n<=0)throw new TypeError("stdDev must be a finite number > 0");let o=new Array(e.length).fill(null),a=new Array(e.length).fill(null),i=new Array(e.length).fill(null);if(e.length<r)return{upper:a,middle:o,lower:i};let s=0,l=0;for(let u=0;u<e.length;u++){let f=e[u];if(s+=f,l+=f*f,u>=r){let c=e[u-r];s-=c,l-=c*c}if(u>=r-1){let c=s/r,d=l/r-c*c;d<0&&d>-1e-12&&(d=0);let m=Math.sqrt(d);o[u]=c,a[u]=c+n*m,i[u]=c-n*m}}return{upper:a,middle:o,lower:i}}function ot(e,t){on(e),ae(t);let r=new Array(e.length).fill(null);if(e.length<t)return r;let n=new Array(e.length);for(let i=0;i<e.length;i++){let s=e[i];if(i===0)n[i]=s.h-s.l;else{let l=e[i-1].c;n[i]=Math.max(s.h-s.l,Math.abs(s.h-l),Math.abs(s.l-l))}}let o=0;for(let i=0;i<t;i++)o+=n[i];let a=o/t;r[t-1]=a;for(let i=t;i<e.length;i++)a=(a*(t-1)+n[i])/t,r[i]=a;return r}import{createHash as sn}from"node:crypto";var st=2,an="93f9c998260e73756c13871dc1a84dd6cdb26ec6113bd1941f023519939db440",cn="68f5b412a9975f04024cf9b9b6209b4bccedd52f176e95f34f786b3f53479c6a",ln="f197a38ff1c0f4ebe13326db8cbb8167ea3dd5d62e6033fe97c2fee8d23d96b5",Qt=sn("sha256").update(JSON.stringify({version:st,compilerSourceHash:an,indicatorsSourceHash:cn,schemaSourceHash:ln})).digest("hex");var he=st,ce=Qt,un=Object.freeze({open:"o",high:"h",low:"l",close:"c",volume:"v",fundingRate:"fundingRate",openInterest:"openInterest"}),fn=Object.freeze({"1m":6e4,"3m":18e4,"5m":3e5,"15m":9e5,"30m":18e5,"1h":36e5,"2h":72e5,"4h":144e5,"8h":288e5,"12h":432e5,"1d":864e5});function Y(e){return typeof e=="number"&&Number.isFinite(e)}function dn(e){let t=new Map(e.map(s=>[s.id,s])),r=s=>{switch(s.type){case"indicator":return s.input?[s.input]:[];case"compare":case"cross":return[s.left,s.right];case"logic":return[...s.inputs];default:return[]}},n=new Map,o=new Map;for(let s of e)n.set(s.id,0),o.set(s.id,[]);for(let s of e)for(let l of r(s))t.has(l)&&(o.get(l).push(s.id),n.set(s.id,n.get(s.id)+1));let a=[];for(let[s,l]of n)l===0&&a.push(s);let i=[];for(;a.length;){let s=a.shift();i.push(s);for(let l of o.get(s))n.set(l,n.get(l)-1),n.get(l)===0&&a.push(l)}if(i.length!==e.length)throw new Error("strategy graph is cyclic");return i}function me(e,t){return e!=null&&typeof e=="object"&&"param"in e?t[e.param].value:e}function pn(e,t,r){if(!Array.isArray(e)||e.length===0)throw new TypeError("bars must be a non-empty array");if(!Number.isInteger(t)||t<0||t>=e.length)throw new RangeError("index out of range");let n=null;for(let o=0;o<=t;o++){let a=e[o];if(a==null||typeof a!="object"||Array.isArray(a))throw new TypeError(`bars[${o}] must be an object`);let{t:i,o:s,h:l,l:u,c:f,v:c}=a;if(!Y(i)&&(typeof i=="number"&&Number.isFinite(i)),!Number.isFinite(i))throw new TypeError(`bars[${o}].t must be finite`);for(let[d,m]of[["o",s],["h",l],["l",u],["c",f],["v",c]])if(!Y(m))throw new TypeError(`bars[${o}].${d} must be a finite number`);for(let[d,m]of[["o",s],["h",l],["l",u],["c",f]])if(!(m>0))throw new TypeError(`bars[${o}].${d} price must be positive`);if(c<0)throw new TypeError(`bars[${o}].v volume must be non-negative`);if(l<Math.max(s,f,u))throw new TypeError(`bars[${o}] high must be >= max(open, close, low)`);if(u>Math.min(s,f,l))throw new TypeError(`bars[${o}] low must be <= min(open, close, high)`);if(n!=null){if(!(i>n))throw new TypeError("bars t must be strictly increasing");if(i-n!==fn[r])throw new TypeError(`bars t must match ${r} cadence`)}if(n=i,"fundingRate"in a&&a.fundingRate!=null&&!Y(a.fundingRate))throw new TypeError(`bars[${o}].fundingRate must be finite when present`);if("openInterest"in a&&a.openInterest!=null){if(!Y(a.openInterest))throw new TypeError(`bars[${o}].openInterest must be finite when present`);if(a.openInterest<0)throw new TypeError(`bars[${o}].openInterest must be non-negative`)}}}function ue(e,t,r,n,o,a){if(a.has(e))return a.get(e);let i=t.get(e),s;switch(i.type){case"input":{let l=un[i.field];s=new Array(o+1);for(let u=0;u<=o;u++){let f=n[u][l];s[u]=f===void 0?null:f}break}case"constant":{let l=me(i.value,r);s=new Array(o+1).fill(l);break}case"indicator":{let l=i.period!=null?me(i.period,r):void 0;if(i.indicator==="atr"){let c=[];for(let d=0;d<=o;d++){let m=n[d];c.push({o:m.o,h:m.h,l:m.l,c:m.c})}s=ot(c,l);break}let f=ue(i.input,t,r,n,o,a).map((c,d)=>{if(c==null||!Y(c))throw new TypeError(`indicator input ${i.input} has non-finite value at ${d}`);return c});if(i.indicator==="sma")s=et(f,l);else if(i.indicator==="ema")s=Ae(f,l);else if(i.indicator==="rsi")s=tt(f,l);else if(i.indicator==="macd")s=rt(f,{fastPeriod:me(i.fastPeriod,r),slowPeriod:me(i.slowPeriod,r),signalPeriod:me(i.signalPeriod,r)})[i.output];else if(i.indicator==="bollinger")s=nt(f,{period:l,stdDev:me(i.stdDev,r)})[i.output];else throw new Error(`unsupported indicator ${i.indicator}`);break}case"compare":{let l=ue(i.left,t,r,n,o,a),u=ue(i.right,t,r,n,o,a);s=new Array(o+1);for(let f=0;f<=o;f++){let c=l[f],d=u[f];if(c==null||d==null||!Y(c)||!Y(d)){s[f]=!1;continue}switch(i.op){case"gt":s[f]=c>d;break;case"gte":s[f]=c>=d;break;case"lt":s[f]=c<d;break;case"lte":s[f]=c<=d;break;case"eq":s[f]=c===d;break;default:s[f]=!1}}break}case"logic":{let l=i.inputs.map(u=>ue(u,t,r,n,o,a));s=new Array(o+1);for(let u=0;u<=o;u++)if(i.op==="not"){let f=l[0][u];s[u]=f===!0?!1:f===!1}else if(i.op==="and"){let f=!0;for(let c of l)if(c[u]!==!0){f=!1;break}s[u]=f}else if(i.op==="or"){let f=!1;for(let c of l)if(c[u]===!0){f=!0;break}s[u]=f}else s[u]=!1;break}case"cross":{let l=ue(i.left,t,r,n,o,a),u=ue(i.right,t,r,n,o,a);s=new Array(o+1),s[0]=!1;for(let f=1;f<=o;f++){let c=l[f-1],d=u[f-1],m=l[f],p=u[f];if(c==null||d==null||m==null||p==null||!Y(c)||!Y(d)||!Y(m)||!Y(p)){s[f]=!1;continue}i.direction==="above"?s[f]=c<=d&&m>p:s[f]=c>=d&&m<p}break}default:throw new Error(`unknown node type ${i.type}`)}return a.set(e,s),s}function z(e,t={}){let r=V(e);t&&Object.keys(t).length&&(r=ye(r,t));let n=new Map(r.nodes.map(m=>[m.id,m])),o=Object.freeze(dn(r.nodes)),a=r.parameters,i=new Set(r.nodes.filter(m=>m.type==="input").map(m=>m.field));if(r.nodes.some(m=>m.type==="indicator"&&m.indicator==="atr"))for(let m of["open","high","low","close"])i.add(m);let s=Object.freeze([...i].sort()),l=fe(r);function u(m,p){let h={};for(let k of o){let P=m.get(k);h[k]=P[p]}let E=k=>k!=null&&h[k]===!0;return{values:h,signals:{entryLong:E(r.rules.entryLong),entryShort:E(r.rules.entryShort),exitLong:E(r.rules.exitLong),exitShort:E(r.rules.exitShort)}}}function f(m,p){pn(m,p,r.market.interval);let h=new Map;for(let E of o)ue(E,n,a,m,p,h);return h}function c(m,p){return u(f(m,p),p)}function d(m){if(!Array.isArray(m)||m.length===0)throw new TypeError("bars must be a non-empty array");let p=m.length-1,h=f(m,p);return Object.freeze(m.map((E,k)=>Object.freeze(u(h,k))))}return Object.freeze({strategy:r,strategyHash:l,compilerVersion:he,compilerHash:ce,requiredSeries:s,nodeOrder:o,evaluate:c,evaluateAll:d})}import{createHash as In}from"node:crypto";import{createHash as mn}from"node:crypto";var hn=Object.freeze({initialEquityUsd:1e4,takerFeeBps:3.5,builderFeeBps:2,slippageBps:2,latencyBars:1,maxVolumeParticipationPct:100});function yn(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function Q(e){return typeof e=="number"&&Number.isFinite(e)}function it(e){if(e==null||typeof e!="object"||Object.isFrozen(e))return e;if(Array.isArray(e)){for(let t of e)it(t);return Object.freeze(e)}for(let t of Object.keys(e))it(e[t]);return Object.freeze(e)}function Le(e){if(Array.isArray(e))return e.map(Le);if(e!=null&&typeof e=="object"){let t={};for(let r of Object.keys(e).sort())t[r]=Le(e[r]);return t}return e}function at(e,t="result"){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`non-finite backtest result at ${t}`);return}if(!(e==null||typeof e!="object")){if(Array.isArray(e)){e.forEach((r,n)=>at(r,`${t}[${n}]`));return}for(let[r,n]of Object.entries(e))at(n,`${t}.${r}`)}}function tr(e){if(!Array.isArray(e)||e.length===0)throw new TypeError("bars must be a non-empty array");let t=null;for(let r=0;r<e.length;r++){let n=e[r];if(n==null||typeof n!="object"||Array.isArray(n))throw new TypeError(`bars[${r}] must be an object`);let{t:o,o:a,h:i,l:s,c:l,v:u}=n;if(!Q(o))throw new TypeError(`bars[${r}].t must be finite`);for(let[f,c]of[["o",a],["h",i],["l",s],["c",l],["v",u]])if(!Q(c))throw new TypeError(`bars[${r}].${f} must be a finite number`);for(let[f,c]of[["o",a],["h",i],["l",s],["c",l]])if(!(c>0))throw new TypeError(`bars[${r}].${f} price must be positive`);if(u<0)throw new TypeError(`bars[${r}].v volume must be non-negative`);if(i<Math.max(a,l,s))throw new TypeError(`bars[${r}] high must be >= max(open, close, low)`);if(s>Math.min(a,l,i))throw new TypeError(`bars[${r}] low must be <= min(open, close, high)`);if(t!=null&&!(o>t))throw new TypeError("bars t must be strictly increasing");if(t=o,"fundingRate"in n&&n.fundingRate!=null&&!Q(n.fundingRate))throw new TypeError(`bars[${r}].fundingRate must be finite when present`);if("fundingPaymentRate"in n&&n.fundingPaymentRate!=null&&!Q(n.fundingPaymentRate))throw new TypeError(`bars[${r}].fundingPaymentRate must be finite when present`);if("openInterest"in n&&n.openInterest!=null&&!Q(n.openInterest))throw new TypeError(`bars[${r}].openInterest must be finite when present`)}}function $e(e){if(!Array.isArray(e))throw new TypeError("bars must be an array");return e.length>0&&tr(e),mn("sha256").update(JSON.stringify(Le(e)),"utf8").digest("hex")}function gn(e){if(e==null&&(e={}),!yn(e))throw new TypeError("options must be a plain object");let t={...hn},r=new Set(["initialEquityUsd","takerFeeBps","builderFeeBps","slippageBps","latencyBars","maxVolumeParticipationPct","nowMs"]);for(let n of Object.keys(e))if(!r.has(n))throw new TypeError(`unknown option "${n}"`);if("initialEquityUsd"in e){if(!Q(e.initialEquityUsd)||e.initialEquityUsd<=0)throw new TypeError("initialEquityUsd must be a positive finite number");t.initialEquityUsd=e.initialEquityUsd}for(let n of["takerFeeBps","builderFeeBps","slippageBps"])if(n in e){let o=e[n];if(!Q(o)||o<0)throw new TypeError(`${n} must be a finite number >= 0`);if(n==="slippageBps"?o>=1e4:o>1e4)throw new TypeError(`${n} exceeds its safe basis-point bound`);t[n]=o}if("latencyBars"in e){let n=e.latencyBars;if(!Number.isInteger(n)||n<1)throw new TypeError("latencyBars must be an integer >= 1");t.latencyBars=n}if("maxVolumeParticipationPct"in e){let n=e.maxVolumeParticipationPct;if(!Q(n)||n<=0||n>100)throw new TypeError("maxVolumeParticipationPct must be in (0,100]");t.maxVolumeParticipationPct=n}if("nowMs"in e){if(!Number.isInteger(e.nowMs))throw new TypeError("nowMs must be an integer epoch milliseconds");t.nowMs=e.nowMs}return t}function je(e){return e/1e4}function wn(e,t,r){let n=je(r);return t==="long"?e*(1+n):e*(1-n)}function bn(e,t,r){let n=je(r);return t==="long"?e*(1-n):e*(1+n)}function er(e,t,r){let n=Math.abs(e)*je(t),o=Math.abs(e)*je(r);return{taker:n,builder:o,total:n+o}}function En(e,t){let r=e*(t.positionSizePct/100)*t.maxLeverage;return Math.min(r,t.maxNotionalUsd)}function xn(e,t,r){let n=r/100;return t==="long"?e*(1-n):e*(1+n)}function Sn(e,t,r){let n=r/100;return t==="long"?e*(1+n):e*(1-n)}function kn(e,t,r,n){if(!(r>0))return t==="long"?0:Number.POSITIVE_INFINITY;let o=Math.min(.99,1/(2*r)+n/1e4);return t==="long"?e*(1-1/r)/(1-o):e*(1+1/r)/(1+o)}function An(e,t,r){return t==="long"?e.l<=r:e.h>=r}function Pn(e,t,r){return t==="long"?e.h>=r:e.l<=r}function $n(e,t,r){return t==="long"?e.l<=r:e.h>=r}function Te(e,t){for(let r of e.requiredSeries)if(["fundingRate","openInterest"].includes(r)&&!t.every(n=>Q(n?.[r])))throw new Error(`strategy required series is absent: ${r}`)}function Tn(e){if(e.length<3)return 0;let t=[];for(let i=1;i<e.length;i++){let s=e[i-1].equity,l=e[i].equity;s>0&&t.push((l-s)/s)}if(t.length<2)return 0;let r=0;for(let i of t)r+=i;let n=r/t.length,o=0;for(let i of t)o+=(i-n)**2;let a=Math.sqrt(o/(t.length-1));return a>0?n/a:0}function _n(e){let t=-1/0,r=0;for(let n of e){let o=n.equity;if(o>t&&(t=o),t>0){let a=(t-o)/t*100;a>r&&(r=a)}}return r}function ne(e,t,r={}){let n=gn(r);tr(t);let o=$e(t);n.nowMs!==void 0&&V(e,{nowMs:n.nowMs});let a=z(e);if(Te(a,t),n.nowMs!==void 0&&a.strategy.risk.expiresAt<=n.nowMs)throw new Error("strategy is expired: risk.expiresAt must be strictly greater than nowMs");let i=a.strategy.risk,s=a.evaluateAll(t),l=n.latencyBars,u=n.slippageBps,f=n.takerFeeBps,c=n.builderFeeBps,d=n.initialEquityUsd,m=0,p=0,h=0,E=0,k=0,P=[],T=[],x=[],N=[],_=[],w=null,J=0,se=null,ie=d,X=!1,y=0,A=0,v=[],L=new Array(t.length).fill(0);function j(b){v.push(b)}function I(b){let $=t[b].v*(n.maxVolumeParticipationPct/100);return Math.max(0,$-L[b])}function M(b){if(!w)return d;let $=w.side==="long"?(b-w.entryPrice)*w.qty:(w.entryPrice-b)*w.qty;return d+$}function D(b,$,S){let F=S.o,O=En(d,i);if(!(O>0)||!(F>0))return;let H=wn(F,$,u),R=O/H,q=I(b),Se=H*q;if(R>q){x.push({kind:"entry",barIndex:b,time:S.t,side:$,requestedNotionalUsd:O,maxFillNotionalUsd:Se,reason:"volume_participation"});return}L[b]+=R;let W=Math.abs(H-F)*R,re=er(O,f,c);d-=re.total,m+=re.taker,p+=re.builder,E+=W,k+=O,w={lifecycleEpoch:++A,side:$,entryBarIndex:b,entryReferencePrice:F,entryPrice:H,qty:R,notionalUsd:O,stop:xn(H,$,i.stopLossPct),take:Sn(H,$,i.takeProfitPct),liq:kn(H,$,i.maxLeverage,f+c),entryFees:re.taker,entryBuilderFees:re.builder,entrySlippageUsd:W,fundingAccrued:0}}function C(b,$,S,F){if(!w)return!1;let O=w.side,H=$,R=H;S!=="liquidation"&&F&&(R=bn(H,O,u));let q=w.qty,Se=q*R;if(S!=="liquidation"){let Dt=I(b),Br=R*Dt;if(q>Dt)return x.push({kind:"exit",barIndex:b,time:t[b].t,side:O,requestedNotionalUsd:Se,maxFillNotionalUsd:Br,reason:"volume_participation",triggerReason:S}),!1;L[b]+=q}let W=er(Se,f,c),re=S==="liquidation"?0:Math.abs(R-H)*q,ke,Ze;O==="long"?(ke=(H-w.entryReferencePrice)*q,Ze=(R-w.entryPrice)*q):(ke=(w.entryReferencePrice-H)*q,Ze=(w.entryPrice-R)*q),d+=Ze,d-=W.total,m+=W.taker,p+=W.builder,E+=re,k+=Se;let qr={side:O,entryBarIndex:w.entryBarIndex,entryTime:t[w.entryBarIndex].t,entryPrice:w.entryPrice,exitBarIndex:b,exitTime:t[b].t,exitPrice:R,exitReason:S,qty:q,notionalUsd:w.notionalUsd,grossPnlUsd:ke,feesUsd:w.entryFees+W.taker,builderFeesUsd:w.entryBuilderFees+W.builder,fundingUsd:w.fundingAccrued,slippageUsd:w.entrySlippageUsd+re,netPnlUsd:ke-(w.entryFees+W.taker+w.entryBuilderFees+W.builder)-w.fundingAccrued-(w.entrySlippageUsd+re)};return P.push(qr),S==="liquidation"&&T.push({barIndex:b,time:t[b].t,side:O,price:R,tradeIndex:P.length-1}),w=null,A+=1,y=b+1+(i.cooldownBars||0),!0}function Z(b,$,S,F){let O=b+1;if(O>=t.length)return;v.some(R=>R.kind==="exit"&&R.side===$&&R.fillBar===O&&R.epoch===F)||j({kind:"exit",side:$,signalBar:b,fillBar:O,reason:S,epoch:F})}function Me(b){let $=v.filter(S=>S.fillBar===b);for(let S=v.length-1;S>=0;S--)v[S].fillBar===b&&v.splice(S,1);$.sort((S,F)=>{let O=H=>H.kind==="exit"?0:1;return O(S)-O(F)});for(let S of $)if(S.kind==="exit"){if(!w||w.side!==S.side||w.lifecycleEpoch!==S.epoch)continue;let F=S.reason||"rule";C(b,t[b].o,F,!0)||Z(b,S.side,F,S.epoch)}else if(S.kind==="entry"){if(w||S.epoch!==A||b<y)continue;D(b,S.side,t[b])}}function Re(b){if(!w)return;let $=t[b],S=$.fundingPaymentRate;if(S==null||!Q(S)||S===0)return;let F=Math.abs(w.qty*$.c),O=S*F;w.side==="long"?(d-=O,w.fundingAccrued+=O,h+=O):(d+=O,w.fundingAccrued-=O,h-=O)}function Ne(b){if(!w)return;let $=t[b].o;(w.side==="long"?$<=w.liq:$>=w.liq)&&C(b,$,"liquidation",!1)}function Ht(b){if(!w)return;let $=t[b],S=w.side,F=$n($,S,w.liq),O=An($,S,w.stop),H=Pn($,S,w.take),R=q=>S==="long"?Math.min(q,$.o):Math.max(q,$.o);if(F){C(b,R(w.liq),"liquidation",!1);return}if(O&&H){C(b,R(w.stop),"stop_loss",!0)||Z(b,S,"stop_loss",w.lifecycleEpoch);return}if(O){C(b,R(w.stop),"stop_loss",!0)||Z(b,S,"stop_loss",w.lifecycleEpoch);return}H&&(C(b,w.take,"take_profit",!0)||Z(b,S,"take_profit",w.lifecycleEpoch))}for(let b=0;b<t.length;b++){let $=Math.floor(t[b].t/864e5);$!==se&&(se=$,ie=M(t[b].o),X=!1),Ne(b),Me(b),Ht(b),Re(b),!X&&M(t[b].c)<=ie*(1-i.maxDailyLossPct/100)&&(X=!0,N.push({type:"daily_loss_limit",barIndex:b,time:t[b].t,message:"daily loss limit reached; new entries blocked for UTC day"}));let S=s[b].signals,F=b+l;if(w)(w.side==="long"&&S.exitLong===!0||w.side==="short"&&S.exitShort===!0)&&F<t.length&&(v.some(q=>q.kind==="exit"&&q.side===w.side&&q.fillBar===F&&q.epoch===w.lifecycleEpoch)||j({kind:"exit",side:w.side,signalBar:b,fillBar:F,reason:"rule",epoch:w.lifecycleEpoch}));else{let H=S.entryLong===!0,R=S.entryShort===!0;H&&R?N.push({type:"conflicting_entry_signals",barIndex:b,time:t[b].t,message:"conflicting entry signals; no position opened"}):!X&&(H||R)&&F<t.length&&b>=y&&j({kind:"entry",side:H?"long":"short",signalBar:b,fillBar:F,epoch:A})}let O=d;w&&(J+=1,O=M(t[b].c)),_.push({barIndex:b,time:t[b].t,equity:O,positionSide:w?w.side:null})}let Ut=null;if(w){let b=t.length-1;if(C(b,t[b].c,"end_of_data",!0))_[b]={barIndex:b,time:t[b].t,equity:d,positionSide:null};else{let S=M(t[b].c);Ut={side:w.side,entryBarIndex:w.entryBarIndex,entryTime:t[w.entryBarIndex].t,entryPrice:w.entryPrice,qty:w.qty,notionalUsd:w.notionalUsd,markPrice:t[b].c,markedEquityUsd:S},N.push({type:"open_position_at_end",barIndex:b,time:t[b].t,message:"end-of-data exit missed; position remains open and marked"})}}let Ct=(w?M(t[t.length-1].c):d)-n.initialEquityUsd,Fr=Ct/n.initialEquityUsd*100,qt=0,Ke=0,Ye=0;for(let b of P)b.netPnlUsd>0?(qt+=1,Ke+=b.netPnlUsd):b.netPnlUsd<0&&(Ye+=-b.netPnlUsd);let Ge=P.length,Hr=Ge===0?0:qt/Ge,Xe=0;Ye>0?Xe=Ke/Ye:Ke>0&&(Xe=1e12);let Ur={netPnlUsd:Ct,netPnlPct:Fr,maxDrawdownPct:_n(_),winRate:Hr,profitFactor:Xe,tradeCount:Ge,sharpe:Tn(_),turnoverUsd:k,exposurePct:J/t.length*100},Cr={initialEquityUsd:n.initialEquityUsd,takerFeeBps:n.takerFeeBps,builderFeeBps:n.builderFeeBps,slippageBps:n.slippageBps,latencyBars:n.latencyBars,maxVolumeParticipationPct:n.maxVolumeParticipationPct},Bt={barsHash:o,strategyHash:a.strategyHash,compilerHash:ce,compilerVersion:he,config:Cr,trades:P,equityCurve:_,metrics:Ur,costs:{feesUsd:m,builderFeesUsd:p,fundingUsd:h,slippageUsd:E},liquidations:T,missedFills:x,openPositionAtEnd:Ut,flags:N};return at(Bt),it(Le(Bt))}var or=Object.freeze(["fail","pass_paper_only","pass_live_eligible"]);function ee(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function ge(e){return typeof e=="number"&&Number.isFinite(e)}function ut(e){if(e==null||typeof e!="object"||Object.isFrozen(e))return e;if(Array.isArray(e)){for(let t of e)ut(t);return Object.freeze(e)}for(let t of Object.keys(e))ut(e[t]);return Object.freeze(e)}function de(e){if(Array.isArray(e))return e.map(de);if(e!=null&&typeof e=="object"){let t={};for(let r of Object.keys(e).sort())t[r]=de(e[r]);return t}return e}function ct(e){return{netPnlUsd:e.metrics.netPnlUsd,netPnlPct:e.metrics.netPnlPct,maxDrawdownPct:e.metrics.maxDrawdownPct,winRate:e.metrics.winRate,profitFactor:e.metrics.profitFactor,tradeCount:e.metrics.tradeCount,sharpe:e.metrics.sharpe,turnoverUsd:e.metrics.turnoverUsd,exposurePct:e.metrics.exposurePct}}function rr(e){return{feesUsd:e.costs.feesUsd,builderFeesUsd:e.costs.builderFeesUsd,fundingUsd:e.costs.fundingUsd,slippageUsd:e.costs.slippageUsd}}function On(e){return(e.feesUsd||0)+(e.builderFeesUsd||0)+Math.max(0,e.fundingUsd||0)+(e.slippageUsd||0)}function vn(e){let t=0;for(let r of e.trades)r.grossPnlUsd>0&&(t+=r.grossPnlUsd);return t}function Mn(e,t,r){return!(!e||e.tradeCount<Math.max(1,Math.min(r,3))||!(e.netPnlUsd>0)||!(e.profitFactor>1)||!(e.maxDrawdownPct<=t.maxDailyLossPct))}function sr(e){if(!ee(e))throw new TypeError("evidence artifact must be a plain object");if(!or.includes(e.status))throw new TypeError("evidence artifact status is invalid");for(let t of["strategyHash","compilerHash","barsHash"])if(typeof e[t]!="string"||!/^[0-9a-f]{64}$/.test(e[t]))throw new TypeError(`evidence artifact ${t} must be a sha256 hash`);if(!ee(e.split))throw new TypeError("evidence artifact split required");if(!Array.isArray(e.flags))throw new TypeError("evidence artifact flags must be an array");if(!ee(e.walkForward)||!Array.isArray(e.walkForward.windows))throw new TypeError("evidence artifact walkForward windows required");if(e.status==="pass_live_eligible"&&(!ee(e.train)||!ee(e.holdout)))throw new TypeError("live-eligible evidence artifact requires train and holdout facts");return de({barsHash:e.barsHash,compilerHash:e.compilerHash,flags:e.flags.map(t=>de(t)),holdout:e.holdout??null,split:e.split,status:e.status,strategyHash:e.strategyHash,train:e.train??null,walkForward:{passRate:e.walkForward.passRate,windowsRun:e.walkForward.windowsRun??e.walkForward.windows.length,windows:e.walkForward.windows.map(t=>({index:t.index,trainStartIndex:t.trainStartIndex,trainEndIndex:t.trainEndIndex,passed:t.passed,reason:t.reason,evalStartIndex:t.evalStartIndex,evalEndIndex:t.evalEndIndex,metrics:t.metrics}))}})}function ft(e){return In("sha256").update(JSON.stringify(sr(e)),"utf8").digest("hex")}function G(e,t,r=0){if(!Number.isInteger(e)||e<r)throw new Error(`${t} must be an integer >= ${r}`);return e}function lt(e,t){if(!ee(e)||!ee(e.metrics))throw new Error(`${t} metrics required`);let r=G(e.tradeCount,`${t}.tradeCount`);if(e.metrics.tradeCount!==r)throw new Error(`${t} tradeCount contradicts metrics.tradeCount`);for(let n of["netPnlUsd","profitFactor","maxDrawdownPct"])if(!ge(e.metrics[n]))throw new Error(`${t}.metrics.${n} must be finite`);if(e.metrics.maxDrawdownPct<0)throw new Error(`${t}.metrics.maxDrawdownPct must be >= 0`);return e.metrics}function Rn(e,{maxDailyLossPct:t}={}){let r=e.split,n=G(r.trainStartIndex,"split.trainStartIndex"),o=G(r.trainEndIndex,"split.trainEndIndex"),a=G(r.trainBarCount,"split.trainBarCount",1),i=G(r.holdoutStartIndex,"split.holdoutStartIndex"),s=G(r.holdoutEndIndex,"split.holdoutEndIndex"),l=G(r.holdoutBarCount,"split.holdoutBarCount",1);if(n!==0||o-n+1!==a||i!==o+1||s-i+1!==l)throw new Error("evidence split must be contiguous, chronological, and count-consistent");if(!ge(r.trainFraction)||r.trainFraction<=0||r.trainFraction>=1)throw new Error("split.trainFraction must be in (0,1)");lt(e.train,"train");let u=lt(e.holdout,"holdout");if(u.tradeCount<1||u.netPnlUsd<=0||u.profitFactor<=1)throw new Error("live-eligible holdout metrics do not pass");if(ge(t)&&u.maxDrawdownPct>t)throw new Error("live-eligible holdout drawdown exceeds strategy risk");if(e.flags.length>0)throw new Error("live-eligible evidence cannot contain failure flags");let f=e.walkForward,c=f.windows;if(c.length<1||f.windowsRun!==c.length)throw new Error("live-eligible walk-forward windowsRun must match nonempty windows");let d=0,m=-1;for(let h=0;h<c.length;h++){let E=c[h];if(!ee(E)||E.index!==h||typeof E.passed!="boolean")throw new Error("walk-forward windows must be ordered and structurally valid");let k=G(E.trainStartIndex,`walkForward.windows[${h}].trainStartIndex`),P=G(E.trainEndIndex,`walkForward.windows[${h}].trainEndIndex`),T=G(E.evalStartIndex,`walkForward.windows[${h}].evalStartIndex`),x=G(E.evalEndIndex,`walkForward.windows[${h}].evalEndIndex`);if(k!==0||P>=T||T>x||T<=m)throw new Error("walk-forward windows must be chronological and disjoint");if(m=x,E.passed){if(d+=1,E.reason!=="pass")throw new Error("passed walk-forward window reason must be pass");let N=lt({metrics:E.metrics,tradeCount:E.metrics?.tradeCount},`walkForward.windows[${h}]`);if(N.tradeCount<1||N.netPnlUsd<=0||N.profitFactor<=1)throw new Error("passed walk-forward window metrics do not pass");if(ge(t)&&N.maxDrawdownPct>t)throw new Error("passed walk-forward drawdown exceeds strategy risk")}else if(E.reason==="pass")throw new Error("failed walk-forward window cannot have pass reason")}let p=d/c.length;if(!ge(f.passRate)||Math.abs(f.passRate-p)>Number.EPSILON||p<.6)throw new Error("walk-forward passRate contradicts concrete windows or is below live threshold")}function dt(e,t={}){if(typeof e?.id!="string"||!/^[0-9a-f]{64}$/.test(e.id))throw new Error("evidence.id must be a sha256 evidence artifact hash");let r=sr(e),n=de({id:e.id,...r});if(JSON.stringify(de(e))!==JSON.stringify(n))throw new Error("evidence artifact contains fields unbound from its deterministic identity");let o=ft(e);if(e.id!==o)throw new Error("evidence.id does not match its deterministic artifact facts digest");return e.status==="pass_live_eligible"&&Rn(e,t),e}function Fe({strategy:e,bars:t,backtestOptions:r={},trainFraction:n=.7,walkForwardWindows:o=3,minTrades:a=10}={}){let i=[];if(!ee(e))throw new TypeError("strategy must be a plain object");if(!Array.isArray(t))throw new TypeError("bars must be an array");if(!ee(r))throw new TypeError("backtestOptions must be a plain object");if(!ge(n)||n<=0||n>=1)throw new TypeError("trainFraction must be in (0,1)");if(!Number.isInteger(o)||o<1)throw new TypeError("walkForwardWindows must be a positive integer");if(!Number.isInteger(a)||a<0)throw new TypeError("minTrades must be an integer >= 0");let s=V(e),l=fe(s),u=$e(t),f=t.length,c=(I=[],M={})=>nr({status:"fail",strategy:s,sHash:l,barsHash:u,split:M.split||{trainStartIndex:0,trainEndIndex:-1,trainBarCount:0,holdoutStartIndex:0,holdoutEndIndex:-1,holdoutBarCount:0,trainFraction:n},train:M.train||null,holdout:M.holdout||null,walkForward:M.walkForward||{windows:[],passRate:0},flags:[...i,...I]});if(f<10)return c([{type:"insufficient_bars",message:"need at least 10 bars for evidence"}]);let d=Math.floor(f*n),m=d,p=f-m;if(d<5||p<3)return c([{type:"invalid_windowing",message:"train/holdout split too small",trainCount:d,holdoutCount:p}]);let h=t.slice(0,d),E=t.slice(m),k,P;try{k=ne(s,h,r),P=ne(s,E,r)}catch(I){return c([{type:"backtest_error",message:String(I.message||I)}])}let T={metrics:ct(k),costs:rr(k),tradeCount:k.metrics.tradeCount},x={metrics:ct(P),costs:rr(P),tradeCount:P.metrics.tradeCount},N={trainStartIndex:0,trainEndIndex:d-1,trainBarCount:d,holdoutStartIndex:m,holdoutEndIndex:f-1,holdoutBarCount:p,trainFraction:n},_=[],w=Math.floor(f/(o+1));if(w<3)i.push({type:"invalid_windowing",message:"walk-forward window size too small",wfSize:w});else for(let I=0;I<o;I++){let M=w*(I+1),D=M,C=Math.min(f,D+w);if(C-D<3||M<3){_.push({index:I,trainStartIndex:0,trainEndIndex:M-1,evalStartIndex:D,evalEndIndex:C-1,passed:!1,reason:"window_too_small",metrics:null});continue}let Z=t.slice(D,C),Me;try{Me=ne(s,Z,r)}catch{_.push({index:I,trainStartIndex:0,trainEndIndex:M-1,evalStartIndex:D,evalEndIndex:C-1,passed:!1,reason:"backtest_error",metrics:null});continue}let Re=ct(Me),Ne=Mn(Re,s.risk,a);_.push({index:I,trainStartIndex:0,trainEndIndex:M-1,evalStartIndex:D,evalEndIndex:C-1,passed:Ne,reason:Ne?"pass":"fail_metrics",metrics:Re})}let J=_.filter(I=>I.passed).length,se=_.length===0?0:J/_.length,ie={windows:_,passRate:se,windowsRun:_.length};x.metrics.tradeCount===0&&T.metrics.tradeCount===0&&i.push({type:"no_trades",message:"no trades in train or holdout"}),x.metrics.tradeCount===0&&i.push({type:"absent_oos_trades",message:"holdout produced no trades"}),x.metrics.netPnlUsd<0&&i.push({type:"holdout_loss",message:"holdout netPnlUsd is negative"}),T.metrics.netPnlUsd>0&&x.metrics.netPnlUsd<0&&T.metrics.netPnlUsd>Math.abs(x.metrics.netPnlUsd)*.25?i.push({type:"overfit",message:"profitable train with losing holdout (OOS collapse)"}):T.metrics.netPnlUsd>0&&x.metrics.netPnlUsd>0&&x.metrics.netPnlUsd<T.metrics.netPnlUsd*.1&&T.metrics.tradeCount>=a&&i.push({type:"severe_oos_collapse",message:"holdout pnl collapsed vs train"});let X=On(x.costs),y=vn(P);y>0&&X>y&&i.push({type:"costs_exceed_gross",message:"holdout costs exceed gross gains"});let A=i.some(I=>["insufficient_bars","invalid_windowing","absent_oos_trades","holdout_loss","no_trades","severe_oos_collapse","backtest_error"].includes(I.type)),v=i.some(I=>I.type==="overfit"),L="fail";return x.metrics.tradeCount>=a&&x.metrics.netPnlUsd>0&&x.metrics.profitFactor>1&&x.metrics.maxDrawdownPct<=s.risk.maxDailyLossPct&&se>=.6&&!(y>0&&X>y)&&!v&&!i.some(I=>I.type==="severe_oos_collapse"||I.type==="invalid_windowing")?L="pass_live_eligible":!A&&x.metrics.tradeCount>0&&T.metrics.tradeCount>0&&Number.isFinite(x.metrics.netPnlUsd)?(L="pass_paper_only",x.metrics.tradeCount<a&&i.push({type:"undersampled",message:"holdout trades below minTrades"})):v&&x.metrics.tradeCount>0&&T.metrics.netPnlUsd>0?L="fail":x.metrics.tradeCount>0&&T.metrics.tradeCount>0&&!A?L="pass_paper_only":L="fail",x.metrics.netPnlUsd<0&&(L=L==="pass_live_eligible"?"fail":L==="pass_paper_only"?"pass_paper_only":"fail",L="fail"),nr({status:L,strategy:s,sHash:l,barsHash:u,split:N,train:T,holdout:x,walkForward:ie,flags:i})}function nr({status:e,strategy:t,sHash:r,barsHash:n,split:o,train:a,holdout:i,walkForward:s,flags:l}){let u={status:e,strategyHash:r,compilerHash:ce,barsHash:n,split:o,train:a,holdout:i,walkForward:s,flags:l};return u.id=ft(u),ut(de(JSON.parse(JSON.stringify(u))))}import{createHash as Nn,createHmac as Ln,timingSafeEqual as As}from"node:crypto";var jn=2,Fn=300*1e3,Ps=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})();function pt(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(pt).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${pt(e[r])}`).join(",")}}`}function ir(e){let t=String(e?.ORACLE_STAMP_HMAC_SECRET||"").trim();return t.length>=16?t:""}function ar(e=process.env){return ir(process.env)||ir(e)}function Hn(e){let{oraclePrepared:t,prepareHash:r,prepareMac:n,note:o,...a}=e||{};return a}function Un(e){let t=Hn(e);return Nn("sha256").update(pt(t)).digest("hex")}function Cn(e,t=ar()){return t?Ln("sha256",t).update(String(e)).digest("hex"):""}function cr(e,{provider:t,kind:r,env:n=process.env}={}){if(!e||typeof e!="object")throw new Error("stampPrepared: payload object required");let o={...e,provider:e.provider||t,kind:e.kind||r,requiresUserSignature:e.requiresUserSignature!==!1,signingReady:!1,broadcastReady:!1,executionReady:!1};if(!o.provider)throw new Error("stampPrepared: provider required");if(!o.kind)throw new Error("stampPrepared: kind required");let a=Date.now(),i=a+Fn,l={...o,preparedAt:a,expiresAt:i,prepareVersion:jn},u=Un(l),f=ar(n),c=f?Cn(u,f):void 0,d={...l,oraclePrepared:!0,prepareHash:u};return c&&(d.prepareMac=c),d}var qn=["privatekey","secretkey","seed","mnemonic","passphrase","password","keystore","keymaterial","apikey","authtoken","accesstoken","refreshtoken","credential","bearer","signature","authorization","xprv","xpriv","wif"];function _e(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function Bn(e){return String(e).toLowerCase().replace(/[^a-z0-9]/g,"")}function ht(e,t="value"){if(Array.isArray(e)){e.forEach((r,n)=>ht(r,`${t}[${n}]`));return}if(_e(e))for(let[r,n]of Object.entries(e)){let o=Bn(r);if(qn.some(a=>o.includes(a)))throw new Error(`handoff: forbidden secret-like field at ${t}.${r}`);ht(n,`${t}.${r}`)}}function mt(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function yt({strategy:e,evidence:t,shadow:r,caps:n,nowMs:o=Date.now(),env:a=process.env}={}){if(ht({strategy:e,evidence:t,shadow:r,caps:n},"handoff"),!_e(e))throw new Error("handoff: strategy required");if(!_e(t))throw new Error("handoff: evidence required");if(!_e(r))throw new Error("handoff: shadow required");if(!_e(n))throw new Error("handoff: caps required");if(typeof r.id!="string"||!r.id.trim())throw new Error("handoff: shadow.id required");if(typeof r.stateHash!="string"||!/^[0-9a-f]{64}$/.test(r.stateHash))throw new Error("handoff: shadow.stateHash must be a sha256 hash");if(r.status!=="running")throw new Error("handoff: shadow.status must be running");if(!Number.isInteger(r.cursor)||r.cursor<=0)throw new Error("handoff: shadow.cursor must be a positive integer");if(!Number.isInteger(r.updatedAt)||r.updatedAt<=0||r.updatedAt>o)throw new Error("handoff: shadow.updatedAt must be a positive integer <= nowMs");let i=V(e,{nowMs:o}),s=z(i);if(dt(t,{maxDailyLossPct:i.risk.maxDailyLossPct}),t.status!=="pass_live_eligible")throw new Error("handoff: evidence.status must be pass_live_eligible");if(t.strategyHash!==s.strategyHash)throw new Error("handoff: evidence.strategyHash mismatch");if(t.compilerHash!==s.compilerHash)throw new Error("handoff: evidence.compilerHash mismatch");let l=["perStrategyNotionalUsd","maxLeverage","dailyLossCapUsd","chainAllowlist","assetAllowlist","expiresAt","killSwitchRequired"];for(let d of l)if(!(d in n)||n[d]==null)throw new Error(`handoff: caps.${d} required`);if(!mt(n.perStrategyNotionalUsd))throw new Error("handoff: caps.perStrategyNotionalUsd must be positive");if(n.perStrategyNotionalUsd>s.strategy.risk.maxNotionalUsd)throw new Error("handoff: caps.perStrategyNotionalUsd exceeds strategy.risk.maxNotionalUsd");if(!mt(n.maxLeverage))throw new Error("handoff: caps.maxLeverage must be positive");if(n.maxLeverage>s.strategy.risk.maxLeverage)throw new Error("handoff: caps.maxLeverage exceeds strategy.risk.maxLeverage");if(!mt(n.dailyLossCapUsd))throw new Error("handoff: caps.dailyLossCapUsd must be positive");let u=s.strategy.risk.maxNotionalUsd*(s.strategy.risk.maxDailyLossPct/100);if(n.dailyLossCapUsd>u)throw new Error("handoff: caps.dailyLossCapUsd exceeds strategy daily loss ceiling");if(!Array.isArray(n.chainAllowlist)||n.chainAllowlist.length===0)throw new Error("handoff: caps.chainAllowlist must be a non-empty array");if(!n.chainAllowlist.every(d=>d==="hyperliquid"))throw new Error("handoff: caps.chainAllowlist must include only hyperliquid");if(!n.chainAllowlist.includes("hyperliquid"))throw new Error("handoff: caps.chainAllowlist must include hyperliquid");if(!Array.isArray(n.assetAllowlist)||n.assetAllowlist.length===0)throw new Error("handoff: caps.assetAllowlist must be a non-empty array");if(n.assetAllowlist.length!==1||n.assetAllowlist[0]!==s.strategy.market.coin)throw new Error("handoff: caps.assetAllowlist must contain only the strategy market coin");if(!Number.isInteger(n.expiresAt)||!(n.expiresAt>o))throw new Error("handoff: caps.expiresAt must be an integer > nowMs");if(n.expiresAt>s.strategy.risk.expiresAt)throw new Error("handoff: caps.expiresAt exceeds strategy.risk.expiresAt");if(n.killSwitchRequired!==!0)throw new Error("handoff: caps.killSwitchRequired must be exactly true");let f={perStrategyNotionalUsd:n.perStrategyNotionalUsd,maxLeverage:n.maxLeverage,dailyLossCapUsd:n.dailyLossCapUsd,chainAllowlist:[...n.chainAllowlist],assetAllowlist:[...n.assetAllowlist],expiresAt:n.expiresAt,killSwitchRequired:!0},c={strategyHash:s.strategyHash,compilerHash:s.compilerHash,evidence:JSON.parse(JSON.stringify(t)),shadow:{id:r.id,stateHash:r.stateHash,status:r.status,cursor:r.cursor,updatedAt:r.updatedAt},compiled:{strategyHash:s.strategyHash,compilerHash:s.compilerHash,compilerVersion:he,venue:"hyperliquid",market:{coin:s.strategy.market.coin,kind:"perp",interval:s.strategy.market.interval},risk:{...s.strategy.risk},strategy:JSON.parse(JSON.stringify(s.strategy))},arming:{liveBroadcast:!1,requiresExplicitUserArm:!0,caps:f},requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,executionReady:!1};return cr(c,{provider:"hl-strategy",kind:"strategy-live-handoff",env:a})}var Dn=Object.freeze({"1m":6e4,"3m":18e4,"5m":3e5,"15m":9e5,"30m":18e5,"1h":36e5,"2h":72e5,"4h":144e5,"8h":288e5,"12h":432e5,"1d":864e5});function we(e,t){let r=Number(e);if(!Number.isFinite(r))throw new TypeError(`${t} must be finite`);return r}function be(e,t){if(!Number.isSafeInteger(e)||e<0)throw new TypeError(`${t} must be a non-negative safe integer`);return e}function Ie(e){if(Array.isArray(e))for(let t of e)Ie(t);else if(e&&typeof e=="object")for(let t of Object.values(e))Ie(t);return Object.freeze(e)}function lr(e){let t=Dn[e];if(!t)throw new TypeError(`unsupported strategy interval: ${e}`);return t}function ur(e,{endTime:t=Number.MAX_SAFE_INTEGER}={}){if(!Array.isArray(e))throw new TypeError("Hyperliquid candles must be an array");be(t,"endTime");let r=new Map;for(let n=0;n<e.length;n++){let o=e[n];if(!o||typeof o!="object"||Array.isArray(o))throw new TypeError(`candles[${n}] must be an object`);let a=be(Number(o.t),`candles[${n}].t`);if(be(Number(o.T),`candles[${n}].T`)>t)continue;let s={t:a,o:we(o.o,`candles[${n}].o`),h:we(o.h,`candles[${n}].h`),l:we(o.l,`candles[${n}].l`),c:we(o.c,`candles[${n}].c`),v:we(o.v,`candles[${n}].v`)};if(s.h<Math.max(s.o,s.c,s.l))throw new TypeError(`candles[${n}].h is below another price`);if(s.l>Math.min(s.o,s.c,s.h))throw new TypeError(`candles[${n}].l is above another price`);if(s.v<0)throw new TypeError(`candles[${n}].v must be non-negative`);let l=r.get(a);if(l&&JSON.stringify(l)!==JSON.stringify(s))throw new TypeError(`conflicting duplicate candle at timestamp ${a}`);l||r.set(a,s)}return Ie([...r.values()].sort((n,o)=>n.t-o.t))}function zn(e,t){if(!Array.isArray(e))throw new TypeError("Hyperliquid funding history must be an array");let r=new Map;for(let n=0;n<e.length;n++){let o=e[n];if(!o||typeof o!="object"||Array.isArray(o))throw new TypeError(`funding[${n}] must be an object`);let a=be(Number(o.time),`funding[${n}].time`);a>t||r.set(a,{time:a,fundingRate:we(o.fundingRate,`funding[${n}].fundingRate`)})}return[...r.values()].sort((n,o)=>n.time-o.time)}async function Vn({coin:e,startTime:t,endTime:r},n){let o=[],a=Math.max(0,t-288e5),i=!1;for(let s=0;s<16&&a<=r;s++){let l=await Zt({coin:e,startTime:a,endTime:r},n);if(!Array.isArray(l))throw new TypeError("Hyperliquid funding history must be an array");o.push(...l);let u=a;for(let f of l){let c=Number(f?.time);Number.isSafeInteger(c)&&c>u&&(u=c)}if(l.length<500||u>=r){i=!0;break}if(u<=a)throw new Error("Hyperliquid funding history pagination did not advance");a=u+1}if(!i)throw new Error("strategy history exceeds the bounded funding history limit");return zn(o,r)}function Jn(e,t,r){let n=0,o=null;return e.map(a=>{let i=a.t+r,s=0;for(;n<t.length&&t[n].time<i;){let l=t[n];o=l.fundingRate,l.time>=a.t&&(s+=l.fundingRate),n+=1}return o==null?{...a,fundingPaymentRate:s}:{...a,fundingRate:o,fundingPaymentRate:s}})}async function gt(e,t={}){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("strategy history input must be an object");let r=String(e.coin||"").trim().toUpperCase();if(!/^[A-Z0-9][A-Z0-9._-]{0,11}$/.test(r))throw new TypeError("coin must be an uppercase Hyperliquid asset id");let n=String(e.interval||"15m"),o=lr(n);if(e.endTime==null)throw new TypeError("endTime is required for deterministic history");let a=be(e.endTime,"endTime"),i=e.count==null?1500:e.count;if(!Number.isInteger(i)||i<20||i>5e3)throw new TypeError("count must be an integer from 20 to 5000");let s=e.startTime==null?Math.max(0,a-i*o):be(e.startTime,"startTime");if(s>=a)throw new TypeError("startTime must be before endTime");let[l,u]=await Promise.all([Xt({coin:r,interval:n,startTime:s,endTime:a},t),Vn({coin:r,startTime:s,endTime:a},t)]),f=ur(l,{endTime:a}),c=Ie(Jn(f,u,o));return Ie({coin:r,interval:n,range:{startTime:s,endTime:a},bars:c})}var Kn=new Set(["1m","3m","5m","15m","30m","1h","2h","4h","8h","12h","1d"]),Yn=new Set(["coin","interval"]);function Gn(e){let t=[];if(!e||typeof e!="object"||Array.isArray(e))return{ok:!1,errors:[{path:"market",message:"must be a plain object"}],market:null};for(let r of Object.keys(e))Yn.has(r)||t.push({path:`market.${r}`,message:"unknown field is not allowed"});return(typeof e.coin!="string"||e.coin.length===0||e.coin.length>32)&&t.push({path:"market.coin",message:"must be a non-empty string max 32"}),(typeof e.interval!="string"||!Kn.has(e.interval))&&t.push({path:"market.interval",message:"must be a supported interval"}),t.length?{ok:!1,errors:t,market:null}:{ok:!0,errors:[],market:{coin:e.coin,interval:e.interval}}}async function Xn(e={}){let t=await Gt(e);if(!t||!Array.isArray(t.universe))throw new TypeError("Hyperliquid market metadata must contain universe");return Object.freeze(t.universe.map((r,n)=>{if(!r||typeof r.name!="string"||!r.name)throw new TypeError(`Hyperliquid market metadata universe[${n}].name is invalid`);return r.name}))}var fr=Object.freeze({id:"hyperliquid",validateMarket:Gn,fetchBars:gt,listMarkets:Xn,prepareIntent(e){return yt(e)}});var Zn=Object.freeze(["id","validateMarket","prepareIntent"]);function Wn(e){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("strategy venue adapter must be an object");if(typeof e.id!="string"||!/^[a-z0-9][a-z0-9._-]{0,63}$/.test(e.id))throw new TypeError("strategy venue adapter id is malformed");for(let t of Zn.slice(1))if(typeof e[t]!="function")throw new TypeError(`strategy venue adapter ${e.id} requires ${t}()`);for(let t of["fetchBars","listMarkets"])if(e[t]!=null&&typeof e[t]!="function")throw new TypeError(`strategy venue adapter ${e.id} ${t} must be a function`);return e}var dr=[fr].map(Wn),Qn=new Map(dr.map(e=>[e.id,e])),eo=Object.freeze([...dr]);function He(e){return typeof e!="string"?null:Qn.get(e)??null}function Ue(e){let t=He(e);if(!t)throw new Error(`unknown strategy venue: ${String(e)}`);return t}var Ce=1,Sr=/^[a-z0-9][a-z0-9._-]{0,63}$/,kr=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,ro=new Set(["open","high","low","close","volume","fundingRate","openInterest"]),no=new Set(["sma","ema","rsi","macd","bollinger","atr"]),oo=new Set(["gt","gte","lt","lte","eq"]),so=new Set(["and","or","not"]),io=new Set(["above","below"]),ao=new Set(["line","signal","histogram"]),co=new Set(["upper","middle","lower"]),wt=new Set(["compare","logic","cross"]),pr=new Set(["version","id","name","venue","market","parameters","nodes","rules","risk"]),mr=new Set(["value","min","max","step"]),bt=new Set(["entryLong","entryShort","exitLong","exitShort"]),hr=new Set(["maxLeverage","maxNotionalUsd","positionSizePct","stopLossPct","takeProfitPct","cooldownBars","maxDailyLossPct","expiresAt"]),lo=new Set(["id","type"]),yr={input:new Set(["id","type","field"]),constant:new Set(["id","type","value"]),indicator:new Set(["id","type","indicator","input","period","fastPeriod","slowPeriod","signalPeriod","stdDev","output"]),compare:new Set(["id","type","op","left","right"]),logic:new Set(["id","type","op","inputs"]),cross:new Set(["id","type","direction","left","right"])},gr=16,wr=128,br=100,pe=class extends Error{constructor(t){let r=t.map(n=>`${n.path}: ${n.message}`);super(`invalid strategy (${t.length} error${t.length===1?"":"s"}): ${r.join("; ")}`),this.name="StrategyValidationError",this.errors=t}};function K(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function U(e){return typeof e=="number"&&Number.isFinite(e)}function Er(e){return Number.isInteger(e)&&e>0}function xt(e){if(e==null||typeof e!="object"||Object.isFrozen(e))return e;if(Array.isArray(e)){for(let t of e)xt(t);return Object.freeze(e)}for(let t of Object.keys(e))xt(e[t]);return Object.freeze(e)}function St(e){if(Array.isArray(e))return e.map(St);if(e!=null&&typeof e=="object"){let t={};for(let r of Object.keys(e).sort())t[r]=St(e[r]);return t}return e}function g(e,t,r){e.push({path:t,message:r})}function le(e,t,r,n){for(let o of Object.keys(e))t.has(o)||g(n,r?`${r}.${o}`:o,"unknown field is not allowed")}function Ar(e,t,r,n){if(!U(e)||!U(t)||!U(r)||!U(n)||n<=0||e<t||e>r)return!1;let o=(e-t)/n;if(!Number.isFinite(o))return!1;let a=Math.round(o);return Math.abs(o-a)<=1e-9}function Et(e,t,r,n){if(K(e)){if(le(e,new Set(["param"]),t,n),typeof e.param!="string"||!e.param)return g(n,`${t}.param`,"must be a parameter name string"),null;if(!Object.prototype.hasOwnProperty.call(r,e.param))return g(n,`${t}.param`,`unknown parameter "${e.param}"`),null;let o=r[e.param];return!K(o)||![o.value,o.min,o.max,o.step].every(Er)?(g(n,`${t}.param`,"referenced period parameter value min max and step must be positive integers"),null):{param:e.param}}return Er(e)?e:(g(n,t,"must be a positive integer or {param}"),null)}function xr(e,t,r,n){return K(e)?(le(e,new Set(["param"]),t,n),typeof e.param!="string"||!e.param?(g(n,`${t}.param`,"must be a parameter name string"),null):Object.prototype.hasOwnProperty.call(r,e.param)?{param:e.param}:(g(n,`${t}.param`,`unknown parameter "${e.param}"`),null)):U(e)?e:(g(n,t,"must be a finite number or {param}"),null)}function qe(e){switch(e.type){case"input":case"constant":return[];case"indicator":return e.input?[e.input]:[];case"compare":case"cross":return[e.left,e.right].filter(Boolean);case"logic":return Array.isArray(e.inputs)?[...e.inputs]:[];default:return[]}}function uo(e){let t=new Map,r=n=>{let o=t.get(n)||0;if(o===1)return!0;if(o===2)return!1;t.set(n,1);let a=e.get(n);if(a){for(let i of qe(a))if(e.has(i)&&r(i))return!0}return t.set(n,2),!1};for(let n of e.keys())if(r(n))return!0;return!1}function fo(e,t){if(!K(e))return g(t,"parameters","must be a plain object"),null;let r=Object.keys(e);if(r.length>gr)return g(t,"parameters",`too many parameters (max ${gr})`),null;let n={};for(let o of r){if(!Sr.test(o)){g(t,`parameters.${o}`,"parameter name is malformed");continue}let a=e[o],i=`parameters.${o}`;if(!K(a)){g(t,i,"must be a plain object");continue}le(a,mr,i,t);for(let c of mr)c in a||g(t,`${i}.${c}`,"required field is missing");let{value:s,min:l,max:u,step:f}=a;U(l)||g(t,`${i}.min`,"must be a finite number"),U(u)||g(t,`${i}.max`,"must be a finite number"),(!U(f)||f<=0)&&g(t,`${i}.step`,"must be a positive finite number"),U(s)||g(t,`${i}.value`,"must be a finite number"),U(l)&&U(u)&&l>u&&g(t,`${i}.min`,"min must be <= max"),U(s)&&U(l)&&U(u)&&U(f)&&f>0&&(Ar(s,l,u,f)||g(t,`${i}.value`,"value must lie on the declared min/max/step grid")),n[o]={value:s,min:l,max:u,step:f}}return n}function po(e,t,r,n){let o=`nodes.${t}`;if(!K(e))return g(n,o,"must be a plain object"),null;if(typeof e.type!="string"||!yr[e.type])return g(n,`${o}.type`,"unknown or missing node type"),le(e,lo,o,n),null;switch(le(e,yr[e.type],o,n),(typeof e.id!="string"||!kr.test(e.id))&&g(n,`${o}.id`,"must be a 1-64 char id starting with alphanumeric"),e.type){case"input":return(typeof e.field!="string"||!ro.has(e.field))&&g(n,`${o}.field`,"must be one of open|high|low|close|volume|fundingRate|openInterest"),{id:e.id,type:"input",field:e.field};case"constant":{let a=xr(e.value,`${o}.value`,r,n);return{id:e.id,type:"constant",value:a}}case"indicator":{(typeof e.indicator!="string"||!no.has(e.indicator))&&g(n,`${o}.indicator`,"must be one of sma|ema|rsi|macd|bollinger|atr");let a=e.indicator,i={id:e.id,type:"indicator",indicator:a};if(a==="atr"){"input"in e&&(typeof e.input!="string"||!e.input?g(n,`${o}.input`,"must be a node id string when provided"):i.input=e.input);let s=Et(e.period,`${o}.period`,r,n);s!=null&&(i.period=s)}else typeof e.input!="string"||!e.input?g(n,`${o}.input`,"must be a node id string"):i.input=e.input;if((a==="sma"||a==="ema"||a==="rsi"||a==="bollinger"||a==="atr")&&("period"in e,a!=="macd"))if(!("period"in e))g(n,`${o}.period`,"required field is missing");else{let s=Et(e.period,`${o}.period`,r,n);s!=null&&(i.period=s)}if(a==="macd"){for(let s of["fastPeriod","slowPeriod","signalPeriod"])if(!(s in e))g(n,`${o}.${s}`,"required field is missing");else{let l=Et(e[s],`${o}.${s}`,r,n);l!=null&&(i[s]=l)}"output"in e?ao.has(e.output)?i.output=e.output:g(n,`${o}.output`,"must be line|signal|histogram"):g(n,`${o}.output`,"required field is missing"),"period"in e&&g(n,`${o}.period`,"forbidden for macd"),"stdDev"in e&&g(n,`${o}.stdDev`,"forbidden for macd")}else if(a==="bollinger"){if(!("stdDev"in e))g(n,`${o}.stdDev`,"required field is missing");else{let s=xr(e.stdDev,`${o}.stdDev`,r,n);s!=null&&(typeof s=="number"&&s<=0?g(n,`${o}.stdDev`,"must be > 0"):i.stdDev=s)}"output"in e?co.has(e.output)?i.output=e.output:g(n,`${o}.output`,"must be upper|middle|lower"):g(n,`${o}.output`,"required field is missing");for(let s of["fastPeriod","slowPeriod","signalPeriod"])s in e&&g(n,`${o}.${s}`,`forbidden for ${a}`)}else{"output"in e&&g(n,`${o}.output`,`forbidden for ${a}`),"stdDev"in e&&a!=="bollinger"&&g(n,`${o}.stdDev`,`forbidden for ${a}`);for(let s of["fastPeriod","slowPeriod","signalPeriod"])s in e&&g(n,`${o}.${s}`,`forbidden for ${a}`)}return i}case"compare":return(typeof e.op!="string"||!oo.has(e.op))&&g(n,`${o}.op`,"must be gt|gte|lt|lte|eq"),(typeof e.left!="string"||!e.left)&&g(n,`${o}.left`,"must be a node id"),(typeof e.right!="string"||!e.right)&&g(n,`${o}.right`,"must be a node id"),{id:e.id,type:"compare",op:e.op,left:e.left,right:e.right};case"logic":{if((typeof e.op!="string"||!so.has(e.op))&&g(n,`${o}.op`,"must be and|or|not"),!Array.isArray(e.inputs))return g(n,`${o}.inputs`,"must be an array of node ids"),{id:e.id,type:"logic",op:e.op,inputs:[]};let a=[];for(let i=0;i<e.inputs.length;i++){let s=e.inputs[i];typeof s!="string"||!s?g(n,`${o}.inputs.${i}`,"must be a node id"):a.push(s)}return e.op==="not"?a.length!==1&&g(n,`${o}.inputs`,"not requires exactly one input"):(e.op==="and"||e.op==="or")&&a.length<2&&g(n,`${o}.inputs`,`${e.op} requires at least two inputs`),{id:e.id,type:"logic",op:e.op,inputs:a}}case"cross":return(typeof e.direction!="string"||!io.has(e.direction))&&g(n,`${o}.direction`,"must be above|below"),(typeof e.left!="string"||!e.left)&&g(n,`${o}.left`,"must be a node id"),(typeof e.right!="string"||!e.right)&&g(n,`${o}.right`,"must be a node id"),{id:e.id,type:"cross",direction:e.direction,left:e.left,right:e.right};default:return null}}function mo(e,t,r){if(!K(e))return g(t,"risk","must be a plain object"),null;le(e,hr,"risk",t);for(let d of hr)(!(d in e)||e[d]==null)&&g(t,`risk.${d}`,"required field is missing");let n={},o=e.maxLeverage;!U(o)||o<=0||o>50?g(t,"risk.maxLeverage","must be a number > 0 and <= 50"):n.maxLeverage=o;let a=e.maxNotionalUsd;!U(a)||a<=0?g(t,"risk.maxNotionalUsd","must be a number > 0"):n.maxNotionalUsd=a;let i=e.positionSizePct;!U(i)||i<=0||i>100?g(t,"risk.positionSizePct","must be a number > 0 and <= 100"):n.positionSizePct=i;let s=e.stopLossPct;!U(s)||s<=0||s>100?g(t,"risk.stopLossPct","must be a number > 0 and <= 100"):n.stopLossPct=s;let l=e.takeProfitPct;!U(l)||l<=0||l>1e3?g(t,"risk.takeProfitPct","must be a number > 0 and <= 1000"):n.takeProfitPct=l;let u=e.cooldownBars;!Number.isInteger(u)||u<0||u>1e5?g(t,"risk.cooldownBars","must be an integer >= 0 and <= 100000"):n.cooldownBars=u;let f=e.maxDailyLossPct;!U(f)||f<=0||f>100?g(t,"risk.maxDailyLossPct","must be a number > 0 and <= 100"):n.maxDailyLossPct=f;let c=e.expiresAt;return!Number.isInteger(c)||c<=0?g(t,"risk.expiresAt","must be an integer epoch milliseconds > 0"):(r.nowMs!==void 0&&(Number.isInteger(r.nowMs)?c<=r.nowMs&&g(t,"risk.expiresAt","must be strictly greater than nowMs"):g(t,"nowMs","must be an integer epoch milliseconds")),n.expiresAt=c),n}function Be(e,t={}){let r=[];if(!K(e))return g(r,"","strategy must be a plain object"),{ok:!1,errors:r,strategy:null};le(e,pr,"",r);for(let c of pr)(!(c in e)||e[c]==null)&&g(r,c,"required field is missing");e.version!==Ce&&g(r,"version",`must be ${Ce}`),(typeof e.id!="string"||!Sr.test(e.id))&&g(r,"id","must match /^[a-z0-9][a-z0-9._-]{0,63}$/"),(typeof e.name!="string"||e.name.length===0||e.name.length>br)&&g(r,"name",`must be a non-empty string max ${br}`);let n=He(e.venue);n||g(r,"venue",`unknown strategy venue "${String(e.venue)}"`);let o=null;if(!n)K(e.market)||g(r,"market","must be a plain object");else{let c=n.validateMarket(e.market);if(!c||typeof c.ok!="boolean"||!Array.isArray(c.errors))g(r,"market",`venue ${n.id} returned an invalid market validation result`);else if(c.ok)o=c.market;else for(let d of c.errors)g(r,d.path,d.message)}let a=fo(e.parameters,r),i=null,s=new Map;if(!Array.isArray(e.nodes))g(r,"nodes","must be an array");else if(e.nodes.length>wr)g(r,"nodes",`too many nodes (max ${wr})`);else{i=[];for(let c=0;c<e.nodes.length;c++){let d=po(e.nodes[c],c,a||{},r);d&&(typeof d.id=="string"&&kr.test(d.id)&&(s.has(d.id)?g(r,`nodes.${c}.id`,`duplicate node id "${d.id}"`):s.set(d.id,d)),i.push(d))}for(let c=0;c<i.length;c++){let d=i[c],m=`nodes.${c}`;for(let p of qe(d))s.has(p)||g(r,m,`unknown node ref "${p}"`);if(d.type==="indicator"||d.type==="compare"||d.type==="cross")for(let p of qe(d)){let h=s.get(p);h&&wt.has(h.type)&&g(r,m,`node ref "${p}" must be numeric`)}if(d.type==="logic")for(let p of qe(d)){let h=s.get(p);h&&!wt.has(h.type)&&g(r,m,`node ref "${p}" must be boolean`)}}uo(s)&&g(r,"nodes","graph contains a cycle")}let l=null;if(!K(e.rules))g(r,"rules","must be a plain object");else{le(e.rules,bt,"rules",r);for(let c of bt)c in e.rules||g(r,`rules.${c}`,"required field is missing");l={};for(let c of bt){let d=e.rules[c];if(d===null){l[c]=null;continue}if(typeof d!="string"||!d){g(r,`rules.${c}`,"must be a node id or null"),l[c]=d;continue}if(!s.has(d)){g(r,`rules.${c}`,`unknown node ref "${d}"`),l[c]=d;continue}let m=s.get(d);wt.has(m.type)||g(r,`rules.${c}`,`rule must reference a boolean node, not ${m.type}`),l[c]=d}}let u=mo(e.risk,r,t);if(r.length)return{ok:!1,errors:r,strategy:null};let f=xt({version:Ce,id:e.id,name:e.name,venue:n.id,market:o,parameters:a,nodes:i,rules:l,risk:u});return{ok:!0,errors:[],strategy:f}}function V(e,t={}){let r=Be(e,t);if(!r.ok)throw new pe(r.errors);return r.strategy}function Pr(e){let t=V(e);return JSON.stringify(St(t))}function fe(e){let t=Pr(e);return to("sha256").update(t,"utf8").digest("hex")}function ye(e,t){if(!K(e))throw new pe([{path:"",message:"strategy must be a plain object"}]);if(!K(t))throw new pe([{path:"overrides",message:"must be a plain object"}]);let r=V(e),n={};for(let[a,i]of Object.entries(r.parameters))n[a]={value:i.value,min:i.min,max:i.max,step:i.step};let o=[];for(let[a,i]of Object.entries(t)){if(!Object.prototype.hasOwnProperty.call(n,a)){g(o,a,`unknown parameter "${a}"`);continue}let s=n[a];if(!U(i)){g(o,a,"override must be a finite number");continue}if(!Ar(i,s.min,s.max,s.step)){g(o,a,"override must lie on the declared min/max/step grid");continue}n[a]={...s,value:i}}if(o.length)throw new pe(o);return V({version:r.version,id:r.id,name:r.name,venue:r.venue,market:{coin:r.market.coin,interval:r.market.interval},parameters:n,nodes:r.nodes.map(a=>{let i={...a};return Array.isArray(a.inputs)&&(i.inputs=[...a.inputs]),i}),rules:{...r.rules},risk:{...r.risk}})}import{createHash as ho}from"node:crypto";var At=256,$r=new Set(["netPnlUsd","profitFactor","sharpe","maxDrawdownPct"]);function Tr(e){let t=String(e).toLowerCase();return t==="holdout"||t==="test"||t==="oos"||t.includes("holdout")||t.includes("oos")?!0:t==="testbars"||t.endsWith("testbars")||t.startsWith("test")||t.endsWith("test")?!t.includes("backtest"):!1}function _r(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function Pt(e){if(e==null||typeof e!="object"||Object.isFrozen(e))return e;if(Array.isArray(e)){for(let t of e)Pt(t);return Object.freeze(e)}for(let t of Object.keys(e))Pt(e[t]);return Object.freeze(e)}function Oe(e){if(Array.isArray(e))return e.map(Oe);if(e!=null&&typeof e=="object"){let t={};for(let r of Object.keys(e).sort())t[r]=Oe(e[r]);return t}return e}function De(e){return JSON.stringify(Oe(e))}function yo(e){let{min:t,max:r,step:n}=e;if(!(n>0)||t>r)return[];let o=[],a=Math.floor((r-t)/n+1e-9);for(let s=0;s<=a;s++){let l=t+s*n;if(l>r+1e-9)break;let u=Math.abs(l-Math.round(l))<1e-9?Math.round(l):Number(l.toPrecision(12));u<t-1e-9||u>r+1e-9||o.push(u)}if(o.length===0)return[];let i=o[o.length-1];if(Math.abs(i-r)>1e-9){let s=(r-t)/n;Math.abs(s-Math.round(s))<=1e-9&&o.push(r)}return o}function go(e,t){if(e.length===0)return[];let r=[{}];for(let n of e){let o=t[n],a=[];for(let i of r)for(let s of o)a.push({...i,[n]:s});r=a}return r.sort((n,o)=>{let a=De(n),i=De(o);return a<i?-1:a>i?1:0}),r}function kt(e,t,r,n,o){let a=0;if(e==="maxDrawdownPct"){if(a=t.maxDrawdownPct-n.maxDrawdownPct,a!==0)return a<0}else if(a=t[e]-n[e],a!==0)return a>0;let i=De(r),s=De(o);return i<s}function $t(e,t,r={}){if(!_r(r))throw new TypeError("options must be a plain object");for(let x of Object.keys(r))if(Tr(x))throw new TypeError(`options must not include holdout/test/oos key "${x}"`);let n=new Set(["maxTrials","objective","backtestOptions"]);for(let x of Object.keys(r))if(!n.has(x))throw new TypeError(`unknown option "${x}"`);let o=64;if("maxTrials"in r){let x=r.maxTrials;if(!Number.isInteger(x)||x<1||x>At)throw new TypeError(`maxTrials must be an integer 1..${At}`);o=x}let a=r.objective??"netPnlUsd";if(!$r.has(a))throw new TypeError(`objective must be one of ${[...$r].join("|")}`);let i=r.backtestOptions??{};if(!_r(i))throw new TypeError("backtestOptions must be a plain object");for(let x of Object.keys(i))if(Tr(x))throw new TypeError(`backtestOptions must not include holdout/test/oos key "${x}"`);let s=V(e),l=Object.keys(s.parameters).sort();if(l.length===0)throw new Error("optimizeStrategy requires at least one declared parameter");let u={},f=1;for(let x of l){let N=yo(s.parameters[x]);if(N.length===0)throw new Error(`parameter "${x}" produces an empty grid`);u[x]=N,f*=N.length}let c=go(l,u);if(c.length===0)throw new Error("parameter grid is empty");let d=c.slice(0,o),m=[],p=null,h=null;for(let x of d){let N=ye(s,x),_=ne(N,t,i);h==null&&(h=_.config);let w={netPnlUsd:_.metrics.netPnlUsd,netPnlPct:_.metrics.netPnlPct,maxDrawdownPct:_.metrics.maxDrawdownPct,winRate:_.metrics.winRate,profitFactor:_.metrics.profitFactor,tradeCount:_.metrics.tradeCount,sharpe:_.metrics.sharpe,turnoverUsd:_.metrics.turnoverUsd},J={parameters:{...x},metrics:w};m.push(J),(!p||kt(a,w,x,p.metrics,p.parameters))&&(p=J)}m.sort((x,N)=>kt(a,x.metrics,x.parameters,N.metrics,N.parameters)?-1:kt(a,N.metrics,N.parameters,x.metrics,x.parameters)?1:0);let E={...p.parameters},k=ye(s,E),P={strategyHash:fe(s),compilerHash:ce,trainBarsHash:$e(t),backtestConfig:h,objective:a,maxTrials:o,trialsRun:m.length,candidates:m,bestParameters:E,bestStrategy:k},T={id:ho("sha256").update(JSON.stringify(Oe(P)),"utf8").digest("hex"),...P};return Pt(Oe(JSON.parse(JSON.stringify(T))))}import{createHash as wo}from"node:crypto";var B=class extends Error{constructor(t){super(t),this.name="StrategyDraftError"}},bo=new Set(["1m","3m","5m","15m","30m","1h","2h","4h","8h","12h","1d"]),Eo=new Set(["BTC","ETH","SOL","HYPE"]),xo=/\b(mnemonic|private\s*key|privkey|seed\s*phrase|seed\b|api[_-]?key|secret\s*key|wallet\s*key|passphrase)\b/i,Ee="Supported grammar: (1) EMA cross: <long|short> <COIN> when EMA <n> crosses <above|below> EMA <m> [on <interval>] [, exit on reverse] [, risk knobs]; (2) RSI: <long|short> <COIN> when RSI <n> <above|below> <threshold> [on <interval>] [, risk knobs]; (3) funding: <long|short> <COIN> when funding rate <above|below> <decimal|percent%> [on <interval>] [, risk knobs]. Risk knobs: stop loss %, take profit %, leverage, position size %, max notional USD. Coins: BTC ETH SOL HYPE or uppercase token <=12 chars. Intervals: 1m 3m 5m 15m 30m 1h 2h 4h 8h 12h 1d.",So=Object.freeze({maxLeverage:1,maxNotionalUsd:100,positionSizePct:5,stopLossPct:2,takeProfitPct:4,cooldownBars:1,maxDailyLossPct:3}),ko=36e5,Ao=30*864e5,Po=864e5;function $o(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function Tt(e){if(e==null||typeof e!="object"||Object.isFrozen(e))return e;if(Array.isArray(e)){for(let t of e)Tt(t);return Object.freeze(e)}for(let t of Object.keys(e))Tt(e[t]);return Object.freeze(e)}function To(e){return String(e).trim().replace(/\s+/g," ")}function _o(e){let t=e.match(/\b(long|short)\b/i);return t?t[1].toLowerCase():null}function Io(e){for(let r of Eo)if(new RegExp(`\\b${r}\\b`,"i").test(e))return r;let t=e.match(/\b([A-Z][A-Z0-9]{1,11})\b/);return t?t[1]:null}function Oo(e){let t=e.match(/\bon\s+(1m|3m|5m|15m|30m|1h|2h|4h|8h|12h|1d)\b/i);if(!t)return"15m";let r=t[1].toLowerCase();return bo.has(r)?r:null}function vo(e){let t={...So},r=e.match(/stop\s*loss\s*(\d+(?:\.\d+)?)\s*%?/i);r&&(t.stopLossPct=Number(r[1]));let n=e.match(/take\s*profit\s*(\d+(?:\.\d+)?)\s*%?/i);n&&(t.takeProfitPct=Number(n[1]));let o=e.match(/leverage\s*(\d+(?:\.\d+)?)/i);o&&(t.maxLeverage=Number(o[1]));let a=e.match(/position\s*size\s*(\d+(?:\.\d+)?)\s*%?/i);a&&(t.positionSizePct=Number(a[1]));let i=e.match(/max\s*notional\s*(?:usd\s*)?\$?\s*(\d+(?:\.\d+)?)/i);return i&&(t.maxNotionalUsd=Number(i[1])),t}function Mo(e){return[/\bon\s+(?:1m|3m|5m|15m|30m|1h|2h|4h|8h|12h|1d)\b/gi,/\bstop\s*loss\s*\d+(?:\.\d+)?\s*%?/gi,/\btake\s*profit\s*\d+(?:\.\d+)?\s*%?/gi,/\bleverage\s*\d+(?:\.\d+)?/gi,/\bposition\s*size\s*\d+(?:\.\d+)?\s*%?/gi,/\bmax\s*notional\s*(?:usd\s*)?\$?\s*\d+(?:\.\d+)?/gi].some(r=>(e.match(r)??[]).length>1)}function Ro(e){let t=wo("sha256").update(e,"utf8").digest("hex").slice(0,10),r=e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40),o=`${r.length?r:"draft"}-${t}`.replace(/[^a-z0-9._-]/g,"").slice(0,64);return/^[a-z0-9]/.test(o)?o:`d${o}`.slice(0,64)}function No(e){let t=e.match(/\bema\s*(\d+)\s*cross(?:es)?\s*(above|below)\s*ema\s*(\d+)\b/i);if(!t)return null;let r=Number(t[1]),n=t[2].toLowerCase(),o=Number(t[3]);if(!(r>0)||!(o>0)||r===o)return null;let a=/\b(exit\s+on\s+reverse|reverse\s+exit)\b/i.test(e);return{kind:"ema_cross",fast:r,slow:o,direction:n,reverse:a}}function Lo(e){let t=e.match(/\brsi\s*(\d+)\s*(above|below)\s*(-?\d+(?:\.\d+)?)/i);if(!t)return null;let r=Number(t[3]);return!Number.isFinite(r)||r<=0||r>=100?null:{kind:"rsi",period:Number(t[1]),op:t[2].toLowerCase(),threshold:r}}function jo(e){let t=e.match(/\bfunding\s*rate\s*(above|below)\s*(-?\d+(?:\.\d+)?)(%?)(?=\s|,|$)/i);if(!t)return null;let r=Number(t[2]);return t[3]==="%"&&(r=r/100),{kind:"funding",op:t[1].toLowerCase(),threshold:r}}function Fo(e,t){let r=e.replace(/^(long|short)\s+[A-Z][A-Z0-9]{1,11}\s+when\s+/i,"");if(r===e)return!1;t.kind==="ema_cross"?r=r.replace(/^ema\s*\d+\s*cross(?:es)?\s*(?:above|below)\s*ema\s*\d+\b/i,""):t.kind==="rsi"?r=r.replace(/^rsi\s*\d+\s*(?:above|below)\s*\d+(?:\.\d+)?\b/i,""):r=r.replace(/^funding\s*rate\s*(?:above|below)\s*-?\d+(?:\.\d+)?%?(?=\s|,|$)/i,"");let n=[/(?:,\s*)?\bon\s+(?:1m|3m|5m|15m|30m|1h|2h|4h|8h|12h|1d)\b/gi,/(?:,\s*)?\bstop\s*loss\s*\d+(?:\.\d+)?\s*%?/gi,/(?:,\s*)?\btake\s*profit\s*\d+(?:\.\d+)?\s*%?/gi,/(?:,\s*)?\bleverage\s*\d+(?:\.\d+)?/gi,/(?:,\s*)?\bposition\s*size\s*\d+(?:\.\d+)?\s*%?/gi,/(?:,\s*)?\bmax\s*notional\s*(?:usd\s*)?\$?\s*\d+(?:\.\d+)?/gi];t.kind==="ema_cross"&&n.push(/(?:,\s*)?\b(?:exit\s+on\s+reverse|reverse\s+exit)\b/gi);for(let o of n)r=r.replace(o,"");return r.replace(/[\s,;]+/g,"")===""}function Ir(e){let t=Math.max(2,Math.floor(e/2));return{value:e,min:Math.max(2,e-t),max:Math.min(500,e+t),step:1}}function Ho({side:e,coin:t,interval:r,risk:n,expiresAt:o,id:a,name:i,spec:s}){let l=[{id:"c",type:"input",field:"close"},{id:"emaLeft",type:"indicator",indicator:"ema",input:"c",period:{param:"ema_left_period"}},{id:"emaRight",type:"indicator",indicator:"ema",input:"c",period:{param:"ema_right_period"}},{id:"cross",type:"cross",direction:s.direction,left:"emaLeft",right:"emaRight"}],u={entryLong:null,entryShort:null,exitLong:null,exitShort:null};if(e==="long"?u.entryLong="cross":u.entryShort="cross",s.reverse){let f=s.direction==="above"?"below":"above";l.push({id:"crossRev",type:"cross",direction:f,left:"emaLeft",right:"emaRight"}),e==="long"?u.exitLong="crossRev":u.exitShort="crossRev"}return{version:1,id:a,name:i,venue:"hyperliquid",market:{coin:t,interval:r},parameters:{ema_left_period:Ir(s.fast),ema_right_period:Ir(s.slow)},nodes:l,rules:u,risk:{...n,expiresAt:o}}}function Uo({side:e,coin:t,interval:r,risk:n,expiresAt:o,id:a,name:i,spec:s}){let l=[{id:"c",type:"input",field:"close"},{id:"rsi",type:"indicator",indicator:"rsi",input:"c",period:s.period},{id:"thr",type:"constant",value:s.threshold},{id:"sig",type:"compare",op:s.op==="above"?"gt":"lt",left:"rsi",right:"thr"}];return{version:1,id:a,name:i,venue:"hyperliquid",market:{coin:t,interval:r},parameters:{},nodes:l,rules:{entryLong:e==="long"?"sig":null,entryShort:e==="short"?"sig":null,exitLong:null,exitShort:null},risk:{...n,expiresAt:o}}}function Co({side:e,coin:t,interval:r,risk:n,expiresAt:o,id:a,name:i,spec:s}){let l=[{id:"fr",type:"input",field:"fundingRate"},{id:"thr",type:"constant",value:s.threshold},{id:"sig",type:"compare",op:s.op==="above"?"gt":"lt",left:"fr",right:"thr"}];return{version:1,id:a,name:i,venue:"hyperliquid",market:{coin:t,interval:r},parameters:{},nodes:l,rules:{entryLong:e==="long"?"sig":null,entryShort:e==="short"?"sig":null,exitLong:null,exitShort:null},risk:{...n,expiresAt:o}}}function _t(e,t={}){if(typeof e!="string")throw new B("prompt must be a string");if(e.length>1e3)throw new B("prompt length must be <= 1000");if(!$o(t))throw new B("options must be a plain object");if(!Number.isInteger(t.nowMs))throw new B("options.nowMs is required integer epoch ms");let r=t.nowMs,n=Po;if("expiresInMs"in t){if(!Number.isInteger(t.expiresInMs))throw new B("expiresInMs must be an integer");if(n=t.expiresInMs,n<ko||n>Ao)throw new B("expiresInMs must be between 1h and 30d")}if(xo.test(e))throw new B(`prompt appears to contain secrets and is rejected. ${Ee}`);let o=To(e);if(!o)throw new B(`empty prompt. ${Ee}`);if(Mo(o))throw new B(`duplicate interval or risk clause. ${Ee}`);let a=_o(o),i=Io(o),s=Oo(o);if(!a||!i||!s)throw new B(`could not parse side/coin/interval. ${Ee}`);let l=vo(o);if(!(l.maxLeverage>0)||l.maxLeverage>50)throw new B("leverage out of range");if(!(l.positionSizePct>0)||l.positionSizePct>100)throw new B("position size out of range");let u=r+n,f=Ro(o),c=`Draft ${i} ${a}`.slice(0,100),d=No(o),m=Lo(o),p=jo(o),h=[d,m,p].filter(Boolean);if(h.length!==1)throw new B(`unsupported or ambiguous prompt. ${Ee}`);if(!Fo(o,h[0]))throw new B(`unsupported or ambiguous prompt. ${Ee}`);let E,k=h[0],P={side:a,coin:i,interval:s,risk:l,expiresAt:u,id:f,name:c,spec:k};k.kind==="ema_cross"?E=Ho(P):k.kind==="rsi"?E=Uo(P):E=Co(P);let T=Be(E,{nowMs:r});if(!T.ok)throw new B(`draft failed validation: ${T.errors.map(x=>x.message).join("; ")}`);return Tt(V(E,{nowMs:r}))}import oe from"node:fs";import ze from"node:path";var Ot=1,qo=["privatekey","secretkey","seed","mnemonic","passphrase","password","keystore","keymaterial","apikey","authtoken","accesstoken","refreshtoken","credential","bearer","signature","authorization","xprv","xpriv","wif"];function Ve(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function te(e){return e==null?e:JSON.parse(JSON.stringify(e))}function Bo(e){return String(e).toLowerCase().replace(/[^a-z0-9]/g,"")}function xe(e,t="record"){if(Array.isArray(e)){e.forEach((r,n)=>xe(r,`${t}[${n}]`));return}if(Ve(e))for(let[r,n]of Object.entries(e)){let o=Bo(r);if(qo.some(a=>o.includes(a)))throw new Error(`shadow-store: forbidden secret-like field at ${t}.${r}`);xe(n,`${t}.${r}`)}}function Do(e){if(typeof e!="string"||!e||!ze.isAbsolute(e))throw new Error("shadow-store: path must be an absolute path")}function Or(e){let t;try{t=oe.lstatSync(e)}catch(n){if(n&&n.code==="ENOENT")return;throw n}if(t.isSymbolicLink())throw new Error("shadow-store: store path must not be a symlink");if(!t.isFile())throw new Error("shadow-store: store path must be a regular file");if(t.mode&511&18)throw new Error("shadow-store: store file must not be group or world writable")}function zo(){return{version:Ot,runners:[]}}function vr(e,t){let r;try{r=JSON.parse(e)}catch{throw new Error("shadow-store: malformed JSON")}if(!Ve(r))throw new Error("shadow-store: malformed JSON root");if(r.version!==Ot)throw new Error(`shadow-store: unsupported version ${r.version}`);if(!Array.isArray(r.runners))throw new Error("shadow-store: runners must be an array");return xe(r,ze.basename(t)),{version:Ot,runners:r.runners.map(n=>te(n))}}function Mr(e,t){xe(t,"store");let r=ze.dirname(e);oe.mkdirSync(r,{recursive:!0,mode:448});let n=ze.join(r,`.shadow-store.${process.pid}.${Date.now()}.tmp`),o=`${JSON.stringify(t)}
3
- `;try{oe.writeFileSync(n,o,{mode:384,flag:"wx"}),oe.renameSync(n,e);try{oe.chmodSync(e,384)}catch{}}catch(a){try{oe.unlinkSync(n)}catch{}throw a}}var It=new Map;function vt(e={}){let t=e.path;if(Do(t),Or(t),oe.existsSync(t)?vr(oe.readFileSync(t,"utf8"),t):Mr(t,zo()),It.has(t))return It.get(t);let r=!1,n=[];function o(){if(r)return;let p=n.shift();if(p){r=!0;try{let h=p.fn();r=!1,p.resolve(h),o()}catch(h){r=!1,p.reject(h),o()}}}function a(p){if(!r&&n.length===0){r=!0;try{return p()}finally{r=!1,queueMicrotask(o)}}return new Promise((h,E)=>{n.push({fn:p,resolve:h,reject:E}),queueMicrotask(o)})}function i(){return Or(t),vr(oe.readFileSync(t,"utf8"),t)}function s(p){Mr(t,p)}function l(p){if(!Ve(p)||typeof p.id!="string"||!p.id)throw new Error("shadow-store: create requires record with string id");xe(p,"record");let h=i();if(h.runners.some(k=>k.id===p.id))throw new Error(`shadow-store: runner id already exists: ${p.id}`);let E=te(p);return h.runners.push(E),s(h),te(E)}function u(p){let h=i().runners.find(E=>E.id===p);return h?te(h):null}function f(){return i().runners.map(p=>te(p))}function c(p,h){if(typeof h!="function")throw new Error("shadow-store: updater must be a function");let E=i(),k=E.runners.findIndex(x=>x.id===p);if(k<0)throw new Error(`shadow-store: runner not found: ${p}`);let P=te(E.runners[k]),T=h(P);if(!Ve(T)||T.id!==p)throw new Error("shadow-store: updater must return record with same id");return xe(T,"record"),E.runners[k]=te(T),s(E),te(E.runners[k])}function d(p){let h=i(),E=h.runners.findIndex(P=>P.id===p);if(E<0)throw new Error(`shadow-store: runner not found: ${p}`);let k=te(h.runners[E]);return k.status!=="stopped"&&(k.status="stopped",h.runners[E]=k,s(h)),te(h.runners[E])}let m={create(p){return a(()=>l(p))},get(p){return u(p)},list(){return f()},update(p,h){return a(()=>c(p,h))},stop(p){return a(()=>d(p))}};return It.set(t,m),m}import{createHash as Nt}from"node:crypto";function Mt(e){return e==null?e:JSON.parse(JSON.stringify(e))}function Rt(e){return Array.isArray(e)?e.map(Rt):e&&typeof e=="object"?Object.fromEntries(Object.keys(e).sort().map(t=>[t,Rt(e[t])])):e}function Nr(e){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("shadow-runner: record must be an object");return Nt("sha256").update(JSON.stringify(Rt(e))).digest("hex")}function Vo(e,t,r,n,o){return Nt("sha256").update(`${e}|${t}|${r}|${n}|${o}`).digest("hex")}function Jo(e,t,r,n){return Nt("sha256").update(`shadow|${e}|${t}|${r}|${n??""}`).digest("hex")}function Ko(e){return e==="entryLong"||e==="exitShort"?"buy":e==="entryShort"||e==="exitLong"?"sell":e}function Rr(e){return e==="entryLong"||e==="entryShort"}function Je({storePath:e,clock:t=Date.now}={}){if(typeof e!="string"||!e)throw new Error("shadow-runner: storePath required");let r=vt({path:e});function n({strategy:l,evidenceId:u=null}={}){let f=z(l),c=u==null?null:String(u),d=r.list().filter(k=>k.status==="running"&&k.strategyHash===f.strategyHash&&k.compilerHash===f.compilerHash&&k.evidenceId===c).sort((k,P)=>k.createdAt-P.createdAt||k.id.localeCompare(P.id))[0];if(d)return Mt(d);let m=t(),p=Jo(m,f.strategyHash,f.compilerHash,c),h=r.get(p);if(h)return Mt(h);let E={id:p,strategy:Mt(f.strategy),strategyHash:f.strategyHash,compilerHash:f.compilerHash,evidenceId:c,status:"running",cursor:null,intendedOrders:[],fills:[],missedFills:[],markouts:[],createdAt:m,updatedAt:m,position:null,cooldownBarsRemaining:0,cooldownStartT:null,lastProcessedBarIndex:-1};return r.create(E)}function o(l){return r.get(l)}function a(){return r.list()}function i(l){return r.stop(l)}function s(l,u,{markoutHorizons:f=[1,4,12]}={}){if(!Array.isArray(u))throw new TypeError("shadow-runner: bars must be an array");return r.update(l,c=>{if(c.status!=="running")throw new Error("shadow-runner: runner is stopped");if(u.length===0)return c;let m=z(c.strategy).evaluateAll(u),p=new Map;for(let y=0;y<u.length;y++)p.set(u[y].t,y);let h=c.cursor,E=[];for(let y=0;y<u.length;y++){let A=u[y].t;(h==null||A>h)&&E.push(y)}if(E.length===0)return c;let k=new Map(c.intendedOrders.map(y=>[y.id,y])),P=new Set(c.fills.map(y=>y.orderId)),T=new Map(c.missedFills.map(y=>[y.orderId,y])),x=(y,A)=>`${y}|${A}`,N=new Map(c.markouts.map(y=>[x(y.orderId,y.horizon),y])),_=c.position?{...c.position}:null,w=Number.isInteger(c.cooldownBarsRemaining)?Math.max(0,c.cooldownBarsRemaining):0,J=Number.isFinite(c.cooldownStartT)?c.cooldownStartT:null;function se({action:y,signalBarT:A,signalIndex:v}){let L=Ko(y),j=Vo(c.id,c.strategyHash,A,L,y);if(k.has(j))return k.get(j);let I=v+1,M=I<u.length,D={id:j,action:y,type:y,side:L,signalBarT:A,fillBarT:M?u[I].t:null,status:M?"open":"missed"};return k.set(j,D),c.intendedOrders.push(D),D}function ie(y,A,v){if(P.has(y.id))return;let L={orderId:y.id,action:Rr(y.action)?"entry":"exit",side:y.side,price:A.o,barT:A.t,signalBarT:y.signalBarT,barIndex:v};if(c.fills.push(L),P.add(y.id),y.status="filled",y.fillBarT=A.t,T.has(y.id)&&(T.delete(y.id),c.missedFills=c.missedFills.filter(j=>j.orderId!==y.id)),Rr(y.action)){_={side:y.action==="entryLong"?"long":"short",entryOrderId:y.id,entryBarT:A.t,entryPrice:A.o,entryBarIndex:v};for(let j of f){let I=x(y.id,j);if(N.has(I))continue;let M={orderId:y.id,horizon:j,entryBarT:A.t,entryPrice:A.o,side:_.side,status:"pending",close:null,barT:null};N.set(I,M),c.markouts.push(M)}}else _=null,w=Number(c.strategy?.risk?.cooldownBars)||0,J=A.t}function X(y){if(P.has(y.id)||T.has(y.id))return;let A={orderId:y.id,action:y.action,side:y.side,signalBarT:y.signalBarT,status:"missed"};T.set(y.id,A),c.missedFills.push(A),y.status="missed"}for(let y of c.intendedOrders){if(y.status==="filled"||P.has(y.id))continue;let A=p.get(y.signalBarT);if(A==null)continue;let v=A+1;v<u.length&&(h==null||u[v].t>h)&&ie(y,u[v],v)}for(let y of E){let A=u[y],v=m[y].signals,L=_,j=M=>{if(_||w>0&&(J==null||A.t>=J))return;let C=se({action:M,signalBarT:A.t,signalIndex:y}),Z=y+1;Z<u.length?ie(C,u[Z],Z):X(C)},I=M=>{if(!_||_.side==="long"&&M!=="exitLong"||_.side==="short"&&M!=="exitShort")return;let D=se({action:M,signalBarT:A.t,signalIndex:y}),C=y+1;C<u.length?ie(D,u[C],C):X(D)};L?(v.exitLong&&I("exitLong"),v.exitShort&&I("exitShort")):v.entryLong&&v.entryShort||(v.entryLong&&j("entryLong"),v.entryShort&&j("entryShort")),w>0&&J!=null&&A.t>=J&&(w-=1,w===0&&(J=null)),c.cursor=A.t,c.lastProcessedBarIndex=y}for(let y of c.markouts){if(y.status!=="pending")continue;let A=c.fills.find(j=>j.orderId===y.orderId&&j.action==="entry");if(!A)continue;let v=p.get(A.barT);if(v==null)continue;let L=v+y.horizon;if(L<u.length){y.close=u[L].c,y.barT=u[L].t,y.status="filled";let j=y.entryPrice;y.markout=y.side==="long"?(y.close-j)/j:(j-y.close)/j}}return c.position=_,c.cooldownBarsRemaining=w,c.cooldownStartT=J,c.updatedAt=t(),c})}return{start:n,step:s,list:a,get:o,stop:i}}import Yo from"node:os";import Go from"node:path";var Xo=["privatekey","secretkey","seed","mnemonic","passphrase","password","keystore","keymaterial","apikey","authtoken","accesstoken","refreshtoken","credential","bearer","signature","authorization","xprv","xpriv","wif"];function ve(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function Zo(e){return String(e).toLowerCase().replace(/[^a-z0-9]/g,"")}function jt(e){if(Array.isArray(e)){for(let t of e)jt(t);return}if(ve(e))for(let[t,r]of Object.entries(e)){if(Xo.some(n=>Zo(t).includes(n)))throw new Error(`strategy service: secret-like field "${t}" is forbidden`);jt(r)}}function Wo(e){if(!ve(e))throw new TypeError("strategy input must be a plain object");return jt(e),e}function Qo(e,t){let r=t.nowMs??e.nowMs??Date.now();if(!Number.isInteger(r))throw new TypeError("nowMs must be an integer epoch milliseconds");return r}async function Lt(e,t,r,n){if(Array.isArray(t.bars))return t.bars;let o=Ue(e.venue),a=r.fetchBars??o.fetchBars;if(typeof a!="function")throw new Error(`strategy venue ${o.id} does not support history`);let i=await a({coin:e.market.coin,interval:e.market.interval,count:t.count??1500,endTime:t.endTime??n}),s=Array.isArray(i)?i:i?.bars;if(!Array.isArray(s))throw new Error("strategy history provider returned no bars");return s}function Ft(e,t){let r=e.backtestOptions??{};if(!ve(r))throw new TypeError("backtestOptions must be a plain object");return{...r,nowMs:t}}function Lr(e,t,r,n,o={}){let a=e.evidenceOptions??{};if(!ve(a))throw new TypeError("evidenceOptions must be a plain object");return{...a,...o,strategy:t,bars:r,backtestOptions:Ft(e,n)}}function jr(){return Go.join(Yo.homedir(),".oracle","strategy-shadow.json")}function es(e,t){return{perStrategyNotionalUsd:e.risk.maxNotionalUsd,maxLeverage:e.risk.maxLeverage,dailyLossCapUsd:e.risk.maxNotionalUsd*(e.risk.maxDailyLossPct/100),chainAllowlist:[e.venue],assetAllowlist:[e.market.coin],expiresAt:Math.min(e.risk.expiresAt,t+864e5),killSwitchRequired:!0}}async function ts(e,t={},r={}){let n=Wo(t),o=Qo(n,r);if(e==="draft")return{strategy:_t(n.prompt,{nowMs:o})};if(e==="validate"){let a=z(n.strategy);if(a.strategy.risk.expiresAt<=o)throw new Error("strategy is expired");return{valid:!0,strategy:a.strategy,strategyHash:a.strategyHash,compilerHash:a.compilerHash,compilerVersion:a.compilerVersion,requiredSeries:a.requiredSeries}}if(e==="backtest"||e==="evidence"){let a=z(n.strategy),i=await Lt(a.strategy,n,r,o);Te(a,i);let s=Fe(Lr(n,a.strategy,i,o));return e==="evidence"?s:{backtest:ne(a.strategy,i,Ft(n,o)),evidence:s}}if(e==="optimize"){let a=z(n.strategy),i=await Lt(a.strategy,n,r,o);Te(a,i);let s=n.trainFraction,l=n.evidenceOptions?.trainFraction;if(s!=null&&l!=null&&s!==l)throw new TypeError("conflicting trainFraction controls are forbidden");let u=s??l??.7;if(typeof u!="number"||u<=0||u>=1)throw new TypeError("trainFraction must be in (0,1)");let f=i.slice(0,Math.floor(i.length*u)),c=n.options??{};if(!ve(c))throw new TypeError("options must be a plain object");let d=$t(a.strategy,f,{...c,...n.maxTrials==null?{}:{maxTrials:n.maxTrials},backtestOptions:Ft(n,o)}),m=d.bestStrategy;return{strategy:m,optimization:d,evidence:Fe(Lr(n,m,i,o,{trainFraction:u}))}}if(e==="shadow"){let a=Je({storePath:r.storePath??jr(),clock:()=>o}),i=n.action;if(i==="start")return await a.start({strategy:n.strategy,evidenceId:n.evidenceId??n.evidence?.id??null});if(i==="list")return await a.list();if(i==="get")return await a.get(n.id);if(i==="stop")return await a.stop(n.id);if(i==="step"){let s=await a.get(n.id);if(!s)throw new Error(`shadow runner not found: ${n.id}`);let l=await Lt(s.strategy,n,r,o);return Te(z(s.strategy),l),await a.step(n.id,l,n.stepOptions??{})}throw new Error(`unknown shadow action: ${i}`)}if(e==="prepare"){let a=z(n.strategy),i=Ue(a.strategy.venue);if(typeof n.shadowId!="string"||!n.shadowId)throw new Error("strategy prepare requires a matching shadow runner id");let l=await Je({storePath:r.storePath??jr(),clock:()=>o}).get(n.shadowId);if(!l)throw new Error("strategy prepare shadow runner not found");if(l.status!=="running")throw new Error("strategy prepare requires an active shadow runner");if(!Number.isFinite(l.cursor))throw new Error("strategy prepare requires a stepped shadow runner");if(l.strategyHash!==a.strategyHash||l.compilerHash!==a.compilerHash)throw new Error("strategy prepare shadow runner does not match strategy artifacts");if(l.evidenceId!==n.evidence?.id)throw new Error("strategy prepare shadow runner does not match evidence artifact");let u=n.caps??es(a.strategy,o);return i.prepareIntent({strategy:a.strategy,evidence:n.evidence,shadow:{id:l.id,stateHash:Nr(l),status:l.status,cursor:l.cursor,updatedAt:l.updatedAt},caps:u,nowMs:o,env:r.env??process.env})}throw new Error(`unknown strategy operation: ${e}`)}export{or as EVIDENCE_STATUSES,At as MAX_OPTIMIZER_TRIALS,ce as STRATEGY_COMPILER_HASH,he as STRATEGY_COMPILER_VERSION,Ce as STRATEGY_VERSION,B as StrategyDraftError,pe as StrategyValidationError,ye as applyParameterOverrides,dt as assertEvidenceArtifact,ot as atr,ne as backtestStrategy,nt as bollinger,Pr as canonicalStrategyJson,z as compileStrategy,ft as computeEvidenceArtifactId,Je as createShadowRunner,_t as draftStrategyFromPrompt,Ae as ema,Fe as evaluateEvidence,gt as fetchHyperliquidStrategyBars,lr as intervalToMs,rt as macd,ur as normalizeHyperliquidCandles,V as normalizeStrategy,vt as openShadowStore,$t as optimizeStrategy,yt as prepareStrategyLiveHandoff,Ue as requireStrategyVenue,He as resolveStrategyVenue,tt as rsi,ts as runStrategyOperation,et as sma,fe as strategyHash,eo as strategyVenues,Be as validateStrategy};
2
+ `),s=Dr("sha256").update(i).digest("hex").slice(0,32);return`${e} ${t} ${s}`}function Wr(e,t){let r=Number(t);return Number.isFinite(r)&&r>0?Math.min(r*1e3,Vt):Math.min(250*2**e,Vt)+Math.floor(Math.random()*100)}var Qr=e=>new Promise(t=>setTimeout(t,e));async function en(e,{fetchImpl:t,method:r,headers:n,body:o,timeoutMs:a}){let i=new AbortController,s=setTimeout(()=>i.abort(),a);try{let l=String(e),u={...n||{}};for(let f=0;f<=Jt;f+=1){let c=await t(l,{method:r,headers:u,body:o,signal:i.signal,redirect:"manual"}),d=await c.text(),m=null;if(d)try{m=JSON.parse(d)}catch{m=null}if(Jr.has(c.status)){if(r!=="GET"&&r!=="HEAD"){let h=new Error(`HTTP ${c.status} ${r} ${l} redirected non-idempotent request`);throw h.status=c.status,h.body=m??d.slice(0,300),h}if(f===Jt)throw new Error(`HTTP redirect loop for ${e}`);let p=Gr(c.headers?.get?.("location"),l);Xr(p,l)||(u=Yr(u)),l=p;continue}if(!c.ok){let p=new Error(`HTTP ${c.status} ${r} ${l}`);throw p.status=c.status,p.retryAfter=c.headers?.get?.("retry-after")??null,p.body=m??d.slice(0,300),p}return m??d}throw new Error(`HTTP redirect loop for ${e}`)}finally{clearTimeout(s)}}async function Yt(e,t={}){let r=t.fetchImpl||globalThis.fetch;if(typeof r!="function")throw new Error("fetch unavailable \u2014 pass opts.fetchImpl");let n=t.timeoutMs??12e3,o=(t.method||"GET").toUpperCase(),a={Accept:"application/json",...t.headers||{}},i=t.body;i!=null&&typeof i!="string"&&(a["Content-Type"]=a["Content-Type"]||"application/json",i=JSON.stringify(i));let s=Number.isInteger(t.retries)?Math.max(t.retries,0):Vr,l=async()=>{let m;for(let p=0;p<=s;p++)try{return await en(e,{fetchImpl:r,method:o,headers:a,body:i,timeoutMs:n})}catch(h){m=h;let E=h?.status,k=h?.name==="AbortError",P=new Set([408,425,429]),T=E!=null?P.has(E)||zr.has(E)&&zt.has(o):!k&&zt.has(o);if(p===s||!T)throw h;await Qr(Wr(p,h?.retryAfter))}throw m};if(!(t.dedupe!==!1&&o==="GET"&&i==null))return l();let f=Zr(o,e,a),c=We.get(f);if(c)return c;let d=l().finally(()=>We.delete(f));return We.set(f,d),d}var tn="https://api.hyperliquid.xyz/info",rn="https://api.hyperliquid-testnet.xyz/info";function nn({testnet:e,baseUrl:t}={}){if(t)return t.replace(/\/$/,"").endsWith("/info")?t:`${t.replace(/\/$/,"")}/info`;if(process.env.HL_INFO_URL)return process.env.HL_INFO_URL;if(process.env.HL_API_URL){let r=process.env.HL_API_URL.replace(/\/$/,"");return r.endsWith("/info")?r:`${r}/info`}return e||process.env.HL_TESTNET==="1"?rn:tn}async function Qe(e,t={}){if(!e||!e.type)throw new Error("hlInfo requires body.type");let r=nn(t);return Yt(r,{method:"POST",body:e,fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs})}async function Gt(e={}){return Qe({type:"meta"},e)}async function Xt({coin:e,interval:t="1h",startTime:r,endTime:n},o={}){if(!e)throw new Error("hlCandleSnapshot requires coin");let a={type:"candleSnapshot",req:{coin:String(e),interval:t,startTime:r??Date.now()-24*3600*1e3,endTime:n??Date.now()}};return Qe(a,o)}async function Zt({coin:e,startTime:t,endTime:r},n={}){if(!e)throw new Error("hlFundingHistory requires coin");return Qe({type:"fundingHistory",coin:String(e),startTime:t??Date.now()-24*3600*1e3,endTime:r??Date.now()},n)}function Pe(e){if(!Array.isArray(e))throw new TypeError("values must be an array");for(let t=0;t<e.length;t++){let r=e[t];if(typeof r!="number"||!Number.isFinite(r))throw new TypeError(`values[${t}] must be a finite number`)}}function ae(e){if(!Number.isInteger(e)||e<=0)throw new TypeError("period must be a positive integer")}function on(e){if(!Array.isArray(e))throw new TypeError("bars must be an array");for(let t=0;t<e.length;t++){let r=e[t];if(r==null||typeof r!="object")throw new TypeError(`bars[${t}] must be an object`);for(let n of["o","h","l","c"]){let o=r[n];if(typeof o!="number"||!Number.isFinite(o))throw new TypeError(`bars[${t}].${n} must be a finite number`)}if(r.h<r.l)throw new TypeError(`bars[${t}] high must be >= low`)}}function et(e,t){Pe(e),ae(t);let r=new Array(e.length).fill(null);if(e.length<t)return r;let n=0;for(let o=0;o<e.length;o++)n+=e[o],o>=t&&(n-=e[o-t]),o>=t-1&&(r[o]=n/t);return r}function Ae(e,t){Pe(e),ae(t);let r=new Array(e.length).fill(null);if(e.length<t)return r;let n=0;for(let i=0;i<t;i++)n+=e[i];let o=n/t;r[t-1]=o;let a=2/(t+1);for(let i=t;i<e.length;i++)o=a*e[i]+(1-a)*o,r[i]=o;return r}function tt(e,t){Pe(e),ae(t);let r=new Array(e.length).fill(null);if(e.length<=t)return r;let n=0,o=0;for(let s=1;s<=t;s++){let l=e[s]-e[s-1];l>=0?n+=l:o-=l}let a=n/t,i=o/t;r[t]=Wt(a,i);for(let s=t+1;s<e.length;s++){let l=e[s]-e[s-1],u=l>0?l:0,f=l<0?-l:0;a=(a*(t-1)+u)/t,i=(i*(t-1)+f)/t,r[s]=Wt(a,i)}return r}function Wt(e,t){return e===0&&t===0?50:t===0?100:e===0?0:100-100/(1+e/t)}function rt(e,t={}){Pe(e);let r=t.fastPeriod,n=t.slowPeriod,o=t.signalPeriod;if(ae(r),ae(n),ae(o),r>=n)throw new TypeError("fastPeriod must be < slowPeriod");let a=Ae(e,r),i=Ae(e,n),s=new Array(e.length).fill(null);for(let c=0;c<e.length;c++)a[c]!=null&&i[c]!=null&&(s[c]=a[c]-i[c]);let l=new Array(e.length).fill(null),u=new Array(e.length).fill(null),f=[];for(let c=0;c<s.length;c++)s[c]!=null&&f.push(c);if(f.length>=o){let c=0;for(let h=0;h<o;h++)c+=s[f[h]];let d=c/o,m=f[o-1];l[m]=d,u[m]=s[m]-d;let p=2/(o+1);for(let h=o;h<f.length;h++){let E=f[h];d=p*s[E]+(1-p)*d,l[E]=d,u[E]=s[E]-d}}return{line:s,signal:l,histogram:u}}function nt(e,t={}){Pe(e);let r=t.period,n=t.stdDev;if(ae(r),typeof n!="number"||!Number.isFinite(n)||n<=0)throw new TypeError("stdDev must be a finite number > 0");let o=new Array(e.length).fill(null),a=new Array(e.length).fill(null),i=new Array(e.length).fill(null);if(e.length<r)return{upper:a,middle:o,lower:i};let s=0,l=0;for(let u=0;u<e.length;u++){let f=e[u];if(s+=f,l+=f*f,u>=r){let c=e[u-r];s-=c,l-=c*c}if(u>=r-1){let c=s/r,d=l/r-c*c;d<0&&d>-1e-12&&(d=0);let m=Math.sqrt(d);o[u]=c,a[u]=c+n*m,i[u]=c-n*m}}return{upper:a,middle:o,lower:i}}function ot(e,t){on(e),ae(t);let r=new Array(e.length).fill(null);if(e.length<t)return r;let n=new Array(e.length);for(let i=0;i<e.length;i++){let s=e[i];if(i===0)n[i]=s.h-s.l;else{let l=e[i-1].c;n[i]=Math.max(s.h-s.l,Math.abs(s.h-l),Math.abs(s.l-l))}}let o=0;for(let i=0;i<t;i++)o+=n[i];let a=o/t;r[t-1]=a;for(let i=t;i<e.length;i++)a=(a*(t-1)+n[i])/t,r[i]=a;return r}import{createHash as sn}from"node:crypto";var st=2,an="93f9c998260e73756c13871dc1a84dd6cdb26ec6113bd1941f023519939db440",cn="68f5b412a9975f04024cf9b9b6209b4bccedd52f176e95f34f786b3f53479c6a",ln="f197a38ff1c0f4ebe13326db8cbb8167ea3dd5d62e6033fe97c2fee8d23d96b5",Qt=sn("sha256").update(JSON.stringify({version:st,compilerSourceHash:an,indicatorsSourceHash:cn,schemaSourceHash:ln})).digest("hex");var he=st,ce=Qt,un=Object.freeze({open:"o",high:"h",low:"l",close:"c",volume:"v",fundingRate:"fundingRate",openInterest:"openInterest"}),fn=Object.freeze({"1m":6e4,"3m":18e4,"5m":3e5,"15m":9e5,"30m":18e5,"1h":36e5,"2h":72e5,"4h":144e5,"8h":288e5,"12h":432e5,"1d":864e5});function Y(e){return typeof e=="number"&&Number.isFinite(e)}function dn(e){let t=new Map(e.map(s=>[s.id,s])),r=s=>{switch(s.type){case"indicator":return s.input?[s.input]:[];case"compare":case"cross":return[s.left,s.right];case"logic":return[...s.inputs];default:return[]}},n=new Map,o=new Map;for(let s of e)n.set(s.id,0),o.set(s.id,[]);for(let s of e)for(let l of r(s))t.has(l)&&(o.get(l).push(s.id),n.set(s.id,n.get(s.id)+1));let a=[];for(let[s,l]of n)l===0&&a.push(s);let i=[];for(;a.length;){let s=a.shift();i.push(s);for(let l of o.get(s))n.set(l,n.get(l)-1),n.get(l)===0&&a.push(l)}if(i.length!==e.length)throw new Error("strategy graph is cyclic");return i}function me(e,t){return e!=null&&typeof e=="object"&&"param"in e?t[e.param].value:e}function pn(e,t,r){if(!Array.isArray(e)||e.length===0)throw new TypeError("bars must be a non-empty array");if(!Number.isInteger(t)||t<0||t>=e.length)throw new RangeError("index out of range");let n=null;for(let o=0;o<=t;o++){let a=e[o];if(a==null||typeof a!="object"||Array.isArray(a))throw new TypeError(`bars[${o}] must be an object`);let{t:i,o:s,h:l,l:u,c:f,v:c}=a;if(!Y(i)&&(typeof i=="number"&&Number.isFinite(i)),!Number.isFinite(i))throw new TypeError(`bars[${o}].t must be finite`);for(let[d,m]of[["o",s],["h",l],["l",u],["c",f],["v",c]])if(!Y(m))throw new TypeError(`bars[${o}].${d} must be a finite number`);for(let[d,m]of[["o",s],["h",l],["l",u],["c",f]])if(!(m>0))throw new TypeError(`bars[${o}].${d} price must be positive`);if(c<0)throw new TypeError(`bars[${o}].v volume must be non-negative`);if(l<Math.max(s,f,u))throw new TypeError(`bars[${o}] high must be >= max(open, close, low)`);if(u>Math.min(s,f,l))throw new TypeError(`bars[${o}] low must be <= min(open, close, high)`);if(n!=null){if(!(i>n))throw new TypeError("bars t must be strictly increasing");if(i-n!==fn[r])throw new TypeError(`bars t must match ${r} cadence`)}if(n=i,"fundingRate"in a&&a.fundingRate!=null&&!Y(a.fundingRate))throw new TypeError(`bars[${o}].fundingRate must be finite when present`);if("openInterest"in a&&a.openInterest!=null){if(!Y(a.openInterest))throw new TypeError(`bars[${o}].openInterest must be finite when present`);if(a.openInterest<0)throw new TypeError(`bars[${o}].openInterest must be non-negative`)}}}function ue(e,t,r,n,o,a){if(a.has(e))return a.get(e);let i=t.get(e),s;switch(i.type){case"input":{let l=un[i.field];s=new Array(o+1);for(let u=0;u<=o;u++){let f=n[u][l];s[u]=f===void 0?null:f}break}case"constant":{let l=me(i.value,r);s=new Array(o+1).fill(l);break}case"indicator":{let l=i.period!=null?me(i.period,r):void 0;if(i.indicator==="atr"){let c=[];for(let d=0;d<=o;d++){let m=n[d];c.push({o:m.o,h:m.h,l:m.l,c:m.c})}s=ot(c,l);break}let f=ue(i.input,t,r,n,o,a).map((c,d)=>{if(c==null||!Y(c))throw new TypeError(`indicator input ${i.input} has non-finite value at ${d}`);return c});if(i.indicator==="sma")s=et(f,l);else if(i.indicator==="ema")s=Ae(f,l);else if(i.indicator==="rsi")s=tt(f,l);else if(i.indicator==="macd")s=rt(f,{fastPeriod:me(i.fastPeriod,r),slowPeriod:me(i.slowPeriod,r),signalPeriod:me(i.signalPeriod,r)})[i.output];else if(i.indicator==="bollinger")s=nt(f,{period:l,stdDev:me(i.stdDev,r)})[i.output];else throw new Error(`unsupported indicator ${i.indicator}`);break}case"compare":{let l=ue(i.left,t,r,n,o,a),u=ue(i.right,t,r,n,o,a);s=new Array(o+1);for(let f=0;f<=o;f++){let c=l[f],d=u[f];if(c==null||d==null||!Y(c)||!Y(d)){s[f]=!1;continue}switch(i.op){case"gt":s[f]=c>d;break;case"gte":s[f]=c>=d;break;case"lt":s[f]=c<d;break;case"lte":s[f]=c<=d;break;case"eq":s[f]=c===d;break;default:s[f]=!1}}break}case"logic":{let l=i.inputs.map(u=>ue(u,t,r,n,o,a));s=new Array(o+1);for(let u=0;u<=o;u++)if(i.op==="not"){let f=l[0][u];s[u]=f===!0?!1:f===!1}else if(i.op==="and"){let f=!0;for(let c of l)if(c[u]!==!0){f=!1;break}s[u]=f}else if(i.op==="or"){let f=!1;for(let c of l)if(c[u]===!0){f=!0;break}s[u]=f}else s[u]=!1;break}case"cross":{let l=ue(i.left,t,r,n,o,a),u=ue(i.right,t,r,n,o,a);s=new Array(o+1),s[0]=!1;for(let f=1;f<=o;f++){let c=l[f-1],d=u[f-1],m=l[f],p=u[f];if(c==null||d==null||m==null||p==null||!Y(c)||!Y(d)||!Y(m)||!Y(p)){s[f]=!1;continue}i.direction==="above"?s[f]=c<=d&&m>p:s[f]=c>=d&&m<p}break}default:throw new Error(`unknown node type ${i.type}`)}return a.set(e,s),s}function z(e,t={}){let r=V(e);t&&Object.keys(t).length&&(r=ye(r,t));let n=new Map(r.nodes.map(m=>[m.id,m])),o=Object.freeze(dn(r.nodes)),a=r.parameters,i=new Set(r.nodes.filter(m=>m.type==="input").map(m=>m.field));if(r.nodes.some(m=>m.type==="indicator"&&m.indicator==="atr"))for(let m of["open","high","low","close"])i.add(m);let s=Object.freeze([...i].sort()),l=fe(r);function u(m,p){let h={};for(let k of o){let P=m.get(k);h[k]=P[p]}let E=k=>k!=null&&h[k]===!0;return{values:h,signals:{entryLong:E(r.rules.entryLong),entryShort:E(r.rules.entryShort),exitLong:E(r.rules.exitLong),exitShort:E(r.rules.exitShort)}}}function f(m,p){pn(m,p,r.market.interval);let h=new Map;for(let E of o)ue(E,n,a,m,p,h);return h}function c(m,p){return u(f(m,p),p)}function d(m){if(!Array.isArray(m)||m.length===0)throw new TypeError("bars must be a non-empty array");let p=m.length-1,h=f(m,p);return Object.freeze(m.map((E,k)=>Object.freeze(u(h,k))))}return Object.freeze({strategy:r,strategyHash:l,compilerVersion:he,compilerHash:ce,requiredSeries:s,nodeOrder:o,evaluate:c,evaluateAll:d})}import{createHash as In}from"node:crypto";import{createHash as mn}from"node:crypto";var hn=Object.freeze({initialEquityUsd:1e4,takerFeeBps:3.5,builderFeeBps:2,slippageBps:2,latencyBars:1,maxVolumeParticipationPct:100});function yn(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function Q(e){return typeof e=="number"&&Number.isFinite(e)}function it(e){if(e==null||typeof e!="object"||Object.isFrozen(e))return e;if(Array.isArray(e)){for(let t of e)it(t);return Object.freeze(e)}for(let t of Object.keys(e))it(e[t]);return Object.freeze(e)}function Le(e){if(Array.isArray(e))return e.map(Le);if(e!=null&&typeof e=="object"){let t={};for(let r of Object.keys(e).sort())t[r]=Le(e[r]);return t}return e}function at(e,t="result"){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`non-finite backtest result at ${t}`);return}if(!(e==null||typeof e!="object")){if(Array.isArray(e)){e.forEach((r,n)=>at(r,`${t}[${n}]`));return}for(let[r,n]of Object.entries(e))at(n,`${t}.${r}`)}}function tr(e){if(!Array.isArray(e)||e.length===0)throw new TypeError("bars must be a non-empty array");let t=null;for(let r=0;r<e.length;r++){let n=e[r];if(n==null||typeof n!="object"||Array.isArray(n))throw new TypeError(`bars[${r}] must be an object`);let{t:o,o:a,h:i,l:s,c:l,v:u}=n;if(!Q(o))throw new TypeError(`bars[${r}].t must be finite`);for(let[f,c]of[["o",a],["h",i],["l",s],["c",l],["v",u]])if(!Q(c))throw new TypeError(`bars[${r}].${f} must be a finite number`);for(let[f,c]of[["o",a],["h",i],["l",s],["c",l]])if(!(c>0))throw new TypeError(`bars[${r}].${f} price must be positive`);if(u<0)throw new TypeError(`bars[${r}].v volume must be non-negative`);if(i<Math.max(a,l,s))throw new TypeError(`bars[${r}] high must be >= max(open, close, low)`);if(s>Math.min(a,l,i))throw new TypeError(`bars[${r}] low must be <= min(open, close, high)`);if(t!=null&&!(o>t))throw new TypeError("bars t must be strictly increasing");if(t=o,"fundingRate"in n&&n.fundingRate!=null&&!Q(n.fundingRate))throw new TypeError(`bars[${r}].fundingRate must be finite when present`);if("fundingPaymentRate"in n&&n.fundingPaymentRate!=null&&!Q(n.fundingPaymentRate))throw new TypeError(`bars[${r}].fundingPaymentRate must be finite when present`);if("openInterest"in n&&n.openInterest!=null&&!Q(n.openInterest))throw new TypeError(`bars[${r}].openInterest must be finite when present`)}}function $e(e){if(!Array.isArray(e))throw new TypeError("bars must be an array");return e.length>0&&tr(e),mn("sha256").update(JSON.stringify(Le(e)),"utf8").digest("hex")}function wn(e){if(e==null&&(e={}),!yn(e))throw new TypeError("options must be a plain object");let t={...hn},r=new Set(["initialEquityUsd","takerFeeBps","builderFeeBps","slippageBps","latencyBars","maxVolumeParticipationPct","nowMs"]);for(let n of Object.keys(e))if(!r.has(n))throw new TypeError(`unknown option "${n}"`);if("initialEquityUsd"in e){if(!Q(e.initialEquityUsd)||e.initialEquityUsd<=0)throw new TypeError("initialEquityUsd must be a positive finite number");t.initialEquityUsd=e.initialEquityUsd}for(let n of["takerFeeBps","builderFeeBps","slippageBps"])if(n in e){let o=e[n];if(!Q(o)||o<0)throw new TypeError(`${n} must be a finite number >= 0`);if(n==="slippageBps"?o>=1e4:o>1e4)throw new TypeError(`${n} exceeds its safe basis-point bound`);t[n]=o}if("latencyBars"in e){let n=e.latencyBars;if(!Number.isInteger(n)||n<1)throw new TypeError("latencyBars must be an integer >= 1");t.latencyBars=n}if("maxVolumeParticipationPct"in e){let n=e.maxVolumeParticipationPct;if(!Q(n)||n<=0||n>100)throw new TypeError("maxVolumeParticipationPct must be in (0,100]");t.maxVolumeParticipationPct=n}if("nowMs"in e){if(!Number.isInteger(e.nowMs))throw new TypeError("nowMs must be an integer epoch milliseconds");t.nowMs=e.nowMs}return t}function je(e){return e/1e4}function gn(e,t,r){let n=je(r);return t==="long"?e*(1+n):e*(1-n)}function bn(e,t,r){let n=je(r);return t==="long"?e*(1-n):e*(1+n)}function er(e,t,r){let n=Math.abs(e)*je(t),o=Math.abs(e)*je(r);return{taker:n,builder:o,total:n+o}}function En(e,t){let r=e*(t.positionSizePct/100)*t.maxLeverage;return Math.min(r,t.maxNotionalUsd)}function xn(e,t,r){let n=r/100;return t==="long"?e*(1-n):e*(1+n)}function Sn(e,t,r){let n=r/100;return t==="long"?e*(1+n):e*(1-n)}function kn(e,t,r,n){if(!(r>0))return t==="long"?0:Number.POSITIVE_INFINITY;let o=Math.min(.99,1/(2*r)+n/1e4);return t==="long"?e*(1-1/r)/(1-o):e*(1+1/r)/(1+o)}function An(e,t,r){return t==="long"?e.l<=r:e.h>=r}function Pn(e,t,r){return t==="long"?e.h>=r:e.l<=r}function $n(e,t,r){return t==="long"?e.l<=r:e.h>=r}function Te(e,t){for(let r of e.requiredSeries)if(["fundingRate","openInterest"].includes(r)&&!t.every(n=>Q(n?.[r])))throw new Error(`strategy required series is absent: ${r}`)}function Tn(e){if(e.length<3)return 0;let t=[];for(let i=1;i<e.length;i++){let s=e[i-1].equity,l=e[i].equity;s>0&&t.push((l-s)/s)}if(t.length<2)return 0;let r=0;for(let i of t)r+=i;let n=r/t.length,o=0;for(let i of t)o+=(i-n)**2;let a=Math.sqrt(o/(t.length-1));return a>0?n/a:0}function _n(e){let t=-1/0,r=0;for(let n of e){let o=n.equity;if(o>t&&(t=o),t>0){let a=(t-o)/t*100;a>r&&(r=a)}}return r}function ne(e,t,r={}){let n=wn(r);tr(t);let o=$e(t);n.nowMs!==void 0&&V(e,{nowMs:n.nowMs});let a=z(e);if(Te(a,t),n.nowMs!==void 0&&a.strategy.risk.expiresAt<=n.nowMs)throw new Error("strategy is expired: risk.expiresAt must be strictly greater than nowMs");let i=a.strategy.risk,s=a.evaluateAll(t),l=n.latencyBars,u=n.slippageBps,f=n.takerFeeBps,c=n.builderFeeBps,d=n.initialEquityUsd,m=0,p=0,h=0,E=0,k=0,P=[],T=[],x=[],R=[],_=[],g=null,J=0,se=null,ie=d,X=!1,y=0,A=0,v=[],L=new Array(t.length).fill(0);function j(b){v.push(b)}function I(b){let $=t[b].v*(n.maxVolumeParticipationPct/100);return Math.max(0,$-L[b])}function M(b){if(!g)return d;let $=g.side==="long"?(b-g.entryPrice)*g.qty:(g.entryPrice-b)*g.qty;return d+$}function D(b,$,S){let F=S.o,O=En(d,i);if(!(O>0)||!(F>0))return;let H=gn(F,$,u),N=O/H,q=I(b),Se=H*q;if(N>q){x.push({kind:"entry",barIndex:b,time:S.t,side:$,requestedNotionalUsd:O,maxFillNotionalUsd:Se,reason:"volume_participation"});return}L[b]+=N;let W=Math.abs(H-F)*N,re=er(O,f,c);d-=re.total,m+=re.taker,p+=re.builder,E+=W,k+=O,g={lifecycleEpoch:++A,side:$,entryBarIndex:b,entryReferencePrice:F,entryPrice:H,qty:N,notionalUsd:O,stop:xn(H,$,i.stopLossPct),take:Sn(H,$,i.takeProfitPct),liq:kn(H,$,i.maxLeverage,f+c),entryFees:re.taker,entryBuilderFees:re.builder,entrySlippageUsd:W,fundingAccrued:0}}function C(b,$,S,F){if(!g)return!1;let O=g.side,H=$,N=H;S!=="liquidation"&&F&&(N=bn(H,O,u));let q=g.qty,Se=q*N;if(S!=="liquidation"){let Dt=I(b),Br=N*Dt;if(q>Dt)return x.push({kind:"exit",barIndex:b,time:t[b].t,side:O,requestedNotionalUsd:Se,maxFillNotionalUsd:Br,reason:"volume_participation",triggerReason:S}),!1;L[b]+=q}let W=er(Se,f,c),re=S==="liquidation"?0:Math.abs(N-H)*q,ke,Ze;O==="long"?(ke=(H-g.entryReferencePrice)*q,Ze=(N-g.entryPrice)*q):(ke=(g.entryReferencePrice-H)*q,Ze=(g.entryPrice-N)*q),d+=Ze,d-=W.total,m+=W.taker,p+=W.builder,E+=re,k+=Se;let qr={side:O,entryBarIndex:g.entryBarIndex,entryTime:t[g.entryBarIndex].t,entryPrice:g.entryPrice,exitBarIndex:b,exitTime:t[b].t,exitPrice:N,exitReason:S,qty:q,notionalUsd:g.notionalUsd,grossPnlUsd:ke,feesUsd:g.entryFees+W.taker,builderFeesUsd:g.entryBuilderFees+W.builder,fundingUsd:g.fundingAccrued,slippageUsd:g.entrySlippageUsd+re,netPnlUsd:ke-(g.entryFees+W.taker+g.entryBuilderFees+W.builder)-g.fundingAccrued-(g.entrySlippageUsd+re)};return P.push(qr),S==="liquidation"&&T.push({barIndex:b,time:t[b].t,side:O,price:N,tradeIndex:P.length-1}),g=null,A+=1,y=b+1+(i.cooldownBars||0),!0}function Z(b,$,S,F){let O=b+1;if(O>=t.length)return;v.some(N=>N.kind==="exit"&&N.side===$&&N.fillBar===O&&N.epoch===F)||j({kind:"exit",side:$,signalBar:b,fillBar:O,reason:S,epoch:F})}function Me(b){let $=v.filter(S=>S.fillBar===b);for(let S=v.length-1;S>=0;S--)v[S].fillBar===b&&v.splice(S,1);$.sort((S,F)=>{let O=H=>H.kind==="exit"?0:1;return O(S)-O(F)});for(let S of $)if(S.kind==="exit"){if(!g||g.side!==S.side||g.lifecycleEpoch!==S.epoch)continue;let F=S.reason||"rule";C(b,t[b].o,F,!0)||Z(b,S.side,F,S.epoch)}else if(S.kind==="entry"){if(g||S.epoch!==A||b<y)continue;D(b,S.side,t[b])}}function Ne(b){if(!g)return;let $=t[b],S=$.fundingPaymentRate;if(S==null||!Q(S)||S===0)return;let F=Math.abs(g.qty*$.c),O=S*F;g.side==="long"?(d-=O,g.fundingAccrued+=O,h+=O):(d+=O,g.fundingAccrued-=O,h-=O)}function Re(b){if(!g)return;let $=t[b].o;(g.side==="long"?$<=g.liq:$>=g.liq)&&C(b,$,"liquidation",!1)}function Ht(b){if(!g)return;let $=t[b],S=g.side,F=$n($,S,g.liq),O=An($,S,g.stop),H=Pn($,S,g.take),N=q=>S==="long"?Math.min(q,$.o):Math.max(q,$.o);if(F){C(b,N(g.liq),"liquidation",!1);return}if(O&&H){C(b,N(g.stop),"stop_loss",!0)||Z(b,S,"stop_loss",g.lifecycleEpoch);return}if(O){C(b,N(g.stop),"stop_loss",!0)||Z(b,S,"stop_loss",g.lifecycleEpoch);return}H&&(C(b,g.take,"take_profit",!0)||Z(b,S,"take_profit",g.lifecycleEpoch))}for(let b=0;b<t.length;b++){let $=Math.floor(t[b].t/864e5);$!==se&&(se=$,ie=M(t[b].o),X=!1),Re(b),Me(b),Ht(b),Ne(b),!X&&M(t[b].c)<=ie*(1-i.maxDailyLossPct/100)&&(X=!0,R.push({type:"daily_loss_limit",barIndex:b,time:t[b].t,message:"daily loss limit reached; new entries blocked for UTC day"}));let S=s[b].signals,F=b+l;if(g)(g.side==="long"&&S.exitLong===!0||g.side==="short"&&S.exitShort===!0)&&F<t.length&&(v.some(q=>q.kind==="exit"&&q.side===g.side&&q.fillBar===F&&q.epoch===g.lifecycleEpoch)||j({kind:"exit",side:g.side,signalBar:b,fillBar:F,reason:"rule",epoch:g.lifecycleEpoch}));else{let H=S.entryLong===!0,N=S.entryShort===!0;H&&N?R.push({type:"conflicting_entry_signals",barIndex:b,time:t[b].t,message:"conflicting entry signals; no position opened"}):!X&&(H||N)&&F<t.length&&b>=y&&j({kind:"entry",side:H?"long":"short",signalBar:b,fillBar:F,epoch:A})}let O=d;g&&(J+=1,O=M(t[b].c)),_.push({barIndex:b,time:t[b].t,equity:O,positionSide:g?g.side:null})}let Ut=null;if(g){let b=t.length-1;if(C(b,t[b].c,"end_of_data",!0))_[b]={barIndex:b,time:t[b].t,equity:d,positionSide:null};else{let S=M(t[b].c);Ut={side:g.side,entryBarIndex:g.entryBarIndex,entryTime:t[g.entryBarIndex].t,entryPrice:g.entryPrice,qty:g.qty,notionalUsd:g.notionalUsd,markPrice:t[b].c,markedEquityUsd:S},R.push({type:"open_position_at_end",barIndex:b,time:t[b].t,message:"end-of-data exit missed; position remains open and marked"})}}let Ct=(g?M(t[t.length-1].c):d)-n.initialEquityUsd,Fr=Ct/n.initialEquityUsd*100,qt=0,Ke=0,Ye=0;for(let b of P)b.netPnlUsd>0?(qt+=1,Ke+=b.netPnlUsd):b.netPnlUsd<0&&(Ye+=-b.netPnlUsd);let Ge=P.length,Hr=Ge===0?0:qt/Ge,Xe=0;Ye>0?Xe=Ke/Ye:Ke>0&&(Xe=1e12);let Ur={netPnlUsd:Ct,netPnlPct:Fr,maxDrawdownPct:_n(_),winRate:Hr,profitFactor:Xe,tradeCount:Ge,sharpe:Tn(_),turnoverUsd:k,exposurePct:J/t.length*100},Cr={initialEquityUsd:n.initialEquityUsd,takerFeeBps:n.takerFeeBps,builderFeeBps:n.builderFeeBps,slippageBps:n.slippageBps,latencyBars:n.latencyBars,maxVolumeParticipationPct:n.maxVolumeParticipationPct},Bt={barsHash:o,strategyHash:a.strategyHash,compilerHash:ce,compilerVersion:he,config:Cr,trades:P,equityCurve:_,metrics:Ur,costs:{feesUsd:m,builderFeesUsd:p,fundingUsd:h,slippageUsd:E},liquidations:T,missedFills:x,openPositionAtEnd:Ut,flags:R};return at(Bt),it(Le(Bt))}var or=Object.freeze(["fail","pass_paper_only","pass_live_eligible"]);function ee(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function we(e){return typeof e=="number"&&Number.isFinite(e)}function ut(e){if(e==null||typeof e!="object"||Object.isFrozen(e))return e;if(Array.isArray(e)){for(let t of e)ut(t);return Object.freeze(e)}for(let t of Object.keys(e))ut(e[t]);return Object.freeze(e)}function de(e){if(Array.isArray(e))return e.map(de);if(e!=null&&typeof e=="object"){let t={};for(let r of Object.keys(e).sort())t[r]=de(e[r]);return t}return e}function ct(e){return{netPnlUsd:e.metrics.netPnlUsd,netPnlPct:e.metrics.netPnlPct,maxDrawdownPct:e.metrics.maxDrawdownPct,winRate:e.metrics.winRate,profitFactor:e.metrics.profitFactor,tradeCount:e.metrics.tradeCount,sharpe:e.metrics.sharpe,turnoverUsd:e.metrics.turnoverUsd,exposurePct:e.metrics.exposurePct}}function rr(e){return{feesUsd:e.costs.feesUsd,builderFeesUsd:e.costs.builderFeesUsd,fundingUsd:e.costs.fundingUsd,slippageUsd:e.costs.slippageUsd}}function On(e){return(e.feesUsd||0)+(e.builderFeesUsd||0)+Math.max(0,e.fundingUsd||0)+(e.slippageUsd||0)}function vn(e){let t=0;for(let r of e.trades)r.grossPnlUsd>0&&(t+=r.grossPnlUsd);return t}function Mn(e,t,r){return!(!e||e.tradeCount<Math.max(1,Math.min(r,3))||!(e.netPnlUsd>0)||!(e.profitFactor>1)||!(e.maxDrawdownPct<=t.maxDailyLossPct))}function sr(e){if(!ee(e))throw new TypeError("evidence artifact must be a plain object");if(!or.includes(e.status))throw new TypeError("evidence artifact status is invalid");for(let t of["strategyHash","compilerHash","barsHash"])if(typeof e[t]!="string"||!/^[0-9a-f]{64}$/.test(e[t]))throw new TypeError(`evidence artifact ${t} must be a sha256 hash`);if(!ee(e.split))throw new TypeError("evidence artifact split required");if(!Array.isArray(e.flags))throw new TypeError("evidence artifact flags must be an array");if(!ee(e.walkForward)||!Array.isArray(e.walkForward.windows))throw new TypeError("evidence artifact walkForward windows required");if(e.status==="pass_live_eligible"&&(!ee(e.train)||!ee(e.holdout)))throw new TypeError("live-eligible evidence artifact requires train and holdout facts");return de({barsHash:e.barsHash,compilerHash:e.compilerHash,flags:e.flags.map(t=>de(t)),holdout:e.holdout??null,split:e.split,status:e.status,strategyHash:e.strategyHash,train:e.train??null,walkForward:{passRate:e.walkForward.passRate,windowsRun:e.walkForward.windowsRun??e.walkForward.windows.length,windows:e.walkForward.windows.map(t=>({index:t.index,trainStartIndex:t.trainStartIndex,trainEndIndex:t.trainEndIndex,passed:t.passed,reason:t.reason,evalStartIndex:t.evalStartIndex,evalEndIndex:t.evalEndIndex,metrics:t.metrics}))}})}function ft(e){return In("sha256").update(JSON.stringify(sr(e)),"utf8").digest("hex")}function G(e,t,r=0){if(!Number.isInteger(e)||e<r)throw new Error(`${t} must be an integer >= ${r}`);return e}function lt(e,t){if(!ee(e)||!ee(e.metrics))throw new Error(`${t} metrics required`);let r=G(e.tradeCount,`${t}.tradeCount`);if(e.metrics.tradeCount!==r)throw new Error(`${t} tradeCount contradicts metrics.tradeCount`);for(let n of["netPnlUsd","profitFactor","maxDrawdownPct"])if(!we(e.metrics[n]))throw new Error(`${t}.metrics.${n} must be finite`);if(e.metrics.maxDrawdownPct<0)throw new Error(`${t}.metrics.maxDrawdownPct must be >= 0`);return e.metrics}function Nn(e,{maxDailyLossPct:t}={}){let r=e.split,n=G(r.trainStartIndex,"split.trainStartIndex"),o=G(r.trainEndIndex,"split.trainEndIndex"),a=G(r.trainBarCount,"split.trainBarCount",1),i=G(r.holdoutStartIndex,"split.holdoutStartIndex"),s=G(r.holdoutEndIndex,"split.holdoutEndIndex"),l=G(r.holdoutBarCount,"split.holdoutBarCount",1);if(n!==0||o-n+1!==a||i!==o+1||s-i+1!==l)throw new Error("evidence split must be contiguous, chronological, and count-consistent");if(!we(r.trainFraction)||r.trainFraction<=0||r.trainFraction>=1)throw new Error("split.trainFraction must be in (0,1)");lt(e.train,"train");let u=lt(e.holdout,"holdout");if(u.tradeCount<1||u.netPnlUsd<=0||u.profitFactor<=1)throw new Error("live-eligible holdout metrics do not pass");if(we(t)&&u.maxDrawdownPct>t)throw new Error("live-eligible holdout drawdown exceeds strategy risk");if(e.flags.length>0)throw new Error("live-eligible evidence cannot contain failure flags");let f=e.walkForward,c=f.windows;if(c.length<1||f.windowsRun!==c.length)throw new Error("live-eligible walk-forward windowsRun must match nonempty windows");let d=0,m=-1;for(let h=0;h<c.length;h++){let E=c[h];if(!ee(E)||E.index!==h||typeof E.passed!="boolean")throw new Error("walk-forward windows must be ordered and structurally valid");let k=G(E.trainStartIndex,`walkForward.windows[${h}].trainStartIndex`),P=G(E.trainEndIndex,`walkForward.windows[${h}].trainEndIndex`),T=G(E.evalStartIndex,`walkForward.windows[${h}].evalStartIndex`),x=G(E.evalEndIndex,`walkForward.windows[${h}].evalEndIndex`);if(k!==0||P>=T||T>x||T<=m)throw new Error("walk-forward windows must be chronological and disjoint");if(m=x,E.passed){if(d+=1,E.reason!=="pass")throw new Error("passed walk-forward window reason must be pass");let R=lt({metrics:E.metrics,tradeCount:E.metrics?.tradeCount},`walkForward.windows[${h}]`);if(R.tradeCount<1||R.netPnlUsd<=0||R.profitFactor<=1)throw new Error("passed walk-forward window metrics do not pass");if(we(t)&&R.maxDrawdownPct>t)throw new Error("passed walk-forward drawdown exceeds strategy risk")}else if(E.reason==="pass")throw new Error("failed walk-forward window cannot have pass reason")}let p=d/c.length;if(!we(f.passRate)||Math.abs(f.passRate-p)>Number.EPSILON||p<.6)throw new Error("walk-forward passRate contradicts concrete windows or is below live threshold")}function dt(e,t={}){if(typeof e?.id!="string"||!/^[0-9a-f]{64}$/.test(e.id))throw new Error("evidence.id must be a sha256 evidence artifact hash");let r=sr(e),n=de({id:e.id,...r});if(JSON.stringify(de(e))!==JSON.stringify(n))throw new Error("evidence artifact contains fields unbound from its deterministic identity");let o=ft(e);if(e.id!==o)throw new Error("evidence.id does not match its deterministic artifact facts digest");return e.status==="pass_live_eligible"&&Nn(e,t),e}function Fe({strategy:e,bars:t,backtestOptions:r={},trainFraction:n=.7,walkForwardWindows:o=3,minTrades:a=10}={}){let i=[];if(!ee(e))throw new TypeError("strategy must be a plain object");if(!Array.isArray(t))throw new TypeError("bars must be an array");if(!ee(r))throw new TypeError("backtestOptions must be a plain object");if(!we(n)||n<=0||n>=1)throw new TypeError("trainFraction must be in (0,1)");if(!Number.isInteger(o)||o<1)throw new TypeError("walkForwardWindows must be a positive integer");if(!Number.isInteger(a)||a<0)throw new TypeError("minTrades must be an integer >= 0");let s=V(e),l=fe(s),u=$e(t),f=t.length,c=(I=[],M={})=>nr({status:"fail",strategy:s,sHash:l,barsHash:u,split:M.split||{trainStartIndex:0,trainEndIndex:-1,trainBarCount:0,holdoutStartIndex:0,holdoutEndIndex:-1,holdoutBarCount:0,trainFraction:n},train:M.train||null,holdout:M.holdout||null,walkForward:M.walkForward||{windows:[],passRate:0},flags:[...i,...I]});if(f<10)return c([{type:"insufficient_bars",message:"need at least 10 bars for evidence"}]);let d=Math.floor(f*n),m=d,p=f-m;if(d<5||p<3)return c([{type:"invalid_windowing",message:"train/holdout split too small",trainCount:d,holdoutCount:p}]);let h=t.slice(0,d),E=t.slice(m),k,P;try{k=ne(s,h,r),P=ne(s,E,r)}catch(I){return c([{type:"backtest_error",message:String(I.message||I)}])}let T={metrics:ct(k),costs:rr(k),tradeCount:k.metrics.tradeCount},x={metrics:ct(P),costs:rr(P),tradeCount:P.metrics.tradeCount},R={trainStartIndex:0,trainEndIndex:d-1,trainBarCount:d,holdoutStartIndex:m,holdoutEndIndex:f-1,holdoutBarCount:p,trainFraction:n},_=[],g=Math.floor(f/(o+1));if(g<3)i.push({type:"invalid_windowing",message:"walk-forward window size too small",wfSize:g});else for(let I=0;I<o;I++){let M=g*(I+1),D=M,C=Math.min(f,D+g);if(C-D<3||M<3){_.push({index:I,trainStartIndex:0,trainEndIndex:M-1,evalStartIndex:D,evalEndIndex:C-1,passed:!1,reason:"window_too_small",metrics:null});continue}let Z=t.slice(D,C),Me;try{Me=ne(s,Z,r)}catch{_.push({index:I,trainStartIndex:0,trainEndIndex:M-1,evalStartIndex:D,evalEndIndex:C-1,passed:!1,reason:"backtest_error",metrics:null});continue}let Ne=ct(Me),Re=Mn(Ne,s.risk,a);_.push({index:I,trainStartIndex:0,trainEndIndex:M-1,evalStartIndex:D,evalEndIndex:C-1,passed:Re,reason:Re?"pass":"fail_metrics",metrics:Ne})}let J=_.filter(I=>I.passed).length,se=_.length===0?0:J/_.length,ie={windows:_,passRate:se,windowsRun:_.length};x.metrics.tradeCount===0&&T.metrics.tradeCount===0&&i.push({type:"no_trades",message:"no trades in train or holdout"}),x.metrics.tradeCount===0&&i.push({type:"absent_oos_trades",message:"holdout produced no trades"}),x.metrics.netPnlUsd<0&&i.push({type:"holdout_loss",message:"holdout netPnlUsd is negative"}),T.metrics.netPnlUsd>0&&x.metrics.netPnlUsd<0&&T.metrics.netPnlUsd>Math.abs(x.metrics.netPnlUsd)*.25?i.push({type:"overfit",message:"profitable train with losing holdout (OOS collapse)"}):T.metrics.netPnlUsd>0&&x.metrics.netPnlUsd>0&&x.metrics.netPnlUsd<T.metrics.netPnlUsd*.1&&T.metrics.tradeCount>=a&&i.push({type:"severe_oos_collapse",message:"holdout pnl collapsed vs train"});let X=On(x.costs),y=vn(P);y>0&&X>y&&i.push({type:"costs_exceed_gross",message:"holdout costs exceed gross gains"});let A=i.some(I=>["insufficient_bars","invalid_windowing","absent_oos_trades","holdout_loss","no_trades","severe_oos_collapse","backtest_error"].includes(I.type)),v=i.some(I=>I.type==="overfit"),L="fail";return x.metrics.tradeCount>=a&&x.metrics.netPnlUsd>0&&x.metrics.profitFactor>1&&x.metrics.maxDrawdownPct<=s.risk.maxDailyLossPct&&se>=.6&&!(y>0&&X>y)&&!v&&!i.some(I=>I.type==="severe_oos_collapse"||I.type==="invalid_windowing")?L="pass_live_eligible":!A&&x.metrics.tradeCount>0&&T.metrics.tradeCount>0&&Number.isFinite(x.metrics.netPnlUsd)?(L="pass_paper_only",x.metrics.tradeCount<a&&i.push({type:"undersampled",message:"holdout trades below minTrades"})):v&&x.metrics.tradeCount>0&&T.metrics.netPnlUsd>0?L="fail":x.metrics.tradeCount>0&&T.metrics.tradeCount>0&&!A?L="pass_paper_only":L="fail",x.metrics.netPnlUsd<0&&(L=L==="pass_live_eligible"?"fail":L==="pass_paper_only"?"pass_paper_only":"fail",L="fail"),nr({status:L,strategy:s,sHash:l,barsHash:u,split:R,train:T,holdout:x,walkForward:ie,flags:i})}function nr({status:e,strategy:t,sHash:r,barsHash:n,split:o,train:a,holdout:i,walkForward:s,flags:l}){let u={status:e,strategyHash:r,compilerHash:ce,barsHash:n,split:o,train:a,holdout:i,walkForward:s,flags:l};return u.id=ft(u),ut(de(JSON.parse(JSON.stringify(u))))}import{createHash as Rn,createHmac as Ln,timingSafeEqual as As}from"node:crypto";var jn=2,Fn=300*1e3,Ps=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})();function pt(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(pt).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${pt(e[r])}`).join(",")}}`}function ir(e){let t=String(e?.ORACLE_STAMP_HMAC_SECRET||"").trim();return t.length>=16?t:""}function ar(e=process.env){return ir(process.env)||ir(e)}function Hn(e){let{oraclePrepared:t,prepareHash:r,prepareMac:n,note:o,...a}=e||{};return a}function Un(e){let t=Hn(e);return Rn("sha256").update(pt(t)).digest("hex")}function Cn(e,t=ar()){return t?Ln("sha256",t).update(String(e)).digest("hex"):""}function cr(e,{provider:t,kind:r,env:n=process.env}={}){if(!e||typeof e!="object")throw new Error("stampPrepared: payload object required");let o={...e,provider:e.provider||t,kind:e.kind||r,requiresUserSignature:e.requiresUserSignature!==!1,signingReady:!1,broadcastReady:!1,executionReady:!1};if(!o.provider)throw new Error("stampPrepared: provider required");if(!o.kind)throw new Error("stampPrepared: kind required");let a=Date.now(),i=a+Fn,l={...o,preparedAt:a,expiresAt:i,prepareVersion:jn},u=Un(l),f=ar(n),c=f?Cn(u,f):void 0,d={...l,oraclePrepared:!0,prepareHash:u};return c&&(d.prepareMac=c),d}var qn=["privatekey","secretkey","seed","mnemonic","passphrase","password","keystore","keymaterial","apikey","authtoken","accesstoken","refreshtoken","credential","bearer","signature","authorization","xprv","xpriv","wif"];function _e(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function Bn(e){return String(e).toLowerCase().replace(/[^a-z0-9]/g,"")}function ht(e,t="value"){if(Array.isArray(e)){e.forEach((r,n)=>ht(r,`${t}[${n}]`));return}if(_e(e))for(let[r,n]of Object.entries(e)){let o=Bn(r);if(qn.some(a=>o.includes(a)))throw new Error(`handoff: forbidden secret-like field at ${t}.${r}`);ht(n,`${t}.${r}`)}}function mt(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function yt({strategy:e,evidence:t,shadow:r,caps:n,nowMs:o=Date.now(),env:a=process.env}={}){if(ht({strategy:e,evidence:t,shadow:r,caps:n},"handoff"),!_e(e))throw new Error("handoff: strategy required");if(!_e(t))throw new Error("handoff: evidence required");if(!_e(r))throw new Error("handoff: shadow required");if(!_e(n))throw new Error("handoff: caps required");if(typeof r.id!="string"||!r.id.trim())throw new Error("handoff: shadow.id required");if(typeof r.stateHash!="string"||!/^[0-9a-f]{64}$/.test(r.stateHash))throw new Error("handoff: shadow.stateHash must be a sha256 hash");if(r.status!=="running")throw new Error("handoff: shadow.status must be running");if(!Number.isInteger(r.cursor)||r.cursor<=0)throw new Error("handoff: shadow.cursor must be a positive integer");if(!Number.isInteger(r.updatedAt)||r.updatedAt<=0||r.updatedAt>o)throw new Error("handoff: shadow.updatedAt must be a positive integer <= nowMs");let i=V(e,{nowMs:o}),s=z(i);if(dt(t,{maxDailyLossPct:i.risk.maxDailyLossPct}),t.status!=="pass_live_eligible")throw new Error("handoff: evidence.status must be pass_live_eligible");if(t.strategyHash!==s.strategyHash)throw new Error("handoff: evidence.strategyHash mismatch");if(t.compilerHash!==s.compilerHash)throw new Error("handoff: evidence.compilerHash mismatch");let l=["perStrategyNotionalUsd","maxLeverage","dailyLossCapUsd","chainAllowlist","assetAllowlist","expiresAt","killSwitchRequired"];for(let d of l)if(!(d in n)||n[d]==null)throw new Error(`handoff: caps.${d} required`);if(!mt(n.perStrategyNotionalUsd))throw new Error("handoff: caps.perStrategyNotionalUsd must be positive");if(n.perStrategyNotionalUsd>s.strategy.risk.maxNotionalUsd)throw new Error("handoff: caps.perStrategyNotionalUsd exceeds strategy.risk.maxNotionalUsd");if(!mt(n.maxLeverage))throw new Error("handoff: caps.maxLeverage must be positive");if(n.maxLeverage>s.strategy.risk.maxLeverage)throw new Error("handoff: caps.maxLeverage exceeds strategy.risk.maxLeverage");if(!mt(n.dailyLossCapUsd))throw new Error("handoff: caps.dailyLossCapUsd must be positive");let u=s.strategy.risk.maxNotionalUsd*(s.strategy.risk.maxDailyLossPct/100);if(n.dailyLossCapUsd>u)throw new Error("handoff: caps.dailyLossCapUsd exceeds strategy daily loss ceiling");if(!Array.isArray(n.chainAllowlist)||n.chainAllowlist.length===0)throw new Error("handoff: caps.chainAllowlist must be a non-empty array");if(!n.chainAllowlist.every(d=>d==="hyperliquid"))throw new Error("handoff: caps.chainAllowlist must include only hyperliquid");if(!n.chainAllowlist.includes("hyperliquid"))throw new Error("handoff: caps.chainAllowlist must include hyperliquid");if(!Array.isArray(n.assetAllowlist)||n.assetAllowlist.length===0)throw new Error("handoff: caps.assetAllowlist must be a non-empty array");if(n.assetAllowlist.length!==1||n.assetAllowlist[0]!==s.strategy.market.coin)throw new Error("handoff: caps.assetAllowlist must contain only the strategy market coin");if(!Number.isInteger(n.expiresAt)||!(n.expiresAt>o))throw new Error("handoff: caps.expiresAt must be an integer > nowMs");if(n.expiresAt>s.strategy.risk.expiresAt)throw new Error("handoff: caps.expiresAt exceeds strategy.risk.expiresAt");if(n.killSwitchRequired!==!0)throw new Error("handoff: caps.killSwitchRequired must be exactly true");let f={perStrategyNotionalUsd:n.perStrategyNotionalUsd,maxLeverage:n.maxLeverage,dailyLossCapUsd:n.dailyLossCapUsd,chainAllowlist:[...n.chainAllowlist],assetAllowlist:[...n.assetAllowlist],expiresAt:n.expiresAt,killSwitchRequired:!0},c={strategyHash:s.strategyHash,compilerHash:s.compilerHash,evidence:JSON.parse(JSON.stringify(t)),shadow:{id:r.id,stateHash:r.stateHash,status:r.status,cursor:r.cursor,updatedAt:r.updatedAt},compiled:{strategyHash:s.strategyHash,compilerHash:s.compilerHash,compilerVersion:he,venue:"hyperliquid",market:{coin:s.strategy.market.coin,kind:"perp",interval:s.strategy.market.interval},risk:{...s.strategy.risk},strategy:JSON.parse(JSON.stringify(s.strategy))},arming:{liveBroadcast:!1,requiresExplicitUserArm:!0,caps:f},requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,executionReady:!1};return cr(c,{provider:"hl-strategy",kind:"strategy-live-handoff",env:a})}var Dn=Object.freeze({"1m":6e4,"3m":18e4,"5m":3e5,"15m":9e5,"30m":18e5,"1h":36e5,"2h":72e5,"4h":144e5,"8h":288e5,"12h":432e5,"1d":864e5});function ge(e,t){let r=Number(e);if(!Number.isFinite(r))throw new TypeError(`${t} must be finite`);return r}function be(e,t){if(!Number.isSafeInteger(e)||e<0)throw new TypeError(`${t} must be a non-negative safe integer`);return e}function Ie(e){if(Array.isArray(e))for(let t of e)Ie(t);else if(e&&typeof e=="object")for(let t of Object.values(e))Ie(t);return Object.freeze(e)}function lr(e){let t=Dn[e];if(!t)throw new TypeError(`unsupported strategy interval: ${e}`);return t}function ur(e,{endTime:t=Number.MAX_SAFE_INTEGER}={}){if(!Array.isArray(e))throw new TypeError("Hyperliquid candles must be an array");be(t,"endTime");let r=new Map;for(let n=0;n<e.length;n++){let o=e[n];if(!o||typeof o!="object"||Array.isArray(o))throw new TypeError(`candles[${n}] must be an object`);let a=be(Number(o.t),`candles[${n}].t`);if(be(Number(o.T),`candles[${n}].T`)>t)continue;let s={t:a,o:ge(o.o,`candles[${n}].o`),h:ge(o.h,`candles[${n}].h`),l:ge(o.l,`candles[${n}].l`),c:ge(o.c,`candles[${n}].c`),v:ge(o.v,`candles[${n}].v`)};if(s.h<Math.max(s.o,s.c,s.l))throw new TypeError(`candles[${n}].h is below another price`);if(s.l>Math.min(s.o,s.c,s.h))throw new TypeError(`candles[${n}].l is above another price`);if(s.v<0)throw new TypeError(`candles[${n}].v must be non-negative`);let l=r.get(a);if(l&&JSON.stringify(l)!==JSON.stringify(s))throw new TypeError(`conflicting duplicate candle at timestamp ${a}`);l||r.set(a,s)}return Ie([...r.values()].sort((n,o)=>n.t-o.t))}function zn(e,t){if(!Array.isArray(e))throw new TypeError("Hyperliquid funding history must be an array");let r=new Map;for(let n=0;n<e.length;n++){let o=e[n];if(!o||typeof o!="object"||Array.isArray(o))throw new TypeError(`funding[${n}] must be an object`);let a=be(Number(o.time),`funding[${n}].time`);a>t||r.set(a,{time:a,fundingRate:ge(o.fundingRate,`funding[${n}].fundingRate`)})}return[...r.values()].sort((n,o)=>n.time-o.time)}async function Vn({coin:e,startTime:t,endTime:r},n){let o=[],a=Math.max(0,t-288e5),i=!1;for(let s=0;s<16&&a<=r;s++){let l=await Zt({coin:e,startTime:a,endTime:r},n);if(!Array.isArray(l))throw new TypeError("Hyperliquid funding history must be an array");o.push(...l);let u=a;for(let f of l){let c=Number(f?.time);Number.isSafeInteger(c)&&c>u&&(u=c)}if(l.length<500||u>=r){i=!0;break}if(u<=a)throw new Error("Hyperliquid funding history pagination did not advance");a=u+1}if(!i)throw new Error("strategy history exceeds the bounded funding history limit");return zn(o,r)}function Jn(e,t,r){let n=0,o=null;return e.map(a=>{let i=a.t+r,s=0;for(;n<t.length&&t[n].time<i;){let l=t[n];o=l.fundingRate,l.time>=a.t&&(s+=l.fundingRate),n+=1}return o==null?{...a,fundingPaymentRate:s}:{...a,fundingRate:o,fundingPaymentRate:s}})}async function wt(e,t={}){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("strategy history input must be an object");let r=String(e.coin||"").trim().toUpperCase();if(!/^[A-Z0-9][A-Z0-9._-]{0,11}$/.test(r))throw new TypeError("coin must be an uppercase Hyperliquid asset id");let n=String(e.interval||"15m"),o=lr(n);if(e.endTime==null)throw new TypeError("endTime is required for deterministic history");let a=be(e.endTime,"endTime"),i=e.count==null?1500:e.count;if(!Number.isInteger(i)||i<20||i>5e3)throw new TypeError("count must be an integer from 20 to 5000");let s=e.startTime==null?Math.max(0,a-i*o):be(e.startTime,"startTime");if(s>=a)throw new TypeError("startTime must be before endTime");let[l,u]=await Promise.all([Xt({coin:r,interval:n,startTime:s,endTime:a},t),Vn({coin:r,startTime:s,endTime:a},t)]),f=ur(l,{endTime:a}),c=Ie(Jn(f,u,o));return Ie({coin:r,interval:n,range:{startTime:s,endTime:a},bars:c})}var Kn=new Set(["1m","3m","5m","15m","30m","1h","2h","4h","8h","12h","1d"]),Yn=new Set(["coin","interval"]);function Gn(e){let t=[];if(!e||typeof e!="object"||Array.isArray(e))return{ok:!1,errors:[{path:"market",message:"must be a plain object"}],market:null};for(let r of Object.keys(e))Yn.has(r)||t.push({path:`market.${r}`,message:"unknown field is not allowed"});return(typeof e.coin!="string"||e.coin.length===0||e.coin.length>32)&&t.push({path:"market.coin",message:"must be a non-empty string max 32"}),(typeof e.interval!="string"||!Kn.has(e.interval))&&t.push({path:"market.interval",message:"must be a supported interval"}),t.length?{ok:!1,errors:t,market:null}:{ok:!0,errors:[],market:{coin:e.coin,interval:e.interval}}}async function Xn(e={}){let t=await Gt(e);if(!t||!Array.isArray(t.universe))throw new TypeError("Hyperliquid market metadata must contain universe");return Object.freeze(t.universe.map((r,n)=>{if(!r||typeof r.name!="string"||!r.name)throw new TypeError(`Hyperliquid market metadata universe[${n}].name is invalid`);return r.name}))}var fr=Object.freeze({id:"hyperliquid",validateMarket:Gn,fetchBars:wt,listMarkets:Xn,prepareIntent(e){return yt(e)}});var Zn=Object.freeze(["id","validateMarket","prepareIntent"]);function Wn(e){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("strategy venue adapter must be an object");if(typeof e.id!="string"||!/^[a-z0-9][a-z0-9._-]{0,63}$/.test(e.id))throw new TypeError("strategy venue adapter id is malformed");for(let t of Zn.slice(1))if(typeof e[t]!="function")throw new TypeError(`strategy venue adapter ${e.id} requires ${t}()`);for(let t of["fetchBars","listMarkets"])if(e[t]!=null&&typeof e[t]!="function")throw new TypeError(`strategy venue adapter ${e.id} ${t} must be a function`);return e}var dr=[fr].map(Wn),Qn=new Map(dr.map(e=>[e.id,e])),eo=Object.freeze([...dr]);function He(e){return typeof e!="string"?null:Qn.get(e)??null}function Ue(e){let t=He(e);if(!t)throw new Error(`unknown strategy venue: ${String(e)}`);return t}var Ce=1,Sr=/^[a-z0-9][a-z0-9._-]{0,63}$/,kr=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,ro=new Set(["open","high","low","close","volume","fundingRate","openInterest"]),no=new Set(["sma","ema","rsi","macd","bollinger","atr"]),oo=new Set(["gt","gte","lt","lte","eq"]),so=new Set(["and","or","not"]),io=new Set(["above","below"]),ao=new Set(["line","signal","histogram"]),co=new Set(["upper","middle","lower"]),gt=new Set(["compare","logic","cross"]),pr=new Set(["version","id","name","venue","market","parameters","nodes","rules","risk"]),mr=new Set(["value","min","max","step"]),bt=new Set(["entryLong","entryShort","exitLong","exitShort"]),hr=new Set(["maxLeverage","maxNotionalUsd","positionSizePct","stopLossPct","takeProfitPct","cooldownBars","maxDailyLossPct","expiresAt"]),lo=new Set(["id","type"]),yr={input:new Set(["id","type","field"]),constant:new Set(["id","type","value"]),indicator:new Set(["id","type","indicator","input","period","fastPeriod","slowPeriod","signalPeriod","stdDev","output"]),compare:new Set(["id","type","op","left","right"]),logic:new Set(["id","type","op","inputs"]),cross:new Set(["id","type","direction","left","right"])},wr=16,gr=128,br=100,pe=class extends Error{constructor(t){let r=t.map(n=>`${n.path}: ${n.message}`);super(`invalid strategy (${t.length} error${t.length===1?"":"s"}): ${r.join("; ")}`),this.name="StrategyValidationError",this.errors=t}};function K(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function U(e){return typeof e=="number"&&Number.isFinite(e)}function Er(e){return Number.isInteger(e)&&e>0}function xt(e){if(e==null||typeof e!="object"||Object.isFrozen(e))return e;if(Array.isArray(e)){for(let t of e)xt(t);return Object.freeze(e)}for(let t of Object.keys(e))xt(e[t]);return Object.freeze(e)}function St(e){if(Array.isArray(e))return e.map(St);if(e!=null&&typeof e=="object"){let t={};for(let r of Object.keys(e).sort())t[r]=St(e[r]);return t}return e}function w(e,t,r){e.push({path:t,message:r})}function le(e,t,r,n){for(let o of Object.keys(e))t.has(o)||w(n,r?`${r}.${o}`:o,"unknown field is not allowed")}function Ar(e,t,r,n){if(!U(e)||!U(t)||!U(r)||!U(n)||n<=0||e<t||e>r)return!1;let o=(e-t)/n;if(!Number.isFinite(o))return!1;let a=Math.round(o);return Math.abs(o-a)<=1e-9}function Et(e,t,r,n){if(K(e)){if(le(e,new Set(["param"]),t,n),typeof e.param!="string"||!e.param)return w(n,`${t}.param`,"must be a parameter name string"),null;if(!Object.prototype.hasOwnProperty.call(r,e.param))return w(n,`${t}.param`,`unknown parameter "${e.param}"`),null;let o=r[e.param];return!K(o)||![o.value,o.min,o.max,o.step].every(Er)?(w(n,`${t}.param`,"referenced period parameter value min max and step must be positive integers"),null):{param:e.param}}return Er(e)?e:(w(n,t,"must be a positive integer or {param}"),null)}function xr(e,t,r,n){return K(e)?(le(e,new Set(["param"]),t,n),typeof e.param!="string"||!e.param?(w(n,`${t}.param`,"must be a parameter name string"),null):Object.prototype.hasOwnProperty.call(r,e.param)?{param:e.param}:(w(n,`${t}.param`,`unknown parameter "${e.param}"`),null)):U(e)?e:(w(n,t,"must be a finite number or {param}"),null)}function qe(e){switch(e.type){case"input":case"constant":return[];case"indicator":return e.input?[e.input]:[];case"compare":case"cross":return[e.left,e.right].filter(Boolean);case"logic":return Array.isArray(e.inputs)?[...e.inputs]:[];default:return[]}}function uo(e){let t=new Map,r=n=>{let o=t.get(n)||0;if(o===1)return!0;if(o===2)return!1;t.set(n,1);let a=e.get(n);if(a){for(let i of qe(a))if(e.has(i)&&r(i))return!0}return t.set(n,2),!1};for(let n of e.keys())if(r(n))return!0;return!1}function fo(e,t){if(!K(e))return w(t,"parameters","must be a plain object"),null;let r=Object.keys(e);if(r.length>wr)return w(t,"parameters",`too many parameters (max ${wr})`),null;let n={};for(let o of r){if(!Sr.test(o)){w(t,`parameters.${o}`,"parameter name is malformed");continue}let a=e[o],i=`parameters.${o}`;if(!K(a)){w(t,i,"must be a plain object");continue}le(a,mr,i,t);for(let c of mr)c in a||w(t,`${i}.${c}`,"required field is missing");let{value:s,min:l,max:u,step:f}=a;U(l)||w(t,`${i}.min`,"must be a finite number"),U(u)||w(t,`${i}.max`,"must be a finite number"),(!U(f)||f<=0)&&w(t,`${i}.step`,"must be a positive finite number"),U(s)||w(t,`${i}.value`,"must be a finite number"),U(l)&&U(u)&&l>u&&w(t,`${i}.min`,"min must be <= max"),U(s)&&U(l)&&U(u)&&U(f)&&f>0&&(Ar(s,l,u,f)||w(t,`${i}.value`,"value must lie on the declared min/max/step grid")),n[o]={value:s,min:l,max:u,step:f}}return n}function po(e,t,r,n){let o=`nodes.${t}`;if(!K(e))return w(n,o,"must be a plain object"),null;if(typeof e.type!="string"||!yr[e.type])return w(n,`${o}.type`,"unknown or missing node type"),le(e,lo,o,n),null;switch(le(e,yr[e.type],o,n),(typeof e.id!="string"||!kr.test(e.id))&&w(n,`${o}.id`,"must be a 1-64 char id starting with alphanumeric"),e.type){case"input":return(typeof e.field!="string"||!ro.has(e.field))&&w(n,`${o}.field`,"must be one of open|high|low|close|volume|fundingRate|openInterest"),{id:e.id,type:"input",field:e.field};case"constant":{let a=xr(e.value,`${o}.value`,r,n);return{id:e.id,type:"constant",value:a}}case"indicator":{(typeof e.indicator!="string"||!no.has(e.indicator))&&w(n,`${o}.indicator`,"must be one of sma|ema|rsi|macd|bollinger|atr");let a=e.indicator,i={id:e.id,type:"indicator",indicator:a};if(a==="atr"){"input"in e&&(typeof e.input!="string"||!e.input?w(n,`${o}.input`,"must be a node id string when provided"):i.input=e.input);let s=Et(e.period,`${o}.period`,r,n);s!=null&&(i.period=s)}else typeof e.input!="string"||!e.input?w(n,`${o}.input`,"must be a node id string"):i.input=e.input;if((a==="sma"||a==="ema"||a==="rsi"||a==="bollinger"||a==="atr")&&("period"in e,a!=="macd"))if(!("period"in e))w(n,`${o}.period`,"required field is missing");else{let s=Et(e.period,`${o}.period`,r,n);s!=null&&(i.period=s)}if(a==="macd"){for(let s of["fastPeriod","slowPeriod","signalPeriod"])if(!(s in e))w(n,`${o}.${s}`,"required field is missing");else{let l=Et(e[s],`${o}.${s}`,r,n);l!=null&&(i[s]=l)}"output"in e?ao.has(e.output)?i.output=e.output:w(n,`${o}.output`,"must be line|signal|histogram"):w(n,`${o}.output`,"required field is missing"),"period"in e&&w(n,`${o}.period`,"forbidden for macd"),"stdDev"in e&&w(n,`${o}.stdDev`,"forbidden for macd")}else if(a==="bollinger"){if(!("stdDev"in e))w(n,`${o}.stdDev`,"required field is missing");else{let s=xr(e.stdDev,`${o}.stdDev`,r,n);s!=null&&(typeof s=="number"&&s<=0?w(n,`${o}.stdDev`,"must be > 0"):i.stdDev=s)}"output"in e?co.has(e.output)?i.output=e.output:w(n,`${o}.output`,"must be upper|middle|lower"):w(n,`${o}.output`,"required field is missing");for(let s of["fastPeriod","slowPeriod","signalPeriod"])s in e&&w(n,`${o}.${s}`,`forbidden for ${a}`)}else{"output"in e&&w(n,`${o}.output`,`forbidden for ${a}`),"stdDev"in e&&a!=="bollinger"&&w(n,`${o}.stdDev`,`forbidden for ${a}`);for(let s of["fastPeriod","slowPeriod","signalPeriod"])s in e&&w(n,`${o}.${s}`,`forbidden for ${a}`)}return i}case"compare":return(typeof e.op!="string"||!oo.has(e.op))&&w(n,`${o}.op`,"must be gt|gte|lt|lte|eq"),(typeof e.left!="string"||!e.left)&&w(n,`${o}.left`,"must be a node id"),(typeof e.right!="string"||!e.right)&&w(n,`${o}.right`,"must be a node id"),{id:e.id,type:"compare",op:e.op,left:e.left,right:e.right};case"logic":{if((typeof e.op!="string"||!so.has(e.op))&&w(n,`${o}.op`,"must be and|or|not"),!Array.isArray(e.inputs))return w(n,`${o}.inputs`,"must be an array of node ids"),{id:e.id,type:"logic",op:e.op,inputs:[]};let a=[];for(let i=0;i<e.inputs.length;i++){let s=e.inputs[i];typeof s!="string"||!s?w(n,`${o}.inputs.${i}`,"must be a node id"):a.push(s)}return e.op==="not"?a.length!==1&&w(n,`${o}.inputs`,"not requires exactly one input"):(e.op==="and"||e.op==="or")&&a.length<2&&w(n,`${o}.inputs`,`${e.op} requires at least two inputs`),{id:e.id,type:"logic",op:e.op,inputs:a}}case"cross":return(typeof e.direction!="string"||!io.has(e.direction))&&w(n,`${o}.direction`,"must be above|below"),(typeof e.left!="string"||!e.left)&&w(n,`${o}.left`,"must be a node id"),(typeof e.right!="string"||!e.right)&&w(n,`${o}.right`,"must be a node id"),{id:e.id,type:"cross",direction:e.direction,left:e.left,right:e.right};default:return null}}function mo(e,t,r){if(!K(e))return w(t,"risk","must be a plain object"),null;le(e,hr,"risk",t);for(let d of hr)(!(d in e)||e[d]==null)&&w(t,`risk.${d}`,"required field is missing");let n={},o=e.maxLeverage;!U(o)||o<=0||o>50?w(t,"risk.maxLeverage","must be a number > 0 and <= 50"):n.maxLeverage=o;let a=e.maxNotionalUsd;!U(a)||a<=0?w(t,"risk.maxNotionalUsd","must be a number > 0"):n.maxNotionalUsd=a;let i=e.positionSizePct;!U(i)||i<=0||i>100?w(t,"risk.positionSizePct","must be a number > 0 and <= 100"):n.positionSizePct=i;let s=e.stopLossPct;!U(s)||s<=0||s>100?w(t,"risk.stopLossPct","must be a number > 0 and <= 100"):n.stopLossPct=s;let l=e.takeProfitPct;!U(l)||l<=0||l>1e3?w(t,"risk.takeProfitPct","must be a number > 0 and <= 1000"):n.takeProfitPct=l;let u=e.cooldownBars;!Number.isInteger(u)||u<0||u>1e5?w(t,"risk.cooldownBars","must be an integer >= 0 and <= 100000"):n.cooldownBars=u;let f=e.maxDailyLossPct;!U(f)||f<=0||f>100?w(t,"risk.maxDailyLossPct","must be a number > 0 and <= 100"):n.maxDailyLossPct=f;let c=e.expiresAt;return!Number.isInteger(c)||c<=0?w(t,"risk.expiresAt","must be an integer epoch milliseconds > 0"):(r.nowMs!==void 0&&(Number.isInteger(r.nowMs)?c<=r.nowMs&&w(t,"risk.expiresAt","must be strictly greater than nowMs"):w(t,"nowMs","must be an integer epoch milliseconds")),n.expiresAt=c),n}function Be(e,t={}){let r=[];if(!K(e))return w(r,"","strategy must be a plain object"),{ok:!1,errors:r,strategy:null};le(e,pr,"",r);for(let c of pr)(!(c in e)||e[c]==null)&&w(r,c,"required field is missing");e.version!==Ce&&w(r,"version",`must be ${Ce}`),(typeof e.id!="string"||!Sr.test(e.id))&&w(r,"id","must match /^[a-z0-9][a-z0-9._-]{0,63}$/"),(typeof e.name!="string"||e.name.length===0||e.name.length>br)&&w(r,"name",`must be a non-empty string max ${br}`);let n=He(e.venue);n||w(r,"venue",`unknown strategy venue "${String(e.venue)}"`);let o=null;if(!n)K(e.market)||w(r,"market","must be a plain object");else{let c=n.validateMarket(e.market);if(!c||typeof c.ok!="boolean"||!Array.isArray(c.errors))w(r,"market",`venue ${n.id} returned an invalid market validation result`);else if(c.ok)o=c.market;else for(let d of c.errors)w(r,d.path,d.message)}let a=fo(e.parameters,r),i=null,s=new Map;if(!Array.isArray(e.nodes))w(r,"nodes","must be an array");else if(e.nodes.length>gr)w(r,"nodes",`too many nodes (max ${gr})`);else{i=[];for(let c=0;c<e.nodes.length;c++){let d=po(e.nodes[c],c,a||{},r);d&&(typeof d.id=="string"&&kr.test(d.id)&&(s.has(d.id)?w(r,`nodes.${c}.id`,`duplicate node id "${d.id}"`):s.set(d.id,d)),i.push(d))}for(let c=0;c<i.length;c++){let d=i[c],m=`nodes.${c}`;for(let p of qe(d))s.has(p)||w(r,m,`unknown node ref "${p}"`);if(d.type==="indicator"||d.type==="compare"||d.type==="cross")for(let p of qe(d)){let h=s.get(p);h&&gt.has(h.type)&&w(r,m,`node ref "${p}" must be numeric`)}if(d.type==="logic")for(let p of qe(d)){let h=s.get(p);h&&!gt.has(h.type)&&w(r,m,`node ref "${p}" must be boolean`)}}uo(s)&&w(r,"nodes","graph contains a cycle")}let l=null;if(!K(e.rules))w(r,"rules","must be a plain object");else{le(e.rules,bt,"rules",r);for(let c of bt)c in e.rules||w(r,`rules.${c}`,"required field is missing");l={};for(let c of bt){let d=e.rules[c];if(d===null){l[c]=null;continue}if(typeof d!="string"||!d){w(r,`rules.${c}`,"must be a node id or null"),l[c]=d;continue}if(!s.has(d)){w(r,`rules.${c}`,`unknown node ref "${d}"`),l[c]=d;continue}let m=s.get(d);gt.has(m.type)||w(r,`rules.${c}`,`rule must reference a boolean node, not ${m.type}`),l[c]=d}}let u=mo(e.risk,r,t);if(r.length)return{ok:!1,errors:r,strategy:null};let f=xt({version:Ce,id:e.id,name:e.name,venue:n.id,market:o,parameters:a,nodes:i,rules:l,risk:u});return{ok:!0,errors:[],strategy:f}}function V(e,t={}){let r=Be(e,t);if(!r.ok)throw new pe(r.errors);return r.strategy}function Pr(e){let t=V(e);return JSON.stringify(St(t))}function fe(e){let t=Pr(e);return to("sha256").update(t,"utf8").digest("hex")}function ye(e,t){if(!K(e))throw new pe([{path:"",message:"strategy must be a plain object"}]);if(!K(t))throw new pe([{path:"overrides",message:"must be a plain object"}]);let r=V(e),n={};for(let[a,i]of Object.entries(r.parameters))n[a]={value:i.value,min:i.min,max:i.max,step:i.step};let o=[];for(let[a,i]of Object.entries(t)){if(!Object.prototype.hasOwnProperty.call(n,a)){w(o,a,`unknown parameter "${a}"`);continue}let s=n[a];if(!U(i)){w(o,a,"override must be a finite number");continue}if(!Ar(i,s.min,s.max,s.step)){w(o,a,"override must lie on the declared min/max/step grid");continue}n[a]={...s,value:i}}if(o.length)throw new pe(o);return V({version:r.version,id:r.id,name:r.name,venue:r.venue,market:{coin:r.market.coin,interval:r.market.interval},parameters:n,nodes:r.nodes.map(a=>{let i={...a};return Array.isArray(a.inputs)&&(i.inputs=[...a.inputs]),i}),rules:{...r.rules},risk:{...r.risk}})}import{createHash as ho}from"node:crypto";var At=256,$r=new Set(["netPnlUsd","profitFactor","sharpe","maxDrawdownPct"]);function Tr(e){let t=String(e).toLowerCase();return t==="holdout"||t==="test"||t==="oos"||t.includes("holdout")||t.includes("oos")?!0:t==="testbars"||t.endsWith("testbars")||t.startsWith("test")||t.endsWith("test")?!t.includes("backtest"):!1}function _r(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function Pt(e){if(e==null||typeof e!="object"||Object.isFrozen(e))return e;if(Array.isArray(e)){for(let t of e)Pt(t);return Object.freeze(e)}for(let t of Object.keys(e))Pt(e[t]);return Object.freeze(e)}function Oe(e){if(Array.isArray(e))return e.map(Oe);if(e!=null&&typeof e=="object"){let t={};for(let r of Object.keys(e).sort())t[r]=Oe(e[r]);return t}return e}function De(e){return JSON.stringify(Oe(e))}function yo(e){let{min:t,max:r,step:n}=e;if(!(n>0)||t>r)return[];let o=[],a=Math.floor((r-t)/n+1e-9);for(let s=0;s<=a;s++){let l=t+s*n;if(l>r+1e-9)break;let u=Math.abs(l-Math.round(l))<1e-9?Math.round(l):Number(l.toPrecision(12));u<t-1e-9||u>r+1e-9||o.push(u)}if(o.length===0)return[];let i=o[o.length-1];if(Math.abs(i-r)>1e-9){let s=(r-t)/n;Math.abs(s-Math.round(s))<=1e-9&&o.push(r)}return o}function wo(e,t){if(e.length===0)return[];let r=[{}];for(let n of e){let o=t[n],a=[];for(let i of r)for(let s of o)a.push({...i,[n]:s});r=a}return r.sort((n,o)=>{let a=De(n),i=De(o);return a<i?-1:a>i?1:0}),r}function kt(e,t,r,n,o){let a=0;if(e==="maxDrawdownPct"){if(a=t.maxDrawdownPct-n.maxDrawdownPct,a!==0)return a<0}else if(a=t[e]-n[e],a!==0)return a>0;let i=De(r),s=De(o);return i<s}function $t(e,t,r={}){if(!_r(r))throw new TypeError("options must be a plain object");for(let x of Object.keys(r))if(Tr(x))throw new TypeError(`options must not include holdout/test/oos key "${x}"`);let n=new Set(["maxTrials","objective","backtestOptions"]);for(let x of Object.keys(r))if(!n.has(x))throw new TypeError(`unknown option "${x}"`);let o=64;if("maxTrials"in r){let x=r.maxTrials;if(!Number.isInteger(x)||x<1||x>At)throw new TypeError(`maxTrials must be an integer 1..${At}`);o=x}let a=r.objective??"netPnlUsd";if(!$r.has(a))throw new TypeError(`objective must be one of ${[...$r].join("|")}`);let i=r.backtestOptions??{};if(!_r(i))throw new TypeError("backtestOptions must be a plain object");for(let x of Object.keys(i))if(Tr(x))throw new TypeError(`backtestOptions must not include holdout/test/oos key "${x}"`);let s=V(e),l=Object.keys(s.parameters).sort();if(l.length===0)throw new Error("optimizeStrategy requires at least one declared parameter");let u={},f=1;for(let x of l){let R=yo(s.parameters[x]);if(R.length===0)throw new Error(`parameter "${x}" produces an empty grid`);u[x]=R,f*=R.length}let c=wo(l,u);if(c.length===0)throw new Error("parameter grid is empty");let d=c.slice(0,o),m=[],p=null,h=null;for(let x of d){let R=ye(s,x),_=ne(R,t,i);h==null&&(h=_.config);let g={netPnlUsd:_.metrics.netPnlUsd,netPnlPct:_.metrics.netPnlPct,maxDrawdownPct:_.metrics.maxDrawdownPct,winRate:_.metrics.winRate,profitFactor:_.metrics.profitFactor,tradeCount:_.metrics.tradeCount,sharpe:_.metrics.sharpe,turnoverUsd:_.metrics.turnoverUsd},J={parameters:{...x},metrics:g};m.push(J),(!p||kt(a,g,x,p.metrics,p.parameters))&&(p=J)}m.sort((x,R)=>kt(a,x.metrics,x.parameters,R.metrics,R.parameters)?-1:kt(a,R.metrics,R.parameters,x.metrics,x.parameters)?1:0);let E={...p.parameters},k=ye(s,E),P={strategyHash:fe(s),compilerHash:ce,trainBarsHash:$e(t),backtestConfig:h,objective:a,maxTrials:o,trialsRun:m.length,candidates:m,bestParameters:E,bestStrategy:k},T={id:ho("sha256").update(JSON.stringify(Oe(P)),"utf8").digest("hex"),...P};return Pt(Oe(JSON.parse(JSON.stringify(T))))}import{createHash as go}from"node:crypto";var B=class extends Error{constructor(t){super(t),this.name="StrategyDraftError"}},bo=new Set(["1m","3m","5m","15m","30m","1h","2h","4h","8h","12h","1d"]),Eo=new Set(["BTC","ETH","SOL","HYPE"]),xo=/\b(mnemonic|private\s*key|privkey|seed\s*phrase|seed\b|api[_-]?key|secret\s*key|wallet\s*key|passphrase)\b/i,Ee="Supported grammar: (1) EMA cross: <long|short> <COIN> when EMA <n> crosses <above|below> EMA <m> [on <interval>] [, exit on reverse] [, risk knobs]; (2) RSI: <long|short> <COIN> when RSI <n> <above|below> <threshold> [on <interval>] [, risk knobs]; (3) funding: <long|short> <COIN> when funding rate <above|below> <decimal|percent%> [on <interval>] [, risk knobs]. Risk knobs: stop loss %, take profit %, leverage, position size %, max notional USD. Coins: BTC ETH SOL HYPE or uppercase token <=12 chars. Intervals: 1m 3m 5m 15m 30m 1h 2h 4h 8h 12h 1d.",So=Object.freeze({maxLeverage:1,maxNotionalUsd:100,positionSizePct:5,stopLossPct:2,takeProfitPct:4,cooldownBars:1,maxDailyLossPct:3}),ko=36e5,Ao=30*864e5,Po=864e5;function $o(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function Tt(e){if(e==null||typeof e!="object"||Object.isFrozen(e))return e;if(Array.isArray(e)){for(let t of e)Tt(t);return Object.freeze(e)}for(let t of Object.keys(e))Tt(e[t]);return Object.freeze(e)}function To(e){return String(e).trim().replace(/\s+/g," ")}function _o(e){let t=e.match(/\b(long|short)\b/i);return t?t[1].toLowerCase():null}function Io(e){for(let r of Eo)if(new RegExp(`\\b${r}\\b`,"i").test(e))return r;let t=e.match(/\b([A-Z][A-Z0-9]{1,11})\b/);return t?t[1]:null}function Oo(e){let t=e.match(/\bon\s+(1m|3m|5m|15m|30m|1h|2h|4h|8h|12h|1d)\b/i);if(!t)return"15m";let r=t[1].toLowerCase();return bo.has(r)?r:null}function vo(e){let t={...So},r=e.match(/stop\s*loss\s*(\d+(?:\.\d+)?)\s*%?/i);r&&(t.stopLossPct=Number(r[1]));let n=e.match(/take\s*profit\s*(\d+(?:\.\d+)?)\s*%?/i);n&&(t.takeProfitPct=Number(n[1]));let o=e.match(/leverage\s*(\d+(?:\.\d+)?)/i);o&&(t.maxLeverage=Number(o[1]));let a=e.match(/position\s*size\s*(\d+(?:\.\d+)?)\s*%?/i);a&&(t.positionSizePct=Number(a[1]));let i=e.match(/max\s*notional\s*(?:usd\s*)?\$?\s*(\d+(?:\.\d+)?)/i);return i&&(t.maxNotionalUsd=Number(i[1])),t}function Mo(e){return[/\bon\s+(?:1m|3m|5m|15m|30m|1h|2h|4h|8h|12h|1d)\b/gi,/\bstop\s*loss\s*\d+(?:\.\d+)?\s*%?/gi,/\btake\s*profit\s*\d+(?:\.\d+)?\s*%?/gi,/\bleverage\s*\d+(?:\.\d+)?/gi,/\bposition\s*size\s*\d+(?:\.\d+)?\s*%?/gi,/\bmax\s*notional\s*(?:usd\s*)?\$?\s*\d+(?:\.\d+)?/gi].some(r=>(e.match(r)??[]).length>1)}function No(e){let t=go("sha256").update(e,"utf8").digest("hex").slice(0,10),r=e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40),o=`${r.length?r:"draft"}-${t}`.replace(/[^a-z0-9._-]/g,"").slice(0,64);return/^[a-z0-9]/.test(o)?o:`d${o}`.slice(0,64)}function Ro(e){let t=e.match(/\bema\s*(\d+)\s*cross(?:es)?\s*(above|below)\s*ema\s*(\d+)\b/i);if(!t)return null;let r=Number(t[1]),n=t[2].toLowerCase(),o=Number(t[3]);if(!(r>0)||!(o>0)||r===o)return null;let a=/\b(exit\s+on\s+reverse|reverse\s+exit)\b/i.test(e);return{kind:"ema_cross",fast:r,slow:o,direction:n,reverse:a}}function Lo(e){let t=e.match(/\brsi\s*(\d+)\s*(above|below)\s*(-?\d+(?:\.\d+)?)/i);if(!t)return null;let r=Number(t[3]);return!Number.isFinite(r)||r<=0||r>=100?null:{kind:"rsi",period:Number(t[1]),op:t[2].toLowerCase(),threshold:r}}function jo(e){let t=e.match(/\bfunding\s*rate\s*(above|below)\s*(-?\d+(?:\.\d+)?)(%?)(?=\s|,|$)/i);if(!t)return null;let r=Number(t[2]);return t[3]==="%"&&(r=r/100),{kind:"funding",op:t[1].toLowerCase(),threshold:r}}function Fo(e,t){let r=e.replace(/^(long|short)\s+[A-Z][A-Z0-9]{1,11}\s+when\s+/i,"");if(r===e)return!1;t.kind==="ema_cross"?r=r.replace(/^ema\s*\d+\s*cross(?:es)?\s*(?:above|below)\s*ema\s*\d+\b/i,""):t.kind==="rsi"?r=r.replace(/^rsi\s*\d+\s*(?:above|below)\s*\d+(?:\.\d+)?\b/i,""):r=r.replace(/^funding\s*rate\s*(?:above|below)\s*-?\d+(?:\.\d+)?%?(?=\s|,|$)/i,"");let n=[/(?:,\s*)?\bon\s+(?:1m|3m|5m|15m|30m|1h|2h|4h|8h|12h|1d)\b/gi,/(?:,\s*)?\bstop\s*loss\s*\d+(?:\.\d+)?\s*%?/gi,/(?:,\s*)?\btake\s*profit\s*\d+(?:\.\d+)?\s*%?/gi,/(?:,\s*)?\bleverage\s*\d+(?:\.\d+)?/gi,/(?:,\s*)?\bposition\s*size\s*\d+(?:\.\d+)?\s*%?/gi,/(?:,\s*)?\bmax\s*notional\s*(?:usd\s*)?\$?\s*\d+(?:\.\d+)?/gi];t.kind==="ema_cross"&&n.push(/(?:,\s*)?\b(?:exit\s+on\s+reverse|reverse\s+exit)\b/gi);for(let o of n)r=r.replace(o,"");return r.replace(/[\s,;]+/g,"")===""}function Ir(e){let t=Math.max(2,Math.floor(e/2));return{value:e,min:Math.max(2,e-t),max:Math.min(500,e+t),step:1}}function Ho({side:e,coin:t,interval:r,risk:n,expiresAt:o,id:a,name:i,spec:s}){let l=[{id:"c",type:"input",field:"close"},{id:"emaLeft",type:"indicator",indicator:"ema",input:"c",period:{param:"ema_left_period"}},{id:"emaRight",type:"indicator",indicator:"ema",input:"c",period:{param:"ema_right_period"}},{id:"cross",type:"cross",direction:s.direction,left:"emaLeft",right:"emaRight"}],u={entryLong:null,entryShort:null,exitLong:null,exitShort:null};if(e==="long"?u.entryLong="cross":u.entryShort="cross",s.reverse){let f=s.direction==="above"?"below":"above";l.push({id:"crossRev",type:"cross",direction:f,left:"emaLeft",right:"emaRight"}),e==="long"?u.exitLong="crossRev":u.exitShort="crossRev"}return{version:1,id:a,name:i,venue:"hyperliquid",market:{coin:t,interval:r},parameters:{ema_left_period:Ir(s.fast),ema_right_period:Ir(s.slow)},nodes:l,rules:u,risk:{...n,expiresAt:o}}}function Uo({side:e,coin:t,interval:r,risk:n,expiresAt:o,id:a,name:i,spec:s}){let l=[{id:"c",type:"input",field:"close"},{id:"rsi",type:"indicator",indicator:"rsi",input:"c",period:s.period},{id:"thr",type:"constant",value:s.threshold},{id:"sig",type:"compare",op:s.op==="above"?"gt":"lt",left:"rsi",right:"thr"}];return{version:1,id:a,name:i,venue:"hyperliquid",market:{coin:t,interval:r},parameters:{},nodes:l,rules:{entryLong:e==="long"?"sig":null,entryShort:e==="short"?"sig":null,exitLong:null,exitShort:null},risk:{...n,expiresAt:o}}}function Co({side:e,coin:t,interval:r,risk:n,expiresAt:o,id:a,name:i,spec:s}){let l=[{id:"fr",type:"input",field:"fundingRate"},{id:"thr",type:"constant",value:s.threshold},{id:"sig",type:"compare",op:s.op==="above"?"gt":"lt",left:"fr",right:"thr"}];return{version:1,id:a,name:i,venue:"hyperliquid",market:{coin:t,interval:r},parameters:{},nodes:l,rules:{entryLong:e==="long"?"sig":null,entryShort:e==="short"?"sig":null,exitLong:null,exitShort:null},risk:{...n,expiresAt:o}}}function _t(e,t={}){if(typeof e!="string")throw new B("prompt must be a string");if(e.length>1e3)throw new B("prompt length must be <= 1000");if(!$o(t))throw new B("options must be a plain object");if(!Number.isInteger(t.nowMs))throw new B("options.nowMs is required integer epoch ms");let r=t.nowMs,n=Po;if("expiresInMs"in t){if(!Number.isInteger(t.expiresInMs))throw new B("expiresInMs must be an integer");if(n=t.expiresInMs,n<ko||n>Ao)throw new B("expiresInMs must be between 1h and 30d")}if(xo.test(e))throw new B(`prompt appears to contain secrets and is rejected. ${Ee}`);let o=To(e);if(!o)throw new B(`empty prompt. ${Ee}`);if(Mo(o))throw new B(`duplicate interval or risk clause. ${Ee}`);let a=_o(o),i=Io(o),s=Oo(o);if(!a||!i||!s)throw new B(`could not parse side/coin/interval. ${Ee}`);let l=vo(o);if(!(l.maxLeverage>0)||l.maxLeverage>50)throw new B("leverage out of range");if(!(l.positionSizePct>0)||l.positionSizePct>100)throw new B("position size out of range");let u=r+n,f=No(o),c=`Draft ${i} ${a}`.slice(0,100),d=Ro(o),m=Lo(o),p=jo(o),h=[d,m,p].filter(Boolean);if(h.length!==1)throw new B(`unsupported or ambiguous prompt. ${Ee}`);if(!Fo(o,h[0]))throw new B(`unsupported or ambiguous prompt. ${Ee}`);let E,k=h[0],P={side:a,coin:i,interval:s,risk:l,expiresAt:u,id:f,name:c,spec:k};k.kind==="ema_cross"?E=Ho(P):k.kind==="rsi"?E=Uo(P):E=Co(P);let T=Be(E,{nowMs:r});if(!T.ok)throw new B(`draft failed validation: ${T.errors.map(x=>x.message).join("; ")}`);return Tt(V(E,{nowMs:r}))}import oe from"node:fs";import ze from"node:path";var Ot=1,qo=["privatekey","secretkey","seed","mnemonic","passphrase","password","keystore","keymaterial","apikey","authtoken","accesstoken","refreshtoken","credential","bearer","signature","authorization","xprv","xpriv","wif"];function Ve(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function te(e){return e==null?e:JSON.parse(JSON.stringify(e))}function Bo(e){return String(e).toLowerCase().replace(/[^a-z0-9]/g,"")}function xe(e,t="record"){if(Array.isArray(e)){e.forEach((r,n)=>xe(r,`${t}[${n}]`));return}if(Ve(e))for(let[r,n]of Object.entries(e)){let o=Bo(r);if(qo.some(a=>o.includes(a)))throw new Error(`shadow-store: forbidden secret-like field at ${t}.${r}`);xe(n,`${t}.${r}`)}}function Do(e){if(typeof e!="string"||!e||!ze.isAbsolute(e))throw new Error("shadow-store: path must be an absolute path")}function Or(e){let t;try{t=oe.lstatSync(e)}catch(n){if(n&&n.code==="ENOENT")return;throw n}if(t.isSymbolicLink())throw new Error("shadow-store: store path must not be a symlink");if(!t.isFile())throw new Error("shadow-store: store path must be a regular file");if(t.mode&511&18)throw new Error("shadow-store: store file must not be group or world writable")}function zo(){return{version:Ot,runners:[]}}function vr(e,t){let r;try{r=JSON.parse(e)}catch{throw new Error("shadow-store: malformed JSON")}if(!Ve(r))throw new Error("shadow-store: malformed JSON root");if(r.version!==Ot)throw new Error(`shadow-store: unsupported version ${r.version}`);if(!Array.isArray(r.runners))throw new Error("shadow-store: runners must be an array");return xe(r,ze.basename(t)),{version:Ot,runners:r.runners.map(n=>te(n))}}function Mr(e,t){xe(t,"store");let r=ze.dirname(e);oe.mkdirSync(r,{recursive:!0,mode:448});let n=ze.join(r,`.shadow-store.${process.pid}.${Date.now()}.tmp`),o=`${JSON.stringify(t)}
3
+ `;try{oe.writeFileSync(n,o,{mode:384,flag:"wx"}),oe.renameSync(n,e);try{oe.chmodSync(e,384)}catch{}}catch(a){try{oe.unlinkSync(n)}catch{}throw a}}var It=new Map;function vt(e={}){let t=e.path;if(Do(t),Or(t),oe.existsSync(t)?vr(oe.readFileSync(t,"utf8"),t):Mr(t,zo()),It.has(t))return It.get(t);let r=!1,n=[];function o(){if(r)return;let p=n.shift();if(p){r=!0;try{let h=p.fn();r=!1,p.resolve(h),o()}catch(h){r=!1,p.reject(h),o()}}}function a(p){if(!r&&n.length===0){r=!0;try{return p()}finally{r=!1,queueMicrotask(o)}}return new Promise((h,E)=>{n.push({fn:p,resolve:h,reject:E}),queueMicrotask(o)})}function i(){return Or(t),vr(oe.readFileSync(t,"utf8"),t)}function s(p){Mr(t,p)}function l(p){if(!Ve(p)||typeof p.id!="string"||!p.id)throw new Error("shadow-store: create requires record with string id");xe(p,"record");let h=i();if(h.runners.some(k=>k.id===p.id))throw new Error(`shadow-store: runner id already exists: ${p.id}`);let E=te(p);return h.runners.push(E),s(h),te(E)}function u(p){let h=i().runners.find(E=>E.id===p);return h?te(h):null}function f(){return i().runners.map(p=>te(p))}function c(p,h){if(typeof h!="function")throw new Error("shadow-store: updater must be a function");let E=i(),k=E.runners.findIndex(x=>x.id===p);if(k<0)throw new Error(`shadow-store: runner not found: ${p}`);let P=te(E.runners[k]),T=h(P);if(!Ve(T)||T.id!==p)throw new Error("shadow-store: updater must return record with same id");return xe(T,"record"),E.runners[k]=te(T),s(E),te(E.runners[k])}function d(p){let h=i(),E=h.runners.findIndex(P=>P.id===p);if(E<0)throw new Error(`shadow-store: runner not found: ${p}`);let k=te(h.runners[E]);return k.status!=="stopped"&&(k.status="stopped",h.runners[E]=k,s(h)),te(h.runners[E])}let m={create(p){return a(()=>l(p))},get(p){return u(p)},list(){return f()},update(p,h){return a(()=>c(p,h))},stop(p){return a(()=>d(p))}};return It.set(t,m),m}import{createHash as Rt}from"node:crypto";function Mt(e){return e==null?e:JSON.parse(JSON.stringify(e))}function Nt(e){return Array.isArray(e)?e.map(Nt):e&&typeof e=="object"?Object.fromEntries(Object.keys(e).sort().map(t=>[t,Nt(e[t])])):e}function Rr(e){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("shadow-runner: record must be an object");return Rt("sha256").update(JSON.stringify(Nt(e))).digest("hex")}function Vo(e,t,r,n,o){return Rt("sha256").update(`${e}|${t}|${r}|${n}|${o}`).digest("hex")}function Jo(e,t,r,n){return Rt("sha256").update(`shadow|${e}|${t}|${r}|${n??""}`).digest("hex")}function Ko(e){return e==="entryLong"||e==="exitShort"?"buy":e==="entryShort"||e==="exitLong"?"sell":e}function Nr(e){return e==="entryLong"||e==="entryShort"}function Je({storePath:e,clock:t=Date.now}={}){if(typeof e!="string"||!e)throw new Error("shadow-runner: storePath required");let r=vt({path:e});function n({strategy:l,evidenceId:u=null}={}){let f=z(l),c=u==null?null:String(u),d=r.list().filter(k=>k.status==="running"&&k.strategyHash===f.strategyHash&&k.compilerHash===f.compilerHash&&k.evidenceId===c).sort((k,P)=>k.createdAt-P.createdAt||k.id.localeCompare(P.id))[0];if(d)return Mt(d);let m=t(),p=Jo(m,f.strategyHash,f.compilerHash,c),h=r.get(p);if(h)return Mt(h);let E={id:p,strategy:Mt(f.strategy),strategyHash:f.strategyHash,compilerHash:f.compilerHash,evidenceId:c,status:"running",cursor:null,intendedOrders:[],fills:[],missedFills:[],markouts:[],createdAt:m,updatedAt:m,position:null,cooldownBarsRemaining:0,cooldownStartT:null,lastProcessedBarIndex:-1};return r.create(E)}function o(l){return r.get(l)}function a(){return r.list()}function i(l){return r.stop(l)}function s(l,u,{markoutHorizons:f=[1,4,12]}={}){if(!Array.isArray(u))throw new TypeError("shadow-runner: bars must be an array");return r.update(l,c=>{if(c.status!=="running")throw new Error("shadow-runner: runner is stopped");if(u.length===0)return c;let m=z(c.strategy).evaluateAll(u),p=new Map;for(let y=0;y<u.length;y++)p.set(u[y].t,y);let h=c.cursor,E=[];for(let y=0;y<u.length;y++){let A=u[y].t;(h==null||A>h)&&E.push(y)}if(E.length===0)return c;let k=new Map(c.intendedOrders.map(y=>[y.id,y])),P=new Set(c.fills.map(y=>y.orderId)),T=new Map(c.missedFills.map(y=>[y.orderId,y])),x=(y,A)=>`${y}|${A}`,R=new Map(c.markouts.map(y=>[x(y.orderId,y.horizon),y])),_=c.position?{...c.position}:null,g=Number.isInteger(c.cooldownBarsRemaining)?Math.max(0,c.cooldownBarsRemaining):0,J=Number.isFinite(c.cooldownStartT)?c.cooldownStartT:null;function se({action:y,signalBarT:A,signalIndex:v}){let L=Ko(y),j=Vo(c.id,c.strategyHash,A,L,y);if(k.has(j))return k.get(j);let I=v+1,M=I<u.length,D={id:j,action:y,type:y,side:L,signalBarT:A,fillBarT:M?u[I].t:null,status:M?"open":"missed"};return k.set(j,D),c.intendedOrders.push(D),D}function ie(y,A,v){if(P.has(y.id))return;let L={orderId:y.id,action:Nr(y.action)?"entry":"exit",side:y.side,price:A.o,barT:A.t,signalBarT:y.signalBarT,barIndex:v};if(c.fills.push(L),P.add(y.id),y.status="filled",y.fillBarT=A.t,T.has(y.id)&&(T.delete(y.id),c.missedFills=c.missedFills.filter(j=>j.orderId!==y.id)),Nr(y.action)){_={side:y.action==="entryLong"?"long":"short",entryOrderId:y.id,entryBarT:A.t,entryPrice:A.o,entryBarIndex:v};for(let j of f){let I=x(y.id,j);if(R.has(I))continue;let M={orderId:y.id,horizon:j,entryBarT:A.t,entryPrice:A.o,side:_.side,status:"pending",close:null,barT:null};R.set(I,M),c.markouts.push(M)}}else _=null,g=Number(c.strategy?.risk?.cooldownBars)||0,J=A.t}function X(y){if(P.has(y.id)||T.has(y.id))return;let A={orderId:y.id,action:y.action,side:y.side,signalBarT:y.signalBarT,status:"missed"};T.set(y.id,A),c.missedFills.push(A),y.status="missed"}for(let y of c.intendedOrders){if(y.status==="filled"||P.has(y.id))continue;let A=p.get(y.signalBarT);if(A==null)continue;let v=A+1;v<u.length&&(h==null||u[v].t>h)&&ie(y,u[v],v)}for(let y of E){let A=u[y],v=m[y].signals,L=_,j=M=>{if(_||g>0&&(J==null||A.t>=J))return;let C=se({action:M,signalBarT:A.t,signalIndex:y}),Z=y+1;Z<u.length?ie(C,u[Z],Z):X(C)},I=M=>{if(!_||_.side==="long"&&M!=="exitLong"||_.side==="short"&&M!=="exitShort")return;let D=se({action:M,signalBarT:A.t,signalIndex:y}),C=y+1;C<u.length?ie(D,u[C],C):X(D)};L?(v.exitLong&&I("exitLong"),v.exitShort&&I("exitShort")):v.entryLong&&v.entryShort||(v.entryLong&&j("entryLong"),v.entryShort&&j("entryShort")),g>0&&J!=null&&A.t>=J&&(g-=1,g===0&&(J=null)),c.cursor=A.t,c.lastProcessedBarIndex=y}for(let y of c.markouts){if(y.status!=="pending")continue;let A=c.fills.find(j=>j.orderId===y.orderId&&j.action==="entry");if(!A)continue;let v=p.get(A.barT);if(v==null)continue;let L=v+y.horizon;if(L<u.length){y.close=u[L].c,y.barT=u[L].t,y.status="filled";let j=y.entryPrice;y.markout=y.side==="long"?(y.close-j)/j:(j-y.close)/j}}return c.position=_,c.cooldownBarsRemaining=g,c.cooldownStartT=J,c.updatedAt=t(),c})}return{start:n,step:s,list:a,get:o,stop:i}}import Yo from"node:os";import Go from"node:path";var Xo=["privatekey","secretkey","seed","mnemonic","passphrase","password","keystore","keymaterial","apikey","authtoken","accesstoken","refreshtoken","credential","bearer","signature","authorization","xprv","xpriv","wif"];function ve(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function Zo(e){return String(e).toLowerCase().replace(/[^a-z0-9]/g,"")}function jt(e){if(Array.isArray(e)){for(let t of e)jt(t);return}if(ve(e))for(let[t,r]of Object.entries(e)){if(Xo.some(n=>Zo(t).includes(n)))throw new Error(`strategy service: secret-like field "${t}" is forbidden`);jt(r)}}function Wo(e){if(!ve(e))throw new TypeError("strategy input must be a plain object");return jt(e),e}function Qo(e,t={}){if(t.nowMs!==void 0){if(!Number.isInteger(t.nowMs))throw new TypeError("nowMs must be an integer epoch milliseconds");return t.nowMs}let r=Date.now();if(e.nowMs===void 0||e.nowMs===null)return r;if(!Number.isInteger(e.nowMs))throw new TypeError("nowMs must be an integer epoch milliseconds");if(Math.abs(e.nowMs-r)>12e4)throw new Error("nowMs outside allowed wall-clock skew (120s); omit nowMs to use server time");return e.nowMs}async function Lt(e,t,r,n){if(Array.isArray(t.bars))return t.bars;let o=Ue(e.venue),a=r.fetchBars??o.fetchBars;if(typeof a!="function")throw new Error(`strategy venue ${o.id} does not support history`);let i=await a({coin:e.market.coin,interval:e.market.interval,count:t.count??1500,endTime:t.endTime??n}),s=Array.isArray(i)?i:i?.bars;if(!Array.isArray(s))throw new Error("strategy history provider returned no bars");return s}function Ft(e,t){let r=e.backtestOptions??{};if(!ve(r))throw new TypeError("backtestOptions must be a plain object");return{...r,nowMs:t}}function Lr(e,t,r,n,o={}){let a=e.evidenceOptions??{};if(!ve(a))throw new TypeError("evidenceOptions must be a plain object");return{...a,...o,strategy:t,bars:r,backtestOptions:Ft(e,n)}}function jr(){return Go.join(Yo.homedir(),".oracle","strategy-shadow.json")}function es(e,t){return{perStrategyNotionalUsd:e.risk.maxNotionalUsd,maxLeverage:e.risk.maxLeverage,dailyLossCapUsd:e.risk.maxNotionalUsd*(e.risk.maxDailyLossPct/100),chainAllowlist:[e.venue],assetAllowlist:[e.market.coin],expiresAt:Math.min(e.risk.expiresAt,t+864e5),killSwitchRequired:!0}}async function ts(e,t={},r={}){let n=Wo(t),o=Qo(n,r);if(e==="draft")return{strategy:_t(n.prompt,{nowMs:o})};if(e==="validate"){let a=z(n.strategy);if(a.strategy.risk.expiresAt<=o)throw new Error("strategy is expired");return{valid:!0,strategy:a.strategy,strategyHash:a.strategyHash,compilerHash:a.compilerHash,compilerVersion:a.compilerVersion,requiredSeries:a.requiredSeries}}if(e==="backtest"||e==="evidence"){let a=z(n.strategy),i=await Lt(a.strategy,n,r,o);Te(a,i);let s=Fe(Lr(n,a.strategy,i,o));return e==="evidence"?s:{backtest:ne(a.strategy,i,Ft(n,o)),evidence:s}}if(e==="optimize"){let a=z(n.strategy),i=await Lt(a.strategy,n,r,o);Te(a,i);let s=n.trainFraction,l=n.evidenceOptions?.trainFraction;if(s!=null&&l!=null&&s!==l)throw new TypeError("conflicting trainFraction controls are forbidden");let u=s??l??.7;if(typeof u!="number"||u<=0||u>=1)throw new TypeError("trainFraction must be in (0,1)");let f=i.slice(0,Math.floor(i.length*u)),c=n.options??{};if(!ve(c))throw new TypeError("options must be a plain object");let d=$t(a.strategy,f,{...c,...n.maxTrials==null?{}:{maxTrials:n.maxTrials},backtestOptions:Ft(n,o)}),m=d.bestStrategy;return{strategy:m,optimization:d,evidence:Fe(Lr(n,m,i,o,{trainFraction:u}))}}if(e==="shadow"){let a=Je({storePath:r.storePath??jr(),clock:()=>o}),i=n.action;if(i==="start")return await a.start({strategy:n.strategy,evidenceId:n.evidenceId??n.evidence?.id??null});if(i==="list")return await a.list();if(i==="get")return await a.get(n.id);if(i==="stop")return await a.stop(n.id);if(i==="step"){let s=await a.get(n.id);if(!s)throw new Error(`shadow runner not found: ${n.id}`);let l=await Lt(s.strategy,n,r,o);return Te(z(s.strategy),l),await a.step(n.id,l,n.stepOptions??{})}throw new Error(`unknown shadow action: ${i}`)}if(e==="prepare"){let a=z(n.strategy),i=Ue(a.strategy.venue);if(typeof n.shadowId!="string"||!n.shadowId)throw new Error("strategy prepare requires a matching shadow runner id");let l=await Je({storePath:r.storePath??jr(),clock:()=>o}).get(n.shadowId);if(!l)throw new Error("strategy prepare shadow runner not found");if(l.status!=="running")throw new Error("strategy prepare requires an active shadow runner");if(!Number.isFinite(l.cursor))throw new Error("strategy prepare requires a stepped shadow runner");if(l.strategyHash!==a.strategyHash||l.compilerHash!==a.compilerHash)throw new Error("strategy prepare shadow runner does not match strategy artifacts");if(l.evidenceId!==n.evidence?.id)throw new Error("strategy prepare shadow runner does not match evidence artifact");let u=n.caps??es(a.strategy,o);return i.prepareIntent({strategy:a.strategy,evidence:n.evidence,shadow:{id:l.id,stateHash:Rr(l),status:l.status,cursor:l.cursor,updatedAt:l.updatedAt},caps:u,nowMs:o,env:r.env??process.env})}throw new Error(`unknown strategy operation: ${e}`)}export{or as EVIDENCE_STATUSES,At as MAX_OPTIMIZER_TRIALS,ce as STRATEGY_COMPILER_HASH,he as STRATEGY_COMPILER_VERSION,Ce as STRATEGY_VERSION,B as StrategyDraftError,pe as StrategyValidationError,ye as applyParameterOverrides,dt as assertEvidenceArtifact,ot as atr,ne as backtestStrategy,nt as bollinger,Pr as canonicalStrategyJson,z as compileStrategy,ft as computeEvidenceArtifactId,Je as createShadowRunner,_t as draftStrategyFromPrompt,Ae as ema,Fe as evaluateEvidence,wt as fetchHyperliquidStrategyBars,lr as intervalToMs,rt as macd,ur as normalizeHyperliquidCandles,V as normalizeStrategy,vt as openShadowStore,$t as optimizeStrategy,yt as prepareStrategyLiveHandoff,Ue as requireStrategyVenue,He as resolveStrategyVenue,tt as rsi,ts as runStrategyOperation,et as sma,fe as strategyHash,eo as strategyVenues,Be as validateStrategy};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oracle-agent/oracle",
3
- "version": "0.22.12",
3
+ "version": "0.22.13",
4
4
  "description": "Oracle: standalone prepare-only multichain agent control plane. Runs its own agent loop, or plugs into any MCP-compatible harness. Policy-bounded intents for a user-signed wallet; the public package never takes your key.",
5
5
  "license": "BUSL-1.1",
6
6
  "type": "module",