openalgo-charts 2.7.2 → 2.7.4

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.
Files changed (51) hide show
  1. package/README.md +29 -29
  2. package/dist/draw/index.d.ts +109 -8
  3. package/dist/index.d.ts +122 -10
  4. package/dist/indicators/index.d.ts +10 -2
  5. package/dist/openalgo-charts.draw.mjs +1 -1
  6. package/dist/openalgo-charts.draw.mjs.map +1 -1
  7. package/dist/openalgo-charts.draw.standalone.js +1 -1
  8. package/dist/openalgo-charts.indicators.mjs +1 -1
  9. package/dist/openalgo-charts.indicators.mjs.map +1 -1
  10. package/dist/openalgo-charts.indicators.standalone.js +1 -1
  11. package/dist/openalgo-charts.mjs +1 -1
  12. package/dist/openalgo-charts.mjs.map +1 -1
  13. package/dist/openalgo-charts.profile.mjs +1 -1
  14. package/dist/openalgo-charts.profile.mjs.map +1 -1
  15. package/dist/openalgo-charts.profile.standalone.js +1 -1
  16. package/dist/openalgo-charts.standalone.js +1 -1
  17. package/dist/openalgo-charts.standalone.js.map +1 -1
  18. package/dist/openalgo-charts.trade.mjs +1 -1
  19. package/dist/openalgo-charts.trade.mjs.map +1 -1
  20. package/dist/openalgo-charts.trade.standalone.js +1 -1
  21. package/dist/openalgo-charts.transform.mjs +1 -1
  22. package/dist/openalgo-charts.transform.mjs.map +1 -1
  23. package/dist/openalgo-charts.transform.standalone.js +1 -1
  24. package/dist/{openalgo-charts.widget.chart-data-export-dialog-CX6h5-cp.mjs → openalgo-charts.widget.chart-data-export-dialog-we0VDywF.mjs} +2 -2
  25. package/dist/{openalgo-charts.widget.chart-data-export-dialog-CX6h5-cp.mjs.map → openalgo-charts.widget.chart-data-export-dialog-we0VDywF.mjs.map} +1 -1
  26. package/dist/{openalgo-charts.widget.chart-type-settings-Bu7g-LFB.mjs → openalgo-charts.widget.chart-type-settings-DYCCD4Ax.mjs} +2 -2
  27. package/dist/{openalgo-charts.widget.chart-type-settings-Bu7g-LFB.mjs.map → openalgo-charts.widget.chart-type-settings-DYCCD4Ax.mjs.map} +1 -1
  28. package/dist/openalgo-charts.widget.grid-bar-CWfujvFQ.mjs +2 -0
  29. package/dist/openalgo-charts.widget.grid-bar-CWfujvFQ.mjs.map +1 -0
  30. package/dist/{openalgo-charts.widget.grid-menus-CPZWEiD3.mjs → openalgo-charts.widget.grid-menus-Ujc8dpxO.mjs} +2 -2
  31. package/dist/{openalgo-charts.widget.grid-menus-CPZWEiD3.mjs.map → openalgo-charts.widget.grid-menus-Ujc8dpxO.mjs.map} +1 -1
  32. package/dist/{openalgo-charts.widget.layouts-templates-menu-CFf0bR9J.mjs → openalgo-charts.widget.layouts-templates-menu-DPPa9Cn1.mjs} +2 -2
  33. package/dist/{openalgo-charts.widget.layouts-templates-menu-CFf0bR9J.mjs.map → openalgo-charts.widget.layouts-templates-menu-DPPa9Cn1.mjs.map} +1 -1
  34. package/dist/openalgo-charts.widget.mjs +1 -1
  35. package/dist/openalgo-charts.widget.mjs.map +1 -1
  36. package/dist/openalgo-charts.widget.standalone.js +1 -1
  37. package/dist/openalgo-charts.widget.storage-idb-JzCQh1Se.mjs +2 -0
  38. package/dist/openalgo-charts.widget.storage-idb-JzCQh1Se.mjs.map +1 -0
  39. package/dist/openalgo-charts.workspace.mjs +1 -1
  40. package/dist/openalgo-charts.workspace.mjs.map +1 -1
  41. package/dist/openalgo-charts.workspace.standalone.js +1 -1
  42. package/dist/profile/index.d.ts +63 -59
  43. package/dist/trade/index.d.ts +69 -9
  44. package/dist/transform/index.d.ts +20 -4
  45. package/dist/widget/index.d.ts +156 -10
  46. package/dist/workspace/index.d.ts +22 -5
  47. package/package.json +1 -1
  48. package/dist/openalgo-charts.widget.grid-bar-Cm_CyA2j.mjs +0 -2
  49. package/dist/openalgo-charts.widget.grid-bar-Cm_CyA2j.mjs.map +0 -1
  50. package/dist/openalgo-charts.widget.storage-idb-WH_o01Wj.mjs +0 -2
  51. package/dist/openalgo-charts.widget.storage-idb-WH_o01Wj.mjs.map +0 -1
@@ -1 +1 @@
1
- if("undefined"==typeof OpenAlgoCharts)throw new Error("openalgo-charts.workspace.standalone.js needs openalgo-charts.standalone.js loaded before it");this.OpenAlgoCharts=this.OpenAlgoCharts||{},this.OpenAlgoCharts.workspace=function(e,t){"use strict";function n(e){return"string"==typeof e&&("right"===e||"left"===e||""===e||e.startsWith("overlay:"))}const a=5242880;class r extends Error{constructor(e){super(e),this.name="WorkspaceDocumentError"}}const o=new Set(["__proto__","prototype","constructor","apikey","secret","clientsecret","apisecret","password","passwordhash","token","accesstoken","refreshtoken","authtoken","authorization","credentials","credential","auth","armed","oneclick","orders","positions","balances","balance","accountbalance","accountid","account"]);function i(e){if("string"==typeof e){if(e.length>a||(new TextEncoder).encode(e).length>a)throw new r("Document size limit exceeded");try{e=JSON.parse(e)}catch{throw new r("Invalid document JSON")}}let t=0,i=0;const s=new Set,c=(e,l,d=!1,p=!1)=>{if(++t>1e5)throw new r("Document node limit exceeded");if(l>32)throw new r("Document depth limit exceeded");if(null===e||"boolean"==typeof e)return e;if("string"==typeof e){if(i+=e.length,i>a)throw new r("Document size limit exceeded");return e}if("number"==typeof e&&Number.isFinite(e))return e;if("object"!=typeof e)throw new r("Document values must be finite JSON data");if(s.has(e))throw new r("Document contains a cycle");if(!Array.isArray(e)&&![Object.prototype,null].includes(Object.getPrototypeOf(e)))throw new r("Document objects must be plain records");if(d||p)for(const t of Reflect.ownKeys(e)){if(Array.isArray(e)&&"length"===t)continue;const n=Object.getOwnPropertyDescriptor(e,t);if("string"!=typeof t||!n.enumerable||Array.isArray(e)&&(!/^(0|[1-9]\d*)$/.test(t)||Number(t)>=e.length))throw new r((p?"Plot scale map":"Opaque payload")+" properties must survive JSON")}let u;if(s.add(e),Array.isArray(e)){if(e.length>1e5)throw new r("Document array limit exceeded");const t=[];for(let n=0;n<e.length;n++){const a=Object.getOwnPropertyDescriptor(e,String(n));if(!a||!("value"in a))throw new r("Document arrays must contain data values");t.push(c(a.value,l+1,d))}u=t}else{const t={},s=Object.getOwnPropertyDescriptor(e,"settings")?.value,h=!d&&"string"==typeof Object.getOwnPropertyDescriptor(e,"indicatorId")?.value&&"number"==typeof Object.getOwnPropertyDescriptor(e,"paneIndex")?.value&&null!==s&&"object"==typeof s&&!Array.isArray(s);for(const s of Object.keys(e)){const u=s.toLowerCase().replace(/[^a-z0-9_]/g,"").replace(/_/g,"");if(!p&&(o.has(s)||o.has(u))){if(d)throw new r("Opaque payload contains a private workspace field");continue}if(i+=s.length,i>a)throw new r("Document size limit exceeded");const f=Object.getOwnPropertyDescriptor(e,s);if(!("value"in f))throw new r("Document accessors are not allowed");if(p&&!n(f.value))throw new r("Invalid indicator plot priceScaleId");const m=c(f.value,l+1,d||"payload"===s,h&&"plotPriceScaleIds"===s);p?Object.defineProperty(t,s,{value:m,enumerable:!0,configurable:!0,writable:!0}):t[s]=m}u=t}return s.delete(e),u},l=c(e,0);if((new TextEncoder).encode(JSON.stringify(l)).length>a)throw new r("Document size limit exceeded");return l}function s(e,t){if(null===e||"object"!=typeof e||Array.isArray(e))throw new r(`${t} must be an object`);return e}function c(e,t,n){if(!Array.isArray(e)||e.length>n)throw new r(`${t} must be an array within the ${n} item limit`);return e}function l(e,t,n=200,a=!1){if("string"!=typeof e||!a&&0===e.trim().length||e.length>n||Array.from(e).some(e=>e.charCodeAt(0)<32))throw new r(`${t} must be ${a?"0":"1"}-${n} characters`);return e.trim()}function d(e,t,n,a=Number.MAX_SAFE_INTEGER,o=!1){if("number"!=typeof e||!Number.isFinite(e)||e<n||e>a||o&&!Number.isInteger(e))throw new r(`${t} must be ${o?"an integer":"a number"} between ${n} and ${a}`);return e}function p(e,t,n){if(void 0===e&&void 0!==n)return n;if("boolean"!=typeof e)throw new r(`${t} must be a boolean`);return e}function u(e,t,n,a){if(void 0===e&&void 0!==a)return a;if("string"!=typeof e||!n.includes(e))throw new r(`${t} is not supported`);return e}function h(e){return!1===e?.removable||!1===e?.listed}const f=31,m=256;function w(e,t){if(e.kind!==t||1!==e.version)throw new r(`Unsupported ${t} kind or version`);const n=d(e.createdAt,"createdAt",0);return{version:1,id:l(e.id,"id",100),name:l(e.name,"name",120),createdAt:n,updatedAt:d(e.updatedAt,"updatedAt",n)}}function g(e,t){if(!n(e))throw new r(`Invalid ${t}`);return e}function y(e,n=!0,a=!0){const o=new Set;return c(e,"indicators",m).map(e=>{const i=s(e,"indicator"),h=s(i.settings,"indicator settings"),m={indicatorId:l(i.indicatorId,"indicatorId"),settings:h,paneIndex:d(i.paneIndex,"indicator paneIndex",0,f,!0)};if(void 0!==i.studyInputs){const e=c(i.studyInputs,"indicator studyInputs",1e5).map(e=>{if("string"!=typeof e||!e.trim())throw new r("Invalid study input key");const t=s(h[e],"study input reference");if("indicator"!==t.kind||3!==Object.keys(t).length)throw new r("Invalid study input reference");const n=l(t.instanceId,"study input instanceId");if("string"!=typeof t.plotKey||!t.plotKey.trim())throw new r("Invalid study input plotKey");return h[e]={kind:"indicator",instanceId:n,plotKey:t.plotKey},e});if(new Set(e).size!==e.length)throw new r("Duplicate study input key");m.studyInputs=e}if(void 0!==i.visible&&(m.visible=p(i.visible,"indicator visibility")),void 0!==i.barSource&&(m.barSource=u(i.barSource,"indicator bar source",["chart","underlying"])),a&&void 0!==i.policy){let e;try{e=t.parseIndicatorPolicy(i.policy)}catch{throw new r("Invalid indicator policy")}Object.keys(e).length&&(m.policy={...e})}if(void 0!==i.priceScaleId&&(m.priceScaleId=g(i.priceScaleId,"indicator priceScaleId")),void 0!==i.plotPriceScaleIds){const e=s(i.plotPriceScaleIds,"indicator plotPriceScaleIds"),t=Object.entries(e).map(([e,t])=>[e,g(t,"indicator plot priceScaleId")]);t.length&&(m.plotPriceScaleIds=Object.fromEntries(t))}if(n&&void 0!==i.instanceId){if(m.instanceId=l(i.instanceId,"indicator instanceId"),o.has(m.instanceId))throw new r("Duplicate indicator instance ID");o.add(m.instanceId)}return m})}function v(e){return y(i(e))}function I(e){const t=!0===e.indicatorRange?.manual;delete e.indicatorRange,delete e.fixedRange,t||(e.autoScale=!0,delete e.range,delete e.ratioLock)}function b(e,n=!1,a){const o=function(e){const n=e.map(e=>s(e,"indicator")),a=n.map(e=>{if(void 0===e.policy)return!1;try{return h(t.parseIndicatorPolicy(e.policy))}catch{throw new r("Invalid indicator policy")}}),o=new Set,i=e=>{const t=e.settings,n=Array.isArray(e.studyInputs)?e.studyInputs:[];return null!==t&&"object"==typeof t&&!Array.isArray(t)&&n.some(e=>{const n="string"==typeof e?t[e]:void 0;return null!==n&&"object"==typeof n&&!Array.isArray(n)&&"string"==typeof n.instanceId&&o.has(n.instanceId)})};for(let e=!0;e;)e=!1,n.forEach((t,n)=>{!a[n]&&i(t)&&(a[n]=e=!0),a[n]&&"string"==typeof t.instanceId&&!o.has(t.instanceId)&&(o.add(t.instanceId),e=!0)});return{kept:e.filter((e,t)=>!a[t]),left:o}}(c(e,"indicators",m)),i=o.kept;for(const e of o.left)a?.add(e);const l=i.some(e=>{const t=s(e,"indicator").studyInputs;return Array.isArray(t)&&t.length>0}),d=y(i,l||n,!1);if(n&&d.some(e=>void 0===e.instanceId))throw new r("Template layout requires every indicator instance ID");if(!l)return d;const p=new Map(d.flatMap((e,t)=>void 0===e.instanceId?[]:[[e.instanceId,t]])),u=d.map((e,t)=>(e.studyInputs??[]).map(n=>{const a=e.settings[n],o=p.get(a.instanceId);if(void 0===o)throw new r(`External study dependency: ${a.instanceId}`);if(o===t)throw new r("A study cannot depend on itself");return o})),f=new Set,w=new Set,g=e=>{if(f.has(e))throw new r("Study dependencies contain a cycle");if(!w.has(e)){f.add(e);for(const t of u[e])g(t);f.delete(e),w.add(e)}};for(let e=0;e<d.length;e++)g(e);return d}function _(e){return c(e,"chart panes",32).map(e=>{try{const n=t.parsePaneState(e);d(n.weight,"pane weight",Number.MIN_VALUE);for(const e of[n.priceScale,...Object.values(n.scales??{})])if(e){if(d(e.marginTop,"marginTop",0,1),d(e.marginBottom,"marginBottom",0,1),d(e.minMove,"minMove",0),e.marginTop+e.marginBottom>=1)throw new r("Price scale margins leave no chart area");for(const t of[e.range,e.fixedRange])if(t&&(d(t.min,"range.min",-Number.MAX_SAFE_INTEGER),d(t.max,"range.max",t.min),t.max===t.min))throw new r("Price scale range must have positive width")}return n}catch(e){throw new r(e instanceof Error?e.message:"Invalid pane scale state")}})}function S(e){if(Array.isArray(e))return{indicators:b(e)};const t=s(e,"indicator template payload"),n=new Set,a=b(t.indicators,void 0!==t.layout,n);if(void 0===t.layout)return{indicators:a};const o=s(t.layout,"indicator template layout"),i=_(o.panes);if(!i.length)throw new r("Template layout needs pane zero");const p=new Map(a.map(e=>[e.instanceId,e]));for(const e of a)if(e.paneIndex>=i.length)throw new r("Template indicator pane is missing");for(const e of i)for(const t of[e.priceScale,...Object.values(e.scales??{})]){const e=t?.indicatorRange;if(t&&e&&n.has(e.instanceId))I(t);else if(t?.indicatorRange&&!p.has(t.indicatorRange.instanceId))throw new r("Template scale range owner is missing")}const u=(e,t)=>{if("right"!==t&&!i[e].scales?.[t])throw new r("Template plot or primary scale is missing")},h=new Map,f=c(o.plots,"template plot bindings",1e5).filter(e=>{const t=s(e,"template plot binding").instanceId;return"string"!=typeof t||!n.has(t)}).map(e=>{const t=s(e,"template plot binding"),n=l(t.instanceId,"template plot instanceId"),a=p.get(n);if(!a)throw new r("Template plot indicator is missing");if("string"!=typeof t.plotKey)throw new r("Template plot key must be a string");const o=t.plotKey,c=d(t.paneIndex,"template plot paneIndex",0,i.length-1,!0);if(0!==c&&c!==a.paneIndex)throw new r("Template plot belongs to another pane");const f=g(t.scaleId,"template plot scaleId");u(c,f);const m=h.get(n)??new Map;if(m.has(o))throw new r("Duplicate template plot binding");return m.set(o,f),h.set(n,m),{instanceId:n,plotKey:o,paneIndex:c,scaleId:f}});for(const e of a)for(const[t,n]of Object.entries(e.plotPriceScaleIds??{}))if(h.get(e.instanceId)?.get(t)!==n)throw new r("Template plot override needs a matching scale binding");const m={indicators:a,layout:{panes:i,plots:f}};if(void 0!==o.primaryScaleId){const e=g(o.primaryScaleId,"template primaryScaleId");u(0,e),m.layout.primaryScaleId=e}return m}function A(e){return S(i(e))}function k(e){const n=s(e,"chart");if(1!==n.version&&2!==n.version)throw new r("Unsupported chart version");const a={version:2===n.version?2:1};void 0!==n.timezone&&(a.timezone=l(n.timezone,"timezone",100));for(const e of["navigation","canvas","statusLine","watermark","trading","events","axisChrome"])void 0!==n[e]&&Object.assign(a,{[e]:s(n[e],e)});if(void 0!==n.viewport){const e=s(n.viewport,"viewport"),t=d(e.from,"viewport.from",-Number.MAX_SAFE_INTEGER);a.viewport={from:t,to:d(e.to,"viewport.to",t)}}if(void 0!==n.barSpacing&&(a.barSpacing=d(n.barSpacing,"barSpacing",Number.MIN_VALUE)),void 0!==n.grid){const e=s(n.grid,"grid");a.grid={vertLines:p(e.vertLines,"vertical grid"),horzLines:p(e.horzLines,"horizontal grid")}}if(void 0!==n.crosshairMode&&(a.crosshairMode=u(n.crosshairMode,"crosshairMode",["normal","magnet"])),void 0!==n.crosshairSnapToBar&&(a.crosshairSnapToBar=p(n.crosshairSnapToBar,"crosshairSnapToBar")),void 0!==n.priceOnlyAutoScale&&(a.priceOnlyAutoScale=p(n.priceOnlyAutoScale,"priceOnlyAutoScale")),void 0!==n.indicatorLegendCollapsed&&(a.indicatorLegendCollapsed=p(n.indicatorLegendCollapsed,"indicatorLegendCollapsed")),void 0!==n.indicators&&(a.indicators=y(n.indicators)),void 0!==n.sourceAbove&&(a.sourceAbove=l(n.sourceAbove,"sourceAbove")),void 0!==n.alerts)try{a.alerts=t.parseAlertsDocument(n.alerts)}catch(e){throw new r(e instanceof Error?e.message:"Invalid alert document")}if(void 0!==n.drawings){if(null===n.drawings||"object"!=typeof n.drawings)throw new r("drawings must be a document or array");a.drawings=n.drawings}if(void 0!==n.panes&&(a.panes=_(n.panes)),void 0!==n.primaryPane){if(2!==n.version)throw new r("A moved price pane needs chart version 2");if(a.primaryPane=d(n.primaryPane,"primaryPane",0,f,!0),!a.panes||a.primaryPane>=a.panes.length)throw new r("The price pane slot must name a saved pane")}return void 0!==n.series&&(a.series=c(n.series,"series descriptors",512).map(e=>{const t=s(e,"series"),n=t.priceScaleId;if("string"!=typeof n)throw new r("priceScaleId must be a string");const a={type:l(t.type,"series type"),style:s(t.style,"series style"),paneIndex:d(t.paneIndex,"series paneIndex",0,f,!0),priceScaleId:n};return void 0!==t.transform&&(a.transform=function(e){const t=s(e,"series transform"),n={type:l(t.type,"series transform type",100)};if(void 0===t.options)return n;const a=s(t.options,"series transform options");for(const e of Object.values(a))if("string"!=typeof e&&("number"!=typeof e||!Number.isFinite(e)))throw new r("Series transform options must be finite numbers or text");return n.options=a,n}(t.transform)),a})),a}function x(e){const n=s(e,"workspace pane"),a=s(n.settings??{},"settings");for(const e of Object.values(a))if(!["string","number","boolean"].includes(typeof e))throw new r("Chart settings must be scalar values");const o=c(n.comparisons??[],"comparisons",32).map(e=>{const t=s(e,"comparison"),n={id:l(t.id,"comparison id",100),symbol:l(t.symbol,"comparison symbol"),exchange:l(t.exchange,"comparison exchange",200,!0),visible:p(t.visible,"comparison visibility",!0)};return void 0!==t.color&&(n.color=l(t.color,"comparison color",200)),n});if(new Set(o.map(e=>e.id)).size!==o.length)throw new r("Duplicate comparison ID");const i={id:l(n.id,"pane id",100),symbol:l(n.symbol,"symbol"),exchange:l(n.exchange,"exchange",200,!0),interval:l(n.interval,"interval",100),chartType:l(n.chartType,"chartType",100),chart:k(n.chart),settings:a,volume:p(n.volume,"volume",!0),magnet:u(n.magnet,"magnet",["off","weak","strong"],"off"),stay:p(n.stay,"stay",!1),comparisons:o,comparisonMode:u(n.comparisonMode,"comparisonMode",["price","percent"],"percent")};if(void 0!==n.historyPeriod&&(i.historyPeriod=l(n.historyPeriod,"historyPeriod",100)),void 0!==n.variant){let e;try{e=t.normalizeDataVariant(n.variant)}catch(e){throw new r(e instanceof Error?e.message:"Invalid data variant")}e&&(i.variant={...e})}return void 0!==n.linkGroup&&(i.linkGroup=l(n.linkGroup,"linkGroup",100)),i}function D(e,t){const n={crosshair:p(e.crosshair,`${t}crosshair sync`,!0),viewport:p(e.viewport,`${t}viewport sync`,!0),symbol:p(e.symbol,`${t}symbol sync`,!1),interval:p(e.interval,`${t}interval sync`,!1)};for(const a of["appearance","chartType","drawings"])void 0!==e[a]&&(n[a]=p(e[a],`${t}${a} sync`));return void 0!==e.whenMissing&&(n.whenMissing=u(e.whenMissing,`${t}whenMissing`,["nearest","hide"])),n}function O(e){const t=c(e.panes,"panes",16).map(x);if(0===t.length)throw new r("A workspace needs at least one pane");const n=new Set(t.map(e=>e.id));if(n.size!==t.length)throw new r("Duplicate pane ID");const a=l(e.activePaneId,"activePaneId",100);if(!n.has(a))throw new r("Focused pane is missing");const o=s(e.layout,"layout"),i=d(o.rows,"rows",1,8,!0),p=d(o.columns,"columns",1,8,!0),u=new Set,h=new Set,f=c(o.slots,"layout slots",16).map(e=>{const t=s(e,"slot"),a={paneId:l(t.paneId,"slot paneId",100),row:d(t.row,"row",0,i-1,!0),column:d(t.column,"column",0,p-1,!0),rowSpan:d(t.rowSpan??1,"rowSpan",1,i,!0),columnSpan:d(t.columnSpan??1,"columnSpan",1,p,!0)};if(!n.has(a.paneId)||u.has(a.paneId))throw new r("Invalid or duplicate layout pane ID");if(u.add(a.paneId),a.row+a.rowSpan>i||a.column+a.columnSpan>p)throw new r("Layout slot is outside the grid");for(let e=a.row;e<a.row+a.rowSpan;e++)for(let t=a.column;t<a.column+a.columnSpan;t++){const n=e*p+t;if(h.has(n))throw new r("Layout slots overlap");h.add(n)}return a});if(u.size!==t.length)throw new r("Every pane needs one layout slot");const m=s(e.sync??{},"sync"),w={layout:{rows:i,columns:p,slots:f},panes:t,activePaneId:a,sync:D(m,"")};void 0!==m.groups&&(w.sync.groups=function(e){const t=new Set;return c(e,"link groups",16).map(e=>{const n=s(e,"link group"),a=l(n.id,"link group id",100);if(t.has(a))throw new r("Duplicate link group ID");return t.add(a),{id:a,name:l(n.name,"link group name",120),...D(n,"link group ")}})}(m.groups));const g=new Set(w.sync.groups?.map(e=>e.id));for(const e of t)if(void 0!==e.linkGroup&&!g.has(e.linkGroup))throw new r(`Link group ${e.linkGroup} is not declared`);void 0!==o.preset&&(w.layout.preset=l(o.preset,"layout preset",100));for(const[e,t]of[["rowWeights",i],["columnWeights",p]]){if(void 0===o[e])continue;const n=c(o[e],e,8).map(t=>d(t,e,Number.MIN_VALUE,1e3));if(n.length!==t)throw new r(`${e} must match the number of grid tracks`);w.layout[e]=n}return w}function E(e){const t=s(i(e),"workspace");return{kind:"workspace",...w(t,"workspace"),...O(t)}}function P(e){return O(s(i(e),"workspace"))}function T(e){const t=s(i(e),"indicator template");return{kind:"indicator-template",...w(t,"indicator-template"),...S(t)}}const j=e=>i(e);function M(){if(!globalThis.crypto?.randomUUID)throw new r("Supply an ID factory when crypto.randomUUID is unavailable");return globalThis.crypto.randomUUID()}class ${constructor(e,t,n,a){Object.defineProperty(this,"_storage",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"_kind",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"_empty",{enumerable:!0,configurable:!0,writable:!0,value:a}),Object.defineProperty(this,"namespace",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_listeners",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"_queue",{enumerable:!0,configurable:!0,writable:!0,value:Promise.resolve()}),this.namespace=l(t,"storage namespace")}async load(){return await this._queue,this._read()}subscribe(e){return this._listeners.add(e),()=>{this._listeners.delete(e)}}transact(e,t={}){const{signal:n}=t,a=void 0===t.expectedRevision?void 0:d(t.expectedRevision,"expected revision",0,Number.MAX_SAFE_INTEGER,!0),r=this._queue.then(async()=>{n?.throwIfAborted();const t=await this._read();if(n?.throwIfAborted(),void 0!==a&&t.revision!==a)throw this._kind.conflict();const r=t.revision,o=e(t);t.revision++;const i=this._kind.parse(t);n?.throwIfAborted(),await this._storage.write(this.namespace,i,r,{signal:n});for(const e of Array.from(this._listeners))try{e(j(i))}catch(e){queueMicrotask(()=>{throw e})}return void 0===o?o:j(o)});return this._queue=r.then(()=>{},()=>{}),r}async _read(){const e=await this._storage.read(this.namespace);return null===e?this._empty():this._kind.parse(e)}}function N(e,t){const n=new Map(Object.entries(e).map(([e,t])=>[e,j(t)]));return{async read(e){const t=n.get(l(e,"storage namespace"));return void 0===t?null:j(t)},async write(e,a,o,i){i?.signal?.throwIfAborted();const s=l(e,"storage namespace"),c=d(o,"expected revision",0,Number.MAX_SAFE_INTEGER,!0),p=t.parse(a);if(p.revision!==c+1)throw new r("A write must advance the catalog revision by one");const u=n.get(s);if((void 0===u?0:t.parse(u).revision)!==c)throw t.conflict();n.set(s,p)}}}function W(e,t,n,a,o,s=0){if("replace"!==n&&"append"!==n)throw new r("Unsupported indicator template mode");if(!Number.isInteger(s)||s<0||s>f)throw new r("Invalid price pane slot");const c=v(e),l=b(i(t));if(l.some(e=>e.studyInputs?.length)&&z(c,l),"append"===n){const e=Math.max(0,...c.map(e=>e.paneIndex));if(!Number.isInteger(o)||o<=Math.max(e,s)||o>32)throw new r("Invalid next indicator pane");const t=[...new Set(l.map(e=>e.paneIndex).filter(e=>e>0))].sort((e,t)=>e-t);for(const e of l)if(e.paneIndex=e.paneIndex>0?o+t.indexOf(e.paneIndex):s,e.paneIndex>f)throw new r("Indicator pane limit exceeded")}else if(s>0)for(const e of l)e.paneIndex=C(e.paneIndex,s);const d="replace"===n?c.filter(e=>h(e.policy)):[],p=new Set(d.map(e=>e.paneIndex).filter(e=>e!==s));if(p.size){const e=[...new Set(l.map(e=>e.paneIndex).filter(e=>e!==s))].sort((e,t)=>e-t),t=new Map;let n=-1;for(const a of e){do{n++}while(p.has(n)||n===s);t.set(a,n)}for(const e of l)e.paneIndex=t.get(e.paneIndex)??e.paneIndex;if(n>f)throw new r("Indicator pane limit exceeded")}const u="replace"===n?[...d,...l]:[...c,...l];return R(u,a),u}function R(e,t){if(e.length>m)throw new r("At most 256 indicator instances are supported");const n=[...new Set(e.filter(e=>!t.has(e.indicatorId)).map(e=>e.indicatorId))];if(n.length)throw new r(`Missing indicators: ${n.join(", ")}`)}function L(e,t){return e===t?0:e<t?e+1:e}function C(e,t){return 0===e?t:e<=t?e-1:e}function z(e,t){const n=new Map;if(!t.length)return n;const a=new Set([...e,...t].flatMap(e=>void 0===e.instanceId?[]:[e.instanceId]));for(const t of e)for(const e of t.studyInputs??[])a.add(t.settings[e].instanceId);if(!globalThis.crypto?.getRandomValues)throw new r("Random IDs are unavailable for connected template copies");const o=Array.from(globalThis.crypto.getRandomValues(new Uint32Array(4)),e=>e.toString(16).padStart(8,"0")).join("");let i=1;for(const e of t){let t;do{t=`template-study-${o}-${i++}`}while(a.has(t));a.add(t),void 0!==e.instanceId&&n.set(e.instanceId,t),e.instanceId=t}for(const e of t)for(const t of e.studyInputs??[]){const a=e.settings[t];e.settings[t]={...a,instanceId:n.get(a.instanceId)}}return n}function G(e){return[["right",e.priceScale],...Object.entries(e.scales??{})]}function U(e,t){return"right"===t?e.priceScale:e.scales?.[t]}function F(e,t,n){const a=e.primarySeries();if(!a)return;const r=a.priceScale();return G(n).find(([n])=>e.panes()[t].scaleFor(n)===r)?.[0]}function K(e,t){return[e[t],...e.filter((e,n)=>n!==t)]}function X(e,t){const n=[];return e.forEach((e,a)=>{n[C(a,t)]=e}),n}function q(e){const n=e.getState(),a=n.panes;if(!a?.length)throw new r("Cannot capture a destroyed chart");const o=e.primaryPaneIndex(),i=K(a,o),s=[];for(const n of e.indicators())for(const a of t.getIndicator(n.indicatorId).plots){const t=n.series(a.key),i=n.plotPriceScaleId(a.key);if(!t||null===e.seriesType(t)||null===i)throw new r("Cannot capture a removed indicator plot");s.push({instanceId:n.id,plotKey:a.key,paneIndex:!0===a.overlay?0:L(n.paneIndex,o),scaleId:i})}const c={panes:i,plots:s},l=F(e,o,i[0]);void 0!==l&&(c.primaryScaleId=l);return A({indicators:(n.indicators??[]).map(e=>({...e,paneIndex:L(e.paneIndex,o)})),layout:c})}function B(e,t,n){const a=e.plots.find(e=>!0!==e.overlay),o=a?n.find(e=>e.plotKey===a.key).scaleId:t.priceScaleId??"right";for(const a of e.fills??[]){const e=!0===a.overlay?0:t.paneIndex,i=a.between.map(t=>n.find(e=>e.plotKey===t)??{paneIndex:e,scaleId:!0===a.overlay?"right":o});if(i.some(t=>t.paneIndex!==e)||i[0].scaleId!==i[1].scaleId)throw new r("Template fill endpoints must share their pane and scale")}}function V(e,n,a){const r=t.parsePaneState({weight:1,priceScale:e}).priceScale;return a?r.indicatorRange&&(r.indicatorRange.instanceId=n.get(r.indicatorRange.instanceId)):(r.autoScale=!0,delete r.range,delete r.ratioLock,r.indicatorRange&&(delete r.indicatorRange,delete r.fixedRange)),r}function J(e,t){for(const n of e)for(const[,e]of G(n)){const n=e.indicatorRange;n&&t.has(n.instanceId)&&I(e)}}function Z(e,n,a,o={}){if("replace"!==a&&"append"!==a)throw new r("Unsupported indicator template mode");const c=e.primaryPaneIndex(),l=function(e,n,a,o,c){const l=s(i(o),"template apply options"),d=u(l.scalePolicy,"scale policy",["copy","share"],"copy"),p="preserve"===u(l.rangePolicy,"range policy",["auto","preserve"],"auto"),m=A(n),w=e.getState();if(!w.panes?.length)throw new r("Cannot plan for a destroyed chart");const g={...w,panes:K(w.panes,c),indicators:(w.indicators??[]).map(e=>({...e,paneIndex:L(e.paneIndex,c)}))},y=new Set(t.registeredIndicators().map(e=>e.id));if(!m.layout)return{indicators:W(g.indicators,m.indicators,a,y,g.panes.length)};const I=m.layout,b=m.indicators,_=v(g.indicators??[]),S="replace"===a?_.filter(e=>h(e.policy)):[],k="append"===a?[..._,...b]:[...S,...b];R(k,y);const x=function(e,n){const a=new Map;for(const e of n.plots){const t=a.get(e.instanceId)??[];t.push(e),a.set(e.instanceId,t)}for(const n of e){const o=t.getIndicator(n.indicatorId),i=a.get(n.instanceId)??[],s=o.inputs.filter(e=>"source"===e.type&&"string"!=typeof(Object.prototype.hasOwnProperty.call(n.settings,e.key)?n.settings[e.key]:e.default)),c=new Set(n.studyInputs??[]);if(s.length!==c.size||s.some(e=>!c.has(e.key)||"source"!==e.type||!0!==e.allowStudyOutputs))throw new r("Template dependency metadata disagrees with its source inputs");for(const a of c){const o=n.settings[a],i=e.find(e=>e.instanceId===o.instanceId),s=t.getIndicator(i.indicatorId).plots.filter(e=>e.key===o.plotKey);if(1!==s.length||void 0!==s[0].ohlc)throw new r("Template study source must identify one declared scalar plot")}if(i.length!==o.plots.length)throw new r("Template needs every declared plot binding");for(const e of i){const t=o.plots.find(t=>t.key===e.plotKey);if(!t||e.paneIndex!==(!0===t.overlay?0:n.paneIndex))throw new r("Template plot key or pane disagrees with its descriptor")}B(o,n,i)}return a}(b,I),D="replace"===a?function(e){const n=e.panes().map(e=>e.series().length),a=e.primaryPaneIndex();for(const r of e.indicators())for(const o of t.getIndicator(r.indicatorId).plots){const t=r.series(o.key);t&&null!==e.seriesType(t)&&n[!0===o.overlay?a:r.paneIndex]--}return new Set(n.flatMap((e,t)=>e>0?[L(t,a)]:[]))}(e):new Set;for(const e of S)e.paneIndex>0&&D.add(e.paneIndex);const O={preserveScaleFormats:g.panes.flatMap((e,t)=>0===t||"append"===a||D.has(t)?G(e).map(([e])=>({paneIndex:t,scaleId:e})):[])};if("append"===a&&!b.length)return{indicators:_,restoreOptions:O};const E=F(e,c,g.panes[0]),P=g.panes.map(e=>t.parsePaneState(e));"replace"===a&&J(P,new Set(_.filter(e=>!S.includes(e)).flatMap(e=>e.instanceId?[e.instanceId]:[])));const T=function(e,t,n){const a=new Map([[0,0]]);let o=n;for(const n of[...new Set(e.map(e=>e.paneIndex).filter(e=>e>0))].sort((e,t)=>e-t)){for(;t.has(o);)o++;if(o>f)throw new r("Indicator pane limit exceeded");a.set(n,o++)}return a}(b,D,"append"===a?P.length:1),j=b.map(e=>e.instanceId),M=z(_,b),$=P[0],N=I.panes[0];!function(e,t,n,a){const o=e[0],i=t[0];for(const[s,c]of n){if(!s)continue;const n=t[s],l=n.weight/i.weight*o.weight;if(!(l>0&&Number.isFinite(l)))throw new r("Template pane weight is not representable");const d=a(n);e[c]={weight:l,priceScale:d[0][1],...d.length>1?{scales:Object.fromEntries(d.slice(1))}:{}}}}(P,I.panes,T,e=>G(e).map(([e,t])=>[e,V(t,M,p)]));const C=new Set(G($).map(([e])=>e)),X=new Map,q=[];let Z=1;const H=(e,t)=>{if(e>0)return t;const n=X.get(t);if(void 0!==n)return n;if(t===I.primaryScaleId&&void 0!==E)return X.set(t,E),E;let a=t;if("copy"===d)do{a=`overlay:template-scale-${b[0].instanceId}-${Z++}`}while(U($,a));if(X.set(t,a),!U($,a)){const e=U(N,t)??{marginTop:.1,marginBottom:.1,minMove:0,minPrecision:0,mode:"linear",inverted:!1,autoScale:!0},n=V(e,M,p);"right"===a?$.priceScale=n:($.scales??($.scales={}),$.scales[a]=n),"copy"===d&&q.push({id:a,source:{...e,placement:e.placement??{side:"left"===t||"right"===t?t:"hidden",order:0}}})}return a};b.forEach((e,n)=>{const a=j[n],r=e.paneIndex,o=(x.get(a)??[]).map(e=>[e.plotKey,H(e.paneIndex,e.scaleId)]);o.length&&(e.plotPriceScaleIds=Object.fromEntries(o)),void 0!==e.priceScaleId?e.priceScaleId=H(r,e.priceScaleId):t.getIndicator(e.indicatorId).plots.some(e=>!0!==e.overlay)||(e.priceScaleId=H(r,"right")),e.paneIndex=T.get(r),B(t.getIndicator(e.indicatorId),e,(x.get(a)??[]).map(t=>({...t,paneIndex:T.get(t.paneIndex),scaleId:e.plotPriceScaleIds[t.plotKey]})))});for(const e of["left","right","hidden"]){let t=Math.max(-1,...G($).filter(([e])=>C.has(e)).map(([e,t])=>t.placement??{side:"left"===e||"right"===e?e:"hidden",order:0}).filter(t=>t.side===e).map(e=>e.order))+1;for(const n of q.filter(t=>t.source.placement.side===e).sort((e,t)=>e.source.placement.order-t.source.placement.order))U($,n.id).placement={side:e,order:t++}}return{indicators:k,panes:P,restoreOptions:O}}(e,n,a,o,c);if(0===c)return l;const d={indicators:l.indicators.map(e=>({...e,paneIndex:C(e.paneIndex,c)})),panes:l.panes?X(l.panes,c):H(e,a),primaryPane:c};return l.restoreOptions&&(d.restoreOptions={preserveScaleFormats:(l.restoreOptions.preserveScaleFormats??[]).map(e=>({...e,paneIndex:C(e.paneIndex,c)}))}),d}function H(e,n){const a=e.getState(),r=(a.panes??[]).map(e=>t.parsePaneState(e));return"replace"===n&&J(r,new Set((a.indicators??[]).flatMap(e=>e.instanceId?[e.instanceId]:[]))),r}class Q extends Error{constructor(){super("The saved workspace changed in another session. Reload and retry."),this.name="WorkspaceConflictError"}}const Y={parse:ee,conflict:()=>new Q};function ee(e){const t=s(i(e),"workspace catalog");if(1!==t.version)throw new r("Unsupported workspace catalog version");const n=c(t.workspaces,"workspaces",100).map(E),a=c(t.templates,"templates",100).map(T),o=[...n,...a].map(e=>e.id);if(new Set(o).size!==o.length)throw new r("Duplicate document ID");const u=new Set(n.map(e=>e.id)),h=c(t.recentWorkspaceIds,"recent workspaces",10).map(e=>l(e,"recent workspace ID",100));if(new Set(h).size!==h.length||h.some(e=>!u.has(e)))throw new r("Invalid recent workspace IDs");const f=null===t.activeWorkspaceId?null:l(t.activeWorkspaceId,"active workspace ID",100);if(null!==f&&!u.has(f))throw new r("Active workspace is missing");return{version:1,revision:d(t.revision,"catalog revision",0,Number.MAX_SAFE_INTEGER,!0),workspaces:n,templates:a,recentWorkspaceIds:h,activeWorkspaceId:f,autosave:p(t.autosave,"autosave")}}function te(){return{version:1,revision:0,workspaces:[],templates:[],recentWorkspaceIds:[],activeWorkspaceId:null,autosave:!1}}function ne(e){const t=s(i(e),"document");if("workspace"===t.kind)return E(t);if("indicator-template"===t.kind)return T(t);throw new r("Unsupported document kind")}function ae(e,t,n,a,o){const i=l(t,"database name");let s=null,c=null,p=!1;const u=()=>new Error(`${n} storage is closed. Create a new adapter to reconnect.`);function h(){return p?Promise.reject(u()):s||(s=new Promise((t,a)=>{const r=e.open(i,1);let o=!1;r.onupgradeneeded=()=>{r.result.objectStoreNames.contains("catalogs")||r.result.createObjectStore("catalogs")},r.onblocked=()=>{o=!0,a(new Error(`${n} database is blocked by another session. Close that session and retry.`))},r.onerror=()=>{o=!0,a(r.error??new Error(`Cannot open ${n.toLowerCase()} database`))},r.onsuccess=()=>{const e=r.result;if(p||o)return e.close(),void a(u());c=e,e.onversionchange=()=>{p=!0,e.close(),c=null},e.onclose=()=>{p=!0,c=null},t(e)}}).catch(e=>{throw s=null,e}),s)}return{async read(e){const t=l(e,"storage namespace"),a=await h();return new Promise((e,r)=>{const o=a.transaction("catalogs","readonly"),i=o.objectStore("catalogs").get(t);let s=null;i.onsuccess=()=>{s=i.result??null},o.oncomplete=()=>e(s),o.onabort=()=>r(o.error??new Error(`${n} read was aborted`))})},async write(e,t,i,s){const c=s?.signal;c?.throwIfAborted();const p=l(e,"storage namespace"),u=d(i,"expected revision",0,Number.MAX_SAFE_INTEGER,!0),f=a(t);if(f.revision!==u+1)throw new r("A write must advance the catalog revision by one");const m=await h();return c?.throwIfAborted(),new Promise((e,t)=>{const r=m.transaction("catalogs","readwrite"),i=r.objectStore("catalogs"),s=i.get(p);let l;const d=()=>{try{r.abort(),l=c?.reason}catch{}},h=()=>c?.removeEventListener("abort",d);c?.addEventListener("abort",d,{once:!0}),s.onsuccess=()=>{try{const e=s.result;if((void 0===e?0:a(e).revision)!==u)throw o();i.put(f,p)}catch(e){l=e,r.abort()}},r.oncomplete=()=>{h(),e()},r.onabort=()=>{h(),t(l??r.error??new Error(`${n} save was aborted`))}})},async close(){p=!0,c&&(c.close(),c=null),s&&await s.catch(()=>{})}}}class re extends Error{constructor(){super("The saved watchlists changed in another session. Reload and retry."),this.name="WatchlistConflictError"}}function oe(e){return JSON.stringify([e.symbol,e.exchange])}function ie(e){const t=s(e,"watchlist entry");return{symbol:l(t.symbol,"symbol",64),exchange:l(t.exchange,"exchange",32,!0)}}function se(e){const t=c(e,"watchlist entries",500).map(ie);if(new Set(t.map(oe)).size!==t.length)throw new r("Duplicate watchlist entry");return t}function ce(e){const t=s(e,"watchlist"),n=d(t.createdAt,"createdAt",0);return{id:l(t.id,"watchlist ID",100),name:l(t.name,"name",120),entries:se(t.entries),createdAt:n,updatedAt:d(t.updatedAt,"updatedAt",n)}}function le(e){const t=s(i(e),"watchlist catalog");if(1!==t.version)throw new r("Unsupported watchlist catalog version");const n=c(t.lists,"watchlists",100).map(ce),a=new Set(n.map(e=>e.id));if(a.size!==n.length)throw new r("Duplicate watchlist ID");const o=null===t.activeListId?null:l(t.activeListId,"active watchlist ID",100);if(null!==o&&!a.has(o))throw new r("Active watchlist is missing");return{version:1,revision:d(t.revision,"catalog revision",0,Number.MAX_SAFE_INTEGER,!0),lists:n,activeListId:o}}const de=()=>({version:1,revision:0,lists:[],activeListId:null}),pe=e=>""===e.exchange?e.symbol:`${e.symbol} on ${e.exchange}`,ue={parse:le,conflict:()=>new re};class he extends Error{constructor(){super("The saved drawing templates changed in another session. Reload and retry."),this.name="DrawingTemplateConflictError"}}const fe=/^(style|text|props)\.[A-Za-z][A-Za-z0-9_]{0,63}$/;function me(e){const t=s(e,"template level"),n={ratio:d(t.ratio,"level ratio",-1e6,1e6)};if(void 0!==t.color&&(n.color=l(t.color,"level color",64)),void 0!==t.enabled){if("boolean"!=typeof t.enabled)throw new r("level enabled must be a boolean");n.enabled=t.enabled}return void 0!==t.label&&(n.label=l(t.label,"level label",64,!0)),n}function we(e,t){if("boolean"==typeof e)return e;if("number"==typeof e)return d(e,t,-1e9,1e9);if("string"==typeof e)return l(e,t,256,!0);if(Array.isArray(e))return c(e,t,64).map(me);throw new r(`${t} must be a string, a number, a boolean or a list of levels`)}function ge(e){const t=s(i(e),"template values"),n=Object.keys(t);if(n.length>64)throw new r("template values must be within the 64 setting limit");const a={};for(const e of n){if(!fe.test(e)||"text.value"===e)throw new r(`${e} is not a template setting`);a[e]=we(t[e],e)}return a}const ye=e=>l(e,"drawing tool",100);function ve(e){const t=s(e,"drawing template"),n=d(t.createdAt,"createdAt",0);return{id:l(t.id,"template ID",100),name:l(t.name,"name",120),tool:ye(t.tool),values:ge(t.values),createdAt:n,updatedAt:d(t.updatedAt,"updatedAt",n)}}function Ie(e){const t=s(e,"drawing default");return{tool:ye(t.tool),values:ge(t.values),updatedAt:d(t.updatedAt,"updatedAt",0)}}function be(e){const t=s(i(e),"drawing template catalog");if(1!==t.version)throw new r("Unsupported drawing template catalog version");const n=c(t.templates,"drawing templates",200).map(ve);if(new Set(n.map(e=>e.id)).size!==n.length)throw new r("Duplicate template ID");const a=c(t.defaults,"drawing defaults",200).map(Ie);if(new Set(a.map(e=>e.tool)).size!==a.length)throw new r("Duplicate tool default");return{version:1,revision:d(t.revision,"catalog revision",0,Number.MAX_SAFE_INTEGER,!0),templates:n,defaults:a}}const _e=()=>({version:1,revision:0,templates:[],defaults:[]}),Se={parse:be,conflict:()=>new he},Ae=(e,t)=>e.trim().toLowerCase()===t.trim().toLowerCase();return e.DrawingTemplateConflictError=he,e.DrawingTemplateRepository=class{constructor(e,t,n={}){Object.defineProperty(this,"_catalog",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_now",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._catalog=new $(e,t,Se,_e),this._now=n.now??Date.now,this._id=n.id??M}get namespace(){return this._catalog.namespace}load(){return this._catalog.load()}subscribe(e){return this._catalog.subscribe(e)}async saveTemplate(e,t,n,a){const r=l(e,"name",120),o=ye(t),i=ge(n);return this._catalog.transact(e=>{const t=this._now(),n=e.templates.find(e=>e.tool===o&&Ae(e.name,r));if(n)return n.values=i,n.updatedAt=this._later(n.updatedAt,t),n;const a={id:this._newId(e),name:r,tool:o,values:i,createdAt:t,updatedAt:t};return e.templates.push(a),a},a)}async renameTemplate(e,t,n){const a=l(t,"name",120);return this._catalog.transact(t=>{const n=this._find(t,e);if(t.templates.some(e=>e!==n&&e.tool===n.tool&&Ae(e.name,a)))throw new r(`A template named ${a} already exists for this tool`);return n.name=a,n.updatedAt=this._later(n.updatedAt,this._now()),n},n)}async removeTemplate(e,t){return this._catalog.transact(t=>{const n=this._find(t,e);t.templates=t.templates.filter(e=>e!==n)},t)}async setDefault(e,t,n){const a=ye(e),r=null===t?null:ge(t);return this._catalog.transact(e=>{const t=e.defaults.find(e=>e.tool===a);if(null===r)return void(e.defaults=e.defaults.filter(e=>e!==t));const n=this._later(t?.updatedAt??0,this._now());t?(t.values=r,t.updatedAt=n):e.defaults.push({tool:a,values:r,updatedAt:n})},n)}_find(e,t){const n=l(t,"template ID",100),a=e.templates.find(e=>e.id===n);if(!a)throw new r("Saved drawing template does not exist");return a}_later(e,t){return Math.max(e,d(t,"current time",0))}_newId(e){const t=l(this._id(),"generated template ID",100);if(e.templates.some(e=>e.id===t))throw new r("Generated template ID collision");return t}},e.WORKSPACE_VERSION=1,e.WatchlistConflictError=re,e.WatchlistRepository=class{constructor(e,t,n={}){Object.defineProperty(this,"_catalog",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_now",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._catalog=new $(e,t,ue,de),this._now=n.now??Date.now,this._id=n.id??M}get namespace(){return this._catalog.namespace}load(){return this._catalog.load()}subscribe(e){return this._catalog.subscribe(e)}async createList(e,t=[],n){const a=l(e,"name",120),r=se(i(t));return this._catalog.transact(e=>{const t=this._now(),n={id:this._newId(e),name:a,entries:r,createdAt:t,updatedAt:t};return e.lists.push(n),n},n)}async renameList(e,t,n){const a=l(t,"name",120);return this._catalog.transact(t=>this._touch(this._find(t,e),e=>{e.name=a}),n)}async duplicateList(e,t,n){const a=l(t,"name",120);return this._catalog.transact(t=>{const n=this._find(t,e),r=this._now(),o={id:this._newId(t),name:a,entries:n.entries.map(e=>({...e})),createdAt:r,updatedAt:r};return t.lists.push(o),o},n)}async removeList(e,t){return this._catalog.transact(t=>{const n=this._find(t,e);t.lists=t.lists.filter(e=>e!==n),t.activeListId===n.id&&(t.activeListId=null)},t)}async setActiveList(e,t){return this._catalog.transact(t=>{t.activeListId=null===e?null:this._find(t,e).id},t)}async addEntry(e,t,n={}){const a=ie(i(t));return this._catalog.transact(t=>this._touch(this._find(t,e),e=>{if(e.entries.some(e=>oe(e)===oe(a)))throw new r(`${pe(a)} is already in this list`);e.entries.splice(this._index(n.index??e.entries.length,e.entries.length),0,a)}),n)}async removeEntry(e,t,n){const a=ie(i(t));return this._catalog.transact(t=>this._touch(this._find(t,e),e=>{e.entries.splice(this._position(e,a),1)}),n)}async moveEntry(e,t,n,a){const r=ie(i(t));return this._catalog.transact(t=>this._touch(this._find(t,e),e=>{const[t]=e.entries.splice(this._position(e,r),1);e.entries.splice(this._index(n,e.entries.length),0,t)}),a)}_find(e,t){const n=l(t,"watchlist ID",100),a=e.lists.find(e=>e.id===n);if(!a)throw new r("Saved watchlist does not exist");return a}_touch(e,t){return t(e),e.updatedAt=Math.max(e.updatedAt,d(this._now(),"current time",0)),e}_position(e,t){const n=e.entries.findIndex(e=>oe(e)===oe(t));if(n<0)throw new r(`${pe(t)} is not in this list`);return n}_index(e,t){return Math.max(0,Math.min(t,Math.trunc(d(e,"entry index",-Number.MAX_SAFE_INTEGER))))}_newId(e){const t=l(this._id(),"generated watchlist ID",100);if(e.lists.some(e=>e.id===t))throw new r("Generated watchlist ID collision");return t}},e.WorkspaceConflictError=Q,e.WorkspaceDocumentError=r,e.WorkspaceRepository=class{constructor(e,t,n={}){Object.defineProperty(this,"_catalog",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_now",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._catalog=new $(e,t,Y,te),this._now=n.now??Date.now,this._id=n.id??M}get namespace(){return this._catalog.namespace}load(){return this._catalog.load()}subscribe(e){return this._catalog.subscribe(e)}async createWorkspace(e,t,n){const a=P(t),r=l(e,"name",120);return this._catalog.transact(e=>{const t=this._now(),n=E({...a,kind:"workspace",version:1,id:this._newId(e),name:r,createdAt:t,updatedAt:t});return e.workspaces.push(n),n},n)}async saveWorkspace(e,t,n){const a=P(t);return this._catalog.transact(t=>{const n=this._find(t,"workspace",e),r=E({...n,...a,updatedAt:this._updatedAt(n)});return t.workspaces[t.workspaces.indexOf(n)]=r,r},n)}async createTemplate(e,t,n){const a=A(t),r=l(e,"name",120);return this._catalog.transact(e=>{const t=this._now(),n=T({kind:"indicator-template",version:1,id:this._newId(e),name:r,createdAt:t,updatedAt:t,...a});return e.templates.push(n),n},n)}async saveTemplate(e,t,n){const a=A(t);return this._catalog.transact(t=>{const n=this._find(t,"indicator-template",e),r=T({kind:"indicator-template",version:n.version,id:n.id,name:n.name,createdAt:n.createdAt,updatedAt:this._updatedAt(n),...a});return t.templates[t.templates.indexOf(n)]=r,r},n)}async rename(e,t,n,a){const r=l(n,"name",120);return this._catalog.transact(n=>{const a=this._find(n,e,t);a.name=r,a.updatedAt=this._updatedAt(a)},a)}async duplicate(e,t,n,a){const r=l(n,"name",120);return this._catalog.transact(n=>this._insert(n,this._find(n,e,t),r),a)}async remove(e,t,n){return this._catalog.transact(n=>{this._find(n,e,t),"indicator-template"===e?n.templates=n.templates.filter(e=>e.id!==t):(n.workspaces=n.workspaces.filter(e=>e.id!==t),n.recentWorkspaceIds=n.recentWorkspaceIds.filter(e=>e!==t),n.activeWorkspaceId===t&&(n.activeWorkspaceId=n.recentWorkspaceIds[0]??null))},n)}async openWorkspace(e,t){return this._catalog.transact(t=>{const n=this._find(t,"workspace",e);return t.activeWorkspaceId=n.id,t.recentWorkspaceIds=[n.id,...t.recentWorkspaceIds.filter(e=>e!==n.id)].slice(0,10),n},t)}async setAutosave(e,t){const n=p(e,"autosave");return this._catalog.transact(e=>{e.autosave=n},t)}async importDocument(e,t){const n=ne(e);return this._catalog.transact(e=>this._insert(e,n,n.name),t)}captureIndicatorTemplate(e){return q(e)}planIndicatorTemplateState(e,t,n,a){return Z(e,t,n,a)}async exportDocument(e,t){const n=await this.load();return JSON.stringify(this._find(n,e,t),null,2)}_find(e,t,n){if("workspace"!==t&&"indicator-template"!==t)throw new r("Unsupported document kind");const a=l(n,"document ID",100),o=("workspace"===t?e.workspaces:e.templates).find(e=>e.id===a);if(!o)throw new r(`Saved ${t} does not exist`);return o}_updatedAt(e){return Math.max(e.updatedAt,d(this._now(),"current time",0))}_newId(e){const t=l(this._id(),"generated document ID",100);if([...e.workspaces,...e.templates].some(e=>e.id===t))throw new r("Generated document ID collision");return t}_insert(e,t,n){const a=this._now(),r=ne({...t,name:n,id:this._newId(e),createdAt:a,updatedAt:a});return"workspace"===r.kind?e.workspaces.push(r):e.templates.push(r),r}},e.captureIndicatorTemplate=q,e.createIndexedDbDrawingTemplateStorage=function(e,t="openalgo-chart-drawing-templates"){return ae(e,t,"Drawing template",be,()=>new he)},e.createIndexedDbWatchlistStorage=function(e,t="openalgo-chart-watchlists"){return ae(e,t,"Watchlist",le,()=>new re)},e.createIndexedDbWorkspaceStorage=function(e,t="openalgo-chart-workspaces"){return ae(e,t,"Workspace",ee,()=>new Q)},e.createMemoryDrawingTemplateStorage=function(e={}){return N(e,Se)},e.createMemoryWatchlistStorage=function(e={}){return N(e,ue)},e.createMemoryWorkspaceStorage=function(e={}){return N(e,Y)},e.migrateWidgetWorkspace=function(e,t){const n=s(i(e),"widget");if(1!==n.version||void 0!==n.kind)throw new r("Unsupported widget state");const a=null===n.rail?{}:s(n.rail??{},"rail");return E({kind:"workspace",version:1,id:t.id,name:t.name,createdAt:t.now,updatedAt:t.now,panes:[{id:"p0",symbol:n.symbol,exchange:n.exchange??"",interval:n.interval,chartType:n.chartType,chart:n.chart,magnet:a.magnet??"off",stay:a.stay??!1,...void 0===n.variant?{}:{variant:n.variant},settings:{"widget.theme":u(n.theme,"theme",["light","dark"],"dark")}}],layout:{rows:1,columns:1,slots:[{paneId:"p0",row:0,column:0,rowSpan:1,columnSpan:1}]},activePaneId:"p0"})},e.parseDrawingTemplateCatalog=be,e.parseDrawingTemplateValues=ge,e.parseIndicatorStates=v,e.parseIndicatorTemplate=T,e.parseIndicatorTemplatePayload=A,e.parseWatchlistCatalog=le,e.parseWorkspaceCatalog=ee,e.parseWorkspaceDocument=E,e.parseWorkspacePayload=P,e.planIndicatorTemplate=W,e.planIndicatorTemplateState=Z,e.watchlistKey=oe,e}({},OpenAlgoCharts);
1
+ if("undefined"==typeof OpenAlgoCharts)throw new Error("openalgo-charts.workspace.standalone.js needs openalgo-charts.standalone.js loaded before it");this.OpenAlgoCharts=this.OpenAlgoCharts||{},this.OpenAlgoCharts.workspace=function(e,t){"use strict";function n(e){return"string"==typeof e&&("right"===e||"left"===e||""===e||e.startsWith("overlay:"))}const r={bytes:5242880,nodes:1e5,depth:32},a={bytes:10*r.bytes,nodes:10*r.nodes,depth:r.depth+2};class o extends Error{constructor(e){super(e),this.name="WorkspaceDocumentError"}}const i=new Set(["__proto__","prototype","constructor","apikey","secret","clientsecret","apisecret","password","passwordhash","token","accesstoken","refreshtoken","authtoken","authorization","credentials","credential","auth","armed","oneclick","orders","positions","balances","balance","accountbalance","accountid","account"]);function s(e,t=r){if("string"==typeof e){if(e.length>t.bytes||(new TextEncoder).encode(e).length>t.bytes)throw new o("Document size limit exceeded");try{e=JSON.parse(e)}catch{throw new o("Invalid document JSON")}}let a=0,s=0;const c=new Set,l=(e,r,d=!1,p=!1)=>{if(++a>t.nodes)throw new o("Document node limit exceeded");if(r>t.depth)throw new o("Document depth limit exceeded");if(null===e||"boolean"==typeof e)return e;if("string"==typeof e){if(s+=e.length,s>t.bytes)throw new o("Document size limit exceeded");return e}if("number"==typeof e&&Number.isFinite(e))return e;if("object"!=typeof e)throw new o("Document values must be finite JSON data");if(c.has(e))throw new o("Document contains a cycle");if(!Array.isArray(e)&&![Object.prototype,null].includes(Object.getPrototypeOf(e)))throw new o("Document objects must be plain records");if(d||p)for(const t of Reflect.ownKeys(e)){if(Array.isArray(e)&&"length"===t)continue;const n=Object.getOwnPropertyDescriptor(e,t);if("string"!=typeof t||!n.enumerable||Array.isArray(e)&&(!/^(0|[1-9]\d*)$/.test(t)||Number(t)>=e.length))throw new o((p?"Plot scale map":"Opaque payload")+" properties must survive JSON")}let u;if(c.add(e),Array.isArray(e)){if(e.length>1e5)throw new o("Document array limit exceeded");const t=[];for(let n=0;n<e.length;n++){const a=Object.getOwnPropertyDescriptor(e,String(n));if(!a||!("value"in a))throw new o("Document arrays must contain data values");t.push(l(a.value,r+1,d))}u=t}else{const a={},c=Object.getOwnPropertyDescriptor(e,"settings")?.value,h=!d&&"string"==typeof Object.getOwnPropertyDescriptor(e,"indicatorId")?.value&&"number"==typeof Object.getOwnPropertyDescriptor(e,"paneIndex")?.value&&null!==c&&"object"==typeof c&&!Array.isArray(c);for(const c of Object.keys(e)){const u=c.toLowerCase().replace(/[^a-z0-9_]/g,"").replace(/_/g,"");if(!p&&(i.has(c)||i.has(u))){if(d)throw new o("Opaque payload contains a private workspace field");continue}if(s+=c.length,s>t.bytes)throw new o("Document size limit exceeded");const f=Object.getOwnPropertyDescriptor(e,c);if(!("value"in f))throw new o("Document accessors are not allowed");if(p&&!n(f.value))throw new o("Invalid indicator plot priceScaleId");const m=l(f.value,r+1,d||"payload"===c,h&&"plotPriceScaleIds"===c);p?Object.defineProperty(a,c,{value:m,enumerable:!0,configurable:!0,writable:!0}):a[c]=m}u=a}return c.delete(e),u},d=l(e,0);if((new TextEncoder).encode(JSON.stringify(d)).length>t.bytes)throw new o("Document size limit exceeded");return d}function c(e,t){if(null===e||"object"!=typeof e||Array.isArray(e))throw new o(`${t} must be an object`);return e}function l(e,t,n){if(!Array.isArray(e)||e.length>n)throw new o(`${t} must be an array within the ${n} item limit`);return e}function d(e,t,n=200,r=!1){if("string"!=typeof e||!r&&0===e.trim().length||e.length>n||Array.from(e).some(e=>e.charCodeAt(0)<32))throw new o(`${t} must be ${r?"0":"1"}-${n} characters`);return e.trim()}function p(e,t,n,r=Number.MAX_SAFE_INTEGER,a=!1){if("number"!=typeof e||!Number.isFinite(e)||e<n||e>r||a&&!Number.isInteger(e))throw new o(`${t} must be ${a?"an integer":"a number"} between ${n} and ${r}`);return e}function u(e,t,n){if(void 0===e&&void 0!==n)return n;if("boolean"!=typeof e)throw new o(`${t} must be a boolean`);return e}function h(e,t,n,r){if(void 0===e&&void 0!==r)return r;if("string"!=typeof e||!n.includes(e))throw new o(`${t} is not supported`);return e}function f(e){return!1===e?.removable||!1===e?.listed}const m=31,w=256;function g(e,t){if(e.kind!==t||1!==e.version)throw new o(`Unsupported ${t} kind or version`);const n=p(e.createdAt,"createdAt",0);return{version:1,id:d(e.id,"id",100),name:d(e.name,"name",120),createdAt:n,updatedAt:p(e.updatedAt,"updatedAt",n)}}function y(e,t){if(!n(e))throw new o(`Invalid ${t}`);return e}function v(e,n=!0,r=!0){const a=new Set;return l(e,"indicators",w).map(e=>{const i=c(e,"indicator"),s=c(i.settings,"indicator settings"),f={indicatorId:d(i.indicatorId,"indicatorId"),settings:s,paneIndex:p(i.paneIndex,"indicator paneIndex",0,m,!0)};if(void 0!==i.studyInputs){const e=l(i.studyInputs,"indicator studyInputs",1e5).map(e=>{if("string"!=typeof e||!e.trim())throw new o("Invalid study input key");const t=c(s[e],"study input reference");if("indicator"!==t.kind||3!==Object.keys(t).length)throw new o("Invalid study input reference");const n=d(t.instanceId,"study input instanceId");if("string"!=typeof t.plotKey||!t.plotKey.trim())throw new o("Invalid study input plotKey");return s[e]={kind:"indicator",instanceId:n,plotKey:t.plotKey},e});if(new Set(e).size!==e.length)throw new o("Duplicate study input key");f.studyInputs=e}if(void 0!==i.visible&&(f.visible=u(i.visible,"indicator visibility")),void 0!==i.barSource&&(f.barSource=h(i.barSource,"indicator bar source",["chart","underlying"])),r&&void 0!==i.policy){let e;try{e=t.parseIndicatorPolicy(i.policy)}catch{throw new o("Invalid indicator policy")}Object.keys(e).length&&(f.policy={...e})}if(void 0!==i.priceScaleId&&(f.priceScaleId=y(i.priceScaleId,"indicator priceScaleId")),void 0!==i.plotPriceScaleIds){const e=c(i.plotPriceScaleIds,"indicator plotPriceScaleIds"),t=Object.entries(e).map(([e,t])=>[e,y(t,"indicator plot priceScaleId")]);t.length&&(f.plotPriceScaleIds=Object.fromEntries(t))}if(n&&void 0!==i.instanceId){if(f.instanceId=d(i.instanceId,"indicator instanceId"),a.has(f.instanceId))throw new o("Duplicate indicator instance ID");a.add(f.instanceId)}return f})}function I(e){return v(s(e))}function b(e){const t=!0===e.indicatorRange?.manual;delete e.indicatorRange,delete e.fixedRange,t||(e.autoScale=!0,delete e.range,delete e.ratioLock)}function _(e,n=!1,r){const a=function(e){const n=e.map(e=>c(e,"indicator")),r=n.map(e=>{if(void 0===e.policy)return!1;try{return f(t.parseIndicatorPolicy(e.policy))}catch{throw new o("Invalid indicator policy")}}),a=new Set,i=e=>{const t=e.settings,n=Array.isArray(e.studyInputs)?e.studyInputs:[];return null!==t&&"object"==typeof t&&!Array.isArray(t)&&n.some(e=>{const n="string"==typeof e?t[e]:void 0;return null!==n&&"object"==typeof n&&!Array.isArray(n)&&"string"==typeof n.instanceId&&a.has(n.instanceId)})};for(let e=!0;e;)e=!1,n.forEach((t,n)=>{!r[n]&&i(t)&&(r[n]=e=!0),r[n]&&"string"==typeof t.instanceId&&!a.has(t.instanceId)&&(a.add(t.instanceId),e=!0)});return{kept:e.filter((e,t)=>!r[t]),left:a}}(l(e,"indicators",w)),i=a.kept;for(const e of a.left)r?.add(e);const s=i.some(e=>{const t=c(e,"indicator").studyInputs;return Array.isArray(t)&&t.length>0}),d=v(i,s||n,!1);if(n&&d.some(e=>void 0===e.instanceId))throw new o("Template layout requires every indicator instance ID");if(!s)return d;const p=new Map(d.flatMap((e,t)=>void 0===e.instanceId?[]:[[e.instanceId,t]])),u=d.map((e,t)=>(e.studyInputs??[]).map(n=>{const r=e.settings[n],a=p.get(r.instanceId);if(void 0===a)throw new o(`External study dependency: ${r.instanceId}`);if(a===t)throw new o("A study cannot depend on itself");return a})),h=new Set,m=new Set,g=e=>{if(h.has(e))throw new o("Study dependencies contain a cycle");if(!m.has(e)){h.add(e);for(const t of u[e])g(t);h.delete(e),m.add(e)}};for(let e=0;e<d.length;e++)g(e);return d}function S(e){return l(e,"chart panes",32).map(e=>{try{const n=t.parsePaneState(e);p(n.weight,"pane weight",Number.MIN_VALUE);for(const e of[n.priceScale,...Object.values(n.scales??{})])if(e){if(p(e.marginTop,"marginTop",0,1),p(e.marginBottom,"marginBottom",0,1),p(e.minMove,"minMove",0),e.marginTop+e.marginBottom>=1)throw new o("Price scale margins leave no chart area");for(const t of[e.range,e.fixedRange])if(t&&(p(t.min,"range.min",-Number.MAX_SAFE_INTEGER),p(t.max,"range.max",t.min),t.max===t.min))throw new o("Price scale range must have positive width")}return n}catch(e){throw new o(e instanceof Error?e.message:"Invalid pane scale state")}})}function A(e){if(Array.isArray(e))return{indicators:_(e)};const t=c(e,"indicator template payload"),n=new Set,r=_(t.indicators,void 0!==t.layout,n);if(void 0===t.layout)return{indicators:r};const a=c(t.layout,"indicator template layout"),i=S(a.panes);if(!i.length)throw new o("Template layout needs pane zero");const s=new Map(r.map(e=>[e.instanceId,e]));for(const e of r)if(e.paneIndex>=i.length)throw new o("Template indicator pane is missing");for(const e of i)for(const t of[e.priceScale,...Object.values(e.scales??{})]){const e=t?.indicatorRange;if(t&&e&&n.has(e.instanceId))b(t);else if(t?.indicatorRange&&!s.has(t.indicatorRange.instanceId))throw new o("Template scale range owner is missing")}const u=(e,t)=>{if("right"!==t&&!i[e].scales?.[t])throw new o("Template plot or primary scale is missing")},h=new Map,f=l(a.plots,"template plot bindings",1e5).filter(e=>{const t=c(e,"template plot binding").instanceId;return"string"!=typeof t||!n.has(t)}).map(e=>{const t=c(e,"template plot binding"),n=d(t.instanceId,"template plot instanceId"),r=s.get(n);if(!r)throw new o("Template plot indicator is missing");if("string"!=typeof t.plotKey)throw new o("Template plot key must be a string");const a=t.plotKey,l=p(t.paneIndex,"template plot paneIndex",0,i.length-1,!0);if(0!==l&&l!==r.paneIndex)throw new o("Template plot belongs to another pane");const f=y(t.scaleId,"template plot scaleId");u(l,f);const m=h.get(n)??new Map;if(m.has(a))throw new o("Duplicate template plot binding");return m.set(a,f),h.set(n,m),{instanceId:n,plotKey:a,paneIndex:l,scaleId:f}});for(const e of r)for(const[t,n]of Object.entries(e.plotPriceScaleIds??{}))if(h.get(e.instanceId)?.get(t)!==n)throw new o("Template plot override needs a matching scale binding");const m={indicators:r,layout:{panes:i,plots:f}};if(void 0!==a.primaryScaleId){const e=y(a.primaryScaleId,"template primaryScaleId");u(0,e),m.layout.primaryScaleId=e}return m}function k(e){return A(s(e))}function x(e,n){const r=c(e,"chart");if(1!==r.version&&2!==r.version)throw new o("Unsupported chart version");const a={version:2===r.version?2:1};void 0!==r.timezone&&(a.timezone=d(r.timezone,"timezone",100));for(const e of["navigation","canvas","statusLine","watermark","trading","events","axisChrome"])void 0!==r[e]&&Object.assign(a,{[e]:c(r[e],e)});if(a.axisChrome&&delete a.axisChrome.clock,void 0!==r.viewport){const e=c(r.viewport,"viewport"),t=p(e.from,"viewport.from",-Number.MAX_SAFE_INTEGER);a.viewport={from:t,to:p(e.to,"viewport.to",t)}}if(void 0!==r.barSpacing&&(a.barSpacing=p(r.barSpacing,"barSpacing",Number.MIN_VALUE)),void 0!==r.grid){const e=c(r.grid,"grid");a.grid={vertLines:u(e.vertLines,"vertical grid"),horzLines:u(e.horzLines,"horizontal grid")}}if(void 0!==r.crosshairMode&&(a.crosshairMode=h(r.crosshairMode,"crosshairMode",["normal","magnet"])),void 0!==r.crosshairSnapToBar&&(a.crosshairSnapToBar=u(r.crosshairSnapToBar,"crosshairSnapToBar")),void 0!==r.priceOnlyAutoScale&&(a.priceOnlyAutoScale=u(r.priceOnlyAutoScale,"priceOnlyAutoScale")),void 0!==r.indicatorLegendCollapsed&&(a.indicatorLegendCollapsed=u(r.indicatorLegendCollapsed,"indicatorLegendCollapsed")),void 0!==r.indicators&&(a.indicators=v(r.indicators,!0,n)),void 0!==r.sourceAbove&&(a.sourceAbove=d(r.sourceAbove,"sourceAbove")),void 0!==r.alerts)try{a.alerts=t.parseAlertsDocument(r.alerts)}catch(e){throw new o(e instanceof Error?e.message:"Invalid alert document")}if(void 0!==r.drawings){if(null===r.drawings||"object"!=typeof r.drawings)throw new o("drawings must be a document or array");n||function(e){const t=Array.isArray(e)?e:c(e,"drawings").drawings;if(Array.isArray(t))for(const e of t)null===e||"object"!=typeof e||Array.isArray(e)||delete e.policy}(r.drawings),a.drawings=r.drawings}if(void 0!==r.panes&&(a.panes=S(r.panes)),void 0!==r.primaryPane){if(2!==r.version)throw new o("A moved price pane needs chart version 2");if(a.primaryPane=p(r.primaryPane,"primaryPane",0,m,!0),!a.panes||a.primaryPane>=a.panes.length)throw new o("The price pane slot must name a saved pane")}return void 0!==r.series&&(a.series=l(r.series,"series descriptors",512).map(e=>{const t=c(e,"series"),n=t.priceScaleId;if("string"!=typeof n)throw new o("priceScaleId must be a string");const r={type:d(t.type,"series type"),style:c(t.style,"series style"),paneIndex:p(t.paneIndex,"series paneIndex",0,m,!0),priceScaleId:n};return void 0!==t.transform&&(r.transform=function(e){const t=c(e,"series transform"),n={type:d(t.type,"series transform type",100)};if(void 0===t.options)return n;const r=c(t.options,"series transform options");for(const e of Object.values(r))if("string"!=typeof e&&("number"!=typeof e||!Number.isFinite(e)))throw new o("Series transform options must be finite numbers or text");return n.options=r,n}(t.transform)),r})),a}function D(e,t){const n={crosshair:u(e.crosshair,`${t}crosshair sync`,!0),viewport:u(e.viewport,`${t}viewport sync`,!0),symbol:u(e.symbol,`${t}symbol sync`,!1),interval:u(e.interval,`${t}interval sync`,!1)};for(const r of["appearance","chartType","drawings"])void 0!==e[r]&&(n[r]=u(e[r],`${t}${r} sync`));return void 0!==e.whenMissing&&(n.whenMissing=h(e.whenMissing,`${t}whenMissing`,["nearest","hide"])),n}function O(e,n){const r=l(e.panes,"panes",16).map(e=>function(e,n){const r=c(e,"workspace pane"),a=c(r.settings??{},"settings");for(const e of Object.values(a))if(!["string","number","boolean"].includes(typeof e))throw new o("Chart settings must be scalar values");const i=l(r.comparisons??[],"comparisons",32).map(e=>{const t=c(e,"comparison"),n={id:d(t.id,"comparison id",100),symbol:d(t.symbol,"comparison symbol"),exchange:d(t.exchange,"comparison exchange",200,!0),visible:u(t.visible,"comparison visibility",!0)};return void 0!==t.color&&(n.color=d(t.color,"comparison color",200)),n});if(new Set(i.map(e=>e.id)).size!==i.length)throw new o("Duplicate comparison ID");const s={id:d(r.id,"pane id",100),symbol:d(r.symbol,"symbol"),exchange:d(r.exchange,"exchange",200,!0),interval:d(r.interval,"interval",100),chartType:d(r.chartType,"chartType",100),chart:x(r.chart,n),settings:a,volume:u(r.volume,"volume",!0),magnet:h(r.magnet,"magnet",["off","weak","strong"],"off"),stay:u(r.stay,"stay",!1),comparisons:i,comparisonMode:h(r.comparisonMode,"comparisonMode",["price","percent"],"percent")};if(void 0!==r.historyPeriod&&(s.historyPeriod=d(r.historyPeriod,"historyPeriod",100)),void 0!==r.variant){let e;try{e=t.normalizeDataVariant(r.variant)}catch(e){throw new o(e instanceof Error?e.message:"Invalid data variant")}e&&(s.variant={...e})}return void 0!==r.linkGroup&&(s.linkGroup=d(r.linkGroup,"linkGroup",100)),s}(e,!1!==n?.keepPolicy));if(0===r.length)throw new o("A workspace needs at least one pane");const a=new Set(r.map(e=>e.id));if(a.size!==r.length)throw new o("Duplicate pane ID");const i=d(e.activePaneId,"activePaneId",100);if(!a.has(i))throw new o("Focused pane is missing");const s=c(e.layout,"layout"),f=p(s.rows,"rows",1,8,!0),m=p(s.columns,"columns",1,8,!0),w=new Set,g=new Set,y=l(s.slots,"layout slots",16).map(e=>{const t=c(e,"slot"),n={paneId:d(t.paneId,"slot paneId",100),row:p(t.row,"row",0,f-1,!0),column:p(t.column,"column",0,m-1,!0),rowSpan:p(t.rowSpan??1,"rowSpan",1,f,!0),columnSpan:p(t.columnSpan??1,"columnSpan",1,m,!0)};if(!a.has(n.paneId)||w.has(n.paneId))throw new o("Invalid or duplicate layout pane ID");if(w.add(n.paneId),n.row+n.rowSpan>f||n.column+n.columnSpan>m)throw new o("Layout slot is outside the grid");for(let e=n.row;e<n.row+n.rowSpan;e++)for(let t=n.column;t<n.column+n.columnSpan;t++){const n=e*m+t;if(g.has(n))throw new o("Layout slots overlap");g.add(n)}return n});if(w.size!==r.length)throw new o("Every pane needs one layout slot");const v=c(e.sync??{},"sync"),I={layout:{rows:f,columns:m,slots:y},panes:r,activePaneId:i,sync:D(v,"")};void 0!==v.groups&&(I.sync.groups=function(e){const t=new Set;return l(e,"link groups",16).map(e=>{const n=c(e,"link group"),r=d(n.id,"link group id",100);if(t.has(r))throw new o("Duplicate link group ID");return t.add(r),{id:r,name:d(n.name,"link group name",120),...D(n,"link group ")}})}(v.groups));const b=new Set(I.sync.groups?.map(e=>e.id));for(const e of r)if(void 0!==e.linkGroup&&!b.has(e.linkGroup))throw new o(`Link group ${e.linkGroup} is not declared`);void 0!==s.preset&&(I.layout.preset=d(s.preset,"layout preset",100));for(const[e,t]of[["rowWeights",f],["columnWeights",m]]){if(void 0===s[e])continue;const n=l(s[e],e,8).map(t=>p(t,e,Number.MIN_VALUE,1e3));if(n.length!==t)throw new o(`${e} must match the number of grid tracks`);I.layout[e]=n}return I}function P(e,t){const n=c(s(e),"workspace");return{kind:"workspace",...g(n,"workspace"),...O(n,t)}}function E(e,t){return O(c(s(e),"workspace"),t)}function T(e){const t=c(s(e),"indicator template");return{kind:"indicator-template",...g(t,"indicator-template"),...A(t)}}const j=e=>s(e,a);function M(){if(!globalThis.crypto?.randomUUID)throw new o("Supply an ID factory when crypto.randomUUID is unavailable");return globalThis.crypto.randomUUID()}class ${constructor(e,t,n,r){Object.defineProperty(this,"_storage",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"_kind",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"_empty",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"namespace",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_listeners",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"_queue",{enumerable:!0,configurable:!0,writable:!0,value:Promise.resolve()}),this.namespace=d(t,"storage namespace")}async load(){return await this._queue,this._read()}subscribe(e){return this._listeners.add(e),()=>{this._listeners.delete(e)}}transact(e,t={}){const{signal:n}=t,r=void 0===t.expectedRevision?void 0:p(t.expectedRevision,"expected revision",0,Number.MAX_SAFE_INTEGER,!0),a=this._queue.then(async()=>{n?.throwIfAborted();const t=await this._read();if(n?.throwIfAborted(),void 0!==r&&t.revision!==r)throw this._kind.conflict();const a=t.revision,o=e(t);t.revision++;const i=this._kind.parse(t);n?.throwIfAborted(),await this._storage.write(this.namespace,i,a,{signal:n});for(const e of Array.from(this._listeners))try{e(j(i))}catch(e){queueMicrotask(()=>{throw e})}return void 0===o?o:j(o)});return this._queue=a.then(()=>{},()=>{}),a}async _read(){const e=await this._storage.read(this.namespace);return null===e?this._empty():this._kind.parse(e)}}function N(e,t){const n=new Map(Object.entries(e).map(([e,t])=>[e,j(t)]));return{async read(e){const t=n.get(d(e,"storage namespace"));return void 0===t?null:j(t)},async write(e,r,a,i){i?.signal?.throwIfAborted();const s=d(e,"storage namespace"),c=p(a,"expected revision",0,Number.MAX_SAFE_INTEGER,!0),l=t.parse(r);if(l.revision!==c+1)throw new o("A write must advance the catalog revision by one");const u=n.get(s);if((void 0===u?0:t.parse(u).revision)!==c)throw t.conflict();n.set(s,l)}}}function W(e,t,n,r,a,i=0){if("replace"!==n&&"append"!==n)throw new o("Unsupported indicator template mode");if(!Number.isInteger(i)||i<0||i>m)throw new o("Invalid price pane slot");const c=I(e),l=_(s(t));if(l.some(e=>e.studyInputs?.length)&&z(c,l),"append"===n){const e=Math.max(0,...c.map(e=>e.paneIndex));if(!Number.isInteger(a)||a<=Math.max(e,i)||a>32)throw new o("Invalid next indicator pane");const t=[...new Set(l.map(e=>e.paneIndex).filter(e=>e>0))].sort((e,t)=>e-t);for(const e of l)if(e.paneIndex=e.paneIndex>0?a+t.indexOf(e.paneIndex):i,e.paneIndex>m)throw new o("Indicator pane limit exceeded")}else if(i>0)for(const e of l)e.paneIndex=C(e.paneIndex,i);const d="replace"===n?c.filter(e=>f(e.policy)):[],p=new Set(d.map(e=>e.paneIndex).filter(e=>e!==i));if(p.size){const e=[...new Set(l.map(e=>e.paneIndex).filter(e=>e!==i))].sort((e,t)=>e-t),t=new Map;let n=-1;for(const r of e){do{n++}while(p.has(n)||n===i);t.set(r,n)}for(const e of l)e.paneIndex=t.get(e.paneIndex)??e.paneIndex;if(n>m)throw new o("Indicator pane limit exceeded")}const u="replace"===n?[...d,...l]:[...c,...l];return R(u,r),u}function R(e,t){if(e.length>w)throw new o("At most 256 indicator instances are supported");const n=[...new Set(e.filter(e=>!t.has(e.indicatorId)).map(e=>e.indicatorId))];if(n.length)throw new o(`Missing indicators: ${n.join(", ")}`)}function L(e,t){return e===t?0:e<t?e+1:e}function C(e,t){return 0===e?t:e<=t?e-1:e}function z(e,t){const n=new Map;if(!t.length)return n;const r=new Set([...e,...t].flatMap(e=>void 0===e.instanceId?[]:[e.instanceId]));for(const t of e)for(const e of t.studyInputs??[])r.add(t.settings[e].instanceId);if(!globalThis.crypto?.getRandomValues)throw new o("Random IDs are unavailable for connected template copies");const a=Array.from(globalThis.crypto.getRandomValues(new Uint32Array(4)),e=>e.toString(16).padStart(8,"0")).join("");let i=1;for(const e of t){let t;do{t=`template-study-${a}-${i++}`}while(r.has(t));r.add(t),void 0!==e.instanceId&&n.set(e.instanceId,t),e.instanceId=t}for(const e of t)for(const t of e.studyInputs??[]){const r=e.settings[t];e.settings[t]={...r,instanceId:n.get(r.instanceId)}}return n}function G(e){return[["right",e.priceScale],...Object.entries(e.scales??{})]}function U(e,t){return"right"===t?e.priceScale:e.scales?.[t]}function F(e,t,n){const r=e.primarySeries();if(!r)return;const a=r.priceScale();return G(n).find(([n])=>e.panes()[t].scaleFor(n)===a)?.[0]}function K(e,t){return[e[t],...e.filter((e,n)=>n!==t)]}function X(e,t){const n=[];return e.forEach((e,r)=>{n[C(r,t)]=e}),n}function q(e){const n=e.getState(),r=n.panes;if(!r?.length)throw new o("Cannot capture a destroyed chart");const a=e.primaryPaneIndex(),i=K(r,a),s=[];for(const n of e.indicators())for(const r of t.getIndicator(n.indicatorId).plots){const t=n.series(r.key),i=n.plotPriceScaleId(r.key);if(!t||null===e.seriesType(t)||null===i)throw new o("Cannot capture a removed indicator plot");s.push({instanceId:n.id,plotKey:r.key,paneIndex:!0===r.overlay?0:L(n.paneIndex,a),scaleId:i})}const c={panes:i,plots:s},l=F(e,a,i[0]);void 0!==l&&(c.primaryScaleId=l);return k({indicators:(n.indicators??[]).map(e=>({...e,paneIndex:L(e.paneIndex,a)})),layout:c})}function B(e,t,n){const r=e.plots.find(e=>!0!==e.overlay),a=r?n.find(e=>e.plotKey===r.key).scaleId:t.priceScaleId??"right";for(const r of e.fills??[]){const e=!0===r.overlay?0:t.paneIndex,i=r.between.map(t=>n.find(e=>e.plotKey===t)??{paneIndex:e,scaleId:!0===r.overlay?"right":a});if(i.some(t=>t.paneIndex!==e)||i[0].scaleId!==i[1].scaleId)throw new o("Template fill endpoints must share their pane and scale")}}function V(e,n,r){const a=t.parsePaneState({weight:1,priceScale:e}).priceScale;return r?a.indicatorRange&&(a.indicatorRange.instanceId=n.get(a.indicatorRange.instanceId)):(a.autoScale=!0,delete a.range,delete a.ratioLock,a.indicatorRange&&(delete a.indicatorRange,delete a.fixedRange)),a}function J(e,t){for(const n of e)for(const[,e]of G(n)){const n=e.indicatorRange;n&&t.has(n.instanceId)&&b(e)}}function Z(e,n,r,a={}){if("replace"!==r&&"append"!==r)throw new o("Unsupported indicator template mode");const i=e.primaryPaneIndex(),l=function(e,n,r,a,i){const l=c(s(a),"template apply options"),d=h(l.scalePolicy,"scale policy",["copy","share"],"copy"),p="preserve"===h(l.rangePolicy,"range policy",["auto","preserve"],"auto"),u=k(n),w=e.getState();if(!w.panes?.length)throw new o("Cannot plan for a destroyed chart");const g={...w,panes:K(w.panes,i),indicators:(w.indicators??[]).map(e=>({...e,paneIndex:L(e.paneIndex,i)}))},y=new Set(t.registeredIndicators().map(e=>e.id));if(!u.layout)return{indicators:W(g.indicators,u.indicators,r,y,g.panes.length)};const v=u.layout,b=u.indicators,_=I(g.indicators??[]),S="replace"===r?_.filter(e=>f(e.policy)):[],A="append"===r?[..._,...b]:[...S,...b];R(A,y);const x=function(e,n){const r=new Map;for(const e of n.plots){const t=r.get(e.instanceId)??[];t.push(e),r.set(e.instanceId,t)}for(const n of e){const a=t.getIndicator(n.indicatorId),i=r.get(n.instanceId)??[],s=a.inputs.filter(e=>"source"===e.type&&"string"!=typeof(Object.prototype.hasOwnProperty.call(n.settings,e.key)?n.settings[e.key]:e.default)),c=new Set(n.studyInputs??[]);if(s.length!==c.size||s.some(e=>!c.has(e.key)||"source"!==e.type||!0!==e.allowStudyOutputs))throw new o("Template dependency metadata disagrees with its source inputs");for(const r of c){const a=n.settings[r],i=e.find(e=>e.instanceId===a.instanceId),s=t.getIndicator(i.indicatorId).plots.filter(e=>e.key===a.plotKey);if(1!==s.length||void 0!==s[0].ohlc)throw new o("Template study source must identify one declared scalar plot")}if(i.length!==a.plots.length)throw new o("Template needs every declared plot binding");for(const e of i){const t=a.plots.find(t=>t.key===e.plotKey);if(!t||e.paneIndex!==(!0===t.overlay?0:n.paneIndex))throw new o("Template plot key or pane disagrees with its descriptor")}B(a,n,i)}return r}(b,v),D="replace"===r?function(e){const n=e.panes().map(e=>e.series().length),r=e.primaryPaneIndex();for(const a of e.indicators())for(const o of t.getIndicator(a.indicatorId).plots){const t=a.series(o.key);t&&null!==e.seriesType(t)&&n[!0===o.overlay?r:a.paneIndex]--}return new Set(n.flatMap((e,t)=>e>0?[L(t,r)]:[]))}(e):new Set;for(const e of S)e.paneIndex>0&&D.add(e.paneIndex);const O={preserveScaleFormats:g.panes.flatMap((e,t)=>0===t||"append"===r||D.has(t)?G(e).map(([e])=>({paneIndex:t,scaleId:e})):[])};if("append"===r&&!b.length)return{indicators:_,restoreOptions:O};const P=F(e,i,g.panes[0]),E=g.panes.map(e=>t.parsePaneState(e));"replace"===r&&J(E,new Set(_.filter(e=>!S.includes(e)).flatMap(e=>e.instanceId?[e.instanceId]:[])));const T=function(e,t,n){const r=new Map([[0,0]]);let a=n;for(const n of[...new Set(e.map(e=>e.paneIndex).filter(e=>e>0))].sort((e,t)=>e-t)){for(;t.has(a);)a++;if(a>m)throw new o("Indicator pane limit exceeded");r.set(n,a++)}return r}(b,D,"append"===r?E.length:1),j=b.map(e=>e.instanceId),M=z(_,b),$=E[0],N=v.panes[0];!function(e,t,n,r){const a=e[0],i=t[0];for(const[s,c]of n){if(!s)continue;const n=t[s],l=n.weight/i.weight*a.weight;if(!(l>0&&Number.isFinite(l)))throw new o("Template pane weight is not representable");const d=r(n);e[c]={weight:l,priceScale:d[0][1],...d.length>1?{scales:Object.fromEntries(d.slice(1))}:{}}}}(E,v.panes,T,e=>G(e).map(([e,t])=>[e,V(t,M,p)]));const C=new Set(G($).map(([e])=>e)),X=new Map,q=[];let Z=1;const H=(e,t)=>{if(e>0)return t;const n=X.get(t);if(void 0!==n)return n;if(t===v.primaryScaleId&&void 0!==P)return X.set(t,P),P;let r=t;if("copy"===d)do{r=`overlay:template-scale-${b[0].instanceId}-${Z++}`}while(U($,r));if(X.set(t,r),!U($,r)){const e=U(N,t)??{marginTop:.1,marginBottom:.1,minMove:0,minPrecision:0,mode:"linear",inverted:!1,autoScale:!0},n=V(e,M,p);"right"===r?$.priceScale=n:($.scales??($.scales={}),$.scales[r]=n),"copy"===d&&q.push({id:r,source:{...e,placement:e.placement??{side:"left"===t||"right"===t?t:"hidden",order:0}}})}return r};b.forEach((e,n)=>{const r=j[n],a=e.paneIndex,o=(x.get(r)??[]).map(e=>[e.plotKey,H(e.paneIndex,e.scaleId)]);o.length&&(e.plotPriceScaleIds=Object.fromEntries(o)),void 0!==e.priceScaleId?e.priceScaleId=H(a,e.priceScaleId):t.getIndicator(e.indicatorId).plots.some(e=>!0!==e.overlay)||(e.priceScaleId=H(a,"right")),e.paneIndex=T.get(a),B(t.getIndicator(e.indicatorId),e,(x.get(r)??[]).map(t=>({...t,paneIndex:T.get(t.paneIndex),scaleId:e.plotPriceScaleIds[t.plotKey]})))});for(const e of["left","right","hidden"]){let t=Math.max(-1,...G($).filter(([e])=>C.has(e)).map(([e,t])=>t.placement??{side:"left"===e||"right"===e?e:"hidden",order:0}).filter(t=>t.side===e).map(e=>e.order))+1;for(const n of q.filter(t=>t.source.placement.side===e).sort((e,t)=>e.source.placement.order-t.source.placement.order))U($,n.id).placement={side:e,order:t++}}return{indicators:A,panes:E,restoreOptions:O}}(e,n,r,a,i);if(0===i)return l;const d={indicators:l.indicators.map(e=>({...e,paneIndex:C(e.paneIndex,i)})),panes:l.panes?X(l.panes,i):H(e,r),primaryPane:i};return l.restoreOptions&&(d.restoreOptions={preserveScaleFormats:(l.restoreOptions.preserveScaleFormats??[]).map(e=>({...e,paneIndex:C(e.paneIndex,i)}))}),d}function H(e,n){const r=e.getState(),a=(r.panes??[]).map(e=>t.parsePaneState(e));return"replace"===n&&J(a,new Set((r.indicators??[]).flatMap(e=>e.instanceId?[e.instanceId]:[]))),a}class Q extends Error{constructor(){super("The saved workspace changed in another session. Reload and retry."),this.name="WorkspaceConflictError"}}const Y={parse:ee,conflict:()=>new Q};function ee(e){const t=c(s(e,a),"workspace catalog");if(1!==t.version)throw new o("Unsupported workspace catalog version");const n=l(t.workspaces,"workspaces",100).map(e=>P(e)),r=l(t.templates,"templates",100).map(T),i=[...n,...r].map(e=>e.id);if(new Set(i).size!==i.length)throw new o("Duplicate document ID");const h=new Set(n.map(e=>e.id)),f=l(t.recentWorkspaceIds,"recent workspaces",10).map(e=>d(e,"recent workspace ID",100));if(new Set(f).size!==f.length||f.some(e=>!h.has(e)))throw new o("Invalid recent workspace IDs");const m=null===t.activeWorkspaceId?null:d(t.activeWorkspaceId,"active workspace ID",100);if(null!==m&&!h.has(m))throw new o("Active workspace is missing");return{version:1,revision:p(t.revision,"catalog revision",0,Number.MAX_SAFE_INTEGER,!0),workspaces:n,templates:r,recentWorkspaceIds:f,activeWorkspaceId:m,autosave:u(t.autosave,"autosave")}}function te(){return{version:1,revision:0,workspaces:[],templates:[],recentWorkspaceIds:[],activeWorkspaceId:null,autosave:!1}}function ne(e,t){const n=c(s(e),"document");if("workspace"===n.kind)return P(n,t);if("indicator-template"===n.kind)return T(n);throw new o("Unsupported document kind")}function re(e,t,n,r,a){const i=d(t,"database name");let s=null,c=null,l=!1;const u=()=>new Error(`${n} storage is closed. Create a new adapter to reconnect.`);function h(){return l?Promise.reject(u()):s||(s=new Promise((t,r)=>{const a=e.open(i,1);let o=!1;a.onupgradeneeded=()=>{a.result.objectStoreNames.contains("catalogs")||a.result.createObjectStore("catalogs")},a.onblocked=()=>{o=!0,r(new Error(`${n} database is blocked by another session. Close that session and retry.`))},a.onerror=()=>{o=!0,r(a.error??new Error(`Cannot open ${n.toLowerCase()} database`))},a.onsuccess=()=>{const e=a.result;if(l||o)return e.close(),void r(u());c=e,e.onversionchange=()=>{l=!0,e.close(),c=null},e.onclose=()=>{l=!0,c=null},t(e)}}).catch(e=>{throw s=null,e}),s)}return{async read(e){const t=d(e,"storage namespace"),r=await h();return new Promise((e,a)=>{const o=r.transaction("catalogs","readonly"),i=o.objectStore("catalogs").get(t);let s=null;i.onsuccess=()=>{s=i.result??null},o.oncomplete=()=>e(s),o.onabort=()=>a(o.error??new Error(`${n} read was aborted`))})},async write(e,t,i,s){const c=s?.signal;c?.throwIfAborted();const l=d(e,"storage namespace"),u=p(i,"expected revision",0,Number.MAX_SAFE_INTEGER,!0),f=r(t);if(f.revision!==u+1)throw new o("A write must advance the catalog revision by one");const m=await h();return c?.throwIfAborted(),new Promise((e,t)=>{const o=m.transaction("catalogs","readwrite"),i=o.objectStore("catalogs"),s=i.get(l);let d;const p=()=>{try{o.abort(),d=c?.reason}catch{}},h=()=>c?.removeEventListener("abort",p);c?.addEventListener("abort",p,{once:!0}),s.onsuccess=()=>{try{const e=s.result;if((void 0===e?0:r(e).revision)!==u)throw a();i.put(f,l)}catch(e){d=e,o.abort()}},o.oncomplete=()=>{h(),e()},o.onabort=()=>{h(),t(d??o.error??new Error(`${n} save was aborted`))}})},async close(){l=!0,c&&(c.close(),c=null),s&&await s.catch(()=>{})}}}class ae extends Error{constructor(){super("The saved watchlists changed in another session. Reload and retry."),this.name="WatchlistConflictError"}}function oe(e){return JSON.stringify([e.symbol,e.exchange])}function ie(e){const t=c(e,"watchlist entry");return{symbol:d(t.symbol,"symbol",64),exchange:d(t.exchange,"exchange",32,!0)}}function se(e){const t=l(e,"watchlist entries",500).map(ie);if(new Set(t.map(oe)).size!==t.length)throw new o("Duplicate watchlist entry");return t}function ce(e){const t=c(e,"watchlist"),n=p(t.createdAt,"createdAt",0);return{id:d(t.id,"watchlist ID",100),name:d(t.name,"name",120),entries:se(t.entries),createdAt:n,updatedAt:p(t.updatedAt,"updatedAt",n)}}function le(e){const t=c(s(e,a),"watchlist catalog");if(1!==t.version)throw new o("Unsupported watchlist catalog version");const n=l(t.lists,"watchlists",100).map(ce),r=new Set(n.map(e=>e.id));if(r.size!==n.length)throw new o("Duplicate watchlist ID");const i=null===t.activeListId?null:d(t.activeListId,"active watchlist ID",100);if(null!==i&&!r.has(i))throw new o("Active watchlist is missing");return{version:1,revision:p(t.revision,"catalog revision",0,Number.MAX_SAFE_INTEGER,!0),lists:n,activeListId:i}}const de=()=>({version:1,revision:0,lists:[],activeListId:null}),pe=e=>""===e.exchange?e.symbol:`${e.symbol} on ${e.exchange}`,ue={parse:le,conflict:()=>new ae};class he extends Error{constructor(){super("The saved drawing templates changed in another session. Reload and retry."),this.name="DrawingTemplateConflictError"}}const fe=/^(style|text|props)\.[A-Za-z][A-Za-z0-9_]{0,63}$/;function me(e){const t=c(e,"template level"),n={ratio:p(t.ratio,"level ratio",-1e6,1e6)};if(void 0!==t.color&&(n.color=d(t.color,"level color",64)),void 0!==t.enabled){if("boolean"!=typeof t.enabled)throw new o("level enabled must be a boolean");n.enabled=t.enabled}return void 0!==t.label&&(n.label=d(t.label,"level label",64,!0)),n}function we(e,t){if("boolean"==typeof e)return e;if("number"==typeof e)return p(e,t,-1e9,1e9);if("string"==typeof e)return d(e,t,256,!0);if(Array.isArray(e))return l(e,t,64).map(me);throw new o(`${t} must be a string, a number, a boolean or a list of levels`)}function ge(e){const t=c(s(e),"template values"),n=Object.keys(t);if(n.length>64)throw new o("template values must be within the 64 setting limit");const r={};for(const e of n){if(!fe.test(e)||"text.value"===e)throw new o(`${e} is not a template setting`);r[e]=we(t[e],e)}return r}const ye=e=>d(e,"drawing tool",100);function ve(e){const t=c(e,"drawing template"),n=p(t.createdAt,"createdAt",0);return{id:d(t.id,"template ID",100),name:d(t.name,"name",120),tool:ye(t.tool),values:ge(t.values),createdAt:n,updatedAt:p(t.updatedAt,"updatedAt",n)}}function Ie(e){const t=c(e,"drawing default");return{tool:ye(t.tool),values:ge(t.values),updatedAt:p(t.updatedAt,"updatedAt",0)}}function be(e){const t=c(s(e,a),"drawing template catalog");if(1!==t.version)throw new o("Unsupported drawing template catalog version");const n=l(t.templates,"drawing templates",200).map(ve);if(new Set(n.map(e=>e.id)).size!==n.length)throw new o("Duplicate template ID");const r=l(t.defaults,"drawing defaults",200).map(Ie);if(new Set(r.map(e=>e.tool)).size!==r.length)throw new o("Duplicate tool default");return{version:1,revision:p(t.revision,"catalog revision",0,Number.MAX_SAFE_INTEGER,!0),templates:n,defaults:r}}const _e=()=>({version:1,revision:0,templates:[],defaults:[]}),Se={parse:be,conflict:()=>new he},Ae=(e,t)=>e.trim().toLowerCase()===t.trim().toLowerCase();return e.DrawingTemplateConflictError=he,e.DrawingTemplateRepository=class{constructor(e,t,n={}){Object.defineProperty(this,"_catalog",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_now",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._catalog=new $(e,t,Se,_e),this._now=n.now??Date.now,this._id=n.id??M}get namespace(){return this._catalog.namespace}load(){return this._catalog.load()}subscribe(e){return this._catalog.subscribe(e)}async saveTemplate(e,t,n,r){const a=d(e,"name",120),o=ye(t),i=ge(n);return this._catalog.transact(e=>{const t=this._now(),n=e.templates.find(e=>e.tool===o&&Ae(e.name,a));if(n)return n.values=i,n.updatedAt=this._later(n.updatedAt,t),n;const r={id:this._newId(e),name:a,tool:o,values:i,createdAt:t,updatedAt:t};return e.templates.push(r),r},r)}async renameTemplate(e,t,n){const r=d(t,"name",120);return this._catalog.transact(t=>{const n=this._find(t,e);if(t.templates.some(e=>e!==n&&e.tool===n.tool&&Ae(e.name,r)))throw new o(`A template named ${r} already exists for this tool`);return n.name=r,n.updatedAt=this._later(n.updatedAt,this._now()),n},n)}async removeTemplate(e,t){return this._catalog.transact(t=>{const n=this._find(t,e);t.templates=t.templates.filter(e=>e!==n)},t)}async setDefault(e,t,n){const r=ye(e),a=null===t?null:ge(t);return this._catalog.transact(e=>{const t=e.defaults.find(e=>e.tool===r);if(null===a)return void(e.defaults=e.defaults.filter(e=>e!==t));const n=this._later(t?.updatedAt??0,this._now());t?(t.values=a,t.updatedAt=n):e.defaults.push({tool:r,values:a,updatedAt:n})},n)}_find(e,t){const n=d(t,"template ID",100),r=e.templates.find(e=>e.id===n);if(!r)throw new o("Saved drawing template does not exist");return r}_later(e,t){return Math.max(e,p(t,"current time",0))}_newId(e){const t=d(this._id(),"generated template ID",100);if(e.templates.some(e=>e.id===t))throw new o("Generated template ID collision");return t}},e.WORKSPACE_VERSION=1,e.WatchlistConflictError=ae,e.WatchlistRepository=class{constructor(e,t,n={}){Object.defineProperty(this,"_catalog",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_now",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._catalog=new $(e,t,ue,de),this._now=n.now??Date.now,this._id=n.id??M}get namespace(){return this._catalog.namespace}load(){return this._catalog.load()}subscribe(e){return this._catalog.subscribe(e)}async createList(e,t=[],n){const r=d(e,"name",120),a=se(s(t));return this._catalog.transact(e=>{const t=this._now(),n={id:this._newId(e),name:r,entries:a,createdAt:t,updatedAt:t};return e.lists.push(n),n},n)}async renameList(e,t,n){const r=d(t,"name",120);return this._catalog.transact(t=>this._touch(this._find(t,e),e=>{e.name=r}),n)}async duplicateList(e,t,n){const r=d(t,"name",120);return this._catalog.transact(t=>{const n=this._find(t,e),a=this._now(),o={id:this._newId(t),name:r,entries:n.entries.map(e=>({...e})),createdAt:a,updatedAt:a};return t.lists.push(o),o},n)}async removeList(e,t){return this._catalog.transact(t=>{const n=this._find(t,e);t.lists=t.lists.filter(e=>e!==n),t.activeListId===n.id&&(t.activeListId=null)},t)}async setActiveList(e,t){return this._catalog.transact(t=>{t.activeListId=null===e?null:this._find(t,e).id},t)}async addEntry(e,t,n={}){const r=ie(s(t));return this._catalog.transact(t=>this._touch(this._find(t,e),e=>{if(e.entries.some(e=>oe(e)===oe(r)))throw new o(`${pe(r)} is already in this list`);e.entries.splice(this._index(n.index??e.entries.length,e.entries.length),0,r)}),n)}async removeEntry(e,t,n){const r=ie(s(t));return this._catalog.transact(t=>this._touch(this._find(t,e),e=>{e.entries.splice(this._position(e,r),1)}),n)}async moveEntry(e,t,n,r){const a=ie(s(t));return this._catalog.transact(t=>this._touch(this._find(t,e),e=>{const[t]=e.entries.splice(this._position(e,a),1);e.entries.splice(this._index(n,e.entries.length),0,t)}),r)}_find(e,t){const n=d(t,"watchlist ID",100),r=e.lists.find(e=>e.id===n);if(!r)throw new o("Saved watchlist does not exist");return r}_touch(e,t){return t(e),e.updatedAt=Math.max(e.updatedAt,p(this._now(),"current time",0)),e}_position(e,t){const n=e.entries.findIndex(e=>oe(e)===oe(t));if(n<0)throw new o(`${pe(t)} is not in this list`);return n}_index(e,t){return Math.max(0,Math.min(t,Math.trunc(p(e,"entry index",-Number.MAX_SAFE_INTEGER))))}_newId(e){const t=d(this._id(),"generated watchlist ID",100);if(e.lists.some(e=>e.id===t))throw new o("Generated watchlist ID collision");return t}},e.WorkspaceConflictError=Q,e.WorkspaceDocumentError=o,e.WorkspaceRepository=class{constructor(e,t,n={}){Object.defineProperty(this,"_catalog",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_now",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._catalog=new $(e,t,Y,te),this._now=n.now??Date.now,this._id=n.id??M}get namespace(){return this._catalog.namespace}load(){return this._catalog.load()}subscribe(e){return this._catalog.subscribe(e)}async createWorkspace(e,t,n){const r=E(t),a=d(e,"name",120);return this._catalog.transact(e=>{const t=this._now(),n=P({...r,kind:"workspace",version:1,id:this._newId(e),name:a,createdAt:t,updatedAt:t});return e.workspaces.push(n),n},n)}async saveWorkspace(e,t,n){const r=E(t);return this._catalog.transact(t=>{const n=this._find(t,"workspace",e),a=P({...n,...r,updatedAt:this._updatedAt(n)});return t.workspaces[t.workspaces.indexOf(n)]=a,a},n)}async createTemplate(e,t,n){const r=k(t),a=d(e,"name",120);return this._catalog.transact(e=>{const t=this._now(),n=T({kind:"indicator-template",version:1,id:this._newId(e),name:a,createdAt:t,updatedAt:t,...r});return e.templates.push(n),n},n)}async saveTemplate(e,t,n){const r=k(t);return this._catalog.transact(t=>{const n=this._find(t,"indicator-template",e),a=T({kind:"indicator-template",version:n.version,id:n.id,name:n.name,createdAt:n.createdAt,updatedAt:this._updatedAt(n),...r});return t.templates[t.templates.indexOf(n)]=a,a},n)}async rename(e,t,n,r){const a=d(n,"name",120);return this._catalog.transact(n=>{const r=this._find(n,e,t);r.name=a,r.updatedAt=this._updatedAt(r)},r)}async duplicate(e,t,n,r){const a=d(n,"name",120);return this._catalog.transact(n=>this._insert(n,this._find(n,e,t),a),r)}async remove(e,t,n){return this._catalog.transact(n=>{this._find(n,e,t),"indicator-template"===e?n.templates=n.templates.filter(e=>e.id!==t):(n.workspaces=n.workspaces.filter(e=>e.id!==t),n.recentWorkspaceIds=n.recentWorkspaceIds.filter(e=>e!==t),n.activeWorkspaceId===t&&(n.activeWorkspaceId=n.recentWorkspaceIds[0]??null))},n)}async openWorkspace(e,t){return this._catalog.transact(t=>{const n=this._find(t,"workspace",e);return t.activeWorkspaceId=n.id,t.recentWorkspaceIds=[n.id,...t.recentWorkspaceIds.filter(e=>e!==n.id)].slice(0,10),n},t)}async setAutosave(e,t){const n=u(e,"autosave");return this._catalog.transact(e=>{e.autosave=n},t)}async importDocument(e,t){const n=ne(e,{keepPolicy:!1});return this._catalog.transact(e=>this._insert(e,n,n.name),t)}captureIndicatorTemplate(e){return q(e)}planIndicatorTemplateState(e,t,n,r){return Z(e,t,n,r)}async exportDocument(e,t){const n=await this.load();return JSON.stringify(this._find(n,e,t),null,2)}_find(e,t,n){if("workspace"!==t&&"indicator-template"!==t)throw new o("Unsupported document kind");const r=d(n,"document ID",100),a=("workspace"===t?e.workspaces:e.templates).find(e=>e.id===r);if(!a)throw new o(`Saved ${t} does not exist`);return a}_updatedAt(e){return Math.max(e.updatedAt,p(this._now(),"current time",0))}_newId(e){const t=d(this._id(),"generated document ID",100);if([...e.workspaces,...e.templates].some(e=>e.id===t))throw new o("Generated document ID collision");return t}_insert(e,t,n){const r=this._now(),a=ne({...t,name:n,id:this._newId(e),createdAt:r,updatedAt:r});return"workspace"===a.kind?e.workspaces.push(a):e.templates.push(a),a}},e.captureIndicatorTemplate=q,e.createIndexedDbDrawingTemplateStorage=function(e,t="openalgo-chart-drawing-templates"){return re(e,t,"Drawing template",be,()=>new he)},e.createIndexedDbWatchlistStorage=function(e,t="openalgo-chart-watchlists"){return re(e,t,"Watchlist",le,()=>new ae)},e.createIndexedDbWorkspaceStorage=function(e,t="openalgo-chart-workspaces"){return re(e,t,"Workspace",ee,()=>new Q)},e.createMemoryDrawingTemplateStorage=function(e={}){return N(e,Se)},e.createMemoryWatchlistStorage=function(e={}){return N(e,ue)},e.createMemoryWorkspaceStorage=function(e={}){return N(e,Y)},e.migrateWidgetWorkspace=function(e,t){const n=c(s(e),"widget");if(1!==n.version||void 0!==n.kind)throw new o("Unsupported widget state");const r=null===n.rail?{}:c(n.rail??{},"rail");return P({kind:"workspace",version:1,id:t.id,name:t.name,createdAt:t.now,updatedAt:t.now,panes:[{id:"p0",symbol:n.symbol,exchange:n.exchange??"",interval:n.interval,chartType:n.chartType,chart:n.chart,magnet:r.magnet??"off",stay:r.stay??!1,...void 0===n.variant?{}:{variant:n.variant},settings:{"widget.theme":h(n.theme,"theme",["light","dark"],"dark")}}],layout:{rows:1,columns:1,slots:[{paneId:"p0",row:0,column:0,rowSpan:1,columnSpan:1}]},activePaneId:"p0"})},e.parseDrawingTemplateCatalog=be,e.parseDrawingTemplateValues=ge,e.parseIndicatorStates=I,e.parseIndicatorTemplate=T,e.parseIndicatorTemplatePayload=k,e.parseWatchlistCatalog=le,e.parseWorkspaceCatalog=ee,e.parseWorkspaceDocument=P,e.parseWorkspacePayload=E,e.planIndicatorTemplate=W,e.planIndicatorTemplateState=Z,e.watchlistKey=oe,e}({},OpenAlgoCharts);
@@ -1,9 +1,66 @@
1
1
  import { ZOrder, IPrimitive, PrimitiveHost, PrimitiveRenderContext, PrimitiveHit } from 'openalgo-charts';
2
2
 
3
+ /**
4
+ * Internal time is always **UTC seconds** (integer). Feed adapters convert
5
+ * broker formats (IST strings, epoch ms) to this at the edge; see ARCHITECTURE.md §4.0.
6
+ */
7
+ type UTCSeconds = number;
8
+ /** A single OHLC(V) bar. `volume` is optional (not all feeds carry it). */
9
+ interface Bar {
10
+ time: UTCSeconds;
11
+ open: number;
12
+ high: number;
13
+ low: number;
14
+ close: number;
15
+ volume?: number;
16
+ /**
17
+ * Open interest: contracts outstanding at the end of this bar. Optional,
18
+ * because only a derivatives feed carries it; on a cash instrument it is
19
+ * absent, and absent is not zero. Zero is a real reading on a contract nobody
20
+ * holds.
21
+ *
22
+ * **It is a level, not a flow, and that is the whole reason it needs saying
23
+ * here.** Volume is a quantity traded *during* the bar, so folding five
24
+ * one-minute bars into a five-minute bar adds five volumes together. Open
25
+ * interest is a position *as at* the bar, so the same fold takes the last
26
+ * one and adding them would produce a number five times too large that still
27
+ * looks entirely plausible on a chart.
28
+ *
29
+ * Every aggregation path in this library therefore treats the two
30
+ * differently: `mergeBars`, the higher-timeframe fold in `securitySeries`,
31
+ * and the tick-to-bar builders all sum volume and carry the latest open
32
+ * interest. A transform that maps one source bar to one output bar passes it
33
+ * through; one that invents bars from price alone (Renko, Point and Figure)
34
+ * does not carry it at all, because a synthetic bar has no instant to be the
35
+ * position as at.
36
+ */
37
+ oi?: number;
38
+ /**
39
+ * Per-bar colour override, honoured by every Family-A renderer: candles and
40
+ * OHLC bars take it on body, border and wick together, histogram and column
41
+ * on the bar, and line, step, area and the HLC-area close line split their
42
+ * stroke into runs at the bars where it changes. Baseline is the exception,
43
+ * its stroke is already split by the above/below-base rule.
44
+ * A MACD histogram is four colours by momentum, and a conditional study is
45
+ * two. Neither is expressible with one colour for the whole series.
46
+ */
47
+ color?: string;
48
+ /**
49
+ * Wick colour for this bar alone, over `color`. A study that paints candles
50
+ * with a translucent body and a solid wick cannot say so with one colour,
51
+ * and without this a per-bar override always set the two together. Read by
52
+ * the candle renderers only; absent means the wick follows `color`.
53
+ */
54
+ wickColor?: string;
55
+ /** Border colour for this bar alone, on the same terms as `wickColor`. */
56
+ borderColor?: string;
57
+ }
58
+
3
59
  /**
4
60
  * Profile data model (ARCHITECTURE.md §6A, Family C). Price-bucketed
5
61
  * distributions: volume-at-price, time-at-price (TPO), and bid/ask footprint.
6
62
  */
63
+
7
64
  interface VolumeProfileResult {
8
65
  /** Volume per price bucket, sorted high to low price. */
9
66
  buckets: {
@@ -66,72 +123,19 @@ interface FootprintBar {
66
123
  lowAsk: number;
67
124
  };
68
125
  }
69
- /** Bucket a price to the tick grid. */
126
+ /**
127
+ * Bucket a price to the row grid of `step`: the centre of the row holding it,
128
+ * the upper row for a price exactly between two.
129
+ */
70
130
  declare function bucketPrice(price: number, step: number): number;
71
131
  /**
72
132
  * Inclusive list of bucket prices spanning [low, high]. A step that is not a
73
133
  * positive finite number gives no buckets, and so does a range the numbers
74
- * cannot step through: a step too small to move a price that large, or a
75
- * price past the largest number.
134
+ * cannot step through: a step too small to move a price that large, or to
135
+ * number its rows exactly, or a price past the largest number.
76
136
  */
77
137
  declare function priceBuckets(low: number, high: number, step: number): number[];
78
138
 
79
- /**
80
- * Internal time is always **UTC seconds** (integer). Feed adapters convert
81
- * broker formats (IST strings, epoch ms) to this at the edge; see ARCHITECTURE.md §4.0.
82
- */
83
- type UTCSeconds = number;
84
- /** A single OHLC(V) bar. `volume` is optional (not all feeds carry it). */
85
- interface Bar {
86
- time: UTCSeconds;
87
- open: number;
88
- high: number;
89
- low: number;
90
- close: number;
91
- volume?: number;
92
- /**
93
- * Open interest: contracts outstanding at the end of this bar. Optional,
94
- * because only a derivatives feed carries it; on a cash instrument it is
95
- * absent, and absent is not zero. Zero is a real reading on a contract nobody
96
- * holds.
97
- *
98
- * **It is a level, not a flow, and that is the whole reason it needs saying
99
- * here.** Volume is a quantity traded *during* the bar, so folding five
100
- * one-minute bars into a five-minute bar adds five volumes together. Open
101
- * interest is a position *as at* the bar, so the same fold takes the last
102
- * one and adding them would produce a number five times too large that still
103
- * looks entirely plausible on a chart.
104
- *
105
- * Every aggregation path in this library therefore treats the two
106
- * differently: `mergeBars`, the higher-timeframe fold in `securitySeries`,
107
- * and the tick-to-bar builders all sum volume and carry the latest open
108
- * interest. A transform that maps one source bar to one output bar passes it
109
- * through; one that invents bars from price alone (Renko, Point and Figure)
110
- * does not carry it at all, because a synthetic bar has no instant to be the
111
- * position as at.
112
- */
113
- oi?: number;
114
- /**
115
- * Per-bar colour override, honoured by every Family-A renderer: candles and
116
- * OHLC bars take it on body, border and wick together, histogram and column
117
- * on the bar, and line, step, area and the HLC-area close line split their
118
- * stroke into runs at the bars where it changes. Baseline is the exception,
119
- * its stroke is already split by the above/below-base rule.
120
- * A MACD histogram is four colours by momentum, and a conditional study is
121
- * two. Neither is expressible with one colour for the whole series.
122
- */
123
- color?: string;
124
- /**
125
- * Wick colour for this bar alone, over `color`. A study that paints candles
126
- * with a translucent body and a solid wick cannot say so with one colour,
127
- * and without this a per-bar override always set the two together. Read by
128
- * the candle renderers only; absent means the wick follows `color`.
129
- */
130
- wickColor?: string;
131
- /** Border colour for this bar alone, on the same terms as `wickColor`. */
132
- borderColor?: string;
133
- }
134
-
135
139
  /**
136
140
  * Volume Profile (ARCHITECTURE.md §6A). Distributes each bar's volume across the
137
141
  * price buckets it spans, then derives the Point of Control and Value Area.
@@ -1,4 +1,4 @@
1
- import { IPrimitive, PrimitiveHost, ZOrder, PrimitiveRenderContext, PrimitiveHit, TradingCapabilityResult, TickSchedule, TradingCapabilitySource, Instrument } from 'openalgo-charts';
1
+ import { IPrimitive, PrimitiveHost, ZOrder, PrimitiveRenderContext, PrimitiveHit, InstrumentKey, TradingCapabilityResult, TickSchedule, TradingCapabilitySource, Instrument } from 'openalgo-charts';
2
2
  export { TradingCapabilities, TradingCapabilityError, TradingCapabilityRequest, TradingCapabilityResult, TradingCapabilitySource, TradingOperation, assertTradingCapability, checkTradingCapability } from 'openalgo-charts';
3
3
 
4
4
  /**
@@ -37,6 +37,13 @@ type OrderRole = 'entry' | 'sl' | 'tp';
37
37
  interface Order {
38
38
  id: string;
39
39
  symbol: string;
40
+ /**
41
+ * The venue, when the provider says. Symbol and exchange together name a
42
+ * contract: one symbol on two exchanges is two instruments.
43
+ */
44
+ exchange?: string | undefined;
45
+ /** The product (`CNC`, `MIS`, `NRML` on OpenAlgo), when the provider says. */
46
+ product?: string | undefined;
40
47
  side: OrderSide;
41
48
  type: OrderType;
42
49
  qty: number;
@@ -50,6 +57,9 @@ interface Order {
50
57
  }
51
58
  interface Position {
52
59
  symbol: string;
60
+ /** As on `Order`. A book holds one row per symbol, exchange and product, and each is its own position. */
61
+ exchange?: string | undefined;
62
+ product?: string | undefined;
53
63
  /** Net signed quantity: positive = long, negative = short, 0 = flat. */
54
64
  netQty: number;
55
65
  avgPrice: number;
@@ -115,7 +125,9 @@ declare class WorkingOrderLine implements IPrimitive {
115
125
  * with a broker-style segmented pill group ([LONG|SHORT][qty][P&L (pct)][close]),
116
126
  * a compact avg-price tag on the axis, and a shaded entry-to-LTP band colored by
117
127
  * P&L sign. Updates cheaply on every LTP tick. The close segment hit-tests as
118
- * `position:<symbol>::close` (wire it to your square-off flow).
128
+ * `position:<symbol>::close` (wire it to your square-off flow), or with a
129
+ * `hitKey` in place of the symbol: `TradeController` gives one to each row of a
130
+ * symbol it draws more than once, so a click names one product.
119
131
  */
120
132
 
121
133
  declare class PositionMarker implements IPrimitive {
@@ -124,9 +136,13 @@ declare class PositionMarker implements IPrimitive {
124
136
  private _host;
125
137
  private _group;
126
138
  private readonly _extent;
139
+ private readonly _hitKey;
127
140
  constructor(position: Position, options?: {
128
141
  extentFromRight?: number;
142
+ hitKey?: string | undefined;
129
143
  });
144
+ /** What its hit ids name after `position:`: the `hitKey` it was built with, else the symbol. */
145
+ get hitKey(): string;
130
146
  attached(host: PrimitiveHost): void;
131
147
  detached(): void;
132
148
  zOrder(): ZOrder;
@@ -146,10 +162,15 @@ declare class PositionMarker implements IPrimitive {
146
162
  * with theme-derived shaded risk/reward zones, rounded "SL/TP @ price" chips at
147
163
  * the left edge, and an R:R chip near entry: the core advanced-trade-management
148
164
  * visualisation. The SL/TP lines thicken on hover and are draggable (OCO modify).
165
+ * They hit-test as `bracket-sl:<symbol>` and `bracket-tp:<symbol>`, or with a
166
+ * `hitKey` in place of the symbol, as `PositionMarker` does.
149
167
  */
150
168
 
151
169
  interface BracketState {
152
170
  symbol: string;
171
+ /** The exchange and product of the position it protects, when the book names them. */
172
+ exchange?: string | undefined;
173
+ product?: string | undefined;
153
174
  side: OrderSide;
154
175
  entry: number;
155
176
  stop: number;
@@ -158,7 +179,12 @@ interface BracketState {
158
179
  declare class BracketGroup implements IPrimitive {
159
180
  private _state;
160
181
  private _host;
161
- constructor(state: BracketState);
182
+ private readonly _hitKey;
183
+ constructor(state: BracketState, options?: {
184
+ hitKey?: string | undefined;
185
+ });
186
+ /** What its hit ids name after `bracket-sl:` and `bracket-tp:`: the `hitKey` it was built with, else the symbol. */
187
+ get hitKey(): string;
162
188
  attached(host: PrimitiveHost): void;
163
189
  detached(): void;
164
190
  zOrder(): ZOrder;
@@ -193,8 +219,16 @@ declare class TradeController {
193
219
  private readonly _brackets;
194
220
  private readonly _ltp;
195
221
  constructor(host: TradeHost);
196
- /** Reconcile a full book snapshot. Idempotent: safe to call on every update or reconnect. */
197
- reconcile(orders: readonly Order[], positions: readonly Position[]): void;
222
+ /**
223
+ * Reconcile a full book snapshot. Idempotent: safe to call on every update or reconnect.
224
+ *
225
+ * Pass the chart's `instrument` to draw only its rows. A book covers the whole
226
+ * account, and without it every working order is drawn on this chart and
227
+ * joins its autoscale: a futures order at 52000 stretches an equity chart to
228
+ * 52000, and an order on another exchange sits at a plausible price where a
229
+ * drag would modify it. Rows of other instruments drawn before are removed.
230
+ */
231
+ reconcile(orders: readonly Order[], positions: readonly Position[], instrument?: InstrumentKey): void;
198
232
  private _reconcileOrderLines;
199
233
  private _reconcilePositions;
200
234
  /**
@@ -204,8 +238,23 @@ declare class TradeController {
204
238
  */
205
239
  private _planBrackets;
206
240
  private _applyBrackets;
207
- /** Push a last price; updates the live P&L / distance on bound primitives. */
208
- onLtp(symbol: string, ltp: number): void;
241
+ /**
242
+ * Push a last price; updates the live P&L / distance on bound primitives.
243
+ * Without `exchange` it reaches every row of the symbol, as it always has.
244
+ * Name it when the book spans exchanges, or an NSE tick moves a BSE row's
245
+ * P&L. A row that names no exchange takes it either way, as `reconcile`
246
+ * matches such a row to an instrument.
247
+ */
248
+ onLtp(symbol: string, ltp: number, exchange?: string): void;
249
+ /** The last price pushed for a row's own exchange, else for its symbol. */
250
+ private _ltpOf;
251
+ /**
252
+ * The position a `position:`, `bracket-sl:` or `bracket-tp:` hit id names,
253
+ * `::close` included, with its exchange and product: the row a close or a
254
+ * stop edit is for. Undefined for any other id, or one nothing drawn
255
+ * carries any more.
256
+ */
257
+ positionOf(externalId: string): Position | undefined;
209
258
  /** Test/introspection helpers. */
210
259
  orderLineCount(): number;
211
260
  positionCount(): number;
@@ -882,6 +931,8 @@ declare class OrderEngine {
882
931
  private readonly _sentTokens;
883
932
  private readonly _lastModifyAt;
884
933
  private readonly _pendingModify;
934
+ /** Modifies sent and not yet answered, by client id, for `commitModify` to wait on. */
935
+ private readonly _modifying;
885
936
  /** Settled client ids, oldest first: the eviction order for the maps above. */
886
937
  private readonly _settledIds;
887
938
  /** Leg rows that named an entry before it was bound, by entry broker id, then leg broker id. */
@@ -1004,8 +1055,16 @@ declare class OrderEngine {
1004
1055
  * it surfaces via `onValidationError` so the UI can snap the line back.
1005
1056
  */
1006
1057
  requestModify(clientId: string, price: number, opts?: ModifyOptions): void;
1007
- /** Force-send any pending modify (e.g. on drag end). */
1058
+ /**
1059
+ * Force-send any pending modify (e.g. on drag end). Resolves once the broker
1060
+ * has answered it and every modify of this order already out: `requestModify`
1061
+ * sends at once when its interval has passed, so on a release there is often
1062
+ * nothing left to flush, and a book read on this promise must not run before
1063
+ * the broker took that write.
1064
+ */
1008
1065
  commitModify(clientId: string): Promise<void>;
1066
+ /** `_flushModify`, joined to the modifies of this order still out. */
1067
+ private _sendModify;
1009
1068
  /**
1010
1069
  * Turn a dragged level into a patch the broker can apply without losing a
1011
1070
  * field it already holds.
@@ -1324,7 +1383,8 @@ interface LadderRow {
1324
1383
  }
1325
1384
  /**
1326
1385
  * Merge bids + asks into price rows, optionally bucketing every `groupBy` ticks
1327
- * (price-step aggregation for deep books). Returns rows sorted high to low price.
1386
+ * (price-step aggregation for deep books), a bid into the group at or below its
1387
+ * price and an ask into the one at or above. Returns rows sorted high to low price.
1328
1388
  * Pass a `TickSchedule` in place of the tick size for an instrument whose tick
1329
1389
  * changes with price: each row is then a price its band allows, and a group
1330
1390
  * spans `groupBy` ticks of that band, so the step changes at a boundary.
@@ -127,6 +127,12 @@ declare class HeikinAshiTransform implements ISeriesTransform {
127
127
  * - `'atr'`: `ATR(period) × multiplier` (Wilder), re-resolved per column.
128
128
  * - `'atrPercent'`: `ATR(period) × percent / 100`, a box that is a share of the ATR.
129
129
  *
130
+ * A box is a price level, the lower edge of its glyph: an X column fills each
131
+ * level its high reaches and an O column each level its low reaches, so a low
132
+ * of 17.99 under an X column at 20 has not reached 17 and is no three-box
133
+ * reversal. Levels are counted on the box grid, so a price that touches one
134
+ * exactly reaches it on a decimal box too (100.3 / 0.1 is 1002.9999999999999).
135
+ *
130
136
  * Each emitted column is a Bar spanning the column's price range, with up =
131
137
  * close ≥ open (X) and down = close < open (O). A column's `high` is the
132
138
  * **exclusive top edge** of its highest box, so `[low, high)` is exactly the
@@ -196,16 +202,16 @@ declare class PointFigureTransform implements ISeriesTransform {
196
202
 
197
203
  /**
198
204
  * Renko bricks (ARCHITECTURE.md §6A). Each box-size move emits one brick.
199
- * Renders with the candlestick renderer (brick = a body). Simplified
200
- * single-box step (no 2× reversal rule): deterministic and incremental for
201
- * live updates.
205
+ * Renders with the candlestick renderer (brick = a body). A reversal is a
206
+ * single box like any other step, so the first brick against the trend is
207
+ * drawn back over the last one rather than after a two-box move from its far
208
+ * side: deterministic and incremental for live updates.
202
209
  *
203
210
  * Brick sizing (`mode`), the same choices as point and figure:
204
211
  * - `'fixed'` (default): a constant `boxSize`.
205
212
  * - `'percent'`: `price × percent / 100`, re-resolved as each brick forms.
206
213
  * - `'atr'`: `ATR(atrPeriod) × atrMultiplier` (Wilder), re-resolved as each
207
214
  * brick forms.
208
- * multiplier divided by 100.
209
215
  * - `'atrPercent'`: `ATR(atrPeriod) × percent / 100`, a brick that is a share of the ATR.
210
216
  *
211
217
  * Prices (`method`): `'close'` (default) moves bricks on the close alone;
@@ -248,6 +254,14 @@ declare class RenkoTransform implements ISeriesTransform {
248
254
  * throws or forms a zero-height brick.
249
255
  */
250
256
  private _resolve;
257
+ /**
258
+ * Boxes `p` has moved from the edge. Both are counted on the box grid, so a
259
+ * move of exactly one decimal box is one: compared as prices, 200 one-box
260
+ * moves of 0.05 formed 199 bricks.
261
+ */
262
+ private _moved;
263
+ /** The edge `dir` boxes on, computed on the grid rather than added, so a run of bricks never drifts off it. */
264
+ private _next;
251
265
  push(bar: Bar): Bar[];
252
266
  }
253
267
 
@@ -255,6 +269,8 @@ declare class RenkoTransform implements ISeriesTransform {
255
269
  * Range bars (ARCHITECTURE.md §6A). A new bar completes when its high−low
256
270
  * reaches the configured range. Built from the close sequence; renders with the
257
271
  * candlestick renderer. Incremental: the in-progress bar is emitted by flush().
272
+ * The range is a threshold, not a fixed span: a close that jumps past it
273
+ * completes one bar covering the whole jump, never invented bars inside it.
258
274
  */
259
275
 
260
276
  interface RangeOptions {