@oracle-agent/oracle 0.30.0 → 0.31.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 ko}from"node:crypto";import{createHash as cn}from"node:crypto";import ue from"node:net";import nn from"node:dns";var on=new Set(["localhost","metadata.google.internal","metadata.goog"]);function He(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("::"),a=r(n),i=r(o);if(!a||!i)return null;let s=t.includes("::"),l=8-a.length-i.length;if(!s&&l!==0||s&&l<1)return null;let u=[...a,...Array(Math.max(0,l)).fill(0),...i];return u.length!==8?null:Uint8Array.from(u.flatMap(d=>[d>>8,d&255]))}function rt(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 a=255<<8-o;return(e[n]&a)===(t[n]&a)}function nt(e){if(ue.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(ue.isIPv6(e)){let t=He(e);if(!t)return!1;let r=He("::ffff:0:0");return rt(t,r,96)?nt([...t.slice(12)].join(".")):rt(t,He("2000::"),3)?![["2001::",23],["2001:db8::",32],["2001:10::",28],["2001:2::",48],["2002::",16],["3fff::",20]].some(([o,a])=>rt(t,He(o),a)):!1}return!1}function sn(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(on.has(r)||r.endsWith(".localhost")||r.endsWith(".internal"))return{ok:!1,error:`refused internal host ${r}`};let n=ue.isIP(r);return n!==0&&!nt(r)?{ok:!1,error:`refused private address ${r}`}:{ok:!0,url:t,host:r,isLiteralIp:n!==0}}async function ot(e,{lookupFn:t=nn.promises.lookup}={}){let r=sn(e);if(!r.ok)return r;if(r.isLiteralIp)return{ok:!0,url:r.url,addresses:[{address:r.host,family:ue.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=>!nt(o.address))?{ok:!1,error:`refused: ${r.host} resolves to a non-public address`}:{ok:!0,url:r.url,addresses:n}}async function st({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(/\.+$/,""),a=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||(ue.isIPv6(f.address)?6:4)})),s=(c,f,p)=>{a.set(o(c),i(typeof f=="string"?[{address:f,family:p}]:f))},l=c=>{let f=o(c);if(ue.isIP(f))return[{address:f,family:ue.isIPv6(f)?6:4}];let p=a.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(
|
|
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 ko}from"node:crypto";import{createHash as cn}from"node:crypto";import ue from"node:net";import nn from"node:dns";var on=new Set(["localhost","metadata.google.internal","metadata.goog"]);function He(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("::"),a=r(n),i=r(o);if(!a||!i)return null;let s=t.includes("::"),l=8-a.length-i.length;if(!s&&l!==0||s&&l<1)return null;let u=[...a,...Array(Math.max(0,l)).fill(0),...i];return u.length!==8?null:Uint8Array.from(u.flatMap(d=>[d>>8,d&255]))}function rt(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 a=255<<8-o;return(e[n]&a)===(t[n]&a)}function nt(e){if(ue.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(ue.isIPv6(e)){let t=He(e);if(!t)return!1;let r=He("::ffff:0:0");return rt(t,r,96)?nt([...t.slice(12)].join(".")):rt(t,He("2000::"),3)?![["2001::",23],["2001:db8::",32],["2001:10::",28],["2001:2::",48],["2002::",16],["3fff::",20]].some(([o,a])=>rt(t,He(o),a)):!1}return!1}function sn(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(on.has(r)||r.endsWith(".localhost")||r.endsWith(".internal"))return{ok:!1,error:`refused internal host ${r}`};let n=ue.isIP(r);return n!==0&&!nt(r)?{ok:!1,error:`refused private address ${r}`}:{ok:!0,url:t,host:r,isLiteralIp:n!==0}}async function ot(e,{lookupFn:t=nn.promises.lookup}={}){let r=sn(e);if(!r.ok)return r;if(r.isLiteralIp)return{ok:!0,url:r.url,addresses:[{address:r.host,family:ue.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=>!nt(o.address))?{ok:!1,error:`refused: ${r.host} resolves to a non-public address`}:{ok:!0,url:r.url,addresses:n}}async function st({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(/\.+$/,""),a=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||(ue.isIPv6(f.address)?6:4)})),s=(c,f,p)=>{a.set(o(c),i(typeof f=="string"?[{address:f,family:p}]:f))},l=c=>{let f=o(c);if(ue.isIP(f))return[{address:f,family:ue.isIPv6(f)?6:4}];let p=a.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(g){return p(g)}return f?.all?p(null,h):p(null,h[0].address,h[0].family)}}}),d=an((c,f={})=>n(c,{...f,dispatcher:u}),s);return{dispatcher:u,fetch:d,pin:s,resolve:l,async close(){try{await u.destroy()}catch{}}}}var it=Symbol.for("oracle.egressGuard.pinCapableFetch");function an(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[it]=Object.freeze({pin:t}),e}function at(e){return typeof e=="function"&&typeof e[it]?.pin=="function"}function tr(e,t,r){if(!at(e))throw new Error("pinFetchToAddresses: fetchImpl is not pin-capable");e[it].pin(t,r)}var ln=new Set([408,425,429,500,502,503,504]),rr=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),un=2,nr=4e3,ar=["authorization","x-api-key","x-tensor-api-key","0x-api-key","api-key","cookie","proxy-authorization"],fn=new Set([301,302,303,307,308]),or=3,dn=64*1024;function pn(e){let t=String(e||"").toLowerCase();return ar.includes(t)||/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(t)}function mn(e){let t={};for(let[r,n]of Object.entries(e||{}))pn(r)||(t[r]=n);return t}function hn(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 yn(e,t){return new URL(String(e)).origin===new URL(String(t)).origin}var ct=new Map;function wn(e,t,r,n={}){let o={};for(let[d,c]of Object.entries(r||{}))o[d.toLowerCase()]=c;let a=Object.keys(o).filter(d=>/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(d)),s=[...new Set([...ar,...a])].sort().map(d=>`${d}=${o[d]??""}`).join(`
|
|
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),g=f?typeof AbortSignal.any=="function"?AbortSignal.any([f,p.signal]):f:p.signal,E=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:T=null}={})=>{let A=await ot(x,$);if(!A.ok)throw Pe(T==null?`HTTP refused ${x}: ${A.error}`:`HTTP redirect to ${x} ${A.error}`,T==null?{}:{status:T});let m=new URL(x).hostname;if(s){if(E&&(await E.close(),E=null),!E)try{E=await st({requireUndici:!0,...d?{importUndici:d}:{}})}catch(M){throw Pe(T==null?`HTTP refused ${x}: ${M?.message||M}`:`HTTP redirect to ${x} refused: ${M?.message||M}`,T==null?{}:{status:T})}E.pin(m,A.addresses),S=E.fetch}else tr(S,m,A.addresses);return A};try{let x=String(e),T={...n||{}};l&&await I(x);for(let A=0;A<=or;A+=1){let m=await S(x,{method:r,headers:T,body:o,signal:g,redirect:"manual"});if(fn.has(m.status)){if(r!=="GET"&&r!=="HEAD"){let P=await sr(m,u??dn,{url:x,truncate:!0}),_=new Error(`HTTP ${m.status} ${r} ${x} redirected non-idempotent request`);throw _.status=m.status,_.body=ir(P)??P.slice(0,300),_}if(A===or)throw $e(m),new Error(`HTTP redirect loop for ${e}`);let U=m.headers?.get?.("location"),z;try{z=hn(U,x)}catch(P){throw $e(m),P}let y=!yn(z,x);if($e(m),y&&(T=mn(T)),l)await I(z,{status:m.status});else if(y){let P=await ot(z,$);if(!P.ok){let _=new Error(`HTTP redirect from ${x} ${P.error}`);throw _.status=m.status,_.retryable=!1,_}s&&P.addresses?.length&&(E||(E=await st(d?{importUndici:d}:{})),E&&(E.pin(new URL(z).hostname,P.addresses),S=E.fetch))}x=z;continue}if(typeof c=="function")try{await c(m,{url:x})}catch(U){throw $e(m),Pe(U?.message||String(U))}let M=await sr(m,u,{url:x,onOversize:()=>p.abort()}),G=ir(M);if(!m.ok){let U=new Error(`HTTP ${m.status} ${r} ${x}`);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),E&&await E.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),g=Number.isFinite(h)&&h>0?Math.floor(h):null,E=async()=>{let T;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:g,importUndici:c,validateResponse:f,signal:p})}catch(m){T=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)||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,_)=>{let L=setTimeout(P,y);p.addEventListener("abort",()=>{clearTimeout(L),_(p.reason||new DOMException("Aborted","AbortError"))},{once:!0})}):await bn(y)}}throw T};if(!(t.dedupe!==!1&&!p&&o==="GET"&&i==null))return E();let $=wn(o,e,a,{untrustedUrl:d,maxResponseBytes:g}),I=ct.get($);if(I)return I;let x=E().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 Ie(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){Ie(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){Ie(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){Ie(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={}){Ie(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 g=0;g<o;g++)c+=s[d[g]];let f=c/o,p=d[o-1];l[p]=f,u[p]=s[p]-f;let h=2/(o+1);for(let g=o;g<d.length;g++){let E=d[g];f=h*s[E]+(1-h)*f,l[E]=f,u[E]=s[E]-f}}return{line:s,signal:l,histogram:u}}function mt(e,t={}){Ie(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",In="68f5b412a9975f04024cf9b9b6209b4bccedd52f176e95f34f786b3f53479c6a",_n="f197a38ff1c0f4ebe13326db8cbb8167ea3dd5d62e6033fe97c2fee8d23d96b5",pr=$n("sha256").update(JSON.stringify({version:yt,compilerSourceHash:Tn,indicatorsSourceHash:In,schemaSourceHash:_n})).digest("hex");var ye=yt,ce=pr,vn=Object.freeze({open:"o",high:"h",low:"l",close:"c",volume:"v",fundingRate:"fundingRate",openInterest:"openInterest"}),On=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!==On[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=vn[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 g={};for(let S of o){let $=p.get(S);g[S]=$[h]}let E=S=>S!=null&&g[S]===!0;return{values:g,signals:{entryLong:E(r.rules.entryLong),entryShort:E(r.rules.entryShort),exitLong:E(r.rules.exitLong),exitShort:E(r.rules.exitShort)}}}function d(p,h){Mn(p,h,r.market.interval);let g=new Map;for(let E of o)fe(E,n,a,p,h,g);return g}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,g=d(p,h);return Object.freeze(p.map((E,S)=>Object.freeze(u(g,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 _e(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 qe(e){return e/1e4}function Hn(e,t,r){let n=qe(r);return t==="long"?e*(1+n):e*(1-n)}function Cn(e,t,r){let n=qe(r);return t==="long"?e*(1-n):e*(1+n)}function mr(e,t,r){let n=Math.abs(e)*qe(t),o=Math.abs(e)*qe(r);return{taker:n,builder:o,total:n+o}}function qn(e,t){let r=e*(t.positionSizePct/100)*t.maxLeverage;return Math.min(r,t.maxNotionalUsd)}function Un(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 ve(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=_e(t);n.nowMs!==void 0&&Y(e,{nowMs:n.nowMs});let a=K(e);if(ve(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,g=0,E=0,S=0,$=[],I=[],x=[],T=[],A=[],m=null,M=0,G=null,U=f,z=!1,y=0,P=0,_=[],L=new Array(t.length).fill(0);function j(b){_.push(b)}function O(b){let v=t[b].v*(n.maxVolumeParticipationPct/100);return Math.max(0,v-L[b])}function R(b){if(!m)return f;let v=m.side==="long"?(b-m.entryPrice)*m.qty:(m.entryPrice-b)*m.qty;return f+v}function J(b,v,k){let H=k.o,N=qn(f,i);if(!(N>0)||!(H>0))return;let C=Hn(H,v,u),F=N/C,D=O(b),ke=C*D;if(F>D){x.push({kind:"entry",barIndex:b,time:k.t,side:v,requestedNotionalUsd:N,maxFillNotionalUsd:ke,reason:"volume_participation"});return}L[b]+=F;let ee=Math.abs(C-H)*F,oe=mr(N,d,c);f-=oe.total,p+=oe.taker,h+=oe.builder,E+=ee,S+=N,m={lifecycleEpoch:++P,side:v,entryBarIndex:b,entryReferencePrice:H,entryPrice:C,qty:F,notionalUsd:N,stop:Un(C,v,i.stopLossPct),take:Bn(C,v,i.takeProfitPct),liq:Dn(C,v,i.maxLeverage,d+c),entryFees:oe.taker,entryBuilderFees:oe.builder,entrySlippageUsd:ee,fundingAccrued:0}}function B(b,v,k,H){if(!m)return!1;let N=m.side,C=v,F=C;k!=="liquidation"&&H&&(F=Cn(C,N,u));let D=m.qty,ke=D*F;if(k!=="liquidation"){let er=O(b),rn=F*er;if(D>er)return x.push({kind:"exit",barIndex:b,time:t[b].t,side:N,requestedNotionalUsd:ke,maxFillNotionalUsd:rn,reason:"volume_participation",triggerReason:k}),!1;L[b]+=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,E+=oe,S+=ke;let tn={side:N,entryBarIndex:m.entryBarIndex,entryTime:t[m.entryBarIndex].t,entryPrice:m.entryPrice,exitBarIndex:b,exitTime:t[b].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:b,time:t[b].t,side:N,price:F,tradeIndex:$.length-1}),m=null,P+=1,y=b+1+(i.cooldownBars||0),!0}function Q(b,v,k,H){let N=b+1;if(N>=t.length)return;_.some(F=>F.kind==="exit"&&F.side===v&&F.fillBar===N&&F.epoch===H)||j({kind:"exit",side:v,signalBar:b,fillBar:N,reason:k,epoch:H})}function Le(b){let v=_.filter(k=>k.fillBar===b);for(let k=_.length-1;k>=0;k--)_[k].fillBar===b&&_.splice(k,1);v.sort((k,H)=>{let N=C=>C.kind==="exit"?0:1;return N(k)-N(H)});for(let k of v)if(k.kind==="exit"){if(!m||m.side!==k.side||m.lifecycleEpoch!==k.epoch)continue;let H=k.reason||"rule";B(b,t[b].o,H,!0)||Q(b,k.side,H,k.epoch)}else if(k.kind==="entry"){if(m||k.epoch!==P||b<y)continue;J(b,k.side,t[b])}}function Fe(b){if(!m)return;let v=t[b],k=v.fundingPaymentRate;if(k==null||!te(k)||k===0)return;let H=Math.abs(m.qty*v.c),N=k*H;m.side==="long"?(f-=N,m.fundingAccrued+=N,g+=N):(f+=N,m.fundingAccrued-=N,g-=N)}function je(b){if(!m)return;let v=t[b].o;(m.side==="long"?v<=m.liq:v>=m.liq)&&B(b,v,"liquidation",!1)}function Gt(b){if(!m)return;let v=t[b],k=m.side,H=Jn(v,k,m.liq),N=zn(v,k,m.stop),C=Vn(v,k,m.take),F=D=>k==="long"?Math.min(D,v.o):Math.max(D,v.o);if(H){B(b,F(m.liq),"liquidation",!1);return}if(N&&C){B(b,F(m.stop),"stop_loss",!0)||Q(b,k,"stop_loss",m.lifecycleEpoch);return}if(N){B(b,F(m.stop),"stop_loss",!0)||Q(b,k,"stop_loss",m.lifecycleEpoch);return}C&&(B(b,m.take,"take_profit",!0)||Q(b,k,"take_profit",m.lifecycleEpoch))}for(let b=0;b<t.length;b++){let v=Math.floor(t[b].t/864e5);v!==G&&(G=v,U=R(t[b].o),z=!1),je(b),Le(b),Gt(b),Fe(b),!z&&R(t[b].c)<=U*(1-i.maxDailyLossPct/100)&&(z=!0,T.push({type:"daily_loss_limit",barIndex:b,time:t[b].t,message:"daily loss limit reached; new entries blocked for UTC day"}));let k=s[b].signals,H=b+l;if(m)(m.side==="long"&&k.exitLong===!0||m.side==="short"&&k.exitShort===!0)&&H<t.length&&(_.some(D=>D.kind==="exit"&&D.side===m.side&&D.fillBar===H&&D.epoch===m.lifecycleEpoch)||j({kind:"exit",side:m.side,signalBar:b,fillBar:H,reason:"rule",epoch:m.lifecycleEpoch}));else{let C=k.entryLong===!0,F=k.entryShort===!0;C&&F?T.push({type:"conflicting_entry_signals",barIndex:b,time:t[b].t,message:"conflicting entry signals; no position opened"}):!z&&(C||F)&&H<t.length&&b>=y&&j({kind:"entry",side:C?"long":"short",signalBar:b,fillBar:H,epoch:P})}let N=f;m&&(M+=1,N=R(t[b].c)),A.push({barIndex:b,time:t[b].t,equity:N,positionSide:m?m.side:null})}let Xt=null;if(m){let b=t.length-1;if(B(b,t[b].c,"end_of_data",!0))A[b]={barIndex:b,time:t[b].t,equity:f,positionSide:null};else{let k=R(t[b].c);Xt={side:m.side,entryBarIndex:m.entryBarIndex,entryTime:t[m.entryBarIndex].t,entryPrice:m.entryPrice,qty:m.qty,notionalUsd:m.notionalUsd,markPrice:t[b].c,markedEquityUsd:k},T.push({type:"open_position_at_end",barIndex:b,time:t[b].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 b of $)b.netPnlUsd>0?(Wt+=1,Ze+=b.netPnlUsd):b.netPnlUsd<0&&(We+=-b.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:g,slippageUsd:E},liquidations:I,missedFills:x,openPositionAtEnd:Xt,flags:T};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 g=0;g<c.length;g++){let E=c[g];if(!re(E)||E.index!==g||typeof E.passed!="boolean")throw new Error("walk-forward windows must be ordered and structurally valid");let S=W(E.trainStartIndex,`walkForward.windows[${g}].trainStartIndex`),$=W(E.trainEndIndex,`walkForward.windows[${g}].trainEndIndex`),I=W(E.evalStartIndex,`walkForward.windows[${g}].evalStartIndex`),x=W(E.evalEndIndex,`walkForward.windows[${g}].evalEndIndex`);if(S!==0||$>=I||I>x||I<=p)throw new Error("walk-forward windows must be chronological and disjoint");if(p=x,E.passed){if(f+=1,E.reason!=="pass")throw new Error("passed walk-forward window reason must be pass");let T=Et({metrics:E.metrics,tradeCount:E.metrics?.tradeCount},`walkForward.windows[${g}]`);if(T.tradeCount<1||T.netPnlUsd<=0||T.profitFactor<=1)throw new Error("passed walk-forward window metrics do not pass");if(ge(t)&&T.maxDrawdownPct>t)throw new Error("passed walk-forward drawdown exceeds strategy risk")}else if(E.reason==="pass")throw new Error("failed walk-forward window cannot have pass reason")}let 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 Ue({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=_e(t),d=t.length,c=(O=[],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,...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 g=t.slice(0,f),E=t.slice(p),S,$;try{S=se(s,g,r),$=se(s,E,r)}catch(O){return c([{type:"backtest_error",message:String(O.message||O)}])}let I={metrics:bt(S),costs:yr(S),tradeCount:S.metrics.tradeCount},x={metrics:bt($),costs:yr($),tradeCount:$.metrics.tradeCount},T={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 O=0;O<o;O++){let R=m*(O+1),J=R,B=Math.min(d,J+m);if(B-J<3||R<3){A.push({index:O,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:O,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:O,trainStartIndex:0,trainEndIndex:R-1,evalStartIndex:J,evalEndIndex:B-1,passed:je,reason:je?"pass":"fail_metrics",metrics:Fe})}let M=A.filter(O=>O.passed).length,G=A.length===0?0:M/A.length,U={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(O=>["insufficient_bars","invalid_windowing","absent_oos_trades","holdout_loss","no_trades","severe_oos_collapse","backtest_error"].includes(O.type)),_=i.some(O=>O.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)&&!_&&!i.some(O=>O.type==="severe_oos_collapse"||O.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"})):_&&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:T,train:I,holdout:x,walkForward:U,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 Zs}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),g=h?ao(p,h):void 0,E={...f,prepareHash:p};return g&&(E.prepareMac=g),E}var co=["privatekey","secretkey","seed","mnemonic","passphrase","password","keystore","keymaterial","apikey","authtoken","accesstoken","refreshtoken","credential","bearer","signature","authorization","xprv","xpriv","wif"];function Oe(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(Oe(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"),!Oe(e))throw new Error("handoff: strategy required");if(!Oe(t))throw new Error("handoff: evidence required");if(!Oe(r))throw new Error("handoff: shadow required");if(!Oe(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 It(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:It,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"]),Io=new Set(["above","below"]),_o=new Set(["line","signal","histogram"]),vo=new Set(["upper","middle","lower"]),_t=new Set(["compare","logic","cross"]),Tr=new Set(["version","id","name","venue","market","parameters","nodes","rules","risk"]),Ir=new Set(["value","min","max","step"]),vt=new Set(["entryLong","entryShort","exitLong","exitShort"]),_r=new Set(["maxLeverage","maxNotionalUsd","positionSizePct","stopLossPct","takeProfitPct","cooldownBars","maxDailyLossPct","expiresAt"]),Oo=new Set(["id","type"]),vr={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"])},Or=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 q(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 w(e,t,r){e.push({path:t,message:r})}function le(e,t,r,n){for(let o of Object.keys(e))t.has(o)||w(n,r?`${r}.${o}`:o,"unknown field is not allowed")}function Hr(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 a=Math.round(o);return Math.abs(o-a)<=1e-9}function Ot(e,t,r,n){if(X(e)){if(le(e,new Set(["param"]),t,n),typeof e.param!="string"||!e.param)return w(n,`${t}.param`,"must be a parameter name string"),null;if(!Object.prototype.hasOwnProperty.call(r,e.param))return w(n,`${t}.param`,`unknown parameter "${e.param}"`),null;let o=r[e.param];return!X(o)||![o.value,o.min,o.max,o.step].every(Rr)?(w(n,`${t}.param`,"referenced period parameter value min max and step must be positive integers"),null):{param:e.param}}return Rr(e)?e:(w(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?(w(n,`${t}.param`,"must be a parameter name string"),null):Object.prototype.hasOwnProperty.call(r,e.param)?{param:e.param}:(w(n,`${t}.param`,`unknown parameter "${e.param}"`),null)):q(e)?e:(w(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 w(t,"parameters","must be a plain object"),null;let r=Object.keys(e);if(r.length>Or)return w(t,"parameters",`too many parameters (max ${Or})`),null;let n={};for(let o of r){if(!Fr.test(o)){w(t,`parameters.${o}`,"parameter name is malformed");continue}let a=e[o],i=`parameters.${o}`;if(!X(a)){w(t,i,"must be a plain object");continue}le(a,Ir,i,t);for(let c of Ir)c in a||w(t,`${i}.${c}`,"required field is missing");let{value:s,min:l,max:u,step:d}=a;q(l)||w(t,`${i}.min`,"must be a finite number"),q(u)||w(t,`${i}.max`,"must be a finite number"),(!q(d)||d<=0)&&w(t,`${i}.step`,"must be a positive finite number"),q(s)||w(t,`${i}.value`,"must be a finite number"),q(l)&&q(u)&&l>u&&w(t,`${i}.min`,"min must be <= max"),q(s)&&q(l)&&q(u)&&q(d)&&d>0&&(Hr(s,l,u,d)||w(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 w(n,o,"must be a plain object"),null;if(typeof e.type!="string"||!vr[e.type])return w(n,`${o}.type`,"unknown or missing node type"),le(e,Oo,o,n),null;switch(le(e,vr[e.type],o,n),(typeof e.id!="string"||!jr.test(e.id))&&w(n,`${o}.id`,"must be a 1-64 char id starting with alphanumeric"),e.type){case"input":return(typeof e.field!="string"||!Ao.has(e.field))&&w(n,`${o}.field`,"must be one of open|high|low|close|volume|fundingRate|openInterest"),{id:e.id,type:"input",field:e.field};case"constant":{let a=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))&&w(n,`${o}.indicator`,"must be one of sma|ema|rsi|macd|bollinger|atr");let a=e.indicator,i={id:e.id,type:"indicator",indicator:a};if(a==="atr"){"input"in e&&(typeof e.input!="string"||!e.input?w(n,`${o}.input`,"must be a node id string when provided"):i.input=e.input);let s=Ot(e.period,`${o}.period`,r,n);s!=null&&(i.period=s)}else typeof e.input!="string"||!e.input?w(n,`${o}.input`,"must be a node id string"):i.input=e.input;if((a==="sma"||a==="ema"||a==="rsi"||a==="bollinger"||a==="atr")&&("period"in e,a!=="macd"))if(!("period"in e))w(n,`${o}.period`,"required field is missing");else{let s=Ot(e.period,`${o}.period`,r,n);s!=null&&(i.period=s)}if(a==="macd"){for(let s of["fastPeriod","slowPeriod","signalPeriod"])if(!(s in e))w(n,`${o}.${s}`,"required field is missing");else{let l=Ot(e[s],`${o}.${s}`,r,n);l!=null&&(i[s]=l)}"output"in e?_o.has(e.output)?i.output=e.output:w(n,`${o}.output`,"must be line|signal|histogram"):w(n,`${o}.output`,"required field is missing"),"period"in e&&w(n,`${o}.period`,"forbidden for macd"),"stdDev"in e&&w(n,`${o}.stdDev`,"forbidden for macd")}else if(a==="bollinger"){if(!("stdDev"in e))w(n,`${o}.stdDev`,"required field is missing");else{let s=Lr(e.stdDev,`${o}.stdDev`,r,n);s!=null&&(typeof s=="number"&&s<=0?w(n,`${o}.stdDev`,"must be > 0"):i.stdDev=s)}"output"in e?vo.has(e.output)?i.output=e.output:w(n,`${o}.output`,"must be upper|middle|lower"):w(n,`${o}.output`,"required field is missing");for(let s of["fastPeriod","slowPeriod","signalPeriod"])s in e&&w(n,`${o}.${s}`,`forbidden for ${a}`)}else{"output"in e&&w(n,`${o}.output`,`forbidden for ${a}`),"stdDev"in e&&a!=="bollinger"&&w(n,`${o}.stdDev`,`forbidden for ${a}`);for(let s of["fastPeriod","slowPeriod","signalPeriod"])s in e&&w(n,`${o}.${s}`,`forbidden for ${a}`)}return i}case"compare":return(typeof e.op!="string"||!$o.has(e.op))&&w(n,`${o}.op`,"must be gt|gte|lt|lte|eq"),(typeof e.left!="string"||!e.left)&&w(n,`${o}.left`,"must be a node id"),(typeof e.right!="string"||!e.right)&&w(n,`${o}.right`,"must be a node id"),{id:e.id,type:"compare",op:e.op,left:e.left,right:e.right};case"logic":{if((typeof e.op!="string"||!To.has(e.op))&&w(n,`${o}.op`,"must be and|or|not"),!Array.isArray(e.inputs))return w(n,`${o}.inputs`,"must be an array of node ids"),{id:e.id,type:"logic",op:e.op,inputs:[]};let a=[];for(let i=0;i<e.inputs.length;i++){let s=e.inputs[i];typeof s!="string"||!s?w(n,`${o}.inputs.${i}`,"must be a node id"):a.push(s)}return e.op==="not"?a.length!==1&&w(n,`${o}.inputs`,"not requires exactly one input"):(e.op==="and"||e.op==="or")&&a.length<2&&w(n,`${o}.inputs`,`${e.op} requires at least two inputs`),{id:e.id,type:"logic",op:e.op,inputs:a}}case"cross":return(typeof e.direction!="string"||!Io.has(e.direction))&&w(n,`${o}.direction`,"must be above|below"),(typeof e.left!="string"||!e.left)&&w(n,`${o}.left`,"must be a node id"),(typeof e.right!="string"||!e.right)&&w(n,`${o}.right`,"must be a node id"),{id:e.id,type:"cross",direction:e.direction,left:e.left,right:e.right};default:return null}}function Lo(e,t,r){if(!X(e))return w(t,"risk","must be a plain object"),null;le(e,_r,"risk",t);for(let f of _r)(!(f in e)||e[f]==null)&&w(t,`risk.${f}`,"required field is missing");let n={},o=e.maxLeverage;!q(o)||o<=0||o>50?w(t,"risk.maxLeverage","must be a number > 0 and <= 50"):n.maxLeverage=o;let a=e.maxNotionalUsd;!q(a)||a<=0?w(t,"risk.maxNotionalUsd","must be a number > 0"):n.maxNotionalUsd=a;let i=e.positionSizePct;!q(i)||i<=0||i>100?w(t,"risk.positionSizePct","must be a number > 0 and <= 100"):n.positionSizePct=i;let s=e.stopLossPct;!q(s)||s<=0||s>100?w(t,"risk.stopLossPct","must be a number > 0 and <= 100"):n.stopLossPct=s;let l=e.takeProfitPct;!q(l)||l<=0||l>1e3?w(t,"risk.takeProfitPct","must be a number > 0 and <= 1000"):n.takeProfitPct=l;let u=e.cooldownBars;!Number.isInteger(u)||u<0||u>1e5?w(t,"risk.cooldownBars","must be an integer >= 0 and <= 100000"):n.cooldownBars=u;let d=e.maxDailyLossPct;!q(d)||d<=0||d>100?w(t,"risk.maxDailyLossPct","must be a number > 0 and <= 100"):n.maxDailyLossPct=d;let c=e.expiresAt;return!Number.isInteger(c)||c<=0?w(t,"risk.expiresAt","must be an integer epoch milliseconds > 0"):(r.nowMs!==void 0&&(Number.isInteger(r.nowMs)?c<=r.nowMs&&w(t,"risk.expiresAt","must be strictly greater than nowMs"):w(t,"nowMs","must be an integer epoch milliseconds")),n.expiresAt=c),n}function Je(e,t={}){let r=[];if(!X(e))return w(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)&&w(r,c,"required field is missing");e.version!==ze&&w(r,"version",`must be ${ze}`),(typeof e.id!="string"||!Fr.test(e.id))&&w(r,"id","must match /^[a-z0-9][a-z0-9._-]{0,63}$/"),(typeof e.name!="string"||e.name.length===0||e.name.length>Mr)&&w(r,"name",`must be a non-empty string max ${Mr}`);let n=Be(e.venue);n||w(r,"venue",`unknown strategy venue "${String(e.venue)}"`);let o=null;if(!n)X(e.market)||w(r,"market","must be a plain object");else{let c=n.validateMarket(e.market);if(!c||typeof c.ok!="boolean"||!Array.isArray(c.errors))w(r,"market",`venue ${n.id} returned an invalid market validation result`);else if(c.ok)o=c.market;else for(let f of c.errors)w(r,f.path,f.message)}let a=Mo(e.parameters,r),i=null,s=new Map;if(!Array.isArray(e.nodes))w(r,"nodes","must be an array");else if(e.nodes.length>Nr)w(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)?w(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)||w(r,p,`unknown node ref "${h}"`);if(f.type==="indicator"||f.type==="compare"||f.type==="cross")for(let h of Ve(f)){let g=s.get(h);g&&_t.has(g.type)&&w(r,p,`node ref "${h}" must be numeric`)}if(f.type==="logic")for(let h of Ve(f)){let g=s.get(h);g&&!_t.has(g.type)&&w(r,p,`node ref "${h}" must be boolean`)}}No(s)&&w(r,"nodes","graph contains a cycle")}let l=null;if(!X(e.rules))w(r,"rules","must be a plain object");else{le(e.rules,vt,"rules",r);for(let c of vt)c in e.rules||w(r,`rules.${c}`,"required field is missing");l={};for(let c of vt){let f=e.rules[c];if(f===null){l[c]=null;continue}if(typeof f!="string"||!f){w(r,`rules.${c}`,"must be a node id or null"),l[c]=f;continue}if(!s.has(f)){w(r,`rules.${c}`,`unknown node ref "${f}"`),l[c]=f;continue}let p=s.get(f);_t.has(p.type)||w(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)){w(o,a,`unknown parameter "${a}"`);continue}let s=n[a];if(!q(i)){w(o,a,"override must be a finite number");continue}if(!Hr(i,s.min,s.max,s.step)){w(o,a,"override must lie on the declared min/max/step grid");continue}n[a]={...s,value:i}}if(o.length)throw new 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,qr=new Set(["netPnlUsd","profitFactor","sharpe","maxDrawdownPct"]);function Ur(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(Ur(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(!qr.has(a))throw new TypeError(`objective must be one of ${[...qr].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(Ur(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 T=jo(s.parameters[x]);if(T.length===0)throw new Error(`parameter "${x}" produces an empty grid`);u[x]=T,d*=T.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,g=null;for(let x of f){let T=we(s,x),A=se(T,t,i);g==null&&(g=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,T)=>Rt(a,x.metrics,x.parameters,T.metrics,T.parameters)?-1:Rt(a,T.metrics,T.parameters,x.metrics,x.parameters)?1:0);let E={...h.parameters},S=we(s,E),$={strategyHash:de(s),compilerHash:ce,trainBarsHash:_e(t),backtestConfig:g,objective:a,maxTrials:o,trialsRun:p.length,candidates:p,bestParameters:E,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"}},qo=new Set(["1m","3m","5m","15m","30m","1h","2h","4h","8h","12h","1d"]),Uo=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]; (4) open interest: <long|short> <COIN> when open interest <above|below> <non-negative number> [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 Uo)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 qo.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){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 ss(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,""):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 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:"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 as({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 cs({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 ls({side:e,coin:t,interval:r,risk:n,expiresAt:o,id:a,name:i,spec:s}){let l=[{id:"oi",type:"input",field:"openInterest"},{id:"thr",type:"constant",value:s.threshold},{id:"sig",type:"compare",op:s.op==="above"?"gt":"lt",left:"oi",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),g=os(o),E=[f,p,h,g].filter(Boolean);if(E.length!==1)throw new V(`unsupported or ambiguous prompt. ${xe}`);if(!ss(o,E[0]))throw new V(`unsupported or ambiguous prompt. ${xe}`);let S,$=E[0],I={side:a,coin:i,interval:s,risk:l,expiresAt:u,id:d,name:c,spec:$};$.kind==="ema_cross"?S=is(I):$.kind==="rsi"?S=as(I):$.kind==="open_interest"?S=ls(I):S=cs(I);let x=Je(S,{nowMs:r});if(!x.ok)throw new V(`draft failed validation: ${x.errors.map(T=>T.message).join("; ")}`);return Ht(Y(S,{nowMs:r}))}import ie from"node:fs";import Ye from"node:path";var Ut=1,us=["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 fs(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=fs(r);if(us.some(a=>o.includes(a)))throw new Error(`shadow-store: forbidden secret-like field at ${t}.${r}`);Se(n,`${t}.${r}`)}}function ds(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 ps(){return{version:Ut,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!==Ut)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:Ut,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 qt=new Map;function Bt(e={}){let t=e.path;if(ds(t),zr(t),ie.existsSync(t)?Vr(ie.readFileSync(t,"utf8"),t):Jr(t,ps()),qt.has(t))return qt.get(t);let r=!1,n=[];function o(){if(r)return;let h=n.shift();if(h){r=!0;try{let g=h.fn();r=!1,h.resolve(g),o()}catch(g){r=!1,h.reject(g),o()}}}function a(h){if(!r&&n.length===0){r=!0;try{return h()}finally{r=!1,queueMicrotask(o)}}return new Promise((g,E)=>{n.push({fn:h,resolve:g,reject:E}),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 g=i();if(g.runners.some(S=>S.id===h.id))throw new Error(`shadow-store: runner id already exists: ${h.id}`);let E=ne(h);return g.runners.push(E),s(g),ne(E)}function u(h){let g=i().runners.find(E=>E.id===h);return g?ne(g):null}function d(){return i().runners.map(h=>ne(h))}function c(h,g){if(typeof g!="function")throw new Error("shadow-store: updater must be a function");let E=i(),S=E.runners.findIndex(x=>x.id===h);if(S<0)throw new Error(`shadow-store: runner not found: ${h}`);let $=ne(E.runners[S]),I=g($);if(!Ge(I)||I.id!==h)throw new Error("shadow-store: updater must return record with same id");return Se(I,"record"),E.runners[S]=ne(I),s(E),ne(E.runners[S])}function f(h){let g=i(),E=g.runners.findIndex($=>$.id===h);if(E<0)throw new Error(`shadow-store: runner not found: ${h}`);let S=ne(g.runners[E]);return S.status!=="stopped"&&(S.status="stopped",g.runners[E]=S,s(g)),ne(g.runners[E])}let p={create(h){return a(()=>l(h))},get(h){return u(h)},list(){return d()},update(h,g){return a(()=>c(h,g))},stop(h){return a(()=>f(h))}};return qt.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 ms(e,t,r,n,o){return Vt("sha256").update(`${e}|${t}|${r}|${n}|${o}`).digest("hex")}function hs(e,t,r,n){return Vt("sha256").update(`shadow|${e}|${t}|${r}|${n??""}`).digest("hex")}function ys(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=hs(p,d.strategyHash,d.compilerHash,c),g=r.get(h);if(g)return Dt(g);let E={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(E)}function o(l){return r.get(l)}function a(){return r.list()}function i(l){return r.stop(l)}function s(l,u,{markoutHorizons: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 g=c.cursor,E=[];for(let y=0;y<u.length;y++){let P=u[y].t;(g==null||P>g)&&E.push(y)}if(E.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}`,T=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:_}){let L=ys(y),j=ms(c.id,c.strategyHash,P,L,y);if(S.has(j))return S.get(j);let O=_+1,R=O<u.length,J={id:j,action:y,type:y,side:L,signalBarT:P,fillBarT:R?u[O].t:null,status:R?"open":"missed"};return S.set(j,J),c.intendedOrders.push(J),J}function U(y,P,_){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:_};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:_};for(let j of d){let O=x(y.id,j);if(T.has(O))continue;let R={orderId:y.id,horizon:j,entryBarT:P.t,entryPrice:P.o,side:A.side,status:"pending",close:null,barT:null};T.set(O,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 _=P+1;_<u.length&&(g==null||u[_].t>g)&&U(y,u[_],_)}for(let y of E){let P=u[y],_=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?U(B,u[Q],Q):z(B)},O=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?U(J,u[B],B):z(J)};L?(_.exitLong&&O("exitLong"),_.exitShort&&O("exitShort")):_.entryLong&&_.entryShort||(_.entryLong&&j("entryLong"),_.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 _=h.get(P.barT);if(_==null)continue;let L=_+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 ws from"node:os";import gs from"node:path";var bs=["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 Es(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(bs.some(n=>Es(t).includes(n)))throw new Error(`strategy service: secret-like field "${t}" is forbidden`);Kt(r)}}function xs(e){if(!Re(e))throw new TypeError("strategy input must be a plain object");return Kt(e),e}function Ss(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 gs.join(ws.homedir(),".oracle","strategy-shadow.json")}function ks(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 As(e,t={},r={}){r.signal?.throwIfAborted?.();let n=xs(t),o=Ss(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);ve(a,i);let s=Ue(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);ve(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:Ue(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 ve(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??ks(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,Ue as evaluateEvidence,It 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,As as runStrategyOperation,ft as sma,de as strategyHash,So as strategyVenues,Je as validateStrategy};
|
package/package.json
CHANGED