@oracle-agent/oracle 0.30.0 → 0.32.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/strategy/index.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{createHash as
|
|
2
|
-
`),l=cn("sha256").update(s).digest("hex").slice(0,32),u=`${n.untrustedUrl?"untrusted":"trusted"}:${n.maxResponseBytes??"unbounded"}`;return`${e} ${t} ${u} ${l}`}function gn(e,t){let r=Number(t);return Number.isFinite(r)&&r>0?Math.min(r*1e3,nr):Math.min(250*2**e,nr)+Math.floor(Math.random()*100)}var bn=e=>new Promise(t=>setTimeout(t,e));function Pe(e,t={}){let r=new Error(e);return r.retryable=!1,Object.assign(r,t),r}function lt(e,t,r){return Pe(`HTTP response from ${e} exceeded maxResponseBytes ${r} (${t})`,{oversize:!0})}function $e(e){try{let t=e?.body?.cancel?.();t&&typeof t.then=="function"&&t.catch(()=>{})}catch{}}function En(e){return e?e.byteLength??e.length??0:0}async function sr(e,t,{url:r,truncate:n=!1,onOversize:o}={}){if(t==null)return await e.text();let a=Number(e.headers?.get?.("content-length"));if(Number.isFinite(a)&&a>t&&($e(e),!n))throw lt(r,`content-length ${a}`,t);let i=e.body?.getReader?.();if(!i){let c=await e.text(),f=Buffer.byteLength(c,"utf8");if(f>t){if(!n)throw lt(r,`body ${f} bytes`,t);return Buffer.from(c,"utf8").subarray(0,t).toString("utf8")}return c}let s=[],l=0,u=!1;try{for(;;){let{value:c,done:f}=await i.read();if(f)break;if(c&&(s.push(Buffer.from(c)),l+=En(c),l>t)){u=!0;break}}}finally{if(u)try{await i.cancel()}catch{}try{i.releaseLock?.()}catch{}}if(u&&(typeof o=="function"&&o(),!n))throw lt(r,`streamed ${l} bytes`,t);let d=Buffer.concat(s);return(u?d.subarray(0,t):d).toString("utf8")}function ir(e){if(!e)return null;try{return JSON.parse(e)}catch{return null}}async function xn(e,{fetchImpl:t,method:r,headers:n,body:o,timeoutMs:a,lookupFn:i,realFetch:s,untrustedUrl:l=!1,maxResponseBytes:u=null,importUndici:d,validateResponse:c,signal:f}){let p=new AbortController,h=setTimeout(()=>p.abort(),a),w=f?typeof AbortSignal.any=="function"?AbortSignal.any([f,p.signal]):f:p.signal,b=null,S=t,$=i?{lookupFn:i}:{};if(l&&!s&&!at(S))throw Pe(`HTTP refused ${e}: untrustedUrl requires a pin-capable fetchImpl (see markPinCapableFetch in egress-guard.mjs) or no fetchImpl override so Oracle can pin the connection itself`);let I=async(x,{status:_=null}={})=>{let A=await ot(x,$);if(!A.ok)throw Pe(_==null?`HTTP refused ${x}: ${A.error}`:`HTTP redirect to ${x} ${A.error}`,_==null?{}:{status:_});let m=new URL(x).hostname;if(s){if(b&&(await b.close(),b=null),!b)try{b=await st({requireUndici:!0,...d?{importUndici:d}:{}})}catch(M){throw Pe(_==null?`HTTP refused ${x}: ${M?.message||M}`:`HTTP redirect to ${x} refused: ${M?.message||M}`,_==null?{}:{status:_})}b.pin(m,A.addresses),S=b.fetch}else tr(S,m,A.addresses);return A};try{let x=String(e),_={...n||{}};l&&await I(x);for(let A=0;A<=or;A+=1){let m=await S(x,{method:r,headers:_,body:o,signal:w,redirect:"manual"});if(fn.has(m.status)){if(r!=="GET"&&r!=="HEAD"){let P=await sr(m,u??dn,{url:x,truncate:!0}),T=new Error(`HTTP ${m.status} ${r} ${x} redirected non-idempotent request`);throw T.status=m.status,T.body=ir(P)??P.slice(0,300),T}if(A===or)throw $e(m),new Error(`HTTP redirect loop for ${e}`);let q=m.headers?.get?.("location"),z;try{z=hn(q,x)}catch(P){throw $e(m),P}let y=!yn(z,x);if($e(m),y&&(_=mn(_)),l)await I(z,{status:m.status});else if(y){let P=await ot(z,$);if(!P.ok){let T=new Error(`HTTP redirect from ${x} ${P.error}`);throw T.status=m.status,T.retryable=!1,T}s&&P.addresses?.length&&(b||(b=await st(d?{importUndici:d}:{})),b&&(b.pin(new URL(z).hostname,P.addresses),S=b.fetch))}x=z;continue}if(typeof c=="function")try{await c(m,{url:x})}catch(q){throw $e(m),Pe(q?.message||String(q))}let M=await sr(m,u,{url:x,onOversize:()=>p.abort()}),G=ir(M);if(!m.ok){let q=new Error(`HTTP ${m.status} ${r} ${x}`);throw q.status=m.status,q.retryAfter=m.headers?.get?.("retry-after")??null,q.body=G??M.slice(0,300),q}return G??M}throw new Error(`HTTP redirect loop for ${e}`)}finally{clearTimeout(h),b&&await b.close()}}async function cr(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):un,l=t.lookupFn,u=!t.fetchImpl,d=t.untrustedUrl===!0,c=t.importUndici,f=t.validateResponse,p=t.signal,h=Number(t.maxResponseBytes),w=Number.isFinite(h)&&h>0?Math.floor(h):null,b=async()=>{let _;for(let A=0;A<=s;A++){p?.throwIfAborted?.();try{return await xn(e,{fetchImpl:r,method:o,headers:a,body:i,timeoutMs:n,lookupFn:l,realFetch:u,untrustedUrl:d,maxResponseBytes:w,importUndici:c,validateResponse:f,signal:p})}catch(m){_=m;let M=m?.status,G=m?.name==="AbortError"||m?.name==="TimeoutError"||p?.aborted,q=new Set([408,425,429]),z=m?.retryable===!1?!1:M!=null?q.has(M)||ln.has(M)&&rr.has(o):!G&&rr.has(o);if(A===s||!z)throw m;let y=gn(A,m?.retryAfter);p?await new Promise((P,T)=>{let L=setTimeout(P,y);p.addEventListener("abort",()=>{clearTimeout(L),T(p.reason||new DOMException("Aborted","AbortError"))},{once:!0})}):await bn(y)}}throw _};if(!(t.dedupe!==!1&&!p&&o==="GET"&&i==null))return b();let $=wn(o,e,a,{untrustedUrl:d,maxResponseBytes:w}),I=ct.get($);if(I)return I;let x=b().finally(()=>ct.delete($));return ct.set($,x),x}var Sn="https://api.hyperliquid.xyz/info",kn="https://api.hyperliquid-testnet.xyz/info";function An({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"?kn:Sn}async function ut(e,t={}){if(!e||!e.type)throw new Error("hlInfo requires body.type");let r=An(t);return cr(r,{method:"POST",body:e,fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs})}async function lr(e={}){return ut({type:"meta"},e)}async function ur({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 ut(a,o)}async function fr({coin:e,startTime:t,endTime:r},n={}){if(!e)throw new Error("hlFundingHistory requires coin");return ut({type:"fundingHistory",coin:String(e),startTime:t??Date.now()-24*3600*1e3,endTime:r??Date.now()},n)}function _e(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 Pn(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 ft(e,t){_e(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 Te(e,t){_e(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 dt(e,t){_e(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]=dr(a,i);for(let s=t+1;s<e.length;s++){let l=e[s]-e[s-1],u=l>0?l:0,d=l<0?-l:0;a=(a*(t-1)+u)/t,i=(i*(t-1)+d)/t,r[s]=dr(a,i)}return r}function dr(e,t){return e===0&&t===0?50:t===0?100:e===0?0:100-100/(1+e/t)}function pt(e,t={}){_e(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=Te(e,r),i=Te(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),d=[];for(let c=0;c<s.length;c++)s[c]!=null&&d.push(c);if(d.length>=o){let c=0;for(let w=0;w<o;w++)c+=s[d[w]];let f=c/o,p=d[o-1];l[p]=f,u[p]=s[p]-f;let h=2/(o+1);for(let w=o;w<d.length;w++){let b=d[w];f=h*s[b]+(1-h)*f,l[b]=f,u[b]=s[b]-f}}return{line:s,signal:l,histogram:u}}function mt(e,t={}){_e(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 d=e[u];if(s+=d,l+=d*d,u>=r){let c=e[u-r];s-=c,l-=c*c}if(u>=r-1){let c=s/r,f=l/r-c*c;f<0&&f>-1e-12&&(f=0);let p=Math.sqrt(f);o[u]=c,a[u]=c+n*p,i[u]=c-n*p}}return{upper:a,middle:o,lower:i}}function ht(e,t){Pn(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 $n}from"node:crypto";var yt=2,Tn="93f9c998260e73756c13871dc1a84dd6cdb26ec6113bd1941f023519939db440",_n="68f5b412a9975f04024cf9b9b6209b4bccedd52f176e95f34f786b3f53479c6a",In="f197a38ff1c0f4ebe13326db8cbb8167ea3dd5d62e6033fe97c2fee8d23d96b5",pr=$n("sha256").update(JSON.stringify({version:yt,compilerSourceHash:Tn,indicatorsSourceHash:_n,schemaSourceHash:In})).digest("hex");var ye=yt,ce=pr,On=Object.freeze({open:"o",high:"h",low:"l",close:"c",volume:"v",fundingRate:"fundingRate",openInterest:"openInterest"}),vn=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 Z(e){return typeof e=="number"&&Number.isFinite(e)}function Nn(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 he(e,t){return e!=null&&typeof e=="object"&&"param"in e?t[e.param].value:e}function Mn(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:d,v:c}=a;if(!Z(i)&&(typeof i=="number"&&Number.isFinite(i)),!Number.isFinite(i))throw new TypeError(`bars[${o}].t must be finite`);for(let[f,p]of[["o",s],["h",l],["l",u],["c",d],["v",c]])if(!Z(p))throw new TypeError(`bars[${o}].${f} must be a finite number`);for(let[f,p]of[["o",s],["h",l],["l",u],["c",d]])if(!(p>0))throw new TypeError(`bars[${o}].${f} price must be positive`);if(c<0)throw new TypeError(`bars[${o}].v volume must be non-negative`);if(l<Math.max(s,d,u))throw new TypeError(`bars[${o}] high must be >= max(open, close, low)`);if(u>Math.min(s,d,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!==vn[r])throw new TypeError(`bars t must match ${r} cadence`)}if(n=i,"fundingRate"in a&&a.fundingRate!=null&&!Z(a.fundingRate))throw new TypeError(`bars[${o}].fundingRate must be finite when present`);if("openInterest"in a&&a.openInterest!=null){if(!Z(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 fe(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=On[i.field];s=new Array(o+1);for(let u=0;u<=o;u++){let d=n[u][l];s[u]=d===void 0?null:d}break}case"constant":{let l=he(i.value,r);s=new Array(o+1).fill(l);break}case"indicator":{let l=i.period!=null?he(i.period,r):void 0;if(i.indicator==="atr"){let c=[];for(let f=0;f<=o;f++){let p=n[f];c.push({o:p.o,h:p.h,l:p.l,c:p.c})}s=ht(c,l);break}let d=fe(i.input,t,r,n,o,a).map((c,f)=>{if(c==null||!Z(c))throw new TypeError(`indicator input ${i.input} has non-finite value at ${f}`);return c});if(i.indicator==="sma")s=ft(d,l);else if(i.indicator==="ema")s=Te(d,l);else if(i.indicator==="rsi")s=dt(d,l);else if(i.indicator==="macd")s=pt(d,{fastPeriod:he(i.fastPeriod,r),slowPeriod:he(i.slowPeriod,r),signalPeriod:he(i.signalPeriod,r)})[i.output];else if(i.indicator==="bollinger")s=mt(d,{period:l,stdDev:he(i.stdDev,r)})[i.output];else throw new Error(`unsupported indicator ${i.indicator}`);break}case"compare":{let l=fe(i.left,t,r,n,o,a),u=fe(i.right,t,r,n,o,a);s=new Array(o+1);for(let d=0;d<=o;d++){let c=l[d],f=u[d];if(c==null||f==null||!Z(c)||!Z(f)){s[d]=!1;continue}switch(i.op){case"gt":s[d]=c>f;break;case"gte":s[d]=c>=f;break;case"lt":s[d]=c<f;break;case"lte":s[d]=c<=f;break;case"eq":s[d]=c===f;break;default:s[d]=!1}}break}case"logic":{let l=i.inputs.map(u=>fe(u,t,r,n,o,a));s=new Array(o+1);for(let u=0;u<=o;u++)if(i.op==="not"){let d=l[0][u];s[u]=d===!0?!1:d===!1}else if(i.op==="and"){let d=!0;for(let c of l)if(c[u]!==!0){d=!1;break}s[u]=d}else if(i.op==="or"){let d=!1;for(let c of l)if(c[u]===!0){d=!0;break}s[u]=d}else s[u]=!1;break}case"cross":{let l=fe(i.left,t,r,n,o,a),u=fe(i.right,t,r,n,o,a);s=new Array(o+1),s[0]=!1;for(let d=1;d<=o;d++){let c=l[d-1],f=u[d-1],p=l[d],h=u[d];if(c==null||f==null||p==null||h==null||!Z(c)||!Z(f)||!Z(p)||!Z(h)){s[d]=!1;continue}i.direction==="above"?s[d]=c<=f&&p>h:s[d]=c>=f&&p<h}break}default:throw new Error(`unknown node type ${i.type}`)}return a.set(e,s),s}function K(e,t={}){let r=Y(e);t&&Object.keys(t).length&&(r=we(r,t));let n=new Map(r.nodes.map(p=>[p.id,p])),o=Object.freeze(Nn(r.nodes)),a=r.parameters,i=new Set(r.nodes.filter(p=>p.type==="input").map(p=>p.field));if(r.nodes.some(p=>p.type==="indicator"&&p.indicator==="atr"))for(let p of["open","high","low","close"])i.add(p);let s=Object.freeze([...i].sort()),l=de(r);function u(p,h){let w={};for(let S of o){let $=p.get(S);w[S]=$[h]}let b=S=>S!=null&&w[S]===!0;return{values:w,signals:{entryLong:b(r.rules.entryLong),entryShort:b(r.rules.entryShort),exitLong:b(r.rules.exitLong),exitShort:b(r.rules.exitShort)}}}function d(p,h){Mn(p,h,r.market.interval);let w=new Map;for(let b of o)fe(b,n,a,p,h,w);return w}function c(p,h){return u(d(p,h),h)}function f(p){if(!Array.isArray(p)||p.length===0)throw new TypeError("bars must be a non-empty array");let h=p.length-1,w=d(p,h);return Object.freeze(p.map((b,S)=>Object.freeze(u(w,S))))}return Object.freeze({strategy:r,strategyHash:l,compilerVersion:ye,compilerHash:ce,requiredSeries:s,nodeOrder:o,evaluate:c,evaluateAll:f})}import{createHash as Gn}from"node:crypto";import{createHash as Rn}from"node:crypto";var Ln=Object.freeze({initialEquityUsd:1e4,takerFeeBps:3.5,builderFeeBps:2,slippageBps:2,latencyBars:1,maxVolumeParticipationPct:100});function Fn(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function te(e){return typeof e=="number"&&Number.isFinite(e)}function wt(e){if(e==null||typeof e!="object"||Object.isFrozen(e))return e;if(Array.isArray(e)){for(let t of e)wt(t);return Object.freeze(e)}for(let t of Object.keys(e))wt(e[t]);return Object.freeze(e)}function Ce(e){if(Array.isArray(e))return e.map(Ce);if(e!=null&&typeof e=="object"){let t={};for(let r of Object.keys(e).sort())t[r]=Ce(e[r]);return t}return e}function gt(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)=>gt(r,`${t}[${n}]`));return}for(let[r,n]of Object.entries(e))gt(n,`${t}.${r}`)}}function hr(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(!te(o))throw new TypeError(`bars[${r}].t must be finite`);for(let[d,c]of[["o",a],["h",i],["l",s],["c",l],["v",u]])if(!te(c))throw new TypeError(`bars[${r}].${d} must be a finite number`);for(let[d,c]of[["o",a],["h",i],["l",s],["c",l]])if(!(c>0))throw new TypeError(`bars[${r}].${d} 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&&!te(n.fundingRate))throw new TypeError(`bars[${r}].fundingRate must be finite when present`);if("fundingPaymentRate"in n&&n.fundingPaymentRate!=null&&!te(n.fundingPaymentRate))throw new TypeError(`bars[${r}].fundingPaymentRate must be finite when present`);if("openInterest"in n&&n.openInterest!=null&&!te(n.openInterest))throw new TypeError(`bars[${r}].openInterest must be finite when present`)}}function Ie(e){if(!Array.isArray(e))throw new TypeError("bars must be an array");return e.length>0&&hr(e),Rn("sha256").update(JSON.stringify(Ce(e)),"utf8").digest("hex")}function jn(e){if(e==null&&(e={}),!Fn(e))throw new TypeError("options must be a plain object");let t={...Ln},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(!te(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(!te(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(!te(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 Ue(e){return e/1e4}function Hn(e,t,r){let n=Ue(r);return t==="long"?e*(1+n):e*(1-n)}function Cn(e,t,r){let n=Ue(r);return t==="long"?e*(1-n):e*(1+n)}function mr(e,t,r){let n=Math.abs(e)*Ue(t),o=Math.abs(e)*Ue(r);return{taker:n,builder:o,total:n+o}}function Un(e,t){let r=e*(t.positionSizePct/100)*t.maxLeverage;return Math.min(r,t.maxNotionalUsd)}function qn(e,t,r){let n=r/100;return t==="long"?e*(1-n):e*(1+n)}function Bn(e,t,r){let n=r/100;return t==="long"?e*(1+n):e*(1-n)}function Dn(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 zn(e,t,r){return t==="long"?e.l<=r:e.h>=r}function Vn(e,t,r){return t==="long"?e.h>=r:e.l<=r}function Jn(e,t,r){return t==="long"?e.l<=r:e.h>=r}function Oe(e,t){for(let r of e.requiredSeries)if(["fundingRate","openInterest"].includes(r)&&!t.every(n=>te(n?.[r])))throw new Error(`strategy required series is absent: ${r}`)}function Kn(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 Yn(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 se(e,t,r={}){let n=jn(r);hr(t);let o=Ie(t);n.nowMs!==void 0&&Y(e,{nowMs:n.nowMs});let a=K(e);if(Oe(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,d=n.takerFeeBps,c=n.builderFeeBps,f=n.initialEquityUsd,p=0,h=0,w=0,b=0,S=0,$=[],I=[],x=[],_=[],A=[],m=null,M=0,G=null,q=f,z=!1,y=0,P=0,T=[],L=new Array(t.length).fill(0);function j(E){T.push(E)}function v(E){let O=t[E].v*(n.maxVolumeParticipationPct/100);return Math.max(0,O-L[E])}function R(E){if(!m)return f;let O=m.side==="long"?(E-m.entryPrice)*m.qty:(m.entryPrice-E)*m.qty;return f+O}function J(E,O,k){let H=k.o,N=Un(f,i);if(!(N>0)||!(H>0))return;let C=Hn(H,O,u),F=N/C,D=v(E),ke=C*D;if(F>D){x.push({kind:"entry",barIndex:E,time:k.t,side:O,requestedNotionalUsd:N,maxFillNotionalUsd:ke,reason:"volume_participation"});return}L[E]+=F;let ee=Math.abs(C-H)*F,oe=mr(N,d,c);f-=oe.total,p+=oe.taker,h+=oe.builder,b+=ee,S+=N,m={lifecycleEpoch:++P,side:O,entryBarIndex:E,entryReferencePrice:H,entryPrice:C,qty:F,notionalUsd:N,stop:qn(C,O,i.stopLossPct),take:Bn(C,O,i.takeProfitPct),liq:Dn(C,O,i.maxLeverage,d+c),entryFees:oe.taker,entryBuilderFees:oe.builder,entrySlippageUsd:ee,fundingAccrued:0}}function B(E,O,k,H){if(!m)return!1;let N=m.side,C=O,F=C;k!=="liquidation"&&H&&(F=Cn(C,N,u));let D=m.qty,ke=D*F;if(k!=="liquidation"){let er=v(E),rn=F*er;if(D>er)return x.push({kind:"exit",barIndex:E,time:t[E].t,side:N,requestedNotionalUsd:ke,maxFillNotionalUsd:rn,reason:"volume_participation",triggerReason:k}),!1;L[E]+=D}let ee=mr(ke,d,c),oe=k==="liquidation"?0:Math.abs(F-C)*D,Ae,tt;N==="long"?(Ae=(C-m.entryReferencePrice)*D,tt=(F-m.entryPrice)*D):(Ae=(m.entryReferencePrice-C)*D,tt=(m.entryPrice-F)*D),f+=tt,f-=ee.total,p+=ee.taker,h+=ee.builder,b+=oe,S+=ke;let tn={side:N,entryBarIndex:m.entryBarIndex,entryTime:t[m.entryBarIndex].t,entryPrice:m.entryPrice,exitBarIndex:E,exitTime:t[E].t,exitPrice:F,exitReason:k,qty:D,notionalUsd:m.notionalUsd,grossPnlUsd:Ae,feesUsd:m.entryFees+ee.taker,builderFeesUsd:m.entryBuilderFees+ee.builder,fundingUsd:m.fundingAccrued,slippageUsd:m.entrySlippageUsd+oe,netPnlUsd:Ae-(m.entryFees+ee.taker+m.entryBuilderFees+ee.builder)-m.fundingAccrued-(m.entrySlippageUsd+oe)};return $.push(tn),k==="liquidation"&&I.push({barIndex:E,time:t[E].t,side:N,price:F,tradeIndex:$.length-1}),m=null,P+=1,y=E+1+(i.cooldownBars||0),!0}function Q(E,O,k,H){let N=E+1;if(N>=t.length)return;T.some(F=>F.kind==="exit"&&F.side===O&&F.fillBar===N&&F.epoch===H)||j({kind:"exit",side:O,signalBar:E,fillBar:N,reason:k,epoch:H})}function Le(E){let O=T.filter(k=>k.fillBar===E);for(let k=T.length-1;k>=0;k--)T[k].fillBar===E&&T.splice(k,1);O.sort((k,H)=>{let N=C=>C.kind==="exit"?0:1;return N(k)-N(H)});for(let k of O)if(k.kind==="exit"){if(!m||m.side!==k.side||m.lifecycleEpoch!==k.epoch)continue;let H=k.reason||"rule";B(E,t[E].o,H,!0)||Q(E,k.side,H,k.epoch)}else if(k.kind==="entry"){if(m||k.epoch!==P||E<y)continue;J(E,k.side,t[E])}}function Fe(E){if(!m)return;let O=t[E],k=O.fundingPaymentRate;if(k==null||!te(k)||k===0)return;let H=Math.abs(m.qty*O.c),N=k*H;m.side==="long"?(f-=N,m.fundingAccrued+=N,w+=N):(f+=N,m.fundingAccrued-=N,w-=N)}function je(E){if(!m)return;let O=t[E].o;(m.side==="long"?O<=m.liq:O>=m.liq)&&B(E,O,"liquidation",!1)}function Gt(E){if(!m)return;let O=t[E],k=m.side,H=Jn(O,k,m.liq),N=zn(O,k,m.stop),C=Vn(O,k,m.take),F=D=>k==="long"?Math.min(D,O.o):Math.max(D,O.o);if(H){B(E,F(m.liq),"liquidation",!1);return}if(N&&C){B(E,F(m.stop),"stop_loss",!0)||Q(E,k,"stop_loss",m.lifecycleEpoch);return}if(N){B(E,F(m.stop),"stop_loss",!0)||Q(E,k,"stop_loss",m.lifecycleEpoch);return}C&&(B(E,m.take,"take_profit",!0)||Q(E,k,"take_profit",m.lifecycleEpoch))}for(let E=0;E<t.length;E++){let O=Math.floor(t[E].t/864e5);O!==G&&(G=O,q=R(t[E].o),z=!1),je(E),Le(E),Gt(E),Fe(E),!z&&R(t[E].c)<=q*(1-i.maxDailyLossPct/100)&&(z=!0,_.push({type:"daily_loss_limit",barIndex:E,time:t[E].t,message:"daily loss limit reached; new entries blocked for UTC day"}));let k=s[E].signals,H=E+l;if(m)(m.side==="long"&&k.exitLong===!0||m.side==="short"&&k.exitShort===!0)&&H<t.length&&(T.some(D=>D.kind==="exit"&&D.side===m.side&&D.fillBar===H&&D.epoch===m.lifecycleEpoch)||j({kind:"exit",side:m.side,signalBar:E,fillBar:H,reason:"rule",epoch:m.lifecycleEpoch}));else{let C=k.entryLong===!0,F=k.entryShort===!0;C&&F?_.push({type:"conflicting_entry_signals",barIndex:E,time:t[E].t,message:"conflicting entry signals; no position opened"}):!z&&(C||F)&&H<t.length&&E>=y&&j({kind:"entry",side:C?"long":"short",signalBar:E,fillBar:H,epoch:P})}let N=f;m&&(M+=1,N=R(t[E].c)),A.push({barIndex:E,time:t[E].t,equity:N,positionSide:m?m.side:null})}let Xt=null;if(m){let E=t.length-1;if(B(E,t[E].c,"end_of_data",!0))A[E]={barIndex:E,time:t[E].t,equity:f,positionSide:null};else{let k=R(t[E].c);Xt={side:m.side,entryBarIndex:m.entryBarIndex,entryTime:t[m.entryBarIndex].t,entryPrice:m.entryPrice,qty:m.qty,notionalUsd:m.notionalUsd,markPrice:t[E].c,markedEquityUsd:k},_.push({type:"open_position_at_end",barIndex:E,time:t[E].t,message:"end-of-data exit missed; position remains open and marked"})}}let Zt=(m?R(t[t.length-1].c):f)-n.initialEquityUsd,Zr=Zt/n.initialEquityUsd*100,Wt=0,Ze=0,We=0;for(let E of $)E.netPnlUsd>0?(Wt+=1,Ze+=E.netPnlUsd):E.netPnlUsd<0&&(We+=-E.netPnlUsd);let Qe=$.length,Wr=Qe===0?0:Wt/Qe,et=0;We>0?et=Ze/We:Ze>0&&(et=1e12);let Qr={netPnlUsd:Zt,netPnlPct:Zr,maxDrawdownPct:Yn(A),winRate:Wr,profitFactor:et,tradeCount:Qe,sharpe:Kn(A),turnoverUsd:S,exposurePct:M/t.length*100},en={initialEquityUsd:n.initialEquityUsd,takerFeeBps:n.takerFeeBps,builderFeeBps:n.builderFeeBps,slippageBps:n.slippageBps,latencyBars:n.latencyBars,maxVolumeParticipationPct:n.maxVolumeParticipationPct},Qt={barsHash:o,strategyHash:a.strategyHash,compilerHash:ce,compilerVersion:ye,config:en,trades:$,equityCurve:A,metrics:Qr,costs:{feesUsd:p,builderFeesUsd:h,fundingUsd:w,slippageUsd:b},liquidations:I,missedFills:x,openPositionAtEnd:Xt,flags:_};return gt(Qt),wt(Ce(Qt))}var gr=Object.freeze(["fail","pass_paper_only","pass_live_eligible"]);function re(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function ge(e){return typeof e=="number"&&Number.isFinite(e)}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 pe(e){if(Array.isArray(e))return e.map(pe);if(e!=null&&typeof e=="object"){let t={};for(let r of Object.keys(e).sort())t[r]=pe(e[r]);return t}return e}function bt(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 yr(e){return{feesUsd:e.costs.feesUsd,builderFeesUsd:e.costs.builderFeesUsd,fundingUsd:e.costs.fundingUsd,slippageUsd:e.costs.slippageUsd}}function Xn(e){return(e.feesUsd||0)+(e.builderFeesUsd||0)+Math.max(0,e.fundingUsd||0)+(e.slippageUsd||0)}function Zn(e){let t=0;for(let r of e.trades)r.grossPnlUsd>0&&(t+=r.grossPnlUsd);return t}function Wn(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 br(e){if(!re(e))throw new TypeError("evidence artifact must be a plain object");if(!gr.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(!re(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(!re(e.walkForward)||!Array.isArray(e.walkForward.windows))throw new TypeError("evidence artifact walkForward windows required");if(e.status==="pass_live_eligible"&&(!re(e.train)||!re(e.holdout)))throw new TypeError("live-eligible evidence artifact requires train and holdout facts");return pe({barsHash:e.barsHash,compilerHash:e.compilerHash,flags:e.flags.map(t=>pe(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 St(e){return Gn("sha256").update(JSON.stringify(br(e)),"utf8").digest("hex")}function W(e,t,r=0){if(!Number.isInteger(e)||e<r)throw new Error(`${t} must be an integer >= ${r}`);return e}function Et(e,t){if(!re(e)||!re(e.metrics))throw new Error(`${t} metrics required`);let r=W(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 Qn(e,{maxDailyLossPct:t}={}){let r=e.split,n=W(r.trainStartIndex,"split.trainStartIndex"),o=W(r.trainEndIndex,"split.trainEndIndex"),a=W(r.trainBarCount,"split.trainBarCount",1),i=W(r.holdoutStartIndex,"split.holdoutStartIndex"),s=W(r.holdoutEndIndex,"split.holdoutEndIndex"),l=W(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)");Et(e.train,"train");let u=Et(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 d=e.walkForward,c=d.windows;if(c.length<1||d.windowsRun!==c.length)throw new Error("live-eligible walk-forward windowsRun must match nonempty windows");let f=0,p=-1;for(let w=0;w<c.length;w++){let b=c[w];if(!re(b)||b.index!==w||typeof b.passed!="boolean")throw new Error("walk-forward windows must be ordered and structurally valid");let S=W(b.trainStartIndex,`walkForward.windows[${w}].trainStartIndex`),$=W(b.trainEndIndex,`walkForward.windows[${w}].trainEndIndex`),I=W(b.evalStartIndex,`walkForward.windows[${w}].evalStartIndex`),x=W(b.evalEndIndex,`walkForward.windows[${w}].evalEndIndex`);if(S!==0||$>=I||I>x||I<=p)throw new Error("walk-forward windows must be chronological and disjoint");if(p=x,b.passed){if(f+=1,b.reason!=="pass")throw new Error("passed walk-forward window reason must be pass");let _=Et({metrics:b.metrics,tradeCount:b.metrics?.tradeCount},`walkForward.windows[${w}]`);if(_.tradeCount<1||_.netPnlUsd<=0||_.profitFactor<=1)throw new Error("passed walk-forward window metrics do not pass");if(ge(t)&&_.maxDrawdownPct>t)throw new Error("passed walk-forward drawdown exceeds strategy risk")}else if(b.reason==="pass")throw new Error("failed walk-forward window cannot have pass reason")}let h=f/c.length;if(!ge(d.passRate)||Math.abs(d.passRate-h)>Number.EPSILON||h<.6)throw new Error("walk-forward passRate contradicts concrete windows or is below live threshold")}function kt(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=br(e),n=pe({id:e.id,...r});if(JSON.stringify(pe(e))!==JSON.stringify(n))throw new Error("evidence artifact contains fields unbound from its deterministic identity");let o=St(e);if(e.id!==o)throw new Error("evidence.id does not match its deterministic artifact facts digest");return e.status==="pass_live_eligible"&&Qn(e,t),e}function qe({strategy:e,bars:t,backtestOptions:r={},trainFraction:n=.7,walkForwardWindows:o=3,minTrades:a=10}={}){let i=[];if(!re(e))throw new TypeError("strategy must be a plain object");if(!Array.isArray(t))throw new TypeError("bars must be an array");if(!re(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=Y(e),l=de(s),u=Ie(t),d=t.length,c=(v=[],R={})=>wr({status:"fail",strategy:s,sHash:l,barsHash:u,split:R.split||{trainStartIndex:0,trainEndIndex:-1,trainBarCount:0,holdoutStartIndex:0,holdoutEndIndex:-1,holdoutBarCount:0,trainFraction:n},train:R.train||null,holdout:R.holdout||null,walkForward:R.walkForward||{windows:[],passRate:0},flags:[...i,...v]});if(d<10)return c([{type:"insufficient_bars",message:"need at least 10 bars for evidence"}]);let f=Math.floor(d*n),p=f,h=d-p;if(f<5||h<3)return c([{type:"invalid_windowing",message:"train/holdout split too small",trainCount:f,holdoutCount:h}]);let w=t.slice(0,f),b=t.slice(p),S,$;try{S=se(s,w,r),$=se(s,b,r)}catch(v){return c([{type:"backtest_error",message:String(v.message||v)}])}let I={metrics:bt(S),costs:yr(S),tradeCount:S.metrics.tradeCount},x={metrics:bt($),costs:yr($),tradeCount:$.metrics.tradeCount},_={trainStartIndex:0,trainEndIndex:f-1,trainBarCount:f,holdoutStartIndex:p,holdoutEndIndex:d-1,holdoutBarCount:h,trainFraction:n},A=[],m=Math.floor(d/(o+1));if(m<3)i.push({type:"invalid_windowing",message:"walk-forward window size too small",wfSize:m});else for(let v=0;v<o;v++){let R=m*(v+1),J=R,B=Math.min(d,J+m);if(B-J<3||R<3){A.push({index:v,trainStartIndex:0,trainEndIndex:R-1,evalStartIndex:J,evalEndIndex:B-1,passed:!1,reason:"window_too_small",metrics:null});continue}let Q=t.slice(J,B),Le;try{Le=se(s,Q,r)}catch{A.push({index:v,trainStartIndex:0,trainEndIndex:R-1,evalStartIndex:J,evalEndIndex:B-1,passed:!1,reason:"backtest_error",metrics:null});continue}let Fe=bt(Le),je=Wn(Fe,s.risk,a);A.push({index:v,trainStartIndex:0,trainEndIndex:R-1,evalStartIndex:J,evalEndIndex:B-1,passed:je,reason:je?"pass":"fail_metrics",metrics:Fe})}let M=A.filter(v=>v.passed).length,G=A.length===0?0:M/A.length,q={windows:A,passRate:G,windowsRun:A.length};x.metrics.tradeCount===0&&I.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"}),I.metrics.netPnlUsd>0&&x.metrics.netPnlUsd<0&&I.metrics.netPnlUsd>Math.abs(x.metrics.netPnlUsd)*.25?i.push({type:"overfit",message:"profitable train with losing holdout (OOS collapse)"}):I.metrics.netPnlUsd>0&&x.metrics.netPnlUsd>0&&x.metrics.netPnlUsd<I.metrics.netPnlUsd*.1&&I.metrics.tradeCount>=a&&i.push({type:"severe_oos_collapse",message:"holdout pnl collapsed vs train"});let z=Xn(x.costs),y=Zn($);y>0&&z>y&&i.push({type:"costs_exceed_gross",message:"holdout costs exceed gross gains"});let P=i.some(v=>["insufficient_bars","invalid_windowing","absent_oos_trades","holdout_loss","no_trades","severe_oos_collapse","backtest_error"].includes(v.type)),T=i.some(v=>v.type==="overfit"),L="fail";return x.metrics.tradeCount>=a&&x.metrics.netPnlUsd>0&&x.metrics.profitFactor>1&&x.metrics.maxDrawdownPct<=s.risk.maxDailyLossPct&&G>=.6&&!(y>0&&z>y)&&!T&&!i.some(v=>v.type==="severe_oos_collapse"||v.type==="invalid_windowing")?L="pass_live_eligible":!P&&x.metrics.tradeCount>0&&I.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"})):T&&x.metrics.tradeCount>0&&I.metrics.netPnlUsd>0?L="fail":x.metrics.tradeCount>0&&I.metrics.tradeCount>0&&!P?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"),wr({status:L,strategy:s,sHash:l,barsHash:u,split:_,train:I,holdout:x,walkForward:q,flags:i})}function wr({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=St(u),xt(pe(JSON.parse(JSON.stringify(u))))}import{createHash as eo,createHmac as to,timingSafeEqual as Gs}from"node:crypto";var ro=2,no=300*1e3,oo=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})();function At(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(At).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${At(e[r])}`).join(",")}}`}function Er(e){let t=String(e?.ORACLE_STAMP_HMAC_SECRET||"").trim();return t.length>=16?t:""}function xr(e=process.env){return Er(process.env)||Er(e)}function so(e){let{prepareHash:t,prepareMac:r,note:n,...o}=e||{};return o}function io(e){let t=so(e);return eo("sha256").update(At(t)).digest("hex")}function ao(e,t=xr()){return t?to("sha256",t).update(String(e)).digest("hex"):""}function Sr(e,{provider:t,kind:r,env:n=process.env,nowMs:o=Date.now(),expiresAtMs:a}={}){if(!e||typeof e!="object")throw new Error("stampPrepared: payload object required");let i=Object.prototype.hasOwnProperty.call(e,"oraclePrepared");if(i&&typeof e.oraclePrepared!="boolean")throw new Error("stampPrepared: oraclePrepared must be boolean");let s={...e,provider:e.provider||t,kind:e.kind||r,requiresUserSignature:e.requiresUserSignature!==!1,signingReady:!1,broadcastReady:!1,executionReady:!1,oraclePrepared:i?e.oraclePrepared:!0};if(!s.provider)throw new Error("stampPrepared: provider required");if(!s.kind)throw new Error("stampPrepared: kind required");let l=Number(o),u=a==null?l+no:Number(a),d=u-l;if(!Number.isSafeInteger(l)||!Number.isSafeInteger(u)||d<=0||d>oo)throw new Error("stampPrepared: bounded preparedAt/expiresAt required");let f={...s,preparedAt:l,expiresAt:u,prepareVersion:ro},p=io(f),h=xr(n),w=h?ao(p,h):void 0,b={...f,prepareHash:p};return w&&(b.prepareMac=w),b}var co=["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 lo(e){return String(e).toLowerCase().replace(/[^a-z0-9]/g,"")}function $t(e,t="value"){if(Array.isArray(e)){e.forEach((r,n)=>$t(r,`${t}[${n}]`));return}if(ve(e))for(let[r,n]of Object.entries(e)){let o=lo(r);if(co.some(a=>o.includes(a)))throw new Error(`handoff: forbidden secret-like field at ${t}.${r}`);$t(n,`${t}.${r}`)}}function Pt(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function Tt({strategy:e,evidence:t,shadow:r,caps:n,nowMs:o=Date.now(),env:a=process.env}={}){if($t({strategy:e,evidence:t,shadow:r,caps:n},"handoff"),!ve(e))throw new Error("handoff: strategy required");if(!ve(t))throw new Error("handoff: evidence required");if(!ve(r))throw new Error("handoff: shadow required");if(!ve(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=Y(e,{nowMs:o}),s=K(i);if(kt(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 f of l)if(!(f in n)||n[f]==null)throw new Error(`handoff: caps.${f} required`);if(!Pt(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(!Pt(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(!Pt(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(f=>f==="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 d={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:ye,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:d},requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,executionReady:!1};return Sr(c,{provider:"hl-strategy",kind:"strategy-live-handoff",env:a})}var uo=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 be(e,t){let r=Number(e);if(!Number.isFinite(r))throw new TypeError(`${t} must be finite`);return r}function Ee(e,t){if(!Number.isSafeInteger(e)||e<0)throw new TypeError(`${t} must be a non-negative safe integer`);return e}function Ne(e){if(Array.isArray(e))for(let t of e)Ne(t);else if(e&&typeof e=="object")for(let t of Object.values(e))Ne(t);return Object.freeze(e)}function kr(e){let t=uo[e];if(!t)throw new TypeError(`unsupported strategy interval: ${e}`);return t}function Ar(e,{endTime:t=Number.MAX_SAFE_INTEGER}={}){if(!Array.isArray(e))throw new TypeError("Hyperliquid candles must be an array");Ee(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=Ee(Number(o.t),`candles[${n}].t`);if(Ee(Number(o.T),`candles[${n}].T`)>t)continue;let s={t:a,o:be(o.o,`candles[${n}].o`),h:be(o.h,`candles[${n}].h`),l:be(o.l,`candles[${n}].l`),c:be(o.c,`candles[${n}].c`),v:be(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 Ne([...r.values()].sort((n,o)=>n.t-o.t))}function fo(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=Ee(Number(o.time),`funding[${n}].time`);a>t||r.set(a,{time:a,fundingRate:be(o.fundingRate,`funding[${n}].fundingRate`)})}return[...r.values()].sort((n,o)=>n.time-o.time)}async function po({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 fr({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 d of l){let c=Number(d?.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 fo(o,r)}function mo(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 _t(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=kr(n);if(e.endTime==null)throw new TypeError("endTime is required for deterministic history");let a=Ee(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):Ee(e.startTime,"startTime");if(s>=a)throw new TypeError("startTime must be before endTime");let[l,u]=await Promise.all([ur({coin:r,interval:n,startTime:s,endTime:a},t),po({coin:r,startTime:s,endTime:a},t)]),d=Ar(l,{endTime:a}),c=Ne(mo(d,u,o));return Ne({coin:r,interval:n,range:{startTime:s,endTime:a},bars:c})}var ho=new Set(["1m","3m","5m","15m","30m","1h","2h","4h","8h","12h","1d"]),yo=new Set(["coin","interval"]);function wo(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))yo.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"||!ho.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 go(e={}){let t=await lr(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 Pr=Object.freeze({id:"hyperliquid",validateMarket:wo,fetchBars:_t,listMarkets:go,prepareIntent(e){return Tt(e)}});var bo=Object.freeze(["id","validateMarket","prepareIntent"]);function Eo(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 bo.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 $r=[Pr].map(Eo),xo=new Map($r.map(e=>[e.id,e])),So=Object.freeze([...$r]);function Be(e){return typeof e!="string"?null:xo.get(e)??null}function De(e){let t=Be(e);if(!t)throw new Error(`unknown strategy venue: ${String(e)}`);return t}var ze=1,Fr=/^[a-z0-9][a-z0-9._-]{0,63}$/,jr=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,Ao=new Set(["open","high","low","close","volume","fundingRate","openInterest"]),Po=new Set(["sma","ema","rsi","macd","bollinger","atr"]),$o=new Set(["gt","gte","lt","lte","eq"]),To=new Set(["and","or","not"]),_o=new Set(["above","below"]),Io=new Set(["line","signal","histogram"]),Oo=new Set(["upper","middle","lower"]),It=new Set(["compare","logic","cross"]),Tr=new Set(["version","id","name","venue","market","parameters","nodes","rules","risk"]),_r=new Set(["value","min","max","step"]),Ot=new Set(["entryLong","entryShort","exitLong","exitShort"]),Ir=new Set(["maxLeverage","maxNotionalUsd","positionSizePct","stopLossPct","takeProfitPct","cooldownBars","maxDailyLossPct","expiresAt"]),vo=new Set(["id","type"]),Or={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"])},vr=16,Nr=128,Mr=100,me=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 X(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function U(e){return typeof e=="number"&&Number.isFinite(e)}function Rr(e){return Number.isInteger(e)&&e>0}function Nt(e){if(e==null||typeof e!="object"||Object.isFrozen(e))return e;if(Array.isArray(e)){for(let t of e)Nt(t);return Object.freeze(e)}for(let t of Object.keys(e))Nt(e[t]);return Object.freeze(e)}function Mt(e){if(Array.isArray(e))return e.map(Mt);if(e!=null&&typeof e=="object"){let t={};for(let r of Object.keys(e).sort())t[r]=Mt(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 Hr(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 vt(e,t,r,n){if(X(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!X(o)||![o.value,o.min,o.max,o.step].every(Rr)?(g(n,`${t}.param`,"referenced period parameter value min max and step must be positive integers"),null):{param:e.param}}return Rr(e)?e:(g(n,t,"must be a positive integer or {param}"),null)}function Lr(e,t,r,n){return X(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 Ve(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 No(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 Ve(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 Mo(e,t){if(!X(e))return g(t,"parameters","must be a plain object"),null;let r=Object.keys(e);if(r.length>vr)return g(t,"parameters",`too many parameters (max ${vr})`),null;let n={};for(let o of r){if(!Fr.test(o)){g(t,`parameters.${o}`,"parameter name is malformed");continue}let a=e[o],i=`parameters.${o}`;if(!X(a)){g(t,i,"must be a plain object");continue}le(a,_r,i,t);for(let c of _r)c in a||g(t,`${i}.${c}`,"required field is missing");let{value:s,min:l,max:u,step:d}=a;U(l)||g(t,`${i}.min`,"must be a finite number"),U(u)||g(t,`${i}.max`,"must be a finite number"),(!U(d)||d<=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(d)&&d>0&&(Hr(s,l,u,d)||g(t,`${i}.value`,"value must lie on the declared min/max/step grid")),n[o]={value:s,min:l,max:u,step:d}}return n}function Ro(e,t,r,n){let o=`nodes.${t}`;if(!X(e))return g(n,o,"must be a plain object"),null;if(typeof e.type!="string"||!Or[e.type])return g(n,`${o}.type`,"unknown or missing node type"),le(e,vo,o,n),null;switch(le(e,Or[e.type],o,n),(typeof e.id!="string"||!jr.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"||!Ao.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=Lr(e.value,`${o}.value`,r,n);return{id:e.id,type:"constant",value:a}}case"indicator":{(typeof e.indicator!="string"||!Po.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=vt(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=vt(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=vt(e[s],`${o}.${s}`,r,n);l!=null&&(i[s]=l)}"output"in e?Io.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=Lr(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?Oo.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"||!$o.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"||!To.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"||!_o.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 Lo(e,t,r){if(!X(e))return g(t,"risk","must be a plain object"),null;le(e,Ir,"risk",t);for(let f of Ir)(!(f in e)||e[f]==null)&&g(t,`risk.${f}`,"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 d=e.maxDailyLossPct;!U(d)||d<=0||d>100?g(t,"risk.maxDailyLossPct","must be a number > 0 and <= 100"):n.maxDailyLossPct=d;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 Je(e,t={}){let r=[];if(!X(e))return g(r,"","strategy must be a plain object"),{ok:!1,errors:r,strategy:null};le(e,Tr,"",r);for(let c of Tr)(!(c in e)||e[c]==null)&&g(r,c,"required field is missing");e.version!==ze&&g(r,"version",`must be ${ze}`),(typeof e.id!="string"||!Fr.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>Mr)&&g(r,"name",`must be a non-empty string max ${Mr}`);let n=Be(e.venue);n||g(r,"venue",`unknown strategy venue "${String(e.venue)}"`);let o=null;if(!n)X(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 f of c.errors)g(r,f.path,f.message)}let a=Mo(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>Nr)g(r,"nodes",`too many nodes (max ${Nr})`);else{i=[];for(let c=0;c<e.nodes.length;c++){let f=Ro(e.nodes[c],c,a||{},r);f&&(typeof f.id=="string"&&jr.test(f.id)&&(s.has(f.id)?g(r,`nodes.${c}.id`,`duplicate node id "${f.id}"`):s.set(f.id,f)),i.push(f))}for(let c=0;c<i.length;c++){let f=i[c],p=`nodes.${c}`;for(let h of Ve(f))s.has(h)||g(r,p,`unknown node ref "${h}"`);if(f.type==="indicator"||f.type==="compare"||f.type==="cross")for(let h of Ve(f)){let w=s.get(h);w&&It.has(w.type)&&g(r,p,`node ref "${h}" must be numeric`)}if(f.type==="logic")for(let h of Ve(f)){let w=s.get(h);w&&!It.has(w.type)&&g(r,p,`node ref "${h}" must be boolean`)}}No(s)&&g(r,"nodes","graph contains a cycle")}let l=null;if(!X(e.rules))g(r,"rules","must be a plain object");else{le(e.rules,Ot,"rules",r);for(let c of Ot)c in e.rules||g(r,`rules.${c}`,"required field is missing");l={};for(let c of Ot){let f=e.rules[c];if(f===null){l[c]=null;continue}if(typeof f!="string"||!f){g(r,`rules.${c}`,"must be a node id or null"),l[c]=f;continue}if(!s.has(f)){g(r,`rules.${c}`,`unknown node ref "${f}"`),l[c]=f;continue}let p=s.get(f);It.has(p.type)||g(r,`rules.${c}`,`rule must reference a boolean node, not ${p.type}`),l[c]=f}}let u=Lo(e.risk,r,t);if(r.length)return{ok:!1,errors:r,strategy:null};let d=Nt({version:ze,id:e.id,name:e.name,venue:n.id,market:o,parameters:a,nodes:i,rules:l,risk:u});return{ok:!0,errors:[],strategy:d}}function Y(e,t={}){let r=Je(e,t);if(!r.ok)throw new me(r.errors);return r.strategy}function Cr(e){let t=Y(e);return JSON.stringify(Mt(t))}function de(e){let t=Cr(e);return ko("sha256").update(t,"utf8").digest("hex")}function we(e,t){if(!X(e))throw new me([{path:"",message:"strategy must be a plain object"}]);if(!X(t))throw new me([{path:"overrides",message:"must be a plain object"}]);let r=Y(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(!Hr(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 me(o);return Y({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 Fo}from"node:crypto";var Lt=256,Ur=new Set(["netPnlUsd","profitFactor","sharpe","maxDrawdownPct"]);function qr(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 Br(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function Ft(e){if(e==null||typeof e!="object"||Object.isFrozen(e))return e;if(Array.isArray(e)){for(let t of e)Ft(t);return Object.freeze(e)}for(let t of Object.keys(e))Ft(e[t]);return Object.freeze(e)}function Me(e){if(Array.isArray(e))return e.map(Me);if(e!=null&&typeof e=="object"){let t={};for(let r of Object.keys(e).sort())t[r]=Me(e[r]);return t}return e}function Ke(e){return JSON.stringify(Me(e))}function jo(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 Ho(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=Ke(n),i=Ke(o);return a<i?-1:a>i?1:0}),r}function Rt(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=Ke(r),s=Ke(o);return i<s}function jt(e,t,r={}){if(!Br(r))throw new TypeError("options must be a plain object");for(let x of Object.keys(r))if(qr(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>Lt)throw new TypeError(`maxTrials must be an integer 1..${Lt}`);o=x}let a=r.objective??"netPnlUsd";if(!Ur.has(a))throw new TypeError(`objective must be one of ${[...Ur].join("|")}`);let i=r.backtestOptions??{};if(!Br(i))throw new TypeError("backtestOptions must be a plain object");for(let x of Object.keys(i))if(qr(x))throw new TypeError(`backtestOptions must not include holdout/test/oos key "${x}"`);let s=Y(e),l=Object.keys(s.parameters).sort();if(l.length===0)throw new Error("optimizeStrategy requires at least one declared parameter");let u={},d=1;for(let x of l){let _=jo(s.parameters[x]);if(_.length===0)throw new Error(`parameter "${x}" produces an empty grid`);u[x]=_,d*=_.length}let c=Ho(l,u);if(c.length===0)throw new Error("parameter grid is empty");let f=c.slice(0,o),p=[],h=null,w=null;for(let x of f){let _=we(s,x),A=se(_,t,i);w==null&&(w=A.config);let m={netPnlUsd:A.metrics.netPnlUsd,netPnlPct:A.metrics.netPnlPct,maxDrawdownPct:A.metrics.maxDrawdownPct,winRate:A.metrics.winRate,profitFactor:A.metrics.profitFactor,tradeCount:A.metrics.tradeCount,sharpe:A.metrics.sharpe,turnoverUsd:A.metrics.turnoverUsd},M={parameters:{...x},metrics:m};p.push(M),(!h||Rt(a,m,x,h.metrics,h.parameters))&&(h=M)}p.sort((x,_)=>Rt(a,x.metrics,x.parameters,_.metrics,_.parameters)?-1:Rt(a,_.metrics,_.parameters,x.metrics,x.parameters)?1:0);let b={...h.parameters},S=we(s,b),$={strategyHash:de(s),compilerHash:ce,trainBarsHash:Ie(t),backtestConfig:w,objective:a,maxTrials:o,trialsRun:p.length,candidates:p,bestParameters:b,bestStrategy:S},I={id:Fo("sha256").update(JSON.stringify(Me($)),"utf8").digest("hex"),...$};return Ft(Me(JSON.parse(JSON.stringify(I))))}import{createHash as Co}from"node:crypto";var V=class extends Error{constructor(t){super(t),this.name="StrategyDraftError"}},Uo=new Set(["1m","3m","5m","15m","30m","1h","2h","4h","8h","12h","1d"]),qo=new Set(["BTC","ETH","SOL","HYPE"]),Bo=/\b(mnemonic|private\s*key|privkey|seed\s*phrase|seed\b|api[_-]?key|secret\s*key|wallet\s*key|passphrase)\b/i,xe="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.",Do=Object.freeze({maxLeverage:1,maxNotionalUsd:100,positionSizePct:5,stopLossPct:2,takeProfitPct:4,cooldownBars:1,maxDailyLossPct:3}),zo=36e5,Vo=30*864e5,Jo=864e5;function Ko(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function Ht(e){if(e==null||typeof e!="object"||Object.isFrozen(e))return e;if(Array.isArray(e)){for(let t of e)Ht(t);return Object.freeze(e)}for(let t of Object.keys(e))Ht(e[t]);return Object.freeze(e)}function Yo(e){return String(e).trim().replace(/\s+/g," ")}function Go(e){let t=e.match(/\b(long|short)\b/i);return t?t[1].toLowerCase():null}function Xo(e){for(let r of qo)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 Zo(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 Uo.has(r)?r:null}function Wo(e){let t={...Do},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 Qo(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 es(e){let t=Co("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 ts(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 rs(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 ns(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 os(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 Dr(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 ss({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 d=s.direction==="above"?"below":"above";l.push({id:"crossRev",type:"cross",direction:d,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:Dr(s.fast),ema_right_period:Dr(s.slow)},nodes:l,rules:u,risk:{...n,expiresAt:o}}}function is({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 as({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 Ct(e,t={}){if(typeof e!="string")throw new V("prompt must be a string");if(e.length>1e3)throw new V("prompt length must be <= 1000");if(!Ko(t))throw new V("options must be a plain object");if(!Number.isInteger(t.nowMs))throw new V("options.nowMs is required integer epoch ms");let r=t.nowMs,n=Jo;if("expiresInMs"in t){if(!Number.isInteger(t.expiresInMs))throw new V("expiresInMs must be an integer");if(n=t.expiresInMs,n<zo||n>Vo)throw new V("expiresInMs must be between 1h and 30d")}if(Bo.test(e))throw new V(`prompt appears to contain secrets and is rejected. ${xe}`);let o=Yo(e);if(!o)throw new V(`empty prompt. ${xe}`);if(Qo(o))throw new V(`duplicate interval or risk clause. ${xe}`);let a=Go(o),i=Xo(o),s=Zo(o);if(!a||!i||!s)throw new V(`could not parse side/coin/interval. ${xe}`);let l=Wo(o);if(!(l.maxLeverage>0)||l.maxLeverage>50)throw new V("leverage out of range");if(!(l.positionSizePct>0)||l.positionSizePct>100)throw new V("position size out of range");let u=r+n,d=es(o),c=`Draft ${i} ${a}`.slice(0,100),f=ts(o),p=rs(o),h=ns(o),w=[f,p,h].filter(Boolean);if(w.length!==1)throw new V(`unsupported or ambiguous prompt. ${xe}`);if(!os(o,w[0]))throw new V(`unsupported or ambiguous prompt. ${xe}`);let b,S=w[0],$={side:a,coin:i,interval:s,risk:l,expiresAt:u,id:d,name:c,spec:S};S.kind==="ema_cross"?b=ss($):S.kind==="rsi"?b=is($):b=as($);let I=Je(b,{nowMs:r});if(!I.ok)throw new V(`draft failed validation: ${I.errors.map(x=>x.message).join("; ")}`);return Ht(Y(b,{nowMs:r}))}import ie from"node:fs";import Ye from"node:path";var qt=1,cs=["privatekey","secretkey","seed","mnemonic","passphrase","password","keystore","keymaterial","apikey","authtoken","accesstoken","refreshtoken","credential","bearer","signature","authorization","xprv","xpriv","wif"];function Ge(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function ne(e){return e==null?e:JSON.parse(JSON.stringify(e))}function ls(e){return String(e).toLowerCase().replace(/[^a-z0-9]/g,"")}function Se(e,t="record"){if(Array.isArray(e)){e.forEach((r,n)=>Se(r,`${t}[${n}]`));return}if(Ge(e))for(let[r,n]of Object.entries(e)){let o=ls(r);if(cs.some(a=>o.includes(a)))throw new Error(`shadow-store: forbidden secret-like field at ${t}.${r}`);Se(n,`${t}.${r}`)}}function us(e){if(typeof e!="string"||!e||!Ye.isAbsolute(e))throw new Error("shadow-store: path must be an absolute path")}function zr(e){let t;try{t=ie.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 fs(){return{version:qt,runners:[]}}function Vr(e,t){let r;try{r=JSON.parse(e)}catch{throw new Error("shadow-store: malformed JSON")}if(!Ge(r))throw new Error("shadow-store: malformed JSON root");if(r.version!==qt)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 Se(r,Ye.basename(t)),{version:qt,runners:r.runners.map(n=>ne(n))}}function Jr(e,t){Se(t,"store");let r=Ye.dirname(e);ie.mkdirSync(r,{recursive:!0,mode:448});let n=Ye.join(r,`.shadow-store.${process.pid}.${Date.now()}.tmp`),o=`${JSON.stringify(t)}
|
|
3
|
-
`;try{ie.writeFileSync(n,o,{mode:384,flag:"wx"}),ie.renameSync(n,e);try{ie.chmodSync(e,384)}catch{}}catch(a){try{ie.unlinkSync(n)}catch{}throw a}}var Ut=new Map;function Bt(e={}){let t=e.path;if(us(t),zr(t),ie.existsSync(t)?Vr(ie.readFileSync(t,"utf8"),t):Jr(t,fs()),Ut.has(t))return Ut.get(t);let r=!1,n=[];function o(){if(r)return;let h=n.shift();if(h){r=!0;try{let w=h.fn();r=!1,h.resolve(w),o()}catch(w){r=!1,h.reject(w),o()}}}function a(h){if(!r&&n.length===0){r=!0;try{return h()}finally{r=!1,queueMicrotask(o)}}return new Promise((w,b)=>{n.push({fn:h,resolve:w,reject:b}),queueMicrotask(o)})}function i(){return zr(t),Vr(ie.readFileSync(t,"utf8"),t)}function s(h){Jr(t,h)}function l(h){if(!Ge(h)||typeof h.id!="string"||!h.id)throw new Error("shadow-store: create requires record with string id");Se(h,"record");let w=i();if(w.runners.some(S=>S.id===h.id))throw new Error(`shadow-store: runner id already exists: ${h.id}`);let b=ne(h);return w.runners.push(b),s(w),ne(b)}function u(h){let w=i().runners.find(b=>b.id===h);return w?ne(w):null}function d(){return i().runners.map(h=>ne(h))}function c(h,w){if(typeof w!="function")throw new Error("shadow-store: updater must be a function");let b=i(),S=b.runners.findIndex(x=>x.id===h);if(S<0)throw new Error(`shadow-store: runner not found: ${h}`);let $=ne(b.runners[S]),I=w($);if(!Ge(I)||I.id!==h)throw new Error("shadow-store: updater must return record with same id");return Se(I,"record"),b.runners[S]=ne(I),s(b),ne(b.runners[S])}function f(h){let w=i(),b=w.runners.findIndex($=>$.id===h);if(b<0)throw new Error(`shadow-store: runner not found: ${h}`);let S=ne(w.runners[b]);return S.status!=="stopped"&&(S.status="stopped",w.runners[b]=S,s(w)),ne(w.runners[b])}let p={create(h){return a(()=>l(h))},get(h){return u(h)},list(){return d()},update(h,w){return a(()=>c(h,w))},stop(h){return a(()=>f(h))}};return Ut.set(t,p),p}import{createHash as Vt}from"node:crypto";function Dt(e){return e==null?e:JSON.parse(JSON.stringify(e))}function zt(e){return Array.isArray(e)?e.map(zt):e&&typeof e=="object"?Object.fromEntries(Object.keys(e).sort().map(t=>[t,zt(e[t])])):e}function Yr(e){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("shadow-runner: record must be an object");return Vt("sha256").update(JSON.stringify(zt(e))).digest("hex")}function ds(e,t,r,n,o){return Vt("sha256").update(`${e}|${t}|${r}|${n}|${o}`).digest("hex")}function ps(e,t,r,n){return Vt("sha256").update(`shadow|${e}|${t}|${r}|${n??""}`).digest("hex")}function ms(e){return e==="entryLong"||e==="exitShort"?"buy":e==="entryShort"||e==="exitLong"?"sell":e}function Kr(e){return e==="entryLong"||e==="entryShort"}function Xe({storePath:e,clock:t=Date.now}={}){if(typeof e!="string"||!e)throw new Error("shadow-runner: storePath required");let r=Bt({path:e});function n({strategy:l,evidenceId:u=null}={}){let d=K(l),c=u==null?null:String(u),f=r.list().filter(S=>S.status==="running"&&S.strategyHash===d.strategyHash&&S.compilerHash===d.compilerHash&&S.evidenceId===c).sort((S,$)=>S.createdAt-$.createdAt||S.id.localeCompare($.id))[0];if(f)return Dt(f);let p=t(),h=ps(p,d.strategyHash,d.compilerHash,c),w=r.get(h);if(w)return Dt(w);let b={id:h,strategy:Dt(d.strategy),strategyHash:d.strategyHash,compilerHash:d.compilerHash,evidenceId:c,status:"running",cursor:null,intendedOrders:[],fills:[],missedFills:[],markouts:[],createdAt:p,updatedAt:p,position:null,cooldownBarsRemaining:0,cooldownStartT:null,lastProcessedBarIndex:-1};return r.create(b)}function o(l){return r.get(l)}function a(){return r.list()}function i(l){return r.stop(l)}function s(l,u,{markoutHorizons:d=[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 p=K(c.strategy).evaluateAll(u),h=new Map;for(let y=0;y<u.length;y++)h.set(u[y].t,y);let w=c.cursor,b=[];for(let y=0;y<u.length;y++){let P=u[y].t;(w==null||P>w)&&b.push(y)}if(b.length===0)return c;let S=new Map(c.intendedOrders.map(y=>[y.id,y])),$=new Set(c.fills.map(y=>y.orderId)),I=new Map(c.missedFills.map(y=>[y.orderId,y])),x=(y,P)=>`${y}|${P}`,_=new Map(c.markouts.map(y=>[x(y.orderId,y.horizon),y])),A=c.position?{...c.position}:null,m=Number.isInteger(c.cooldownBarsRemaining)?Math.max(0,c.cooldownBarsRemaining):0,M=Number.isFinite(c.cooldownStartT)?c.cooldownStartT:null;function G({action:y,signalBarT:P,signalIndex:T}){let L=ms(y),j=ds(c.id,c.strategyHash,P,L,y);if(S.has(j))return S.get(j);let v=T+1,R=v<u.length,J={id:j,action:y,type:y,side:L,signalBarT:P,fillBarT:R?u[v].t:null,status:R?"open":"missed"};return S.set(j,J),c.intendedOrders.push(J),J}function q(y,P,T){if($.has(y.id))return;let L={orderId:y.id,action:Kr(y.action)?"entry":"exit",side:y.side,price:P.o,barT:P.t,signalBarT:y.signalBarT,barIndex:T};if(c.fills.push(L),$.add(y.id),y.status="filled",y.fillBarT=P.t,I.has(y.id)&&(I.delete(y.id),c.missedFills=c.missedFills.filter(j=>j.orderId!==y.id)),Kr(y.action)){A={side:y.action==="entryLong"?"long":"short",entryOrderId:y.id,entryBarT:P.t,entryPrice:P.o,entryBarIndex:T};for(let j of d){let v=x(y.id,j);if(_.has(v))continue;let R={orderId:y.id,horizon:j,entryBarT:P.t,entryPrice:P.o,side:A.side,status:"pending",close:null,barT:null};_.set(v,R),c.markouts.push(R)}}else A=null,m=Number(c.strategy?.risk?.cooldownBars)||0,M=P.t}function z(y){if($.has(y.id)||I.has(y.id))return;let P={orderId:y.id,action:y.action,side:y.side,signalBarT:y.signalBarT,status:"missed"};I.set(y.id,P),c.missedFills.push(P),y.status="missed"}for(let y of c.intendedOrders){if(y.status==="filled"||$.has(y.id))continue;let P=h.get(y.signalBarT);if(P==null)continue;let T=P+1;T<u.length&&(w==null||u[T].t>w)&&q(y,u[T],T)}for(let y of b){let P=u[y],T=p[y].signals,L=A,j=R=>{if(A||m>0&&(M==null||P.t>=M))return;let B=G({action:R,signalBarT:P.t,signalIndex:y}),Q=y+1;Q<u.length?q(B,u[Q],Q):z(B)},v=R=>{if(!A||A.side==="long"&&R!=="exitLong"||A.side==="short"&&R!=="exitShort")return;let J=G({action:R,signalBarT:P.t,signalIndex:y}),B=y+1;B<u.length?q(J,u[B],B):z(J)};L?(T.exitLong&&v("exitLong"),T.exitShort&&v("exitShort")):T.entryLong&&T.entryShort||(T.entryLong&&j("entryLong"),T.entryShort&&j("entryShort")),m>0&&M!=null&&P.t>=M&&(m-=1,m===0&&(M=null)),c.cursor=P.t,c.lastProcessedBarIndex=y}for(let y of c.markouts){if(y.status!=="pending")continue;let P=c.fills.find(j=>j.orderId===y.orderId&&j.action==="entry");if(!P)continue;let T=h.get(P.barT);if(T==null)continue;let L=T+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=A,c.cooldownBarsRemaining=m,c.cooldownStartT=M,c.updatedAt=t(),c})}return{start:n,step:s,list:a,get:o,stop:i}}import hs from"node:os";import ys from"node:path";var ws=["privatekey","secretkey","seed","mnemonic","passphrase","password","keystore","keymaterial","apikey","authtoken","accesstoken","refreshtoken","credential","bearer","signature","authorization","xprv","xpriv","wif"];function Re(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function gs(e){return String(e).toLowerCase().replace(/[^a-z0-9]/g,"")}function Kt(e){if(Array.isArray(e)){for(let t of e)Kt(t);return}if(Re(e))for(let[t,r]of Object.entries(e)){if(ws.some(n=>gs(t).includes(n)))throw new Error(`strategy service: secret-like field "${t}" is forbidden`);Kt(r)}}function bs(e){if(!Re(e))throw new TypeError("strategy input must be a plain object");return Kt(e),e}function Es(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 Jt(e,t,r,n){if(Array.isArray(t.bars))return t.bars;let o=De(e.venue),a=r.fetchBars??o.fetchBars;if(typeof a!="function")throw new Error(`strategy venue ${o.id} does not support history`);r.signal?.throwIfAborted?.();let i=await a({coin:e.market.coin,interval:e.market.interval,count:t.count??1500,endTime:t.endTime??n},{signal:r.signal});r.signal?.throwIfAborted?.();let s=Array.isArray(i)?i:i?.bars;if(!Array.isArray(s))throw new Error("strategy history provider returned no bars");return s}function Yt(e,t){let r=e.backtestOptions??{};if(!Re(r))throw new TypeError("backtestOptions must be a plain object");return{...r,nowMs:t}}function Gr(e,t,r,n,o={}){let a=e.evidenceOptions??{};if(!Re(a))throw new TypeError("evidenceOptions must be a plain object");return{...a,...o,strategy:t,bars:r,backtestOptions:Yt(e,n)}}function Xr(){return ys.join(hs.homedir(),".oracle","strategy-shadow.json")}function xs(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 Ss(e,t={},r={}){r.signal?.throwIfAborted?.();let n=bs(t),o=Es(n,r);if(e==="draft")return{strategy:Ct(n.prompt,{nowMs:o})};if(e==="validate"){let a=K(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=K(n.strategy),i=await Jt(a.strategy,n,r,o);Oe(a,i);let s=qe(Gr(n,a.strategy,i,o));return e==="evidence"?s:{backtest:se(a.strategy,i,Yt(n,o)),evidence:s}}if(e==="optimize"){let a=K(n.strategy),i=await Jt(a.strategy,n,r,o);Oe(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 d=i.slice(0,Math.floor(i.length*u)),c=n.options??{};if(!Re(c))throw new TypeError("options must be a plain object");let f=jt(a.strategy,d,{...c,...n.maxTrials==null?{}:{maxTrials:n.maxTrials},backtestOptions:Yt(n,o)}),p=f.bestStrategy;return{strategy:p,optimization:f,evidence:qe(Gr(n,p,i,o,{trainFraction:u}))}}if(e==="shadow"){let a=Xe({storePath:r.storePath??Xr(),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 Jt(s.strategy,n,r,o);return Oe(K(s.strategy),l),await a.step(n.id,l,n.stepOptions??{})}throw new Error(`unknown shadow action: ${i}`)}if(e==="prepare"){let a=K(n.strategy),i=De(a.strategy.venue);if(typeof n.shadowId!="string"||!n.shadowId)throw new Error("strategy prepare requires a matching shadow runner id");let l=await Xe({storePath:r.storePath??Xr(),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??xs(a.strategy,o);return i.prepareIntent({strategy:a.strategy,evidence:n.evidence,shadow:{id:l.id,stateHash:Yr(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{gr as EVIDENCE_STATUSES,Lt as MAX_OPTIMIZER_TRIALS,ce as STRATEGY_COMPILER_HASH,ye as STRATEGY_COMPILER_VERSION,ze as STRATEGY_VERSION,V as StrategyDraftError,me as StrategyValidationError,we as applyParameterOverrides,kt as assertEvidenceArtifact,ht as atr,se as backtestStrategy,mt as bollinger,Cr as canonicalStrategyJson,K as compileStrategy,St as computeEvidenceArtifactId,Xe as createShadowRunner,Ct as draftStrategyFromPrompt,Te as ema,qe as evaluateEvidence,_t as fetchHyperliquidStrategyBars,kr as intervalToMs,pt as macd,Ar as normalizeHyperliquidCandles,Y as normalizeStrategy,Bt as openShadowStore,jt as optimizeStrategy,Tt as prepareStrategyLiveHandoff,De as requireStrategyVenue,Be as resolveStrategyVenue,dt as rsi,Ss as runStrategyOperation,ft as sma,de as strategyHash,So as strategyVenues,Je as validateStrategy};
|
|
1
|
+
import{createHash as Io}from"node:crypto";import{createHash as dn}from"node:crypto";import fe from"node:net";import cn from"node:dns";var ln=new Set(["localhost","metadata.google.internal","metadata.goog"]);function qe(e){let t=String(e).toLowerCase().split("%")[0];if((t.match(/::/g)||[]).length>1)return null;let r=d=>{if(!d)return[];let c=d.split(":"),f=c.at(-1);if(f?.includes(".")){let p=f.split(".").map(Number);if(p.length!==4||p.some(h=>!Number.isInteger(h)||h<0||h>255))return null;c.splice(c.length-1,1,(p[0]<<8|p[1]).toString(16),(p[2]<<8|p[3]).toString(16))}return c.some(p=>!/^[0-9a-f]{1,4}$/.test(p))?null:c.map(p=>Number.parseInt(p,16))},[n,o]=t.split("::"),s=r(n),i=r(o);if(!s||!i)return null;let a=t.includes("::"),l=8-s.length-i.length;if(!a&&l!==0||a&&l<1)return null;let u=[...s,...Array(Math.max(0,l)).fill(0),...i];return u.length!==8?null:Uint8Array.from(u.flatMap(d=>[d>>8,d&255]))}function ot(e,t,r){let n=Math.floor(r/8),o=r%8;for(let i=0;i<n;i+=1)if(e[i]!==t[i])return!1;if(!o)return!0;let s=255<<8-o;return(e[n]&s)===(t[n]&s)}function st(e){if(fe.isIPv4(e)){let t=e.split(".").map(Number);return!(t[0]===0||t[0]===10||t[0]===127||t[0]>=224||t[0]===100&&t[1]>=64&&t[1]<=127||t[0]===169&&t[1]===254||t[0]===172&&t[1]>=16&&t[1]<=31||t[0]===192&&(t[1]===0||t[1]===2||t[1]===168)||t[0]===192&&t[1]===88&&t[2]===99||t[0]===198&&(t[1]===18||t[1]===19||t[1]===51)||t[0]===203&&t[1]===0&&t[2]===113)}if(fe.isIPv6(e)){let t=qe(e);if(!t)return!1;let r=qe("::ffff:0:0");return ot(t,r,96)?st([...t.slice(12)].join(".")):ot(t,qe("2000::"),3)?![["2001::",23],["2001:db8::",32],["2001:10::",28],["2001:2::",48],["2002::",16],["3fff::",20]].some(([o,s])=>ot(t,qe(o),s)):!1}return!1}function un(e){let t;try{t=new URL(String(e))}catch{return{ok:!1,error:`not a valid URL: ${String(e).slice(0,120)}`}}if(t.protocol!=="http:"&&t.protocol!=="https:")return{ok:!1,error:`refused protocol ${t.protocol} (only http/https)`};let r=t.hostname.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,"");if(ln.has(r)||r.endsWith(".localhost")||r.endsWith(".internal"))return{ok:!1,error:`refused internal host ${r}`};let n=fe.isIP(r);return n!==0&&!st(r)?{ok:!1,error:`refused private address ${r}`}:{ok:!0,url:t,host:r,isLiteralIp:n!==0}}async function it(e,{lookupFn:t=cn.promises.lookup}={}){let r=un(e);if(!r.ok)return r;if(r.isLiteralIp)return{ok:!0,url:r.url,addresses:[{address:r.host,family:fe.isIPv6(r.host)?6:4}]};let n;try{n=await t(r.host,{all:!0,verbatim:!0})}catch{return{ok:!1,error:`refused: ${r.host} did not resolve`}}return!Array.isArray(n)||n.length===0||n.some(o=>!st(o.address))?{ok:!1,error:`refused: ${r.host} resolves to a non-public address`}:{ok:!0,url:r.url,addresses:n}}async function at({requireUndici:e=!1,importUndici:t=()=>import("undici")}={}){let r,n;try{let c=await t();r=c.Agent,n=c.fetch}catch(c){if(e)throw new Error(`egress-guard: untrustedUrl pinning requires the undici package, which failed to load: ${c?.message||c}`);return null}if(typeof r!="function"||typeof n!="function"){if(e)throw new Error("egress-guard: untrustedUrl pinning requires undici's Agent and fetch exports, which were not found on the imported module");return null}let o=c=>String(c).toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,""),s=new Map,i=c=>(Array.isArray(c)?c:[c]).map(f=>typeof f=="string"?{address:f}:f).filter(f=>f&&f.address).map(f=>({address:f.address,family:f.family||(fe.isIPv6(f.address)?6:4)})),a=(c,f,p)=>{s.set(o(c),i(typeof f=="string"?[{address:f,family:p}]:f))},l=c=>{let f=o(c);if(fe.isIP(f))return[{address:f,family:fe.isIPv6(f)?6:4}];let p=s.get(f);if(!p||!p.length)throw new Error(`refused: unpinned host ${c} during pinned fetch`);return p},u=new r({connect:{lookup(c,f,p){let h;try{h=l(c)}catch(w){return p(w)}return f?.all?p(null,h):p(null,h[0].address,h[0].family)}}}),d=fn((c,f={})=>n(c,{...f,dispatcher:u}),a);return{dispatcher:u,fetch:d,pin:a,resolve:l,async close(){try{await u.destroy()}catch{}}}}var ct=Symbol.for("oracle.egressGuard.pinCapableFetch");function fn(e,t){if(typeof e!="function")throw new Error("markPinCapableFetch: fetchImpl must be a function");if(typeof t!="function")throw new Error("markPinCapableFetch: pin must be a function");return e[ct]=Object.freeze({pin:t}),e}function lt(e){return typeof e=="function"&&typeof e[ct]?.pin=="function"}function rr(e,t,r){if(!lt(e))throw new Error("pinFetchToAddresses: fetchImpl is not pin-capable");e[ct].pin(t,r)}var pn=new Set([408,425,429,500,502,503,504]),nr=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),mn=2,or=4e3,cr=["authorization","x-api-key","x-tensor-api-key","0x-api-key","api-key","cookie","proxy-authorization"],hn=new Set([301,302,303,307,308]),sr=3,yn=64*1024;function wn(e){let t=String(e||"").toLowerCase();return cr.includes(t)||/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(t)}function gn(e){let t={};for(let[r,n]of Object.entries(e||{}))wn(r)||(t[r]=n);return t}function bn(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 En(e,t){return new URL(String(e)).origin===new URL(String(t)).origin}var ut=new Map;function kn(e,t,r,n={}){let o={};for(let[d,c]of Object.entries(r||{}))o[d.toLowerCase()]=c;let s=Object.keys(o).filter(d=>/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(d)),a=[...new Set([...cr,...s])].sort().map(d=>`${d}=${o[d]??""}`).join(`
|
|
2
|
+
`),l=dn("sha256").update(a).digest("hex").slice(0,32),u=`${n.untrustedUrl?"untrusted":"trusted"}:${n.maxResponseBytes??"unbounded"}`;return`${e} ${t} ${u} ${l}`}function xn(e,t){let r=Number(t);return Number.isFinite(r)&&r>0?Math.min(r*1e3,or):Math.min(250*2**e,or)+Math.floor(Math.random()*100)}var Sn=e=>new Promise(t=>setTimeout(t,e));function Pe(e,t={}){let r=new Error(e);return r.retryable=!1,Object.assign(r,t),r}function ft(e,t,r){return Pe(`HTTP response from ${e} exceeded maxResponseBytes ${r} (${t})`,{oversize:!0})}function Te(e){try{let t=e?.body?.cancel?.();t&&typeof t.then=="function"&&t.catch(()=>{})}catch{}}function An(e){return e?e.byteLength??e.length??0:0}async function ir(e,t,{url:r,truncate:n=!1,onOversize:o}={}){if(t==null)return await e.text();let s=Number(e.headers?.get?.("content-length"));if(Number.isFinite(s)&&s>t&&(Te(e),!n))throw ft(r,`content-length ${s}`,t);let i=e.body?.getReader?.();if(!i){let c=await e.text(),f=Buffer.byteLength(c,"utf8");if(f>t){if(!n)throw ft(r,`body ${f} bytes`,t);return Buffer.from(c,"utf8").subarray(0,t).toString("utf8")}return c}let a=[],l=0,u=!1;try{for(;;){let{value:c,done:f}=await i.read();if(f)break;if(c&&(a.push(Buffer.from(c)),l+=An(c),l>t)){u=!0;break}}}finally{if(u)try{await i.cancel()}catch{}try{i.releaseLock?.()}catch{}}if(u&&(typeof o=="function"&&o(),!n))throw ft(r,`streamed ${l} bytes`,t);let d=Buffer.concat(a);return(u?d.subarray(0,t):d).toString("utf8")}function ar(e){if(!e)return null;try{return JSON.parse(e)}catch{return null}}async function $n(e,{fetchImpl:t,method:r,headers:n,body:o,timeoutMs:s,lookupFn:i,realFetch:a,untrustedUrl:l=!1,maxResponseBytes:u=null,importUndici:d,validateResponse:c,signal:f}){let p=new AbortController,h=setTimeout(()=>p.abort(),s),w=f?typeof AbortSignal.any=="function"?AbortSignal.any([f,p.signal]):f:p.signal,k=null,S=t,I=i?{lookupFn:i}:{};if(l&&!a&&!lt(S))throw Pe(`HTTP refused ${e}: untrustedUrl requires a pin-capable fetchImpl (see markPinCapableFetch in egress-guard.mjs) or no fetchImpl override so Oracle can pin the connection itself`);let _=async(g,{status:P=null}={})=>{let x=await it(g,I);if(!x.ok)throw Pe(P==null?`HTTP refused ${g}: ${x.error}`:`HTTP redirect to ${g} ${x.error}`,P==null?{}:{status:P});let m=new URL(g).hostname;if(a){if(k&&(await k.close(),k=null),!k)try{k=await at({requireUndici:!0,...d?{importUndici:d}:{}})}catch(M){throw Pe(P==null?`HTTP refused ${g}: ${M?.message||M}`:`HTTP redirect to ${g} refused: ${M?.message||M}`,P==null?{}:{status:P})}k.pin(m,x.addresses),S=k.fetch}else rr(S,m,x.addresses);return x};try{let g=String(e),P={...n||{}};l&&await _(g);for(let x=0;x<=sr;x+=1){let m=await S(g,{method:r,headers:P,body:o,signal:w,redirect:"manual"});if(hn.has(m.status)){if(r!=="GET"&&r!=="HEAD"){let $=await ir(m,u??yn,{url:g,truncate:!0}),T=new Error(`HTTP ${m.status} ${r} ${g} redirected non-idempotent request`);throw T.status=m.status,T.body=ar($)??$.slice(0,300),T}if(x===sr)throw Te(m),new Error(`HTTP redirect loop for ${e}`);let U=m.headers?.get?.("location"),z;try{z=bn(U,g)}catch($){throw Te(m),$}let y=!En(z,g);if(Te(m),y&&(P=gn(P)),l)await _(z,{status:m.status});else if(y){let $=await it(z,I);if(!$.ok){let T=new Error(`HTTP redirect from ${g} ${$.error}`);throw T.status=m.status,T.retryable=!1,T}a&&$.addresses?.length&&(k||(k=await at(d?{importUndici:d}:{})),k&&(k.pin(new URL(z).hostname,$.addresses),S=k.fetch))}g=z;continue}if(typeof c=="function")try{await c(m,{url:g})}catch(U){throw Te(m),Pe(U?.message||String(U))}let M=await ir(m,u,{url:g,onOversize:()=>p.abort()}),G=ar(M);if(!m.ok){let U=new Error(`HTTP ${m.status} ${r} ${g}`);throw U.status=m.status,U.retryAfter=m.headers?.get?.("retry-after")??null,U.body=G??M.slice(0,300),U}return G??M}throw new Error(`HTTP redirect loop for ${e}`)}finally{clearTimeout(h),k&&await k.close()}}async function lr(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(),s={Accept:"application/json",...t.headers||{}},i=t.body;i!=null&&typeof i!="string"&&(s["Content-Type"]=s["Content-Type"]||"application/json",i=JSON.stringify(i));let a=Number.isInteger(t.retries)?Math.max(t.retries,0):mn,l=t.lookupFn,u=!t.fetchImpl,d=t.untrustedUrl===!0,c=t.importUndici,f=t.validateResponse,p=t.signal,h=Number(t.maxResponseBytes),w=Number.isFinite(h)&&h>0?Math.floor(h):null,k=async()=>{let P;for(let x=0;x<=a;x++){p?.throwIfAborted?.();try{return await $n(e,{fetchImpl:r,method:o,headers:s,body:i,timeoutMs:n,lookupFn:l,realFetch:u,untrustedUrl:d,maxResponseBytes:w,importUndici:c,validateResponse:f,signal:p})}catch(m){P=m;let M=m?.status,G=m?.name==="AbortError"||m?.name==="TimeoutError"||p?.aborted,U=new Set([408,425,429]),z=m?.retryable===!1?!1:M!=null?U.has(M)||pn.has(M)&&nr.has(o):!G&&nr.has(o);if(x===a||!z)throw m;let y=xn(x,m?.retryAfter);p?await new Promise(($,T)=>{let L=setTimeout($,y);p.addEventListener("abort",()=>{clearTimeout(L),T(p.reason||new DOMException("Aborted","AbortError"))},{once:!0})}):await Sn(y)}}throw P};if(!(t.dedupe!==!1&&!p&&o==="GET"&&i==null))return k();let I=kn(o,e,s,{untrustedUrl:d,maxResponseBytes:w}),_=ut.get(I);if(_)return _;let g=k().finally(()=>ut.delete(I));return ut.set(I,g),g}var Pn="https://api.hyperliquid.xyz/info",Tn="https://api.hyperliquid-testnet.xyz/info";function In({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"?Tn:Pn}async function Ie(e,t={}){if(!e||!e.type)throw new Error("hlInfo requires body.type");let r=In(t);return lr(r,{method:"POST",body:e,fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs})}async function ur(e,t={}){if(!e)throw new Error("hlL2Book requires coin");return Ie({type:"l2Book",coin:String(e)},t)}async function fr(e={}){return Ie({type:"meta"},e)}async function dr(e={}){let t={type:"metaAndAssetCtxs"};return e.dex&&(t.dex=e.dex),Ie(t,e)}async function pr({coin:e,interval:t="1h",startTime:r,endTime:n},o={}){if(!e)throw new Error("hlCandleSnapshot requires coin");let s={type:"candleSnapshot",req:{coin:String(e),interval:t,startTime:r??Date.now()-24*3600*1e3,endTime:n??Date.now()}};return Ie(s,o)}async function mr({coin:e,startTime:t,endTime:r},n={}){if(!e)throw new Error("hlFundingHistory requires coin");return Ie({type:"fundingHistory",coin:String(e),startTime:t??Date.now()-24*3600*1e3,endTime:r??Date.now()},n)}function ve(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 ce(e){if(!Number.isInteger(e)||e<=0)throw new TypeError("period must be a positive integer")}function _n(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 dt(e,t){ve(e),ce(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 _e(e,t){ve(e),ce(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 s=2/(t+1);for(let i=t;i<e.length;i++)o=s*e[i]+(1-s)*o,r[i]=o;return r}function pt(e,t){ve(e),ce(t);let r=new Array(e.length).fill(null);if(e.length<=t)return r;let n=0,o=0;for(let a=1;a<=t;a++){let l=e[a]-e[a-1];l>=0?n+=l:o-=l}let s=n/t,i=o/t;r[t]=hr(s,i);for(let a=t+1;a<e.length;a++){let l=e[a]-e[a-1],u=l>0?l:0,d=l<0?-l:0;s=(s*(t-1)+u)/t,i=(i*(t-1)+d)/t,r[a]=hr(s,i)}return r}function hr(e,t){return e===0&&t===0?50:t===0?100:e===0?0:100-100/(1+e/t)}function mt(e,t={}){ve(e);let r=t.fastPeriod,n=t.slowPeriod,o=t.signalPeriod;if(ce(r),ce(n),ce(o),r>=n)throw new TypeError("fastPeriod must be < slowPeriod");let s=_e(e,r),i=_e(e,n),a=new Array(e.length).fill(null);for(let c=0;c<e.length;c++)s[c]!=null&&i[c]!=null&&(a[c]=s[c]-i[c]);let l=new Array(e.length).fill(null),u=new Array(e.length).fill(null),d=[];for(let c=0;c<a.length;c++)a[c]!=null&&d.push(c);if(d.length>=o){let c=0;for(let w=0;w<o;w++)c+=a[d[w]];let f=c/o,p=d[o-1];l[p]=f,u[p]=a[p]-f;let h=2/(o+1);for(let w=o;w<d.length;w++){let k=d[w];f=h*a[k]+(1-h)*f,l[k]=f,u[k]=a[k]-f}}return{line:a,signal:l,histogram:u}}function ht(e,t={}){ve(e);let r=t.period,n=t.stdDev;if(ce(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),s=new Array(e.length).fill(null),i=new Array(e.length).fill(null);if(e.length<r)return{upper:s,middle:o,lower:i};let a=0,l=0;for(let u=0;u<e.length;u++){let d=e[u];if(a+=d,l+=d*d,u>=r){let c=e[u-r];a-=c,l-=c*c}if(u>=r-1){let c=a/r,f=l/r-c*c;f<0&&f>-1e-12&&(f=0);let p=Math.sqrt(f);o[u]=c,s[u]=c+n*p,i[u]=c-n*p}}return{upper:s,middle:o,lower:i}}function yt(e,t){_n(e),ce(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 a=e[i];if(i===0)n[i]=a.h-a.l;else{let l=e[i-1].c;n[i]=Math.max(a.h-a.l,Math.abs(a.h-l),Math.abs(a.l-l))}}let o=0;for(let i=0;i<t;i++)o+=n[i];let s=o/t;r[t-1]=s;for(let i=t;i<e.length;i++)s=(s*(t-1)+n[i])/t,r[i]=s;return r}import{createHash as vn}from"node:crypto";var wt=3,On="7477966facc4ef928a94e6221c8fd238eef4fcbeec46b96ae1b89178e13c2d5f",Nn="68f5b412a9975f04024cf9b9b6209b4bccedd52f176e95f34f786b3f53479c6a",Mn="967fd45ecddd0d59ac0f662fe92ea813c32620ba751f249b4ace6cb6b809fb5e",yr=vn("sha256").update(JSON.stringify({version:wt,compilerSourceHash:On,indicatorsSourceHash:Nn,schemaSourceHash:Mn})).digest("hex");var we=wt,le=yr,Rn=Object.freeze({open:"o",high:"h",low:"l",close:"c",volume:"v",fundingRate:"fundingRate",openInterest:"openInterest",premium:"premium",oiDelta:"oiDelta",bookImbalance:"bookImbalance"}),Ln=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 X(e){return typeof e=="number"&&Number.isFinite(e)}function Fn(e){let t=new Map(e.map(a=>[a.id,a])),r=a=>{switch(a.type){case"indicator":return a.input?[a.input]:[];case"compare":case"cross":return[a.left,a.right];case"logic":return[...a.inputs];default:return[]}},n=new Map,o=new Map;for(let a of e)n.set(a.id,0),o.set(a.id,[]);for(let a of e)for(let l of r(a))t.has(l)&&(o.get(l).push(a.id),n.set(a.id,n.get(a.id)+1));let s=[];for(let[a,l]of n)l===0&&s.push(a);let i=[];for(;s.length;){let a=s.shift();i.push(a);for(let l of o.get(a))n.set(l,n.get(l)-1),n.get(l)===0&&s.push(l)}if(i.length!==e.length)throw new Error("strategy graph is cyclic");return i}function ye(e,t){return e!=null&&typeof e=="object"&&"param"in e?t[e.param].value:e}function jn(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 s=e[o];if(s==null||typeof s!="object"||Array.isArray(s))throw new TypeError(`bars[${o}] must be an object`);let{t:i,o:a,h:l,l:u,c:d,v:c}=s;if(!X(i)&&(typeof i=="number"&&Number.isFinite(i)),!Number.isFinite(i))throw new TypeError(`bars[${o}].t must be finite`);for(let[f,p]of[["o",a],["h",l],["l",u],["c",d],["v",c]])if(!X(p))throw new TypeError(`bars[${o}].${f} must be a finite number`);for(let[f,p]of[["o",a],["h",l],["l",u],["c",d]])if(!(p>0))throw new TypeError(`bars[${o}].${f} price must be positive`);if(c<0)throw new TypeError(`bars[${o}].v volume must be non-negative`);if(l<Math.max(a,d,u))throw new TypeError(`bars[${o}] high must be >= max(open, close, low)`);if(u>Math.min(a,d,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!==Ln[r])throw new TypeError(`bars t must match ${r} cadence`)}if(n=i,"fundingRate"in s&&s.fundingRate!=null&&!X(s.fundingRate))throw new TypeError(`bars[${o}].fundingRate must be finite when present`);if("openInterest"in s&&s.openInterest!=null){if(!X(s.openInterest))throw new TypeError(`bars[${o}].openInterest must be finite when present`);if(s.openInterest<0)throw new TypeError(`bars[${o}].openInterest must be non-negative`)}for(let f of["premium","oiDelta"])if(f in s&&s[f]!=null&&!X(s[f]))throw new TypeError(`bars[${o}].${f} must be finite when present`);if("bookImbalance"in s&&s.bookImbalance!=null){if(!X(s.bookImbalance))throw new TypeError(`bars[${o}].bookImbalance must be finite when present`);if(s.bookImbalance<-1||s.bookImbalance>1)throw new TypeError(`bars[${o}].bookImbalance must be within [-1, 1]`)}}}function de(e,t,r,n,o,s){if(s.has(e))return s.get(e);let i=t.get(e),a;switch(i.type){case"input":{let l=Rn[i.field];a=new Array(o+1);for(let u=0;u<=o;u++){let d=n[u][l];a[u]=d===void 0?null:d}break}case"constant":{let l=ye(i.value,r);a=new Array(o+1).fill(l);break}case"indicator":{let l=i.period!=null?ye(i.period,r):void 0;if(i.indicator==="atr"){let c=[];for(let f=0;f<=o;f++){let p=n[f];c.push({o:p.o,h:p.h,l:p.l,c:p.c})}a=yt(c,l);break}let d=de(i.input,t,r,n,o,s).map((c,f)=>{if(c==null||!X(c))throw new TypeError(`indicator input ${i.input} has non-finite value at ${f}`);return c});if(i.indicator==="sma")a=dt(d,l);else if(i.indicator==="ema")a=_e(d,l);else if(i.indicator==="rsi")a=pt(d,l);else if(i.indicator==="macd")a=mt(d,{fastPeriod:ye(i.fastPeriod,r),slowPeriod:ye(i.slowPeriod,r),signalPeriod:ye(i.signalPeriod,r)})[i.output];else if(i.indicator==="bollinger")a=ht(d,{period:l,stdDev:ye(i.stdDev,r)})[i.output];else throw new Error(`unsupported indicator ${i.indicator}`);break}case"compare":{let l=de(i.left,t,r,n,o,s),u=de(i.right,t,r,n,o,s);a=new Array(o+1);for(let d=0;d<=o;d++){let c=l[d],f=u[d];if(c==null||f==null||!X(c)||!X(f)){a[d]=!1;continue}switch(i.op){case"gt":a[d]=c>f;break;case"gte":a[d]=c>=f;break;case"lt":a[d]=c<f;break;case"lte":a[d]=c<=f;break;case"eq":a[d]=c===f;break;default:a[d]=!1}}break}case"logic":{let l=i.inputs.map(u=>de(u,t,r,n,o,s));a=new Array(o+1);for(let u=0;u<=o;u++)if(i.op==="not"){let d=l[0][u];a[u]=d===!0?!1:d===!1}else if(i.op==="and"){let d=!0;for(let c of l)if(c[u]!==!0){d=!1;break}a[u]=d}else if(i.op==="or"){let d=!1;for(let c of l)if(c[u]===!0){d=!0;break}a[u]=d}else a[u]=!1;break}case"cross":{let l=de(i.left,t,r,n,o,s),u=de(i.right,t,r,n,o,s);a=new Array(o+1),a[0]=!1;for(let d=1;d<=o;d++){let c=l[d-1],f=u[d-1],p=l[d],h=u[d];if(c==null||f==null||p==null||h==null||!X(c)||!X(f)||!X(p)||!X(h)){a[d]=!1;continue}i.direction==="above"?a[d]=c<=f&&p>h:a[d]=c>=f&&p<h}break}default:throw new Error(`unknown node type ${i.type}`)}return s.set(e,a),a}function K(e,t={}){let r=Y(e);t&&Object.keys(t).length&&(r=ge(r,t));let n=new Map(r.nodes.map(p=>[p.id,p])),o=Object.freeze(Fn(r.nodes)),s=r.parameters,i=new Set(r.nodes.filter(p=>p.type==="input").map(p=>p.field));if(r.nodes.some(p=>p.type==="indicator"&&p.indicator==="atr"))for(let p of["open","high","low","close"])i.add(p);let a=Object.freeze([...i].sort()),l=pe(r);function u(p,h){let w={};for(let S of o){let I=p.get(S);w[S]=I[h]}let k=S=>S!=null&&w[S]===!0;return{values:w,signals:{entryLong:k(r.rules.entryLong),entryShort:k(r.rules.entryShort),exitLong:k(r.rules.exitLong),exitShort:k(r.rules.exitShort)}}}function d(p,h){jn(p,h,r.market.interval);let w=new Map;for(let k of o)de(k,n,s,p,h,w);return w}function c(p,h){return u(d(p,h),h)}function f(p){if(!Array.isArray(p)||p.length===0)throw new TypeError("bars must be a non-empty array");let h=p.length-1,w=d(p,h);return Object.freeze(p.map((k,S)=>Object.freeze(u(w,S))))}return Object.freeze({strategy:r,strategyHash:l,compilerVersion:we,compilerHash:le,requiredSeries:a,nodeOrder:o,evaluate:c,evaluateAll:f})}import{createHash as eo}from"node:crypto";import{createHash as Hn}from"node:crypto";var Cn=Object.freeze({initialEquityUsd:1e4,takerFeeBps:3.5,builderFeeBps:2,slippageBps:2,latencyBars:1,maxVolumeParticipationPct:100});function qn(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function te(e){return typeof e=="number"&&Number.isFinite(e)}function gt(e){if(e==null||typeof e!="object"||Object.isFrozen(e))return e;if(Array.isArray(e)){for(let t of e)gt(t);return Object.freeze(e)}for(let t of Object.keys(e))gt(e[t]);return Object.freeze(e)}function Ue(e){if(Array.isArray(e))return e.map(Ue);if(e!=null&&typeof e=="object"){let t={};for(let r of Object.keys(e).sort())t[r]=Ue(e[r]);return t}return e}function bt(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)=>bt(r,`${t}[${n}]`));return}for(let[r,n]of Object.entries(e))bt(n,`${t}.${r}`)}}function gr(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:s,h:i,l:a,c:l,v:u}=n;if(!te(o))throw new TypeError(`bars[${r}].t must be finite`);for(let[d,c]of[["o",s],["h",i],["l",a],["c",l],["v",u]])if(!te(c))throw new TypeError(`bars[${r}].${d} must be a finite number`);for(let[d,c]of[["o",s],["h",i],["l",a],["c",l]])if(!(c>0))throw new TypeError(`bars[${r}].${d} price must be positive`);if(u<0)throw new TypeError(`bars[${r}].v volume must be non-negative`);if(i<Math.max(s,l,a))throw new TypeError(`bars[${r}] high must be >= max(open, close, low)`);if(a>Math.min(s,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&&!te(n.fundingRate))throw new TypeError(`bars[${r}].fundingRate must be finite when present`);if("fundingPaymentRate"in n&&n.fundingPaymentRate!=null&&!te(n.fundingPaymentRate))throw new TypeError(`bars[${r}].fundingPaymentRate must be finite when present`);if("openInterest"in n&&n.openInterest!=null&&!te(n.openInterest))throw new TypeError(`bars[${r}].openInterest must be finite when present`)}}function Oe(e){if(!Array.isArray(e))throw new TypeError("bars must be an array");return e.length>0&&gr(e),Hn("sha256").update(JSON.stringify(Ue(e)),"utf8").digest("hex")}function Un(e){if(e==null&&(e={}),!qn(e))throw new TypeError("options must be a plain object");let t={...Cn},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(!te(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(!te(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(!te(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 De(e){return e/1e4}function Dn(e,t,r){let n=De(r);return t==="long"?e*(1+n):e*(1-n)}function Bn(e,t,r){let n=De(r);return t==="long"?e*(1-n):e*(1+n)}function wr(e,t,r){let n=Math.abs(e)*De(t),o=Math.abs(e)*De(r);return{taker:n,builder:o,total:n+o}}function zn(e,t){let r=e*(t.positionSizePct/100)*t.maxLeverage;return Math.min(r,t.maxNotionalUsd)}function Vn(e,t,r){let n=r/100;return t==="long"?e*(1-n):e*(1+n)}function Jn(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 Yn(e,t,r){return t==="long"?e.l<=r:e.h>=r}function Gn(e,t,r){return t==="long"?e.h>=r:e.l<=r}function Xn(e,t,r){return t==="long"?e.l<=r:e.h>=r}var Wn=Object.freeze(["fundingRate","openInterest","premium","oiDelta","bookImbalance"]);function Ne(e,t){for(let r of e.requiredSeries)if(Wn.includes(r)&&!t.every(n=>te(n?.[r])))throw new Error(`strategy required series is absent: ${r}`)}function Zn(e){if(e.length<3)return 0;let t=[];for(let i=1;i<e.length;i++){let a=e[i-1].equity,l=e[i].equity;a>0&&t.push((l-a)/a)}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 s=Math.sqrt(o/(t.length-1));return s>0?n/s:0}function Qn(e){let t=-1/0,r=0;for(let n of e){let o=n.equity;if(o>t&&(t=o),t>0){let s=(t-o)/t*100;s>r&&(r=s)}}return r}function ie(e,t,r={}){let n=Un(r);gr(t);let o=Oe(t);n.nowMs!==void 0&&Y(e,{nowMs:n.nowMs});let s=K(e);if(Ne(s,t),n.nowMs!==void 0&&s.strategy.risk.expiresAt<=n.nowMs)throw new Error("strategy is expired: risk.expiresAt must be strictly greater than nowMs");let i=s.strategy.risk,a=s.evaluateAll(t),l=n.latencyBars,u=n.slippageBps,d=n.takerFeeBps,c=n.builderFeeBps,f=n.initialEquityUsd,p=0,h=0,w=0,k=0,S=0,I=[],_=[],g=[],P=[],x=[],m=null,M=0,G=null,U=f,z=!1,y=0,$=0,T=[],L=new Array(t.length).fill(0);function j(E){T.push(E)}function O(E){let v=t[E].v*(n.maxVolumeParticipationPct/100);return Math.max(0,v-L[E])}function R(E){if(!m)return f;let v=m.side==="long"?(E-m.entryPrice)*m.qty:(m.entryPrice-E)*m.qty;return f+v}function J(E,v,A){let H=A.o,N=zn(f,i);if(!(N>0)||!(H>0))return;let C=Dn(H,v,u),F=N/C,B=O(E),Ae=C*B;if(F>B){g.push({kind:"entry",barIndex:E,time:A.t,side:v,requestedNotionalUsd:N,maxFillNotionalUsd:Ae,reason:"volume_participation"});return}L[E]+=F;let ee=Math.abs(C-H)*F,se=wr(N,d,c);f-=se.total,p+=se.taker,h+=se.builder,k+=ee,S+=N,m={lifecycleEpoch:++$,side:v,entryBarIndex:E,entryReferencePrice:H,entryPrice:C,qty:F,notionalUsd:N,stop:Vn(C,v,i.stopLossPct),take:Jn(C,v,i.takeProfitPct),liq:Kn(C,v,i.maxLeverage,d+c),entryFees:se.taker,entryBuilderFees:se.builder,entrySlippageUsd:ee,fundingAccrued:0}}function D(E,v,A,H){if(!m)return!1;let N=m.side,C=v,F=C;A!=="liquidation"&&H&&(F=Bn(C,N,u));let B=m.qty,Ae=B*F;if(A!=="liquidation"){let tr=O(E),an=F*tr;if(B>tr)return g.push({kind:"exit",barIndex:E,time:t[E].t,side:N,requestedNotionalUsd:Ae,maxFillNotionalUsd:an,reason:"volume_participation",triggerReason:A}),!1;L[E]+=B}let ee=wr(Ae,d,c),se=A==="liquidation"?0:Math.abs(F-C)*B,$e,nt;N==="long"?($e=(C-m.entryReferencePrice)*B,nt=(F-m.entryPrice)*B):($e=(m.entryReferencePrice-C)*B,nt=(m.entryPrice-F)*B),f+=nt,f-=ee.total,p+=ee.taker,h+=ee.builder,k+=se,S+=Ae;let sn={side:N,entryBarIndex:m.entryBarIndex,entryTime:t[m.entryBarIndex].t,entryPrice:m.entryPrice,exitBarIndex:E,exitTime:t[E].t,exitPrice:F,exitReason:A,qty:B,notionalUsd:m.notionalUsd,grossPnlUsd:$e,feesUsd:m.entryFees+ee.taker,builderFeesUsd:m.entryBuilderFees+ee.builder,fundingUsd:m.fundingAccrued,slippageUsd:m.entrySlippageUsd+se,netPnlUsd:$e-(m.entryFees+ee.taker+m.entryBuilderFees+ee.builder)-m.fundingAccrued-(m.entrySlippageUsd+se)};return I.push(sn),A==="liquidation"&&_.push({barIndex:E,time:t[E].t,side:N,price:F,tradeIndex:I.length-1}),m=null,$+=1,y=E+1+(i.cooldownBars||0),!0}function Q(E,v,A,H){let N=E+1;if(N>=t.length)return;T.some(F=>F.kind==="exit"&&F.side===v&&F.fillBar===N&&F.epoch===H)||j({kind:"exit",side:v,signalBar:E,fillBar:N,reason:A,epoch:H})}function je(E){let v=T.filter(A=>A.fillBar===E);for(let A=T.length-1;A>=0;A--)T[A].fillBar===E&&T.splice(A,1);v.sort((A,H)=>{let N=C=>C.kind==="exit"?0:1;return N(A)-N(H)});for(let A of v)if(A.kind==="exit"){if(!m||m.side!==A.side||m.lifecycleEpoch!==A.epoch)continue;let H=A.reason||"rule";D(E,t[E].o,H,!0)||Q(E,A.side,H,A.epoch)}else if(A.kind==="entry"){if(m||A.epoch!==$||E<y)continue;J(E,A.side,t[E])}}function He(E){if(!m)return;let v=t[E],A=v.fundingPaymentRate;if(A==null||!te(A)||A===0)return;let H=Math.abs(m.qty*v.c),N=A*H;m.side==="long"?(f-=N,m.fundingAccrued+=N,w+=N):(f+=N,m.fundingAccrued-=N,w-=N)}function Ce(E){if(!m)return;let v=t[E].o;(m.side==="long"?v<=m.liq:v>=m.liq)&&D(E,v,"liquidation",!1)}function Xt(E){if(!m)return;let v=t[E],A=m.side,H=Xn(v,A,m.liq),N=Yn(v,A,m.stop),C=Gn(v,A,m.take),F=B=>A==="long"?Math.min(B,v.o):Math.max(B,v.o);if(H){D(E,F(m.liq),"liquidation",!1);return}if(N&&C){D(E,F(m.stop),"stop_loss",!0)||Q(E,A,"stop_loss",m.lifecycleEpoch);return}if(N){D(E,F(m.stop),"stop_loss",!0)||Q(E,A,"stop_loss",m.lifecycleEpoch);return}C&&(D(E,m.take,"take_profit",!0)||Q(E,A,"take_profit",m.lifecycleEpoch))}for(let E=0;E<t.length;E++){let v=Math.floor(t[E].t/864e5);v!==G&&(G=v,U=R(t[E].o),z=!1),Ce(E),je(E),Xt(E),He(E),!z&&R(t[E].c)<=U*(1-i.maxDailyLossPct/100)&&(z=!0,P.push({type:"daily_loss_limit",barIndex:E,time:t[E].t,message:"daily loss limit reached; new entries blocked for UTC day"}));let A=a[E].signals,H=E+l;if(m)(m.side==="long"&&A.exitLong===!0||m.side==="short"&&A.exitShort===!0)&&H<t.length&&(T.some(B=>B.kind==="exit"&&B.side===m.side&&B.fillBar===H&&B.epoch===m.lifecycleEpoch)||j({kind:"exit",side:m.side,signalBar:E,fillBar:H,reason:"rule",epoch:m.lifecycleEpoch}));else{let C=A.entryLong===!0,F=A.entryShort===!0;C&&F?P.push({type:"conflicting_entry_signals",barIndex:E,time:t[E].t,message:"conflicting entry signals; no position opened"}):!z&&(C||F)&&H<t.length&&E>=y&&j({kind:"entry",side:C?"long":"short",signalBar:E,fillBar:H,epoch:$})}let N=f;m&&(M+=1,N=R(t[E].c)),x.push({barIndex:E,time:t[E].t,equity:N,positionSide:m?m.side:null})}let Wt=null;if(m){let E=t.length-1;if(D(E,t[E].c,"end_of_data",!0))x[E]={barIndex:E,time:t[E].t,equity:f,positionSide:null};else{let A=R(t[E].c);Wt={side:m.side,entryBarIndex:m.entryBarIndex,entryTime:t[m.entryBarIndex].t,entryPrice:m.entryPrice,qty:m.qty,notionalUsd:m.notionalUsd,markPrice:t[E].c,markedEquityUsd:A},P.push({type:"open_position_at_end",barIndex:E,time:t[E].t,message:"end-of-data exit missed; position remains open and marked"})}}let Zt=(m?R(t[t.length-1].c):f)-n.initialEquityUsd,tn=Zt/n.initialEquityUsd*100,Qt=0,Qe=0,et=0;for(let E of I)E.netPnlUsd>0?(Qt+=1,Qe+=E.netPnlUsd):E.netPnlUsd<0&&(et+=-E.netPnlUsd);let tt=I.length,rn=tt===0?0:Qt/tt,rt=0;et>0?rt=Qe/et:Qe>0&&(rt=1e12);let nn={netPnlUsd:Zt,netPnlPct:tn,maxDrawdownPct:Qn(x),winRate:rn,profitFactor:rt,tradeCount:tt,sharpe:Zn(x),turnoverUsd:S,exposurePct:M/t.length*100},on={initialEquityUsd:n.initialEquityUsd,takerFeeBps:n.takerFeeBps,builderFeeBps:n.builderFeeBps,slippageBps:n.slippageBps,latencyBars:n.latencyBars,maxVolumeParticipationPct:n.maxVolumeParticipationPct},er={barsHash:o,strategyHash:s.strategyHash,compilerHash:le,compilerVersion:we,config:on,trades:I,equityCurve:x,metrics:nn,costs:{feesUsd:p,builderFeesUsd:h,fundingUsd:w,slippageUsd:k},liquidations:_,missedFills:g,openPositionAtEnd:Wt,flags:P};return bt(er),gt(Ue(er))}var kr=Object.freeze(["fail","pass_paper_only","pass_live_eligible"]);function re(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function be(e){return typeof e=="number"&&Number.isFinite(e)}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 me(e){if(Array.isArray(e))return e.map(me);if(e!=null&&typeof e=="object"){let t={};for(let r of Object.keys(e).sort())t[r]=me(e[r]);return t}return e}function Et(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 br(e){return{feesUsd:e.costs.feesUsd,builderFeesUsd:e.costs.builderFeesUsd,fundingUsd:e.costs.fundingUsd,slippageUsd:e.costs.slippageUsd}}function to(e){return(e.feesUsd||0)+(e.builderFeesUsd||0)+Math.max(0,e.fundingUsd||0)+(e.slippageUsd||0)}function ro(e){let t=0;for(let r of e.trades)r.grossPnlUsd>0&&(t+=r.grossPnlUsd);return t}function no(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 xr(e){if(!re(e))throw new TypeError("evidence artifact must be a plain object");if(!kr.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(!re(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(!re(e.walkForward)||!Array.isArray(e.walkForward.windows))throw new TypeError("evidence artifact walkForward windows required");if(e.status==="pass_live_eligible"&&(!re(e.train)||!re(e.holdout)))throw new TypeError("live-eligible evidence artifact requires train and holdout facts");return me({barsHash:e.barsHash,compilerHash:e.compilerHash,flags:e.flags.map(t=>me(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 St(e){return eo("sha256").update(JSON.stringify(xr(e)),"utf8").digest("hex")}function Z(e,t,r=0){if(!Number.isInteger(e)||e<r)throw new Error(`${t} must be an integer >= ${r}`);return e}function kt(e,t){if(!re(e)||!re(e.metrics))throw new Error(`${t} metrics required`);let r=Z(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(!be(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 oo(e,{maxDailyLossPct:t}={}){let r=e.split,n=Z(r.trainStartIndex,"split.trainStartIndex"),o=Z(r.trainEndIndex,"split.trainEndIndex"),s=Z(r.trainBarCount,"split.trainBarCount",1),i=Z(r.holdoutStartIndex,"split.holdoutStartIndex"),a=Z(r.holdoutEndIndex,"split.holdoutEndIndex"),l=Z(r.holdoutBarCount,"split.holdoutBarCount",1);if(n!==0||o-n+1!==s||i!==o+1||a-i+1!==l)throw new Error("evidence split must be contiguous, chronological, and count-consistent");if(!be(r.trainFraction)||r.trainFraction<=0||r.trainFraction>=1)throw new Error("split.trainFraction must be in (0,1)");kt(e.train,"train");let u=kt(e.holdout,"holdout");if(u.tradeCount<1||u.netPnlUsd<=0||u.profitFactor<=1)throw new Error("live-eligible holdout metrics do not pass");if(be(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 d=e.walkForward,c=d.windows;if(c.length<1||d.windowsRun!==c.length)throw new Error("live-eligible walk-forward windowsRun must match nonempty windows");let f=0,p=-1;for(let w=0;w<c.length;w++){let k=c[w];if(!re(k)||k.index!==w||typeof k.passed!="boolean")throw new Error("walk-forward windows must be ordered and structurally valid");let S=Z(k.trainStartIndex,`walkForward.windows[${w}].trainStartIndex`),I=Z(k.trainEndIndex,`walkForward.windows[${w}].trainEndIndex`),_=Z(k.evalStartIndex,`walkForward.windows[${w}].evalStartIndex`),g=Z(k.evalEndIndex,`walkForward.windows[${w}].evalEndIndex`);if(S!==0||I>=_||_>g||_<=p)throw new Error("walk-forward windows must be chronological and disjoint");if(p=g,k.passed){if(f+=1,k.reason!=="pass")throw new Error("passed walk-forward window reason must be pass");let P=kt({metrics:k.metrics,tradeCount:k.metrics?.tradeCount},`walkForward.windows[${w}]`);if(P.tradeCount<1||P.netPnlUsd<=0||P.profitFactor<=1)throw new Error("passed walk-forward window metrics do not pass");if(be(t)&&P.maxDrawdownPct>t)throw new Error("passed walk-forward drawdown exceeds strategy risk")}else if(k.reason==="pass")throw new Error("failed walk-forward window cannot have pass reason")}let h=f/c.length;if(!be(d.passRate)||Math.abs(d.passRate-h)>Number.EPSILON||h<.6)throw new Error("walk-forward passRate contradicts concrete windows or is below live threshold")}function At(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=xr(e),n=me({id:e.id,...r});if(JSON.stringify(me(e))!==JSON.stringify(n))throw new Error("evidence artifact contains fields unbound from its deterministic identity");let o=St(e);if(e.id!==o)throw new Error("evidence.id does not match its deterministic artifact facts digest");return e.status==="pass_live_eligible"&&oo(e,t),e}function Be({strategy:e,bars:t,backtestOptions:r={},trainFraction:n=.7,walkForwardWindows:o=3,minTrades:s=10}={}){let i=[];if(!re(e))throw new TypeError("strategy must be a plain object");if(!Array.isArray(t))throw new TypeError("bars must be an array");if(!re(r))throw new TypeError("backtestOptions must be a plain object");if(!be(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(s)||s<0)throw new TypeError("minTrades must be an integer >= 0");let a=Y(e),l=pe(a),u=Oe(t),d=t.length,c=(O=[],R={})=>Er({status:"fail",strategy:a,sHash:l,barsHash:u,split:R.split||{trainStartIndex:0,trainEndIndex:-1,trainBarCount:0,holdoutStartIndex:0,holdoutEndIndex:-1,holdoutBarCount:0,trainFraction:n},train:R.train||null,holdout:R.holdout||null,walkForward:R.walkForward||{windows:[],passRate:0},flags:[...i,...O]});if(d<10)return c([{type:"insufficient_bars",message:"need at least 10 bars for evidence"}]);let f=Math.floor(d*n),p=f,h=d-p;if(f<5||h<3)return c([{type:"invalid_windowing",message:"train/holdout split too small",trainCount:f,holdoutCount:h}]);let w=t.slice(0,f),k=t.slice(p),S,I;try{S=ie(a,w,r),I=ie(a,k,r)}catch(O){return c([{type:"backtest_error",message:String(O.message||O)}])}let _={metrics:Et(S),costs:br(S),tradeCount:S.metrics.tradeCount},g={metrics:Et(I),costs:br(I),tradeCount:I.metrics.tradeCount},P={trainStartIndex:0,trainEndIndex:f-1,trainBarCount:f,holdoutStartIndex:p,holdoutEndIndex:d-1,holdoutBarCount:h,trainFraction:n},x=[],m=Math.floor(d/(o+1));if(m<3)i.push({type:"invalid_windowing",message:"walk-forward window size too small",wfSize:m});else for(let O=0;O<o;O++){let R=m*(O+1),J=R,D=Math.min(d,J+m);if(D-J<3||R<3){x.push({index:O,trainStartIndex:0,trainEndIndex:R-1,evalStartIndex:J,evalEndIndex:D-1,passed:!1,reason:"window_too_small",metrics:null});continue}let Q=t.slice(J,D),je;try{je=ie(a,Q,r)}catch{x.push({index:O,trainStartIndex:0,trainEndIndex:R-1,evalStartIndex:J,evalEndIndex:D-1,passed:!1,reason:"backtest_error",metrics:null});continue}let He=Et(je),Ce=no(He,a.risk,s);x.push({index:O,trainStartIndex:0,trainEndIndex:R-1,evalStartIndex:J,evalEndIndex:D-1,passed:Ce,reason:Ce?"pass":"fail_metrics",metrics:He})}let M=x.filter(O=>O.passed).length,G=x.length===0?0:M/x.length,U={windows:x,passRate:G,windowsRun:x.length};g.metrics.tradeCount===0&&_.metrics.tradeCount===0&&i.push({type:"no_trades",message:"no trades in train or holdout"}),g.metrics.tradeCount===0&&i.push({type:"absent_oos_trades",message:"holdout produced no trades"}),g.metrics.netPnlUsd<0&&i.push({type:"holdout_loss",message:"holdout netPnlUsd is negative"}),_.metrics.netPnlUsd>0&&g.metrics.netPnlUsd<0&&_.metrics.netPnlUsd>Math.abs(g.metrics.netPnlUsd)*.25?i.push({type:"overfit",message:"profitable train with losing holdout (OOS collapse)"}):_.metrics.netPnlUsd>0&&g.metrics.netPnlUsd>0&&g.metrics.netPnlUsd<_.metrics.netPnlUsd*.1&&_.metrics.tradeCount>=s&&i.push({type:"severe_oos_collapse",message:"holdout pnl collapsed vs train"});let z=to(g.costs),y=ro(I);y>0&&z>y&&i.push({type:"costs_exceed_gross",message:"holdout costs exceed gross gains"});let $=i.some(O=>["insufficient_bars","invalid_windowing","absent_oos_trades","holdout_loss","no_trades","severe_oos_collapse","backtest_error"].includes(O.type)),T=i.some(O=>O.type==="overfit"),L="fail";return g.metrics.tradeCount>=s&&g.metrics.netPnlUsd>0&&g.metrics.profitFactor>1&&g.metrics.maxDrawdownPct<=a.risk.maxDailyLossPct&&G>=.6&&!(y>0&&z>y)&&!T&&!i.some(O=>O.type==="severe_oos_collapse"||O.type==="invalid_windowing")?L="pass_live_eligible":!$&&g.metrics.tradeCount>0&&_.metrics.tradeCount>0&&Number.isFinite(g.metrics.netPnlUsd)?(L="pass_paper_only",g.metrics.tradeCount<s&&i.push({type:"undersampled",message:"holdout trades below minTrades"})):T&&g.metrics.tradeCount>0&&_.metrics.netPnlUsd>0?L="fail":g.metrics.tradeCount>0&&_.metrics.tradeCount>0&&!$?L="pass_paper_only":L="fail",g.metrics.netPnlUsd<0&&(L=L==="pass_live_eligible"?"fail":L==="pass_paper_only"?"pass_paper_only":"fail",L="fail"),Er({status:L,strategy:a,sHash:l,barsHash:u,split:P,train:_,holdout:g,walkForward:U,flags:i})}function Er({status:e,strategy:t,sHash:r,barsHash:n,split:o,train:s,holdout:i,walkForward:a,flags:l}){let u={status:e,strategyHash:r,compilerHash:le,barsHash:n,split:o,train:s,holdout:i,walkForward:a,flags:l};return u.id=St(u),xt(me(JSON.parse(JSON.stringify(u))))}import{createHash as so,createHmac as io,timingSafeEqual as fi}from"node:crypto";var ao=2,co=300*1e3,lo=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})();function $t(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map($t).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${$t(e[r])}`).join(",")}}`}function Sr(e){let t=String(e?.ORACLE_STAMP_HMAC_SECRET||"").trim();return t.length>=16?t:""}function Ar(e=process.env){return Sr(process.env)||Sr(e)}function uo(e){let{prepareHash:t,prepareMac:r,note:n,...o}=e||{};return o}function fo(e){let t=uo(e);return so("sha256").update($t(t)).digest("hex")}function po(e,t=Ar()){return t?io("sha256",t).update(String(e)).digest("hex"):""}function $r(e,{provider:t,kind:r,env:n=process.env,nowMs:o=Date.now(),expiresAtMs:s}={}){if(!e||typeof e!="object")throw new Error("stampPrepared: payload object required");let i=Object.prototype.hasOwnProperty.call(e,"oraclePrepared");if(i&&typeof e.oraclePrepared!="boolean")throw new Error("stampPrepared: oraclePrepared must be boolean");let a={...e,provider:e.provider||t,kind:e.kind||r,requiresUserSignature:e.requiresUserSignature!==!1,signingReady:!1,broadcastReady:!1,executionReady:!1,oraclePrepared:i?e.oraclePrepared:!0};if(!a.provider)throw new Error("stampPrepared: provider required");if(!a.kind)throw new Error("stampPrepared: kind required");let l=Number(o),u=s==null?l+co:Number(s),d=u-l;if(!Number.isSafeInteger(l)||!Number.isSafeInteger(u)||d<=0||d>lo)throw new Error("stampPrepared: bounded preparedAt/expiresAt required");let f={...a,preparedAt:l,expiresAt:u,prepareVersion:ao},p=fo(f),h=Ar(n),w=h?po(p,h):void 0,k={...f,prepareHash:p};return w&&(k.prepareMac=w),k}var mo=["privatekey","secretkey","seed","mnemonic","passphrase","password","keystore","keymaterial","apikey","authtoken","accesstoken","refreshtoken","credential","bearer","signature","authorization","xprv","xpriv","wif"];function Me(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function ho(e){return String(e).toLowerCase().replace(/[^a-z0-9]/g,"")}function Tt(e,t="value"){if(Array.isArray(e)){e.forEach((r,n)=>Tt(r,`${t}[${n}]`));return}if(Me(e))for(let[r,n]of Object.entries(e)){let o=ho(r);if(mo.some(s=>o.includes(s)))throw new Error(`handoff: forbidden secret-like field at ${t}.${r}`);Tt(n,`${t}.${r}`)}}function Pt(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function It({strategy:e,evidence:t,shadow:r,caps:n,nowMs:o=Date.now(),env:s=process.env}={}){if(Tt({strategy:e,evidence:t,shadow:r,caps:n},"handoff"),!Me(e))throw new Error("handoff: strategy required");if(!Me(t))throw new Error("handoff: evidence required");if(!Me(r))throw new Error("handoff: shadow required");if(!Me(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=Y(e,{nowMs:o}),a=K(i);if(At(t,{maxDailyLossPct:i.risk.maxDailyLossPct}),t.status!=="pass_live_eligible")throw new Error("handoff: evidence.status must be pass_live_eligible");if(t.strategyHash!==a.strategyHash)throw new Error("handoff: evidence.strategyHash mismatch");if(t.compilerHash!==a.compilerHash)throw new Error("handoff: evidence.compilerHash mismatch");let l=["perStrategyNotionalUsd","maxLeverage","dailyLossCapUsd","chainAllowlist","assetAllowlist","expiresAt","killSwitchRequired"];for(let f of l)if(!(f in n)||n[f]==null)throw new Error(`handoff: caps.${f} required`);if(!Pt(n.perStrategyNotionalUsd))throw new Error("handoff: caps.perStrategyNotionalUsd must be positive");if(n.perStrategyNotionalUsd>a.strategy.risk.maxNotionalUsd)throw new Error("handoff: caps.perStrategyNotionalUsd exceeds strategy.risk.maxNotionalUsd");if(!Pt(n.maxLeverage))throw new Error("handoff: caps.maxLeverage must be positive");if(n.maxLeverage>a.strategy.risk.maxLeverage)throw new Error("handoff: caps.maxLeverage exceeds strategy.risk.maxLeverage");if(!Pt(n.dailyLossCapUsd))throw new Error("handoff: caps.dailyLossCapUsd must be positive");let u=a.strategy.risk.maxNotionalUsd*(a.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(f=>f==="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]!==a.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>a.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 d={perStrategyNotionalUsd:n.perStrategyNotionalUsd,maxLeverage:n.maxLeverage,dailyLossCapUsd:n.dailyLossCapUsd,chainAllowlist:[...n.chainAllowlist],assetAllowlist:[...n.assetAllowlist],expiresAt:n.expiresAt,killSwitchRequired:!0},c={strategyHash:a.strategyHash,compilerHash:a.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:a.strategyHash,compilerHash:a.compilerHash,compilerVersion:we,venue:"hyperliquid",market:{coin:a.strategy.market.coin,kind:"perp",interval:a.strategy.market.interval},risk:{...a.strategy.risk},strategy:JSON.parse(JSON.stringify(a.strategy))},arming:{liveBroadcast:!1,requiresExplicitUserArm:!0,caps:d},requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,executionReady:!1};return $r(c,{provider:"hl-strategy",kind:"strategy-live-handoff",env:s})}var yo=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 Ee(e,t){let r=Number(e);if(!Number.isFinite(r))throw new TypeError(`${t} must be finite`);return r}function ke(e,t){if(!Number.isSafeInteger(e)||e<0)throw new TypeError(`${t} must be a non-negative safe integer`);return e}function Re(e){if(Array.isArray(e))for(let t of e)Re(t);else if(e&&typeof e=="object")for(let t of Object.values(e))Re(t);return Object.freeze(e)}function Pr(e){let t=yo[e];if(!t)throw new TypeError(`unsupported strategy interval: ${e}`);return t}function Tr(e,{endTime:t=Number.MAX_SAFE_INTEGER}={}){if(!Array.isArray(e))throw new TypeError("Hyperliquid candles must be an array");ke(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 s=ke(Number(o.t),`candles[${n}].t`);if(ke(Number(o.T),`candles[${n}].T`)>t)continue;let a={t:s,o:Ee(o.o,`candles[${n}].o`),h:Ee(o.h,`candles[${n}].h`),l:Ee(o.l,`candles[${n}].l`),c:Ee(o.c,`candles[${n}].c`),v:Ee(o.v,`candles[${n}].v`)};if(a.h<Math.max(a.o,a.c,a.l))throw new TypeError(`candles[${n}].h is below another price`);if(a.l>Math.min(a.o,a.c,a.h))throw new TypeError(`candles[${n}].l is above another price`);if(a.v<0)throw new TypeError(`candles[${n}].v must be non-negative`);let l=r.get(s);if(l&&JSON.stringify(l)!==JSON.stringify(a))throw new TypeError(`conflicting duplicate candle at timestamp ${s}`);l||r.set(s,a)}return Re([...r.values()].sort((n,o)=>n.t-o.t))}function wo(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 s=ke(Number(o.time),`funding[${n}].time`);s>t||r.set(s,{time:s,fundingRate:Ee(o.fundingRate,`funding[${n}].fundingRate`)})}return[...r.values()].sort((n,o)=>n.time-o.time)}async function go({coin:e,startTime:t,endTime:r},n){let o=[],s=Math.max(0,t-288e5),i=!1;for(let a=0;a<16&&s<=r;a++){let l=await mr({coin:e,startTime:s,endTime:r},n);if(!Array.isArray(l))throw new TypeError("Hyperliquid funding history must be an array");o.push(...l);let u=s;for(let d of l){let c=Number(d?.time);Number.isSafeInteger(c)&&c>u&&(u=c)}if(l.length<500||u>=r){i=!0;break}if(u<=s)throw new Error("Hyperliquid funding history pagination did not advance");s=u+1}if(!i)throw new Error("strategy history exceeds the bounded funding history limit");return wo(o,r)}function bo(e,t,r){let n=0,o=null;return e.map(s=>{let i=s.t+r,a=0;for(;n<t.length&&t[n].time<i;){let l=t[n];o=l.fundingRate,l.time>=s.t&&(a+=l.fundingRate),n+=1}return o==null?{...s,fundingPaymentRate:a}:{...s,fundingRate:o,fundingPaymentRate:a}})}async function _t(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=Pr(n);if(e.endTime==null)throw new TypeError("endTime is required for deterministic history");let s=ke(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 a=e.startTime==null?Math.max(0,s-i*o):ke(e.startTime,"startTime");if(a>=s)throw new TypeError("startTime must be before endTime");let[l,u]=await Promise.all([pr({coin:r,interval:n,startTime:a,endTime:s},t),go({coin:r,startTime:a,endTime:s},t)]),d=Tr(l,{endTime:s}),c=Re(bo(d,u,o));return Re({coin:r,interval:n,range:{startTime:a,endTime:s},bars:c})}var Eo=new Set(["1m","3m","5m","15m","30m","1h","2h","4h","8h","12h","1d"]),ko=new Set(["coin","interval"]);function xo(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))ko.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"||!Eo.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 So(e={}){let t=await fr(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 Ir=Object.freeze({id:"hyperliquid",validateMarket:xo,fetchBars:_t,listMarkets:So,prepareIntent(e){return It(e)}});var Ao=Object.freeze(["id","validateMarket","prepareIntent"]);function $o(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 Ao.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 _r=[Ir].map($o),Po=new Map(_r.map(e=>[e.id,e])),To=Object.freeze([..._r]);function ze(e){return typeof e!="string"?null:Po.get(e)??null}function Ve(e){let t=ze(e);if(!t)throw new Error(`unknown strategy venue: ${String(e)}`);return t}var Je=1,Cr=/^[a-z0-9][a-z0-9._-]{0,63}$/,qr=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,_o=new Set(["open","high","low","close","volume","fundingRate","openInterest","premium","oiDelta","bookImbalance"]),vo=new Set(["sma","ema","rsi","macd","bollinger","atr"]),Oo=new Set(["gt","gte","lt","lte","eq"]),No=new Set(["and","or","not"]),Mo=new Set(["above","below"]),Ro=new Set(["line","signal","histogram"]),Lo=new Set(["upper","middle","lower"]),vt=new Set(["compare","logic","cross"]),vr=new Set(["version","id","name","venue","market","parameters","nodes","rules","risk"]),Or=new Set(["value","min","max","step"]),Ot=new Set(["entryLong","entryShort","exitLong","exitShort"]),Nr=new Set(["maxLeverage","maxNotionalUsd","positionSizePct","stopLossPct","takeProfitPct","cooldownBars","maxDailyLossPct","expiresAt"]),Fo=new Set(["id","type"]),Mr={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"])},Rr=16,Lr=128,Fr=100,he=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 W(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function q(e){return typeof e=="number"&&Number.isFinite(e)}function jr(e){return Number.isInteger(e)&&e>0}function Mt(e){if(e==null||typeof e!="object"||Object.isFrozen(e))return e;if(Array.isArray(e)){for(let t of e)Mt(t);return Object.freeze(e)}for(let t of Object.keys(e))Mt(e[t]);return Object.freeze(e)}function Rt(e){if(Array.isArray(e))return e.map(Rt);if(e!=null&&typeof e=="object"){let t={};for(let r of Object.keys(e).sort())t[r]=Rt(e[r]);return t}return e}function b(e,t,r){e.push({path:t,message:r})}function ue(e,t,r,n){for(let o of Object.keys(e))t.has(o)||b(n,r?`${r}.${o}`:o,"unknown field is not allowed")}function Ur(e,t,r,n){if(!q(e)||!q(t)||!q(r)||!q(n)||n<=0||e<t||e>r)return!1;let o=(e-t)/n;if(!Number.isFinite(o))return!1;let s=Math.round(o);return Math.abs(o-s)<=1e-9}function Nt(e,t,r,n){if(W(e)){if(ue(e,new Set(["param"]),t,n),typeof e.param!="string"||!e.param)return b(n,`${t}.param`,"must be a parameter name string"),null;if(!Object.prototype.hasOwnProperty.call(r,e.param))return b(n,`${t}.param`,`unknown parameter "${e.param}"`),null;let o=r[e.param];return!W(o)||![o.value,o.min,o.max,o.step].every(jr)?(b(n,`${t}.param`,"referenced period parameter value min max and step must be positive integers"),null):{param:e.param}}return jr(e)?e:(b(n,t,"must be a positive integer or {param}"),null)}function Hr(e,t,r,n){return W(e)?(ue(e,new Set(["param"]),t,n),typeof e.param!="string"||!e.param?(b(n,`${t}.param`,"must be a parameter name string"),null):Object.prototype.hasOwnProperty.call(r,e.param)?{param:e.param}:(b(n,`${t}.param`,`unknown parameter "${e.param}"`),null)):q(e)?e:(b(n,t,"must be a finite number or {param}"),null)}function Ke(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 jo(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 s=e.get(n);if(s){for(let i of Ke(s))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 Ho(e,t){if(!W(e))return b(t,"parameters","must be a plain object"),null;let r=Object.keys(e);if(r.length>Rr)return b(t,"parameters",`too many parameters (max ${Rr})`),null;let n={};for(let o of r){if(!Cr.test(o)){b(t,`parameters.${o}`,"parameter name is malformed");continue}let s=e[o],i=`parameters.${o}`;if(!W(s)){b(t,i,"must be a plain object");continue}ue(s,Or,i,t);for(let c of Or)c in s||b(t,`${i}.${c}`,"required field is missing");let{value:a,min:l,max:u,step:d}=s;q(l)||b(t,`${i}.min`,"must be a finite number"),q(u)||b(t,`${i}.max`,"must be a finite number"),(!q(d)||d<=0)&&b(t,`${i}.step`,"must be a positive finite number"),q(a)||b(t,`${i}.value`,"must be a finite number"),q(l)&&q(u)&&l>u&&b(t,`${i}.min`,"min must be <= max"),q(a)&&q(l)&&q(u)&&q(d)&&d>0&&(Ur(a,l,u,d)||b(t,`${i}.value`,"value must lie on the declared min/max/step grid")),n[o]={value:a,min:l,max:u,step:d}}return n}function Co(e,t,r,n){let o=`nodes.${t}`;if(!W(e))return b(n,o,"must be a plain object"),null;if(typeof e.type!="string"||!Mr[e.type])return b(n,`${o}.type`,"unknown or missing node type"),ue(e,Fo,o,n),null;switch(ue(e,Mr[e.type],o,n),(typeof e.id!="string"||!qr.test(e.id))&&b(n,`${o}.id`,"must be a 1-64 char id starting with alphanumeric"),e.type){case"input":return(typeof e.field!="string"||!_o.has(e.field))&&b(n,`${o}.field`,"must be one of open|high|low|close|volume|fundingRate|openInterest|premium|oiDelta|bookImbalance"),{id:e.id,type:"input",field:e.field};case"constant":{let s=Hr(e.value,`${o}.value`,r,n);return{id:e.id,type:"constant",value:s}}case"indicator":{(typeof e.indicator!="string"||!vo.has(e.indicator))&&b(n,`${o}.indicator`,"must be one of sma|ema|rsi|macd|bollinger|atr");let s=e.indicator,i={id:e.id,type:"indicator",indicator:s};if(s==="atr"){"input"in e&&(typeof e.input!="string"||!e.input?b(n,`${o}.input`,"must be a node id string when provided"):i.input=e.input);let a=Nt(e.period,`${o}.period`,r,n);a!=null&&(i.period=a)}else typeof e.input!="string"||!e.input?b(n,`${o}.input`,"must be a node id string"):i.input=e.input;if((s==="sma"||s==="ema"||s==="rsi"||s==="bollinger"||s==="atr")&&("period"in e,s!=="macd"))if(!("period"in e))b(n,`${o}.period`,"required field is missing");else{let a=Nt(e.period,`${o}.period`,r,n);a!=null&&(i.period=a)}if(s==="macd"){for(let a of["fastPeriod","slowPeriod","signalPeriod"])if(!(a in e))b(n,`${o}.${a}`,"required field is missing");else{let l=Nt(e[a],`${o}.${a}`,r,n);l!=null&&(i[a]=l)}"output"in e?Ro.has(e.output)?i.output=e.output:b(n,`${o}.output`,"must be line|signal|histogram"):b(n,`${o}.output`,"required field is missing"),"period"in e&&b(n,`${o}.period`,"forbidden for macd"),"stdDev"in e&&b(n,`${o}.stdDev`,"forbidden for macd")}else if(s==="bollinger"){if(!("stdDev"in e))b(n,`${o}.stdDev`,"required field is missing");else{let a=Hr(e.stdDev,`${o}.stdDev`,r,n);a!=null&&(typeof a=="number"&&a<=0?b(n,`${o}.stdDev`,"must be > 0"):i.stdDev=a)}"output"in e?Lo.has(e.output)?i.output=e.output:b(n,`${o}.output`,"must be upper|middle|lower"):b(n,`${o}.output`,"required field is missing");for(let a of["fastPeriod","slowPeriod","signalPeriod"])a in e&&b(n,`${o}.${a}`,`forbidden for ${s}`)}else{"output"in e&&b(n,`${o}.output`,`forbidden for ${s}`),"stdDev"in e&&s!=="bollinger"&&b(n,`${o}.stdDev`,`forbidden for ${s}`);for(let a of["fastPeriod","slowPeriod","signalPeriod"])a in e&&b(n,`${o}.${a}`,`forbidden for ${s}`)}return i}case"compare":return(typeof e.op!="string"||!Oo.has(e.op))&&b(n,`${o}.op`,"must be gt|gte|lt|lte|eq"),(typeof e.left!="string"||!e.left)&&b(n,`${o}.left`,"must be a node id"),(typeof e.right!="string"||!e.right)&&b(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"||!No.has(e.op))&&b(n,`${o}.op`,"must be and|or|not"),!Array.isArray(e.inputs))return b(n,`${o}.inputs`,"must be an array of node ids"),{id:e.id,type:"logic",op:e.op,inputs:[]};let s=[];for(let i=0;i<e.inputs.length;i++){let a=e.inputs[i];typeof a!="string"||!a?b(n,`${o}.inputs.${i}`,"must be a node id"):s.push(a)}return e.op==="not"?s.length!==1&&b(n,`${o}.inputs`,"not requires exactly one input"):(e.op==="and"||e.op==="or")&&s.length<2&&b(n,`${o}.inputs`,`${e.op} requires at least two inputs`),{id:e.id,type:"logic",op:e.op,inputs:s}}case"cross":return(typeof e.direction!="string"||!Mo.has(e.direction))&&b(n,`${o}.direction`,"must be above|below"),(typeof e.left!="string"||!e.left)&&b(n,`${o}.left`,"must be a node id"),(typeof e.right!="string"||!e.right)&&b(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 qo(e,t,r){if(!W(e))return b(t,"risk","must be a plain object"),null;ue(e,Nr,"risk",t);for(let f of Nr)(!(f in e)||e[f]==null)&&b(t,`risk.${f}`,"required field is missing");let n={},o=e.maxLeverage;!q(o)||o<=0||o>50?b(t,"risk.maxLeverage","must be a number > 0 and <= 50"):n.maxLeverage=o;let s=e.maxNotionalUsd;!q(s)||s<=0?b(t,"risk.maxNotionalUsd","must be a number > 0"):n.maxNotionalUsd=s;let i=e.positionSizePct;!q(i)||i<=0||i>100?b(t,"risk.positionSizePct","must be a number > 0 and <= 100"):n.positionSizePct=i;let a=e.stopLossPct;!q(a)||a<=0||a>100?b(t,"risk.stopLossPct","must be a number > 0 and <= 100"):n.stopLossPct=a;let l=e.takeProfitPct;!q(l)||l<=0||l>1e3?b(t,"risk.takeProfitPct","must be a number > 0 and <= 1000"):n.takeProfitPct=l;let u=e.cooldownBars;!Number.isInteger(u)||u<0||u>1e5?b(t,"risk.cooldownBars","must be an integer >= 0 and <= 100000"):n.cooldownBars=u;let d=e.maxDailyLossPct;!q(d)||d<=0||d>100?b(t,"risk.maxDailyLossPct","must be a number > 0 and <= 100"):n.maxDailyLossPct=d;let c=e.expiresAt;return!Number.isInteger(c)||c<=0?b(t,"risk.expiresAt","must be an integer epoch milliseconds > 0"):(r.nowMs!==void 0&&(Number.isInteger(r.nowMs)?c<=r.nowMs&&b(t,"risk.expiresAt","must be strictly greater than nowMs"):b(t,"nowMs","must be an integer epoch milliseconds")),n.expiresAt=c),n}function Ye(e,t={}){let r=[];if(!W(e))return b(r,"","strategy must be a plain object"),{ok:!1,errors:r,strategy:null};ue(e,vr,"",r);for(let c of vr)(!(c in e)||e[c]==null)&&b(r,c,"required field is missing");e.version!==Je&&b(r,"version",`must be ${Je}`),(typeof e.id!="string"||!Cr.test(e.id))&&b(r,"id","must match /^[a-z0-9][a-z0-9._-]{0,63}$/"),(typeof e.name!="string"||e.name.length===0||e.name.length>Fr)&&b(r,"name",`must be a non-empty string max ${Fr}`);let n=ze(e.venue);n||b(r,"venue",`unknown strategy venue "${String(e.venue)}"`);let o=null;if(!n)W(e.market)||b(r,"market","must be a plain object");else{let c=n.validateMarket(e.market);if(!c||typeof c.ok!="boolean"||!Array.isArray(c.errors))b(r,"market",`venue ${n.id} returned an invalid market validation result`);else if(c.ok)o=c.market;else for(let f of c.errors)b(r,f.path,f.message)}let s=Ho(e.parameters,r),i=null,a=new Map;if(!Array.isArray(e.nodes))b(r,"nodes","must be an array");else if(e.nodes.length>Lr)b(r,"nodes",`too many nodes (max ${Lr})`);else{i=[];for(let c=0;c<e.nodes.length;c++){let f=Co(e.nodes[c],c,s||{},r);f&&(typeof f.id=="string"&&qr.test(f.id)&&(a.has(f.id)?b(r,`nodes.${c}.id`,`duplicate node id "${f.id}"`):a.set(f.id,f)),i.push(f))}for(let c=0;c<i.length;c++){let f=i[c],p=`nodes.${c}`;for(let h of Ke(f))a.has(h)||b(r,p,`unknown node ref "${h}"`);if(f.type==="indicator"||f.type==="compare"||f.type==="cross")for(let h of Ke(f)){let w=a.get(h);w&&vt.has(w.type)&&b(r,p,`node ref "${h}" must be numeric`)}if(f.type==="logic")for(let h of Ke(f)){let w=a.get(h);w&&!vt.has(w.type)&&b(r,p,`node ref "${h}" must be boolean`)}}jo(a)&&b(r,"nodes","graph contains a cycle")}let l=null;if(!W(e.rules))b(r,"rules","must be a plain object");else{ue(e.rules,Ot,"rules",r);for(let c of Ot)c in e.rules||b(r,`rules.${c}`,"required field is missing");l={};for(let c of Ot){let f=e.rules[c];if(f===null){l[c]=null;continue}if(typeof f!="string"||!f){b(r,`rules.${c}`,"must be a node id or null"),l[c]=f;continue}if(!a.has(f)){b(r,`rules.${c}`,`unknown node ref "${f}"`),l[c]=f;continue}let p=a.get(f);vt.has(p.type)||b(r,`rules.${c}`,`rule must reference a boolean node, not ${p.type}`),l[c]=f}}let u=qo(e.risk,r,t);if(r.length)return{ok:!1,errors:r,strategy:null};let d=Mt({version:Je,id:e.id,name:e.name,venue:n.id,market:o,parameters:s,nodes:i,rules:l,risk:u});return{ok:!0,errors:[],strategy:d}}function Y(e,t={}){let r=Ye(e,t);if(!r.ok)throw new he(r.errors);return r.strategy}function Dr(e){let t=Y(e);return JSON.stringify(Rt(t))}function pe(e){let t=Dr(e);return Io("sha256").update(t,"utf8").digest("hex")}function ge(e,t){if(!W(e))throw new he([{path:"",message:"strategy must be a plain object"}]);if(!W(t))throw new he([{path:"overrides",message:"must be a plain object"}]);let r=Y(e),n={};for(let[s,i]of Object.entries(r.parameters))n[s]={value:i.value,min:i.min,max:i.max,step:i.step};let o=[];for(let[s,i]of Object.entries(t)){if(!Object.prototype.hasOwnProperty.call(n,s)){b(o,s,`unknown parameter "${s}"`);continue}let a=n[s];if(!q(i)){b(o,s,"override must be a finite number");continue}if(!Ur(i,a.min,a.max,a.step)){b(o,s,"override must lie on the declared min/max/step grid");continue}n[s]={...a,value:i}}if(o.length)throw new he(o);return Y({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(s=>{let i={...s};return Array.isArray(s.inputs)&&(i.inputs=[...s.inputs]),i}),rules:{...r.rules},risk:{...r.risk}})}var Uo=50;function ne(e,t){let r=Number(e);if(!Number.isFinite(r))throw new TypeError(`${t} must be finite`);return r}function Br(e,t,r){if(!Array.isArray(e))throw new TypeError(`${r} must be an array`);let n=0;for(let o=0;o<e.length;o++){let s=ne(e[o]?.px,`${r}[${o}].px`),i=ne(e[o]?.sz,`${r}[${o}].sz`);if(i<0)throw new TypeError(`${r}[${o}].sz must be non-negative`);Math.abs((s-t)/t)*1e4<=Uo&&(n+=i)}return n}async function Do(e,t={}){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("sampleLiveSeries 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");if(!Number.isSafeInteger(e.nowMs)||e.nowMs<=0)throw new TypeError("nowMs is required integer epoch ms");let[n,o]=await Promise.all([dr(t),ur(r,t)]),s=n?.[0]?.universe,i=n?.[1];if(!Array.isArray(s)||!Array.isArray(i))throw new TypeError("metaAndAssetCtxs payload malformed");let a=s.findIndex(w=>w?.name===r);if(a<0)throw new Error(`unknown coin: ${r}`);let l=i[a];if(!l||typeof l!="object")throw new TypeError("asset ctx malformed");let u=ne(l.premium,"ctx.premium"),d=ne(l.openInterest,"ctx.openInterest");if(d<0)throw new TypeError("ctx.openInterest must be non-negative");let c=ne(l.midPx,"ctx.midPx"),f=o?.levels;if(!Array.isArray(f)||f.length!==2)throw new TypeError("l2Book levels malformed");let p=Br(f[0],c,"book.bids"),h=Br(f[1],c,"book.asks");if(p+h<=0)throw new TypeError("book depth near mid is empty");return Object.freeze({coin:r,t:e.nowMs,premium:u,openInterest:d,book:Object.freeze({bidDepth:p,askDepth:h})})}function Bo(e){if(!Array.isArray(e)||e.length===0)throw new TypeError("snapshots must be a non-empty array");let t=e[0]?.coin,r=[],n=null;for(let o=0;o<e.length;o++){let s=e[o];if(!s||typeof s!="object")throw new TypeError(`snapshots[${o}] must be an object`);if(s.coin!==t)throw new TypeError("snapshots must be a single coin");let i=ne(s.t,`snapshots[${o}].t`);if(n!=null&&!(i>n.t))throw new TypeError("snapshot times must be strictly increasing");let a=ne(s.premium,`snapshots[${o}].premium`),l=ne(s.openInterest,`snapshots[${o}].openInterest`),u=ne(s.book?.bidDepth,`snapshots[${o}].book.bidDepth`),d=ne(s.book?.askDepth,`snapshots[${o}].book.askDepth`),c=u+d;if(!(c>0))throw new TypeError(`snapshots[${o}] book depth must be positive`);r.push({coin:t,t:i,premium:a,openInterest:l,oiDelta:n==null?null:l-n.openInterest,bookImbalance:(u-d)/c}),n={t:i,openInterest:l}}return r}function zo(e,t,r){if(!Array.isArray(e))throw new TypeError("bars must be an array");if(!Array.isArray(t))throw new TypeError("rows must be an array");if(!Number.isSafeInteger(r)||r<=0)throw new TypeError("intervalMs must be a positive integer");let n=0;return e.map(o=>{let s=o.t+r,i=null;for(;n<t.length&&t[n].t<s;)t[n].t>=o.t&&(i=t[n]),n+=1;if(!i)return{...o};let a={...o};return i.premium!=null&&(a.premium=i.premium),i.openInterest!=null&&(a.openInterest=i.openInterest),i.oiDelta!=null&&(a.oiDelta=i.oiDelta),i.bookImbalance!=null&&(a.bookImbalance=i.bookImbalance),a})}import{createHash as Vo}from"node:crypto";var Ft=256,zr=new Set(["netPnlUsd","profitFactor","sharpe","maxDrawdownPct"]);function Vr(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 Jr(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function jt(e){if(e==null||typeof e!="object"||Object.isFrozen(e))return e;if(Array.isArray(e)){for(let t of e)jt(t);return Object.freeze(e)}for(let t of Object.keys(e))jt(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 Ge(e){return JSON.stringify(Le(e))}function Jo(e){let{min:t,max:r,step:n}=e;if(!(n>0)||t>r)return[];let o=[],s=Math.floor((r-t)/n+1e-9);for(let a=0;a<=s;a++){let l=t+a*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 a=(r-t)/n;Math.abs(a-Math.round(a))<=1e-9&&o.push(r)}return o}function Ko(e,t){if(e.length===0)return[];let r=[{}];for(let n of e){let o=t[n],s=[];for(let i of r)for(let a of o)s.push({...i,[n]:a});r=s}return r.sort((n,o)=>{let s=Ge(n),i=Ge(o);return s<i?-1:s>i?1:0}),r}function Lt(e,t,r,n,o){let s=0;if(e==="maxDrawdownPct"){if(s=t.maxDrawdownPct-n.maxDrawdownPct,s!==0)return s<0}else if(s=t[e]-n[e],s!==0)return s>0;let i=Ge(r),a=Ge(o);return i<a}function Ht(e,t,r={}){if(!Jr(r))throw new TypeError("options must be a plain object");for(let g of Object.keys(r))if(Vr(g))throw new TypeError(`options must not include holdout/test/oos key "${g}"`);let n=new Set(["maxTrials","objective","backtestOptions"]);for(let g of Object.keys(r))if(!n.has(g))throw new TypeError(`unknown option "${g}"`);let o=64;if("maxTrials"in r){let g=r.maxTrials;if(!Number.isInteger(g)||g<1||g>Ft)throw new TypeError(`maxTrials must be an integer 1..${Ft}`);o=g}let s=r.objective??"netPnlUsd";if(!zr.has(s))throw new TypeError(`objective must be one of ${[...zr].join("|")}`);let i=r.backtestOptions??{};if(!Jr(i))throw new TypeError("backtestOptions must be a plain object");for(let g of Object.keys(i))if(Vr(g))throw new TypeError(`backtestOptions must not include holdout/test/oos key "${g}"`);let a=Y(e),l=Object.keys(a.parameters).sort();if(l.length===0)throw new Error("optimizeStrategy requires at least one declared parameter");let u={},d=1;for(let g of l){let P=Jo(a.parameters[g]);if(P.length===0)throw new Error(`parameter "${g}" produces an empty grid`);u[g]=P,d*=P.length}let c=Ko(l,u);if(c.length===0)throw new Error("parameter grid is empty");let f=c.slice(0,o),p=[],h=null,w=null;for(let g of f){let P=ge(a,g),x=ie(P,t,i);w==null&&(w=x.config);let m={netPnlUsd:x.metrics.netPnlUsd,netPnlPct:x.metrics.netPnlPct,maxDrawdownPct:x.metrics.maxDrawdownPct,winRate:x.metrics.winRate,profitFactor:x.metrics.profitFactor,tradeCount:x.metrics.tradeCount,sharpe:x.metrics.sharpe,turnoverUsd:x.metrics.turnoverUsd},M={parameters:{...g},metrics:m};p.push(M),(!h||Lt(s,m,g,h.metrics,h.parameters))&&(h=M)}p.sort((g,P)=>Lt(s,g.metrics,g.parameters,P.metrics,P.parameters)?-1:Lt(s,P.metrics,P.parameters,g.metrics,g.parameters)?1:0);let k={...h.parameters},S=ge(a,k),I={strategyHash:pe(a),compilerHash:le,trainBarsHash:Oe(t),backtestConfig:w,objective:s,maxTrials:o,trialsRun:p.length,candidates:p,bestParameters:k,bestStrategy:S},_={id:Vo("sha256").update(JSON.stringify(Le(I)),"utf8").digest("hex"),...I};return jt(Le(JSON.parse(JSON.stringify(_))))}import{createHash as Yo}from"node:crypto";var V=class extends Error{constructor(t){super(t),this.name="StrategyDraftError"}},Go=new Set(["1m","3m","5m","15m","30m","1h","2h","4h","8h","12h","1d"]),Xo=new Set(["BTC","ETH","SOL","HYPE"]),Wo=/\b(mnemonic|private\s*key|privkey|seed\s*phrase|seed\b|api[_-]?key|secret\s*key|wallet\s*key|passphrase)\b/i,xe="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]; (4) open interest: <long|short> <COIN> when open interest <above|below> <non-negative number> [on <interval>] [, risk knobs]; (5) premium: <long|short> <COIN> when premium <above|below> <decimal|percent%> [on <interval>] [, risk knobs]; (6) oi delta: <long|short> <COIN> when oi delta <above|below> <number> [on <interval>] [, risk knobs]; (7) book imbalance: <long|short> <COIN> when book imbalance <above|below> <-1..1> [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.",Zo=Object.freeze({maxLeverage:1,maxNotionalUsd:100,positionSizePct:5,stopLossPct:2,takeProfitPct:4,cooldownBars:1,maxDailyLossPct:3}),Qo=36e5,es=30*864e5,ts=864e5;function rs(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function Ct(e){if(e==null||typeof e!="object"||Object.isFrozen(e))return e;if(Array.isArray(e)){for(let t of e)Ct(t);return Object.freeze(e)}for(let t of Object.keys(e))Ct(e[t]);return Object.freeze(e)}function ns(e){return String(e).trim().replace(/\s+/g," ")}function os(e){let t=e.match(/\b(long|short)\b/i);return t?t[1].toLowerCase():null}function ss(e){for(let r of Xo)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 is(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 Go.has(r)?r:null}function as(e){let t={...Zo},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 s=e.match(/position\s*size\s*(\d+(?:\.\d+)?)\s*%?/i);s&&(t.positionSizePct=Number(s[1]));let i=e.match(/max\s*notional\s*(?:usd\s*)?\$?\s*(\d+(?:\.\d+)?)/i);return i&&(t.maxNotionalUsd=Number(i[1])),t}function cs(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 ls(e){let t=Yo("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 us(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 s=/\b(exit\s+on\s+reverse|reverse\s+exit)\b/i.test(e);return{kind:"ema_cross",fast:r,slow:o,direction:n,reverse:s}}function fs(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 ds(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 ps(e){let t=e.match(/\bopen\s*interest\s*(above|below)\s*(-?\d+(?:\.\d+)?)(?=\s|,|$)/i);if(!t)return null;let r=Number(t[2]);return!Number.isFinite(r)||r<0?null:{kind:"open_interest",op:t[1].toLowerCase(),threshold:r}}function ms(e){let t=e.match(/\bpremium\s*(above|below)\s*(-?\d+(?:\.\d+)?)(%?)(?=\s|,|$)/i);if(!t)return null;let r=Number(t[2]);return Number.isFinite(r)?(t[3]==="%"&&(r=r/100),{kind:"premium",op:t[1].toLowerCase(),threshold:r}):null}function hs(e){let t=e.match(/\boi\s*delta\s*(above|below)\s*(-?\d+(?:\.\d+)?)(?=\s|,|$)/i);if(!t)return null;let r=Number(t[2]);return Number.isFinite(r)?{kind:"oi_delta",op:t[1].toLowerCase(),threshold:r}:null}function ys(e){let t=e.match(/\bbook\s*imbalance\s*(above|below)\s*(-?\d+(?:\.\d+)?)(?=\s|,|$)/i);if(!t)return null;let r=Number(t[2]);return!Number.isFinite(r)||r<-1||r>1?null:{kind:"book_imbalance",op:t[1].toLowerCase(),threshold:r}}function ws(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,""):t.kind==="open_interest"?r=r.replace(/^open\s*interest\s*(?:above|below)\s*-?\d+(?:\.\d+)?(?=\s|,|$)/i,""):t.kind==="premium"?r=r.replace(/^premium\s*(?:above|below)\s*-?\d+(?:\.\d+)?%?(?=\s|,|$)/i,""):t.kind==="oi_delta"?r=r.replace(/^oi\s*delta\s*(?:above|below)\s*-?\d+(?:\.\d+)?(?=\s|,|$)/i,""):t.kind==="book_imbalance"?r=r.replace(/^book\s*imbalance\s*(?:above|below)\s*-?\d+(?:\.\d+)?(?=\s|,|$)/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 Kr(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 gs({side:e,coin:t,interval:r,risk:n,expiresAt:o,id:s,name:i,spec:a}){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:a.direction,left:"emaLeft",right:"emaRight"}],u={entryLong:null,entryShort:null,exitLong:null,exitShort:null};if(e==="long"?u.entryLong="cross":u.entryShort="cross",a.reverse){let d=a.direction==="above"?"below":"above";l.push({id:"crossRev",type:"cross",direction:d,left:"emaLeft",right:"emaRight"}),e==="long"?u.exitLong="crossRev":u.exitShort="crossRev"}return{version:1,id:s,name:i,venue:"hyperliquid",market:{coin:t,interval:r},parameters:{ema_left_period:Kr(a.fast),ema_right_period:Kr(a.slow)},nodes:l,rules:u,risk:{...n,expiresAt:o}}}function bs({side:e,coin:t,interval:r,risk:n,expiresAt:o,id:s,name:i,spec:a}){let l=[{id:"c",type:"input",field:"close"},{id:"rsi",type:"indicator",indicator:"rsi",input:"c",period:a.period},{id:"thr",type:"constant",value:a.threshold},{id:"sig",type:"compare",op:a.op==="above"?"gt":"lt",left:"rsi",right:"thr"}];return{version:1,id:s,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 Es({side:e,coin:t,interval:r,risk:n,expiresAt:o,id:s,name:i,spec:a}){let l=[{id:"fr",type:"input",field:"fundingRate"},{id:"thr",type:"constant",value:a.threshold},{id:"sig",type:"compare",op:a.op==="above"?"gt":"lt",left:"fr",right:"thr"}];return{version:1,id:s,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 ks({side:e,coin:t,interval:r,risk:n,expiresAt:o,id:s,name:i,spec:a}){let l=[{id:"oi",type:"input",field:"openInterest"},{id:"thr",type:"constant",value:a.threshold},{id:"sig",type:"compare",op:a.op==="above"?"gt":"lt",left:"oi",right:"thr"}];return{version:1,id:s,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}}}var xs=Object.freeze({funding:"fundingRate",open_interest:"openInterest",premium:"premium",oi_delta:"oiDelta",book_imbalance:"bookImbalance"});function Ss({side:e,coin:t,interval:r,risk:n,expiresAt:o,id:s,name:i,spec:a}){let u=[{id:"sig_input",type:"input",field:xs[a.kind]},{id:"thr",type:"constant",value:a.threshold},{id:"sig",type:"compare",op:a.op==="above"?"gt":"lt",left:"sig_input",right:"thr"}];return{version:1,id:s,name:i,venue:"hyperliquid",market:{coin:t,interval:r},parameters:{},nodes:u,rules:{entryLong:e==="long"?"sig":null,entryShort:e==="short"?"sig":null,exitLong:null,exitShort:null},risk:{...n,expiresAt:o}}}function qt(e,t={}){if(typeof e!="string")throw new V("prompt must be a string");if(e.length>1e3)throw new V("prompt length must be <= 1000");if(!rs(t))throw new V("options must be a plain object");if(!Number.isInteger(t.nowMs))throw new V("options.nowMs is required integer epoch ms");let r=t.nowMs,n=ts;if("expiresInMs"in t){if(!Number.isInteger(t.expiresInMs))throw new V("expiresInMs must be an integer");if(n=t.expiresInMs,n<Qo||n>es)throw new V("expiresInMs must be between 1h and 30d")}if(Wo.test(e))throw new V(`prompt appears to contain secrets and is rejected. ${xe}`);let o=ns(e);if(!o)throw new V(`empty prompt. ${xe}`);if(cs(o))throw new V(`duplicate interval or risk clause. ${xe}`);let s=os(o),i=ss(o),a=is(o);if(!s||!i||!a)throw new V(`could not parse side/coin/interval. ${xe}`);let l=as(o);if(!(l.maxLeverage>0)||l.maxLeverage>50)throw new V("leverage out of range");if(!(l.positionSizePct>0)||l.positionSizePct>100)throw new V("position size out of range");let u=r+n,d=ls(o),c=`Draft ${i} ${s}`.slice(0,100),f=us(o),p=fs(o),h=ds(o),w=ps(o),k=ms(o),S=hs(o),I=ys(o),_=[f,p,h,w,k,S,I].filter(Boolean);if(_.length!==1)throw new V(`unsupported or ambiguous prompt. ${xe}`);if(!ws(o,_[0]))throw new V(`unsupported or ambiguous prompt. ${xe}`);let g,P=_[0],x={side:s,coin:i,interval:a,risk:l,expiresAt:u,id:d,name:c,spec:P};P.kind==="ema_cross"?g=gs(x):P.kind==="rsi"?g=bs(x):P.kind==="open_interest"?g=ks(x):P.kind==="funding"?g=Es(x):g=Ss(x);let m=Ye(g,{nowMs:r});if(!m.ok)throw new V(`draft failed validation: ${m.errors.map(M=>M.message).join("; ")}`);return Ct(Y(g,{nowMs:r}))}import ae from"node:fs";import Xe from"node:path";var Dt=1,As=["privatekey","secretkey","seed","mnemonic","passphrase","password","keystore","keymaterial","apikey","authtoken","accesstoken","refreshtoken","credential","bearer","signature","authorization","xprv","xpriv","wif"];function We(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function oe(e){return e==null?e:JSON.parse(JSON.stringify(e))}function $s(e){return String(e).toLowerCase().replace(/[^a-z0-9]/g,"")}function Se(e,t="record"){if(Array.isArray(e)){e.forEach((r,n)=>Se(r,`${t}[${n}]`));return}if(We(e))for(let[r,n]of Object.entries(e)){let o=$s(r);if(As.some(s=>o.includes(s)))throw new Error(`shadow-store: forbidden secret-like field at ${t}.${r}`);Se(n,`${t}.${r}`)}}function Ps(e){if(typeof e!="string"||!e||!Xe.isAbsolute(e))throw new Error("shadow-store: path must be an absolute path")}function Yr(e){let t;try{t=ae.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 Ts(){return{version:Dt,runners:[]}}function Gr(e,t){let r;try{r=JSON.parse(e)}catch{throw new Error("shadow-store: malformed JSON")}if(!We(r))throw new Error("shadow-store: malformed JSON root");if(r.version!==Dt)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 Se(r,Xe.basename(t)),{version:Dt,runners:r.runners.map(n=>oe(n))}}function Xr(e,t){Se(t,"store");let r=Xe.dirname(e);ae.mkdirSync(r,{recursive:!0,mode:448});let n=Xe.join(r,`.shadow-store.${process.pid}.${Date.now()}.tmp`),o=`${JSON.stringify(t)}
|
|
3
|
+
`;try{ae.writeFileSync(n,o,{mode:384,flag:"wx"}),ae.renameSync(n,e);try{ae.chmodSync(e,384)}catch{}}catch(s){try{ae.unlinkSync(n)}catch{}throw s}}var Ut=new Map;function Bt(e={}){let t=e.path;if(Ps(t),Yr(t),ae.existsSync(t)?Gr(ae.readFileSync(t,"utf8"),t):Xr(t,Ts()),Ut.has(t))return Ut.get(t);let r=!1,n=[];function o(){if(r)return;let h=n.shift();if(h){r=!0;try{let w=h.fn();r=!1,h.resolve(w),o()}catch(w){r=!1,h.reject(w),o()}}}function s(h){if(!r&&n.length===0){r=!0;try{return h()}finally{r=!1,queueMicrotask(o)}}return new Promise((w,k)=>{n.push({fn:h,resolve:w,reject:k}),queueMicrotask(o)})}function i(){return Yr(t),Gr(ae.readFileSync(t,"utf8"),t)}function a(h){Xr(t,h)}function l(h){if(!We(h)||typeof h.id!="string"||!h.id)throw new Error("shadow-store: create requires record with string id");Se(h,"record");let w=i();if(w.runners.some(S=>S.id===h.id))throw new Error(`shadow-store: runner id already exists: ${h.id}`);let k=oe(h);return w.runners.push(k),a(w),oe(k)}function u(h){let w=i().runners.find(k=>k.id===h);return w?oe(w):null}function d(){return i().runners.map(h=>oe(h))}function c(h,w){if(typeof w!="function")throw new Error("shadow-store: updater must be a function");let k=i(),S=k.runners.findIndex(g=>g.id===h);if(S<0)throw new Error(`shadow-store: runner not found: ${h}`);let I=oe(k.runners[S]),_=w(I);if(!We(_)||_.id!==h)throw new Error("shadow-store: updater must return record with same id");return Se(_,"record"),k.runners[S]=oe(_),a(k),oe(k.runners[S])}function f(h){let w=i(),k=w.runners.findIndex(I=>I.id===h);if(k<0)throw new Error(`shadow-store: runner not found: ${h}`);let S=oe(w.runners[k]);return S.status!=="stopped"&&(S.status="stopped",w.runners[k]=S,a(w)),oe(w.runners[k])}let p={create(h){return s(()=>l(h))},get(h){return u(h)},list(){return d()},update(h,w){return s(()=>c(h,w))},stop(h){return s(()=>f(h))}};return Ut.set(t,p),p}import{createHash as Jt}from"node:crypto";function zt(e){return e==null?e:JSON.parse(JSON.stringify(e))}function Vt(e){return Array.isArray(e)?e.map(Vt):e&&typeof e=="object"?Object.fromEntries(Object.keys(e).sort().map(t=>[t,Vt(e[t])])):e}function Zr(e){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("shadow-runner: record must be an object");return Jt("sha256").update(JSON.stringify(Vt(e))).digest("hex")}function Is(e,t,r,n,o){return Jt("sha256").update(`${e}|${t}|${r}|${n}|${o}`).digest("hex")}function _s(e,t,r,n){return Jt("sha256").update(`shadow|${e}|${t}|${r}|${n??""}`).digest("hex")}function vs(e){return e==="entryLong"||e==="exitShort"?"buy":e==="entryShort"||e==="exitLong"?"sell":e}function Wr(e){return e==="entryLong"||e==="entryShort"}function Ze({storePath:e,clock:t=Date.now}={}){if(typeof e!="string"||!e)throw new Error("shadow-runner: storePath required");let r=Bt({path:e});function n({strategy:l,evidenceId:u=null}={}){let d=K(l),c=u==null?null:String(u),f=r.list().filter(S=>S.status==="running"&&S.strategyHash===d.strategyHash&&S.compilerHash===d.compilerHash&&S.evidenceId===c).sort((S,I)=>S.createdAt-I.createdAt||S.id.localeCompare(I.id))[0];if(f)return zt(f);let p=t(),h=_s(p,d.strategyHash,d.compilerHash,c),w=r.get(h);if(w)return zt(w);let k={id:h,strategy:zt(d.strategy),strategyHash:d.strategyHash,compilerHash:d.compilerHash,evidenceId:c,status:"running",cursor:null,intendedOrders:[],fills:[],missedFills:[],markouts:[],createdAt:p,updatedAt:p,position:null,cooldownBarsRemaining:0,cooldownStartT:null,lastProcessedBarIndex:-1};return r.create(k)}function o(l){return r.get(l)}function s(){return r.list()}function i(l){return r.stop(l)}function a(l,u,{markoutHorizons:d=[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 p=K(c.strategy).evaluateAll(u),h=new Map;for(let y=0;y<u.length;y++)h.set(u[y].t,y);let w=c.cursor,k=[];for(let y=0;y<u.length;y++){let $=u[y].t;(w==null||$>w)&&k.push(y)}if(k.length===0)return c;let S=new Map(c.intendedOrders.map(y=>[y.id,y])),I=new Set(c.fills.map(y=>y.orderId)),_=new Map(c.missedFills.map(y=>[y.orderId,y])),g=(y,$)=>`${y}|${$}`,P=new Map(c.markouts.map(y=>[g(y.orderId,y.horizon),y])),x=c.position?{...c.position}:null,m=Number.isInteger(c.cooldownBarsRemaining)?Math.max(0,c.cooldownBarsRemaining):0,M=Number.isFinite(c.cooldownStartT)?c.cooldownStartT:null;function G({action:y,signalBarT:$,signalIndex:T}){let L=vs(y),j=Is(c.id,c.strategyHash,$,L,y);if(S.has(j))return S.get(j);let O=T+1,R=O<u.length,J={id:j,action:y,type:y,side:L,signalBarT:$,fillBarT:R?u[O].t:null,status:R?"open":"missed"};return S.set(j,J),c.intendedOrders.push(J),J}function U(y,$,T){if(I.has(y.id))return;let L={orderId:y.id,action:Wr(y.action)?"entry":"exit",side:y.side,price:$.o,barT:$.t,signalBarT:y.signalBarT,barIndex:T};if(c.fills.push(L),I.add(y.id),y.status="filled",y.fillBarT=$.t,_.has(y.id)&&(_.delete(y.id),c.missedFills=c.missedFills.filter(j=>j.orderId!==y.id)),Wr(y.action)){x={side:y.action==="entryLong"?"long":"short",entryOrderId:y.id,entryBarT:$.t,entryPrice:$.o,entryBarIndex:T};for(let j of d){let O=g(y.id,j);if(P.has(O))continue;let R={orderId:y.id,horizon:j,entryBarT:$.t,entryPrice:$.o,side:x.side,status:"pending",close:null,barT:null};P.set(O,R),c.markouts.push(R)}}else x=null,m=Number(c.strategy?.risk?.cooldownBars)||0,M=$.t}function z(y){if(I.has(y.id)||_.has(y.id))return;let $={orderId:y.id,action:y.action,side:y.side,signalBarT:y.signalBarT,status:"missed"};_.set(y.id,$),c.missedFills.push($),y.status="missed"}for(let y of c.intendedOrders){if(y.status==="filled"||I.has(y.id))continue;let $=h.get(y.signalBarT);if($==null)continue;let T=$+1;T<u.length&&(w==null||u[T].t>w)&&U(y,u[T],T)}for(let y of k){let $=u[y],T=p[y].signals,L=x,j=R=>{if(x||m>0&&(M==null||$.t>=M))return;let D=G({action:R,signalBarT:$.t,signalIndex:y}),Q=y+1;Q<u.length?U(D,u[Q],Q):z(D)},O=R=>{if(!x||x.side==="long"&&R!=="exitLong"||x.side==="short"&&R!=="exitShort")return;let J=G({action:R,signalBarT:$.t,signalIndex:y}),D=y+1;D<u.length?U(J,u[D],D):z(J)};L?(T.exitLong&&O("exitLong"),T.exitShort&&O("exitShort")):T.entryLong&&T.entryShort||(T.entryLong&&j("entryLong"),T.entryShort&&j("entryShort")),m>0&&M!=null&&$.t>=M&&(m-=1,m===0&&(M=null)),c.cursor=$.t,c.lastProcessedBarIndex=y}for(let y of c.markouts){if(y.status!=="pending")continue;let $=c.fills.find(j=>j.orderId===y.orderId&&j.action==="entry");if(!$)continue;let T=h.get($.barT);if(T==null)continue;let L=T+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=x,c.cooldownBarsRemaining=m,c.cooldownStartT=M,c.updatedAt=t(),c})}return{start:n,step:a,list:s,get:o,stop:i}}import Os from"node:os";import Ns from"node:path";var Ms=["privatekey","secretkey","seed","mnemonic","passphrase","password","keystore","keymaterial","apikey","authtoken","accesstoken","refreshtoken","credential","bearer","signature","authorization","xprv","xpriv","wif"];function Fe(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function Rs(e){return String(e).toLowerCase().replace(/[^a-z0-9]/g,"")}function Yt(e){if(Array.isArray(e)){for(let t of e)Yt(t);return}if(Fe(e))for(let[t,r]of Object.entries(e)){if(Ms.some(n=>Rs(t).includes(n)))throw new Error(`strategy service: secret-like field "${t}" is forbidden`);Yt(r)}}function Ls(e){if(!Fe(e))throw new TypeError("strategy input must be a plain object");return Yt(e),e}function Fs(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 Kt(e,t,r,n){if(Array.isArray(t.bars))return t.bars;let o=Ve(e.venue),s=r.fetchBars??o.fetchBars;if(typeof s!="function")throw new Error(`strategy venue ${o.id} does not support history`);r.signal?.throwIfAborted?.();let i=await s({coin:e.market.coin,interval:e.market.interval,count:t.count??1500,endTime:t.endTime??n},{signal:r.signal});r.signal?.throwIfAborted?.();let a=Array.isArray(i)?i:i?.bars;if(!Array.isArray(a))throw new Error("strategy history provider returned no bars");return a}function Gt(e,t){let r=e.backtestOptions??{};if(!Fe(r))throw new TypeError("backtestOptions must be a plain object");return{...r,nowMs:t}}function Qr(e,t,r,n,o={}){let s=e.evidenceOptions??{};if(!Fe(s))throw new TypeError("evidenceOptions must be a plain object");return{...s,...o,strategy:t,bars:r,backtestOptions:Gt(e,n)}}function en(){return Ns.join(Os.homedir(),".oracle","strategy-shadow.json")}function js(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 Hs(e,t={},r={}){r.signal?.throwIfAborted?.();let n=Ls(t),o=Fs(n,r);if(e==="draft")return{strategy:qt(n.prompt,{nowMs:o})};if(e==="validate"){let s=K(n.strategy);if(s.strategy.risk.expiresAt<=o)throw new Error("strategy is expired");return{valid:!0,strategy:s.strategy,strategyHash:s.strategyHash,compilerHash:s.compilerHash,compilerVersion:s.compilerVersion,requiredSeries:s.requiredSeries}}if(e==="backtest"||e==="evidence"){let s=K(n.strategy),i=await Kt(s.strategy,n,r,o);Ne(s,i);let a=Be(Qr(n,s.strategy,i,o));return e==="evidence"?a:{backtest:ie(s.strategy,i,Gt(n,o)),evidence:a}}if(e==="optimize"){let s=K(n.strategy),i=await Kt(s.strategy,n,r,o);Ne(s,i);let a=n.trainFraction,l=n.evidenceOptions?.trainFraction;if(a!=null&&l!=null&&a!==l)throw new TypeError("conflicting trainFraction controls are forbidden");let u=a??l??.7;if(typeof u!="number"||u<=0||u>=1)throw new TypeError("trainFraction must be in (0,1)");let d=i.slice(0,Math.floor(i.length*u)),c=n.options??{};if(!Fe(c))throw new TypeError("options must be a plain object");let f=Ht(s.strategy,d,{...c,...n.maxTrials==null?{}:{maxTrials:n.maxTrials},backtestOptions:Gt(n,o)}),p=f.bestStrategy;return{strategy:p,optimization:f,evidence:Be(Qr(n,p,i,o,{trainFraction:u}))}}if(e==="shadow"){let s=Ze({storePath:r.storePath??en(),clock:()=>o}),i=n.action;if(i==="start")return await s.start({strategy:n.strategy,evidenceId:n.evidenceId??n.evidence?.id??null});if(i==="list")return await s.list();if(i==="get")return await s.get(n.id);if(i==="stop")return await s.stop(n.id);if(i==="step"){let a=await s.get(n.id);if(!a)throw new Error(`shadow runner not found: ${n.id}`);let l=await Kt(a.strategy,n,r,o);return Ne(K(a.strategy),l),await s.step(n.id,l,n.stepOptions??{})}throw new Error(`unknown shadow action: ${i}`)}if(e==="prepare"){let s=K(n.strategy),i=Ve(s.strategy.venue);if(typeof n.shadowId!="string"||!n.shadowId)throw new Error("strategy prepare requires a matching shadow runner id");let l=await Ze({storePath:r.storePath??en(),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!==s.strategyHash||l.compilerHash!==s.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??js(s.strategy,o);return i.prepareIntent({strategy:s.strategy,evidence:n.evidence,shadow:{id:l.id,stateHash:Zr(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{kr as EVIDENCE_STATUSES,Ft as MAX_OPTIMIZER_TRIALS,le as STRATEGY_COMPILER_HASH,we as STRATEGY_COMPILER_VERSION,Je as STRATEGY_VERSION,V as StrategyDraftError,he as StrategyValidationError,ge as applyParameterOverrides,At as assertEvidenceArtifact,yt as atr,zo as attachDerivedSeries,ie as backtestStrategy,ht as bollinger,Dr as canonicalStrategyJson,K as compileStrategy,St as computeEvidenceArtifactId,Ze as createShadowRunner,Bo as deriveSeries,qt as draftStrategyFromPrompt,_e as ema,Be as evaluateEvidence,_t as fetchHyperliquidStrategyBars,Pr as intervalToMs,mt as macd,Tr as normalizeHyperliquidCandles,Y as normalizeStrategy,Bt as openShadowStore,Ht as optimizeStrategy,It as prepareStrategyLiveHandoff,Ve as requireStrategyVenue,ze as resolveStrategyVenue,pt as rsi,Hs as runStrategyOperation,Do as sampleLiveSeries,dt as sma,pe as strategyHash,To as strategyVenues,Ye as validateStrategy};
|
package/package.json
CHANGED