(self.webpackChunktradingview=self.webpackChunktradingview||[]).push([[24345],{288812:e=>{e.exports={screen:"screen-otjoFNF2",fade:"fade-otjoFNF2",screenfade:"screenfade-otjoFNF2"}},207322:e=>{e.exports={}},898586:e=>{e.exports={css_value_currency_label_radius:"4",css_wrapper_margin:"4",css_row_left_right_padding:"3",css_fade_height:"10","price-axis-currency-label-wrapper":"price-axis-currency-label-wrapper-y5H41VPj",hidden:"hidden-y5H41VPj","price-axis-currency-label":"price-axis-currency-label-y5H41VPj",row:"row-y5H41VPj",expanded:"expanded-y5H41VPj","price-axis-currency-label-arrow-down":"price-axis-currency-label-arrow-down-y5H41VPj","price-axis-currency-label-text":"price-axis-currency-label-text-y5H41VPj"}},569960:e=>{e.exports={}},606593:e=>{e.exports={}},499650:e=>{e.exports={"css-value-chart-controls-bar-height-with-border":"39px","css-value-chart-controls-bar-border":"1px"}},958729:e=>{e.exports={}},100366:(e,t,i)=>{"use strict";async function s(){return(await Promise.all([i.e(4908),i.e(77142),i.e(90385),i.e(20139)]).then(i.bind(i,254543))).ErrorCardRenderer}i.d(t,{getErrorCardRenderer:()=>s})},113610:(e,t,i)=>{"use strict";i.d(t,{getChartStorage:()=>m});var s=i(120780),o=i(895370),r=i(175203),n=i(652171),a=i(198303),l=i(266325),c=i(474759);function d(){const e=document.querySelector('link[rel~="chart-storage"]'),t=new URL((null==e?void 0:e.href)||"/charts-storage/",location.href);return t.pathname.endsWith("/")||(t.pathname+="/"),t}function h(e){const{charts:t={},countSourcesTotal:i=0,limitBytesTotal:s=0,sizeBytesTotal:o=0}=e,r=new Map;for(const e in t){const i=t[e].symbols,s=new Map;for(const e in i||{}){const t=i[e];s.set(e,{countSources:t.countSources,sizeBytes:t.sizeBytes,ids:t.ids})}r.set(e,s)}return{charts:r,countSourcesTotal:i,limitBytesTotal:s,sizeBytesTotal:o}}const u={sources:new Map,groups:new Map};class _{constructor(){this._lastSaveRequest=Promise.resolve(),this._requestsCounter=0,this._lastSharedToolsLoadingRequest=Promise.resolve(u)}async saveLineToolsAndGroups(e,t,i,h,u){if(""===e||void 0===e)return Promise.reject("Unnamed chart cannot be saved");const _=`${e}.${t}.${this._requestsCounter++}`,p=`ChartStorage.Save.TotallyProcessing.${_}`,m=(0,o.perfMeasureOperation)(p,(()=>this._lastSaveRequest.then((async()=>{if(null==u?void 0:u.aborted)throw(0,l.createAbortError)();const p=`ChartStorage.Save.GettingToken.${_}`,m=await(0,o.perfMeasureOperation)(p,(()=>(0,n.getStorageTarget)(e,t,h,u))),g=new URL(m.path,d());m.chartId&&g.searchParams.append("chart_id",m.chartId),g.searchParams.append("jwt",m.token);const S=(0,c.stringifyLineToolsAndGroupsDTO)(i),v=`ChartStorage.Save.GettingResponse.${_}`;return(0,o.perfMeasureOperation)(v,(()=>(0,s.fetch)(g.toString(),{signal:u,method:"PUT",headers:{"Content-Type":"application/json","X-BUILD-TIME":window.BUILD_TIME},credentials:"include",body:S}).then((e=>{if(!e.ok){const t=429===e.status;throw new a.SavingLineToolsError(t,`Response status is not success: ${e.status}`)}const t=e.json();return r.telemetry.sendLineToolsStorageReport("line_tools_save_success"),t })).then((s=>({content:s,savedDto:i,layoutId:e,chartId:t,sharingMode:h})))))}))));return this._lastSaveRequest=m.catch((e=>{r.telemetry.sendLineToolsStorageReport("line_tools_save_error")})),m}async loadLineToolsAndGroups(e,t,i){if(""===e||void 0===e)return u;const a=`${e}.${t}.${i.requestType}.${this._requestsCounter++}`,l=`ChartStorage.Load.GettingToken.${a}`,h=await(0,o.perfMeasureOperation)(l,(()=>(0,n.getStorageTarget)(e,t,i.sharingMode))),_=`get/${h.path}`,p=new URL(_,d());switch(h.chartId&&p.searchParams.append("chart_id",h.chartId),window.user.is_superuser&&2===i.sharingMode&&p.searchParams.append("layout_id",e),p.searchParams.append("jwt",h.token),i.requestType){case"mainSeriesLineTools":p.searchParams.append("symbol",i.symbol),0===i.sharingMode&&p.searchParams.append("includeOwnerSource",i.seriesSourceId),p.searchParams.append("brokerName",i.brokerName);break;case"studiesLineTools":p.searchParams.append("excludeOwnerSource",i.seriesSourceId);break;case"lineToolsWithoutSymbol":p.searchParams.append("symbol",""),0===i.sharingMode&&p.searchParams.append("includeOwnerSource",i.seriesSourceId)}const m=`ChartStorage.Load.GettingResponse.${a}`,g=()=>(0,s.fetch)(p.toString(),{method:"GET",credentials:"include"}).then((e=>{if(!e.ok)throw new Error("Response status is not success");const t=e.headers.get("X-Request-Id");return e.json().then((e=>{if(null===e)throw new Error("Body is null");if(!e.success)throw new Error("Response is not success");const i=(0,c.parseLineToolsAndGroupsDTO)(e.payload||{},t);return r.telemetry.sendLineToolsStorageReport("line_tools_load_success"),i}))})),S=0===i.sharingMode?g:()=>this._lastSharedToolsLoadingRequest.then(g),v=(0,o.perfMeasureOperation)(m,S).catch((e=>{throw r.telemetry.sendLineToolsStorageReport("line_tools_load_error"),e}));return 0!==i.sharingMode&&(this._lastSharedToolsLoadingRequest=v.catch((()=>u))),v}async removeLineTools(e,t,i,a){if(""===e||void 0===e)return!1;const l=`${e}.${t}.${this._requestsCounter++}`,c=`ChartStorage.Remove.GettingToken.${l}`,h=await(0,o.perfMeasureOperation)(c,(()=>(0,n.getStorageTarget)(e,t,i))),u=new URL(h.path,d());h.chartId&&u.searchParams.append("chart_id",h.chartId),u.searchParams.append("jwt",h.token),u.searchParams.append("symbol",a);const _=`ChartStorage.Remove.GettingResponse.${l}`;return(0,o.perfMeasureOperation)(_,(()=>(0,s.fetch)(u.toString(),{method:"DELETE",credentials:"include"}).then((e=>{if(!e.ok)throw new Error("Response status is not success");return e.json().then((e=>{if(null===e)throw new Error("Body is null");if(!e.success)throw new Error("Response is not success");return r.telemetry.sendLineToolsStorageReport("line_tools_remove_by_symbol_success"),!0}))})))).catch((e=>{throw r.telemetry.sendLineToolsStorageReport("line_tools_remove_by_symbol_error"),e}))}async getLayoutDrawingsSizeInfo(e,t){if(""===e||void 0===e)return{charts:new Map,countSourcesTotal:0,limitBytesTotal:0,sizeBytesTotal:0};const i=`${e}.${t}.${this._requestsCounter++}`,s=`ChartStorage.GetSizes.GettingToken.${i}`,a=await(0,o.perfMeasureOperation)(s,(()=>(0, n.getStorageTarget)(e,t,0))),l=new URL(`layout/${e}/sizes`,d());return l.searchParams.append("jwt",a.token),this._fetchData(`ChartStorage.GetSizes.GettingResponse.${i}`,l,{method:"GET",credentials:"include"}).then((e=>(r.telemetry.sendLineToolsStorageReport("line_tools_size_info_success"),h(e||{})))).catch((e=>{throw r.telemetry.sendLineToolsStorageReport("line_tools_size_info_error"),e}))}async getUserGlobalDrawingsSizeInfo(e){if(""===e||void 0===e)return{charts:new Map,countSourcesTotal:0,limitBytesTotal:0,sizeBytesTotal:0};const t=this._requestsCounter++,i=await(0,o.perfMeasureOperation)(`ChartStorage.GetGlobalSizes.GettingToken.${t}`,(()=>(0,n.getStorageTarget)(e,"",2))),s=new URL("user/sizes",d());return s.searchParams.append("jwt",i.token),this._fetchData(`ChartStorage.GetGlobalSizes.GettingResponse.${t}`,s,{credentials:"include"}).then((e=>(r.telemetry.sendLineToolsStorageReport("global_line_tools_size_info_success"),h(e||{})))).catch((e=>{throw r.telemetry.sendLineToolsStorageReport("global_line_tools_size_info_error"),e}))}async _fetchData(e,t,i){const r=await(0,o.perfMeasureOperation)(e,(()=>(0,s.fetch)(t.toString(),i)));if(!r.ok)throw new Error("Response status is not success");const n=await r.json();if(null===n)throw new Error("Body is null");if(!n.success)throw new Error("Response is not success");return n.payload}}let p=null;async function m(){return null===p&&(p=new _),p}},474759:(e,t,i)=>{"use strict";function s(e){const t={};return e.sources&&(t.sources={},e.sources.forEach(((e,i)=>{t.sources[i]=e}))),t.drawing_groups={},e.groups.forEach(((e,i)=>{t.drawing_groups[i]=e})),t.clientId=e.clientId,JSON.stringify(t)}function o(e,t){const i={sources:null,groups:new Map};if(null!==e.sources){i.sources=new Map;for(const t in e.sources||{}){const s=e.sources[t];i.sources.set(t,s)}}for(const t in e.drawing_groups||{}){const s=e.drawing_groups[t];i.groups.set(t,s)}return null!==t&&(i.serverRequestId=t),i.clientId=e.clientId,i.symbol=e.symbol,i}i.d(t,{parseLineToolsAndGroupsDTO:()=>o,stringifyLineToolsAndGroupsDTO:()=>s})},198303:(e,t,i)=>{"use strict";i.d(t,{SavingLineToolsError:()=>s});class s extends Error{constructor(e,t){super(t),this.shouldBeCooled=e}}Error},652171:(e,t,i)=>{"use strict";i.d(t,{getStorageTarget:()=>a,globallySharedChartId:()=>n,sharedChartId:()=>r});var s=i(175203),o=i(266325);const r="_shared",n="UserSync";async function a(e,t,i,n){try{const a=new URL("/chart-token/",location.href);a.searchParams.append("image_url",e);const l=window.user.id||-1;a.searchParams.append("user_id",""+l);const c=await fetch(a.toString(),{signal:n});if(!c.ok)throw new Error(`Http response is not ok: ${c.status}}`);const d=await c.json();if(s.telemetry.sendLineToolsStorageReport("line_tools_token_request_success"),null==n?void 0:n.aborted)throw(0,o.createAbortError)();let h=t;return 2===i?h=void 0:1===i&&(h=r),{token:d.token,chartId:h,path:2===i?"user/sources":`layout/${e}/sources`}}catch(e){throw(0,o.isAbortError)(e)||s.telemetry.sendLineToolsStorageReport("line_tools_token_request_error"),e}}},709404:(e,t,i)=>{ "use strict";i.d(t,{getExchanges:()=>o});var s=i(279274);function o(){return s}},456335:(e,t,i)=>{"use strict";i.d(t,{featureCheck:()=>r});var s=i(778016);function o(e,t,i){return t.value||(0,s.enabled)(e,i)}function r(e,t,i){switch(e){case"SCREENER_INTERVALS":return function(e,t){const i=(0,s.getConfig)("SCREENER_INTERVALS",t);return!(!i||!i.interval)&&i.interval.includes(e.interval)}(t,i);case"SCREENER_AUTO_REFRESH":return o("SCREENER_AUTO_REFRESH",t,i);case"ALERTS_NO_EXPIRATION":return o("ALERTS_NO_EXPIRATION",t,i);default:return(0,s.enabled)(e,i)}}},31214:(e,t,i)=>{"use strict";i.d(t,{reloginOrGoPro:()=>c,runOrGoPro:()=>l,runOrGoProWithoutSync:()=>a});var s=i(526225),o=i(960337),r=i(456335),n=i(781666);function a(e,t,i,s){(0,r.featureCheck)(t,s)?e():(0,o.createGoProDialog)({...i,runOrGoproWithFeatureCheckOptions:{featureCheck:()=>(0,r.featureCheck)(t,s),signInSuccess:e}})}async function l(e,t,i,o={}){const r=window.is_authenticated;window.is_authenticated&&window.user.is_pro&&await(0,s.syncUserData)("gopro"),r===window.is_authenticated?a(e,t,i,o):(0,n.showSignModal)({source:i.goproSource,feature:i.feature,signinSuccess:e})}async function c(e){const t=window.is_authenticated;window.is_authenticated&&window.user.is_pro&&await(0,s.syncUserData)("gopro"),t===window.is_authenticated?(0,o.createGoProDialog)(e):(0,n.showSignModal)({source:e.goproSource,feature:e.feature})}},359663:(e,t,i)=>{"use strict";i.d(t,{FeatureToggleWatchedValue:()=>r});var s=i(125226),o=i(401580);class r extends o.WatchedValue{constructor(e,t){super(function(e,t){return(0,s.isFeatureEnabled)(e)}(e)),(0,s.onFeaturesStateChanged)().subscribe(this,(t=>{e===t&&this.setValue((0,s.isFeatureEnabled)(e))}))}destroy(){(0,s.onFeaturesStateChanged)().unsubscribeAll(this),super.destroy()}}},515312:(e,t,i)=>{"use strict";i.d(t,{isNativeUIInteraction:()=>s.isNativeUIInteraction,isTextEditingField:()=>s.isTextEditingField});var s=i(607423)},542682:(e,t,i)=>{"use strict";i.d(t,{isTouchEvent:()=>o});var s=i(778785);function o(e){const t=e.sourceCapabilities;let i=t&&t.firesTouchEvents;return void 0===i&&(i=s.touch),i}},895370:(e,t,i)=>{"use strict";i.d(t,{addPerfMark:()=>c,perfMeasureOperation:()=>d});var s=i(541558);function o(){}const r=console.timeStamp?console.timeStamp.bind(console):o,n=window.performance&&performance.mark?performance.mark.bind(performance):o,a=window.performance&&performance.measure?performance.measure.bind(performance):o,l=window.performance&&performance.clearMarks?performance.clearMarks.bind(performance):o;function c(e){r(e),n(e)}async function d(e,t){const i=`measure-${e}-${(0,s.randomHash)()}`;n(i);try{return await t()}finally{a(e,i),l(i)}}},887357:(e,t,i)=>{"use strict";var s;i.d(t,{NewsWidgetPlacement:()=>s}),function(e){e.WidgetBar="widgetbar",e.Main="main",e.Chart="chart",e.Screener="screener"}(s||(s={}))},67302:(e,t,i)=>{"use strict";i.d(t,{showThemeAction:()=>n,showThemeSwitcher:()=>r});var s=i(638456),o=i(347402);function r(){return!(0,s.isDesktopApp)()||(0,o.desktopVersionIsLess)("1.0.10")}function n(){return(0, s.isDesktopApp)()&&!(0,o.desktopVersionIsLess)("1.0.11")}},526225:(e,t,i)=>{"use strict";i.d(t,{syncUserConversionData:()=>h,syncUserData:()=>d});var s=i(201089),o=i(345848),r=i(120780),n=i(290576);const a=(0,s.getLogger)("User.Sync");function l(e){return`${e}_${window.user&&window.user.username||""}`}function c(e,t,i,s=!0){i!==window.user.pro_plan&&(window.user.pro_plan=i,window.user.is_pro=Boolean(i),(0,o.trackEvent)("Sync User Data","Different Pro Plan",l(e))),t!==window.is_authenticated&&(window.is_authenticated=t,s&&window.loginStateChange.fire(),(0,o.trackEvent)("Sync User Data","Different Auth",l(e)))}async function d(e){try{c(e,!0,(await(0,n.getProPlanDetailsForUser)()).pro_plan)}catch(t){!function(e,t){403===t.status&&["not_authenticated","login_required"].includes(t.type||"")?c(e,!1,void 0):a.logError(t.message)}(e,t)}}async function h(e,t=!0){var i;const s=new URL("/pricing/",window.location.origin),o=new URLSearchParams(window.location.search);o.has("_test_country")&&s.searchParams.append("_test_country",null!==(i=o.get("_test_country"))&&void 0!==i?i:"");const n=await(0,r.fetch)(s.href),a=await n.json();return c(e,a.is_authenticated,a.user.pro_plan,t),a}},484400:(e,t,i)=>{"use strict";i.d(t,{DEFAULT_THEME:()=>s});const s="light"},514811:(e,t,i)=>{"use strict";i.d(t,{themes:()=>l});var s=i(86746),o=i(444372) ;const r=JSON.parse('{"color-header-bg":"color-black","color-body-bg":"color-black","color-body-secondary-bg":"color-cold-gray-900","color-bg-primary":"color-cold-gray-850","color-bg-primary-hover":"color-cold-gray-800","color-bg-secondary":"color-cold-gray-900","color-bg-highlight":"color-cold-gray-900","color-bg-scroll-buttons":"color-cold-gray-800","color-legacy-bg-scroll-buttons":"color-cold-gray-550","color-legacy-bg-widget":"color-cold-gray-900","color-text-primary":"color-cold-gray-200","color-text-secondary":"color-cold-gray-450","color-text-tertiary":"color-cold-gray-400","color-text-disabled":"color-cold-gray-650","color-accent-content":"color-white","color-divider":"color-cold-gray-700","color-divider-hover":"color-cold-gray-800","color-divider-secondary":"color-cold-gray-800","color-box-shadow":"color-cold-gray-900","color-active-hover-text":"color-cold-gray-200","color-alert-text":"color-cold-gray-200","color-border":"color-cold-gray-750","color-border-chat-fields":"color-cold-gray-750","color-border-hover":"color-cold-gray-650","color-border-table":"color-cold-gray-800","color-brand":"color-tv-blue-500","color-brand-hover":"color-tv-blue-600","color-brand-active":"color-tv-blue-700","color-button-hover-bg":"color-cold-gray-850","color-chart-page-bg":"color-cold-gray-800","color-common-tooltip-bg":"color-cold-gray-750","color-danger":"color-ripe-red-600","color-danger-hover":"color-ripe-red-500","color-danger-active":"color-ripe-red-400","color-depthrenderer-fill-style":"color-cold-gray-150","color-depthrenderer-stroke-style":"color-cold-gray-650","color-disabled-border-and-color":"color-cold-gray-800","color-disabled-input":"color-cold-gray-750","color-empty-container-message":"color-cold-gray-450","color-halal":"color-iguana-green-400","color-continuous":"color-cold-gray-500","color-highlight-new":"color-tv-blue-a800","color-icons":"color-cold-gray-450","color-input-bg":"color-cold-gray-800","color-input-textarea-readonly":"color-cold-gray-650","color-input-placeholder-text":"color-cold-gray-700","color-input-publish-bg":"color-cold-gray-900","color-item-active-blue":"color-tv-blue-a900","color-item-hover-active-bg":"color-cold-gray-800","color-item-hover-bg":"color-cold-gray-800","color-item-hover-blue":"color-tv-blue-a800","color-item-selected-blue":"color-tv-blue-a800","color-item-active-text":"color-cold-gray-200","color-item-active-bg":"color-tv-blue-500","color-link":"color-tv-blue-500","color-link-hover":"color-tv-blue-600","color-link-active":"color-tv-blue-700","color-list-item":"color-cold-gray-450","color-list-nth-child-bg":"color-cold-gray-850","color-news-highlight":"color-cold-gray-800","color-pane-bg":"color-cold-gray-900","color-pane-secondary-bg":"color-cold-gray-850","color-placeholder":"color-cold-gray-650","color-popup-menu-item-hover-bg":"color-cold-gray-800","color-popup-menu-separator":"color-cold-gray-700","color-primary-symbol":"color-sky-blue-500","color-row-hover-active-bg":"color-cold-gray-800","color-sb-scrollbar-body-bg":"color-cold-gray-650","color-screener-description":"color-cold-gray-200","color-section-separator-border":"color-cold-gray-750","color-search-button-hover":"color-cold-gray-700","color-separator-table-chat":"color-cold-gray-750","color-success":"color-minty-green-700","color-success-hover":"color-minty-green-600","color-success-active":"color-minty-green-500","color-tag-active-bg":"color-cold-gray-750","color-tag-hover-bg":"color-cold-gray-800","color-text-regular":"color-cold-gray-200","color-toolbar-button-text":"color-cold-gray-200","color-toolbar-button-text-hover":"color-cold-gray-200","color-toolbar-button-text-active":"color-tv-blue-500","color-toolbar-button-text-active-hover":"color-tv-blue-600","color-toolbar-button-background-hover":"color-cold-gray-800","color-toolbar-button-background-secondary-hover":"color-cold-gray-750","color-toolbar-button-background-active":"color-tv-blue-a900","color-toolbar-button-background-active-hover":"color-tv-blue-a800","color-toolbar-toggle-button-background-active":"color-tv-blue-500","color-toolbar-toggle-button-background-active-hover":"color-tv-blue-600","color-toolbar-toggle-button-icon":"color-cold-gray-650","color-toolbar-interactive-element-text-normal":"color-cold-gray-200","color-toolbar-opened-element-bg":"color-cold-gray-800","color-toolbar-divider-background":"color-cold-gray-700","color-popup-background":"color-cold-gray-850","color-popup-element-text":"color-cold-gray-200","color-popup-element-text-hover":"color-cold-gray-250","color-popup-element-background-hover":"color-cold-gray-800","color-popup-element-secondary-text":"color-cold-gray-500","color-popup-element-hint-text":"color-cold-gray-600","color-popup-element-text-active":"color-cold-gray-200","color-popup-element-background-active":"color-tv-blue-500","color-popup-element-toolbox-text":"color-cold-gray-500","color-popup-element-toolbox-text-hover":"color-cold-gray-200","color-popup-element-toolbox-text-active-hover":"color-tv-blue-200","color-popup-element-toolbox-background-hover":"color-cold-gray-750","color-popup-element-toolbox-background-active-hover":"color-tv-blue-700","color-tooltip-bg":"color-cold-gray-750","color-tv-button-checked":"color-cold-gray-450","color-tv-dialog-caption":"color-cold-gray-50","color-tv-dropdown-item-hover-bg":"color-cold-gray-800","color-underlined-text":"color-cold-gray-450","color-widget-pages-bg":"color-cold-gray-900","color-warning":"color-tan-orange-700","color-forex-icon":"color-white","color-list-item-active-bg":"color-tv-blue-500","color-list-item-hover-bg":"color-cold-gray-800","color-list-item-text":"color-cold-gray-200","color-price-axis-label-back":"color-cold-gray-800","color-price-axis-label-text":"color-cold-gray-500","color-price-axis-gear":"color-cold-gray-200","color-price-axis-gear-hover":"color-cold-gray-400","color-price-axis-highlight":"color-cold-gray-800","color-bid":"color-tv-blue-500","color-scroll-bg":"color-cold-gray-750","color-scroll-border":"color-cold-gray-850","color-widget-border":"color-cold-gray-800","color-scroll-buttons-arrow":"color-white","color-control-intent-default":"color-cold-gray-650","color-control-intent-success":"color-minty-green-500","color-control-intent-primary":"color-tv-blue-500","color-control-intent-warning":"color-tan-orange-500","color-control-intent-danger":"color-ripe-red-500","color-growing":"color-minty-green-500","color-falling":"color-ripe-red-500","color-goto-label-background":"color-cold-gray-650","color-pre-market":"color-tan-orange-600","color-pre-market-bg":"color-tan-orange-400","color-post-market":"color-tv-blue-500","color-post-market-bg":"color-tv-blue-400","color-market-open":"color-minty-green-500","color-market-open-bg":"color-minty-green-400","color-market-closed":"color-cold-gray-400","color-market-holiday":"color-cold-gray-400","color-market-expired":"color-ripe-red-500","color-invalid-symbol":"color-ripe-red-400","color-invalid-symbol-hover":"color-ripe-red-500","color-delisted-symbol":"color-ripe-red-600","color-delisted-symbol-hover":"color-ripe-red-800","color-replay-mode":"color-tv-blue-500","color-replay-mode-point-select":"color-cold-gray-250","color-replay-mode-icon":"color-tv-blue-50","color-replay-mode-hover":"color-tv-blue-600","color-notaccurate-mode":"color-berry-pink-600","color-delay-mode":"color-tan-orange-700","color-delay-mode-bg":"color-tan-orange-400","color-eod-mode":"color-grapes-purple-700","color-eod-mode-bg":"color-grapes-purple-400","color-data-problem":"color-ripe-red-600","color-data-problem-bg":"color-ripe-red-400","color-data-problem-hover":"color-ripe-red-500","color-list-item-bg-highlighted":"color-tv-blue-a900","color-list-item-bg-selected":"color-tv-blue-a800","color-list-item-bg-highlighted-hover":"color-tv-blue-a800","color-list-item-bg-selected-hover":"color-tv-blue-a700","color-screener-header-bg":"color-cold-gray-850","color-screener-header-bg-hover":"color-cold-gray-800","color-overlay":"color-cold-gray-950","color-boost-button-content-selected":"color-tv-blue-100","color-boost-button-content-hover":"color-white","color-boost-button-bg-hover":"color-cold-gray-750","color-boost-button-border-hover":"color-cold-gray-750","color-boost-button-border-default":"color-cold-gray-700","color-x-twitter-content":"color-white","color-card-border":"color-cold-gray-700","color-card-border-hover":"color-cold-gray-600","color-background-special-primary":"color-black","color-stroke-special-primary":"color-cold-gray-800","color-selection-bg":"color-tv-blue-a700","color-default-gray":"color-cold-gray-450","color-featured-broker-badge-bg":"color-white","color-featured-broker-badge-bg-hover":"color-cold-gray-100","color-featured-broker-badge-text":"color-cold-gray-900"}'),n=JSON.parse('{"color-toolbar-button-text-active":"color-seeking-alpha-brand"}') ;var a=i(195294);const l={[s.StdTheme.Light]:{name:s.StdTheme.Light,label:()=>o.t(null,{context:"colorThemeName"},i(669841)),order:2,getThemedColor:e=>(0,a.getHexColorByName)(e)},[s.StdTheme.Dark]:{name:s.StdTheme.Dark,label:()=>o.t(null,{context:"colorThemeName"},i(14642)),order:1,getThemedColor:e=>{const t=r[e]||e;return(0,a.getHexColorByName)(t)}}};l.sa={isPrivate:!0,noChartTheme:!0,name:"sa",getThemedColor:e=>{const t=n[e]||e;return(0,a.getHexColorByName)(t)}}},560420:(e,t,i)=>{"use strict";i.d(t,{activateKeyPressHandler:()=>u,showDialog:()=>_});var s=i(449628),o=i(826531),r=i(244842),n=i(230296),a=i(868683),l=i(34831),c=i(345848);let d=null;function h(e){if(!(0,o.globalKeypressMatches)(e))return!1;e.preventDefault();const t=String.fromCharCode(e.charCode);return r.enabled("show_interval_dialog_on_key_press")&&function(e){return/[1-9]/.test(e)}(t)?(0,n.showChangeIntervalDialogAsync)({initVal:t}):r.enabled("symbol_search_hot_key")&&(_({defaultValue:t,selectSearchOnInit:!1,source:"keyboard",trackResultsOptions:{trackResults:!r.enabled("widget"),emptySearchType:"empty_result__supercharts"}}),(0,c.trackEvent)("GUI","SS","hotkey")),!0}function u(){(0,a.loadChangeIntervalDialog)(),s.pushBackListener("symbolEdit",h)}function _(e){const t=d=(0,l.loadNewSymbolSearch)().then((i=>{t===d&&i.showDefaultSearchDialog(e)}));return t}},711496:(e,t,i)=>{"use strict";i.d(t,{hasFinancialsByAvailabilityFlags:()=>d,hasFinancialsByTypespecs:()=>c});var s=i(519073);const o=new Set(["stock","dr","right","warrant","structured","bond"]),r=new Set(["mutual","unit","trust","reit","closedend","etn"]),n=new Set(["etn"]),a=new Set(["convertible","corporate"]),l=new Set(["cfd"]);function c(e,t){return!(e&&t&&(0,s.isEtf)(e,t))&&("structured"===e&&(null==t?void 0:t.length)?t.filter((e=>n.has(e))).length>0:"fund"===e&&(null==t?void 0:t.length)?t.filter((e=>r.has(e))).length>0:"bond"===e&&(null==t?void 0:t.length)?t.filter((e=>a.has(e))).length>0:"stock"===e&&(null==t?void 0:t.length)?0===t.filter((e=>l.has(e))).length:Boolean(e&&o.has(e)))}function d(e,t,i){if(t&&i&&(0,s.isEtf)(t,i))return!1;const{dividendsAvailability:o,earningsAvailability:r,financialsAvailability:n}=e;return 1===n||1===o||1===r}},2606:(e,t,i)=>{"use strict";i.d(t,{isDetailsReady:()=>s});const s=new(i(401580).WatchedValue)(!1)},396231:(e,t,i)=>{"use strict";i.d(t,{createSymbolNote:()=>S,showMindsPage:()=>g,showSymbolIdeas:()=>m,showSymbolNews:()=>p,showSymbolNotes:()=>_});var s=i(2606),o=i(421219),r=i(777453),n=i(731380),a=i(442731),l=i(881607),c=i(544855),d=i(515828);let h=null;function u(e,t){if(h&&s.isDetailsReady.unsubscribe(h),h=()=>{var i,s,o;(null===(o=null===(s=null===(i=null===window||void 0===window?void 0:window.widgetbar)||void 0===i?void 0:i.layout)||void 0===s?void 0:s.getWidgetByType("detail"))||void 0===o?void 0:o.widgetObject).navigate(e,t)},s.isDetailsReady.value())return h(),void(h=null);s.isDetailsReady.subscribe(h,{once:!0})}function _(e=null,t){const i=(0,o.pathToGroup)(null!=e?e:"");t?(0,n.showNotesDialog)(i):u(i)}function p(e,t){const i=(0, r.newsPathToGroup)(null!=e?e:"");t?(0,a.showNewsDialog)(i):u(i)}function m(e,t){const i=(0,l.ideasPathToGroup)(null!=e?e:"");t?(0,c.showIdeasDialog)(i):u(i)}function g(e,t,i){u((0,d.createMindsPath)(null!=e?e:"",t,i))}function S(e=null,t){const i=(0,o.pathToGroup)(null!=e?e:"")+"?new="+performance.now();t&&(0,n.showNotesDialog)(i),u(i)}},881607:(e,t,i)=>{"use strict";i.d(t,{IDEAS_GROUP_PATH_PATTERN:()=>s,ideasPathToGroup:()=>o});const s="/ideas/groups/:symbol/";function o(e){return s.replace(":symbol",encodeURIComponent(e))}},777453:(e,t,i)=>{"use strict";i.d(t,{NEWS_GROUP_PATH_PATTERN:()=>s,newsPathToGroup:()=>o});const s="/news/groups/:symbol/";function o(e){return s.replace(":symbol",encodeURIComponent(e))}},421219:(e,t,i)=>{"use strict";i.d(t,{GROUP_PATH_PATTERN:()=>o,NOTES_PATH_PATTERN:()=>s,UNATTENDED_PATH_PATTERN:()=>r,pathToGroup:()=>n});const s="/notes/",o="/notes/groups/:symbol/",r="/notes/unattended/";function n(e){return e?o.replace(":symbol",encodeURIComponent(e)):r}},834698:(e,t,i)=>{"use strict";i.d(t,{CompareDialogRenderer:()=>r});var s=i(111393);var o=i(251954);class r extends s.DialogRenderer{constructor(e){super(),this._dialog=null,this._subscribe=e=>{this._setVisibility(e)},this._chartWidgetCollection=e}show(e){this._load().then((t=>{var i,s;null===(i=this._dialog)||void 0===i||i.hide(),null===(s=this._dialog)||void 0===s||s.visible().unsubscribe(this._subscribe),this._dialog=t,t.visible().subscribe(this._subscribe),t.show(e),o.emit("compare_add")}))}hide(){var e;null===(e=this._dialog)||void 0===e||e.hide()}_load(){return Promise.all([Promise.all([i.e(14819),i.e(73224),i.e(72718),i.e(45389),i.e(57271)]).then(i.bind(i,910261)),Promise.all([i.e(14819),i.e(73224),i.e(72718),i.e(93327),i.e(32662),i.e(5987),i.e(98996),i.e(43387),i.e(66458),i.e(5761),i.e(4343),i.e(28430),i.e(70428),i.e(44597),i.e(1413),i.e(4908),i.e(52078),i.e(70621),i.e(89508),i.e(62033),i.e(13633),i.e(61204),i.e(19216),i.e(37132),i.e(66323),i.e(85258),i.e(16005),i.e(87940),i.e(63276),i.e(63751),i.e(29647),i.e(87473),i.e(10637),i.e(16165),i.e(85131),i.e(10714),i.e(94712),i.e(44794),i.e(39076),i.e(45338),i.e(47877),i.e(84418),i.e(95884),i.e(42616),i.e(56676),i.e(12971),i.e(90385),i.e(92833),i.e(42942),i.e(3889),i.e(92158),i.e(39434),i.e(18561),i.e(26854),i.e(30731)]).then(i.bind(i,635647))]).then((([e,t])=>{const i=new e.CompareModel(this._chartWidgetCollection);return t.getCompareDialogRenderer(i)}))}}},105580:(e,t,i)=>{"use strict";i.d(t,{showDetailsDialog:()=>n});var s=i(111393);let o;class r extends s.DialogRenderer{constructor(){super(...arguments),this._dialog=null,this._promise=null,this._subscribe=e=>{this._setVisibility(e)}}show(e){ const t=this._promise=Promise.all([i.e(14819),i.e(73224),i.e(68716),i.e(22309),i.e(19515),i.e(37729),i.e(23025),i.e(12265),i.e(32662),i.e(5987),i.e(98996),i.e(66458),i.e(5761),i.e(4343),i.e(28430),i.e(70428),i.e(1413),i.e(70621),i.e(89508),i.e(62033),i.e(13633),i.e(37132),i.e(14),i.e(36827),i.e(37657),i.e(36701),i.e(87940),i.e(61576),i.e(63276),i.e(29647),i.e(81543),i.e(72100),i.e(48277),i.e(7818),i.e(90365),i.e(45469),i.e(50442),i.e(74978),i.e(3891),i.e(52499),i.e(98993),i.e(86307),i.e(64071),i.e(72833),i.e(20850),i.e(37138),i.e(97539),i.e(24319),i.e(45123),i.e(89448),i.e(1707),i.e(86713),i.e(32399),i.e(90385),i.e(42942),i.e(60801),i.e(15462),i.e(67550),i.e(53286),i.e(83433),i.e(29508),i.e(44246),i.e(11085),i.e(2022),i.e(30666),i.e(16298),i.e(14474),i.e(26720)]).then(i.bind(i,863308)).then((i=>{this._promise===t&&(this._dialog&&(this._dialog.hide(),this._dialog.visible().unsubscribe(this._subscribe)),this._dialog=new i.DetailsDialogRenderer,this._dialog.visible().subscribe(this._subscribe),this._dialog.show(e))}))}hide(){var e,t;null===(e=this._dialog)||void 0===e||e.hide(),null===(t=this._dialog)||void 0===t||t.visible().unsubscribe(this._subscribe)}static getInstance(){return o||(o=new r),o}}function n(e){r.getInstance().show(e)}},544855:(e,t,i)=>{"use strict";async function s(e){(await Promise.all([i.e(32662),i.e(5987),i.e(98996),i.e(43387),i.e(66458),i.e(5761),i.e(4343),i.e(4908),i.e(70621),i.e(62033),i.e(13633),i.e(37132),i.e(36827),i.e(36701),i.e(87940),i.e(63276),i.e(70651),i.e(29647),i.e(81543),i.e(91986),i.e(35367),i.e(7818),i.e(74978),i.e(88346),i.e(67566),i.e(69078),i.e(4045),i.e(90385),i.e(35475),i.e(32576),i.e(94673)]).then(i.bind(i,790348))).renderIdeasDialog(e)}i.d(t,{showIdeasDialog:()=>s})},442731:(e,t,i)=>{"use strict";async function s(e){(await Promise.all([i.e(32662),i.e(5987),i.e(98996),i.e(66458),i.e(5761),i.e(4343),i.e(28430),i.e(70428),i.e(1413),i.e(70621),i.e(89508),i.e(62033),i.e(13633),i.e(37132),i.e(36827),i.e(36701),i.e(45444),i.e(87940),i.e(61576),i.e(63276),i.e(29647),i.e(81543),i.e(91986),i.e(7818),i.e(90365),i.e(45469),i.e(50442),i.e(74978),i.e(64071),i.e(45123),i.e(76424),i.e(90385),i.e(63295),i.e(76207),i.e(11085),i.e(84482)]).then(i.bind(i,23154))).renderNewsDialog(e)}i.d(t,{showNewsDialog:()=>s})},731380:(e,t,i)=>{"use strict";async function s(e){Promise.all([i.e(32662),i.e(5987),i.e(98996),i.e(43387),i.e(66458),i.e(5761),i.e(4343),i.e(28430),i.e(44597),i.e(70621),i.e(89508),i.e(62033),i.e(13633),i.e(37132),i.e(35697),i.e(87940),i.e(63276),i.e(5378),i.e(29647),i.e(84064),i.e(91986),i.e(31500),i.e(98993),i.e(50389),i.e(69078),i.e(4540),i.e(7707),i.e(90385),i.e(42942),i.e(53464),i.e(99676),i.e(60571),i.e(50996)]).then(i.bind(i,768175)).then((t=>{t.renderNotesDialog(e)}))}i.d(t,{showNotesDialog:()=>s})},597101:(e,t,i)=>{"use strict";i.d(t,{hideStateChange:()=>s});const s=new(i(707957).Delegate)},161590:(e,t,i)=>{"use strict";i.d(t,{GeneralChartPropertiesRenderer:()=>o});var s=i(111393);class o extends s.DialogRenderer{constructor(e){super(),this._dialog=null,this._subscribe=e=>{ this._setVisibility(e)},this._chartWidgetCollection=e}show(e){const t=this._chartWidgetCollection,s=t.activeChartWidget.value();return s.generalPropertiesDefinitions().then((o=>Promise.all([i.e(14819),i.e(73224),i.e(72718),i.e(93327),i.e(52540),i.e(32662),i.e(5987),i.e(98996),i.e(43387),i.e(66458),i.e(5761),i.e(4343),i.e(28430),i.e(70428),i.e(44597),i.e(1413),i.e(4908),i.e(52078),i.e(70621),i.e(89508),i.e(62033),i.e(13633),i.e(61204),i.e(19216),i.e(37132),i.e(66323),i.e(14),i.e(50473),i.e(37657),i.e(35697),i.e(31149),i.e(84331),i.e(85258),i.e(16005),i.e(79656),i.e(83483),i.e(87940),i.e(63276),i.e(63751),i.e(5378),i.e(29647),i.e(77382),i.e(87473),i.e(10637),i.e(16165),i.e(85131),i.e(10714),i.e(94712),i.e(44794),i.e(39076),i.e(71093),i.e(45338),i.e(66233),i.e(29946),i.e(5400),i.e(47877),i.e(42332),i.e(57876),i.e(84418),i.e(95884),i.e(20221),i.e(954),i.e(21975),i.e(70631),i.e(98133),i.e(23040),i.e(45183),i.e(55713),i.e(28288),i.e(87142),i.e(30408),i.e(4267),i.e(75803),i.e(77849),i.e(99403),i.e(37578),i.e(16723),i.e(90385),i.e(92833),i.e(42942),i.e(28019),i.e(3889),i.e(92158),i.e(39434),i.e(68581),i.e(18561),i.e(26854),i.e(72539),i.e(70334),i.e(97406),i.e(37305),i.e(31063),i.e(94025),i.e(68052),i.e(37078)]).then(i.bind(i,824306)).then((i=>{var r,n;const a=new i.GeneralChartPropertiesDialogRenderer({chartWidgetCollection:t,propertyPages:o,activePageId:this._activePageId,model:s.model()});return null===(r=this._dialog)||void 0===r||r.hide(),null===(n=this._dialog)||void 0===n||n.visible().unsubscribe(this._subscribe),this._dialog=a,a.visible().subscribe(this._subscribe),a.show(e),this._activePageId=void 0,a}))))}hide(){var e;null===(e=this._dialog)||void 0===e||e.hide()}isVisible(){return this.visible().value()}focusOnText(){}setActivePage(e){this._activePageId=e}}},826939:(e,t,i)=>{"use strict";i.d(t,{WATCHLIST_WIDGET_ID:()=>s});const s="watchlist-widget"},305514:(e,t,i)=>{"use strict";i.d(t,{showWatchListsDialog:()=>n});var s=i(111393);let o;class r extends s.DialogRenderer{constructor(){super(...arguments),this._dialog=null,this._subscribe=e=>{this._setVisibility(e)}}show(e){this._load(e).then((e=>e.show()))}hide(){var e,t;null===(e=this._dialog)||void 0===e||e.hide(),null===(t=this._dialog)||void 0===t||t.visible().unsubscribe(this._subscribe)}static getInstance(){return o||(o=new r),o}_load(e){return Promise.all([i.e(14819),i.e(73224),i.e(30867),i.e(32662),i.e(5987),i.e(98996),i.e(43387),i.e(66458),i.e(5761),i.e(4343),i.e(28430),i.e(70428),i.e(44597),i.e(1413),i.e(4908),i.e(52078),i.e(70621),i.e(89508),i.e(62033),i.e(13633),i.e(61204),i.e(19216),i.e(66323),i.e(50473),i.e(85258),i.e(16005),i.e(61576),i.e(63751),i.e(82452),i.e(87473),i.e(10637),i.e(16165),i.e(47686),i.e(10714),i.e(44794),i.e(71093),i.e(11803),i.e(5824),i.e(67154),i.e(31500),i.e(6143),i.e(29700),i.e(37578),i.e(64730),i.e(65916),i.e(40843),i.e(90385),i.e(92833),i.e(42942),i.e(5483),i.e(60801),i.e(3889),i.e(92158),i.e(18561),i.e(17774),i.e(56694),i.e(23852),i.e(13506),i.e(4571),i.e(57945)]).then(i.bind(i,485865)).then((t=>{var i,s ;return null===(i=this._dialog)||void 0===i||i.hide(),null===(s=this._dialog)||void 0===s||s.visible().unsubscribe(this._subscribe),this._dialog=new t.WatchListsDialogRenderer(e),this._dialog.visible().subscribe(this._subscribe),this._dialog}))}}function n(e){r.getInstance().show(e)}},104436:(e,t,i)=>{"use strict";var s;i.d(t,{ToolboxType:()=>s}),function(e){e[e.Delete=0]="Delete"}(s||(s={}))},92458:e=>{e.exports={chartsSplitter:"chartsSplitter-L0xapso5",hovered:"hovered-L0xapso5","i-active":"i-active-L0xapso5"}},986564:e=>{e.exports={"css-value-pane-controls-padding-left":"1px","css-value-pane-controls-padding-right":"4px"}},854606:e=>{e.exports={paneSeparator:"paneSeparator-uqBaC1Ki",handle:"handle-uqBaC1Ki",hovered:"hovered-uqBaC1Ki",active:"active-uqBaC1Ki"}},604481:e=>{e.exports={priceScaleModeButtons:"priceScaleModeButtons-PEm49B2T",priceScaleModeButtons__buttonWrapper:"priceScaleModeButtons__buttonWrapper-PEm49B2T",priceScaleModeButtons__button:"priceScaleModeButtons__button-PEm49B2T",priceScaleModeButtons__button_activated:"priceScaleModeButtons__button_activated-PEm49B2T"}},529191:e=>{e.exports={"css-value-small-size":"18px","css-value-medium-size":"22px","css-value-large-size":"28px","css-value-border-radius-small-size":"9px","css-value-border-radius-medium-size":"11px","css-value-border-radius-large-size":"8px",statuses:"statuses-Lgtz1OtS",statusItem:"statusItem-Lgtz1OtS",statuses_hidden:"statuses_hidden-Lgtz1OtS",small:"small-Lgtz1OtS",medium:"medium-Lgtz1OtS",large:"large-Lgtz1OtS",blinking:"blinking-Lgtz1OtS","blinking-animation":"blinking-animation-Lgtz1OtS",marketStatusOpen:"marketStatusOpen-Lgtz1OtS",marketStatusClose:"marketStatusClose-Lgtz1OtS",marketStatusPre:"marketStatusPre-Lgtz1OtS",marketStatusPost:"marketStatusPost-Lgtz1OtS",marketStatusHoliday:"marketStatusHoliday-Lgtz1OtS",marketStatusDelisted:"marketStatusDelisted-Lgtz1OtS",marketStatusExpired:"marketStatusExpired-Lgtz1OtS",marketStatusCustom:"marketStatusCustom-Lgtz1OtS",invalidSymbol:"invalidSymbol-Lgtz1OtS",replayModeAutoPlay:"replayModeAutoPlay-Lgtz1OtS",replayModePause:"replayModePause-Lgtz1OtS",replayModePointSelect:"replayModePointSelect-Lgtz1OtS","blinking-animation-custom":"blinking-animation-custom-Lgtz1OtS",notAccurate:"notAccurate-Lgtz1OtS",openedInPineEditor:"openedInPineEditor-Lgtz1OtS",openedInDetachedPineEditor:"openedInDetachedPineEditor-Lgtz1OtS",delay:"delay-Lgtz1OtS",eod:"eod-Lgtz1OtS",dataProblemHigh:"dataProblemHigh-Lgtz1OtS",dataProblemLow:"dataProblemLow-Lgtz1OtS"}},538660:(e,t,i)=>{"use strict";i.d(t,{ChartSession:()=>c});var s=i(707957),o=i(650151),r=i(401580),n=i(541558);const a=(0,i(201089).getLogger)("ChartApi.AbstractSession");var l=i(389137);class c extends class{constructor(e,t,i){this._isConnected=new r.WatchedValue(!1),this._state=0,this._isConnectForbidden=!1,this._sessionId="",this._sessionIdChanged=new s.Delegate,this._chartApi=e,this._sessionPrefix=t,this._shouldReconnectAfterCriticalError=i}destroy(){this._logNormal("Destroying session"),this._isConnected.unsubscribe(),this.disconnect(), this._sessionIdChanged.destroy(),delete this._chartApi,this._logNormal("Session has been destroyed")}isConnected(){return this._isConnected}sessionId(){return this._sessionId}onSessionIdChanged(){return this._sessionIdChanged}connect(){0===this._state&&((0,o.assert)(!this._isConnectForbidden,"Cannot call connect because it is forbidden at this moment"),this._setSessionId(`${this._sessionPrefix}_${(0,n.randomHash)()}`),this._logNormal("Connecting session - wait until transport stay connected"),this._state=1,this._chartApi.createSession(this._sessionId,this))}disconnect(){0!==this._state&&((0,o.assert)(""!==this._sessionId,"sessionId must not be invalid"),this._logNormal("Disconnecting session..."),this._forbidConnectWhile((()=>{this._chartApi.connected()&&this._sendRemoveSession(),this._processDestroyingOnServer()})))}onMessage(e){switch(e.method){case"connected":return void this._onChartApiConnected();case"disconnected":return void this._onChartApiDisconnected();case"critical_error":const t=String(e.params[0]),i=String(e.params[1]);return void this._onCriticalError(t,i)}this._onMessage(e)}serverTime(){return this._chartApi.serverTime()}_getChartApi(){return this._chartApi}_generateLogMessage(e){return`[${this._sessionId}] ${e}`}_onCriticalError(e,t){this._logError(`Critical error. Reason=${e}, info=${t}.`),this._forbidConnectWhile((()=>{this._processDestroyingOnServer()})),this._shouldReconnectAfterCriticalError?(this._logNormal("Reconnecting after critical error..."),this.connect()):this._logNormal("Reconnecting after critical error skipped")}_onChartApiConnected(){(0,o.assert)(1===this._state,"Session is not registered"),this._logNormal("Transport is connected. Creating session on the server"),this._sendCreateSession(),this._state=2,this._isConnected.setValue(!0)}_onChartApiDisconnected(){this._logNormal("Transport is disconnected. Reconnecting..."),this._forbidConnectWhile((()=>{this._processDestroyingOnServer()})),this.connect()}_setSessionId(e){const t=this._sessionId;this._logNormal(`Changing sessionId: old=${t}, new=${e}`),this._sessionId=e,this._sessionIdChanged.fire(e,t)}_logNormal(e){a.logNormal(this._generateLogMessage(e))}_logError(e){a.logError(this._generateLogMessage(e))}_processDestroyingOnServer(){this._state=0,this._isConnected.setValue(!1),this._chartApi.removeSession(this._sessionId),this._setSessionId("")}_forbidConnectWhile(e){this._isConnectForbidden=!0,e(),this._isConnectForbidden=!1}}{constructor(e,t=!1){super(e,"cs",!1),this._sessionDisabled=!1,this._handler=null,this._criticalError=new s.Delegate,this._symbolResolveMap=new Map,this._lastSymbolResolveInfoMap=new Map,this._disableStatistics=t}destroy(){this._criticalError.destroy(),this._handler=null,this._symbolResolveMap.clear(),super.destroy()}switchTimezone(e){return this._getChartApi().switchTimezone(this.sessionId(),e)}defaultResolutions(){return this._getChartApi().defaultResolutions()}availableCurrencies(){return this._getChartApi().availableCurrencies()}availableUnits(){return this._getChartApi().availableUnits()} availablePriceSources(e){return this._getChartApi().availablePriceSources(e)}resolveSymbol(e,t,i){if(this._symbolResolveMap.has(t)){const[e,s]=this._symbolResolveMap.get(t);return Array.isArray(s)?s.push(i):s.then(i),e}{const s=[i];return this._getChartApi().resolveSymbol(this.sessionId(),e,t,(i=>{if("symbol_error"===i.method)this._symbolResolveMap.delete(t);else{this._symbolResolveMap.set(t,[e,Promise.resolve(i)]);const[,s]=i.params,o={pro_name:s.pro_name,ticker:s.ticker};this._lastSymbolResolveInfoMap.set(t,o),o.pro_name&&this._lastSymbolResolveInfoMap.set(o.pro_name,o),s.full_name&&this._lastSymbolResolveInfoMap.set(s.full_name,o),o.ticker&&this._lastSymbolResolveInfoMap.set(o.ticker,o)}s.forEach((e=>e(i)))})),this._symbolResolveMap.set(t,[e,s]),e}}requestFirstBarTime(e,t,i){return this._getChartApi().requestFirstBarTime(this.sessionId(),e,t,i)}lastSymbolResolveInfo(e){var t;return null!==(t=this._lastSymbolResolveInfoMap.get(e))&&void 0!==t?t:null}createSeries(e,t,i,s,o,r,n){return this._getChartApi().createSeries(this.sessionId(),e,t,i,s,o,r,n)}modifySeries(e,t,i,s,o,r,n){return this._getChartApi().modifySeries(this.sessionId(),e,t,i,s,o,r,n)}removeSeries(e){return!!this.isConnected().value()&&this._getChartApi().removeSeries(this.sessionId(),e)}requestMoreData(e,t,i){return"number"==typeof e?this._getChartApi().requestMoreData(this.sessionId(),e):this._getChartApi().requestMoreData(this.sessionId(),e,t,i)}requestMoreTickmarks(e,t,i){return(0,l.isNumber)(e)?this._getChartApi().requestMoreTickmarks(this.sessionId(),e):this._getChartApi().requestMoreTickmarks(this.sessionId(),e,t,i)}canCreateStudy(e,t){return this._getChartApi().canCreateStudy(this.sessionId(),e,t)}getStudyCounter(){return this._getChartApi().getStudyCounter(this.sessionId())}getFundamentalCounter(){return this._getChartApi().getFundamentalCounter(this.sessionId())}createStudy(e,t,i,s,o,r,n){return this._getChartApi().createStudy(this.sessionId(),e,t,i,s,o,r,n)}modifyStudy(e,t,i,s,o){return this._getChartApi().modifyStudy(this.sessionId(),e,t,i,s,o)}notifyStudy(e,t,i){return this._getChartApi().notifyStudy(this.sessionId(),e,t,i)}removeStudy(e){return this._getChartApi().removeStudy(this.sessionId(),e)}createPointset(e,t,i,s,o,r){return this._getChartApi().createPointset(this.sessionId(),e,t,i,s,o,r)}modifyPointset(e,t,i,s){return this._getChartApi().modifyPointset(this.sessionId(),e,t,i,s)}removePointset(e){return this._getChartApi().removePointset(this.sessionId(),e)}setVisibleTimeRange(e,t,i,s,o,r){0}criticalError(){return this._criticalError}connect(e=null){null!==e&&(this._handler=e),this._symbolResolveMap.clear(),super.connect()}setHandler(e){this._handler=e}connected(){return this.isConnected().value()&&!this._sessionDisabled}disable(){this._sessionDisabled=!0}chartApi(){return this._getChartApi()}_sendCreateSession(){Object.keys(this).forEach((e=>{/^(s|st|symbol_)\d+$/.test(e)&&delete this[e]})),this._getChartApi().chartCreateSession(this.sessionId(),this._disableStatistics)}_sendRemoveSession(){ this._getChartApi().chartDeleteSession(this.sessionId())}_onMessage(e){this._handler&&this._handler(e)}_onCriticalError(e,t){this._criticalError.fire(e,t),super._onCriticalError(e,t)}}},15458:(e,t,i)=>{"use strict";i.r(t),i.d(t,{availableTimezones:()=>l,timezoneIsAvailable:()=>u,timezoneIsSupported:()=>_,timezoneTitle:()=>p,updateAvailableTimezones:()=>h});var s=i(444372),o=i(245302);const r=[{id:"Etc/UTC",title:s.t(null,void 0,i(850406))},{id:"exchange",title:s.t(null,void 0,i(777295))}],n=[{id:"Africa/Cairo",title:s.t(null,void 0,i(994099)),offset:0},{id:"Africa/Casablanca",title:s.t(null,void 0,i(753705)),offset:0},{id:"Africa/Johannesburg",title:s.t(null,void 0,i(387469)),offset:0},{id:"Africa/Lagos",title:s.t(null,void 0,i(89155)),offset:0},{id:"Africa/Nairobi",title:s.t(null,void 0,i(679023)),offset:0},{id:"Africa/Tunis",title:s.t(null,void 0,i(193855)),offset:0},{id:"America/Anchorage",title:s.t(null,void 0,i(399873)),offset:0},{id:"America/Argentina/Buenos_Aires",title:s.t(null,void 0,i(882446)),offset:0},{id:"America/Bogota",title:s.t(null,void 0,i(54173)),offset:0},{id:"America/Caracas",title:s.t(null,void 0,i(846837)),offset:0},{id:"America/Chicago",title:s.t(null,void 0,i(228244)),offset:0},{id:"America/El_Salvador",title:s.t(null,void 0,i(768553)),offset:0},{id:"America/Juneau",title:s.t(null,void 0,i(124435)),offset:0},{id:"America/Lima",title:s.t(null,void 0,i(725846)),offset:0},{id:"America/Los_Angeles",title:s.t(null,void 0,i(687604)),offset:0},{id:"America/Mexico_City",title:s.t(null,void 0,i(185095)),offset:0},{id:"America/New_York",title:s.t(null,void 0,i(291203)),offset:0},{id:"America/Phoenix",title:s.t(null,void 0,i(219093)),offset:0},{id:"America/Santiago",title:s.t(null,void 0,i(965412)),offset:0},{id:"America/Sao_Paulo",title:s.t(null,void 0,i(913538)),offset:0},{id:"America/Toronto",title:s.t(null,void 0,i(83836)),offset:0},{id:"America/Vancouver",title:s.t(null,void 0,i(115771)),offset:0},{id:"US/Mountain",title:s.t(null,void 0,i(257701)),offset:0},{id:"Asia/Almaty",title:s.t(null,void 0,i(391013)),offset:0},{id:"Asia/Ashkhabad",title:s.t(null,void 0,i(559340)),offset:0},{id:"Asia/Bahrain",title:s.t(null,void 0,i(53260)),offset:0},{id:"Asia/Bangkok",title:s.t(null,void 0,i(732376)),offset:0},{id:"Asia/Chongqing",title:s.t(null,void 0,i(649648)),offset:0},{id:"Asia/Colombo",title:s.t(null,void 0,i(115168)),offset:0},{id:"Asia/Dhaka",title:s.t(null,void 0,i(724477)),offset:0},{id:"Asia/Dubai",title:s.t(null,void 0,i(822429)),offset:0},{id:"Asia/Ho_Chi_Minh",title:s.t(null,void 0,i(587338)),offset:0},{id:"Asia/Hong_Kong",title:s.t(null,void 0,i(532918)),offset:0},{id:"Asia/Jakarta",title:s.t(null,void 0,i(652707)),offset:0},{id:"Asia/Jerusalem",title:s.t(null,void 0,i(642890)),offset:0},{id:"Asia/Karachi",title:s.t(null,void 0,i(202693)),offset:0},{id:"Asia/Kathmandu",title:s.t(null,void 0,i(303155)),offset:0},{id:"Asia/Kolkata",title:s.t(null,void 0,i(916245)),offset:0},{id:"Asia/Kuala_Lumpur",title:s.t(null,void 0,i(710086)),offset:0},{id:"Asia/Kuwait",title:s.t(null,void 0,i(872374)), offset:0},{id:"Asia/Manila",title:s.t(null,void 0,i(290271)),offset:0},{id:"Asia/Muscat",title:s.t(null,void 0,i(442769)),offset:0},{id:"Asia/Nicosia",title:s.t(null,void 0,i(733566)),offset:0},{id:"Asia/Qatar",title:s.t(null,void 0,i(619056)),offset:0},{id:"Asia/Riyadh",title:s.t(null,void 0,i(152588)),offset:0},{id:"Asia/Seoul",title:s.t(null,void 0,i(605961)),offset:0},{id:"Asia/Shanghai",title:s.t(null,void 0,i(969240)),offset:0},{id:"Asia/Singapore",title:s.t(null,void 0,i(156683)),offset:0},{id:"Asia/Taipei",title:s.t(null,void 0,i(438788)),offset:0},{id:"Asia/Tehran",title:s.t(null,void 0,i(16267)),offset:0},{id:"Asia/Tokyo",title:s.t(null,void 0,i(294284)),offset:0},{id:"Asia/Yangon",title:s.t(null,void 0,i(769293)),offset:0},{id:"Atlantic/Reykjavik",title:s.t(null,void 0,i(626833)),offset:0},{id:"Australia/Adelaide",title:s.t(null,void 0,i(717365)),offset:0},{id:"Australia/Brisbane",title:s.t(null,void 0,i(511741)),offset:0},{id:"Australia/Perth",title:s.t(null,void 0,i(635590)),offset:0},{id:"Australia/Sydney",title:s.t(null,void 0,i(111020)),offset:0},{id:"Europe/Amsterdam",title:s.t(null,void 0,i(688010)),offset:0},{id:"Europe/Athens",title:s.t(null,void 0,i(921983)),offset:0},{id:"Europe/Belgrade",title:s.t(null,void 0,i(254861)),offset:0},{id:"Europe/Berlin",title:s.t(null,void 0,i(326825)),offset:0},{id:"Europe/Bratislava",title:s.t(null,void 0,i(605262)),offset:0},{id:"Europe/Brussels",title:s.t(null,void 0,i(690204)),offset:0},{id:"Europe/Bucharest",title:s.t(null,void 0,i(537728)),offset:0},{id:"Europe/Budapest",title:s.t(null,void 0,i(787143)),offset:0},{id:"Europe/Copenhagen",title:s.t(null,void 0,i(743432)),offset:0},{id:"Europe/Dublin",title:s.t(null,void 0,i(609497)),offset:0},{id:"Europe/Helsinki",title:s.t(null,void 0,i(899820)),offset:0},{id:"Europe/Istanbul",title:s.t(null,void 0,i(537885)),offset:0},{id:"Europe/Lisbon",title:s.t(null,void 0,i(450091)),offset:0},{id:"Europe/London",title:s.t(null,void 0,i(50286)),offset:0},{id:"Europe/Luxembourg",title:s.t(null,void 0,i(164352)),offset:0},{id:"Europe/Madrid",title:s.t(null,void 0,i(758038)),offset:0},{id:"Europe/Malta",title:s.t(null,void 0,i(334190)),offset:0},{id:"Europe/Moscow",title:s.t(null,void 0,i(118665)),offset:0},{id:"Europe/Oslo",title:s.t(null,void 0,i(782906)),offset:0},{id:"Europe/Paris",title:s.t(null,void 0,i(595995)),offset:0},{id:"Europe/Prague",title:s.t(null,void 0,i(546298)),offset:0},{id:"Europe/Riga",title:s.t(null,void 0,i(605871)),offset:0},{id:"Europe/Rome",title:s.t(null,void 0,i(974214)),offset:0},{id:"Europe/Stockholm",title:s.t(null,void 0,i(248767)),offset:0},{id:"Europe/Tallinn",title:s.t(null,void 0,i(939108)),offset:0},{id:"Europe/Vienna",title:s.t(null,void 0,i(732166)),offset:0},{id:"Europe/Vilnius",title:s.t(null,void 0,i(475354)),offset:0},{id:"Europe/Warsaw",title:s.t(null,void 0,i(48474)),offset:0},{id:"Europe/Zurich",title:s.t(null,void 0,i(984301)),offset:0},{id:"Pacific/Auckland",title:s.t(null,void 0,i(824143)),offset:0},{id:"Pacific/Chatham",title:s.t(null,void 0,i(59884)),offset:0},{ id:"Pacific/Fakaofo",title:s.t(null,void 0,i(520466)),offset:0},{id:"Pacific/Honolulu",title:s.t(null,void 0,i(961351)),offset:0},{id:"Pacific/Norfolk",title:s.t(null,void 0,i(99203)),offset:0}];function a(e,t,i){const s=function(e){return e.map((({id:e,title:t})=>{const{string:i,offset:s}=(0,o.parseTzOffset)(e);return{id:e,offset:s,title:`(${i}) ${t}`}}))}(e),r=i.filter((({alias:e})=>Boolean(e))).map((({title:e,alias:t,id:i})=>{const{string:s,offset:r}=(0,o.parseTzOffset)(t);return{id:i,offset:r,title:`(${s}) ${e}`,alias:t}})),n=function(e){return e.sort(((e,t)=>{const i=e.offset-t.offset;return 0!==i?i:e.title.localeCompare(t.title)}))}(s.concat(r));return t.concat(n)}const l=a(n,r,[]),c=new Map;l.forEach((e=>{c.set(e.id,!0)}));const d=new Map;r.concat(n).forEach((e=>{d.set(e.id,!0)}));const h=e=>{l.splice(0,l.length,...a(n,r,e)),l.forEach((e=>{c.set(e.id,!0)}))};function u(e){return c.has(e)}function _(e){return d.get(e)||!1}function p(e){for(const{id:t,title:i}of n)if(t===e){return`${i} (${(0,o.parseTzOffset)(e).string})`}for(const{id:t,title:i}of l)if(t===e)return`${i}`;return e}},651065:(e,t,i)=>{"use strict";function s(e){return"economic"===e}i.d(t,{isNonTradableSymbolType:()=>s})},230285:(e,t,i)=>{"use strict";function s(e){return e.includes(":")?e.split(":"):["",e]}i.d(t,{splitSymbolName:()=>s})},747971:(e,t,i)=>{"use strict";i.d(t,{ActionWithStandardIcon:()=>r});var s=i(373571),o=i(982368);class r extends s.Action{constructor(e){var t,i;const{options:s,customActionOptions:r}=e;s.iconId&&(s.icon=null!==(t=s.icon)&&void 0!==t?t:o.icons.get(s.iconId)),r&&r.iconId&&(r.icon=null!==(i=r.icon)&&void 0!==i?i:o.icons.get(r.iconId)),super(e)}}},982368:(e,t,i)=>{"use strict";i.d(t,{icons:()=>E});var s=i(539706),o=i(472382),r=i(198083),n=i(80465),a=i(748040),l=i(324020),c=i(527409),d=i(845437),h=i(428026),u=i(625923),_=i(270068),p=i(789795),m=i(439970),g=i(808757),S=i(634369),v=i(139267),f=i(993544),b=i(484959),y=i(437924),C=i(677067),w=i(416911),P=i(225191),T=i(854190),M=i(706862),x=i(397874),I=i(902872),A=i(201457),L=i(593379);let k=[["Chart.Reset",v],["Chart.RemoveSelectedObject",f],["Settings",S],["Chart.Hide",b],["Chart.SymbolInfo",y],["Chart.VisualOrder",C],["Chart.ShowObject",w],["Chart.PriceScale",P],["Chart.Move",T],["Chart.ApplyIndicator",M],["Chart.UnlockObject",x],["Chart.LockObject",I],["Chart.Clone",A],["Chart.AddHorzLine",L]];k=k.concat([["TextNote.Add",l],["Platform.ColorTheme",c],["Watchlist.AddSymbol",d],["Watchlist.CreateNew",d],["Chart.Financials",h],["Alert.Add",u],["Alert.Edit",_],["Alert.Restart",p],["Alert.Stop",m],["Alert.EventsExport",g]]),k=k.concat([["Chart.ShowDataWindow",s],["Trading.Sell",o],["Trading.Buy",r],["ObjectsTree.CreateGroup",n],["ObjectsTree.RenameItem",a]]);const E=new Map(k)},794389:(e,t,i)=>{"use strict";i.d(t,{Animation:()=>n});var s=i(81979),o=i(764005);const r={duration:250,easing:s.easingFunc.easeOutCubic};class n{constructor(e){this._onFinishCalled=!1,this._options={...r,...e},this._startTime=performance.now()}getStartPosition(){return this._options.from}getPosition(e){ const t=this._calculateProgress(e);return 1===t?(this._options.onFinish&&!this._onFinishCalled&&(this._options.onFinish(!0),this._onFinishCalled=!0),this._options.to):(0,o.lerp)(this._options.from,this._options.to,this._options.easing(t))}finished(e){return 1===this._calculateProgress(e)}onFinish(e){var t,i;this._onFinishCalled||(null===(i=(t=this._options).onFinish)||void 0===i||i.call(t,e),this._onFinishCalled=!0)}_calculateProgress(e){const t=e-this._startTime;return t>=this._options.duration?1:t/this._options.duration}}},356893:(e,t,i)=>{"use strict";i.d(t,{clipboardDataForSources:()=>l,isLineToolClipboardData:()=>a});var s=i(650151),o=i(982217),r=i(238433),n=i(713473);function a(e){return"drawing"===e.type}function l(e,t){if(1===t.length&&(0,r.isStudy)(t[0])){const e=t[0];return{title:e.title(o.TitleDisplayTarget.StatusLine),sources:[{source:(0,s.ensureNotNull)(e.state()),type:"study"}]}}const i={sources:[],title:""};return i.sources=t.filter((e=>e.copiable()&&(0,n.isLineTool)(e))).map((t=>{const i={type:"drawing",geometry:t.geometry(),source:{...t.state(!1),points:t.normalizedPoints()},modelId:e};return delete i.source.alertId,i})),i.sources.length>0?(1===i.sources.length?i.title=t[0].title(o.TitleDisplayTarget.StatusLine):i.title="Drawings",i):null}},237872:(e,t,i)=>{"use strict";i.d(t,{ChartHotkeysListener:()=>v,globalEnvironmentState:()=>S,modifierPressed:()=>g,shiftPressed:()=>m});var s,o,r,n=i(799786),a=i(470316),l=i(515312),c=i(401580),d=i(950740);const h=new c.WatchedValue(Boolean((null!==(s=n.pressedKeys.value())&&void 0!==s?s:0)&a.Modifiers.Shift)),u=new c.WatchedValue(Boolean((null!==(o=n.pressedKeys.value())&&void 0!==o?o:0)&a.Modifiers.Mod)),_=new c.WatchedValue(Boolean((null!==(r=n.pressedKeys.value())&&void 0!==r?r:0)&a.Modifiers.Alt)),p=[a.Modifiers.None,a.Modifiers.Alt,a.Modifiers.Mod,a.Modifiers.Alt+a.Modifiers.Shift];function m(){return h}function g(){return u}function S(){return new d.EnvironmentState({altKey:_.value(),ctrlKey:g().value(),metaKey:g().value(),shiftKey:m().value()})}n.pressedKeys.subscribe(((e=0)=>{h.setValue(Boolean(e&a.Modifiers.Shift)),u.setValue(Boolean(e&a.Modifiers.Mod)),_.setValue(Boolean(e&a.Modifiers.Alt))}));class v{constructor(e,t){this._pressedKeyCode=null,this._boundKeydownHandler=null,this._boundKeyupHandler=null,this._chartWidget=e,this._parent=t,this._boundKeydownHandler=this._keydownHandler.bind(this),this._boundKeyupHandler=this._keyupHandler.bind(this),this._parent.ownerDocument.addEventListener("keydown",this._boundKeydownHandler),this._parent.ownerDocument.addEventListener("keyup",this._boundKeyupHandler)}destroy(){null!==this._boundKeydownHandler&&(this._parent.ownerDocument.removeEventListener("keydown",this._boundKeydownHandler),this._boundKeydownHandler=null),null!==this._boundKeyupHandler&&(this._parent.ownerDocument.removeEventListener("keyup",this._boundKeyupHandler),this._boundKeyupHandler=null)}_keydownHandler(e){ this._chartWidget.hasModel()&&window.document.activeElement===window.document.body&&this._chartWidget.isActive().value()&&(e.defaultPrevented||(this._handleMoveDrawingsKeyDown(e)||this._handleScrollKeyDown(e)||this._handleZoomKeyDown(e))&&e.preventDefault())}_keyupHandler(e){this._chartWidget.hasModel()&&this._handleScrollKeyUp(e)}_handleMoveDrawingsKeyDown(e){const t=255&(0,a.hashFromEvent)(e),i=this._chartWidget.model();switch(t){case 37:return i.moveSelectedToolsLeft();case 39:return i.moveSelectedToolsRight();case 38:return i.moveSelectedToolsUp();case 40:return i.moveSelectedToolsDown()}return!1}_handleScrollKeyDown(e){if(null!==this._pressedKeyCode)return!1;const t=(0,a.hashFromEvent)(e),i=255&t,s=(0,a.modifiersFromEvent)(e);let o;if(37===i)o=1;else{if(39!==i)return!1;o=-1}return!(a.isMacKeyboard&&s===a.Modifiers.Mod||!p.includes(s))&&(!(0,l.isNativeUIInteraction)(t,e.target)&&(this._pressedKeyCode=i,s===a.Modifiers.None?this._chartWidget.scrollHelper().moveByBar(o):s===a.Modifiers.Alt||s===a.Modifiers.Mod?this._chartWidget.scrollHelper().move(o):-1===o?this._chartWidget.model().timeScale().scrollToRealtime(!0):this._chartWidget.model().timeScale().scrollToFirstBar(),!0))}_handleScrollKeyUp(e){if(null===this._pressedKeyCode)return!1;const t=(0,a.hashFromEvent)(e);if((0,l.isNativeUIInteraction)(t,e.target))return!1;return(255&t)===this._pressedKeyCode&&(this._pressedKeyCode=null,this._chartWidget.scrollHelper().stopMove(),!0)}_handleZoomKeyDown(e){const t=(0,a.hashFromEvent)(e),i=255&t;if((0,a.modifiersFromEvent)(e)!==a.Modifiers.Mod||(0,l.isNativeUIInteraction)(t,e.target))return!1;const s=this._chartWidget.model();if(38===i)s.zoomIn();else{if(40!==i)return!1;s.zoomOut()}return!0}}},148010:(e,t,i)=>{"use strict";i.d(t,{ChartWidgetBase:()=>Cc});var s=i(743068),o=i(895171),r=i(650151),n=i(591800),a=i(444372),l=i(251954),c=i(638456),d=i(62802),h=i(429874),u=i(345848),_=i(799786),p=i(246733),m=i(201089),g=i(268222),S=i(242907),v=i(560420),f=i(951713),b=i(111393);let y;class C extends b.DialogRenderer{constructor(){super(),this._dialog=null,this._subscribe=e=>{this._setVisibility(e)}}show(){this._load().then((e=>e.show()))}hide(){var e;null===(e=this._dialog)||void 0===e||e.hide()}static getInstance(){return y||(y=new C),y}_load(){return Promise.all([i.e(32662),i.e(5987),i.e(98996),i.e(66458),i.e(5761),i.e(4343),i.e(28430),i.e(70428),i.e(44597),i.e(1413),i.e(70621),i.e(89508),i.e(62033),i.e(13633),i.e(19216),i.e(85258),i.e(36701),i.e(87940),i.e(61576),i.e(63751),i.e(91986),i.e(71093),i.e(5400),i.e(5824),i.e(57254),i.e(27990),i.e(1993),i.e(43912),i.e(90385),i.e(92833),i.e(5483),i.e(60801),i.e(41167),i.e(27404),i.e(56694),i.e(48662),i.e(81137),i.e(34862)]).then(i.bind(i,938785)).then((e=>{var t,i;return null===(t=this._dialog)||void 0===t||t.hide(),null===(i=this._dialog)||void 0===i||i.visible().unsubscribe(this._subscribe),this._dialog=new e.ObjectTreeDialogRenderer,this._dialog.visible().subscribe(this._subscribe),this._dialog}))}}var w=i(389137),P=i(62745),T=i(354950);async function M(e,t,s,o,r,n="default"){ let l,c=[];const d=e.model().model(),h=(0,w.clone)(t),u=new T.Property({inputs:h}),_=function(e,t){return"symbol"===t?e.inputs.filter((t=>t.id===e.symbolInputId())):e.inputs.filter((e=>e.confirm))}(s,n),p=()=>{l&&d.removeCustomSource(l)},m=()=>{p(),r()},g=e=>{o({inputs:e,parentSources:c}),p()},S=_.filter(P.isTimeOrPriceNotHiddenInput);if(S.length>0)try{const t=await Promise.all([i.e(14819),i.e(73224),i.e(72718),i.e(93327),i.e(99410),i.e(32662),i.e(5987),i.e(98996),i.e(43387),i.e(66458),i.e(5761),i.e(4343),i.e(28430),i.e(70428),i.e(44597),i.e(1413),i.e(4908),i.e(52078),i.e(70621),i.e(89508),i.e(62033),i.e(13633),i.e(61204),i.e(19216),i.e(37132),i.e(66323),i.e(14),i.e(50473),i.e(37657),i.e(35697),i.e(31149),i.e(85258),i.e(16005),i.e(79656),i.e(83483),i.e(87940),i.e(63276),i.e(63751),i.e(5378),i.e(29647),i.e(77382),i.e(87473),i.e(10637),i.e(16165),i.e(85131),i.e(10714),i.e(94712),i.e(44794),i.e(39076),i.e(45338),i.e(66233),i.e(47877),i.e(42332),i.e(57876),i.e(84418),i.e(95884),i.e(20221),i.e(21975),i.e(70631),i.e(98133),i.e(45183),i.e(55713),i.e(75803),i.e(38982),i.e(90385),i.e(92833),i.e(42942),i.e(3889),i.e(92158),i.e(39434),i.e(68581),i.e(18561),i.e(26854),i.e(70334),i.e(97406),i.e(31063),i.e(53030)]).then(i.bind(i,280881)),o=await t.selectInputValuesOnChart(e,S,u,s.shortDescription,s.inputs);if(l=o.customSourceId,o.destPane){const e=o.destPane.mainDataSource();c=e===d.mainSeries()?[]:[e]}else c=[]}catch(e){return void m()}S.length!==_.length?Promise.all([i.e(14819),i.e(73224),i.e(72718),i.e(93327),i.e(99410),i.e(32662),i.e(5987),i.e(98996),i.e(43387),i.e(66458),i.e(5761),i.e(4343),i.e(28430),i.e(70428),i.e(44597),i.e(1413),i.e(4908),i.e(52078),i.e(70621),i.e(89508),i.e(62033),i.e(13633),i.e(61204),i.e(19216),i.e(37132),i.e(66323),i.e(14),i.e(50473),i.e(37657),i.e(35697),i.e(31149),i.e(85258),i.e(16005),i.e(79656),i.e(83483),i.e(87940),i.e(63276),i.e(63751),i.e(5378),i.e(29647),i.e(77382),i.e(87473),i.e(10637),i.e(16165),i.e(85131),i.e(10714),i.e(94712),i.e(44794),i.e(39076),i.e(45338),i.e(66233),i.e(47877),i.e(42332),i.e(57876),i.e(84418),i.e(95884),i.e(20221),i.e(21975),i.e(70631),i.e(98133),i.e(45183),i.e(55713),i.e(75803),i.e(38982),i.e(90385),i.e(92833),i.e(42942),i.e(3889),i.e(92158),i.e(39434),i.e(68581),i.e(18561),i.e(26854),i.e(70334),i.e(97406),i.e(31063),i.e(53030)]).then(i.bind(i,49294)).then((t=>{const o=new t.ConfirmInputsDialogRenderer(function(e){if("symbol"===e)return a.t(null,void 0,i(345743));return a.t(null,void 0,i(846689))}(n),_,u,n,s,e.model(),g,m);return o.show(),o})):g(u.state().inputs||{})}let x=null;var I=i(941285),A=i(674981),L=i(66732),k=i(15458),E=i(707957),D=i(244842);function B(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function N(e){return e.reduce(((e,t)=>{for(const i in t)if(B(t,i)){const s=t[i],o=e[i];o?o.push(s):e[i]=[s]}return e}),{})}var R=i(809796),O=i(401580),V=i(199471),W=i(237872);const F=new R.TranslatedString("move left",a.t(null,void 0,i(415086))),H=new R.TranslatedString("move right",a.t(null,void 0,i(461711)));class z{constructor(e){this._chartModel=null, this._animation=null,this._chart=e,this._chart.withModel(this,(()=>{this._chartModel=this._chart.model()}))}destroy(){var e;null===(e=this._animation)||void 0===e||e.stop()}move(e){if(null!==this._chartModel){if(this._chartModel.timeScale().isEmpty())return;const t=.003,i=1.1,s=Math.round(i/t);this._moveImpl(e,((o,r,n)=>{const a=Math.min(r,s),l=e*t*Math.pow(a,2)/2;if(r<=s)return o+l;const c=Number.isFinite(n)?Math.max(0,s-n):0;return o+l+e*(r-a-c)*i+e*(i*c-t*Math.pow(c,2)/2)}),(e=>Math.max(0,s-e)+s))}}moveByBar(e){if(null!==this._chartModel){const t=this._chartModel.timeScale(),i=t.visibleBarsStrictRange();if(t.isEmpty()||null===i)return;const s=300,o=i.lastBar();this._moveImpl(e,((i,r)=>{const n=Math.floor(Math.max(0,r-s)/100)+1,a=o+e*n,l=t.indexToCoordinate(o);return i+(t.indexToCoordinate(a)-l)}),(()=>0),!0)}}stopMove(){var e;null===(e=this._animation)||void 0===e||e.stop(),this._animation=null}scrollToRealtime(e){null!==this._chartModel&&this._chartModel.timeScale().scrollToRealtime(e)}_moveImpl(e,t,i,s){if(null===this._chartModel)return;const o=this._chartModel.timeScale();if(o.isEmpty())return;if(this._chartModel.changeTimeScale(1===e?F:H,!1),s&&null!==o.visibleBarsStrictRange()){const e=o.indexToCoordinate(o.visibleBarsStrictRange().lastBar())+o.barSpacing()/2;Math.abs(o.width()-e)>o.barSpacing()/6&&o.setRightOffset(Math.round(o.rightOffset()))}const r=performance.now();let n=1/0;this._animation={getStartPosition:()=>0,getPosition:e=>(e=Math.min(n,e),t(0,e-r,n-e)),finished:e=>e>=n,stop:()=>{const e=performance.now()-r;n=performance.now()+i(e)}},this._chartModel.model().stopTimeScaleAnimation(),this._chartModel.model().setTimeScaleAnimation(this._animation)}}var U=i(794349);function G(e,t,s,o,r){return Promise.all([i.e(14819),i.e(73224),i.e(72718),i.e(93327),i.e(36914),i.e(52540),i.e(34477),i.e(96591),i.e(32662),i.e(5987),i.e(98996),i.e(43387),i.e(66458),i.e(5761),i.e(4343),i.e(28430),i.e(70428),i.e(44597),i.e(1413),i.e(4908),i.e(52078),i.e(70621),i.e(89508),i.e(62033),i.e(13633),i.e(61204),i.e(19216),i.e(37132),i.e(66323),i.e(14),i.e(50473),i.e(37657),i.e(35697),i.e(31149),i.e(84331),i.e(85258),i.e(16005),i.e(79656),i.e(83483),i.e(87940),i.e(63276),i.e(63751),i.e(5378),i.e(29647),i.e(82452),i.e(77382),i.e(87473),i.e(10637),i.e(16165),i.e(85131),i.e(10714),i.e(94712),i.e(44794),i.e(39076),i.e(71093),i.e(45338),i.e(66233),i.e(29946),i.e(28593),i.e(47877),i.e(42332),i.e(67154),i.e(57876),i.e(84418),i.e(95884),i.e(20221),i.e(954),i.e(21975),i.e(70631),i.e(98133),i.e(23040),i.e(45183),i.e(55713),i.e(28288),i.e(87142),i.e(30408),i.e(4267),i.e(75803),i.e(99403),i.e(13130),i.e(27363),i.e(84988),i.e(23621),i.e(90385),i.e(92833),i.e(42942),i.e(5483),i.e(60801),i.e(28019),i.e(3889),i.e(92158),i.e(39434),i.e(68581),i.e(18561),i.e(26854),i.e(72539),i.e(70334),i.e(97406),i.e(37305),i.e(31063),i.e(94025),i.e(68052),i.e(61581),i.e(46265)]).then(i.bind(i,336276)).then((i=>{const n=new(0,i.EditObjectDialogRenderer)(e,t,o,r);return n.show(s),n}))}var q=i(238433);let j=null;var Z=i(924788),K=i(713473);const Y={ [U.TabNames.symbol]:"symbol",[U.TabNames.legend]:"legend",[U.TabNames.scales]:"scales",[U.TabNames.trading]:"trading",[U.TabNames.events]:"events",[U.TabNames.eventsAndAlerts]:"events",[U.TabNames.timezoneSessions]:"canvas",[U.TabNames.text]:"text",[U.TabNames.style]:"style",[U.TabNames.visibility]:"visibility"},$={[U.TabNames.style]:"style",[U.TabNames.visibility]:"visibilities"};async function X(e,t,s={},o,r){const n=o.activeChartWidget.value(),{initialTab:a,tabName:l}=s;if(l&&!a&&(s.initialTab=$[l]),(0,K.isStudyLineTool)(e)&&function(e){if(!(0,K.isStudyLineTool)(e))return!1;return["LineToolFixedRangeVolumeProfile","LineToolVbPFixed","LineToolAnchoredVolumeProfile"].filter(w.notNull).some((t=>e.toolname===t))}(e))return n.propertiesDefinitionsForSource(e).then((i=>null!==i?G(e,t,s,r,i):null));if((0,q.isStudy)(e)&&function(e){const{shortId:t}=e.metaInfo();return"Overlay"===t}(e)||(0,K.isLineTool)(e))return n.propertiesDefinitionsForSource(e).then((o=>{if(null!==o){return function(e){return Promise.all([i.e(14819),i.e(73224),i.e(72718),i.e(93327),i.e(52540),i.e(32662),i.e(5987),i.e(98996),i.e(43387),i.e(66458),i.e(5761),i.e(4343),i.e(28430),i.e(70428),i.e(44597),i.e(1413),i.e(4908),i.e(52078),i.e(70621),i.e(89508),i.e(62033),i.e(13633),i.e(61204),i.e(19216),i.e(37132),i.e(66323),i.e(14),i.e(50473),i.e(37657),i.e(35697),i.e(31149),i.e(84331),i.e(85258),i.e(16005),i.e(79656),i.e(83483),i.e(87940),i.e(63276),i.e(63751),i.e(5378),i.e(29647),i.e(77382),i.e(87473),i.e(10637),i.e(16165),i.e(85131),i.e(10714),i.e(94712),i.e(44794),i.e(39076),i.e(71093),i.e(45338),i.e(66233),i.e(29946),i.e(28593),i.e(47877),i.e(42332),i.e(57876),i.e(84418),i.e(95884),i.e(20221),i.e(954),i.e(21975),i.e(70631),i.e(98133),i.e(23040),i.e(45183),i.e(55713),i.e(28288),i.e(87142),i.e(30408),i.e(4267),i.e(75803),i.e(99403),i.e(13130),i.e(84988),i.e(70484),i.e(90385),i.e(92833),i.e(42942),i.e(5483),i.e(60801),i.e(28019),i.e(3889),i.e(92158),i.e(39434),i.e(68581),i.e(18561),i.e(26854),i.e(72539),i.e(70334),i.e(97406),i.e(37305),i.e(31063),i.e(94025),i.e(68052),i.e(61581),i.e(46780)]).then(i.bind(i,757381)).then((t=>{const i=new(0,t.SourcePropertiesEditorRenderer)(e);return null!==j&&j.hide(),i.show({shouldReturnFocus:e.shouldReturnFocus}),j=i,i}))}({propertyPages:o,model:t,source:e,activePageId:l&&Y[l],shouldReturnFocus:s.shouldReturnFocus})}return null}));if((0,q.isStudy)(e)&&!(0,Z.isLollipopDataSource)(e))return G(e,t,s,r);{const t=(0,Z.isLollipopDataSource)(e)?"events":l&&Y[l],i=o.getChartPropertiesDialogRenderer();return i.setActivePage(t),i.show(s)}}var J=i(195294),Q=i(331633),ee=i(61499),te=i(100366),ie=i(1500),se=i(963456),oe=i(444331),re=i(628544);const ne=(0,J.getHexColorByName)("color-cold-gray-700"),ae=(0,J.getHexColorByName)("color-cold-gray-400"),le=(0,J.getHexColorByName)("color-cold-gray-900"),ce=(0,J.getHexColorByName)("color-white"),de=a.t(null,void 0,i(405158));function he(e){return e?{...e,message:(0,se.formatStudyError)(e.message),rawHtml:!0}:null}class ue{constructor(e){this._container=null,this._errorCardRenderer=null, this._mainSeriesErrorMessage=null,this._banErrorMessage=new O.WatchedValue(null).spawn(),this._errorMessageHandler=e=>{e=he(e),this._chartWidget.hasModel()?this._updatePaneWidgets(e):this._renderErrorWithoutModel(e)},this._chartWidget=e,this._subscribeToMainSeriesErrors()}destroy(){var e,t;null===(e=this._mainSeriesErrorMessage)||void 0===e||e.destroy(),this._banErrorMessage.destroy(),null===(t=this._errorCardRenderer)||void 0===t||t.then((e=>{e.container.remove(),e.destroy()}))}updatePaneWidgets(){this._updatePaneWidgets()}setContainer(e){var t;if(this._container!==e){this._container=e,null===(t=this._errorCardRenderer)||void 0===t||t.then((e=>e.container.remove()));const i=this._getErrorMessage();i&&this._errorMessageHandler(i)}}_updatePaneWidgets(e=this._getErrorMessage()){this._chartWidget.paneWidgets().forEach((t=>t.setErrorMessage(e)))}async _renderErrorWithoutModel(e){if(null===this._container||null===e&&null===this._errorCardRenderer)return;const t=await this._getErrorCardRenderer();this._container.contains(t.container)||this._container.appendChild(t.container),t.update(this._createErrorCardRendererState(e))}async _getErrorCardRenderer(){return this._errorCardRenderer||(this._errorCardRenderer=this._createErrorCardRenderer())}async _createErrorCardRenderer(){return new(await(0,te.getErrorCardRenderer)())}_createErrorCardRendererState(e){return e?{message:e.message,icon:e.icon,textColor:Q.watchedTheme.value()===ee.StdTheme.Dark?ae:ne,backgroundColor:Q.watchedTheme.value()===ee.StdTheme.Dark?le:ce,solutionId:e.solutionId,rawHtml:e.rawHtml,buttons:e.buttons}:{message:null}}_subscribeToMainSeriesErrors(){const e=this._chartWidget;this._banErrorMessage=(0,L.combine)((e=>{if(!e)return null;let t;if("banned by ip"===e.reason)t=a.t(null,void 0,i(311884));else t=a.t(null,void 0,i(585684));return{message:t,solutionId:ie.solutionIds.WHY_IS_MY_ACCOUNT_BANNED,icon:"stop-hand"}}),window.ChartApiInstance.connectionBanInfo().weakReference()),this._banErrorMessage.subscribe(this._errorMessageHandler,{callWithLast:!0}),e.withModel(this,(()=>{const t=e.model().model().mainSeries();this._mainSeriesErrorMessage=(0,L.combine)(((t,s)=>{if(t)return t;if(null===s)return null;switch(s.type){case"invalid_symbol":return{message:a.t(null,void 0,i(132619)),icon:"ghost"};case"calculations_error":return{message:s.errorMessage,icon:"attention"};case"no_data":return{message:a.t(null,void 0,i(395222)),icon:"ghost"};case"unsupported_resolution":return this._createErrorParamsForUnsupportedResolution(e)}}),this._banErrorMessage.weakReference(),(0,oe.getSeriesDisplayErrorWV)(t).ownership()),this._mainSeriesErrorMessage.subscribe(this._errorMessageHandler,{callWithLast:!0})}))}_createErrorParamsForUnsupportedResolution(e){const t=e.model(),i=t.mainSeries().unsupportedResolutionState().value();return null===i?null:{message:(0,re.getErrorFromUnsupportedResolutionState)(i,!0),icon:"unsupported-resolution",rawHtml:!0,maxHeight:400,zeroHeight:200,buttons:[{name:de.format({resolution:i.applicableResolution}),onClick:()=>{ t.setResolution(t.model().mainSeries(),i.applicableResolution)}}]}}_getErrorMessage(){var e;return he(this._banErrorMessage.value()||(null===(e=this._mainSeriesErrorMessage)||void 0===e?void 0:e.value())||null)}}var _e=i(109154),pe=i(572230),me=i(86121),ge=i(533422),Se=i(792795),ve=i(826989),fe=i(339315),be=i(288812);class ye{constructor(e,t){this._showed=!1,this._cw=e,this._element=document.createElement("div"),this._element.classList.add(be.screen),t.appendChild(this._element),this._cw.withModel(this,this._connectToModel)}show(e){if(e){const e=this._cw.model().mainSeries().status();if(1!==e&&2!==e)return}this._cw.setInLoadingState(!0),this._showed||(this._showed=!0,this._show())}hide(){this._cw.setInLoadingState(!1),this._showed&&this._hide()}isShown(){return this._showed}_connectToModel(){const e=this._cw.model().mainSeries(),t=e.dataEvents();t.symbolError().subscribe(this,(e=>{e!==ve.permissionDenied&&this.hide()})),t.seriesError().subscribe(this,(()=>{(0,D.enabled)("hide_loading_screen_on_series_error")&&this.hide()})),e.statusWV().subscribe((e=>{(fe.seriesReadyStatuses.has(e)||4===e||12===e||13===e||14===e)&&this.hide()}))}_show(){const e=this._cw.properties().childs().paneProperties.childs();let t;if(e.backgroundType.value()===Se.ColorType.Solid)t=e.background.value();else{t=`linear-gradient(${e.backgroundGradientStartColor.value()},${e.backgroundGradientEndColor.value()})`}this._element.style.background=t,this._element.classList.add(be.fade)}_hide(){this._showed=!1,this._element.classList.remove(be.fade)}}function Ce(e,t){let{deltaX:i,deltaY:s}=e;switch(i/=100,s/=100,t.deltaMode){case t.DOM_DELTA_PAGE:i*=120,s*=120;break;case t.DOM_DELTA_LINE:i*=32,s*=32}return{deltaX:i,deltaY:s}}class we{constructor(){this._totalDeltaX=0,this._totalDeltaY=0,this._prevWheelTime=0}processWheel(e){e.timeStamp-this._prevWheelTime>100&&this._reset();const t=!(0,c.isMac)()&&e.shiftKey,i=t?-e.deltaY:e.deltaX,s=t?e.deltaX:e.deltaY;this._totalDeltaX+=i,this._totalDeltaY+=s,this._prevWheelTime=e.timeStamp;const o={deltaX:i,deltaY:s};return 0===this._totalDeltaX||0===this._totalDeltaY||(Math.abs(this._totalDeltaX)>=Math.abs(3*this._totalDeltaY)&&(o.deltaY=0),Math.abs(this._totalDeltaY)>=Math.abs(3*this._totalDeltaX)&&(o.deltaX=0)),Ce(o,e)}_reset(){this._totalDeltaX=0,this._totalDeltaY=0}}var Pe=i(724377),Te=i(678515),Me=i(431912),xe=i(854606);class Ie{constructor(e,t,i){this._handleEl=null,this._resizeInfo=null,this._colorCache={lineColor:"",backgroundColor:"",color:""},this._chart=e,this._topPaneIndex=t,this._bottomPaneIndex=i,this._element=document.createElement("div"),this._element.classList.add(xe.paneSeparator),this._element.style.background=this._color(),this.adjustSize(),this._element.addEventListener("click",(()=>{}));const s=document.createElement("div");s.classList.add(xe.handle),this._element.appendChild(s),this._mouseEventHandler=new Me.MouseEventHandler(s,this,{treatVertTouchDragAsPageScroll:!1,treatHorzTouchDragAsPageScroll:!0}),this._handleEl=s,this._element.setAttribute("aria-hidden","true")}destroy(){ this._mouseEventHandler.destroy(),this._element.parentElement&&this._element.parentElement.removeChild(this._element)}getElement(){return this._element}hide(){this._element.classList.add("js-hidden")}show(){this._element.classList.remove("js-hidden")}adjustSize(){this._element.style.height=Ie.height()+"px"}mouseEnterEvent(e){const{topPane:t,bottomPane:i}=this._topBottomPane(!0);null!==t&&null!==i&&(0,r.ensureNotNull)(this._handleEl).classList.add(xe.hovered)}mouseLeaveEvent(e){(0,r.ensureNotNull)(this._handleEl).classList.remove(xe.hovered)}mouseDownEvent(e){this._mouseDownOrTouchStartEvent(e)}touchStartEvent(e){this._mouseDownOrTouchStartEvent(e)}pressedMouseMoveEvent(e){this._pressedMouseOrTouchMoveEvent(e)}touchMoveEvent(e){this._pressedMouseOrTouchMoveEvent(e)}mouseUpEvent(e){this._mouseUpOrTouchEndEvent(e)}touchEndEvent(e){this._mouseUpOrTouchEndEvent(e)}update(){this._element.style.background=this._color().toString()}paint(){}image(){const{topPane:e}=this._topBottomPane(!1),t=e.leftPriceAxisesContainer().getWidth(),i=e.width(),o=e.rightPriceAxisesContainer().getWidth(),r=this._color(),n=(0,V.createDisconnectedCanvas)(document,(0,s.size)({width:t,height:1})),a=(0,V.getPrescaledContext2D)(n);a.fillStyle=r,a.fillRect(0,0,t,1);const l=(0,V.createDisconnectedCanvas)(document,(0,s.size)({width:i,height:1})),c=(0,V.getPrescaledContext2D)(l);c.fillStyle=r,c.fillRect(0,0,i,1);const d=(0,V.createDisconnectedCanvas)(document,(0,s.size)({width:o,height:1})),h=(0,V.getPrescaledContext2D)(d);return h.fillStyle=r,h.fillRect(0,0,o,1),{type:"separator",leftAxis:{content:n.toDataURL(),canvas:n,contentWidth:t,contentHeight:1},rightAxis:{content:d.toDataURL(),canvas:d,contentWidth:o,contentHeight:1},content:l.toDataURL(),canvas:l,contentWidth:i,contentHeight:1}}static height(){const e=window.devicePixelRatio||1;return e>=1?1:1/e}_mouseDownOrTouchStartEvent(e){const{topPane:t,bottomPane:i}=this._topBottomPane(!0);if(null===t||null===i)return;const s=t.state().stretchFactor()+i.state().stretchFactor(),o=s/(t.height()+i.height()),n=30*o;s<=2*n||(this._resizeInfo={startY:e.pageY,prevStretchTopPane:t.state().stretchFactor(),maxPaneStretch:s-n,totalStretch:s,pixelStretchFactor:o,minPaneStretch:n},(0,r.ensureNotNull)(this._handleEl).classList.add(xe.active))}_pressedMouseOrTouchMoveEvent(e){const{topPane:t,bottomPane:i}=this._topBottomPane(!0),s=this._resizeInfo;if(null===s||null===t||null===i)return;const o=(e.pageY-s.startY)*s.pixelStretchFactor,r=(0,Te.clamp)(s.prevStretchTopPane+o,s.minPaneStretch,s.maxPaneStretch);t.state().setStretchFactor(r),i.state().setStretchFactor(s.totalStretch-r),this._chart.model().model().fullUpdate()}_mouseUpOrTouchEndEvent(e){const{topPane:t,bottomPane:i}=this._topBottomPane(!0),s=this._resizeInfo;null!==s&&null!==t&&null!==i&&(this._chart.model().addPaneStretchFactorUndoCommand(t.state(),i.state(),s.prevStretchTopPane,t.state().stretchFactor()),this._resizeInfo=null,(0,r.ensureNotNull)(this._handleEl).classList.remove(xe.active))}_color(){ const e=this._chart.properties().childs().paneProperties.childs().separatorColor.value(),t=this._chart.model().model().backgroundColor().value();if(this._colorCache.lineColor!==e||this._colorCache.backgroundColor!==t){const i=(0,Pe.parseRgba)(t),s=(0,Pe.parseRgba)(e),o=0===i[3]&&0===s[3]?"rgba(0,0,0,0)":(0,Pe.rgbaToString)((0,Pe.blendRgba)(i,s));this._colorCache={lineColor:e,backgroundColor:t,color:o}}return this._colorCache.color}_topBottomPane(e){const t=this._chart.paneWidgets();let i=null,s=null;for(let s=this._topPaneIndex;s>=0;--s){const o=t[s];if(!e||!o.state().collapsed().value()){i=o;break}}for(let i=this._bottomPaneIndex;i{this.update(),this._textWidthCache.reset()},this._timeAxisWidget=n,this._isLeft="left"===e;const{rendererOptionsProvider:a,sourcesTitlesProvider:l,contextMenuItemsProvider:c,backgroundBasedTheme:d,onActiveOrHoveredChart:h=new O.WatchedValue(!1).ownership(),requestRepaint:u,getBackgroundTopColor:_,getBackgroundBottomColor:p,showHorizontalBorder:m}=o;this._rendererOptionsProvider=a,this._sourcesTitlesProvider=l,this._contextMenuItemsProvider=c,this._backgroundBasedTheme=d,this._onActiveOrHoveredChart=h,this._requestRepaint=u,this._getBackgroundTopColor=_,this._getBackgroundBottomColor=p,this._showHorizontalBorder=Boolean(m),this._properties=t,this._axisInfo=i,this._labelOptions={...Ke,...r},this._properties.lineColor.subscribe(this,this._onPropertyChanged),this._cell=document.createElement("div"),this._labelOptions.enableTooltip&&this._cell.classList.add("apply-common-tooltip"),this._cell.style.width="25px",this._cell.style.height="100%",this._cell.style.position="absolute",this._cell.style.left="0",this._cell.style.overflow="hidden",this._labelOptions.showLabels&&(this._labelOptions.enableTooltip&&(0,Ge.setTooltipData)(this._cell,"text",(e=>this._tooltipContent())),this._onActiveOrHoveredChart.subscribe(u)),this._mouseEventHandler=new Me.MouseEventHandler(this._cell,this,{treatHorzTouchDragAsPageScroll:!0,treatVertTouchDragAsPageScroll:!0}),this._canvasBinding=(0,V.createBoundCanvas)(this._cell,(0,s.size)({width:16,height:16})),this._canvasBinding.subscribeSuggestedBitmapSizeChanged(this._canvasConfiguredHandler) ;const g=this._canvasBinding.canvasElement;g.style.position="absolute",g.style.left="0",g.style.top="0",this._cell.setAttribute("aria-hidden","true")}destroy(){this._canvasBinding.unsubscribeSuggestedBitmapSizeChanged(this._canvasConfiguredHandler),this._canvasBinding.dispose(),this._properties.lineColor.unsubscribe(this,this._onPropertyChanged),this._mouseEventHandler.destroy(),this._backgroundBasedTheme.release(),this._onActiveOrHoveredChart.unsubscribe(this._requestRepaint),this._onActiveOrHoveredChart.release()}mouseEnterEvent(e){this._mouseOrTouchEnterEvent(e)}touchStartEvent(e){this._mouseOrTouchEnterEvent(e)}mouseLeaveEvent(e){this._mouseOrTouchLeaveEvent(e)}touchEndEvent(e){this._mouseOrTouchLeaveEvent(e)}mouseClickEvent(e){this._mouseClickOrTapEvent(e)}tapEvent(e){this._mouseClickOrTapEvent(e)}update(){}getElement(){return this._cell}onLabelHovered(){return this._onLabelHovered}setSizeAndOffset(e,t){(0,s.equalSizes)(this._size,e)||(this._size=e,this._canvasBinding.resizeCanvasElement(e),this._cell.style.width=`${e.width}px`,this._cell.style.minWidth=`${e.width}px`,this._cell.style.height=`${e.height}px`,this._invalidated=!0),this._offset!==t&&(this._offset=t,this._cell.style.left=`${t}px`)}paint(e){e{e.fillText(o.label,_.x/n,_.y/a+t)}))}else if(!i&&this._onActiveOrHoveredChart.value()){const t=this._gearRenderer.viewBox(),i=Math.round(_.x-t.width*n/2),o=Math.round(_.y-t.height*a/2);e.fillStyle=h.themes[s].getThemedColor("color-text-primary"),e.imageSmoothingQuality="high",this._gearRenderer.render(e,{targetViewBox:{x:i,y:o,width:t.width*n,height:t.height*a},doNotApplyColors:!0})}}_vertBorderColor(){return this._properties.lineColor.value()}_horzBorderColor(){var e,t;return null!==(t=null===(e=this._timeAxisWidget)||void 0===e?void 0:e.lineColor())&&void 0!==t?t:this._vertBorderColor()}_tooltipContent(){return this._sourcesTitlesProvider().join("\n")}_mouseOrTouchEnterEvent(e){this._labelOptions.showLabels&&this._labelOptions.enableHighlight&&this._setHighlighted(!0)}_mouseOrTouchLeaveEvent(e){this._labelOptions.showLabels&&this._labelOptions.enableHighlight&&this._setHighlighted(!1)}_mouseClickOrTapEvent(e){if(e.preventDefault(),null!==this._fixedLabelMode||1===this._labelMode||!this._labelOptions.enableMenu||!this._labelOptions.showLabels)return void Ue.ContextMenuManager.hideAll();this._fixedLabelMode=this._labelMode,this.setLabelMode(0);const t=this._cell.getBoundingClientRect();Ue.ContextMenuManager.showMenu(this._contextMenuItemsProvider(),{clientX:this._isLeft?t.left:t.right,clientY:t.top,attachToXBy:this._isLeft?"left":"right",attachToYBy:"bottom"},{statName:"PriceScaleLabelContextMenu",doNotCloseOn:this.getElement()},{menuName:"PriceScaleLabelContextMenu"},(()=>{this.setLabelMode((0,r.ensureNotNull)(this._fixedLabelMode)),this._fixedLabelMode=null}))}}var Xe=i(175070);class Je{constructor(e,t,i,o,r,n=null){this._axises=[],this._stubs=[],this._size=(0,s.size)({width:0,height:0}),this._onLabelHovered=new E.Delegate,this._scalesProperties=e,this._priceAxisWidgetFactory=i,this._timeAxisWidget=n,this._rendererOptionsProvider=o.rendererOptionsProvider,this._titlesProvider=o.titlesProvider,this._stubContextMenuProvider=o.stubContextMenuProvider,this._backgroundBasedTheme=o.backgroundBasedTheme,this._onActiveOrHoveredChart=o.onActiveOrHoveredChart, this._getBackgroundTopColor=o.getBackgroundTopColor,this._getBackgroundBottomColor=o.getBackgroundBottomColor,this._requestRepaint=o.requestRepaint,this._showHorisontalBorder=Boolean(o.showHorizontalBorder),this._labelsOptions={...Ke,...r};const a=this._scalesProperties.childs();this._stubProperties={lineColor:a.lineColor,fontSize:a.fontSize},this._side=t,this._cell=document.createElement("div"),this._cell.classList.add("chart-markup-table","price-axis-container"),this._cell.style.width="25px",this._cell.style.position="relative"}destroy(){var e;this.setScales([],0,0,0),this._backgroundBasedTheme.release(),null===(e=this._onActiveOrHoveredChart)||void 0===e||e.release()}onLabelHovered(){return this._onLabelHovered}setScales(e,t,i,s){for(;e.length>this._axises.length&&this._axises.lengthn;){const e=(0,r.ensureDefined)(this._stubs.pop());e.onLabelHovered().unsubscribeAll(this),this._cell.removeChild(e.getElement()),e.destroy()}for(;this._stubs.length{this._labelsOptions.showLabels&&this._labelsOptions.enableHighlight&&this._onLabelHovered.fire({owner:t,axis:(0,r.ensureNotNull)(e)},i)})),this._stubs.push(t),this._cell.appendChild(t.getElement())}const a=this._labelsOptions.enableMenu;1===s?this._stubs.forEach(((e,t)=>e.setLabelMode(a?0:1))):this._stubs.forEach(((e,t)=>e.setLabelMode(te.updateCurrencyLabel()))}optimalWidths(){return this._axises.map((e=>e.optimalWidth()))}setSizes(e,t){this._size=(0,s.size)({width:t.reduce(((e,t)=>e+t),0),height:e}),this._cell.style.width=this._size.width+"px",this._cell.style.minWidth=this._size.width+"px",this._cell.style.height=this._size.height+"px",t.length!==this._axises.length+this._stubs.length&&(0,r.assert)(t.length===this._axises.length+this._stubs.length,"Widgets count should be the same as widths one");let i=0;this._forEachWidgetFromLeft(((o,r)=>{const n=t[r];o.setSizeAndOffset((0,s.size)({width:n,height:e}),i),i+=n}))}update(){this._axises.forEach((e=>e.update())),this._stubs.forEach((e=>e.update()))}paint(e){this._axises.forEach(((t,i)=>t.paint(e(i)))),this._stubs.forEach(((t,i)=>t.paint(e(i))))}paintStubs(e){this._stubs.forEach((t=>t.paint(e)))}restoreDefaultCursor(){ this._axises.forEach((e=>e.restoreDefaultCursor()))}getWidth(){return this._size.width}findAxisWidgetForScale(e){const t=this._axises.find((t=>t.priceScale()===e));return void 0===t?null:t}getScreenshotData(){const e=this._getImage();return{canvas:e,content:e.toDataURL(),contentHeight:this._size.height,contentWidth:this._size.width}}getImage(){return this._getImage()}slotsCount(){return this._axises.length+this._stubs.length}highlightPriceAxisByLabel(e){this._axises.forEach((t=>{const i=t.axisInfo();t.setHighlighted(null!==i&&i.equals(e))}))}axes(){return this._axises}_stubParams(e){var t;return{rendererOptionsProvider:this._rendererOptionsProvider,backgroundBasedTheme:this._backgroundBasedTheme.spawnOwnership(),onActiveOrHoveredChart:null===(t=this._onActiveOrHoveredChart)||void 0===t?void 0:t.spawnOwnership(),sourcesTitlesProvider:()=>this._titlesProvider(this._side,e),contextMenuItemsProvider:()=>this._stubContextMenuProvider(this._side,e),getBackgroundTopColor:this._getBackgroundTopColor,getBackgroundBottomColor:this._getBackgroundBottomColor,requestRepaint:this._requestRepaint,showHorizontalBorder:this._showHorisontalBorder}}_getImage(){const e=(0,V.createDisconnectedCanvas)(document,this._size),t=(0,V.getPrescaledContext2D)(e);let i=0;return this._forEachWidgetFromLeft(((e,s)=>{const o=e.getWidth();0!==o&&0!==this._size.height&&(t.drawImage(e.getImage(),i,0,o,this._size.height),i+=o)})),e}_forEachWidgetFromLeft(e){const t=[...this._axises,...this._stubs],i="left"===this._side,s=i?-1:t.length,o=i?-1:1;for(let r=i?t.length-1:0;r!==s;r+=o)e(t[r],r,t)}}var Qe=i(414592),et=i(855824),tt=i(898586);class it{constructor(){this._width=null,this._labelBottom=null,this._currencyInfo=null,this._unitInfo=null,this._measureUnitIdInfo=null,this._fontSize=0,this._currencyAndUnitLabelsWrapper=document.createElement("div"),this._currencyAndUnitLabelsWrapper.className=tt["price-axis-currency-label-wrapper"],this._currencyAndUnitLabelsWrapper.setAttribute("data-name","currency-unit-label-wrapper"),this._controlsContainer=document.createElement("div"),this._controlsContainer.className=tt["price-axis-currency-label"],this._currencyAndUnitLabelsWrapper.appendChild(this._controlsContainer),this._currencyLabelDiv=document.createElement("div"),this._currencyLabelDiv.className=tt.row,this._currencyLabelDiv.classList.add("apply-common-tooltip"),(0,Ge.setTooltipData)(this._currencyLabelDiv,"text",(e=>this._currencyTooltipContent())),this._currencyText=document.createElement("div"),this._currencyText.className=tt["price-axis-currency-label-text"],this._currencyLabelDiv.appendChild(this._currencyText),this._currencyArrowDown=document.createElement("div"),this._currencyArrowDown.className=tt["price-axis-currency-label-arrow-down"],this._currencyArrowDown.innerHTML=et,this._currencyLabelDiv.appendChild(this._currencyArrowDown),this._measureUnitIdLabelDiv=document.createElement("div"),this._measureUnitIdLabelDiv.className=tt.row,this._measureUnitIdLabelDiv.classList.add("apply-common-tooltip"), this._measureUnitIdLabelDiv.classList.add("readonly"),(0,Ge.setTooltipData)(this._measureUnitIdLabelDiv,"text",(e=>this._measureUnitIdTooltipContent())),this._measureUnitIdText=document.createElement("div"),this._measureUnitIdText.className=tt["price-axis-currency-label-text"],this._measureUnitIdLabelDiv.appendChild(this._measureUnitIdText),this._unitLabelDiv=document.createElement("div"),this._unitLabelDiv.className=tt.row,this._unitLabelDiv.classList.add("apply-common-tooltip"),(0,Ge.setTooltipData)(this._unitLabelDiv,"text",(e=>this._unitTooltipContent())),this._unitText=document.createElement("div"),this._unitText.className=tt["price-axis-currency-label-text"],this._unitLabelDiv.appendChild(this._unitText),this._unitArrowDown=document.createElement("div"),this._unitArrowDown.className=tt["price-axis-currency-label-arrow-down"],this._unitArrowDown.innerHTML=et,this._unitLabelDiv.appendChild(this._unitArrowDown),this._controlsContainer.appendChild(this._currencyLabelDiv),this._controlsContainer.appendChild(this._measureUnitIdLabelDiv),this._controlsContainer.appendChild(this._unitLabelDiv),this.disableCurrency(),this.disableUnit()}element(){return this._currencyAndUnitLabelsWrapper}currencyLabelElement(){return this._currencyLabelDiv}unitLabelElement(){return this._unitLabelDiv}isEnabled(){return this.currencyLabelEnabled()||this.unitLabelEnabled()||this.measureUnitIdLableEnabled()}isHidden(){return this._currencyAndUnitLabelsWrapper.classList.contains(tt.hidden)}setCurrencyExpanded(e){this._currencyLabelDiv.classList.toggle(tt.expanded,e)}setUnitExpanded(e){this._unitLabelDiv.classList.toggle(tt.expanded,e)}width(){if(null!==this._width)return this._width;let e=0;if(this.currencyLabelEnabled()){const t=this._currencyText.getBoundingClientRect(),i=this._currencyArrowDown.getBoundingClientRect();e=Math.max(e,t.width+i.width+2*this._textMarginAndPadding())}if(this.measureUnitIdLableEnabled()){const t=this._measureUnitIdText.getBoundingClientRect();e=Math.max(e,t.width+2*this._textMarginAndPadding())}if(this.unitLabelEnabled()){const t=this._unitText.getBoundingClientRect(),i=this._unitArrowDown.getBoundingClientRect();e=Math.max(e,t.width+i.width+2*this._textMarginAndPadding())}return this._width=e}drawLabel(e,t,i){var s,o,r;if(!this.isEnabled())return;const n=Math.round(Number(tt.css_wrapper_margin)*i),a=(0,Te.ceiledEven)(t*i)-2*n,l=Math.round(this.labelBottom()*i),c=l-2*n,d=Math.round(Number(tt.css_value_currency_label_radius)*i);e.fillStyle=getComputedStyle(this._currencyAndUnitLabelsWrapper).backgroundColor,e.fillRect(0,0,Math.ceil(t*i),l);const h=[];h.push(this.currencyLabelEnabled()&&null!==(s=this._currencyText.textContent)&&void 0!==s?s:""),h.push(this.measureUnitIdLableEnabled()&&null!==(o=this._measureUnitIdText.textContent)&&void 0!==o?o:""),h.push(this.unitLabelEnabled()&&null!==(r=this._unitText.textContent)&&void 0!==r?r:""),e.font=(0,Fe.makeFont)(this._fontSize,qe.CHART_FONT_FAMILY);const u=new ze.TextWidthCache;let _=0;const p=[];h.forEach((t=>{let i=0;""!==t&&(i=u.yMidCorrection(e,t),_++),p.push(i) }));const m=c/_;e.beginPath();const g=getComputedStyle(this._controlsContainer);e.fillStyle=g.backgroundColor,e.strokeStyle=g.borderColor,(0,We.drawRoundRect)(e,n,n,a,c,d),e.fill(),e.stroke(),e.fillStyle=getComputedStyle(this._currencyLabelDiv).color,e.textBaseline="middle",e.textAlign="left";const S=Math.round(this._textMarginAndPadding()*i)+n,v=m/2;let f=n+v;h.forEach(((t,s)=>{""!==t&&((0,V.drawScaled)(e,i,i,(()=>{e.fillText(t,S/i,(f+p[s])/i)})),f=Math.ceil(f+2*v))}))}setHidden(e){this._currencyAndUnitLabelsWrapper.classList.toggle(tt.hidden,e)}enableCurrency(){this._currencyLabelDiv.classList.remove("js-hidden"),this._resetSizesAndVisibility()}disableCurrency(){this._currencyLabelDiv.classList.add("js-hidden"),this._resetSizesAndVisibility()}enableUnit(){this._unitLabelDiv.classList.remove("js-hidden"),this._resetSizesAndVisibility()}disableUnit(){this._unitLabelDiv.classList.add("js-hidden"),this._resetSizesAndVisibility()}enableMeasureUnitId(){this._measureUnitIdLabelDiv.classList.remove("js-hidden"),this._resetSizesAndVisibility()}disableMeasureUnitId(){this._measureUnitIdLabelDiv.classList.add("js-hidden"),this._resetSizesAndVisibility()}currencyLabelEnabled(){return!this._currencyLabelDiv.classList.contains("js-hidden")}unitLabelEnabled(){return!this._unitLabelDiv.classList.contains("js-hidden")}measureUnitIdLableEnabled(){return!this._measureUnitIdLabelDiv.classList.contains("js-hidden")}currencyConversionAvailable(){return!this._currencyLabelDiv.classList.contains("readonly")}unitConversionAvailable(){return!this._unitLabelDiv.classList.contains("readonly")}setCurrencyInfo(e){if(this._currencyInfo===e)return!1;this._currencyInfo=e;const t=null===e.selectedCurrency?a.t(null,void 0,i(795093)):(0,r.ensureDefined)(e.displayedValues.get(e.selectedCurrency));return this._currencyText.textContent!==t&&(this._currencyText.textContent=t,this._width=null),this._currencyArrowDown.classList.contains("js-hidden")!==e.readOnly&&(this._currencyArrowDown.classList.toggle("js-hidden",e.readOnly),this._currencyLabelDiv.classList.toggle("readonly",e.readOnly),this._width=null),!0}setUnitInfo(e){if(null!==this._unitInfo&&this._unitInfo.selectedUnit===e.selectedUnit&&0===this._unitInfo.availableGroups.size==(0===e.availableGroups.size)&&this._unitInfo.originalUnits.size===e.originalUnits.size)return this._unitInfo=e,!1;this._unitInfo=e;const t=null===e.selectedUnit?a.t(null,void 0,i(795093)):(0,r.ensureDefined)(e.names.get(e.selectedUnit));return this._unitText.textContent!==t&&(this._unitText.textContent=t,this._width=null),this._unitArrowDown.classList.contains("js-hidden")!==(0===e.availableGroups.size)&&(this._unitArrowDown.classList.toggle("js-hidden",0===e.availableGroups.size),this._unitLabelDiv.classList.toggle("readonly",0===e.availableGroups.size),this._width=null),!0}setMeasureUnitIdInfo(e){if(this._measureUnitIdInfo===e)return!1;this._measureUnitIdInfo=e;const t=null===e.selectedMeasureUnitId?a.t(null,void 0,i(795093)):(0,r.ensureDefined)(e.names.get(e.selectedMeasureUnitId)) ;return this._measureUnitIdText.textContent!==t&&(this._measureUnitIdText.textContent=t,this._width=null),this._measureUnitIdLabelDiv.classList.contains("js-hidden")!==(0===e.names.size)&&(this._measureUnitIdLabelDiv.classList.toggle("js-hidden",0===e.names.size),this._width=null),!0}currencyInfo(){return this._currencyInfo}unitInfo(){return this._unitInfo}measureUnitIdInfo(){return this._measureUnitIdInfo}setFontSize(e){this._fontSize!==e&&(this._fontSize=e,this._currencyLabelDiv.style.fontSize=e+"px",this._measureUnitIdLabelDiv.style.fontSize=e+"px",this._unitLabelDiv.style.fontSize=e+"px",this._width=null,this._labelBottom=null)}labelBottom(){if(null!==this._labelBottom)return this._labelBottom;const e=this._controlsContainer.getBoundingClientRect(),t=this._currencyAndUnitLabelsWrapper.getBoundingClientRect(),i=e.y-t.y;return this._labelBottom=e.height+2*i}_resetSizesAndVisibility(){this._width=null,this._labelBottom=null,this._updateVisibility()}_textMarginAndPadding(){return Number(tt.css_wrapper_margin)+Number(tt.css_row_left_right_padding)+2}_currencyTooltipContent(){const e=this._currencyInfo;return null===e?"":null===e.selectedCurrency?Array.from(e.currencies).map((t=>(0,r.ensureDefined)(e.displayedValues.get(t)))).join(", "):e.readOnly?a.t(null,void 0,i(29257)):a.t(null,void 0,i(950868))}_unitTooltipContent(){const e=this._unitInfo;return null===e?"":null===e.selectedUnit?Array.from(e.units).map((t=>(0,r.ensureDefined)(e.names.get(t)))).join(", "):0===e.availableGroups.size?a.t(null,void 0,i(73022)):a.t(null,void 0,i(29302))}_measureUnitIdTooltipContent(){const e=this._measureUnitIdInfo;return null===e?"":null===e.selectedMeasureUnitId?Array.from(e.measureUnitIds).map((t=>(0,r.ensureDefined)(e.names.get(t)))).join(", "):e.descriptions.get(e.selectedMeasureUnitId)||""}_updateVisibility(){const e=this.isEnabled();this._currencyAndUnitLabelsWrapper.classList.toggle("js-hidden",!e)}}async function st(e,t,s,o,r,n){const{UnitConversionRenderer:a}=await Promise.all([i.e(32662),i.e(5987),i.e(98996),i.e(66458),i.e(5761),i.e(4343),i.e(70428),i.e(1413),i.e(70621),i.e(62033),i.e(13633),i.e(84331),i.e(87473),i.e(10637),i.e(5824),i.e(88484),i.e(60839),i.e(90385),i.e(62526),i.e(32704)]).then(i.bind(i,300203));return new a(e,s,t,o,r,n)}var ot=i(373571);class rt{constructor(e){const{action:t,property:i,undoModel:s,undoText:o,callback:r=null}=e;this._property=i,this._undoModel=s,this._undoText=o,this._action=t,this.setValue(i.value()),i.subscribe(this,this._propertyChanged),null!==r?t.update({onExecute:r.bind(this)}):t.update({onExecute:this._onActionCallback.bind(this)})}destroy(){this._property.unsubscribe(this,this._propertyChanged)}value(){return this._action.isChecked()}setValue(e){this._action.update({checked:Boolean(e)})}_onActionCallback(){this._undoModel.setProperty(this._property,this.value(),this._undoText)}_propertyChanged(e){this.setValue(e.value())}}class nt extends ot.Action{constructor(e,t){super(e),this._binding=new rt({action:this,...t})}destroy(){this._binding.destroy(),super.destroy()}} var at=i(470316),lt=i(327453),ct=i(621618),dt=i(261066),ht=i(480059),ut=i(497754),_t=i.n(ut),pt=i(604481);class mt{constructor({setMode:e,className:t=""}){const s=this._wrapper=document.createElement("div");s.classList.add(t),s.addEventListener("dblclick",this._stopPropagation,{capture:!0}),s.addEventListener("touchstart",this._stopPropagation,{capture:!0});const o=s.appendChild(document.createElement("div"));o.className=pt.priceScaleModeButtons;const[r,n]=this._createButton({title:a.t(null,{context:'The first letter of the "auto" word'},i(9846)),tooltip:a.t(null,void 0,i(550834)),onClick:()=>e("auto"),ariaLabel:a.t(null,void 0,i(974327))});this._autoScaleButton=n,o.appendChild(r);const[l,c]=this._createButton({title:a.t(null,{context:'The first letter of the "logarithmic" word'},i(655765)),tooltip:a.t(null,void 0,i(512285)),onClick:()=>e("log"),ariaLabel:a.t(null,void 0,i(184112))});this._logarithmButton=c,o.appendChild(l)}destroy(){this._wrapper.removeEventListener("dblclick",this._stopPropagation),this._wrapper.removeEventListener("touchstart",this._stopPropagation),this._wrapper.remove()}element(){return this._wrapper}width(){return 52}updateMode(e){const{log:t,autoScale:i}=e;this._logarithmButton.classList.toggle(pt.priceScaleModeButtons__button_activated,!!t),this._autoScaleButton.classList.toggle(pt.priceScaleModeButtons__button_activated,!!i)}_createButton(e){const{ariaLabel:t,title:i,tooltip:s,onClick:o,className:r}=e,n=document.createElement("div");n.className=pt.priceScaleModeButtons__buttonWrapper;const a=document.createElement("button");a.className=_t()(pt.priceScaleModeButtons__button,r,"apply-common-tooltip"),a.textContent=i,a.dataset.tooltip=s;let l=a;return c.CheckMobile.any()&&(l=n),l.addEventListener("click",o),t&&l.setAttribute("aria-label",t),n.appendChild(a),[n,a]}_stopPropagation(e){e.stopPropagation()}}var gt=i(747971);i(569960);const St=new R.TranslatedString("change no overlapping labels",a.t(null,void 0,i(783935))),vt=new R.TranslatedString("toggle auto scale",a.t(null,void 0,i(863060))),ft=new R.TranslatedString("toggle log scale",a.t(null,void 0,i(160166))),bt=a.t(null,void 0,i(375633)),yt=a.t(null,void 0,i(194420)),Ct=a.t(null,void 0,i(881520)),wt=a.t(null,void 0,i(125933)),Pt=a.t(null,void 0,i(417258)),Tt=a.t(null,void 0,i(550834)),Mt=a.t(null,{context:"scale_menu"},i(670361)),xt=a.t(null,{context:"scale_menu"},i(547807)),It=a.t(null,{context:"scale_menu"},i(934727)),At=a.t(null,{context:"scale_menu"},i(172116)),Lt=a.t(null,{context:"scale_menu"},i(19238)),kt=a.t(null,{context:"scale_menu"},i(454138));const Et=function(e){const t=new lt.LimitedPrecisionNumericFormatter(e);return(e,i)=>(0,w.isNumber)(i)&&!e.isLog()?t.format(i):""}(4),Dt=D.enabled("currency_menu_disabled"),Bt=D.enabled("unit_menu_disabled"),Nt={contextMenuEnabled:!0,currencyConversionEnabled:!1,unitConversionEnabled:!1,countdownEnabled:!0,contextMenu:{general:!0,source:!0},pressedMouseMoveScale:!0,mouseWheelScale:!0,pinchScale:!0,croppedTickMarks:!0};class Rt{constructor(e,t,i,o,r,n,a,l,c){this._actions=null, this._priceScale=null,this._scaleModeButtons=null,this._widthCache=new ze.TextWidthCache(1e3),this._color=null,this._fontSize=null,this._currencyFontSize=0,this._currencyLabelWidth=null,this._isVisible=!0,this._currencyMenu=null,this._unitMenu=null,this._size=(0,s.size)({width:0,height:0}),this._currentCursorClassName="",this._destroyed=!1,this._highlighted=!1,this._highlightColorCache=null,this._mouseWheelHelper=null,this._dragScaleActive=!1,this._offset=NaN,this._pinching=!1,this._lastHittestResult=null,this._isHovered=new O.WatchedValue(!1),this._recalcCurrencyAndUnitVisibility=()=>{if(null===this._currencyLabel)return;let e=!0;switch((0,dt.currencyUnitVisibilityProperty)().value()){case"alwaysOff":e=!1;break;case"visibleOnMouseOver":const t=this._chart.anyPriceAxisHovered().value(),i=null!==this._currencyMenu&&this._currencyMenu.isOpened(),s=null!==this._unitMenu&&this._unitMenu.isOpened();e=t||i||s}this._currencyLabel.setHidden(!e)},this._handleAutoLogButtonsVisibilityProperty=e=>{const t=e.value();"alwaysOff"===t?this._scaleModeButtons&&this._destroyScaleModeButtons():(this._scaleModeButtons||this._createScaleModeButtons(),"alwaysOn"===t?(this._isHovered.unsubscribe(this._updatePriceScaleModeButtonsVisibility),this._updatePriceScaleModeButtonsVisibility(!0)):this._isHovered.subscribe(this._updatePriceScaleModeButtonsVisibility,{callWithLast:!0}))},this._updatePriceScaleModeButtonsVisibility=e=>{var t;null===(t=this._scaleModeButtons)||void 0===t||t.element().classList.toggle("price-axis__modeButtons_hidden",!e)},this._updateScaleModeButtons=()=>{var e;this._priceScale&&(null===(e=this._scaleModeButtons)||void 0===e||e.updateMode(this._priceScale.mode()))},this._chart=e,this._pane=t,this._undoModel=i,this._properties=o,this._isLeft="left"===n,this._options=(0,w.merge)((0,w.clone)(Nt),a),this._rendererOptionsProvider=r,this._backgroundBasedTheme=c,this._cell=document.createElement("div"),this._cell.className="price-axis",this._cell.style.width="25px",this._cell.style.left="0",this._canvasConfiguredHandler=()=>{this._undoModel.model().lightUpdate()},this._canvasBinding=(0,V.createBoundCanvas)(this._cell,(0,s.size)({width:16,height:16})),this._canvasBinding.subscribeSuggestedBitmapSizeChanged(this._canvasConfiguredHandler);const d=this._canvasBinding.canvasElement;d.style.position="absolute",d.style.zIndex="1",d.style.left="0",d.style.top="0",this._topCanvasBinding=(0,V.createBoundCanvas)(this._cell,(0,s.size)({width:16,height:16})),this._topCanvasBinding.subscribeSuggestedBitmapSizeChanged(this._canvasConfiguredHandler);const h=this._topCanvasBinding.canvasElement;h.style.position="absolute",h.style.zIndex="2",h.style.left="0",h.style.top="0",this._cell.setAttribute("aria-hidden","true"),this._mouseEventHandler=new Me.MouseEventHandler(this._cell,this,{treatVertTouchDragAsPageScroll:!1,treatHorzTouchDragAsPageScroll:!0}),this._options.currencyConversionEnabled||this._options.unitConversionEnabled?(this._currencyLabel=new it,this._cell.appendChild(this._currencyLabel.element())):this._currencyLabel=null, this._properties.childs().fontSize.subscribe(this,this._onFontSizeChanged),this._options.mouseWheelScale&&(this._mouseWheelHelper=new we,this._cell.addEventListener("wheel",this._onMousewheel.bind(this),{passive:!1})),this._axisInfo=l,this._offset=0,this.restoreDefaultCursor(),(0,dt.currencyUnitVisibilityProperty)().subscribe(this,this._recalcCurrencyAndUnitVisibility),(0,ht.autoLogButtonsVisibilityProperty)().subscribe(this,this._handleAutoLogButtonsVisibilityProperty),this._handleAutoLogButtonsVisibilityProperty((0,ht.autoLogButtonsVisibilityProperty)()),this._chart.anyPriceAxisHovered().subscribe(this._recalcCurrencyAndUnitVisibility,{callWithLast:!0}),this.update()}getContextMenuActions(){var e;this._initActions();const t=(0,r.ensureNotNull)(this._actions),i=this._chart.actions(),s=[];return(null===(e=this._priceScale)||void 0===e?void 0:e.resetScaleAvailable().value())&&s.push(t.reset,new ot.Separator),s.push(this._autoScaleAction()),this._isMainSeriesAxis()&&s.push(this._lockScaleAction()),s.push(i.scaleSeriesOnly,this._invertAction(),new ot.Separator,this._regularScaleAction(),this._percentageAction(),this._indexedTo100Action(),this._logAction(),new ot.Separator),c.CheckMobile.any()||(s.push(this._createMergeScalesAction()),s.push(new ot.Separator)),D.enabled("fundamental_widget")||s.push(new ot.Action({actionId:"Chart.PriceScale.Labels",options:{label:yt,subItems:[i.showSymbolLabelsAction,i.showSeriesLastValue,i.showSeriesPrevCloseValue,i.showPrePostMarketPriceLabel,i.showHighLowPriceLabels,D.enabled("show_average_close_price_line_and_label")?i.showAverageClosePriceLabel:null,this._undoModel.model().hasCustomSource("bidask")&&i.showBidAskLabels,i.showStudyPlotNamesAction,i.showStudyLastValue,t.alignLabels].filter(Boolean)}})),s.push((0,ct.createLinesAction)(this._chart)),this._options.countdownEnabled&&s.push(i.showCountdown),this._undoModel.crossHairSource().isMenuEnabled()&&s.push(i.addPlusButton),!this._chart.onWidget()&&D.enabled("show_chart_property_page")&&D.enabled("chart_property_page_scales")&&i.scalesProperties&&s.push(new ot.Separator,i.scalesProperties),s}getElement(){return this._cell}onOptimalWidthNeedToBeRecalculated(e){(this._size.width1e-14){const n=o.formatPrice(Math.floor(Math.min(e,i))+.11111111111111,r),a=o.formatPrice(Math.ceil(Math.max(e,i))-.11111111111111,r);s=Math.max(s,this._widthCache.measureText(t,n),this._widthCache.measureText(t,a))}}}let n=0;this._isCurrencyLabelEnabled()&&(null===this._currencyLabelWidth&&(this._currencyLabelWidth=(0,r.ensureNotNull)(this._currencyLabel).width()),n=Math.round(this._currencyLabelWidth));const a=s||34;let l=Math.max(n,null!==(i=null===(t=this._scaleModeButtons)||void 0===t?void 0:t.width())&&void 0!==i?i:0,Math.ceil(o.borderSize+o.additionalPaddingInner+o.paddingInner+o.paddingOuter+a+4));return l+=l%2,l}setSizeAndOffset(e,t){(0,s.equalSizes)(this._size,e)||(this._size=e,this._canvasBinding.resizeCanvasElement(e),this._topCanvasBinding.resizeCanvasElement(e),this._cell.style.width=e.width+"px",this._cell.style.height=e.height+"px",this._cell.style.minWidth=e.width+"px"),this._offset!==t&&(this._offset=t,this._cell.style.left=t+"px")}getWidth(){return this._size.width}getImage(){const e=this._size,t=(0,V.createDisconnectedCanvas)(document,e);return(0,V.getPrescaledContext2D)(t).drawImage(this._canvasBinding.canvasElement,0,0,e.width,e.height),null===this._currencyLabel||this._currencyLabel.isHidden()||this._currencyLabel.drawLabel((0,V.getContext2D)(t),e.width,(0,_e.getCanvasDevicePixelRatio)(t)),t}update(){null!==this._priceScale&&(this._priceScale.marks(),this._updateCurrencyLabelFont(),this.rendererOptions())}paint(e){if(!this._isVisible||0===this._size.width||0===this._size.height)return;if(e===pe.InvalidationLevel.None)return;const t=this._pane.state(),i=!t.maximized().value()&&t.collapsed().value(),s=this._pane.hasState();(0,V.tryApplySuggestedCanvasBitmapSize)(this._canvasBinding),(0,V.tryApplySuggestedCanvasBitmapSize)(this._topCanvasBinding);const o=this._groupedSources(),n=null!==this._currencyLabel&&!this._currencyLabel.isHidden(),a=(e,t,i)=>{if(n){e.save(),e.beginPath();const i=(0,r.ensureNotNull)(this._currencyLabel).labelBottom();e.rect(0,i*t.verticalPixelRatio,t.bitmapSize.width,t.bitmapSize.height),e.clip()}i(),n&&e.restore()};if(e>pe.InvalidationLevel.Cursor){const e=(0,V.getContext2D)(this._canvasBinding.canvasElement),t=(0,V.getBindingRenderingInfo)(this._canvasBinding);i||this._alignLabels(),s&&this.updateCurrencyLabel(),this._drawBackground(e,t),a(e,t,(()=>{this._drawDrawingsHighlight(e,t)})),this._drawBorder(e,t),s&&(this._scaleModeButtons&&(this._scaleModeButtons.element().style.background=this._highlighted?this._highlightColor():this.backgroundColor()),i||a(e,t,(()=>{this._drawTickMarks(e,t),this._drawLabels(this._views(0,o),e,t)})))}if(s&&!i){const e=(0,V.getContext2D)(this._topCanvasBinding.canvasElement),t=(0,V.getBindingRenderingInfo)(this._topCanvasBinding);e.clearRect(0,0,t.bitmapSize.width,t.bitmapSize.height),a(e,t,(()=>{this._drawLabels(this._views(1,o),e,t),this._drawCrossHairLabel(e,t)}))}}restoreDefaultCursor(){this._setCursor("")}priceScale(){return(0, r.ensureNotNull)(this._priceScale)}setPriceScale(e){this._priceScale!==e&&(null!==this._priceScale&&(this._priceScale.onMarksChanged().unsubscribe(this,this.onOptimalWidthNeedToBeRecalculated),this._priceScale.modeChanged().unsubscribeAll(this)),this._priceScale=e,null!==e&&(e.onMarksChanged().subscribe(this,this.onOptimalWidthNeedToBeRecalculated),e.modeChanged().subscribe(this,(()=>this.onOptimalWidthNeedToBeRecalculated(!0))),this.onOptimalWidthNeedToBeRecalculated(),this._scaleModeButtons&&(e.modeChanged().subscribe(this,this._updateScaleModeButtons),this._updateScaleModeButtons())))}isVisible(){return this._isVisible}setVisible(e){(e=!!e)!==this._isVisible&&(this._cell.style.display=e?"table-cell":"none",this._isVisible=e)}destroy(){null!==this._currencyMenu&&(this._currencyMenu.close(),this._currencyMenu=null),null!==this._unitMenu&&(this._unitMenu.close(),this._unitMenu=null),this._topCanvasBinding.unsubscribeSuggestedBitmapSizeChanged(this._canvasConfiguredHandler),this._topCanvasBinding.dispose(),this._canvasBinding.unsubscribeSuggestedBitmapSizeChanged(this._canvasConfiguredHandler),this._canvasBinding.dispose(),null!==this._priceScale&&(this._priceScale.onMarksChanged().unsubscribe(this,this.onOptimalWidthNeedToBeRecalculated),this._priceScale.modeChanged().unsubscribeAll(this)),this._priceScale=null,this._mouseEventHandler.destroy(),this._properties.childs().fontSize.unsubscribe(this,this._onFontSizeChanged),null!==this._actions&&(Object.values(this._actions).forEach((e=>{e.destroy()})),this._actions=null),(0,dt.currencyUnitVisibilityProperty)().unsubscribeAll(this),this._chart.anyPriceAxisHovered().unsubscribe(this._recalcCurrencyAndUnitVisibility),(0,ht.autoLogButtonsVisibilityProperty)().unsubscribeAll(this),this._chart.setPriceAxisHovered(this,!1),this._destroyScaleModeButtons(),this._destroyed=!0}axisInfo(){return this._axisInfo}setHighlighted(e){this._highlighted=e}backgroundColor(){return this._pane.state().model().backgroundColor().value()}backgroundTopColor(){return this._pane.state().model().backgroundTopColor().value()}lineColor(){return this._properties.childs().lineColor.value()}textColor(){return this._properties.childs().textColor.value()}fontSize(){return this._properties.childs().fontSize.value()}baseFont(){return(0,Fe.makeFont)(this.fontSize(),qe.CHART_FONT_FAMILY,"")}rendererOptions(){let e=this._rendererOptionsProvider.options();return this._color===e.color&&this._fontSize===e.fontSize||(this._color=e.color),this._fontSize!==e.fontSize&&(this._widthCache.reset(),this._fontSize=e.fontSize,this._currencyLabelWidth=null,this._currencyFontSize=0,this._updateCurrencyLabelFont(),this.onOptimalWidthNeedToBeRecalculated()),this._chart.onWidget()||(e=Object.assign({},e,{paddingInner:Math.max(e.paddingInner,Qe.ALERT_LABEL_WIDTH)})),e}mouseEnterEvent(e){this._chart.setPriceAxisHovered(this,!0),this._isHovered.setValue(!0),this._applyLightUpdateIfRequired(),this._mouseEnterOrTouchStartEvent(e)}mouseMoveEvent(e){this._mouseOrTouchMoveEvent(e)}mouseDownEvent(e){this._mouseDownOrTouchStartEvent(e)} touchStartEvent(e){this._mouseOrTouchMoveEvent(e),this._mouseEnterOrTouchStartEvent(e),this._mouseDownOrTouchStartEvent(e)}pressedMouseMoveEvent(e){this._pressedMouseOrTouchMoveEvent(e)}touchMoveEvent(e){this._pressedMouseOrTouchMoveEvent(e)}pinchStartEvent(e,t,i,s){return s.bothPointsOnTargetElement}pinchEvent(e,t,i){if(this._zoomAvailable()&&this._options.pinchScale){if(this._dragScaleActive&&this._finishScale(),!this._pinching)return this._pinching=!0,void this._undoModel.startTwoPointsScalePrice(this._pane.state(),this.priceScale(),t.y,i.y);this._undoModel.twoPointsScalePriceTo(this._pane.state(),this.priceScale(),t.y,i.y)}}pinchEndEvent(){this._pinching=!1,this._undoModel.endTwoPointsScalePrice(this._pane.state(),this.priceScale())}mouseDownOutsideEvent(){this._finishScale()}touchStartOutsideEvent(){this._finishScale()}mouseUpEvent(e){this._mouseUpOrTouchEndEvent(e)}touchEndEvent(e){this._mouseLeaveOrTouchEndEvent(e),this._mouseUpOrTouchEndEvent(e)}mouseClickEvent(e){this._mouseClickOrTapEvent(e)}tapEvent(e){this._mouseClickOrTapEvent(e)}mouseLeaveEvent(e){this._chart.setPriceAxisHovered(this,!1),this._isHovered.setValue(!1),this._applyLightUpdateIfRequired(),this._mouseLeaveOrTouchEndEvent(e)}mouseDoubleClickEvent(e){this._mouseDoubleClickOrDoubleTapEvent(e)}doubleTapEvent(e){this._mouseDoubleClickOrDoubleTapEvent(e)}contextMenuEvent(e){this._contextMenuOrTouchContextMenuEvent(e)}touchContextMenuEvent(e){this._contextMenuOrTouchContextMenuEvent(e)}dataSourceAtPoint(e,t){const i=this._pane.state();if(!i.maximized().value()&&i.collapsed().value())return null;const s=this._groupedSources(),o=[...s.sources,...s.topLevelSources,...i.customSources()];let r=null,n=null;if(!this._priceScale)return null;const a=(e,t)=>{var i;const s=null!==(i=null==n?void 0:n.target())&&void 0!==i?i:0;e.target()>s&&(n=e,r=t)},l=new ke.Point(e,t),c=(0,V.getBindingRenderingInfo)(this._canvasBinding);for(let e=o.length-1;e>=0;--e){const t=o[e],s=t.priceAxisViews(i,this._priceScale);if(s&&0!==s.length)for(let e=s.length-1;e>=0;--e){const i=s[e].renderer();if(void 0!==i.hitTest){const e=i.hitTest(l,c,this._isLeft?"left":"right");null!==e&&a(e,t)}}}return this._lastHittestResult=n,r}reset(){const e=this._pane.state(),t=this.priceScale();this._undoModel.resetPriceScale(e,t),this.onOptimalWidthNeedToBeRecalculated(!0)}updateCurrencyLabel(){if(null===this._currencyLabel)return;let e=!1;if(this._options.currencyConversionEnabled){const t=this.priceScale().currency(this._undoModel.model().availableCurrencies());null===t||"alwaysOff"===(0,dt.currencyUnitVisibilityProperty)().value()?(e=this._currencyLabel.currencyLabelEnabled(),this._currencyLabel.disableCurrency()):(e=!this._currencyLabel.currencyLabelEnabled(),this._currencyLabel.enableCurrency(),e=this._currencyLabel.setCurrencyInfo(t)||e)}else this._currencyLabel.disableCurrency();if(this._options.unitConversionEnabled){const t="alwaysOff"===(0,dt.currencyUnitVisibilityProperty)().value(),i=this._undoModel.model().availableUnits(),s=this.priceScale().unit(i) ;null===s||t?(e=e||this._currencyLabel.unitLabelEnabled(),this._currencyLabel.disableUnit()):(e=e||!this._currencyLabel.unitLabelEnabled(),this._currencyLabel.enableUnit(),e=this._currencyLabel.setUnitInfo(s)||e);const o=this.priceScale().measureUnitId(i);null===o||t?(e=e||this._currencyLabel.measureUnitIdLableEnabled(),this._currencyLabel.disableMeasureUnitId()):(e=e||!this._currencyLabel.measureUnitIdLableEnabled(),this._currencyLabel.enableMeasureUnitId(),e=this._currencyLabel.setMeasureUnitIdInfo(o)||e)}else this._currencyLabel.disableUnit(),this._currencyLabel.disableMeasureUnitId();this._updateCurrencyLabelFont(),e&&(this._currencyLabelWidth=null)}_groupedSources(){var e;const t=this._pane.state(),i=t.model(),s=this._pane.state().sourcesByGroup(),o=this._isLeft?s.leftPriceScalesSources():s.rightPriceScalesSources(),r=this._priceScale===t.defaultPriceScale(),n=new Set(t.customSources()),a=e=>!!n.has(e)||(e.priceScale()===this._priceScale||r&&t.isOverlay(e)),l={sources:[...o.filter(a),...t.customSources()],topLevelSources:new Set};if(r){const e=this._pane.state().dataSources();for(const i of e)t.isOverlay(i)&&l.sources.push(i)}const c=null!==(e=i.lineBeingEdited())&&void 0!==e?e:i.lineBeingCreated();c&&a(c)&&(l.topLevelSources.add(c),l.lineBeingEditedOrCreated=c);const d=i.customSourceBeingMoved();d&&a(d)&&(l.topLevelSources.add(d),l.customSourceBeingMoved=d);const h=i.sourcesBeingMoved().filter(a);h.length>0&&(i.sourcesBeingMoved().forEach((e=>l.topLevelSources.add(e))),l.sourcesBeingMoved=h);const u=i.selection().allSources().filter(a);u.length>0&&(u.forEach((e=>l.topLevelSources.add(e))),l.selectedSources=u);const _=i.hoveredSource();return _&&a(_)&&(l.topLevelSources.add(_),l.hoveredSource=_),l}_isCurrencyLabelEnabled(){return null!==this._currencyLabel&&this._currencyLabel.isEnabled()}_updateCurrencyLabelFont(){if(null===this._currencyLabel)return;const e=this.fontSize();e!==this._currencyFontSize&&(this._currencyLabel.setFontSize(e),this._currencyFontSize=e,this._currencyLabelWidth=null,this.onOptimalWidthNeedToBeRecalculated())}_alignLabels(){var e,t,i,s,o;const r=this._size.height;let n=r/2;const a=[],l=this.priceScale(),c=l.orderedSources().slice(),d=this._pane.state(),h=this.rendererOptions();if(l===d.defaultPriceScale()){const e=d.priceDataSources();for(let t=0;t{if(e.ignoreAlignment()||!e.isVisible())return!1;const{total:t}=e.topBottomTotalHeight(h),i=e.floatCoordinate();return i>-t&&ie.floatCoordinate()<=n)),p=a.filter((e=>e.floatCoordinate()>n));_.sort(((e,t)=>t.floatCoordinate()-e.floatCoordinate())),_.length>0&&p.length>0&&p.push(_[0]), p.sort(((e,t)=>e.floatCoordinate()-t.floatCoordinate()));for(const e of a)e.setFixedCoordinate(e.coordinate());if(l.properties().childs().alignLabels.value()){if(p.length>0||_.length>0){{const e=null!==(s=_[0])&&void 0!==s?s:p[0],t=e.getFixedCoordinate(),{top:i,bottom:o,total:n}=e.topBottomTotalHeight(h);n0&&e.setFixedCoordinate(i)}{const e=null!==(o=p[0])&&void 0!==o?o:_[0],t=e.getFixedCoordinate(),{top:i,bottom:s,total:n}=e.topBottomTotalHeight(h);nr&&e.setFixedCoordinate(r-s)}}for(let e=1;e<_.length;e++){const t=_[e],i=_[e-1],{top:s,bottom:o,total:r}=t.topBottomTotalHeight(h),n=t.getFixedCoordinate(),a=i.getFixedCoordinate();if(n>a-r)t.setFixedCoordinate(a-r);else if(a>0&&n-s<0&&n+o>0){const{top:e}=i.topBottomTotalHeight(h);t.setFixedCoordinate(Math.min(a-e-o,s))}}for(let e=1;er&&t.setFixedCoordinate(Math.max(a+s+e,r-i))}}}}_drawTickMarks(e,t){const i=this.priceScale().marks();e.save(),e.font=this.baseFont();const s=this.rendererOptions(),{horizontalPixelRatio:o,verticalPixelRatio:n}=t,a=this._isLeft?Math.floor((this._size.width-s.additionalPaddingInner)*o):0,l=this._isLeft?Math.round(a-s.paddingInner*o):Math.round(a+(s.additionalPaddingInner+s.paddingInner)*o),c=this.fontSize(),d=this._isCurrencyLabelEnabled()?(0,r.ensureNotNull)(this._currencyLabel).labelBottom():0,h=i.map((t=>{if(this._options.croppedTickMarks)return{visible:!0,yCorrection:this._widthCache.yMidCorrection(e,t.label)};const i=t.coord-c/2,s=t.coord+c/2,o=!(s>this._size.height||ithis._size.height||i{for(let t=i.length;t--;){if(!h[t].visible)continue;const s=i[t];e.fillText(s.label,l/o,s.coord+h[t].yCorrection)}})),e.restore()}async _showCurrenciesContextMenu(){var e;if(null!==this._currencyMenu&&this._currencyMenu.isOpened())return void this._currencyMenu.close();(0,u.trackEvent)("GUI","Currency conversion");const{currencyActions:t}=await Promise.all([i.e(32662),i.e(5987),i.e(98996),i.e(66458),i.e(5761),i.e(4343),i.e(70428),i.e(1413),i.e(70621),i.e(62033),i.e(13633),i.e(84331),i.e(87473),i.e(10637),i.e(5824),i.e(88484),i.e(60839),i.e(90385),i.e(62526),i.e(32704)]).then(i.bind(i,87423)),s=await st(Ct,(()=>t(this._undoModel,(0,r.ensureNotNull)(this._currencyLabel).currencyInfo(),this.priceScale())),(0,r.ensureNotNull)(this._currencyLabel).currencyLabelElement(),Dt,(()=>["toggle_currency_menu_inner",this._undoModel.model().id(),this._pane.state().id(),this.priceScale().id()]),(()=>{var e;this._recalcCurrencyAndUnitVisibility(),null===(e=this._currencyLabel)||void 0===e||e.setCurrencyExpanded(!1)}));null===(e=this._currencyLabel)||void 0===e||e.setCurrencyExpanded(!0), this._destroyed?s.close():this._currencyMenu=s}async _showUnitsContextMenu(){var e;if(null!==this._unitMenu&&this._unitMenu.isOpened())return void this._unitMenu.close();(0,u.trackEvent)("GUI","Unit conversion");const{unitActions:t}=await Promise.all([i.e(32662),i.e(5987),i.e(98996),i.e(66458),i.e(5761),i.e(4343),i.e(70428),i.e(1413),i.e(70621),i.e(62033),i.e(13633),i.e(84331),i.e(87473),i.e(10637),i.e(5824),i.e(88484),i.e(60839),i.e(90385),i.e(62526),i.e(32704)]).then(i.bind(i,63189)),s=await st(wt,(()=>t(this._undoModel,(0,r.ensureNotNull)(this._currencyLabel).unitInfo(),this.priceScale())),(0,r.ensureNotNull)(this._currencyLabel).unitLabelElement(),Bt,(()=>["toggle_unit_menu_inner",this._undoModel.model().id(),this._pane.state().id(),this.priceScale().id()]),(()=>{var e;this._recalcCurrencyAndUnitVisibility(),null===(e=this._currencyLabel)||void 0===e||e.setUnitExpanded(!1)}));null===(e=this._currencyLabel)||void 0===e||e.setUnitExpanded(!0),this._destroyed?s.close():this._unitMenu=s}_onFontSizeChanged(){this._currencyLabelWidth=null,this._currencyFontSize=0,this._updateCurrencyLabelFont(),this.onOptimalWidthNeedToBeRecalculated()}_mouseOrTouchMoveEvent(e){var t,i,s,o;if(!this._priceScale)return;if(e.localX<0||e.localY<0||e.localX>=this._size.width||e.localY>=this._size.height)return;let r=!0;const n=this.dataSourceAtPoint(e.localX,e.localY);n?(this._setCursorClassName("pointer"),(null===(i=null===(t=this._lastHittestResult)||void 0===t?void 0:t.data())||void 0===i?void 0:i.hoverModelFromAxis)&&(this._undoModel.model().setHoveredSource(n,null!==(o=null===(s=this._lastHittestResult)||void 0===s?void 0:s.data())&&void 0!==o?o:null,0),r=!1)):this._setResizeCursor(),r&&this._undoModel.model().setHoveredSource(null,null)}_mouseDownOrTouchStartEvent(e){this._zoomAvailable()&&this._options.pressedMouseMoveScale&&!this._pinching&&(this._dragScaleActive=!0,this._undoModel.startScalePrice(this._pane.state(),this.priceScale(),e.localY))}_mouseEnterOrTouchStartEvent(e){this._setResizeCursor()}_pressedMouseOrTouchMoveEvent(e){if(this._dragScaleActive){const t=this.priceScale();this._undoModel.scalePriceTo(this._pane.state(),t,e.localY)}}_mouseUpOrTouchEndEvent(e){this._finishScale()}_finishScale(){this._dragScaleActive&&(this._undoModel.endScalePrice(this._pane.state(),this.priceScale()),this.restoreDefaultCursor(),this._dragScaleActive=!1)}_mouseClickOrTapEvent(e){if(this._currencyLabel){if(this._currencyLabel.currencyConversionAvailable()&&this._currencyLabel.currencyLabelElement().contains(e.target))return this._showCurrenciesContextMenu(),void e.preventDefault();if(this._currencyLabel.unitConversionAvailable()&&this._currencyLabel.unitLabelElement().contains(e.target))return this._showUnitsContextMenu(),void e.preventDefault()}const t=this.dataSourceAtPoint(e.localX,e.localY);t&&this._undoModel.selectionMacro((e=>{var i,s,o;e.selection().isSelected(t)&&this._undoModel.model().lastSelectedHittestData()===(null===(i=this._lastHittestResult)||void 0===i?void 0:i.data())||(e.clearSelection(), e.addSourceToSelection(t,null!==(o=null===(s=this._lastHittestResult)||void 0===s?void 0:s.data())&&void 0!==o?o:null))}))}_mouseLeaveOrTouchEndEvent(e){this._setCursorClassName("")}_mouseDoubleClickOrDoubleTapEvent(e){var t,i,s;if((null===(t=this._currencyLabel)||void 0===t?void 0:t.currencyLabelElement().contains(e.target))||(null===(i=this._currencyLabel)||void 0===i?void 0:i.unitLabelElement().contains(e.target)))return;const o=this.dataSourceAtPoint(e.localX,e.localY);o?this._pane.processDoubleClickOnSource(o,null!==(s=this._lastHittestResult)&&void 0!==s?s:void 0,{origin:"price_scale"}):(this.reset(),(0,u.trackEvent)("GUI","Double click price scale"))}_contextMenuOrTouchContextMenuEvent(e){if(this._options.contextMenuEnabled){const t=this.dataSourceAtPoint(e.localX,e.localY);if(null!==t&&this._options.contextMenu.source){return void this._undoModel.model().selectionMacro((i=>{i.selection().isSelected(t)||(i.clearSelection(),i.addSourceToSelection(t)),this._pane.showContextMenuForSelection(e,{origin:"price_scale"})}))}this._options.contextMenu.general&&Ue.ContextMenuManager.showMenu(this.getContextMenuActions(),e,{statName:"PriceScaleContextMenu"},{menuName:"PriceScaleContextMenu"})}}_setResizeCursor(){const e=this.priceScale();e.isPercentage()||e.isIndexedTo100()?this._setCursorClassName(""):this._zoomAvailable()&&(this._options.pressedMouseMoveScale||this._options.mouseWheelScale)&&this._setCursorClassName("ns-resize")}_setCursorClassName(e){let t="";e&&(t="price-axis--cursor-"+e),this._currentCursorClassName!==t&&(this._currentCursorClassName&&this._cell.classList.remove(this._currentCursorClassName),t&&this._cell.classList.add(t),this._currentCursorClassName=t)}_zoomAvailable(){return!this.priceScale().isEmpty()&&this.priceScale().hasCalculatedPriceRange()&&this._undoModel.model().zoomEnabled()}_onMousewheel(e){if(!this._zoomAvailable()||!this._options.mouseWheelScale)return;const t=(0,r.ensureNotNull)(this._mouseWheelHelper).processWheel(e).deltaY;if(0===t)return;e.cancelable&&e.preventDefault();const i=this._undoModel,s=this._pane.state(),o=this.priceScale(),n=this._cell.getBoundingClientRect(),a=e.clientY-n.top,l=a+15*t;i.startScalePrice(s,this.priceScale(),a,!0),i.scalePriceTo(s,o,l),i.endScalePrice(s,o),e.stopPropagation()}_drawCrossHairLabel(e,t){const i=this._pane.state(),s=i.model(),o=this.priceScale(),r=s.crossHairSource().priceAxisViews(i,o);r&&r.length>0&&this._drawLabels(r,e,t)}_drawBackground(e,t){const i=this.backgroundTopColor(),s=this.backgroundColor(),{bitmapSize:o}=t;if(i===s?(0,V.clearRect)(e,0,0,o.width,o.height,this.backgroundColor()):(0,We.clearRectWithGradient)(e,0,0,o.width,o.height,i,s),this._highlighted){e.globalAlpha=.5;const t=h.themes[this._backgroundBasedTheme.value()].getThemedColor("color-price-axis-highlight");(0,V.fillRect)(e,0,0,o.width,o.height,t),e.globalAlpha=1}}_drawDrawingsHighlight(e,t){const i=this._pane.state().model(),s=this.priceScale(),o=i.selection().lineDataSources().filter((e=>e.priceScale()===s)).reduce(((e,t)=>{const i=t.priceAxisPoints() ;return 0===i.length?e:e.concat(i)}),[]);o.length>0&&this._hightlightBackground(e,o,this.priceScale().mainSource(),t);const r=i.crossHairSource();r.startMeasurePoint()&&this._hightlightBackground(e,r.measurePoints(),this.priceScale().mainSource(),t)}_drawBorder(e,t){e.save(),e.fillStyle=this.lineColor();const{horizontalPixelRatio:i}=t,s=Math.max(1,Math.floor(this.rendererOptions().borderSize*i)),o=this._isLeft?t.bitmapSize.width-s:0;e.fillRect(o,0,s,t.bitmapSize.height),e.restore()}_drawLabels(e,t,i){const s=this.rendererOptions(),o=this._isLeft?"right":"left";for(const r of e)r.isAxisLabelVisible()&&(t.save(),r.renderer().draw(t,i,s,this._widthCache,o),t.restore())}_hightlightBackground(e,t,i,s){if(!i)return;const o=i.firstValue();if(null===o)return;let r=t[0].price,n=t[0].price;for(let e=1;e=r&&(r=e,a=i),e<=t&&(t=e,n=i)}}return a&&n?[a,n]:[]}}_views(e,t){var i,s;const o=this._pane.state(),r=this.priceScale(),n=[];if(1!==e)for(const e of t.sources)t.topLevelSources.has(e)||n.push(...null!==(i=e.priceAxisViews(o,r))&&void 0!==i?i:[]);if(0!==e){const e=new Set,i=t=>!e.has(t),a=t=>{const s=t.filter(i);n.push(...this._viewsOrMaxMinViews(s));for(const t of s)e.add(t)};t.customSourceBeingMoved&&a([t.customSourceBeingMoved]),t.sourcesBeingMoved&&a(t.sourcesBeingMoved),t.selectedSources&&a(t.selectedSources),t.hoveredSource&&a([t.hoveredSource]),t.lineBeingEditedOrCreated&&a([t.lineBeingEditedOrCreated]);for(const e of[...t.sources,...o.customSources()])e.topPriceAxisViews&&n.push(...null!==(s=e.topPriceAxisViews(o,r))&&void 0!==s?s:[])}return n}_initActions(){if(!this._pane.hasState()||null!==this._actions)return;const e=this._undoModel,t=new gt.ActionWithStandardIcon({actionId:"Chart.PriceScale.Reset",options:{label:Pt,iconId:"Chart.Reset",shortcutHint:(0,at.humanReadableHash)(at.Modifiers.Alt+82),statName:"ResetScale",onExecute:()=>this.reset()}}),i=new ot.Action({actionId:"Chart.PriceScale.ToggleAutoScale",options:{label:Tt,checkable:!0,checked:!0,statName:"ToggleAutoScale",onExecute:()=>{e.togglePriceScaleAutoScaleMode(this.priceScale()),this._updateScalesActions()}}}),s=new ot.Action({actionId:"Chart.PriceScale.TogglePercentage",options:{label:Mt,checkable:!0,checked:this.priceScale().isPercentage(),statName:"TogglePercantage",onExecute:()=>{e.togglePriceScalePercentageScaleMode(this.priceScale()),this._updateScalesActions()}}}),o=new ot.Action({ actionId:"Chart.PriceScale.ToggleIndexedTo100",options:{label:xt,checkable:!0,checked:this.priceScale().isIndexedTo100(),statName:"ToggleIndexedTo100",onExecute:()=>{e.togglePriceScaleIndexedTo100ScaleMode(this.priceScale()),this._updateScalesActions()}}}),r=new ot.Action({actionId:"Chart.PriceScale.ToggleLogarithmic",options:{label:It,checkable:!0,checked:this.priceScale().isLog(),statName:"ToggleLogScale",onExecute:()=>{e.togglePriceScaleLogScaleMode(this.priceScale()),this._updateScalesActions()}}}),n=new ot.Action({actionId:"Chart.PriceScale.ToggleRegular",options:{label:At,checkable:!0,checked:this.priceScale().isRegular(),statName:"ToggleRegularScale",onExecute:()=>{e.setPriceScaleRegularScaleMode(this.priceScale()),this._updateScalesActions()}}}),a=new nt({actionId:"Chart.PriceScale.Labels.ToggleNoOverlappingLabelsVisibility",options:{label:Lt,checkable:!0,checked:this.priceScale().properties().childs().alignLabels.value(),statName:"TogglePreciseLabels"}},{property:this.priceScale().properties().childs().alignLabels,undoModel:e,undoText:St}),l=new ot.Action({actionId:"Chart.PriceScale.ToggleInvertScale",options:{label:kt,checkable:!0,checked:this.priceScale().isInverted(),statName:"Invert Scale",onExecute:()=>{e.invertPriceScale(this.priceScale()),this._updateScalesActions()}}});this._actions={reset:t,setAutoScale:i,setPercentage:s,setIndexedTo100:o,setLog:r,setRegular:n,alignLabels:a,invertScale:l},this._updateScalesActions()}_logAction(){return this._isMainSeriesAxis()?this._chart.actions().logSeriesScale:(0,r.ensureNotNull)(this._actions).setLog}_percentageAction(){return this._isMainSeriesAxis()?this._chart.actions().percentSeriesScale:(0,r.ensureNotNull)(this._actions).setPercentage}_indexedTo100Action(){return this._isMainSeriesAxis()?this._chart.actions().indexedTo100SeriesScale:(0,r.ensureNotNull)(this._actions).setIndexedTo100}_autoScaleAction(){return this._isMainSeriesAxis()?this._chart.actions().autoSeriesScale:(0,r.ensureNotNull)(this._actions).setAutoScale}_regularScaleAction(){return this._isMainSeriesAxis()?this._chart.actions().regularSeriesScale:(0,r.ensureNotNull)(this._actions).setRegular}_lockScaleAction(){const e=this._chart.actions().lockSeriesScale,t=Et(this.priceScale(),this._undoModel.model().mainSeriesScaleRatio());return e.update({hint:t}),e}_invertAction(){return this._isMainSeriesAxis()?this._chart.actions().invertSeriesScale:(0,r.ensureNotNull)(this._actions).invertScale}_isMainSeriesAxis(){return this.priceScale().hasMainSeries()}_updateScalesActions(){const e=this.priceScale(),t=this._isMainSeriesAxis(),i=(0,r.ensureNotNull)(e.mainSource()).properties(),s=t&&e.isLockScale(),o=t&&6===i.style.value(),n=(0,r.ensureNotNull)(this._actions);n.setRegular.update({checked:e.isRegular(),disabled:s||o}),n.setPercentage.update({checked:e.isPercentage(),disabled:s||o}),n.setIndexedTo100.update({checked:e.isIndexedTo100(),disabled:s||o}),n.setLog.update({checked:e.isLog(),disabled:s||o}),n.setAutoScale.update({checked:e.isAutoScale(),disabled:e.properties().childs().autoScaleDisabled.value() })}_createMergeScalesAction(){const e=this._chart.actions(),t=this._undoModel.model().priceScaleSlotsCount();if(t.left+t.right===1)return 0===t.left?e.moveScaleToLeft:e.moveScaleToRight;const i=[];return i.push(e.mergeLeftScalesAction),i.push(e.mergeRightScalesAction),new ot.Action({actionId:"Chart.PriceScale.MergeAllScales",options:{label:bt,subItems:i}})}_setCursor(e){let t="";"grabbing"!==e&&"ns-resize"!==e||(t="price-axis--cursor-"+e),this._currentCursorClassName!==t&&(this._currentCursorClassName&&this._cell.classList.remove(this._currentCursorClassName),t&&this._cell.classList.add(t),this._currentCursorClassName=t,this._cell.style.cursor)}_createScaleModeButtons(){var e;const t=this._scaleModeButtons=new mt({className:"price-axis__modeButtons",setMode:e=>{this._priceScale&&("log"===e?this._chart.model().setPriceScaleMode({log:!this._priceScale.isLog()},this._priceScale,ft):this._chart.model().setPriceScaleMode({autoScale:!this._priceScale.isAutoScale()},this._priceScale,vt))}});return t.element().style.background=this.backgroundColor(),this._cell.appendChild(t.element()),null===(e=this._priceScale)||void 0===e||e.modeChanged().subscribe(this,this._updateScaleModeButtons),this._updateScaleModeButtons(),t}_destroyScaleModeButtons(){var e;this._scaleModeButtons&&(this._isHovered.unsubscribe(this._updatePriceScaleModeButtonsVisibility),null===(e=this._priceScale)||void 0===e||e.modeChanged().unsubscribe(this,this._updateScaleModeButtons),this._scaleModeButtons.destroy(),this._scaleModeButtons=null)}_highlightColor(){const e=this.backgroundColor(),t=this._backgroundBasedTheme.value();if(null===this._highlightColorCache||this._highlightColorCache.backgroundColor!==e||this._highlightColorCache.theme!==t){const i=(0,p.applyTransparency)(h.themes[this._backgroundBasedTheme.value()].getThemedColor("color-price-axis-highlight"),50),s=(0,Pe.rgbaToString)((0,Pe.blendRgba)((0,Pe.parseRgba)(this.backgroundColor()),(0,Pe.parseRgba)(i)));this._highlightColorCache={theme:t,backgroundColor:e,resultColor:s}}return this._highlightColorCache.resultColor}_applyLightUpdateIfRequired(){"visibleOnMouseOver"===(0,dt.currencyUnitVisibilityProperty)().value()&&this._undoModel.model().lightUpdate()}}var Ot=i(104415),Vt=i(142257);const Wt=(0,m.getLogger)("Chart.ChartUndoModel");class Ft extends Vt.UndoCommand{constructor(e,t,i,s=!0){super(i,!1,s),this._newRightOffsetAndBarSpacing=null,this._model=e,this._rightOffsetAndBarSpacing=t}undo(){if(null!==this._newRightOffsetAndBarSpacing)return void Wt.logDebug("TimeScaleChangeUndoCommand.undo: Command is already undone");const e=this._model.timeScale();this._newRightOffsetAndBarSpacing={barSpacing:e.barSpacing(),rightOffset:e.rightOffset()},e.setBarSpacing(this._rightOffsetAndBarSpacing.barSpacing),e.setRightOffset(this._rightOffsetAndBarSpacing.rightOffset),this._model.lightUpdate()}redo(){if(null===this._newRightOffsetAndBarSpacing)return void Wt.logDebug("TimeScaleChangeUndoCommand.redo: Command is not undone");const e=this._model.timeScale() ;e.setBarSpacing(this._newRightOffsetAndBarSpacing.barSpacing),e.setRightOffset(this._newRightOffsetAndBarSpacing.rightOffset),this._model.lightUpdate(),this._newRightOffsetAndBarSpacing=null}}const Ht=(0,m.getLogger)("Chart.ChartUndoModel"),zt=new R.TranslatedString("scale price",a.t(null,void 0,i(347222)));class Ut extends Vt.UndoCommand{constructor(e,t,i,s,o,r=!0){super(zt,!1,r),this._newPriceScaleState=null,this._model=e,this._paneIndex=e.panes().indexOf(t),this._priceScaleId=i.id(),this._state=s,this._timestamp=o?performance.now():null}undo(){if(null!==this._newPriceScaleState)return void Ht.logDebug("PriceScaleChangeUndoCommand.undo: Command is already undone");const[e,t]=this._paneAndScale();this._newPriceScaleState=t.state(),this._model.restorePriceScaleState(e,t,this._state)}redo(){if(null===this._newPriceScaleState)return void Ht.logDebug("PriceScaleChangeUndoCommand.redo: Command is not undone");const[e,t]=this._paneAndScale();this._model.restorePriceScaleState(e,t,this._newPriceScaleState),this._newPriceScaleState=null}canMerge(e){return e instanceof Ut&&null!==this._timestamp&&null!==e._timestamp&&null===this._newPriceScaleState&&e._model===this._model&&e._paneIndex===this._paneIndex&&e._priceScaleId===this._priceScaleId&&Math.abs(e._timestamp-this._timestamp)<1e3}merge(e){this._timestamp=e._timestamp}_paneAndScale(){const e=this._model.panes()[this._paneIndex],t=(0,r.ensureNotNull)(e.getPriceScaleById(this._priceScaleId));return[e,t]}}var Gt=i(547871),qt=i(974655),jt=i(558793),Zt=i(606097),Kt=i(779196),Yt=i(776734);function $t(e,t){(0,Yt.getTracker)().then((i=>{if(null!==i){const s=(0,r.ensureNotNull)(e.model().mainSeries().symbolInfo()),o=s.pro_name||s.name;i.trackDrawingsAnalytics(o,e.name(),t)}}))}function Xt(e){$t(e,"create")}function Jt(e){$t(e,"paste")}var Qt=i(616117),ei=i(147354),ti=i(673747),ii=i(451798);function si(e){return"startMoving"in e&&"move"in e&&"endMoving"in e&&"convertYCoordinateToPriceForMoving"in e}var oi=i(440617),ri=i(276871),ni=i(964824),ai=i(986564);i(207322);const li=parseInt(ai["css-value-pane-controls-padding-left"]),ci=parseInt(ai["css-value-pane-controls-padding-right"]),di=(0,J.getHexColorByName)("color-cold-gray-700"),hi=(0,J.getHexColorByName)("color-cold-gray-400");let ui;Kt.performanceTestMode&&(async()=>{ui=await i.e(6316).then(i.bind(i,122331))})();const _i=new R.TranslatedString("scroll",a.t(null,void 0,i(468193))),pi=a.t(null,void 0,i(482232)),mi=a.t(null,void 0,i(398478));function gi(e,t,i){e.drawBackground&&e.drawBackground(t,i)}function Si(e,t,i){e.draw(t,i)}function vi(e,t){return e.paneViews(t)}function fi(e,t){var i,s;return null!==(s=null===(i=e.topPaneViews)||void 0===i?void 0:i.call(e,t))&&void 0!==s?s:[]}function bi(e,t){return e.labelPaneViews(t)}function yi(e,t){const i=e.strategyOrdersPaneView();return null===i?null:[i]}function Ci(e,t){return null===e||e.source!==t?null:e.hittest.data()}function wi(e,t,i,s,o){var r,n;const a=null!==(n=null===(r=e.result)||void 0===r?void 0:r.hittest.target())&&void 0!==n?n:0;t.target()>a&&(e.result={hittest:t, source:i,renderer:s,isCustom:o})}const Pi={contextMenuEnabled:!0,contextMenu:ct.defaultContextMenuOptions,priceScaleContextMenuEnabled:!0,legendWidgetEnabled:!0,controlsEnabled:!0,propertyPagesEnabled:!0,sourceSelectionEnabled:!0,countdownEnabled:!0},Ti=new Map([[De.AreaName.Text,"Text"],[De.AreaName.Style,"Style"]]),Mi=!D.enabled("display_legend_on_all_charts");let xi=null;function Ii(e,t){return!(0,De.shouldDefaultActionBeExecuted)(e,t,"pressedMouseMoveHandler","touchMoveHandler")}class Ai{constructor(e,t,i,o){this._legendWidget=null,this._paneControls=null,this._isDestroyed=!1,this._trackCrosshairOnlyAfterLongTap=(0,me.lastMouseOrTouchEventInfo)().isTouch,this._startTrackPoint=null,this._exitTrackingModeOnNextTry=!1,this._startMoveSourceParams=null,this._startChangeLineToolParams=null,this._preventSourceChange=!1,this._preventScrollUntilNextMouseDownOrTouchStart=!1,this._clonningAtMoveLineTools=null,this._startCloningPoint=null,this._size=(0,s.size)({width:0,height:0}),this._themedTopColor=null,this._initCrossHairPosition=null,this._firstZoomPoint=null,this._editDialog=null,this._processing=!1,this._pressedMoveStage=0,this._touchMove=!1,this._startTouchPoint=null,this._isSelecting=!1,this._prevHoveredHittest=null,this._contextMenuX=0,this._contextMenuY=0,this._startScrollingPos=null,this._isScrolling=!1,this._scrollPriceScale=null,this._scrollXAnimation=null,this._prevPinchScale=1,this._pinching=!1,this._wasPinched=!1,this._longTap=!1,this._contextMenuOpenedOnLastTap=!1,this._paneControlsResizeObserver=null,this._lastClickedSource=null,this._customLegendWidgetsFactoryMap=new Map,this._prevMoveEventPosition=null,this._onMagnetStateChangedListener=this._onMagnetStateChanged.bind(this),this._onShiftKeyStateChangedListener=this._onShiftKeyStateChanged.bind(this),this._currentCursorClassName="",this._lastFinishedToolId=null,this._needResetMeasureLater=!1,this._currentChangingLineToolHitTest=null,this._currentMovingHitTest=null,this._prevTooltipData=null,this._errorRenderer=null,this._highlightedPriceAxis=new O.WatchedValue({owner:"",axis:null}),this._visuallyCollapsed=new O.WatchedValue(!1),this._endOfSeriesDataBanner=null,this._selectionBeforeMouseDown=new WeakSet,this._canvasConfiguredHandler=()=>this._state&&this._chartModel().lightUpdate(),this._updateVisuallyCollapsed=()=>{this._visuallyCollapsed.setValue(!this.state().maximized().value()&&this.state().collapsed().value())},this._chart=e,this._state=t,this._options=(0,w.merge)((0,w.clone)(Pi),i),this._paneWidgetsSharedState=o,this._state&&this._subscribeToState();const n={contextMenuEnabled:this._options.priceScaleContextMenuEnabled,pressedMouseMoveScale:this._options.handleScale.axisPressedMouseMove.price,mouseWheelScale:this._options.handleScale.mouseWheel,currencyConversionEnabled:this._options.currencyConversionEnabled,unitConversionEnabled:this._options.unitConversionEnabled,countdownEnabled:this._options.countdownEnabled,croppedTickMarks:this._options.croppedTickMarks} ;void 0!==this._options.priceScaleContextMenu&&(n.contextMenu=this._options.priceScaleContextMenu);const a=(e,t,i,s,o)=>new Rt(this._chart,this,this._chartUndoModel(),i,t,e,n,s,o),l=e.properties().childs().scalesProperties,c=this._chartModel().rendererOptionsProvider(),d={backgroundBasedTheme:e.backgroundBasedTheme().spawnOwnership(),stubContextMenuProvider:()=>[],titlesProvider:()=>[],rendererOptionsProvider:c,getBackgroundTopColor:()=>this._chartModel().backgroundTopColor().value(),getBackgroundBottomColor:()=>this._chartModel().backgroundColor().value(),requestRepaint:()=>this._chartModel().lightUpdate()},h={showLabels:!1};this._lhsPriceAxisesContainer=new Je(l,"left",a,d,h),this._rhsPriceAxisesContainer=new Je(l,"right",a,d,h),this._paneCell=document.createElement("div"),this._paneCell.classList.add("chart-markup-table","pane"),this._div=document.createElement("div"),this._div.classList.add("chart-gui-wrapper"),this._div.setAttribute("data-name","pane-widget-chart-gui-wrapper"),this._paneCell.appendChild(this._div),this._canvasBinding=(0,V.createBoundCanvas)(this._div,(0,s.size)({width:16,height:16})),this._canvasBinding.subscribeSuggestedBitmapSizeChanged(this._canvasConfiguredHandler);const u=this._canvasBinding.canvasElement;u.style.position="absolute",u.style.left="0",u.style.top="0",this._topCanvasBinding=(0,V.createBoundCanvas)(this._div,(0,s.size)({width:16,height:16})),this._topCanvasBinding.subscribeSuggestedBitmapSizeChanged(this._canvasConfiguredHandler);const _=this._topCanvasBinding.canvasElement;_.style.position="absolute",_.style.left="0",_.style.top="0",this._rowElement=document.createElement("div"),this._rowElement.style.display="flex",this._rowElement.appendChild(this._lhsPriceAxisesContainer.getElement()),this._rowElement.appendChild(this._paneCell),this._rowElement.appendChild(this._rhsPriceAxisesContainer.getElement()),u.setAttribute("aria-hidden","true");const p=this._chartModel().mainSeries();p.dataEvents().symbolResolved().subscribe(this,this._updateAccesibilityAttr),p.onIntervalChanged().subscribe(this,this._updateAccesibilityAttr),this._updateAccesibilityAttr(),this._options.legendWidgetEnabled&&(this._options.customLegendWidgetFactories&&(this._customLegendWidgetsFactoryMap=this._options.customLegendWidgetFactories),this._loadAndCreateLegendWidget()),this._state&&!this._chart.readOnly()&&this._options.controlsEnabled&&this._loadAndCreatePaneControlsWidget(),(0,ii.magnetEnabled)().subscribe(this._onMagnetStateChangedListener),(0,W.shiftPressed)().subscribe(this._onShiftKeyStateChangedListener),this._paneCell.addEventListener("dragover",(e=>{e.dataTransfer&&Array.from(e.dataTransfer.files).some(Zt.blobImageFilter)&&e.preventDefault()})),this._paneCell.addEventListener("drop",(e=>{if(window.user.id&&e.dataTransfer&&this._state){const t=Array.from(e.dataTransfer.files).find(Zt.blobImageFilter);if(t){e.preventDefault();const i=(0,Zt.uploadImage)(t),s=URL.createObjectURL(t);this._chartUndoModel().pasteImageAsLineTool(i,s,this._state),i.catch((e=>{ this._chart.chartWidgetCollection().getToasts().then((t=>{(0,r.ensureNotNull)(t).showSimpleToast({title:mi,text:e.message,role:"alert",intent:Le.ToastIntent.Warning})}))}))}}})),this.setCursorForTool(),this._mouseEventHandler=new Me.MouseEventHandler(this._topCanvasBinding.canvasElement,this,{treatVertTouchDragAsPageScroll:!this._options.handleScroll.vertTouchDrag,treatHorzTouchDragAsPageScroll:!this._options.handleScroll.horzTouchDrag}),this._prevHoveredHittest=null,this._highlightedPriceAxis.subscribe((e=>this._highlightPriceAxisByLabel(e.axis))),this._prevPinchScale=0,this._isDestroyed=!1}destroy(){var e;this._chart.onPaneWidgetDestroyed(this);const t=this._chartModel().mainSeries();t.dataEvents().symbolResolved().unsubscribeAll(this),t.onIntervalChanged().unsubscribeAll(this),this._customLegendWidgetsFactoryMap.clear(),this._topCanvasBinding.unsubscribeSuggestedBitmapSizeChanged(this._canvasConfiguredHandler),this._topCanvasBinding.dispose(),this._canvasBinding.unsubscribeSuggestedBitmapSizeChanged(this._canvasConfiguredHandler),this._canvasBinding.dispose(),this._legendWidget&&(this._legendWidget.destroy(),this._legendWidget=null),null!==this._paneControlsResizeObserver&&this._paneControlsResizeObserver.disconnect(),null!==this._paneControls&&(this._paneControls.destroy(),this._paneControls=null),this._lhsPriceAxisesContainer.destroy(),this._rhsPriceAxisesContainer.destroy(),this.hasState()&&this._unsubscribeFromState(),(0,ii.magnetEnabled)().unsubscribe(this._onMagnetStateChangedListener),(0,W.shiftPressed)().unsubscribe(this._onShiftKeyStateChangedListener),this._paneWidgetsSharedState.onPaneDestroyed(this),this._errorRenderer&&this._errorRenderer.then((e=>{e.destroy(),this._errorRenderer=null})),this._prevHoveredHittest=null,this._mouseEventHandler.destroy(),null===(e=this._rowElement.parentElement)||void 0===e||e.removeChild(this._rowElement),this._isDestroyed=!0}size(){return this._size}setSize(e){(0,s.equalSizes)(this._size,e)||(this._size=e,this._canvasBinding.resizeCanvasElement(e),this._topCanvasBinding.resizeCanvasElement(e),this._paneCell.style.width=e.width+"px",this._paneCell.style.height=e.height+"px",this._div.style.width=e.width+"px",this._div.style.height=e.height+"px",this._rowElement.classList.toggle("js-hidden",0===e.height),null!==this._legendWidget&&this._legendWidget.updateWidgetModeBySize(e),null!==this._paneControls&&this._paneControls.updateWidgetModeByWidth(e.width))}width(){return this._size.width}height(){return this._size.height}backgroundColor(){return this._chartModel().backgroundColor().value()}highlightedPriceAxis(){return this._highlightedPriceAxis}processDoubleClickOnSource(e,t,i){if((0,Qe.isAlertLabel)(e)){const t=e.alert(),s=t.id().value();if(t.isNew()||!s)return;(0,jt.getChartAlertsFacade)().then((e=>{var t;(0,u.trackEvent)("chart_alert","edit",`double_click_on_${null!==(t=null==i?void 0:i.origin)&&void 0!==t?t:"line"}`),e.openEditDialog(s,{actionSource:"alert_label_double_click",dataSourceHub:this._chartModel()})}))}else(0, Re.isDataSource)(e)&&e.id()!==this._lastFinishedToolId&&this._showEditDialogForSource(e,t)}stretchFactor(){return this._state?this._state.stretchFactor():0}setStretchFactor(e){this.hasState()&&this.state().setStretchFactor(e)}setCursorForTool(e,t,i){if(t&&t.mod()&&e&&e!==this._chartModel().crossHairSource())return void this._setCursorClassName("pointer");if(void 0!==i){switch(i){case ei.PaneCursorType.VerticalResize:this._setCursorClassName("ns-resize");break;case ei.PaneCursorType.HorizontalResize:this._setCursorClassName("ew-resize");break;case ei.PaneCursorType.DiagonalNeSwResize:this._setCursorClassName("nesw-resize");break;case ei.PaneCursorType.DiagonalNwSeResize:this._setCursorClassName("nwse-resize");break;case ei.PaneCursorType.Default:this._setCursorClassName("default");break;case ei.PaneCursorType.Pointer:this._setCursorClassName("pointer");break;case ei.PaneCursorType.Grabbing:this._setCursorClassName("grabbing");break;case ei.PaneCursorType.Text:this._setCursorClassName("text")}return}const s=Oe.tool.value();if((0,Oe.toolIsCursor)(s)){if(null!==this._paneWidgetsSharedState.draggingSource()||this._isScrolling||this._chartUndoModel()&&this._chartUndoModel().model().sourcesBeingMoved().length)return void this._setCursorClassName("grabbing");if(e&&this._options.sourceSelectionEnabled)return void this._setCursorClassName("pointer")}if("eraser"===s)return void this._setCursorClassName("eraser");if("performance"===s)return void this._setCursorClassName("performance");if("zoom"===s)return void this._setCursorClassName("zoom-in");const o=Oe.cursorTool.value();"dot"!==o?"arrow"!==o?this._setCursorClassName(""):this._setCursorClassName("default"):this._setCursorClassName("dot")}showContextMenuForSelection(e,t,i){const s=this._chartUndoModel().selection();if(s.isEmpty())return;const o=s.dataSources().filter((e=>e.hasContextMenu()));this.showContextMenuForSources(o,e,void 0,t,i)}async showContextMenuForSources(e,t,i,s,o){var r,n,a,l,c;if(!e.length||!this._state)return Promise.resolve(null);const d=e[0],h=(0,w.merge)((0,w.clone)(this._options.contextMenu),i||{}),u=new ct.ActionsProvider(this._chart,h);if(d===this._chartUndoModel().crossHairSource())return d.handleContextMenuEvent(t),Promise.resolve(null);{const i=await u.contextMenuActionsForSources(e,this._state,t,null==s?void 0:s.origin,null===(r=null==o?void 0:o.data())||void 0===r?void 0:r.customActions);if(0===i.length)return Promise.resolve(null);{let e;return e=d instanceof oi.Series?{menuName:null!==(n=null==s?void 0:s.origin)&&void 0!==n?n:"ObjectTreeContextMenu",detail:{type:"series",id:d.instanceId()}}:(0,K.isLineTool)(d)?{menuName:null!==(a=null==s?void 0:s.origin)&&void 0!==a?a:"ObjectTreeContextMenu",detail:{type:"shape",id:null!==(l=null==d?void 0:d.id())&&void 0!==l?l:null}}:{menuName:null!==(c=null==s?void 0:s.origin)&&void 0!==c?c:"ObjectTreeContextMenu",detail:{type:"study",id:(null==d?void 0:d.id())||null}},Ue.ContextMenuManager.createMenu(i,{takeFocus:!0,returnFocus:!0,isKeyboardEvent:h.isKeyboardEvent},e).then((e=>(e.show(t),e)))}}} leftPriceAxisesContainer(){return this._lhsPriceAxisesContainer}rightPriceAxisesContainer(){return this._rhsPriceAxisesContainer}setPriceAxisSizes(e,t,i){this._priceAxisesContainer(e).setSizes(t,i)}state(){return(0,r.ensureNotNull)(this._state)}hasState(){return null!==this._state}setState(e){this._state!==e&&(this.hasState()&&this._unsubscribeFromState(),this._state=e,this.hasState()&&(this._subscribeToState(),this.updatePriceAxisWidgetsStates()))}getScreenshotData(e){var t,i,s,o;const r=[],n=[];let a,l=[];const c=this.state().sourcesByGroup().priceSources().slice().reverse(),d=this._chart.properties().childs().paneProperties.childs().legendProperties.childs();for(const h of c){const c=h.statusView();if((0,q.isStudy)(h)&&(d.showLegend.value()||(null==e?void 0:e.showCollapsedStudies))){const s=d.showStudyTitles.value(),o=!0;if(h.properties().childs().visible.value()&&this._chartModel().paneForSource(h)===this.state()&&c&&o){r.push(s?h.statusProvider(null==e?void 0:e.status).text():"");const o=D.enabled("use_last_visible_bar_value_in_legend")&&null!==(i=null===(t=this._chartModel().timeScale().visibleBarsStrictRange())||void 0===t?void 0:t.lastBar())&&void 0!==i?i:null,a=h.legendValuesProvider().getValues(o);n.push(a)}}else if(h===this._chartModel().mainSeries()&&c&&d.showSeriesTitle.value()){a=h.statusProvider((null==e?void 0:e.status)||{}).text();const t=D.enabled("use_last_visible_bar_value_in_legend")&&null!==(o=null===(s=this._chartModel().timeScale().visibleBarsStrictRange())||void 0===s?void 0:s.lastBar())&&void 0!==o?o:null;l=h.legendValuesProvider().getValues(t)}}return{type:"pane",leftAxis:this._lhsPriceAxisesContainer.getScreenshotData(),rightAxis:this._rhsPriceAxisesContainer.getScreenshotData(),content:this._canvasBinding.canvasElement.toDataURL(),canvas:this._canvasBinding.canvasElement,contentWidth:this._size.width,contentHeight:this._size.height,studies:r,studiesValues:n,containsMainSeries:this.containsMainSeries(),mainSeriesText:a,mainSeriesValues:l}}updatePriceAxisWidgetsStates(){if(!this.hasState())return;const e=this._chartModel(),t=e.paneForSource(e.mainSeries());if(!t)return;const i=e.priceScaleSlotsCount(),s=this.state(),o=s.visibleLeftPriceScales(),r=s.visibleRightPriceScales();this._lhsPriceAxisesContainer.setScales(o,i.left,t.leftPriceScales().length,i.left+i.right),this._rhsPriceAxisesContainer.setScales(r,i.right,t.rightPriceScales().length,i.left+i.right)}updatePriceAxisWidgets(){this._lhsPriceAxisesContainer.update(),this._rhsPriceAxisesContainer.update()}update(){this.hasState()&&(this.updatePriceAxisWidgets(),null!==this._legendWidget&&this._legendWidget.update(),this.updateControls())}updateStatusWidget(e){this.hasState()&&null!==this._legendWidget&&(e.legendWidgetLayoutInvalidated()?this._legendWidget.updateLayout():this._legendWidget.update())}updateControls(){this.hasState()&&null!==this._paneControls&&this._paneControls.update()}updateThemedColors(e){this._themedTopColor=e.topColor,this._updateByThemedColors()}statusWidget(){return this._legendWidget}getElement(){ return this._rowElement}canvasElement(){return this._canvasBinding.canvasElement}hasCanvas(e){return this._canvasBinding.canvasElement===e||this._topCanvasBinding.canvasElement===e}pinchStartEvent(){return null===this._paneWidgetsSharedState.scrollingPane()&&null===this._paneWidgetsSharedState.pinchingPane()&&(this._onTouchEvent(),!!this._options.handleScale.pinch&&(this._chartModel().stopTimeScaleAnimation(),this._prevPinchScale=1,this._pinching=!0,this._wasPinched=!0,this._paneWidgetsSharedState.setPinchingPane(this),!0))}pinchEvent(e,t,i,s){if(null!==this._paneWidgetsSharedState.scrollingPane()||this._paneWidgetsSharedState.pinchingPane()!==this)return;if(this._onTouchEvent(),!this._options.handleScale.pinch)return;const o=10*(s-this._prevPinchScale);this._prevPinchScale=s,this._chartModel().zoomTime(e.x,o,!0),this._prevPinchScale=s}pinchEndEvent(){null===this._paneWidgetsSharedState.scrollingPane()&&this._paneWidgetsSharedState.pinchingPane()===this&&(this._onTouchEvent(),this._pinching=!1,this._paneWidgetsSharedState.setPinchingPane(null))}mouseClickEvent(e){this._onMouseEvent(),this._mouseClickOrTapEvent(e)}tapEvent(e){this._preventTouchEventsExceptPinch()||(this._onTouchEvent(),this._mouseClickOrTapEvent(e))}mouseDownEvent(e){this._onMouseEvent(),this.hasState()&&this._mouseDownOrTouchStartEvent(e,this._dataSourceAtPoint(e.localX,e.localY))}touchStartEvent(e){if(this._paneWidgetsSharedState.startTouch(this),this._preventTouchEventsExceptPinch())return;const t=!this._trackCrosshairOnlyAfterLongTap&&null!==xi&&xi.stateId===this.state().id()&&Math.abs(xi.x-e.localX)+Math.abs(xi.y-e.localY)<5;this._onTouchEvent(),this._chart.setActivePaneWidget(this);const i=this._dataSourceAtPoint(e.localX,e.localY);if(t){const t=this._chartModel().crossHairSource();null!==i&&i.source===t||t.selectPointMode().value()!==Oe.SelectPointMode.None?this.startTrackingMode(new ke.Point(e.localX,e.localY),new ke.Point(e.localX,e.localY)):!this._chart.readOnly()&&null!==i&&((0,K.isLineTool)(i.source)&&i.source.userEditEnabled()||(0,Qe.isAlertLabel)(i.source))&&this._chartUndoModel().selectionMacro((e=>{e.clearSelection(),e.addSourceToSelection(i.source,i.hittest.data())}))}this._mouseDownOrTouchStartEvent(e,i),this._mouseOrTouchMoveEvent(e)}mouseUpEvent(e){this._onMouseEvent(),this._mouseUpOrTouchEndEvent(e)}touchEndEvent(e){this._paneWidgetsSharedState.endTouch(this),this._preventTouchEventsExceptPinch()||(this._onTouchEvent(),this._mouseOrTouchLeaveEvent(e),this._mouseUpOrTouchEndEvent(e))}mouseMoveEvent(e){this._onMouseEvent(),this._mouseOrTouchMoveEvent(e)}pressedMouseMoveEvent(e){this._onMouseEvent(),this._pressedMouseOrTouchMoveEvent(e)}touchMoveEvent(e){this._preventTouchEventsExceptPinch()||(this._onTouchEvent(),this._pressedMouseOrTouchMoveEvent(e))}mouseLeaveEvent(e){this._onMouseEvent(),this._updateHoveredSource(null,new Ne.EnvironmentState(e)),this._mouseOrTouchLeaveEvent(e)}mouseDoubleClickEvent(e){this._onMouseEvent(),this._mouseDoubleClickOrDoubleTapEvent(e)}wheelClickEvent(e){if(this._chart.readOnly())return ;const t=this._dataSourceAtPoint(e.localX,e.localY);if(null===t||t.isCustom)return;if((t.hittest.target()||0)<=De.HitTarget.MovePointBackground)return;const i=new Ne.EnvironmentState(e),s=t.hittest.eraseMarker();if(i.mod()&&void 0!==s&&t.source.processErase)return void t.source.processErase(this._chartUndoModel(),s);const o=this._chartUndoModel();o.selection().isSelected(t.source)||o.selectionMacro((e=>{e.clearSelection();const i=(0,r.ensureNotNull)(t.source);e.addSourceToSelection(i,Ci(t,i))})),this._chart.removeSelectedSources()}doubleTapEvent(e){this._preventTouchEventsExceptPinch()||(this._onTouchEvent(),this._mouseDoubleClickOrDoubleTapEvent(e))}longTapEvent(e){if(null===this._state||this._preventTouchEventsExceptPinch())return;if(this._onTouchEvent(),this._longTap=!0,null!==this._startTrackPoint||!this._trackingModeShouldBeActive())return;const t=this._chartModel().selection();if(!t.isEmpty()){const i=this._dataSourceAtPoint(e.localX,e.localY);if(null!==i&&t.isSelected(i.source))return}this.startTrackingMode(new ke.Point(e.localX,e.localY),new ke.Point(e.localX,e.localY),new Ne.EnvironmentState(e))}mouseEnterEvent(e){if(this._onMouseEvent(),!this.hasState())return;this._chart.setActivePaneWidget(this);const t=this._dataSourceAtPoint(e.localX,e.localY);this._updateHoveredSource(t,new Ne.EnvironmentState(e)),this.setCursorPosition(e.localX,e.localY,new Ne.EnvironmentState(e))}contextMenuEvent(e){this._onMouseEvent(),this._contextMenuEvent(e)}touchContextMenuEvent(e){this._preventTouchEventsExceptPinch()||(this._onTouchEvent(),this._contextMenuEvent(e))}mouseDownOutsideEvent(e){this._processOutsideClick(null,e)}touchStartOutsideEvent(e){this._processOutsideClick(null,e)}cancelZoom(){this._chartModel().crossHairSource().clearSelection(),this._firstZoomPoint=null,this._preventCrossHairMove()&&this._clearCursorPosition()}startTrackingMode(e,t,i){this._startChangeLineToolParams=null,this._startMoveSourceParams=null,this._currentChangingLineToolHitTest=null,this._currentMovingHitTest=null,this._chartUndoModel().selectionMacro((e=>e.clearSelection())),this._startTrackPoint=e,this._exitTrackingModeOnNextTry=!1,this.setCursorPosition(t.x,t.y,i),this._initCrossHairPosition=this._chartModel().crossHairSource().currentPoint()}setDragToAnotherPaneCursor(){this._setCursorClassName("grabbing")}cloneLineTools(e,t){return this._chartUndoModel().cloneLineTools(e,t)}exitTrackingMode(){null!==this._state&&null!==this._startTrackPoint&&(this._exitTrackingModeOnNextTry=!0,this._tryExitTrackingMode())}trackingModeEnabled(){return null!==this._state&&null!==this._startTrackPoint}addCustomWidgetToLegend(e,t){this._options.legendWidgetEnabled&&(this._customLegendWidgetsFactoryMap.set(e,t),null!==this._legendWidget&&this._legendWidget.addCustomWidgetToLegend(e,t))}containsMainSeries(){return!!this.hasState()&&this.state().containsMainSeries()}paint(e){if(!this._chartUndoModel()||!this.hasState()||0===this._size.width||0===this._size.height)return;(0,V.tryApplySuggestedCanvasBitmapSize)(this._canvasBinding),(0, V.tryApplySuggestedCanvasBitmapSize)(this._topCanvasBinding),this._state&&(e.priceScaleSideMaxLevel("left")>pe.InvalidationLevel.Cursor||e.priceScaleSideMaxLevel("right")>pe.InvalidationLevel.Cursor)&&(this._recalculatePriceScales((0,ni.viewportChangeEvent)()),null!==xi&&xi.stateId===this.state().id()&&this.setCursorPosition(xi.x,xi.y,xi.envState));const t=e.fullInvalidation();if(t>pe.InvalidationLevel.Cursor&&null!==xi&&xi.stateId===this.state().id()){const e=this._dataSourceAtPoint(xi.x,xi.y);this._updateHoveredSource(e,(0,W.globalEnvironmentState)())}if(this._lhsPriceAxisesContainer.paint(e.getterForPriceScaleInvalidationLevelBySide("left")),this._rhsPriceAxisesContainer.paint(e.getterForPriceScaleInvalidationLevelBySide("right")),t===pe.InvalidationLevel.None)return;const i=this._state&&(this._state.maximized().value()||!this._state.collapsed().value());if(t>pe.InvalidationLevel.Cursor){const e=(0,r.ensureNotNull)(this._canvasBinding.canvasElement.getContext("2d"));e.setTransform(1,0,0,1,0,0);const t=(0,V.getBindingRenderingInfo)(this._canvasBinding);this._makeSureIsUpdated(t),this._drawBackground(e,t),i&&this._drawSources(e,t)}if(null!==this._state){const e=(0,r.ensureNotNull)(this._topCanvasBinding.canvasElement.getContext("2d"));e.setTransform(1,0,0,1,0,0);const t=(0,V.getBindingRenderingInfo)(this._topCanvasBinding);e.clearRect(0,0,t.bitmapSize.width,t.bitmapSize.height),i&&this._drawTopViews(e,t),this._drawCrossHair(e,t),i&&this._drawActiveLineTools(e,t)}this._updateEndOfSeriesBanner()}cancelCreatingLineTool(){const e=this._chartUndoModel(),t=this._chartUndoModel().lineBeingCreated();if(t)if(t.pointsCount()<=0&&!(0,Qt.isLineDrawnWithPressedButton)(t.toolname)){const i=t.points();if(i.length>2){const s=i[i.length-2];e.continueCreatingLine(s),this._finishTool(t)}else e.cancelCreatingLine()}else e.cancelCreatingLine();null!==this._firstZoomPoint&&this.cancelZoom(),this.setCursorForTool()}drawRightThere(e){if((0,Qt.isLineToolName)(e)&&this.hasState()){const t=this._chartUndoModel(),i=t.crossHairSource(),s=t.model().magnet().align(i.price,i.index,this.state());t.createLineTool({pane:this.state(),point:{index:i.index,price:s},linetool:e})}}cancelMeasuring(){this._chartUndoModel().crossHairSource().clearMeasure(),(0,Oe.resetToCursor)(),this.setCursorForTool()}async setErrorMessage(e){var t,i,s;e&&!this._errorRenderer&&(this._errorRenderer=this._createErrorBlock()),null===(t=await this._errorRenderer)||void 0===t||t.update({message:null==e?void 0:e.message,icon:(null===(i=this._state)||void 0===i?void 0:i.containsMainSeries())||(null===(s=this._state)||void 0===s?void 0:s.maximized().value())?null==e?void 0:e.icon:void 0,backgroundColor:`linear-gradient(${this._chartModel().backgroundTopColor().value()}, ${this._chartModel().backgroundColor().value()})`,textColor:this._chartModel().dark().value()?hi:di,solutionId:null==e?void 0:e.solutionId,rawHtml:null==e?void 0:e.rawHtml,buttons:this.containsMainSeries()?null==e?void 0:e.buttons:void 0,maxWidth:null==e?void 0:e.maxWidth,maxHeight:null==e?void 0:e.maxHeight, zeroHeight:null==e?void 0:e.zeroHeight})}collapsedHeight(){var e,t;return Math.max(Math.ceil(null!==(t=null===(e=this._paneControls)||void 0===e?void 0:e.bottomWithMargin())&&void 0!==t?t:0),33)}setCursorPosition(e,t,i){this._updateLastCrosshairPosition(e,t,i),this._chartModel().setAndSaveCurrentPosition(this._correctXCoord(e),this._correctYCoord(t),this.state(),i)}_tryExitTrackingMode(e){this._exitTrackingModeOnNextTry&&(this._startTrackPoint=null,e||this._clearCursorPosition())}_tryStartMeasure(e,t,i,s,o){return!(!(0,Oe.toolIsMeasure)(Oe.tool.value())||t.startMeasurePoint())&&(e.isTouch||this._preventCrossHairMove()||this.setCursorPosition(e.localX,e.localY,i),s=this._chartModel().magnet().align(s,o,this.state()),t.startMeasuring({price:s,index:o},this.state()),!0)}_tryFinishMeasure(e,t){if(t.startMeasurePoint()&&!t.endMeasurePoint()){let i=t.price;const s=t.index;return i=this._chartModel().magnet().align(i,s,this.state()),t.finishMeasure({price:i,index:s}),e.isTouch?(0,Oe.resetToCursor)():this._needResetMeasureLater=!0,this._preventCrossHairMove()&&this._clearCursorPosition(),!0}return!1}_tryStartZoom(e,t,i,s){const o=this._chart.model().model().zoomEnabled();if("zoom"===Oe.tool.value()&&o){const o=this._chartUndoModel(),r=o.timeScale().indexToCoordinate(i)-.5*o.timeScale().barSpacing();return this._firstZoomPoint={price:t,index:i,x:r,y:e.localY},this._preventCrossHairMove()||this.setCursorPosition(e.localX,e.localY,s),this._chartModel().crossHairSource().startSelection(this.state()),!0}return!1}_finishZoom(e){const t=this.state(),i=t.defaultPriceScale(),s=(0,r.ensureNotNull)(t.mainDataSource()).firstValue(),o=i.coordinateToPrice(e.localY,(0,r.ensureNotNull)(s)),n=this._chartUndoModel(),a=Math.round(n.timeScale().coordinateToIndex(e.localX)),l=(0,r.ensureNotNull)(this._firstZoomPoint);a!==l.index&&n.zoomToViewport(l.index,a,l.price,o,t),this._chartModel().crossHairSource().clearSelection(),this._firstZoomPoint=null,(0,Oe.resetToCursor)(),this._preventCrossHairMove()&&this._clearCursorPosition()}_tryFinishZoom(e){return null!==this._firstZoomPoint&&(this._finishZoom(e),!0)}_tryHandleEraserMouseDown(e,t){if(!("eraser"!==Oe.tool.value()||e.isCustom||(i=e.source,i&&i.customization&&i.customization.disableErasing))){const i=this._chartUndoModel();if((0,K.isLineTool)(e.source)||(0,q.isStudy)(e.source)){const s=e.hittest.eraseMarker();return t.mod()&&void 0!==s&&e.source.processErase?e.source.processErase(i,s):i.removeSource(e.source,!1),!0}}var i;return!1}_tryStartChangingLineTool(e,t,i,s){var o,n,a;if(e.isTouch&&null!==this._startTrackPoint)return!1;const l=t.hittest;if((!e.isTouch||!this._preventSourceChange)&&l&&(0,K.isLineTool)(t.source)&&l.target()===De.HitTarget.ChangePoint){const c=this._chartUndoModel(),d=(0,r.ensure)(null===(o=this.state().mainDataSource())||void 0===o?void 0:o.firstValue()),h=(0,r.ensureNotNull)(t.source.priceScale()).coordinateToPrice(e.localY,d);c.selectionMacro((e=>{e.clearSelection(),e.addSourceToSelection(t.source,l.data())}));let u=h ;t.source.priceScale()===c.mainSeries().priceScale()&&(u=c.model().magnet().align(h,s,this.state()));const _=null===(n=l.data())||void 0===n?void 0:n.nonDiscreteIndex;_&&(s=c.timeScale().coordinateToFloatIndex(e.localX));const p=null===(a=l.data())||void 0===a?void 0:a.pointIndex;return this._startChangeLineToolParams={source:t.source,startPoint:{index:s,price:u,nonDiscreteIndex:_},screenPoint:{x:e.localX,y:e.localY},pointIndex:p,envState:i},!0}return this._startChangeLineToolParams=null,!1}_tryStartCloning(e,t,i,s){if(i.mod()){const t=this._chartUndoModel().selection().dataSources().filter((e=>e.cloneable()));if(s&&s.cloneable()&&t.push(s),t.length>0)return this._clonningAtMoveLineTools=t.map((e=>e.id())),this._startCloningPoint=new ke.Point(e.localX,e.localY),!0}return!1}_tryFinishClonning(e,t,i){const s=this._chartUndoModel(),o=this._chartModel();if(t.mod()&&this._clonningAtMoveLineTools){const n=new ke.Point(e.localX,e.localY),a=(0,r.ensureNotNull)(this._startCloningPoint).subtract(n).length(),l=[];for(const e of this._clonningAtMoveLineTools){const t=o.dataSourceForId(e);null!==t&&l.push(t)}if(0===l.length)return!1;if(a>8){const o=this.cloneLineTools(l,!0).map((e=>(0,r.ensureNotNull)(s.model().dataSourceForId(e))));s.selectionMacro((e=>{e.clearSelection();let t=null;o.forEach((s=>{null===t&&(t=Ci(i,s)),e.addSourceToSelection(s,t)}))}));const n=new ke.Point(e.localX,e.localY),a=(0,r.ensureNotNull)(o[0].priceScale()),c=(0,r.ensureNotNull)(this.state().mainDataSource()).firstValue(),d={index:s.timeScale().coordinateToIndex(e.localX),price:a.coordinateToPrice(e.localY,(0,r.ensureNotNull)(c))};s.startMovingSources(o,{logical:d,screen:n},null,t),this._clonningAtMoveLineTools=null,this._startCloningPoint=null}return!0}return!1}_mouseDownEventForLineTool(e,t,i,s){var o,n;const a=Oe.tool.value();if(!this.hasState()||(0,Qt.isLineToolDrawWithoutPoints)(a))return;const l=this._chartUndoModel();let c=!1,d=null;(0,Oe.hideAllDrawings)().value()&&(0,f.toggleHideMode)(),(0,Oe.lockDrawings)().setValue(!1),e.isTouch&&!e.stylus&&((0,Qt.isLineToolName)(a)&&!(0,Qt.isLineDrawnWithPressedButton)(a)||l.lineBeingCreated())&&this._initToolCreationModeParams(e);const h=l.lineBeingCreated();if(h&&!(0,Qt.isLineDrawnWithPressedButton)(h.toolname)){const a=(0,r.ensure)(null===(o=h.ownerSource())||void 0===o?void 0:o.firstValue());if(e.isTouch&&!e.stylus){if(!this._startTouchPoint){this._startTouchPoint=new ke.Point(e.pageX,e.pageY);const t=h.points(),i=t[t.length-1],s=l.timeScale().indexToCoordinate(i.index),o=(0,r.ensureNotNull)(h.priceScale()).priceToCoordinate(i.price,a);return void(this._initCrossHairPosition=new ke.Point(s,o))}}else if(!e.isTouch){d=h;const o=l.model().paneForSource(h);if(o!==this._state&&null!==o){const i=this._externalPaneXCoord(o,e.localX),s=this._externalPaneYCoord(o,e.localY);c=l.continueCreatingLine({index:Math.round(l.timeScale().coordinateToIndex(i)),price:(0,r.ensure)(null===(n=h.priceScale())||void 0===n?void 0:n.coordinateToPrice(s,a))},t)}else{const e=l.model().magnet().align(s,i,this.state()) ;c=l.continueCreatingLine({index:i,price:e},t)}}}else if(!e.isTouch||e.stylus||(0,Qt.isLineDrawnWithPressedButton)(a)){const e={index:i,price:l.model().magnet().align(s,i,this.state())};d=l.createLineTool({pane:this.state(),point:e,linetool:a}),l.lineBeingCreated()||(c=!0)}const u=this._dataSourceAtPoint(e.localX,e.localY);d&&l.selectionMacro((e=>{e.addSourceToSelection((0,r.ensureNotNull)(d),null==u?void 0:u.hittest.data())})),c&&d&&(this._finishTool(d,u),e.preventDefault())}_handleSelectionMouseDownAndGetJustDeselectedSource(e,t,i){const s=this._chartUndoModel();let o=null;return(null===t||t.source.isSelectionEnabled())&&s.selectionMacro((s=>{!this._preventSourceChange&&null!==t&&(e.isTouch?t.hittest.target()>=De.HitTarget.MovePointBackground:t.hittest.target()>De.HitTarget.MovePointBackground)?(i.mod()||s.selection().isSelected(t.source)||s.clearSelection(),i.mod()&&s.selection().isSelected(t.source)?(o=t.source,s.removeSourceFromSelection(t.source)):s.addSourceToSelection(t.source,t.hittest.data()),s.selection().allSources().length>1&&(0,u.trackEvent)("GUI","Multiselect","Click Select")):i.mod()||s.clearSelection()})),o}_processMouseMoveWhileZoom(e,t){this._preventCrossHairMove()||this.setCursorPosition(e.localX,e.localY,t)}_updateCommonTooltip(e,t){let i=null;if(null!==e&&null!==e.hittest){const t=e.hittest.data();t&&(i=t.tooltip||null)}if(null===this._prevTooltipData&&null===i)return;if(null===i||""===i.text)return this._prevTooltipData=null,void(0,ti.hide)(t);if(this._prevTooltipData&&(0,Ae.default)(i,this._prevTooltipData))return;this._prevTooltipData=i;const s=(0,w.clone)(i);if(void 0!==s.rect){const e=this._paneCell.getBoundingClientRect();s.rect.x+=e.left,s.rect.y+=e.top}(0,ti.show)(s)}_setCursorPositionOnExternalPane(e,t,i,s){t=this._externalPaneXCoord(e,t),i=this._externalPaneYCoord(e,i);this._chart.paneByState(e).setCursorPosition(t,i,s)}_updateLastCrosshairPosition(e,t,i){const s=this.state().id();xi={x:e,y:t,envState:i,stateId:s}}_setCursorClassName(e){let t="";e&&(t="pane--cursor-"+e),this._currentCursorClassName!==t&&(this._currentCursorClassName&&this._paneCell.classList.remove(this._currentCursorClassName),t&&this._paneCell.classList.add(t),this._currentCursorClassName=t,this._paneCell.style.cursor)}_processMouseUpOrTouchEndHandler(e){const t=this._dataSourceAtPoint(e.localX,e.localY);if(null!==t){const i=this._sourceWasSelected(t);t.hittest.tryCallMouseUpOrTouchEndHandler(e,{sourceWasSelected:i})}}_crossHairShouldBeVisible(){const e=this._chartModel().crossHairSource();return(0,Qt.isLineToolName)(Oe.tool.value())||(0,Oe.toolIsMeasure)(Oe.tool.value())||e.startMeasurePoint()&&!e.endMeasurePoint()||null!==this._firstZoomPoint||null!==this._chartModel().lineBeingEdited()||null!==this._chartModel().lineBeingCreated()}_clearCursorPosition(){xi=null,this._chartModel().clearCurrentPosition()}_dataSourceAtPoint(e,t){var i,s;if(!this.hasState())return null;const o={result:null},r=this._chartUndoModel();if((0,Qt.isLineToolName)(Oe.tool.value())||null!==r.lineBeingCreated())return o.result ;if(this._currentChangingLineToolHitTest)return this._currentChangingLineToolHitTest;const n=new Set;if(this._currentMovingHitTest&&this._currentMovingHitTest.sourceAtPoint.hittest.data()){if(!(null===(i=this._currentMovingHitTest.cancelledContainer)||void 0===i?void 0:i.cancelled))return this._currentMovingHitTest.sourceAtPoint;n.add(this._currentMovingHitTest.sourceAtPoint.source.id())}if(this._currentMovingHitTest&&this._currentMovingHitTest.sourceAtPoint.hittest.data()&&!(null===(s=this._currentMovingHitTest.cancelledContainer)||void 0===s?void 0:s.cancelled))return this._currentMovingHitTest.sourceAtPoint;const a=this.state(),l=(0,V.getBindingRenderingInfo)(this._canvasBinding);this._makeSureIsUpdated(l);const c=wi.bind(null,o),d=new ke.Point(e,t);if(!a.maximized().value()&&a.collapsed().value()||(0,me.lastMouseOrTouchEventInfo)().isTouch&&(Oe.activePointSelectionMode.value()!==Oe.SelectPointMode.None||null!==this._startTrackPoint))return this._hitTestSources(l,[r.crossHairSource()],d,c,!1,n),o.result;const h=a.sourcesByGroup(),u=r.selection(),_=u.dataSources().filter((e=>e.isMultiPaneEnabled()||r.paneForSource(e)===a));this._hitTestSources(l,_,d,c,!1,n),this._hitTestSources(l,u.customSources(),d,c,!0,n),u.allSources().forEach((e=>n.add(e.id()))),this._hitTestSources(l,[r.crossHairSource()],d,c,!1,n),this._hitTestSources(l,a.customSources(Be.CustomSourceLayer.Topmost),d,c,!0,n),this._hitTestSources(l,h.tradingSources(),d,c,!1,n),this._hitTestSources(l,a.customSources(Be.CustomSourceLayer.Foreground),d,c,!0,n);const p=h.hitTestSources();if(this._hitTestSources(l,p,d,c,!1,n),this.containsMainSeries()){const e=r.activeStrategySource().value();if(null!==e&&!n.has(e.id())){const t=e.strategyOrdersPaneView();if(null!==t){const i=t.renderer(l);if(null!==i){const t=i.hitTest(d,l);t&&wi(o,t,e,i,!1)}}}}return null===o.result&&this._hitTestSources(l,a.customSources(Be.CustomSourceLayer.Background),d,c,!0,n),o.result}_sourceWasSelected(e){return!!e&&this._selectionBeforeMouseDown.has(e.source)}_hitTestSources(e,t,i,s,o,n){const a=(0,r.ensureNotNull)(this._state);for(let r=t.length-1;r>=0;--r){const l=t[r];if(n.has(l.id()))continue;const c=l.paneViews(a);if(null!==c&&0!==c.length)for(let t=c.length-1;t>=0;--t){const r=c[t].renderer(e);if(r&&r.hitTest){const t=r.hitTest(i,e);null!==t&&s(t,l,r,o)}}}}_tryStartMovingLineTool(e,t,i,s){var o;if(null===t.source||!t.source.movable()||null!==this._startTrackPoint)return!1;if(!this._preventSourceChange){const n=this._chartUndoModel(),a=(0,r.ensureNotNull)((0,r.ensureNotNull)(this._state).mainDataSource()).firstValue(),l=(0,r.ensureNotNull)(t.source.priceScale()).coordinateToPrice(e.localY,(0,r.ensureNotNull)(a));let c=(t.source.isSelectionEnabled()?n.selection().allSources():[t.source]).filter(si);const d=c.filter(K.isLineTool);c=d.length>0?d:c.includes(t.source)?[t.source]:[c[0]];const h=new ke.Point(e.localX,e.localY),u={index:s,price:l},_=null===(o=t.hittest.data())||void 0===o?void 0:o.activeItem;return this._startMoveSourceParams={source:c,startPoint:{logical:u,screen:h}, activeItem:void 0===_?null:_,envState:i},!0}return this._startMoveSourceParams=null,!1}_chartModel(){return this._chart.model().model()}_chartUndoModel(){return this._chart.model()}_externalPaneXCoord(e,t){t+=this._div.getBoundingClientRect().left+document.body.scrollLeft;const i=(0,r.ensureNotNull)(this._chart.paneByState(e)),s=i._div.getBoundingClientRect().left+document.body.scrollLeft;return i._correctXCoord(t-s)}_externalPaneYCoord(e,t){t+=this._div.getBoundingClientRect().top+document.body.scrollTop;const i=(0,r.ensureNotNull)(this._chart.paneByState(e)),s=i._div.getBoundingClientRect().top+document.body.scrollTop;return i._correctYCoord(t-s)}_correctXCoord(e){return Math.max(0,Math.min(e,this._size.width-1))}_correctYCoord(e){return Math.max(0,Math.min(e,this._size.height-1))}_processScroll(e){if(!this._chart.model().model().scrollEnabled())return;const t=performance.now();this._startScrollingPos||this._preventScroll()||(this._startScrollingPos={x:e.clientX,y:e.clientY,timestamp:t,localX:e.localX,localY:e.localY});const i=this._chartUndoModel();let s=this.state().defaultPriceScale();if(this._startScrollingPos&&!this._isScrolling&&(this._startScrollingPos.x!==e.clientX||this._startScrollingPos.y!==e.clientY))return i.beginUndoMacro(_i),null===this._scrollXAnimation&&this._options.useKineticScroll&&(this._scrollXAnimation=new Ot.KineticAnimation(.2,7,.997,15),this._scrollXAnimation.addPosition(e.clientX,this._startScrollingPos.timestamp)),i.selection().isEmpty()||(s=i.selection().allSources()[0].priceScale()),null===s||s.isEmpty()||(this._scrollPriceScale=s,i.startScrollPrice(this.state(),s,e.localY)),i.startScrollTime(e.localX),this._isScrolling=!0,this.setCursorForTool(),void this._paneWidgetsSharedState.setScrollingPane(this);this._isScrolling&&(null!==this._scrollPriceScale&&i.scrollPriceTo(this.state(),this._scrollPriceScale,e.localY),i.scrollTimeTo(e.localX),null!==this._scrollXAnimation&&this._scrollXAnimation.addPosition(e.clientX,t))}_finishScroll(){const e=this._chartUndoModel();e.endScrollTime(),null!==this._scrollPriceScale&&e.endScrollPrice(this.state(),this._scrollPriceScale),e.endUndoMacro(),this._isScrolling=!1,this._startScrollingPos=null,this._scrollPriceScale=null,this.setCursorForTool(),this._paneWidgetsSharedState.setScrollingPane(null)}_endScroll(e){if(!this._isScrolling)return!1;this._finishScroll();const t=this._scrollUndoCommandInStack(),i=performance.now();return null!==this._scrollXAnimation&&(this._scrollXAnimation.start(e.clientX,i),this._scrollXAnimation.finished(i)||(this._chartModel().stopTimeScaleAnimation(),this._chartModel().setTimeScaleAnimation(this._scrollXAnimation),this._scrollXAnimation=null)),t}_preventScroll(){return this._trackCrosshairOnlyAfterLongTap&&this._longTap||this._contextMenuOpenedOnLastTap||(0,Qt.isLineToolName)(Oe.tool.value())||Boolean(this._chartUndoModel().lineBeingCreated())||null!==this._startTrackPoint||this._preventScrollUntilNextMouseDownOrTouchStart}_isSelectPointModeEnabled(){ return this._chartUndoModel().crossHairSource().selectPointMode().value()!==Oe.SelectPointMode.None}_preventCrossHairMove(){return!!this._trackCrosshairOnlyAfterLongTap&&(null===this._chart.trackingModePaneWidget()&&(!!this._contextMenuOpenedOnLastTap||!this._crossHairShouldBeVisible()&&null===this._startTrackPoint))}_finishTool(e,t=null){const i=this._chartUndoModel(),s=e.toolname;if(s===Oe.tool.value()&&(0,Oe.resetToCursor)(),this._preventCrossHairMove()&&this._clearCursorPosition(),i.selectionMacro((i=>{i.addSourceToSelection(e,Ci(t,e))})),(0,K.isEditableTextLineTool)(e)&&e.activateEditingOnCreation())e.activateTextEditingOn(this._div,!0);else if((0,Qt.isTextToolName)(s)){const t=i.createUndoCheckpoint();this._chart.showChartPropertiesForSource(e,U.TabNames.text,void 0,t)}this._lastFinishedToolId=e.id(),(0,l.emit)("drawing_event",e.id(),"create"),Xt(e)}_alignSourcesThatBeingMoved(e,t,i,s){const o=this._chartUndoModel(),r=o.timeScale().coordinateToIndex(t);o.model().sourcesBeingMoved().forEach((e=>{var n;let a=r,l=e.convertYCoordinateToPriceForMoving(i,this.state().mainDataSource());if(null!==l){if((0,q.isStudy)(e)){const e=o.mainSeries(),t=e.bars().firstIndex(),i=e.bars().lastIndex();null!==t&&null!==i&&(a=Math.min(Math.max(r,t),i)),l=this._chartModel().magnet().align(l,r,this.state())}null!==this._currentMovingHitTest&&void 0!==(null===(n=this._currentMovingHitTest.sourceAtPoint.hittest.data())||void 0===n?void 0:n.cursorType)||this.setCursorForTool(),o.moveSources({screen:new ke.Point(t,i),logical:{index:a,price:l}},s)}}))}_resetMeasureIfRequired(){this._needResetMeasureLater&&((0,Oe.resetToCursor)(),this._needResetMeasureLater=!1)}_makeSureIsUpdated(e){var t;const i=this.state(),s=[...i.dataSources(),...i.customSources()];for(const o of s){const s=o.paneViews(i);if(null!==s)for(const i of s)null===(t=i.makeSureIsUpdated)||void 0===t||t.call(i,e)}}_drawBackground(e,t){const i=this._chartModel(),s=i.backgroundTopColor().value(),o=i.backgroundColor().value();s===o?(0,V.clearRect)(e,0,0,t.bitmapSize.width,t.bitmapSize.height,o):(0,We.clearRectWithGradient)(e,0,0,t.bitmapSize.width,t.bitmapSize.height,s,o)}_drawWatermark(e,t){const i=this._chartModel().watermarkSource();if(null===i)return;if(!this.state().containsMainSeries())return;const s=i.paneViews();for(const i of s){e.save();const s=i.renderer(t);s&&s.draw(e,t),e.restore()}}_drawCrossHair(e,t){const i=this._chartUndoModel().crossHairSource();i.invalidateLockPosition(),i.visible||null===Oe.crosshairLock.value()||i.updateAllViews((0,ni.sourceChangeEvent)(i.id())),this._drawSourceImpl(e,t,vi,Si,i)}_drawActiveLineTools(e,t){const i=this._chartModel(),s=[i.lineBeingCreated(),i.lineBeingEdited(),...i.sourcesBeingMoved(),i.customSourceBeingMoved()].filter((e=>!!e));for(const o of s){(i.paneForSource(o)===this.state()||(0,Re.isDataSource)(o)&&o.isMultiPaneEnabled())&&this._drawSourceImpl(e,t,vi,Si,o)}}_drawTopViews(e,t){for(const i of this.state().sourcesByGroup().all())i.topPaneViews&&this._drawSourceImpl(e,t,fi,Si,i)}_drawSources(e,t){ const i=this.state(),s=i.model(),o=i.sourcesByGroup(),r=o.tradingSources(),n=o.generalSources(),a=o.phantomSources(),l=i.customSources(Be.CustomSourceLayer.Background).slice(),c=i.customSources(Be.CustomSourceLayer.Foreground).slice(),d=i.customSources(Be.CustomSourceLayer.Topmost).slice(),h=s.activeStrategySource().value(),u=s.replayStudyStrategy().value();this._drawSourceImpl(e,t,vi,Si,s.gridSource()),this._drawWatermark(e,t);for(const i of l)this._drawSourceImpl(e,t,vi,gi,i);for(const i of n)this._drawSourceImpl(e,t,vi,gi,i);for(const i of c)this._drawSourceImpl(e,t,vi,gi,i);for(const i of a)this._drawSourceImpl(e,t,vi,gi,i);const _=new Set;[s.lineBeingCreated(),s.lineBeingEdited(),...s.sourcesBeingMoved(),s.customSourceBeingMoved()].filter(w.notNull).forEach((e=>_.add(e.id())));let p=s.hoveredSource();null!==p&&((0,Re.isDataSource)(p)&&!p.showOnTopOnHovering()||_.has(p.id())||(0,Re.isDataSource)(p)&&!n.includes(p)?p=null:_.add(p.id()));const m=s.selection().allSources().filter((e=>!((0,Re.isDataSource)(e)&&!n.includes(e))&&!_.has(e.id())));m.forEach((e=>_.add(e.id())));for(const i of l)this._drawSourceImpl(e,t,vi,Si,i,_);for(const i of n)this._drawSourceImpl(e,t,vi,Si,i,_);for(const i of c)this._drawSourceImpl(e,t,vi,Si,i,_);h&&this.containsMainSeries()&&this._drawSourceImpl(e,t,yi,Si,h,_),u&&this._drawSourceImpl(e,t,yi,Si,u,_);for(const i of r)this._drawSourceImpl(e,t,vi,gi,i);for(const i of d)this._drawSourceImpl(e,t,vi,gi,i);for(const i of n)this._drawSourceImpl(e,t,bi,Si,i,_);for(const i of c)this._drawSourceImpl(e,t,bi,Si,i,_);for(const i of r)this._drawSourceImpl(e,t,vi,Si,i,_);for(const i of d)this._drawSourceImpl(e,t,vi,Si,i,_);for(const i of m)this._drawSourceImpl(e,t,vi,Si,i),i===h&&this.containsMainSeries()&&this._drawSourceImpl(e,t,yi,Si,h);for(const i of m)this._drawSourceImpl(e,t,bi,Si,i);p&&(this._drawSourceImpl(e,t,vi,Si,p),p===h&&this.containsMainSeries()&&this._drawSourceImpl(e,t,yi,Si,h),this._drawSourceImpl(e,t,bi,Si,p));for(const i of a)this._drawSourceImpl(e,t,vi,Si,i,_)}_drawSourceImpl(e,t,i,s,o,r){if(r&&r.has(o.id()))return;const n=i(o,this.state());if(n)for(const i of n){const o=i.renderer(t);o&&(e.save(),s(o,e,t),e.restore())}}_updateByThemedColors(){null!==this._legendWidget&&this._legendWidget.updateThemedColors(this._themedTopColor),null!==this._paneControls&&this._paneControls.updateThemedColors(this._themedTopColor)}_scrollUndoCommandInStack(){const e=this._chartUndoModel().undoHistory().undoStack();if(e.isEmpty())return!1;const t=e.head();if(!(t instanceof Ve.UndoMacroCommand))return!1;if(t.isEmpty())return!1;const i=t.commands()[0];return i instanceof Ut||i instanceof Ft}_onStateDestroyed(){this.setState(null)}_onDataSourcesCollectionChanged(){this._startMoveSourceParams=null}_processMouseEnterLeaveMoveHandlers(e,t){var i,s,o,r;if(null!==this._prevHoveredHittest&&(this._prevHoveredHittest.renderer!==(null==e?void 0:e.renderer)||(null===(i=this._prevHoveredHittest.hittest.data())||void 0===i?void 0:i.activeItem)!==(null===(s=e.hittest.data())||void 0===s?void 0:s.activeItem))){ const e=this._sourceWasSelected(this._prevHoveredHittest);(0,De.tryCallHandler)(t,{sourceWasSelected:e},null===(o=this._prevHoveredHittest.hittest.data())||void 0===o?void 0:o.mouseLeaveHandler),this._prevHoveredHittest=null}if(!t.isTouch&&null!==e){const i=this._sourceWasSelected(e);(null===(r=this._prevHoveredHittest)||void 0===r?void 0:r.renderer)!==e.renderer&&(e.hittest.tryCallMouseEnterHandler(t,{sourceWasSelected:i}),this._prevHoveredHittest=e),e.hittest.tryCallMouseMoveHandler(t,{sourceWasSelected:i})}}_startChangeOrMoveLineToolIfNeeded(){if(null!==this._startChangeLineToolParams){const e=this._startChangeLineToolParams;this._chartUndoModel().startChangingLinetool(e.source,e.startPoint,e.pointIndex,e.envState)}if(null!==this._startMoveSourceParams){const e=this._startMoveSourceParams;this._chartUndoModel().startMovingSources(e.source,e.startPoint,e.activeItem,e.envState)}this._startMoveSourceParams=null,this._startChangeLineToolParams=null}_trackingModeShouldBeActive(){return!(!this._trackCrosshairOnlyAfterLongTap||this._contextMenuOpenedOnLastTap||this._crossHairShouldBeVisible())&&this._longTap}_processOutsideClick(e,t){var i;let s=null;const o=this._chartModel();if(null!==e&&(s=e.isCustom?o.customSourceName(e.source):e.source.id()),null!==this._lastClickedSource&&this._lastClickedSource.id!==s){const e=this._lastClickedSource.id;let i=this._lastClickedSource.isCustom?o.customSourceForName(e):o.dataSourceForId(e);null!==i||this._lastClickedSource.isCustom||(i=o.dataSourceForId(e)),null!==i&&i.onClickOutside&&(i.onClickOutside((0,V.getBindingRenderingInfo)(this._canvasBinding),t),this._chartModel().updateSource(i))}this._lastClickedSource=null!==s?{id:s,isCustom:null!==(i=null==e?void 0:e.isCustom)&&void 0!==i&&i}:null}_mouseClickOrTapEvent(e){var t;if(!this.hasState())return;Kt.performanceTestMode&&"performance"===Oe.tool.value()&&ui&&ui.confetti(e.pageX,e.pageY);const i=this._dataSourceAtPoint(e.localX,e.localY),s=i&&i.source,o=this._chartUndoModel(),n=Boolean(null===(t=null==i?void 0:i.hittest.data())||void 0===t?void 0:t.hideCrosshairLinesOnHover);this._processOutsideClick(i,e),!this._isSelectPointModeEnabled()||n||e.isTouch&&this.trackingModeEnabled()&&!this._exitTrackingModeOnNextTry||o.crossHairSource().trySelectCurrentPoint();const a=this._sourceWasSelected(i);null!==i&&i.hittest.tryCallClickOrTapHandler(e,{sourceWasSelected:a})&&o.model().updateSource((0,r.ensureNotNull)(s)),!e.isTouch||this._isSelectPointModeEnabled()||i&&i.source===o.crossHairSource()||this._tryExitTrackingMode(),s&&(0,K.isLineTool)(s)&&this._lastFinishedToolId!==s.id()&&(0,l.emit)("drawing_event",s.id(),"click"),this._resetMeasureIfRequired()}_mouseDownOrTouchStartEvent(e,t){var i,s,o,n,a,c,d;this._pressedMoveStage=1,this._preventScrollUntilNextMouseDownOrTouchStart=!1,this._selectionBeforeMouseDown=new Set(this._chartModel().selection().allSources()),e.isTouch&&(this._longTap=!1,this._exitTrackingModeOnNextTry=null!==this._startTrackPoint,this._paneWidgetsSharedState.clearDraggingSource()),this._contextMenuOpenedOnLastTap=!1, this._lastFinishedToolId=null;const h=this._chartModel();if(h.stopTimeScaleAnimation(),e.isTouch&&this._switchTrackingModeFromAnotherPaneIfNeeded(e),document.activeElement!==document.body&&document.activeElement!==document.documentElement)document.activeElement&&document.activeElement.blur?document.activeElement.blur():document.body.focus();else{const e=document.getSelection();null!==e&&e.removeAllRanges()}(0,l.emit)("mouse_down",{clientX:e.clientX,clientY:e.clientY,pageX:e.pageX,pageY:e.pageY,screenX:e.screenX,screenY:e.screenY}),this._updateCommonTooltip(null);const u=this._chartUndoModel(),_=new Ne.EnvironmentState(e);u.mainSeries().clearGotoDateResult();const p=this.state().defaultPriceScale();if(u.timeScale().isEmpty())return;const m=u.crossHairSource();if(!e.isTouch&&!(0,Qt.isLineDrawnWithPressedButton)(Oe.tool.value())){const t=u.lineBeingCreated(),i=null!==t?u.model().paneForSource(t):null;null!==i&&i!==this._state?this._setCursorPositionOnExternalPane(i,e.localX,e.localY,_):this.setCursorPosition(e.localX,e.localY,_)}e.isTouch&&(0,Qt.isLineToolName)(Oe.tool.value())&&((0,Qt.isLineDrawnWithPressedButton)(Oe.tool.value())||null!==m.pane?(0,Qt.isLineDrawnWithPressedButton)(Oe.tool.value())&&this._clearCursorPosition():this._chart.updateCrossHairPositionIfNeeded());const g=(0,r.ensureNotNull)(this.state().mainDataSource()).firstValue();if(null===g||p.isEmpty())return void(this._chart.readOnly()||(this._handleSelectionMouseDownAndGetJustDeselectedSource(e,t,_),null!==t&&(0,qt.isPriceDataSource)(t.source)&&t.source.isDraggable()&&this._paneWidgetsSharedState.trySetDraggingSource(t.source,this)));let S=p.coordinateToPrice(e.localY,g),v=h.timeScale().coordinateToIndex(e.localX);if(m.startMeasurePoint()&&m.endMeasurePoint()&&m.clearMeasure(),_.shift()&&(null===t||!(null===(s=null===(i=t.hittest.data())||void 0===i?void 0:i.hasOwnShortcutsBehaviourFor)||void 0===s?void 0:s.shiftKey))&&(0,Oe.toolIsCursor)(Oe.tool.value())&&u.selection().isEmpty()&&Oe.tool.setValue("measure"),(e.isTouch&&!e.stylus||!this._tryStartMeasure(e,m,_,S,v))&&(e.isTouch&&!e.stylus||!this._tryFinishMeasure(e,m))&&!this._tryFinishZoom(e)&&!this._tryStartZoom(e,S,v,_)){if(e.isTouch&&(null!==this._startTrackPoint?(this._initCrossHairPosition=m.currentPoint(),this._startTrackPoint=new ke.Point(e.localX,e.localY)):this._isSelectPointModeEnabled()&&null===this._chart.trackingModePaneWidget()&&this.startTrackingMode(new ke.Point(e.localX,e.localY),new ke.Point(e.localX,e.localY),new Ne.EnvironmentState(e))),e.isTouch&&(this._preventSourceChange=null===t||!u.selection().isSelected(t.source)),!this._isSelectPointModeEnabled()&&!this._isScrolling){if(e.isTouch&&!e.stylus&&((0,Oe.toolIsMeasure)(Oe.tool.value())||null!==m.measurePane().value()))return void this._initToolCreationModeParams(e);if((0,Qt.isLineToolName)(Oe.tool.value())||u.lineBeingCreated())return _.shift()||u.selectionMacro((e=>e.clearSelection())),void this._mouseDownEventForLineTool(e,_,v,S)}if(null!==t){const i=this._sourceWasSelected(t);t.hittest.tryCallMouseDownOrTouchStartHandler(e,{ sourceWasSelected:i})}if(!this._chart.readOnly()){const i=this._handleSelectionMouseDownAndGetJustDeselectedSource(e,t,_);if(null!==t&&!this._preventSourceChange){const i=t.hittest.data();if(t.isCustom){if(t.hittest.hasPressedMoveHandler(e))return u.model().setMovingCustomSource(t.source,i),this._preventScrollUntilNextMouseDownOrTouchStart=!0,this._currentMovingHitTest={sourceAtPoint:t,cancelledContainer:null!==(o=u.model().customSourceMovingHitTestData())&&void 0!==o?o:void 0},void u.selectionMacro((e=>{e.clearSelection(),e.addSourceToSelection((0,r.ensureNotNull)(t.source),(0,r.ensureNotNull)(i))}))}else if((null==i?void 0:i.areaName)===De.AreaName.SourceItemMove){const s=null==i?void 0:i.activeItem;if(void 0!==s)return u.startCustomMoving(t.source,s,e),this._currentMovingHitTest={sourceAtPoint:t},void u.selectionMacro((e=>{e.clearSelection(),e.addSourceToSelection((0,r.ensureNotNull)(t.source),(0,r.ensureNotNull)(i))}))}}if(null!==t&&this._tryHandleEraserMouseDown(t,_))return;const s=null!==t&&(0,K.isLineTool)(t.source)&&t.source.isLocked&&t.source.isLocked();if(!((0,Oe.lockDrawings)().value()||s)&&null!==t&&!t.isCustom){if(!t.source.userEditEnabled())return;const s=null===(n=t.hittest.data())||void 0===n?void 0:n.snappingPrice,o=null===(a=t.hittest.data())||void 0===a?void 0:a.snappingIndex;let l=e.localY,d=e.localX;if(void 0!==s&&(l=(0,r.ensure)(null===(c=t.source)||void 0===c?void 0:c.priceScale()).priceToCoordinate(s,g),S=s),void 0!==o&&(d=h.timeScale().indexToCoordinate(o),v=o),l===e.localY&&d===e.localX||(e={...e,localY:l,localX:d},this.setCursorPosition(e.localX,e.localY,_)),this._tryStartChangingLineTool(e,t,_,v))return void(this._currentChangingLineToolHitTest=t);if(this._currentChangingLineToolHitTest=null,(f=t.hittest.target())===De.HitTarget.MovePoint||f===De.HitTarget.MovePointBackground&&(0,me.lastMouseOrTouchEventInfo)().isTouch){if(this._tryStartCloning(e,t,_,i))return;if(this._tryStartMovingLineTool(e,t,_,v))return void(this._currentMovingHitTest={sourceAtPoint:t});this._currentMovingHitTest=null}}if(null!==t&&(0,qt.isPriceDataSource)(t.source)&&t.source.isDraggable()&&(null===(d=this._state)||void 0===d?void 0:d.hasDataSource(t.source))&&this._paneWidgetsSharedState.trySetDraggingSource(t.source,this))return}var f;null!==t&&t.hittest.target()===De.HitTarget.Regular||(this._processing=!0)}}_mouseUpOrTouchEndEvent(e){var t,i;if(!this.hasState())return;this._pressedMoveStage=0;const s=e.isTouch&&null!==this._startTrackPoint,o=e.isTouch&&this._wasPinched;e.isTouch&&(this._wasPinched=!1,this._longTap=!1),this._startMoveSourceParams=null,this._startChangeLineToolParams=null,this._currentChangingLineToolHitTest=null,this._currentMovingHitTest=null;const n=this._chartUndoModel(),a=n.model().customSourceMovingHitTestData();null!==a||n.customMoveBeingProcessed()||this._processMouseUpOrTouchEndHandler(e),this._isSelecting=!1;const c=n.model(),d=c.crossHairSource(),h=this._dataSourceAtPoint(e.localX,e.localY);if(d.selection()&&null===this._firstZoomPoint){ const e=this.state().lineToolsForArea(d.selection(),(0,V.getBindingRenderingInfo)(this._canvasBinding));n.selectionMacro((t=>{let i=null;e.forEach((e=>{null===i&&(i=Ci(h,e)),t.addSourceToSelection(e,i)}))})),d.clearSelection(),(0,u.trackEvent)("GUI","Multiselect","Area Select")}(0,l.emit)("mouse_up",{clientX:e.clientX,clientY:e.clientY,pageX:e.pageX,pageY:e.pageY,screenX:e.screenX,screenY:e.screenY});const _=e.isTouch&&this._touchMove;e.isTouch&&(this._touchMove=!1);const p=new Ne.EnvironmentState(e),m=Oe.tool.value();if(e.isTouch&&((0,Oe.toolIsMeasure)(m)||null!==d.measurePane().value())){if(!_&&!e.stylus&&null===d.measurePane().value()&&d.pane!==this._state)return void this.setCursorPosition(e.localX,e.localY);if(!_&&!e.stylus&&this._tryStartMeasure(e,d,p,d.price,d.index))return;if((!_||e.stylus)&&this._tryFinishMeasure(e,d))return}if(e.isTouch&&!_&&!(0,Qt.isLineDrawnWithPressedButton)(m)&&(0,Qt.isLineToolName)(m)&&!n.lineBeingCreated()){if(this._chart.justActivated())return;if(d.pane!==this._state)return void this.setCursorPosition(e.localX,e.localY,p);const i=d.currentPoint(),s=this.state().defaultPriceScale(),o=(0,r.ensure)(null===(t=this.state().mainDataSource())||void 0===t?void 0:t.firstValue()),a={index:Math.round(n.timeScale().coordinateToIndex(i.x)),price:s.coordinateToPrice(i.y,o)},l=(0,r.ensureNotNull)(n.createLineTool({pane:this.state(),point:a,linetool:m}));return n.selectionMacro((e=>{e.addSourceToSelection(l)})),n.lineBeingCreated()||(this._finishTool(l,h),e.preventDefault()),void(this._startTouchPoint=null)}const g=n.lineBeingCreated();if(g&&!(0,Qt.isLineDrawnWithPressedButton)(g.toolname)&&e.isTouch&&(this._startTouchPoint||e.stylus)){if(this._startTouchPoint=null,!_||e.stylus){const t=g.points()[g.points().length-1],i=n.continueCreatingLine({index:t.index,price:t.price},new Ne.EnvironmentState(e));this._initCrossHairPosition=null,i&&(this._finishTool(g,h),e.preventDefault())}return}if(null!==this._firstZoomPoint&&this._firstZoomPoint.draggingMode)return void this._finishZoom(e);if(this._processing=!1,n.customMoveBeingProcessed())return void n.endCustomMoving();if(null!==a){if(a.beingMoved&&!a.cancelled){const t=this._sourceWasSelected(h);(0,De.tryCallHandler)(e,{sourceWasSelected:t},a.mouseUpHandler,a.touchEndHandler),this.setCursorForTool()}if(c.setMovingCustomSource(null,null),Ii(e,a))return}if(c.lineBeingEdited())return n.endChangingLinetool(!1),void(this._preventCrossHairMove()&&this._clearCursorPosition());if((0,Qt.isLineDrawnWithPressedButton)(m)&&!this._isSelectPointModeEnabled()){const t=n.lineBeingCreated();null!==t&&(Xt(t),t.finish(),"LineToolBrush"===t.toolname&&(0,l.emit)("drawing_event",t.id(),"create"));const s=this.state().defaultPriceScale();if(s.isEmpty())return;if(!t)return;const o=(0,r.ensure)(null===(i=t.ownerSource())||void 0===i?void 0:i.firstValue()),a=s.coordinateToPrice(e.localY,o),c={index:Math.round(n.timeScale().coordinateToIndex(e.localX)),price:a};return void n.continueCreatingLine(c)}if(c.sourcesBeingMoved().length)return n.endMovingSource(!1,!1), c.sourcesBeingMoved().filter(K.isLineTool).forEach((e=>{this.setCursorForTool(e)})),void c.invalidate(pe.InvalidationMask.cursor());if(!this._chart.readOnly()){const t=e.localX>=0&&e.localXDe.HitTarget.MovePointBackground||(0,me.lastMouseOrTouchEventInfo)().isTouch)&&n.selectionMacro((e=>{e.clearSelection();const t=(0,r.ensureNotNull)(h.source);e.addSourceToSelection(t,Ci(h,t))})),e.isTouch&&(this._touchMove=!1)}_mouseOrTouchMoveEvent(e){if(!this.hasState())return;this._resetMeasureIfRequired();const t=this._dataSourceAtPoint(e.localX,e.localY);this._processMouseEnterLeaveMoveHandlers(t,e);const i=this._chartUndoModel();if(!i)return;const s=e.localX,o=e.localY;this._prevMoveEventPosition=new ke.Point(s,o);const r=new Ne.EnvironmentState(e);if(null===this._firstZoomPoint){if(this._updateHoveredSource(t,r,e),!e.isTouch&&i.lineBeingCreated()){const e=i.lineBeingCreated(),t=null===e?null:i.model().paneForSource(e);if(null!==t&&t!==this._state)return void this._setCursorPositionOnExternalPane(t,s,o,r)}e.isTouch||this.setCursorPosition(s,o,r)}else this._processMouseMoveWhileZoom(e,r)}_pressedMouseOrTouchMoveEvent(e){var t;if(!this.hasState()||this._pinching||e.isTouch&&this._contextMenuOpenedOnLastTap)return;this._pressedMoveStage=2,this._resetMeasureIfRequired(),this._startChangeOrMoveLineToolIfNeeded(),e.isTouch&&(this._touchMove=!0,this._preventSourceChange=!1);const i=new Ne.EnvironmentState(e),s=this._chartUndoModel(),o=s.crossHairSource(),n=e.localX,a=e.localY;if(this._prevMoveEventPosition=new ke.Point(n,a),null!==this._firstZoomPoint)return this._processMouseMoveWhileZoom(e),void(this._firstZoomPoint.draggingMode=!0);const l=Oe.tool.value();if(e.isTouch&&this._startTouchPoint&&(0,Qt.isLineToolName)(l)&&!(0,Qt.isLineDrawnWithPressedButton)(l)&&!s.lineBeingCreated()&&!this._isSelectPointModeEnabled())return void this._updateCrosshairPositionInToolCreationMode(e,this.state()) ;const c=o.measurePane().value();if(e.isTouch&&(this._startTouchPoint||e.stylus)&&((0,Oe.toolIsMeasure)(l)||null!==c))return void(e.stylus?this.setCursorPosition(e.localX,e.localY,new Ne.EnvironmentState(e)):this._updateCrosshairPositionInToolCreationMode(e,c||this.state()));const d=s.lineBeingCreated();if(e.isTouch&&!e.stylus&&d&&!(0,Qt.isLineDrawnWithPressedButton)(d.toolname)){if(this._startTouchPoint){const t=(0,r.ensureNotNull)(s.lineBeingCreated()),i=(0,r.ensureNotNull)(s.model().paneForSource(t));this._updateCrosshairPositionInToolCreationMode(e,i)}return}if(e.isTouch&&null!==this._startTrackPoint){this._exitTrackingModeOnNextTry=!1;const e=(0,r.ensureNotNull)(this._initCrossHairPosition),t=new ke.Point(n,a).subtract(this._startTrackPoint),s=e.add(t);this.setCursorPosition(s.x,s.y,i)}else e.isTouch&&this._preventCrossHairMove()||this.setCursorPosition(n,a,i);const h=this._isSelectPointModeEnabled();if((0,Qt.isLineToolName)(l)&&!(0,Qt.isLineDrawnWithPressedButton)(l)&&!h&&!i.mod())return;if((0,Qt.isLineDrawnWithPressedButton)(l)&&!h){const i=this.state().defaultPriceScale();if(i.isEmpty())return;const o=s.lineBeingCreated();if(!o)return;const n=new ke.Point(e.localX,e.localY),a=(0,r.ensure)(null===(t=o.ownerSource())||void 0===t?void 0:t.firstValue());return n.price=i.coordinateToPrice(e.localY,a),n.index=Math.round(s.timeScale().coordinateToIndex(e.localX)),void s.continueCreatingLine(n)}if(null!==this._paneWidgetsSharedState.draggingSource()){const t=e.target,i=this._chart.paneByCanvas(t);i&&(i!==this?i.setDragToAnotherPaneCursor():i.setCursorForTool());const s=this._chart.timeAxisByCanvas(t);s&&s.setCursor("grabbing")}if(s.timeScale().isEmpty())return;const u=this._options.handleScroll;if((!u.pressedMouseMove||e.isTouch)&&(!u.horzTouchDrag&&!u.vertTouchDrag||!e.isTouch))return;if(s.customMoveBeingProcessed())return void s.processCustomMove(e);const _=s.model().customSourceMovingHitTestData();if(null!==_&&(this._updateCommonTooltip(null,!0),_.cancelled||(s.model().processingCustomSourceMove(),(0,De.tryCallHandler)(e,{sourceWasSelected:this._selectionBeforeMouseDown.has(s.model().customSourceBeingMoved())},_.pressedMouseMoveHandler,_.touchMoveHandler)),Ii(e,_)))return;if(s.model().lineBeingEdited())return void this.setCursorPosition(n,a,i);if(s.model().sourcesBeingMoved().length)return void this._alignSourcesThatBeingMoved(s.model().sourcesBeingMoved(),e.localX,e.localY,i);const p=this._dataSourceAtPoint(e.localX,e.localY);if(this._tryFinishClonning(e,new Ne.EnvironmentState(e),p))return;const m=(0,Oe.toolIsMeasure)(l)||o.startMeasurePoint()&&o.endMeasurePoint();this._chart.readOnly()||!i.mod()||(0,Qt.isLineToolName)(l)||m||h?(this._processScroll(e),this._preventScroll()&&!this._preventCrossHairMove()&&null===this._startTrackPoint&&this.setCursorPosition(e.localX,e.localY,new Ne.EnvironmentState(e))):this._isSelecting||(o.startSelection(this.state()),this._isSelecting=!0)}_mouseOrTouchLeaveEvent(e){var t;if(!this.hasState())return;const i=this._chartUndoModel();if(!i)return;const s=i.crossHairSource() ;e.isTouch||null!==s.measurePane().value()&&null===s.endMeasurePoint()||this._clearCursorPosition();if(this._chartModel().setHoveredSource(null,null),null!==this._prevHoveredHittest){const i=this._sourceWasSelected(this._prevHoveredHittest);(0,De.tryCallHandler)(e,{sourceWasSelected:i},null===(t=this._prevHoveredHittest.hittest.data())||void 0===t?void 0:t.mouseLeaveHandler),this._prevHoveredHittest=null}this._updateCommonTooltip(null),this._chart.unsetActivePaneWidget()}_mouseDoubleClickOrDoubleTapEvent(e){if(!this.hasState())return;const t=!this._chart.readOnly()&&!(0,Qt.isLineToolName)(Oe.tool.value())&&this._dataSourceAtPoint(e.localX,e.localY)||null,i=this._sourceWasSelected(t);if(null!==t&&t.isCustom)t.hittest.tryCallDblClickOrDblTapHandler(e,{sourceWasSelected:i});else if(null!==t&&(e.isTouch||t.hittest.target()>De.HitTarget.MovePointBackground))t.hittest.tryCallDblClickOrDblTapHandler(e,{sourceWasSelected:i})&&!(0,De.shouldDefaultActionBeExecuted)(e,(0,r.ensureNotNull)(t.hittest.data()),"doubleClickHandler","doubleTapHandler")||this.processDoubleClickOnSource(t.source,t.hittest?t.hittest:void 0);else if(!this._chart.readOnly()&&!(0,Qt.isLineToolName)(Oe.tool.value())&&!this._chartUndoModel().lineBeingCreated()&&this._chartUndoModel().selection().isEmpty()){const t=this.state();new Ne.EnvironmentState(e).mod()&&!t.maximized().value()?(t.collapsed().value()||this._chartModel().paneCollapsingAvailable().value())&&this._chartUndoModel().toggleCollapsedPane(this.state()):this._chart.toggleMaximizePane(this)}}_contextMenuEvent(e){const t=this._chartUndoModel();if(t.crossHairSource().startMeasurePoint()&&!this._trackCrosshairOnlyAfterLongTap)return t.crossHairSource().clearMeasure(),void(0,Oe.resetToCursor)(!0);if(this._pinching)return;if(null===this._firstZoomPoint||this._trackCrosshairOnlyAfterLongTap||this.cancelZoom(),!(0,Oe.toolIsCursor)(Oe.tool.value())||this._isSelectPointModeEnabled()){if(e.isTouch)return;return(0,Oe.resetToCursor)(!0),this.setCursorForTool(),void(t.lineBeingCreated()&&t.cancelCreatingLine())}if(!this._options.contextMenuEnabled)return;const i=this._dataSourceAtPoint(e.localX,e.localY),s=i?i.source:null;if(e.isTouch&&null!==this._startTrackPoint){if(this._preventSourceChange)return;this._clearCursorPosition()}e.isTouch&&(this._contextMenuOpenedOnLastTap=!0,this._startTrackPoint=null),this._contextMenuX=e.localX,this._contextMenuY=e.localY;const o=i&&i.hittest?i.hittest.target():0,r=o>=De.HitTarget.Regular||o>=De.HitTarget.MovePointBackground&&e.isTouch;if(this._chart.updateActions(),t.selectionMacro((t=>{null!==s&&r?t.selection().isSelected(s)||(t.clearSelection(),t.addSourceToSelection(s,Ci(i,s))):(this._options.contextMenu.general&&this._showContextMenu(e),t.clearSelection())})),null!==i&&r&&null!==s)if((0,Re.isDataSource)(s)&&s.hasContextMenu())s.isSelectionEnabled()?this.showContextMenuForSelection(e,void 0,i.hittest):this.showContextMenuForSources([s],e,void 0,void 0,i.hittest);else{const t=this._sourceWasSelected(i);i.hittest.tryCallContextMenuHandler(e,{sourceWasSelected:t})}} _onMouseEvent(){this._preventSourceChange=!1,this._startTrackPoint=null,this._trackCrosshairOnlyAfterLongTap=!1}_onTouchEvent(){this._trackCrosshairOnlyAfterLongTap=!0}_switchTrackingModeFromAnotherPaneIfNeeded(e){const t=this._chart.trackingModePaneWidget();if(null!==t&&t!==this){const i=this._chartModel().crossHairSource().currentPoint();t._exitTrackingModeOnNextTry=!0,t._tryExitTrackingMode(!0),this.startTrackingMode(new ke.Point(e.localX,e.localY),new ke.Point(i.x,e.localY),new Ne.EnvironmentState(e))}}async _showContextMenu(e){const t=e=>e instanceof ot.Separator,i=this._customActions(),s=(await this._initActions(e)).filter((e=>null!==e));i.remove.forEach((e=>{for(let t=0;t0;e--)t(o[e])&&t(o[e-1])&&o.splice(e,1);o.length&&t(o[0])&&o.splice(0,1),o.length&&t(o[o.length-1])&&o.splice(o.length-1,1),Ue.ContextMenuManager.showMenu(o,e,{statName:"ChartContextMenu"},{menuName:"ChartContextMenu"})}async _initActions(e){var t;const i=this._chart.actions(),s=[];if(this._chart.model().model().resetScalesAvailable().value()&&(s.push(i.chartReset),s.push(new ot.Separator)),!this.state().isEmpty()&&D.enabled("datasource_copypaste")){const t=(0,ct.createActionCopyPrice)(this.state(),e.localY),i=(0,ct.createPasteAction)(this._chart,this.state());(t||i)&&(t&&s.push(t),i&&s.push(i),s.push(new ot.Separator))}if(D.enabled("alerts")&&(s.length&&s.push(new ot.Separator),(0,r.ensureNotNull)(this.state().mainDataSource()).alertCreationAvailable().value())){const t=(await(0,Gt.getAlertsChartActionCreators)()).createAlert(this._chart,{localY:e.localY,pane:this.state()});null!==t&&s.push(t)}this._options.contextMenu.mainSeriesTrade&&this.containsMainSeries()&&s.push((0,ct.createActionTrade)(this._chart,this.state(),e)),s[s.length-1]instanceof ot.Separator||s.push(new ot.Separator);return Boolean(null===(t=window.widgetbar)||void 0===t?void 0:t.widget("watchlist"))&&i.addToWatchlist&&s.push(i.addToWatchlist),D.enabled("text_notes")&&s.push(i.addToTextNotes),s[s.length-1]instanceof ot.Separator||s.push(new ot.Separator),i.moveChartAction&&!i.moveChartAction.isDisabled()&&s.push(i.moveChartAction,new ot.Separator),s.push(this._createLockTimeAxisAction(e)),s.push(new ot.Separator),i.paneObjectTree&&s.push(i.paneObjectTree),!D.enabled("charting_library_base")&&i.applyColorTheme&&s.push(i.applyColorTheme),s[s.length-1]instanceof ot.Separator||s.push(new ot.Separator),this._chart.applyIndicatorsToAllChartsAvailable()&&(s.push(i.applyStudiesToAllCharts),s.push(new ot.Separator)),s.push(i.paneRemoveAllDrawingTools),s.push(i.paneRemoveAllStudies),s.push(new ot.Separator),D.enabled("show_chart_property_page")&&s.push(i.chartProperties),s[s.length-1]instanceof ot.Separator&&s.pop(),s}_loadAndCreateLegendWidget(){ Promise.all([i.e(36420),i.e(32662),i.e(5987),i.e(98996),i.e(43387),i.e(66458),i.e(5761),i.e(4343),i.e(44597),i.e(1413),i.e(4908),i.e(52078),i.e(89508),i.e(19216),i.e(37132),i.e(16005),i.e(16165),i.e(85131),i.e(94712),i.e(44794),i.e(39076),i.e(45338),i.e(80775),i.e(1337),i.e(14640),i.e(90385),i.e(59255),i.e(42942),i.e(62526),i.e(3889),i.e(92158),i.e(5093)]).then(i.bind(i,365422)).then((e=>{if(this._isDestroyed)return;const t=e.LegendWidget,i=(0,Ee.deepExtend)({},this._options.legendWidget);i.canShowSourceCode=!this._chart.onWidget()&&!c.CheckMobile.any(),i.readOnlyMode=i.readOnlyMode||this._chart.readOnly(),i.statusesWidgets={sourceStatusesEnabled:this._options.sourceStatusesWidgetEnabled,sourceStatuses:this._options.sourceStatusesWidget||{},marketStatusEnabled:this._options.marketStatusWidgetEnabled,dataUpdateModeEnabled:this._options.chartWarningWidgetEnabled,dataUpdateMode:this._options.chartWarningWidget||{},dataProblemEnabled:this._options.dataProblemWidgetEnabled,pineSourceStatusEnabled:this._options.pineSourceStatusEnabled};const s=(0,L.combine)(((e,t)=>Mi&&this._chart!==e&&!t),this._chart.chartWidgetCollection().activeChartWidget.weakReference(),this._chart.chartWidgetCollection().lock.crosshair.weakReference()),o=(0,L.combine)(((e,t)=>null!==e?e===this._state:(0,Oe.toolIsMeasure)(t)),this._chartModel().crossHairSource().measurePane().weakReference(),Oe.tool.weakReference());this._legendWidget=new t(this._chartUndoModel(),this,this._chart.backgroundTopTheme().spawnOwnership(),s.ownership(),this._visuallyCollapsed.spawnOwnership(),o.ownership(),i,{showContextMenuForSelection:this.showContextMenuForSelection.bind(this),showContextMenuForSources:this.showContextMenuForSources.bind(this),updateActions:this._chart.updateActions.bind(this._chart),showChartPropertiesForSource:this._chart.showChartPropertiesForSource.bind(this._chart),showGeneralChartProperties:this._chart.showGeneralChartProperties.bind(this._chart),showObjectsTreeDialog:this._chart.showObjectsTreeDialog.bind(this._chart),onLegendRowFocused:()=>{this._chart.chartWidgetCollection().activeChartWidget.setValue(this._chart)}}),this._div.appendChild(this._legendWidget.getElement()),this._legendWidget.updateLayout(),this._legendWidget.updateWidgetModeBySize(this._size),this._legendWidget.updateThemedColors(this._themedTopColor);for(const e of Array.from(this._customLegendWidgetsFactoryMap.keys()))this._legendWidget.addCustomWidgetToLegend(e,(0,r.ensureDefined)(this._customLegendWidgetsFactoryMap.get(e)))}))}_loadAndCreatePaneControlsWidget(){ Promise.all([Promise.all([i.e(36420),i.e(32662),i.e(5987),i.e(98996),i.e(43387),i.e(66458),i.e(5761),i.e(4343),i.e(44597),i.e(1413),i.e(4908),i.e(52078),i.e(89508),i.e(19216),i.e(37132),i.e(16005),i.e(16165),i.e(85131),i.e(94712),i.e(44794),i.e(39076),i.e(45338),i.e(80775),i.e(1337),i.e(14640),i.e(90385),i.e(59255),i.e(42942),i.e(62526),i.e(3889),i.e(92158),i.e(5093)]).then(i.bind(i,580723)),Promise.all([i.e(36420),i.e(32662),i.e(5987),i.e(98996),i.e(43387),i.e(66458),i.e(5761),i.e(4343),i.e(44597),i.e(1413),i.e(4908),i.e(52078),i.e(89508),i.e(19216),i.e(37132),i.e(16005),i.e(16165),i.e(85131),i.e(94712),i.e(44794),i.e(39076),i.e(45338),i.e(80775),i.e(1337),i.e(14640),i.e(90385),i.e(59255),i.e(42942),i.e(62526),i.e(3889),i.e(92158),i.e(5093)]).then(i.bind(i,159255))]).then((([e,t])=>{var i;if(this._isDestroyed)return;const s=e.PaneControlsWidget;this._paneControls=new s(this._chartUndoModel(),this,{backgroundThemeName:this._chart.backgroundTopTheme()},{toggleMaximizePane:this._chart.toggleMaximizePane.bind(this._chart)},this._div),this._paneControls.updateWidgetModeByWidth(this._size.width),this._paneControls.updateThemedColors(this._themedTopColor),this._paneControlsResizeObserver=new t.default(this._handleRestrictLegendWidth.bind(this)),this._paneControlsResizeObserver.observe(this._paneControls.getElement()),(null===(i=this._state)||void 0===i?void 0:i.collapsed().value())&&this._chartModel().fullUpdate()}))}_handleRestrictLegendWidth(e){if(null===this._legendWidget||null===this._paneControls)return;const t=e[e.length-1].contentRect.width,i=0===t?0:t+li+ci;this._legendWidget.addMargin(i)}_onMagnetStateChanged(){this._chart.isActive().value()&&(this._isSelectPointModeEnabled()||this._isToolActionActiveOnPane(!0))&&this._chartModel().crossHairSource().visible&&this._updateLineToolUsingMagnetOrShift()}_onShiftKeyStateChanged(){this._chart.isActive().value()&&this._isToolActionActiveOnPane(!1)&&this._chartModel().crossHairSource().visible&&this._updateLineToolUsingMagnetOrShift(Ne.EnvironmentState.create((0,W.shiftPressed)().value()))}_isToolActionActiveOnPane(e){const t=this._chartModel(),i=t.lineBeingCreated()||t.lineBeingEdited()||t.sourcesBeingMoved().length>0&&t.sourcesBeingMoved()[0];return i?t.paneForSource(i)===this._state:e&&(0,Qt.isLineToolName)(Oe.tool.value())&&t.crossHairSource().pane===this._state}_updateLineToolUsingMagnetOrShift(e){if(null===this._prevMoveEventPosition)return;const{x:t,y:i}=this._prevMoveEventPosition,s=this._chartModel().sourcesBeingMoved();s.length>0?(Oe.isStudyEditingNow.value()&&this.setCursorPosition(t,i,e),this._alignSourcesThatBeingMoved(s,t,i,e)):this.setCursorPosition(t,i,e)}_showEditDialogForSource(e,t){if(this._options.propertyPagesEnabled&&e.userEditEnabled())if(e===this._chartUndoModel().mainSeries())this._chart.showGeneralChartProperties(U.TabNames.symbol);else if((0,K.isLineTool)(e)||(0,q.isStudy)(e)||(0,Z.isLollipopDataSource)(e)){let i;const s=null==t?void 0:t.data();if(null!=s){const e=s.areaName;void 0!==e&&(i=Ti.get(e))} this._chart.showChartPropertiesForSource(e,i).then((e=>{this._editDialog=e}))}}_initToolCreationModeParams(e){this._startTouchPoint=new ke.Point(e.pageX,e.pageY),this._initCrossHairPosition=this._chartModel().crossHairSource().currentPoint()}_updateCrosshairPositionInToolCreationMode(e,t){if(t!==this._state){const i=this._chart.paneByState(t);return i._startTouchPoint=this._startTouchPoint,i._initCrossHairPosition=this._initCrossHairPosition,void i._updateCrosshairPositionInToolCreationMode(e,t)}const i=this._chartModel().crossHairSource();this._chart.justActivated()&&(this._initCrossHairPosition=i.currentPoint());const s=e.pageX,o=e.pageY,n=(0,r.ensureNotNull)(this._initCrossHairPosition),a=new ke.Point(s,o).subtract((0,r.ensureNotNull)(this._startTouchPoint)),l=n.add(a);this.setCursorPosition(l.x,l.y,new Ne.EnvironmentState(e))}_priceAxisesContainer(e){return"left"===e?this._lhsPriceAxisesContainer:this._rhsPriceAxisesContainer}_recalculatePriceScales(e){const t=this.state();for(const i of t.leftPriceScales())t.recalculatePriceScale(i,e);for(const i of t.rightPriceScales())t.recalculatePriceScale(i,e);for(const i of t.sourcesByGroup().overlayPriceScaleSources())(0,K.isLineTool)(i)||t.recalculatePriceScale(i.priceScale(),e)}_createLockTimeAxisAction(e){var t;const i=0===(null===(t=Oe.crosshairLock.value())||void 0===t?void 0:t.type);return new ot.Action({actionId:"Chart.Crosshair.LockVerticalCursor",options:{label:pi,statName:"LockCursorInTime",checkable:!0,checked:i,onExecute:()=>this._toggleLockTimeAxis(e.localX,!i)}})}_toggleLockTimeAxis(e,t){if(t){const t=this._chartUndoModel().timeScale(),i=t.coordinateToIndex(e),s=t.points().roughTime(i);if(null!==s)return void Oe.crosshairLock.setValue({type:0,time:s})}Oe.crosshairLock.setValue(null)}_preventTouchEventsExceptPinch(){return this._paneWidgetsSharedState.hasTouchesOnOtherPanes(this)||null!==this._paneWidgetsSharedState.pinchingPane()}_updateHoveredSource(e,t,i){var s,o;const r=this._chartUndoModel(),n=r.model();let a=!1;const l=e&&e.source,c=this._chart.readOnly();if(n.crossHairSource().isReplaySelection())this._setCursorClassName("none");else if(!(!c||e&&(0,K.isLineTool)(e.source))||this._editDialog&&this._editDialog.visible().value())c&&(n.setHoveredSource(null,null),this.setCursorForTool());else{const d=Oe.tool.value();let h=null;if(!this._processing&&((0,Oe.toolIsCursor)(d)||"eraser"===d&&!c||t.mod()||!r.lineBeingCreated())){const t=null==e?void 0:e.hittest;a=Boolean(null===(s=null==t?void 0:t.data())||void 0===s?void 0:s.hideCrosshairLinesOnHover),t&&t.target()>De.HitTarget.MovePointBackground?(h=l,!(null==l?void 0:l.isHoveredEnabled())||"eraser"===d&&l===r.mainSeries()?n.setHoveredSource(null,null):n.setHoveredSource(l,t.data(),0)):n.setHoveredSource(null,null)}c?this.setCursorForTool(h,t,ei.PaneCursorType.Default):this._options.sourceSelectionEnabled&&(this._isSelectPointModeEnabled()?this._setCursorClassName("pointer"):this.setCursorForTool(h,t,null===(o=null==e?void 0:e.hittest.data())||void 0===o?void 0:o.cursorType)) ;const u=n.customSourceBeingMoved(),_=null!==u?[u]:n.sourcesBeingMoved();if((!_.length||null!==e&&-1===_.indexOf(e.source))&&this._updateCommonTooltip(e),!c&&null!==e&&i&&e.hittest.hasPressedMoveHandler(i)){switch((e.hittest.data()||{}).cursorType){case ei.PaneCursorType.VerticalResize:this._setCursorClassName("ns-resize");break;case ei.PaneCursorType.HorizontalResize:this._setCursorClassName("we-resize");break;case ei.PaneCursorType.DiagonalNeSwResize:this._setCursorClassName("nesw-resize");break;case ei.PaneCursorType.DiagonalNwSeResize:this._setCursorClassName("nwse-resize")}}}this._preventCrossHairMove()&&this._clearCursorPosition(),1!==this._pressedMoveStage&&n.crossHairSource().setLinesShouldBeHidden(a)}async _createErrorBlock(){const e=new(await(0,te.getErrorCardRenderer)());return this._div.insertBefore(e.container,this._topCanvasBinding.canvasElement.nextSibling),e}_customActions(){const e={top:[],bottom:[],remove:[]},t=this._chartUndoModel().timeScale(),i=this._state&&this._state.defaultPriceScale();if(!D.enabled("custom_items_in_context_menu"))return e;const s=t.isEmpty()?void 0:t.indexToUserTime(t.coordinateToIndex(this._contextMenuX));let o;if(i&&!i.isEmpty()){const e=(0,r.ensureNotNull)(this.state().mainDataSource()).firstValue();o=i.coordinateToPrice(this._contextMenuY,(0,r.ensureNotNull)(e))}return(0,l.emit)("onContextMenu",{unixtime:null!=s?s.getTime()/1e3:void 0,price:o,callback:t=>{[...t].forEach((t=>{if(t.text)if(t.text.length>1&&"-"===t.text[0])e.remove.push(t.text.slice(1));else{let i;i="-"===t.text?new ot.Separator:new ot.Action({actionId:"Chart.ExternalActionId",options:{label:t.text,onExecute:t.click}}),t.position&&"top"===t.position?e.top.push(i):e.bottom.push(i)}}))}}),e}_highlightPriceAxisByLabel(e){this._lhsPriceAxisesContainer.highlightPriceAxisByLabel(e),this._rhsPriceAxisesContainer.highlightPriceAxisByLabel(e)}_subscribeToState(){const e=this.state();e.onDestroyed().subscribe(this,this._onStateDestroyed,!0),e.dataSourcesCollectionChanged().subscribe(this,this._onDataSourcesCollectionChanged),e.maximized().subscribe(this._updateVisuallyCollapsed),e.collapsed().subscribe(this._updateVisuallyCollapsed)}_unsubscribeFromState(){const e=this.state();e.onDestroyed().unsubscribeAll(this),e.dataSourcesCollectionChanged().unsubscribeAll(this),e.maximized().unsubscribe(this._updateVisuallyCollapsed),e.collapsed().unsubscribe(this._updateVisuallyCollapsed)}_updateAccesibilityAttr(){if(this.state().isMainPane()){const e=this._chartModel().mainSeries(),t=e.symbol(),s=(0,ri.getTranslatedResolutionModel)(e.interval()).hint,o=a.t(null,{replace:{symbol:t,interval:s}},i(88732));this._topCanvasBinding.canvasElement.setAttribute("aria-label",o)}else this._topCanvasBinding.canvasElement.setAttribute("aria-hidden","true")}async _updateEndOfSeriesBanner(){var e,t,s,o;{const n=()=>{var e,t;if(window.user.is_pro)return null;const i=this._state;if(!i)return null===(e=this._endOfSeriesDataBanner)||void 0===e||e.setVisible(!1),null;if(!this._chart.isActive().value())return null;const s=i.model().mainSeries() ;if(!s)return null;if(!i.isMainPane())return null;if(2===s.status()||s.requestMoreDataAvailable())return null===(t=this._endOfSeriesDataBanner)||void 0===t||t.setVisible(!1),null;const o=s.bars().firstIndex();return null===o?null:{state:i,series:s,firstIndex:o}},a=()=>{if(this._legendWidget){const e=this._legendWidget.getElement().getBoundingClientRect();return e.bottom-e.top}return 0};let l=n();if(!l||"end"===l.series.endOfDataType())return void(null===(e=this._endOfSeriesDataBanner)||void 0===e||e.setVisible(!1));l.series.doNotShowLastAvailableBar(!1);const c=l.series.endOfDataType(),d=(0,r.ensureNotNull)(this._state).model().timeScale().indexToCoordinate(l.firstIndex)-l.state.model().timeScale().barSpacing();if(!this._endOfSeriesDataBanner&&!D.enabled("widget")){const e=await Promise.all([i.e(32662),i.e(5987),i.e(98996),i.e(43387),i.e(66458),i.e(4343),i.e(52078),i.e(16005),i.e(2182),i.e(90385),i.e(62526),i.e(66849)]).then(i.bind(i,939651));if(l=n(),!l)return;this._endOfSeriesDataBanner||(this._endOfSeriesDataBanner=new e.EndOfSeriesBanner,this._div.appendChild(this._endOfSeriesDataBanner.element()))}const h=a();null===(t=this._endOfSeriesDataBanner)||void 0===t||t.setVisible(!0),null===(s=this._endOfSeriesDataBanner)||void 0===s||s.update(l.state,h,d,c);const u=null===(o=this._endOfSeriesDataBanner)||void 0===o?void 0:o.currentSize();l.series.doNotShowLastAvailableBar(null!==u&&0!==u)}}}class Li{constructor(){this._draggingSource=null,this._activeTouchPanes=new Set,this._scrollingPane=null,this._pinchingPane=null}onPaneDestroyed(e){this._activeTouchPanes.delete(e),this._scrollingPane===e&&(this._scrollingPane=null),this._pinchingPane===e&&(this._pinchingPane=null)}startTouch(e){this._activeTouchPanes.add(e)}endTouch(e){this._activeTouchPanes.delete(e)}hasTouchesOnOtherPanes(e){return this._activeTouchPanes.size>1||1===this._activeTouchPanes.size&&!this._activeTouchPanes.has(e)}trySetDraggingSource(e,t){return!this.hasTouchesOnOtherPanes(t)&&((0,r.assert)(null===this._draggingSource||this._draggingSource===e),this._draggingSource=e,!0)}clearDraggingSource(){null!==this._draggingSource&&(this._draggingSource=null)}draggingSource(){return this._draggingSource}setScrollingPane(e){(0,r.assert)(null===e||null===this._scrollingPane||this._scrollingPane===e),this._scrollingPane=e}scrollingPane(){return this._scrollingPane}setPinchingPane(e){(0,r.assert)(null===e||null===this._pinchingPane||this._pinchingPane===e),this._pinchingPane=e}pinchingPane(){return this._pinchingPane}}var ki=i(970109),Ei=i(30574);i(606593);const Di={contextMenuEnabled:!0,timezoneMenuEnabled:!0,pressedMouseMoveScale:!0},Bi=new R.TranslatedString("change session",a.t(null,void 0,i(765303))),Ni=a.t(null,void 0,i(25866));class Ri{constructor(e,t,i,o,r){this._rendererOptions=null,this._onLabelHovered=new E.Delegate,this._mousedown=!1,this._currentCursorClassName="invalid",this._options=(0,w.merge)((0,w.clone)(Di),t||{}),this.chart=e,this._properties=e.properties().childs().scalesProperties,this._element=document.createElement("div"), this._element.style.display="flex",this._backgroundBasedTheme=r;const n=e.model().model().rendererOptionsProvider(),a=()=>this.backgroundColor(),l=()=>{throw new Error("Time axis does not support real price scales")},c={titlesProvider:i,stubContextMenuProvider:(e,t)=>{const i=o(e,t),s=this.getContextMenuActions(!0);return 0===s.length?i:i.concat(new ot.Separator,s)},backgroundBasedTheme:r.spawnOwnership(),onActiveOrHoveredChart:(0,L.combine)(((e,t)=>e||t),this.chart.isActive().weakReference(),this.chart.isHovered().weakReference()).ownership(),rendererOptionsProvider:n,getBackgroundTopColor:a,getBackgroundBottomColor:a,requestRepaint:()=>this.chart.model().model().lightUpdate(),showHorizontalBorder:!0};this._lhsStubContainer=new Je(this._properties,"left",l,c,this._options.priceAxisLabelsOptions,this),this._lhsStubContainer.onLabelHovered().subscribe(this,((e,t)=>{this._onLabelHovered.fire(e,t)})),this._rhsStubContainer=new Je(this._properties,"right",l,c,this._options.priceAxisLabelsOptions,this),this._rhsStubContainer.onLabelHovered().subscribe(this,((e,t)=>{this._onLabelHovered.fire(e,t)})),this._element.appendChild(this._lhsStubContainer.getElement()),this._cell=document.createElement("div"),this._element.appendChild(this._cell),this._cell.classList.add("chart-markup-table","time-axis"),this._cell.style.height="25px",this._dv=document.createElement("div"),this._dv.style.width="100%",this._dv.style.height="100%",this._dv.style.position="relative",this._dv.style.overflow="hidden",this._cell.appendChild(this._dv),this._canvasConfiguredHandler=()=>this.chart.model().model().lightUpdate(),this._canvasBinding=(0,V.createBoundCanvas)(this._dv,(0,s.size)({width:16,height:16})),this._canvasBinding.subscribeSuggestedBitmapSizeChanged(this._canvasConfiguredHandler);const d=this._canvasBinding.canvasElement;d.style.position="absolute",d.style.zIndex="1",d.style.left="0",d.style.top="0",this._topCanvasBinding=(0,V.createBoundCanvas)(this._dv,(0,s.size)({width:16,height:16})),this._topCanvasBinding.subscribeSuggestedBitmapSizeChanged(this._canvasConfiguredHandler);const h=this._topCanvasBinding.canvasElement;h.style.position="absolute",h.style.zIndex="2",h.style.left="0",h.style.top="0",this._dv.setAttribute("aria-hidden","true"),this._element.appendChild(this._rhsStubContainer.getElement()),this.restoreDefaultCursor(),this.update(),this._minVisibleSpan=ki.MINUTE_SPAN,this._mouseEventHandler=new Me.MouseEventHandler(this._topCanvasBinding.canvasElement,this,{treatVertTouchDragAsPageScroll:!0,treatHorzTouchDragAsPageScroll:!1}),this.size=(0,s.size)({width:0,height:0})}destroy(){this._mouseEventHandler.destroy(),this._topCanvasBinding.unsubscribeSuggestedBitmapSizeChanged(this._canvasConfiguredHandler),this._topCanvasBinding.dispose(),this._canvasBinding.unsubscribeSuggestedBitmapSizeChanged(this._canvasConfiguredHandler),this._canvasBinding.dispose(),this._rhsStubContainer.onLabelHovered().unsubscribeAll(this),this._lhsStubContainer.onLabelHovered().unsubscribeAll(this),this._lhsStubContainer.destroy(), this._rhsStubContainer.destroy(),this.chart.properties().childs().paneProperties.childs().background.unsubscribeAll(this),this._backgroundBasedTheme.release()}setCursor(e){let t="";"grabbing"!==e&&"ew-resize"!==e||(t="time-axis--cursor-"+e),this._currentCursorClassName!==t&&(this._currentCursorClassName&&this._cell.classList.remove(this._currentCursorClassName),t&&this._cell.classList.add(t),this._currentCursorClassName=t,this._cell.style.cursor)}restoreDefaultCursor(){this.setCursor("")}getElement(){return this._element}optimalHeight(){const e=this.rendererOptions();return Math.ceil(e.borderSize+e.offsetSize+e.fontSize+e.paddingTop+e.paddingBottom+e.labelBottomOffset)}setSizes(e,t,i){this.size&&(0,s.equalSizes)(this.size,e)||(this.size=e,this._canvasBinding.resizeCanvasElement(e),this._topCanvasBinding.resizeCanvasElement(e),this._cell.style.width=e.width+"px",this._cell.style.height=e.height+"px"),this._lhsStubContainer.setSizes(e.height,t),this._rhsStubContainer.setSizes(e.height,i)}rendererOptions(){if(!this._rendererOptions||this._rendererOptions.fontSize!==this.fontSize()){const e=this.fontSize();this._rendererOptions={borderSize:1,offsetSize:5,fontSize:e,font:(0,Fe.makeFont)(e,qe.CHART_FONT_FAMILY,""),widthCache:new ze.TextWidthCache,paddingTop:3*e/12,paddingBottom:3*e/12,paddingHorizontal:9*e/12,labelBottomOffset:4*e/12}}return this._rendererOptions}backgroundColor(){return this.chart.model().model().backgroundColor().value()}lineColor(){const e=this._properties.childs().lineColor.value();if(0===(0,Pe.parseRgba)(e)[3]){const e=this.chart.model().model().lastPane();if(e&&(e.collapsed().value()||e.isMainPane()&&this._areEventsEnabled()))return this.chart.properties().childs().paneProperties.childs().separatorColor.value()}return e}textColor(){return this._properties.childs().textColor.value()}fontSize(){return this._properties.childs().fontSize.value()}baseFont(){return(0,Fe.makeFont)(this.fontSize(),qe.CHART_FONT_FAMILY)}baseBoldFont(){return(0,Fe.makeFont)(this.fontSize(),qe.CHART_FONT_FAMILY,"","bold")}hasCanvas(e){return this._canvasBinding.canvasElement===e||this._topCanvasBinding.canvasElement===e}onLabelHovered(){return this._onLabelHovered}getScreenshotData(){return{content:this._canvasBinding.canvasElement.toDataURL(),canvas:this._canvasBinding.canvasElement,contentWidth:this.size.width,contentHeight:this.size.height,lhsStub:this._lhsStubContainer.getScreenshotData(),rhsStub:this._rhsStubContainer.getScreenshotData()}}getContextMenuActions(e){var t;const i=this.chart;i.updateActions();const s=i.actions(),o=[];if(e||(i.model().timeScale().resetAvailable().value()&&(o.push(s.timeScaleReset),o.push(new ot.Separator)),this._options.timezoneMenuEnabled&&o.push(s.applyTimeZone),o.push(s.sessionBreaks)),!i.model().mainSeries().isDWM()){const e=null===(t=i.model())||void 0===t?void 0:t.mainSeries().symbolInfo();if(e){const t=i.model().mainSeries().properties().childs().sessionId,s=(e.subsessions||[]).filter((e=>!e.private));if(s.length>1){const e=s.map((e=>new ot.Action({actionId:"Chart.SetSession",options:{ label:(0,Ei.translateSessionDescription)(e.description),checkable:!0,checked:t.value()===e.id,statName:"SetSession",onExecute:()=>{i.model().setProperty(t,e.id,Bi)}}}))),r=new ot.Action({actionId:"Chart.SetSession",options:{label:Ni,statName:"SetSession",subItems:e}});o.push(r)}}}return o}update(){if(!this.chart.hasModel())return;const e=this.chart.model().timeScale().marks();if(e){this._minVisibleSpan=ki.YEAR_SPAN;for(const t of e)this._minVisibleSpan=Math.min(t.span,this._minVisibleSpan)}}updatePriceAxisStubs(){const e=this.chart.model().model(),t=this.chart.isMaximizedPane()?(0,r.ensureNotNull)(this.chart.maximizedPaneWidget()).state():e.paneForSource(e.mainSeries());if(!t)return;const i=e.priceScaleSlotsCount();this._lhsStubContainer.setScales([],i.left,t.leftPriceScales().length,i.left+i.right),this._rhsStubContainer.setScales([],i.right,t.rightPriceScales().length,i.left+i.right)}paint(e){if(e===pe.InvalidationLevel.None||0===this.size.width||0===this.size.height)return;(0,V.tryApplySuggestedCanvasBitmapSize)(this._canvasBinding),(0,V.tryApplySuggestedCanvasBitmapSize)(this._topCanvasBinding);const t=(0,V.getContext2D)(this._topCanvasBinding.canvasElement);if(e>pe.InvalidationLevel.Cursor){const i=(0,V.getContext2D)(this._canvasBinding.canvasElement),s=(0,V.getBindingRenderingInfo)(this._canvasBinding);this.drawBackground(i,s),this.chart.hasModel()&&(this.drawBorder(i,s),this.drawTickMarks(i,s),this.drawBackLabels(i,s),this.drawCrossHairLabel(t,s)),this._lhsStubContainer.paintStubs(e),this._rhsStubContainer.paintStubs(e)}this.drawCrossHairLabel(t,(0,V.getBindingRenderingInfo)(this._topCanvasBinding))}drawBackground(e,t){if((0,V.clearRect)(e,0,0,t.bitmapSize.width,t.bitmapSize.height,this.backgroundColor()),!this.chart.hasModel())return;const i=this.chart.model();if(!i.timeScale().isEmpty()){const s=i.model().selection().lineDataSources().reduce(((e,t)=>{const i=t.timeAxisPoints();return 0===i.length?e:e.concat(i)}),[]);s.length>0&&this._highlightBackground(e,s,t)}const s=i.model().crossHairSource();s.startMeasurePoint()&&this._highlightBackground(e,s.measurePoints(),t)}drawBorder(e,t){e.save(),e.fillStyle=this.lineColor();const i=Math.max(1,Math.floor(this.rendererOptions().borderSize*t.verticalPixelRatio)),s=t.bitmapSize.width;e.fillRect(0,0,s,i),e.restore()}drawTickMarks(e,t){const i=this.chart.model().timeScale().marks();if(!i||0===i.length)return;let s=i.reduce(((e,t)=>e.span>t.span?e:t),i[0]).span;s>30&&s<40&&(s=30),e.save(),e.strokeStyle=this.lineColor();const o=this.rendererOptions(),r=o.borderSize+o.offsetSize+o.paddingTop+o.fontSize/2;e.textAlign="center",e.textBaseline="middle",e.fillStyle=this.textColor(),(0,V.drawScaled)(e,t.horizontalPixelRatio,t.verticalPixelRatio,(()=>{e.font=this.baseFont();for(let t=0;t=s&&e.fillText(o.label,o.coord,r)}})),e.restore()}drawBackLabels(e,t){var i;e.save();const s=new Set,o=this.chart.model().model();let r=o.dataSources() ;const n=o.selection().allSources();for(const e of n)s.add(e);o.hoveredSource()&&s.add(o.hoveredSource());for(const e of o.sourcesBeingMoved())s.add(e);const a=o.customSourceBeingMoved();null!==a&&s.add(a);const l=null!==(i=o.lineBeingEdited())&&void 0!==i?i:o.lineBeingCreated();l&&s.add(l),s.add(this.chart.model().crossHairSource()),r=r.concat(o.customSources());const c=this.rendererOptions();for(let i=0;i=s&&(s=a,r=n),a<=i&&(i=a,o=n)}}return r&&t.push(r),o&&t.push(o),t}_zoomAvailable(){return!this.chart.model().timeScale().isEmpty()&&this.chart.model().model().zoomEnabled()&&this._options.pressedMouseMoveScale}_mouseDownOrTouchStartEvent(e){if(this._mousedown||!this._zoomAvailable())return;this._mousedown=!0;const t=this.chart.model();t.timeScale().isEmpty()||t.startScaleTime(e.localX)}_pressedMouseOrTouchMoveEvent(e){this._zoomAvailable()&&this.chart.model().scaleTimeTo(e.localX)}_mouseUpOrTouchEndEvent(e){this._zoomAvailable()&&(this._mousedown=!1,this.chart.model().endScaleTime(),this.restoreDefaultCursor())}_contextMenuOrTouchContextMenuEvent(e){this._options.contextMenuEnabled&&Ue.ContextMenuManager.showMenu(this.getContextMenuActions(),e,{statName:"TimeScaleContextMenu"},{menuName:"TimeScaleContextMenu"})}_mouseOrTouchEnterEvent(e){this._zoomAvailable()&&this.setCursor("ew-resize")}_mouseOrTouchLeaveEvent(e){this.restoreDefaultCursor()}_mouseDoubleClickOrDoubleTapEvent(e){(0,u.trackEvent)("GUI","Double click time scale"),this.chart.model().resetTimeScale()}_areEventsEnabled(){var e;{const t=this.chart.model().mainSeries();switch(null===(e=t.symbolInfo())||void 0===e?void 0:e.type){case"forex":case"cfd":return!D.enabled("widget")&&this.chart.model().model().properties().childs().chartEventsSourceProperties.childs().visible.value();case"stock":case"fund":if(!D.enabled("widget")||D.enabled("esdonwidget")){const{esdShowDividends:e,esdShowSplits:i,esdShowEarnings:s}=t.properties().childs();return e.value()||i.value()||s.value()}return!1;default:return!1}}}}var Oi=i(685459),Vi=i.n(Oi),Wi=i(81979),Fi=(i(397150),i(526075)),Hi=i(315347),zi=i(223699);function Ui(e,t){return!!zi.Interval.isEqual(e.res,t.res)&&(0,Hi.areEqualTimeFrames)(e.val,t.val)}var Gi=i(13294),qi=i(794389),ji=i(356893),Zi=i(764005),Ki=i(677305);const Yi=new R.TranslatedString("toggle collapsed pane state",a.t(null,void 0,i(74724)));class $i extends Vt.UndoCommand{constructor(e,t){super(Yi),this._chartModel=e,this._paneIndex=t}redo(){this._chartModel.toggleCollapsedPane(this._paneIndex)}undo(){this._chartModel.toggleCollapsedPane(this._paneIndex)}}var Xi=i(125226),Ji=i(703089),Qi=i(405117),es=i(960337),ts=i(371927),is=i(982217);const ss=a.t(null,void 0,i(875139));function os(e,t){const i="pro_premium_expert"===window.user.pro_plan;switch(t.reason){case"child":(0,es.createGoProDialog)({feature:"studyOnStudy",actions:i?[{text:ss,action:ts.PredefinedAction.Close}]:void 0});break;case"fundamental":const t=e.allStudies().filter(q.isFundamentalStudy).map((e=>e.title(is.TitleDisplayTarget.StatusLine)));(0,es.createGoProDialog)({feature:"fundamentalsOnChart",actions:i?[{text:ss,action:ts.PredefinedAction.Close}]:void 0,customParams:t});break;default:(0,Qi.trackGoProFeature)("studyLimit");const s=e.listUserStudies({dontCountVolume:!0,dontCountOverlay:!0,dontCountCompare:!0});(0,es.createGoProDialog)({feature:"studyLimit",customParams:s,actions:i?[{text:ss, action:ts.PredefinedAction.Close}]:void 0})}}const rs=new R.TranslatedString("move all scales to left",a.t(null,void 0,i(581898))),ns=new R.TranslatedString("move all scales to right",a.t(null,void 0,i(622863))),as=(0,m.getLogger)("Chart.MergeAllScales");class ls extends Vt.UndoCommand{constructor(e,t,i,s,o,r){super(r),this._model=e,this._paneIndex=e.panes().indexOf(t),this._targetPosition=s,this._targetIndex=o,this._scaleId=i.id(),this._sourcePosition=t.priceScalePosition(i),"overlay"!==this._sourcePosition&&(this._sourceIndex=t.priceScaleIndex(i,this._sourcePosition))}redo(){const e=this._model.panes()[this._paneIndex],t=(0,r.ensureNotNull)(e.getPriceScaleById(this._scaleId));e.movePriceScale(t,this._targetPosition,this._targetIndex),this._model.fullUpdate()}undo(){const e=this._model.panes()[this._paneIndex],t=(0,r.ensureNotNull)(e.getPriceScaleById(this._scaleId));e.movePriceScale(t,this._sourcePosition,this._sourceIndex),this._model.fullUpdate()}}var cs=i(440941);class ds extends Vt.UndoCommand{constructor(e,t,i,s){super(s,void 0,!cs.lineToolsDoNotAffectChartInvalidation),this._createdIds=[],this._model=e,this._withoutShift=i,this._origStates=t.map((e=>e.state(!0)));const o=e.lineToolsGroupModel();this._origGroups=t.map((e=>{const t=o.groupForLineTool(e);return t&&t.id}))}redo(){const e=this._model.lineToolsGroupModel(),t=this._origStates.map(((t,i)=>{const s=(0,r.ensureNotNull)(this._model.dataSourceForId(t.id)),o=0===this._createdIds.length?void 0:(0,r.ensureDefined)(this._createdIds[i]),n=(0,K.cloneLineTool)(this._model,s,!this._withoutShift,o);void 0!==t.sharingMode&&n.share(t.sharingMode);const a=(0,r.ensureNotNull)(s.priceScale());(0,r.ensureNotNull)(this._model.paneForSource(s)).addDataSource(n,a,!1);const l=this._origGroups[i];if(null!==l){const t=e.groupForId(l);t&&t.addLineTools([n])}return this._model.updateSource(n),n}));0===this._createdIds.length&&(this._createdIds=t.map((e=>e.id()))),this._model.selectionMacro((e=>{e.clearSelection(),t.forEach((t=>{e.addSourceToSelection(t)}))})),this._model.setShouldBeSavedEvenIfHidden(!0)}undo(){const e=this._model.lineToolsGroupModel();this._createdIds.forEach((t=>{const i=(0,r.ensureNotNull)(this._model.dataSourceForId(t)),s=e.groupForLineTool(i);null!==s&&s.excludeLineTool(i),this._model.removeSource(i)}))}newIds(){return this._createdIds}}function hs(e,t){const i=e.metaInfo(),s=!e.isPine()||e.isStandardPine()?i.description:i.scriptIdPart,o=i.productId,r=Fi.StudyMetaInfo.isScriptStrategy(i),n=window.user&&window.user.pro_plan||"";(0,Yt.getTracker)().then((e=>{e&&e.trackStudiesAnalytics(s,o,t,r,n)}))}class us extends Vt.UndoCommand{constructor(e,t,i,s=!0){super(t,i,s),this._invalidateViaSync=!1,this._chartModel=e,this._invalidateViaSync=e.lineToolsSynchronizer().invalidateViaSync()}redo(){this._invalidateViaSync?this._chartModel.lineToolsSynchronizer().executeSyncedAction((()=>this._redo())):this._redo()}undo(){this._invalidateViaSync?this._chartModel.lineToolsSynchronizer().executeSyncedAction((()=>this._undo())):this._undo()}}function _s(e,t){let i=[] ;const s=e.children(t,!1);for(let t=0;t{e.children(t,!1).forEach((e=>{i.has(e)||(i.add(e),s(e))}))};return t.forEach(s),t.filter((e=>!i.has(e))).map((t=>_s(e,t))).reduce(((e,t)=>e.concat(t)),[])}i(586463);const ms=new R.TranslatedString("exclude line tools from group {group}",a.t(null,void 0,i(363391)));class gs extends Vt.UndoCommand{constructor(e,t,i){super(ms.format({group:t.name().value()}),void 0,!cs.lineToolsDoNotAffectChartInvalidation),this._model=e,this._groupId=t.id,this._groupName=t.name().value(),this._lineToolsIds=i.map((e=>e.id()))}redo(){const e=(0,r.ensureNotNull)(this._model.lineToolsGroupModel().groupForId(this._groupId)),t=this._lineToolsIds.map((e=>this._model.dataSourceForId(e))).filter(w.notNull);e.excludeLineTools(t),0===e.lineTools().length&&this._model.lineToolsGroupModel().removeGroup(e)}undo(){const e=this._lineToolsIds.map((e=>this._model.dataSourceForId(e))),t=this._model.lineToolsGroupModel().groupForId(this._groupId);null!==t?t.addLineTools(e):this._model.lineToolsGroupModel().createGroup(e,this._groupName,this._groupId)}}class Ss extends us{constructor({chartModel:e,title:t,lineDataSourceIds:i}){super(e,t,void 0,!cs.lineToolsDoNotAffectChartInvalidation),this._excludeLineToolsFromGroupUndoCommands=[],this._undoState=[],this._lineDataSourceIds=i}_redo(){const e=this._lineDataSourceIds.map((e=>(0,r.ensureNotNull)(this._chartModel.dataSourceForId(e))));this._groupLineToolsByGroups(e).forEach(((e,t)=>{const i=new gs(this._chartModel,t,e);i.redo(),this._excludeLineToolsFromGroupUndoCommands.push(i)})),e.forEach((e=>{this._undoState.push({state:e.state(!1),paneIndex:this._chartModel.panes().indexOf((0,r.ensureNotNull)(this._chartModel.paneForSource(e))),sharingMode:e.sharingMode().value()}),this._chartModel.removeSource(e)}))}_undo(){var e;for(let t=this._undoState.shift();t;t=this._undoState.shift())null===(e=this._chartModel.restoreSource(!1,t.paneIndex,null,t.state,null))||void 0===e||e.share(t.sharingMode);this._excludeLineToolsFromGroupUndoCommands.forEach((e=>e.undo()))}_groupLineToolsByGroups(e){const t=this._chartModel.lineToolsGroupModel();return e.reduce(((e,i)=>{const s=t.groupForLineTool(i);if(null!==s){const t=e.get(s)||[];t.push(i),e.set(s,t)}return e}),new Map)}}var vs=i(347710),fs=i(305934);const bs=(0,m.getLogger)("Chart.RemoveSourcesUndoCommand"),ys=new R.TranslatedString("remove line data sources",a.t(null,void 0,i(66414)));class Cs extends us{constructor(e,t,i){super(e,i,void 0,(0,fs.sourcesAffectState)(t)),this._removeLineDataSourcesUndoCommand=null,this._initialPriceScaleMode=null;const[s,o]=ps(e,t).reduce(((e,t)=>((0,K.isLineTool)(t)?e[1].push(t.id()):e[0].push(t.id()),e)),[[],[]]);this._sourceIds=s,this._lineDataSourceIds=o,this._sourceStates=[],this._paneIndexes=[],this._priceScalePositionIds=[],this._paneStates=[],this._restorePanes=[];const n=t[0];1===t.length&&(0,q.isStudy)(n)&&(this._initialPriceScaleMode=(0,r.ensureNotNull)(n.priceScale()).mode())}removedIds(){ return[...this._sourceIds,...this._lineDataSourceIds]}_redo(){const e=this._chartModel.panes().length,t=this._sourceIds.map((e=>(0,r.ensureNotNull)(this._chartModel.dataSourceForId(e))));this._sourceStates=t.map((e=>{const t=e.state(!1);return null===t&&(0,q.isStudyStub)(e)?e.getDescriptor():t}));const i=t.map((e=>(0,r.ensureNotNull)(this._chartModel.paneForSource(e))));this._paneIndexes=i.map((e=>this._chartModel.panes().indexOf(e))),this._lineDataSourceIds.length>0&&(this._removeLineDataSourcesUndoCommand=new Ss({title:ys,chartModel:this._chartModel,lineDataSourceIds:this._lineDataSourceIds}),this._removeLineDataSourcesUndoCommand.redo()),this._priceScalePositionIds=t.map(((e,t)=>{const s=e.priceScale();if(null===s)return null;const o=i[t].priceScalePosition(s);return{id:s.id(),position:o,priceScaleIndex:i[t].priceScaleIndex(s,o)}}));const s=new Set;t.forEach(((e,t)=>{s.add(this._paneIndexes[t])})),this._paneStates=t.map(((e,t)=>{const o=this._paneIndexes[t];return s.has(o)?i[t].state(!1,!0):null})),this._restorePanes=t.map((e=>this._chartModel.removeSource(e))),t.forEach((e=>{(0,q.isStudy)(e)&&hs(e,"remove")})),e!==this._chartModel.panes().length&&this._chartModel.setShouldBeSavedEvenIfHidden(!0)}_undo(){const e=[];for(let t=this._sourceStates.length-1;t>=0;t--){const i=this._sourceStates[t];if(null!==i){let s=null;s="descriptor"in i&&(0,vs.isStudyDescriptor)(i.descriptor)?this._chartModel.restoreStudyStub(i):this._chartModel.restoreSource(this._restorePanes[t],this._paneIndexes[t],this._paneStates[t],i,this._priceScalePositionIds[t]),s&&e.push(s)}}e.some(((t,i)=>t.id()!==this._sourceIds[e.length-i-1]))&&bs.logError("Source was restored improperly - source ids does not match"),null!==this._initialPriceScaleMode&&(0,r.ensureNotNull)(e[0].priceScale()).setMode(this._initialPriceScaleMode),this._removeLineDataSourcesUndoCommand&&this._removeLineDataSourcesUndoCommand.undo()}}class ws extends Vt.UndoCommand{constructor(e,t,i,s=!0){super(i,s,(0,fs.sourcesAffectState)(t)),this._newStates=[],this._model=e,this._savedStates=t.map((e=>e.state(!1)))}redo(){this._applyState(this._newStates)}undo(){0===this._newStates.length&&this.saveNewState(),this._applyState(this._savedStates)}saveNewState(){const e=this._savedStates.filter(w.notNull).map((e=>(0,r.ensureNotNull)(this._model.dataSourceForId(e.id))));this._newStates=e.map((e=>e.state(!1)))}_applyState(e){for(const t of e)if(null!==t){const e=this._model.dataSourceForId(t.id);if(null!==e)if((0,q.isStudy)(e)){const i=t.state.inputs,s=e.properties().childs().inputs.childs();for(const e in i)s[e]&&s[e].setValue(i[e])}else this._model.restoreLineToolState(e,t,!0)}}}class Ps extends Vt.UndoCommand{constructor(e,t,i){super(i),this._chartModel=e,this._sourceId=t.id();const s=(0,r.ensureNotNull)(t.priceScale());this._initialPriceScaleId=s.id(),this._initialPriceScaleState=(0,r.ensureNotNull)(t.priceScale()).state();const o=(0,r.ensureNotNull)(e.paneForSource(t));this._initialPriceScalePosition=o.priceScalePosition(s), this._initialPriceScaleIndex=o.priceScaleIndex(s,this._initialPriceScalePosition),this._initialPaneIndex=e.panes().indexOf(o)}_newPriceScaleState(e){const t={...this._initialPriceScaleState};return delete t.m_isLockScale,delete t.id,delete t.m_topMargin,delete t.m_bottomMargin,delete t.hasCalculatedPriceRange,t}_originalPriceScaleState(){return this._initialPriceScaleState}}class Ts extends Ps{constructor(e,t,i){super(e,t,i)}redo(){const e=(0,r.ensureNotNull)(this._chartModel.dataSourceForId(this._sourceId)),t=(0,r.ensureNotNull)(this._chartModel.paneForSource(e)),i=this._chartModel.children(e,!0);t.bulkActionMacro((()=>{i.forEach((e=>this._chartModel.detachSource(e))),this._chartModel.detachSource(e)}));const s=this._chartModel.createPane(this.targetPaneIndex()),o=s.findSuitableScale(e);s.bulkActionMacro((()=>{s.addDataSource(e,o,!1),i.forEach((e=>s.addDataSource(e,o,!1)))}));const n=(0,r.ensureNotNull)(e.priceScale());n.restoreState(this._newPriceScaleState(s.isOverlay(e))),n.setHeight(s.height()),this._chartModel.fullUpdate(),this._chartModel.setShouldBeSavedEvenIfHidden(!0)}undo(){const e=(0,r.ensureNotNull)(this._chartModel.dataSourceForId(this._sourceId)),t=(0,r.ensureNotNull)(this._chartModel.paneForSource(e)),i=this._chartModel.children(e,!0);t.bulkActionMacro((()=>{i.forEach((e=>this._chartModel.detachSource(e)));const t=this._chartModel.detachSource(e);(0,r.assert)(t,"Undo of detaching must remove pane")}));const s=this._chartModel.panes()[this._initialPaneIndex];let o=s.getPriceScaleById(this._initialPriceScaleId);null===o&&(o=s.createPriceScaleAtPosition(this._initialPriceScalePosition,this._initialPriceScaleIndex)),s.bulkActionMacro((()=>{s.addDataSource(e,o,!0),i.forEach((e=>s.addDataSource(e,o,!1)))}));const n=(0,r.ensureNotNull)(e.priceScale());n.restoreState(this._originalPriceScaleState()),n.setHeight(s.height()),this._chartModel.fullUpdate()}}class Ms extends Ts{constructor(e,t,i){super(e,t,i)}targetPaneIndex(){return this._initialPaneIndex+1}}class xs extends Ts{constructor(e,t,i){super(e,t,i)}targetPaneIndex(){return this._initialPaneIndex}}class Is extends Ts{constructor(e,t,i){super(e,t,i)}targetPaneIndex(){return this._chartModel.panes().length}}class As extends Ps{constructor(e,t,i,s){super(e,t,i),this._restorePane=!1,this._keepZOrder=null!=s&&s,this._initialZOrder=t.zorder()}redo(){const e=this._chartModel.panes().length,t=this._chartModel.panes()[this._targetPaneIndex()],i=(0,r.ensureNotNull)(this._chartModel.dataSourceForId(this._sourceId)),s=(0,r.ensureNotNull)(this._chartModel.paneForSource(i)),o=this._chartModel.children(i,!0);s.bulkActionMacro((()=>{o.forEach((e=>this._chartModel.detachSource(e))),this._restorePane=this._chartModel.detachSource(i)}));const n="overlay"===this._initialPriceScalePosition?this._initialPriceScalePosition:void 0,a=t.findSuitableScale(i,void 0,n),l=0===a.dataSources().length;if(t.bulkActionMacro((()=>{t.addDataSource(i,a,this._keepZOrder),o.forEach((e=>t.addDataSource(e,a,this._keepZOrder)))})),i===this._chartModel.mainSeries()){ const e=t.priceScalePosition(a);t.movePriceScale(a,e,0)}if(l){const e=(0,r.ensureNotNull)(i.priceScale());e.restoreState(this._newPriceScaleState(t.isOverlay(i))),e.setHeight(t.height())}this._chartModel.fullUpdate(),e!==this._chartModel.panes().length&&this._chartModel.setShouldBeSavedEvenIfHidden(!0)}undo(){let e;e=this._restorePane?this._chartModel.createPane(this._initialPaneIndex):this._chartModel.panes()[this._initialPaneIndex];const t=(0,r.ensureNotNull)(this._chartModel.dataSourceForId(this._sourceId)),i=(0,r.ensureNotNull)(this._chartModel.paneForSource(t)),s=this._chartModel.children(t,!0);i.bulkActionMacro((()=>{s.forEach((e=>this._chartModel.detachSource(e))),this._chartModel.detachSource(t)}));let o=e.getPriceScaleById(this._initialPriceScaleId);null===o&&(o=e.createPriceScaleAtPosition(this._initialPriceScalePosition,this._initialPriceScaleIndex)),e.bulkActionMacro((()=>{t.setZorder(this._initialZOrder),e.addDataSource(t,o,!0),s.forEach((t=>e.addDataSource(t,o,!1)))}));const n=(0,r.ensureNotNull)(t.priceScale());n.restoreState(this._originalPriceScaleState()),n.setHeight(e.height()),this._chartModel.fullUpdate()}}class Ls extends As{constructor(e,t,i){super(e,t,i)}_targetPaneIndex(){return this._initialPaneIndex-1}}class ks extends As{constructor(e,t,i){super(e,t,i)}_targetPaneIndex(){return this._initialPaneIndex+1}}class Es extends As{constructor(e,t,i,s,o){super(e,t,s,o),this._targetPane=i}_targetPaneIndex(){return this._targetPane}}var Ds=i(888929),Bs=i(996986),Ns=i(918208);const Rs=new R.TranslatedString("create {tool}",a.t(null,void 0,i(581791)));class Os extends us{constructor({model:e,pane:t,lineTool:i,ownerSource:s,drawOnAllChartsMode:o=0,id:r}){super(e,Rs.format({tool:new R.TranslatedString(i,Ns.lineToolsLocalizedNames[i])}),!1,!cs.lineToolsDoNotAffectChartInvalidation),this._lineId=null,this._lineState=null,this._paneIndex=e.panes().indexOf(t),this._lineTool=i,this._ownerSourceId=s.id(),this._lineId=null!=r?r:null,this._drawOnAllChartsMode=o}startCreatingLine(e,t,i,s,o){var r;const n=this._chartModel.panes()[this._paneIndex],a=this._chartModel.dataSourceForId(this._ownerSourceId)||void 0,l=this._chartModel.createLineTool({pane:n,point:e,linetool:this._lineTool,properties:t,linkKey:i,sharingMode:s,ownerSource:a,id:null!==(r=this._lineId)&&void 0!==r?r:void 0,fromExternalModel:o});return this._lineId=l.id(),this._fromExternalModel=o,!this._chartModel.lineBeingCreated()}continueCreatingLine(e,t,i,s){const o=this._chartModel.continueCreatingLine(e,t,i,s,this._fromExternalModel);return o&&this._chartModel.setShouldBeSavedEvenIfHidden(!0),o}line(){return null===this._lineId?null:this._chartModel.dataSourceForId(this._lineId)}drawOnAllCharts(){return 0!==this._drawOnAllChartsMode}_redo(){if(null===this._lineState)return;const e=this._chartModel.restoreSource(!1,this._paneIndex,null,(0,r.ensureNotNull)(this._lineState),null);null!==e&&(this._lineId=e.id(),this._lineState=null,e.share(this._drawOnAllChartsMode))}_undo(){const e=this.line();null!==e&&(this._lineState=e.state(!1), this._chartModel.removeSource(e),this._lineId=null)}}const Vs=new R.TranslatedString("bring {title} to front",a.t(null,void 0,i(178246))),Ws=new R.TranslatedString("send {title} to back",a.t(null,void 0,i(166781))),Fs=new R.TranslatedString("insert {title} after {targetTitle}",a.t(null,void 0,i(53146))),Hs=new R.TranslatedString("insert {title} before {targetTitle}",a.t(null,void 0,i(667176))),zs=new R.TranslatedString("send {title} backward",a.t(null,void 0,i(216259))),Us=new R.TranslatedString("bring {title} forward",a.t(null,void 0,i(356763))),Gs=new R.TranslatedString("send group {title} backward",a.t(null,void 0,i(404998))),qs=new R.TranslatedString("bring group {title} forward",a.t(null,void 0,i(27195)));function js(e){return new R.TranslatedString(e.name(),e.title(is.TitleDisplayTarget.StatusLine))}class Zs extends Vt.UndoCommand{constructor(e,t,i){super(i,void 0,(0,fs.sourcesAffectState)(t)),this._sourcesByPanes=new Map,this._originalState=new Map,this._model=e,t.forEach((t=>{const i=(0,r.ensureNotNull)(e.paneForSource(t)),s=e.panes().indexOf(i),o=this._sourcesByPanes.get(s)||[];o.push(t.id()),this._sourcesByPanes.set(s,o)})),Array.from(this._sourcesByPanes.keys()).forEach((t=>{const i=e.panes()[t],s=new Map,o=new Set(i.sourcesByGroup().multipaneSources());i.sourcesByGroup().allIncludingHidden().filter((e=>!o.has(e))).forEach((e=>{s.set(e.id(),e.zorder())})),this._originalState.set(t,s)}))}undo(){this._originalState.forEach(((e,t)=>{const i=this._model.panes()[t],s=new Map;e.forEach(((e,t)=>{const o=(0,r.ensureNotNull)(i.dataSourceForId(t));s.set(o,e)})),i.setZOrders(s)}))}redo(){this._sourcesByPanes.forEach(((e,t)=>{const i=this._model.panes()[t],s=e.map((e=>(0,r.ensureNotNull)(i.dataSourceForId(e))));this._paneOperation(i,s)}))}}class Ks extends Zs{constructor(e,t){super(e,t,Vs.format({title:js(t[0])}))}_paneOperation(e,t){e.bringToFront(t)}}class Ys extends Zs{constructor(e,t){super(e,t,Ws.format({title:js(t[0])}))}_paneOperation(e,t){e.sendToBack(t)}}class $s extends Zs{constructor(e,t,i,s){super(e,t,s),this._targetSource=i}_paneOperation(e,t){e.insertAfter(t,this._targetSource)}}class Xs extends $s{constructor(e,t,i){super(e,t,i,Fs.format({title:js(t[0]),targetTitle:js(i)}))}}class Js extends Zs{constructor(e,t,i,s){super(e,t,s),this._targetSource=i}_paneOperation(e,t){e.insertBefore(t,this._targetSource)}}class Qs extends Js{constructor(e,t,i){super(e,t,i,Hs.format({title:js(t[0]),targetTitle:js(i)}))}}function eo(e,t){const i=t[0],s=e.sourcesByGroup().all().filter((e=>e.zorder()e.zorder()>i.zorder()));if(0===s.length)throw new Error("Cannot bring forward source that alreadt on back") ;let o=s[0];if((0,K.isLineTool)(o)){const t=e.model().lineToolsGroupModel().groupForLineTool(o);if(null!==t){const e=t.lineTools();o=e[e.length-1]}}return o}class so extends $s{constructor(e,t,i){super(e,i,io(t,i),Us.format({title:js(i[0])}))}}function oo(e,t){return(0,r.ensureNotNull)(e.paneForSource(t.lineTools()[0]))}class ro extends Js{constructor(e,t){super(e,t.lineTools(),eo(oo(e,t),t.lineTools()),Gs.format({title:t.name().value()}))}}class no extends $s{constructor(e,t){super(e,t.lineTools(),io(oo(e,t),t.lineTools()),qs.format({title:t.name().value()}))}}const ao=new R.TranslatedString("rearrange panes",a.t(null,void 0,i(233348)));class lo extends Vt.UndoCommand{constructor(e,t,i){super(ao),this._chartModel=e,this._index=t,(0,w.isNumber)(i)?this._dstIndex=i:this._dstIndex="up"===i?t-1:t+1}redo(){this._checkIndices()&&this._chartModel.movePane(this._index,this._dstIndex)}undo(){this._checkIndices()&&this._chartModel.movePane(this._dstIndex,this._index)}_checkIndices(){const e=this._chartModel.panes().length;return this._index>=0&&this._index=0&&this._dstIndex{var s,o;e.setValue(t[i].val),(null!==(o=null===(s=e.dependents)||void 0===s?void 0:s.call(e))&&void 0!==o?o:[]).forEach((e=>po(e,t[i].dependenValues)))}))}class mo extends Vt.UndoCommand{constructor(e,t,i,s,o=!0){super(i,void 0,o),this._targetObj=e,this._newValue=t,this._oldValue=this._targetObj.value(),this._dependentValues=_o(this._targetObj),this._model=s}redo(){(0,co.allowSavingDefaults)(!0),this._targetObj.setValue(this._newValue),(0,co.allowSavingDefaults)(!1),this._model.recalculateAllPanes((0,ni.globalChangeEvent)()),this._model.lightUpdate()}undo(){(0,co.allowSavingDefaults)(!0),this._targetObj.setValue(this._oldValue),po(this._targetObj,this._dependentValues),(0,co.allowSavingDefaults)(!1),this._model.recalculateAllPanes((0,ni.globalChangeEvent)()),this._model.lightUpdate()}}class go extends Vt.UndoCommand{constructor(e,t,i,s,o,r){super(s),this._prevPriceAxisProps={},this._dependentValues=[],this._property=e,this._mainSeries=i,this._value=t,this._model=o,this._chartWidget=r}redo(){const e=this._mainSeries,t=e.properties().childs();this._dependentValues=_o(this._property),this._prevResolution=t.interval.value(),this._prevValue=this._property.value(),this._storePriceAxisProps(),(0,co.allowSavingDefaults)(!0);const i=t.interval.value(),s=this._model.defaultResolutions(),o=(0,ri.getResolutionByChartStyle)(this._value,i,s);ho.linking.interval.setValue(o),e.setChartStyleWithIntervalIfNeeded(this._value,o),(0,oe.setLastUsedStyle)(this._value,e.symbolInfo()),(0,oe.preparePriceAxisProperties)(t),(0, co.allowSavingDefaults)(!1),this._invalidateModel(),this._chartWidget.screen.show(!0)}undo(){const e=this._mainSeries;(0,co.allowSavingDefaults)(!0),e.setChartStyleWithIntervalIfNeeded(this._prevValue,this._prevResolution),this._restorePriceAxisProps(),ho.linking.interval.setValue(this._prevResolution),po(this._property,this._dependentValues),(0,co.allowSavingDefaults)(!1),this._invalidateModel(),this._chartWidget.screen.show(!0)}_storePriceAxisProps(){const e=this._mainSeries.priceScale();this._prevPriceAxisProps=e.mode()}_restorePriceAxisProps(){this._mainSeries.priceScale().setMode(this._prevPriceAxisProps)}_invalidateModel(){this._model&&(this._model.recalculateAllPanes((0,ni.sourceChangeEvent)(this._model.mainSeries().id())),this._model.lightUpdate())}}const So=new R.TranslatedString("change date range",a.t(null,void 0,i(207151)));class vo extends Vt.UndoCommand{constructor(e,t){super(So),this._modelsData=[],this._rangeOptions=t,this._modelsData.push({model:e,prevResolution:e.mainSeries().properties().childs().interval.value(),barSpacing:e.timeScale().barSpacing(),rightOffset:e.timeScale().rightOffset(),rangeOptions:e.appliedTimeFrame().value()})}redo(){for(const e of this._modelsData){const t=e.model.mainSeries(),i=t.properties().childs().interval;zi.Interval.isEqual(this._rangeOptions.res,i.value())?t.loadDataTo(this._rangeOptions.val):(t.setDefaultTimeframe(this._rangeOptions.val),t.setSymbolParams({interval:this._rangeOptions.res}))}}undo(){for(const e of this._modelsData){const t=e.model.mainSeries(),i=t.properties().childs().interval;e.prevResolution!==i.value()?(null!==e.rangeOptions&&t.setDefaultTimeframe(e.rangeOptions.val),t.setSymbolParams({interval:e.prevResolution})):null!==e.rangeOptions&&t.loadDataTo(e.rangeOptions.val);const s=e.model.timeScale();s.setBarSpacing(e.barSpacing),s.setRightOffset(e.rightOffset)}}canMerge(e){return e instanceof vo&&Ui(e._rangeOptions,this._rangeOptions)}merge(e){if(!(e instanceof vo))throw new Error("Invalid command to merge");this._modelsData=this._modelsData.concat(e._modelsData)}}var fo=i(391534);class bo extends Vt.UndoCommand{constructor(e,t,i){super(i,void 0,!cs.lineToolsDoNotAffectChartInvalidation),this._model=e,this._groupId=t.id,this._groupName=t.name().value(),this._lineToolsIds=t.lineTools().map((e=>e.id()))}redo(){const e=(0,r.ensureNotNull)(this._model.lineToolsGroupModel().groupForId(this._groupId));this._model.lineToolsGroupModel().removeGroup(e)}undo(){const e=this._lineToolsIds.map((e=>this._model.dataSourceForId(e))),t=new fo.LineToolsGroup(e,this._groupName,this._groupId);this._model.lineToolsGroupModel().addGroup(t)}}const yo=new R.TranslatedString("create line tools group",a.t(null,void 0,i(3195)));class Co extends Vt.UndoCommand{constructor(e,t){super(yo,void 0,!cs.lineToolsDoNotAffectChartInvalidation),this._groupId=null,this._model=e,this._sourcesIds=t.map((e=>e.id()))}redo(){const e=this._sourcesIds.map((e=>this._model.dataSourceForId(e))),t=null===this._groupId?void 0:this._groupId ;this._groupId=this._model.lineToolsGroupModel().createGroup(e,this._title,t).id}undo(){const e=(0,r.ensureNotNull)(this._model.lineToolsGroupModel().groupForId((0,r.ensureNotNull)(this._groupId)));this._model.lineToolsGroupModel().removeGroup(e)}createdGroupId(){return this._groupId}}const wo=new R.TranslatedString("add line tool(s) to group {group}",a.t(null,void 0,i(240242)));class Po extends Vt.UndoCommand{constructor(e,t,i){super(wo.format({group:t.name().value()}),void 0,!cs.lineToolsDoNotAffectChartInvalidation),this._model=e,this._groupId=t.id,this._lineToolsIds=i.map((e=>e.id()))}redo(){const e=(0,r.ensureNotNull)(this._model.lineToolsGroupModel().groupForId(this._groupId)),t=this._lineToolsIds.map((e=>this._model.dataSourceForId(e)));e.addLineTools(t)}undo(){const e=this._lineToolsIds.map((e=>this._model.dataSourceForId(e)));(0,r.ensureNotNull)(this._model.lineToolsGroupModel().groupForId(this._groupId)).excludeLineTools(e)}}class To extends Vt.UndoCommand{constructor(e,t,i,s){super(s,void 0,!cs.lineToolsDoNotAffectChartInvalidation),this._chartModel=e,this._groupId=t.id,this._oldName=t.name().value(),this._newName=i}redo(){(0,r.ensureNotNull)(this._chartModel.lineToolsGroupModel().groupForId(this._groupId)).setName(this._newName)}undo(){(0,r.ensureNotNull)(this._chartModel.lineToolsGroupModel().groupForId(this._groupId)).setName(this._oldName)}}var Mo=i(541558);class xo extends Vt.UndoCommand{constructor(e,t,i,s){super(s,void 0,!cs.lineToolsDoNotAffectChartInvalidation),this._model=i,this._id=e.id(),this._targetSharingMode=t,this._originSharingMode=e.sharingMode().value()}redo(){const e=this._model.dataSourceForId(this._id);e&&(e.share(this._targetSharingMode),0!==this._targetSharingMode&&0===this._originSharingMode&&(e.linkKey().setValue((0,Mo.randomHash)()),this._model.copyToOtherCharts([e],!1)))}undo(){const e=this._model.dataSourceForId(this._id);e&&(e.share(this._originSharingMode),0===this._originSharingMode&&((0,Oe.removeLineTool)({withUndo:!1,model:this._model,symbol:e.symbol(),linkKey:(0,r.ensureNotNull)(e.linkKey().value()),sourceTitle:(0,Bs.getTranslatedStringForSource)(is.TitleDisplayTarget.StatusLine,e),lineToolState:e.state(!1),unlink:!0}),e.linkKey().setValue(null)))}}const Io=new R.TranslatedString("create line tools group from selection",a.t(null,void 0,i(192659))),Ao=new R.TranslatedString("removing line tools group {name}",a.t(null,void 0,i(578811))),Lo=new R.TranslatedString("add line tool {lineTool} to group {name}",a.t(null,void 0,i(799113))),ko=new R.TranslatedString("make group {group} visible",a.t(null,void 0,i(587927))),Eo=new R.TranslatedString("make group {group} invisible",a.t(null,void 0,i(445223))),Do=new R.TranslatedString("lock group {group}",a.t(null,void 0,i(304963))),Bo=new R.TranslatedString("unlock group {group}",a.t(null,void 0,i(551114))),No=new R.TranslatedString("rename group {group} to {newName}",a.t(null,void 0,i(916338)));class Ro{constructor(e){this._environment=e}createGroupFromSelection(){const e=this._environment.model();(0, r.assert)(!e.selection().isEmpty(),"Cannot create group from empty selection");const t=(0,Ds.sortSources)(e.selection().lineDataSources());(0,r.assert)(t.length===e.selection().allSources().length,"A group could contain line tools only");const i=t.length>1||null!==this._environment.model().lineToolsGroupModel().groupForLineTool(t[0]),s=t.reduce(((e,t)=>e.zorder()>t.zorder()?e:t),t[0]);let o=s;const n=e.lineToolsGroupModel().groupForLineTool(s);if(null!==n){const e=n.lineTools();o=e[e.length-1]}this._environment.beginUndoMacro(Io);const a=new Map,l=new Set;t.forEach((t=>{const i=this._groupForLineTool(t);if(null===i)return;const s=a.get(i)||[];s.push(t),a.set(i,s);const o=(0,r.ensureNotNull)(e.paneForSource(t));l.add(o)})),(0,r.assert)(l.size<=1,"All selected sources should be on the same pane"),a.forEach(((t,i)=>{const s=new gs(e,i,t);this._environment.pushUndoCommand(s)}));const c=new Co(e,(0,Ds.sortSources)(t));if(this._environment.pushUndoCommand(c),i){const i=new Xs(e,t,o);this._environment.pushUndoCommand(i)}this._environment.endUndoMacro();const d=(0,r.ensureNotNull)(c.createdGroupId());return(0,r.ensureNotNull)(e.lineToolsGroupModel().groupForId(d))}removeGroup(e){const t=this._environment.model(),i=e.lineTools();this._environment.beginUndoMacro(Ao.format({name:e.name().value()}));const s=new bo(t,e,null);this._environment.pushUndoCommand(s);const o=new Cs(t,i,null);this._environment.pushUndoCommand(o);const n=t.mainSeries().symbol();i.forEach((e=>{null!==e.linkKey().value()&&(0,Oe.removeLineTool)({withUndo:!0,model:t,symbol:n,sourceTitle:new R.TranslatedString(e.name(),e.title(is.TitleDisplayTarget.DataWindow)),lineToolState:e.state(!1),linkKey:(0,r.ensureNotNull)(e.linkKey().value())})})),this._environment.endUndoMacro()}groups(){return this._environment.model().lineToolsGroupModel().groups()}excludeLineToolFromGroup(e,t){const i=this._environment.model(),s=new gs(i,e,[t]);this._environment.pushUndoCommand(s)}addLineToolToGroup(e,t){const i=this._environment.model(),s=i.lineToolsGroupModel().groupForLineTool(t);if(s===e)return;const o=Lo.format({lineTool:new R.TranslatedString(t.name(),t.title(is.TitleDisplayTarget.StatusLine)),name:e.name().value()});this._environment.beginUndoMacro(o),null!==s&&this._environment.pushUndoCommand(new gs(i,s,[t]));{const s=e.sharingMode().value();t.sharingMode().value()!==s&&this._environment.pushUndoCommand(new xo(t,s,i,null))}this._environment.pushUndoCommand(new Po(i,e,[t])),this._environment.endUndoMacro()}bringToFront(e){const t=this._environment.model(),i=new Ks(t,e.lineTools());this._environment.pushUndoCommand(i),this._environment.emitEvent("changeZOrder",[e.lineTools()])}sendToBack(e){const t=this._environment.model(),i=new Ys(t,e.lineTools());this._environment.pushUndoCommand(i),this._environment.emitEvent("changeZOrder",[e.lineTools()])}bringForward(e){const t=this._environment.model(),i=new no(t,e);this._environment.pushUndoCommand(i),this._environment.emitEvent("changeZOrder",[e.lineTools()])}sendBackward(e){const t=this._environment.model(),i=new ro(t,e) ;this._environment.pushUndoCommand(i),this._environment.emitEvent("changeZOrder",[e.lineTools()])}insertAfter(e,t){const i=this._environment.model();let s;if(t instanceof fo.LineToolsGroup){const e=t.lineTools();s=e[e.length-1]}else s=t;const o=new Xs(i,e.lineTools(),s);this._environment.pushUndoCommand(o),this._environment.emitEvent("changeZOrder",[e.lineTools()])}insertBefore(e,t){const i=this._environment.model();let s;if(t instanceof fo.LineToolsGroup){s=t.lineTools()[0]}else s=t;const o=new Qs(i,e.lineTools(),s);this._environment.pushUndoCommand(o),this._environment.emitEvent("changeZOrder",[e.lineTools()])}availableZOrderOperations(e){const t=this._environment.model(),i=e.lineTools(),s=i[0],o=i[i.length-1],n=(0,r.ensureNotNull)(t.paneForSource(i[0])).sourcesByGroup().allExceptSpecialSources(),a=n[0],l=n[n.length-1];return{bringForwardEnabled:o!==l,bringToFrontEnabled:o!==l,sendBackwardEnabled:s!==a,sendToBackEnabled:s!==a}}setGroupVisibility(e,t){const i=(t?ko:Eo).format({group:e.name().value()}),s=this._environment.model();this._environment.beginUndoMacro(i),e.lineTools().forEach((e=>{const i=e.properties().visible,o=new mo(i,t,null,s,!cs.lineToolsDoNotAffectChartInvalidation);this._environment.pushUndoCommand(o)})),this._environment.endUndoMacro()}setGroupLock(e,t){const i=(t?Do:Bo).format({group:e.name().value()}),s=this._environment.model();this._environment.beginUndoMacro(i),e.lineTools().forEach((e=>{const i=e.properties().frozen,o=new mo(i,t,null,s,!cs.lineToolsDoNotAffectChartInvalidation);this._environment.pushUndoCommand(o)})),this._environment.endUndoMacro()}setGroupName(e,t){const i=this._environment.model(),s=No.format({group:e.name().value(),newName:t}),o=new To(i,e,t,s);this._environment.pushUndoCommand(o)}canBeGroupped(e){const t=this._environment.model();return new Set(e.map((e=>t.paneForSource(e)))).size<=1}_groupForLineTool(e){return this._environment.model().lineToolsGroupModel().groups().find((t=>t.containsLineTool(e)))||null}}var Oo=i(852290),Vo=i(790524),Wo=i(46955);const Fo=new R.TranslatedString("apply study template {template}",a.t(null,void 0,i(526065)));function Ho(e){for(const t of e.panes)for(const e of t.sources)if((0,Vo.isMainSeriesState)(e))return e.id;return null}class zo extends Vt.UndoCommand{constructor(e,t,i){var s,o;super(Fo.format({template:i})),this._newSymbolParams={},this._model=e,this._templateContent=function(e,t){const i=(0,Oo.default)({},e),s=(0,r.ensureNotNull)(Ho(i));for(const e of i.panes){e.mainSourceId===s&&(e.mainSourceId=t);for(const i of e.sources)if(i.id===s){i.id=t;const o=e=>{const i=e.indexOf(s);-1!==i&&e.splice(i,1,t)};if(e.leftAxisesState&&e.rightAxisesState?(e.leftAxisesState.forEach((e=>o(e.sources))),e.rightAxisesState.forEach((e=>o(e.sources)))):(o(e.leftAxisSources),o(e.rightAxisSources)),e.overlayPriceScales){const i=e.overlayPriceScales[s];i&&(delete e.overlayPriceScales[s],e.overlayPriceScales[t]=i)}}else i.ownerSource===s&&(i.ownerSource=t)}return i}(t,e.mainSeries().id()),this._initialState=e.studyTemplate(!0,!0,!0);const n=e.mainSeries() ;t.symbol&&(this._newSymbolParams={symbol:t.symbol,currency:null!==(s=t.currency)&&void 0!==s?s:null,unit:null!==(o=t.unit)&&void 0!==o?o:null}),t.interval&&(this._newSymbolParams.interval=t.interval,this._newSymbolParams.style=(0,oe.getChartStyleByResolution)(t.interval,n.style())),this._initialSymbolParams={symbol:n.symbol(),currency:n.currency(),unit:n.unit(),interval:n.interval(),style:n.style()},this._initialState=e.studyTemplate(),this._initialGroupsState=e.lineToolsGroupModel().state()}redo(){this._model.mainSeries().setSymbolParams(this._newSymbolParams);const e=this._merge(this._templateContent).filter(K.isLineTool);this._model.lineToolsGroupModel().removeLineTools(e);const t=this._model.mainSeries().properties();(0,oe.preparePriceAxisProperties)(t),this._model.recalcVisibleRangeStudies(Be.RecalcVisibleRangeStudiesReason.StudyCreation),this._model.setShouldBeSavedEvenIfHidden(!0)}undo(){this._model.mainSeries().setSymbolParams(this._initialSymbolParams),this._merge(this._initialState)}_merge(e){const t=e.version||0,i=this._model,s=i.mainSeries();(0,r.assert)(s.id()===Ho(e)),s.priceScale().properties().childs().lockScale.setValue(!1);const o=i.panes(),n=[];for(let e=o.length;e--;){const t=o[e],i=t.containsMainSeries(),s=t.dataSources();for(let e=s.length;e--;){const t=s[e];(!i||((0,q.isStudy)(t)||(0,q.isStudyStub)(t))&&t.isRemovedByStudyTemplates())&&n.push(t)}}i.resetDeferredStudies();const a=ps(i,n);for(let e=0;ee.zorder-t.zorder));for(let e=0;e-1,c=a?o[e]:i.createPane(e);if(a&&t<3&&(0,Wo.reorderDataSourcesStateZOrder)(n.sources),c.restoreState({state:n,withData:!1,version:t}),null!==c.mainDataSource()){const e=(0,r.ensureNotNull)(this._model.alertsWatcher());for(const t of c.dataSources())e.syncSourceAlertLabels(t)}else i.removePane(c)}return i.syncLollipopSources(),s.priceScale().setMode({autoScale:!0}),i.startNotStartedStudies(),i.recalculateAllPanes((0,ni.globalChangeEvent)()),i.fullUpdate(),a}}var Uo=i(981107);const Go=(0,m.getLogger)("Chart.ChartUndoModel"),qo=new R.TranslatedString("paste drawing",a.t(null,void 0,i(896916)));class jo extends Vt.UndoCommand{constructor(e,t,i,s,o){super(qo,void 0,!cs.lineToolsDoNotAffectChartInvalidation),this._needCopyToOtherCharts=!1,this._sourceState=null,this._model=e,this._clipboardData=t,this._paneIndex=this._model.panes().indexOf(i||(0,r.ensureNotNull)(this._model.paneForSource(this._model.mainSeries()))),this._pasteWithData=!!s,this._keepZIndex=!!o}redo(){const e=this._model.panes()[this._paneIndex],t=(0,r.ensureNotNull)(e.clipboardLineToolOwnerSource(this._clipboardData.source.id)),i=t===this._model.mainSeries();null===this._sourceState&&(this._sourceState=this._getSourceState(t,i));const s=(0,r.ensureNotNull)(e.restoreLineTool(this._sourceState,this._pasteWithData,this._keepZIndex,void 0,t));(0, r.ensureNotNull)(t.priceScale()).addDataSource(s),this._clipboardData.centeredOnChart&&s.centerPosition&&s.centerPosition(),s.restoreFixedPoint(),s.createServerPoints(),this._needCopyToOtherCharts=Boolean(i&&s.isSynchronizable()&&0!==s.sharingMode().value()),this._model.setShouldBeSavedEvenIfHidden(!0)}undo(){if(!this._sourceState)return void Go.logError("This command was never executed - nothing to undo");const e=this.source();this._clipboardData.centeredOnChart&&(this._clipboardData.centeredOnChart=!1,this._sourceState.points=e.normalizedPoints()),this._model.removeSource(e)}source(){return(0,r.ensureNotNull)(this._model.dataSourceForId((0,r.ensureNotNull)(this._sourceState).id))}needCopyToOtherCharts(){return this._needCopyToOtherCharts}_getSourceState(e,t){const i=(0,w.clone)(this._clipboardData.source);delete i.state.symbol,t?(null!=i.linkKey||void 0!==i.sharingMode&&0!==i.sharingMode)&&(i.linkKey=(0,Mo.randomHash)()):(i.linkKey=null,i.sharingMode=0);const s=(0,r.ensureNotNull)(e.priceScale()),o=this._model,{symbol:n,currencyId:a,unitId:l}=this._clipboardData.source.state,c=(0,r.ensureNotNull)(e.symbolSource());let d=!1;!c.symbolSameAsCurrent(n)||(null!==a?a!==(0,oe.symbolCurrency)(c.symbolInfo(),void 0,!0):c.isConvertedToOtherCurrency())||(null!==l?l!==(0,oe.symbolUnit)(c.symbolInfo(),this._model.unitConversionEnabled()):c.isConvertedToOtherUnit())||((0,Uo.isActingAsSymbolSource)(e)?d=!0:(0,q.isStudy)(e)&&(d=Boolean(e.metaInfo().is_price_study))),i.state.currencyId=o.currencyConversionEnabled()&&c.isConvertedToOtherCurrency()?c.currency():null,i.state.unitId=o.unitConversionEnabled()&&c.isConvertedToOtherUnit()?c.unit():null;const h=e=>{const t=e.x*o.timeScale().width(),i=e.y*s.height()-40;return new ke.Point(t,i)},u=(0,r.ensureNotNull)(e.firstValue());if(this._model.id()===this._clipboardData.modelId||!d){for(let e=0;e{(0,r.ensureNotNull)(this._chartModel.dataSourceForId(t)).setCurrency(e)})),this._chartModel.selectionMacro((e=>{e.clearSelection()})), this._showFade&&this._chartModel.undoModel().loadingScreen().show(!0)}}class Ko extends Vt.UndoCommand{constructor(e,t,i,s){super(s),this._newSourcesUnits=new Map,this._oldSourcesUnits=new Map,this._showFade=!1,this._chartModel=e;const o=e.mainSeries();for(const e of t.seriesLikeSources()){if(!e.isVisible()||!e.isActingAsSymbolSource().value())continue;const t=i||(0,oe.symbolOriginalUnit)((0,r.ensureNotNull)(e.symbolInfo()),this._chartModel.unitConversionEnabled());this._newSourcesUnits.set(e.id(),t),this._oldSourcesUnits.set(e.id(),e.unit()),this._showFade=this._showFade||e===o&&e.unit()!==t}}redo(){this._applyUnits(this._newSourcesUnits)}undo(){this._applyUnits(this._oldSourcesUnits)}_applyUnits(e){e.forEach(((e,t)=>{(0,r.ensureNotNull)(this._chartModel.dataSourceForId(t)).setUnit(e)})),this._chartModel.selectionMacro((e=>{e.clearSelection()})),this._showFade&&this._chartModel.undoModel().loadingScreen().show(!0)}}class Yo extends Ps{constructor(e,t,i,s){super(e,t,s),this._sourcePaneRemoved=!1,this._targetPaneIndex=e.panes().indexOf(i)}redo(){const e=this._chartModel.panes()[this._initialPaneIndex],t=this._chartModel.panes()[this._targetPaneIndex],i=e!==t,s=this._targetPriceScale(t),o=(0,r.ensureNotNull)(this._chartModel.dataSourceForId(this._sourceId)),n=this._chartModel.children(o,!0);for(const e of n)i?(this._chartModel.detachSource(e),t.addDataSource(e,s,!1)):t.move(e,s);i?(this._sourcePaneRemoved=this._chartModel.detachSource(o),t.addDataSource(o,s,!1)):t.move(o,s);const a=t.priceScalePosition(s);t.movePriceScale(s,a,this._targetPriceScaleIndex(o)),this._chartModel.fullUpdate()}undo(){this._sourcePaneRemoved&&this._chartModel.createPane(this._initialPaneIndex);const e=this._chartModel.panes()[this._initialPaneIndex],t=e!==this._chartModel.panes()[this._targetPaneIndex],i=(0,r.ensureNotNull)(this._chartModel.dataSourceForId(this._sourceId));let s=e.getPriceScaleById(this._initialPriceScaleId);null===s&&(s=e.createPriceScaleAtPosition(this._initialPriceScalePosition,this._initialPriceScaleIndex));const o=this._chartModel.children(i,!0);for(const i of o)t?(this._chartModel.detachSource(i),e.addDataSource(i,s,!1)):e.move(i,s);t?(this._chartModel.detachSource(i),e.addDataSource(i,s,!1)):e.move(i,s);const n=(0,r.ensureNotNull)(i.priceScale());n.restoreState(this._originalPriceScaleState()),n.setHeight(e.height()),this._chartModel.fullUpdate()}}class $o extends Yo{constructor(e,t,i,s,o){super(e,t,i,o),this._targetPriceScalePosition=s}_targetPriceScale(e){const t=e.createPriceScaleAtPosition(this._targetPriceScalePosition);return t.restoreState(this._newPriceScaleState("overlay"===this._targetPriceScalePosition)),t.setHeight(e.height()),t}_targetPriceScaleIndex(e){return e===this._chartModel.mainSeries()?0:void 0}}class Xo extends Yo{constructor(e,t,i,s,o){super(e,t,i,o),this._targetPriceScaleId=s.id()}_targetPriceScale(e){return(0,r.ensureNotNull)(e.getPriceScaleById(this._targetPriceScaleId))}_targetPriceScaleIndex(e){}}var Jo=i(912445);class Qo extends Vt.UndoCommand{constructor(e,t,i,s){super(e), this._charts=new Map,this._firstRedo=!0,this._creationTime=performance.now(),this._linkingGroupIndex=s.linkingGroupIndex().value(),this._charts.set(s,{sourceId:t.id(),newSymbolParams:i,prevSymbolParams:t.symbolParams(),showFade:this._showFade(t,s),chartWidget:s})}redo(){this._firstRedo||(0,Jo.muteLinkingGroup)(this._linkingGroupIndex,!0),this._charts.forEach((e=>{this._symbolSource(e).setSymbolParams(e.newSymbolParams),e.showFade&&e.chartWidget.screen.show(!0)})),this._firstRedo||(0,Jo.muteLinkingGroup)(this._linkingGroupIndex,!1),this._firstRedo=!1}undo(){(0,Jo.muteLinkingGroup)(this._linkingGroupIndex,!0),this._charts.forEach((e=>{this._symbolSource(e).setSymbolParams(e.prevSymbolParams),e.showFade&&e.chartWidget.screen.show(!0)})),(0,Jo.muteLinkingGroup)(this._linkingGroupIndex,!1)}canMerge(e){if(!(e instanceof Qo)||e._linkingGroupIndex!==this._linkingGroupIndex||!this._containsMainSeriesOnly()||!e._containsMainSeriesOnly()||e._creationTime-this._creationTime>500)return!1;for(const[t]of e._charts)if(this._charts.has(t))return!1;return!0}merge(e){if(e instanceof Qo)for(const[t,i]of e._charts)this._charts.set(t,i)}_showFade(e,t){return e===t.model().mainSeries()}_symbolSource(e){return(0,r.ensureNotNull)(e.chartWidget.model().model().dataSourceForId(e.sourceId))}_containsMainSeriesOnly(){for(const[e,t]of this._charts)if(t.sourceId!==e.model().mainSeries().id())return!1;return!0}}const er=new R.TranslatedString("change symbol",a.t(null,void 0,i(600526)));class tr extends Qo{constructor(e,t,i){super(er,e,{symbol:t,currency:null,unit:null},i),this._symbol=t}canMerge(e){return e instanceof tr&&e._symbol===this._symbol&&super.canMerge(e)}}const ir=(0,m.getLogger)("Chart.ChartUndoModel"),sr=new R.TranslatedString("paste indicator",a.t(null,void 0,i(780611)));class or extends Vt.UndoCommand{constructor(e,t,i){super(sr),this._sourceState=null,this._model=e,this._clipboardData=t,this._paneId=i}redo(){if(!this._sourceState){const e=(0,w.clone)(this._clipboardData.source);e.id=(0,Mo.randomHashN)(6),this._sourceState=e}let e,t;e=this._paneId?(0,r.ensureNotNull)(this._model.paneForId(this._paneId)):this._sourceState.metaInfo.is_price_study?(0,r.ensureNotNull)(this._model.paneForSource(this._model.mainSeries())):this._model.createPane();const i=!e.mainDataSource();this._sourceState.zorder=e.newStudyZOrder();const s=(0,r.ensureNotNull)(e.restoreStudy(this._sourceState,!1));i||(t=this._sourceState.metaInfo.is_price_study?t=this._model.mainSeries().priceScale():this._paneId?e.findSuitableScale(s):e.defaultPriceScale(),t!==s.priceScale()&&e.move(s,t)),(0,q.isStudy)(s)&&s.start()}undo(){if(null===this._sourceState)return void ir.logError("This command was never executed - nothing to undo");const e=(0,r.ensureNotNull)(this._model.dataSourceForId(this._sourceState.id));this._model.removeSource(e)}state(){return this._sourceState}}class rr extends Vt.UndoCommand{constructor(e,t,i,s,o){super(null,!1),this._model=e,this._paneA=t,this._paneB=i,this._prevStretchA=s,this._currStretchA=o}redo(){ const e=this._paneA.stretchFactor()+this._paneB.stretchFactor();this._paneA.setStretchFactor(this._currStretchA),this._paneB.setStretchFactor(e-this._currStretchA),this._model.fullUpdate()}undo(){const e=this._paneA.stretchFactor()+this._paneB.stretchFactor();this._paneA.setStretchFactor(this._prevStretchA),this._paneB.setStretchFactor(e-this._prevStretchA),this._model.fullUpdate()}}const nr=new R.TranslatedString("move",a.t(null,void 0,i(647107)));class ar extends Vt.UndoCommand{constructor(e,t,i,s){super(nr,!1),this._endEvent=null,this._model=e,this._sourceId=t.id(),this._itemIndex=i,this._startEvent=s}move(e){this._endEvent=e,this._move(e)}hasChanges(){return null!==this._endEvent}undo(){this._move(this._startEvent)}redo(){this._move((0,r.ensureNotNull)(this._endEvent))}_move(e){const t=(0,r.ensureNotNull)(this._model.dataSourceForId(this._sourceId));(0,r.assert)(void 0!==t.moveItem,'The method "moveItem" is not defined'),t.moveItem&&t.moveItem(new ke.Point(e.localX,e.localY),this._itemIndex,new Ne.EnvironmentState(e))}}var lr=i(181728),cr=i(778016);class dr extends Vt.UndoCommand{constructor(e,t,i,s,o,r,n,a,l,c,d,h,u){super(u),this._paneState=null,this._lastInsertionStartPromise=null,this._additionalStudiesIds=[],this._chartModel=e,this._studyMetaInfo=t,this._props=s,this._addAsOverlay=o,this._parentIds=r.map((e=>e.id())),this._inputs=i,this._targetZOrder=d,this._preferredPriceScale=n,this._allowChangeCurrency=a,this._allowChangeUnit=l,this._paneSize=c,this._studyId=null!=h?h:null}redo(){const e=this._parentIds.map((e=>this._chartModel.dataSourceForId(e))),t=this._chartModel.insertStudyWithParams(this._studyMetaInfo,this._inputs,this._targetZOrder,this._props,this._addAsOverlay,e,this._preferredPriceScale,this._allowChangeCurrency,this._allowChangeUnit,this._paneSize,null===this._studyId?void 0:this._studyId),i=t.study;if((0,q.isFundamentalStudy)(i))this._createCopiesOfNewFundamentalForAllStocks(i);else if((0,Uo.isSymbolSource)(i)){null!==i.symbolInfo()?this._createCopiesOfExistingFundamentalsForNewStock(i):i.symbolResolved().subscribe(this,(()=>this._createCopiesOfExistingFundamentalsForNewStock(i)),!0)}if(this._lastInsertionStartPromise=t.startPromise,this._studyId=i.id(),i.childStudyByRebind().subscribe(null,(()=>(0,u.trackEvent)("SOS","Apply SOS","Rebind SOS"))),hs(i,"add"),this._chartModel.setShouldBeSavedEvenIfHidden(!0),null!==this._paneState){(0,r.ensureNotNull)(this._chartModel.paneForSource(i)).restoreState({state:this._paneState,withData:!1,version:this._chartModel.version()}),this._paneState=null}}undo(){const e=(0,r.ensureNotNull)(this._chartModel.dataSourceForId((0,r.ensureNotNull)(this._studyId)));(0,Uo.isSymbolSource)(e)&&e.symbolResolved().unsubscribeAll(this);const t=(0,r.ensureNotNull)(this._chartModel.paneForSource(e)).state();this._additionalStudiesIds.forEach((e=>{const t=(0,r.ensureNotNull)(this._chartModel.dataSourceForId(e));this._chartModel.removeSource(t)})),this._additionalStudiesIds=[],this._chartModel.removeSource(e)&&(this._paneState=t)}insertedStudy(){ return this._chartModel.dataSourceForId((0,r.ensureNotNull)(this._studyId))}lastInsertionStartPromise(){var e;return null!==(e=this._lastInsertionStartPromise)&&void 0!==e?e:Promise.resolve()}_createCopiesOfNewFundamentalForAllStocks(e){let t=(0,r.ensureNotNull)((0,cr.getConfig)("FUNDAMENTALS_ON_CHART")).limit-this._chartModel.chartApi().getFundamentalCounter();e.isStarted()||(t-=1);const i=this._studyMetaInfo.symbolInputId(),s=this._chartModel.symbolSources();for(const o of s){if(t<=0)break;if(!o.isVisible()||o===e.symbolSource())continue;const s=o.symbolInfo();if(null!==s&&(0,lr.isStockSymbol)(s.type,s.typespecs)){const e={};e[(0,r.ensureNotNull)(i)]=o.symbol();const s=this._chartModel.insertStudyWithParams(this._studyMetaInfo,e,null,this._props,!1);this._additionalStudiesIds.push(s.study.id()),t-=1}}}_createCopiesOfExistingFundamentalsForNewStock(e){let t=(0,r.ensureNotNull)((0,cr.getConfig)("FUNDAMENTALS_ON_CHART")).limit-this._chartModel.chartApi().getFundamentalCounter();const i=e.symbolInfo();if(null!==i&&(0,lr.isStockSymbol)(i.type,i.typespecs)){const i=new Set,s=this._chartModel.allStudies(!0).filter((e=>(0,q.isFundamentalStudy)(e)&&e.isVisible()));for(const o of s){if(t<=0)break;const s=o.metaInfo();if(!i.has(s.fullId)){const o={};o[(0,r.ensureNotNull)(s.symbolInputId())]=e.symbol();const n=this._chartModel.insertStudyWithParams(s,o,null,this._props,!1);this._additionalStudiesIds.push(n.study.id()),t-=1,i.add(s.fullId)}}}}}class hr extends Vt.UndoCommand{constructor(e,t,i,s){super(i),this._newMode=e,this._priceScaleId=t.id(),this._model=s,this._oldMode=t.mode()}redo(){this._applyMode(this._newMode)}undo(){this._applyMode(this._oldMode)}_applyMode(e){const t=this._findPriceScaleById();null!==t&&((0,co.allowSavingDefaults)(!0),t.setMode(e),(0,co.allowSavingDefaults)(!1),this._model&&(this._model.recalculateAllPanes((0,ni.viewportChangeEvent)()),this._model.lightUpdate()))}_findPriceScaleById(){const e=this._model.panes();for(let t=0;t(0,P.isStudyInputDependsOnChart)({id:e})))&&(0,Er.patchPropertiesAsync)(this._study.properties(),this._study.metaInfo(),e)}}}var Nr=i(395098),Rr=i(42292);function Or(e){const{visible:t,...i}=e;return i}function Vr(e){const{visible:t,...i}=e;return i}function Wr(e){const{drawWick:t,drawBorder:i,drawBody:s,barColorsOnPrevClose:o,...r}=e;return r}function Fr(e){const{drawWick:t,drawBorder:i,drawBody:s,...o}=e;return o}function Hr(e){ const{drawWick:t,drawBorder:i,drawBody:s,showRealLastPrice:o,inputs:r,...n}=e;return n}function zr(e){const{barColorsOnPrevClose:t,dontDrawOpen:i,thinBars:s,...o}=e;return o}function Ur(e){const{showBorders:t,showLabels:i,drawBody:s,...o}=e;return o}function Gr(e){const{linestyle:t,linewidth:i,priceSource:s,...o}=e;return o}function qr(e){const{linestyle:t,linewidth:i,priceSource:s,...o}=e;return o}function jr(e){const{inputs:t,...i}=e;return i}function Zr(e){const{inputs:t,...i}=e;return i}function Kr(e){const{inputs:t,...i}=e;return i}function Yr(e){const{inputs:t,...i}=e;return i}function $r(e){const{topLineWidth:t,bottomLineWidth:i,baseLevelPercentage:s,priceSource:o,...r}=e;return r}function Xr(e){const{thinBars:t,inputs:i,...s}=e;return s}function Jr(e){return{bgColors:e.bgColors}}function Qr(e){return{color:e.color,tpo:{colors:e.tpo.colors},volumeProfile:{valuesColor:e.volumeProfile.valuesColor,volumeColor:e.volumeProfile.volumeColor,valueAreaColor:e.volumeProfile.valueAreaColor,vah:{color:e.volumeProfile.vah.color},val:{color:e.volumeProfile.val.color},poc:{color:e.volumeProfile.poc.color}}}}function en(e){const{volumeProfile:{valuesColor:t,volumeColorUp:i,volumeColorDown:s,valueAreaColorUp:o,valueAreaColorDown:r,histogramBoxColor:n}}=e;return{volumeProfile:{valuesColor:t,volumeColorUp:i,volumeColorDown:s,valueAreaColorUp:o,valueAreaColorDown:r,histogramBoxColor:n},vah:{color:e.vah.color},val:{color:e.val.color},poc:{color:e.poc.color},developingPoc:{color:e.developingPoc.color},developingVA:{color:e.developingVA.color}}}function tn(e){const{visible:t,style:i,symbol:s,interval:o,sessionId:r,highLowAvgPrice:n,showCountdown:a,bidAsk:l,prePostMarket:c,priceAxisProperties:d,candleStyle:h,volCandlesStyle:u,hollowCandleStyle:_,haStyle:p,barStyle:m,hiloStyle:g,lineStyle:S,lineWithMarkersStyle:v,steplineStyle:f,areaStyle:b,renkoStyle:y,pbStyle:C,kagiStyle:w,pnfStyle:P,baselineStyle:T,rangeStyle:M,volFootprintStyle:x,tpoStyle:I,svpStyle:A,esdShowDividends:L,esdShowSplits:k,esdShowEarnings:E,esdShowBreaks:D,showContinuousContractSwitches:B,showContinuousContractSwitchesBreaks:N,showFuturesContractExpiration:R,showLastNews:O,...V}=e;return{bidAsk:Or(l),prePostMarket:Vr(c),candleStyle:Wr(h),hollowCandleStyle:Fr(_),haStyle:Hr(p),barStyle:zr(m),hiloStyle:Ur(g),lineStyle:Gr(S),lineWithMarkersStyle:Gr(v),steplineStyle:Gr(f),areaStyle:qr(b),renkoStyle:jr(y),pbStyle:Zr(C),kagiStyle:Kr(w),pnfStyle:Yr(P),baselineStyle:$r(T),rangeStyle:Xr(M),volFootprintStyle:Jr(x),tpoStyle:Qr(I),svpStyle:en(A),volCandlesStyle:Wr(u),...V}}function sn(e){const{scaleSeriesOnly:t,showSeriesLastValue:i,showStudyLastValue:s,showSymbolLabels:o,showBidAskLabels:r,showPrePostMarketPriceLabel:n,showStudyPlotLabels:a,showFundamentalNameLabel:l,showFundamentalLastValue:c,seriesLastValueMode:d,...h}=e;return h}function on(e){const{topMargin:t,bottomMargin:i,...s}=e;return s}const rn=new R.TranslatedString("apply chart theme",a.t(null,void 0,i(766568)));class nn extends Vt.UndoCommand{constructor(e,t,i){var s,o,r;super(rn),this._model=e, this._newSessionProps=t.sessions||(0,Rr.factoryDefaults)("sessions"),["candleStyle","hollowCandleStyle","haStyle"].forEach((e=>{t.mainSourceProperties[e].wickUpColor=t.mainSourceProperties[e].wickUpColor||t.mainSourceProperties[e].wickColor,t.mainSourceProperties[e].wickDownColor=t.mainSourceProperties[e].wickDownColor||t.mainSourceProperties[e].wickColor})),t.chartProperties=null!==(s=t.chartProperties)&&void 0!==s?s:{paneProperties:{},scalesProperties:void 0},t.chartProperties.paneProperties.vertGridProperties=null!==(o=t.chartProperties.paneProperties.vertGridProperties)&&void 0!==o?o:t.chartProperties.paneProperties.gridProperties,t.chartProperties.paneProperties.horzGridProperties=null!==(r=t.chartProperties.paneProperties.horzGridProperties)&&void 0!==r?r:t.chartProperties.paneProperties.gridProperties;const n=this._model.properties().state().paneProperties.legendProperties;delete n.backgroundTransparency,t.chartProperties.paneProperties.legendProperties={...t.chartProperties.paneProperties.legendProperties,...n};const a=(0,Rr.factoryDefaults)("chartproperties"),l=(0,Ee.deepExtend)({},a,t.chartProperties);this._newChartProps={paneProperties:on(l.paneProperties),scalesProperties:sn(l.scalesProperties)},e.timeScale().preserveBarSpacing()&&delete this._newChartProps.scalesProperties.barSpacing;const c=(0,Rr.factoryDefaults)("chartproperties.mainSeriesProperties"),d=(0,Ee.deepExtend)({},c,t.mainSourceProperties);this._newSeriesProps=i?d:tn(d);const h=e.properties().state();this._oldChartProps={paneProperties:on(h.paneProperties),scalesProperties:sn(h.scalesProperties)};const u=e.mainSeries().properties().state();this._oldSeriesProps=i?u:tn(u),this._oldSessionProps=this._model.sessions().properties().state()}undo(){this._merge(this._oldChartProps,this._oldSeriesProps,this._oldSessionProps),this._model.mainSeries().onChartStyleChanged(),this._model.updateScales(),this._model.chartThemeLoaded()}redo(){this._merge(this._newChartProps,this._newSeriesProps,this._newSessionProps),this._model.mainSeries().onChartStyleChanged(),this._model.updateScales(),this._model.chartThemeLoaded()}_merge(e,t,i){var s,o,r,n;const a=this._model;(0,co.allowSavingDefaults)(!0),e&&(a.properties().childs().paneProperties.mergeAndFire(e.paneProperties),a.properties().childs().scalesProperties.mergeAndFire(e.scalesProperties)),"priceAxisProperties"in t&&a.mainSeries().priceScale().setMode({autoScale:null===(s=t.priceAxisProperties)||void 0===s?void 0:s.autoScale,percentage:null===(o=t.priceAxisProperties)||void 0===o?void 0:o.percentage,log:null===(r=t.priceAxisProperties)||void 0===r?void 0:r.log,lockScale:null===(n=t.priceAxisProperties)||void 0===n?void 0:n.lockScale}),a.mainSeries().properties().mergeAndFire(t),a.mainSeries().properties().updateThemedColors(),a.mainSeries().properties().saveDefaults(),a.mainSeries().createPaneView(),a.mainSeries().invalidateBarStylesCache(),a.recalculateAllPanes((0,ni.globalChangeEvent)()),a.fullUpdate(),a.properties().saveDefaults(),a.sessions().restoreState({properties:i},!1),(0, co.allowSavingDefaults)(!1)}}const an=new R.TranslatedString("change resolution",a.t(null,void 0,i(932303)));class ln extends Qo{constructor(e,t,i){super(an,e,function(e,t){let i;const s=(0,oe.isRangeStyle)(e.style()),o=zi.Interval.isRange(t);return!s&&o?i=11:s&&!o&&(i=(0,oe.getLastUsedStyle)()),{interval:t,style:i}}(e,t),i),this._resolution=t}canMerge(e){return e instanceof ln&&e._resolution===this._resolution&&super.canMerge(e)}_showFade(e,t){return!0}}var cn=i(993713);class dn extends cn.SetWatchedValueCommand{constructor(){super(...arguments),this._firstRedo=!0}redo(){this._firstRedo||(0,Jo.muteLinkingGroup)(this._newValue,!0),(0,Jo.muteLinkingGroup)(this._oldValue,!0),super.redo(),this._firstRedo||(0,Jo.muteLinkingGroup)(this._newValue,!1),(0,Jo.muteLinkingGroup)(this._oldValue,!1),this._firstRedo=!1}undo(){(0,Jo.muteLinkingGroup)(this._newValue,!0),(0,Jo.muteLinkingGroup)(this._oldValue,!0),super.undo(),(0,Jo.muteLinkingGroup)(this._newValue,!1),(0,Jo.muteLinkingGroup)(this._oldValue,!1)}}var hn=i(849245),un=i(832733);class _n extends Vt.UndoCommand{constructor(e,t,i){super(i),this._chartModel=e,this._stubDescriptor=(0,r.ensureNotNull)(t.getDescriptor())}redo(){this._chartModel.dataSourceForId(this._stubDescriptor.id)||this._chartModel.restoreStudyStub(this._stubDescriptor)}undo(){this._chartModel.removeStudyStub(this._stubDescriptor.id)}}class pn extends Vt.UndoCommand{constructor(e,t,i){super(i,void 0,!cs.lineToolsDoNotAffectChartInvalidation),this._source=e,this._newState=t,this._oldState=e.properties().state()}redo(){this._source.applyTemplate(this._newState)}undo(){this._source.applyTemplate(this._oldState)}}var mn=i(155964),gn=i(992543),Sn=i(827023),vn=i(14952),fn=i(535503),bn=i(939702),yn=i(287790),Cn=i(690142),wn=i(440058),Pn=i(490515),Tn=i(939243),Mn=i(439016),xn=i(360758);const In=new R.TranslatedString("apply all chart properties",a.t(null,void 0,i(64034)));class An extends Vt.UndoCommand{constructor(e){super(In),this._trading=null,this._oldShowSellBuyButtons=null,this._oldNoConfirmEnabled=null,this._oldShowOnlyRejectionNotifications=null,this._oldShowPricesWithZeroVolume=null,this._oldShowPricesWithSpread=null,this._oldOrderExecutedSoundEnabled=null,this._prevWatermarkPreferences=null,this._prevAlertPreferences=null,this._model=e,this._trading=(0,Mn.tradingService)(),null!==this._trading&&(this._oldShowSellBuyButtons=this._trading.showSellBuyButtons.value(),this._oldNoConfirmEnabled=this._trading.noConfirmEnabled.value(),this._oldShowOnlyRejectionNotifications=this._trading.showOnlyRejectionNotifications.value(),this._oldShowPricesWithZeroVolume=this._trading.showPricesWith().zeroVolume.value(),this._oldShowPricesWithSpread=this._trading.showPricesWith().spread.value(),this._oldOrderExecutedSoundEnabled=this._trading.orderExecutedSoundParams.enabled.value()),this._defaultsPreferences=(0,mn.defaultsPreferencesByWhiteList)(this._model,this._model.mainSeries()),this._oldPreferences=e.preferences(),this._prevDateFormat=gn.dateFormatProperty.value(),this._prevAlertPreferences=(0, Tn.getSettingsProperty)().state(),this._model.onWidget()||(this._prevWithWeekday=Cn.withWeekdayProperty.value()),this._prevTimeHoursFormat=Sn.timeHoursFormatProperty.value(),this._prevAddPlusButton=xn.addPlusButtonProperty.value(),this._prevShowOpenMarkerStatus=vn.showMarketOpenStatusProperty.value(),this._prevCurrencyUnitVisibility=(0,dt.currencyUnitVisibilityProperty)().value(),this._prevAutoLogButtonsVisibility=(0,ht.autoLogButtonsVisibilityProperty)().value(),this._prevNavigationButtonsVisibility=(0,fn.property)().value(),this._prevPaneButtonsVisibility=(0,bn.property)().value();const t=this._model.watermarkSource();null!==t&&(this._prevWatermarkPreferences=t.properties().state())}redo(){var e,t,i;null!==this._trading&&(this._trading.showSellBuyButtons.setValue(!0),this._trading.noConfirmEnabled.setValue(!1),this._trading.showOnlyRejectionNotifications.setValue(!1),this._trading.showPricesWith().zeroVolume.setValue(!0),this._trading.showPricesWith().spread.setValue(!0),this._trading.orderExecutedSoundParams.enabled.setValue(!1)),(0,Oo.default)(this._defaultsPreferences,{mainSeries:{volFootprintStyle:{bgColors:(0,Pn.getBgColorsDefaults)()}}}),"Auto"===(null===(i=null===(t=null===(e=this._defaultsPreferences.mainSeries)||void 0===e?void 0:e.tpoStyle)||void 0===t?void 0:t.inputs)||void 0===i?void 0:i.rowSize)&&delete this._defaultsPreferences.mainSeries.tpoStyle.inputs.ticksPerRow,this._model.applyPreferences(this._defaultsPreferences),this._model.updateScales(),(0,gn.restoreDateFormatSettingsValue)(),(0,Sn.restoreTimeHoursFormatSettingsValue)(),(0,xn.restoreAddPlusButtonSettingsValue)(),(0,vn.restoreShowMarketOpenStatusProperty)(),(0,dt.restoreCurrencyUnitVisibilitySettingsValue)(),(0,ht.restoreAutoLogButtonsVisibilitySettingsValue)(),(0,fn.restoreNavigationButtonsVisibilitySettingsValue)(),(0,bn.restorePaneButtonsVisibilitySettingsValue)(),(0,Cn.restoreWithWeekdaySettingsValue)(),(0,wn.restoreShowOnScreenshotSettingsValue)(),(0,yn.restoreShowNewsNotificationSettingsValue)(),(0,Tn.restoreSettingsProperty)();const s=this._model.watermarkSource();null!==s&&s.restorePropertiesDefaults()}undo(){null!==this._trading&&(this._trading.showSellBuyButtons.setValue((0,r.ensureNotNull)(this._oldShowSellBuyButtons)),this._trading.noConfirmEnabled.setValue((0,r.ensureNotNull)(this._oldNoConfirmEnabled)),this._trading.showOnlyRejectionNotifications.setValue((0,r.ensureNotNull)(this._oldShowOnlyRejectionNotifications)),this._trading.showPricesWith().zeroVolume.setValue((0,r.ensureNotNull)(this._oldShowPricesWithZeroVolume)),this._trading.showPricesWith().spread.setValue((0,r.ensureNotNull)(this._oldShowPricesWithSpread)),this._trading.orderExecutedSoundParams.enabled.setValue((0,r.ensureNotNull)(this._oldOrderExecutedSoundEnabled))),this._model.applyPreferences(this._oldPreferences),this._model.updateScales(),gn.dateFormatProperty.setValue(this._prevDateFormat),Sn.timeHoursFormatProperty.setValue(this._prevTimeHoursFormat),vn.showMarketOpenStatusProperty.setValue(this._prevShowOpenMarkerStatus), xn.addPlusButtonProperty.setValue(this._prevAddPlusButton),(0,dt.currencyUnitVisibilityProperty)().setValue(this._prevCurrencyUnitVisibility),(0,ht.autoLogButtonsVisibilityProperty)().setValue(this._prevAutoLogButtonsVisibility),(0,fn.property)().setValue(this._prevNavigationButtonsVisibility),(0,bn.property)().setValue(this._prevPaneButtonsVisibility),null!==this._prevAlertPreferences&&(0,Tn.getSettingsProperty)().mergeAndFire(this._prevAlertPreferences),this._model.onWidget()||Cn.withWeekdayProperty.setValue(this._prevWithWeekday);const e=this._model.watermarkSource();null!==e&&null!==this._prevWatermarkPreferences&&e.properties().mergeAndFire(this._prevWatermarkPreferences)}}class Ln extends Vt.UndoCommand{constructor(e,t,i,s){super(i),this._property=e,this._newValue=t,this._model=s,this._priceScale=this._model.mainSeries().priceScale(),this._oldValue=this._property.value(),this._oldMode=this._priceScale.mode()}redo(){this._oldValue=this._property.value(),this._oldMode=this._priceScale.mode(),(0,co.allowSavingDefaults)(!0),this._priceScale.setMode({autoScale:!1,percentage:!1,log:!1}),this._property.setValue(this._newValue),(0,co.allowSavingDefaults)(!1),this._model.recalculateAllPanes((0,ni.viewportChangeEvent)()),this._model.lightUpdate()}undo(){(0,co.allowSavingDefaults)(!0),this._property.setValue(this._oldValue),this._priceScale.setMode(this._oldMode),(0,co.allowSavingDefaults)(!1),this._model.recalculateAllPanes((0,ni.viewportChangeEvent)()),this._model.lightUpdate()}}var kn=i(116193);class En extends Vt.UndoCommand{constructor(e,t){var s,o;super(new R.TranslatedString("apply all chart properties",a.t(null,void 0,i(64034)))),this._model=e,this._newProperties=t,s=(0,r.ensureDefined)(this._newProperties.mainSeries),o=(0,r.ensureDefined)(this._newProperties.paneProperties),["candleStyle","hollowCandleStyle","haStyle"].forEach((e=>{const t=s[e];void 0!==t&&(t.wickUpColor=t.wickUpColor||t.wickColor,t.wickDownColor=t.wickDownColor||t.wickColor)})),o.vertGridProperties=o.vertGridProperties||(0,kn.default)(o.gridProperties),o.horzGridProperties=o.horzGridProperties||(0,kn.default)(o.gridProperties),void 0===s.hollowCandleStyle&&(s.hollowCandleStyle=(0,kn.default)(s.candleStyle)),this._oldProperties=(0,mn.preferencesByWhiteList)(e,e.mainSeries())}redo(){this._merge(this._newProperties),this._model.mainSeries().onChartStyleChanged(),this._model.updateScales()}undo(){this._merge(this._oldProperties),this._model.mainSeries().onChartStyleChanged(),this._model.updateScales()}_merge(e){(0,co.allowSavingDefaults)(!0),this._model.applyPreferences(e),(0,co.allowSavingDefaults)(!1)}}var Dn=i(944876);class Bn{constructor(e){this._leftScales=e.leftPriceScales().map((e=>e.id())),this._rightScales=e.rightPriceScales().map((e=>e.id()))}restorePane(e){this._leftScales.reverse().map((t=>(0,r.ensureNotNull)(e.getPriceScaleById(t)))).forEach((t=>e.movePriceScale(t,"left"))),this._rightScales.reverse().map((t=>(0,r.ensureNotNull)(e.getPriceScaleById(t)))).forEach((t=>e.movePriceScale(t,"right")))}}class Nn extends Vt.UndoCommand{ constructor(e,t,i){super(i),this._chartModel=e,this._targetStrategy=(0,Dn.createPriceScaleSelectionStrategy)(t),this._initialState=e.panes().map((e=>new Bn(e)))}redo(){this._chartModel.panes().forEach((e=>e.setPriceScaleSelectionStrategy(this._targetStrategy))),this._chartModel.fullUpdate()}undo(){const e=this._chartModel.panes();for(let t=0;t{this._undoHistory.beginUndoMacro(e)},endUndoMacro:this._undoHistory.endUndoMacro.bind(this._undoHistory),emitEvent:this.emitEvent.bind(this)})}id(){return this._model().id()}undoHistory(){return this._undoHistory}setWatchedValue(e,t,i){this._undoHistory.setWatchedValue(e,t,i)}lineToolsGroupController(){return this._lineToolsGroupController}mergeAllScales(e){!function(e,t){e.beginUndoMacro("left"===t?rs:ns),e.model().panes().forEach((i=>{const s="left"===t?i.rightPriceScales():i.leftPriceScales(),o=("left"===t?i.leftPriceScales():i.rightPriceScales()).concat(s),r="overlay"===i.priceScalePosition(i.defaultPriceScale())?o[0]:i.defaultPriceScale();e.movePriceScale(i,r,t,0),o.forEach((t=>{if(t===r)return;let s=t.mainSource();for(;null!==s;){e.moveToScale(s,i,r,null,!0);const o=t.mainSource();if(o===s){as.logError("Loop detected while trying to merge scales");break}s=o}}))})),e.endUndoMacro(),e.model().fullUpdate()}(this,e)}movePriceScale(e,t,i,s){const o=new ls(this._model(),e,t,i,s,Gn);this._pushUndoCommand(o)}createLineTool({pane:e,point:t,linetool:i,properties:s,linkKey:o,ownerSource:n,disableSynchronization:a,sharingMode:l=Va(),id:c}){const d=un.lineToolsStudyIds[i];if((0,r.assert)(!(0,Qt.isStudyLineToolName)(d)||!!d),d){const e=this.canCreateStudy({id:d});if(!e.success)return Wa(this.model(),e),(0,Qt.isStudyLineToolName)(Oe.tool.value())&&(0,Oe.resetToCursor)(),null}const h=_a.format({tool:new R.TranslatedString(i,Ns.lineToolsLocalizedNames[i])});this.beginUndoMacro(h);const u=!a;this._createLineCommand=new Os({model:this._model(),pane:e,lineTool:i,ownerSource:n||(0,r.ensureNotNull)(e.mainDataSource()),drawOnAllChartsMode:l,id:c});const _=this._createLineCommand.startCreatingLine(t,s,o||null,l,a),p=(0,r.ensureNotNull)(this._createLineCommand.line());let m=null;if(_&&(u&&this.finishLineTool(p), this._pushUndoCommand(this._createLineCommand),this._createLineCommand=null,m={points:p.normalizedPoints(),interval:this.mainSeries().interval()}),u&&void 0===o&&(0,Oe.drawOnAllCharts)().value()&&p.isSynchronizable()){const e=(0,r.ensureNotNull)(this.model().externalTimeStamp(t.index)),s={point:{price:t.price,timeStamp:e},linetool:i,properties:p.properties(),symbol:this.mainSeries().symbol(),model:this.model(),linkKey:(0,r.ensureNotNull)(p.linkKey().value()),finalState:m,id:p.id(),sharingMode:p.sharingMode().value()};p.isFixed()&&(s.pointPositionPercents=p.calcPositionPercents()),(0,Oe.createLineTool)(s)}return this.endUndoMacro(),p}continueCreatingLine(e,t,i,s){const o=(0,r.ensureNotNull)(this._createLineCommand);this.beginUndoMacro(o.text());const n=(0,r.ensureNotNull)(this._model().lineBeingCreated()),a=o.continueCreatingLine(e,t,i,s);let l=null;if(a&&(this.finishLineTool(n),this._pushUndoCommand(o),this._createLineCommand=null,l={points:n.normalizedPoints(),interval:this.mainSeries().interval()}),o.drawOnAllCharts()&&n.isSynchronizable()){const i=(0,r.ensureNotNull)(this._model().externalTimeStamp(e.index));(0,Oe.continueLineTool)({point:{price:e.price,timeStamp:i},envState:t,finalState:l,model:this._model()})}return this.endUndoMacro(),a}continueExternalLine(e,t,i){const s=(0,r.ensureNotNull)(this._createLineCommand),o=s.continueCreatingLine(e,t,i);return o&&(this._pushUndoCommand(s),this._createLineCommand=null),o}finishLineTool(e){this._model().finishLineTool(e)}cancelCreatingLine(){this.m_model.cancelCreatingLine()}lineBeingCreated(){return this.m_model.lineBeingCreated()}pasteImageAsLineTool(e,t,i,s){const o=this._model().timeScale(),n=o.width(),a=i.height(),l=i.defaultPriceScale(),c=(0,r.ensureNotNull)((0,r.ensureNotNull)(l.mainSource()).firstValue()),d={price:l.coordinateToPrice(a/2,c),index:o.coordinateToIndex(n/2)},h=(0,K.createLineToolProperties)("LineToolImage",void 0,this.model());void 0!==s&&h.childs().transparency.setValue(s);const u=(0,r.ensureNotNull)(l.mainSource());(0,K.prepareLineToolPropertiesByOwnerSource)(h,u);const _=this.createLineTool({pane:i,point:d,linetool:"LineToolImage",properties:h});return _&&(_.setBlobImageUrl(t),this.selectionMacro((e=>{e.clearSelection(),e.addSourceToSelection(_,null)})),e.then((e=>{_.properties().childs().url.setValue(e)})).catch((e=>{const t=_.linkKey().value(),i=this.model();null!==t&&(0,Oe.removeLineTool)({withUndo:!1,model:i,linkKey:t,symbol:_.symbol(),sourceTitle:new R.TranslatedString(_.name(),_.translatedType()),lineToolState:_.state(!1)}),i.removeSource(_)}))),_}loadRange(e){const t=this._model(),i=t.appliedTimeFrame().value();return(null===i||!Ui(i,e))&&(this._pushUndoCommand(new vo(t,e)),!0)}mainSeries(){return this.m_model.mainSeries()}model(){return this.m_model}publishedChartsTimelineSource(){return this.m_model.publishedChartsTimelineSource()}unlinkLines(e){const t=this.model();this.beginUndoMacro(qn);for(const i of e)null!==i.linkKey().value()&&(0,Oe.removeLineTool)({withUndo:!0,model:this.model(),symbol:i.symbol(),linkKey:(0, r.ensureNotNull)(i.linkKey().value()),sourceTitle:(0,Bs.getTranslatedStringForSource)(is.TitleDisplayTarget.StatusLine,i),lineToolState:i.state(!1),unlink:!0}),this._pushUndoCommand(new xr(t,i));this.endUndoMacro()}zoomFromViewport(){const e=new Tr((0,r.ensureDefined)(this._zoomStack.head()),this._zoomStack,!1);this._pushUndoCommand(e)}zoomToViewport(e,t,i,s,o){const r=new Cr(this.m_model,e,t,i,s,o),n=new Tr(r,this._zoomStack,!0);this._pushUndoCommand(n)}zoomStack(){return this._zoomStack}timeScale(){return this.m_model.timeScale()}selection(){return this.m_model.selection()}selectionMacro(e,t){return this.m_model.selectionMacro(e,t)}onSelectedSourceChanged(){return this.m_model.onSelectedSourceChanged()}onTagsChanged(){return this.m_model.onTagsChanged()}lineCancelled(){return this.m_model.lineCancelled()}hoveredSource(){return this.m_model.hoveredSource()}crossHairSource(){return this.m_model.crossHairSource()}activeStrategySource(){return this.m_model.activeStrategySource()}setProperty(e,t,i,s){if(e&&e.value()!==t){this.beginUndoMacro(i);const o=new mo(e,t,i,this.m_model,!s);this._pushUndoCommand(o),this.endUndoMacro(),this.emitEvent("setProperty")}}setProperties(e,t,i,s=!0){this.beginUndoMacro(i),this.m_model.selectionMacro((()=>{for(let o=0;o{this.startScaleTime(0),this.scaleTimeTo(e),this.endScaleTime()}}))}zoomIn(){const e=this.timeScale().width();this.canZoomIn()&&(this.changeTimeScale(Zn),(0,Zi.doAnimate)({to:e/5,onStep:e=>{this.startScaleTime(e),this.scaleTimeTo(0),this.endScaleTime()}}))}scrollChart(e){this.m_model.scrollEnabled()&&(this.startScrollTime(0),this.scrollTimeTo(e),this.endScrollTime())}startMovingSources(e,t,i,s){e.filter((e=>e.doesMovingAffectsUndo())).length&&(this._currentSourceMoveCommand=new ws(this.model(),e,Kn,!1)),this.model().startMovingSources(e,t,i,new Map,s)}moveSources(e,t){this.model().moveSources(e,new Map,t)}endMovingSource(e,t){this.model().endMovingSources(e,void 0,t),null!==this._currentSourceMoveCommand&&(this._currentSourceMoveCommand.saveNewState(),this._pushUndoCommand(this._currentSourceMoveCommand)),this._currentSourceMoveCommand=null}startChangingLinetool(e,t,i,s,o){this._currentLineChangeCommand=new ws(this.model(),[e],pa.format({pointIndex:i}),!1),this.model().startChangingLinetool(e,t,i,s,o)}changeLinePoint(e,t){this.model().changeLinePoint(e,t)}endChangingLinetool(e){this.model().endChangingLinetool(e),null!==this._currentLineChangeCommand&&(this._currentLineChangeCommand.saveNewState(),this._pushUndoCommand(this._currentLineChangeCommand)),this._currentLineChangeCommand=null}setChartStyleProperty(e,t,i){if(e.value()!==t){const s=fr.chartStylePermissions.get(t),o=()=>{this.beginUndoMacro(i);const s=new go(e,t,this.mainSeries(),i,this.model(),this._chartWidget);var o;this._pushUndoCommand(s),this.emitEvent("setChartStyleProperty"),o=e.value(),(0,Yt.getTracker)().then((e=>{if(null!==e){const t=fe.STYLE_SHORT_NAMES[o];e.trackChartStyle(t)}})),this.endUndoMacro()};s?(0,br.runOrGoPro)(o,s.feature,{feature:s.featureName}):o()}}setPriceAutoScale(e,t,i){this._pushUndoCommand(new Ut(this.m_model,e,t,t.state())),this.m_model.setPriceAutoScale(e,t,i)}setPriceScaleMode(e,t,i){if(!(0,Ae.default)(t.mode(),e)){const s=new hr(e,t,i,this.m_model);this._pushUndoCommand(s)}}setPriceScaleSelectionStrategy(e){if(this.m_model.properties().priceScaleSelectionStrategyName.value()===e)return;(0,u.trackEvent)("Chart","Change PriceScale Selection Strategy");const t=xa.format({title:e});this.beginUndoMacro(t),this.setProperty(this.m_model.properties().priceScaleSelectionStrategyName,e,t);const i=new Nn(this.m_model,e,t);this._pushUndoCommand(i),this.endUndoMacro()}setScaleRatioProperty(e,t,i){if(e.value()!==t){const s=new Ln(e,t,i,this.m_model);this._pushUndoCommand(s)}}createUndoCheckpoint(){return this._undoHistory.createUndoCheckpoint()}undoToCheckpoint(e){this._undoHistory.undoToCheckpoint(e)}restorePropertiesForSource(e){(0,K.isLineTool)(e)?this._restoreLineToolFactoryDefaults(e):this._restoreStudyFactoryDefaults(e)}restoreLineToolsFactoryDefaults(e){1===e.length?this._restoreLineToolFactoryDefaults(e[0]):(this.beginUndoMacro($n),e.forEach((e=>this._restoreLineToolFactoryDefaults(e))),this.endUndoMacro())}restorePreferences(){ const e=new An(this.model());this._pushUndoCommand(e)}restoreState(e,t,i){return this.m_model.restoreState(e,t,i)}async clipboardCopy(e,t=this.selection().dataSources()){if(!(0,D.enabled)("datasource_copypaste"))return;const i=t.filter((e=>e.copiable()));if(0===i.length)return;for(const e of i)if((0,q.isStudy)(e)&&e.isChildStudy())throw new Error("Can not copy child study");const s=(0,ji.clipboardDataForSources)(this._model().id(),i);return null!==s?e.write({app:JSON.stringify(s),text:s.title}):void 0}async clipboardCut(e,t=this.selection().dataSources()){if(!(0,D.enabled)("datasource_copypaste"))return;const i=t.filter((e=>e.copiable()));if(0===i.length)return;await this.clipboardCopy(e,i);const s=i.filter((e=>e.isUserDeletable()));if(0===s.length)return;const o=(1===s.length?Fn:Hn).format({title:(0,Bs.getTranslatedStringForSource)(is.TitleDisplayTarget.StatusLine,s[0])});this.beginUndoMacro(o),this.m_model.selectionMacro((()=>this.removeSources(s,!1,o)),!0),this.endUndoMacro()}async clipboardPaste(e,t){let i=null;if((0,D.enabled)("datasource_copypaste")&&(i=i||await e.read(),i.app)){const e=JSON.parse(i.app);if(null!==await this.pasteSourceFromClip(t,e))return}await this._processSpecialLineToolsContents(e,i,t)}applyStudyTemplate(e,t){const i=new zo(this._model(),e,t);this._pushUndoCommand(i),(0,l.emit)("load_study_template")}createStudyInserter(e,t,i={}){const{stubTitle:s,isOverlay:o}=i,r={createStudy:(e,t,i,s,o,r,n,a,c,d,h,_)=>{if(!this.checkIfFeatureAvailable(e,n))return Na.logNormal("Cannot insert study "+e.id),null;(0,u.trackEvent)("studies","Study_"+e.id),"Compare@tv-basicstudies"===e.id&&(0,u.trackEvent)("compare","symbol:"+t.symbol),s&&this.m_model.removeSource(s);const p=this._insertStudy(e,t,o,r,n,a,c,d,h,null,_);return(0,l.emit)("study_event",p.study.id(),"create"),p},storeFailedStub:e=>{this._storeFailedStub(e)}};void 0!==s&&(r.createStub=()=>this.m_model.insertStudyStub(s,o).id(),r.removeStub=e=>this.m_model.removeStudyStub(e));const n=new hn.StudyInserter(e,r);return n.setParentSources(t),n}applyLineToolTemplate(e,t,i){this.beginUndoMacro(i),this.saveLineToolState(e,i);const s=new pn(e,t,i);this._pushUndoCommand(s),this.saveLineToolState(e,i),this.endUndoMacro(),this.model().updateSource(e)}replayStatus(){return this.m_model.replayStatus()}setReplayStatus(e){return this.m_model.setReplayStatus(e)}isInReplay(){return this.m_model.isInReplay()}getSymbolString(){return this.m_model.getSymbolString()}interval(){return this.m_model.interval()}onInReplayStateChanged(){return this.m_model.onInReplayStateChanged()}switchToReplay(e,t){this._undoHistory.clearStack(),this.m_model.switchToReplay(e,t)}switchToRealtime(){this._undoHistory.clearStack(),this.m_model.switchToRealtime()}async canChangeResolution(e){return this.model().canChangeResolution(e)}startCustomMoving(e,t,i){this._currentCustomMoveCommand=new ar(this.model(),e,t,i)}customMoveBeingProcessed(){return null!==this._currentCustomMoveCommand}processCustomMove(e){(0,r.ensureNotNull)(this._currentCustomMoveCommand).move(e)}endCustomMoving(){ null!==this._currentCustomMoveCommand&&this._currentCustomMoveCommand.hasChanges()&&(this._pushUndoCommand(this._currentCustomMoveCommand),this._currentCustomMoveCommand=null)}state(e,t,i,s){return this.m_model.state(e,t,i,s)}panes(){return this.m_model.panes()}cloneLineTools(e,t){for(let t=0;t(0,r.ensureNotNull)(this.model().dataSourceForId(e)))).filter((e=>0!==e.sharingMode().value()));return s.length&&this._model().copyToOtherCharts(s,!0),this.endUndoMacro(),this.emitEvent("cloneLineTools"),i.newIds()}removeSource(e,t,i){this.lineBeingCreated()!==e?this.removeSources([e],t,zn.format({title:(0,Bs.getTranslatedStringForSource)(is.TitleDisplayTarget.StatusLine,e)}),i):this.cancelCreatingLine()}removeSelectedSources(){const e=this._model().selection().dataSources();if(!e.length)return;const t=(e.length>1?Un:zn).format({title:(0,Bs.getTranslatedStringForSource)(is.TitleDisplayTarget.StatusLine,e[0])});this.removeSources(e,!1,t)}removeSources(e,t,i,s){s||(e=e.filter((e=>e.isUserDeletable())));const o=this._model(),n=o.lineToolsGroupModel();this.beginUndoMacro(i),o.selectionMacro((s=>{const a=new Map;e.forEach((e=>{if((0,K.isLineTool)(e)){const t=n.groupForLineTool(e);if(null!==t){const i=a.get(t)||[];i.push(e),a.set(t,i)}null!==e.linkKey().value()&&(0,Oe.removeLineTool)({withUndo:!0,model:this.model(),linkKey:(0,r.ensureNotNull)(e.linkKey().value()),symbol:this.model().mainSeries().symbol(),lineToolState:e.state(!1),sourceTitle:(0,Bs.getTranslatedStringForSource)(is.TitleDisplayTarget.StatusLine,e)})}}));const l=new Cs(o,e,i),c=l.removedIds();this._pushUndoCommand(l),!t&&c.length>0&&(1===c.length?this.emitEvent("removeSource",[c[0]]):this.emitEvent("removeSources",[c]))}),!0),this.endUndoMacro()}async scrollToLineTool(e){const t=this.timeScale().logicalRange();if(null===t)return;const i=e.points().map((e=>e.index)),s=this.timeScale().points().range().value();if(null===s)return;let o=s.firstIndex;const n=s.lastIndex,a=t.length()/2;if(0===i.length||i.some((e=>t.contains(e))))return;const l=()=>{const t=e.points().map((e=>e.index)),i=t.filter((e=>e<=n)).reduce(((e,t)=>null===e?t:Math.max(e,t)),null);return null!==i?i:t.reduce(((e,t)=>Math.min(e,t)))};let c=l();if(o-a>c){const t=e.points().map((e=>e.time)).filter(w.notUndefined).map((e=>1e3*e));if(0===t.length)return;const i=t.reduce(((e,t)=>Math.min(e,t)),t[0]);await this.model().gotoTime(i),c=l();if((0,r.ensureNotNull)(this.timeScale().logicalRange()).contains(c))return;o=(0,r.ensureNotNull)(this.timeScale().points().range().value()).firstIndex}o-a>c&&this.mainSeries().setGotoDateResult({timestamp:(0,r.ensureNotNull)(this.timeScale().points().valueAt(o)),eod:!0});const d=this.timeScale().width()/2,h=this.timeScale().indexToCoordinate(c);this.model().stopTimeScaleAnimation(),this.model().setTimeScaleAnimation(new qi.Animation({from:0,to:d-h,duration:Wi.dur,easing:Wi.easingFunc.easeInOutCubic}))}mergeSourceUp(e){ const t=new Ls(this._model(),e,ea);this._mergeUnmergeSource(e,t)}mergeSourceDown(e){const t=new ks(this._model(),e,ta);this._mergeUnmergeSource(e,t)}mergeToPane(e,t,i){const s=this._model().panes().indexOf(t),o=new Es(this._model(),e,s,ia,i);this._mergeUnmergeSource(e,o)}unmergeSourceUp(e){const t=new xs(this._model(),e,sa);this._mergeUnmergeSource(e,t)}unmergeSourceDown(e){const t=new Ms(this._model(),e,oa);this._mergeUnmergeSource(e,t)}unmergeToNewBottomPane(e){const t=new Is(this._model(),e,ra);this._mergeUnmergeSource(e,t)}moveLeft(){this.beginUndoMacro(Ta),(0,Zi.doAnimate)({to:this.m_model.timeScale().width()/5,onStep:e=>{this.startScrollTime(e),this.scrollTimeTo(0),this.endScrollTime()},onComplete:()=>{this.endUndoMacro()}})}moveRight(){this.beginUndoMacro(Ma),(0,Zi.doAnimate)({to:this.m_model.timeScale().width()/5,onStep:e=>{this.startScrollTime(0),this.scrollTimeTo(e),this.endScrollTime()},onComplete:()=>{this.endUndoMacro()}})}availableZOrderOperations(e){const t=this._model().lineToolsGroupModel(),i=e.filter(K.isLineTool),s=i.map((e=>t.groupForLineTool(e)));(0,r.assert)(new Set(s).size<=1,"Cannot move line tools from different group");const o=0===s.length?null:s[0];let n={bringForwardEnabled:!1,bringToFrontEnabled:!1,sendBackwardEnabled:!1,sendToBackEnabled:!1};const a=new Set(i);for(const t of(0,Ds.sortSources)(e)){if((0,K.isLineTool)(t)&&null!==o){const e=(0,Ds.sortSources)(o.lineTools().filter((e=>!a.has(e)||e===t)));n=Oa(n,{bringForwardEnabled:t!==e[e.length-1],bringToFrontEnabled:t!==e[e.length-1],sendBackwardEnabled:t!==e[0],sendToBackEnabled:t!==e[0]});continue}const e=(0,r.ensureNotNull)(this._model().paneForSource(t)).sourcesByGroup().allExceptSpecialSources();if(0===e.length)continue;const i=t.zorder(),s=e[0].zorder(),l=e[e.length-1].zorder();n=Oa(n,{bringForwardEnabled:i!==l,bringToFrontEnabled:i!==l,sendBackwardEnabled:i!==s,sendToBackEnabled:i!==s})}return n}sendToBack(e){if(!this.availableZOrderOperations(e).sendToBackEnabled)throw new Error("Send to back operation is unavailable");let t=null;const i=e[0];if((0,K.isLineTool)(i)){const s=this._model().lineToolsGroupModel().groupForLineTool(i);if(null!==s){const i=s.lineTools();t=new Qs(this.model(),(0,Ds.sortSources)(e),i[0])}}null===t&&(t=new Ys(this.model(),(0,Ds.sortSources)(e))),this._pushUndoCommand(t),this.emitEvent("changeZOrder",[e])}bringToFront(e){if(!this.availableZOrderOperations(e).bringToFrontEnabled)throw new Error("Bring to front operation is unavailable");let t=null;const i=e[0];if((0,K.isLineTool)(i)){const s=this._model().lineToolsGroupModel().groupForLineTool(i);if(null!==s){const i=s.lineTools();t=new Xs(this.model(),(0,Ds.sortSources)(e),i[i.length-1])}}null===t&&(t=new Ks(this.model(),(0,Ds.sortSources)(e))),this._pushUndoCommand(t),this.emitEvent("changeZOrder",[e])}sendBackward(e){if(!this.availableZOrderOperations(e).sendBackwardEnabled)throw new Error("Send backward operation is unavailable");const t=Rn.format({title:(0,Bs.getTranslatedStringForSource)(is.TitleDisplayTarget.StatusLine,e[0])}) ;this._sendBackOrBringForward(t,(0,Ds.sortSources)(e),((e,t)=>new to(this.model(),e,t)))}bringForward(e){if(!this.availableZOrderOperations(e).bringForwardEnabled)throw new Error("Bring forward operation is unavailable");const t=On.format({title:(0,Bs.getTranslatedStringForSource)(is.TitleDisplayTarget.StatusLine,e[0])});this._sendBackOrBringForward(t,(0,Ds.sortSources)(e),((e,t)=>new so(this.model(),e,t)))}insertAfter(e,t){e=(0,Ds.sortSources)(e);const i=Vn.format({title:(0,Bs.getTranslatedStringForSource)(is.TitleDisplayTarget.StatusLine,e[0]),target:(0,Bs.getTranslatedStringForSource)(is.TitleDisplayTarget.StatusLine,t)});this._insertAfterOrBefore(i,e,t,(()=>new Xs(this.model(),e,t)))}insertBefore(e,t){e=(0,Ds.sortSources)(e);const i=Wn.format({title:(0,Bs.getTranslatedStringForSource)(is.TitleDisplayTarget.StatusLine,e[0]),target:(0,Bs.getTranslatedStringForSource)(is.TitleDisplayTarget.StatusLine,t)});this._insertAfterOrBefore(i,e,t,(()=>new Qs(this.model(),e,t)))}detachToRight(e,t){(0,u.trackEvent)("Chart","Move to new right scale");const i=na.format({title:(0,Bs.getTranslatedStringForSource)(is.TitleDisplayTarget.StatusLine,e)}),s=new $o(this.model(),e,t,"right",i);this._pushUndoCommand(s),this.emitEvent("moveSource",[e])}detachToLeft(e,t){(0,u.trackEvent)("Chart","Move to new left scale");const i=aa.format({title:(0,Bs.getTranslatedStringForSource)(is.TitleDisplayTarget.StatusLine,e)}),s=new $o(this.model(),e,t,"left",i);this._pushUndoCommand(s),this.emitEvent("moveSource",[e])}detachNoScale(e,t){(0,u.trackEvent)("Chart","Make source no scale");const i=la.format({title:(0,Bs.getTranslatedStringForSource)(is.TitleDisplayTarget.StatusLine,e)}),s=new $o(this.model(),e,t,"overlay",i);this._pushUndoCommand(s),this.emitEvent("moveSource",[e])}moveToScale(e,t,i,s,o){(0,u.trackEvent)("Chart","Move source to target scale"),this.beginUndoMacro(s);const r=new Xo(this.model(),e,t,i,s),n=o?null:(0,Ki.sourceNewCurrencyOnPinningToPriceScale)(e,i,this._model()),a=o?null:(0,pr.sourceNewUnitOnPinningToPriceScale)(e,i,this._model());this._pushUndoCommand(r),null!==n&&this.setPriceScaleCurrency(i,n),null!==a&&this.setPriceScaleUnit(i,a),this.endUndoMacro(),this.emitEvent("moveSource",[e])}setLinkingGroupIndex(e){this._undoHistory.beginUndoMacro(Ba),this._pushUndoCommand(new dn(this.model().linkingGroupIndex(),e,Ba)),this._model().setShouldBeSavedEvenIfHidden(!0),this._undoHistory.endUndoMacro()}startScrollPrice(e,t,i){t.isAutoScale()||(this._initialPriceScrollState=t.state(),this._initialPriceScrollPos=i,this._model().startScrollPrice(e,t,i))}scrollPriceTo(e,t,i){t.isAutoScale()||(this._initialPriceScrollState&&this._initialPriceScrollPos&&Math.abs(this._initialPriceScrollPos-i)>20&&(this._pushUndoCommand(new Ut(this.m_model,e,t,this._initialPriceScrollState,void 0,!1)),this._initialPriceScrollState=null,this._initialPriceScrollPos=null),this._model().scrollPriceTo(e,t,i))}endScrollPrice(e,t){t.isAutoScale()||(this._initialPriceScrollState=null,this._initialPriceScrollPos=null,this._model().endScrollPrice(e,t))} startScrollTime(e){const t=this.timeScale();this._initialTimeScrollState={rightOffset:t.rightOffset(),barSpacing:t.barSpacing()},this._initialTimeScrollPos=e,this.model().startScrollTime(e)}scrollTimeTo(e){null!==this._initialTimeScrollPos&&null!==this._initialTimeScrollState&&Math.abs(e-this._initialTimeScrollPos)>20&&(this._pushUndoCommand(new Ft(this.model(),this._initialTimeScrollState,ca,!1)),this._initialTimeScrollPos=null,this._initialTimeScrollState=null),this.model().scrollTimeTo(e)}endScrollTime(){this.model().endScrollTime(),this._initialTimeScrollPos=null,this._initialTimeScrollState=null}startScaleTime(e){const t=this.timeScale();this._initialTimeScaleState={rightOffset:t.rightOffset(),barSpacing:t.barSpacing()},this.model().startScaleTime(e)}scaleTimeTo(e){null!==this._initialTimeScaleState&&this._initialTimeScaleState.barSpacing!==this.timeScale().barSpacing()&&(this._pushUndoCommand(new Ft(this.model(),this._initialTimeScaleState,da,!0)),this._initialTimeScaleState=null),this.model().scaleTimeTo(e)}endScaleTime(){this.model().endScaleTime()}resetTimeScale(){this.changeTimeScale(ha,this.timeScale().resetAvailable().value()),this.model().resetTimeScale()}changeTimeScale(e,t=!0){const i=this.timeScale(),s={rightOffset:i.rightOffset(),barSpacing:i.barSpacing()};this._pushUndoCommand(new Ft(this.model(),s,e,t))}startScalePrice(e,t,i,s){this._scalePriceInfo={priceScaleState:t.state(),tryMergeConsecutiveScales:s},this.model().startScalePrice(e,t,i)}scalePriceTo(e,t,i){this.model().scalePriceTo(e,t,i)}endScalePrice(e,t){this.model().endScalePrice(e,t);const i=(0,r.ensureNotNull)(this._scalePriceInfo);(0,Ae.default)(i.priceScaleState,t.state())||this._pushUndoCommand(new Ut(this.model(),e,t,i.priceScaleState,i.tryMergeConsecutiveScales)),this._scalePriceInfo=null}startTwoPointsScalePrice(e,t,i,s,o){this._scalePriceInfo={priceScaleState:t.state(),tryMergeConsecutiveScales:o},this.model().startTwoPointsScalePrice(e,t,i,s)}twoPointsScalePriceTo(e,t,i,s){this.model().twoPointsScalePriceTo(e,t,i,s)}endTwoPointsScalePrice(e,t){this.model().endTwoPointsScalePrice(e,t);const i=(0,r.ensureNotNull)(this._scalePriceInfo);(0,Ae.default)(i.priceScaleState,t.state())||this._pushUndoCommand(new Ut(this.model(),e,t,i.priceScaleState,i.tryMergeConsecutiveScales)),this._scalePriceInfo=null}resetPriceScale(e,t){const i=t.state();this.model().resetPriceScale(e,t),(0,Ae.default)(i,t.state())||this._pushUndoCommand(new Ut(this.m_model,e,t,i))}rearrangePanes(e,t){const i=new lo(this._model(),e,t);this._pushUndoCommand(i)}movePane(e,t){const i=new lo(this._model(),e,t);this._pushUndoCommand(i)}toggleCollapsedPane(e){const t=this.panes().findIndex((t=>t===e));t<0||this._pushUndoCommand(new $i(this._model(),t))}readOnly(){return this.m_model.readOnly()}checkIfFeatureAvailable(e,t){const i=t.length>0,s=(0,vr.isFundamentalStudyMetaInfo)(e),o=this.canCreateStudy({id:e.id,child:i,fundamental:s});return!!o.success||(Wa(this.model(),o),!1)}async pasteSourceFromClip(e,t,i){const s=t;if(!s||0===s.sources.length)return null;const o=e||(0, r.ensureNotNull)(this.model().paneForSource(this.mainSeries()));if(!s.sources.some((e=>"drawing"!==e.type||null!==o.clipboardLineToolOwnerSource(e.source.id))))return null;const n=Array.from(new Set(s.sources.filter(ji.isLineToolClipboardData).map((e=>e.source.type))));await Promise.all(n.map((e=>(0,K.initLineTool)(e)))),this.beginUndoMacro(ma.format({title:s.title}));let a=0;const l=[],c=[];for(const t of s.sources)if("drawing"===t.type&&null!==o.clipboardLineToolOwnerSource(t.source.id)){const e=this.pasteLineTool(o,t);a<5&&(Jt(e),a+=1),c.push(e),l.push(e)}else"study"===t.type&&t.source&&t.source.metaInfo&&this.checkIfFeatureAvailable(new Fi.StudyMetaInfo(t.source.metaInfo),[])&&l.push(this.pasteStudy(t,i?e:void 0));return c.length&&this.selectionMacro((e=>{e.clearSelection(),c.forEach((t=>{e.addSourceToSelection(t,null)}))})),this.endUndoMacro(),l}pasteLineTool(e,t,i,s){t.source.state.intervalsVisibilities=(0,Nr.mergeIntervalVisibilitiesDefaults)(t.source.state.intervalsVisibilities),(0,Nr.makeIntervalsVisibilitiesVisibleAtInterval)(t.source.state.intervalsVisibilities,this.model().mainSeries().intervalObj());const o=new jo(this.model(),t,e,i,s);this._pushUndoCommand(o);const r=o.source();return o.needCopyToOtherCharts()&&this._model().copyToOtherCharts([r],!0),this.selectionMacro((e=>{e.clearSelection(),e.addSourceToSelection(r,null)})),r}pasteStudy(e,t){const i=new or(this.model(),e,null==t?void 0:t.id());this._pushUndoCommand(i);const s=(0,r.ensureNotNull)(i.state()).id;return(0,l.emit)("study_event",s,"paste_study"),(0,r.ensureNotNull)(this._model().dataSourceForId(s))}removePane(e){const t=this.m_model.panes()[e].dataSources().slice();this.removeSources(t,!1,Sa)}createPane(e){return this.m_model.createPane(e)}setPriceScaleCurrency(e,t){const i=new Zo(this.m_model,e,t,Xn);this._pushUndoCommand(i)}setPriceScaleUnit(e,t){const i=new Ko(this.m_model,e,t,Jn);this._pushUndoCommand(i)}setSymbol(e,t){e.symbolSameAsResolved(t)||this._pushUndoCommand(new tr(e,t,this._chartWidget))}setResolution(e,t){zi.Interval.isEqual(e.interval(),t)||this._pushUndoCommand(new ln(e,t,this._chartWidget))}hideMaximizedPaneIfRequired(){this._chartWidget.isMaximizedPane()&&this._chartWidget.toggleMaximizePane(null)}syncCrosshair(e,t,i){this._chartWidget.chartWidgetCollection().syncCrosshair(e,this._chartWidget.id(),t,i)}loadingScreen(){return this._chartWidget.screen}chartLoadTheme(e,t,i){const s=new nn(this.model(),e,t);i?s.redo():this._pushUndoCommand(s)}isJustClonedChart(){return this._chartWidget.isJustClonedChart()}isMultipleLayout(){return this._chartWidget.isMultipleLayout()}addPaneStretchFactorUndoCommand(e,t,i,s){const o=new rr(this.model(),e,t,i,s);this._pushUndoCommand(o)}applyPreferences(e){{const t=new En(this.m_model,e);this._pushUndoCommand(t)}}paneForSource(e){return this.m_model.paneForSource(e)}destroy(){this.m_model.destroy()}moveSelectedToolsLeft(){return this._moveSelectedTools(2)}moveSelectedToolsUp(){return this._moveSelectedTools(0)}moveSelectedToolsRight(){return this._moveSelectedTools(3)}moveSelectedToolsDown(){ return this._moveSelectedTools(1)}insertStudyWithoutCheck(e,t,i,s){return this._insertStudy(e,t,{},!1,[],void 0,void 0,void 0,void 0,null!=i?i:null,void 0,s)}saveLineToolState(e,t){this._pushUndoCommand(new ws(this.m_model,[e],t))}resetScales(){this._model().stopTimeScaleAnimation(),this.beginUndoMacro(ua),this.resetTimeScale();for(const e of this.m_model.panes()){for(const t of e.leftPriceScales())this.resetPriceScale(e,t);for(const t of e.rightPriceScales())this.resetPriceScale(e,t)}this.endUndoMacro(),this.m_model.recalculateAllPanes((0,ni.viewportChangeEvent)())}shareLineTools(e,t){const i=0===t?ka:1===t?Ea:Da;this.withMacro(i,(()=>{0===t&&this.unlinkLines(e),e.forEach((i=>{const s=this.model().lineToolsGroupModel().groupForLineTool(i);if(s){s.lineTools().every((t=>e.includes(t)))||this.lineToolsGroupController().excludeLineToolFromGroup(s,i)}this._pushUndoCommand(new xo(i,t,this.model(),null))}))}))}canCreateStudy(e,t){return this.model().chartApi().canCreateStudy(e,t)}chartWidgetCollectionLock(){return this._chartWidget.chartWidgetCollection().lock}onSymbolIntervalChanged(){return this.m_model.onSymbolIntervalChanged()}paneBeingCreatedLineOn(){return this.m_model.paneBeingCreatedLineOn()}invalidate(e){this.m_model.invalidate(e)}setWidth(e){this.m_model.setWidth(e)}setPaneHeight(e,t){this.m_model.setPaneHeight(e,t)}dataSourceForId(e){return this.m_model.dataSourceForId(e)}lineBeingEdited(){return this.m_model.lineBeingEdited()}sourcesBeingMoved(){return this.m_model.sourcesBeingMoved()}gridSource(){return this.m_model.gridSource()}watermarkSource(){return this.m_model.watermarkSource()}mainSeriesScaleRatioProperty(){return this.m_model.mainSeriesScaleRatioProperty()}setHoveredSource(e,t){this.m_model.setHoveredSource(e,t)}setCurrentPosition(e,t,i,s){this.m_model.setCurrentPosition(e,t,i,s)}setAndSaveCurrentPosition(e,t,i,s){this.m_model.setAndSaveCurrentPosition(e,t,i,s)}version(){return this.m_model.version()}restart(){this.m_model.restart()}disconnect(){this.m_model.disconnect()}calculateDefaultTags(){return this.m_model.calculateDefaultTags()}_model(){return this.m_model}_pushUndoCommand(e){this._undoHistory.pushUndoCommand(e)}_mergeUnmergeSource(e,t){this.beginUndoMacro(t.text());const i=(0,r.ensureNotNull)(this._model().paneForSource(e)),s=new Set(i.sourcesByGroup().lineSources().filter((t=>t.ownerSource()===e)));this._model().lineToolsGroupModel().groups().filter((e=>{const t=e.lineTools().some((e=>s.has(e))),i=e.lineTools().some((e=>!s.has(e)));return t&&i})).forEach((e=>{this._pushUndoCommand(new gs(this._model(),e,e.lineTools()))})),this._pushUndoCommand(t),this.endUndoMacro()}_insertStudy(e,t,i,s,o,n,a,l,c,d,h,u){const _=ga.format({title:e.description});this.beginUndoMacro(_);const p=new dr(this.model(),e,t,i,s,o,n,a,l,c,d||null,u,_);this._pushUndoCommand(p);const m=p.insertedStudy();if(void 0!==h){const e=new hr(h,(0,r.ensureNotNull)(m.priceScale()),null,this.model());this._pushUndoCommand(e)}return this.endUndoMacro(),{study:m,startPromise:p.lastInsertionStartPromise()}}_storeFailedStub(e){ const t=ga.format({title:e.title()});this.beginUndoMacro(t);const i=new _n(this.model(),e,t);this._pushUndoCommand(i),this.endUndoMacro()}async _processSpecialLineToolsContents(e,t,i){if(t=t||await e.read(),window.user.id&&t.files){const e=Array.from(t.files).find(Zt.blobImageFilter);if(e){const t=URL.createObjectURL(e),s=(0,Zt.uploadImage)(e);return void 0===i&&(i=(0,r.ensureNotNull)(this._model().paneForSource(this.mainSeries()))),this.pasteImageAsLineTool(s,t,i),void await s}}t.text&&(window.user.id&&!Ra&&(0,mr.isTwitterUrl)(t.text)?(0,mr.createTweetLineToolByUrl)(t.text,this,!0):window.user.id&&(0,Sr.isIdeaUrl)(t.text)?(0,Sr.createIdeaLineToolByUrl)(t.text,this,!0):function(e,t){if(null===t.timeScale().logicalRange())return null;const i=t.mainSeries(),s=i.priceScale(),o=t.timeScale(),n=(0,r.ensureNotNull)(t.model().paneForSource(i)),a=(0,r.ensureNotNull)((0,r.ensureNotNull)(s.mainSource()).firstValue()),l=o.coordinateToIndex(t.timeScale().width()/2),c=n.height()/2,h={price:s.coordinateToPrice(c,a),time_t:(0,r.ensureNotNull)(o.indexToTimePoint(l)),offset:0},u=n.newLineToolZOrder(!0),_=gr.LineToolText.createProperties().state();_.text=e,_.interval=i.interval();const p={type:"drawing",source:{id:(0,Mo.randomHashN)(6),zorder:u,type:"LineToolText",state:_,symbol:i.symbol(),ownerSource:i.id(),points:[h]},geometry:[],modelId:t.model().id(),centeredOnChart:!0},m=t.pasteLineTool(n,p,!1,!1);d.setValue("hint.pasteText",!0,{forceFlush:!0})}(t.text,this))}_insertAfterOrBefore(e,t,i,s){const o=(0,r.ensureNotNull)(this._model().paneForSource(i));if(t.some((e=>(0,K.isLineTool)(e)&&this._model().paneForSource(e)!==o)))throw new Error("Cannot insert line tool after target on another pane");this.beginUndoMacro(e),t.forEach((e=>{(0,r.ensureNotNull)(this.model().paneForSource(e))!==o&&this.mergeToPane(e,o)}));const n=s();this._pushUndoCommand(n),this.emitEvent("changeZOrder",[t]),this.endUndoMacro()}_sendBackOrBringForward(e,t,i){const s=new Map;t.forEach((e=>{const t=(0,r.ensureNotNull)(this._model().paneForSource(e)),i=s.get(t)||[];i.push(e),s.set(t,i)})),this.beginUndoMacro(e),s.forEach(((e,t)=>{this._pushUndoCommand(i(t,e))})),this.endUndoMacro(),this.emitEvent("changeZOrder",[t])}_moveSelectedTools(e){const t=this.model().selection().lineDataSources();if(0===t.length)return!1;if((0,Oe.lockDrawings)().value())return!0;const i=this.timeScale().visibleBarsStrictRange();if(null===i)return!1;const s=function(e){const t=new Map;for(const i of e){const e=i.ownerSource();if(null===e)continue;let s=t.get(e);if(void 0===s){const o=e.priceScale(),r=e.priceStep(),n=e.firstValue();if(null===o||null===r||null===n)continue;if(null===o.priceRange())continue;s={sources:[],priceScale:o,priceStep:r,startPrice:i.points()[0].price,firstValue:n},t.set(e,s)}s.sources.push(i)}return t}(t);if(0===s.size)return!1;this.beginUndoMacro(Kn);const o=i.firstBar(),r=this.timeScale().indexToCoordinate(o),n=o+(3===e?1:2===e?-1:0),a=this.timeScale().indexToCoordinate(n);return Oe.isDirectionalMovementActive.setValue(!0),s.forEach((t=>{ const{startPrice:i,priceStep:s,priceScale:l,firstValue:c}=t,d=i+(0===e?s:1===e?-s:0),h=l.priceToCoordinate(i,c),u=l.priceToCoordinate(d,c),_={logical:{index:o,price:i},screen:new ke.Point(r,h)},p={logical:{index:n,price:d},screen:new ke.Point(a,u)};this.startMovingSources(t.sources,_,null),this.moveSources(p),this.endMovingSource(!1,!0)})),Oe.isDirectionalMovementActive.setValue(!1),this.endUndoMacro(),!0}_restoreStudyFactoryDefaults(e){const t=new Br(this.m_model,e);this._pushUndoCommand(t)}_restoreLineToolFactoryDefaults(e){this.beginUndoMacro(Yn),this.saveLineToolState(e,Yn);const t=new kr(this.m_model,e.properties(),Yn);this._pushUndoCommand(t),this.saveLineToolState(e,Yn),this.endUndoMacro(),this.model().updateSource(e)}_removeAllDrawingToolsImpl(e){this.selectionMacro((()=>{this.lineBeingCreated()&&this.cancelCreatingLine();this.dataSources().filter(K.isLineTool).filter((e=>e.isActualSymbol()&&e.isUserDeletable())).filter((t=>!e||e===t.toolname)).forEach((e=>this.removeSource(e,!1)))}),!0)}_removeAllStudiesImpl(){const e=this.dataSources(),t=e.filter(q.isStudy).filter((e=>!e.isChildStudy()&&e.removeByRemoveAllStudies())),i=e.filter(q.isStudyStub);t.concat(i).forEach((e=>this.removeSource(e,!1)))}}var Ha=i(359663),za=i(709404),Ua=i(234271);class Ga{constructor(){this._session={startDate:(new Date).toISOString(),url:window.location.href,entries:[]}}addPersistentLogEntry(e,t,i){this._session.entries.push({date:(new Date).toISOString(),level:t,message:e,category:i})}async getLastSessions(e){return[this._session]}pendingEntries(){return this._session.entries}}var qa=i(33900),ja=i(147675),Za=i(786559);const Ka=a.t(null,void 0,i(123536));function Ya(e){if("replaced_to_exchange"===e.type)return{text:Ka,warningIcon:Za,warningType:"notaccurate",solutionId:ie.solutionIds.WHAT_IS_CBOE_BZX_EXCHANGE}}class $a{constructor(e){this._activeHint=null,this._deferredPromise=null,this._chart=e;e.model().mainSeries().dataEvents().symbolResolved().subscribe(this,this._onSymbolResolved)}destroy(){this._destroyActiveHint();this._chart.model().mainSeries().dataEvents().symbolResolved().unsubscribe(this,this._onSymbolResolved)}_destroyActiveHint(){null!==this._activeHint&&(this._activeHint.destroy(),this._activeHint=null),this._deferredPromise=null}async _createHint(){if(null===this._deferredPromise){const e=(0,g.createDeferredPromise)();this._deferredPromise=e,Promise.all([i.e(4343),i.e(13031),i.e(22847),i.e(90385),i.e(83129)]).then(i.bind(i,629981)).then((t=>{e.resolve(new t.ChartWarningHintRenderer(this._chart))}))}return this._deferredPromise.promise}_onSymbolResolved(e){const t=function(e){const t=(0,ja.firstReplacedByBatsExchange)(e);return null!==t?{type:"replaced_to_exchange",exchange:t}:null}(e),i=t&&function(e){return`warning.noSubsc_${e.exchange}`}(t);if(null===t||null===i||Boolean(d.getBool(i)))return void this._destroyActiveHint();const s={...Ya(t),onClose:()=>{d.setValue(i,!0,{forceFlush:!0}),this._destroyActiveHint()}};null!==this._activeHint?this._activeHint.show(s):this._createHint().then((e=>{this._activeHint=e, this._activeHint.show(s)}))}}var Xa=i(521506);const Ja=a.t(null,void 0,i(858018));class Qa extends class{constructor(e){this._lastResolvedSymbol=null,this._chart=e,this._chart.withModel(this,this._connectToModel)}_getPopupContent(){const e=this._getProSymbol(),t=new URL("https://www.tradingview.com/chart/");t.searchParams.append("symbol",e),t.searchParams.append("utm_source","www.tradingview.com"),t.searchParams.append("utm_medium","widget"),t.searchParams.append("utm_campaign","chart"),t.searchParams.append("utm_term",e);return Ja.format({linkStart:``,linkEnd:""})}_onPopupClosed(){const e=this._chart.defaultSymbol(),t=this._getSymbol();let i;i=this._lastResolvedSymbol?this._lastResolvedSymbol:e!==t?e:"AAPL",this._chart.setSymbol(i)}_getProSymbol(){return this._chart.model().mainSeries().proSymbol()}_getSymbol(){return this._chart.model().mainSeries().actualSymbol()}_connectToModel(){const e=this._chart.model().mainSeries();e.dataEvents().symbolResolved().subscribe(this,this._onSymbolResolved),e.dataEvents().symbolGroupNotPermitted().subscribe(this,this._onSymbolGroupNotPermitted),e.dataEvents().symbolNotPermitted().subscribe(this,this.show)}_onSymbolResolved(){this._lastResolvedSymbol=this._getSymbol()}_onSymbolGroupNotPermitted(){this.show()}}{show(){(0,qa.createNoticeDialog)({content:this._getPopupContent()}).then((e=>{e.on("destroy",this._onPopupClosed.bind(this)),e.open()}))}}var el=i(538660),tl=i(547944);var il=i(370552),sl=(i(534741),i(12481)),ol=i(833713),rl=i(895370),nl=i(198303),al=i(113610);const ll=(0,m.getLogger)("Chart.LinkKeyResolver");class cl{constructor(e,t,i){this._pendingRequests=new Map,this._startRequestingDebounced=(0,sl.default)((()=>this._startNextRequest()),500),this._layoutId=e,this._chartId=t,this._ownerSourceId=i}resolveLinkKey(e,t,i){var s;const o=function(e,t){return JSON.stringify([e,t])}(e,i),r=null!==(s=this._pendingRequests.get(o))&&void 0!==s?s:new Map;if(r.has(t))return r.get(t).promise;const n=(0,g.createDeferredPromise)();return r.set(t,n),this._pendingRequests.set(o,r),this._startRequestingDebounced(),n.promise}async _startNextRequest(){if(0===this._pendingRequests.size)return;const e=await(0,al.getChartStorage)(),t=this._pendingRequests.entries().next().value,{symbol:i,brokerName:s}=function(e){const t=JSON.parse(e);return{symbol:t[0],brokerName:t[1]}}(t[0]),o=t[1],r={requestType:"mainSeriesLineTools",seriesSourceId:this._ownerSourceId,symbol:i,brokerName:s,sharingMode:0};try{const t=await e.loadLineToolsAndGroups(this._layoutId,this._chartId,r,i);null!==t&&null!==t.sources&&(t.sources.forEach(((e,t)=>{if(null===e)return;const i=e.state.linkKey;if(!i)return;const s=o.get(i);null==s||s.resolve(e.id),o.delete(i)})),t.serverRequestId&&console.log(`PROCESSED:${t.serverRequestId}`))}catch(e){ll.logError(`Error requesting line tools: ${e}`)}o.forEach((e=>{e.resolve(null)})),this._pendingRequests.delete(t[0]),await this._startNextRequest()}}var dl=i(459711),hl=i(266325);const ul=[0,1,2],_l=(0,m.getLogger)("LineToolsSynchronizer") ;function pl(e,t){return{id:e.id,name:e.name().value(),symbol:e.symbol(),currencyId:e.currencyId(),unitId:e.unitId()}}function ml(e,t,i){const s=new Map,o=new Set(null==i?void 0:i.keys());return e.forEach(((e,r)=>{const n=!i||i.has(r);(e.timestamp>t||!n)&&(s.set(r,e),o.delete(r))})),{stillInvalidated:s,validated:Array.from(o)}}function gl(e){return(0,K.isLineTool)(e)||(0,dl.isStudyLineToolStub)(e)}const Sl=/(\w+)\/(\w+)\/(\w+)/;class vl{constructor(e,t,i){this._invalidatedLineToolsAndStudyStubs=new Map,this._allLineToolsAndStudyStubs=new Map,this._originalLineToolSharingMode=new Map,this._invalidatedLineToolGroups=new Map,this._originalLineToolGroupsSharingMode=new Map,this._ignoreInvalidatingEventsDepth=0,this._saveChartService=null,this._debouncedSave=(0,sl.default)((()=>this._saveInvalidatedIfRequired(!1)),500),this._currentlyLoadedSymbol=new Map,this._linkKeyResolver=null,this._brokerName="",this._hasChanges=new O.WatchedValue(!1),this._lastBanTime=null,this._invalidateViaSync=0,this._savingAbortControllersBySharingMode=new Map,this._onChangeAutosave=e=>{e&&this._debouncedSave()},this._origin=e,this._chartModel=t,this._options=i,this._assignAllLineTools(this._chartModel.panes()),this._chartModel.panesCollectionChanged().subscribe(this,this._processPanesCollectionChanged.bind(this)),this._chartModel.dataSourceCollectionChanged().subscribe(this,this._processDataSourceCollectionChanged.bind(this)),this._chartModel.lineToolsGroupModel().onChanged().subscribe(this,this._processLineToolsGroupModelChanged.bind(this)),this._chartModel.mainSeries().dataEvents().symbolResolved().subscribe(this,this._onSymbolResolved.bind(this)),this._chartModel.sourcePropertiesChanged().subscribe(this,this._processPropertiesChanged.bind(this)),this._chartModel.sourceZOrderChanged().subscribe(this,this._processPropertiesChanged.bind(this)),this._linkKeyResolver=new cl(e.layoutId,e.chartId,t.mainSeries().id()),this._brokerIdSession=new Ha.FeatureToggleWatchedValue("broker_id_session",!1),ul.forEach((e=>{0===e&&this._loadAndMergeLineToolsOnStudies(e,!1),this._loadAndMergeLineToolsWithoutSymbol(e,!1)})),(0,c.onWidget)()||window.loginStateChange.subscribe(this,(()=>{window.is_authenticated&&this.reloadAllLineTools()}))}destroy(){(0,c.onWidget)()||window.loginStateChange.unsubscribeAll(this),this._brokerIdSession.destroy(),this._chartModel.mainSeries().dataEvents().symbolResolved().unsubscribeAll(this),this._chartModel.sourcePropertiesChanged().unsubscribeAll(this),this._chartModel.sourceZOrderChanged().unsubscribeAll(this),this._chartModel.panesCollectionChanged().unsubscribeAll(this),this._chartModel.dataSourceCollectionChanged().unsubscribeAll(this),this._chartModel.lineToolsGroupModel().onChanged().unsubscribeAll(this)}reloadAllLineTools(){this._currentlyLoadedSymbol.clear(),ul.forEach((e=>{0===e&&this._loadAndMergeLineToolsOnStudies(e,!0),this._loadAndMergeLineToolsWithoutSymbol(e,!0)}));const e=this._chartModel.mainSeries().symbolInfo();e&&this._onSymbolResolved(e)}hasChanges(){return this._hasChanges}setSaveChartService(e){ this._saveChartService&&this._saveChartService.autoSaveEnabled().unsubscribe(this._onChangeAutosave),this._saveChartService=e,this._saveChartService.autoSaveEnabled().subscribe(this._onChangeAutosave)}prepareDTO(e=!1){const t=new Map;return ul.forEach((i=>{t.set(i,this._prepareDTOItem(e,i))})),t}getDTO(e=0,t=!1,i=!1){return i&&this.invalidateAll(),this._prepareDTOItem(t,e)}async applyDTO(e,t=0){this.resetInvalidated(Date.now().valueOf(),e,t),await this._applyLineToolsAndGroupsDTO(e,t)}markAsValidatedBecauseOfSavingToContent(e){this._invalidatedLineToolsAndStudyStubs.forEach((t=>{t.savedToChartContent=e})),this._invalidatedLineToolGroups.forEach((t=>{t.savedToChartContent=e})),this._recalculateHasChanges()}resetInvalidated(e,t,i){const s=(e,t,s,o)=>{if(!s.has(o)||s.get(o))s.has(o)&&t(o,i);else{const s=e.get(o);s&&(s===i?t(o,null):0===i&&t(o,s))}};if(null===t.sources)return;const{groups:o,sources:r,lineToolsToValidate:n,groupsToValidate:a}=t,l=ml(this._invalidatedLineToolsAndStudyStubs,e,new Set(null!=n?n:r.keys()));this._invalidatedLineToolsAndStudyStubs=l.stillInvalidated,l.validated.forEach(s.bind(this,this._originalLineToolSharingMode,this._setOriginalLineToolSharingMode.bind(this),r));const c=ml(this._invalidatedLineToolGroups,e,new Set(null!=a?a:o.keys()));l.validated.forEach(s.bind(this,this._originalLineToolGroupsSharingMode,this._setOriginalLineToolGroupsSharingMode.bind(this),o)),this._invalidatedLineToolGroups=c.stillInvalidated,Array.from(r.keys()).forEach((e=>{const t=this._chartModel.dataSourceForId(e);t&&null===t.serverUpdateTime()&&t.setServerUpdateTime((new Date).valueOf())})),this._recalculateHasChanges()}applyLineToolUpdateNotification(e,t){var i;const s=function(e){const t=Sl.exec(e);return 4===(null==t?void 0:t.length)?{layoutId:t[1],chartId:t[2],clientId:t[3]}:{layoutId:"",chartId:"",clientId:e}}(null!==(i=e.clientId)&&void 0!==i?i:"");s.clientId===this._origin.clientId&&s.chartId===this._origin.chartId||(void 0!==e.symbol&&null===e.sources?this._withoutInvalidating((()=>{const i=this._chartModel.dataSources().filter(K.isLineTool).filter((i=>i.sharingMode().value()===t&&i.symbol()===e.symbol));i.length>0&&this._chartModel.undoModel().removeSources(i,!0,null)})):this._applyLineToolsAndGroupsDTO(e,t,s))}startApplyingLineToolUpdateNotification(){this._ignoreInvalidatingEventsDepth++}endApplyingLineToolUpdateNotification(){this._ignoreInvalidatingEventsDepth--,this._ignoreInvalidatingEventsDepth<0&&(_l.logError("Logic error, startApplyingLineToolUpdateNotification/endApplyingLineToolUpdateNotification mismatch, autofixing"),this._ignoreInvalidatingEventsDepth=0)}applyAlertIdByExternalSource(e,t){this._withoutInvalidating((()=>{const i=this._chartModel.dataSourceForId(e);i&&(0,K.isLineTool)(i)&&i.setAlert(t)}))}deleteAlertByExternalSource(e){this._withoutInvalidating((()=>{const t=this._chartModel.dataSourceForId(e);t&&(0,K.isLineTool)(t)&&t.removeAlert()}))}async markSyncedLineToolAsDeleted(e,t){if(this._linkKeyResolver){const i=await this._linkKeyResolver.resolveLinkKey(t,e,this._brokerName) ;if(null!==i){const t=(0,K.lineToolByLinkKey)(this._chartModel,e);null===t?this._invalidateLineToolOrStudyStub(i,performance.now()):this._withoutInvalidating((()=>{const e=(0,r.ensureNotNull)(this._chartModel.paneForSource(t)),i=this._allLineToolsAndStudyStubs.get(e.id())||new Map;t.detachAlert(),this._chartModel.removeSource(t),i.delete(t.id())})),this._debouncedSave()}return i}return null}invalidateAll(){const e=performance.now();this._allLineToolsAndStudyStubs.forEach((t=>{t.forEach(((t,i)=>{this._invalidateLineToolOrStudyStub(i,e)}))})),this._chartModel.lineToolsGroupModel().groupsForAllSymbols().forEach((t=>{this._invalidateLineToolGroup(t.id,e)})),this.markAsValidatedBecauseOfSavingToContent(!0)}executeSyncedAction(e){this._invalidateViaSync+=1;try{e()}finally{this._invalidateViaSync-=1}}invalidateViaSync(){return this._invalidateViaSync>0}flushPendingSavings(){return this._invalidatedLineToolGroups.size||this._invalidatedLineToolsAndStudyStubs.size?this._saveInvalidatedIfRequired(!1,!0):null}_assignAllLineTools(e){e.forEach((e=>{const t=e.dataSources().filter(gl).map((e=>[e.id(),e.linkKey().value()])),i=new Map(t);this._allLineToolsAndStudyStubs.set(e.id(),i)}))}_processPropertiesChanged(e,t){gl(t)&&this._invalidateLineToolOrStudyStub(t.id(),performance.now())}_processLineToolsGroupModelChanged(e,t){const i=performance.now();this._invalidateLineToolGroup(e,i),t&&(t.affectedLineTools||[]).forEach((e=>this._invalidateLineToolOrStudyStub(e,i)))}_processPanesCollectionChanged(e){const t=e.map((e=>e.id())),i=new Set(t),s=performance.now();Array.from(this._allLineToolsAndStudyStubs.keys()).filter((e=>!i.has(e))).forEach((e=>{Array.from((0,r.ensureDefined)(this._allLineToolsAndStudyStubs.get(e)).keys()).forEach((e=>{this._invalidateLineToolOrStudyStub(e,s)}))})),e.filter((e=>!this._allLineToolsAndStudyStubs.has(e.id()))).forEach((e=>{e.dataSources().filter(gl).forEach((e=>this._invalidateLineToolOrStudyStub(e.id(),s)))})),this._assignAllLineTools(e)}_processDataSourceCollectionChanged(e){const t=e.dataSources().filter(gl),i=t.map((e=>[e.id(),e.linkKey().value()])),s=new Map(i);let o;const n=performance.now();if(this._allLineToolsAndStudyStubs.has(e.id())){const i=(0,r.ensureDefined)(this._allLineToolsAndStudyStubs.get(e.id()));o=t.filter((e=>!i.has(e.id()))),o.forEach((e=>this._invalidateLineToolOrStudyStub(e.id(),n))),Array.from(i.entries()).filter((e=>!s.has(e[0]))).forEach((e=>{null!==e[1]&&this._debouncedSave(),this._invalidateLineToolOrStudyStub(e[0],n)}))}else o=t,t.forEach((e=>this._invalidateLineToolOrStudyStub(e.id(),n)));o.forEach((e=>{if((0,K.isLineTool)(e)){this._setOriginalLineToolSharingMode(e.id(),e.sharingMode().value());const t=this._chartModel.lineToolsGroupModel().groupForLineTool(e);t&&this._setOriginalLineToolGroupsSharingMode(t.id,e.sharingMode().value())}})),this._allLineToolsAndStudyStubs.set(e.id(),s)}_unloadLineTools(e,t,i){ const s=e.filter((e=>!this._invalidatedLineToolsAndStudyStubs.has(e))).map((e=>this._chartModel.dataSourceForId(e))).filter(K.isLineTool).filter(w.notNull).filter((e=>e.sharingMode().value()===i)).filter(t).filter((e=>{const t=this._chartModel.lineToolsGroupModel().groupForLineTool(e);return null===t||!this._invalidatedLineToolGroups.has(t.id)}));this._withoutInvalidating((()=>{s.forEach((e=>{var t;e.hasAlert().value()&&e.detachAlert();const i=(0,r.ensureNotNull)(this._chartModel.paneForSource(e));this._chartModel.removeSource(e);(null!==(t=this._allLineToolsAndStudyStubs.get(i.id()))&&void 0!==t?t:new Map).delete(e.id())})),this._chartModel.lineToolsGroupModel().removeLineTools(s)}))}_unloadLinesOnSeries(e,t,i){const s=this._chartModel.mainSeries();if(!(null==i?void 0:i.size))return;const o=Array.from(i.keys()).filter((t=>!e(t)));this._unloadLineTools(o,(e=>e.boundToSymbol()&&e.ownerSource()===s),t)}_isAutosaveEnabled(){return Boolean(this._saveChartService&&this._saveChartService.autoSaveEnabled().value())}async _saveInvalidatedIfRequired(e,t){if(null!==this._lastBanTime){if(!(performance.now()-this._lastBanTime>=3e5))return Promise.resolve();this._lastBanTime=null}if(!this._isAutosaveEnabled()&&!t||this._options.readOnlyMode||!window.is_authenticated||""===this._origin.layoutId)return;const i=this.prepareDTO(e),s=ul.map((e=>{var t,s;const o=i.get(e);if(!o||null===o.sources)return null;const n=null!==(t=o.lineToolsToValidate)&&void 0!==t?t:Array.from(o.sources.keys()),a=null!==(s=o.groupsToValidate)&&void 0!==s?s:Array.from(o.groups.keys());if(0===n.length&&0===a.length)return null;const l=performance.now();if(o.sources.size||o.groups.size){const t=this._savingAbortControllersBySharingMode.get(e);t&&t.abort();const i=new AbortController;return this._savingAbortControllersBySharingMode.set(e,i),o.sources.forEach(((t,i)=>{t&&this._setOriginalLineToolSharingMode(i,e)})),(0,r.ensureNotNull)(this._saveChartService).saveChartLineTools(this._origin.chartId,o,e,i.signal).then((()=>{this.resetInvalidated(l,o,e)})).catch((async t=>{if(t instanceof nl.SavingLineToolsError&&t.shouldBeCooled&&(this._lastBanTime=performance.now()),!(0,hl.isAbortError)(t))throw t;_l.logDebug(`Save request has been aborted. ChartId: ${this._origin.chartId} sharingMode: ${e}`)}))}return this.resetInvalidated(l,o,e),null})).filter(w.notNull);return s.length?Promise.all(s).then((()=>{})):void 0}async _savePromise(e,t){var i,s;return this._isAutosaveEnabled()?null!==(s=null===(i=this._debouncedSave)||void 0===i?void 0:i.flush())&&void 0!==s?s:Promise.resolve():this._saveInvalidatedIfRequired(e,t)}_seriesLineToolsUnloader(e,t,i){const s=this._chartModel.mainSeries();"mainSeriesLineTools"===e.requestType&&s.symbolSameAsCurrent(e.symbol)&&(this._unloadLinesOnSeries(i,e.sharingMode,t),this._currentlyLoadedSymbol.set(e.sharingMode,e.symbol))}_mainPaneLineToolsAndStubs(){const e=this._chartModel.mainSeries(),t=(0,r.ensureNotNull)(this._chartModel.paneForSource(e));return new Map(this._allLineToolsAndStudyStubs.get(t.id()))}_onSymbolResolved(e){ const t=ul.map((t=>{const i={requestType:"mainSeriesLineTools",seriesSourceId:this._chartModel.mainSeries().id(),symbol:e.pro_name,brokerName:"",sharingMode:t},s=this._seriesLineToolsUnloader.bind(this,i,this._mainPaneLineToolsAndStubs());return this._makeLoadRequestAndMerge(i,s,e.pro_name||e.ticker||e.full_name)}));Promise.all(t).then((()=>{this._withoutInvalidating((()=>{this._chartModel.dataSources().filter(K.isLineTool).filter((e=>0===e.sharingMode().value()&&e.linkKey().value())).forEach((e=>{if(e.share(1),this._options.migrateSyncedLineTools){this._invalidateLineToolOrStudyStub(e.id(),performance.now(),!0);const t=this._chartModel.lineToolsGroupModel().groupForLineTool(e);t&&this._invalidateLineToolGroup(t.id,performance.now(),!0)}}))}))}))}async _makeLoadRequestAndMerge(e,t,i){var s;const o=this._chartModel.mainSeries(),r=null!==(s=this._currentlyLoadedSymbol.get(e.sharingMode))&&void 0!==s?s:"";if(!!o.symbolSameAsCurrent(r))return;this._currentlyLoadedSymbol.delete(e.sharingMode);const n=await(0,al.getChartStorage)();return this._savePromise("mainSeriesLineTools"===e.requestType).catch((()=>{})).then((()=>n.loadLineToolsAndGroups(this._origin.layoutId,this._origin.chartId,e,i))).catch((()=>null)).then((async i=>{if(null!==i&&null!==i.sources){const s=i.sources;t((e=>s.has(e))),await this._applyLineToolsAndGroupsDTO(i,e.sharingMode),i.serverRequestId&&console.log(`PROCESSED:${i.serverRequestId}`)}}))}_restoreGroups(e,t,i,s){const o=new Map;return(t.groups||new Map).forEach(((t,n)=>{const a=this._chartModel.lineToolsGroupModel().groupForId(n);if(null===t){if(a){const e=s&&s.layoutId===this._origin.layoutId&&s.chartId===this._origin.chartId;a.lineTools()[0].sharingMode().value()===i&&(e&&0!==i||(new gs(this._chartModel,a,a.lineTools()).redo(),this._setOriginalLineToolGroupsSharingMode(n,null)))}}else{if(a&&t.serverUpdateTime){const i=(0,r.ensureDefined)(t.serverUpdateTime);if(null!==e&&e>=i)return;a.setName(t.name)}else o.set(n,t);this._setOriginalLineToolGroupsSharingMode(n,i)}})),o}_createNewLineTool(e){const t=this._chartModel.dataSourceForId(e.ownerSource);if(null===t)return null;const i=(0,r.ensureNotNull)(this._chartModel.paneForSource(t)),s=this._chartModel.panes().indexOf(i),o=this._chartModel.restoreSource(!1,s,null,e.state,null);if(null!==o){const e=this._allLineToolsAndStudyStubs.get(i.id())||new Map;e.set(o.id(),o.linkKey().value()),this._allLineToolsAndStudyStubs.set(i.id(),e)}return o}_migrateStateFromMetainfo(e){const t=void 0!==e.symbol&&e.symbol!==e.state.state.symbol;t&&(e.state.state.symbol=e.symbol);const i=void 0!==e.currencyId&&e.currencyId!==e.state.state.currencyId;i&&(e.state.state.currencyId=e.currencyId);const s=void 0!==e.unitId&&e.unitId!==e.state.state.unitId;return s&&(e.state.state.unitId=e.unitId),t||i||s}_restoreLineTool(e,t,i,s){var o;if((null!==(o=t.state.points)&&void 0!==o?o:[]).some((e=>!(0,w.isNumber)(e.time_t))))return null;let r=this._chartModel.dataSourceForId(t.id);if(null===r&&t.state.linkKey&&(r=(0,K.lineToolByLinkKey)(this._chartModel,t.state.linkKey)), null!==r&&!(0,K.isLineTool)(r))return null;if(this._origin.clientId===(null==s?void 0:s.clientId)&&!r)return null;if(r&&t.serverUpdateTime){const o=t.serverUpdateTime,n=r.serverUpdateTime();if(null!==e&&e>=o||null!==n&&n>=o)return 0!==i&&(r.share(i),this._setOriginalLineToolSharingMode(r.id(),i)),this._restoreLineToolAlert(r,t.state.alertId),null;this._origin.clientId!==(null==s?void 0:s.clientId)&&(this._chartModel.restoreLineToolState(r,t.state,!1),r.sharingMode().value()!==i&&(r.share(i),this._setOriginalLineToolSharingMode(r.id(),i)),r.calcIsActualSymbol())}0!==i&&(t.ownerSource=this._chartModel.mainSeries().id(),t.state.ownerSource=this._chartModel.mainSeries().id());const n=this._migrateStateFromMetainfo(t);let a=r||this._createNewLineTool(t);if(a&&(n&&this._invalidateLineToolOrStudyStub(t.id,performance.now(),!0),t.serverUpdateTime&&a.setServerUpdateTime(t.serverUpdateTime),this._restoreLineToolAlert(a,t.state.alertId),0!==i&&a.share(i),void 0===s&&(0,K.isEditableTextLineTool)(a))){this._removeTextLineToolIfEmpty(a)&&(a=null)}return a}_restoreLineToolAlert(e,t){t?e.restoreAlert(+t,{syncFocusFromAlert:!0}).catch((e=>{_l.logError(`Failed to restore lineTool alert: ${Error,e}`)})):e.detachAlert()}_removeLineTool(e){const t=this._chartModel.dataSourceForId(e);null!==t&&new Cs(this._chartModel,[t],null).redo()}_removeTextLineToolIfEmpty(e){return!(!e.removeIfEditableTextIsEmpty()||0!==e.editableTextProperties().text.value().length)&&(this._chartModel.removeSource(e),this._invalidateLineToolOrStudyStub(e.id(),performance.now(),!0),!0)}_restoreLineDTO(e,t,i,s,o,n){if(!this._invalidatedLineToolsAndStudyStubs.get(t))if(null===e){const e=this._chartModel.dataSourceForId(t);if(!e)return;if(!(0,K.isLineTool)(e))return;e.sharingMode().value()===o&&this._origin.clientId!==(null==n?void 0:n.clientId)&&(this._removeLineTool(t),this._setOriginalLineToolSharingMode(t,null))}else{const a=this._restoreLineTool(s,e,o,n);if(a){if(e.groupId){const t=this._chartModel.lineToolsGroupModel().groupForLineTool(a),s=this._chartModel.lineToolsGroupModel().groupForId(e.groupId);if(null!==t&&s===t)return;if(null!==t&&(t.excludeLineTool(a),0===t.lineTools().length&&this._chartModel.lineToolsGroupModel().removeGroup(t)),s&&!s.containsLineTool(a))s.addLineTools([a]);else if(!s&&i.has(e.groupId)){const t=(0,r.ensureDefined)(i.get(e.groupId));this._chartModel.lineToolsGroupModel().createGroup([a],t.name,t.id)}}else{this._chartModel.lineToolsGroupModel().removeLineTools([a]).forEach((e=>{this._invalidateLineToolGroup(e,performance.now(),!0)}))}void 0===this._originalLineToolSharingMode.get(t)&&this._setOriginalLineToolSharingMode(t,o),this._setOriginalLineToolSharingMode(t,o)}}}async _applyLineToolsAndGroupsDTO(e,t,i){const s=this._chartModel.chartSaveTime(),o=this._withoutInvalidating((()=>this._restoreGroups(s,e,t,i))),r=`ChartStorage.Synchronizer.ApplyingDTO.${`${this._origin.layoutId}.${this._origin.chartId}`}`,n=new Set;(e.sources||new Map).forEach((e=>{e&&n.add(e.state.type)})),await Promise.all(Array.from(n).map((e=>(0,K.initLineTool)(e)))), (0,rl.perfMeasureOperation)(r,(()=>this._withoutInvalidating((()=>{(e.sources||new Map).forEach(((e,r)=>{try{if(e&&(0,Qt.isMtpPredictorToolName)(e.state.type))return void _l.logWarn(`No longer supported tool ${e.state.type} is skipped while restoring state`);this._restoreLineDTO(e,r,o,s,t,i)}catch(e){_l.logError(`Error restoring line tool ${r}: ${e}`)}})),(e.groups||new Map).forEach(((e,t)=>{this._invalidatedLineToolGroups.delete(t)})),this._recalculateHasChanges()}))))}_withoutInvalidating(e){try{return this._ignoreInvalidatingEventsDepth++,e()}finally{this._ignoreInvalidatingEventsDepth--}}_invalidateLineToolOrStudyStub(e,t,i){var s;if(this._ignoreInvalidatingEventsDepth>0&&!i)return;const o=null===(s=this._invalidatedLineToolsAndStudyStubs.get(e))||void 0===s?void 0:s.invalidatedViaSyncOnly,r=(void 0===o||o)&&this.invalidateViaSync();this._invalidatedLineToolsAndStudyStubs.set(e,{timestamp:t,invalidatedViaSyncOnly:r}),this._hasChanges.setValue(!0),this._debouncedSave()}_invalidateLineToolGroup(e,t,i){this._ignoreInvalidatingEventsDepth>0&&!i||(this._invalidatedLineToolGroups.set(e,{timestamp:t,invalidatedViaSyncOnly:this.invalidateViaSync()}),this._hasChanges.setValue(!0),this._debouncedSave())}_prepareDTOItem(e,t){const i=new Map,s=new Map,o=[],n=[];return this._invalidatedLineToolsAndStudyStubs.forEach(((n,a)=>{if(0!==t&&n.invalidatedViaSyncOnly)return void o.push(a);const l=this._chartModel.dataSourceForId(a);if(!(0,dl.isStudyLineToolStub)(l))if(null===l){this._originalLineToolSharingMode.get(a)===t&&i.set(a,null)}else{if(l===this._chartModel.lineBeingCreated()||l===this._chartModel.lineBeingEdited()||!l.isSavedInChart())return;const o=l.ownerSource()===this._chartModel.mainSeries(),n=!e||o,c=l.sharingMode().value()===t;if(n){const e=this._chartModel.lineToolsGroupModel().groupForLineTool(l);if(c)i.set(a,function(e,t){const i=t.lineToolsGroupModel().groupForLineTool(e),s={id:e.id(),ownerSource:(0,r.ensureNotNull)(e.ownerSource()).id(),state:e.state(!1)};return e.boundToSymbol()&&(s.symbol=e.symbol()),s.currencyId=e.properties().childs().currencyId.value(),s.unitId=e.properties().childs().unitId.value(),null!==i&&(s.groupId=i.id),s}(l,this._chartModel)),null!==e&&s.set(e.id,pl(e,this._chartModel));else{const o=this._originalLineToolSharingMode.get(a);o===t&&i.set(a,null),null!==e&&o===t&&s.set(e.id,null)}}}})),this._invalidatedLineToolGroups.forEach(((e,i)=>{if(0!==t&&e.invalidatedViaSyncOnly)n.push(i);else if(!s.has(i)){const e=this._chartModel.lineToolsGroupModel().groupForId(i);if(null===e){this._originalLineToolGroupsSharingMode.get(i)===t&&s.set(i,null)}else e.sharingMode().value()===t&&s.set(i,pl(e,this._chartModel))}})),{sources:i,groups:s,clientId:this._generateOrigin(),lineToolsToValidate:Array.from(i.keys()).concat(o),groupsToValidate:Array.from(s.keys()).concat(n)}}_setOriginalLineToolSharingMode(e,t){null!==t?this._originalLineToolSharingMode.set(e,t):this._originalLineToolSharingMode.delete(e)}_setOriginalLineToolGroupsSharingMode(e,t){ null!==t?this._originalLineToolGroupsSharingMode.set(e,t):this._originalLineToolGroupsSharingMode.delete(e)}_loadAndMergeLineToolsOnStudies(e,t){const i={requestType:"studiesLineTools",seriesSourceId:this._chartModel.mainSeries().id(),sharingMode:e},s=this._chartModel.mainSeries();this._makeLoadRequestAndMerge(i,(i=>{const o=t?(0,ol.default)(Array.from(this._allLineToolsAndStudyStubs.values()).map((e=>Array.from(e.keys())))).filter((e=>!i(e))):[];this._unloadLineTools(o,(e=>e.ownerSource()!==s),e)}))}_loadAndMergeLineToolsWithoutSymbol(e,t){const i={requestType:"lineToolsWithoutSymbol",seriesSourceId:this._chartModel.mainSeries().id(),sharingMode:e},s=this._chartModel.mainSeries(),o=(0,r.ensureNotNull)(this._chartModel.paneForSource(s)),n=this._allLineToolsAndStudyStubs.get(o.id());this._makeLoadRequestAndMerge(i,(i=>{const o=t&&n?Array.from(n.keys()).filter((e=>!i(e))):[];this._unloadLineTools(o,(e=>!e.boundToSymbol()&&e.ownerSource()===s),e)}))}_recalculateHasChanges(){const e=Array.from(this._invalidatedLineToolsAndStudyStubs.values()).some((e=>!e.savedToChartContent)),t=Array.from(this._invalidatedLineToolGroups.values()).some((e=>!e.savedToChartContent));this._hasChanges.setValue(e||t)}_generateOrigin(){return`${this._origin.layoutId}/${this._origin.chartId}/${this._origin.clientId}`}}var fl=i(631110),bl=i(67302),yl=i(232650),Cl=i(700134),wl=i(72368),Pl=i(105580),Tl=i(854798),Ml=i(396231),xl=i(982368);var Il=i(523359),Al=i(167975);function Ll(e){return e.hasModel()?e.model().mainSeries().proSymbol():e.symbolWV().value()}var kl=i(167222);const El={};function Dl(e,t){return{...t,iconId:"Watchlist.AddSymbol",icon:xl.icons.get("Watchlist.AddSymbol"),statName:"AddToWatchlist",hotkeyHash:at.Modifiers.Alt+87,onExecute:()=>{(0,kl.runOrSigninWithFeature)((()=>{!function(e){if(!window.widgetbar)return;const t=(0,r.ensureNotNull)(window.widgetbar.setPage("base")).widget("watchlist");t&&(t.widgetObject?e(t.widgetObject):(t.widgetStarted().unsubscribeAll(El),t.widgetStarted().subscribe(El,(t=>e(t.widgetObject)),!0)))}((t=>{null==t||t.addSymbols([Ll(e)])}))}),{feature:"watchList",source:"add symbol to watchlist"})}}}var Bl=i(306388),Nl=i(826939),Rl=i(440498);class Ol extends ot.Action{constructor(e,t){super({actionId:"Chart.AddSymbolToWatchList",options:{...Dl(e,t),subItems:[new ot.Loader("Loading")]}}),this._hadSymbolOnInit=!1,this._isMobile=(0,wl.isMobile)(),this._onRequest=null,this._unsubscribe=null,this._chart=e,this._load()}updateLabel(e){this.update({label:a.t(null,void 0,i(655980)).format({symbol:e})})}request(){var e;this._hadSymbolOnInit=!1,this._isMobile=(0,wl.isMobile)(),this.update({subItems:[new ot.Loader("Loading")]}),null===(e=this._onRequest)||void 0===e||e.call(this)}destroy(){var e;super.destroy(),null===(e=this._unsubscribe)||void 0===e||e.call(this),this._chart=null,this._onRequest=null}async _load(){const[e,t,s,o,r,n,l]=await Promise.all([Promise.resolve().then(i.t.bind(i,50959,19)),(0, Bl.initSymbolListService)(),Promise.all([i.e(32662),i.e(5987),i.e(98996),i.e(43387),i.e(66458),i.e(4343),i.e(44597),i.e(1413),i.e(52078),i.e(19216),i.e(16005),i.e(16165),i.e(90385),i.e(42942),i.e(5483),i.e(62526),i.e(3889),i.e(92158),i.e(17774),i.e(5069),i.e(44692),i.e(1026)]).then(i.bind(i,38506)),Promise.all([i.e(32662),i.e(5987),i.e(98996),i.e(43387),i.e(66458),i.e(4343),i.e(44597),i.e(1413),i.e(52078),i.e(19216),i.e(16005),i.e(16165),i.e(90385),i.e(42942),i.e(5483),i.e(62526),i.e(3889),i.e(92158),i.e(17774),i.e(5069),i.e(44692),i.e(1026)]).then(i.bind(i,244692)),Promise.all([i.e(14819),i.e(73224),i.e(80937),i.e(32662),i.e(5987),i.e(98996),i.e(43387),i.e(66458),i.e(5761),i.e(4343),i.e(28430),i.e(70428),i.e(44597),i.e(1413),i.e(52078),i.e(89508),i.e(61204),i.e(19216),i.e(37132),i.e(66323),i.e(50473),i.e(36827),i.e(84331),i.e(85258),i.e(36701),i.e(16005),i.e(87940),i.e(61576),i.e(63276),i.e(82452),i.e(77382),i.e(16165),i.e(85131),i.e(94712),i.e(91986),i.e(44794),i.e(39076),i.e(71093),i.e(45338),i.e(85686),i.e(29946),i.e(47877),i.e(67154),i.e(57254),i.e(42616),i.e(85573),i.e(6143),i.e(43242),i.e(27990),i.e(77538),i.e(92541),i.e(64730),i.e(77504),i.e(14108),i.e(22375),i.e(84650),i.e(90385),i.e(92833),i.e(42942),i.e(5483),i.e(60801),i.e(41167),i.e(60581),i.e(3889),i.e(92158),i.e(17774),i.e(30666),i.e(48662),i.e(23852),i.e(13506),i.e(90968),i.e(41412),i.e(91196)]).then(i.bind(i,291676)),Promise.all([i.e(14819),i.e(73224),i.e(80937),i.e(32662),i.e(5987),i.e(98996),i.e(43387),i.e(66458),i.e(5761),i.e(4343),i.e(28430),i.e(70428),i.e(44597),i.e(1413),i.e(52078),i.e(89508),i.e(61204),i.e(19216),i.e(37132),i.e(66323),i.e(50473),i.e(36827),i.e(84331),i.e(85258),i.e(36701),i.e(16005),i.e(87940),i.e(61576),i.e(63276),i.e(82452),i.e(77382),i.e(16165),i.e(85131),i.e(94712),i.e(91986),i.e(44794),i.e(39076),i.e(71093),i.e(45338),i.e(85686),i.e(29946),i.e(47877),i.e(67154),i.e(57254),i.e(42616),i.e(85573),i.e(6143),i.e(43242),i.e(27990),i.e(77538),i.e(92541),i.e(64730),i.e(77504),i.e(14108),i.e(22375),i.e(84650),i.e(90385),i.e(92833),i.e(42942),i.e(5483),i.e(60801),i.e(41167),i.e(60581),i.e(3889),i.e(92158),i.e(17774),i.e(30666),i.e(48662),i.e(23852),i.e(13506),i.e(90968),i.e(41412),i.e(91196)]).then(i.bind(i,436779)),Promise.all([i.e(14819),i.e(73224),i.e(80937),i.e(32662),i.e(5987),i.e(98996),i.e(43387),i.e(66458),i.e(5761),i.e(4343),i.e(28430),i.e(70428),i.e(44597),i.e(1413),i.e(52078),i.e(89508),i.e(61204),i.e(19216),i.e(37132),i.e(66323),i.e(50473),i.e(36827),i.e(84331),i.e(85258),i.e(36701),i.e(16005),i.e(87940),i.e(61576),i.e(63276),i.e(82452),i.e(77382),i.e(16165),i.e(85131),i.e(94712),i.e(91986),i.e(44794),i.e(39076),i.e(71093),i.e(45338),i.e(85686),i.e(29946),i.e(47877),i.e(67154),i.e(57254),i.e(42616),i.e(85573),i.e(6143),i.e(43242),i.e(27990),i.e(77538),i.e(92541),i.e(64730),i.e(77504),i.e(14108),i.e(22375),i.e(84650),i.e(90385),i.e(92833),i.e(42942),i.e(5483),i.e(60801),i.e(41167),i.e(60581),i.e(3889),i.e(92158),i.e(17774),i.e(30666),i.e(48662),i.e(23852),i.e(13506),i.e(90968),i.e(41412),i.e(91196)]).then(i.bind(i,631530))]) ;if(this._destroyed)return;const{store:c}=t;this._onRequest=()=>c.dispatch(s.getCustomWatchlistsThunk(null)),this._unsubscribe=c.subscribe((()=>{if(!this._chart)return;const t=c.getState();if(null===r.getCustomListsState(t).timestamp)return;const s=Ll(this._chart),d=r.getCustomLists(t),{activeSymbolList:h}=t,u=d.find((e=>e.id===h));this._hadSymbolOnInit||(this._hadSymbolOnInit=!!u&&u.symbols.includes(s));const _=D.enabled("multiple_watchlists")?d.filter((e=>e.id!==h)).sort(n.sortComparator):[];let p=u?[u,..._]:_;p=p.filter((e=>!(0,Rl.isDeletedSymbolsList)(e.id)));const m=p.map((t=>{const i=t.symbols.includes(s),r={shortcutHint:t.id===h?(0,at.humanReadableHash)(at.Modifiers.Alt+87):void 0,invisibleHotkey:t.id===h?i:void 0,doNotCloseOnClick:!0,onExecute:()=>{const e=i?o.removeSymbolsThunk(Nl.WATCHLIST_WIDGET_ID,s,t.id,!0):o.addSymbolsToCustomListThunk(Nl.WATCHLIST_WIDGET_ID,t.id,[s]);t.id!==h||window.is_authenticated||this._hadSymbolOnInit?c.dispatch(e):window.runOrSignIn((()=>{c.dispatch(e)}),{source:"Chart context menu"})}};return new ot.Action({actionId:"Watchlist.Actions",options:{...r,label:t.name,checkable:!0,checked:i},customActionOptions:{...r,jsxLabel:e.createElement(l.ContextMenuWatchlistItem,{title:t.name,isChecked:i,isSmallSize:this._isMobile})}})})),g=new ot.Action({actionId:"Watchlist.Create",options:{label:(0,Al.appendEllipsis)(a.t(null,void 0,i(732340))),iconId:this._isMobile?"Watchlist.CreateNew":void 0,onExecute:()=>{(0,br.runOrGoPro)((()=>{c.dispatch(o.userCreateWatchlistThunk(null,{symbols:[s]}))}),"MULTIPLE_WATCHLISTS",{feature:"multipleWatchLists",featureLocation:"moveSymbolsToNew"})}}});this.update({subItems:[...m,new ot.Separator,g]})}))}}var Vl=i(263955),Wl=i(516684);function Fl(){const e=window.widgetbar;if(e){const t=(0,r.ensureNotNull)(e.setPage("object_tree")),i=(0,r.ensureNotNull)(t.widget("object_tree"));(0,r.ensureDefined)(i.properties).setValue({selectedPage:"data-window"})}else;}var Hl=i(568247),zl=i(277774);var Ul=i(230296);function Gl(e){const t=e.options(),s={label:(0,Al.appendEllipsis)(fl.t(null,void 0,i(699374))),statName:"ChangeInterval",onExecute:()=>(0,Ul.showChangeIntervalDialogAsync)({initVal:ho.linking.interval.value(),selectOnInit:!0})};return!(0,D.enabled)("show_interval_dialog_on_key_press")||t.readOnly||t.hideSymbolSearch||(s.shortcutHint=",",s.hotkeyGroup=e.hotkeys(),s.hotkeyHash=188),new ot.Action({actionId:"Chart.Dialogs.ShowChangeInterval",options:s})}class ql extends ot.Action{constructor(e,t=new O.WatchedValue(!1)){super({...e,options:{...e.options,checkable:!0,checked:t.value(),onExecute:()=>{this._wv.setValue(!this._wv.value())}}}),this._updateChecked=e=>{this.update({checked:e})},t.subscribe(this._updateChecked),this._wv=t}destroy(){this._wv.unsubscribe(this._updateChecked),super.destroy()}}var jl=i(197050) ;const Zl=new R.TranslatedString("scale price chart only",fl.t(null,void 0,i(599042))),Kl=new R.TranslatedString("stay in drawing mode",fl.t(null,void 0,i(52010))),Yl=new R.TranslatedString("hide marks on bars",fl.t(null,void 0,i(744974))),$l=new R.TranslatedString("change symbol last value visibility",fl.t(null,void 0,i(253150))),Xl=new R.TranslatedString("change symbol previous close value visibility",fl.t(null,void 0,i(112707))),Jl=new R.TranslatedString("change previous close price line visibility",fl.t(null,void 0,i(259883))),Ql=new R.TranslatedString("change symbol labels visibility",fl.t(null,void 0,i(109402))),ec=new R.TranslatedString("change indicators and financials value labels visibility",fl.t(null,void 0,i(90512))),tc=new R.TranslatedString("change indicators and financials name labels visibility",fl.t(null,void 0,i(559820))),ic=new R.TranslatedString("change bid and ask labels visibility",fl.t(null,void 0,i(805100))),sc=new R.TranslatedString("change bid and ask lines visibility",fl.t(null,void 0,i(432311))),oc=new R.TranslatedString("change pre/post market price label visibility",fl.t(null,void 0,i(549889))),rc=new R.TranslatedString("change pre/post market price line visibility",fl.t(null,void 0,i(16750))),nc=new R.TranslatedString("change high and low price labels visibility",fl.t(null,void 0,i(466805))),ac=new R.TranslatedString("change high and low price lines visibility",fl.t(null,void 0,i(992556))),lc=(new R.TranslatedString("change average close price label visibility",fl.t(null,void 0,i(739402))),new R.TranslatedString("change average close price line visibility",fl.t(null,void 0,i(498866))),new R.TranslatedString("change countdown to bar close visibility",fl.t(null,void 0,i(58108)))),cc=new R.TranslatedString("change plus button visibility",fl.t(null,void 0,i(450190))),dc=new R.TranslatedString("change session breaks visibility",fl.t(null,void 0,i(115403))),hc=new R.TranslatedString("change price line visibility",fl.t(null,void 0,i(867761)));function uc(e){const t=e.hotkeys(),s=e.model(),o=e.options(),r=e.properties(),l=new ot.Action({actionId:"Chart.Series.PriceScale.ToggleInvertPriceScale",options:{label:fl.t(null,void 0,i(353239)),statName:"Invert Scale",checkable:!0,onExecute:()=>s.invertPriceScale(s.mainSeries().priceScale()),hotkeyGroup:t,hotkeyHash:n.Modifiers.Alt+73}}),d=new ot.Action({actionId:"Chart.Series.PriceScale.ToggleAutoScale",options:{label:fl.t(null,void 0,i(550834)),checkable:!0,onExecute:e=>{const t=s.mainSeries().priceScale();s.togglePriceScaleAutoScaleMode(t),e.update({checked:t.isAutoScale()})}}}),h=new ot.Action({actionId:"Chart.Scales.ToggleLockPriceToBarRatio",options:{label:fl.t(null,void 0,i(518219)),checkable:!0,statName:"ToggleLockScale",onExecute:()=>s.togglePriceScaleLockScaleMode(s.mainSeries().priceScale())}}),_=new ot.Action({actionId:"Chart.Series.PriceScale.ToggleRegular",options:{label:fl.t(null,{context:"scale_menu"},i(172116)),checkable:!0,statName:"ToggleRegularScale",onExecute:e=>{const t=s.mainSeries().priceScale() ;s.setPriceScaleRegularScaleMode(t),e.update({checked:t.isRegular()})}}}),p=new ot.Action({actionId:"Chart.Series.PriceScale.TogglePercentage",options:{label:fl.t(null,void 0,i(351102)),checkable:!0,statName:"TogglePercantage",onExecute:()=>s.togglePriceScalePercentageScaleMode(s.mainSeries().priceScale()),hotkeyGroup:t,hotkeyHash:n.Modifiers.Alt+80}}),m=new ot.Action({actionId:"Chart.Series.PriceScale.ToggleIndexedTo100",options:{label:fl.t(null,void 0,i(520062)),checkable:!0,statName:"ToggleIndexedTo100",onExecute:()=>s.togglePriceScaleIndexedTo100ScaleMode(s.mainSeries().priceScale())}}),g=new ot.Action({actionId:"Chart.Series.PriceScale.ToggleLogarithmic",options:{label:fl.t(null,void 0,i(512285)),statName:"ToggleLogScale",checkable:!0,onExecute:()=>s.togglePriceScaleLogScaleMode(s.mainSeries().priceScale()),hotkeyGroup:t,hotkeyHash:n.Modifiers.Alt+76}}),S=new ot.Action({actionId:"Chart.ChangeTimeZone",options:{label:fl.t(null,void 0,i(164375)),statName:"TimeZone"}}),b=new gt.ActionWithStandardIcon({actionId:"Chart.TimeScale.Reset",options:{label:fl.t(null,void 0,i(825333)),iconId:"Chart.Reset",statName:"ResetScale",onExecute:()=>s.resetTimeScale(),hotkeyGroup:e.hotkeys(),hotkeyHash:n.Modifiers.Mod+n.Modifiers.Alt+81}}),y=new ot.Action({actionId:"Chart.Dialogs.ShowInsertIndicators",options:{label:(0,Al.appendEllipsis)(fl.t(null,void 0,i(398767))),statName:"InsertIndicator",onExecute:()=>e.showIndicators(),...o.indicatorsDialogShortcutEnabled?{hotkeyGroup:t,hotkeyHash:191}:void 0}}),C=new ot.Action({actionId:"Chart.Dialogs.ShowCompareOrAddSymbol",options:{label:(0,Al.appendEllipsis)(fl.t(null,void 0,i(220229))),statName:"CompareOrAddSymbol",onExecute:()=>e.toggleCompareOrAdd()}}),w=new gt.ActionWithStandardIcon({actionId:"Chart.Dialogs.ShowGeneralSettings",options:{label:(0,Al.appendEllipsis)(fl.t(null,void 0,i(389517))),iconId:"Settings",statName:"ChartProperties",onExecute:()=>e.showGeneralChartProperties()}}),P=new gt.ActionWithStandardIcon({actionId:"Chart.Dialogs.ShowGeneralSettings.SymbolTab",options:{label:(0,Al.appendEllipsis)(fl.t(null,void 0,i(389517))),iconId:"Settings",statName:"MainSeriesProperties",onExecute:()=>e.showGeneralChartProperties(U.TabNames.symbol)}}),T=new gt.ActionWithStandardIcon({actionId:"Chart.Dialogs.ShowGeneralSettings.ScalesTab",options:{label:(0,Al.appendEllipsis)(fl.t(null,void 0,i(389517))),iconId:"Settings",statName:"ScalesProperties",onExecute:()=>e.showGeneralChartProperties(U.TabNames.scales)}}),M=new ot.Action({actionId:"Chart.SelectedObject.ToggleLocked",options:{label:fl.t(null,void 0,i(101441)),statName:"ToggleLockSelectedObject",onExecute:()=>e.toggleLockSelectedObject()}}),x=new gt.ActionWithStandardIcon({actionId:"Chart.SelectedObject.Hide",options:{label:fl.t(null,void 0,i(831971)),iconId:"Chart.Hide",statName:"HideSelectedObject",onExecute:()=>e.hideSelectedObject()}}),I=new nt({actionId:"Chart.PriceScale.ToggleAutoScaleSeriesOnly",options:{label:fl.t(null,void 0,i(937207)),checkable:!0,statName:"ScalePriceChartOnly"}},{ property:r.childs().scalesProperties.childs().scaleSeriesOnly,undoModel:s,undoText:Zl}),A=new ql({actionId:"Chart.DrawingToolbar.ToggleVisibility",options:{label:fl.t(null,void 0,i(222903)),statName:"ToggleDrawingToolbar"}},o.isDrawingToolbarVisible),L=new nt({actionId:"",options:{label:fl.t(null,void 0,i(593161)),checkable:!0,statName:"ToggleStayInDrawingMode"}},{property:Oe.properties().childs().stayInDrawingMode,undoModel:s,undoText:Kl}),k=new nt({actionId:"Chart.Marks.ToggleVisibility",options:{label:fl.t(null,void 0,i(2441)),checkable:!0,statName:"ToggleHideMarksOnBars"}},{property:Oe.hideMarksOnBars(),undoModel:s,undoText:Yl,callback:e=>Oe.hideMarksOnBars().setValue(e.isChecked())}),E=new nt({actionId:"Chart.PriceScale.Labels.ToggleSeriesLastValueVisibility",options:{label:fl.t(null,void 0,i(752054)),checkable:!0,checked:!1,statName:"ToggleSymbolLastValue"}},{property:r.childs().scalesProperties.childs().showSeriesLastValue,undoModel:s,undoText:$l}),B=new nt({actionId:"Chart.PriceScale.Labels.ToggleSymbolNameLabelsVisibility",options:{label:fl.t(null,void 0,i(390932)),checkable:!0,checked:!1,statName:"ToggleSymbolLabels"}},{property:r.childs().scalesProperties.childs().showSymbolLabels,undoModel:s,undoText:Ql}),N=(0,jl.combineProperty)(((e,t)=>e||t),r.childs().scalesProperties.childs().showStudyLastValue.weakReference(),r.childs().scalesProperties.childs().showFundamentalLastValue.weakReference()),R=new nt({actionId:"Chart.PriceScale.Labels.ToggleIndicatorsValueLabelsVisibility",options:{label:fl.t(null,void 0,i(192945)),checkable:!0,checked:!1,statName:"ToggleStudiesAndFundamentalsPriceLabels",onDestroy:()=>{N.destroy()}}},{property:N,undoModel:s,undoText:null,callback:()=>{const e=!N.value();s.beginUndoMacro(ec),s.setProperty(r.childs().scalesProperties.childs().showStudyLastValue,e,null),s.setProperty(r.childs().scalesProperties.childs().showFundamentalLastValue,e,null),s.endUndoMacro()}}),O=(0,jl.combineProperty)(((e,t)=>e||t),r.childs().scalesProperties.childs().showStudyPlotLabels.weakReference(),r.childs().scalesProperties.childs().showFundamentalNameLabel.weakReference()),V=new nt({actionId:"Chart.PriceScale.Labels.ToggleIndicatorsNameLabelsVisibility",options:{label:fl.t(null,void 0,i(47587)),checkable:!0,checked:!1,statName:"ToggleStudiesAndFundamentalsNameLabels",onDestroy:()=>{O.destroy()}}},{property:O,undoModel:s,undoText:null,callback:()=>{const e=!O.value();s.beginUndoMacro(tc),s.setProperty(r.childs().scalesProperties.childs().showStudyPlotLabels,e,null),s.setProperty(r.childs().scalesProperties.childs().showFundamentalNameLabel,e,null),s.endUndoMacro()}}),W=s.mainSeries().properties().childs().highLowAvgPrice.childs(),F=new nt({actionId:"Chart.PriceScale.Labels.ToggleHighLowPriceLabelsVisibility",options:{label:fl.t(null,void 0,i(953150)),checkable:!0,checked:!1,statName:"ToggleHighLowPriceLabels"}},{property:W.highLowPriceLabelsVisible,undoModel:s,undoText:nc}),H=new nt({actionId:"Chart.Lines.ToggleHighLowLinesVisibility",options:{label:fl.t(null,void 0,i(321803)),checkable:!0,checked:!1, statName:"ToggleHighLowPriceLine"}},{property:W.highLowPriceLinesVisible,undoModel:s,undoText:ac}),z=new nt({actionId:"Chart.PriceScale.ToggleCountdownToBarCloseVisibility",options:{label:fl.t(null,void 0,i(894370)),checkable:!0,checked:!1,statName:"ToggleCountdown"}},{property:s.mainSeries().properties().childs().showCountdown,undoModel:s,undoText:lc}),G=new nt({actionId:"Chart.PriceScale.ToggleAddOrderPlusButtonVisibility",options:{label:fl.t(null,void 0,i(897378)),checkable:!0,checked:xn.addPlusButtonProperty.value(),statName:"ToggleAddOrderPlusButton"}},{property:xn.addPlusButtonProperty,undoModel:s,undoText:cc}),j=new gt.ActionWithStandardIcon({actionId:"Chart.Dialogs.ShowSymbolInfo",options:{label:(0,Al.appendEllipsis)((0,wl.isMobile)()?fl.t(null,void 0,i(358021)):fl.t(null,void 0,i(979758))),iconId:"Chart.SymbolInfo",checkable:!1,statName:"SymbolInfo",onExecute:()=>{if((0,wl.isMobile)())(0,D.enabled)("mobile_app_action_open_details_webview")&&o.onDetailsWebviewOpen?o.onDetailsWebviewOpen():(0,Pl.showDetailsDialog)(),(0,u.trackEvent)("ContextMenuClick","Mobile","SymbolInfo");else{const t=e.model().model(),i=t.mainSeries().symbolInfo();if(i){const e=t.availableUnits(),s=t.unitConversionEnabled();(0,Hl.showSymbolInfoDialog)({symbolInfo:i,showUnit:s,unitDescription:t=>t?e.description(t):"",dateFormatter:t.dateFormatter()})}}}}}),Z=new ot.Action({actionId:"Chart.PriceScale.MergeAllScalesToLeft",options:{label:fl.t(null,void 0,i(615241)),statName:"MergeAllScalesToLeft",onExecute:()=>s.mergeAllScales("left")}}),K=new ot.Action({actionId:"Chart.PriceScale.MergeAllScalesToRight",options:{label:fl.t(null,void 0,i(529404)),statName:"MergeAllScalesToRight",onExecute:()=>s.mergeAllScales("right")}}),Y=new ot.Action({actionId:"Chart.PriceScale.MoveToLeft",options:{label:fl.t(null,void 0,i(844302)),statName:"MoveScaleToLeft",onExecute:()=>s.mergeAllScales("left")}}),$=new ot.Action({actionId:"Chart.PriceScale.MoveToRight",options:{label:fl.t(null,void 0,i(994338)),statName:"MoveScaleToRight",onExecute:()=>s.mergeAllScales("right")}}),X=new gt.ActionWithStandardIcon({actionId:"Chart.Scales.Reset",options:{label:fl.t(null,void 0,i(834301)),iconId:"Chart.Reset",statName:"ResetChart",onExecute:()=>e.GUIResetScales(),hotkeyGroup:t,hotkeyHash:n.Modifiers.Alt+82}}),J=new nt({actionId:"Chart.SessionBreaks.ToggleVisibility",options:{label:fl.t(null,void 0,i(259827)),checkable:!0,statName:"ToggleSessionBreaks"}},{property:s.model().sessions().properties().childs().graphics.childs().vertlines.childs().sessBreaks.childs().visible,undoModel:s,undoText:dc}),Q=new nt({actionId:"Chart.Lines.ToggleSeriesPriceLineVisibility",options:{label:fl.t(null,void 0,i(491492)),checkable:!0,statName:"TogglePriceLine"}},{property:s.mainSeries().properties().childs().showPriceLine,undoModel:s,undoText:hc}),ee=new ot.Action({actionId:"Chart.Undo",options:{label:fl.t(null,void 0,i(881320)),onExecute:()=>{(0,u.trackEvent)("GUI","Undo"),s.undoHistory().undo()},onDestroy:()=>{e.model().undoHistory().undoStack().onChange().unsubscribeAll(ee)},disabled:!0, hotkeyGroup:t,hotkeyHash:n.Modifiers.Mod+90,isRepeatAccepted:!0}});e.model().undoHistory().undoStack().onChange().subscribe(ee,(()=>ee.update({disabled:e.model().undoHistory().undoStack().isEmpty()})));const te=new ot.Action({actionId:"Chart.Redo",options:{label:fl.t(null,void 0,i(641615)),onExecute:()=>{(0,u.trackEvent)("GUI","Redo"),e.model().undoHistory().redo()},onDestroy:()=>{e.model().undoHistory().redoStack().onChange().unsubscribeAll(te)},disabled:!0,hotkeyGroup:t,hotkeyHash:n.Modifiers.Mod+89,isRepeatAccepted:!0}});e.model().undoHistory().redoStack().onChange().subscribe(te,(()=>te.update({disabled:e.model().undoHistory().redoStack().isEmpty()})));const ie={invertSeriesScale:l,autoSeriesScale:d,lockSeriesScale:h,regularSeriesScale:_,percentSeriesScale:p,indexedTo100SeriesScale:m,logSeriesScale:g,applyTimeZone:S,symbolSearch:new ot.Action({actionId:"Chart.Dialogs.ShowChangeSymbol",options:{label:(0,Al.appendEllipsis)(a.t(null,void 0,i(128089))),statName:"ChangeSymbol",onExecute:()=>{(0,v.showDialog)({defaultValue:"",trackResultsOptions:{trackResults:!D.enabled("widget"),emptySearchType:"empty_result__supercharts"}})}}}),changeInterval:Gl(e),timeScaleReset:b,insertIndicator:y,compareOrAdd:C,chartProperties:w,mainSeriesPropertiesAction:P,scalesProperties:T,lineToggleLock:M,seriesHide:x,studyHide:x,lineHide:x,scaleSeriesOnly:I,drawingToolbarAction:A,stayInDrawingModeAction:L,hideAllMarks:k,showSeriesLastValue:E,showSymbolLabelsAction:B,showStudyLastValue:R,showStudyPlotNamesAction:V,showHighLowPriceLabels:F,showHighLowPriceLines:H,showCountdown:z,addPlusButton:G,showSymbolInfoDialog:j,mergeLeftScalesAction:Z,mergeRightScalesAction:K,moveScaleToLeft:Y,moveScaleToRight:$,chartReset:X,sessionBreaks:J,showPriceLine:Q,undo:ee,redo:te};o.goToDateEnabled&&(ie.gotoDate=new ot.Action({actionId:"Chart.Dialogs.ShowGoToDate",options:{label:(0,Al.appendEllipsis)(fl.t(null,void 0,i(475190))),statName:"GoToDate",onExecute:()=>(0,zl.showGoToDateDialog)(e.chartWidgetCollection().activeChartWidget.value()),hotkeyGroup:t,hotkeyHash:n.Modifiers.Alt+71}})),(0,D.enabled)("show_object_tree")&&(ie.paneObjectTree=new ot.Action({actionId:"Chart.ObjectTree.Show",options:{label:(0,Al.appendEllipsis)(fl.t(null,void 0,i(500675))),statName:"ObjectsTree",onExecute:()=>e.showObjectsTreePanelOrDialog()}})),(0,D.enabled)("property_pages")&&(ie.format=new gt.ActionWithStandardIcon({actionId:"Chart.SelectedObject.ShowSettingsDialog",options:{label:(0,Al.appendEllipsis)(fl.t(null,void 0,i(389517))),iconId:"Settings",statName:"EditSelectedObject",onExecute:()=>e.showSelectedSourcesProperties()}})),e.readOnly()||(ie.paneRemoveAllStudies=new ot.Action({actionId:"Chart.RemoveAllIndicators",options:{label:fl.t(null,void 0,i(413951)),statName:"RemoveAllIndicators",onExecute:()=>e.removeAllStudies()}}),ie.paneRemoveAllDrawingTools=new ot.Action({actionId:"Chart.RemoveAllLineTools",options:{label:fl.t(null,void 0,i(801434)),statName:"RemoveAllDrawingTools",onExecute:()=>e.removeAllDrawingTools()}}),ie.paneRemoveAllStudiesDrawingTools=new ot.Action({ actionId:"Chart.RemoveAllIndicatorsAndLineTools",options:{label:fl.t(null,void 0,i(897305)),statName:"RemoveAllIndicatorsAndDrawingTools",onExecute:()=>e.removeAllStudiesDrawingTools()}}),ie.applyStudiesToAllCharts=new ot.Action({actionId:"Chart.ApplyIndicatorsToAllCharts",options:{label:fl.t(null,void 0,i(295910)),statName:"ApplyIndicatorsToAllCharts",onExecute:()=>e.chartWidgetCollection().applyIndicatorsToAllCharts(e)}}),ie.studyRemove=ie.lineRemove=new gt.ActionWithStandardIcon({actionId:"Chart.SelectedObject.Remove",options:{label:fl.t(null,void 0,i(734596)),iconId:"Chart.RemoveSelectedObject",statName:"RemoveSelectedObject",onExecute:()=>{var t;(null!==(t=e.chartWidgetCollection().activeChartWidget.value())&&void 0!==t?t:e).removeSelectedSources()},hotkeyGroup:t,hotkeyHash:n.isMacKeyboard?8:46}})),(0,c.onWidget)()||(0,D.enabled)("text_notes")&&(ie.addToTextNotes=function(e){return new ot.Action({actionId:"Note.Create",options:{iconId:"TextNote.Add",icon:xl.icons.get("TextNote.Add"),label:a.t(null,void 0,i(534999)),statName:"AddToTextNotes",onExecute:()=>{window.runOrSignIn((()=>{var t;null===(t=window.widgetbar)||void 0===t||t.setPage("base"),(0,Ml.createSymbolNote)(e.symbolWV().value(),(0,wl.isMobile)())}),{source:"Add text note in chart context menu"})},hotkeyHash:at.Modifiers.Alt+78,hotkeyGroup:e.hotkeys()}})}(e)),window.is_authenticated&&((0,bl.showThemeSwitcher)()||(0,bl.showThemeAction)())&&(ie.applyColorTheme=new ot.Action({actionId:"Chart.Theme.Apply",options:{name:"apply-color-theme",label:fl.t(null,void 0,i(132409)),iconId:"Platform.ColorTheme",icon:xl.icons.get("Platform.ColorTheme"),subItems:[new ot.Action({actionId:"Loading",options:{label:fl.t(null,void 0,i(25911))}})],statName:"ColorTheme"}})),o.showFinancialsEnabled&&(ie.showFinancials=new gt.ActionWithStandardIcon({actionId:"Chart.Dialogs.ShowInsertFinancials",options:{label:(0,Al.appendEllipsis)(fl.t(null,void 0,i(677720))),iconId:"Chart.Financials",statName:"Financials",onExecute:()=>{(0,D.enabled)("mobile_app_action_open_financials_webview")?(0,yl.openFinancialsWebview)(new URLSearchParams):(0,Cl.showFinancialsDialog)(),window.matchMedia("screen and (max-width: 430px)").matches&&(0,u.trackEvent)("ContextMenuClick","","Financials"),(0,Yt.getTracker)().then((e=>{null==e||e.trackFinancialsDialog(ho.linking.ensuredProSymbol.value(),"contextMenu")}))}}})),(0,D.enabled)("show_source_code")&&(ie.viewSourceCode=new ot.Action({actionId:"Chart.Indicator.PineSource",options:{label:(0,Al.appendEllipsis)(fl.t(null,void 0,i(966324))),statName:"OpenSelectedObjectSource",onExecute:()=>{if(!window.TradingView.bottomWidgetBar)return;const[e]=s.selection().dataSources();if(!(0,q.isStudy)(e))return;const t=e.metaInfo();t&&t.scriptIdPart&&t.pine&&(0,Wl.getPineSourceCode)(t.scriptIdPart,t.pine.version).done((e=>{if(!e)return;const{bottomWidgetBar:i}=window.TradingView;if(!i)return;const{lastVersionMaj:s,scriptName:o,scriptTitle:r,version:n,source:a}=e,l=s?Tl.Version.parse(s):new Tl.Version(0,0);i.activateScriptEditorTab({scriptSource:a,scriptName:o,scriptTitle:r, version:n,scriptIdPart:t.scriptIdPart,isOld:!l.isZero()&&l.major()!==Tl.Version.parse(n).major()})})).fail(Vl.showScriptInfoErrorNoticeDialog)}}}));{const e=ie.showPrePostMarketPriceLabel=new nt({actionId:"Chart.PriceScale.Labels.TogglePrePostMarketLabelsVisibility",options:{label:fl.t(null,void 0,i(11240)),checkable:!0,checked:!1,statName:"TogglePrePostMarketPriceLabel",onDestroy:()=>{s.mainSeries().isPrePostMarketPricesAvailableProperty().unsubscribeAll(e)}}},{property:r.childs().scalesProperties.childs().showPrePostMarketPriceLabel,undoModel:s,undoText:oc});s.mainSeries().isPrePostMarketPricesAvailableProperty().subscribe(e,(t=>{e.update({disabled:!t.value()})}))}{const e=ie.showPrePostMarketPriceLine=new nt({actionId:"Chart.Lines.TogglePrePostMarketPriceLineVisibility",options:{label:fl.t(null,void 0,i(296768)),checkable:!0,checked:!1,statName:"TogglePrePostMarketPriceLine",onDestroy:()=>{s.mainSeries().isPrePostMarketPricesAvailableProperty().unsubscribeAll(e)}}},{property:s.mainSeries().properties().childs().prePostMarket.childs().visible,undoModel:s,undoText:rc});s.mainSeries().isPrePostMarketPricesAvailableProperty().subscribe(e,(t=>{e.update({disabled:!t.value()})}))}ie.hideAllLineTools=new nt({actionId:"Chart.ToggleVisibility.AllLineTools",options:{label:fl.t(null,void 0,i(647617)),checkable:!0,statName:"ToggleHideMarksOnBars",hotkeyGroup:e.hotkeys(),hotkeyHash:n.Modifiers.Mod+n.Modifiers.Alt+72}},{property:Oe.hideMarksOnBars(),undoModel:s,undoText:Yl,callback:()=>(0,f.toggleHideMode)()});{const a=ie.showSeriesPrevCloseValue=new nt({actionId:"Chart.PriceScale.Labels.ToggleSymbolPrevCloseValueVisibility",options:{label:fl.t(null,void 0,i(590537)),checkable:!0,checked:!1,statName:"ToggleSymbolPrevCloseValue",onDestroy:()=>s.mainSeries().onRestarted().unsubscribeAll(a)}},{property:r.childs().scalesProperties.childs().showSeriesPrevCloseValue,undoModel:s,undoText:Xl});s.mainSeries().onRestarted().subscribe(a,(()=>{a.update({disabled:s.mainSeries().isDWM()})}));const l=ie.showSeriesPrevCloseLine=new nt({actionId:"Chart.Lines.ToggleSeriesPrevCloseLineVisibility",options:{label:fl.t(null,void 0,i(336857)),checkable:!0,checked:!1,statName:"ToggleSymbolPrevCloseLine",onDestroy:()=>s.mainSeries().onRestarted().unsubscribeAll(l)}},{property:s.mainSeries().properties().childs().showPrevClosePriceLine,undoModel:s,undoText:Jl});if(s.mainSeries().onRestarted().subscribe(l,(()=>{l.update({disabled:s.mainSeries().isDWM()})})),ie.showBidAskLabels=new nt({actionId:"Chart.PriceScale.Labels.ToggleBidAskLabelsVisibility",options:{label:fl.t(null,void 0,i(665287)),checkable:!0,checked:!1,statName:"ToggleBidAskLabels"}},{property:r.childs().scalesProperties.childs().showBidAskLabels,undoModel:s,undoText:ic}),ie.showBidAskLines=new nt({actionId:"Chart.Lines.ToggleBidAskLinesVisibility",options:{label:fl.t(null,void 0,i(240548)),checkable:!0,checked:!1,statName:"ToggleBidAskLines"}},{property:s.mainSeries().properties().childs().bidAsk.childs().visible,undoModel:s,undoText:sc}),ie.moveChartAction=new ot.Action({ actionId:"Chart.MoveChartInLayout",options:{label:fl.t(null,void 0,i(456462)),subItems:[new ot.Action({actionId:"Chart.MoveChartInLayout.Forward",options:{label:fl.t(null,void 0,i(472781)),statName:"MoveChartRight",onExecute:()=>e.chartWidgetCollection().moveActiveChartWithUndo(!1)}}),new ot.Action({actionId:"Chart.MoveChartInLayout.Back",options:{label:fl.t(null,void 0,i(762592)),statName:"MoveChartLeft",onExecute:()=>e.chartWidgetCollection().moveActiveChartWithUndo(!0)}})]}}),ie.showDataWindow=new gt.ActionWithStandardIcon({actionId:"Chart.DataWindow.Show",options:{label:(0,Al.appendEllipsis)(fl.t(null,void 0,i(409068))),statName:"DataWindow",hotkeyGroup:t,hotkeyHash:n.Modifiers.Alt+68,iconId:"Chart.ShowDataWindow",onExecute:Fl}}),o.addToWatchlistEnabled){const i={hotkeyGroup:t};ie.addToWatchlist=new Ol(e,i),t.add({desc:"Add symbol to watchlist",hotkey:n.Modifiers.Mod+n.Modifiers.Alt+87,handler:()=>(0,Il.showAddSymbolDialog)(Ll(e))})}}return ie}i(958729);const _c=(0,m.getLogger)("ChartWidget",{color:"#606"}),pc=D.enabled("chart_content_overrides_by_defaults"),mc=D.enabled("symphony_embed"),gc=new R.TranslatedString("hide {title}",a.t(null,void 0,i(470301)));let Sc=null;if(location.search.toLowerCase().includes("logcanvassaverestoreleaks")){if(!c.isChrome)throw new Error("CanvasRenderingContext2D save/restore leak detection is available for now in Chrome only");i.e(15803).then(i.bind(i,128151)).then((e=>{e.enableCanvasRenderingContext2DSaveRestoreLeaksDetection(),Sc=e.reportCanvasRenderingContext2DSaveRestoreLeaks}))}const vc={addToWatchlistEnabled:!0,showFinancialsEnabled:!1,sourceSelectionEnabled:!0,propertyPagesEnabled:!0,paneContextMenuEnabled:!0,priceScaleContextMenuEnabled:!0,currencyConversionEnabled:!1,unitConversionEnabled:!1,goToDateEnabled:!1,marketStatusWidgetEnabled:!0,chartWarningWidgetEnabled:!0,dataProblemWidgetEnabled:!0,paneControlsEnabled:!0,isSymbolAvailable:e=>Promise.resolve(!0),legendWidgetEnabled:!0,chartEventsEnabled:!0,newsNotificationsEnabled:!0,esdEnabled:!1,latestUpdatesEnabled:{news:!1,minds:!1},continuousContractSwitchesEnabled:!1,futuresContractExpirationEnabled:!1,croppedTickMarks:!0,countdownEnabled:!0,lastPriceAnimationEnabled:!0,useKineticScroll:c.CheckMobile.any(),indicatorsDialogShortcutEnabled:!0,handleScale:{mouseWheel:!0,pinch:!0,axisPressedMouseMove:{time:!0,price:!0}},handleScroll:{mouseWheel:!0,pressedMouseMove:!0,horzTouchDrag:!0,vertTouchDrag:!0}};function fc(e,t,i,s=0){const o=t.mainSeries().syncModel(),r=e.mainSeries().syncModel();let n=i;if(null!==o&&null!==r){const t=e.createSyncPoint(o.syncSourceTarget(),r.syncSourceTarget());0!==s&&(i=o.projectTime(i,s)),n=t.sourceTimeToTargetTime(i)}return e.timeScale().points().roughIndex(n,r&&r.distance.bind(r))} const bc=new Set(["Volume@tv-basicstudies","Compare@tv-basicstudies","Overlay@tv-basicstudies","Dividends@tv-basicstudies","Earnings@tv-basicstudies","Splits@tv-basicstudies","BarSetContinuousRollDates@tv-corestudies","Sessions@tv-basicstudies","VbPSessionsRough@tv-volumebyprice","AnchoredVWAP@tv-basicstudies","RegressionTrend@tv-basicstudies","VbPAnchored@tv-basicstudies","VbPFixed@tv-basicstudies","VbPFixed@tv-volumebyprice"]),yc=(0,o.default)((()=>{window.ChartApiInstance.setIsNonCountedStudyFn((e=>bc.has(e)))}));class Cc{constructor(e,t,s){this.activePaneWidget=null,this._model=null,this._paneWidgets=[],this._maximizedPaneWidget=null,this._timeAxisWidget=null,this._paneSeparators=[],this._controlBarNavigation=null,this._lineToolsSynchronizer=null,this._modelCreated=new E.Delegate,this._isDestroyed=!1,this._customLegendWidgetsFactoryMap=new Map,this._backgroundTopTheme=new O.WatchedValue("light"),this._backgroundBasedTheme=new O.WatchedValue("light"),this._backgroundBottomTheme=new O.WatchedValue("light"),this._lhsAxesWidth=0,this._rhsAxesWidth=0,this._lhsPriceAxisWidthChanged=new E.Delegate,this._rhsPriceAxisWidthChanged=new E.Delegate,this._mainDiv=null,this._parent=null,this._elTooltipDiv=null,this._hotkeysListener=null,this._mouseWheelHelper=null,this._onWheelBound=null,this._justActivated=!1,this._inited=!1,this._containsData=!1,this._initialLoading=!1,this._defTimeframe=void 0,this._removeMaximizeHotkey=null,this._invalidationMask=null,this._drawPlanned=!1,this._drawRafId=0,this._inLoadingState=!1,this._timingsMeter=null,this._tagsChanged=new E.Delegate,this._redraw=new E.Delegate,this._isVisible=new O.WatchedValue(!0),this._collapsed=new O.WatchedValue(!1),this._dataWindowWidget=null,this._resizeHandler=null,this._spinner=null,this._properties=null,this._symbolWV=new O.WatchedValue,this._resolutionWV=new O.WatchedValue,this._actions=null,this._updateThemedColorBound=this._updateThemedColor.bind(this),this._disconnected=new E.Delegate,this._reconnectBailout=new E.Delegate,this._connected=new E.Delegate,this._chartWidgetInitialized=new E.Delegate,this._saveChartService=null,this._objectTreeDialogController=null,this._chartPaintedPromise=null,this._noExchangeSubscrptionWarning=null,this._paneWidgetsSharedState=new Li,this._onZoom=new E.Delegate,this._onScroll=new E.Delegate,this._availableScreen=null,this._hoveredPriceAxes=new Set,this._anyAxisHovered=new O.WatchedValue(!1),this._linkingGroupIndex=new O.WatchedValue(null),this._isHovered=new O.WatchedValue(!1),this._activeHint=null,this._eventHintDeferredPromise=null,this._warningHintDeferredPromise=null,this._setSymbolIntervalContentOverrides={},this._ariaPriceDescription=null,this._updateScalesActions=()=>{const e=this.actions(),t=this.model().mainSeries(),i=t.priceScale(),s=t.properties(),o=i.isLockScale(),r=6===s.childs().style.value();e.percentSeriesScale.update({disabled:o||r,checked:i.isPercentage()}),e.logSeriesScale.update({disabled:o||r,checked:i.isLog()}),e.regularSeriesScale.update({disabled:o||r,checked:i.isRegular()}), e.indexedTo100SeriesScale.update({disabled:o||r,checked:i.isIndexedTo100()}),e.invertSeriesScale.update({checked:i.isInverted()}),e.lockSeriesScale.update({checked:i.isLockScale()}),e.autoSeriesScale.update({checked:i.isAutoScale(),disabled:i.properties().childs().autoScaleDisabled.value()})},this._invalidationHandler=e=>{if(!(e instanceof pe.InvalidationMask))throw new Error("Invalid mask");null!==this._invalidationMask?this._invalidationMask.merge(e):this._invalidationMask=e,this._drawPlanned||(this._drawPlanned=!0,this._options.visible.when((()=>{const e=!document.hidden,t=this.screen&&this.screen.isShown();null!==this._timingsMeter&&e&&!t&&this._timingsMeter.startWaitingDraw();const i=(0,r.ensureNotNull)((0,r.ensureNotNull)(this._parent).ownerDocument.defaultView);this._drawRafId=i.requestAnimationFrame(this._invalidationRAFCallback.bind(this))})))},this._onChartSessionIsConnectedChanged=e=>{e?this._onConnection():this._onDisconnect()},this._subscribeToBanInfo=e=>{var t,i;e?null===(t=this._spinner)||void 0===t||t.stop():null===(i=this._spinner)||void 0===i||i.spin()},this._id=t,this._layoutId=s,this._options=(0,w.merge)((0,w.clone)(vc),e),this._chartWidgetCollection=this._options.chartWidgetCollection,this._isActive=new O.WatchedValue(!!this._options.isActive),this._options.customLegendWidgetFactories&&(this._customLegendWidgetsFactoryMap=this._options.customLegendWidgetFactories),this._subscribeToDrawingState(),this.withModel(this,(()=>{const e=this.model().model();e.backgroundTopColor().subscribe(this._updateThemedColorBound),e.backgroundColor().subscribe(this._updateThemedColorBound)})),this._errorRenderer=new ue(this),this._scrollHelper=new z(this),this._objectTreeDialogController=C.getInstance(),this._properties=new co.DefaultProperty({defaultName:"chartproperties",useUserPreferences:this._options.useUserChartPreferences,excludedDefaultsKeys:["scalesProperties.axisHighlightColor","scalesProperties.axisLineToolLabelBackgroundColorActive","scalesProperties.axisLineToolLabelBackgroundColorCommon","scalesProperties.showPriceScaleCrosshairLabel","scalesProperties.showTimeScaleCrosshairLabel","scalesProperties.crosshairLabelBgColorLight","scalesProperties.crosshairLabelBgColorDark"]}),this._startSpinner(this._options.container.value()),window.ChartApiInstance.connectionBanInfo().subscribe(this._subscribeToBanInfo,{callWithLast:!0}),this._chartSession=new el.ChartSession(window.ChartApiInstance),yc(),this._isMultipleLayout=(0,L.combine)((e=>(0,ge.isMultipleLayout)(e)),this._chartWidgetCollection.layout.weakReference()),this._properties.childs().scalesProperties.childs().scaleSeriesOnly.subscribe(null,(()=>{const e=this.model().model();e.recalculateAllPanes((0,ni.viewportChangeEvent)()),e.invalidate(pe.InvalidationMask.full())})),this._hotkeys=_.createGroup({desc:"Chart actions",isDisabled:()=>!this.isActive().value()}),(0,c.onWidget)()||(this._persistentLogSwitcher=new Ha.FeatureToggleWatchedValue("support_persistent_logs",!1),this._persistentLogSwitcher.subscribe((async e=>{var t;if(e){if((0, Ua.getPersistentLogger)())return;(0,Ua.setPersistentLogger)(new Ga);const{initPersistentLogger:e}=await i.e(94882).then(i.bind(i,327629));(null===(t=this._persistentLogSwitcher)||void 0===t?void 0:t.value())?e():(0,Ua.setPersistentLogger)(null)}else(0,Ua.setPersistentLogger)(null)}),{callWithLast:!0}))}refreshMarks(){this.model().barsMarksSources().forEach((e=>e.refreshData()))}clearMarks(e){this.model().barsMarksSources().forEach((t=>t.clearMarks(e)))}setTimezone(e){const t=e;t&&(0,k.timezoneIsAvailable)(t)?this.properties().childs().timezone.setValue(t):console.warn("Incorrect timezone: "+JSON.stringify(t))}getTimezone(){return this.properties().childs().timezone.value()}destroy(){var e,t,i;this._unsetActions(),this._hotkeys&&this._hotkeys.destroy(),null===(e=this._lineToolsSynchronizer)||void 0===e||e.destroy(),null===(t=this._noExchangeSubscrptionWarning)||void 0===t||t.destroy(),window.loginStateChange.unsubscribe(this,this._handleLoginStateChanged),null!==this._model&&(this._model.model().backgroundTopColor().unsubscribe(this._updateThemedColorBound),this._model.model().backgroundColor().unsubscribe(this._updateThemedColorBound),this._model.model().crossHairSource().moved().unsubscribe(this,this._updateAriaPriceDescription),this._model.destroy()),window.ChartApiInstance.connectionBanInfo().unsubscribe(this._subscribeToBanInfo),this._ariaPriceDescription=null,this._customLegendWidgetsFactoryMap.clear(),this._scrollHelper.destroy(),this._errorRenderer.destroy(),this._chartSession.criticalError().unsubscribe(this,this._onChartSessionCriticalError),this._chartSession.isConnected().unsubscribe(this._onChartSessionIsConnectedChanged),this._chartSession.destroy(),null===(i=this._persistentLogSwitcher)||void 0===i||i.destroy(),this._isDestroyed=!0}emulateCriticalError(){this._chartSession.removeSeries("-1")}chartSession(){return this._chartSession}onDisconnected(){return this._disconnected}onReconnectBailout(){return this._reconnectBailout}onConnected(){return this._connected}chartWidgetInitialized(){return this._chartWidgetInitialized}setVisibleTimeRange(e,t,i,s){throw new Error("Not implemented")}lineToolsSynchronizer(){return this._lineToolsSynchronizer}actions(){return null===this._actions?this._setActions():this._actions}requestFullscreen(){this.getResizerDetacher().requestFullscreen()}exitFullscreen(){this.getResizerDetacher().exitFullscreen()}inFullscreen(){return this.getResizerDetacher().fullscreen.value()}model(){return(0,r.ensureNotNull)(this._model)}id(){return this._id}layoutId(){return this._chartWidgetCollection.metaInfo.uid.value()}isActive(){return this._isActive.readonly()}isHovered(){return this._isHovered.readonly()}crossHairSyncEnabled(){return this._chartWidgetCollection.lock.crosshair.value()}isVisible(){return this._isVisible.value()}setVisible(e){this._isVisible.setValue(e)}visible(){return this._isVisible.readonly()}isCollapsed(){return this._collapsed.value()}setCollapsed(e){this._collapsed.setValue(e)}collapsed(){return this._collapsed.readonly()}isJustClonedChart(){ return!!(this._options||{}).justCloned}removeAllDrawingTools(){this.model().removeAllDrawingTools()}removeAllStudies(){this.model().removeAllStudies()}removeAllStudiesDrawingTools(){this.model().removeAllStudiesAndDrawingTools()}getSymbol(e){var t,i,s,o;let r;return r=this._model?this._model.mainSeries().properties().childs():this.properties().childs().mainSeriesProperties.childs(),r?e&&r.shortName&&r.shortName.value()?null!==(i=null===(t=r.shortName)||void 0===t?void 0:t.value())&&void 0!==i?i:"":null!==(o=null===(s=r.symbol)||void 0===s?void 0:s.value())&&void 0!==o?o:"":""}setSymbol(e){this._model?(this._symbolWV.setValue(e),this._model.setSymbol(this._model.mainSeries(),e)):(this.properties().childs().mainSeriesProperties.merge({symbol:e}),this._symbolWV.setValue(e),this._setSymbolIntervalContentOverrides.symbol=e)}setResolution(e){this._model?(this._resolutionWV.setValue(e),this._model.setResolution(this._model.mainSeries(),e)):(this.properties().childs().mainSeriesProperties.merge({interval:e}),this._resolutionWV.setValue(e),this._setSymbolIntervalContentOverrides.interval=e)}getResolution(){return this._model?this._model.mainSeries().properties().childs().interval.value():this.properties().childs().mainSeriesProperties.childs().interval.value()}symbolWV(){return this._symbolWV.readonly()}resolutionWV(){return this._resolutionWV.readonly()}loadRange(e){if(this._model){this.screen.show();this._model.loadRange(e)||this.screen.hide()}}async showGeneralChartProperties(e,t){if(!D.enabled("show_chart_property_page"))return Promise.resolve(null);const s=await this._showChartProperties(this.model().mainSeries(),e,{doNotCloseOnBgClick:!0,onResetToDefault:async()=>{this.model().restorePreferences();const e=await i.e(83767).then(i.bind(i,429874)),t=e.getCurrentTheme().name;e.loadTheme(this.chartWidgetCollection(),{themeName:t,standardTheme:!0})},shouldReturnFocus:null==t?void 0:t.shouldReturnFocus});if(null===s)return null;const o=()=>{s.hide(),this._chartWidgetCollection.activeChartWidget.unsubscribe(o)};return this._chartWidgetCollection.activeChartWidget.subscribe(o),s}showChartPropertiesForSource(e,t,i,s){return D.enabled("property_pages")&&e.userEditEnabled()?e===this.model().model().mainSeries()?this.showGeneralChartProperties(t):((i=i||{}).onResetToDefault=()=>{((0,K.isLineTool)(e)||(0,q.isStudy)(e))&&this.model().restorePropertiesForSource.bind(this._model,e)},this._showChartProperties(e,t,i,s)):Promise.resolve(null)}options(){return this._options}async showChartPropertiesForSources(e){if(!D.enabled("property_pages"))return Promise.resolve(null);const{sources:t,title:s,tabName:o,renamable:n}=e,l=(0, r.ensureNotNull)(this._model),c=N(t.map((e=>e.properties().childs()))),d=N(t.map((e=>e.properties().childs().intervalsVisibilities))),[{createPropertyPage:h},{getSelectionStylePropertiesDefinitions:u},{getSelectionIntervalsVisibilitiesPropertiesDefinition:_},{getSelectionCoordinatesPropertyDefinition:p}]=await Promise.all([Promise.all([i.e(36914),i.e(47495),i.e(30154),i.e(82375),i.e(18537)]).then(i.bind(i,402417)),Promise.all([i.e(36914),i.e(47495),i.e(30154),i.e(82375),i.e(18537)]).then(i.bind(i,136172)),Promise.all([i.e(36914),i.e(47495),i.e(30154),i.e(82375),i.e(18537)]).then(i.bind(i,46622)),Promise.all([i.e(36914),i.e(47495),i.e(30154),i.e(82375),i.e(18537)]).then(i.bind(i,678904))]);return async function(e){const{SourcesPropertiesEditorRenderer:t}=await Promise.all([i.e(14819),i.e(73224),i.e(72718),i.e(93327),i.e(52540),i.e(32662),i.e(5987),i.e(98996),i.e(43387),i.e(66458),i.e(5761),i.e(4343),i.e(28430),i.e(70428),i.e(44597),i.e(1413),i.e(4908),i.e(52078),i.e(70621),i.e(89508),i.e(62033),i.e(13633),i.e(61204),i.e(19216),i.e(37132),i.e(66323),i.e(14),i.e(50473),i.e(37657),i.e(35697),i.e(31149),i.e(84331),i.e(85258),i.e(16005),i.e(79656),i.e(83483),i.e(87940),i.e(63276),i.e(63751),i.e(5378),i.e(29647),i.e(77382),i.e(87473),i.e(10637),i.e(16165),i.e(85131),i.e(10714),i.e(94712),i.e(44794),i.e(39076),i.e(71093),i.e(45338),i.e(66233),i.e(29946),i.e(28593),i.e(47877),i.e(42332),i.e(57876),i.e(84418),i.e(95884),i.e(20221),i.e(954),i.e(21975),i.e(70631),i.e(98133),i.e(23040),i.e(45183),i.e(55713),i.e(28288),i.e(87142),i.e(30408),i.e(4267),i.e(75803),i.e(99403),i.e(13130),i.e(84988),i.e(70484),i.e(90385),i.e(92833),i.e(42942),i.e(5483),i.e(60801),i.e(28019),i.e(3889),i.e(92158),i.e(39434),i.e(68581),i.e(18561),i.e(26854),i.e(72539),i.e(70334),i.e(97406),i.e(37305),i.e(31063),i.e(94025),i.e(68052),i.e(61581),i.e(46780)]).then(i.bind(i,578569)),s=new t(e);return null!==x&&(x.hide(),x=s),s.show(),s}({sources:t,propertyPages:[h(u(c,l),"style",a.t(null,void 0,i(394969))),h({definitions:[p(t,l)]},"displacement",a.t(null,void 0,i(962764))),h(_(d,l),"visibility",a.t(null,void 0,i(221852)))],undoModel:l,title:s,activeTabId:o,renamable:n})}getPriceAxisWidthChangedByName(e){return"left"===e?this._lhsPriceAxisWidthChanged:this._rhsPriceAxisWidthChanged}getPriceAxisMaxWidthByName(e){return"left"===e?this._lhsAxesWidth:this._rhsAxesWidth}timeAxisHeight(){return null!==this._timeAxisWidget?this._timeAxisWidget.size.height:0}withModel(e,t){null!==this._model?t.call(e):this.modelCreated().subscribe(e,t,!0)}hasModel(){return null!==this._model}onRedraw(){return this._redraw}copyLineToOtherCharts(){const e=(0,r.ensureNotNull)(this._model),t=e.selection().lineDataSources().filter((e=>e.isSynchronizable()));e.model().copyToOtherCharts(t,!0)}hideDataSources(e){if(e.length){const t=e.map((e=>e.properties().visible)),i=e.map((()=>!1));this.model().setProperties(t,i,gc.format({title:new R.TranslatedString(e[0].name(),e[0].title(is.TitleDisplayTarget.StatusLine))}))}}hideSelectedObject(){ this.hideDataSources(this.model().selection().dataSources().filter((e=>!(0,Qe.isAlertLabel)(e))))}unlinkSelectedLine(){const e=(0,r.ensureNotNull)(this._model),t=e.selection().lineDataSources();e.unlinkLines(t)}selectPointMode(){return(0,r.ensureNotNull)(this._model).model().selectPointMode()}cancelRequestSelectPoint(){const e=(0,r.ensureNotNull)(this._model).model();e.cancelRequestSelectPoint(),e.setReplayStatus(e.isInReplay().value()?3:0),e.clearCurrentPosition()}requestSelectPoint(e,t){const i=(0,r.ensureNotNull)(this._model);return e.selectPointMode===Oe.SelectPointMode.Replay&&i.model().setReplayStatus(1),new Promise(((s,o)=>{const r=()=>!!this.isVisible()||(o("Chartwidget must be visible"),this.cancelRequestSelectPoint(),!1);if(!r())return;(0,Oe.resetToCursor)(!0),i.lineBeingCreated()&&i.cancelCreatingLine();let n=!1;const a={};i.model().onPointSelected().subscribe(a,((e,t)=>{n=!0,this._isVisible.unsubscribe(r),this._hideHint(),s({point:e,pane:t})}),!0),i.model().requestSelectPoint(e),this.startTrackingMode(),void 0!==t&&this._showEventHint(t),this._isVisible.subscribe(r),this.selectPointMode().subscribe((()=>{setTimeout((()=>{n||(this.selectPointMode().value()===Oe.SelectPointMode.None&&this._hideHint(),i.model().onPointSelected().unsubscribeAll(a),this._isVisible.unsubscribe(r),o("cancelled"))}))}),{once:!0})}))}onScroll(){return this._onScroll}onZoom(){return this._onZoom}images(e){window.TradingView.printing=!0;const t=this.model().selection().allSources();this.model().selectionMacro((e=>e.clearSelection())),this.model().model().recalculateAllPanes((0,ni.globalChangeEvent)());const i=(t,i)=>{t.paint(i);const s={showCollapsedStudies:Boolean(null==e?void 0:e.showCollapsedStudies),status:null==e?void 0:e.status};return t.getScreenshotData(s)},s=[];if(null!==this._maximizedPaneWidget){const e=this._paneWidgets.indexOf(this._maximizedPaneWidget);s.push(i(this._maximizedPaneWidget,pe.InvalidationMask.light().invalidateForPane(e)))}else for(let e=0;e{t.forEach((t=>{e.addSourceToSelection(t)}))})),this.model().model().recalculateAllPanes((0,ni.globalChangeEvent)()),this.model().model().lightUpdate();const r=this.mainSeriesQuotesAndMetainfo();return{panes:s,timeAxis:o,colors:{text:this.properties().childs().scalesProperties.childs().textColor.value(),bg:this.properties().childs().paneProperties.childs().background.value(),scales:this.properties().childs().scalesProperties.childs().lineColor.value()},meta:r.meta,ohlc:r.ohlc,quotes:r.quotes}}insertStudy(e,t,i,s,o){return this._insertStudyOrReplaceStub(e,t,void 0,i,s,o)}replaceStubByStudy(e,t,i,s,o,r){return e.updateDescriptor(t),this._insertStudyOrReplaceStub(t,i,e,s,o,r)} addOverlayStudy(e,t,i){const s=this.model();return this._options&&this._options.isSymbolAvailable?this._options.isSymbolAvailable(e).then((async o=>{if(!o)return null;await(0,vs.studyMetaInfoRepository)().requestMetaInfo();const r=s.createStudyInserter({type:"java",studyId:"Overlay@tv-basicstudies"},[]),n={allowExtendTimeScale:i};if(D.enabled("use_overrides_for_overlay")){const e=(0,Rr.factoryDefaults)("study_Overlay@tv-basicstudies.style");n.style=e}return r.setPropertiesState(n),r.setForceOverlay(t),r.insert((()=>Promise.resolve({inputs:{symbol:e},parentSources:[]})))})):Promise.resolve(null)}addCompareStudy(e){const t=this.model();return this._options&&this._options.isSymbolAvailable?this._options.isSymbolAvailable(e).then((async i=>i?(await(0,vs.studyMetaInfoRepository)().requestMetaInfo(),t.createStudyInserter({type:"java",studyId:"Compare@tv-basicstudies"},[]).insert((()=>Promise.resolve({inputs:{symbol:e},parentSources:[]})))):null)):Promise.resolve(null)}showIndicators(e,t){if(window.studyMarket)return window.studyMarket.visible().value()?void window.studyMarket.hide():(window.studyMarket.show(e,t),window.studyMarket)}setSaveChartService(e){this._saveChartService=e,null!==this._lineToolsSynchronizer&&this._lineToolsSynchronizer.setSaveChartService(e)}getSaveChartService(){return this._saveChartService}mainSeriesQuotesAndMetainfo(){let e,t,i;const s=this._model&&this._model.mainSeries();if(s){const o=e=>null==e?"":s.formatter().format(e,{signNegative:!0,useRtlFormat:!1}),r=e=>null==e?"":e+"";e={resolution:s.interval(),symbol:s.symbol(),values:s.legendValuesProvider().getValues(null)};const n=s.symbolInfo();n&&(e.symbol=n.full_name,e.description=n.description,e.exchange=n.exchange);const a=s.bars().last();null!==a&&(t=a.value.slice(1,5).map(o));const l=s.quotes();l&&(i={change:o(l.change),changePercent:r(l.change_percent),last:o(l.last_price)})}return{meta:e,ohlc:t,quotes:i}}isMultipleLayout(){return this._isMultipleLayout}updateCrossHairPositionIfNeeded(){if(this._model){const e=Oe.tool.value();this._model.model().setCurrentTool(e);const t=(0,me.lastMouseOrTouchEventInfo)();if(t.isTouch){const e=this._maximizedPaneWidget||this._paneWidgets[0];if(e.hasState()&&(!t.stylus&&(this._isLineToolModeExceptBrush()||(0,Oe.toolIsMeasure)(Oe.tool.value()))||this.selectPointMode().value()!==Oe.SelectPointMode.None)){const t=.5*this._model.model().timeScale().width(),i=.5*e.state().defaultPriceScale().height();e.setCursorPosition(t,i)}const i=this._model.model().crossHairSource();i.updateAllViews((0,ni.sourceChangeEvent)(i.id()))}}}trackingModePaneWidget(){if(!(0,me.lastMouseOrTouchEventInfo)().isTouch)return null;for(const e of this.paneWidgets())if(e.trackingModeEnabled())return e;return null}startTrackingMode(){if((0,me.lastMouseOrTouchEventInfo)().isTouch){this.exitTrackingMode(),this.updateCrossHairPositionIfNeeded();const e=this._maximizedPaneWidget||this._paneWidgets[0],t=this.model().model().crossHairSource().currentPoint();e.startTrackingMode(t,t)}}exitTrackingMode(){(0, me.lastMouseOrTouchEventInfo)().isTouch&&this.paneWidgets().some((e=>e.trackingModeEnabled()))&&(this.paneWidgets().forEach((e=>e.exitTrackingMode())),this.model().model().clearCurrentPosition())}onToolChanged(){const e=this.model().model();e.lineBeingCreated()&&!e.lineBeingCreateFromExternal()&&this._cancelCreatingLine(),this.selectPointMode().value()!==Oe.SelectPointMode.None&&this.cancelRequestSelectPoint(),this.exitTrackingMode()}setInLoadingState(e){this._inLoadingState=e}paint(e){const t=null!=e?e:pe.InvalidationMask.full();t.validationActions().forEach((e=>e())),this._paneWidgets.forEach(((e,i)=>{null!==this._maximizedPaneWidget&&this._maximizedPaneWidget!==e||e.paint(t.invalidateForPane(i))})),this._timeAxisWidget&&this._timeAxisWidget.paint(t.invalidateForTimeScale()),null==Sc||Sc(),this._redraw.fire()}GUIResetScales(){(0,u.trackEvent)("GUI","Reset Scales"),null!==this._model&&this._model.resetScales()}toggleMaximizePane(e){var t;if(!(this._paneWidgets.length<2)){this._maximizedPaneWidget?(this._maximizedPaneWidget.state().maximized().setValue(!1),this._maximizedPaneWidget=null,this._paneSeparators.forEach((e=>e.show()))):(this._maximizedPaneWidget=e,this._maximizedPaneWidget.state().maximized().setValue(!0),this._paneSeparators.forEach((e=>e.hide())));for(let e=this._paneWidgets.length;e--;)this._paneWidgets[e].updateControls(),this._paneWidgets[e].updatePriceAxisWidgetsStates();this._errorRenderer.updatePaneWidgets(),null===(t=this._timeAxisWidget)||void 0===t||t.updatePriceAxisStubs(),this._adjustSize(),this.updateCrossHairPositionIfNeeded()}}maximizedPaneWidget(){return this._maximizedPaneWidget}isMaximizedPane(){return null!==this._maximizedPaneWidget}setActive(e){(0,me.lastMouseOrTouchEventInfo)().isTouch&&(e&&this.selectPointMode().value()!==Oe.SelectPointMode.None?this.startTrackingMode():this.exitTrackingMode());for(const e of this._paneWidgets)e.update();e||this.model().selectionMacro((e=>{e.clearSelection()})),this._isActive.setValue(e)}justActivated(){return this._justActivated}unsetActivePaneWidget(){this.activePaneWidget=null}setActivePaneWidget(e){this.activePaneWidget=e}onPaneWidgetDestroyed(e){this.activePaneWidget===e&&(this.activePaneWidget=null)}backgroundTopTheme(){return this._backgroundTopTheme.readonly()}backgroundBasedTheme(){return this._backgroundBasedTheme.readonly()}backgroundBottomTheme(){return this._backgroundBottomTheme.readonly()}lineToolsAndGroupsDTO(){return(0,r.ensureNotNull)(this._lineToolsSynchronizer).prepareDTO()}resetLineToolsInvalidated(e,t,i){(0,r.ensureNotNull)(this._lineToolsSynchronizer).resetInvalidated(e,t,i)}applyLineToolUpdateNotification(e,t){(0,r.ensureNotNull)(this._lineToolsSynchronizer).applyLineToolUpdateNotification(e,t)}reloadAllLineTools(){(0,r.ensureNotNull)(this._lineToolsSynchronizer).reloadAllLineTools()}startApplyingLineToolUpdateNotification(){var e;null===(e=this._lineToolsSynchronizer)||void 0===e||e.startApplyingLineToolUpdateNotification()}endApplyingLineToolUpdateNotification(){var e ;null===(e=this._lineToolsSynchronizer)||void 0===e||e.endApplyingLineToolUpdateNotification()}applyAlertIdByExternalSource(e,t){var i;null===(i=this._lineToolsSynchronizer)||void 0===i||i.applyAlertIdByExternalSource(e,t)}deleteAlertByExternalSource(e,t){var i;null===(i=this._lineToolsSynchronizer)||void 0===i||i.deleteAlertByExternalSource(e)}shouldBeSavedEvenIfHidden(){return this._model?this.model().model().shouldBeSavedEvenIfHidden():!!this._options.content.shouldBeSavedEvenIfHidden}showObjectsTreePanelOrDialog(){let e=!1;const t=window.widgetbar;if(t&&t.isVisible()){const i=(0,r.ensureNotNull)(t.setPage("object_tree")),s=(0,r.ensureNotNull)(i.widget("object_tree"));(0,r.ensureDefined)(s.properties).setValue({selectedPage:"object_tree"}),e="object_tree"===i.name}e||this.showObjectsTreeDialog()}showObjectsTreeDialog(){var e;null===(e=this._objectTreeDialogController)||void 0===e||e.show()}addCustomWidgetToLegend(e,t){this._customLegendWidgetsFactoryMap.set(e,t);for(const i of this.paneWidgets())i.addCustomWidgetToLegend(e,t)}applyIndicatorsToAllChartsAvailable(){if(!this.chartWidgetCollection().applyIndicatorsToAllChartsAvailable())return!1;for(const e of this.model().model().panes()){if(e.sourcesByGroup().all().some((e=>(0,q.isStudy)(e)&&!(0,Z.isLollipopDataSource)(e))))return!0}return!1}restoreState(e,t,s){this._adjustSize();const o=(0,r.ensureNotNull)(this._model),n=o.restoreState(this._content,t,s),a=o.mainSeries().properties().childs();this._symbolWV.setValue(a.symbol.value()),this._resolutionWV.setValue(a.interval.value()),n&&n.lines_limit_exceeded&&!this.readOnly()&&Promise.all([i.e(5657),i.e(14260),i.e(8954),i.e(88430),i.e(85686),i.e(60678),i.e(45340),i.e(25977),i.e(33904),i.e(47484),i.e(74823),i.e(90609)]).then(i.bind(i,215079)).then((({showLinetoolsLimitExceededDialog:e})=>{e(this)}))}addCompareAsOverlay(e,t,i){const s=this.model();return(0,r.ensureDefined)(this._options.isSymbolAvailable)(e).then((async o=>{if(!o)return null;await(0,vs.studyMetaInfoRepository)().requestMetaInfo();const r=s.createStudyInserter({type:"java",studyId:"Overlay@tv-basicstudies"},[]);return r.setForceOverlay(!0),r.setPreferredPriceScale("as-series"),!0!==i&&r.setTargetPriceScaleMode({percentage:!0}),void 0!==t&&r.setPropertiesState({allowExtendTimeScale:t}),r.insert((async()=>({inputs:{symbol:e},parentSources:[]})))}))}scrollHelper(){return this._scrollHelper}chartPainted(){return this._drawPlanned?(null===this._chartPaintedPromise&&(this._chartPaintedPromise=(0,g.createDeferredPromise)()),this._chartPaintedPromise.promise):Promise.resolve()}setDataWindowWidget(e){this._dataWindowWidget=e}removeDataWindowWidget(){this._dataWindowWidget=null}showSelectedSourcesProperties(e){const t=(0,r.ensureNotNull)(this._model).selection().dataSources();if(1===t.length)this.showSourceProperties(t[0],e);else{const i=t.filter(K.isLineTool);i.length>0&&this.showChartPropertiesForSources({sources:i,tabName:e})}}executeActionById(e){ if("takeScreenshot"===e)return console.warn('Action "takeScreenshot" is deprecated. Use method "takeScreenshot" instead'),void this._chartWidgetCollection.takeScreenshot();const t=this.actions()[e];t?t.execute():console.warn("Unknown action id: "+e)}getCheckableActionState(e){const t=this.actions()[e];if(t){if(t.isCheckable())return t.isChecked();console.warn("Action "+e+" has no state")}else console.warn("Unknown action id: "+e);return null}connect(){this._chartSession.isConnected().subscribe(this._onChartSessionIsConnectedChanged),this._chartSession.criticalError().subscribe(this,this._onChartSessionCriticalError),this._chartSession.connect(this._onData.bind(this))}finishInitWithoutConnect(){this._chartSession.disable(),this._init(),this._chartWidgetInitialized.fire()}reconnect(){this._chartSession.disconnect(),this._chartSession.connect()}update(){if(this.hasModel()){for(const e of this._paneWidgets)e.update();this._timeAxisWidget&&this._timeAxisWidget.update()}}setPriceAxisHovered(e,t){t?this._hoveredPriceAxes.add(e):this._hoveredPriceAxes.delete(e),this._anyAxisHovered.setValue(this._hoveredPriceAxes.size>0)}anyPriceAxisHovered(){return this._anyAxisHovered.readonly()}linkingGroupIndex(){return this._linkingGroupIndex}offsetInDocument(e){const t=this._paneWidgets.find((t=>t.state()===e));if(void 0===t)return{left:NaN,top:NaN};const i=t.getElement().getBoundingClientRect();return{left:Math.round(i.left+document.body.scrollLeft),top:Math.round(i.top+document.body.scrollTop)}}showHint(e,...t){0===e?this._showEventHint(...t):1===e&&this._showWarningHint(...t)}hotkeys(){return this._hotkeys}_clearSelectionHotkey(){return{desc:"Cancel selection",hotkey:27,handler:()=>{var e,t,i,s,o;if(this._checkIsTradedGroupSelected()&&(null===(e=(0,Mn.tradingService)())||void 0===e||e.clearTradedContextLinking()),this.selectPointMode().value()!==Oe.SelectPointMode.None)return this.selectPointMode().value()===Oe.SelectPointMode.Replay&&this._chartWidgetCollection.getAll().forEach((e=>{e!==this&&e.selectPointMode().value()===Oe.SelectPointMode.Replay&&e.cancelRequestSelectPoint()})),void this.cancelRequestSelectPoint();null===(t=this._model)||void 0===t||t.selectionMacro((e=>{this._cancelCreatingLine(),e.clearSelection()}));const r=null===(i=this._model)||void 0===i?void 0:i.model().customSourceMovingHitTestData();r&&r.cancelMoveHandler&&r.cancelMoveHandler()&&(r.cancelled=!0,null===(s=this._model)||void 0===s||s.model().setMovingCustomSource(null,null),null===(o=this._model)||void 0===o||o.model().lightUpdate())},isDisabled:()=>{const e=this._model;if(!e)return!0;const t=0===e.selection().allSources().length,i=null===e.crossHairSource().measurePane().value(),s=this.selectPointMode().value()===Oe.SelectPointMode.None;return t&&i&&s}}}_insertStudyOrReplaceStub(e,t,i,s,o,r){{const o=this.model().model().chartApi().canCreateStudy({id:"java"===e.type?e.studyId:"",child:t.length>0,fundamental:null==s?void 0:s.isFundamental});if(!o.success)return i&&this.model().model().removeSource(i,!0),os(this.model().model(),o),Promise.resolve(null)} const n="java"===e.type;return new Promise((async a=>{if(0===t.length)return null==r||r(),n&&await(0,vs.studyMetaInfoRepository)().requestMetaInfo(),void a(this._insertOrReplaceStubByStudyImpl(e,t,i,s,o));window.runOrSignIn((async()=>{null==r||r(),n&&await(0,vs.studyMetaInfoRepository)().requestMetaInfo(),a(this._insertOrReplaceStubByStudyImpl(e,t,i,s,o))}),{source:"study on study"})})).catch((()=>null))}_insertOrReplaceStubByStudyImpl(e,t,s,o,n){const l=(0,r.ensureNotNull)(this._model).createStudyInserter(e,t,o);l.setForceOverlay("java"===e.type&&"Volume@tv-basicstudies"===e.studyId&&D.enabled("volume_force_overlay"));const c=l.insert(((e,i,s)=>new Promise(((o,r)=>{this.selectPointMode().value()!==Oe.SelectPointMode.None&&this.cancelRequestSelectPoint(),n?o(n(e,i,s)):(0,q.isSymbolicStudy)(s)?((0,u.trackEvent)("GUI","Confirmation dialogs","Symbol confirmation dialog"),M(this,e,s,o,r,"symbol")):(0,q.hasConfirmInputs)(i)?((0,u.trackEvent)("GUI","Confirmation dialogs","Inputs confirmation dialog"),M(this,e,s,o,r)):o({inputs:{},parentSources:t})}))),void 0,s);return c.then((()=>{(0,Oe.hideAllIndicators)().value()&&(0,f.toggleHideMode)()})).catch((e=>{s||(e===il.InsertionErrorCode.StudyCannotBeChild&&(0,qa.showNoticeDialog)({type:"modal",title:a.t(null,void 0,i(900850)),content:a.t(null,void 0,i(465943))}),e===il.InsertionErrorCode.CannotCompilePub&&(0,qa.showNoticeDialog)({type:"modal",title:a.t(null,void 0,i(900850)),content:a.t(null,void 0,i(81214))}),e===il.InsertionErrorCode.CannotGetMetainfo&&(0,qa.showNoticeDialog)({type:"modal",title:a.t(null,void 0,i(900850)),content:a.t(null,void 0,i(164968))}))})),c}async _showChartProperties(e,t,i,s){if(!this._model)return null;t&&((0,d.setValue)("properties_dialog.active_tab.chart",t),i.tabName=t);const o=await X(e,this._model,i,this._options.chartWidgetCollection,s);return(null==o?void 0:o.visible().value())?o:null}_createLineToolsSynchronizerIfNeeded(){var e;{const t={readOnlyMode:this.readOnly(),migrateSyncedLineTools:this===this._options.chartWidgetCollection.getAll()[0]},i=vl;this._lineToolsSynchronizer=new i({layoutId:this.layoutId(),chartId:this._id,clientId:this._chartWidgetCollection.clientId},this.model().model(),t),null!==this._saveChartService&&this._lineToolsSynchronizer.setSaveChartService(this._saveChartService),this._lineToolsSynchronizer.invalidateAll(),null===(e=this._model)||void 0===e||e.model().setLineToolsSynchronizer(this._lineToolsSynchronizer)}}_updateThemedColor(){const e=this.model().model(),t=e.backgroundColorAtYPercentFromTop(.5);let i=e.backgroundTopColor().value(),s=e.backgroundColor().value();const o=(0,p.isColorDark)(t),r=(0,p.isColorDark)(i),n=(0,p.isColorDark)(s);this.widget().classList.toggle("chart-widget--themed-dark",o),this.widget().classList.toggle("chart-widget--themed-light",!o),this.widget().classList.toggle("chart-widget__top--themed-dark",r),this.widget().classList.toggle("chart-widget__top--themed-light",!r),this.widget().classList.toggle("chart-widget__bottom--themed-dark",n), this.widget().classList.toggle("chart-widget__bottom--themed-light",!n),this._backgroundTopTheme.setValue(r?"dark":"light"),this._backgroundBasedTheme.setValue(o?"dark":"light"),this._backgroundBottomTheme.setValue(n?"dark":"light"),i===s&&(0,h.isStdThemedDefaultValue)("chartProperties.paneProperties.background",i,this._backgroundBasedTheme.value())&&(i=null,s=null);for(const e of this._paneWidgets)e.updateThemedColors({topColor:i,bottomColor:s})}_isLineToolModeExceptBrush(){const e=Oe.tool.value();return(0,Qt.isLineToolName)(e)&&!(0,Qt.isLineDrawnWithPressedButton)(e)&&this.selectPointMode().value()===Oe.SelectPointMode.None}_cancelCreatingLine(){const e=(0,r.ensureNotNull)(this._model).model(),t=e.lineBeingCreated();if(null!==t){const i=(0,r.ensureNotNull)(e.paneForSource(t));(0,r.ensureNotNull)(this.paneByState(i)).cancelCreatingLineTool(),t.toolname===Oe.tool.value()&&(0,Oe.resetToCursor)()}const i=e.crossHairSource().measurePane().value();if(null!==i){(0,r.ensureNotNull)(this.paneByState(i)).cancelMeasuring()}}_adjustSize(e){var t;let i=0;const o=null===this._model?null:this._model.model().priceScaleSlotsCount(),r=new Uint32Array(null===o?0:o.left),n=new Uint32Array(null===o?0:o.right),a=(0,_e.getCanvasDevicePixelRatio)(document.body),c=(e,t)=>e+t,d=(e,t)=>{t.forEach(((t,i)=>{e[i]=Math.max(e[i],t)}))},h=this._width(),u=this._height(),_=this._paneSeparators.length,p=this.isMaximizedPane()?0:Ie.height()*_,m=null!==this._timeAxisWidget?this._timeAxisWidget.optimalHeight():0;let g=u-m>=61?m:0;g%2&&(g+=1);const S=Math.max(1,Math.floor((u-p-g)/this._paneWidgets.length));let v=0,f=null;for(const e of this._paneWidgets)if(!this._maximizedPaneWidget||this._maximizedPaneWidget===e){e.leftPriceAxisesContainer().updateCurrencyLabels();const t=e.leftPriceAxisesContainer().optimalWidths();e.rightPriceAxisesContainer().updateCurrencyLabels();const s=e.rightPriceAxisesContainer().optimalWidths();d(r,t),d(n,s),this._maximizedPaneWidget!==e&&e.state().collapsed().value()?v+=Math.min(S,e.collapsedHeight()):(i+=e.stretchFactor(),f=e)}let b=r.reduce(c,0),y=n.reduce(c,0),C=Math.max(h-b-y,0);if(C<=102){b=0,y=0,C=h;for(let e=0;e0){const e=new Ie(this,o-1,o);this._paneSeparators.push(e),this._timeAxisWidget?this._elMainTable.insertBefore(e.getElement(),this._timeAxisWidget.getElement()):this._elMainTable.appendChild(e.getElement())}this._timeAxisWidget?this._elMainTable.insertBefore(i.getElement(),this._timeAxisWidget.getElement()):this._elMainTable.appendChild(i.getElement())}for(let i=0;ipe.InvalidationLevel.Cursor&&(null===(i=this._timeAxisWidget)||void 0===i||i.update(),this._paneWidgets.forEach((e=>{ e.updatePriceAxisWidgets()})),this._applyTimeScaleInvalidations(e,t),(null===(s=this._invalidationMask)||void 0===s?void 0:s.fullInvalidation())===pe.InvalidationLevel.Full&&(this._invalidationMask.merge(e),this._adjustSize(this._invalidationMask.isVisibleTimeRangeLockedOnResize()),this._applyTimeScaleInvalidations(this._invalidationMask,t),e=this._invalidationMask,this._invalidationMask=null)),this.paint(e),this._dataWindowWidget){const t=e.maxPaneInvalidation();t===pe.InvalidationLevel.Full?this._dataWindowWidget.fullUpdate():t>pe.InvalidationLevel.None&&this._dataWindowWidget.update()}for(let t=0;tthis._justActivated=!1),0)}_requestActive(){this._beginRequestActive(),this._endRequestActive()}_updateGui(e){this._model&&(this._makeTimeAxisWidget(),this._makePaneWidgetsAndSeparators(),this._elMainTable.style.userSelect="none",this._adjustSize(e))}_setElement(e){if(this._mainDiv){this._mainDiv.remove();const e=document.createRange();e.selectNodeContents((0,r.ensureNotNull)(this._parent)),e.deleteContents()}this._controlBarNavigation&&(this._controlBarNavigation.destroy(),this._controlBarNavigation=null),null!==this._removeMaximizeHotkey&&this._removeMaximizeHotkey(),this._removeMaximizeHotkey=this._initMaximizeHotkey(e);const t=e.ownerDocument,s=t.createElement("div");s.classList.add("chart-container-border"),e.insertBefore(s,e.firstChild),this._parent=s;const o=t.createElement("div") ;if(o.classList.add("chart-widget"),this._mainDiv=o,this._elTooltipDiv=t.createElement("div"),this._elTooltipDiv.className="tooltip-wrapper",this._mainDiv.appendChild(this._elTooltipDiv),this._elMainTable=t.createElement("div"),this._elMainTable.className="chart-markup-table",this._mainDiv.appendChild(this._elMainTable),o.setAttribute("role","region"),o.setAttribute("aria-label",a.t(null,{replace:{index:this.id()}},i(886715))),this._hotkeysListener&&this._hotkeysListener.destroy(),this._errorRenderer.setContainer(this._parent),this._hotkeysListener=new W.ChartHotkeysListener(this,this._mainDiv),(this._options.controlBarEnabled||D.enabled("control_bar"))&&this._createControlBar(),this._options.handleScale.mouseWheel||this._options.handleScroll.mouseWheel){this._mouseWheelHelper=new we;const e=this._onMousewheel.bind(this);this._onWheelBound=e,this._mainDiv.addEventListener("wheel",e,{passive:!1})}this._mainDiv.addEventListener("mouseenter",(()=>this._isHovered.setValue(!0))),this._mainDiv.addEventListener("mouseleave",(()=>this._isHovered.setValue(!1))),this.resize(),this._justActivated=!1,this.withModel(this,(()=>{s.appendChild(o),o.addEventListener("mousedown",this._beginRequestActive.bind(this)),o.addEventListener("mouseup",this._endRequestActive.bind(this)),o.addEventListener("touchstart",this._beginRequestActive.bind(this)),o.addEventListener("touchmove",this._endRequestActive.bind(this)),o.addEventListener("touchend",this._endRequestActive.bind(this)),o.addEventListener("click",this._requestActive.bind(this))})),this._inited&&(null!==this._timeAxisWidget&&(this._timeAxisWidget.destroy(),this._timeAxisWidget=null),this._paneWidgets.forEach((e=>{e.destroy()})),this._paneWidgets.length=0,this._paneSeparators.forEach((e=>{e.destroy()})),this._paneSeparators.length=0,this._update(pe.InvalidationMask.full(),performance.now()))}_init(){this.hasModel()&&this.model().mainSeries().clearData(),this._initColors(),this._makeDefaultGui();this._makeDefaultModel(),(()=>{this._checkObsoleteTimezone(),this._chartSession&&this._chartSession.connected()&&this.model().model().restart(),this._content&&(this._initColors(),this._updateGui(),this.update()),this._resizeHandler=()=>{this._invalidationHandler(pe.InvalidationMask.full())},this._resizeHandler(),(0,r.ensureNotNull)(this._parent).appendChild((0,r.ensureNotNull)(this._mainDiv)),this._spinner&&(this._spinner.stop(),this._spinner=null),this._activateSymbolSearchHotkeys(),this.model().timeScale().onScroll().subscribe(this,(()=>this._onScroll.fire())),this._inited=!0})()}_makeDefaultModel(){let e;if(this._content&&this._content.timeScale.points){const t=this._content.timeScale.points.items[0];e={startDate:t}}const t=()=>{var t,i;const s={readOnly:this.readOnly(),isSnapshot:!!this._containsData,...(0, S.pickFields)(this._options,["timeScale","crossHair","chartEventsEnabled","newsNotificationsEnabled","esdEnabled","latestUpdatesEnabled","continuousContractSwitchesEnabled","futuresContractExpirationEnabled","countdownEnabled","lastPriceAnimationEnabled","currencyConversionEnabled","unitConversionEnabled","watermarkEnabled","shiftVisibleRangeOnNewBar","hideIdeas","onWidget"])},o=function(e,t,i,s,o,r,n,a,l,c,d){const h=new Fa(e,t,i,s,o,r,n,a,l,c,d);return h.model().fullUpdate(),h}(this._chartSession,this._invalidationHandler,this.properties(),e,this,this._options.undoHistory,this._options.barsMarksContainersFactory,s,this._collapsed,this._linkingGroupIndex,null!==(i=null===(t=this._saveChartService)||void 0===t?void 0:t.autoSaveEnabled())&&void 0!==i?i:new O.WatchedValue(!0));return this._createSessions(o.model()),this._createPrePostMarket(o.model()),o};D.enabled("lean_chart_load")?this._model=this._model||t():this._model=t(),this._model.model().setChartSaveTime(1e3*this._chartWidgetCollection.metaInfo.lastModified.value()),this._createVolumeIfNeeded();if(this._content){let e=this._setSymbolIntervalContentOverrides;pc&&this._initialLoading&&(e={...e,symbol:this._defSymbol,interval:this._defInterval,style:this._defStyle},zi.Interval.isRange(this._defInterval)&&(e.style=11)),this.restoreState(this._content,this._containsData,e),this._setSymbolIntervalContentOverrides={},pc&&this._defSymbol&&this.model().model().recalculatePriceRangeOnce()}this._setActions(),this._createLineToolsSynchronizerIfNeeded(),(()=>{const e=(0,r.ensureNotNull)(this._model);e.onTagsChanged().subscribe(this,(()=>this.onModelTagsChanged())),this._initBackgroundColor(),this._updateGui(),this._modelCreated.fire(e),this._tagsChanged.fire();const t=e.mainSeries(),i=t.properties().childs();this._defTimeframe&&t.setDefaultTimeframe(this._defTimeframe),t.dataEvents().symbolNotPermitted().subscribe(null,(e=>t.setSymbolParams({symbol:e}))),this._symbolWV.setValue(i.symbol.value()),i.symbol.subscribe(this,(e=>this._symbolWV.setValue(e.value()))),this._resolutionWV.setValue(i.interval.value()),i.interval.subscribe(this,(e=>this._resolutionWV.setValue(e.value()))),window.loginStateChange.subscribe(this,this._handleLoginStateChanged),this._handleLoginStateChanged(),t.dataEvents().symbolResolved().subscribe(this,(e=>{const i=e.pro_name,s=e.pro_perm;i&&this._options.isSymbolAvailable&&this._options.isSymbolAvailable(i,s).then((e=>{e||t.setSymbolParams({symbol:window.DEFAULT_SYMBOL})}))})),void 0!==this._options.requestFallbackSymbol&&t.dataEvents().symbolGroupNotPermitted().subscribe(this,(e=>{(0,r.ensureDefined)(this._options.requestFallbackSymbol)(i.symbol.value(),{type:"group_not_permitted",symbolGroup:e}).then((e=>{e&&t.setSymbolParams({symbol:e})}))})),(0,r.ensureDefined)(t.onInReplayStateChanged).bind(t)().subscribe(this.screen,this.screen.show),i.style.unsubscribe(this,this._onChartStyleChanged),i.style.subscribe(this,this._onChartStyleChanged),t.dataEvents().completed().subscribe(this,(()=>this._addPerfMark("SeriesCompleted")),!0), t.dataEvents().barReceived().subscribe(this,(()=>this._addPerfMark("SeriesFirstDataReceived")),!0);const s=this._options;t.dataEvents().chartTypeNotPermitted().subscribe(null,(()=>{t.setSymbolParams({interval:"D"}),s.muteSessionErrors||((0,Qi.trackGoProFeature)("kagiRenko"),(0,br.reloginOrGoPro)({feature:"kagiRenko"}))})),t.dataEvents().intradaySpreadNotPermitted().subscribe(null,(()=>{t.setSymbolParams({interval:"D"}),s.muteSessionErrors||(0,br.reloginOrGoPro)({feature:"intradaySpread"})})),t.dataEvents().customIntervalNotPermitted().subscribe(null,(i=>{const o=e.model().defaultResolutions(),r=o.find((e=>(0,ri.compareResolutions)(e,i)>=0)),n=null!=r?r:o[o.length-1];t.setSymbolParams({interval:n}),s.muteSessionErrors||(0,br.reloginOrGoPro)({feature:"customIntervals"})})),t.dataEvents().secondsIntervalNotPermitted().subscribe(null,(()=>{t.setSymbolParams({interval:"1"}),s.muteSessionErrors||(0,br.reloginOrGoPro)({feature:"secondsIntervals",forceUpgradeBtn:!0})})),t.dataEvents().ticksIntervalNotPermitted().subscribe(null,(()=>{t.setSymbolParams({interval:"1"}),s.muteSessionErrors||(0,br.reloginOrGoPro)({feature:"tickIntervals",forceUpgradeBtn:!0,isTrialAvailable:!1})})),t.dataEvents().intradayExchangeNotPermitted().subscribe(null,(()=>{if(t.setSymbolParams({interval:"D"}),!s.muteSessionErrors){let e=(0,r.ensureNotNull)(t.symbolInfo()).listed_exchange;(0,za.getExchanges)().forEach((t=>{t.value===e&&(e=t.name)})),(0,br.reloginOrGoPro)({feature:"intradayExchange"})}})),t.requestingStyleIsNotSupported.subscribe(null,(()=>{const i=t.interval(),s=e.model().defaultResolutions(),o=(0,oe.getLastUsedSingleValueBasedStyle)(),r=(0,ri.getResolutionByChartStyle)(o,i,s);t.setChartStyleWithIntervalIfNeeded(o,r)})),t.requestingStyleSupportRecovered.subscribe(null,(i=>{const s=t.interval(),o=e.model().defaultResolutions(),r=(0,ri.getResolutionByChartStyle)(i,s,o);t.setChartStyleWithIntervalIfNeeded(i,r)}))})()}_addHotkeys(){if(this._hotkeys.add({desc:"Maximize",hotkey:n.Modifiers.Alt+13,handler:()=>this.toggleFullscreen(),isDisabled:()=>!this.getResizerDetacher().fullscreenable.value()}),this._hotkeys.add(this._clearSelectionHotkey()),this._options.indicatorsDialogShortcutEnabled&&this._hotkeys.add({desc:"Show insert indicator dialog",hotkey:111,handler:()=>this.showIndicators()}),!this.readOnly()){this._hotkeys.add({desc:"Remove selected source",hotkey:n.isMacKeyboard?46:8,handler:()=>this.removeSelectedSources()});{const e=(e,t)=>{this.activePaneWidget&&("drawRightThere"===t.action?this.activePaneWidget.drawRightThere(e):Oe.tool.setValue(e))},t=(t,i)=>()=>e(t,i);Object.entries(Xa.lineToolsSelectHotkeys).map((([e,i])=>({desc:i.description,hotkey:i.hash,handler:t(e,i)}))).forEach((e=>this._hotkeys.add(e)))}}this.withModel(null,(()=>{const e=()=>this._hotkeys.promote();this.model().onSelectedSourceChanged().subscribe(null,e),this.model().crossHairSource().measurePane().subscribe((t=>{null!==t&&e()}))}))}_startSpinner(e){this._spinner||e&&(this._spinner=(new I.Spinner).spin(e))}_handleLoginStateChanged(){ D.enabled("popup_hints")&&window.user&&window.user.is_pro?this._noExchangeSubscrptionWarning=new $a(this):null!==this._noExchangeSubscrptionWarning&&(this._noExchangeSubscrptionWarning.destroy(),this._noExchangeSubscrptionWarning=null)}_checkObsoleteTimezone(){const e=this.properties().childs().timezone.value();(0,k.timezoneIsAvailable)(e)||this.properties().childs().timezone.setValue({UTC:"Etc/UTC",EST:"America/New_York",CST:"America/Chicago",PST:"America/Los_Angeles"}[e]||"exchange")}_initColors(){const e=this.properties().childs(),t=e.scalesProperties.childs();t.lineColor.listeners().subscribe(this,this._updateAndPaint),t.textColor.listeners().subscribe(this,this._updateAndPaint),e.paneProperties.childs().separatorColor.listeners().subscribe(this,this._setPaneSeparatorLineColor)}_setPaneSeparatorLineColor(){this._paneSeparators.forEach((e=>e.update())),this._updateAndPaint()}_updateAndPaint(){this.update(),this.paint()}_makeDefaultGui(){this._makeLoadingScreen(),this.onWidget()&&this._makeAvailableOnTVPopup(),this.hasModel()&&(this._makeTimeAxisWidget(),this._makePaneWidgetsAndSeparators(),this._updateScalesActions()),this._adjustSize(),(0,V.disableSelection)(this._elMainTable),this._updateAndPaint()}_makeLoadingScreen(){if(D.enabled("lean_chart_load")){if(this.screen)return;this.screen=new ye(this,(0,r.ensureNotNull)(this._parent))}else this.screen=new ye(this,(0,r.ensureNotNull)(this._mainDiv))}_makeAvailableOnTVPopup(){this._availableScreen||(this._availableScreen=new Qa(this))}_activateSymbolSearchHotkeys(){this.readOnly()||this._options.hideSymbolSearch||(0,v.activateKeyPressHandler)()}_makeTimeAxisWidget(){if(this._timeAxisWidget)return void this._timeAxisWidget.updatePriceAxisStubs();const e=this.model();this._timeAxisWidget=new Ri(this,this._options.timeScaleWidget,this._titlesProvider.bind(this),this._menuItemsProvider.bind(this),this._backgroundBasedTheme.spawnOwnership()),this._elMainTable.appendChild(this._timeAxisWidget.getElement()),this._timeAxisWidget.updatePriceAxisStubs(),this._timeAxisWidget.onLabelHovered().subscribe(this,((t,i)=>{const s=this._maximizedPaneWidget?this._maximizedPaneWidget.state():e.paneForSource(e.mainSeries()),o=(0,r.ensureNotNull)(this.paneByState((0,r.ensureNotNull)(s))).highlightedPriceAxis(),n=o.value();(i||n.owner===t.owner)&&(o.setValue({owner:t.owner,axis:i?t.axis:null}),this.model().model().lightUpdate())}))}_updateAriaPriceDescription(e){}_titlesProvider(e,t){const i=this.model(),s=(0,r.ensureNotNull)(this._maximizedPaneWidget?this._maximizedPaneWidget.state():i.paneForSource(i.mainSeries())),o="right"===e?s.rightPriceScales():s.leftPriceScales();if(o.lengthe===i.mainSeries()||(0,q.isStudy)(e)));return n.reverse(),n=(0,A.moveToHead)(n,i.mainSeries()),n.map((e=>e.title(is.TitleDisplayTarget.StatusLine,!0,void 0,!1)))}_menuItemsProvider(e,t){const i=this.model(),s=(0, r.ensureNotNull)(this._maximizedPaneWidget?this._maximizedPaneWidget.state():i.paneForSource(i.mainSeries())),o="right"===e?s.visibleRightPriceScales():s.visibleLeftPriceScales();if(o.length{const i=this._model ;if(null===i)return;const s=i.model();e.model!==s&&(this._lineToolsSynchronizer?this._lineToolsSynchronizer.executeSyncedAction((()=>t(s,i))):t(s,i))};Oe.createdLineTool.subscribe(null,(t=>{e(t,((e,i)=>{const s=(0,r.ensureNotNull)(e.paneForSource(e.mainSeries()));let o,n=null;if(void 0===t.pointPositionPercents){if(n=fc(e,t.model,t.point.timeStamp),null===n)return;o=t.point.price}else{const i=t.pointPositionPercents.x*e.timeScale().width(),s=e.mainSeries().priceScale(),r=t.pointPositionPercents.y*s.height(),a=e.mainSeries().firstValue();if(null===a)return;n=e.timeScale().coordinateToIndex(i),o=s.coordinateToPrice(r,a)}const a={index:(0,r.ensureNotNull)(n),price:o},l=i.createLineTool({pane:s,point:a,linetool:t.linetool,properties:t.properties,linkKey:t.linkKey,ownerSource:e.mainSeries(),disableSynchronization:!0,id:t.id,sharingMode:t.sharingMode});null!==l&&!Boolean(this.model().lineBeingCreated())&&t.finalState&&l.restoreExternalPoints(t.finalState,{indexesChanged:!0,pricesChanged:!0})}))})),Oe.continuedLineTool.subscribe(null,(t=>{e(t,((e,i)=>{var s;const o=fc(e,t.model,t.point.timeStamp);if(null===o)return;const r={index:o,price:t.point.price},n=e.lineBeingCreated();if(null===n)return;i.continueExternalLine(r,null!==(s=t.envState)&&void 0!==s?s:void 0,!!t.finalState)&&t.finalState&&n.restoreExternalPoints(t.finalState,{indexesChanged:!0,pricesChanged:!0})}))})),Oe.cancelledLineTool.subscribe(null,(t=>{e(t,((e,t)=>{e.cancelCreatingLine()}))})),Oe.beenSetLineToolLastPoint.subscribe(null,(t=>{e(t,((e,i)=>{const s=e.lineBeingCreated();if(null===s||s.linkKey().value()!==t.linkKey)return;const o=fc(e,t.model,t.point.timeStamp);if(null===o)return;const r={index:o,price:t.point.price};s.setLastPoint(r),s.updateAllViews((0,ni.sourceChangeEvent)(s.id())),e.lightUpdate()}))})),Oe.startedMovingLineTool.subscribe(null,(t=>{e(t,((e,i)=>{var s;const o=t.linkKeys.map(K.lineToolByLinkKey.bind(null,e)).filter(w.notNull);if(o.length){const i=fc(e,t.model,t.point.timeStamp);if(null===i)return;const r={index:i,price:t.point.price},n=null!==(s=t.activeItem)&&void 0!==s?s:null,a=o[0].pointToScreenPoint(r);a&&e.startMovingSources(o,{logical:r,screen:a},n,t.pointPositionPercents,null===t.envState?void 0:t.envState,!0)}}))})),Oe.movedLineTool.subscribe(null,(t=>{e(t,((e,i)=>{var s;const o=e.sourcesBeingMoved().filter(K.isLineTool).filter((e=>(e=>t.linkKeys.some((t=>e.linkKey().value()===t)))(e)));if(!o.length)return;const r=fc(e,t.model,t.point.timeStamp);if(null===r)return;const n={index:r,price:t.point.price},a=o[0].pointToScreenPoint(n);a&&e.moveSources({logical:n,screen:a},t.pointPositionPercents,null!==(s=t.envState)&&void 0!==s?s:void 0,!0)}))})),Oe.finishedMovingLineTool.subscribe(null,(t=>{e(t,((e,i)=>{const s=e.sourcesBeingMoved().filter(K.isLineTool);if(0===s.length)return;s.forEach((i=>{const s=(e=>{for(let i=0;i{e(t,((e,i)=>{var s;const o=(0,K.lineToolByLinkKey)(e,t.linkKey);if(null!==o){const i=o.getPoint(t.pointIndex),r=i?i.index:fc(e,t.model,t.point.timeStamp);if(null===r)return;if(o.isActualSymbol()&&o.isActualCurrency()&&o.isActualUnit()){const i={index:r,price:t.point.price};e.startChangingLinetool(o,i,t.pointIndex,null!==(s=t.envState)&&void 0!==s?s:void 0,!0)}}}))})),Oe.changedLineTool.subscribe(null,(t=>{e(t,((e,i)=>{const s=e.lineBeingEdited();if(null===s||s.linkKey().value()!==t.linkKey)return;let o=null;if(o=t.changes.indexesChanged?fc(e,t.model,t.point.timeStamp):(0,r.ensureNotNull)(e.linePointBeingChanged()).index,null!==o&&s.isActualSymbol()&&s.isActualCurrency()&&s.isActualUnit()){const i={index:o,price:t.point.price};e.changeLinePoint(i,void 0,!0)}}))})),Oe.finishedChangingLineTool.subscribe(null,(t=>{e(t,((e,i)=>{const s=(0,K.lineToolByLinkKey)(e,t.linkKey);null!==s&&s.isActualSymbol()&&s.isActualCurrency()&&s.isActualUnit()&&null!==e.lineBeingEdited()&&e.endChangingLinetool(!!t.finalState,!0),null!==s&&t.finalState&&s.restoreExternalPoints(t.finalState,t.changes)}))})),Oe.removedLineTool.subscribe(null,(t=>{e(t,((e,i)=>{const{withUndo:s,unlink:o,linkKey:r}=t,n=(0,K.lineToolByLinkKey)(e,r);null!==n&&(o&&n.detachAlert(),s?i.removeSource(n,!1):(e.lineToolsGroupModel().removeLineTools([n]),e.removeSource(n)))}))})),Oe.finishedLineTool.subscribe(null,(t=>{e(t,((e,i)=>{const s=(0,K.lineToolByLinkKey)(e,t.linkKey);null!==s&&(0,Qt.isLineToolFinishRequiredWhenCreatedByApi)(s.toolname)&&s.finish()}))})),Oe.changedLineStyle.subscribe(null,(t=>{e(t,((e,i)=>{const s=(0,K.lineToolByLinkKey)(e,t.linkKey);null!==s&&(s.restoreExternalState(t.state),s.propertiesChanged(!0),t.alertId&&s.syncAlert(t.alertId))}))})),Oe.restoredLineToolState.subscribe(null,(t=>{e(t,((e,i)=>{const s=(0,K.lineToolByLinkKey)(e,t.linkKey);if(null!==s){const i={...t.state};i.indexes=t.state.points.map((i=>({index:fc(e,t.model,i.time_t),price:i.price}))),e.restoreLineToolState(s,i,!1)}}))})),Oe.restoredLineTool.subscribe(null,(t=>{e(t,((e,i)=>{e.restoreSource(t.state.restorePane,t.state.paneIndex,t.state.paneState,t.state.sourceState,null)}))})),Oe.copiedLineTool.subscribe(null,(t=>{e(t,((e,i)=>{const s=(0,r.ensureNotNull)(e.paneForSource(e.mainSeries()));let o;const n={...t.state,intervalsVisibilities:(0,Nr.mergeIntervalVisibilitiesDefaults)(t.state.intervalsVisibilities)},a=(0,K.createLineToolProperties)(t.linetool,n,e),l=e.dataSourceForId(t.id);if(l){if(!(0,K.isLineTool)(l))return void _c.logError(`Error sync creating line tool. Object with id ${t.id} is already in use and it is not a line tool`);if(l.toolname!==t.linetool)return void _c.logError(`Error sync creating line tool. Object with id ${t.id} is already in use and its type differs: ${l.toolname} and ${t.linetool}`)}if(l&&(l.linkKey().setValue(t.linkKey),l.share(t.sharingMode)),t.pointPositionPercents){const e={index:0,price:0} ;if(o=null!=l?l:i.createLineTool({pane:s,point:e,linetool:t.linetool,properties:a,linkKey:t.linkKey,disableSynchronization:!0,id:t.id}),null===o)return;o.restorePositionPercents((0,r.ensureDefined)(t.pointPositionPercents))}else{const n=t.points.map((i=>({index:(0,r.ensureNotNull)(fc(e,t.model,i.timeStamp)),price:i.price}))),c=n[0];if(l)o=l;else if(t.withUndo)o=i.createLineTool({pane:s,point:c,linetool:t.linetool,properties:a,linkKey:t.linkKey,sharingMode:t.sharingMode,disableSynchronization:!0,id:t.id});else{const e=new Os({model:i.model(),pane:s,lineTool:t.linetool,ownerSource:(0,r.ensureNotNull)(s.mainDataSource()),drawOnAllChartsMode:t.sharingMode,id:t.id});e.redo(),e.startCreatingLine(c,a,t.linkKey||null,t.sharingMode,!0),o=(0,r.ensureNotNull)(e.line())}if(null===o)return;const d=(e,s)=>{t.withUndo?i.continueCreatingLine(e,new Ne.EnvironmentState(void 0,!0),s,!0):i.model().continueCreatingLine(e,new Ne.EnvironmentState(void 0,!0),s,!0)},h=(0,Qt.isLineToolFinishRequiredWhenCreatedByApi)(t.linetool);if(e.lineBeingCreated())if(n.length>1)for(let e=1;e0){const i=Math.ceil(e.timeScale().width()/t.barCount);e.timeScale().setBarSpacing(i)}}_createEventHint(){if(null===this._eventHintDeferredPromise){const e=(0,g.createDeferredPromise)();this._eventHintDeferredPromise=e,Promise.all([i.e(66458),i.e(51439),i.e(90385),i.e(26166)]).then(i.bind(i,410837)).then((t=>{e.resolve(new t.ChartEventHintRenderer(this._chartWidgetCollection.getContainer()))}))}return this._eventHintDeferredPromise.promise}async _createWarningHint(){if(null===this._warningHintDeferredPromise){const e=(0,g.createDeferredPromise)();this._warningHintDeferredPromise=e,Promise.all([i.e(4343),i.e(13031),i.e(22847),i.e(90385),i.e(83129)]).then(i.bind(i,629981)).then((t=>{e.resolve(new t.ChartWarningHintRenderer(this))}))}return this._warningHintDeferredPromise.promise}_showEventHint(e){D.enabled("popup_hints")&&(null!==this._activeHint&&0===this._activeHint.type?this._activeHint.show(e):(this._hideHint(),this._createEventHint().then((t=>{this._activeHint=t,void 0!==e&&this._activeHint.show(e)}))))}_showWarningHint(e){D.enabled("popup_hints")&&(null!==this._activeHint&&1===this._activeHint.type?this._activeHint.show(e):(this._hideHint(),this._createWarningHint().then((t=>{if(null!==t){if(this._activeHint=t,void 0===e)return;this._activeHint.show(e)}}))))}_hideHint(){null!==this._activeHint&&this._activeHint.hide()}_checkIsTradedGroupSelected(){const e=this.model(),t=e.model();return e.selection().customSources().some((e=>{var i;return null===(i=t.customSourceName(e))||void 0===i?void 0:i.startsWith("tradedGroup:PlaceOrder")}))}_setActions(){return this._unsetActions(),this._addHotkeys(),this._actions=uc(this),this.withModel(null,(()=>{const e=this.model().mainSeries(),t=e.properties();t.childs().priceAxisProperties.subscribe(this,this._updateScalesActions),e.priceScaleAboutToBeChanged().subscribe(this,(()=>{t.childs().priceAxisProperties.unsubscribeAll(this)})),e.priceScaleChanged().subscribe(this,(()=>{t.childs().priceAxisProperties.subscribe(this,this._updateScalesActions),this._updateScalesActions()}))})),this._updateScalesActions(),this._actions}_unsetActions(){this._actions&&(Object.values(this._actions).forEach((e=>{e.destroy()})),this._actions=null)}}},749765:(e,t,i)=>{"use strict";i.r(t),i.d(t,{activeLinkingGroupWV:()=>Bi,allInitialModelsCreated:()=>mi,allInitialSymbolsResolved:()=>pi,allLinkingGroupsWV:()=>Ri,applyIndicatorToAllChartsImpl:()=>bt,applyIndicatorsToAllChartsImpl:()=>ft,applyLineToolUpdateNotificationImpl:()=>xt,applyStudiesOverrides:()=>Ji,applyThemeImpl:()=>vi,chartsSymbolsImpl:()=>kt,checkProFeatureImpl:()=>gi,combinedTrackTimeLock:()=>Hi, computeContentBoxImpl:()=>zt,copyScreenshotToClipboard:()=>Ot,createBroadcastChannel:()=>hi,createChartStorageSubscriptionsIfRequired:()=>Et,createChartWidgetCollectionNewsNotifier:()=>Dt,createClipboardHandler:()=>At,createLeftBottomChartWidgetWV:()=>Wt,deserializedChartIds:()=>Tt,destroyBroadcastChannel:()=>ui,downloadScreenshot:()=>Rt,generateNewChartId:()=>Xt,getAllLinkingGroups:()=>Ni,getAsyncStateForChartImpl:()=>Pt,getChartWidgetsForIntervalLock:()=>ki,getClientSnapshot:()=>Ht,getLinkingGroupCharts:()=>Oi,getSnapshot:()=>Ft,getStateForChartImpl:()=>wt,getVisuallyAdjacentDefImpl:()=>Yt,handleConnectionLimitReachedChanged:()=>Wi,handleDateRangeLockChange:()=>Pi,handleInternalDateRangeLockChange:()=>wi,handleInternalIntervalLockChange:()=>yi,handleInternalSymbolLockChange:()=>fi,handleInternalTrackTimeLockChange:()=>Ti,handleIntervalLockChange:()=>Ci,handleSymbolLockChange:()=>bi,handleTrackTimeLockChange:()=>Mi,hideChartImpl:()=>ti,lineToolsAndGroupsDTOsImpl:()=>Ct,removeChartWidgetSubscriptionsImpl:()=>si,resetLayoutSizesImpl:()=>qt,resetLineToolsInvalidatedImpl:()=>Mt,setBrokerImpl:()=>Lt,setChartLayoutWithUndoImpl:()=>Si,setChartStyleToWidget:()=>Ai,setLayoutImpl:()=>li,setResolution:()=>Ei,setSymbol:()=>xi,setSymbolAll:()=>Ii,someOfWidgetsAreInSelectingReplayPointMode:()=>Fi,stateImpl:()=>$i,subscribeToCompletedEventForDateRangeUpdate:()=>zi,subscribeToEventsForDateRangeSync:()=>ji,syncChartsDateRangesWithActiveChartRange:()=>Yi,syncCrosshairImpl:()=>di,syncScrollImpl:()=>_i,takeScreenshot:()=>Bt,takeServerScreenshot:()=>Nt,unloadUnusedChartsImpl:()=>oi,unsubscribeFromEventsForDateRangeSync:()=>Zi,updateLayoutImpl:()=>Kt,updateLayoutPartialImpl:()=>Zt,updateLinkingGroupCharts:()=>Vi});var s=i(650151),o=i(86441),r=i(201089),n=i(444372),a=i(912445),l=i(638456),c=i(809796),d=i(244842);function h(e){const t={};return{promise:new Promise(((i,s)=>{e.subscribe(t,i,!0)})),destroy:()=>{e.unsubscribeAll(t)}}}var u=i(401580),_=i(270294),p=i(142257);class m extends p.UndoCommand{constructor(e,t){super(null),this._chartModel=e,this._targetIndex=t}redo(){const e=this._chartModel.createPane(this._targetIndex,void 0,this._paneId);this._paneId=e.id()}undo(){const e=(0,s.ensureDefined)(this._paneId),t=this._chartModel.panes().find((t=>t.id()===e));void 0!==t&&this._chartModel.removePane(t)}createdPaneId(){return this._paneId}}class g extends p.UndoCommand{constructor(e,t,i,s){super(s),this._setter=e,this._oldValue=t,this._newValue=i}redo(){this._setter(this._newValue)}undo(){this._setter(this._oldValue)}}class S extends g{constructor(e,t,i,s){super((e=>this._vwState.setValue(e)),t,i,s),this._vwState=e}}var v=i(919476),f=i(963239),b=i(793993);const y=(0,r.getLogger)("Clipboard");class C{constructor(e){this._e=e}write(e){return(0,f.writeImpl)(this._toRaw(e),this._e)}_toRaw(e){const t={files:[]};t.text=e.text,void 0!==e.app?t.html=this._serializeAppData(e.app,e.text):e.html&&(t.html=e.html);for(const i of e.files||[])t.files.push(i);return t}_serializeAppData(e,t){return`${t?(0,v.htmlEscape)(t.slice(0,256)):"📈"}`}}class w{constructor(e){this._e=e}async read(){this._e&&0===this._e.eventPhase&&(y.logWarn("Cannot use an already dispatched ClipboardEvent for reading"),this._e=null);const e=this._e?this._readUsingEvent(this._e):await this._readUsingApi();return this._fromRaw(e)}_readUsingEvent(e){const t=(0,s.ensure)(e.clipboardData);e.preventDefault();const i={files:[]};for(let e=0;e0&&(t.files=e.files),t}_parseAppData(e){if(-1===e.slice(0,1024).indexOf("data-tradingview-clip"))return;const t=(new DOMParser).parseFromString(e,"text/html").querySelector("[data-tradingview-clip]");return t?t.getAttribute("data-tradingview-clip")||"":void 0}_readBlobAsText(e){return new Promise(((t,i)=>{const s=new FileReader;s.onloadend=()=>{t(s.result)},s.onerror=()=>{i(s.error)},s.readAsText(e)}))}}var P=i(515312);function T(e){const t=e.target;return null!==t&&1===t.nodeType&&(0,P.isTextEditingField)(t)}function M(e){const t=e.target;if(null===t)return!1;const i=(t.ownerDocument||t).getSelection();return null!==i&&!i.isCollapsed}class x extends class{constructor(e){this._callbacks=Object.assign({},e),this._boundOnCopy=this._onCopyEv.bind(this),this._boundOnCut=this._onCutEv.bind(this),this._boundOnPaste=this._onPasteEv.bind(this)}listen(){document.addEventListener("copy",this._boundOnCopy),document.addEventListener("cut",this._boundOnCut),document.addEventListener("paste",this._boundOnPaste)}async peek(){if("granted"!==(await navigator.permissions.query({name:"clipboard-read"})).state)throw new Error("clipboard-read is not granted");return new w(null).read()}uiRequestCopy(e){this._callbacks.copyRequested&&this._callbacks.copyRequested(new C(null),e)}uiRequestCut(e){this._callbacks.cutRequested&&this._callbacks.cutRequested(new C(null),e)}uiRequestPaste(e){this._callbacks.pasteRequested&&this._callbacks.pasteRequested(new w(null),e)}destroy(){document.removeEventListener("copy",this._boundOnCopy),document.removeEventListener("cut",this._boundOnCut),document.removeEventListener("paste",this._boundOnPaste)}_onCopyEv(e){e.defaultPrevented||this._callbacks.copyRequested&&this._callbacks.copyRequested(new C(e))}_onCutEv(e){ e.defaultPrevented||this._callbacks.cutRequested&&this._callbacks.cutRequested(new C(e))}_onPasteEv(e){e.defaultPrevented||this._callbacks.pasteRequested&&this._callbacks.pasteRequested(new w(e))}}{_onCopyEv(e){if(!T(e)&&!M(e))return super._onCopyEv(e)}_onCutEv(e){if(!T(e)&&!M(e))return super._onCutEv(e)}_onPasteEv(e){if(!T(e))return super._onPasteEv(e)}}const I=()=>i.e(54389).then(i.bind(i,425471));function A(e,t={}){return I().then((i=>i.copyToClipboardImageOfChart(e,t)))}function L(e,t={}){return I().then((i=>i.getImageOfChartSilently(e,t)))}var k=i(470316),E=i(410864),D=i(588948),B=i(572230);const N=(0,r.getLogger)("TimingsMeter.Service"),R=(0,r.getLogger)("TimingsMeter.Stats",{maxCount:160});function O(){return{[B.InvalidationLevel.None]:{count:0,lastTime:0,maxTime:0,totalTime:0},[B.InvalidationLevel.Cursor]:{count:0,lastTime:0,maxTime:0,totalTime:0},[B.InvalidationLevel.Light]:{count:0,lastTime:0,maxTime:0,totalTime:0},[B.InvalidationLevel.Full]:{count:0,lastTime:0,maxTime:0,totalTime:0}}}function V(e,t){e.lastTime=t,e.totalTime+=t,++e.count,t>e.maxTime&&(e.maxTime=t)}function W(e){return e.toFixed(2)}function F(e){const t=e.count;if(0===t)return"no events";const i=e.totalTime/t,s=W(e.maxTime);return`count=${t}, last=${W(e.lastTime)}, max=${s}, avg=${W(i)}`}class H{constructor(e){this._waitDrawStartTime=-1,this._startDrawTime=-1,this._currentDrawLevel=B.InvalidationLevel.Full,this._currentDrawItems=O(),this._currentWaitingItem={count:0,lastTime:0,maxTime:0,totalTime:0},this._dumpTimingsStatsInterval=0,this._logPrefix=`[${e}]`}destroy(){this.stopCollect()}startCollect(){0!==this._dumpTimingsStatsInterval&&(N.logWarn(`${this._logPrefix} Multiple start detected`),this.stopCollect()),this._clearCurrentState(),this._dumpTimingsStatsInterval=setInterval(this._dumpTimingsStats.bind(this),15e3),N.logNormal(`${this._logPrefix} Collecting started`)}stopCollect(){0!==this._dumpTimingsStatsInterval&&(clearInterval(this._dumpTimingsStatsInterval),this._dumpTimingsStatsInterval=0,N.logNormal(`${this._logPrefix} Collecting stopped. Dumping last state...`),this._dumpTimingsStats())}startWaitingDraw(){this._waitDrawStartTime=window.performance.now()}startDraw(e){this._startDrawTime=window.performance.now(),this._currentDrawLevel=e}stopDraw(){const e=window.performance.now();if(-1===this._startDrawTime||-1===this._waitDrawStartTime)return;const t=this._startDrawTime-this._waitDrawStartTime;V(this._currentWaitingItem,t),this._waitDrawStartTime=-1;const i=e-this._startDrawTime;V(this._currentDrawItems[this._currentDrawLevel],i),this._startDrawTime=-1}_dumpTimingsStats(){const e=[this._logPrefix," awaiting:",F(this._currentWaitingItem),"; cursor:",F(this._currentDrawItems[B.InvalidationLevel.Cursor]),"; light:",F(this._currentDrawItems[B.InvalidationLevel.Light]),"; full:",F(this._currentDrawItems[B.InvalidationLevel.Full])].join("");R.logNormal(e),this._clearCurrentState()}_clearCurrentState(){this._currentDrawItems=O(),this._currentWaitingItem={count:0,lastTime:0,maxTime:0,totalTime:0}}}var z=i(922850),U=i(616117);function G(e){ return{...e,panes:(t=e.panes,t.map((e=>{return{...e,sources:(t=e.sources,t.filter((e=>!(0,U.isLineToolName)(e.type))))};var t})))};var t}function q(e,t){var i;const s=e.find((e=>e.tools.includes(t)));return null!==(i=null==s?void 0:s.id)&&void 0!==i?i:null}function j(e){var t,i;const o=e.panes.map((e=>e.sources.filter((e=>(0,U.isLineToolName)(e.type))))).reduce(((e,t)=>t.concat(e)),[]),r=null!==(i=null===(t=e.lineToolsGroups)||void 0===t?void 0:t.groups)&&void 0!==i?i:[],n=new Map;o.forEach((e=>{const t=e.id;n.set(t,function(e,t){var i;return{id:e.id,symbol:e.state.symbol,ownerSource:(0,s.ensureDefined)(e.ownerSource),state:e,groupId:null!==(i=q(t,e.id))&&void 0!==i?i:void 0}}(e,r))}));const a=new Map;return r.forEach((e=>{const t=function(e,t){var i,s;if(0===e.tools.length)return null;const o=e.tools[0];return null!==(s=null===(i=t.get(o))||void 0===i?void 0:i.symbol)&&void 0!==s?s:null}(e,n);null!==t&&a.set(e.id,{id:e.id,name:e.name,symbol:t})})),{sources:n,groups:a}}var Z=i(531005),K=i(405117),Y=i(778016),$=i(960337),X=i(371927),J=i(154765),Q=i(1500),ee=i(500521),te=i(175203),ie=i(314802),se=i(368654),oe=i(652171),re=i(474759),ne=i(944454),ae=i(266325),le=i(930003);const ce=new class{constructor(){this._timerWorker=null,this._timerIdCounter=1,this._timersMap=new Map,this._rejectsToCall=new Set,this._processMessage=e=>{const t=this._timersMap.get(e.data.turnaround);switch(e.data.type){case"timerCreated":t&&(t.scheduledForRemoving?("interval"===t.type?this._getTimerWorker().postMessage({type:"clearInterval",id:e.data.id}):this._getTimerWorker().postMessage({type:"clearTimeout",id:e.data.id}),this._deleteTimerFromMap(e.data.turnaround)):t.workerTimerId=e.data.id);break;case"timerFired":t&&(t.callback(),"timeout"===t.type&&this._deleteTimerFromMap(e.data.turnaround))}}}destroy(){var e;this._rejectsToCall.forEach((e=>e((0,ae.createAbortError)()))),null===(e=this._timerWorker)||void 0===e||e.terminate(),this._timerWorker=null,this._timersMap.clear()}setTimeout(e,t){return this._setTimeoutImpl(e,t,"timeout")}clearTimeout(e){const t=this._timersMap.get(e);t&&(t.workerTimerId?(this._getTimerWorker().postMessage({type:"clearTimeout",id:t.workerTimerId}),this._deleteTimerFromMap(e)):t.scheduledForRemoving=!0)}setInterval(e,t){const i=this._nextTimerId();return this._timersMap.set(i,{callback:e,type:"interval"}),this._getTimerWorker().postMessage({type:"setInterval",delay:t,turnaround:i}),i}clearInterval(e){const t=this._timersMap.get(e);t&&(t.workerTimerId?(this._getTimerWorker().postMessage({type:"clearInterval",id:t.workerTimerId}),this._deleteTimerFromMap(e)):t.scheduledForRemoving=!0)}async createTimeout(e,t){let i;return new Promise(((s,o)=>{var r;i=o,this._rejectsToCall.add(i);const n=this.setTimeout(s,e);null===(r=null==t?void 0:t.signal)||void 0===r||r.addEventListener("abort",(()=>{this.clearTimeout(n),o((0,ae.createAbortError)())}))})).finally((()=>{this._rejectsToCall.delete(i)}))}async*createInterval(e,t){let i=()=>{},s=e=>{};const o=this.setInterval((()=>{i()}),e);t.signal.addEventListener("abort",(()=>{ this.clearInterval(o),s((0,ae.createAbortError)())}));try{for(;;)await new Promise(((e,t)=>{i=e,this._rejectsToCall.delete(s),s=t,this._rejectsToCall.add(s)})),yield}catch(e){if(!(0,ae.isAbortError)(e))throw e}}_getTimerWorker(){return null===this._timerWorker&&(this._timerWorker=new le.Worker(new URL(i.p+i.u(77050),i.b),{name:"Timer worker"}),this._timerWorker.onmessage=this._processMessage),this._timerWorker}_setTimeoutImpl(e,t,i){const s=this._nextTimerId();return this._timersMap.set(s,{callback:e,type:i}),this._getTimerWorker().postMessage({type:"setTimeout",delay:t,turnaround:s}),s}_deleteTimerFromMap(e){if(this._timersMap.delete(e),0===this._timersMap.size){const e=this._setTimeoutImpl((()=>{var t;1===this._timersMap.size&&this._timersMap.has(e)&&(this._timersMap.delete(e),null===(t=this._timerWorker)||void 0===t||t.terminate(),this._timerWorker=null)}),6e4,"terminal_timer")}}_nextTimerId(){return this._timerIdCounter++}};var de=i(707957),he=i(125226);const ue=new Set(["chart_storage_hibernation_delay_60min","chart_storage_hibernation_delay_10min","chart_storage_hibernation_delay_5min"]);const _e=new u.WatchedValue(pe());function pe(){return(0,he.isFeatureEnabled)("chart_storage_hibernation_delay_60min")?36e5:(0,he.isFeatureEnabled)("chart_storage_hibernation_delay_10min")?6e5:(0,he.isFeatureEnabled)("chart_storage_hibernation_delay_5min")?3e5:6e4}(0,he.onFeaturesStateChanged)().subscribe(null,(e=>{if(!function(e){return ue.has(e)}(e))return;const t=pe();_e.setValue(t,!1)}));const me=_e.readonly();function ge(e){const t=document.querySelector('link[rel~="chart-storage-notifications"]');return(null==t?void 0:t.href)?e?new URL(e,t.href):new URL(t.href):null}function Se(e,t){return Boolean(e.metaInfo.uid.value())&&!t.containsData&&!t.onWidget&&function(){if(!(0,ie.isOnMobileAppPage)("new"))return!0;const e=/TradingView\/(\d+)\.(\d+)\.(\d+)\.?/.exec(navigator.userAgent);if(null===e)return!0;const t=Number(e[1])-1,i=Number(e[2])-15,s=Number(e[3])-0;if(t>0||0===t&&i>0||0===t&&0===i&&s>0)return!0;return!1}()&&null!==ge()}const ve=(0,r.getLogger)("ChartStorageChangesSubscription");class fe extends se.PersistentEventSourceTransport{constructor(e,t){super((e=>this._onMessage(e))),this._destroyed=!1,this._onChangeVisibilityBound=this._onChangeVisibility.bind(this),this._hibernateTimerId=null,this._hibernateDelay=me.spawn(),this._beforeUnhibernating=new de.Delegate,this._haveEverBeenHibernated=!1,this._chartWidgetsCollection=e,this._layoutVisibility=e.resizerBridge().visible.spawn(),this._layoutVisibility.subscribe(this._onChangeVisibilityBound,{callWithLast:!0}),te.telemetry.sendLineToolsStorageReport("line_tools_subscription_initial_connect"),this._connectionStatus.subscribe((e=>{e===ne.ConnectionStatus.Closed&&te.telemetry.sendLineToolsStorageReport("line_tools_subscription_disconnected")})),this._subscribeForSharingLayout=t,this.connect(),this._hibernateDelay.subscribe((e=>{null!==this._hibernateTimerId&&this._scheduleHibernation(e)}))}destroy(){this._layoutVisibility.destroy(),this._hibernateDelay.destroy(), this.disconnect(),this._destroyed=!0}beforeUnhibernating(){return this._beforeUnhibernating}async _prepareParamsForConnection(e){const t=this._chartWidgetsCollection.metaInfo.uid.value();if(this._destroyed)return Promise.reject("Subscription is being destroyed");const i=await(0,oe.getStorageTarget)(t,"",0),s=ge(`/charts-storage/layout/${t}/subscribe`);null!==s?(s.searchParams.delete("jwt"),s.searchParams.append("jwt",i.token),this._subscribeForSharingLayout&&window.user.id&&window.user.is_pro&&s.searchParams.append("id",""+window.user.id),this._url=s.toString()):this._url=""}_tryReconnectImpl(){super._tryReconnectImpl(),te.telemetry.sendLineToolsStorageReport("line_tools_subscription_reconnecting")}_onMessage(e){if("string"!=typeof e)throw new Error("Wrong message type, expected string");const t=JSON.parse(e);Object.entries(t).forEach((e=>{const t=(0,re.parseLineToolsAndGroupsDTO)(e[1],""),i=e[0];let s=0;i===oe.sharedChartId?s=1:i===oe.globallySharedChartId&&(s=2),this._chartWidgetsCollection.applyLineToolUpdateNotification(i,t,s)}))}_onChangeVisibility(){const e=this._layoutVisibility.value();e&&this.connectionStatus().value()===ne.ConnectionStatus.Closed?(this.connect(),this._beforeUnhibernating.fire(),this._haveEverBeenHibernated&&(ve.logNormal("Connect due to becoming visible"),te.telemetry.sendLineToolsStorageReport("line_tools_unhibenate_subscription"))):e||this._scheduleHibernation(me.value())}_scheduleHibernation(e){null!==this._hibernateTimerId&&ce.clearTimeout(this._hibernateTimerId),this._hibernateTimerId=ce.setTimeout((()=>this._disconnectIfInvisible()),e)}_disconnectIfInvisible(){this._hibernateTimerId=null,this._layoutVisibility.value()||(ve.logNormal("Disconnect due to becoming invisible"),this.disconnect(),te.telemetry.sendLineToolsStorageReport("line_tools_hibenate_subscription"),this._haveEverBeenHibernated=!0)}}var be=i(850775),ye=i(743354),Ce=i(988124),we=i(444331),Pe=i(429874),Te=i(228018),Me=i(674981),xe=i(541558),Ie=i(533422),Ae=i(251954),Le=i(581996),ke=i(300426),Ee=i(208044),De=i(103221),Be=i(431912),Ne=i(237872);const Re=new c.TranslatedString("change chart layout to {title}",n.t(null,void 0,i(130501)));class Oe extends p.UndoCommand{constructor(e,t){super(Re.format({title:Ie.layouts[t].title})),this._chartWidgetCollection=e,this._newLayoutType=t,this._oldLayoutType=e.layout.value()}redo(){this._chartWidgetCollection.setLayout(this._newLayoutType)}undo(){this._chartWidgetCollection.setLayout(this._oldLayoutType)}}var Ve=i(389137),We=i(331633);const Fe=new c.TranslatedString("apply toolbars theme",n.t(null,void 0,i(558570)));class He extends p.UndoCommand{constructor(e,t,i=!0){super(Fe),this._prevThemeName=e,this._themeName=t,this._syncState=i}undo(){(0,Pe.isStdThemeName)(this._prevThemeName)&&((0,We.setTheme)(this._prevThemeName),this._syncState&&(0,Pe.syncTheme)())}redo(){(0,Pe.isStdThemeName)(this._themeName.toLowerCase())&&((0,We.setTheme)(this._themeName.toLowerCase()),this._syncState&&(0,Pe.syncTheme)())}} var ze=i(66732),Ue=i(784547),Ge=i(885482),qe=i(938550),je=i(223699),Ze=i(779923),Ke=i(276871),Ye=i(347710),$e=i(526075),Xe=i(92458);i(499650);const Je=!l.CheckMobile.any(),Qe=(0,r.getLogger)("ChartWidgetCollectionBase"),et=new c.TranslatedString("apply indicators to entire layout",n.t(null,void 0,i(744547))),tt=new c.TranslatedString("sync time",n.t(null,void 0,i(260635))),it=new c.TranslatedString("resize layout",n.t(null,void 0,i(113034))),st=new c.TranslatedString("reset layout sizes",n.t(null,void 0,i(830910))),ot=new c.TranslatedString("apply chart theme",n.t(null,void 0,i(766568))),rt=new c.TranslatedString("symbol lock",n.t(null,void 0,i(292831))),nt=new c.TranslatedString("interval lock",n.t(null,void 0,i(128916))),at=new c.TranslatedString("date range lock",n.t(null,void 0,i(390621))),lt=new c.TranslatedString("track time",n.t(null,void 0,i(247122))),ct=new c.TranslatedString("change series style",n.t(null,void 0,i(53438))),dt=n.t(null,void 0,i(46669)),ht=n.t(null,void 0,i(398478)),ut=n.t(null,void 0,i(834004)),_t=n.t(null,void 0,i(796260)),pt=n.t(null,void 0,i(838641)),mt=n.t(null,void 0,i(110160)),gt=n.t(null,void 0,i(219149)),St=n.t(null,void 0,i(838660)),vt=n.t(null,void 0,i(947228));function ft(e,t){const i=t.model().model().studyTemplate();e.undoHistory.beginUndoMacro(et);for(let s=0;se.id()===r)))}const l=await t.pasteSourceFromClip(n,i,!0);if(l&&1===l.length){const e=l[0];if(o.asCompare){const i=(0,s.ensureNotNull)(t.mainSeries().priceScale());t.moveToScale(e,(0,s.ensureDefined)(n),i,r),t.setPriceScaleMode({percentage:!0},i,null)}}t.model().lightUpdate()}}e.undoHistory.endUndoMacro()}function yt(e){let t=1;for(;e.has(""+t);)t++;return""+t}function Ct(e){const t=new Map,i=e.chartsCountToSave(),s=new Set;for(let o=0;o(0,s.ensureDefined)(e.content.chartId)))}function Mt(e,t,i){const s=e.chartsCountToSave();i.forEach((i=>{const s=(o=i.chartId,null!==(n=null===(r=e.chartWidgetsDefs.find((e=>e.chartWidget.id()===o)))||void 0===r?void 0:r.chartWidget)&&void 0!==n?n:null);var o,r,n;null==s||s.resetLineToolsInvalidated(t,i.savedDto,i.sharingMode)}));for(let t=e.chartWidgetsDefs.length;te.chartWidget)).filter((e=>e.hasModel())).filter((e=>e.id()===t||0!==s));try{o.forEach((e=>e.startApplyingLineToolUpdateNotification())),o.forEach((e=>e.applyLineToolUpdateNotification(i,s)))}finally{o.forEach((e=>e.endApplyingLineToolUpdateNotification()))}}function It(e){return e instanceof Error?e.message:null}function At(e){return new x({copyRequested:(t,i)=>{e.activeChartWidget.value().model().clipboardCopy(t,i).catch((t=>{var i;null===(i=e.toastsFactory)||void 0===i||i.getChartToasts().then((e=>{var i;(0,s.ensureNotNull)(e).showSimpleToast({title:ht,text:null!==(i=It(t))&&void 0!==i?i:dt.format({keystroke:(0,k.humanReadableHash)(k.Modifiers.Mod+67)}),role:"alert",intent:E.ToastIntent.Warning})}))}))},cutRequested:(t,i)=>{e.activeChartWidget.value().model().clipboardCut(t,i).catch((t=>{var i;null===(i=e.toastsFactory)||void 0===i||i.getChartToasts().then((e=>{var i;(0,s.ensureNotNull)(e).showSimpleToast({title:ut,text:null!==(i=It(t))&&void 0!==i?i:dt.format({keystroke:(0,k.humanReadableHash)(k.Modifiers.Mod+88)}),role:"alert",intent:E.ToastIntent.Warning})}))}))},pasteRequested:(t,i)=>{(i?i.model().undoModel():e.activeChartWidget.value().model()).clipboardPaste(t,i).catch((t=>{var i;null===(i=e.toastsFactory)||void 0===i||i.getChartToasts().then((e=>{var i;(0,s.ensureNotNull)(e).showSimpleToast({title:_t,text:null!==(i=It(t))&&void 0!==i?i:dt.format({keystroke:(0,k.humanReadableHash)(k.Modifiers.Mod+86)}),role:"alert",intent:E.ToastIntent.Warning})}))}))}})}function Lt(e,t){(0,Z.setBroker)(t)}function kt(e){const t={};return e.chartWidgetsDefs.map((e=>e.chartWidget)).forEach((e=>t[e.id()]=function(e){var t,i,o,r,n;const a={};if(!e.hasModel()){const r=e.options().content;if(!r)return a;const n=(0,s.ensureNotNull)(r.panes.reduce(((e,t)=>{var i;return null!==(i=null!=e?e:t.sources.find((e=>"MainSeries"===e.type)))&&void 0!==i?i:null}),null));return a.resolution=null===(t=n.state)||void 0===t?void 0:t.interval,a.symbol=null===(i=n.state)||void 0===i?void 0:i.symbol,a.short_name=null===(o=n.state)||void 0===o?void 0:o.shortName,a}const l=e.model().mainSeries(),c=l.properties().childs(),d=l.symbolInfo();a.resolution=c.interval.value(),a.symbol_type=null!==d&&d.type||"",a.exchange=null!==d&&d.exchange||"", a.listed_exchange=null!==d&&d.listed_exchange||"";const h=null!==(r=null==d?void 0:d.legs)&&void 0!==r?r:[];if(null!==d&&l.isSpread()){const e=h[0];let t=d.base_name[0];t=t.split(":")[1],a.symbol=e,a.short_name=t,a.expression=d.full_name}else a.symbol=null!==d&&d.ticker||c.symbol.value(),a.short_name=c.shortName.value();const u=null!==(n=null==d?void 0:d.base_name)&&void 0!==n?n:[];return a.legs=h.map(((e,t)=>({symbol:e,pro_symbol:u[t]}))),a}(e))),t}function Et(e,t){if(Se(e,t.widgetOptions)){const i=new fe(e,!e.readOnly());i.beforeUnhibernating().subscribe(e,(()=>{!function(e){e.chartWidgetsDefs.map((e=>e.chartWidget)).forEach((e=>e.reloadAllLineTools()))}(t)})),t.setChartStorageNotificationSubscription(i)}}async function Dt(e,t){if(t.widgetOptions.newsNotificationsEnabled){return new((await Promise.all([i.e(5761),i.e(4343),i.e(36827),i.e(69267),i.e(7818),i.e(90365),i.e(45469),i.e(50442),i.e(74978),i.e(64071),i.e(63841),i.e(11085),i.e(56370)]).then(i.bind(i,300777))).ChartWidgetCollectionNewsNotifier)(e)}return null}function Bt(e,t){const i={snapshotUrl:e};return i.asyncSave=!window.TVD,L(t,i).then((e=>((0,Ae.emit)("onScreenshotReady",e),e)))}function Nt(e,t){const i={snapshotUrl:e};i.asyncSave=!window.TVD;const s=(0,ie.isOnMobileAppPage)("any");return(s?L:A)(t,i).then((e=>((0,Ae.emit)("onScreenshotReady",e),s||(0,Ae.emit)("onServerScreenshotCopiedToClipboard"),e)))}function Rt(e){return function(e){return I().then((t=>t.downloadClientScreenshot(e)))}(e)}function Ot(e){return function(e){return I().then((t=>t.copyToClipboardClientScreenshot(e)))}(e).then((()=>{(0,Ae.emit)("onClientScreenshotCopiedToClipboard")}))}const Vt={s:0,"2h":0,"2v":1,"2-1":1,"3s":0,"3h":0,"3v":2,4:1,6:1,8:1,"1-2":1,"3r":1,"4h":0,"4v":3,"4s":0,"4s-l":0,"5h":0,"5v":0,"6h":0,"6v":0,"7h":0,"8h":0,"8v":0,"1-3":1,"2-2":3,"2-2-l":0,"2-3":2,"3-2":3,"1-4":1,"2-4":2,"5s":0,"6c":4,"8c":6,"9s":6,"9h":0,"9v":0,"10h":0,"10v":0,"10c5":1,"12c6":1,"12c4":3,"14c7":1,"16c8":1,"16c4":3};function Wt(e,t,i,s){let o=0;const r=(0,Ue.createWVFromGetterAndSubscriptions)((()=>++o),[i,s]);return(0,ze.combine)((t=>{var i;return null!==(i=e()[Vt[t]])&&void 0!==i?i:null}),t.weakReference(),r.ownership())}function Ft(e,t,i,s){var o;const r=Math.max(1,window.devicePixelRatio||1),n=e.getAll();let a;{const s=t||"TradingView.com",r={timezone:null!==(o=e.activeChartWidget.value().model().model().timezoneExceptExchange().value())&&void 0!==o?o:"exchange",dateFormat:"MMM dd, yyyy"},n=new ye.DateTimeWithTzFormatter(r).format(window.ChartApiInstance.serverTime()/1e3),l=e.metaInfo.username.value(),c=!l||e.readOnly()||i?mt:pt,d=[c.split(/{date}/)[0].format({userName:l,customer:s}).trim(),n],h=[c.format({userName:l,customer:s,date:n}).trim()];a="phone-vertical"===be.mediaState.device?d:h}const l=e.maximizedChartWidget().value();if(s&&s.onlyActiveChart||l)return{layout:"s",hidpiRatio:r,theme:(0,Pe.getCurrentTheme)().name,charts:[e.activeChartWidget.value().images(s)],publishedBy:a};const c=[],d=Ie.layouts[e.layout.value()].count,h={showCollapsedStudies:(s=s||{}).showCollapsedStudies, status:s.status};for(let e=0;et?e.allLayoutSizesState.set(s,t):e.allLayoutSizesState.delete(s);if(t)return e.sizingState.setValue(i),void o(i);e.undoHistory.beginUndoMacro(st),e.undoHistory.pushUndoCommand(new S(e.sizingState,e.sizingState.value(),i,st)),e.undoHistory.pushUndoCommand(new g(o,e.allLayoutSizesState.get(e.layoutTemplate.value().layoutType),i,st)),e.undoHistory.endUndoMacro()}function qt(e,t){Gt(e,t)}class jt{constructor(e,t,i){this._onShiftPressed=e=>{const t=this._state.currentLayoutResizeAction.value();t&&this._applyMouseMove(t.delta,e)},this._state=e,this._splitterElement=t,this._splitter=i,(0,Ne.shiftPressed)().subscribe(this._onShiftPressed)}destroy(){(0,Ne.shiftPressed)().unsubscribe(this._onShiftPressed)}mouseDownEvent(e){this._mouseDownOrTouchStartEvent(e)}touchStartEvent(e){this._mouseDownOrTouchStartEvent(e)}pressedMouseMoveEvent(e){this._pressedMouseOrTouchMoveEvent(e)}touchMoveEvent(e){this._pressedMouseOrTouchMoveEvent(e)}mouseUpEvent(e){this._mouseUpOrTouchEndEvent(e)}touchEndEvent(e){this._mouseUpOrTouchEndEvent(e)}mouseEnterEvent(e){this._highlightSplitters(e.shiftKey)}mouseLeaveEvent(e){const t=Ut(this._splitter.className);Array.from(this._state.parent.getElementsByClassName(t)).forEach((e=>e.classList.remove(Xe.hovered)))}mouseDoubleClickEvent(e){Gt(this._state)}_highlightSplitters(e){const t=Ut(this._splitter.className);Array.from(this._state.parent.getElementsByClassName(t)).forEach((e=>e.classList.remove(Xe.hovered)));(e?Array.from(this._state.parent.getElementsByClassName(t)):[this._splitterElement]).forEach((e=>e.classList.add(Xe.hovered)))}_mouseDownOrTouchStartEvent(e){const t=new o.Point(e.localX+this._splitterElement.offsetLeft,e.localY+this._splitterElement.offsetTop),i=(0,De.deepCopy)(this._state.sizingState.value());this._state.currentLayoutResizeAction.setValue({point:t,splitter:this._splitter,initialState:i,alignedState:this._state.layoutTemplate.value().syncSublayoutsBySplitter(this._splitter,(0,De.deepCopy)(i)),shiftState:e.shiftKey,delta:0}),this._splitterElement.classList.add(Xe["i-active"]),this._highlightSplitters(e.shiftKey)} _pressedMouseOrTouchMoveEvent(e){const t=this._state.currentLayoutResizeAction.value();if(!t)return;t.shiftState!==e.shiftKey&&(this._highlightSplitters(e.shiftKey),t.shiftState=e.shiftKey);const i=new o.Point(e.localX+this._splitterElement.offsetLeft,e.localY+this._splitterElement.offsetTop);t.delta="v"===t.splitter.orientation?i.y-t.point.y:i.x-t.point.x,this._applyMouseMove(t.delta,e.shiftKey)}_mouseUpOrTouchEndEvent(e){const t=this._state.currentLayoutResizeAction.value();if(t&&(this._splitterElement.classList.remove(Xe["i-active"]),this._state.currentLayoutResizeAction.setValue(null),t.currentState)){this._state.undoHistory.beginUndoMacro(it),this._state.undoHistory.pushUndoCommand(new S(this._state.sizingState,t.initialState,t.currentState,it));const e=this._state.layoutTemplate.value().layoutType;this._state.undoHistory.pushUndoCommand(new g((t=>t?this._state.allLayoutSizesState.set(e,t):this._state.allLayoutSizesState.delete(e)),this._state.allLayoutSizesState.get(this._state.layoutTemplate.value().layoutType),this._state.sizingState.value(),st)),this._state.undoHistory.endUndoMacro(),this._state.layoutSizesChanged.setValue(!0)}}_applyMouseMove(e,t){var i;const o=(0,s.ensureNotNull)(this._state.currentLayoutResizeAction.value()),r=t?o.alignedState:o.initialState,n=null!==(i=this._state.options.padding)&&void 0!==i?i:2,a=zt(this._state);o.currentState=this._state.layoutTemplate.value().resizeApplier(a,n,e,o.splitter,(0,De.deepCopy)(r),t),this._state.sizingState.setValue(o.currentState)}}function Zt(e,t,i,s,o){var r,n;const a=null!==(r=e.options.padding)&&void 0!==r?r:2,l=null!==(n=e.options.border)&&void 0!==n?n:0;o=null!=o?o:e.layoutTemplate.value();const c=zt(e),d=o.sizer(c,i,s,a+l,Je?e.sizingState.value():void 0);d.width=Math.max(Math.round(d.width),0),d.height=Math.max(Math.round(d.height),0),d.top=Math.round(d.top),d.left=Math.round(d.left),t.metrics=d;const h=t.container.value();if(h){h.style.width=d.width+"px",h.style.height=d.height+"px",h.style.top=d.top+"px",h.style.left=d.left+"px";const e=1===s;h.classList.toggle("single-visible",e);const t=Math.round(c.width),i=0===d.top&&0===d.left,o=0===d.top&&d.left+d.width===t,r=0===d.top&&d.width===t;h.classList.toggle("top-left-chart",!e&&!r&&i),h.classList.toggle("top-right-chart",!e&&!r&&o),h.classList.toggle("top-full-width-chart",e||r)}t.width.setValue(d.width),t.height.setValue(d.height)}function Kt(e){var t,i,s;let o;const r=e.layoutTemplate.value(),n=e.maximizedChartDef.value();if(o=n?[n]:e.chartWidgetsDefs.slice(0,r.count).filter((e=>!e.hiddenInLayout.value())),o.forEach(((t,i)=>Zt(e,t,i,o.length))),Je&&!e.maximizedChartDef.value()){const o=zt(e),n=null!==(t=e.options.padding)&&void 0!==t?t:2,a=null!==(i=e.options.border)&&void 0!==i?i:0,l=r.splitters(o,n+a,e.sizingState.value()),c=null!==(s=e.splitters.value())&&void 0!==s?s:[];c.forEach(((e,t)=>{t>=l.length&&(e.splitterElement.remove(),e.mouseHandler.destroy(),e.mouseListener.destroy())}));const d=l.map(((t,i)=>{const s=i({def:t,metrics:e.layoutTemplate.value().sizer({top:0,left:0,width:256,height:256},i,s.length,0)}))).sort(((e,t)=>e.metrics.top-t.metrics.top||e.metrics.left-t.metrics.left)).map((e=>e.def));if(s.length<2)return null;let o=s.indexOf(t);return-1===o?null:(o=(o+(i?s.length-1:1))%s.length,s[o])}function $t(e,t){return e.chartWidgetsDefs.some((e=>{var i;return(null===(i=e.chartWidget)||void 0===i?void 0:i.id())===t}))}function Xt(e){let t=1;for(;e(""+t);)t++;return""+t}function Jt(e,t,i){const s=[];if(null==i?void 0:i.publishedChartsEnabled){const i=new z.PublishedChartsTimeline(e,(e=>function(e,t){e={...e,chartWidgetCollection:t},(0,ee.pushChartPage)(e)}(e,t)));s.push(i)}return s}function Qt(e,t,i){var o,r;const{toastsFactory:n,chartWidgetsDefs:a,customLegendWidgetsFactoriesMap:c}=e;let d={chartWidgetCollection:t,isActive:0===a.length,barsMarksContainersFactory:i=>Jt(i,t,e.options),undoHistory:e.undoHistory,readOnly:e.readOnly,initialLoading:e.initialLoading,getToasts:n?()=>n.getChartToasts():void 0,...null!=i?i:{}};void 0!==c&&(d.customLegendWidgetFactories=new Map(c));const h=document.createElement("div");h.classList.add("chart-container"),h.style.position="absolute",h.style.overflow="hidden",e.parent.insertBefore(h,e.bottomToolbar.value()),l.isEdge&&(h.style.touchAction="none",h.style.msTouchAction="none"),d.className&&h.classList.add(d.className);const _={alive:new u.WatchedValue(!0),container:new u.WatchedValue(h),width:new u.WatchedValue,height:new u.WatchedValue,collapsed:new u.WatchedValue(!1),hiddenInLayout:new u.WatchedValue(!1),visible:new u.WatchedValue,rdState:new Le.ResizerDetacherState,requestFullscreen:()=>{e.globalDetachable.value()&&(e.setMaximized(_),e.activeChartWidget.setValue((0,s.ensureNotNull)(_.chartWidget)))},exitFullscreen:()=>{e.activeChartWidget.value()===_.chartWidget&&e.setMaximized(null)},detachable:e.globalDetachable,fullscreenable:e.globalDetachable,fullscreen:new u.WatchedValue,chartWidget:null};_.rdState.pushOwner(_),a.push(_);const p=()=>{_.visible.setValue(!_.hiddenInLayout.value()&&e.options.resizerBridge.visible.value())};_.hiddenInLayout.subscribe((()=>{(0,s.ensureNotNull)(_.chartWidget).setVisible(!_.hiddenInLayout.value()),p()})),_.collapsed.subscribe((()=>(0, s.ensureNotNull)(_.chartWidget).setCollapsed(_.collapsed.value()))),e.options.resizerBridge.visible.subscribe(p),p(),function(e,t){let i=0,s=0;const o=t.layoutTemplate.value();for(let r=0;r$t(e,t))),g=_.chartWidget=new ke.ChartWidget(d,m,t.metaInfo.uid.value());e.saveChartService&&g.setSaveChartService(e.saveChartService),e.readOnly||(_.timingsMeter=new H(String(a.length-1)),g.setTimingsMeter(_.timingsMeter)),d.containsData?g.finishInitWithoutConnect():g.connect(),g.withModel(null,(()=>{const t=g.model().model();e.customSources.forEach(((e,i)=>{t.addCustomSource(i,e.factory,e.layer)}))})),e.updateWatchedValue(),e.updateActivityView();const S=null!==(r=null===(o=null==d?void 0:d.content)||void 0===o?void 0:o.linkingGroup)&&void 0!==r?r:null;g.linkingGroupIndex().setValue(S),g.linkingGroupIndex().subscribe(e.updateLinkingGroupCharts);const v=Oi(e,S).value();return v.length>0&&(e.symbolLock.value()&&g.setSymbol(v[0].symbolWV().value()),e.intervalLock.value()&&g.setResolution(v[0].resolutionWV().value())),e.updateLinkingGroupCharts(),e.chartWidgetCreatedDelegate.fire(g),_}function ei(e,t,i,s){let o,r=e.savedChartWidgetOptions.shift();if(void 0!==r){const t=e.activeChartWidget.value();t&&t.lineToolsSynchronizer()&&(o=t.lineToolsAndGroupsDTO())}else r=function(e){const t=e.activeChartWidget.value();if(t){const i=t.state();return i.chartId=Xt((t=>$t(e,t))),i.shouldBeSavedEvenIfHidden=!1,i.panes.forEach((e=>{e.sources.forEach((e=>{"alertId"in e&&(e.alertId=void 0)}))})),{content:i}}}(e);const n={...e.widgetOptions,...r,...0===i||e.symbolLock.value()?void 0:{defSymbol:null}},a=Qt(e,t,n),{chartWidget:l}=a;return l.modelCreated().subscribe(null,(()=>{s?s():e.checkAllPendingModelsAlreadyCreated(),e.dateRangeLock.value()&&l===e.activeChartWidget.value()&&e.subscribeToCompletedEventForDateRangeSync(l,!0);const t=l.lineToolsSynchronizer();void 0!==o&&t&&[...o.entries()].map((([e,i])=>{0!==e&&t.applyDTO(i,e).then((()=>{t.invalidateAll()}))}));const i=e.chartWidgetsDefs.filter((e=>e.chartWidget.hasModel())).map((e=>e.chartWidget.model()));e.chartModels.setValue(i)}),!0),a}function ti(e){e.hiddenInLayout.setValue(!0);const t=e.container.value();t.parentNode&&t.parentNode.removeChild(t),e.fullscreen.setValue(!1)}function ii(e,t,i){const o=(0,s.ensureNotNull)(e.chartWidget);o.onZoom().unsubscribeAll(i),o.onScroll().unsubscribeAll(i),o.withModel(null,(()=>{const e=o.lineToolsSynchronizer();null!==e&&(e.hasChanges().unsubscribe(t.recalcHasChanges),t.recalcHasChanges())}))}function si(e,t){e.chartWidgetsDefs.forEach((i=>{ii(i,e,t)}))}function oi(e,t){const i=e.actualLayoutCount();for(let s=i;s{const o=(0,s.ensureNotNull)(i.chartWidget);o.onZoom().subscribe(t,(t=>e.onZoom.fire(t))), o.onScroll().subscribe(t,(()=>e.onScroll.fire())),o.withModel(null,(()=>{const t=o.lineToolsSynchronizer();null!==t&&(t.hasChanges().subscribe(e.recalcHasChanges),e.recalcHasChanges())}))}))}const ni=["2-3","5h","6h","7h","8h"],ai=["10c5","12c6","12c4","14c7","16c8","16c4"];async function li(e){var t,i;const o=this.innerState();(0,D.getInitData)().is_mobile_new&&(ni.includes(e)&&!(0,d.enabled)("mobile_app_supports_new_layout_types")||ai.includes(e)&&!(0,d.enabled)("mobile_app_supports_new_layout_types_2"))&&(e="s");{let e=!1;if(o.saveChartService&&(e=Boolean(o.saveChartService.autoSaveEnabled().value())),e)try{const e=o.chartWidgetsDefs.map((e=>{var t,i,s;return null!==(s=null===(i=null===(t=e.chartWidget)||void 0===t?void 0:t.lineToolsSynchronizer())||void 0===i?void 0:i.flushPendingSavings())&&void 0!==s?s:null})).filter(Ve.notNull);e.length&&await Promise.all(e)}catch(e){Qe.logError(`Error flushing line tools: ${e}`)}}(e=o.checkProFeature(e))in Ie.layouts||(e="s"),si(o,this);const r=o.layoutType,n=Ie.layouts[e].count;(0,Ae.emit)("layout_about_to_be_changed",e),(null!==(t=o.splitters.value())&&void 0!==t?t:[]).forEach(((e,t)=>{e.splitterElement.remove(),e.mouseHandler.destroy()})),o.splitters.setValue([]);const a=Ie.layouts[e];o.layoutTemplate.setValue(a);const l=null!==(i=o.allLayoutSizesState.get(a.layoutType))&&void 0!==i?i:(0,Ee.layoutInitialSizingState)(a.expression);o.allLayoutSizesState.set(a.layoutType,l),o.sizingState.setValue(l);const c=o.maximizedChartDef.value();if(o.isPhoneSize.value()&&o.viewMode.value()===_.CollectionViewMode.ForceFullscreen)if(c){const e=o.chartWidgetsDefs.indexOf(c);(e<0||e>=n)&&o.maximizedChartDef.setValue(o.chartWidgetsDefs[0])}else o.maximizedChartDef.setValue(o.chartWidgetsDefs[0]);else r!==e&&o.maximizedChartDef.value()&&o.maximizedChartDef.setValue(null);c&&o.activeChartWidget.setValue((0,s.ensureNotNull)(c.chartWidget));for(let e=0;e=n;if(t=o.maximizedChartDef.value()?o.maximizedChartDef.value()===i:e1),i.fullscreen.setValue(o.maximizedChartDef.value()===i),i.collapsed.setValue(r)}else i?(ti(i),i.collapsed.setValue(r)):o.isPhoneSize.value()&&o.viewMode.value()===_.CollectionViewMode.ForceFullscreen&&(ei(o,this,e,void 0),ti(o.chartWidgetsDefs[e]),o.chartWidgetsDefs[e].collapsed.setValue(r))}o.sizingState.setValue(l),Kt(o),o.layoutWV.setValue(e),o.setLayoutType(e),o.updateWatchedValue(),function(e){const t=e.layoutTemplate.value().count;e.inlineChartsCount.setValue(t),e.globalDetachable.setValue(t>1)}(o),o.checkAllPendingModelsAlreadyCreated(),ri(o,this),o.initialLoading||o.updateViewMode(), o.inlineChartsCount.value()<1&&n>0&&o.chartWidgetsDefs[n-1].rdState.bridge().attach()}function ci(e,t,i,s,o){const r=e.actualLayoutCount();return e.chartWidgetsDefs.slice(0,r).filter((e=>e.rdState.bridge().visible.value())).map((e=>e.chartWidget)).filter((t=>t.id()!==i&&(!!t.hasModel()&&(t.selectPointMode().value()===Ge.SelectPointMode.Replay&&"AllCharts"===J.replayModeProperty.value()||(s||e.crosshairLockRaw))))).forEach((e=>e.model().model().setExternalPosition(t,o))),!0}function di(e,t,i,s,o){if(ci(e,t,i,s,o)){const i=e.crossHairSyncBroadcast;if(i){const e={type:"crosshair",payload:{point:t,envState:o,sourceUniqueId:i.uniqueId}};i.channel.postMessage(e)}}}function hi(e){const t=new BroadcastChannel("ChartWidgetsCollection");return t.onmessage=t=>{const i=t.data,s=e();if(s.crossHairSyncBroadcast&&"crosshair"===i.type)s.crossHairSyncBroadcast.uniqueId!==i.payload.sourceUniqueId&&ci(s,i.payload.point,null,!1,i.payload.envState)},{channel:t,uniqueId:(0,xe.randomHashN)(6)}}function ui(e){var t;null===(t=e.crossHairSyncBroadcast)||void 0===t||t.channel.close()}function _i(e,t,i){if(!e.combinedTrackTimeLock.value()||e.dateRangeLock.value())return;const s=e.layoutTemplate.value().count;e.undoHistory.beginUndoMacro(tt),e.chartWidgetsDefs.slice(0,s).filter((e=>e.chartWidget.hasModel()&&e.chartWidget.model().model()!==i)).forEach((e=>{const i=e.chartWidget.model().model(),s=i.mainSeries().syncModel();s&&i.syncTimeWithModel(s.syncSourceTarget(),t)})),e.undoHistory.endUndoMacro(),(0,Ae.emit)("sync_time",t)}function pi(e){return Promise.all(e.map((e=>{const t=e.model().mainSeries();return t.symbolResolvingActive().value()?h(t.dataEvents().symbolResolved()).promise:t.symbolInfo()})))}function mi(e){return e.chartWidgetsDefs.every((e=>e.chartWidget.hasModel()))?Promise.resolve(e.chartWidgetsDefs.map((e=>e.chartWidget))):Promise.all(e.chartWidgetsDefs.map((e=>e.chartWidget.hasModel()||h(e.chartWidget.modelCreated()).promise))).then((()=>mi(e)))}function gi(e,t){var i,o,r;if((0,d.enabled)("charting_library_base"))return t;if("s"===t||e.widgetOptions.containsData||e.readOnly||(0,Y.enabled)("MULTIPLE_CHARTS")&&(0,s.ensure)(null===(i=(0,Y.getConfig)("MULTIPLE_CHARTS"))||void 0===i?void 0:i.limit)>=Ie.layouts[t].count)return t;let n="s";{let t=1;const i=null!==(r=null===(o=(0,Y.getConfig)("MULTIPLE_CHARTS"))||void 0===o?void 0:o.limit)&&void 0!==r?r:0;for(const e of Object.keys(Ie.layouts)){const s=Ie.layouts[e].count;s<=i&&s>t&&(n=e,t=s)}mi(e).then(pi).then((()=>{(0,K.trackGoProFeature)("multipleCharts"),(0,$.createGoProDialog)({feature:"multipleCharts"})}))}return n}async function Si(e,t,i){if(i=gi(e,i),e.layoutWV.value()===i)return!1;{let t=!1;if(e.saveChartService&&(t=Boolean(e.saveChartService.autoSaveEnabled().value())),t){const t=e.chartWidgetsDefs.map((e=>{var t,i,s;return null!==(s=null===(i=null===(t=e.chartWidget)||void 0===t?void 0:t.lineToolsSynchronizer())||void 0===i?void 0:i.flushPendingSavings())&&void 0!==s?s:null})).filter(Ve.notNull);if(t.length)try{await Promise.all(t)}catch(e){ Qe.logError(`Error flushing line tools: ${e}`)}}}return e.undoHistory.pushUndoCommand(new Oe(t,i)),!0}async function vi(e,t,i){const{theme:s,onlyActiveChart:o,restoreNonThemeDefaults:r,themeName:n,standardTheme:a,syncState:l=!0,noUndo:c}=i,d=(0,Pe.getCurrentTheme)().name;let h;o?h=[e.activeChartWidget.value()]:(si(e,t),await Promise.all(e.savedChartWidgetOptions.map(((i,s)=>new Promise((i=>{ti(ei(e,t,s,i))}))))),h=e.chartWidgetsDefs.map((e=>e.chartWidget)),ri(e,t)),c?(a&&new He(d,n,l).redo(),h.forEach((e=>{e.model().model().restoreTheme(s,r,c)}))):(e.undoHistory.beginUndoMacro(ot),a&&e.undoHistory.pushUndoCommand(new He(d,n,l)),h.forEach((e=>{e.model().model().restoreTheme(s,r)})),e.undoHistory.endUndoMacro()),await Promise.all(h.map((e=>e.model().model().colorStudiesPropertiesReady())))}function fi(e,t){e.symbolLock.setValue(t)}function bi(e,t){const{internalSymbolLock:i,activeChartWidget:s,undoHistory:o,dateRangeLock:r,loadingContent:n,linkingGroupsCharts:l,chartWidgetsDefs:c}=e;if(t!==i.value())if(n)i.setValue(t);else{if(e.undoHistory.beginUndoMacro(rt),t){const t=s.value(),i=c.map((e=>e.chartWidget));l.forEach(((s,o)=>{const n=t.linkingGroupIndex().value()===o?t:i.find((e=>e.linkingGroupIndex().value()===o));if(void 0!==n){(0,a.muteLinkingGroup)(o,!0);for(const t of s.value())t!==n&&t.symbolWV().value()!==n.symbolWV().value()&&(t.setSymbol(n.symbolWV().value()),r.value()&&e.subscribeToCompletedEventForDateRangeSync(t,!0));(0,a.muteLinkingGroup)(o,!1)}}))}o.setWatchedValue(i,t,rt),o.endUndoMacro()}}function yi(e,t){e.intervalLock.setValue(t)}function Ci(e,t){const{internalIntervalLock:i,activeChartWidget:s,undoHistory:o,dateRangeLock:r,loadingContent:n,chartWidgetsDefs:l,linkingGroupsCharts:c}=e;if(t!==i.value())if(n)i.setValue(t);else{if(o.beginUndoMacro(nt),t&&t){const t=s.value(),i=l.map((e=>e.chartWidget));c.forEach(((s,o)=>{const n=t.linkingGroupIndex().value()===o?t:i.find((e=>e.linkingGroupIndex().value()===o));if(void 0!==n){(0,a.muteLinkingGroup)(o,!0);for(const t of s.value())t!==n&&t.resolutionWV().value()!==n.resolutionWV().value()&&(t.setResolution(n.resolutionWV().value()),r.value()&&e.subscribeToCompletedEventForDateRangeSync(t,!0));(0,a.muteLinkingGroup)(o,!1)}}))}o.setWatchedValue(i,t,nt),o.endUndoMacro()}}function wi(e,t){const i=e.activeChartWidget.value();if(i&&i.hasModel()){const s=i.model();t?(e.subscribeToEventsForDateRangeSync(s),e.syncChartsDateRangesWithActiveChartRange()):e.unsubscribeFromEventsForDateRangeSync(s)}e.dateRangeLock.setValue(t)}function Pi(e,t){const{internalDateRangeLock:i,undoHistory:s,loadingContent:o}=e;o?i.setValue(t):s.setWatchedValue(i,t,at)}function Ti(e,t){e.trackTimeLock.setValue(t)}function Mi(e,t){const{internalTrackTimeLock:i,undoHistory:s,loadingContent:o}=e;o?i.setValue(t):s.setWatchedValue(i,t,lt)}function xi(e,t,i){e.symbolLock.value()?Ii(e,t,i):e.activeChartWidget.value().setSymbol(t)}function Ii(e,t,i){const s=e.activeChartWidget.value();void 0===i&&(i=s.linkingGroupIndex().value());for(const s of e.chartWidgetsDefs){const e=s.chartWidget ;(e.hasModel()?e.model().mainSeries().symbolSameAsResolved(t):e.symbolWV().value()===t)||void 0!==i&&e.linkingGroupIndex().value()!==i||e.setSymbol(t)}}async function Ai(e,t=this.activeChartWidget.value()){if(!t)return!1;{if(je.Interval.isTicks(t.resolutionWV().value())&&(4===e||7===e||5===e||6===e))return t.showHint(1,{text:vt.format({chartStyle:(0,we.getTranslatedChartStyleName)(e)}),solutionId:Q.solutionIds.WHY_RENKO_NOT_WORK,solutionText:n.t(null,void 0,i(639571))}),!1;let s=!1;const o=ki(this.innerState());for(const t of o){const i=t.model().model();if(i.isInReplay().value()&&!i.mainSeries().isStyleSupported(e)){s=!0;break}}const r=this.innerState().flags;return!s||r.isConfirmationAboutReplayLocked?(Li(t,e),!0):new Promise((i=>{(0,Ze.showConfirm)({text:gt,onConfirm:s=>{r.isConfirmationAboutReplayLocked=!0,Li(t,e),r.isConfirmationAboutReplayLocked=!1,s.dialogClose(),i(!0)},onClose:()=>i(!1),onCancel:e=>{e.dialogClose(),i(!1)}})}))}}function Li(e,t){const i=e.model(),s=i.mainSeries().properties().childs().style;i.setChartStyleProperty(s,t,ct)}function ki(e){return(e.intervalLock.value()?e.chartWidgetsDefs.map((e=>e.chartWidget)):[e.activeChartWidget.value()]).filter((e=>e.hasModel()))}async function Ei(e,t,s,o){if(e.flags.loadingChart||e.flags.setTimeFrameActive||e.flags.setNewResolution)return!1;{const o=je.Interval.isTicks(t),r=ki(e);if(o)for(const e of r){const t=e.model().model().mainSeries().style();if(4===t||7===t||5===t||6===t)return e.showHint(1,{text:vt.format({chartStyle:(0,we.getTranslatedChartStyleName)(t)}),solutionId:Q.solutionIds.WHY_RENKO_NOT_WORK,solutionText:n.t(null,void 0,i(639571))}),!1}let a="",l=!1;const c=je.Interval.isRange(t);if(c||o)for(const e of r){const t=e.model().model();if(t.isInReplay().value()){if(c&&11!==t.mainSeries().style()){l=!0,a=gt;break}o&&(l=!0,a=St)}}const d=r.filter((e=>e.model().isInReplay().value()));if(d.length){if(!(await Promise.all(d.map((e=>e.model().canChangeResolution(t))))).every(Boolean))return!1}return!l||e.flags.isConfirmationAboutReplayLocked?(Di(e,t,s),!0):new Promise((i=>{(0,Ze.showConfirm)({text:a,onConfirm:o=>{e.flags.isConfirmationAboutReplayLocked=!0,Di(e,t,s),e.flags.isConfirmationAboutReplayLocked=!1,o.dialogClose(),i(!0)},onClose:()=>i(!1),onCancel:e=>{e.dialogClose(),i(!1)}})}))}}function Di(e,t,i,s){if((0,Ke.setLastUsedResolution)(t),e.flags.setNewResolution=!0,s=null!=s?s:e.activeChartWidget.value(),void 0===i&&(i=s.linkingGroupIndex().value()),e.intervalLock.value())for(const s of e.chartWidgetsDefs){const e=s.chartWidget;e.resolutionWV().value()===t||void 0!==i&&e.linkingGroupIndex().value()!==i||e.setResolution(t)}else s.setResolution(t);e.flags.setNewResolution=!1}function Bi(e){const t=new u.WatchedValue(null),i=()=>{t.setValue(e.value().linkingGroupIndex().value())};e.value()&&i();const s=e.spawn();let o;return s.subscribe((e=>{null==o||o.destroy(),o=e.linkingGroupIndex().spawn(),o.subscribe(i),i()})),t.spawn((()=>{s.destroy(),null==o||o.destroy()}))}function Ni(e){const t=new Set(e.map((e=>e.chartWidget.linkingGroupIndex().value()))) ;return Array.from(t).sort(((e,t)=>(null!=e?e:-1)-(null!=t?t:-1)))}function Ri(e){const t=new qe.WatchedObject(Ni(e.chartWidgetsDefs)),i=()=>{t.setValue(Ni(e.chartWidgetsDefs))};e.chartWidgetsDefs.forEach((e=>e.chartWidget.linkingGroupIndex().subscribe(i)));const s=e=>{e.linkingGroupIndex().subscribe(i),i()};return e.chartWidgetCreatedDelegate.subscribe(null,s),t.spawn((()=>{e.chartWidgetsDefs.forEach((e=>e.chartWidget.linkingGroupIndex().unsubscribe(i))),e.chartWidgetCreatedDelegate.unsubscribe(null,s)}))}function Oi(e,t){let i=e.linkingGroupsCharts.get(t);return void 0===i&&(i=new qe.WatchedObject([],Me.compareTwoCollectionsByIds),e.linkingGroupsCharts.set(t,i)),i}function Vi(e){var t;const i=new Map;for(const t of e.chartWidgetsDefs){const e=t.chartWidget.linkingGroupIndex().value();let s=i.get(e);void 0===s&&(s=[],i.set(e,s)),s.push(t.chartWidget)}for(const s of(0,Me.join)(new Set(e.linkingGroupsCharts.keys()),new Set(i.keys())))Oi(e,s).setValue(null!==(t=i.get(s))&&void 0!==t?t:[])}function Wi(e){if(e){const e=function(){var e,t,i,o;const r=null!==(t=null===(e=(0,Y.getConfig)("BACKEND_CONNECTIONS"))||void 0===e?void 0:e.limit)&&void 0!==t?t:0,n=(0,s.ensureDefined)(window.pro),a=n.getProductsByType(n.PRODUCT_TYPES.pro_plan);for(const e of a)if((null!==(o=null===(i=(0,Y.getConfig)("BACKEND_CONNECTIONS",(0,s.ensureDefined)(e.id)))||void 0===i?void 0:i.limit)&&void 0!==o?o:0)>r)return{connectionCount:r,moreConnectionsPlanAvailable:!0};return{connectionCount:r,moreConnectionsPlanAvailable:!1}}(),t=[{text:n.t(null,void 0,i(881492)),action:X.PredefinedAction.Close,variant:"secondary",color:"gray",compactMode:!0,onClick:()=>window.ChartApiInstance.connect()}];e.moreConnectionsPlanAvailable&&t.push({action:X.PredefinedAction.OpenGopro,text:n.t(null,void 0,i(834805)),compactMode:!0}),(0,$.createGoProDialog)({feature:"connectionsLimit",actionButtonsLayout:X.ActionButtonsLayout.Row,actions:t,customParams:e})}}function Fi(e,t){let i=[];const s={},o=()=>{i.forEach((e=>e.unsubscribe(a))),i=t.filter((e=>e.chartWidget.hasModel())).map((e=>e.chartWidget.selectPointMode())),i.forEach((e=>e.subscribe(a))),t.forEach((e=>{e.chartWidget.hasModel()||e.chartWidget.withModel(s,(()=>{o(),a()}))}))};o();const r=()=>i.some((e=>e.value()===Ge.SelectPointMode.Replay))&&"AllCharts"===J.replayModeProperty.value(),n=new u.WatchedValue(r()),a=()=>n.setValue(r()),l=()=>{o(),a()};e.subscribe(l),J.replayModeProperty.subscribe(n,a);return n.spawn((()=>{J.replayModeProperty.unsubscribe(n,a),e.unsubscribe(l),i.forEach((e=>e.subscribe(a)))}))}function Hi(e,t,i){return(0,ze.combine)(((e,t)=>e||t),t.weakReference(),Fi(e,i).ownership())}function zi(e,t,i){const s=t.id();if(e.chartWidgetIdToCompletedCallbackMap.has(s))return;const o=()=>{e.chartWidgetIdToCompletedCallbackMap.has(s)&&(e.chartWidgetIdToCompletedCallbackMap.delete(s),Yi(e,i?t:void 0))};t.model().mainSeries().dataEvents().completed().subscribe(null,o,!0),e.chartWidgetIdToCompletedCallbackMap.set(s,{cw:t,callback:o})}function Ui(e){Yi(e)}const Gi=new Map;function qi(e){var t ;const i=null!==(t=Gi.get(e.id()))&&void 0!==t?t:{};return Gi.set(e.id(),i),i}function ji(e,t){t.timeScale().visibleBarsStrictRangeChanged().subscribe(qi(t),Ui.bind(null,e))}function Zi(e,t){t.timeScale().visibleBarsStrictRangeChanged().unsubscribeAll(qi(t)),e.chartWidgetIdToCompletedCallbackMap.forEach((e=>{const t=e.cw,i=e.callback;t.model().mainSeries().dataEvents().completed().unsubscribe(null,i)})),e.chartWidgetIdToCompletedCallbackMap.clear()}function Ki(e,t,i){e.model().model().gotoTimeRange(t,i),(0,Ae.emit)("sync_date_range",t,i)}function Yi(e,t){if(!e.dateRangeLock.value()||null!==e.currentLayoutResizeAction.value())return;const i=e.activeChartWidget.value(),o=i.model().mainSeries();if(!(0,we.isTimeBasedStyle)(o.style()))return;const r=i.model().timeScale(),n=r.visibleBarsStrictRange();if(null===n)return;const a=(0,s.ensureNotNull)(r.points().range().value());let l=r.indexToTimePoint(n.firstBar());null===l&&o.endOfData()&&(l=r.indexToTimePoint(a.firstIndex));let c=r.indexToTimePoint(n.lastBar());if(null===c&&(c=r.indexToTimePoint(a.lastIndex)),null===l||null===c)return void zi(e,i,!1);e.chartWidgetIdToCompletedCallbackMap.delete(i.id());let d=1e3*l,h=1e3*c;if(o.isDWM()){const e=new Date(d),t=new Date(h);(0,Ce.set_hms)(e,0,0,0,0),(0,Ce.set_hms)(t,0,0,0,0),d=e.getTime(),h=t.getTime()}for(let s=0;s/^study_?.*$/gim.test(e.type);t={...t,panes:t.panes.map((t=>({...t,sources:t.sources.map((t=>{if(e(t)){const{metaInfo:e,metaInfo:{fullId:i,pine:s},...o}=t;a||(a={});const r=`${i}${s?`[v.${s.version}]`:""}`;return a[r]||(a[r]=e),{...o,metaInfo:r}}return t}))})))}}n.push(t)}}const l=t?void 0:Array.from(s.allLayoutSizesState.entries()).reduce(((e,[t,i])=>(e[t]=i,e)),{});return{name:this.metaInfo.name.value(),layout:t?"s":s.layoutType,charts:n,symbolLock:Xi(s.symbolLock),intervalLock:Xi(s.intervalLock),trackTimeLock:Xi(s.trackTimeLock),dateRangeLock:Xi(s.dateRangeLock),crosshairLock:Xi(s.crosshairLock),layoutsSizes:l,studyMetaInfoMap:a}}function Xi(e){return e.value()?1:0}function Ji(e){$e.StudyMetaInfo.mergeDefaultsOverrides(e),(0,Ye.studyMetaInfoRepository)().isReady()&&$e.StudyMetaInfo.overrideDefaults((0,Ye.studyMetaInfoRepository)().getInternalMetaInfoArray())}},300426:(e,t,i)=>{"use strict" ;var s=i(230285).splitSymbolName,o=i(809796).TranslatedString,r=i(650151).assert,n=i(244842),a=i(794349).TabNames,l=i(470316),c=i(663554).showDeleteStudyTreeConfirm,d=i(779923).showConfirm,h=i(992393).confirmDatasourceRemoving,u=i(67302).showThemeSwitcher,_=i(67302).showThemeAction,p=i(514315).updateThemeActions,m=i(470452).Study,g=i(306682).StudyStub,S=i(238433).isStudy,v=i(821979).LineDataSource,f=i(713473),b=f.isLineTool,y=f.isStudyLineTool,C=i(368135).STUDYPLOTDISPLAYTARGET,w=i(347710).studyMetaInfoRepository,P=i(373571).Action,T=i(607509).ACTION_ID,M=i(223699).Interval,x=i(444331),I=x.getDefaultStyle,A=x.hasVolume,L=i(15458),k=L.availableTimezones,E=L.timezoneIsAvailable,D=i(440941).lineToolsDoNotAffectChartInvalidation,B=i(345848).trackEvent,N=i(42292),R=i(707957).Delegate,O=i(201089).getLogger("ChartWidget",{color:"#606"}),V=i(895370).addPerfMark,W=i(148010).ChartWidgetBase,F=i(638456).CheckMobile.any(),H=i(315347).TIMEFRAMETYPE,z=new o("change timezone",i.tf(null,void 0,i(820505))),U=new o("unlock {title}",i.tf(null,void 0,i(192421))),G=new o("lock {title}",i.tf(null,void 0,i(850193)));e.exports.ChartWidget=class extends W{constructor(e,t,i){super(e,t,i),this._options.timeScaleWidget&&(this._options.timeScaleWidget.pressedMouseMoveScale=this._options.handleScale.axisPressedMouseMove.time);var s=this,o=this._options.content,r=this._options.readOnly;this._removeMaximizeHotkey=null;var n=this._options.containsData,a=this._options.onWidget,l=this._options.onCmeWidget;l&&O.logWarn("[ChartWidget] 'onCmeWidget' option is depricated");var c=this._options.widgetCustomer,d=this._options.timezone,h=this._options.hideSymbolSearch,u=this._options.defSymbol,_=M.isValid(this._options.defInterval)?this._options.defInterval:void 0,p=parseInt(this._options.defStyle),m=x.isValidStyle(p)?p:void 0,g=this._options.defSessionId,S=void 0!==this._options.defTimeframe?"string"==typeof this._options.defTimeframe?{value:this._options.defTimeframe.toUpperCase(),type:H.PeriodBack}:{...this._options.defTimeframe,type:H.TimeRange}:void 0;this._content=o,this._initialLoading=this._options.initialLoading,this._readOnly=r,this._containsData=n,this._defSymbol=u,this._defInterval=_,this._defTimeframe=S,this._defStyle=m,this._onWidget=!!a,this._compareSymbols=this._options.compareSymbols,this._onWidget&&(l?this._widgetCustomer="cme":c&&(this._widgetCustomer=c)),this._hideSymbolSearch=h,this._frameTime=30,this._model=null,this._metaInfo={},this._drawRafId=0,this._compareDialog=this._chartWidgetCollection.getCompareDialogRenderer();var v=this._contentSeriesProperties();v&&(u=v.symbol,_=v.interval),void 0===this._options.useUserChartPreferences&&(this._options.useUserChartPreferences=!0);var f="chartproperties.mainSeriesProperties",b=this._options.useUserChartPreferences?N.defaults(f):N.factoryDefaults(f);this._properties.mainSeriesProperties.merge(b),this._properties.mainSeriesProperties.hasChild("esdBreaksStyle")&&this._properties.mainSeriesProperties.removeProperty("esdBreaksStyle"),_=_||b.interval||"D", x.isValidStyle(m)||(m=x.isValidStyle(b.style)?b.style:I(M.isRange(_))),this._properties.mainSeriesProperties.merge({visible:!0,symbol:u||DEFAULT_SYMBOL,shortName:"",timeframe:"",onWidget:this._onWidget,interval:_,currencyId:null,unitId:null,style:m,sessionId:g}),this._symbolWV.setValue(this.getSymbol()),this._resolutionWV.setValue(this.getResolution()),this._containsData&&this._properties.mainSeriesProperties.merge({showCountdown:!1}),d&&E(d)&&this._properties.timezone.setValue(d),this._tagsChanged=new R,this._timingsMeter=null,this._options.container.subscribe((function(e){s._setElement(e)}),{callWithLast:!0});var y=function(){s.resize()};this._options.width.subscribe(y),this._options.height.subscribe(y),this._options.visible.subscribe(this._updateTimingsMeterState.bind(this)),this._aboutToBeDestroyed=new R,this._definitionsViewModel=null,this._backgroundTopColorSpawn=null,this._backgroundBottomColorSpawn=null}isInitialized(){return Boolean(this._inited)}compareSymbols(){return this._compareSymbols}async _getChartPropertyDefinitionsViewModel(){if(null===this._definitionsViewModel){const{ChartPropertyDefinitionsViewModel:e}=await Promise.all([i.e(9408),i.e(15289),i.e(30154),i.e(47924),i.e(83596)]).then(i.bind(i,3775));if(this._isDestroyed)throw new Error("Chart widget already destroyed");await new Promise((e=>this.withModel(null,e))),null===this._definitionsViewModel&&(this._definitionsViewModel=new e(this.model(),this.properties(),this._options))}return this._definitionsViewModel}_initMaximizeHotkey(e){var t=this;function i(e){e.defaultPrevented||l.modifiersFromEvent(e)===l.Modifiers.Alt&&e.stopPropagation()}function s(e){e.defaultPrevented||l.modifiersFromEvent(e)===l.Modifiers.Alt&&(e.preventDefault(),e.stopPropagation(),t.toggleFullscreen())}return e.addEventListener("mousedown",i,!0),e.addEventListener("click",s,!0),function(){e.removeEventListener("mousedown",i,!0),e.removeEventListener("click",s,!0)}}toggleFullscreen(){var e=this.getResizerDetacher();e.fullscreenable.value()&&(e.fullscreen.value()?e.exitFullscreen():e.requestFullscreen())}setTimezone(e){e&&E(e)?this._properties.timezone.setValue(e):console.warn("Incorrect timezone: "+JSON.stringify(e))}getTimezone(){return this._properties.timezone.value()}refreshMarks(){this.model().barsMarksSources().forEach((function(e){e.refreshData()}))}clearMarks(e){this.model().barsMarksSources().forEach((function(t){t.clearMarks(e)}))}_initBackgroundColor(){null===this._backgroundTopColorSpawn&&(this._backgroundTopColorSpawn=this._model.model().backgroundTopColor().spawn(),this._backgroundTopColorSpawn.subscribe(this._onBackgroundColorChanged.bind(this))),null===this._backgroundBottomColorSpawn&&(this._backgroundBottomColorSpawn=this._model.model().backgroundColor().spawn(),this._backgroundBottomColorSpawn.subscribe(this._onBackgroundColorChanged.bind(this)))}paneWidgets(){return this._paneWidgets}paneByCanvas(e){for(var t=0;t0;)for(var t=this._content.panes[e].sources,i=t.length;i-- >0;)if("MainSeries"===t[i].type)return t[i].state}containsVolume(){return this.model().dataSources().some((function(e){return e instanceof m&&"Volume"===e.metaInfo().shortId}))}containsStudyByPredicate(e){return!!this._model&&this._model.dataSources().some((function(t){if(!(t instanceof m))return!1;var i=t.metaInfo();return e(i)}))}containsStudy(e){return this.containsStudyByPredicate((function(t){return t.id===e||t.fullId===e}))}isSmall(){return this._width()<550||this._height()<300}onWidget(){return this._onWidget}onCmeWidget(){return"cme"===this.widgetCustomer()}widgetCustomer(){return this._widgetCustomer}resize(){var e=this._height()+"px",t=this._width()+"px";this._mainDiv.style.height=e,this._mainDiv.style.width=t,this._elMainTable.style.height=e,this._elMainTable.style.width=t,this._resizeHandler&&this._mainDiv&&this._resizeHandler()}applyOverrides(e){var t={};for(var i in e)i.startsWith("mainSeriesProperties.priceAxisProperties")||(t[i]=e[i]);if(applyPropertiesOverrides(this.properties(),null,!1,t,null),this._model){ applyPropertiesOverrides(this._model.model().properties(),null,!1,t),applyPropertiesOverrides(this._model.mainSeries().properties(),null,!1,t,"mainSeriesProperties"),this._model.model().sessions().applyOverrides(t);const e=this._model.model().watermarkSource();null!==e&&e.applyOverrides(t)}}showReplayOrderConfirmationDialog(){return this.model().isInReplay().value()?new Promise((function(e,t){d({text:i.tf(null,void 0,i(180623)),onConfirm:function(t){e(),t.dialogClose()},onClose:t})})):Promise.resolve()}_addPerfMark(e){V("ChartWidget."+this._id+"."+e)}getResizerDetacher(){return this._options}}},325050:(e,t,i)=>{"use strict";const{clone:s}=i(389137);var o=i(650151).assert,r=i(533422).layouts,n=i(176019).createUndoHistory,a=i(885482),l=i(799786),c=i(470316),d=i(251954),h=i(244842),u=i(938550).WatchedObject,_=i(401580).WatchedValue,p=i(201089).getLogger("Chart.ChartWidgetCollection"),m=i(777466).preventDefaultForContextMenu,g=i(339315),S=i(161590).GeneralChartPropertiesRenderer,v=i(834698).CompareDialogRenderer,f=i(314802).isOnMobileAppPage,b=i(707957).Delegate;const{isSupportedLayout:y,tryGuessingTheMostSuitableLayout:C}=i(533422);var w=i(270294).CollectionViewMode,P=i(850775).mediaState,T=i(744728).SwapChartsUndoCommand,M=i(394905).ToastsFactory,x=i(531005).reconnectChartApi,I=i(397245).marketStatusText;const A=i(541558).randomHash;var L=i(749765),k=L.applyIndicatorsToAllChartsImpl,E=L.applyIndicatorToAllChartsImpl,D=L.lineToolsAndGroupsDTOsImpl,B=L.resetLineToolsInvalidatedImpl,N=L.applyLineToolUpdateNotificationImpl,R=L.createClipboardHandler,O=L.chartsSymbolsImpl,V=L.updateLayoutImpl,W=L.computeContentBoxImpl,F=L.getVisuallyAdjacentDefImpl,H=L.setLayoutImpl,z=L.removeChartWidgetSubscriptionsImpl,U=L.generateNewChartId,G=L.syncCrosshairImpl,q=L.createBroadcastChannel,j=L.destroyBroadcastChannel,Z=L.syncScrollImpl,K=L.allInitialModelsCreated,Y=L.allInitialSymbolsResolved,$=L.applyThemeImpl,X=L.handleDateRangeLockChange,J=L.handleInternalDateRangeLockChange,Q=L.handleTrackTimeLockChange,ee=L.handleInternalTrackTimeLockChange,te=L.handleIntervalLockChange,ie=L.handleInternalIntervalLockChange,se=L.handleSymbolLockChange,oe=L.handleInternalSymbolLockChange,re=L.handleConnectionLimitReachedChanged,ne=L.createLeftBottomChartWidgetWV,ae=L.subscribeToEventsForDateRangeSync,le=L.unsubscribeFromEventsForDateRangeSync,ce=L.syncChartsDateRangesWithActiveChartRange,de=L.subscribeToCompletedEventForDateRangeUpdate,he=L.resetLayoutSizesImpl,ue=L.unloadUnusedChartsImpl,_e=L.applyStudiesOverrides,pe=new Map,me=L.setBrokerImpl,ge={saveChartEnabled:!0,takeScreenshotEnabled:!0,publishedChartsEnabled:!0};e.exports=function(e){var t=this,Se=Object.assign({},ge,e),ve=new _,fe=Se.readOnly||!1,be=!1,ye=A(),Ce=[],we=0,Pe=new _,Te=new _,Me=new _,xe="s",Ie=new _(null),Ae=new Map,Le=new _([]),ke=new _;ke.setValue(w.ForceFullscreen);var Ee=[];const De={isConfirmationAboutReplayLocked:!1,loadingChart:!1,setTimeFrameActive:!1,setNewResolution:!1};var Be=!1,Ne=!1,Re=new _(!1),Oe=new _(null),Ve=new _(!1),We=new _(!1);We.subscribe((e=>se(At(),e))) ;var Fe=new _(We.value());Fe.subscribe((e=>oe(At(),e)));var He=new _(!1);He.subscribe((e=>te(At(),e)));var ze=new _(He.value());ze.subscribe((e=>ie(At(),e)));var Ue=new _(xe),Ge=new _(!1);Ge.subscribe((e=>Q(At(),e)));var qe=L.combinedTrackTimeLock(Ue,Ge,Ce);Ge.subscribe((e=>Q(At(),e)));var je=new _(qe.value());je.subscribe((e=>ee(At(),e)));var Ze=new _(!1);Ze.subscribe((e=>X(At(),e))),Ie.subscribe(oi);var Ke=new _(Ze.value());Ke.subscribe((e=>J(At(),e)));var Ye=new _(TVSettings.getBool("chart.syncCrosshair",!0)),$e=l.createGroup({desc:"Layout"}),Xe=null,Je=null,Qe=null,et=null,tt=null;if(window.TVD){var it=window.TVD.crosshairSyncEnabled;it?(it.value()&&(et=q(At)),tt=it.subscribe((e=>{e?et=q(At):(j(At()),et=null)}))):et=q(At)}var st=Ye.value();Ye.subscribe((function(e){st=e=!!e,TVSettings.setValue("chart.syncCrosshair",e);for(var t=0;t{at.setValue(null===e?null:e.chartWidget)}));var lt=Se.widgetOptions||{},ct=Se.metaInfo||{},dt={id:new _(ct.id||null),name:new _(ct.name),description:new _(ct.description),username:new _(ct.username),uid:new _(ct.uid),lastModified:new _(ct.lastModified)},ht=n();ht.onChange().subscribe(null,(function(e){d.emit("undo_redo_state_changed",e)}));var ut=Se.resizerBridge.container.value();ut.addEventListener("contextmenu",m);var _t,pt=new b,mt=new b,gt=new b,St=new _(!1),vt=new _(null),ft=null,bt=null;Se.seriesControlBarEnabled&&(_t="0px",vt.setValue(document.createElement("div")),vt.value().style.left=_t,vt.value().style.right=_t,vt.value().style.bottom=_t,vt.value().classList.add("chart-toolbar","chart-controls-bar"),vt.value().setAttribute("data-is-chart-toolbar-component","true"),ut.appendChild(vt.value()),Promise.all([i.e(52556),i.e(5987),i.e(5761),i.e(28430),i.e(70428),i.e(1413),i.e(52078),i.e(89508),i.e(62033),i.e(84331),i.e(85258),i.e(87940),i.e(61576),i.e(85131),i.e(91986),i.e(5400),i.e(67346),i.e(16818),i.e(90385),i.e(56694),i.e(47260)]).then(i.bind(i,648393)).then((({BottomToolbarRenderer:e})=>{var i=Se.resizerBridge,s=[i.container.spawn(),i.width.spawn(),i.height.spawn()],o=i.container.value(),r=function(){var e=o.getBoundingClientRect(),t=W(At());return t.top=e.top+t.top,t.left=e.left+t.left,t},n=new b,a=function(){n.fire()};s.forEach((function(e){e.subscribe(a)}));var l=function(){s.forEach((function(e){e.destroy()})),n.destroy(),window.ChartApiInstance.connectionsLimitReached().unsubscribe(re)};ft=new e(vt.value(),n,r,t,ChartApiInstance,lt,Se.seriesControlBar),bt=function(){null!==ft&&(ft.destroy(),ft=null,vt.value().remove(),vt.setValue(null)),l()}})));var yt=new S(t),Ct=new v(t),wt=null;function Pt(){St.setValue(Ce.some((e=>{const t=e.chartWidget.lineToolsSynchronizer();return null!==t&&t.hasChanges().value()})))}function Tt(e){return L.checkProFeatureImpl(At(),e)}wt=new M(Se.resizerBridge,(function(){return vt.value()?vt.offsetHeight:0})), window.ChartApiInstance.connectionsLimitReached().subscribe(re,{callWithLast:!0}),Oe.subscribe((()=>Et()));const Mt=new Map,xt=()=>L.updateLinkingGroupCharts(At()),It=new u([]);function At(){return{undoHistory:ht,chartWidgetsDefs:Ce,chartsCountToSave:Lt,actualLayoutCount:kt,savedChartWidgetOptions:Ee,activeChartWidget:ve,options:Se,parent:ut,toastsFactory:wt,crosshairLockRaw:st,crossHairSyncBroadcast:et,setChartStorageNotificationSubscription:e=>{Je=e},maximizedChartDef:nt,setMaximized:Ht,layoutTemplate:Me,widthWV:ot,heightWV:rt,checkProFeature:Tt,lineToolsSynchronizerHasChanges:St,recalcHasChanges:Pt,onZoom:mt,onScroll:gt,layoutType:xe,layoutWV:Ue,setLayoutType:e=>{xe=e},isPhoneSize:Re,viewMode:ke,updateViewMode:Ut,loadingContent:Be,setLoadingContent:e=>{Be=e},initialLoading:Ne,inlineChartsCount:Te,updateWatchedValue:Gt,checkAllPendingModelsAlreadyCreated:zt,readOnly:fe,symbolLock:We,internalSymbolLock:Fe,intervalLock:He,internalIntervalLock:ze,dateRangeLock:Ke,internalDateRangeLock:Ke,trackTimeLock:Ge,internalTrackTimeLock:je,crosshairLock:Ye,customLegendWidgetsFactoriesMap:_i,globalDetachable:Pe,saveChartService:Xe,customSources:hi,updateActivityView:qt,chartWidgetCreatedDelegate:pt,sizingState:Oe,currentLayoutResizeAction:Ie,allLayoutSizesState:Ae,splitters:Le,widgetOptions:lt,bottomToolbar:vt,replayContainer:ui,layoutSizesChanged:Ve,subscribeToCompletedEventForDateRangeSync:(e,t)=>de(At(),e,t),subscribeToEventsForDateRangeSync:e=>ae(At(),e),unsubscribeFromEventsForDateRangeSync:e=>le(At(),e),syncChartsDateRangesWithActiveChartRange:e=>ce(At(),e),combinedTrackTimeLock:qe,chartWidgetIdToCompletedCallbackMap:pe,flags:De,linkingGroupsCharts:Mt,chartModels:It,updateLinkingGroupCharts:xt}}function Lt(){return Ce.length+Ee.length}function kt(){return r[xe].count}function Et(){V(At())}ot.subscribe(Et),rt.subscribe(Et),this.updateLayout=Et;const Dt=L.activeLinkingGroupWV(ve),Bt=L.allLinkingGroupsWV(At());var Nt;Re.setValue(!1);var Rt=["phone","phone-vertical"];function Ot(e,t){Se.mobileForceChartMaximizeEnabled&&(!Rt.includes(P.device)||t&&Rt.includes(t)?Rt.includes(P.device)||t&&!Rt.includes(t)||Re.setValue(!1):Re.setValue(!0))}function Vt(){if(window.is_authenticated){var e=h.enabled("app_phone");!h.enabled("app_tablet")&&(e||Re.value())?ke.value()===w.ForceFullscreen&&(Nt=nt.value(),ve.value().requestFullscreen()):Nt||(Ht(null),Ut())}}function Wt(e){return e.rdState.owner.value()!==e}function Ft(e){return H.call(t,e)}function Ht(e){nt.value()!==e&&(nt.setValue(e),Ft(xe))}function zt(){Ce.every((e=>e.chartWidget.hasModel()))&&(Gt(),d.emit("layout_changed"))}function Ut(){"s"===xe||nt.value()?ke.setValue(w.ForceFullscreen):ke.setValue(w.Multichart)}function Gt(){var e=Math.min(Me.value().count,Ce.length)-1;if(e<0)ve.deleteValue();else{var t=we;t<0&&(t=0),t>e&&(t=e),ve.setValue(Ce[t].chartWidget)}}function qt(){for(var e=Ce.length;e--;){var t=e===we;Ce[e].container.value().classList.toggle("active",t),Ce[e].container.value().classList.toggle("inactive",!t)}}function jt(e){0}function Zt(e,t){return F(At(),e,t)} function Kt(e){var t=Zt(Ce[we],e);jt(t?t.chartWidget:ve.value()),t&&(ve.setValue(t.chartWidget),nt.value()&&Ft(xe))}const Yt=new b;function $t(e,t){var i=Ce.findIndex((function(t){return t.chartWidget===e})),s=Ce.findIndex((function(e){return e.chartWidget===t}));if(-1===i||-1===s)throw new Error("chart is not in the layout");var o=Ce[i],r=Ce[s];Ce[i]=r,Ce[s]=o,we===i?we=s:we===s&&(we=i),Et(),Yt.fire()}var Xt=new b,Jt=new _,Qt=new _([]),ei=null;function ti(e){var t=e.mainSeries().properties();t.style.subscribe(null,ii),ii(t.style),e.model().onSelectedSourceChanged().subscribe(null,si),Ze.value()&&(ae(At(),e),ce(At())),si(e.selection().allSources())}function ii(e){Jt.setValue(e.value())}function si(){var e=ei.model();Qt.setValue(e.selection().allSources())}function oi(e){Ze.value()&&null===e&&ce(At())}ve.subscribe((function(e){if(e){for(var t,i=Ce.length;i--;)if(Ce[i].chartWidget===e){t=i;break}if(!isFinite(t))throw new Error("Cannot make detached ChartWidget active");if(we!==t){nt.value()&&(Wt(Ce[t])||nt.setValue(Ce[t])),we=t,qt();for(i=Ce.length;i--;)Ce[i].chartWidget!==e&&Ce[i].chartWidget.setActive(!1);wi(),e.setActive(!0),a.activePointSelectionMode.setValue(e.selectPointMode().value())}!function(e){if(ei!==e){if(ei&&(ei.modelCreated().unsubscribe(null,ti),ei.hasModel())){var t=ei.model();Ze.value()&&le(At(),t),t.mainSeries().properties().style.unsubscribe(null,ii),t.model().onSelectedSourceChanged().unsubscribe(null,si),ei=null}e&&(ei=e,e.hasModel()?ti(e.model()):e.modelCreated().subscribe(null,ti))}}(e)}}),{callWithLast:!0});var ri=new b;function ni(){Se.resizerBridge.requestFullscreen()}function ai(){Se.resizerBridge.exitFullscreen()}function li(){return Se.resizerBridge.fullscreenable}function ci(){return Se.resizerBridge.fullscreen}function di(e){if(0!==Ce.length){for(var t=Ce.length;t--;)Ce[t].chartWidget.setActive(!1);Ce[we].chartWidget.setActive(e)}}fe||($e.add({desc:"Switch active chart",hotkey:h.enabled("accessible_keyboard_shortcuts")?c.Modifiers.Shift+39:9,handler:function(){Kt(!1)}}),$e.add({desc:"Switch active chart",hotkey:h.enabled("accessible_keyboard_shortcuts")?c.Modifiers.Shift+37:c.Modifiers.Shift+9,handler:function(){Kt(!0)}})),$e.add({desc:"Fullscreen mode",hotkey:c.Modifiers.Shift+70,isDisabled:h.enabled("widget")||!li().value(),handler:function(){ci().value()?ai():ni()}}),Se.takeScreenshotEnabled&&($e.add({desc:"Screenshot server",hotkey:c.Modifiers.Alt+83,handler:L.takeServerScreenshot.bind(this,Se.snapshotUrl,t)}),f("any")||($e.add({desc:"Download client screenshot",hotkey:c.Modifiers.Mod+c.Modifiers.Alt+83,handler:L.downloadScreenshot.bind(this,t)}),$e.add({desc:"Copy client screenshot",hotkey:c.Modifiers.Mod+c.Modifiers.Shift+83,handler:L.copyScreenshotToClipboard.bind(this,t)}))),Se.saveChartEnabled&&$e.add({desc:"Save Chart Layout",hotkey:c.Modifiers.Mod+83,handler:function(){Xt.fire()}});var hi=new Map,ui=null,_i=new Map;const pi=R(At());Se.globalEvents&&pi.listen() ;const mi=We.spawn(),gi=He.spawn(),Si=Ze.spawn(),vi=Ge.spawn(),fi=Ye.spawn(),bi=()=>Ce.map((e=>e.chartWidget)),yi=ne(bi,Ue.readonly(),Yt,pt);function Ci(e,t){if(Be=!0,Ne=Boolean(t),Ee.splice(0),e){if(e.charts||(e={layout:"s",charts:[e]}),e.layoutsSizes)for(const t of Object.keys(e.layoutsSizes))Ae.set(t,e.layoutsSizes[t]);var i=new Set;e.charts.forEach((function(e){e.chartId&&i.add(e.chartId)})),e.charts.forEach((function(e){if(!e.chartId){var t=U((function(e){return i.has(e)}));i.add(t),e.chartId=t}}));let t=e.layout;if(!y(t)){const e=C(t);p.logError(`Loading unsupported layout ${t}. Force migration to ${e}`),t=e}xe=Tt(t||"s");for(const t of e.charts)e.studyMetaInfoMap&&t.panes.forEach((t=>{t.sources.forEach((t=>{"string"==typeof t.metaInfo&&(t.metaInfo=s(e.studyMetaInfoMap[t.metaInfo]))}))})),Ee.push({content:t});void 0!==e.symbolLock&&We.setValue(Boolean(e.symbolLock)),void 0!==e.intervalLock&&He.setValue(Boolean(e.intervalLock)),void 0!==e.trackTimeLock&&Ge.setValue(Boolean(e.trackTimeLock)),void 0!==e.dateRangeLock&&Ze.setValue(Boolean(e.dateRangeLock)),void 0!==e.crosshairLock&&Ye.setValue(Boolean(e.crosshairLock))}Ft(xe),"s"===xe||Se.mobileForceChartMaximizeEnabled||ke.setValue(w.Multichart),a.init(),a.tool.subscribe(Pi),a.tool.subscribe(wi),Be=!1,Ne=!1}function wi(){var e=ve.value();Ce.forEach((function(t){t.chartWidget!==e&&t.chartWidget.updateCrossHairPositionIfNeeded()})),e&&e.updateCrossHairPositionIfNeeded()}function Pi(){Ce.forEach((function(e){e.chartWidget.onToolChanged()}))}Object.assign(this,{innerState:At,getAll:bi,maximizedChartWidget:()=>at.readonly(),leftBottomChartWidget:()=>yi,activeLinkingGroup:()=>Dt,allLinkingGroups:()=>Bt,linkingGroupsCharts:e=>L.getLinkingGroupCharts(At(),e).readonly(),destroy:function(){if(ri.fire(),di(!1),null!==bt&&(bt(),bt=null),z(At()),mi.destroy(),gi.destroy(),vi.destroy(),Si.destroy(),qe.destroy(),fi.destroy(),Ie.unsubscribe(oi),Ce.forEach((function(e){void 0!==e.timingsMeter&&e.timingsMeter.destroy(),e.chartWidget.linkingGroupIndex().unsubscribe(xt),e.chartWidget.destroy()})),Se.resizerBridge.remove(),Le.value().forEach((e=>{e.mouseHandler.destroy(),e.mouseListener.destroy()})),window.removeEventListener("resize",Et),P.off("changeDevice",Ot),Se.mobileForceChartMaximizeEnabled&&!Se.handleMaximizedChartOnResizeDisabled&&P.off("changeDevice",Vt),a.tool.unsubscribe(wi),a.tool.unsubscribe(Pi),ut.remove(),hi.clear(),_i.clear(),$e.destroy(),Je&&Je.destroy(),pi&&pi.destroy(),Qe&&Qe.destroy(),Dt.destroy(),Bt.destroy(),window.TVD){const e=window.TVD.crosshairSyncEnabled;e&&e.unsubscribe(tt),j(At())}yi.destroy(),be=!0},onAboutToBeDestroyed:ri,layout:Ue.readonly(),setLayout:Ft,activeChartWidget:ve,viewMode:ke,activeChartStyle:Jt.readonly(),setChartStyleToWidget:L.setChartStyleToWidget.bind(this),selectedSources:Qt.readonly(),metaInfo:dt,state:function(e,i,s,o,r){return L.stateImpl.call(t,{withData:e,skipLineToolsFromOtherSymbols:i,wipeSensitiveData:s,skipLineTools:o,addOnlyActiveChart:r})},lineToolsAndGroupsDTOs:function(){return D(At())}, resetLineToolsInvalidated:function(e,t){return B(At(),e,t)},applyLineToolUpdateNotification:N.bind(null,Ce),readOnly:function(){return fe},onZoom:function(){return mt},onScroll:function(){return gt},resizerBridge:function(){return Se.resizerBridge},lock:{symbol:mi,interval:gi,dateRange:Si,crosshair:fi,trackTime:vi},setSymbol:(e,t)=>L.setSymbol(At(),e,t),setSymbolAll:(e,t)=>L.setSymbolAll(At(),e,t),setResolution:(e,t,i)=>L.setResolution(At(),e,t,i),setTimeFrame:function(e){De.loadingChart||De.setTimeFrameActive||(De.setTimeFrameActive=!0,He.value()?Ce.forEach((function(t){t.chartWidget.loadRange(e)})):ve.value().loadRange(e),De.setTimeFrameActive=!1)},updateLayout:Et,setChartLayoutWithUndo:function(e){return L.setChartLayoutWithUndoImpl(At(),this,e)},images:L.getSnapshot.bind(this,this,Se.widgetOptions.customerReadableName,lt.onWidget),clientSnapshot:L.getClientSnapshot.bind(this,this,Se.widgetOptions.customerReadableName,lt.onWidget),tags:function(){for(var e=[],t=0;tG(At(),e,t,i,s),syncScroll:function(e,t){return Z(At(),e,t)},clearChartMetaInfo:function(){dt.id.setValue(null),dt.uid.setValue(void 0),dt.name.setValue(void 0)},takeScreenshot:L.takeScreenshot.bind(this,Se.snapshotUrl,this),takeServerScreenshot:L.takeServerScreenshot.bind(this,Se.snapshotUrl,this),loadContent:Ci,purgeUnusedWidgets:function(){for(var e=r[xe].count;e1},applyIndicatorToAllCharts:async function(e,t,i,s){await E(At(),e,t,i,s)},setActive:di,inlineChartsCount:Te.readonly(),revertToInline:function(){if(!Re.value()||ke.value()!==w.ForceFullscreen){Ht(null);for(var e=0;eEt())),Et()},destroyReplayWidget:function(){o(null!==ui,"Cannot remove replay container, container is not created"),ui.remove(),ui=null,Et()},setViewMode:function(e){ke.setValue(e)},moveActiveChartWithUndo:function(e){var t=Ce[we],i=Zt(t,e);i&&ht.pushUndoCommand(new T($t,t.chartWidget,i.chartWidget))},activeChartCanBeMoved:function(){return!(fe||Te.value()<2||Wt(Ce[we]))},generalPropertiesDefinitions:function(){return ve.value().generalPropertiesDefinitions()},reconnectChartApi:function(e){x(e)},setBroker:function(e){me(At(),e)},setSaveChartService:function(e){Xe=e;for(var t=0;tVe,clientId:ye,ariaDescribeChart:jt,chartModels:()=>It.readonly()}),L.createChartStorageSubscriptionsIfRequired(this,At()),Ci(Se.content,!0),L.createChartWidgetCollectionNewsNotifier(this,At()).then((e=>{be||(Qe=e)})),Ue.subscribe((function(){qt()})),Ue.hook=function(e){return e===this.value()?e:Tt(e)},fe&&(Ue.writeLock=!0),window.addEventListener("resize",Et),Se.mobileForceChartMaximizeEnabled&&(P.on("changeDevice",Ot),Se.handleMaximizedChartOnResizeDisabled||P.on("changeDevice",Vt),Ot(),Vt());var Ti=0;function Mi(){0===--Ti&&d.emitOnce("onChartReady")}Ce.forEach((function(e){if(e){Ti++;var t=e.chartWidget;t.withModel(null,(function(){Se.metaInfo&&t.model().model().setChartSaveTime(1e3*Se.metaInfo.lastModified);var e=t.model().mainSeries();if(e.bars().size()>0||e.isFailed())Mi();else{var i=e.dataEvents(),s=function(){Mi(),i.barReceived().unsubscribe(null,s),i.completed().unsubscribe(null,s),i.error().unsubscribe(null,s),i.unsupportedResolutionRequested().unsubscribe(null,s)};i.barReceived().subscribe(null,s),i.completed().subscribe(null,s),i.error().subscribe(null,s), i.unsupportedResolutionRequested().subscribe(null,s)}}))}})),K(At()).then(Y).then((function(){window.saver&&window.is_authenticated&&Se.widgetOptions.justCloned&&window.saver.saveChartSilently()})).catch(p.logError.bind(p))}},783375:(e,t,i)=>{"use strict";i.d(t,{ContextMenuManager:()=>s});var s,o=i(674981),r=i(373571),n=i(224743);!function(e){let t=null,s=null;const a=[],l={createAction:e=>new r.Action({actionId:"Chart.CustomActionId",options:e}),createAsyncAction:e=>new r.Action({actionId:"Chart.CustomActionId",options:{},optionsLoader:e}),createSeparator:()=>new r.Separator};async function c(e,r={},n={menuName:""},c){null!==t&&(e=await t(e,l,n));let h=null;const u=()=>{const e=(0,o.indexOf)(a,(e=>e.renderer===h));-1!==e&&a.splice(e,1),void 0!==c&&c()};let _=!1;if(null!==s&&(h=await s(e,n,u)),h)_=!0,d();else{const t=await Promise.all([i.e(70428),i.e(52078),i.e(89508),i.e(61204),i.e(66323),i.e(85131),i.e(94712),i.e(71093),i.e(5824),i.e(57216),i.e(90385),i.e(76448),i.e(91584)]).then(i.bind(i,639051));h=new t.ContextMenuRenderer(e,r,u,d)}return a.push({renderer:h,isExternal:_}),h}function d(){(0,n.globalCloseMenu)(),a.forEach((e=>{e.isExternal&&e.renderer.isShown()&&e.renderer.hide()}))}e.createMenu=c,e.showMenu=function(e,t,i={},s,o){return c(e,i,s,o).then((e=>e.show(t)))},e.setCustomRendererFactory=function(e){s=e},e.setCustomItemsProcessor=function(e){t=e},e.hideAll=d,e.getShown=function(){for(let e=0;e{"use strict";var s;i.d(t,{TabNames:()=>s}),function(e){e.background="Background",e.coordinates="Coordinates",e.drawings="Drawings",e.events="Events",e.eventsAndAlerts="Events & Alerts",e.inputs="Inputs",e.properties="Properties",e.scales="Scales",e.legend="Legend",e.sourceCode="Source Code",e.style="Style",e.symbol="Symbol",e.timezoneSessions="Timezone/Sessions",e.trading="Trading",e.visibility="Visibility",e.text="Text"}(s||(s={}))},175070:(e,t,i)=>{"use strict";i.d(t,{getPriceAxisNameInfo:()=>n});const s=["Z","Y","X","W","V","U","T","S"],o=["A","B","C","D","E","F","G","H"];class r{constructor(e){this.label=e}equals(e){return null!==e&&this.label===e.label}}function n(e,t){const i="left"===e?s:o;return new r(t{"use strict";i.d(t,{KineticAnimation:()=>n});var s=i(650151);function o(e,t){return e.position-t.position}function r(e,t,i){const s=(e.position-t.position)/(e.time-t.time);return Math.sign(s)*Math.min(Math.abs(s),i)}class n{constructor(e,t,i,s){this._position1=null,this._position2=null,this._position3=null,this._position4=null,this._animationStartPosition=null,this._durationMsecs=0,this._speedPxPerMsec=0,this._minSpeed=e,this._maxSpeed=t,this._dumpingCoeff=i,this._minMove=s}addPosition(e,t){if(null!==this._position1){if(this._position1.time===t)return void(this._position1.position=e);if(Math.abs(this._position1.position-e)50)return;let i=0;const s=r(this._position1,this._position2,this._maxSpeed),n=o(this._position1,this._position2),a=[s],l=[n];if(i+=n,null!==this._position3){const e=r(this._position2,this._position3,this._maxSpeed);if(Math.sign(e)===Math.sign(s)){const t=o(this._position2,this._position3);if(a.push(e),l.push(t),i+=t,null!==this._position4){const e=r(this._position3,this._position4,this._maxSpeed);if(Math.sign(e)===Math.sign(s)){const t=o(this._position3,this._position4);a.push(e),l.push(t),i+=t}}}}let c=0;for(let e=0;e{"use strict";i.d(t,{icons:()=>o});var s=i(631110);const o=[{icon:"🔶",label:s.t(null,void 0,i(21116))},{icon:"🍀",label:s.t(null,void 0,i(387058))},{icon:"💧",label:s.t(null,void 0,i(111948))},{icon:"❤️",label:s.t(null,void 0,i(376566))},{icon:"💩",label:s.t(null,void 0,i(158635))}]},453817:(e,t,i)=>{"use strict";i.d(t,{LayoutChartsSyncContextMenuAction:()=>a});var s=i(861814),o=i(444372),r=i(373571),n=i(12943);class a extends r.Action{constructor(e,t){const a={icon:s,statName:"SetLayoutChartsSyncGroup",label:o.t(null,void 0,i(680818))};super({actionId:"Chart.LinkingGroupSync",options:{...a,subItems:n.icons.map((({icon:t},i)=>new r.Action({actionId:"Chart.LinkingGroupSync.ChangeGroup",options:{label:t,checkable:!0,checked:e.value()===i,onExecute:()=>this._setLinkingGroupIndexImpl(i)}})))},customActionOptions:{...a,subItems:[new r.Action({actionId:"Chart.LinkingGroupSync.ChangeGroup",options:{},optionsLoader:async()=>{const[e,{LayoutChartsSyncContextMenuItem:t}]=await Promise.all([Promise.resolve().then(i.t.bind(i,50959,19)),Promise.all([i.e(14),i.e(37657),i.e(28288),i.e(25967),i.e(10184)]).then(i.bind(i,339148))]);return{doNotCloseOnClick:!1,noInteractive:!0,jsxLabel:e.createElement(t,{active:this._linkingGroupIndex,icons:n.icons,onClick:e=>{this._setLinkingGroupIndexImpl(e)}})}}})]}}),this._setLinkingGroupIndexImpl=e=>{this._setLinkingGroupIndex(this._linkingGroupIndex.value()===e?null:e)},this._linkingGroupIndex=e.spawn(),this._setLinkingGroupIndex=t}}},521506:(e,t,i)=>{"use strict";i.d(t,{lineToolsSelectHotkeys:()=>o});i(586463);var s=i(470316);const o={LineToolFibRetracement:{hash:s.Modifiers.Alt+70,action:"setTool",description:"Draw Fib Retracement"}, LineToolHorzLine:{hash:s.Modifiers.Alt+72,action:"drawRightThere",description:"Draw Horizontal Line here"},LineToolHorzRay:{hash:s.Modifiers.Alt+74,action:"drawRightThere",description:"Draw Horizontal Ray here"},LineToolRectangle:{hash:s.Modifiers.Alt+s.Modifiers.Shift+82,action:"setTool",description:"Draw Rectangle"},LineToolTrendLine:{hash:s.Modifiers.Alt+84,action:"setTool",description:"Draw Trend Line"},LineToolVertLine:{hash:s.Modifiers.Alt+86,action:"drawRightThere",description:"Draw Vertical Line here"},LineToolCrossLine:{hash:s.Modifiers.Alt+67,action:"drawRightThere",description:"Draw Cross Line here"}}},535503:(e,t,i)=>{"use strict";i.d(t,{actualBehavior:()=>a,availableValues:()=>n,navigationButtonsVisibilityKey:()=>o,property:()=>r,restoreNavigationButtonsVisibilitySettingsValue:()=>l});var s=i(87053);const o="NavigationButtons.visibility",{property:r,availableValues:n,actualBehavior:a,restoreDefaultValue:l}=(0,s.createVisibilityController)(o)},939702:(e,t,i)=>{"use strict";i.d(t,{actualBehavior:()=>a,availableValues:()=>n,property:()=>r,restorePaneButtonsVisibilitySettingsValue:()=>l});var s=i(87053),o=i(535503);const{property:r,availableValues:n,actualBehavior:a,restoreDefaultValue:l}=(0,s.createVisibilityController)("PaneButtons.visibility",o.navigationButtonsVisibilityKey)},779196:(e,t,i)=>{"use strict";i.d(t,{performanceTestMode:()=>n});var s=i(125226),o=i(638456),r=i(314802);const n=navigator.userAgent.toLowerCase().indexOf("chrome")>-1&&-1===navigator.userAgent.toLowerCase().indexOf("edge")&&!o.CheckMobile.any()&&!(0,r.isOnMobileAppPage)("any")&&!window.TVD&&!(0,o.onWidget)()&&(0,s.isFeatureEnabled)("performance_test_mode")&&!window.matchMedia("(prefers-reduced-motion)").matches},261525:(e,t,i)=>{"use strict";i.d(t,{isCustomStudy:()=>o});const s={LinearRegression:!0,PivotPointsHighLow:!0,VbPSessions:!0,VbPSessionsRoughDetailed:!0,VbPPeriodic:!0,VbPAutoAnchored:!0,ZigZag:!0,TPOPeriodic:!0,TPOSessions:!0,VbPFixed:!0,PivotPointsStandard:!0,VbPVisible:!0,VbPAnchored:!0};function o(e){return e in s}},827710:(e,t,i)=>{"use strict";i.d(t,{MetaInfoHelper:()=>u});var s=i(650151),o=i(526075),r=i(368135),n=i(389137),a=i(201089),l=i(62745);function c(e){return!e.groupId&&!e.isHidden&&e.id!==l.RangeDependentStudyInputNames.FirstBar&&e.id!==l.RangeDependentStudyInputNames.LastBar}var d=i(261525);const h=(0,a.getLogger)("Platform.GUI.PropertyDialog.Indicators.MetaInfo");class u{constructor(e){this._metaInfo=e}hasUserEditableInputs(){return this._metaInfo.inputs.some(c)}getUserEditableInputs(){return this._metaInfo.inputs.filter(c)}hasUserEditableProperties(){return o.StudyMetaInfo.isScriptStrategy(this._metaInfo)}hasUserEditableStyles(){const e=this._metaInfo;return e.plots.length>0||void 0!==e.bands||void 0!==e.filledAreas||(0,d.isCustomStudy)(e.shortId)||o.StudyMetaInfo.isScriptStrategy(this._metaInfo)||Object.values(e.graphics).some((e=>void 0!==e))}getUserEditablePlots(){const e=new Set,t=this._metaInfo;return t.plots.filter((i=>{if((0,r.isColorerPlot)(i)||(0,r.isTextColorerPlot)(i)||(0, r.isDataOffsetPlot)(i)||(0,r.isOhlcColorerPlot)(i)||(0,r.isAlertConditionPlot)(i)||(0,r.isDataPlot)(i))return!1;if((0,r.isOhlcPlot)(i)){const o=i.target;if(e.has(o))return!1;e.add(o);const r=(0,s.ensureDefined)(t.ohlcPlots);return!(0,s.ensureDefined)(r[o]).isHidden}{const e=t.styles?t.styles[i.id]:void 0;return void 0===e||!e.isHidden}}))}hasUserEditableOptions(){return this.hasUserEditableInputs()||this.hasUserEditableProperties()||this.hasUserEditableStyles()}getStrategyProperties(){const e=this._metaInfo,t=e.inputs.filter(p),i={..._};for(const s of t){const t=s.internalID;i[t]=s,_.hasOwnProperty(t)||h.logWarn(`Unknown strategy input internal id ${t} in ${e.fullId}`)}return(0,n.clone)(i)}}const _={currency:void 0,backtest_fill_limits_assumption:void 0,calc_on_every_tick:void 0,calc_on_order_fills:void 0,commission_value:void 0,commission_type:void 0,initial_capital:void 0,pyramiding:void 0,slippage:void 0,default_qty_type:void 0,default_qty_value:void 0,margin_long:void 0,margin_short:void 0,use_bar_magnifier:void 0,process_orders_on_close:void 0,fill_orders_on_standard_ohlc:void 0};function p(e){return"strategy_props"===e.groupId}},263955:(e,t,i)=>{"use strict";i.d(t,{showScriptInfoErrorNoticeDialog:()=>r});var s=i(444372),o=i(33900);function r(){(0,o.showNoticeDialog)({type:"modal",title:s.t(null,void 0,i(457898)),content:s.t(null,void 0,i(27937))})}},14952:(e,t,i)=>{"use strict";i.d(t,{restoreShowMarketOpenStatusProperty:()=>l,showMarketOpenStatusProperty:()=>a});var s=i(152633),o=i(62802);const r="Chart.ShowMarketOpenStatus";function n(){return o.getBool(r,true)}const a=(0,s.createPrimitiveProperty)(n());function l(){a.setValue(true),o.remove(r)}o.onSync.subscribe(null,(()=>a.setValue(n()))),a.subscribe(null,(()=>o.setValue(r,a.value())))},397245:(e,t,i)=>{"use strict";i.d(t,{marketStatusText:()=>o});var s=i(380271);function o(e){const t=e.value();if(null!==t){const e=s.titleMap.get(t);if(void 0!==e)return e}return""}},380271:(e,t,i)=>{"use strict";i.d(t,{actionMap:()=>J,classNameMap:()=>U,countdownFnMap:()=>X,iconMap:()=>z,marketStatusDescription:()=>Z,titleColorMap:()=>j,titleMap:()=>q,tooltipMap:()=>G});var s=i(195294),o=i(444372),r=i(553218),n=i(732140),a=i(262998),l=i(725230),c=i(315507),d=i(643401),h=i(85290),u=i(212462),_=i(792263),p=i(24165),m=i(421672),g=i(792845),S=i(109494),v=i(529191) ;const f=o.t(null,void 0,i(383949)),b=o.t(null,void 0,i(356042)),y=o.t(null,void 0,i(429985)),C=o.t(null,void 0,i(895814)),w=o.t(null,void 0,i(988958)),P=o.t(null,void 0,i(269419)),T=o.t(null,void 0,i(801653)),M=o.t(null,void 0,i(540519)),x=o.t(null,void 0,i(957048)),I=o.t(null,void 0,i(987202)),A=o.t(null,void 0,i(539348)),L=o.t(null,void 0,i(107827)),k=o.t(null,void 0,i(19830)),E=o.t(null,void 0,i(735701)),D=o.t(null,void 0,i(298105)),B=o.t(null,void 0,i(950634)),N=o.t(null,void 0,i(574537)),R=new Map([["market",new Map([["small",n],["medium",a],["large",a]])],["pre_market",new Map([["small",h],["medium",u],["large",u]])],["post_market",new Map([["small",c],["medium",d],["large",d]])],["out_of_session",new Map([["small",r],["medium",r],["large",r]])],["holiday",new Map([["small",l],["medium",l],["large",l]])]]),O=new Map([["market",v.marketStatusOpen],["pre_market",v.marketStatusPre],["post_market",v.marketStatusPost],["out_of_session",v.marketStatusClose],["holiday",v.marketStatusHoliday]]),V=new Map([["market",f],["pre_market",b],["post_market",y],["out_of_session",C],["holiday",w]]),W=new Map([["market",f],["pre_market",b],["post_market",y],["out_of_session",C],["holiday",w]]),F=new Map([["market",s.colorsPalette["color-market-open"]],["pre_market",s.colorsPalette["color-pre-market"]],["post_market",s.colorsPalette["color-post-market"]],["out_of_session",s.colorsPalette["color-market-closed"]],["holiday",s.colorsPalette["color-market-holiday"]]]),H=new Map([["market",P],["pre_market",T],["post_market",M],["out_of_session",x],["holiday",I]]);R.set("delisted",new Map([["small",_],["medium",p],["large",m]])),R.set("expired",new Map([["small",g],["medium",S],["large",S]])),O.set("delisted",v.marketStatusDelisted),O.set("expired",v.marketStatusExpired),V.set("delisted",o.t(null,void 0,i(389905))),V.set("expired",o.t(null,void 0,i(911235))),W.set("delisted",o.t(null,void 0,i(137432))),W.set("expired",o.t(null,void 0,i(911235))),F.set("delisted",s.colorsPalette["color-delisted-symbol"]),F.set("expired",s.colorsPalette["color-market-expired"]),H.set("delisted","This is no longer publicly trading so no new data will be added. But you can explore the historicals here."),H.set("expired",o.t(null,void 0,i(929493)));const z=R,U=O,G=V,q=W,j=F,Z=H;function K(e){return o.t(null,{plural:"{number} minutes",count:e},i(467151)).format({number:e.toString()})}function Y(e){return o.t(null,{plural:"{number} hours",count:e},i(224430)).format({number:e.toString()})}function $(e){const t=Math.floor(e/86400),s=Math.floor((e-86400*t)/3600),r=Math.floor((e-86400*t-3600*s)/60);return 0===t&&0===s&&0===r?A:t>0?L.format({days:(n=t,o.t(null,{plural:"{number} days",count:n},i(458609)).format({number:n.toString()})),hours:Y(s)}):s>0?k.format({hours:Y(s),minutes:K(r)}):K(r);var n}const X={market:e=>("post_market"===e.status?B:D).format({remainingTime:$(e.remainingSeconds)}),pre_market:e=>E.format({remainingTime:$(e.remainingSeconds)}),post_market:e=>D.format({remainingTime:$(e.remainingSeconds)}), out_of_session:e=>("pre_market"===e.status?N:E).format({remainingTime:$(e.remainingSeconds)}),holiday:e=>("pre_market"===e.status?N:E).format({remainingTime:$(e.remainingSeconds)}),delisted:e=>"",expired:e=>""},J=new Map([["market",null],["pre_market",null],["post_market",null],["out_of_session",null],["holiday",null],["delisted",null]])},826531:(e,t,i)=>{"use strict";i.d(t,{canShowSpreadActions:()=>o,globalKeypressMatches:()=>r});i(244842),i(276871),i(583912);var s=i(846540);new RegExp("^"+s.types.QUANDL,"i");function o(){let e=!1;return e="cme"!==window.TradingView.widgetCustomer&&"bovespa"!==window.TradingView.widgetCustomer,e}function r(e){if(e.ctrlKey)return!1;if(e.metaKey)return!1;if(!e.charCode)return!1;if(!e.which||e.which<=32)return!1;const t=e.target;if(t&&(/^(input|textarea)$/i.test(t.tagName)||"listbox"===t.getAttribute("role")))return!1;{const e=i.c[911595];if(e&&e.exports.isOpenedModals())return!1}return!0}},34831:(e,t,i)=>{"use strict";function s(){return Promise.all([i.e(14819),i.e(73224),i.e(72718),i.e(35554),i.e(93327),i.e(32662),i.e(5987),i.e(98996),i.e(43387),i.e(66458),i.e(5761),i.e(4343),i.e(28430),i.e(70428),i.e(44597),i.e(1413),i.e(4908),i.e(52078),i.e(70621),i.e(89508),i.e(62033),i.e(13633),i.e(19216),i.e(37132),i.e(85258),i.e(16005),i.e(87940),i.e(63276),i.e(63751),i.e(29647),i.e(87473),i.e(10637),i.e(16165),i.e(85131),i.e(10714),i.e(94712),i.e(44794),i.e(39076),i.e(45338),i.e(47877),i.e(84418),i.e(95884),i.e(57254),i.e(76620),i.e(90385),i.e(92833),i.e(42942),i.e(5483),i.e(3889),i.e(92158),i.e(39434),i.e(18561),i.e(26854),i.e(17774),i.e(81548),i.e(21754)]).then(i.bind(i,788048))}i.d(t,{loadNewSymbolSearch:()=>s})},394905:(e,t,i)=>{"use strict";i.d(t,{ToastsFactory:()=>s});class s{constructor(e,t){this._chartToastsPromise=null,this._resizerBridge=e,this._bottomToolbarOffsetHeightProvider=t}async getChartToasts(){return null!==this._chartToastsPromise||(this._chartToastsPromise=async function(){return Promise.all([Promise.all([i.e(4343),i.e(69267),i.e(87556),i.e(90385),i.e(66875),i.e(53088)]).then(i.bind(i,78181)),Promise.all([i.e(87556),i.e(90385),i.e(66875),i.e(94291)]).then(i.bind(i,13830))]).then((e=>[e[0].ChartToasts,e[1].globalToasts]))}().then((e=>{const t=e[0],i=e[1];return new t(this._resizerBridge,this._resizerBridge.container.value(),i,this._bottomToolbarOffsetHeightProvider())}))),this._chartToastsPromise}}},406849:(e,t,i)=>{"use strict";i.d(t,{createTradeContext:()=>o});var s=i(650151);async function o(e,t){let i=NaN,o=NaN,r="";const n=e.proSymbol(),a=(e.symbolInfo()||{name:null}).name||n,l=e.priceScale();if(t){const s=e.firstValue();i=null!==s?l.coordinateToPrice(t,s):null,r=null!==i?e.formatter().format(i):""}const c=e.bars().last();null!==c&&(o=(0,s.ensure)(c.value[TradingView.CLOSE_PLOT]));return{symbol:n,displaySymbol:a,value:i,formattedValue:r,last:o,symbolInfoTradable:!!(e.symbolInfo()||{is_tradable:!1}).is_tradable}}},834075:(e,t,i)=>{"use strict";i.d(t,{isMobileTradingAvailable:()=>h,isMobileTradingAvailableInApp:()=>u});var s=i(638456),o=i(125226),r=i(314802),n=i(244842) ;const a=(0,o.isFeatureEnabled)("mobile_trading_ios")&&s.CheckMobile.iOS()&&(0,r.isOnMobileAppPage)("old"),l=(0,o.isFeatureEnabled)("mobile_trading_android")&&s.CheckMobile.Android()&&(0,r.isOnMobileAppPage)("new"),c=(0,o.isFeatureEnabled)("mobile_trading_web")&&s.CheckMobile.any()&&!s.CheckMobile.isIPad()&&(window.matchMedia("screen and (orientation: portrait) and (max-width: 567px)").matches||window.matchMedia("screen and (orientation: landscape) and (max-height: 567px)").matches)&&!(0,r.isOnMobileAppPage)("any"),d=n.enabled("mobile_trading")&&(a||l||c);function h(){return d}function u(){return a||l}},514315:(e,t,i)=>{"use strict";i.d(t,{updateThemeActions:()=>u});var s=i(444372),o=i(461794),r=i(345848),n=i(373571),a=i(167975),l=i(104436),c=i(67302);const d=["system","dark","light"],h={dark:s.t(null,void 0,i(40890)),light:s.t(null,void 0,i(950020)),system:s.t(null,void 0,i(980899))};async function u(e){const[t,u]=await Promise.all([i.e(83767).then(i.bind(i,429874)),i.e(83767).then(i.bind(i,867432))]),_=async _=>{let p=[];if((0,c.showThemeSwitcher)()){const i=t.getStdThemeNames(),s=t.getCurrentTheme().name;p=i.map((i=>{const a=new n.Action({actionId:"Chart.Theme.Apply",options:{name:"theme-switch-to-"+i,label:(0,o.clean)(t.translateStdThemeName(i)),checkable:!0,checked:s===i,onExecute:()=>{a.update({checked:!0}),t.loadTheme(e.chartWidgetCollection(),{themeName:i,standardTheme:!0}).then((()=>{e.readOnly()||window.saver.saveChartSilently(),(0,r.trackEvent)("GUI","Themes","Switch to "+i+" theme")}))}}});return a})),p.sort(((e,t)=>e.getLabel()>t.getLabel()?-1:1))}else if((0,c.showThemeAction)()&&window.TVD&&window.TVD.getThemeSetting){const e=await window.TVD.getThemeSetting();e&&(p=d.map((t=>{const i=new n.Action({actionId:"Chart.Theme.Apply",options:{name:"theme-switch-to-"+t,label:h[t],checkable:!0,checked:e===t,onExecute:()=>{i.update({checked:!0}),window.TVD&&window.TVD.setThemeSetting&&window.TVD.setThemeSetting(t)}}});return i})))}const m=[...p];if(window.is_authenticated){m.length&&m.push(new n.Separator);const t=new n.Action({actionId:"Chart.Theme.SaveAs",options:{name:"theme-save-as",label:(0,a.appendEllipsis)(s.t(null,void 0,i(309908))),onExecute:()=>u.showThemeSaveDialogAsync(e.model().model().theme())}});m.push(t)}_&&_.length&&window.is_authenticated&&(m.length&&m.push(new n.Separator),_.forEach((i=>{const s=new n.Action({actionId:"Chart.Theme.Apply.Custom",options:{label:(0,o.clean)(t.translateStdThemeName(i)),checkable:!1,onExecute:()=>{t.loadTheme(e.chartWidgetCollection(),{themeName:i,standardTheme:!1}).then((()=>{window.saver.saveChartSilently(),(0,r.trackEvent)("GUI","Switch to custom theme")}))},toolbox:{type:l.ToolboxType.Delete,action:()=>u.showRemoveThemeDialogAsync(i)},showToolboxOnHover:!0}});m.push(s)}))),e.actions().applyColorTheme.update({subItems:m})};window.is_authenticated?t.getThemeNames().then(_):_()}},360758:(e,t,i)=>{"use strict";i.d(t,{addPlusButtonProperty:()=>u,restoreAddPlusButtonSettingsValue:()=>_,showPlusButtonOnCursor:()=>d});var s=i(799786),o=(i(244842), i(62802)),r=i(152633),n=i(401580);const a="add_plus_button";function l(){const e=s.keyboardPressedKeysState.value();return void 0!==e&&(Boolean(e.modifiers&s.Modifiers.Alt&&e.modifiers&s.Modifiers.Mod)&&(void 0===e.code||e.altOrOptionCode()||e.controlOrMetaCode()))}const c=new n.WatchedValue(l());s.keyboardPressedKeysState.subscribe((()=>c.setValue(l())));const d=c.readonly();function h(){return o.getBool(a,!0)}const u=(0,r.createPrimitiveProperty)(h());function _(){u.setValue(!0),o.remove(a)}o.onSync.subscribe(null,(()=>u.setValue(h()))),u.subscribe(null,(()=>{o.setValue(a,u.value())}))},939243:(e,t,i)=>{"use strict";i.d(t,{getAlertColorLineByTheme:()=>y,getSettingsProperty:()=>f,restoreSettingsProperty:()=>b});var s=i(650151),o=i(822914),r=i(316230),n=i(852290),a=i(195294),l=i(62802),c=i(61499),d=i(354950),h=i(853965),u=i(42292);const _="alertLabels";let p;const m={visible:!0,showOnlyActive:!0,line:{color:"",visible:!0}},g=new Map([[c.StdTheme.Light,{line:{color:(0,a.getHexColorByName)("color-cold-gray-900")}}],[c.StdTheme.Dark,{line:{color:(0,a.getHexColorByName)("color-cold-gray-200")}}]]);function S(){let e=(0,l.getJSON)(_,null);if(null===e){const t=(0,u.defaults)("chartproperties");t&&t.alertsProperties&&t.alertsProperties.labels&&(e=t.alertsProperties.labels)}null===e&&(e=(0,o.default)(m));const t=(0,h.extractAllPropertiesKeys)(m),i=(0,h.extractAllPropertiesKeys)(e);if(!(0,r.default)(t,i)){const i=(0,h.extractState)(e,t);e=(0,n.default)((0,o.default)(m),i)}return e}function v(){p&&(0,l.setJSON)(_,p.state())}function f(){return p||(p=new d.Property(S()),p.listeners().subscribe(null,v),l.onSync.subscribe(null,(()=>{p.mergeAndFire(S())})),p)}function b(){p&&p.mergeAndFire(m)}function y(e){const t=e.dark().value()?c.StdTheme.Dark:c.StdTheme.Light;return(0,s.ensureDefined)(g.get(t)).line.color}},414592:(e,t,i)=>{"use strict";i.d(t,{ALERT_LABEL_WIDTH:()=>ae,AlertLabel:()=>he,isAlertLabel:()=>le});var s,o=i(650151),r=i(195294),n=i(678183),a=i(572230),l=i(996986),c=i(888929),d=i(354950),h=i(742391),u=i(223699),_=i(444331),p=i(964824),m=i(345848),g=i(939243),S=i(86441),v=i(444372),f=i(142119),b=i(315801),y=i(230058),C=i(953725),w=i(582665),P=i(458963),T=i(787123),M=i(9640),x=i(43192);!function(e){e[e.ConnectorOffsetFromIcon=28]="ConnectorOffsetFromIcon",e[e.ConnectorCircleRadius=4]="ConnectorCircleRadius",e[e.IconWidth=21]="IconWidth"}(s||(s={}));class I extends x.BitmapCoordinatesPaneRenderer{constructor(e){super(),this._data=e}hitTest(e,t){const i=(0,M.interactionTolerance)().line;for(let s=0;s=a&&e.x<=l)return new b.HitTestResult(b.HitTarget.MovePoint,{activeItem:s,hideCrosshairLinesOnHover:!0,areaName:b.AreaName.Line})}const o=this._data.levels.map((e=>e.y)),r=Math.min(...o),n=Math.max(...o),a=this._data.isLeft?Math.round(s.ConnectorOffsetFromIcon+s.IconWidth):Math.round(t.mediaSize.width-(s.ConnectorOffsetFromIcon+s.IconWidth)) ;if(Math.abs(a-e.x)=r&&e.y<=n){const t=o.reduce(((t,i,s)=>{const o=Math.abs(t.level-e.y);return Math.abs(i-e.y){const s=Math.round(i.y*e.verticalPixelRatio),[o,r]=this._calculateLeftRight(this._data,i,e.bitmapSize.width,e.horizontalPixelRatio);(0,T.drawHorizontalLine)(t,s,o,r)})),this._data.levels.length>1){const i=this._data.isLeft?Math.round((s.ConnectorOffsetFromIcon+s.IconWidth)*e.horizontalPixelRatio)+.5:Math.round(e.bitmapSize.width-(s.ConnectorOffsetFromIcon+s.IconWidth)*e.horizontalPixelRatio)+.5,o=this._data.levels.map((e=>e.y)),r=Math.min(...o),n=Math.max(...o);t.beginPath(),t.moveTo(i,r*e.verticalPixelRatio),t.lineTo(i,n*e.verticalPixelRatio),t.stroke();const a=Math.round(s.ConnectorCircleRadius*e.horizontalPixelRatio);(0,T.setLineStyle)(t,P.LINESTYLE_SOLID),t.fillStyle=this._data.connectorsBackColor,[r,n].forEach((s=>{const o=Math.round(s*e.verticalPixelRatio);t.beginPath(),t.arc(i,o,a,0,2*Math.PI,!0),t.fill(),t.stroke()}))}}_calculateLeftRight(e,t,i,o){const r=1===e.levels.length?0:Math.floor(s.ConnectorCircleRadius*o);let n,a;return this._data.isLeft?(a=0,n="full"===t.mode?i:"toConnector"===t.mode?Math.round((s.ConnectorOffsetFromIcon+s.IconWidth-r)*o):Math.round(this._data.distanceToTooltip*o)):(n="full"===t.mode?0:"toConnector"===t.mode?Math.round(i-(s.ConnectorOffsetFromIcon+s.IconWidth-r)*o):Math.round(i-this._data.distanceToTooltip*o),a=i),[n,a]}}var A=i(934026),L=i(199471),k=i(422333),E=i(511131),D=i(294162),B=i(674981),N=i(167975);const R=(0,E.makeFont)(12,k.CHART_FONT_FAMILY),O=new Path2D("M5 3.06574L10.9014 7L5 10.9343V3.06574ZM6 9.06574L9.09861 7L6 4.93426V9.06574ZM7 13C10.3137 13 13 10.3137 13 7C13 3.68629 10.3137 1 7 1C3.68629 1 1 3.68629 1 7C1 10.3137 3.68629 13 7 13ZM7 14C10.866 14 14 10.866 14 7C14 3.13401 10.866 0 7 0C3.13401 0 0 3.13401 0 7C0 10.866 3.13401 14 7 14Z"),V=" • ";class W extends x.BitmapCoordinatesPaneRenderer{constructor(){super(),this._data=null,this._lastPaintTextWidth=null,this._lastPaintPaneWidth=null,this._widthCache=new D.TextWidthCache}setData(e){this._data=e}hitTest(e){const t=this._data;if(null===this._lastPaintTextWidth||!t||null===this._lastPaintPaneWidth)return null;const i=this._lastPaintTextWidth+16+26,s=this._calculatePoint(t,i,this._lastPaintPaneWidth);{const o=new S.Point(s.x-26+i,s.y-9.5),r=o.add(new S.Point(26,19));if((0,A.pointInBox)(e,(0,S.box)(o,r)))return new b.HitTestResult(b.HitTarget.Custom,{activeItem:t.lineIndex,hideCrosshairLinesOnHover:!0,areaName:b.AreaName.Button,clickHandler:t.buttonAction,tapHandler:t.buttonAction})}{const o=new S.Point(s.x,s.y-9.5),r=o.add(new S.Point(i,19));if((0,A.pointInBox)(e,(0, S.box)(o,r)))return new b.HitTestResult(b.HitTarget.MovePoint,{activeItem:t.lineIndex,hideCrosshairLinesOnHover:!0,areaName:b.AreaName.Tooltip})}return null}_drawImpl(e){const t=this._data;if(!t)return;const i=e.context;this._lastPaintPaneWidth=e.mediaSize.width,i.font=R;const s=t.text,r=t.additionalText;let n=!1,a=null;r&&(this._lastPaintTextWidth=this._widthCache.measureText(i,s+V+r),a=this._tooltipSizes(e),n=a.contentWidth<=a.maxWidth);let l=s;if(!n&&(this._lastPaintTextWidth=this._widthCache.measureText(i,l),a=this._tooltipSizes(e),a.contentWidth>a.maxWidth)){l=function(e,t,i){const s=(0,B.lowerboundExt)((t=>e.substring(0,t)),t,((t,s)=>i(t===e?e:(0,N.appendEllipsis)(t))this._widthCache.measureText(i,e)))}const c=(0,o.ensureNotNull)(a).maxWidth,d=Math.round(c*e.horizontalPixelRatio),h=Math.round(19*e.verticalPixelRatio),u=this._calculatePoint(t,c,this._lastPaintPaneWidth);this._drawBorderAround(t,e,u,d,h,(e=>e.fill())),this._drawButton(t,e,u,d,h),this._drawText(t,e,u,l),n&&this._drawAdditionalText(t,e,u),this._drawBorderAround(t,e,u,d,h,(e=>e.stroke()))}_drawButton(e,t,i,s,o){const r=t.context;i=i.add(new S.Point(s/t.horizontalPixelRatio,0));{const s=Math.round((i.x-26)*t.horizontalPixelRatio)+.5,n=Math.round(i.y*t.verticalPixelRatio-.5*o)+.5;r.fillStyle=e.buttonBackColor,r.fillRect(s,n,26*t.horizontalPixelRatio,o),r.strokeStyle=e.buttonBorderColor,r.lineWidth=Math.max(1,Math.floor(t.verticalPixelRatio)),r.beginPath(),r.moveTo(s,n),r.lineTo(s,n+o),r.stroke()}0===e.buttonType?this._drawCloseButton(e,t,i):1===e.buttonType&&this._drawRestartButton(e,t,i)}_drawCloseButton(e,t,i){const s=t.context;s.strokeStyle=e.lineColor,s.beginPath();const o=Math.round((i.x-13-4+.5)*t.horizontalPixelRatio),r=Math.round((i.y-4+.5)*t.verticalPixelRatio),n=Math.round(8*t.horizontalPixelRatio),a=Math.round(8*t.verticalPixelRatio);s.moveTo(o,r),s.lineTo(o+n,r+a),s.moveTo(o,r+a),s.lineTo(o+n,r),s.stroke()}_drawRestartButton(e,t,i){const s=t.context,r=Math.round((i.x-26+6+.5)*t.horizontalPixelRatio),n=Math.round((i.y-7+.5)*t.verticalPixelRatio);s.save(),s.translate(r,n),s.scale(t.horizontalPixelRatio,t.verticalPixelRatio),s.fillStyle=(0,o.ensureDefined)(e.restartIconColor),s.fill(O,"evenodd"),s.restore()}_tooltipSizes(e){const t=(0,o.ensureNotNull)(this._lastPaintTextWidth)+16+26,i=Math.max(20,.9*(e.mediaSize.width-80));return{contentWidth:t,maxWidth:Math.min(t,i)}}_drawText(e,t,i,s){const o=t.context,r=Math.round((i.x+8)*t.horizontalPixelRatio),n=Math.round((i.y+5)*t.verticalPixelRatio);o.save(),o.translate(r,n),(0,L.drawScaled)(o,t.horizontalPixelRatio,t.verticalPixelRatio,(()=>{o.fillStyle=e.textColor,o.fillText(s,0,0)})),o.restore()}_drawAdditionalText(e,t,i){const s=t.context,r=Math.round(this._widthCache.measureText(s,e.text)*t.horizontalPixelRatio),n=Math.round(this._widthCache.measureText(s,V)*t.horizontalPixelRatio),a=Math.round((i.x+8)*t.horizontalPixelRatio)+r,l=Math.round((i.y+5)*t.verticalPixelRatio);s.save(),s.fillStyle=(0, o.ensureDefined)(e.additionalTextColor),s.translate(a,l),(0,L.drawScaled)(s,t.horizontalPixelRatio,t.verticalPixelRatio,(()=>{s.fillStyle=(0,o.ensureDefined)(e.textColor),s.fillText(V,0,0)})),s.translate(n,0),(0,L.drawScaled)(s,t.horizontalPixelRatio,t.verticalPixelRatio,(()=>{s.fillStyle=(0,o.ensureDefined)(e.additionalTextColor),s.fillText((0,o.ensureDefined)(e.additionalText),0,0)})),s.restore()}_drawBorderAround(e,t,i,s,o,r){const n=t.context,a=Math.round(i.x*t.horizontalPixelRatio)+.5,l=Math.round(i.y*t.verticalPixelRatio-o/2)+.5;n.strokeStyle=e.lineColor,n.lineWidth=Math.max(1,Math.floor(t.verticalPixelRatio));const c=Math.round(4*t.horizontalPixelRatio);n.fillStyle=e.backColor,n.beginPath(),(0,T.drawRoundRect)(n,a,l,s,o,c),r(n)}_calculatePoint(e,t,i){const s=e.point;if(e.center){const o=Math.max(0,.5*(i-t));return e.isLeft?ol.priceToCoordinate(e,a),d=[];if("channel"===r.type){const e=c(r.upper),t=c(r.lower);d.push(e),d.push(t)}else d.push(c(r.price));const h=i.isSelected(),u=i.isHovered(),_=this._model.lastHittestData(),p=this._model.lastSelectedHittestData();let m=0;u&&(m=null!==(e=null==_?void 0:_.activeItem)&&void 0!==e?e:0),h&&(m=null!==(t=null==p?void 0:p.activeItem)&&void 0!==t?t:0);const g=this._alertLabel.colors(),v=i.labelLineColor(),f=d.map(((e,t)=>({y:e,mode:i.drawHorzLine()?"full":t===m&&1===d.length?"toTooltip":"toConnector" }))),P=n.leftPriceScales().includes(l),T=1===d.length?F.NoLineModeOffsetSingleLine:F.NoLineModeOffsetMultipleLines,M={distanceToTooltip:T,levels:f,color:v,connectorsBackColor:g.connectorBackColor,iconBackgroundWithCorners:h||u,iconColor:g.iconColor,isLeft:P};if((i.drawHorzLine()||h||u)&&this._compositeRenderer.append(new I(M)),h){const e=n.height(),t=d.map((t=>this._model.backgroundColorAtYPercentFromTop(t/e))),i=P?F.SelectionPointOffset:n.width()-F.SelectionPointOffset,s={points:d.map((e=>new S.Point(i,e))),hittestResult:b.HitTarget.MovePoint,bgColors:t,visible:!0,barSpacing:this._model.timeScale().barSpacing()};this._compositeRenderer.append(new y.SelectionRenderer(s))}if((h||u)&&!this._alertLabel.isMoving()){const e=u&&(null==_?void 0:_.areaName)===b.AreaName.Button,t=P?T:n.width()-T,o=s.name()||(i.isMoving()?s.defaultDescription():s.description()),r=this._alertLabel.isInactive()?g.inActiveTextBaseColor:v,a=async()=>{const e=this._alertLabel.alert().id().value(),t=this._alertLabel.alert().isNew();e&&!t&&(await(0,C.getAlertsActionCreators)()).deleteAlert(e,{confirmation:(0,w.selectedRemoveConfirmation)([s]),analytics:{actionLabel:"Alert label source",actionSource:"Chart",event:"restart"}}).execute()},l=async()=>{const e=this._alertLabel.alert().id().value(),t=this._alertLabel.alert().isNew();e&&!t&&(await(0,C.getAlertsActionCreators)()).restartAlert(e,{analytics:{actionLabel:"Alert label source",actionSource:"Chart",event:"restart"}}).execute()},c=i.stopReason(),h=void 0!==c,p={isLeft:P,point:new S.Point(t,d[m]),lineIndex:m,center:i.drawHorzLine(),text:o,textColor:r,additionalText:Z(c),additionalTextColor:K(c,g),lineColor:v,backColor:g.connectorBackColor,buttonType:h?1:0,buttonBorderColor:g.tooltipButtonBorderColor,buttonBackColor:e?g.tooltipButtonBorderColorHovered:g.connectorBackColor,buttonAction:h?l:a,restartIconColor:h?g.restartIconColor:void 0,themeName:this._model.dark().value()?"dark":"light"};this._tooltipRenderer.setData(p),this._compositeRenderer.append(this._tooltipRenderer)}}}var $=i(246733),X=i(229765);class J{constructor(e){this._renderers=null!=e?e:[]}clear(){this._renderers=[]}add(e){this._renderers.push(e)}draw(e,t,i,s,o){for(const r of this._renderers)r.draw(e,t,i,s,o)}lastDrawnBodyBox(){let e=null;for(const t of this._renderers)if(t.lastDrawnBodyBox){const i=t.lastDrawnBodyBox();if(null!==i){if(null===e){e=i;continue}e=(0,S.box)((0,S.point)(Math.min(e.min.x,i.min.x),Math.min(e.min.y,i.min.y)),(0,S.point)(Math.max(e.max.x,i.max.x),Math.max(e.max.y,i.max.y)))}}return e}hitTest(e,t,i){var s,o;let r=null;for(let n=this._renderers.length-1;n>=0;n-=1){const a=null===(o=(s=this._renderers[n]).hitTest)||void 0===o?void 0:o.call(s,e,t,i);null!=a&&(null===r||a.target()>r.target())&&(r=a)}return r}topBottomTotalHeight(e){const t={top:0,bottom:0,total:0};for(const i of this._renderers){const s=i.topBottomTotalHeight(e);t.top=Math.max(t.top,s.top),t.bottom=Math.max(t.bottom,s.bottom),t.top=t.top+t.bottom}return t}setData(e,t){for(const i of this._renderers)i.setData(e,t)}}var Q=i(601183) ;const ee=new Path2D("M6.21 5.27 1.68 1.06A1 1 0 0 0 0 1.79v8.42a1 1 0 0 0 1.68.73l4.53-4.2a1 1 0 0 0 0-1.47Z");class te{constructor(){this._data=null,this._commonData=null,this._bodyBox=null}setData(e,t){this._data=e,this._commonData=t}lastDrawnBodyBox(){return this._bodyBox}draw(e,t,i,s,o){var r;const n=this._data,a=this._commonData;if(!n||!a)return;e.save(),e.fillStyle=null!==(r=n.backgroung)&&void 0!==r?r:a.background;const{horizontalPixelRatio:l,verticalPixelRatio:c,bitmapSize:d,mediaSize:h}=t,u="right"===o?d.width:0;e.translate(u,Math.round((a.coordinate-6.5+1)*c)),(0,L.drawScaled)(e,"right"===o?-l:l,c,(()=>{e.fill(ee)})),e.restore();const _="right"===o?h.width-7:0;this._bodyBox=(0,S.box)((0,S.point)(_,a.coordinate-6.5),(0,S.point)(_+7,a.coordinate+6.5))}topBottomTotalHeight(e){return{top:0,bottom:0,total:0}}hitTest(e,t,i){return this._data?(0,Q.hittestByData)(this._data,e):null}}var ie;!function(e){e[e.IconMinWidth=23]="IconMinWidth"}(ie||(ie={}));class se extends X.PriceAxisView{constructor(e,t){super(),this._collapsedAxisRenderer=new te,this._lastDrawnAxisBox=null,this._lastDrawnPaneBox=null,this._alertLabel=e,this._levelIndex=t,this._collapsedAxisRenderer.setData(this._axisRendererData,this._commonRendererData)}renderer(){return this._updateRendererDataIfNeeded(),this._rendererImpl()}ignoreAlignment(){return!0}_updateRendererData(e,t,i){var s,o,r,n,a,l;if(e.visible=!1,t.visible=!1,!this._alertLabel.labelVisible())return;const c=this._alertLabel.priceScale();if(!c)return;const d=c.mainSource(),h=null!==d?d.firstValue():null;if(c.isEmpty()||null===h)return;const u=this._alertLabel.priceOfLevel(this._levelIndex);if(null===u)return;const _=this._alertLabel.colors(),p=this._alertLabel.labelLineColor();i.background=(0,$.resetTransparency)(p),i.textColor=_.iconColor,i.coordinate=c.priceToCoordinate(u,h);const m=this._alertLabel.animation();if(null!==m){const e=m.data(performance.now());i.globalAlpha=e.alpha}else i.globalAlpha=void 0;e.text=c.formatPrice(u,h);const g=null!==(r=null===(o=(s=this._rendererImpl()).lastDrawnBodyBox)||void 0===o?void 0:o.call(s))&&void 0!==r?r:this._lastDrawnAxisBox;this._lastDrawnAxisBox=null!=g?g:this._lastDrawnAxisBox,this._lastDrawnAxisBox&&(e.hitTestData={hoverModelFromAxis:!0,itemBox:this._lastDrawnAxisBox,activeItem:this._levelIndex});const S=null!==(l=null===(a=(n=this._paneRenderer).lastDrawnBodyBox)||void 0===a?void 0:a.call(n))&&void 0!==l?l:this._lastDrawnPaneBox;this._lastDrawnPaneBox=null!=S?S:this._lastDrawnPaneBox,this._lastDrawnPaneBox&&(t.hitTestData={hoverModelFromAxis:!0,itemBox:this._lastDrawnPaneBox,activeItem:this._levelIndex}),t.hitTarget=b.HitTarget.MovePoint,e.hitTarget=b.HitTarget.Regular,t.labelIcon=1,t.labelIconMinWidth=ie.IconMinWidth,t.visible=!0,e.visible=!0}_rendererImpl(){return null===this._alertLabel.animation()?this._alertLabel.isHovered()||this._alertLabel.isSelected()?this._axisRenderer:this._collapsedAxisRenderer:new J([this._collapsedAxisRenderer,this._axisRenderer])}}var oe=i(81979) ;const re=c.sortSourcesPreOrdered.AlertLabel,ne=c.sortSourcesPreOrdered.AlertLabelInactive,ae=5;function le(e){return e instanceof he}const ce={newAlertColor:(0,r.getHexColorByName)("color-cold-gray-450"),inActiveAlertColor:(0,r.getHexColorByName)("color-cold-gray-600"),inActiveTextBaseColor:(0,r.getHexColorByName)("color-cold-gray-450"),inActiveTextManualColor:(0,r.getHexColorByName)("color-cold-gray-450"),inActiveTextTriggeredColor:(0,r.getHexColorByName)("color-tan-orange-500"),inActiveTextExpiredColor:(0,r.getHexColorByName)("color-ripe-red-500"),connectorBackColor:(0,r.getHexColorByName)("color-cold-gray-900"),iconColor:(0,r.getHexColorByName)("color-cold-gray-900"),restartIconColor:(0,r.getHexColorByName)("color-cold-gray-200"),tooltipButtonBorderColor:(0,r.getHexColorByName)("color-cold-gray-800"),tooltipButtonBorderColorHovered:(0,r.getHexColorByName)("color-cold-gray-800")},de={newAlertColor:(0,r.getHexColorByName)("color-cold-gray-450"),inActiveAlertColor:(0,r.getHexColorByName)("color-cold-gray-300"),inActiveTextBaseColor:(0,r.getHexColorByName)("color-cold-gray-550"),inActiveTextManualColor:(0,r.getHexColorByName)("color-cold-gray-550"),inActiveTextTriggeredColor:(0,r.getHexColorByName)("color-tan-orange-500"),inActiveTextExpiredColor:(0,r.getHexColorByName)("color-ripe-red-500"),connectorBackColor:(0,r.getHexColorByName)("color-white"),iconColor:(0,r.getHexColorByName)("color-white"),restartIconColor:(0,r.getHexColorByName)("color-cold-gray-900"),tooltipButtonBorderColor:(0,r.getHexColorByName)("color-cold-gray-100"),tooltipButtonBorderColorHovered:(0,r.getHexColorByName)("color-cold-gray-100")};class he extends l.DataSource{constructor(e,t,i,s){super(),this._priceAxisViews=[],this._paneLabelsPaneViews=[],this._propertyMock=new d.Property,this._startMovingPoint=null,this._currentMovingPoint=null,this._animation=null,this._onConditionChanged=()=>{const e=this.alert().condition(),t=e?"channel"===e.type?2:1:0;if(this._priceAxisViews.length!==t){for(let e=this._priceAxisViews.length;ee.updateSource(this))),this._active=t.active().spawn(),this._active.subscribe((()=>e.updateSource(this)))}destroy(){this._alertId.destroy(),this._isBeingEdited.destroy(),this._localFireTime.destroy(),this._active.destroy(),this._selected.destroy(),(0,g.getSettingsProperty)().unsubscribeAll(this),this._alert.onConditionChanged().unsubscribeAll(this),super.destroy()}model(){return this._model}zorder(){return this.isInactive()?ne:re}colors(){return{...this._themedColors(),lineColor:this.labelLineColor()}}alertOwnerSource(){return this._alertOwnerSource}alertSeriesId(){return this._alertSeriesId}alignCrossHairToMovePoint(){return!0}name(){return"AlertLabel"}isSpeciallyZOrderedSource(){return!0}stop(){this._alert.id().unsubscribe(this._resetUserEditEnabled),this._alert.isBeingEdited().unsubscribe(this._resetUserEditEnabled),this._alert.selected().unsubscribe(this._onAlertSelectedChanged)}alert(){return this._alert}isMoving(){return null!==this._startMovingPoint}isHovered(){return this===this._model.hoveredSource()}isSelected(){return this._model.selection().isSelected(this)}alertId(){return this.alert().id().value()}getAlert(){return Promise.resolve(this._alert)}getAlertSync(){return this._alert}priceOfLevel(e){const t=this.alert().condition();return t?"channel"===t.type?[t.upper,t.lower][e]:t.price:null}convertYCoordinateToPriceForMoving(e,t){const i=this.priceScale();if(!t||!i||i.isEmpty())return null;const s=t.firstValue();return null===s?null:i.coordinateToPrice(e,s)}isSynchronizable(){return!1}state(){const e=this.alert().condition(),t=[];return null!==e&&("channel"===e.type?(t.push({price:e.upper}),t.push({price:e.lower})):t.push({price:e.price})),{id:this._id,type:"AlertLabel",zorder:this.zorder(),points:t}}restorePoints(e){}createServerPoints(){}properties(){return this._propertyMock}paneViews(){return window.TradingView.printing||!this.labelVisible()?null:[this._paneView]}topPaneViews(){const e=performance.now();return null!==this._animation&&this._continueOrFinishAnimation(e),!window.TradingView.printing&&this.labelVisible()&&this._animationActive(e)?(this.updateAllViews((0,p.sourceChangeEvent)(this.id())),this._paneLabelsPaneViews):null}dataWindowView(){return null}priceAxisViews(e,t){return this.labelVisible()&&this.priceScale()===t&&!this._animationActive()&&this.canDrawLabelForAlert()?this._priceAxisViews:[]}topPriceAxisViews(e,t){const i=performance.now();return null!==this._animation&&this._continueOrFinishAnimation(i),this.priceScale()===t&&this._animationActive(i)&&this.canDrawLabelForAlert()?(this.updateAllViews((0,p.sourceChangeEvent)(this.id())),this._priceAxisViews):[]}updateAllViews(e){this._paneView.update(),this._priceAxisViews.forEach((t=>t.update(e))),this._paneLabelsPaneViews.forEach((t=>t.update(e)))}pointsCount(){return 0}title(){return this.alert().title()}movable(){ return!this._alert.isBeingEdited().value()&&!this._alert.isNew()}startMoving(e,t,i,s){this._userEditEnabled=!1,this._startMovingPoint=e,this.alert().startEditing()}move(e,t,i,s){if(!e.logical||null===t)return;const r=e.logical.price,n=this.alert(),a=(0,o.ensureNotNull)(n.condition());if(this._currentMovingPoint={...e},"channel"===a.type){let{upper:e,lower:i}=a;const s=this._alertOwnerSource.base()||100;0===t?(0,o.ensureDefined)(this._currentMovingPoint.logical).price=e=Math.max(r,i+1/s):1===t&&((0,o.ensureDefined)(this._currentMovingPoint.logical).price=i=Math.min(r,e-1/s)),n.setCondition({...a,lower:i,upper:e})}else n.setCondition({type:"price",price:r})}endMoving(){const e=this._startMovingPoint,t=this._currentMovingPoint;if(this._userEditEnabled=!0,this._startMovingPoint=null,this._currentMovingPoint=null,!e||!t||e===t)return;(0,m.trackEvent)("chart_alert","edit","move"),this._invokeAlertEditor({dataSourceHub:this._model,alert:this.alert(),type:"edit_alert",onEditCancel:()=>{setTimeout((async()=>{if(this.isInactive()){const e=this.alert().id().value();void 0!==e&&(await(0,C.getAlertsActionCreators)()).restartAlert(e,{analytics:{actionLabel:"Alert label source",actionSource:"Chart",event:"restart"}}).execute()}else this.alert().abortEditing();this._model.lightUpdate()}),0)},silent:!0,actionSource:"alert_label_move"})}currentMovingPoint(){return this._currentMovingPoint}showInObjectTree(){return!1}isRemovedByStudyTemplates(){return!1}isUserDeletable(){return!1}doesMovingAffectsUndo(){return!1}drawHorzLine(){return this.labelLineVisible()}canDrawLabelForAlert(){const e=this.alert(),t=this._model.mainSeries(),i=t&&t.properties().childs(),s=i&&i.style&&i.style.value(),o=(0,_.isRangeBasedStyle)(s)?s:null,r=e.crossInterval()||u.Interval.isEqual(e.resolution(),t.interval()),n=e.rangeBasedStyle()===o;return e.isPrice()&&r&&n}labelVisible(){const e=this._alertOwnerSource.symbolSource();if(e&&(e.isConvertedToOtherCurrency()||e.isConvertedToOtherUnit()))return!1;if(this._model.isInReplay().value())return!1;if(!this.isInactive())return(0,g.getSettingsProperty)().childs().visible.value();const t=this.stopReason();return void 0!==t&&(t===n.AlertStopReason.Created||this._animationActive()||!this.showOnlyActive())}labelLineColor(){const e=(0,g.getSettingsProperty)().childs().line.childs().color.value(),t=e||(0,g.getAlertColorLineByTheme)(this.model());if(null!==this._animation)return(0,o.ensureDefined)(t);const i=this._themedColors();return this._alert.isNew()?(0,o.ensureDefined)(i.newAlertColor):this._alert.active().value()||this._alert.stopReason()===n.AlertStopReason.Created?t:(0,o.ensureDefined)(i.inActiveAlertColor)}labelLineVisible(){return(0,g.getSettingsProperty)().childs().line.childs().visible.value()}showOnlyActive(){return(0,g.getSettingsProperty)().childs().showOnlyActive.value()}stopReason(){return this.isInactive()?this._alert.stopReason():void 0}animation(){return this._animation}isInactive(){return!this._alert.active().value()&&!this._alert.isNew()}_themedColors(){return this._model.dark().value()?ce:de} _resetUserEditEnabled(){const e=this._alert;this._userEditEnabled=!(e.isBeingEdited().value()||e.isNew()||!e.isPrice()||null===e.condition())}_onAlertSelectedChanged(e){this.canDrawLabelForAlert()&&(e?this._selectAlertLabel():this._unselectAlertLabel())}_selectAlertLabel(){this._model.selectionMacro((e=>{e.selection().isSelected(this)||(e.clearSelection(),e.addSourceToSelection(this))}))}_unselectAlertLabel(){this._model.selectionMacro((e=>{e.selection().isSelected(this)&&e.removeSourceFromSelection(this)}))}_onAlertFireTimeChanged(e){var t,i;null!==e&&(this._animation=(t=e,i=this.isHovered()||this.isSelected()?1:0,{finished:e=>e-t>=2400,data:e=>{const s=Math.min(e-t,2400)%1200,o=s%600,r=Math.round(s/1200),n=(0,oe.easingFunc.linear)(o/600);return{alpha:0===r==(0===i)?n:1-n}}}),this._model.updateSource(this))}_continueOrFinishAnimation(e){(0,o.ensureNotNull)(this._animation).finished(e)?(this._animation=null,this._model.updateSource(this)):this._model.invalidate(a.InvalidationMask.cursor())}_animationActive(e=performance.now()){return null!==this._animation&&!this._animation.finished(e)}}},108039:(e,t,i)=>{"use strict";i.d(t,{AppliedTimeFrame:()=>o});var s=i(938550);class o{constructor(e){this._appliedTimeFrame=new s.WatchedObject(null),this._appliedTimeFrameInfo=null,this._appliedTimeFrameChangedBound=this._appliedTimeFrameChanged.bind(this),this._model=e,e.mainSeries().dataEvents().seriesTimeFrame().subscribe(this,this._onSeriesTimeFrame),this._appliedTimeFrame.subscribe(this._appliedTimeFrameChangedBound)}destroy(){this._appliedTimeFrame.unsubscribe(this._appliedTimeFrameChangedBound),this._model.timeScale().logicalRangeChanged().unsubscribeAll(this),this._model.mainSeries().dataEvents().seriesTimeFrame().unsubscribeAll(this)}appliedTimeFrame(){return this._appliedTimeFrame}_appliedTimeFrameChanged(){this._model.timeScale().logicalRangeChanged().unsubscribe(this,this._invalidateAppliedTimeFrame)}_onSeriesTimeFrame(e,t,i,s){if(s){const e=this._model.timeScale();this._appliedTimeFrameInfo={logicalRange:e.logicalRange(),baseIndex:e.baseIndex()},e.logicalRangeChanged().subscribe(this,this._invalidateAppliedTimeFrame)}}_invalidateAppliedTimeFrame(){if(null===this._appliedTimeFrameInfo)return;const e=this._model.timeScale(),t=e.logicalRange(),i=e.baseIndex(),s=this._appliedTimeFrameInfo.logicalRange,o=this._appliedTimeFrameInfo.baseIndex;(null===t||null===s||Math.abs(i-t.left()-(o-s.left()))>=.01||Math.abs(i-t.right()-(o-s.right()))>=.01)&&this._appliedTimeFrame.setValue(null)}}},155964:(e,t,i)=>{"use strict";i.d(t,{defaultsPreferencesByWhiteList:()=>D,preferencesByWhiteList:()=>E});var s=i(389137),o=i(507795),r=i(488530),n=i(201089),a=i(909598),l=i(42292),c=i(530239),d=i(329806),h=i(792795),u=i(195294);const _={visible:!1,lineStyle:i(458963).LINESTYLE_DOTTED,lineWidth:1,bidLineColor:u.colorsPalette["color-tv-blue-500"],askLineColor:u.colorsPalette["color-ripe-red-400"]};var p=i(993171),m=i(138839),g=i(490515);const S={...r.candleStylePreferencesDefault,deltaAdjust:!0,showSummary:!0, type:m.VolumeFootprintTypeValues.BuyAndSell,pointOfControl:!0,bgColors:(0,g.getBgColorsDefaults)(),imbalanceHighlight:{buyColor:(0,u.getHexColorByName)("color-minty-green-500"),sellColor:(0,u.getHexColorByName)("color-ripe-red-500"),visible:!0},inputs:{rowSize:"Auto",atrLength:14,imbalancePercent:300,ticksPerRow:100,showVA:!0,vaPercent:70,calcStackedImbalance:!1,stackedImbalanceCount:3}};var v=i(70843),f=i(881861);const b=(0,n.getLogger)("Chart.ApplyPreferencesToAllCharts"),y={color:"",style:0},C={autoScale:!1,autoScaleDisabled:!1,lockScale:!1,percentage:!1,percentageDisabled:!1,log:!1,logDisabled:!1,alignLabels:!1,isInverted:!1,indexedTo100:!1},w={backgroundType:h.ColorType.Solid,background:"",backgroundGradientStartColor:"",backgroundGradientEndColor:"",topMargin:0,bottomMargin:0,rightOffset:0,gridLinesMode:"both",horzGridProperties:(0,d.deepExtend)({},y),vertGridProperties:(0,d.deepExtend)({},y),crossHairProperties:(0,d.deepExtend)({},{color:"",style:0,transparency:0,width:0}),legendProperties:(0,d.deepExtend)({},{showStudyArguments:!1,showStudyTitles:!1,showStudyValues:!1,showSeriesTitle:!1,showSeriesOHLC:!1,showLegend:!1,showLastDayChange:!1,showBarChange:!0,showVolume:!1,showPriceSource:!1,showBackground:!0,backgroundTransparency:0,showLogo:!0}),axisProperties:(0,d.deepExtend)({},C),separatorColor:""},P={lineColor:"",textColor:"",fontSize:0,scaleSeriesOnly:!1,showSeriesLastValue:!1,seriesLastValueMode:a.PriceAxisLastValueMode.LastValueAccordingToScale,showSeriesPrevCloseValue:!1,showStudyLastValue:!1,showSymbolLabels:!1,showStudyPlotLabels:!1,showBidAskLabels:!1,showPrePostMarketPriceLabel:!0,showFundamentalLastValue:!1,showFundamentalNameLabel:!1,showPriceScaleCrosshairLabel:!0,showTimeScaleCrosshairLabel:!0},T={...P},M={visible:!1,futureOnly:!1,breaks:(0,d.deepExtend)({},{color:"",visible:!1,style:0,width:0})},x={style:0,minTick:"",showPriceLine:!1,priceLineWidth:0,priceLineColor:"",baseLineColor:"",showPrevClosePriceLine:!1,showCountdown:!0,prevClosePriceLineWidth:0,sessionId:"regular",prevClosePriceLineColor:"",esdShowDividends:!1,esdShowSplits:!1,esdShowEarnings:!1,esdShowBreaks:!1,showContinuousContractSwitches:!1,showContinuousContractSwitchesBreaks:!1,showFuturesContractExpiration:!1,showLastNews:!1,dividendsAdjustment:!1,backAdjustment:!1,settlementAsClose:!0,statusViewStyle:(0,d.deepExtend)({},{fontSize:16,showExchange:!0,showInterval:!0,symbolTextSource:"description"}),priceAxisProperties:(0,d.deepExtend)({},C),bidAsk:(0,d.deepExtend)({},_),prePostMarket:(0,d.deepExtend)({},p.defaultPrePostMarketPreferences),volFootprintStyle:(0,d.deepExtend)({},S),tpoStyle:(0,d.deepExtend)({},v.tpoStylePreferencesDefault),volCandlesStyle:(0,d.deepExtend)({},r.candleStylePreferencesDefault),svpStyle:(0,d.deepExtend)({},f.svpStylePreferencesDefault),highLowAvgPrice:(0,d.deepExtend)({},{highLowPriceLinesVisible:!1,highLowPriceLabelsVisible:!1,averageClosePriceLabelVisible:!1,averageClosePriceLineVisible:!1,highLowPriceLinesColor:"",highLowPriceLinesWidth:0,averagePriceLineColor:"",averagePriceLineWidth:0}), candleStyle:(0,d.deepExtend)({},r.candleStylePreferencesDefault),hollowCandleStyle:(0,d.deepExtend)({},r.hollowCandlePreferencesStyleDefault),barStyle:(0,d.deepExtend)({},r.barStylePreferencesDefault),lineStyle:(0,d.deepExtend)({},r.lineStyleDefault),lineWithMarkersStyle:(0,d.deepExtend)({},r.lineStyleDefault),steplineStyle:(0,d.deepExtend)({},r.lineStyleDefault),areaStyle:(0,d.deepExtend)({},r.areaStylePreferencesDefault),hlcAreaStyle:(0,d.deepExtend)({},r.hlcAreaStylePreferencesDefault),baselineStyle:(0,d.deepExtend)({},r.baselineStylePreferencesDefault),hiloStyle:(0,d.deepExtend)({},r.hiloStylePreferencesDefault),haStyle:(0,d.deepExtend)({},r.haStylePreferencesDefault),renkoStyle:(0,d.deepExtend)({},r.renkoStylePreferencesDefault),pbStyle:(0,d.deepExtend)({},r.pbStylePreferencesDefault),kagiStyle:(0,d.deepExtend)({},r.kagiStylePreferencesDefault),pnfStyle:(0,d.deepExtend)({},r.pnfStylePreferencesDefault),rangeStyle:(0,d.deepExtend)({},r.rangeStylePreferencesDefault),columnStyle:(0,d.deepExtend)({},r.columnStylePreferencesDefault)},I={priceScaleSelectionStrategyName:"auto",timeScale:(0,d.deepExtend)({},{defaultRightOffset:0,defaultRightOffsetPercentage:5,usePercentageRightOffset:!1}),mainSeries:(0,d.deepExtend)({},x),sessions:(0,d.deepExtend)({},c.sessionsPreferencesDefault),paneProperties:(0,d.deepExtend)({},w),chartEventsSourceProperties:(0,d.deepExtend)({},M),tradingProperties:(0,d.deepExtend)({},o.tradingPreferencesDefault)},A={timezone:"",scalesProperties:(0,d.deepExtend)({},T),...I},L={scalesProperties:(0,d.deepExtend)({},P),...I};function k(e,t,i,o,r=!0){if(void 0===t[e])return b.logDebug(`We haven't had this property ${o}.${e} yet, please, remove it from whiteList`),null;if((0,s.isObject)(i[e])){const s=Object.keys(i[e]);let n="";return s.map((s=>({[s]:k(s,t[e],i[e],`${o}.${e}`,r)}))).reduce(((e,t)=>(n=Object.keys(t)[0],e[n]=t[n],e)),{})}return r?t[e].value():t[e]}function E(e,t,i=A){const s={timezone:"",priceScaleSelectionStrategyName:"auto",timeScale:{defaultRightOffset:e.timeScale().defaultRightOffset().value(),defaultRightOffsetPercentage:e.timeScale().defaultRightOffsetPercentage().value(),usePercentageRightOffset:e.timeScale().usePercentageRightOffset().value()},mainSeries:{},sessions:{},paneProperties:{},scalesProperties:{},chartEventsSourceProperties:{},tradingProperties:{}},o=["timeScale","mainSeries","sessions"],r=i.mainSeries,n=Object.keys(i),a=Object.keys(r),l=t.properties(),c=e.properties(),d=i.sessions,h=Object.keys(d),u=e.sessions().properties();return a.forEach((e=>{s.mainSeries[e]=k(e,l,r,"mainSeries")})),h.forEach((e=>{s.sessions[e]=k(e,u,d,"sessions")})),n.forEach((e=>{o.includes(e)||(s[e]=k(e,c,i,"preferences"))})),s}function D(e,t,i=L,s=!0){const o={timeScale:{defaultRightOffset:e.timeScale().rightOffsetDefaultValue(),defaultRightOffsetPercentage:e.timeScale().defaultRightOffsetPercentage().value(),usePercentageRightOffset:e.timeScale().usePercentageRightOffset().value()},mainSeries:{},sessions:(0,d.deepExtend)({},c.sessionsPreferencesDefault),paneProperties:{},scalesProperties:{}, chartEventsSourceProperties:{},tradingProperties:{},priceScaleSelectionStrategyName:"auto"},r=["timeScale","mainSeries","sessions"],n=i.mainSeries,a=Object.keys(i),h=Object.keys(n),u=(0,l.factoryDefaults)("chartproperties.mainSeriesProperties"),_=(0,l.factoryDefaults)("chartproperties");return h.forEach((e=>{s&&"style"===e||(o.mainSeries[e]=k(e,u,n,"mainSeries",!1))})),a.forEach((e=>{r.includes(e)||(o[e]=k(e,_,i,"preferences",!1))})),o}},480059:(e,t,i)=>{"use strict";i.d(t,{autoLogButtonsVisibilityOptions:()=>r,autoLogButtonsVisibilityProperty:()=>o,restoreAutoLogButtonsVisibilitySettingsValue:()=>n});var s=i(87053);const{property:o,availableValues:r,restoreDefaultValue:n}=(0,s.createVisibilityController)("PriceAxisAutoLogButtons.visibility")},838042:(e,t,i)=>{"use strict";i.d(t,{BarsMarksContainer:()=>m});var s=i(650151),o=i(201089),r=i(62802),n=i.n(r),a=i(244842),l=i(223699),c=i(389137),d=i(444331),h=i(996986),u=i(964824);const _=(0,o.getLogger)("Chart.BarsMarksContainer"),p=Math.round(new Date(2037,0,1).getTime()/1e3);class m extends h.DataSource{constructor(e,t,i){const o=e.onWidget();let r;r=o?!e.hideIdeas():!!a.enabled("bars_marks")&&n().getBool("BarsMarksContainer.visibile",!1),t.merge({visible:r}),t.childs().visible.subscribe(null,(t=>{o||e.isSnapshot()||!a.enabled("bars_marks")||n().setValue("BarsMarksContainer.visibile",!!t.value())})),super(i),this._paneViews=[],this._model=e,this._properties=t,this._requests=[],this._marks={},this._loadedRange=null,this._getDataTimeout=null,this._collectedRange=null,this._lastRange=null;const l=this._model.mainSeries();l.onSymbolIntervalChanged().subscribe(this,this.clearMarks),l.dataEvents().symbolResolved().subscribe(this,this.clearMarks),l.dataEvents().completed().subscribe(this,(()=>{var e,t;const i=l.data();if(0===i.size())return;const o=(0,s.ensureNotNull)(i.first()).index,r=(0,s.ensureNotNull)(i.last()).index,n=this.timeScale();this.getData({start:null!==(e=n.indexToTimePoint(o))&&void 0!==e?e:1/0,end:null!==(t=n.indexToTimePoint(r))&&void 0!==t?t:-1/0})})),this._initialize(),this._pinnedTooltips={}}destroy(){const e=this._model.mainSeries();e.onSymbolIntervalChanged().unsubscribeAll(this),e.dataEvents().symbolResolved().unsubscribeAll(this),e.dataEvents().completed().unsubscribeAll(this),super.destroy()}properties(){return this._properties}marks(){return this._marks}pinTooltip(e,t){this._pinnedTooltips[e]=t}timeScale(){return this._model.timeScale()}getIntervalInTicks(){const e=this._model.mainSeries().properties().childs().interval.value(),t=l.Interval.parse(e);if(!t.isValid())throw new TypeError("Unexpected interval");return t.isRange()?60:t.inMilliseconds()/1e3}getVisibleTickMarksRange(){var e,t;if(this.timeScale().isEmpty())return{start:0,end:0};const i=(0,s.ensureNotNull)(this.timeScale().visibleBarsStrictRange()),{firstIndex:o,lastIndex:r}=(0,s.ensureNotNull)(this.timeScale().points().range().value());if(!(i.lastBar()>o&&i.firstBar(){var o,r;const n=this._marks[s],a=n.tickmark;a>=(null!==(o=t.start)&&void 0!==o?o:1/0)&&a<=(null!==(r=t.end)&&void 0!==r?r:-1/0)+i&&e.push(n)})),e}getPublishedPlates(){const e={};return window.is_authenticated?(this.getVisibleRangePlates().forEach((t=>{t.is_public&&(this._pinnedTooltips[t.id]||t.user__id===window.user.id)&&(e[t.id]=t)})),e):e}filterDisplayedPlates(e){const t=e.reduce(((e,t)=>{const i=this._getIndex(t.tickmark);return null!==i&&(e[i]=e[i]||[],e[i].push(t)),e}),{});return Object.keys(t).reduce(((e,i)=>{let s=t[i];return s=s.sort(((e,t)=>t.views_count-e.views_count)),s=s.slice(0,10),e.concat(s)}),[])}getPlatesViewData(){var e,t,i;const o=this._model.mainSeries();if(o.data().isEmpty())return[];const r=(0,d.isPriceSourceStyle)(o.style())?o.barFunction():null,n=this.filterDisplayedPlates(this.getVisibleRangePlates()),a={},l=null!==(e=this._model.lastHittestData())&&void 0!==e?e:this._model.lastSelectedHittestData();let c=null;null!==l&&this._model.hoveredSource()===this&&(c=null!==(t=l.activeItem)&&void 0!==t?t:null);const h=[];for(const e of n){const t=(0,s.ensureNotNull)(this._getIndex(e.tickmark)),i=this._getBar(t);if(null===i)continue;const o=this._layout(e.direction),n=this._theme(e.direction),l=c===e.id,d=this.timeScale().indexToCoordinate(t),u=this._offset(o,i,r),_=(0,s.ensureNotNull)(this.priceScale()).isInverted();let p=0;t in a||(a[t]={up:0,down:0}),p=a[t][o]++,h.push({id:e.id,x:d,y:u,yInverted:_,order:p,direction:o,theme:n,hovered:l,pinned:!0===this._pinnedTooltips[e.id],user__id:e.user__id,label:e.label,labelFontColor:e.labelFontColor||"#444",minSize:e.minSize||5,...this._plateViewData(e)})}const u=h.filter((e=>!0===e.hovered));for(let e=0;ee.hovered&&!t.hovered?1:0)),h}priceAxisViews(){return null}updateAllViews(e){for(const t of this._paneViews)t.update(e)}updateAllViewsAndRepaint(){this.updateAllViews((0,u.sourceChangeEvent)(this.id())),this._model.updateSource(this)}roundRange(e){return{start:Math.round(e.start),end:Math.round(e.end)}}refreshData(){null!==this._lastRange&&this.getData(this._lastRange)}getData(e){(0,c.isNumber)(e.start)&&(0,c.isNumber)(e.end)?(this._lastRange=e,e.end=p,this._pushGetDataStack(Object.assign({},e))):_.logError("Wrong range")}clearMarks(){this._abortAllRequests(),this._marks={},this._loadedRange=null}isUserDeletable(){return!1}isSavedInChart(e){return!1}isSpeciallyZOrderedSource(){return!0}showInObjectTree(){return!1}_plateViewData(e){return{}}_layout(e){switch(e){default:case 0:case 2:case 3:case 4:case 5:case 6:return"up";case 1:return"down"}}_theme(e){switch(e){default:case 0:return"neutral";case 1:case 5:return"green";case 2:case 6: return"red";case 3:return"yellow";case 4:return"blue"}}_offset(e,t,i){let o;switch(e){default:case"up":o=null===i?t[2]:i(t);break;case"down":o=null===i?t[3]:i(t)}return(0,s.ensureNotNull)(this.priceScale()).priceToCoordinate(o,(0,s.ensureNotNull)((0,s.ensureNotNull)(this.ownerSource()).firstValue()))}_getIndex(e){return this.timeScale().timePointToIndex(e)}_getBar(e){return this._model.mainSeries().data().valueAt(e)}_rangeDifference(e){return e=Object.assign({start:1/0,end:-1/0},e),this._loadedRange&&(e.startthis._loadedRange.end&&(e.start=this._loadedRange.end)),e}_rangeUnion(e,t){return e=Object.assign({start:1/0,end:-1/0},e),t&&(e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end)),e}_pushGetDataStack(e){(0,c.isNumber)(e.start)&&(0,c.isNumber)(e.end)?(this._getDataTimeout&&clearTimeout(this._getDataTimeout),this._collectedRange=this._rangeUnion(e,this._collectedRange),this._getDataTimeout=setTimeout((()=>{this._getData(this._collectedRange),this._getDataTimeout=this._collectedRange=null}),300)):_.logError("Wrong tickmark range")}_abortAllRequests(){this._requests.forEach((e=>{e.cancel()})),this._requests=[],this._getDataTimeout&&clearTimeout(this._getDataTimeout),this._getDataTimeout=this._collectedRange=null}}},384874:(e,t,i)=>{"use strict";i.d(t,{BarsRange:()=>o});var s=i(650151);class o{constructor(e,t){(0,s.assert)(e<=t,"The last bar in the bars range should be greater than or equal to the first bar"),this._firstBar=e,this._lastBar=t}firstBar(){return this._firstBar}lastBar(){return this._lastBar}count(){return this._lastBar-this._firstBar+1}contains(e){return this._firstBar<=e&&e<=this._lastBar}equals(e){return this._firstBar===e.firstBar()&&this._lastBar===e.lastBar()}static compare(e,t){return null===e||null===t?e===t:e.equals(t)}}},447285:(e,t,i)=>{"use strict";var s;i.d(t,{ChartEventsSourceId:()=>s}),function(e){e.Value="ChartEventsSource"}(s||(s={}))},890165:(e,t,i)=>{"use strict";i.d(t,{ChartModelBase:()=>ho});var s=i(12481),o=i(343370),r=i(822914),n=i(650151),a=i(86441),l=i(724377),c=i(195294),d=i(444372),h=i(331633),u=i(429874),_=i(345848),p=i(268222),m=i(251954),g=i(49437),S=i(623551),v=i(507795),f=i(913984),b=i(674981),y=i(414592),C=i(713473);function w(e){return(0,C.isLineTool)(e)&&e.boundToSymbol()||(0,y.isAlertLabel)(e)}class P{constructor(){this._items=[],this._set=new Set,this._dataSourcesCache=null,this._customSourcesCache=null,this._lineSourcesCache=null}isEmpty(){return 0===this._items.length}add(e){if(this._items.length>0&&!w(this._items[0])&&this.clear(),w(e)){const t=(0,b.lowerbound)(this._items,e,((e,t)=>e.zorder()!(0,f.isDataSource)(e)))),this._customSourcesCache}checkLineToolSelection(){this._items.forEach((e=>(0,C.isLineTool)(e)&&e.calcIsActualSymbol())),this._items=this._items.filter((e=>!(0,C.isLineTool)(e)||e.isActualSymbol())),this._invalidateCache()}remove(e){this._items=this._items.filter((t=>t!==e)),this._set.delete(e),this._invalidateCache()}clear(){this._items=[],this._set.clear(),this._invalidateCache()}_invalidateCache(){this._customSourcesCache=null,this._dataSourcesCache=null,this._lineSourcesCache=null}}var T=i(62745),M=i(306682),x=i(470452),I=i(223699),A=i(853965),L=i(354950),k=i(511131),E=i(422333);class D{constructor(e){this._rendererOptions={borderSize:1,additionalPaddingInner:0,fontSize:NaN,font:"",color:"",paneBackgroundColor:"",paddingBottom:0,paddingInner:0,paddingOuter:0,paddingTop:0,lineSpacing:0},this._chartModel=e}options(){const e=this._rendererOptions,t=this._chartModel.properties().childs(),i=t.scalesProperties.childs().fontSize.value();return e.fontSize!==i&&(e.fontSize=i,e.font=(0,k.makeFont)(i,E.CHART_FONT_FAMILY,""),e.paddingTop=i/12*2.5,e.paddingBottom=i/12*2.5,e.paddingInner=i/12*4,e.additionalPaddingInner=i/12*4,e.paddingOuter=i/12*4,e.lineSpacing=i/12*2),e.color=t.scalesProperties.childs().textColor.value(),e.paneBackgroundColor=t.paneProperties.childs().background.value(),this._rendererOptions}}var B=i(347710),N=i(526075),R=i(405721),O=i(484812),V=i(624444),W=i(42292),F=i(949529),H=i(244842),z=i(444331),U=i(530239),G=i(964824);const q=new V.PriceFormatter,j="sessions";class Z extends F.CustomSourceBase{constructor(e,t,i){super(e,t),this._studySource=null,this._paneViews=[],this._metaInfo=null,this._destroyed=!1,this._isStarted=!1,this._loadedGraphics=null,this._doubleClickHandler=i,this._properties=new A.DefaultProperty({defaultName:"sessions"}),(0,W.applyDefaultsOverrides)(this._properties.childs().graphics,void 0,!1,j),this._removeDuplicateProperties(),this._properties.subscribe(this,this._onPropertiesChanged),this._requestAndProcessMetaInfo(),t.timeScale().onReset().subscribe(this,this._clearData),t.timeScale().logicalRangeChanged().subscribe(this,this.updateAllViews.bind(this,(0,G.viewportChangeEvent)())),t.mainSeries().sessionIdProxyProperty().subscribe(this,this._updateVisibleOfPreAndPostMarketBackground),t.mainSeries().properties().childs().interval.subscribe(this,this._processHibernate),this._updateVisibleOfPreAndPostMarketBackground(t.mainSeries().properties().childs().sessionId)}applyOverrides(e){(0,W.applyPropertiesOverrides)(this._properties.childs().graphics,void 0,!1,e,j),this._model.updateSource(this)}start(){this._isStarted=!0,this._processHibernate()}restart(){this._clearData(),H.enabled("stop_study_on_restart")&&this.stop(),this.start()}isStarted(){return this._isStarted}stop(){this._isStarted=!1, null!==this._studySource&&this._studySource.stop()}isHoveredEnabled(){return!1}paneViews(e){return this._paneViews}updateAllViews(e){this._paneViews.forEach((t=>t.update(e)))}updateViewsForPane(e,t){this.updateAllViews(t)}destroy(){this._destroyed=!0,null!==this._studySource&&(this._studySource.dataCleared().unsubscribeAll(this),this._studySource.dataUpdated().unsubscribeAll(this),this._studySource.destroy(),this._studySource=null),this._model.timeScale().logicalRangeChanged().unsubscribeAll(this),this._model.timeScale().onReset().unsubscribeAll(this),this._model.mainSeries().sessionIdProxyProperty().unsubscribeAll(this),this._model.mainSeries().properties().childs().interval.unsubscribeAll(this),this._properties.unsubscribeAll(this)}series(){return this._model.mainSeries()}priceScale(){return this.series().priceScale()}graphics(){return this._loadedGraphics||(0,n.ensureNotNull)(this._studySource).graphics()}valueAt(e,t){return null}properties(){return this._properties}graphicsInfo(){return(0,n.ensureNotNull)(this._metaInfo).graphics}firstValue(e){return this._model.mainSeries().firstValue()}formatter(){return q}state(e){const t={properties:this._properties.state()};return e&&null!==this._metaInfo&&(t.data={graphics:(0,O.saveStudyGraphics)(this.graphics(),this._model.timeScale().visibleBarsStrictRange()),metaInfo:this._metaInfo.state()}),t}restoreState(e,t){const i=e.properties;this._migrateOutOfSessionProperty(i),this._properties.mergeAndFire(i),this._removeDuplicateProperties(),this._updateVisibleOfPreAndPostMarketBackground(this._model.mainSeries().properties().childs().sessionId),void 0!==e.data&&t&&(this._loadStudyGraphics(e.data.graphics),this._setMetaInfo(new N.StudyMetaInfo(e.data.metaInfo)),this._createPaneViews())}restoreOldState(e,t){const i={properties:{graphics:e.state.graphics}};void 0!==e.data&&void 0!==e.metaInfo&&t&&(i.data={metaInfo:e.metaInfo,graphics:e.data.graphics}),this.restoreState(i,t)}applyPreferences(e){this._properties.mergePreferences(e)}metaInfo(){return(0,n.ensureNotNull)(this._metaInfo)}async _requestAndProcessMetaInfo(){if(this._model.isSnapshot())return;const e=await(0,B.studyMetaInfoRepository)().findById({type:"java",studyId:"Sessions@tv-basicstudies"});this._destroyed||null===this._loadedGraphics&&(this._setMetaInfo(e),null!==this._metaInfo&&(this._studySource=new R.StudyDataSource(this._model.chartApi(),this._model.mainSeries().seriesSource(),"sessions_",this._metaInfo),this._createPaneViews(),this._studySource.dataCleared().subscribe(this,this.updateAllViews.bind(this,(0,G.sourceChangeEvent)(this.id()))),this._studySource.dataUpdated().subscribe(this,this.updateAllViews.bind(this,(0,G.sourceChangeEvent)(this.id()))),this._studySource.setInputs({}),this._processHibernate()))}_loadStudyGraphics(e){const t=e.backgrounds;if(void 0!==t){const e=t.findIndex((e=>"inSession"===e.styleId));-1!==e&&t.splice(e,1)}this._loadedGraphics=(0,O.loadStudyGraphics)(e)}_setMetaInfo(e){const t=e.graphics.backgrounds;void 0!==t&&void 0!==t.inSession&&delete t.inSession,this._metaInfo=e} _updateVisibleOfPreAndPostMarketBackground(e){const t=!(0,z.isRegularSessionId)(e.value());this._outOfSessionVisibilityProperty().setValue(t),this._preMarketVisibilityProperty().setValue(t),this._postMarketVisibilityProperty().setValue(t)}_clearData(){null!==this._studySource&&this._studySource.clearData()}_createPaneViews(){const e={doubleClickHandler:this._doubleClickHandler};(0,O.createGraphicsPaneViews)(this,this._model,e).then((e=>{this._paneViews=e.regularPaneViews,this._model.lightUpdate()}))}_onPropertiesChanged(){this._processHibernate(),this.updateAllViews((0,G.sourceChangeEvent)(this.id()))}_processHibernate(){if(null!==this._studySource){const e=this._canBeHibernated(),t=this._isHibernated(),i=this._studySource.isStarted();!t&&e&&i?this._studySource.stop():!t||e||i||this._studySource.start()}}_canBeHibernated(){const e=this._model.mainSeries(),t=this._preMarketVisibilityProperty().value()&&this._postMarketVisibilityProperty().value()&&this._outOfSessionVisibilityProperty().value();return e.isDWM()||!t&&!this._vertLinesVisibleProperty().value()}_isHibernated(){return this._isStarted&&(null===this._studySource||!this._studySource.isStarted())}_outOfSessionVisibilityProperty(){return this._properties.childs().graphics.childs().backgrounds.childs().outOfSession.childs().visible}_preMarketVisibilityProperty(){return this._properties.childs().graphics.childs().backgrounds.childs().preMarket.childs().visible}_postMarketVisibilityProperty(){return this._properties.childs().graphics.childs().backgrounds.childs().postMarket.childs().visible}_vertLinesVisibleProperty(){return this._properties.childs().graphics.childs().vertlines.childs().sessBreaks.childs().visible}_removeDuplicateProperties(){this._properties.hasChild("properties")&&(this._properties.removeProperty("properties"),(0,A.allowSavingDefaults)(!0),this._properties.childChanged(null,""),(0,A.allowSavingDefaults)(!1))}_migrateOutOfSessionProperty(e){const t=e.graphics.backgrounds;if(void 0!==t){const i=t.outOfSession;i.color===(0,n.ensureDefined)(U.sessionsPreferencesDefault.graphics.backgrounds).outOfSession.color||"postMarket"in t||(e.graphics.backgrounds={...t,postMarket:{color:i.color,transparency:i.transparency,visible:i.visible},preMarket:{color:i.color,transparency:i.transparency,visible:i.visible}})}}}var K=i(238433),Y=i(707957),$=i(401580),X=i(938550),J=i(572230),Q=i(261066),ee=i(480059),te=i(895171),ie=i(62802);const se="symbolWatermark",oe={visibility:!1,color:"rgba(80, 83, 94, 0.25)"};function re(){const e=ie.getJSON(se);return Object.assign({},oe,e)}const ne=(0,te.default)((()=>{const e=new L.Property(re());return ie.onSync.subscribe(null,(()=>e.mergeAndFire(re()))),e.subscribe(null,(()=>ie.setJSON(se,e.state()))),e}));var ae=i(996986),le=i(665570),ce=i(168883),de=i(710455),he=i(294162);class ue extends de.MediaCoordinatesPaneRenderer{constructor(){super(...arguments),this._data=null,this._widthCache=new he.TextWidthCache}setData(e){this._data=e}hitTest(e){return null}_drawImpl(e){if(!this._data)return ;const{lines:t,color:i}=this._data,{context:s,mediaSize:{width:o,height:r}}=e;s.fillStyle=i;let n=0;const a=[];for(const e of t){if(!e.text)continue;s.font=e.font;const t=this._widthCache.measureText(s,e.text),i=t>o?o/t:1;a.push(i),n+=e.lineHeight*i}let l=Math.max((r-n)/2,0),c=-1;for(const e of t){if(!e.text)continue;c+=1;const t=a[c];s.save(),s.translate(o/2,l),s.textBaseline="top",s.textAlign="center",s.font=e.font,s.scale(t,t),s.fillText(e.text,0,e.vertOffset),s.restore(),l+=e.lineHeight*t}}}class _e{constructor(e,t){this._renderer=new ue,this._invalidated=!0,this._model=e,this._watermark=t}update(){this._invalidated=!0}renderer(){return this._invalidated&&(this._updateImpl(),this._invalidated=!1),this._renderer}_updateImpl(){const e=this._watermark.properties().childs(),t=this._model.mainSeries(),i=t.symbolInfo();if(!i||!e.visibility.value())return void this._renderer.setData(null);let s=i.name;if(/QUANDL/.test(i.exchange)){const e=s.split(/\//);e.length&&(s=e[e.length-1])}const o={description:i.description,short_description:i.short_description,pro_name:i.pro_name,short_name:i.name,local_description:i.local_description,language:i.language},r=[{text:s?`${s}, ${(0,ce.translatedIntervalString)(t.interval())}`:"",font:(0,k.makeFont)(96,E.CHART_FONT_FAMILY),lineHeight:117,vertOffset:0},{text:(0,le.getTranslatedSymbolDescription)(o)||"",font:(0,k.makeFont)(48,E.CHART_FONT_FAMILY),lineHeight:58,vertOffset:5}];this._renderer.setData({color:e.color.value(),lines:r})}}const pe="symbolWatermark";class me extends ae.DataSource{constructor(e){super(),this._properties=ne(),(0,W.applyDefaultsOverrides)(this._properties,void 0,!1,pe),this._properties.subscribe(this,(()=>e.updateSource(this))),this._paneView=new _e(e,this)}destroy(){this._properties.unsubscribeAll(this),super.destroy()}name(){return"watermark"}properties(){return this._properties}restorePropertiesDefaults(){ne().mergeAndFire(oe)}applyOverrides(e){(0,W.applyPropertiesOverrides)(this._properties,void 0,!1,e,pe)}paneViews(){return[this._paneView]}updateAllViews(e){super.updateAllViews(e),this._paneView.update()}}var ge=i(201089),Se=i(541558),ve=i(234271),fe=i(944876),be=i(389137),ye=i(623336),Ce=i(900569),we=i(459711),Pe=i(924788),Te=i(811630),Me=i(974655),xe=i(888929);function Ie(e,t,i){return i.hasDataSource(t)?ke(t,i)===e:!!i.isMainPane()&&ke(i.model().mainSeries(),i)===e}const Ae=new Map([["price",e=>(0,Me.isPriceDataSource)(e)],["trading",e=>(0,C.isTrading)(e)],["drawing",e=>(0,C.isLineTool)(e)&&!(0,C.isTrading)(e)&&!e.isPhantom()],["drawingsForAllSymbols",e=>(0,C.isLineTool)(e)&&!(0,C.isTrading)(e)&&!e.isPhantom()],["phantom",e=>(0,C.isLineTool)(e)&&e.isPhantom()],["restRowSources",e=>!(0,C.isLineTool)(e)&&!(0,C.isTrading)(e)],["legendViewSources",(e,t)=>t.hasDataSource(e)&&((0,Me.isPriceDataSource)(e)||(0, C.isStudyLineTool)(e))],["leftPriceScale",Ie.bind(null,"left")],["rightPriceScale",Ie.bind(null,"right")],["overlayPriceScale",Ie.bind(null,"overlay")],["multipane",(e,t)=>!t.hasDataSource(e)],["allWithoutMultipane",(e,t)=>t.hasDataSource(e)]]),Le=new Map([["price","visibleSorted"],["trading","visibleSorted"],["drawing","visibleSorted"],["drawingsForAllSymbols","allSorted"],["phantom","visibleSorted"],["restRowSources","visibleSorted"],["legendViewSources","visibleSorted"],["leftPriceScale","visibleSorted"],["rightPriceScale","visibleSorted"],["overlayPriceScale","visibleSorted"],["multipane","visibleSorted"],["allWithoutMultipane","visibleSorted"]]);function ke(e,t){const i=e.priceScale();return null===i?"overlay":t.priceScalePosition(i)}class Ee{constructor(e){this._groupedSources=new Map,this._sources=null,this._pane=e}clear(){this._groupedSources.clear(),this._sources=null}destroy(){this.clear()}all(){return this._groupedSources.has("visibleSorted")||this._sortSources(),(0,n.ensureDefined)(this._groupedSources.get("visibleSorted"))}allIncludingHidden(){return this._groupedSources.has("allSorted")||this._sortSources(),(0,n.ensureDefined)(this._groupedSources.get("allSorted"))}allWithoutMultipane(){return this._getSourcesByGroupType("allWithoutMultipane")}allExceptSpecialSources(){if(!this._groupedSources.has("exceptSpecial")){const e=this.allIncludingHidden().filter((e=>!e.isSpeciallyZOrderedSource()));this._groupedSources.set("exceptSpecial",e)}return(0,n.ensureDefined)(this._groupedSources.get("exceptSpecial"))}tradingSources(){return this._getSourcesByGroupType("trading")}priceSources(){return this._getSourcesByGroupType("price")}lineSources(){return this._getSourcesByGroupType("drawing")}lineSourcesForAllSymbols(){return this._getSourcesByGroupType("drawingsForAllSymbols")}phantomSources(){return this._getSourcesByGroupType("phantom")}allExceptLineAndTradingSources(){return this._getSourcesByGroupType("restRowSources")}hitTestSources(){if(!this._groupedSources.has("hitTest")){const e=this.allExceptLineAndTradingSources().concat(this.lineSources());this._groupedSources.set("hitTest",(0,xe.sortSources)(e,this._pane))}return(0,n.ensureDefined)(this._groupedSources.get("hitTest"))}generalSources(){if(!this._groupedSources.has("general")){const e=this.allExceptLineAndTradingSources().concat(this.lineSources());this._groupedSources.set("general",(0,xe.sortSources)(e,this._pane))}return(0,n.ensureDefined)(this._groupedSources.get("general"))}leftPriceScalesSources(){return this._getSourcesByGroupType("leftPriceScale")}rightPriceScalesSources(){return this._getSourcesByGroupType("rightPriceScale")}overlayPriceScaleSources(){return this._getSourcesByGroupType("overlayPriceScale")}multipaneSources(){return this._getSourcesByGroupType("multipane")}legendViewSources(){return this._getSourcesByGroupType("legendViewSources")}_getSourcesByGroupType(e){const t=(0,n.ensureDefined)(Le.get(e));return this._groupedSources.has(t)?this._groupedSources.has(e)||this._groupSources(e):(this._sortSources(),this._groupSources(e)),(0, n.ensureDefined)(this._groupedSources.get(e))}_sortSources(){null===this._sources&&(this._sources=this._pane.dataSources());const e=this._pane.model().multiPaneSources(this._pane),t=(0,xe.sortSources)(this._sources.concat(e),this._pane),i=t.filter((e=>!(0,C.isLineTool)(e)||e.isActualSymbol()&&e.isActualCurrency()&&e.isActualUnit()));this._groupedSources.set("allSorted",t),this._groupedSources.set("visibleSorted",i)}_groupSources(e){const t=(0,n.ensureDefined)(Le.get(e)),i=Ae.get(e);if(void 0!==i){const s=(0,n.ensureDefined)(this._groupedSources.get(t)).filter((e=>i(e,this._pane)));this._groupedSources.set(e,s)}}}var De=i(616117),Be=i(291784),Ne=i(740086),Re=i(440617),Oe=i(981107),Ve=i(438907),We=i(960521),Fe=i(678515);function He(e,t,i){const s=e.div(t).toNumber();return Math.abs(Math.round(s)-s)100)throw new Error("something wrong with base")}}}tickSpan(e,t,i){const s=0===this._base?0:1/this._base,o=Math.min(1e-14,(e-t)/1e3);let r=Math.pow(10,Math.max(0,Math.ceil((0,Fe.log10)(e-t))));if(!isFinite(r))return 1e305;let n=0,a=this._integralDividers[0];for(;;){const e=(0,Fe.greaterOrEqual)(r,s,o)&&r>s+o,t=(0,Fe.greaterOrEqual)(r,i*a,o),l=(0,Fe.greaterOrEqual)(r,1,o),c=new We.Big(r).div(a),d=0===s||He(c,s,o);if(!(e&&t&&l&&d))break;r=c.toNumber(),a=this._integralDividers[++n%this._integralDividers.length]}if(r<=s+o&&(r=s),r=Math.max(1,r),this._fractionalDividers.length>0&&(0,Fe.equal)(r,1,o))for(n=0,a=this._fractionalDividers[0];;){const e=(0,Fe.greaterOrEqual)(r,i*a,o)&&r>s+o,t=new We.Big(r).div(a),l=0===s||He(t,s,o);if(!e||!l)break;r=t.toNumber(),a=this._fractionalDividers[++n%this._fractionalDividers.length]}return r}}class qe{constructor(e,t,i,s){this._marks=null,this._priceScale=e,this._base=t,this._coordinateToLogicalFunc=i,this._logicalToCoordinateFunc=s}base(){return this._base}setBase(e){if(e<0)throw new Error("base < 0");this._base=e}tickSpan(e,t,i=0){if(e{const n=o.tickSpan(e,t,r);return n>i?Math.min(n,s):s}),1/0);return n>0&&isFinite(n)?n:e-t}rebuildTickMarks(){this._marks=null}marks(){return null===this._marks&&(this._marks=this._rebuildTickMarksImpl()),this._marks}_fontHeight(){return this._priceScale.fontSize()}_tickMarkHeight(){return Math.ceil(2.5*this._fontHeight())}_rebuildTickMarksImpl(){const e=this._priceScale,t=[],i=e.mainSource() ;if(e.isEmpty()||!e.hasCalculatedPriceRange()||null===i)return t;let s=i.firstValue();null===s&&(s=0);const o=e.height(),r=this._coordinateToLogicalFunc(o-1,s),n=this._coordinateToLogicalFunc(0,s),a=Math.max(r,n),l=Math.min(r,n);if(a===l)return t;let c=this.tickSpan(a,l),d=a%c;d+=d<0?c:0;const h=a>=l?1:-1;let u=null;const _=e.formatter();let p=NaN;for(let i=a-d;i>l;i-=c){i===p&&(c=this.tickSpan(a,l,c)),p=i;const o=this._logicalToCoordinateFunc(i,s);null!==u&&Math.abs(o-u){const e=this.mainSource();if(e&&e.model()){const t=e.model().paneForSource(e);t&&e.model().updatePane(t)}})),this._scalesProperties.subscribe(this,(()=>{this._marksCache=null})),this._properties.childs().lockScale.subscribe(this,this._updateResetAvailableValue),this._properties.childs().autoScale.subscribe(this,this._updateResetAvailableValue),this._updateResetAvailableValue(),this.setId((0,Se.randomHash)())}id(){return this._id}setId(e){this._id=e} isLog(){return this._properties.childs().log.value()}isPercentage(){return this._properties.childs().percentage.value()}isInverted(){return this._properties.childs().isInverted.value()}isIndexedTo100(){return this._properties.childs().indexedTo100.value()}isAutoScale(){return this._properties.childs().autoScale.value()&&!this.isLockScale()}isLockScale(){return this._properties.childs().lockScale.value()}isRegular(){return!this.isPercentage()&&!this.isLog()&&!this.isIndexedTo100()}isScaleSeriesOnly(){return this._scaleSeriesOnly}properties(){return this._properties}height(){return this.m_height}setHeight(e){this.m_height!==e&&(this.m_height=e,this._invalidateInternalHeightCache(),this._marksCache=null)}internalHeight(){if(this._internalHeightCache)return this._internalHeightCache;const e=this.height()-this.topPixelMargin()-this.bottomPixelMargin();return this._internalHeightCache=e,e}fontSize(){return this._scalesProperties.childs().fontSize.value()}priceRange(){return this._makeSureItIsValid(),this._priceRange}setPriceRange(e,t,i){if(!(e instanceof Be.PriceRange))throw new TypeError("incorrect price range");const s=this._priceRange;if(!t&&Be.PriceRange.compare(s,e))return;const o=null!==this._maxPriceRange&&this._maxPriceRange.containsStrictly(e),r=null!==this._minPriceRange&&e.containsStrictly(this._minPriceRange);this.isLockScale()&&!t&&(o||r)||(this._marksCache=null,this._priceRange=e,i||this._priceRangeChanged.fire(s,e))}setMinPriceRange(e){this._minPriceRange=e}setMaxPriceRange(e){this._maxPriceRange=e}recalculatePriceRangeOnce(){this._recalculatePriceRangeOnce=!0}priceRangeShouldBeRecalculatedOnce(){if(!this._recalculatePriceRangeOnce||this.isLockScale())return!1;const e=this.mainSource();return null!==e&&e.priceRangeReady()}priceRangeChanged(){return this._priceRangeChanged}mode(){const e=this._properties.childs();return{autoScale:e.autoScale.value(),lockScale:e.lockScale.value(),percentage:e.percentage.value(),indexedTo100:e.indexedTo100.value(),log:e.log.value()}}setMode(e){const t={},i=this.mode(),s=this._properties.state();let o=null;void 0!==e.autoScale&&e.autoScale!==s.autoScale&&(t.autoScale=e.autoScale,this._setAutoScaleValueWithDependentProperties(e.autoScale)),void 0!==e.lockScale&&e.lockScale!==s.lockScale&&(t.lockScale=e.lockScale,this._setLockScaleValueWithDependentProperties(e.lockScale)),void 0!==e.percentage&&e.percentage!==s.percentage&&(t.percentage=e.percentage,this._setPercentageValueWithDependentProperties(e.percentage),this._invalidatedForRange.isValid=!1),void 0!==e.indexedTo100&&e.indexedTo100!==s.indexedTo100&&(t.indexedTo100=e.indexedTo100,this._setIndexedTo100ValueWithDependentProperties(e.indexedTo100),this._invalidatedForRange.isValid=!1),void 0!==e.log&&e.log!==s.log&&(t.log=e.log,this._setLogValueWithDependentProperties(e.log));const r=this._properties.childs();s.log&&!r.log.value()&&(this._canConvertPriceRangeFromLog(this._priceRange)?(o=this._convertPriceRangeFromLog(this._priceRange),null!==o&&this.setPriceRange(o)):r.autoScale.setValue(!0)), !s.log&&r.log.value()&&(o=this._convertPriceRangeToLog(this._priceRange),null!==o&&this.setPriceRange(o)),s.autoScale!==r.autoScale.value()&&r.autoScale.listeners().fire(r.autoScale,""),s.autoScaleDisabled!==r.autoScaleDisabled.value()&&r.autoScaleDisabled.listeners().fire(r.autoScaleDisabled,""),s.lockScale!==r.lockScale.value()&&r.lockScale.listeners().fire(r.lockScale,""),s.percentage!==r.percentage.value()&&(r.percentage.listeners().fire(r.percentage,""),this.updateFormatter()),s.indexedTo100!==r.indexedTo100.value()&&(r.indexedTo100.listeners().fire(r.indexedTo100,""),this.updateFormatter()),s.percentageDisabled!==r.percentageDisabled.value()&&r.percentageDisabled.listeners().fire(r.percentageDisabled,""),s.log!==r.log.value()&&r.log.listeners().fire(r.log,""),s.logDisabled!==r.logDisabled.value()&&r.logDisabled.listeners().fire(r.logDisabled,""),void 0===t.log&&void 0===t.percentage&&void 0===t.lockScale&&void 0===t.autoScale&&void 0===t.indexedTo100||this._modeChanged.fire(i,this.mode())}modeChanged(){return this._modeChanged}isEmpty(){return this._makeSureItIsValid(),0===this.m_height||!this._priceRange||this._priceRange.isEmpty()}hasCalculatedPriceRange(){return this._hasCalculatedPriceRange}canDetachSource(e){return this.m_dataSources.some((t=>t!==e&&!(0,Pe.isLollipopDataSource)(t)&&(0,Me.isPriceDataSource)(t)&&!((0,K.isStudy)(t)&&t.isLinkedToSeries())))}updateAllViews(e){const t=this._getSourcesToUpdateViews();for(const i of t)i.updateAllViews(e)}logFormula(){return this._logFormula}state(){var e;const t=this._properties.childs();return{id:this._id,m_priceRange:this.isAutoScale()?null:(null===(e=this.priceRange())||void 0===e?void 0:e.serialize())||null,m_isAutoScale:this.isAutoScale(),m_isPercentage:t.percentage.value(),m_isIndexedTo100:t.indexedTo100.value(),m_isLog:t.log.value(),m_isLockScale:this.isLockScale(),m_isInverted:this.isInverted(),m_topMargin:this._margins.top,m_bottomMargin:this._margins.bottom,alignLabels:t.alignLabels.value(),logFormula:(0,be.clone)(this._logFormula),hasCalculatedPriceRange:this._hasCalculatedPriceRange}}restoreState(e){var t;let i=e.m_priceRange;if(void 0===i)throw new TypeError("invalid state");if(void 0===e.m_isAutoScale)throw new TypeError("invalid state");void 0!==e.id&&(this._id=e.id);const s={autoScale:e.m_isAutoScale};void 0!==e.m_isPercentage&&(s.percentage=e.m_isPercentage),void 0!==e.m_isIndexedTo100&&(s.indexedTo100=e.m_isIndexedTo100),void 0!==e.m_isLog&&(s.log=e.m_isLog),void 0!==e.m_isLockScale&&(s.lockScale=e.m_isLockScale),void 0!==e.m_isInverted&&this._properties.childs().isInverted.setValue(e.m_isInverted),this.setMode(s),this._hasCalculatedPriceRange=null!==(t=e.hasCalculatedPriceRange)&&void 0!==t?t:null!==i,i?(i instanceof Be.PriceRange||(i=new Be.PriceRange(i)),this.setPriceRange(i,!0)):this.clearPriceRange(),e.logFormula&&(this._logFormula=e.logFormula),void 0!==e.m_topMargin&&(this._margins.top=e.m_topMargin),void 0!==e.m_bottomMargin&&(this._margins.bottom=e.m_bottomMargin), void 0!==e.alignLabels&&this._properties.childs().alignLabels.setValue(e.alignLabels),this._mainSource=null,this._scaleSeriesOnly=!1}priceToLogical(e){return this.isLog()&&e?(0,Ne.toLog)(e,this._logFormula):e}logicalToPrice(e){return this.isLog()?(0,Ne.fromLog)(e,this._logFormula):e}priceToCoordinate(e,t){const i=this._priceToPercentOrIndexedTo100IfNeeded(e,t);return this._logicalToCoordinate(i)}coordinateToPrice(e,t){let i=this._coordinateToLogical(e);return this.isPercentage()?i=(0,Ne.fromPercent)(i,t):this.isIndexedTo100()&&(i=(0,Ne.fromIndexedTo100)(i,t)),i}mainSource(){if(null!==this._mainSource)return this._mainSource;let e;for(const t of this._priceDataSources){if(t instanceof Re.Series){e=t;break}e||(e=t)}return this._mainSource=e||null,this._correctedMarginsCache=null,this._mainSource}priceToCoordinateFn(e){this._makeSureItIsValid();const t=this.bottomPixelMargin(),i=(0,n.ensureNotNull)(this.priceRange()),s=i.minValue(),o=i.maxValue(),r=this.internalHeight()-1,a=this.isInverted(),l=r/(o-s),c=this.m_height,d=e=>{const i=t+l*(e-s);return a?i:c-1-i};return this.isPercentage()?t=>d((0,Ne.toPercent)(t,e)):this.isIndexedTo100()?t=>d((0,Ne.toIndexedTo100)(t,e)):this.isLog()?e=>d((0,Ne.toLog)(e,this._logFormula)):e=>d(e)}pricesArrayToCoordinates(e,t,i){this._makeSureItIsValid();const s=this.bottomPixelMargin(),o=(0,n.ensureNotNull)(this.priceRange()),r=o.minValue(),a=o.maxValue(),l=this.internalHeight()-1,c=this.isInverted(),d=l/(a-r);void 0===i&&(i=e.length);const h=this.isPercentage(),u=this.isIndexedTo100(),_=this.isLog(),p=this.m_height;let m,g;for(let o=0;oe?(0,Ne.toLog)(e,this._logFormula):e),0===s.length)return;const d="open"in s[0],h="close"in s[0];if(null!==c)for(let e=0;e0){const t=(0,Ve.unitConvertibleGroups)(h,_,e);l=(0,b.intersect)(l,new Set(t))}d+=1}if(null!==t)for(const i of this._priceDataSources){if(u.includes(i))continue;const c=i;if(!c.isUnitSource()||!c.isVisible())continue;const d=c.unit();if(null===d){t=null;break}s.add(d),h+=1;const _=(0,n.ensureNotNull)(c.symbolSource()),p=_.symbolInfo();if(null===p){t=null;break}if(l.size>0){const t=(0,Ve.unitConvertibleGroups)(p,d,e);l=(0,b.intersect)(l,new Set(t))}if(o.set(d,e.name(d)),r.set(d,e.description(d)),u.includes(_)||(l=new Set),void 0===a)a=d;else if(null!==a&&a!==d){a=null;break}}if(void 0===t)if(0===d&&0===h)t=null;else{t={availableGroups:l,selectedUnit:a||null,units:s,originalUnits:i,symbolSourceCount:d,allUnitsAreOriginal:c,names:o,descriptions:r}}return this._unitCache={value:t,availableUnitsCount:e.size()},t}measureUnitId(e){if(null!==this._measureUnitIdCache&&e.size()===this._measureUnitIdCache.availableUnitsCount)return this._measureUnitIdCache.value;let t,i;const s=new Map,o=new Map,r=new Set;let n=0;const a=this._seriesLikeSources.filter(Oe.isActingAsSymbolSource);for(const l of a){if(!l.isVisible())continue;const a=l.measureUnitId();if(null===a){t=null;break}r.add(a),s.set(a,e.name(a)),o.set(a,e.description(a)),void 0===i?i=a:null!==i&&i!==a&&(i=null),n+=1}return void 0===t&&(t=0===n?null:{selectedMeasureUnitId:i||null,measureUnitIds:r,names:s,descriptions:o,symbolSourceCount:n}),this._measureUnitIdCache={value:t,availableUnitsCount:e.size()},t}setMargins(e){if(!(0,be.isNumber)(e.top)||!(0,be.isNumber)(e.bottom))throw new TypeError("invalid margin");if(e.top<0||e.top>30||e.bottom<0||e.bottom>30)throw new RangeError("invalid margin");this._margins.top===e.top&&this._margins.bottom===e.bottom||(this._margins=e,this._correctedMarginsCache=null,this._invalidateInternalHeightCache(),this._marksCache=null)}topMargin(){return this._correctedMargins().top}bottomMargin(){return this._correctedMargins().bottom}invalidateMargins(){this._correctedMarginsCache=null}topPixelMargin(){return this.isInverted()?this.bottomMargin()*this.height()+this._bottomPixelMargin:this.topMargin()*this.height()+this._topPixelMargin}bottomPixelMargin(){return this.isInverted()?this.topMargin()*this.height()+this._topPixelMargin:this.bottomMargin()*this.height()+this._bottomPixelMargin}marks(){return this.isEmpty()?(this._marksCache=null,[]):(null===this._marksCache&&(this._markBuilder.rebuildTickMarks(),this._marksCache=this._markBuilder.marks(),this._onMarksChanged.fire()),this._marksCache)}onMarksChanged(){return this._onMarksChanged}priceRangeInPrice(){if(this.isEmpty())return null;const e=this.mainSource();if(null===e)return null;const t=(0,n.ensureNotNull)(e.firstValue()),i=this.height();return{from:this.coordinateToPrice(i-1,t),to:this.coordinateToPrice(0,t)}}setPriceRangeInPrice(e){if(this.isPercentage()||this.isIndexedTo100())return;const t=this.isInverted(),i=t?this.bottomMargin():this.topMargin(),s=t?this.topMargin():this.bottomMargin(),o=this.isLog();let r=o?(0, Ne.toLog)(e.from,this._logFormula):e.from,n=o?(0,Ne.toLog)(e.to,this._logFormula):e.to;const a=n-r;r+=s*a,n-=i*a,this.setMode({autoScale:!1}),this.setPriceRange(new Be.PriceRange(r,n)),this._marksCache=null,this._onMarksChanged.fire()}hasMainSeries(){return this._hasSeries}getStudies(){return this.dataSources().filter(K.isStudy)}lastSourceRemoved(){return this._lastSourceRemoved}sourcesForAutoscale(){return this._mainSource&&this._scaleSeriesOnly!==this._scalesProperties.childs().scaleSeriesOnly.value()&&(this._sourcesForAutoscale=null),this._sourcesForAutoscale||(this._sourcesForAutoscale=this._recalculateSourcesForAutoscale()),this._sourcesForAutoscale}recalculatePriceRange(e){this._invalidatedForRange={visibleBars:e,isValid:!1}}internalHeightChanged(){return this._internalHeightChanged}orderedSources(){if(this._cachedOrderedSoruces)return this._cachedOrderedSoruces;let e=this.m_dataSources.slice();return e=e.filter((e=>!(0,Pe.isLollipopDataSource)(e))),e=(0,xe.sortSources)(e),this._cachedOrderedSoruces=e,this._cachedOrderedSoruces}invalidateSourcesCache(){this._cachedOrderedSoruces=null,this._sourcesToUpdateViews=null}startScale(e){var t,i;this.isEmpty()||this.isPercentage()||this.isIndexedTo100()||null!==this._scaleStartPoint||null!==this._priceRangeSnapshot||(this._scaleStartPoint=this.m_height-e,this._priceRangeSnapshot=null!==(i=null===(t=this.priceRange())||void 0===t?void 0:t.clone())&&void 0!==i?i:null)}scaleTo(e){if(this.isPercentage()||this.isIndexedTo100()||null===this._scaleStartPoint)return;this.setMode({autoScale:!1}),(e=this.m_height-e)<0&&(e=0);let t=(this._scaleStartPoint+.2*(this.m_height-1))/(e+.2*(this.m_height-1));const i=(0,n.ensureNotNull)(this._priceRangeSnapshot).clone();t=Math.max(t,.1),i.scaleAroundCenter(t),this.setPriceRange(i)}endScale(){this.isPercentage()||this.isIndexedTo100()||null!==this._scaleStartPoint&&(this._scaleStartPoint=null,this._priceRangeSnapshot=null)}startTwoPointsScale(e,t){if(this.isEmpty()||this.isPercentage()||this.isIndexedTo100()||null!==this._twoPointsScaleStartPosition)return;const i=Math.min(e,t),s=Math.max(e,t);this._twoPointsScaleStartPosition={topLogical:this._coordinateToLogical(i),bottomLogical:this._coordinateToLogical(s)}}twoPointsScale(e,t){if(this.isPercentage()||this.isIndexedTo100()||null===this._twoPointsScaleStartPosition)return;this.setMode({autoScale:!1});const i=Math.min(e,t),s=Math.max(e,t),{topLogical:o,bottomLogical:r}=this._twoPointsScaleStartPosition,n=this.bottomPixelMargin(),a=this.internalHeight()-1,l=(this._invertedCoordinate(i)-n)/a,c=(r-o)/((this._invertedCoordinate(s)-n)/a-l);if(!Number.isFinite(c))return;const d=o-c*l,h=d+c;this.setPriceRange(new Be.PriceRange(this.priceToLogical(d),this.priceToLogical(h)))}endTwoPointsScale(){this._twoPointsScaleStartPosition=null}startScroll(e){var t,i;this.isAutoScale()||null===this._scrollStartPoint&&null===this._priceRangeSnapshot&&(this.isEmpty()||(this._scrollStartPoint=e,this._priceRangeSnapshot=null!==(i=null===(t=this.priceRange())||void 0===t?void 0:t.clone())&&void 0!==i?i:null))} scrollTo(e){if(this.isAutoScale())return;if(null===this._scrollStartPoint||null===this._priceRangeSnapshot)return;const t=this.priceRange();if(null===t)return;let i=e-this._scrollStartPoint;this.isInverted()&&(i*=-1);const s=i*(t.length()/(this.internalHeight()-1)),o=this._priceRangeSnapshot.clone();o.shift(s),this.setPriceRange(o,!0),this._marksCache=null}endScroll(){this.isAutoScale()||null!==this._scrollStartPoint&&(this._scrollStartPoint=null,this._priceRangeSnapshot=null)}clearPriceRange(){this._priceRange=null,this.recalculatePriceRangeOnce()}isVisible(){return this._isVisible}_addDataSourceImpl(e,t,i){if(t||-1===this.m_dataSources.indexOf(e)){if((0,Me.isPriceDataSource)(e)){if(void 0===i?this._priceDataSources.push(e):this._priceDataSources.splice(i,0,e),e.currencyChanged().subscribe(this,(()=>this._currencyCache=null)),e.unitChanged().subscribe(this,(()=>this._unitCache=null)),(0,Oe.isSymbolSource)(e)&&(this._seriesLikeSources.push(e),e.symbolResolved().subscribe(this,(()=>{this._currencyCache=null,this._unitCache=null,this._measureUnitIdCache=null})),e.isActingAsSymbolSource().subscribe(this._boundOnSourceIsActingAsSymbolSourceChanged),e instanceof Re.Series)){const t=e.properties();this._hasSeries||(t.childs().lockScale&&(this.setMode({lockScale:t.childs().lockScale.value()}),t.removeProperty("lockScale")),t.childs().pnfStyle.child("lockScale")&&t.childs().pnfStyle.removeProperty("lockScale")),this._hasSeries=!0}e.isSpeciallyZOrderedSource()||(this._sourcesThatAffectVisibility.push(e),e.properties().childs().visible.listeners().subscribe(this,this._onSourceVisibilityChanged))}(0,K.isStudy)(e)&&(e.onIsActualIntervalChange().subscribe(this,this._dropScaleCache),e.onHibernationStateChange().subscribe(this,this._dropScaleCache),0===this._studiesCount&&(0,je.hideAllIndicators)().subscribe(this,this._dropScaleCache),this._studiesCount++),(0,C.isLineTool)(e)&&(0===this._drawingCount&&(0,je.hideAllDrawings)().subscribe(this,this._dropScaleCache),this._drawingCount++),this.m_dataSources.push(e),this._mainSource=null,this.mainSource()===e&&(this._correctedMarginsCache=null,this._internalHeightCache=null,this._marksCache=null),this._dropScaleCache(),this.updateFormatter(),this._initScaleProperties(),this.invalidateSourcesCache(),this._updateIsVisible()}}_recalculateSourcesForAutoscale(){this._mainSource&&(this._scaleSeriesOnly=this._scalesProperties.childs().scaleSeriesOnly.value());const e=this._scaleSeriesOnly&&this._hasSeries;return this.m_dataSources.filter((t=>!!(t.properties().visible.value()||t instanceof Re.Series)&&(e?t instanceof Re.Series:(0,K.isStudy)(t)?!t.isSourceHidden()&&t.isIncludedInAutoScale():t.isIncludedInAutoScale())))}_updateAutoScaleDisabledProperty(e){const t=this._properties.childs(),i=t.indexedTo100.value()||t.percentage.value()||t.lockScale.value();e?t.autoScaleDisabled.setValueSilently(i):t.autoScaleDisabled.setValue(i)}_setAutoScaleValueWithDependentProperties(e){const t=this._properties.childs();t.autoScale.setValueSilently(e),e&&(t.percentage.setValueSilently(!1), t.indexedTo100.setValueSilently(!1),t.lockScale.setValueSilently(!1),t.logDisabled.setValueSilently(!1)),this._updateAutoScaleDisabledProperty(!0)}_setLockScaleValueWithDependentProperties(e){const t=this._properties.childs();t.lockScale.setValueSilently(e),e&&(t.autoScale.setValueSilently(!1),t.percentage.setValueSilently(!1),t.indexedTo100.setValueSilently(!1),t.log.setValueSilently(!1)),t.percentageDisabled.setValueSilently(e),t.logDisabled.setValueSilently(e),this._updateAutoScaleDisabledProperty(!0)}_setPercentageValueWithDependentProperties(e){const t=this._properties.childs();t.percentage.setValueSilently(e),e&&(t.autoScale.setValueSilently(!0),t.log.setValueSilently(!1),t.lockScale.setValueSilently(!1),t.indexedTo100.setValueSilently(!1)),this._updateAutoScaleDisabledProperty(!0)}_setIndexedTo100ValueWithDependentProperties(e){const t=this._properties.childs();t.indexedTo100.setValueSilently(e),e&&(t.autoScale.setValueSilently(!0),t.log.setValueSilently(!1),t.lockScale.setValueSilently(!1),t.percentage.setValueSilently(!1)),this._updateAutoScaleDisabledProperty(!0)}_setLogValueWithDependentProperties(e){const t=this._properties.childs();t.log.setValueSilently(e),e&&(t.lockScale.setValueSilently(!1),t.percentage.setValueSilently(!1),t.indexedTo100.setValueSilently(!1)),this._updateAutoScaleDisabledProperty(!0)}_recalculatePriceRangeImpl(){const e=this._invalidatedForRange.visibleBars;if(null===e)return;let t=null;const i=this.sourcesForAutoscale(),s=this.isPercentage(),o=this.isIndexedTo100();let r=0,n=0;const a={targetPriceScale:this,scaleSeriesOnly:this._scaleSeriesOnly};for(const l of i){if(!l.properties().visible.value())continue;const i=l.firstValue();if(null===i||s&&0===i)continue;const c=e.firstBar(),d=e.lastBar(),h=l.autoScaleInfo(c,d,a);let u=h.range;u&&(s?u=(0,Ne.toPercentRange)(u,i):o&&(u=(0,Ne.toIndexedTo100Range)(u,i)),t=null===t?u:t.merge(u)),void 0!==h.topPixelMargin&&(r=Math.max(r,h.topPixelMargin)),void 0!==h.bottomPixelMargin&&(n=Math.max(n,h.bottomPixelMargin))}if((Math.abs(r-this._topPixelMargin)>0||Math.abs(n-this._bottomPixelMargin)>0)&&(this._bottomPixelMargin=n,this._topPixelMargin=r,this._marksCache=null,this._invalidateInternalHeightCache()),t){if(this._hasCalculatedPriceRange=!0,t.minValue()===t.maxValue()&&(t=new Be.PriceRange(t.minValue()-.5,t.maxValue()+.5)),this.isLog()){const e=this._convertPriceRangeFromLog(t),i=(0,Ne.logFormulaForPriceRange)(e);if(!(0,Ne.logFormulasAreSame)(i,this._logFormula)){const s=this._priceRangeSnapshot?this._convertPriceRangeFromLog(this._priceRangeSnapshot):null;this._logFormula=i,t=this._convertPriceRangeToLog(e),s&&(this._priceRangeSnapshot=this._convertPriceRangeToLog(s))}}this.setPriceRange(t)}else this._priceRange||(this.setPriceRange(new Be.PriceRange(-.5,.5)),this._logFormula=(0,Ne.logFormulaForPriceRange)(null));this._invalidatedForRange.isValid=!0;const l=this.mainSource();null!==l&&this._recalculatePriceRangeOnce&&(this._recalculatePriceRangeOnce=!l.priceRangeReady())}_makeSureItIsValid(){ this._invalidatedForRange.isValid||(this._invalidatedForRange.isValid=!0,this._recalculatePriceRangeImpl())}_invalidateInternalHeightCache(){this._internalHeightCache=null,this._internalHeightChanged.fire()}_coordinateToLogical(e){if(this._makeSureItIsValid(),this.isEmpty())return 0;const t=this._invertedCoordinate(e),i=(0,n.ensureNotNull)(this.priceRange()),s=i.minValue()+(i.maxValue()-i.minValue())*((t-this.bottomPixelMargin())/(this.internalHeight()-1));return this.logicalToPrice(s)}_logicalToCoordinate(e){if(this._makeSureItIsValid(),this.isEmpty())return 0;e=this.priceToLogical(e);const t=(0,n.ensureNotNull)(this.priceRange()),i=this.bottomPixelMargin()+(this.internalHeight()-1)*(e-t.minValue())/(t.maxValue()-t.minValue());return this._invertedCoordinate(i)}_convertPriceRangeFromLog(e){if(null===e)return null;const t=(0,Ne.fromLog)(e.minValue(),this._logFormula),i=(0,Ne.fromLog)(e.maxValue(),this._logFormula);return new Be.PriceRange(t,i)}_convertPriceRangeToLog(e){if(null===e)return null;const t=(0,Ne.toLog)(e.minValue(),this._logFormula),i=(0,Ne.toLog)(e.maxValue(),this._logFormula);return new Be.PriceRange(t,i)}_canConvertPriceRangeFromLog(e){if(null===e)return!1;const t=(0,Ne.fromLog)(e.minValue(),this._logFormula),i=(0,Ne.fromLog)(e.maxValue(),this._logFormula);return isFinite(t)&&isFinite(i)}_onSourceVisibilityChanged(){this._dropScaleCache(),this._updateIsVisible()}_dropScaleCache(){this._sourcesForAutoscale=null,this._currencyCache=null,this._unitCache=null,this._measureUnitIdCache=null}_updateIsVisible(){this._isVisible.setValue(!0)}_invertedCoordinate(e){return this.isInverted()?e:this.height()-1-e}_initScaleProperties(){const e=this.isLockScale(),t=this.properties().childs();e&&(t.percentage.setValue(!1),t.indexedTo100.setValue(!1),t.log.setValue(!1),t.autoScale.setValue(!1)),t.percentageDisabled.setValue(e),t.logDisabled.setValue(e),this._updateAutoScaleDisabledProperty(!1),t.percentage.value()&&(t.log.setValue(!1),t.indexedTo100.setValue(!1)),t.indexedTo100.value()&&(t.log.setValue(!1),t.percentage.setValue(!1))}_correctedMargins(){if(null===this._correctedMarginsCache){const e=this.mainSource();this._correctedMarginsCache=null!==e?e.correctScaleMargins(this._margins):this._margins}return this._correctedMarginsCache}_getSourcesToUpdateViews(){return this._sourcesToUpdateViews||(this._sourcesToUpdateViews=this.m_dataSources.filter((e=>!(0,C.isLineTool)(e)||e.isActualSymbol()&&e.isActualCurrency()))),this._sourcesToUpdateViews}_mainSourceFormatter(){const e=this.mainSource();return(null==e?void 0:e.formatter())||Ye}_priceToPercentOrIndexedTo100IfNeeded(e,t){return this.isPercentage()?(0,Ne.toPercent)(e,t):this.isIndexedTo100()?(0,Ne.toIndexedTo100)(e,t):e}_onSourceIsActingAsSymbolSourceChanged(){this._dropScaleCache()}_onIsInvertedChanged(){this._marksCache=null,this._markBuilder.rebuildTickMarks()}_updateResetAvailableValue(){this._resetScaleAvailable.setValue(!this.isLockScale()&&!this.isAutoScale())}}var Je=i(915179),Qe=i(46955),et=i(790524),tt=i(339315),it=i(7288);const st=[],ot=[];class rt{ constructor(e){this._studies={},this._deferreds={},this._container=e,st.push(e),ot.push(this)}add(e,t){this._deferreds[e]&&(this._deferreds[e].resolve(t),delete this._deferreds[e]),this._studies[e]=t}get(e){return this._studies[e]?Promise.resolve(this._studies[e]):(this._deferreds[e]||(this._deferreds[e]=(0,p.createDeferredPromise)()),this._deferreds[e].promise)}delete(e){delete this._studies[e],delete this._deferreds[e]}reset(){const e=st.indexOf(this._container);~e&&(st.splice(e,1),ot.splice(e,1))}static instance(e){const t=st.indexOf(e);return~t?ot[t]:new rt(e)}}var nt=i(960690);var at=i(395098),lt=i(180148),ct=i(844295),dt=i(167723),ht=i(711755),ut=i(247035),_t=i(707621),pt=i(107973);const mt=(0,ge.getLogger)("Chart.Pane");function gt(e,t,i){e.setMargins({top:t,bottom:i})}const St="chart.pane";class vt{constructor(e,t,i,s){this.m_dataSources=[],this._sourceWatchedValuesSubscriptions=new Map,this.m_mainDataSource=null,this._cachedOrderedSources=new Ee(this),this._sourcesById=new Map,this._priceSourcesById=new Map,this._sourcePropertiesChanged=new Y.Delegate,this._sourcesZOrderChanged=new Y.Delegate,this._tagsChanged=new Y.Delegate,this._stretchFactor=1e3,this._isInInsertManyDataSourcesState=!1,this._lastLineDataSourceZOrder=null,this._rightPriceScales=[],this._leftPriceScales=[],this._lockedPriceScale=null,this._currentPriceScaleRatio=null,this._onPriceScalesChanged=new Y.Delegate,this._isRecalculatingScales=!1,this._priceDataSources=[],this._symbolSources=[],this._lollipopDataSources=[],this._symbolSourceResolved=new Y.Delegate,this._symbolSourceResolvingActive=new $.WatchedValue(!1),this._bulkActions={activeCounter:0},this._height=0,this._width=0,this._sizeChanged=new Y.Delegate,this._dataSourcesCollectionChanged=new Y.Delegate,this._symbolSourceCollectionChanged=new Y.Delegate,this._priceSourcesCollectionChanged=new Y.Delegate,this._maximized=new $.WatchedValue(!1),this._collapsed=new $.WatchedValue(!1),this._resetPriceScalesAvailable=new $.WatchedValue(!1),this._destroyed=new Y.Delegate,this._executionsPositionController=null,this._seriesDisplayError=null,this._onPriceScaleIsVisibleChanged=()=>{this._model.fullUpdate()},this._recalcSymbolSourceResolvingActive=()=>{for(const e of this._symbolSources)if(e.symbolResolvingActive().value())return void this._symbolSourceResolvingActive.setValue(!0);this._symbolSourceResolvingActive.setValue(!1)},this._onSymbolSourceCollectionChanged=()=>{0===this._bulkActions.activeCounter?this._symbolSourceCollectionChanged.fire():this._bulkActions.symbolSourceCollectionChanged=!0},this._onSeriesDisplayError=e=>{},this._updateResetPriceScalesAvailableValue=()=>{const e=e=>e.resetScaleAvailable().value(),t=this._leftPriceScales.some(e)||this._rightPriceScales.some(e);this._resetPriceScalesAvailable.setValue(t)},this._priceScaleSelectionStrategy=(0,fe.createPriceScaleSelectionStrategy)(i.properties().childs().priceScaleSelectionStrategyName.value()),this._id=null!=s?s:(0,Se.randomHashN)(6),this._timeScale=e,this.m_mainDataSource=null,this._properties=t,this._model=i, i.properties().childs().priceScaleSelectionStrategyName.subscribe(null,(e=>{this._priceScaleSelectionStrategy=(0,fe.createPriceScaleSelectionStrategy)(e.value()),this._priceScaleSelectionStrategy.apply(this)})),this._timeScale.barSpacingChanged().subscribe(this,(()=>{this.m_mainDataSource===this._model.mainSeries()&&this._recalculatePriceScaleByScaleRatio(this.m_mainDataSource.priceScale())})),i.onMultipaneSourcesCollectionChanged().subscribe(this,this._invalidateSourcesCache),i.panesCollectionChanged().subscribe(this,this._invalidateSourcesCache),t.childs().topMargin.subscribe(this,this._updateMargins),t.childs().bottomMargin.subscribe(this,this._updateMargins),this._updateMargins()}destroy(){var e;this._properties.childs().topMargin.unsubscribeAll(this),this._properties.childs().bottomMargin.unsubscribeAll(this),this._model.properties().childs().priceScaleSelectionStrategyName.unsubscribeAll(this),this._timeScale.barSpacingChanged().unsubscribeAll(this),this._leftPriceScales.concat(this._rightPriceScales).forEach((e=>{e.modeChanged().unsubscribeAll(this),e.priceRangeChanged().unsubscribeAll(this),e.internalHeightChanged().unsubscribeAll(this),e.isVisible().unsubscribe(this._onPriceScaleIsVisibleChanged),e.resetScaleAvailable().unsubscribe(this._updateResetPriceScalesAvailableValue)}));for(const e of this.m_dataSources)this.removeSourceFromPriceScale(e),e.destroy&&e.destroy();null===(e=this._seriesDisplayError)||void 0===e||e.destroy(),this._model.onMultipaneSourcesCollectionChanged().unsubscribeAll(this),this._model.panesCollectionChanged().unsubscribeAll(this),this._destroyed.fire()}id(){return this._id}bulkActionMacro(e){const t=this._bulkActions;t.activeCounter+=1,e(),t.activeCounter-=1,0===t.activeCounter&&(this._dataSourcesCollectionChanged.fire(),t.symbolSourceCollectionChanged&&(this._symbolSourceCollectionChanged.fire(),t.symbolSourceCollectionChanged=!1),t.priceSourcesCollectionChanged&&(this._priceSourcesCollectionChanged.fire(),t.priceSourcesCollectionChanged=!1))}defaultPriceScale(){var e,t;const i=null!==(t=null===(e=this.m_mainDataSource)||void 0===e?void 0:e.priceScale())&&void 0!==t?t:null;if(null!==i)return i;const s=this.properties().childs().axisProperties.state();return s.autoScale=!0,new Xe(this._model.properties().childs().scalesProperties,s)}leftPriceScales(){return this._leftPriceScales}rightPriceScales(){return this._rightPriceScales}visibleLeftPriceScales(){var e;const t=this._model.priceScaleSlotsCount(),i=this._leftPriceScales.filter((e=>e.isVisible().value())),s=null===(e=this.mainDataSource())||void 0===e?void 0:e.priceScale();if(i.length>t.left&&(null==s?void 0:s.isVisible().value())){const e=(0,b.moveToHead)(i,s);return e.splice(t.left),e}return i}visibleRightPriceScales(){var e;const t=this._model.priceScaleSlotsCount(),i=this._rightPriceScales.filter((e=>e.isVisible().value())),s=null===(e=this.mainDataSource())||void 0===e?void 0:e.priceScale();if(i.length>t.right&&(null==s?void 0:s.isVisible().value())){const e=(0,b.moveToHead)(i,s);return e.splice(t.right),e}return i} clearSeries(e){const t=this._model.mainSeries();for(let i=this.m_dataSources.length-1;i>=0;i--)this.m_dataSources[i]===t&&this._removeSourceFromCollections(i,e)}sourcesByGroup(){return this._cachedOrderedSources}dataSourceForId(e){return this._sourcesById.get(e)||null}changeSourceId(e,t){var i;e===this._model.mainSeries()&&(null===(i=(0,ve.getPersistentLogger)())||void 0===i||i.addPersistentLogEntry(`changeSourceId for series from ${e.id()} to ${t}`,ge.LOGLEVEL.INFO,St)),(0,n.assert)(this.hasDataSource(e));const s=e.id();e.setId(t),this._sourcesById.delete(s),this._sourcesById.set(t,e),(0,Me.isPriceDataSource)(e)&&(this._priceSourcesById.delete(s),this._priceSourcesById.set(t,e))}movePriceScale(e,t,i){const s=this.priceScalePosition(e);if(s!==t)this.removePriceScale(e),this._placePriceScale(e,t,i),e.invalidateMargins(),this._invalidateSourcesCache();else if(void 0!==i&&"overlay"!==s){const t="left"===s?this._leftPriceScales:this._rightPriceScales,o=t.indexOf(e);t.splice(o,1),t.splice(i,0,e)}}mainDataSource(){return this.m_mainDataSource}isEmpty(){return null===this.m_mainDataSource}recalculatePriceScale(e,t){if(!e)return;let i=e.sourcesForAutoscale();if(e===this._model.mainSeries().priceScale()&&(i=[...i,...this._cachedOrderedSources.multipaneSources()]),(e.isAutoScale()||e.priceRangeShouldBeRecalculatedOnce()||null===e.priceRange())&&i.length>0&&!this.timeScale().isEmpty()){const t=this.timeScale().visibleBarsStrictRange();e.recalculatePriceRange(t)}e.updateAllViews(t)}onSourceTagsChanged(){this._tagsChanged.fire()}insertDataSource(e,t,i,s){e.setZorder(i),t||(s=!1,t=this.findSuitableScale(e)),this._addSourceToCollections(e);let o=!1;e===this.model().mainSeries()?(this.m_mainDataSource=this.model().mainSeries(),o=!0):null===this.m_mainDataSource&&(0,Me.isPriceDataSource)(e)&&(this.m_mainDataSource=e,o=!0),s||t.addDataSource(e,this._isInInsertManyDataSourcesState),e.setPriceScale(t),t.invalidateMargins(),e.onTagsChanged&&e.onTagsChanged().subscribe(this,this.onSourceTagsChanged),o&&this._processMainSourceChange(),this._tagsChanged.fire(),(0,Me.isPriceDataSource)(e)&&this.recalculatePriceScale(t,(0,G.sourceChangeEvent)(e.id())),this._invalidateSourcesCache(),this._isInInsertManyDataSourcesState||(0,n.ensureNotNull)(this.model().alertsWatcher()).syncSourceAlertLabels(e)}addDataSource(e,t,i){let s=e.zorder();i||((0,C.isLineTool)(e)&&!e.isSpeciallyZOrderedSource()?(s=null!==this._lastLineDataSourceZOrder?this._lastLineDataSourceZOrder+1:this.newLineToolZOrder(),this._isInInsertManyDataSourcesState&&(this._lastLineDataSourceZOrder=s)):(0,K.isStudy)(e)&&!e.isSpeciallyZOrderedSource()&&(s=this.newStudyZOrder())),this.insertDataSource(e,t,s)}removeDataSource(e,t,i,s){const o=this.m_dataSources.indexOf(e);if(-1===o)return void mt.logDebug("removeDataSource: invalid data source");(0,n.ensureNotNull)(this.model().alertsWatcher()).detachSourceAlertLabels(e),this._removeSourceFromCollections(o,!!i),e!==this.m_mainDataSource||t||(this.m_mainDataSource=null);const r=e.priceScale();s||this.removeSourceFromPriceScale(e), e.onTagsChanged&&e.onTagsChanged().unsubscribe(this,this.onSourceTagsChanged),(0,Me.isPriceDataSource)(e)&&!t&&this._processMainSourceChange(),(0,K.isStudy)(e)&&e.metaInfo().hasForceOverlayPlots()&&this._model.removeMultiPaneSource(e),this._tagsChanged.fire(),r&&(0,Me.isPriceDataSource)(e)&&this.recalculatePriceScale(r,(0,G.sourceChangeEvent)(e.id())),this._invalidateSourcesCache()}hasDataSource(e){return this._sourcesById.has(e.id())}hasPriceDataSource(e){return this._priceSourcesById.has(e.id())}dataSources(){return this.m_dataSources}priceDataSources(){return this._priceDataSources}lollipopDataSources(){return this._lollipopDataSources}symbolSources(){return this._symbolSources}replaceSource(e,t,i){const s=this.m_mainDataSource===e,o=e.zorder(),r=null==i?void 0:i.replaceSource(e,t);this.removeDataSource(e,s,void 0,r),this.insertDataSource(t,i,o,r),this._sourcesById.set(t.id(),t),(0,Me.isPriceDataSource)(t)&&this._priceSourcesById.set(t.id(),t),s&&(this.m_mainDataSource=t,this._processMainSourceChange())}findSuitableScale(e,t,i){return this._priceScaleSelectionStrategy.findSuitableScale(this,e,t,i)}createNewPriceScaleIfPossible(){return this._priceScaleSelectionStrategy.createNewPriceScaleIfPossible(this)}canCreateNewPriceScale(){return this._priceScaleSelectionStrategy.canCreateNewPriceScale(this)}isOverlay(e){const t=e.priceScale();return null===t||"overlay"===this.priceScalePosition(t)}recalculate(e){this._leftPriceScales.forEach((t=>this.recalculatePriceScale(t,e))),this._rightPriceScales.forEach((t=>this.recalculatePriceScale(t,e)));for(const t of this.m_dataSources)this.isOverlay(t)&&!(0,C.isLineTool)(t)&&this.recalculatePriceScale(t.priceScale(),e);this.updateAllViews(e),this._model.updatePane(this)}updateAllViews(e){const t=this._cachedOrderedSources.all();for(const i of t)i.updateAllViews(e);for(const t of this.model().customSources())t.updateViewsForPane(this,e)}updateLollipopViews(e){for(const t of this._lollipopDataSources)t.updateAllViews(e)}priceScalePosition(e){return this._leftPriceScales.includes(e)?"left":this._rightPriceScales.includes(e)?"right":"overlay"}createPriceScaleAtPosition(e,t){const i=this.properties().childs().axisProperties.state();i.autoScale=!0;const s=new Xe(this.model().properties().childs().scalesProperties,i);return s.setHeight(this.height()),gt(s,this._defaultTopMargin(),this._defaultBottomMargin()),this._placePriceScale(s,e,t),s}removePriceScale(e){e.modeChanged().unsubscribeAll(this),e.priceRangeChanged().unsubscribeAll(this),e.internalHeightChanged().unsubscribeAll(this),e.isVisible().unsubscribe(this._onPriceScaleIsVisibleChanged),e.resetScaleAvailable().unsubscribe(this._updateResetPriceScalesAvailableValue),e===this._lockedPriceScale&&(this._lockedPriceScale=null,this._currentPriceScaleRatio=null);const t=this._leftPriceScales.indexOf(e);-1!==t&&(this._leftPriceScales[t].invalidateMargins(),this._leftPriceScales.splice(t,1));const i=this._rightPriceScales.indexOf(e);if(-1!==i&&(this._rightPriceScales[i].invalidateMargins(),this._rightPriceScales.splice(i,1)), null===e.mainSource()){const t=e.dataSources().length;0!==t&&mt.logError("Invalid priceScale state: empty mainSource but non-empty data sources="+t)}this._onPriceScalesChanged.fire(),this._updateResetPriceScalesAvailableValue()}priceScaleIndex(e,t){switch(t){case"left":return this.leftPriceScales().indexOf(e);case"right":return this.rightPriceScales().indexOf(e)}}move(e,t,i){const s=e.priceScale();this.removeSourceFromPriceScale(e),t.addDataSource(e),e.setPriceScale(t),t.invalidateMargins(),this._processMainSourceChange(),this._invalidateSourcesCache(),e.isIncludedInAutoScale()&&(null!==s&&this.recalculatePriceScale(s,(0,G.sourceChangeEvent)(e.id())),this.recalculatePriceScale(t,(0,G.sourceChangeEvent)(e.id()))),this._onPriceScalesChanged.fire()}setZOrders(e){e.forEach(((e,t)=>{t.setZorder(e)})),this._invalidateSourcesCache(),0===this._bulkActions.activeCounter&&this._dataSourcesCollectionChanged.fire(),this.model().lightUpdate()}isMainPane(){return this.hasDataSource(this.model().mainSeries())}isLast(){const e=this.model().panes();return e[e.length-1]===this}newStudyZOrder(){return(0,Qe.newStudyZOrder)(this._priceDataSources)}newLineToolZOrder(e){return(0,Qe.newLineToolZOrder)(this.m_dataSources,e)}model(){return this._model}containsMainSeries(){return this._sourcesById.has(this.model().mainSeries().id())}applyPriceScaleRatio(e,t){var i;null!==this._lockedPriceScale&&this._lockedPriceScale!==e||this._currentPriceScaleRatio===t||!this.isMainPane()||null===this._lockedPriceScale&&e!==(null===(i=this.mainDataSource())||void 0===i?void 0:i.priceScale())||(this._setNewPriceRangeByScaleRatio(e,t,this._mainSourceVisiblePriceRange(e),!0,!0),null!==this._lockedPriceScale?this._tryToApplyNewPriceScaleRatio():e.isLog()||this.model().mainSeriesScaleRatioPropertyOnChanged())}sendToBack(e){const t=this.sourcesByGroup().allExceptSpecialSources();this._batchReorder(e,t[0],Qe.moveBeforeSource)}bringToFront(e){const t=this.sourcesByGroup().allExceptSpecialSources();this._batchReorder(e,t[t.length-1],Qe.moveAfterSource)}sendBackward(e){const t=this.sourcesByGroup().allIncludingHidden(),i=t.indexOf(e[0]);if(0===i)this.bringToFront(e);else{const s=t[i-1];this.insertBefore(e,s)}}bringForward(e){const t=this.sourcesByGroup().allExceptSpecialSources(),i=t.indexOf(e[e.length-1]);if(i===t.length-1)this.sendToBack(e);else{const s=t[i+1];this.insertAfter(e,s)}}insertAfter(e,t){this._batchReorder(e,t,Qe.moveAfterSource)}insertBefore(e,t){this._batchReorder(e,t,Qe.moveBeforeSource)}maximized(){return this._maximized}collapsed(){return this._collapsed}getPriceScaleById(e){const t=this.m_dataSources.find((t=>{var i;return(null===(i=t.priceScale())||void 0===i?void 0:i.id())===e}));return void 0===t?null:t.priceScale()}priceScaleSelectionStrategy(){return this._priceScaleSelectionStrategy}setPriceScaleSelectionStrategy(e){this._priceScaleSelectionStrategy=e,e.apply(this)}findTargetPriceAxisViews(e,t,i,s){if((0,f.isDataSource)(e)&&this.model().paneForSource(e)!==this)return[];const o=e.priceScale();if(t===o)return i;if(null===o)return[] ;if("overlay"===this.priceScalePosition(o))return t===this.defaultPriceScale()?i:[];const r=this.priceScalePosition(t);if(r!==this.priceScalePosition(o))return[];const n="left"===r?this.leftPriceScales():this.rightPriceScales();return n.indexOf(t)1}properties(){return this._properties}setPriceAutoScale(e,t){e.setMode({autoScale:t}),this.timeScale().isEmpty()||this.recalculatePriceScale(e,(0,G.viewportChangeEvent)())}state(e,t,i,s,o,r){var n,a;const l={sources:[],mainSourceId:null===(n=this.m_mainDataSource)||void 0===n?void 0:n.id(),stretchFactor:this._stretchFactor,leftAxisesState:[],rightAxisesState:[],overlayPriceScales:{},priceScaleRatio:this._currentPriceScaleRatio,isCollapsed:this._collapsed.value()},c=new Map,d=e=>{if(c.has(e))return c.get(e);let n=null;const a=i&&!e.isSavedInStudyTemplates()||(0,y.isAlertLabel)(e)||!e.state||(0,C.isLineTool)(e)&&r||!e.isSavedInChart(Boolean(t))||!(n=e.state(t,o))||s&&(0,C.isLineTool)(e)&&e.isActualSymbol&&!e.isActualSymbol()||e.isPhantom()?null:n;return c.set(e,a),a};if(e){l.sources=[];for(let e=0;enull!==c.get(e),u=e=>!r||!(0,C.isLineTool)(e);l.leftAxisesState=this._leftPriceScales.map((e=>({state:e.state(),sources:e.dataSources().filter(h).filter(u).map((e=>e.id()))}))),l.rightAxisesState=this._rightPriceScales.map((e=>({state:e.state(),sources:e.dataSources().filter(h).filter(u).map((e=>e.id()))}))),l.overlayPriceScales={};for(const e of this.m_dataSources)if(this.isOverlay(e)&&e.isSavedInChart(Boolean(t))){const t=e.priceScale();l.overlayPriceScales[e.id()]=null!==(a=null==t?void 0:t.state())&&void 0!==a?a:null}return l}restoreState(e){var t;const{state:i,withData:s,version:o,seriesId:r=this._model.mainSeries().id(),settingsMigration:a={},contentOverrides:l,restoreSilently:c,reason:d=0}=e;null===(t=(0,ve.getPersistentLogger)())||void 0===t||t.addPersistentLogEntry(`Restoring pane with seriesId ${r}`,ge.LOGLEVEL.INFO,St),i.stretchFactor&&(this._stretchFactor=i.stretchFactor);const h={};if(i.sources){const e=i.sources.filter((e=>{var t;return!!e&&("MainSeries"===e.type||(!(null===(t=e.points)||void 0===t?void 0:t.some((e=>null===e.time_t||!isFinite(e.time_t))))||(mt.logNormal("Dropped invalid "+e.type+". Reason: non-numeric point time"),!1)))})),t=e.findIndex(et.isMainSeriesState);-1!==t&&this.model().mainSeries().setObsoleteZOrder(e[t].zorder),o<3&&(0,Qe.reorderDataSourcesStateZOrder)(e);const n=-1!==this.m_dataSources.indexOf(this._model.mainSeries());this.clearSeries(Boolean(c)),this.m_mainDataSource=null,n&&this._addSourceToCollections(this._model.mainSeries(),c),(()=>{const t=e.find((e=>e.id===i.mainSourceId));if(void 0===t)return void mt.logWarn("There is no main source with id "+i.mainSourceId+", total sources="+e.length);if(!window.TradingView[t.type]||!(0, De.isLineToolName)(t.type))return void mt.logNormal("The type of main source is not line tool - fix is unnecessary");let s=null;for(const i of e)if(!window.TradingView[t.type]||!(0,De.isLineToolName)(i.type)){if(null!==s)return void mt.logWarn("Pane contains more than 1 possibly main sources - auto fix cannot be applied");s=i}if(null===s)return void mt.logWarn("Pane contains only line tools - possible we need to remove this pane?");const o=i.mainSourceId;let r=0;i.mainSourceId=s.id,e.forEach((e=>{e.ownerSource===o&&(e.ownerSource=null==s?void 0:s.id,r+=1)})),mt.logNormal("Auto fix broken pane is applied, changed line tools="+r+", changed from="+o+" to="+s.id)})();for(const t of e)if("study_Sessions"===t.type){this.model().sessions().restoreOldState(t,s);break}for(const t of e)"study_Sessions"!==t.type&&(null===this._model.dataSourceForId(t.id)||"MainSeries"===t.type?(h[t.id]=t.ownerSource,(0,et.isMainSeriesState)(t)?this._restoreMainSeries(t,s,n,a,l,c):(0,et.isStudyState)(t)?this.restoreStudy(t,s,r,a,c,d):(0,et.isLineToolState)(t)?(t.state&&(t.state.zOrderVersion=2),this.restoreLineTool(t,s,void 0,c)):"ChartEventsSource"===t.type&&this._restoreSpecialSource(t,s,c)):mt.logError("Duplicate id while restoring pane: "+t.type+","+t.id))}const u=new Set,_=(e,t)=>{e.priceScale()!==t&&(this.removeSourceFromPriceScale(e),e.setPriceScale(t),t.addDataSource(e))},p=(e,t,i)=>{if(u.has(e))return;u.add(e);const s=i.m_showSymbolLabels;void 0!==s&&e===this.model().mainSeries()&&this.model().properties().childs().scalesProperties.childs().showSymbolLabels.setValue(s),this._model.children(e,!0).forEach((e=>p(e,t,i))),_(e,t)},m=e=>{const t=(0,W.defaults)("chartproperties").paneProperties.axisProperties,i=new Xe(this.model().properties().childs().scalesProperties,t);return i.restoreState(e.state),i.setHeight(this._height),e.sources.forEach((e=>{const s=this.dataSourceForId(e);s&&p(s,i,t)})),0===i.dataSources().length?null:i},g=e=>e.map(m).filter((e=>null!==e));let S;if(i.leftAxisesState)S=g(i.leftAxisesState);else{const e=m({state:i.leftAxisState,sources:i.leftAxisSources});S=null!==e?[e]:[]}let v;if(this._leftPriceScales.slice().forEach((e=>this.removePriceScale(e))),this._leftPriceScales=[],S.forEach((e=>this._placePriceScale(e,"left"))),i.rightAxisesState)v=g(i.rightAxisesState);else{const e=m({state:i.rightAxisState,sources:i.rightAxisSources});v=null!==e?[e]:[]}this._rightPriceScales.slice().forEach((e=>this.removePriceScale(e))),this._rightPriceScales=[],v.forEach((e=>this._placePriceScale(e,"right"))),this._currentPriceScaleRatio=i.priceScaleRatio||i.leftPriceScaleRatio||i.rightPriceScaleRatio||null;const f=new Map;for(const e of this.m_dataSources){if(u.has(e))continue;let t;if(i.overlayPriceScales&&i.overlayPriceScales[e.id()]){let s=i.overlayPriceScales[e.id()];f.has(null==s?void 0:s.id)?t=f.get(null==s?void 0:s.id):(s=(0,n.ensure)(s),t=new Xe(this._model.properties().childs().scalesProperties),t.setHeight(this._height),s.m_isAutoScale=!0,s.m_isLog=!1,s.m_isPercentage=!1,s.m_isLockScale=!1,t.restoreState(s),f.set(s.id,t)) }else t=new Xe(this._model.properties().childs().scalesProperties),t.setHeight(this._height);_(e,t)}for(const e of Object.keys(h)){const t=h[e],i=this.dataSourceForId(e);t&&i&&null===i.ownerSource()&&i.setOwnerSource(this.dataSourceForId(t))}if(i.mainSourceId&&!this.containsMainSeries()&&(this.m_mainDataSource=this.dataSourceForId(i.mainSourceId)),!this.m_mainDataSource)for(const e of this.m_dataSources)if((0,Me.isPriceDataSource)(e)){this.m_mainDataSource=e;break}for(const e of this.m_dataSources)(0,C.isLineTool)(e)?(e.ownerSource()||e.setOwnerSource(this.mainDataSource()),e.isFixed()&&e.restoreFixedPoint()):(0,K.isStudy)(e)&&!e.ownerSource()&&e.isLinkedToSeries()&&e.setOwnerSource(this.model().mainSeries());this._updateMargins(),this._cachedOrderedSources.clear()}onPriceScalesChanged(){return this._onPriceScalesChanged}setPaneSize(e){let t;switch(e){case"large":t=1;break;case"medium":t=.6;break;case"small":t=.3;break;case"tiny":t=.15;break;default:throw new Error("Unknown size enum value: "+e)}this._stretchFactor=1e3*t}stretchFactor(){return this._stretchFactor}setStretchFactor(e){this._stretchFactor=e}customSources(e){return this.model().customSources(e)}createDrawingsCaches(){0}clearDrawingCaches(){0}executionsPositionController(){return null}width(){return this._width}height(){return this._height}setHeight(e){if(this._height!==e){this._height=e,this._leftPriceScales.forEach((t=>t.setHeight(e))),this._rightPriceScales.forEach((t=>t.setHeight(e)));for(let t=0;t(e.paneViews(this)||[]).some((e=>{const s=e.renderer(t);return s&&s.doesIntersectWithBox&&s.doesIntersectWithBox(i,t)}))))}logicalRectToPixels(e){const t=this.defaultPriceScale(),i=this.timeScale(),s=(0,n.ensureNotNull)((0, n.ensureNotNull)(t.mainSource()).firstValue()),o=t.priceToCoordinate(e.p1.price,s),r=i.indexToCoordinate(e.p1.index),l=t.priceToCoordinate(e.p2.price,s),c=i.indexToCoordinate(e.p2.index),d=new a.Point(Math.min(r,c),Math.min(o,l)),h=new a.Point(Math.max(r,c),Math.max(o,l));return(0,a.box)(d,h)}timeScale(){return this._timeScale}restoreLineTool(e,t,s,o,r){var a,l,c,h,u,_,p,m,g,S,v,f;if((0,De.isMtpPredictorToolName)(e.type))return mt.logWarn(`No longer supported tool ${e.type} is skipped while restoring state`),null;delete e.state.lastUpdateTime,e.state.intervalsVisibilities=(0,at.mergeIntervalVisibilitiesDefaults)(e.state.intervalsVisibilities),s=void 0===s||s,nt.LineToolElliott.migrateState(e),"LineToolGannComplex"!==(f=e).type||void 0!==f.version&&1!==f.version||(f.type="LineToolGannFixed"),Array.isArray(e.positionPercents)&&(e.positionPercents=e.positionPercents[0]);const b=e.type,y=e.id,w=e.state,P=s?e.zorder:this.newLineToolZOrder();(0,n.assert)((0,De.isLineToolName)(b),"invalid data source type:"+b+" (expected to be a Line Tool)");let T,M,x=null;if((0,et.isStudyLineToolState)(e)){x=this._model.isSnapshot()?new pt.StudyVersioning([],[]):(0,B.studyMetaInfoRepository)().studyVersioning();const s=pt.StudyVersioning.patchPointsBasedStudyState(e);e=s;const r=new N.StudyMetaInfo(s.metaInfo);if(!t&&r){const t=r.productId;if(!(null===(a=window.pro)||void 0===a?void 0:a.hasPackage(t))){const t=new we.StudyLineToolStub(this._model,e,r.shortDescription);return t.setId(y),this._addSourceToCollections(t,o),void 0!==P&&t.setZorder(P),t.setFailed(d.t(null,void 0,i(994125))),null}}const n=x.updateMetaInfo(r),l=null!=n?n:r;M=(0,C.createStudyLineToolProperties)(b,r,l,w,x),T=(0,C.createLineTool)(b,this._model,M,l,!0)}else M=(0,C.createLineToolProperties)(b,w,this._model,!1),t?null===(l=M.child("fixedSize"))||void 0===l||l.setValue(!1):null===(c=M.child("fixedSize"))||void 0===c||c.setValue(!0),T=(0,C.createLineTool)(b,this._model,M,null,!0);T.setId(y),T.linkKey().setValue(e.linkKey||null);const I=e.alertId;I&&T.canHasAlert()&&Te.alertsAvailable&&!this._model.readOnly()&&!this._model.isJustClonedChart()&&T.restoreAlert(+I);let A=null!==(h=e.indexes)&&void 0!==h?h:[];if(A=A.slice(0,null!==(_=null===(u=e.points)||void 0===u?void 0:u.length)&&void 0!==_?_:A.length),T.isFixed()?void 0!==e.positionPercents?T.restorePositionPercents(e.positionPercents):T.restorePositionPercents({x:.5,y:.5}):e.points&&T.restorePoints(e.points,A,t),T instanceof lt.LineToolBarsPattern||T instanceof ct.LineToolCallout||T instanceof dt.LineToolTrendAngle||T instanceof ht.LineToolGhostFeed||T instanceof ut.LineToolParallelChannel||T instanceof ye.LineToolTweet||T instanceof Ce.LineToolIdea)null===(m=(p=T).restoreData)||void 0===m||m.call(p,e);else if(t&&(0,et.isStudyLineToolState)(e)&&T.restoreData){const t=e;x&&(t.graphics=pt.StudyVersioning.patchPointsBasedStudyData(new N.StudyMetaInfo(t.metaInfo),t.graphics)),null===(g=T.restoreData)||void 0===g||g.call(T,t)}const L=null==e.version?1:e.version,k=null==T.version?1:T.version ;if(L!==k&&(null===(v=(S=T).migrateVersion)||void 0===v||v.call(S,L,k,{pane:this,model:this._model,properties:M})),void 0!==P&&T.setZorder(P),r)(0,C.prepareLineToolPropertiesByOwnerSource)(T.properties(),r),T.setOwnerSource(r);else{const t=e.ownerSource?this.dataSourceForId(e.ownerSource):null;T.setOwnerSource(t)}return T.isFixed()&&T.restoreFixedPoint(),void 0!==e.sharingMode&&T.share(e.sharingMode),this._addSourceToCollections(T,o),this._cachedOrderedSources.clear(),T}restoreStudy(e,t,s,o,r,n){var a,l;if(t&&void 0===e.data&&void 0===e.nonSeriesData&&void 0===e.indexes)return mt.logError("Cannot restore (skipping) study without data "+e.id+", "+e.metaInfo.id),null;const c=e.id,h=e.state,u=e.zorder;s=null!=s?s:this._model.mainSeries().id();const _=(null!==(a=e.parentSources)&&void 0!==a?a:e.ownerSource?[e.ownerSource]:[]).filter((e=>e!==s));let p=new N.StudyMetaInfo(e.metaInfo);if(function(e){return"Script$TV_EARNINGS@tv-scripting"===e||"Script$TV_DIVIDENDS@tv-scripting"===e||"Script$TV_SPLITS@tv-scripting"===e||"ESD$TV_EARNINGS@tv-scripting"===e||"ESD$TV_DIVIDENDS@tv-scripting"===e||"ESD$TV_SPLITS@tv-scripting"===e||"Earnings@tv-basicstudies"===e||"Dividends@tv-basicstudies"===e||"Splits@tv-basicstudies"===e||"BarSetContinuousRollDates@tv-corestudies"===e}(p.id)&&!t)return mt.logNormal("Skipping study "+p.id),null;let g=h;const S=new M.StudyStub(this._model,e,null!==(l=p.shortDescription)&&void 0!==l?l:p.name);let v;S.setId(c),S.setZorder(u);let f=!1;const b=(i,s)=>{if(f&&this._model.dataSourceForId(c)!==S)return;S.setStatus({type:it.StudyStatusType.Undefined});const o=null!=i?i:p,r=rt.instance(this._model),a=a=>{var l;const d=(0,x.prepareStudyPropertiesForLoadChart)(p,i,g,s),h=(0,K.createStudy)(this._model,d,a,o,void 0,n);if(h.setId(c),h.setOwnFirstValue(null!==(l=e.ownFirstValue)&&void 0!==l?l:null),e.customFields&&h.restoreStateCustomFields(e.customFields),t){const t=e,{data:i,nsData:s,indexes:o}=pt.StudyVersioning.patchStudyData(p,t.data,t.nonSeriesData,t.indexes);h.restoreData(i,s,o)}this._model.replaceStudyStub(S,h)||(v=h),r.add(c,h)};if(_.length>0){const e=_.map((e=>r.get(e)));Promise.all(e).then(a)}else a([])};let y;if(t){const e=pt.StudyVersioning.patchPropsStateAndMetaInfo(h,p,{oldShowStudyLastValueProperty:!(null==o?void 0:o.showStudyLastValueProperty)});y=Promise.resolve(new N.StudyMetaInfo(e.metaInfo))}else{y=(0,B.studyMetaInfoRepository)().requestMetaInfo().then((()=>i.e(37819).then(i.bind(i,532338)).then((e=>{const{pineIdForJavaId:i,migrateJavaStateToPine:s}=e,r=i(p.id);if(r)return(0,B.studyMetaInfoRepository)().findById({pineId:r,pineVersion:"last",type:"pine"}).then((e=>(s(h,p,e),p=e,m.emit("chart_migrated"),e)));{const e=pt.StudyVersioning.patchPropsStateAndMetaInfo(h,p,{oldShowStudyLastValueProperty:t&&!(null==o?void 0:o.showStudyLastValueProperty)});return g=e.propsState,new N.StudyMetaInfo(e.metaInfo)}}))))}y.then((e=>{var t;const i=this._model.isSnapshot()?new pt.StudyVersioning([],[]):(0,B.studyMetaInfoRepository)().studyVersioning();if(null===e||this._model.isSnapshot())return void b(e,i) ;const s=i.updateMetaInfoAsync(e);s.sync?b(null!==(t=s.result)&&void 0!==t?t:e,i):s.result.then((e=>b(e,i))).catch((e=>S.setFailed("error: "+e)))})).catch((()=>S.setFailed(d.t(null,void 0,i(328523)))));const C=null!=v?v:S;if(C){C.setZorder(u);const t=e.metaInfo.linkedToSeries?this._model.mainSeries():_.length?this.dataSourceForId(_[0]):null;C.setOwnerSource(t),this._addSourceToCollections(C,r),this._processMainSourceChange(),f=C===S}return this._cachedOrderedSources.clear(),C}clipboardLineToolOwnerSource(e){const t=this.dataSourceForId(e);if(null!==t){const e=t.ownerSource();if(null!==e&&null!==e.firstValue())return e}const i=this.mainDataSource();if(null!==i&&null!==i.firstValue())return i;for(const e of this.dataSources())if((0,Me.isPriceDataSource)(e)&&null!==e.firstValue())return e;return null}realignLineTools(e){var t;let i=!1;for(const s of this.m_dataSources)!(0,C.isLineTool)(s)||void 0!==e&&(null===(t=null==s?void 0:s.ownerSource())||void 0===t?void 0:t.symbolSource())!==e&&(0,Oe.isActingAsSymbolSource)(e)||(s.realign(),s.updateAllViews((0,G.sourceChangeEvent)(s.id())),i=!0);return i&&this._invalidateSourcesCache(),i}startScalePrice(e,t){e.startScale(t)}scalePriceTo(e,t){e.scaleTo(t),this.updateAllViews((0,G.viewportChangeEvent)())}endScalePrice(e){e.endScale()}startScrollPrice(e,t){e.startScroll(t)}scrollPriceTo(e,t){e.scrollTo(t),this.updateAllViews((0,G.viewportChangeEvent)())}endScrollPrice(e){e.endScroll()}resetPriceScale(e){const t=this.timeScale().visibleBarsStrictRange();e.resetScaleAvailable().value()&&e.resetScale(),e.recalculatePriceRange(t),this.updateAllViews((0,G.viewportChangeEvent)())}resetPriceScalesAvailable(){return this._resetPriceScalesAvailable.readonly()}restorePriceScaleState(e,t){e.restoreState(t),this.updateAllViews((0,G.viewportChangeEvent)())}beginInsertManyLineDataSources(){this._isInInsertManyDataSourcesState=!0,this._lastLineDataSourceZOrder=null}endInsertManyLineDataSources(){this._isInInsertManyDataSourcesState=!1,this._lastLineDataSourceZOrder=null;{const e=(0,n.ensureNotNull)(this.model().alertsWatcher());for(const t of this.m_dataSources)e.syncSourceAlertLabels(t)}}removeSourceFromPriceScale(e){const t=e.priceScale();if(null!==t){const i=t.dataSources();i.indexOf(e)>=0&&t.removeDataSource(e),0===i.length&&this.removePriceScale(t)}}_invalidateSourcesCache(){this._cachedOrderedSources.clear(),this._leftPriceScales.forEach((e=>e.invalidateSourcesCache())),this._rightPriceScales.forEach((e=>e.invalidateSourcesCache()))}_processMainSourceChange(){let e=!1;if(null===this.m_mainDataSource)for(const t of this.m_dataSources)if((0,Me.isPriceDataSource)(t)&&!this.isOverlay(t)&&(!(0,K.isStudy)(t)||!t.isLinkedToSeries())){this.m_mainDataSource=t,e=!0;break}if(this.m_mainDataSource&&e){let e=this.m_dataSources.filter(C.isLineTool);e=(0,xe.sortSources)(e);for(const t of e)this.move(t,(0,n.ensureNotNull)(this.m_mainDataSource.priceScale()),!0)}else if(!this.m_mainDataSource||this.isOverlay(this.m_mainDataSource)&&0===this._nonOverlayPricesSourcesCount()){let e=null ;if(this.m_dataSources.includes(this._model.mainSeries()))e=this._model.mainSeries();else for(const t of this.m_dataSources)if((0,Me.isPriceDataSource)(t)&&this.isOverlay(t)&&t.showInObjectTree()){e=t;break}if(null!==e){const t=this.m_mainDataSource===e;this.m_mainDataSource=e;const i=this.createNewPriceScaleIfPossible();if(t&&e===this._model.mainSeries()){const t=(0,n.ensureNotNull)(e.priceScale());this._model.children(e,!0).forEach((e=>{this.removeSourceFromPriceScale(e),i.addDataSource(e),e.setPriceScale(i)})),this.removePriceScale(t)}this.move(e,i,!0),this.recalculatePriceScale(e.priceScale(),(0,G.globalChangeEvent)())}}}_addSourceToCollections(e,t){this.m_dataSources.push(e),this._sourcesById.set(e.id(),e),this._invalidateSourcesCache();const i=()=>{this._sourcePropertiesChanged.fire(e)};e.properties().subscribe(this,i),e.zOrderChanged().subscribe(this,(t=>this._sourcesZOrderChanged.fire(e,t))),(0,C.isLineTool)(e)&&(e.normalizedPointsChanged().subscribe(this,i),e.fixedPointChanged().subscribe(this,i),e.hasAlert().subscribe(i),e.sharingMode().subscribe(i),e.linkKey().subscribe(i),this._sourceWatchedValuesSubscriptions.set(e.id(),i));const s=(0,Oe.isSymbolSource)(e)?e:null;(0,Me.isPriceDataSource)(e)&&(this._priceSourcesById.set(e.id(),e),e.currencyChanged().subscribe(this,(()=>this._invalidateSourcesCache())),e.unitChanged().subscribe(this,(()=>this._invalidateSourcesCache())),this._priceDataSources.push(e),this._onPriceSourcesCollectionChanged(),null!==s&&(this._symbolSources.push(s),s.symbolResolved().subscribe(this,(()=>this._symbolSourceResolved.fire(e))),s.symbolResolvingActive().subscribe(this._recalcSymbolSourceResolvingActive),s.symbolHibernated().subscribe(this._onSymbolSourceCollectionChanged),this._recalcSymbolSourceResolvingActive(),this._onSymbolSourceCollectionChanged())),e.isMultiPaneAvailable()&&this.model().addMultiPaneSource(e),(0,Pe.isLollipopDataSource)(e)&&(this._lollipopDataSources.push(e),this.updateLollipopViews((0,G.sourceChangeEvent)(e.id()))),t||0!==this._bulkActions.activeCounter||this._dataSourcesCollectionChanged.fire()}_removeSourceFromCollections(e,t){const i=this.m_dataSources[e],s=i.id();if(i.properties().unsubscribeAll(this),i.zOrderChanged().unsubscribeAll(this),this.m_dataSources.splice(e,1),this._sourcesById.delete(i.id()),(0,C.isLineTool)(i)&&(i.normalizedPointsChanged().unsubscribeAll(this),i.fixedPointChanged().unsubscribeAll(this),this._sourceWatchedValuesSubscriptions.has(s))){const e=this._sourceWatchedValuesSubscriptions.get(s);i.hasAlert().unsubscribe(e),i.linkKey().unsubscribe(e)}this._invalidateSourcesCache();const o=(0,Oe.isSymbolSource)(i)?i:null;(0,Me.isPriceDataSource)(i)&&(this._priceSourcesById.delete(i.id()),i.currencyChanged().unsubscribeAll(this),i.unitChanged().unsubscribeAll(this),(0,b.removeItemFromArray)(this._priceDataSources,i),this._onPriceSourcesCollectionChanged(),null!==o&&((0,b.removeItemFromArray)(this._symbolSources,o),o.symbolResolved().unsubscribeAll(this),o.symbolResolvingActive().unsubscribe(this._recalcSymbolSourceResolvingActive), o.symbolHibernated().unsubscribe(this._onSymbolSourceCollectionChanged),this._recalcSymbolSourceResolvingActive(),this._onSymbolSourceCollectionChanged())),i.isMultiPaneAvailable()&&this.model().removeMultiPaneSource(i),(0,Pe.isLollipopDataSource)(i)&&((0,b.removeItemFromArray)(this._lollipopDataSources,i),this.updateLollipopViews((0,G.sourceChangeEvent)(i.id()))),t||0!==this._bulkActions.activeCounter||this._dataSourcesCollectionChanged.fire()}_recalculatePriceScaleByScaleRatio(e){this.isMainPane()&&e===this._lockedPriceScale&&(null!==this._currentPriceScaleRatio?this._applyOldScaleRatioToPriceScale():this._tryToApplyNewPriceScaleRatio())}_defaultBottomMargin(){return.01*this.properties().childs().bottomMargin.value()}_defaultTopMargin(){return.01*this.properties().childs().topMargin.value()}_updateMargins(){const e=this._defaultTopMargin(),t=this._defaultBottomMargin();for(const i of this._leftPriceScales)gt(i,e,t);for(const i of this._rightPriceScales)gt(i,e,t);for(const i of this.m_dataSources)if(this.isOverlay(i)){const s=i.priceScale();null!==s&&(gt(s,e,t),this.recalculatePriceScale(s,(0,G.viewportChangeEvent)()))}for(const e of this._leftPriceScales)this.recalculatePriceScale(e,(0,G.viewportChangeEvent)());for(const e of this._rightPriceScales)this.recalculatePriceScale(e,(0,G.viewportChangeEvent)());this.updateAllViews((0,G.viewportChangeEvent)())}_batchReorder(e,t,i){i(this.sourcesByGroup().allExceptSpecialSources(),e,t),this._invalidateSourcesCache(),this._dataSourcesCollectionChanged.fire(),this.model().fullUpdate()}_placePriceScale(e,t,i){if("overlay"===t)return void e.invalidateMargins();const s="left"===t?this._leftPriceScales:this._rightPriceScales,o=void 0===i?s.length:i;s.splice(o,0,e),e.modeChanged().subscribe(this,this._onPriceScaleModeChanged.bind(this,e)),e.internalHeightChanged().subscribe(this,this._recalculatePriceScaleByScaleRatio.bind(this,e)),e.priceRangeChanged().subscribe(this,this._recalculateTimeScaleByScaleRatio.bind(this,e)),e.priceRangeChanged().subscribe(this,this._onPriceScaleSetMinMaxPriceRange.bind(this,e)),e.isVisible().subscribe(this._onPriceScaleIsVisibleChanged),e.resetScaleAvailable().subscribe(this._updateResetPriceScalesAvailableValue),e.isLockScale()&&((0,n.assert)(null===this._lockedPriceScale),this._lockedPriceScale=e,this._currentPriceScaleRatio=null),e.invalidateMargins(),this._onPriceScalesChanged.fire(),this._updateResetPriceScalesAvailableValue()}_onPriceScaleModeChanged(e,t,i){if(i.lockScale&&(this._lockedPriceScale!==e&&null!==this._lockedPriceScale&&this._lockedPriceScale.setMode({lockScale:!1}),this._lockedPriceScale=e,this._currentPriceScaleRatio=(0,Je.scaleRatio)(this.timeScale(),e)),t.lockScale&&!i.lockScale&&(this._lockedPriceScale=null,this._currentPriceScaleRatio=null),t.percentage===i.percentage&&t.indexedTo100===i.indexedTo100)return;const s=this.timeScale().visibleBarsStrictRange();null!==s&&(e.recalculatePriceRange(s),e.updateAllViews((0,G.viewportChangeEvent)()))}_applyOldScaleRatioToPriceScale(){ this._isRecalculatingScales||null===this._currentPriceScaleRatio||null===this._lockedPriceScale||(this._isRecalculatingScales=!0,this._setNewPriceRangeByScaleRatio(this._lockedPriceScale,this._currentPriceScaleRatio,this._mainSourceVisiblePriceRange(this._lockedPriceScale)),this._isRecalculatingScales=!1)}_setNewPriceRangeByScaleRatio(e,t,i,s,o){const r=(0,Je.priceRangeByScaleRatio)(e,this.timeScale().barSpacing(),t);e.setPriceRange(null!==r?r:i,s,o)}_applyOldScaleRatioToTimeScale(){this._isRecalculatingScales||null===this._currentPriceScaleRatio||(this._isRecalculatingScales=!0,this._setNewBarSpacingByScaleRatio(),this._isRecalculatingScales=!1)}_tryToApplyNewPriceScaleRatio(){const e=(0,n.ensureNotNull)(this._lockedPriceScale),t=(0,Je.scaleRatio)(this.timeScale(),e);this._currentPriceScaleRatio===t||e.isLog()||(this._currentPriceScaleRatio=t,this.model().mainSeriesScaleRatioPropertyOnChanged())}_recalculateTimeScaleByScaleRatio(e){e===this._lockedPriceScale&&(null!==this._currentPriceScaleRatio?this._applyOldScaleRatioToTimeScale():this._tryToApplyNewPriceScaleRatio())}_setNewBarSpacingByScaleRatio(){const e=this.timeScale().getValidBarSpacing((0,Je.barSpacingByScaleRatio)((0,n.ensureNotNull)(this._lockedPriceScale),this._currentPriceScaleRatio));this.timeScale().isValidBarSpacing(e)&&this.timeScale().setBarSpacing(e)}_mainSourceVisiblePriceRange(e){const t=this.timeScale().visibleBarsStrictRange();return null!==t?(0,n.ensureNotNull)((0,n.ensureNotNull)(e.mainSource()).priceRange(t.firstBar(),t.lastBar(),{targetPriceScale:e,scaleSeriesOnly:e.isScaleSeriesOnly()})):new Be.PriceRange(-.5,.5)}_setMinMaxPriceRange(){const e=(0,n.ensureNotNull)(this._lockedPriceScale),t=(0,Je.priceRangeByScaleRatio)(e,this.timeScale().maxBarSpacing(),this._currentPriceScaleRatio),i=(0,Je.priceRangeByScaleRatio)(e,this.timeScale().minBarSpacing(),this._currentPriceScaleRatio);null!==t&&e.setMaxPriceRange(t),null!==i&&e.setMinPriceRange(i)}_onPriceScaleSetMinMaxPriceRange(e){e===this._lockedPriceScale&&this._setMinMaxPriceRange()}_onPriceSourcesCollectionChanged(){0===this._bulkActions.activeCounter?this._priceSourcesCollectionChanged.fire():this._bulkActions.priceSourcesCollectionChanged=!0}_nonOverlayPricesSourcesCount(){return this.m_dataSources.filter((e=>(!(0,K.isStudy)(e)||!e.isLinkedToSeries())&&((0,Me.isPriceDataSource)(e)&&e.showInObjectTree()&&!this.isOverlay(e)))).length}_restoreMainSeries(e,t,i,s,o,r){var a,l,c;const d=e.id,h=e.state;if(h&&o&&(h.style=null!==(a=o.style)&&void 0!==a?a:h.style,h.interval=o.interval||h.interval,o.symbol&&o.symbol!==h.symbol&&(h.symbol=o.symbol,delete h.currencyId,delete h.unitId)),h&&["candleStyle","hollowCandleStyle","haStyle"].forEach((e=>{h[e]&&(h[e].wickUpColor=h[e].wickUpColor||h[e].wickColor,h[e].wickDownColor=h[e].wickDownColor||h[e].wickColor)})),h&&(h.statusViewStyle=h.statusViewStyle||{},!h.statusViewStyle.symbolTextSource)){const e=!!h.statusViewStyle.showSymbolAsDescription;h.statusViewStyle.symbolTextSource=e?"ticker":"description"}if(h){ h.extendedHours?h.sessionId="extended":h.sessionId||(h.sessionId="regular"),delete h.extendedHours,(0,_t.allChartStyles)().includes(h.style)||(h.style=2);const e=h.lineStyle.styleType;let t;delete h.lineStyle.styleType,0===e&&(t=14,h.lineWithMarkersStyle=(0,be.clone)(h.lineStyle)),1===e&&(t=15,h.steplineStyle=(0,be.clone)(h.lineStyle)),void 0!==t&&2===h.style&&(h.style=t)}if(!i){const e=this._model.mainSeries();(0,n.ensureNotNull)(this._model.mainPane()).removeDataSource(e,!1,r),this._addSourceToCollections(e,r)}const u=this.model().mainSeries(),_=u.properties().childs();this.m_mainDataSource=u;const p=h&&h.style?h.style:void 0;6===p&&"ATR"===_.pnfStyle.childs().inputs.childs().style.value()?_.pnfStyle.childs().inputs.childs().style.setValueSilently("Traditional"):4===p&&"ATR"===_.renkoStyle.childs().inputs.childs().style.value()&&_.renkoStyle.childs().inputs.childs().style.setValueSilently("Traditional"),h&&!h.hasOwnProperty("showSessions")&&(h.showSessions=!1),h&&void 0===h.settlementAsClose&&(h.settlementAsClose=!1),h&&t&&(h.showCountdown=!1),h&&(t&&!("showSeriesLastValueProperty"in s)&&"showLastValue"in h&&this._model.properties().childs().scalesProperties.childs().showSeriesLastValue.setValue(h.showLastValue),delete h.showLastValue),h&&this._restoreMainSeriesStudyInputs(e,u.styleStudyInfos());const m=u.sessionId();null===(l=(0,ve.getPersistentLogger)())||void 0===l||l.addPersistentLogEntry(`Restore series. source.id: ${e.id} id: ${d}`,ge.LOGLEVEL.INFO,St),u.restoreState(e,t),this.changeSourceId(u,d),null===(c=(0,ve.getPersistentLogger)())||void 0===c||c.addPersistentLogEntry(`Series has been successfully restored. id: ${u.id()}`,ge.LOGLEVEL.INFO,St),u.sessionId()!==m&&_.sessionId.listeners().fire(_.sessionId,"")}async _restoreMainSeriesStudyInputs(e,t){const i={haStyle:(0,z.chartStyleStudyId)(8,!0),renkoStyle:(0,z.chartStyleStudyId)(4,!0),pbStyle:(0,z.chartStyleStudyId)(7,!0),kagiStyle:(0,z.chartStyleStudyId)(5,!0),pnfStyle:(0,z.chartStyleStudyId)(6,!0),rangeStyle:(0,z.chartStyleStudyId)(11,!0),volFootprintStyle:(0,z.chartStyleStudyId)(17,!0),tpoStyle:(0,z.chartStyleStudyId)(18,!0),svpStyle:(0,z.chartStyleStudyId)(20,!0)};await(0,B.studyMetaInfoRepository)().requestMetaInfo();const s=(0,B.studyMetaInfoRepository)().studyVersioning(),o=Object.keys(tt.SYMBOL_STRING_DATA),r={},a=(0,n.ensureDefined)(e.state);for(let n=0;nthis._items[this._items.length-1])return t?this._validOffsetToIndex(this._items.length-1):null;for(let i=0;in){const i=e-n;if(i<500&&null!=t)return t(l,i);return l+i*c}return null}roughIndex(e,t=null){const i=this._items;if(!i.length||i.length<2)return null;const s=i.length-1,o=this._validOffsetToIndex(0),r=this._validOffsetToIndex(s),n=i[0],a=i[s];if(e>=n&&e<=a)return this.closestIndexLeft(e);const l=(a-n)/(r-o);if(ea){const i=e-a;let s=Math.trunc(i/l);if(s<500&&null!==t){const i=t(a,e);i.success&&(s=i.result)}return r+s}return null}closestIndexLeft(e){const t=this._items;if(!t.length)return null;if(Number.isNaN(e))return null;let i=t.length-1;if(e>=t[i])return this._validOffsetToIndex(i);let s=0;const o=t[s];if(es+1;){const o=s+i>>1,r=t[o];if(r>e)i=o;else{if(!(rthis._zoffset&&e+t>0)return wt.logError("merge: when the first time point index is updated, we should fill the time points starting from the first one"),[];if(0===this._items.length)return this._items=i.slice(),this._zoffset=t,[{change:"rebuild",index:this._validOffsetToIndex(0)}];const s=e+this._zoffset;if(s<0){const o=Math.abs(s) ;if(i.lengththis._items.length){const e=n-this._items.length;for(let t=r;t{this._usePercentageRightOffset.setValue(!1),this._defaultRightOffsetOptionsUpdated()})),this._defaultRightOffsetPercentage.subscribe((e=>{if(e>=100||e<0){const t=Math.max(0,Math.min(e,99));this._defaultRightOffsetPercentage.setValue(t)}else this._usePercentageRightOffset.setValue(!0),this._defaultRightOffsetOptionsUpdated()})),this._usePercentageRightOffset.subscribe((()=>{this._defaultRightOffsetOptionsUpdated()})),this._options.preserveBarSpacing&&(this._barSpacing=this._scalesProperties.childs().barSpacing.value()||6),this._barSpacingChanged.subscribe(this,this._maxRightOffsetOnChanged),this._barSpacingChanged.subscribe(this,this._updateResetAvailableValue),this._rightOffsetChanged.subscribe(this,this._updateResetAvailableValue),this._widthChanged.subscribe(this,this._maxRightOffsetOnChanged),this._updateResetAvailableValue()}destroy(){this._barSpacingChanged.unsubscribeAll(this),this._barSpacingChanged.destroy(),this._widthChanged.unsubscribeAll(this),this._widthChanged.destroy()}isEmpty(){return 0===this._width||!this.canNormalize()}canNormalize(){return this._points.size()>0}update(e,t,i,s){this._visibleBarsInvalidated=!0,i.length>0&&this._points.merge(e,t,i),this._tickMarks.merge(s),this.correctOffset()}addTail(e,t,i){this._tickMarks.removeTail(t);const s=e.params,o=(0,n.ensureDefined)(this._tickMarks.maxIndex)+(i?0:1);for(let e=0;e0&&(s*=this._width/e.width)),t&&this._pointWeights.needAdjustingOnDataRestoring()){this._tryToUpdateBarSpacing(this._barSpacing,s);const e=this._points.range().value();if(e){const t=e.firstIndex;let i=s,o=s,r=0;(()=>{r=this.indexToCoordinate(t),r<0?(o=s,i=s/10):(i=s,o=10*s)})();for(let e=0;e<20&&Math.abs(r)>2;e++){const e=(o+i)/2;this._tryToUpdateBarSpacing(this._barSpacing,e),r=this.indexToCoordinate(t),r<0?o=e:i=e}}}else this._tryToUpdateBarSpacing(this._barSpacing,s);this.correctOffset(),this._usePercentageRightOffset.value()&&(this._rightOffset=this.percentsToBarIndexLength(this._defaultRightOffsetPercentage.value())),this._rightOffsetChanged.fire(this._rightOffset)}marks(){if(this.isEmpty())return null;const e=this._barSpacing,t=5*((this._scalesProperties.childs().fontSize.value()||0)+4),i=Math.round(t/e),s=(0,n.ensureNotNull)(this.visibleBarsStrictRange()),o=Math.max(s.firstBar(),s.firstBar()-i),r=Math.max(s.lastBar(),s.lastBar()-i),a=this._tickMarks.build(e,t),l=[];for(const e of a){if(!(o<=e.index&&e.index<=r))continue;const t=this._tickMarks.indexToTime(e.index);null!==t&&l.push({coord:this.indexToCoordinate(e.index),label:this.formatLabel(t,e.span),span:e.span,major:e.label>=Lt.DAY_SPAN})}return l}visibleBarsStrictRange(){return this._visibleBarsInvalidated&&(this._visibleBarsInvalidated=!1,this._updateVisibleBars()),this._visibleBars.strictRange()} visibleBarsStrictRangeChanged(){return this._visibleBarsChanged}visibleStrictDataRange(e){const t=this.visibleBarsStrictRange();if(null===t)return null;const i=e.search(t.firstBar(),Ot.PlotRowSearchMode.NearestRight),s=e.search(t.lastBar(),Ot.PlotRowSearchMode.NearestLeft);return null===i||null===s?null:new yt.BarsRange(i.index,s.index)}visibleExtendedDataRange(e,t){const i=this.visibleBarsStrictRange();if(null===i)return null;let s=1===t?null:e.search(i.firstBar()-1,Ot.PlotRowSearchMode.NearestLeft),o=0===t?null:e.search(i.lastBar()+1,Ot.PlotRowSearchMode.NearestRight);return null===s&&(s=e.search(i.firstBar(),Ot.PlotRowSearchMode.NearestRight)),null===o&&(o=e.search(i.lastBar(),Ot.PlotRowSearchMode.NearestLeft)),null===s||null===o?null:new yt.BarsRange(s.index,o.index)}logicalRangeChanged(){return this._logicalRangeChanged}tickMarks(){return this._tickMarks}points(){return this._points}width(){return this._width}setWidth(e,t){if(!Number.isFinite(e)||e<=0)return void Gt.logWarn(`setWidth: invalid argument: ${e}`);if(this._width===e)return;const i=this._usePercentageRightOffset.value()&&this._rightOffset>0?this.barIndexLengthToPercents(this._rightOffset):-1;if(this._visibleBarsInvalidated=!0,(t||this._options.lockVisibleTimeRangeOnResize)&&this._width){const t=this._barSpacing*e/this._width;this._tryToUpdateBarSpacing(this._barSpacing,t)}else this._width&&this.setBarSpacing(this._barSpacing);if(null!==this._leftEdgeIndex){if((0,n.ensureNotNull)(this.visibleBarsStrictRange()).firstBar()<=this._leftEdgeIndex){const t=this._width-e;this._rightOffset-=Math.round(t/this._barSpacing)+1}}this._width=e,this._widthChanged.fire(e);const s=this._rightOffset;i>0?this._rightOffset=this.percentsToBarIndexLength(i):this.correctOffset(),this._rightOffset!==s&&this._rightOffsetChanged.fire(this._rightOffset),this._requestMoreData()}setLeftEdgeFix(e){this._leftEdgeIndex=e;const t=this.visibleBarsStrictRange();if(null===t)return;const i=t.firstBar()-e;if(i<0){const e=this._rightOffset-i-1;this.scrollToOffsetAnimated(e,500)}}indexToCoordinate(e){if(this.isEmpty())return 0;const t=this.baseIndex(),i=this._pointWeights.indexToTotalWeight(t+this._rightOffset+.5)-this._pointWeights.indexToTotalWeight(e);return this._width-i*this._barSpacing}indexToUserTime(e){return this._tickMarks.indexToTime(e)}timePointToIndex(e,t){switch(t){case 0:return this._points.indexOf(e,!1);case 1:return this._points.closestIndexLeft(e);default:return this._points.indexOf(e,!0)}}indexToTimePoint(e){return this._points.valueAt(e)}timeToCoordinate(e){const t=this._points.closestIndexLeft(e);if(null===t)return null;const i=(0,n.ensureNotNull)(this._points.valueAt(t)),s=this.indexToCoordinate(t);if(s<=0||s>=this._width)return null;const o=this.barSpacing(),r=this.baseIndex();let a;a=0===r?this._model.mainSeries().intervalObj().inMilliseconds()/1e3:(0,n.ensureNotNull)(this._points.valueAt(r))-(0,n.ensureNotNull)(this._points.valueAt(r-1));const l=s+(e-i)/a*o+1;return l<=0||l>=this._width?null:l}barBorders(e){const t={timePointIndex:e,left:NaN,center:NaN,right:NaN} ;return this.fillBarBorders([t]),t}fillBarBorders(e,t,i){var s,o;if(0===e.length)return;let r=null!==(s=null==t?void 0:t.startItemIndex)&&void 0!==s?s:0;const a=(null!==(o=null==t?void 0:t.endItemIndex)&&void 0!==o?o:e.length)-1;if(!0===i&&(r=(0,b.upperbound)(e,Mt.UNPLOTTABLE_TIME_POINT_INDEX,((e,t)=>ea)return;const l=this._pointWeights.indexToTotalWeight(this.baseIndex()+this._rightOffset+.5),c=this._pointWeights.indexRangeToWeights(e[r].timePointIndex,e[a].timePointIndex,this._weightedPointsCache);let d=0,h=c[d];const u=h,_=c[c.length-1];let p=NaN,m=NaN,g=NaN,S=!0;for(let t=r;t<=a;t+=1){const i=e[t];if(i.timePointIndex_.timePointIndex)g=_.right+(i.timePointIndex-_.timePointIndex),m=g-.5,p=g-1;else for(S&&(p=h.left,m=h.center,g=h.right,S=!1);h.timePointIndexe{void 0!==t&&t(),this._requestMoreData()};if(e){const e=this.logicalRange(),t=this._model.mainSeries().bars().lastIndex();if(null===e||null===t)return;const i=this.indexToCoordinate(e.right()+.5),o=this.indexToCoordinate(t+this._defaultRightOffset.value()+.5);return this._model.stopTimeScaleAnimation(),void this._model.setTimeScaleAnimation(new Vt.Animation({from:0,to:i-o,duration:1e3,easing:ft.easingFunc.easeInOutQuint,onFinish:s}))}this._visibleBarsInvalidated=!0,this._updateRightOffset(i),this._onScroll.fire(),s()}scrollToFirstBar(e=(()=>{})){this._model.gotoTime(new Date("1800-01-01").getTime()).then(e),this._onScroll.fire()}scrollToOffsetAnimated(e,t){if(!isFinite(e))throw new RangeError("offset is required and must be finite number");const i=void 0===t?400:t;if(!isFinite(i)||i<=0)throw new RangeError("animationDuration (optional) must be finite positive number");const s=this._rightOffset,o=Date.now(),r=()=>{this._visibleBarsInvalidated=!0;const t=(Date.now()-o)/i;if(t>=1)return this._updateRightOffset(e),this._visibleBarsInvalidated=!0,this._model.recalculateAllPanes((0, G.viewportChangeEvent)()),void this._model.lightUpdate();const n=s+(e-s)*t;this._updateRightOffset(n),this._model.recalculateAllPanes((0,G.viewportChangeEvent)()),setTimeout(r,20)};r()}defaultRightOffset(){return this._defaultRightOffset}rightOffsetDefaultValue(){return 10}defaultRightOffsetPercentage(){return this._defaultRightOffsetPercentage}usePercentageRightOffset(){return this._usePercentageRightOffset}barSpacing(){return this._barSpacing}setBarSpacing(e){Number.isFinite(e)?(e=this.getValidBarSpacing(e),this._tryToUpdateBarSpacing(this._barSpacing,e)&&(this.correctOffset(),this._options.preserveBarSpacing&&((0,A.allowSavingDefaults)(!0),this._scalesProperties.childs().barSpacing.setValue(this._barSpacing),(0,A.allowSavingDefaults)(!1)),this._model.recalculateAllPanes((0,G.viewportChangeEvent)()),this._model.lightUpdate())):Gt.logWarn(`setBarSpacing: invalid argument: ${e}`)}barSpacingChanged(){return this._barSpacingChanged}getValidBarSpacing(e){return null==e&&(e=this.barSpacing()),ethis.maxBarSpacing()?this.maxBarSpacing():e}isValidBarSpacing(e){return e>=this.minBarSpacing()&&e<=this.maxBarSpacing()}preserveBarSpacing(){return this._options.preserveBarSpacing}normalizeBarIndex(e){let t=0,i=0;const s=this.baseIndex(),o=(0,n.ensureNotNull)(this._points.range().value()).firstIndex;return es?(t=(0,n.ensureNotNull)(this._points.valueAt(s)),i=e-s):(t=(0,n.ensureNotNull)(this._points.valueAt(e)),i=0),{time_t:t,offset:i}}denormalizeTimePoint(e){const t=this._points.indexOf(e.time_t,!1);if(null!==t)return t+e.offset}rightOffset(){return this._rightOffset}rightOffsetChanged(){return this._rightOffsetChanged}minRightOffset(){var e;const t=null===(e=this.points().range().value())||void 0===e?void 0:e.firstIndex,i=this._baseIndex;if(void 0===t||null===i)return null;if(null!==this._leftEdgeIndex){const e=this.width()/this._barSpacing;return this._leftEdgeIndex-i+e-1}return t-i-1+Ut}maxRightOffset(){return this.width()/this._barSpacing-Ut}maxRightOffsetChanged(){return this._maxRightOffsetChanged}onReset(){return this._resetDelegate}baseIndex(){return this._baseIndex||0}zoom(e,t,i){if(!Number.isFinite(e)||!Number.isFinite(t))return void Gt.logWarn(`zoom: invalid arguments: ${e}, ${t}, ${i}`);const s=this.rightOffset(),o=void 0!==i?!i:this._options.rightBarStaysOnScroll,r=o&&this.usePercentageRightOffset().value()&&s>=0,n=r?this.barIndexLengthToPercents(s):void 0,a=this.coordinateToIndex(e),l=this.barSpacing(),c=l+t*(l/10);this.setBarSpacing(c),o||(this.startScroll(this.indexToCoordinate(a)),this.scrollTo(e),this.endScroll()),r&&void 0!==n&&this.setRightOffset(this.percentsToBarIndexLength(n)),this._requestMoreData()}zoomToBarsRange(e,t){if(null!==this._leftEdgeIndex&&(e=Math.max(e,this._leftEdgeIndex)),tthis._options.minBarSpacing}minBarSpacing(){return this._options.minBarSpacing}maxBarSpacing(){const e=this.width();return zt?e:e/Ut}minVisibleBarCount(){return Ut}resetRightOffset(){this.setRightOffset(this.targetDefaultRightOffset())}reset(){this._visibleBarsInvalidated=!0,this._points.clear(),this._scrollData=null,this._scaleStartPoint=null,this._clearCommonTransitionsStartState(),this._tickMarks.reset(),this._leftEdgeIndex=null,this._resetDelegate.fire(),this.disconnect()}resetAvailable(){return this._resetAvailable.readonly()}disconnect(){this._requestingMoreData=!1,this._requestedTickmarksCount=0,this._endOfData=!1}setBaseIndex(e){Number.isFinite(e)?(this._visibleBarsInvalidated=!0,this._baseIndex=e,this._pointWeights.setBaseIndex(this._baseIndex),this.correctOffset()):Gt.logDebug(`setBaseIndex: invalid argument: ${e}`)}resetBaseIndex(){this._visibleBarsInvalidated=!0,this._baseIndex=null}setRightOffset(e){Number.isFinite(e)?(this._visibleBarsInvalidated=!0,this._updateRightOffset(e)):Gt.logWarn(`setRightOffset: invalid argument: ${e}`)}correctBarSpacing(){this.isEmpty()||this.points().size()e&&(this._rightOffset=e,this._visibleBarsInvalidated=!0);const t=this.minRightOffset();null!==t&&this._rightOffset=0&&this.setRightOffset(this.percentsToBarIndexLength(s))}endScale(){null!==this._scaleStartPoint&&(this._scaleStartPoint=null,this._clearCommonTransitionsStartState(),this._requestMoreData())}startScroll(e){null===this._scrollData&&null===this._commonTransitionStartState&&(this.isEmpty()||(this._scrollData={startCoordinate:e,startRightEdgeLogical:this.baseIndex()+this._rightOffset+.5,startBaseIndex:this.baseIndex()},this._saveCommonTransitionsStartState()))}scrollTo(e){if(this._visibleBarsInvalidated=!0,null===this._scrollData)return;const{startCoordinate:t,startRightEdgeLogical:i,startBaseIndex:s}=this._scrollData,o=e-t,r=i+(this.baseIndex()-s),n=this.indexToCoordinate(r),a=this.coordinateToFloatIndex(n-o)-.5-this.baseIndex();this._updateRightOffset(a),this._onScroll.fire()}endScroll(){null!==this._scrollData&&(this._scrollData=null,this._clearCommonTransitionsStartState(),this._requestMoreData())}formatLabel(e,t){const i="24-hours"===Bt.timeHoursFormatProperty.value()?t.toString():`${t}_ampm`;let s=this._formattedBySpan.get(i);return void 0===s&&(s=new kt((e=>this.formatLabelImpl(e,t))),this._formattedBySpan.set(i,s)),s.format(new Date(e))}formatLabelImpl(e,t){if(!(e&&e instanceof Date))return"incorrect time";const s=function(e,t){if(e===Lt.MILLISECOND_SPAN&&t)return"TimeWithMilliseconds";if(e{e.onChanged().subscribe(null,(t=>this._onChanged.fire(e.id,t)))}))}groups(){return this._groups.filter((e=>e.isActualSymbol()))}groupsForAllSymbols(){return this._groups}createGroup(e,t,i){t=t||this._generateNextName();const s=new Yt.LineToolsGroup(e,t,i);this._groups.push(s),s.onChanged().subscribe(null,(e=>this._onChanged.fire(s.id,e)));const o={visibilityChanged:!1,lockedChanged:!1,isActualIntervalChanged:!1,affectedLineTools:e.map((e=>e.id()))};return this._onChanged.fire(s.id,o),s}addGroup(e){this._groups.push(e),e.onChanged().subscribe(null,(t=>this._onChanged.fire(e.id,t))),this._onChanged.fire(e.id)}removeGroup(e){const t=this._groups.findIndex((t=>t.id===e.id));this._groups.splice(t,1),this._onChanged.fire(e.id)}groupForId(e){return this._groups.find((t=>t.id===e))||null}groupForLineTool(e){return this._groups.find((t=>t.containsLineTool(e)))||null}removeLineTools(e){const t=new Set;this._groups.forEach((i=>{const s=e.filter(i.containsLineTool.bind(i));s.length&&(i.excludeLineTools(s),t.add(i.id))}));return this._groups.filter((e=>0===e.lineTools().length)).forEach((e=>this.removeGroup(e))),Array.from(t)}state(e){return{groups:(e?this._groups.filter((e=>e.isActualSymbol())):this._groups).map((e=>e.state()))}}onChanged(){return this._onChanged}fireChangedAll(){this._groups.forEach((e=>{this._onChanged.fire(e.id)}))}static fromState(e,t){const i=[];for(const s of t.groups){const t=Yt.LineToolsGroup.fromState(e,s);null!==t&&i.push(t)}return new $t(i)}_generateNextName(){const e=new Set(this.groups().map((e=>e.name().value())));for(let t=1;;t++){const i=`Group ${t}`,s=`Group_${t}`;if(!e.has(i)&&!e.has(s))return i}}}var Xt=i(988124),Jt=i.n(Xt),Qt=i(547944);let ei=null;function ti(e){return Boolean(e.symbolInfo.timezone)&&Boolean(e.symbolInfo.session)}class ii{constructor(e,t){var i,s;this._sourceTargetBarBuilder=null,this._cache=new Map,this._source=e,this._sourceSession=Qt.SessionInfo.fromState(e.session),this._target=t,this._targetSession=Qt.SessionInfo.fromState(t.session),this._isResolutionTheSame=I.Interval.isEqual(e.resolution,t.resolution)||I.Interval.isTicks(e.resolution)&&I.Interval.isTicks(t.resolution),this._isSessionTheSame=(i=e.symbolInfo,s=t.symbolInfo,i.timezone===s.timezone&&i.session===s.session&&i.session_holidays===s.session_holidays&&i.corrections===s.corrections),this._shouldCorrectTradingDay=I.Interval.isDWM(e.resolution)&&!this._isSessionTheSame}sourceTimeToTargetTime(e){if(this._isSessionTheSame&&this._isResolutionTheSame)return e;if(!ti(this._source)||!ti(this._target))return e;let t=this._cache.get(e);if(void 0===t){let i=1e3*e;if(this._shouldCorrectTradingDay){ let e=Jt().utc_to_cal(this._sourceSession.timezone,i);e=this._sourceSession.spec.correctTradingDay(e);const t=new Date(e);Jt().set_hms(t,0,0,0,0,this._sourceSession.timezone),i=t.valueOf()}const s=this._sourceTargetBuilder();s.moveTo(i);const o=s.indexOfBar(i);t=s.startOfBar(Math.max(0,o))/1e3,this._cache.set(e,t)}return t}_sourceTargetBuilder(){if(null===this._sourceTargetBarBuilder){const e=this._isSessionTheSame?this._targetSession:(null===ei&&(ei=new Qt.SessionInfo("Etc/UTC","24x7")),ei);this._sourceTargetBarBuilder=(0,Qt.newBarBuilder)(this._target.resolution,this._targetSession,e)}return this._sourceTargetBarBuilder}}var si=i(638456),oi=i(314802),ri=i(86746);const ni="#000000";var ai=i(558793);async function li(e){(await(0,ai.getChartAlertsFacade)()).invokeAlertEditor(e)}class ci{constructor(e){this._alertLabelsBySource=new Map,this._alertsByAlertSeriesId=new Map,this._alertSeriesIdByAlert=new Map,this._alertLabelsOwnerSourcesByAlert=new Map,this._chartModel=e}destroy(){this.removeAllAlertLabels()}removeAllAlertLabels(){const e=this._alertLabelsBySource;this._alertLabelsBySource=new Map,this._alertsByAlertSeriesId.clear(),this._alertSeriesIdByAlert.clear(),this._alertLabelsOwnerSourcesByAlert.clear(),e.forEach((e=>{e.forEach((e=>this._chartModel.removeSource(e)))}))}removeSourceAlertLabels(e){for(const t of this._getAlertLabelsBySource(e))this.removeAlertLabel(t)}syncSourceAlertLabels(e){if(!(0,Me.isPriceDataSource)(e)||!e.hasStateForAlert())return;for(const t of this._getAlertLabelsBySource(e))t.alertOwnerSource().idForAlert()===t.alertSeriesId()||t.alert().isOHLC()||this.removeAlertLabel(t);const t=this._alertsByAlertSeriesId.get(e.idForAlert()),i=this._getAlertLabelsBySource(e);void 0!==t&&t.forEach((e=>{i.some((t=>t.alert()===e))||this._updateAlertLabelsByAlert(e,(0,n.ensureDefined)(this._alertSeriesIdByAlert.get(e)))}));const s=(0,n.ensureNotNull)(this._chartModel.paneForSource(e));for(const t of this._getAlertLabelsBySource(e)){const i=this._chartModel.paneForSource(t);i!==s?(null!==i&&i.removeDataSource(t),s.addDataSource(t,(0,n.ensureNotNull)(e.priceScale()),!1)):e.priceScale()!==t.priceScale()&&s.move(t,(0,n.ensureNotNull)(e.priceScale()))}}detachSourceAlertLabels(e){for(const t of this._getAlertLabelsBySource(e))this._chartModel.detachSource(t)}removeAlertLabel(e){const t=e.alertOwnerSource(),i=this._alertLabelsBySource.get(t);void 0!==i&&(i.delete(e),0===i.size&&this._alertLabelsBySource.delete(t));const s=e.alert(),o=this._alertLabelsOwnerSourcesByAlert.get(s);void 0!==o&&(o.delete(t),0===o.size&&this._alertLabelsOwnerSourcesByAlert.delete(s)),this._chartModel.removeSource(e)}addAlert(e,t){(0,n.assert)(!this._alertSeriesIdByAlert.has(e),"Alert is already added on the chart"),this._alertSeriesIdByAlert.set(e,t);let i=this._alertsByAlertSeriesId.get(t);void 0===i&&(i=new Set,this._alertsByAlertSeriesId.set(t,i)),i.add(e),this._updateAlertLabelsByAlert(e,t)}removeAlert(e){const t=this._alertLabelsOwnerSourcesByAlert.get(e);void 0!==t&&t.forEach((t=>{const i=this._alertLabelsBySource.get(t) ;void 0!==i&&i.forEach((t=>{t.alert()===e&&this.removeAlertLabel(t)}))}));const i=this._alertSeriesIdByAlert.get(e);if(!i)return;this._alertSeriesIdByAlert.delete(e);const s=this._alertsByAlertSeriesId.get(i);void 0!==s&&s.delete(e)}_findPanes(e){const t=[];for(const i of this._chartModel.panes()){const s=i.priceDataSources(),o=new Set;for(const t of s)t.hasStateForAlert()&&t.idForAlert()===e&&o.add(t);o.size>0&&t.push({pane:i,sources:o})}return t}_addLabelToPane(e,t,i,s){const o=new y.AlertLabel(this._chartModel,e,s,li);i.addDataSource(o,s.priceScale(),!1);let r=this._alertLabelsBySource.get(s);void 0===r&&(r=new Set,this._alertLabelsBySource.set(s,r)),r.add(o);let n=this._alertLabelsOwnerSourcesByAlert.get(e);void 0===n&&(n=new Set,this._alertLabelsOwnerSourcesByAlert.set(e,n)),n.add(s)}_updateAlertLabelsByAlert(e,t){const i=this._findPanes(t);if(i.length)for(const s of i)s.sources.forEach((i=>this._addLabelToPane(e,t,s.pane,i)));else if(e.isOHLC()){const i=this._chartModel.mainSeries();this._addLabelToPane(e,t,(0,n.ensureNotNull)(this._chartModel.paneForSource(i)),i)}this._chartModel.lightUpdate()}_getAlertLabelsBySource(e){const t=this._alertLabelsBySource.get(e);return void 0===t?[]:Array.from(t)}}var di=i(993171),hi=i(960337),ui=i(778016),_i=i(690142),pi=i(922850),mi=i(371927),gi=i(275028),Si=i(315801),vi=i(458963),fi=i(246733),bi=i(838042),yi=i(792795);function Ci(e,t){return e.codet.code?1:0}class wi{constructor(e){this._convertibleItems=e,this._idsToItems=new Map;for(const t of e)this._idsToItems.set(t.id,t)}convertible(e){return void 0!==this._idsToItems.get(e)}item(e){var t;return null!==(t=this._idsToItems.get(e))&&void 0!==t?t:null}size(){return this._convertibleItems.length}filterConvertible(e,t){const i=this._convertibleItems.filter(function(e,t){return i=>!e.has(i.id)&&t(i.id)}(e,t));return i.sort(Ci),i}getItems(){return this._convertibleItems.map((e=>e.id))}}class Pi{constructor(e){this._allGroups=new Set,this._idToName=new Map,this._idToDescription=new Map,this._groupedUnitIds=new Map,this._groupedUnits=new Map,this._groupById=new Map,this._size=0,this._units=e;for(const t in e)if(e.hasOwnProperty(t)){this._allGroups.add(t),this._groupedUnitIds.set(t,new Set(e[t].map((e=>e.id)))),this._groupedUnits.set(t,e[t]);for(const i of e[t])this._size++,this._idToName.set(i.id,i.name),this._idToDescription.set(i.id,i.description),this._groupById.set(i.id,t)}}unitsChanged(e){return this._units!==e}size(){return this._size}name(e){return this._idToName.get(e)||e}description(e){return this._idToDescription.get(e)||e}unitGroupById(e){return this._groupById.get(e)||null}allGroups(){return new Set(this._allGroups)}unitsByGroups(e){const t=[];return e.forEach((e=>{const i=this._groupedUnits.get(e);void 0!==i&&t.push({name:e,units:i})})),t}convertible(e,t){for(const i of t){const t=this._groupedUnitIds.get(i);if(void 0!==t&&t.has(e))return!0}return!1}}var Ti=i(150335);class Mi{constructor(e){this._source=null,this._sourcePane=null,this._currentToolSupportsPhantomMode=!1,this._model=e}destroy(){ this._source=null,this._sourcePane=null}source(){return this._source}onToolChanged(){this._removeSource();const e=this._model.currentTool();this._currentToolSupportsPhantomMode=(0,De.isLineToolName)(e)&&(0,C.supportsPhantomMode)(e)}onCursorPositionUpdated(){if(!this._currentToolSupportsPhantomMode)return;const e=this._model.crossHairSource();if(this._sourcePane!==e.pane&&this._removeSource(),null===e.pane||!(0,Ti.isNumber)(e.index)||!(0,Ti.isNumber)(e.price))return void this._removeSource();const t={index:e.index,price:e.price};null!==this._source?this._source.setPoint(0,t):(this._source=this._model.createLineTool({pane:e.pane,point:t,linetool:this._model.currentTool()}),this._sourcePane=e.pane)}_removeSource(){null!==this._source&&(this._model.removeSource(this._source),this._source=null,this._sourcePane=null)}}var xi=i(315347),Ii=i(80646),Ai=i(451798);class Li{constructor(){this._lastValue=null}align(e,t,i){this._lastValue=null;let s=e;if(!(0,Ai.magnetEnabled)().value())return s;const o=i.mainDataSource();if(null===o)return s;const r=o.model().mainSeries();if(o!==r)return s;const a=r.priceScale();if(a.isEmpty())return s;const l=function(e,t){const i=e.bars().valueAt(t);if(null===i)return;let s;if(null!==e.priceSource())s=[e.barFunction()(i)];else switch(e.style()){case 12:s=[i[2],i[3]];break;case 16:s=[i[2],i[4],i[3]];break;default:s=[i[1],i[2],i[3],i[4]]}return s}(r,t);if(!l)return s;const c=(0,n.ensure)(r.firstValue()),d=l.map((e=>({y:a.priceToCoordinate(e,c),price:e}))),h=a.priceToCoordinate(e,c);d.sort(((e,t)=>Math.abs(e.y-h)-Math.abs(t.y-h)));const u=d[0];return((0,Ai.magnetMode)().value()===Ii.MagnetMode.StrongMagnet||Math.abs(u.y-h)<50)&&(s=u.price,this._lastValue=s),s}lastValue(){return this._lastValue}resetLastValue(){this._lastValue=null}}var ki=i(242558),Ei=i(787123),Di=i(43192);class Bi extends Di.BitmapCoordinatesPaneRenderer{constructor(){super(...arguments),this._data=null}setData(e){this._data=e}hitTest(e){return null}_drawImpl(e){if(null===this._data)return;const{context:t,verticalPixelRatio:i,horizontalPixelRatio:s,bitmapSize:o}=e,r=Math.max(1,Math.floor(s));t.lineWidth=r;const n=Math.ceil(o.height*i),a=Math.ceil(o.width*s);if(t.lineCap="butt",this._data.vertLinesVisible){t.strokeStyle=this._data.vertLinesColor,(0,Ei.setLineStyle)(t,this._data.vertLineStyle);for(const e of this._data.timeMarks){const i=Math.round(e.coord*s);(0,Ei.drawVerticalLine)(t,i,0,n)}}if(this._data.horzLinesVisible){t.strokeStyle=this._data.horzLinesColor,(0,Ei.setLineStyle)(t,this._data.horzLineStyle);for(const e of this._data.priceMarks){const s=Math.round(e.coord*i);(0,Ei.drawHorizontalLine)(t,s,0,a)}}}}class Ni{constructor(e){this._renderer=new Bi,this._pane=e}update(){}renderer(){const e=this._pane.defaultPriceScale(),t=this._pane.model().timeScale();if(e.isEmpty()||t.isEmpty())return null;const i=this._pane.model().properties().childs().paneProperties.childs(),s=t.marks(),o=i.gridLinesMode.value(),r={horzLinesVisible:"both"===o||"horz"===o,vertLinesVisible:"both"===o||"vert"===o, horzLinesColor:i.horzGridProperties.childs().color.value(),vertLinesColor:i.vertGridProperties.childs().color.value(),horzLineStyle:i.horzGridProperties.childs().style.value(),vertLineStyle:i.vertGridProperties.childs().style.value(),priceMarks:e.marks(),timeMarks:null!==s?s:[]};return this._renderer.setData(r),this._renderer}}class Ri extends ae.DataSource{id(){return"grid"}paneViews(e){return[new Ni(e)]}name(){return"Grid"}}var Oi=i(229765);class Vi extends Oi.PriceAxisView{constructor(e,t,i,s){super(),this._source=e,this._pane=t,this._priceScale=i,this._priceProvider=s,this._properties=e.model().properties().childs().scalesProperties}setHitTestData(e){this._hitTestData=e}setXCoord(e){this._xCoord=e}additionalPadding(e){return 0}_updateRendererData(e,t,i){e.visible=!1,t.visible=!1;const s=this._priceScale,o=s.mainSource(),r=null!==o?o.firstValue():null;if(!this._isVisible()||s.isEmpty()||null===r)return;const n=this._currentPrice(s);if(null===n)return;i.background=(0,fi.resetTransparency)(this._bgColor()),i.textColor=this.generateTextColor(i.background);const a=this.additionalPadding(s.fontSize());i.additionalPaddingTop=a,i.additionalPaddingBottom=a,i.coordinate=s.priceToCoordinate(n,r),e.text=s.formatPrice(n,r),e.visible=!0,t.visible=!0,t.hitTestData=this._hitTestData,t.xCoord=this._xCoord}_currentPrice(e){return this._priceProvider(e)}}class Wi extends Vi{additionalPadding(e){return 2/12*e}_isVisible(){const e=this._source.lockedPane();return this._properties.childs().showPriceScaleCrosshairLabel.value()&&(this._source.visible||null!==e)&&(null!=e?e:this._source.pane)===this._pane}_currentPrice(e){const t=je.crosshairLock.value();return null!==t&&1===t.type?this._pane===this._source.lockedPane()?t.price:null:super._currentPrice(e)}_bgColor(){const e=this._properties.childs();return this._source.model().dark().value()?e.crosshairLabelBgColorDark.value():e.crosshairLabelBgColorLight.value()}_updateRendererData(e,t,i){const s=t.visible;super._updateRendererData(e,t,i),this._source.isHovered()?t.backgroung=this._source.model().dark().value()?c.colorsPalette["color-cold-gray-600"]:c.colorsPalette["color-cold-gray-650"]:t.backgroung=void 0,s||(t.visible=s)}}class Fi extends Vi{_isVisible(){return null!==this._source.measurePane().value()}_bgColor(){return this._properties.childs().axisLineToolLabelBackgroundColorCommon.value()}}var Hi=i(742391),zi=i(439016),Ui=i(406849),Gi=i(373571),qi=i(461794),ji=i(167222),Zi=i(703089),Ki=i(726778),Yi=i(976737),$i=i(651065),Xi=i(783375),Ji=i(982217),Qi=i(360758),es=i(747971);function ts(e){const t=e.priceScale();return null===t?0:t.isPercentage()||t.isIndexedTo100()?2:1}class is extends Hi.PanePriceAxisView{constructor(e,t,i,s,o){super(e,t,s),this._crossHairMenuCachedState=null,this._hasActions=!1,this._gaOrigin="CH menu",this._crosshairPriceAxisView=e,e.setPaneRendererLabelIcon(0),this._crosshair=t,this._scale=i,this._options=o,this._updateGaOrigin(),(0,zi.waitTradingService)().then((()=>{this._crossHairMenuCachedState=null}))}_updateImpl(e){ const t=this._crosshair.y,i=this._chartModel.properties().childs().scalesProperties.childs().fontSize.value(),s=this._chartModel.timeScale().width(),o=this._crosshair.model().priceAxisRendererOptions(),r=i+2*this._crosshairPriceAxisView.additionalPadding(i)+o.paddingTop+o.paddingBottom,n=r,l=t-r/2,c=this._crosshair.pane,d=this._mainDataSourceOnPane(),h=d&&d.symbolSource(),u=!!h&&(h.isConvertedToOtherCurrency()||h.isConvertedToOtherUnit());if(this._updateGaOrigin(),null!==d){const e=ts(d),t=d.idForAlert(),i=this._chartModel.isInReplay().value(),s=this._crossHairMenuCachedState,o=H.enabled("chart_crosshair_menu");null!==s&&s.id===t&&s.priceScale===e&&s.isCurrencyOrUnitConverted===u&&s.isInReplay===i&&s.isMenuEnabled===o||(this._updateTooltipAndActionsAvailability(d,e,u),this._crossHairMenuCachedState={id:t,priceScale:e,isCurrencyOrUnitConverted:u,isInReplay:i,isMenuEnabled:o})}null!==d&&(0,Oe.isActingAsSymbolSource)(d)&&d.symbol();const _=null!==c&&(c.maximized().value()||!c.collapsed().value())&&this._hasActions;this._crosshairPriceAxisView.setPaneLabelVisible(_);const p=this._position();if(null!==p){const e=0,t=s-n,i=Boolean(Qi.showPlusButtonOnCursor.value()),o=i?this._crosshair.x:void 0,c=void 0!==o?o-n/2:"left"===p?e:t,d=void 0!==o?o+n/2:"left"===p?e+n:t+n,h=(0,a.box)(new a.Point(c,l),new a.Point(d,l+r));this._data={itemBox:h,clickHandler:this._handleClick.bind(this,p,i,h)},this._crosshairPriceAxisView.setHitTestData(this._data),this._crosshairPriceAxisView.setXCoord(o)}super._updateImpl(e)}_priceScale(){return this._scale}_updateGaOrigin(){this._gaOrigin=Boolean(Qi.showPlusButtonOnCursor.value())?"CH menu cursor":"CH menu"}_updateTooltipAndActionsAvailability(e,t,i){this._hasActions=!1;if(!(1===t))return;const s=!this._chartModel.isInReplay().value(),o=!i&&e.alertCreationAvailable().value()&&s,r=!this._options.disableDrawHorizLineMenuAction,n=!i&&e===this._chartModel.mainSeries()&&Boolean((0,zi.tradingService)())&&s;this._hasActions=n||o||r}_handleClick(e,t,i,s,o){if(H.enabled("widget")&&H.enabled("referral_program_for_widget_owners"))return void(0,Zi.showGoToTradingViewReferralDialog)({feature:"plusMenu"});(0,_.trackEvent)(this._gaOrigin,"click");const r=this._mainDataSourceOnPane(),n=null!==r&&(0,Oe.isActingAsSymbolSource)(r)?r.symbol():null,a={pageX:o.pageX,pageY:o.pageY,clientX:o.clientX,clientY:o.clientY,screenX:o.screenX,screenY:o.screenY,price:this._crosshair.price,symbol:n};m.emit("onPlusClick",a),this._getMenuItems(e).then((s=>{s.length>0&&this._showContextMenu(s,t,i,o,e)}))}_getMenuItems(e){const t=this._chartModel.mainSeries(),i=t.symbolInfo(),s=this._options.disableTradingMenuActions?null:(0,zi.tradingService)(),o=(0,n.ensureNotNull)(this._crosshair.pane).mainDataSource(),r=!this._chartModel.isInReplay().value(),a=r,l=o===t&&!(0,$i.isNonTradableSymbolType)(null==i?void 0:i.type)&&Boolean(s)&&r,c=a?this._createAlertMenuItems(e):Promise.resolve([]),d=l?this._createTradingMenuItems():Promise.resolve([]);return Promise.all([c,d]).then((([e,t])=>{t.length>0&&(0, n.ensureNotNull)(s).trackEvent(this._gaOrigin,"click");const i=this._createAddHorizontalLineMenuItem(),o=e.length>0&&t.length>0;return[...e,o?new Gi.Separator:null,...t,(e.length>0||t.length>0)&&i.length>0?new Gi.Separator:null,...i].filter((e=>null!==e))}))}_createAlertMenuItems(e){if(null===this._crosshair.pane)return Promise.resolve([]);const t=this._crosshair.pane.mainDataSource();if(null===t)return Promise.resolve([]);const i=t.symbolSource();if(!!i&&(i.isConvertedToOtherCurrency()||i.isConvertedToOtherUnit()))return Promise.resolve([]);const s=this._crosshair.y;if(this._options.menuForMainSourceOnly){if(t.alertCreationAvailable().value()&&t.isVisible()){const e=this._getActionAddAlert({source:t,y:s,isDisabled:!1});return Promise.resolve(null===e?[]:[e])}return Promise.resolve([])}const o=(0,n.ensureNotNull)(this._crosshair.pane).sourcesByGroup();let r=("left"===e?o.leftPriceScalesSources():o.rightPriceScalesSources()).filter((e=>(0,Me.isPriceDataSource)(e)&&e.alertCreationAvailable().value()&&e.isVisible()));return r.reverse(),r=(0,b.moveToHead)(r,this._chartModel.mainSeries()),(0,Ki.filterAccessibleDataSources)(r).then((e=>{const t=new Set(e),i=[];for(const e of r){const o=this._getActionAddAlert({source:e,y:s,isDisabled:!t.has(e)});null!==o&&i.push(o)}return i}))}_createTradingMenuItems(){const e=this._crosshair.y,t=(0,zi.tradingService)();if(null===t||null===this._crosshair.pane)return Promise.resolve([]);const i=this._crosshair.pane.mainDataSource();if(null===i)return Promise.resolve([]);const s=i.symbolSource(),o=!!s&&(s.isConvertedToOtherCurrency()||s.isConvertedToOtherUnit()),r=ts(i);return o||1!==r?Promise.resolve([]):(0,Ui.createTradeContext)(i,e).then((e=>t.chartContextMenuActions(e,{onlyMainActions:!0,hideNotExecutableAction:!0,gaOrigin:this._gaOrigin})))}_createAddHorizontalLineMenuItem(){if(null===this._crosshair.pane)return[];const e=this._crosshair.pane.mainDataSource();if(null===e)return[];const t=this._crosshair.y,i=this._getActionAddHorizontalLine({source:e,y:t,pane:this._crosshair.pane});return null===i?[]:[i]}_getActionAddAlert(e){const{source:t,y:s,isDisabled:o}=e,r=this._getValue(t,s),n=this._chartModel.mainSeries().interval();if(null===r||I.Interval.isTicks(n))return null;const a=this._formatValue(r,t),l=function(e){return(0,Oe.isActingAsSymbolSource)(e)?e.symbolTitle(Ji.TitleDisplayTarget.StatusLine,!0,!0):(0,qi.clean)(e.title(Ji.TitleDisplayTarget.StatusLine,!0,{},!0),!0)}(t),c={label:(0,Yi.hasUsualAlertPlots)(t)?d.t(null,{replace:{title:l,price:a}},i(107005)):d.t(null,{replace:{title:l}},i(764615)),iconId:"Alert.Add"};return o?c.disabled=!0:c.onExecute=()=>this._addAlert(r,t),new es.ActionWithStandardIcon({actionId:"Alert.Add",options:c})}_getActionAddHorizontalLine(e){if(this._options.disableDrawHorizLineMenuAction)return null;const{source:t,y:s,pane:o}=e,r=this._getValue(t,s);if(null===r)return null;const n=this._formatValue(r,t),a={label:d.t(null,void 0,i(508338))+` ${n}`,iconId:"Chart.AddHorzLine"};return a.onExecute=()=>this._addHorizontalLineTool(o,r), new es.ActionWithStandardIcon({actionId:"Chart.Crosshair.PlusButton.DrawHorizontalLine",options:a})}_getValue(e,t){const i=e.priceScale(),s=e.firstValue();if(null===i||null===s)return null;return i.isPercentage()||i.isIndexedTo100()?null:i.coordinateToPrice(t,s)}_formatValue(e,t){return t.formatter().format(e)}async _addAlert(e,t){const s=await async function(){const{invokeAlertEditorWithOnlineSeries:e}=await Promise.all([i.e(61285),i.e(94949),i.e(29589),i.e(22172)]).then(i.bind(i,429589));return e}(),o=async()=>{const i={dataSourceHub:this._chartModel,silent:!0,actionSource:"crosshair_menu"};(0,C.isLineTool)(t)?i.drawing=t:(i.series=t,i.value=e),s(i),(0,_.trackEvent)(this._gaOrigin,"alert")};(0,ji.runOrSigninWithFeature)((()=>o()),{feature:"alert",source:this._gaOrigin})}_addHorizontalLineTool(e,t){this._chartModel.undoModel().createLineTool({pane:e,point:{price:t,index:0},linetool:"LineToolHorzLine"})}_showContextMenu(e,t,i,s,o){const r="left"===o;setTimeout((()=>{const o=s.clientX-s.localX,a=s.clientY-s.localY,l=i.min.x+o,c=i.max.x+o,d=i.min.y+a,h=c-l,u=i.max.y+a-d,_=t?je.crosshairLock.value():void 0;if(void 0!==_){const e=(0,n.ensureNotNull)(this._chartModel.timeScale().points().roughTime(this._crosshair.index));je.crosshairLock.setValue({type:1,price:this._crosshair.price,time:e,modelId:this._chartModel.id(),paneId:(0,n.ensureNotNull)(this._crosshair.pane).id()})}Xi.ContextMenuManager.showMenu(e,{clientX:s.clientX,clientY:s.clientY,box:{x:l,w:h,y:d,h:u},attachToXBy:t?"auto":r?"left":"right",attachToYBy:"auto-strict",marginX:t?0:-h},void 0,{menuName:"CrosshairMenuView"},(()=>{void 0!==_&&je.crosshairLock.setValue(_)}))}))}_mainDataSourceOnPane(){const e=this._crosshair.pane;return null!==e?e.mainDataSource():null}}var ss=i(86121);class os extends Di.BitmapCoordinatesPaneRenderer{constructor(e){super(),this._data=e}hitTest(e){return void 0===this._data.clickHandler?null:new Si.HitTestResult(Si.HitTarget.Custom,{clickHandler:this._data.clickHandler,tapHandler:this._data.clickHandler})}_drawImpl(e){const t=this._data.vertLinesVisible,i=this._data.horzLinesVisible;if(!t&&!i)return;const{context:s,horizontalPixelRatio:o,verticalPixelRatio:r,bitmapSize:n}=e;s.lineWidth=Math.max(1,Math.floor(this._data.lineWidth*o)),s.strokeStyle=this._data.color,s.fillStyle=this._data.color,s.lineCap="butt",(0,Ei.setLineStyle)(s,this._data.lineStyle);const a=Math.round(this._data.x*o),l=Math.round(this._data.y*r),c=Math.ceil(n.width*o),d=Math.ceil(n.height*r);t&&a>=0&&(0,Ei.drawVerticalLine)(s,a,0,d),i&&l>=0&&(0,Ei.drawHorizontalLine)(s,l,0,c),this._data.drawCenter&&(s.beginPath(),s.arc(a,l,Math.round(3*o),0,2*Math.PI,!0),s.fillStyle=this._data.color,s.fill()),this._data.scissors&&function(e,t,i){const{context:s,bitmapSize:o,horizontalPixelRatio:r,verticalPixelRatio:n}=e,a=24*r,l=Math.round(t-a/2);let c=Math.round(i-a/2);if(c<0)c=0;else{const e=o.height-a;c>e&&(c=e)}s.translate(l,c),s.scale(r,n),s.fillStyle="#131722",s.fill(rs),s.strokeStyle="#fff",s.lineWidth=1,s.stroke(rs)}(e,a,l)}} const rs=new Path2D("m15.68 3.72-3.82 5.52-3.83-5.52-.28-.42-.42.3a2.84 2.84 0 0 0-.68 3.92l3.27 4.73-1.16 1.68a3.34 3.34 0 0 0-4.26 3.22 3.34 3.34 0 0 0 3.32 3.35 3.34 3.34 0 0 0 3.08-4.6l1-1.44 1.13 1.62a3.34 3.34 0 0 0 3.15 4.42c1.84 0 3.32-1.5 3.32-3.35a3.34 3.34 0 0 0-4.42-3.17l-1.23-1.78 3.22-4.65a2.86 2.86 0 0 0-.69-3.96l-.41-.29-.29.42ZM7.82 16.27c.47 0 .86.39.86.88 0 .48-.39.87-.86.87a.87.87 0 0 1-.86-.87c0-.5.4-.88.86-.88Zm8.36 0c.47 0 .86.39.86.88 0 .48-.4.87-.86.87a.87.87 0 0 1-.86-.87c0-.5.39-.88.86-.88Z");const ns=c.colorsPalette["color-tv-blue-500"];class as{constructor(e,t){this._rendererData={},this._renderer=new os(this._rendererData),this._source=e,this._pane=t}update(){}renderer(){var e,t;const i=this._source.selectPointMode().value()!==je.SelectPointMode.None,s=this._source.lockedPane(),o=(this._source.visible||null!==s)&&(this._source.areLinesVisible||i)&&!this._source.linesShouldBeHidden(),r=this._rendererData;if(!o||null===this._pane)return null;const a=this._source.paneForPointSelect(),l=this._source.isReplaySelection(),c=null!=s?s:this._source.pane,d=this._pane===c,h=l||(null!==a?c===a&&this._pane===a:d);if(r.scissors=!1,i&&(l||this._source.isOnHoveredChartWidget())&&h){const e=(0,n.ensureNotNull)(this._source.pointToSelect());r.color=this._source.lineColor()||ns,l?(r.lineWidth=2,r.scissors=d):r.lineWidth=1,r.lineStyle=vi.LINESTYLE_SOLID,r.horzLinesVisible=!0,r.vertLinesVisible=!0,r.drawCenter=!1,"time"===e?r.horzLinesVisible=!1:"price"===e&&(r.vertLinesVisible=!1)}else{const e=this._source.properties(),t=this._source.model().currentTool(),i=(0,ss.lastMouseOrTouchEventInfo)(),s=i.isTouch&&!i.stylus&&((0,De.isLineToolName)(t)||(0,je.toolIsMeasure)(t));let o;o=s?ns:e.childs().color.value();const n=e.childs().transparency.value();!s&&n>0&&(o=(0,fi.generateColor)(o,n)),r.color=o,r.horzLinesVisible=this._pane===c&&(this._pane.maximized().value()||!this._pane.collapsed().value()),r.vertLinesVisible=!0,r.lineWidth=e.childs().width.value(),r.lineStyle=e.childs().style.value(),r.drawCenter=s&&this._pane===c}return r.x=null!==(e=this._source.lockedX())&&void 0!==e?e:this._source.x,r.y=null!==(t=this._source.lockedY())&&void 0!==t?t:this._source.y,this._renderer}}var ls=i(189767);const cs={backgroundColor:(0,fi.generateColor)(c.colorsPalette["color-tv-blue-500"],70),borderColor:(0,fi.generateColor)(c.colorsPalette["color-tv-blue-500"],20)};class ds{constructor(e){this._renderer=new ls.RectangleRenderer,this._rectangle=null,this._crosshair=e}update(){const e=this._crosshair.selection();null!==e&&null!==this._crosshair.pane?this._rectangle=this._crosshair.pane.logicalRectToPixels(e):this._rectangle=null}renderer(){if(!this._rectangle)return null;const e={backcolor:cs.backgroundColor,color:cs.borderColor,fillBackground:!0,linewidth:1,points:[this._rectangle.min,this._rectangle.max],extendLeft:!1,extendRight:!1};return this._renderer.setData(e),this._renderer}}var hs=i(31341),us=i(754480),_s=i(541801),ps=i(535698),ms=i(142119),gs=i(855152);const Ss=d.t(null,void 0,i(33355)),vs=d.t(null,{context:"study" },i(32819)),fs=(0,Ze.getPercentageFormatter)(),bs=new us.TimeSpanFormatter,ys=(0,Ze.getVolumeFormatter)(),Cs=(0,c.getHexColorByName)("color-tv-blue-500"),ws=(0,c.getHexColorByName)("color-ripe-red-400"),Ps={bgColorPositive:(0,fi.generateColor)(Cs,80),bgColorNegative:(0,fi.generateColor)(ws,80),colorPositive:(0,c.getHexColorByName)("color-tv-blue-600"),colorNegative:(0,c.getHexColorByName)("color-ripe-red-400"),labelBgColorPositive:Cs,labelBgColorNegative:ws};class Ts{constructor(e,t){this._horzTrenRenderer=new _s.TrendLineRenderer,this._vertTrenRenderer=new _s.TrendLineRenderer,this._bgRenderer=new ls.RectangleRenderer,this._labelRenderer=new ps.TextRenderer,this._p1=null,this._p2=null,this._label=null,this._source=e,this._pane=t}update(e){var t,i;const[s,o]=this._source.measurePoints();if(void 0===o)return this._p1=null,void(this._p2=null);const r=(0,n.ensureNotNull)(this._source.measurePane().value()),l=s.price,c=o.price,d=o.index-s.index,h=(0,hs.forceLTRStr)(""+d),u=(0,n.ensureNotNull)(r.mainDataSource()),_=(0,n.ensureNotNull)(u.formatter()),p=o.price-l;let m=null!==(i=null===(t=_.formatChange)||void 0===t?void 0:t.call(_,o.price,l))&&void 0!==i?i:_.format(p);if(Math.abs(l)>1e-8){const e=p/Math.abs(l);m+=" ("+fs.format(100*e)+")"}const g=(0,hs.forceLTRStr)(m);this._label=g+"\n"+Ss.format({count:h});const S=(0,n.ensureNotNull)(u.firstValue()),v=this._source.model().timeScale().indexToCoordinate(s.index),f=this._source.model().timeScale().indexToCoordinate(o.index),b=r.defaultPriceScale().priceToCoordinate(l,S),y=r.defaultPriceScale().priceToCoordinate(c,S);this._p1=new a.Point(v,b),this._p2=new a.Point(f,y);const C=this._source.model().timeScale().indexToUserTime(s.index),w=this._source.model().timeScale().indexToUserTime(o.index);let P=null;null!==C&&null!==w&&(P=(w.valueOf()-C.valueOf())/1e3);const T=this._pane.model().mainSeries().symbolInfo(),M=T&&(0,Ze.getPipFormatter)(T),x=M?M.format(p):null,I=null!==x?" , "+x:"",A=null!==P?bs.format(P):null,L=null!==A?", "+(0,hs.startWithLTR)(A):"";this._label=(0,hs.forceLTRStr)(g+I)+"\n"+Ss.format({count:h})+L;const k=this._source.measureVolume();Number.isNaN(k)||(this._label+=`\n${vs} ${ys.format(k)}`);const D=c=50?gs.LineEnd.Arrow:gs.LineEnd.Normal};this._horzTrenRenderer.setData(s)}{const e=Math.round(O.x),t=new a.Point(e,this._p1.y),i=new a.Point(e,this._p2.y),s={points:[t,i],color:B,linewidth:1,linestyle:vi.LINESTYLE_SOLID,extendleft:!1,extendright:!1,leftend:gs.LineEnd.Normal, rightend:Math.abs(t.y-i.y)>=50?gs.LineEnd.Arrow:gs.LineEnd.Normal};this._vertTrenRenderer.setData(s)}const V={x:0,y:10},W=.5*(this._p1.x+this._p2.x),F=this._p2.y,H=new a.Point(W,F),z=(U=(0,n.ensureNotNull)(this._label),{points:[H],text:U,color:"#FFFFFF",horzAlign:"center",vertAlign:"middle",font:E.CHART_FONT_FAMILY,offsetX:V.x,offsetY:V.y,bold:!1,italic:!1,fontsize:12,padding:8,highlightBorder:!1,backgroundColor:N,backgroundTransparency:10,boxPaddingVert:9,boxPaddingHorz:9,backgroundRoundRect:4});var U;this._labelRenderer.setData(z);const G=this._labelRenderer.measure(),q=(0,ps.calculateLabelPosition)(G,this._p1,this._p2,V,this._pane.height());this._labelRenderer.setPoints([q])}renderer(){if(null===this._p1||null===this._p2)return null;const e=new ms.CompositeRenderer;return e.append(this._bgRenderer),e.append(this._horzTrenRenderer),e.append(this._vertTrenRenderer),e.append(this._labelRenderer),e}}var Ms=i(500477),xs=i(699875);class Is extends de.MediaCoordinatesPaneRenderer{constructor(e){super(),this._svgMap=new Map,this._data=e,this._svgMap.set(e.theme,this._createSvgRenderer(e.theme))}hitTest(){return null}setData(e){this._svgMap.has(e.theme)||this._svgMap.set(e.theme,this._createSvgRenderer(e.theme)),this._data=e}_drawImpl(e){const{context:t,mediaSize:i}=e,{theme:s,x:o}=this._data,r=this._svgMap.get(s);if(!r)return;const n=r.viewBox(),{width:a,height:l}=n,c=a/2;o+c<0||o-c>i.width||(t.translate(o-c,i.height-l),r.render(t,{targetViewBox:n}))}_createSvgRenderer(e){const t=1===e?xs.replace("backgroundColor",(0,c.getHexColorByName)("color-cold-gray-900")).replace("lineColor",(0,c.getHexColorByName)("color-cold-gray-450")):xs.replace("backgroundColor",(0,c.getHexColorByName)("color-white")).replace("lineColor",(0,c.getHexColorByName)("color-cold-gray-550"));return(0,Ms.svgRenderer)(t)}}class As{constructor(e){this._source=e,this._renderer=new Is(this._getRenderData(0))}update(){}renderer(){var e;const t=this._source.visible&&this._source.areLinesVisible,i=this._source.lockedX(),s=0===(null===(e=je.crosshairLock.value())||void 0===e?void 0:e.type);return t&&s&&null!==i?(this._renderer.setData(this._getRenderData(i+1)),this._renderer):null}_getRenderData(e){return{x:e,theme:this._source.model().dark().value()?1:0}}}const Ls=30;class ks{constructor(e,t,i){this._renderer=new ls.RectangleRenderer,this._invalidated=!0,this._source=e,this._pane=t,this._model=i}update(){this._invalidated=!0}renderer(){return this._invalidated&&(this._updateImpl(),this._invalidated=!1),this._renderer}_updateImpl(){var e;if(this._renderer.setData(null),!this._pane||!this._source.visible)return;if(!this._source.model().mainSeries().lastValueData(void 0,!0,!0).index)return;const t=new a.Point(null!==(e=this._source.lockedX())&&void 0!==e?e:this._source.x,0),i=new a.Point(this._pane.width(),this._pane.height()),s={backcolor:(0,fi.applyTransparency)(this._model.backgroundColorAtYPercentFromTop(.5),Ls),color:(0,fi.applyTransparency)(this._model.backgroundColorAtYPercentFromTop(.5),Ls),fillBackground:!0,linewidth:0,points:[t,i],nohittest:!0, extendLeft:!1,extendRight:!1};this._renderer.setData(s)}}var Es=i(154765),Ds=i(782086),Bs=i(60897);class Ns extends Ds.DataWindowView{constructor(e){super(),this._invalidated=!0,this._dateItem=new Ds.DataWindowItem("",d.t(null,void 0,i(676912)),""),this._timeItem=new Ds.DataWindowItem("",d.t(null,void 0,i(631976)),""),this._model=e,this._items.push(this._dateItem),this._items.push(this._timeItem)}update(){this._invalidated=!0}items(){return this._invalidated&&(this._updateImpl(),this._invalidated=!1),this._items}_updateImpl(){const e=this._model.mainSeries().isDWM();if(this._timeItem.setVisible(!e),this._timeItem.setValue(Bs.notAvailable),this._dateItem.setValue(Bs.notAvailable),this._model.timeScale().isEmpty())return;let t=this._model.crossHairSource().appliedIndex();if(!(0,Ti.isNumber)(t)){const e=this._model.mainSeries().data().last();if(null===e)return;t=e.index}const i=this._model.timeScale().indexToUserTime(t);null!==i&&(this._dateItem.setValue(this._model.dateFormatter().format(i)),e||this._timeItem.setValue(this._model.timeFormatter().format(i)))}}var Rs=i(161164);const Os=c.colorsPalette["color-tv-blue-500"],Vs=d.t(null,{context:"Replay"},i(420747));class Ws extends Rs.TimeAxisView{constructor(e,t,i,s=!1){super(e),this._indexProvider=i,this._highlighted=s,this._source=t,this._properties=e.properties().childs().scalesProperties}_getText(e){if(this._source.isReplaySelection()){const t=this._model.timeScale().indexToUserTime(e);return null!==t?`${Vs}: ${this._model.dateTimeFormatter().format(t)}`:""}return super._getText(e)}_getBgColor(){if(this._source.isReplaySelection())return Os;const e=this._properties.childs();return this._highlighted?e.axisLineToolLabelBackgroundColorCommon.value():this._model.dark().value()?e.crosshairLabelBgColorDark.value():e.crosshairLabelBgColorLight.value()}_getIndex(){return this._model.crossHairSource().visible||null!==this._source.lockedPane()?this._indexProvider():null}_isVisible(){return this._properties.childs().showTimeScaleCrosshairLabel.value()}}var Fs=i(3140),Hs=i(276871);const zs={menuEnabled:!1,menuForMainSourceOnly:!1,disableTradingMenuActions:!1,disableDrawHorizLineMenuAction:!1};let Us=0;const Gs=(0,ge.getLogger)("Chart.Crosshair");class qs extends ae.DataSource{constructor(e,t,i){super(),this.pane=null,this.price=NaN,this.index=NaN,this.visible=!0,this.areLinesVisible=!0,this.x=NaN,this.y=NaN,this._lockData=null,this._measurePane=new $.WatchedValue(null),this._measurePaneViewCache=new WeakMap,this._startMeasurePoint=null,this._endMeasurePoint=null,this._lastValidMeasurePoint=null,this._isOnHoveredChartWidget=!1,this._crossHairSelectPointMode=new $.WatchedValue(je.SelectPointMode.None),this._selectionPane=null,this._selectionView=new ds(this),this._selectionStartPoint=null,this._timeLockPaneView=null,this._crosshairPaneViewCache=new WeakMap,this._pointSelectionPaneViewCache=new WeakMap,this._priceAxisViews=new Map,this._panePriceAxisViews=new Map,this._startMeasurePriceAxisViews=new Map,this._endMeasurePriceAxisViews=new Map,this._originX=NaN,this._originY=NaN, this._subscribed=!1,this._movedDelegate=new Y.Delegate,this._pointSelectedDelegate=new Y.Delegate,this._requestedPoint=null,this._paneForRequestedPoint=null,this._selectLineColor=null,this._volumeCalculator=null,this._selectFromAllChartsIfOutOfData=null,this._currentMeasurePointsetAndSymbolId=null,this._model=e,this._options=Object.assign({},zs,i||{}),this._linesShouldBeHidden=this._model.readOnly(),this._dataWindowView=new Ns(e),this.setSelectionEnabled(!1);const s=e=>t=>t===(0,n.ensureNotNull)(this._measurePane.value()).defaultPriceScale()?e():null;this._currentPosPriceProvider=e=>{const t=(0,n.ensureNotNull)(this.pane);if(e===t.defaultPriceScale())return this.price;const i=(0,n.ensureNotNull)(t.defaultPriceScale().mainSource()).firstValue();if(null===i)return null;const s=t.defaultPriceScale().priceToCoordinate(this.price,i),o=(0,n.ensureNotNull)(e.mainSource()).firstValue();return null===o?null:e.coordinateToPrice(s,o)},this._startMeasurePriceProvider=s((()=>(0,n.ensureNotNull)(this._startMeasurePoint).price)),this._endMeasurePriceProvider=s((()=>(0,n.ensureNotNull)(this._lastMeasurePoint()).price)),this._properties=t;this._timeAxisView=new Ws(e,this,(()=>this.appliedIndex()),!1),this._startMeasureTimeAxisView=new Ws(e,this,(()=>(0,n.ensureNotNull)(this._startMeasurePoint).index),!0),this._endMeasureTimeAxisView=new Ws(e,this,(()=>(0,n.ensureNotNull)(this._lastMeasurePoint()).index),!0),e.readOnly()||je.cursorTool.subscribe((e=>this.areLinesVisible="arrow"!==e),{callWithLast:!0}),this._crosshairLock=je.crosshairLock.spawn(),this._showPlusButtonOnCursor=Qi.showPlusButtonOnCursor.spawn();const o=()=>{this.updateAllViews((0,G.sourceChangeEvent)(this.id())),this._model.lightUpdate()};this._crosshairLock.subscribe(o),this._showPlusButtonOnCursor.subscribe(o)}destroy(){null!==this._volumeCalculator&&this._volumeCalculator.destroy(),this._measurePane.setValue(null),this._crosshairLock.destroy(),this._showPlusButtonOnCursor.destroy(),this._removeMeasurePointset(),super.destroy()}name(){return"Crosshair"}moved(){return this._movedDelegate}originX(){return this._originX}originY(){return this._originY}saveOriginCoords(e,t){this._originX=e,this._originY=t}clearOriginCoords(){this._originX=NaN,this._originY=NaN}currentPoint(){return new a.Point(this.x,this.y)}model(){return this._model}appliedIndex(){var e;return null!==(e=this._getLockData().index)&&void 0!==e?e:this.index}lockedX(){var e;return null!==(e=this._getLockData().xCoord)&&void 0!==e?e:null}lockedY(){var e;return null!==(e=this._getLockData().yCoord)&&void 0!==e?e:null}lockedPane(){const e=je.crosshairLock.value();return null===e||1!==e.type?null:this._model.id()===e.modelId?this._model.paneForId(e.paneId):this._model.mainPane()}invalidateLockPosition(){this._lockData=null}startMeasurePoint(){return this._startMeasurePoint||null}endMeasurePoint(){return this._endMeasurePoint||null}measureVolume(){if(null===this._volumeCalculator)return NaN;const[e,t]=this.measurePoints();return void 0===t?NaN:this._volumeCalculator.volume(e.index,t.index)}measurePane(){ return this._measurePane.readonly()}startMeasuring(e,t){this._startMeasurePoint=e,this._measurePane.setValue(t),t.containsMainSeries()&&((0,n.assert)(null===this._volumeCalculator),this._volumeCalculator=new Fs.SeriesTimeRangeVolumeCalculator(this.model().mainSeries())),this._model.updatePane(t)}finishMeasure(e){this._endMeasurePoint=e,this._createMeasurePointset((0,n.ensureNotNull)(this._startMeasurePoint),this._endMeasurePoint)}clearMeasure(){this._removeMeasurePointset(),this._measurePane.setValue(null),delete this._startMeasurePoint,delete this._endMeasurePoint,delete this._lastValidMeasurePoint,this._model.lightUpdate(),null!==this._volumeCalculator&&(this._volumeCalculator.destroy(),this._volumeCalculator=null)}measurePoints(){const e=[(0,n.ensureNotNull)(this._startMeasurePoint)],t=this._lastMeasurePoint();return null!==t&&e.push(t),e}startSelection(e){this._selectionStartPoint=this.currentLogicalPoint(),this._selectionPane=e}clearSelection(){this._selectionStartPoint=null,this._selectionPane=null}selection(){return this._selectionStartPoint?{p1:this._selectionStartPoint,p2:this.currentLogicalPoint()}:null}currentLogicalPoint(){return{index:this.appliedIndex(),price:this.price}}selectPointMode(){return this._crossHairSelectPointMode}lineColor(){return this._selectLineColor}cancelRequestSelectPoint(){this._crossHairSelectPointMode.value()!==je.SelectPointMode.None&&this._setSelectPointModeState(je.SelectPointMode.None),this._selectFromAllChartsIfOutOfData=null}requestSelectPoint(e){(0,n.assert)(this._crossHairSelectPointMode.value()===je.SelectPointMode.None,"Point already requested");const{pointType:t,pane:i,lineColor:s=null,selectFromAllChartsIfOutOfData:o,selectPointMode:r=je.SelectPointMode.Study}=e;i&&((0,n.assert)(-1!==this._model.panes().indexOf(i),"Chartmodel doesn't contains specified pane"),this._paneForRequestedPoint=i,this._model.panesCollectionChanged().subscribe(this,this._paneCollectionChanged)),this._selectLineColor=s,this._requestedPoint=t,this._selectFromAllChartsIfOutOfData=null!=o?o:null,this._setSelectPointModeState(r)}onPointSelected(){return this._pointSelectedDelegate}trySelectCurrentPoint(){var e;const t=this.pane;if(!t)return;const i=(0,n.ensureNotNull)(this._requestedPoint);let s=null;if(!this._model.mainSeries().bars().search(this.index,Ot.PlotRowSearchMode.Exact)&&"price"!==i&&(this._selectFromAllChartsIfOutOfData&&(s=null!==(e=Math.min(...Array.from(je.barTimesUnderCursor.values())))&&void 0!==e?e:null),null===s))return;if(this._paneForRequestedPoint&&this._paneForRequestedPoint!==t)return;let o,r=s;if("price"===i||null!==s||(r=this._model.timeScale().indexToTimePoint(this.index),null!==r)){if("time"!==i){const e=t.mainDataSource();if(null===e)return;const i=e.firstValue(),s=e.priceScale();if(null===i||null===s)return;o=s.coordinateToPrice(this.y,i)}this._setSelectPointModeState(je.SelectPointMode.None),this._pointSelectedDelegate.fire({time:null!=r?r:void 0,price:o},t)}}isOnHoveredChartWidget(){return this._isOnHoveredChartWidget}setOnHoveredChartWidget(e){ this._isOnHoveredChartWidget=e}isReplaySelection(){return("AllCharts"===Es.replayModeProperty.value()||this._isOnHoveredChartWidget)&&this._crossHairSelectPointMode.value()===je.SelectPointMode.Replay}clearPosition(){this.visible=!1,this.index=NaN,this.price=NaN,this.x=NaN,this.y=NaN,this.pane=null,this.clearOriginCoords(),this._updateVisibilityDependentPaneViews()}setPosition(e,t,i){this._subscribed||(this._model.mainSeries().onRestarted().subscribe(this,this.clearMeasure),this._subscribed=!0),this.visible=!0;const s=this._model.id(),o=this._model.mainSeries().bars().search(this.index,Ot.PlotRowSearchMode.NearestRight);return o&&je.barTimesUnderCursor.set(s,o.value[0]),this._tryToUpdateViews(e,t,i)}setLinesShouldBeHidden(e){this._linesShouldBeHidden=e}linesShouldBeHidden(){return this._linesShouldBeHidden}handleContextMenuEvent(e){this._crossHairSelectPointMode.value()!==je.SelectPointMode.None&&this._setSelectPointModeState(je.SelectPointMode.None)}properties(){return this._properties}priceAxisViews(e,t){var i;const s=null===this._requestedPoint||"time"!==this._requestedPoint||!this._isOnHoveredChartWidget,o=[];return(null!==(i=this.lockedPane())&&void 0!==i?i:this.pane)===e&&s&&o.push(this._createPriceAxisViewOnDemand(this._priceAxisViews,this._panePriceAxisViews,e,t,this._currentPosPriceProvider,Wi,!0)[0]),this._startMeasurePoint&&o.push(this._createPriceAxisViewOnDemand(this._startMeasurePriceAxisViews,null,e,t,this._startMeasurePriceProvider,Fi)[0]),this._lastMeasurePoint()&&o.push(this._createPriceAxisViewOnDemand(this._endMeasurePriceAxisViews,null,e,t,this._endMeasurePriceProvider,Fi)[0]),o}timeAxisViews(){const e=[],t=null===this._requestedPoint||"price"!==this._requestedPoint||!this._isOnHoveredChartWidget;return this._linesShouldBeHidden||!this.visible&&null===je.crosshairLock.value()||!t||e.push(this._timeAxisView),this._startMeasurePoint&&e.push(this._startMeasureTimeAxisView),this._lastMeasurePoint()&&e.push(this._endMeasureTimeAxisView),e}paneViews(e){var t,i;if(void 0===e)return null;const s=[];if(this.isReplaySelection()){let t=this._pointSelectionPaneViewCache.get(e);t||(t=new ks(this,e,this._model),this._pointSelectionPaneViewCache.set(e,t)),s.push(t)}let o=this._crosshairPaneViewCache.get(e);if(o||(o=new as(this,e),this._crosshairPaneViewCache.set(e,o)),s.push(o),e===this._selectionPane&&s.push(this._selectionView),e===this._measurePane.value()){let t=this._measurePaneViewCache.get(e);t||(t=new Ts(this,e),this._measurePaneViewCache.set(e,t)),t.update((0,G.sourceChangeEvent)(this.id())),s.push(t)}if((Qi.addPlusButtonProperty.value()||this._showPlusButtonOnCursor.value())&&1!==(null===(t=je.crosshairLock.value())||void 0===t?void 0:t.type)){const t=e===this.pane,i=!si.CheckMobile.any()||window.screen.width>=320,o=je.tool.value(),r=(0,De.isLineToolName)(o),n=null!==this._model.lineBeingEdited()||null!==this._model.lineBeingCreated()||this._model.sourcesBeingMoved().length>0||null!==this._model.customSourceBeingMoved()||(0,je.toolIsMeasure)(o) ;if(t&&this._isOnHoveredChartWidget&&this._crossHairSelectPointMode.value()===je.SelectPointMode.None&&i&&!r&&!n){const t=e.mainDataSource();if(null!==t){const i=t.priceScale();if(null!==i){const t=this._createPriceAxisViewOnDemand(this._priceAxisViews,this._panePriceAxisViews,e,i,this._currentPosPriceProvider,Wi,!0)[1];null!==t&&s.push(t)}}}}return 0===(null===(i=je.crosshairLock.value())||void 0===i?void 0:i.type)&&(null===this._timeLockPaneView&&(this._timeLockPaneView=new As(this)),s.push(this._timeLockPaneView)),s}dataWindowView(){return this._dataWindowView}updateAllViews(e){this._priceAxisViews.forEach((t=>{t.forEach((t=>t.update(e)))})),this._panePriceAxisViews.forEach((t=>{t.forEach((t=>t.update(e)))})),this._startMeasurePoint&&(this._startMeasurePriceAxisViews.forEach((t=>{t.forEach((t=>t.update(e)))})),this._startMeasureTimeAxisView.update(e)),this._lastMeasurePoint()&&(this._endMeasurePriceAxisViews.forEach((t=>{t.forEach((t=>t.update(e)))})),this._endMeasureTimeAxisView.update(e)),this._timeAxisView.update(e),this._selectionView.update(),this._dataWindowView.update(),this._updateVisibilityDependentPaneViews()}isMenuEnabled(){return this._options.menuEnabled}isHoveredEnabled(){return Qi.addPlusButtonProperty.value()||this._showPlusButtonOnCursor.value()}isHovered(){return this._model.hoveredSource()===this}pointToSelect(){return this._requestedPoint}paneForPointSelect(){return this._paneForRequestedPoint}_lastMeasurePoint(){return this._endMeasurePoint?this._endMeasurePoint:(null!==this.pane&&this._measurePane.value()===this.pane&&(this._lastValidMeasurePoint={price:this._model.magnet().align(this.price,this.index,this.pane),index:this.index}),this._lastValidMeasurePoint||null)}_createPriceAxisViewOnDemand(e,t,i,s,o,r,a=!1){let l=e.get(i),c=null!==t?t.get(i):void 0;void 0===l&&(l=new Map,e.set(i,l),this.isMenuEnabled()&&null!==t&&(c=new Map,t.set(i,c)),a&&i.onDestroyed().subscribe(this,(()=>this._onPaneDestroyed(i))));let d=l.get(s);if(void 0===d){if(d=new r(this,i,s,o),l.set(s,d),void 0!==c){const e=new is(d,this,s,this._model,this._options);c.set(s,e)}a&&s.lastSourceRemoved().subscribe(this,(()=>this._onPriceScaleCleared(s)))}let h=null;return void 0!==c&&(h=(0,n.ensureDefined)(c.get(s))),[d,h]}_onPaneDestroyed(e){e.onDestroyed().unsubscribeAll(this),this._priceAxisViews.delete(e),this._panePriceAxisViews.delete(e),this._startMeasurePriceAxisViews.delete(e),this._endMeasurePriceAxisViews.delete(e)}_onPriceScaleCleared(e){e.lastSourceRemoved().unsubscribeAll(this),this._priceAxisViews.forEach((t=>t.delete(e))),this._panePriceAxisViews.forEach((t=>t.delete(e))),this._startMeasurePriceAxisViews.forEach((t=>t.delete(e))),this._endMeasurePriceAxisViews.forEach((t=>t.delete(e)))}_tryToUpdateViews(e,t,i){return!!this._tryToUpdateData(e,t,i)&&(this.updateAllViews((0,G.sourceChangeEvent)(this.id())),this._movedDelegate.fire({index:this.index,price:this.price}),!0)}_tryToUpdateData(e,t,i){const s=this.x,o=this.y,r=this.price,a=this.index,l=this.pane,c=this._priceScaleByPane(i);if(this.index=e, this.x=isNaN(e)?NaN:this._model.timeScale().indexToCoordinate(e),null!==c&&null!==i){this.pane=i,this.price=t;const e=(0,n.ensureNotNull)(i.mainDataSource()).firstValue();this.y=null===e?NaN:c.priceToCoordinate(t,e)}else this.pane=null,this.price=NaN,this.y=NaN;return s!==this.x||o!==this.y||a!==this.index||r!==this.price||l!==this.pane}_priceScaleByPane(e){return e&&!e.defaultPriceScale().isEmpty()?e.defaultPriceScale():null}_setSelectPointModeState(e){e===je.SelectPointMode.None&&(this._requestedPoint=null,this._selectLineColor=null,this._paneForRequestedPoint&&(this._paneForRequestedPoint=null,this._model.panesCollectionChanged().unsubscribe(this,this._paneCollectionChanged))),je.activePointSelectionMode.setValue(e),this._crossHairSelectPointMode.setValue(e),this._model.lightUpdate()}_paneCollectionChanged(e){const t=this._paneForRequestedPoint;null!==t&&-1===e.indexOf(t)&&this.cancelRequestSelectPoint()}_updateVisibilityDependentPaneViews(){var e;for(const t of this.model().panes())null===(e=this._pointSelectionPaneViewCache.get(t))||void 0===e||e.update()}_getLockData(){var e;if(null===this._lockData){const t=je.crosshairLock.value();if(null===t)this._lockData={};else{const i=this._model.timeScale(),s=null!==(e=i.points().roughIndex(t.time))&&void 0!==e?e:void 0,o=void 0===s?void 0:i.indexToCoordinate(s);switch(t.type){case 0:this._lockData={index:s,xCoord:o};break;case 1:{let e;const i=this.lockedPane();if(null!==i){const s=i.mainDataSource();if(null!==s){const i=s.firstValue(),o=s.priceScale();null!==o&&null!==i&&(e=o.priceToCoordinate(t.price,i))}}this._lockData={index:s,xCoord:o,yCoord:e}}}}}return this._lockData}_createMeasurePointset(e,t){const i=this._normalizePoint(e),s=this._normalizePoint(t),o=[[i.time_t,i.offset],[s.time_t,s.offset]];this._removeMeasurePointset(),++Us,this._currentMeasurePointsetAndSymbolId={measurePointsetId:Us,symbolId:(0,n.ensureNotNull)(this._model.mainSeries().seriesSource().symbolInstanceId())};const r=(0,Hs.getServerInterval)(this._model.mainSeries().interval());this._model.chartApi().createPointset(this._currentMeasurePointsetIdWithPrefix(),"turnaround",this._currentMeasurePointsetAndSymbolId.symbolId,r,o,this._onPointsetResponse.bind(this))}_removeMeasurePointset(){null!==this._currentMeasurePointsetAndSymbolId&&this._model.chartApi().isConnected().value()&&this._model.chartApi().removePointset(this._currentMeasurePointsetIdWithPrefix()),this._currentMeasurePointsetAndSymbolId=null}_currentMeasurePointsetIdWithPrefix(){return"pointsetMeasure_"+(0,n.ensureNotNull)(this._currentMeasurePointsetAndSymbolId).measurePointsetId}_normalizePoint(e){return{...this._model.timeScale().normalizeBarIndex(e.index),price:e.price}}_onPointsetResponse(e){if("pointset_error"===e.method)return void Gs.logError(`Error getting pointset: ${e.params[0]} ${e.params[1]}`);if(e.params.customId!==this._currentMeasurePointsetIdWithPrefix())return;if(null===this._startMeasurePoint||null===this._endMeasurePoint)return;const t=e.params.plots;if(2!==t.length)return;const i=t[0].value[0],s=t[1].value[0] ;this._startMeasurePoint.index=i,this._endMeasurePoint.index=s,this.updateAllViews((0,G.sourceChangeEvent)(this.id())),this._model.updateSource(this)}}var js=i(983898),Zs=i(155964),Ks=i(808068),Ys=i(809796),$s=i(677305),Xs=i(772466);class Js{constructor(e){this._priceSourceNamesById=new Map,e.forEach((e=>this._priceSourceNamesById.set(e.id,e.name)))}name(e){var t;return null!==(t=this._priceSourceNamesById.get(e))&&void 0!==t?t:null}priceSourcesChanged(e){return e.length!==this._priceSourceNamesById.size}}var Qs=i(66732),eo=i(197050);const to=new Ys.TranslatedString("remove deselected empty line tools",d.t(null,void 0,i(59211))),io=H.enabled("auto_enable_symbol_labels"),so=(0,ge.getLogger)("Chart.ChartModel");function oo(e,t){const i=e.indexOf(t);return-1!==i&&(e.splice(i,1),!0)}function ro(e){var t,i;for(let s=e.length;s--;){const o=e[s].dataSources();for(let e=o.length;e--;)null===(t=o[e].dataWindowView())||void 0===t||t.update();const r=e[s].priceDataSources();for(let e=r.length;e--;)null===(i=r[e].legendView())||void 0===i||i.update()}}const no={isSnapshot:!1,readOnly:!1,watermarkEnabled:!0,shiftVisibleRangeOnNewBar:!0,currencyConversionEnabled:!1,unitConversionEnabled:!1,countdownEnabled:!0,lastPriceAnimationEnabled:!0,onWidget:!1,hideIdeas:!1},ao={throttle:o.default,debounce:s.default},lo=new Map([[v.RecalcVisibleRangeStudiesReason.ViewportChangeUserAction,{timeout:2e3,adapter:"debounce"}],[v.RecalcVisibleRangeStudiesReason.DataUpdate,{timeout:5e3,adapter:"throttle"}],[v.RecalcVisibleRangeStudiesReason.SeriesRestart,{timeout:2e3,adapter:"debounce"}],[v.RecalcVisibleRangeStudiesReason.SeriesCompleted,{timeout:2e3,adapter:"debounce"}],[v.RecalcVisibleRangeStudiesReason.StudyCreation,{timeout:2e3,adapter:"debounce"}]]),co=Array.from(lo.values());class ho{constructor(e,t,i,o,r,n,a,l,c,d){this._onRearrangePanes=new Y.Delegate,this._lineToolsGroupModel=new $t,this._sourcesBeingMoved=[],this._activeItemBeingMoved=null,this._lineBeingEdited=null,this._linePointBeingEdited=null,this._linePointBeingChanged=null,this._customSourceBeingMovedHitTestData=null,this._customSourceBeingMoved=null,this._dataSourceCollectionChanged=new Y.Delegate,this._sourceProperitesChanged=new Y.Delegate,this._sourceZOrderChanged=new Y.Delegate,this._symbolSourceResolved=new Y.Delegate,this._symbolSourceResolvingActive=new $.WatchedValue(!1),this._adjustForDividendsAvailability=new $.WatchedValue(0),this._adjustForDividendsEnabled=new $.WatchedValue(!1),this._sessions=null,this._currentTool="",this._lineBeingCreated=null,this._paneBeingCreatedLineOn=null,this._lineCancelled=new Y.Delegate,this._phantomSourceContainer=new Mi(this),this._destroyed=!1,this._isSettingsExternalPosition=!1,this._isTimeScrolling=!1,this._magnet=new Li,this._scrollingState=null,this._modelIntervals=[],this._rendererOptionsProvider=new D(this),this._studyInserted=new Y.Delegate,this._cachedStudiesMaxOffset=0,this._replayStatus=new $.WatchedValue(0),this._panes=[],this._tagsChanged=new Y.Delegate,this._strategySources=[],this._strategySourcesChange=new Y.Delegate, this._activeStrategySource=new $.WatchedValue(null),this._symbolIntervalChanged=new Y.Delegate,this._paneCollapsingAvailable=new $.WatchedValue(!1),this._panesCollectionChanged=new Y.Delegate,this._scrollEnabled=H.enabled("chart_scroll"),this._zoomEnabled=H.enabled("chart_zoom"),this._lollipopSourcesWatcher=null,this._alertsWatcher=null,this._hoveredSource=null,this._hoveredSourceChanged=new Y.Delegate,this._lastHoveredHittestData=null,this._hoveredSourceOrigin=null,this._lastSelectedHittestData=null,this._topmostCustomSources=[],this._fgCustomSources=[],this._bgCustomSources=[],this._allCustomSources=[],this._customSourcesMap=new Map,this._multiPaneSources=[],this._showLegendProperty=new L.Property,this._id=(0,Se.guid)(),this._chartSaveTime=null,this._availableCurrenciesList=null,this._availableCurrencies=new wi([]),this._availablePriceSources=new Js([]),this._availableUnitsObject=null,this._availableUnits=new Pi({}),this._availablePriceSourcesBySymbol=new Map,this._shouldBeSavedEvenIfHidden=!1,this._watchedThemeSpawn=h.watchedTheme.spawn(),this._gradientColorsCache=null,this._studiesWV=new X.WatchedObject([],b.compareTwoCollectionsByIds),this._studiesExcludeInternalWV=new X.WatchedObject([],b.compareTwoCollectionsByIds),this._resetScalesAvailable=new $.WatchedValue(!1),this._recalcVRStudiesParams={reasons:new Set},this._recalcColorStudiesParams={},this._replayStudyStrategy=new $.WatchedValue(null),this._recalcVisibleRangeStudiesImplDebouncedByAdapter=new Map(Object.keys(ao).map((e=>[e,new Map(co.filter((t=>t.adapter===e)).map((e=>[e.timeout,ao[e.adapter](this._recalcVisibleRangeStudiesImpl.bind(this,this._recalcVRStudiesParams),e.timeout)])))]))),this._recalcColorStudiesImplDebounced=(0,s.default)(this._recalcColorStudiesImpl.bind(this,this._recalcColorStudiesParams),250),this._width=0,this._resetScales=new Y.Delegate,this._chartThemeLoaded=new Y.Delegate,this._selection=new P,this._selectedSourceChanged=new Y.Delegate,this._symbolSourceCollectionChanged=new Y.Delegate,this._gridSource=new Ri,this._visibleRangeStudiesInputs=new X.WatchedObject(null),this._syncPointCache=new Map,this._lastAppliedGotoTimeRange=null,this._lastGotoTimeRange=null,this._lollipopSourcesWatcherLoader=null,this._onMultipaneSourcesCollectionChanged=new Y.Delegate,this._replayStudyStrategyInputs=null,this._clearSelection=()=>{this._lastSelectedHittestData=null,this._selection.clear()},this._removeSourceFromSelection=e=>{this._selection.remove(e)},this._addSourceToSelection=(e,t)=>{const i=this._selection.isSelected(e);i&&this._lastSelectedHittestData===t||e&&!e.isSelectionEnabled()||(this._lastSelectedHittestData=t||null,i||this._selection.add(e))},this._recalcSymbolResolvingActive=()=>{for(const e of this._panes)if(e.symbolSourceResolvingActive().value())return void this._symbolSourceResolvingActive.setValue(!0);this._symbolSourceResolvingActive.setValue(!1)},this._recalcAdjustForDividendsAvailability=()=>{var e,t,i,s;if(this._symbolSourceResolvingActive.value())return;const o=this.mainSeries() ;switch(null!==(t=null===(e=o.symbolInfo())||void 0===e?void 0:e.allowed_adjustment)&&void 0!==t?t:"none"){case"dividends":return void this._adjustForDividendsAvailability.setValue(2);case"splits":return void this._adjustForDividendsAvailability.setValue(1);case"any":return void this._adjustForDividendsAvailability.setValue(3)}for(const e of this.symbolSources().filter(Oe.isActingAsSymbolSource)){if(e.symbolHibernated().value()||e===o)continue;if("any"===(null!==(s=null===(i=e.symbolInfo())||void 0===i?void 0:i.allowed_adjustment)&&void 0!==s?s:"none"))return void this._adjustForDividendsAvailability.setValue(3)}this._adjustForDividendsAvailability.setValue(0)},this._recalcAdjustForDividendsEnabled=()=>{switch(this._adjustForDividendsAvailability.value()){case 2:return void this._adjustForDividendsEnabled.setValue(!0);case 0:case 1:return void this._adjustForDividendsEnabled.setValue(!1)}this._adjustForDividendsEnabled.setValue(this.mainSeries().properties().childs().dividendsAdjustment.value())},this._recalcPaneCollapsingAvailable=e=>{let t=this._panes.filter((e=>!e.collapsed().value())).length;0===t&&e&&this._panes.length>0&&(this._panes[0].collapsed().setValue(!1),t=1),this._paneCollapsingAvailable.setValue(t>1)},this._updateResetScalesAvailableValue=()=>{const e=this._timeScale.resetAvailable().value()||this._panes.some((e=>e.resetPriceScalesAvailable().value()));this._resetScalesAvailable.setValue(e)},this._chartApi=e,this._invalidateHandler=t,this._undoModel=r,this._properties=i,this._options=(0,be.merge)((0,be.clone)(no),a),this._hibernateWV=l,this._linkingGroupIndex=c,this._isAutoSaveEnabled=d,this._readOnly=this._options.readOnly,this._isSnapshot=this._options.isSnapshot,this._alertsWatcher=new ci(this),this.onWidget()||_i.withWeekdayProperty.subscribe(this,(()=>this._updateDateTimeFormatter())),this._chartSaveTime=(new Date).valueOf(),this._backgroundColor=new $.WatchedValue(this._getBackgroundColor()),this._backgroundTopColor=new $.WatchedValue(this._getBackgroundColor(!0)),this._properties.childs().paneProperties.childs().background.subscribe(this,this._updateBackgroundColor),this._properties.childs().paneProperties.childs().backgroundType.subscribe(this,this._updateBackgroundColor),this._properties.childs().paneProperties.childs().backgroundGradientStartColor.subscribe(this,this._updateBackgroundColor),this._properties.childs().paneProperties.childs().backgroundGradientEndColor.subscribe(this,this._updateBackgroundColor),this._backgroundColor.subscribe(this.recalcColorStudies.bind(this,!1)),this._backgroundTopColor.subscribe(this.recalcColorStudies.bind(this,!1)),this._backgroundCounterColor=new $.WatchedValue(this._getBackgroundCounterColor()),this._backgroundColor.subscribe((()=>this._backgroundCounterColor.setValue(this._getBackgroundCounterColor()))),this._isDark=(0,Qs.combine)((e=>"white"===e),this._backgroundCounterColor.weakReference()),this._watchedThemeSpawn.subscribe(this._updateBackgroundColor.bind(this)),this._symbolSourceResolvingActive.subscribe(this._recalcAdjustForDividendsAvailability), (0,je.init)();const u=this._readOnly?new L.Property((0,W.defaults)("chartproperties.paneProperties.crossHairProperties")):this._properties.childs().paneProperties.childs().crossHairProperties;this.m_crossHairSource=new qs(this,u,this._options.crossHair),this._crossHairSelectPointMode=this.m_crossHairSource.selectPointMode().spawn(),this._crossHairSelectPointMode.subscribe((e=>{if(e!==je.SelectPointMode.None&&this.lineBeingCreated()){const e=je.tool.value();this.cancelCreatingLine(),je.tool.setValue(e)}})),this._tagsChanged=new Y.Delegate;const _=new A.DefaultProperty({defaultName:"chartproperties.mainSeriesProperties",excludedDefaultsKeys:["priceAxisProperties.lockScale","priceAxisProperties.percentage","priceAxisProperties.indexedTo100","priceAxisProperties.isInverted","priceAxisProperties.log","priceAxisProperties.logDisabled","priceAxisProperties.percentageDisabled","priceAxisProperties.autoScaleDisabled"]});_.merge(i.childs().mainSeriesProperties.state()),this._timeScale=new qt(this,this._options.timeScale),this._timeScale.resetAvailable().subscribe(this._updateResetScalesAvailableValue);const p={countdownEnabled:this._options.countdownEnabled,lastPriceAnimationEnabled:this._options.lastPriceAnimationEnabled};this.m_mainSeries=new Re.Series(this,_,p,o),this.m_mainSeries.onStyleChanged().subscribe(this._timeScale,this._timeScale.invalidateVisibleBars);const m=()=>this.fullUpdate();this.m_mainSeries.properties().childs().showCountdown.subscribe(this,(()=>{this.m_mainSeries.updateAllViews((0,G.sourceChangeEvent)(this.m_mainSeries.id())),m()})),(0,Q.currencyUnitVisibilityProperty)().subscribe(this,m),(0,ee.autoLogButtonsVisibilityProperty)().subscribe(this,m),this._timeScale.visibleBarsStrictRangeChanged().subscribe(this.m_mainSeries,this.m_mainSeries.clearHighLowPriceCache),this._timeScale.visibleBarsStrictRangeChanged().subscribe(this.m_mainSeries,this.m_mainSeries.clearAveragePriceCache),this.createPane(void 0,{axisProperties:_.childs().priceAxisProperties.state(["autoScale"])}),this._adjustForDividendsAvailability.subscribe(this._recalcAdjustForDividendsEnabled),this.mainSeries().properties().childs().dividendsAdjustment.subscribe(this,this._recalcAdjustForDividendsEnabled),this._recalcAdjustForDividendsEnabled(),this._boundUpdateStudiesMaxOffset=this._updateStudiesMaxOffset.bind(this),this.mainSeries().dataEvents().seriesTimeFrame().subscribe(this,((e,t,i,s)=>{if(null!==this._lastAppliedGotoTimeRange&&null!==i&&s&&(0,xi.areEqualTimeFrames)(this._lastAppliedGotoTimeRange.range,i)){const e=this.appliedTimeFrame().value();null!==e&&!this._lastAppliedGotoTimeRange.actual&&(0,xi.areEqualTimeFrames)(this._lastAppliedGotoTimeRange.range,e.val)&&this.appliedTimeFrame().setValue(null),this._lastAppliedGotoTimeRange=null}})),this.mainSeries().dataEvents().completed().subscribe(this,(e=>{null===this._lastAppliedGotoTimeRange&&null!==this._lastGotoTimeRange&&(this.gotoTimeRange(this._lastGotoTimeRange.from,this._lastGotoTimeRange.to),this._lastGotoTimeRange=null)}));const g=this._panes[0] ;g.setStretchFactor(2*g.stretchFactor()),this._properties.listeners().subscribe(this,this.lightUpdate),this._properties.childs().timezone.subscribe(null,(()=>{this._chartApi&&this._chartApi.isConnected().value()&&this._chartApi.switchTimezone(this.timezone())})),g.addDataSource(this.m_mainSeries,g.findSuitableScale(this.m_mainSeries),!1),this._barsMarksSources=n(this);for(const e of this._barsMarksSources)e.setOwnerSource(this.m_mainSeries),g.addDataSource(e,this.m_mainSeries.priceScale(),!0);this.m_mainSeries.symbolResolved().subscribe(this,this._clearAvailablePriceSources),this.m_mainSeries.onSymbolIntervalChanged().subscribe(this,this._onSymbolIntervalChanged),this._createLollipopSourcesWatcher(),this._watermarkSource=this._options.watermarkEnabled?new me(this):null,this._timezoneExceptExchange=(0,Qs.combine)(((e,t)=>"exchange"!==e?e:t),(0,eo.createWVFromProperty)(this._properties.childs().timezone).ownership(),(0,eo.createWVFromGetterAndSubscription)((()=>{var e,t;return null!==(t=null===(e=this.mainSeries().symbolInfo())||void 0===e?void 0:e.timezone)&&void 0!==t?t:null}),this.mainSeries().symbolResolved()).ownership())}restart(){this._chartApi.switchTimezone(this.timezone()),this._timeScale.reset(),this.m_mainSeries.restart();for(const e of this.dataSources())e.restart&&e!==this.m_mainSeries&&e.restart();this.sessions().restart()}version(){return 3}collapsed(){return this._hibernateWV}visibleRangeStudiesInputs(){return this._visibleRangeStudiesInputs.readonly()}chartSaveTime(){return this._chartSaveTime}setChartSaveTime(e){this._chartSaveTime=e}destroy(){var e;this._phantomSourceContainer.destroy(),this._hoveredSourceChanged.destroy(),null!==this._watermarkSource&&(this._watermarkSource.destroy(),this._watermarkSource=null),Array.from(this._customSourcesMap.keys()).forEach(this._removeCustomSource,this),(0,n.assert)(0===this._topmostCustomSources.length),(0,n.assert)(0===this._fgCustomSources.length),(0,n.assert)(0===this._bgCustomSources.length),(0,n.assert)(0===this._allCustomSources.length),(0,n.assert)(0===this._customSourcesMap.size),null!==this._lollipopSourcesWatcher&&(this._lollipopSourcesWatcher.destroy(),this._lollipopSourcesWatcher=null),null!==this._alertsWatcher&&this._alertsWatcher.destroy(),this.onWidget()||_i.withWeekdayProperty.unsubscribeAll(this),this._properties.childs().paneProperties.childs().background.unsubscribeAll(this),this._properties.childs().paneProperties.childs().backgroundType.unsubscribeAll(this),this._properties.childs().paneProperties.childs().backgroundGradientEndColor.unsubscribeAll(this),this._properties.childs().paneProperties.childs().backgroundGradientStartColor.unsubscribeAll(this),this._watchedThemeSpawn.destroy(),this._lastHoveredHittestData=null,this._lastSelectedHittestData=null,(0,Q.currencyUnitVisibilityProperty)().unsubscribeAll(this),(0,ee.autoLogButtonsVisibilityProperty)().unsubscribeAll(this),this._alertsList&&(this._alertsList.destroy(),this._alertsList=void 0),window.loginStateChange.unsubscribeAll(this),this._crossHairSelectPointMode.destroy(), this.m_mainSeries.symbolResolved().unsubscribe(this,this._clearAvailablePriceSources),this.m_mainSeries.onSymbolIntervalChanged().unsubscribe(this,this._onSymbolIntervalChanged),this._timezoneExceptExchange.destroy(),null===(e=this._lollipopSourcesWatcherLoader)||void 0===e||e.destroy(),this._destroyed=!0}undoModel(){return this._undoModel}onData(e){switch(e.method){case"timescale_update":{const t=e.params;this._updateTimeScale({index:t.index,zoffset:t.zoffset,values:t.changes,indexDiffs:t.index_diff,baseIndex:t.baseIndex,marks:t.marks,clearFlag:t.clear});break}case"timescale_completed":{const t=Boolean(e.params[0]);this._timeScale.onTimeScaleCompleted(t);break}}}addStrategySource(e,t){1!==t&&-1===this._strategySources.indexOf(e)&&(this._strategySources.push(e),this._strategySourcesChange.fire(t),this.setActiveStrategySource(e))}removeStrategySource(e,t){if(1===t)return;const i=this._strategySources.indexOf(e);if(-1!==i){if(this._strategySources.splice(i,1)[0]===this._activeStrategySource.value()&&this.unsetActiveStrategySource(),this._strategySources.length>0){const e=this._strategySources[this._strategySources.length-1];this.setActiveStrategySource(e)}this._strategySourcesChange.fire(t)}}setActiveStrategySource(e){-1!==this._strategySources.indexOf(e)&&this._activeStrategySource.setValue(e)}unsetActiveStrategySource(){this._activeStrategySource.setValue(null)}activeStrategySource(){return this._activeStrategySource}strategySources(){return this._strategySources}strategySourcesChange(){return this._strategySourcesChange}replayStudyStrategy(){return this._replayStudyStrategy}setReplayStudyStrategy(e){this._replayStudyStrategy.setValue(e)}async replayStudyStrategyProperties(){if(!this._replayStudyStrategyInputs){const e=await(0,gi.getReplayStrategyMetaInfo)();this._replayStudyStrategyInputs=new L.Property(e.defaults.inputs)}return this._replayStudyStrategyInputs}setScrollEnabled(e){this._scrollEnabled=e}scrollEnabled(){return this._scrollEnabled}setZoomEnabled(e){this._zoomEnabled=e}zoomEnabled(){return this._zoomEnabled}zoomToViewport(e,t,i,s,o){this.setTimeViewport(e,t);let r=Math.min(i,s),n=Math.max(i,s);const a=o.defaultPriceScale();a.isPercentage()||a.setMode({autoScale:!1}),a.isLog()&&(r=a.priceToLogical(r),n=a.priceToLogical(n)),a.setPriceRange(new Be.PriceRange(r,n)),this.recalculateAllPanes((0,G.viewportChangeEvent)()),this.invalidate(this._paneInvalidationMask(o,J.InvalidationLevel.Light))}setTimeViewport(e,t){const i=this.appliedTimeFrame().value();null!==this._lastAppliedGotoTimeRange&&null!==i&&(0,xi.areEqualTimeFrames)(this._lastAppliedGotoTimeRange.range,i.val)&&!this._lastAppliedGotoTimeRange.actual||(this.timeScale().zoomToBarsRange(e,t),this.recalculateAllPanes((0,G.viewportChangeEvent)()),this.recalcVisibleRangeStudies(v.RecalcVisibleRangeStudiesReason.ViewportChangeUserAction),this.lightUpdate())}onTagsChanged(){return this._tagsChanged}canZoomIn(){return this._timeScale.canZoomIn()&&this._zoomEnabled}canZoomOut(){return this._timeScale.canZoomOut()&&this._zoomEnabled}onPaneTagsChanged(){ this._tagsChanged.fire()}panesCollectionChanged(){return this._panesCollectionChanged}dataSourceCollectionChanged(){return this._dataSourceCollectionChanged}symbolSourceCollectionChanged(){return this._symbolSourceCollectionChanged}symbolSourceResolved(){return this._symbolSourceResolved}symbolSourceResolvingActive(){return this._symbolSourceResolvingActive}adjustForDividendsAvailability(){return this._adjustForDividendsAvailability}adjustForDividendsEnabled(){return this._adjustForDividendsEnabled}paneCollapsingAvailable(){return this._paneCollapsingAvailable}sourcePropertiesChanged(){return this._sourceProperitesChanged}sourceZOrderChanged(){return this._sourceZOrderChanged}zoomTime(e,t,i){if(!this._zoomEnabled)return;const s=this.timeScale();if(s.isEmpty()||0===t)return;const o=s.width();e=Math.max(1,Math.min(e,o-2)),s.zoom(e,t,i),this.recalculateAllPanes((0,G.viewportChangeEvent)()),this.lightUpdate(),this.recalcVisibleRangeStudies(v.RecalcVisibleRangeStudiesReason.ViewportChangeUserAction)}lineBeingEdited(){return this._lineBeingEdited}linePointBeingEdited(){return this._linePointBeingEdited}activeItemBeingMoved(){return this._activeItemBeingMoved}linePointBeingChanged(){return this._linePointBeingChanged}mainSeries(){return this.m_mainSeries}updateAllPaneViews(e){var t;for(const t of this._panes)t.updateAllViews(e);null===(t=this._watermarkSource)||void 0===t||t.updateAllViews(e)}dataSources(){const e=[this.crossHairSource()];for(const t of this._panes)for(const i of t.dataSources())e.push(i);return e}priceDataSources(){const e=[];for(const t of this._panes)for(const i of t.priceDataSources())e.push(i);return e}symbolSources(){const e=[];for(const t of this._panes)for(const i of t.symbolSources())e.push(i);return e}orderedDataSources(e){let t=[this.m_crossHairSource];for(let i=0;ie.updateAllViews((0,G.selectionChangeEvent)())));let r=[];if(s.forEach((e=>{if((0,C.isLineTool)(e)){const i=e.hasAlert().value()&&e.getAlertSync();i&&!i.isPrice()&&i.setSelected(!1),!t&&e.shouldBeRemovedOnDeselect()&&r.push(e)}})),o.forEach((e=>{const t=(0,C.isLineTool)(e)&&e.hasAlert&&e.hasAlert().value()&&e.getAlertSync();t&&t.setSelected(!0)})),1===o.length){const[e]=o;(0,C.isLineTool)(e)&&e.hasAlert().value()&&0===e.alertStatus().value()&&e.synchronizeAlert().catch((()=>{}))}r=r.filter((e=>null!==this.dataSourceForId(e.id()))),r.length>0&&this._undoModel.removeSources(r,!1,to),this.lightUpdate(),(s.length>0||o.length>0)&&this._selectedSourceChanged.fire()} onSelectedSourceChanged(){return this._selectedSourceChanged}checkLineToolSelection(){const e=this.selection().allSources();this._selection.checkLineToolSelection(),e.length!==this.selection().allSources().length&&this._selectedSourceChanged.fire()}lineToolsGroupModel(){return this._lineToolsGroupModel}restoreLineToolsGroups(e){this._lineToolsGroupModel=$t.fromState(this,e)}realignLineTools(e){for(const t of this._panes)(void 0===e||t.hasDataSource(e))&&t.realignLineTools(e)&&this._dataSourceCollectionChanged.fire(t)}copyToOtherCharts(e,t){const i=this.mainSeries(),s=i.syncModel(),o=this.timeScale();if(s)for(const r of e){if(!r.isSynchronizable())continue;const e=r.linkKey().value()||(0,Se.randomHash)();r.linkKey().setValue(e);const a=r.state(!1),l=r.normalizedPoints(),c=r.properties().interval.value(),d=i.interval();let h;if(I.Interval.isEqual(c,d))h=l.map((e=>{const t=(0,n.ensureNotNull)(o.timePointToIndex(e.time_t))+e.offset;return{price:e.price,timeStamp:(0,n.ensureNotNull)(this.externalTimeStamp(t))}}));else{const e=s.createNewModelWithResolution(c);h=l.map((t=>({price:t.price,timeStamp:0===t.offset?t.time_t:e.projectTime(t.time_t,t.offset)})))}const u={...a,id:r.id(),linkKey:e,points:h,linetool:r.toolname,model:this,symbol:i.symbol(),withUndo:t,zOrder:r.zorder(),finalState:{points:l,interval:c},pointPositionPercents:r.isFixed()?r.calcPositionPercents():void 0,sharingMode:r.sharingMode().value()};(0,je.copyLineTool)(u)}}isSnapshot(){return this._isSnapshot}onWidget(){return this._options.onWidget}hideIdeas(){return this._options.hideIdeas}updateSource(e){const t=this._invalidationMaskForSource(e);null!==t&&this.invalidate(t)}updateSourcePriceScale(e){const t=this._invalidationMaskForSourcePriceScale(e);null!==t&&this.invalidate(t)}updatePane(e){this.invalidate(this._paneInvalidationMask(e))}updateTimeScaleBaseIndex(e){const t=this.mainSeries().bars();t.isEmpty()||this._updateBaseIndex((0,n.ensureNotNull)(t.lastIndex()),!!(e&&e.index>0))}setInterval(e,t){const i=setInterval(e,t);return this._modelIntervals.push(i),i}clearInterval(e){clearInterval(e);const t=this._modelIntervals.indexOf(e);t>-1&&this._modelIntervals.splice(t,1)}clearIntervals(){for(let e=0;e{i.ownerSource()===e&&i.setOwnerSource(t)})),this._invalidateBarColorerCaches(),t.start(),this.recalculatePane(i,(0,G.sourceChangeEvent)(t.id())),this.fullUpdate(),!0}insertStudyStub(e,t,i,s){const o=void 0!==t,r=new M.StudyStub(this,null!=i?i:null,e,o,null!=s?s:null);let a;if(t||!o){a=(0,n.ensureNotNull)(this.mainPane());const e=!0===t?this.mainSeries().priceScale():a.createPriceScaleAtPosition("overlay");a.addDataSource(r,e,!1)}else a=this.createPane(),a.addDataSource(r,null,!1);return r.setZorder(a.newStudyZOrder()),this.recalculatePane(a,(0,G.sourceChangeEvent)(r.id())),this.fullUpdate(),r}removeStudyStub(e){const t=this.dataSourceForId(e);return null===t?(so.logNormal("StudyStub id="+e+" is not found in chart model"),!1):(this.removeSource(t),!0)}restoreStudyStub(e){var t;const i=this.insertStudyStub(e.title,e.isOverlay,e.descriptor);return null===(t=this.paneForSource(i))||void 0===t||t.changeSourceId(i,e.id),i.setStatus(e.status),i}allLineTools(){return this._getAllSources(C.isLineTool)}setHoveredSource(e,t=null,i){const s=this._hoveredSource!==e;if(this._hoveredSourceOrigin=null!=i?i:null,!s&&(0,Si.hitTestResultDataAreEqual)(this._lastHoveredHittestData,t))return;this._lastHoveredHittestData=t;let o=null;if(this._hoveredSource){this._hoveredSource.updateAllViews((0,G.selectionChangeEvent)()),o=new J.InvalidationMask(J.InvalidationLevel.Cursor) ;const e=this._invalidationMaskForSource(this._hoveredSource,J.InvalidationLevel.Light);null!==e&&o.merge(e)}if(this._hoveredSource=e,e){e.updateAllViews((0,G.selectionChangeEvent)()),o||(o=new J.InvalidationMask(J.InvalidationLevel.Cursor));const t=this._invalidationMaskForSource(e,J.InvalidationLevel.Light);null!==t&&o.merge(t)}o&&this.invalidate(o),s&&this._hoveredSourceChanged.fire(e)}properties(){return this._properties}chartApi(){return this._chartApi}disconnect(){this.sessions().stop();for(const e of this.dataSources())e.disconnect&&e.disconnect();this._timeScale.disconnect()}crossHairSource(){return this.m_crossHairSource}gridSource(){return this._gridSource}publishedChartsTimelineSource(){for(const e of this._barsMarksSources)if(e instanceof pi.PublishedChartsTimeline)return e;return null}hoveredSource(){return this._hoveredSource}hoveredSourceOrigin(){return this._hoveredSourceOrigin}hoveredSourceChanged(){return this._hoveredSourceChanged}lastHittestData(){return this._lastHoveredHittestData}lastSelectedHittestData(){return this._lastSelectedHittestData}lightUpdate(){this.invalidate(J.InvalidationMask.light())}fullUpdate(){this.invalidate(J.InvalidationMask.full())}syncTimeWithModel(e,t){const i=this.mainSeries().syncModel();if(null===i)return;const s=1e3*this.createSyncPoint(e,i.syncSourceTarget()).sourceTimeToTargetTime(t/1e3),o=(0,Xt.get_timezone)(this.timezone());let r=(0,Xt.utc_to_cal)(o,s);this.mainSeries().isDWM()&&(r=i.getSession().spec.correctTradingDay(r),(0,Xt.set_hms)(r,0,0,0,0,(0,Xt.get_timezone)("Etc/UTC"))),this._gotoTimeImpl(r.getTime(),{centerIfVisible:!1})}gotoTime(e){return this._gotoTimeImpl(e,{centerIfVisible:!0})}recalculatePane(e,t){null==e||e.recalculate(t)}recalculateAllPanes(e){this._panes.forEach((t=>t.recalculate(e))),this.updateAllPaneViews(e),this.crossHairSource().updateAllViews(e)}gotoTimeRange(e,t){const i=this.timeScale(),s=i.tickMarks(),o=this.mainSeries();if(void 0===s.minIndex)return void(this._lastGotoTimeRange={from:e,to:t});let r=e,a=t;if(null!==o.symbolInfo()){const i=(0,n.ensureNotNull)(this.timezoneExceptExchange().value()),s=(0,Xt.get_timezone)(i),l=(0,Xt.utc_to_cal)(s,e),c=(0,Xt.utc_to_cal)(s,t);if(o.isDWM()){const e=(0,Xt.get_timezone)("Etc/UTC");(0,Xt.set_hms)(l,0,0,0,0,e),(0,Xt.set_hms)(c,0,0,0,0,e)}r=l.getTime(),a=c.getTime()}const l=(0,n.ensureDefined)(s.maxIndex),c=(0,n.ensureDefined)(s.minIndex);if(r>=(0,n.ensureNotNull)(s.indexToTime(c)).valueOf()||o.endOfData()){const e=(e,t)=>e(0,n.ensureNotNull)(s.indexToTime(e)).valueOf(),d=(0,b.lowerboundExt)(t,r,e,s.nearestIndex(r),l);let h=r===a?d:(0,b.lowerboundExt)(t,a,e,s.nearestIndex(a),l);this._lastGotoTimeRange=null,null!==this._lastAppliedGotoTimeRange&&(this._lastAppliedGotoTimeRange.actual=!1);const u=i.baseIndex();if(d+Math.max(h-d+1,i.minVisibleBarCount())>u){const e=i.targetDefaultRightOffset();h-u=0;t--)if(this._panes[t].hasDataSource(e))return this._panes[t];return e instanceof bi.BarsMarksContainer?this.paneForSource(this.mainSeries()):null}mainPane(){var e;return null!==(e=this._panes.find((e=>e.isMainPane())))&&void 0!==e?e:null}lastPane(){return this._panes[this._panes.length-1]}removeSource(e,t){this.selectionMacro((t=>t.removeSourceFromSelection(e)),!0),this._hoveredSource===e&&(this._hoveredSource=null,this._lastHoveredHittestData=null),this._sourcesBeingMoved.includes(e)&&(this._sourcesBeingMoved=this._sourcesBeingMoved.filter((t=>t!==e)),this._sourcesBeingMoved.length||(this._activeItemBeingMoved=null)),e===this._lineBeingEdited&&(this._lineBeingEdited=null,je.isToolEditingNow.setValue(!1)),e===this.lineBeingCreated()&&(this._lineBeingCreated=null,je.isToolCreatingNow.setValue(!1)),!t&&e.stop&&e.stop();(0,n.ensureNotNull)(this.alertsWatcher()).removeSourceAlertLabels(e);const i=this.detachSource(e),s=this.mainSeries().priceScale();return(0,K.isStudy)(e)&&(0,Oe.isActingAsSymbolSource)(e)&&e.priceScale()===s&&s.isPercentage()&&1===s.seriesLikeSources().filter(Oe.isActingAsSymbolSource).length&&s.setMode({percentage:!1}),this.fullUpdate(),this._invalidateBarColorerCaches(),(0,K.isStudy)(e)&&((0,m.emit)("study_event",e.id(),"remove"),e.isChildStudy()&&e.parentSources().forEach((t=>t.unsetChild(e))),e.maxOffset().unsubscribe(this._boundUpdateStudiesMaxOffset)),!t&&e.destroy&&e.destroy(),(0,C.isLineTool)(e)&&(e.removeAlert(),(0,m.emit)("drawing_event",e.id(),"remove")),i}timezone(){return this._properties.childs().timezone.value()}timezoneExceptExchange(){return this._timezoneExceptExchange}allStudies(e){const t=e?e=>(0,K.isStudy)(e)&&!(0,Pe.isLollipopDataSource)(e):K.isStudy;return this._getAllSources(t)}studiesWV(e){return e?this._studiesExcludeInternalWV.readonly():this._studiesWV.readonly()}listUserStudies(e){const t=[];for(const i of this._panes)for(const s of i.priceDataSources())if((0,K.isStudy)(s)&&!(0,K.isFundamentalStudy)(s)&&s.showInObjectTree()){const{id:i,shortDescription:o}=s.metaInfo();if(e.dontCountVolume&&"Volume@tv-basicstudies"===i||e.dontCountCompare&&"Compare@tv-basicstudies"===i||e.dontCountOverlay&&"Overlay@tv-basicstudies"===i)continue;t.push(o)}return t}findNonOverlayStudyWithGroupingKey(e,t){const i=void 0!==t?[t]:this._panes;for(const t of i){const i=t.dataSources().find((i=>(0,K.isStudy)(i)&&i.metaInfo().groupingKey===e&&!t.isOverlay(i)));if(void 0!==i)return{pane:t,study:i}}return null}movePaneUp(e){this.movePane(e,e-1)}movePaneDown(e){this.movePane(e,e+1)}movePane(e,t){const i=this._panes[e];this._panes.splice(e,1),this._panes.splice(t,0,i), this._panesCollectionChanged.fire(this._panes),this._onRearrangePanes.fire(),this.invalidate(J.InvalidationMask.panesOrder())}toggleCollapsedPane(e){const t=this._panes[e];t.collapsed().setValue(!t.collapsed().value()),this.fullUpdate()}backgroundColor(){return this._backgroundColor}backgroundTopColor(){return this._backgroundTopColor}backgroundColorAtYPercentFromTop(e){const t=this.backgroundColor().value(),i=this.backgroundTopColor().value();if(t===i)return t;if(e=Math.max(0,Math.min(100,Math.round(100*e))),null===this._gradientColorsCache||this._gradientColorsCache.topColor!==i||this._gradientColorsCache.bottomColor!==t)this._gradientColorsCache={topColor:i,bottomColor:t,colors:new Map};else{const t=this._gradientColorsCache.colors.get(e);if(void 0!==t)return t}const s=(0,fi.gradientColorAtPercent)(i,t,e/100);return this._gradientColorsCache.colors.set(e,s),s}backgroundCounterColor(){return this._backgroundCounterColor.readonly()}dark(){return this._isDark}readOnly(){return this._readOnly}defaultResolutions(){return this.chartApi().defaultResolutions()}availableCurrencies(){const e=this._getAvailableCurrencies();return e.length!==this._availableCurrencies.size()&&(this._availableCurrencies=new wi(e)),this._availableCurrencies}currencyConversionEnabled(){return this._options.currencyConversionEnabled}availableUnits(){const e=this._getAvailableUnits();return this._availableUnits.unitsChanged(e)&&(this._availableUnits=new Pi(e)),this._availableUnits}unitConversionEnabled(){return this._options.unitConversionEnabled}availablePriceSources(e){const t=this._getAvailablePriceSources(e);return null!==t&&this._availablePriceSources.priceSourcesChanged(t)&&(this._availablePriceSources=new Js(t)),this._availablePriceSources}resetDeferredStudies(){rt.instance(this).reset()}waitForStudy(e){return rt.instance(this).get(e)}resetWaitForStudy(e){rt.instance(this).delete(e)}isJustClonedChart(){return this._undoModel.isJustClonedChart()}studyTemplate(e,t,i){const s={panes:[],version:this.version()};for(const e of this.panes())s.panes.push(e.state(!0,!1,!0));const o=this.mainSeries();return e&&(s.symbol=o.symbol(),this.currencyConversionEnabled()&&i&&(s.currency=o.currency()),this.unitConversionEnabled()&&i&&(s.unit=o.unit())),t&&(s.interval=o.interval()),s}getStudyById(e){const t=this.dataSourceForId(e);return null!==t&&(0,K.isStudy)(t)?t:null}getLineToolById(e){const t=this.dataSourceForId(e);return null!==t&&(0,C.isLineTool)(t)?t:null}restoreLineToolState(e,t,i){var s;e.restorePoints(t.points,t.indexes||[]),t.state.intervalsVisibilities=(0,at.mergeIntervalVisibilitiesDefaults)(t.state.intervalsVisibilities),e.properties().merge(t.state),e.restoreData&&e.restoreData(t),e.linkKey().setValue(t.linkKey||null),e.createServerPoints(),e.setZorder(null!==(s=t.zorder)&&void 0!==s?s:e.zorder()),this.fullUpdate();const o=e.linkKey().value();null!==o&&i&&(0,je.restoreLineToolState)({model:this,linkKey:o,state:t})}restoreFactoryDefaults(e){e.restoreFactoryDefaults(), this.recalcVisibleRangeStudies(v.RecalcVisibleRangeStudiesReason.ViewportChangeUserAction)}preferences(){return(0,Zs.preferencesByWhiteList)(this,this.mainSeries())}restoreTheme(e,t,i){e.mainSourceProperties.hollowCandleStyle||(e.mainSourceProperties.hollowCandleStyle=e.mainSourceProperties.candleStyle),this._undoModel.chartLoadTheme(e,t,i)}onResetScales(){return this._resetScales}startMovingSources(e,t,i,s,o,r){this._sourcesBeingMoved=e,this._activeItemBeingMoved=i;let a=!1;if(this._sourcesBeingMoved.forEach((e=>{!a&&(0,K.isStudy)(e)&&(a=!0);const l=(0,n.ensureNotNull)(this.paneForSource(e)),c=(0,C.isLineTool)(e),d=c&&e.linkKey().value();if(!1!==d&&null!==d&&s.has(d)&&c&&e.isFixed()){const t=(0,n.ensureDefined)(s.get(d)),a={screen:this._percentPositionToPoint(t,l)};e.startMoving(a,i,o,r)}else e.startMoving(t,i,o,r);const h=this._paneInvalidationMask(l,J.InvalidationLevel.Light);this.invalidate(h)})),!r){const s=e.filter(C.isLineTool).filter((e=>e.linkKey().value()&&e.isSynchronizable())).map((e=>e.linkKey().value()));if(s.length&&t.logical){const r=this.externalTimeStamp(t.logical.index),a={linkKeys:s,model:this,symbol:this.mainSeries().symbol(),point:{price:t.logical.price,timeStamp:r},activeItem:null!==i?i:void 0,envState:o,pointPositionPercents:new Map};e.forEach((e=>{if((0,C.isLineTool)(e)){const i=e.linkKey().value();if(i&&e.isSynchronizable()&&e.isFixed()){const s=(0,n.ensureNotNull)(this.paneForSource(e));a.pointPositionPercents.set(i,this._pointToPercentPosition((0,n.ensureDefined)(t.screen),s))}}})),(0,je.startMovingLineTool)(a)}}je.isToolMovingNow.setValue(!0),a&&je.isStudyEditingNow.setValue(!0)}moveSources(e,t,i,s){if(this._sourcesBeingMoved.filter((e=>!e.isLocked||!e.isLocked())).forEach((o=>{const r=(0,C.isLineTool)(o)?o.linkKey().value():null;if(null!==r&&t.has(r)){const e=(0,n.ensureNotNull)(this.paneForSource(o)),a=(0,n.ensureDefined)(t.get(r)),l={screen:this._percentPositionToPoint(a,e)};o.move(l,this._activeItemBeingMoved,i,s)}else o.move(e,this._activeItemBeingMoved,i,s)})),this.lightUpdate(),!s&&e.logical){const t=this._sourcesBeingMoved.filter(C.isLineTool).filter((e=>e.isSynchronizable()&&!!e.linkKey().value())).map((e=>e.linkKey().value())),s=this.externalTimeStamp(e.logical.index),o={linkKeys:t,model:this,point:{price:e.logical.price,timeStamp:s},envState:i,pointPositionPercents:new Map};this._sourcesBeingMoved.filter(C.isLineTool).forEach((t=>{if(t.linkKey().value()&&t.isSynchronizable()&&t.isFixed()){const i=(0,n.ensureNotNull)(this.paneForSource(t));o.pointPositionPercents.set(t.linkKey().value(),this._pointToPercentPosition((0,n.ensureDefined)(e.screen),i))}})),(0,je.moveLineTool)(o)}}endMovingSources(e,t,i){const s=this._sourcesBeingMoved.map((s=>{const o=(0,n.ensureNotNull)(this.paneForSource(s)),r=s.endMoving(e,t,i),a=this._paneInvalidationMask(o,J.InvalidationLevel.Light);return a.invalidateAll(J.InvalidationLevel.Light),this.invalidate(a),r })),o=this._sourcesBeingMoved.filter(C.isLineTool).filter((e=>e.isSynchronizable()&&!!e.linkKey().value())).map((e=>e.linkKey().value())),r=this._sourcesBeingMoved.filter(C.isLineTool).filter((e=>e.isSynchronizable()&&!!e.linkKey)).map((e=>{const t={points:e.normalizedPoints(),interval:this.mainSeries().interval()};return e.isFixed()&&(t.pointPositionPercents=e.calcPositionPercents()),t}));o.length&&(0,je.finishMovingLineTool)({linkKeys:o,model:this,finalStates:r,changes:s}),this._sourcesBeingMoved=[],this._activeItemBeingMoved=null,je.isToolMovingNow.setValue(!1),je.isStudyEditingNow.setValue(!1)}sourcesBeingMoved(){return this._sourcesBeingMoved}setMovingCustomSource(e,t){this._customSourceBeingMoved=e,this._customSourceBeingMovedHitTestData=null!==t?{beingMoved:!1,cancelled:!1,...t}:null}processingCustomSourceMove(){null!==this._customSourceBeingMovedHitTestData&&(this._customSourceBeingMovedHitTestData.beingMoved=!0)}customSourceMovingHitTestData(){return this._customSourceBeingMovedHitTestData}customSourceBeingMoved(){return null!==this._customSourceBeingMovedHitTestData&&this._customSourceBeingMovedHitTestData.beingMoved?this._customSourceBeingMoved:null}lineToolsSynchronizer(){return this._lineToolsSynchronizer}setLineToolsSynchronizer(e){this._lineToolsSynchronizer=e}width(){return this._width}setWidth(e,t){(this._panes.reduce(((t,i)=>i.setWidth(e)||t),!1)||this._width!==e)&&(this._width=e,this._timeScale.setWidth(e,t),this.recalculateAllPanes((0,G.viewportChangeEvent)()),this.recalcVisibleRangeStudies(v.RecalcVisibleRangeStudiesReason.ViewportChangeUserAction))}setPaneHeight(e,t){e.setHeight(t),this.recalculateAllPanes((0,G.viewportChangeEvent)()),this.lightUpdate()}resetScalesAvailable(){return this._resetScalesAvailable.readonly()}panes(){return this._panes}paneForId(e){return this._panes.find((t=>t.id()===e))||null}createPane(e,t,i){this._undoModel.hideMaximizedPaneIfRequired();const s=this._properties.childs().paneProperties;t&&s.merge(t);const o=new vt(this._timeScale,s,this,i);return void 0!==e?this._panes.splice(e,0,o):this._panes.push(o),o.onTagsChanged().subscribe(this,ho.prototype.onPaneTagsChanged),o.dataSourcesCollectionChanged().subscribe(this,(()=>this._dataSourceCollectionChanged.fire(o))),o.symbolSourceCollectionChanged().subscribe(this,(()=>this._onSymbolSourceCollectionChanged(o))),o.priceSourcesCollectionChanged().subscribe(this,(()=>this._onPriceSourcesCollectionChanged(o))),o.sourcePropertiesChanged().subscribe(this,(e=>this._sourceProperitesChanged.fire(o,e))),o.sourceZOrderChanged().subscribe(this,(e=>this._sourceZOrderChanged.fire(o,e))),o.symbolSourceResolved().subscribe(this,(e=>this._symbolSourceResolved.fire(o,e))),o.symbolSourceResolvingActive().subscribe(this._recalcSymbolResolvingActive),o.collapsed().subscribe(this._recalcPaneCollapsingAvailable),o.resetPriceScalesAvailable().subscribe(this._updateResetScalesAvailableValue,{callWithLast:!0}),this._recalcPaneCollapsingAvailable(),this._panesCollectionChanged.fire(this._panes),this.invalidate(J.InvalidationMask.panesOrder()),o} removePane(e){this._undoModel.hideMaximizedPaneIfRequired();const t=e;t.destroy();const i=this._panes.indexOf(t);-1!==i&&(this._panes.splice(i,1),e.dataSourcesCollectionChanged().unsubscribeAll(this),e.symbolSourceCollectionChanged().unsubscribeAll(this),e.priceSourcesCollectionChanged().unsubscribeAll(this),e.sourcePropertiesChanged().unsubscribeAll(this),e.onTagsChanged().unsubscribeAll(this),e.symbolSourceResolved().unsubscribeAll(this),t.symbolSourceResolvingActive().unsubscribe(this._recalcSymbolResolvingActive),e.collapsed().unsubscribe(this._recalcPaneCollapsingAvailable),e.resetPriceScalesAvailable().unsubscribe(this._updateResetScalesAvailableValue),this._recalcPaneCollapsingAvailable(!0)),this._updateResetScalesAvailableValue();this.crossHairSource().pane===e&&this.clearCurrentPosition(),this._panesCollectionChanged.fire(this._panes),this.invalidate(J.InvalidationMask.panesOrder())}changePanesHeight(e,t){if(this._panes.length<2)return;(0,n.assert)(e>=0&&ee+t.stretchFactor()),0),o=this._panes.reduce(((e,t)=>e+t.height()),0),r=o-30*(this._panes.length-1);t=Math.min(r,Math.max(30,t));const a=s/o,l=i.height();i.setStretchFactor(t*a);let c=t-l,d=this._panes.length-1;for(const e of this._panes)if(e!==i){const t=Math.min(r,Math.max(30,e.height()-c/d));c-=e.height()-t,d-=1;const i=t*a;e.setStretchFactor(i)}this.fullUpdate()}clearCurrentPosition(){const e=this.crossHairSource();e.clearPosition(),(0,n.ensureNotNull)(e.dataWindowView()).update(),ro(this._panes),this.invalidate(J.InvalidationMask.cursor()),this._undoModel.syncCrosshair(null),this._phantomSourceContainer.onCursorPositionUpdated()}setAndSaveCurrentPosition(e,t,i,s){this.crossHairSource().saveOriginCoords(e,t),this.setCurrentPosition(e,t,i,s)}setCurrentPosition(e,t,i,s){var o,r,a,l,c,d;let h=NaN;const u=this._timeScale.coordinateToVisibleIndex(e),_=null!==(a=null===(r=null!==(o=this._lineBeingEdited)&&void 0!==o?o:this.lineBeingCreated())||void 0===r?void 0:r.priceScale())&&void 0!==a?a:i.defaultPriceScale();let p=null;!_.isEmpty()&&Number.isFinite(t)&&(p=(0,n.ensureNotNull)(i.mainDataSource()).firstValue(),null!==p&&(h=_.coordinateToPrice(t,p)));const m=this._crossHairSelectPointMode.value()!==je.SelectPointMode.None,g=this.currentTool(),S=this.mainSeries(),v=this.crossHairSource(),f=v.index,b=v.price,y=m||je.isStudyEditingNow.value(),C=_===this.m_mainSeries.priceScale()&&(this._lineBeingCreated||this._lineBeingEdited||(0,De.isLineToolName)(g)||(0,je.toolIsMeasure)(g)||y);!this._isSettingsExternalPosition&&C?(h=this._magnet.align(h,u,i),null!==p&&this._setCorrectedPositionToCrosshair(u,h,i)):this._magnet.resetLastValue();let w=null;if(isNaN(h)||(w=i),this._isTimeScrolling){if(!this._isSettingsExternalPosition&&m){const e=S.bars().firstIndex(),t=S.bars().lastIndex();if(null!==e&&null!==t){const s=Math.min(Math.max(u,e),t);s!==u&&this._setCorrectedPositionToCrosshair(s,h,i)}}else v.setPosition(v.index,h,w);return}v.setOnHoveredChartWidget(!0),v.setPosition(u,h,w), (0,n.ensureNotNull)(v.dataWindowView()).update(),ro(this._panes);const P=S.syncModel();this.crossHairSource().startMeasurePoint()||this._lineBeingCreated?this.lightUpdate():this.invalidate(J.InvalidationMask.cursor());const T=this.lineBeingCreated();if(T){const e=T.linkKey().value();if(!this._isSettingsExternalPosition){const t=T.setLastPoint({index:u,price:h},s);if(T.updateAllViews((0,G.sourceChangeEvent)(T.id())),t.price===h&&t.index===u||this._setCorrectedPositionToCrosshair(t.index,t.price,i),P&&e){const i=this._timeScale.points().roughTime(t.index,P.projectTime.bind(P));(0,je.setLineToolLastPoint)({model:this,linkKey:e,point:{timeStamp:(0,n.ensureNotNull)(i),price:t.price}})}}}if(!this._isSettingsExternalPosition&&null!==this._lineBeingEdited&&null!==this._linePointBeingEdited){const e={index:u,price:h};if(null===(l=this._linePointBeingChanged)||void 0===l?void 0:l.nonDiscreteIndex){const t=this.crossHairSource().originX();Number.isFinite(t)&&(e.index=this._timeScale.coordinateToFloatIndex(t))}this.changeLinePoint(e,s);const t=this._lineBeingEdited.alignCrossHairToAnchor(this._linePointBeingEdited)?this._lineBeingEdited.getPoint(this._linePointBeingEdited):e;null!==t&&this._setCorrectedPositionToCrosshair(t.index,t.price,i)}if(!this._isSettingsExternalPosition&&1===this._sourcesBeingMoved.length){const e=this._sourcesBeingMoved[0];if(null===(c=e.alignCrossHairToMovePoint)||void 0===c?void 0:c.call(e)){const t=null===(d=e.currentMovingPoint)||void 0===d?void 0:d.call(e);t&&t.logical&&this._setCorrectedPositionToCrosshair(t.logical.index,t.logical.price,i)}}if(!this._isSettingsExternalPosition&&y){const e=S.bars().firstIndex(),t=S.bars().lastIndex();if(null!==e&&null!==t){const s=Math.min(Math.max(u,e),t);s!==u&&this._setCorrectedPositionToCrosshair(s,h,i)}}(f!==u||b!==h)&&this._syncCrosshair(s)}setExternalPosition(e,t){let i;const s=this.crossHairSource();if(s.setOnHoveredChartWidget(!1),null!==e&&(0,be.isNumber)(e.timeStamp)){const t=this.mainSeries().syncModel();if(t){const s=this.createSyncPoint(e.syncSourceTarget,t.syncSourceTarget()).sourceTimeToTargetTime(e.timeStamp);i=this._timeScale.points().roughIndex(s,t.distance.bind(t))}}if(null!==e&&null!=i&&Number.isFinite(i)){this._isSettingsExternalPosition=!0;const o=(0,n.ensureNotNull)(this.paneForSource(this.mainSeries())),r=this._timeScale.indexToCoordinate(i),a=(0,n.ensureNotNull)(o.mainDataSource()).firstValue();if(null!==a){let i=NaN;void 0!==e.price&&Number.isFinite(e.price)&&(i=this.mainSeries().priceScale().priceToCoordinate(e.price,a)),s.clearOriginCoords(),this.setCurrentPosition(r,i,o,t)}return s.setOnHoveredChartWidget(!1),void(this._isSettingsExternalPosition=!1)}s.clearPosition(),(0,n.ensureNotNull)(s.dataWindowView()).update(),ro(this._panes),this.invalidate(J.InvalidationMask.cursor())}startScaleTime(e){this._timeScale.startScale(e)}scaleTimeTo(e){this._timeScale.scaleTo(e),this.recalculateAllPanes((0,G.viewportChangeEvent)()),this.lightUpdate()}endScaleTime(){this._timeScale.endScale(),this.lightUpdate(), this.recalcVisibleRangeStudies(v.RecalcVisibleRangeStudiesReason.ViewportChangeUserAction)}resetTimeScale(){this._timeScale.restoreDefault(),this.recalculateAllPanes((0,G.viewportChangeEvent)()),this.recalcVisibleRangeStudies(v.RecalcVisibleRangeStudiesReason.ViewportChangeUserAction),this.lightUpdate(),this._resetScales.fire()}startScalePrice(e,t,i){e.startScalePrice(t,i)}scalePriceTo(e,t,i){e.scalePriceTo(t,i),this.mainSeries().priceScale().isLockScale()?this.lightUpdate():this.invalidate(this._paneInvalidationMask(e,J.InvalidationLevel.Light))}endScalePrice(e,t){e.endScalePrice(t),this.invalidate(this._paneInvalidationMask(e,J.InvalidationLevel.Light))}startTwoPointsScalePrice(e,t,i,s){t.startTwoPointsScale(i,s)}twoPointsScalePriceTo(e,t,i,s){t.twoPointsScale(i,s),this.invalidate(this._paneInvalidationMask(e))}endTwoPointsScalePrice(e,t){t.endTwoPointsScale(),this.invalidate(this._paneInvalidationMask(e))}resetPriceScale(e,t){e.resetPriceScale(t),this.invalidate(this._paneInvalidationMask(e,J.InvalidationLevel.Light))}restorePriceScaleState(e,t,i){e.restorePriceScaleState(t,i),this.invalidate(this._paneInvalidationMask(e,J.InvalidationLevel.Light))}currentTool(){return this._currentTool}setCurrentTool(e){this._currentTool!==e&&((0,De.isLineToolName)(e)&&this.selectionMacro((e=>{e.clearSelection()})),this._currentTool=e,this._phantomSourceContainer.onToolChanged())}detachSource(e){const t=this.paneForSource(e);return!!t&&(t.removeDataSource(e),t.isEmpty()?(this._lineBeingCreated&&t===this._paneBeingCreatedLineOn&&this.cancelCreatingLine(),this.removePane(t),!0):(this.fullUpdate(),!1))}children(e,t){return this.dataSources().filter((i=>(0,K.isStudy)(i)&&!(0,Pe.isLollipopDataSource)(i)?!t&&i.parentSources().includes(e):i.ownerSource()===e))}onRearrangePanes(){return this._onRearrangePanes}studyInserted(){return this._studyInserted}finishLineTool(e){const t=e.linkKey().value();(0,je.drawOnAllCharts)().value()&&null!==t&&e.isSynchronizable()&&(0,je.finishLineTool)({linkKey:t,model:this})}startChangingLinetool(e,t,i,s,o){this._lineBeingEdited=e,this._linePointBeingChanged=t||null,this._linePointBeingEdited=void 0===i?null:i,this._lineBeingEdited.startChanging(i,t,o),je.isToolEditingNow.setValue(!0);const r=(0,n.ensureNotNull)(this.paneForSource(e));this._lineBeingEdited.startDragPoint&&void 0!==i&&void 0!==t&&this._lineBeingEdited.startDragPoint(i,t),o||void 0===i||void 0===t||this._lineBeingEdited.setPoint(i,t,s,o),this._lineBeingEdited.updateAllViews((0,G.sourceChangeEvent)(this._lineBeingEdited.id()));const a=this._paneInvalidationMask(r,J.InvalidationLevel.Light);this.invalidate(a);const l=e.linkKey().value();if(l&&e.isSynchronizable()&&void 0!==i&&void 0!==t){const e=(0,n.ensureNotNull)(this.externalTimeStamp(t.index));(0,je.startChangingLineTool)({linkKey:l,model:this,symbol:this.mainSeries().symbol(),point:{price:t.price,timeStamp:e},pointIndex:i,envState:s||null})}}createLineTool(e){const{pane:t,point:i,linetool:s,linkKey:o=null,sharingMode:r=0,id:l,fromExternalModel:c}=e;let{properties:d,ownerSource:h}=e;if((0, n.assert)((0,De.isLineToolName)(s),`Cannot create unknown line tool: ${s}`),d){const e={...Ks.intervalsVisibilitiesDefaults},t=d.childs().intervalsVisibilities.state();(0,be.merge)(e,null!=t?t:{});const i=d.state();i.intervalsVisibilities=e,d=(0,C.createLineToolProperties)(s,i,this)}const u=(0,C.createLineTool)(s,this,d,null,void 0,l);if("LineToolExecution"!==s){let e;switch(s){case"LineToolIcon":e=u.properties().childs().icon.value().toString(16).toUpperCase();break;case"LineToolEmoji":e=u.properties().childs().emoji.value();break;case"LineToolSticker":e=u.properties().childs().sticker.value()}(0,_.trackEvent)("drawings","Study_Drawing_"+s,e)}(0,C.isStudyLineTool)(u)&&(0,_.trackEvent)("studies",`Study_${u.metaInfo().id}`);const p=!u.linkKey().value()&&!o;h=(0,n.ensureDefined)(h||(0,n.ensureNotNull)(t.mainDataSource())),d||(0,C.prepareLineToolPropertiesByOwnerSource)(u.properties(),h),u.setOwnerSource(h);const m=h.priceScale();if(u.setPriceScale(m),h===this.mainSeries()&&u.share(r),t.addDataSource(u,m,!1),null!==u.preferredZOrder()&&t.insertAfter([u],this.mainSeries()),(0,je.drawOnAllCharts)().value()){const e=u.isSynchronizable()?o||(0,Se.randomHash)():null;u.linkKey().setValue(e)}else u.linkKey().setValue(o);let g;if(u.isFixed()){const e=(0,n.ensureNotNull)((0,n.ensureNotNull)(t.mainDataSource()).firstValue()),s=this._timeScale.indexToCoordinate(i.index),o=(0,n.ensureNotNull)(m).priceToCoordinate(i.price,e);g=u.addFixedPoint(new a.Point(s,o))}else g=u.addPoint(i);return g||(this._lineBeingCreated={lineDataSource:u,fromExternal:!!c},this._paneBeingCreatedLineOn=t,je.isToolCreatingNow.setValue(!0)),p&&u.enableCurrentIntervalVisibility(),this.fullUpdate(),u}endChangingLinetool(e,t){const i=(0,n.ensureNotNull)(this._lineBeingEdited),s=i.endChanging(!1,e,t);this._lineBeingEdited=null,je.isToolEditingNow.setValue(!1),this._linePointBeingEdited=null,this._linePointBeingChanged=null,this.lightUpdate();const o={points:i.normalizedPoints(),interval:this.mainSeries().interval()},r=i.linkKey().value();null!==r&&i.isSynchronizable()&&!t&&(0,je.finishChangingLineTool)({model:this,linkKey:r,symbol:this.mainSeries().symbol(),finalState:o,changes:s})}continueCreatingLine(e,t,i,s,o){const r=(0,n.ensureNotNull)(this.lineBeingCreated()),a=r.addPoint(e,t,i,o);r.updateAllViews((0,G.sourceChangeEvent)(r.id()));const l=new J.InvalidationMask(J.InvalidationLevel.Light);return a&&(this._paneBeingCreatedLineOn=null,this._lineBeingCreated=null,je.isToolCreatingNow.setValue(!1)),this.invalidate(l),a}cancelCreatingLine(){const e=this.lineBeingCreated();e&&(this.removeSource(e),this._lineBeingCreated=null,this._lineCancelled.fire(),je.isToolCreatingNow.setValue(!1),(0,je.drawOnAllCharts)().value()&&e.isSynchronizable()&&(0,je.cancelLineTool)({model:this}))}lineBeingCreated(){var e;return(null===(e=this._lineBeingCreated)||void 0===e?void 0:e.lineDataSource)||null}lineBeingCreateFromExternal(){var e;return(null===(e=this._lineBeingCreated)||void 0===e?void 0:e.fromExternal)||!1}paneBeingCreatedLineOn(){return this._paneBeingCreatedLineOn} lineCancelled(){return this._lineCancelled}isPhantomLine(e){return this._phantomSourceContainer.source()===e}changeLinePoint(e,t,i){const s=(0,n.ensureNotNull)(this._lineBeingEdited),o=(0,n.ensureNotNull)(this._linePointBeingEdited);let r=e.price,a=e.index;if(s.setPoint(o,e,t,i),!i){const t=s.alignCrossHairToAnchor(o)?s.getPoint(o):e;null!==t&&(a=t.index,r=t.price)}s.updateAllViews((0,G.sourceChangeEvent)(s.id())),this.lightUpdate();const l=s.linkKey().value();if(!i&&null!==l&&s.isSynchronizable()){const e=(0,n.ensureNotNull)(this._linePointBeingChanged),i={indexesChanged:a!==e.index,pricesChanged:r!==e.price},c=s.getChangePointForSync(o);if(null!==c){const e=this.externalTimeStamp(a);null!==e&&(r=c.price,(0,je.changeLineTool)({linkKey:l,model:this,symbol:this.mainSeries().symbol(),point:{price:r,timeStamp:e},envState:t,changes:i}))}}}changeLinePoints(e,t,i){const s=e.points(),o=e.linkKey().value();!i&&o&&e.isSynchronizable()&&t.forEach(((t,i)=>{const r=s[i],a=r.price!==t.price,l=r.index!==t.index;if(e.getChangePointForSync(i)){const e=(0,n.ensureNotNull)(this.externalTimeStamp(t.index));(0,je.changeLineTool)({linkKey:o,model:this,symbol:this.mainSeries().symbol(),point:{price:t.price,timeStamp:e},changes:{pricesChanged:a,indexesChanged:l}})}})),e.setPoints(t),e.updateAllViews((0,G.sourceChangeEvent)(e.id())),this.lightUpdate()}startScrollTime(e){this._timeScale.startScroll(e),this._isTimeScrolling=!0,this.mainSeries().clearGotoDateResult()}scrollTimeTo(e){this._timeScale.scrollTo(e),this.recalculateAllPanes((0,G.viewportChangeEvent)()),this.lightUpdate()}endScrollTime(){this._timeScale.endScroll(),this.lightUpdate(),this.recalcVisibleRangeStudies(v.RecalcVisibleRangeStudiesReason.ViewportChangeUserAction),this._isTimeScrolling=!1}startScrollPrice(e,t,i){e.startScrollPrice(t,i)}scrollPriceTo(e,t,i){e.scrollPriceTo(t,i),this.invalidate(this._paneInvalidationMask(e,J.InvalidationLevel.Light))}endScrollPrice(e,t){e.endScrollPrice(t),this.invalidate(this._paneInvalidationMask(e,J.InvalidationLevel.Light))}addCustomSource(e,t,i=v.CustomSourceLayer.Foreground){this._customSourcesMap.has(e)&&so.logWarn(`Attempt to add the same custom source multiple time "${e}"`),so.logNormal(`Adding custom source "${e}"`);const s=t(e,this);switch(i){case v.CustomSourceLayer.Background:this._bgCustomSources.push(s);break;case v.CustomSourceLayer.Foreground:this._fgCustomSources.push(s);break;case v.CustomSourceLayer.Topmost:this._topmostCustomSources.push(s);break;default:throw new Error(`Unknown custom sources layer ${i}`)}this._allCustomSources.push(s),this._customSourcesMap.set(e,s),this.lightUpdate()}removeCustomSource(e){this._removeCustomSource(e),this.lightUpdate()}hasCustomSource(e){return this._customSourcesMap.has(e)}customSourceForName(e){return this._customSourcesMap.get(e)||null}customSourceName(e){let t=null;return this._customSourcesMap.forEach(((i,s)=>{i===e&&(t=s)})),t}customSources(e){switch(e){case v.CustomSourceLayer.Background:return this._bgCustomSources;case v.CustomSourceLayer.Foreground:return this._fgCustomSources ;case v.CustomSourceLayer.Topmost:return this._topmostCustomSources;default:return this._allCustomSources}}addMultiPaneSource(e){this._multiPaneSources.push(e),this._onMultipaneSourcesCollectionChanged.fire(),this.lightUpdate()}removeMultiPaneSource(e){const t=this._multiPaneSources.indexOf(e);-1===t?so.logWarn("Attempt to remove multi-pane source which does not exist in the model"):(this._onMultipaneSourcesCollectionChanged.fire(),this._multiPaneSources.splice(t,1)),this.lightUpdate()}multiPaneSources(e){return this._multiPaneSources.filter((t=>!e.hasDataSource(t)))}onMultipaneSourcesCollectionChanged(){return this._onMultipaneSourcesCollectionChanged}rendererOptionsProvider(){return this._rendererOptionsProvider}magnet(){return this._magnet}priceAxisRendererOptions(){return this._rendererOptionsProvider.options()}dateTimeFormatter(){return this._dateTimeFormatter}dateFormatter(){return this._dateFormatter}timeFormatter(){return this._timeFormatter}isUnmergeAvailableForSource(e){if(!this._unmergeAvailable(e))return!1;return(0,n.ensureNotNull)(this.paneForSource(e)).dataSources().filter(this._unmergeAvailable,this).length>1}isMergeDownAvailableForSource(e){if(!this._unmergeAvailable(e))return!1;const t=this.paneForSource(e),i=this.panes();return t!==i[i.length-1]}isMergeUpAvailableForSource(e){if(!this._unmergeAvailable(e))return!1;return this.paneForSource(e)!==this.panes()[0]}sessions(){return(0,n.ensureNotNull)(this._sessions)}createSessions(e){(0,n.assert)(null===this._sessions,"Sessions are already created"),this.addCustomSource("sessions",((t,i)=>(this._sessions=new Z(t,i,e),this._sessions.start(),this._sessions)),v.CustomSourceLayer.Background)}createPrePostMarket(e){this.addCustomSource("prePostMarket",((t,i)=>new di.PrePostMarket(t,i,e)))}watermarkSource(){return this._watermarkSource}watermarkContentProvider(){return null}replayStatus(){return this._replayStatus}setReplayStatus(e){this._replayStatus.setValue(e)}isInReplay(){return this.m_mainSeries.isInReplay()}getSymbolString(){return this.m_mainSeries.getSymbolString()}interval(){return this.m_mainSeries.interval()}switchToReplay(e,t){this.m_mainSeries.switchToReplay(e,t)}switchToRealtime(){this.m_mainSeries.switchToRealtime(),this._timeScale.resetRightOffset(),this.setReplayStatus(0),this._scrollingState&&(this._scrollingState.deferred.reject(),this._scrollingState=null)}async canChangeResolution(e){return this.m_mainSeries.canChangeResolution(e)}theme(){const e=this.properties().childs().paneProperties.state(["horzGridProperties.style","vertGridProperties.style"]);delete e.topMargin,delete e.bottomMargin;const t=this.mainSeries().state().state;t&&(delete t.symbol,delete t.interval,delete t.currencyId,delete t.unitId);const i={mainSourceProperties:t,sessions:this.sessions().properties().state(),chartProperties:{paneProperties:e,scalesProperties:this.properties().childs().scalesProperties.state()},version:this.version()};return i.version=this.version(),i}onChartThemeLoaded(){return this._chartThemeLoaded}chartThemeLoaded(){this._chartThemeLoaded.fire()} async colorStudiesPropertiesReady(){this._recalcColorStudiesImpl(this._recalcVRStudiesParams);const e=this.allStudies(!0).filter((e=>e.metaInfo().inputs.filter(T.isStudyInputDependsOnChartColors).length>0));await Promise.all(e.map((e=>e.propertiesPatched())))}state(e,t,i,s){var o;const r=this.publishedChartsTimelineSource(),n=this.properties().childs(),a=n.tradingProperties.state(),l={panes:this._panes.map((o=>o.state(!0,e,!1,t,i,s))),timeScale:this._timeScale.state(e),chartProperties:{paneProperties:n.paneProperties.state(["horzGridProperties.style","vertGridProperties.style"]),scalesProperties:n.scalesProperties.state(),publishedChartsTimelineProperties:r?r.state(e):void 0,chartEventsSourceProperties:null===(o=n.chartEventsSourceProperties)||void 0===o?void 0:o.state(),tradingProperties:a,priceScaleSelectionStrategyName:n.priceScaleSelectionStrategyName.value()},sessions:this.sessions().state(e),version:this.version(),timezone:this.timezone(),shouldBeSavedEvenIfHidden:this._shouldBeSavedEvenIfHidden,linkingGroup:this._linkingGroupIndex.value()};return s||(l.lineToolsGroups=this.lineToolsGroupModel().state(t)),l}restoreState(e,t,s){var o;rt.instance(this).reset();const r={};if(!e.panes)return void so.logDebug("ChartModel.restoreState: invalid state");if(!Array.isArray(e.panes))return void so.logDebug("ChartModel.restoreState: invalid state");if(e.panes.length<1)return void so.logDebug("ChartModel.restoreState: invalid state");for(const e of this._barsMarksSources)this.detachSource(e);if(this._shouldBeSavedEvenIfHidden=void 0===e.shouldBeSavedEvenIfHidden||e.shouldBeSavedEvenIfHidden,e.chartProperties&&!e.chartProperties.timezone&&(e.chartProperties.timezone=e.timezone),e.chartProperties){const i=(0,W.factoryDefaults)("chartproperties").scalesProperties;(0,be.merge)(i,e.chartProperties.scalesProperties),!("showLastValue"in i)||"showSeriesLastValue"in i||"showStudyLastValue"in i||(i.showSeriesLastValueProperty=i.showLastValue,i.showStudyLastValueProperty=i.showLastValue),"showSeriesLastValue"in i&&(r.showSeriesLastValueProperty=!0),"showStudyLastValue"in i&&(r.showStudyLastValueProperty=!0),(!this.isSnapshot()&&!this.readOnly()&&"showCurrency"in i||"showUnit"in i)&&((0,Q.migrateShowCurrencyAndShowUnitProperties)(i.showCurrency,i.showUnit),delete i.showCurrency,delete i.showUnit);{const{paneProperties:t}=e.chartProperties;t.vertGridProperties=t.vertGridProperties||(0,be.clone)(t.gridProperties),t.horzGridProperties=t.horzGridProperties||(0,be.clone)(t.gridProperties),t.horzGridProperties.style=t.vertGridProperties.style=vi.LINESTYLE_SOLID,"backgroundType"in t||(t.backgroundType=yi.ColorType.Solid),"separatorColor"in t||(t.separatorColor=(0,u.getThemedColor)("color-chart-page-bg")),this._properties.childs().paneProperties.mergeAndFire(t)}this._properties.childs().scalesProperties.mergeAndFire(i),e.chartProperties.timezone&&this._properties.childs().timezone.setValue(e.chartProperties.timezone), e.chartProperties.chartEventsSourceProperties&&this._properties.hasChild("chartEventsSourceProperties")&&this._properties.childs().chartEventsSourceProperties.mergeAndFire(e.chartProperties.chartEventsSourceProperties),e.chartProperties.tradingProperties&&this._properties.hasChild("tradingProperties")&&(void 0===e.chartProperties.tradingProperties.horizontalAlignment&&(e.chartProperties.tradingProperties.horizontalAlignment=(a=e.chartProperties.tradingProperties.lineLength)<=40?v.TradedGroupHorizontalAlignment.Right:a>=60?v.TradedGroupHorizontalAlignment.Left:v.TradedGroupHorizontalAlignment.Center),this._properties.childs().tradingProperties.mergeAndFire(e.chartProperties.tradingProperties)),this._timeScale.restoreState(e.timeScale,t),this._updateDateTimeFormatter()}var a;if(e.timeScale&&this._timeScale.restoreState(e.timeScale,t),!this.readOnly()){const t=this._getExceedingChildStudies(e.panes);if(t.length){for(let i=e.panes.length-1;i>=0;--i){const s=e.panes[i];for(let e=s.sources.length-1;e>=0;--e){const i=s.sources[e];~t.indexOf(i)&&s.sources.splice(e,1)}s.sources.length||e.panes.splice(i,1)}{const e=window.user.pro_plan;setTimeout((()=>(0,hi.createGoProDialog)({feature:"studyOnStudy",actions:e&&"pro_premium_expert"===e?[{text:d.t(null,void 0,i(875139)),action:mi.PredefinedAction.Close}]:void 0})),500)}}}const l=e.version||0,c=e.panes;let h="_seriesId";for(const e of c){const t=e.sources.find((e=>"MainSeries"===e.type));if(t){h=t.id;break}}this.panes()[0].restoreState({state:c[0],withData:t,version:l,seriesId:h,settingsMigration:r,contentOverrides:s,restoreSilently:true,reason:2});let _=1;for(let i=1;if&&m%100==0?{lines_limit_exceeded:!0,line_tools_count:m}:(this.panes().forEach((e=>this._dataSourceCollectionChanged.fire(e))),this._lineToolsGroupModel.fireChangedAll(),this._linkingGroupIndex.setValue(null!==(o=e.linkingGroup)&&void 0!==o?o:null),{})}shouldBeSavedEvenIfHidden(){return this._shouldBeSavedEvenIfHidden}setShouldBeSavedEvenIfHidden(e){this._shouldBeSavedEvenIfHidden=e}externalTimeStamp(e){const t=this.mainSeries().syncModel();return this.timeScale().points().roughTime(e,t&&t.projectTime.bind(t))}syncLollipopSources(){var e;null===(e=this._lollipopSourcesWatcherLoader)||void 0===e||e.callFunction((()=>{null!==this._lollipopSourcesWatcher&&this._lollipopSourcesWatcher.syncSources()}))}restoreChartEvents(e){var t;null===(t=this._lollipopSourcesWatcherLoader)||void 0===t||t.callFunction((()=>{null!==this._lollipopSourcesWatcher&&this._options.chartEventsEnabled&&this._lollipopSourcesWatcher.restoreChartEvents(e)}))}recalcVisibleRangeStudies(e){var t;if(this._recalcVRStudiesParams.reasons.add(e),this.m_mainSeries.isStarted()&&this.m_mainSeries.isCompleted()){const i=(0,n.ensureDefined)(lo.get(e)).adapter,s=Math.min(...Array.from(this._recalcVRStudiesParams.reasons).map((e=>(0,n.ensureDefined)(lo.get(e)))).filter((e=>e.adapter===i)).map((e=>e.timeout)));(0,n.ensureDefined)(null===(t=this._recalcVisibleRangeStudiesImplDebouncedByAdapter.get(i))||void 0===t?void 0:t.get(s))()}else this._recalcVisibleRangeStudiesImpl(this._recalcVRStudiesParams)}recalcColorStudies(e){this._recalcColorStudiesParams.force=this._recalcColorStudiesParams.force||Boolean(e),this._recalcColorStudiesImplDebounced()}recalcStudyBasedLineTools(){this.dataSources().forEach((e=>{(0,C.isStudyLineTool)(e)&&e.recalcStudyIfNeeded()}))}alertsWatcher(){return this._alertsWatcher}showLegend(){return this._showLegendProperty}id(){return this._id}selectPointMode(){return this._crossHairSelectPointMode}cancelRequestSelectPoint(){this.m_crossHairSource.cancelRequestSelectPoint()}requestSelectPoint(e){return this.m_crossHairSource.requestSelectPoint(e)}onPointSelected(){return this.m_crossHairSource.onPointSelected()}recalculatePriceRangeOnce(){const e=this.mainSeries();for(const t of this._panes)for(const i of t.priceDataSources())i.symbolSource()===e&&i.disablePriceRangeReady()}invalidate(e){var t;null===(t=this._invalidateHandler)||void 0===t||t.call(this,e)}appliedTimeFrame(){return this._appliedTimeFrame.appliedTimeFrame()}barsMarksSources(){return this._barsMarksSources}createSyncPoint(e,t){return(0,js.getDefault2Lazy)(this._syncPointCache,e.uniqueId,t.uniqueId,(()=>new ii(e,t)))}isAutoSaveEnabled(){return this._isAutoSaveEnabled}linkingGroupIndex(){return this._linkingGroupIndex}studyAwareDefaultRightOffset(){return this._timeScale.usePercentageRightOffset().value()?this._timeScale.percentsToBarIndexLength(this.studyAwareDefaultRightOffsetPercentage()):Math.max(this._timeScale.defaultRightOffset().value(),this._cachedStudiesMaxOffset)} studyAwareDefaultRightOffsetPercentage(){return this._timeScale.usePercentageRightOffset().value()?Math.max(this._timeScale.defaultRightOffsetPercentage().value(),this._timeScale.barIndexLengthToPercents(this._cachedStudiesMaxOffset)):this._timeScale.barIndexLengthToPercents(this.studyAwareDefaultRightOffset())}clearAllStudies(){this.dataSources().forEach((e=>{var t;return null===(t=e.clearData)||void 0===t?void 0:t.call(e)}))}setTimeScaleAnimation(e,t){const i=J.InvalidationMask.light(),s=this._timeScale;i.setTimeScaleAnimation(e,null!=t?t:s.width()-s.indexToCoordinate(s.baseIndex())),this.invalidate(i)}stopTimeScaleAnimation(){this._timeScale.endScroll();const e=J.InvalidationMask.light();e.stopTimeScaleAnimation(),this.invalidate(e)}lollipopSourcesOptions(){const e=this._options;return{chartEventsEnabled:!this._options.isSnapshot&&this._options.chartEventsEnabled,esdEnabled:e.esdEnabled,newsNotificationsEnabled:e.newsNotificationsEnabled,continuousContractSwitchesEnabled:e.continuousContractSwitchesEnabled,futuresContractExpirationEnabled:e.futuresContractExpirationEnabled,latestUpdatesEnabled:e.latestUpdatesEnabled}}onSymbolIntervalChanged(){return this._symbolIntervalChanged}_initAlertsList(){return this._alertsListPromise||(this._alertsListPromise=(0,ai.getChartAlertsFacade)().then((e=>{this._alertsList=e.createCollection((()=>this.mainSeries().interval()),(()=>this.mainSeries().actualSymbol())),this._alertsList.alertAdded().subscribe(this,this._addAlertLabelToChart.bind(this)),this._alertsList.alertRemoved().subscribe(this,this._removeAlertLabelFromChart.bind(this)),this._alertsList.alertChanged().subscribe(this,(e=>{this._removeAlertLabelFromChart(e),this._addAlertLabelToChart(e)})),this._alertsList.sync();const t=e=>{this.mainSeries().dataEvents().symbolResolved()[e](this,i),this.mainSeries().dataEvents().symbolError()[e](this,this._removeAllAlertLabelsFromChart),this.mainSeries().properties().childs().interval[e](this,i)},i=()=>{var e;null===(e=this._alertsList)||void 0===e||e.sync()};return window.loginStateChange.subscribe(this,(()=>{var e;null===(e=this._alertsList)||void 0===e||e.reset(),t(window.is_authenticated?"subscribe":"unsubscribe")})),window.is_authenticated&&t("subscribe"),this._alertsList}))),this._alertsListPromise}_updateStudiesMaxOffset(){const e=Math.max(...this.allStudies().map((e=>e.maxOffset().value())));this._cachedStudiesMaxOffset=e;const t=this._timeScale.rightOffset();if(t<0)return;if(e<=t)return;const i=this._timeScale.logicalRange();i?this._timeScale.zoomToBarsRange(i.left(),this._timeScale.baseIndex()+Math.max(this._timeScale.rightOffset(),e)):this._timeScale.setRightOffset(Math.max(t,e))}_updateBaseIndex(e,t){const i=this._timeScale,s=i.baseIndex(),o=i.logicalRange();if(null!==o&&t){const t=o.contains(s),r=e-s,n=t?null:i.rightOffset()-r;if(!this._options.shiftVisibleRangeOnNewBar&&t){const e=i.width()/i.barSpacing(),t=e/(e+r),s=Math.max(i.minBarSpacing(),i.barSpacing()*t);i.setBarSpacing(s)}null!==n&&i.setRightOffset(n)}i.setBaseIndex(e)}async _createLollipopSourcesWatcher(){{ const e=this.lollipopSourcesOptions(),t=[e.esdEnabled,e.continuousContractSwitchesEnabled,e.futuresContractExpirationEnabled,e.latestUpdatesEnabled.minds,e.latestUpdatesEnabled.news,e.chartEventsEnabled],s=(0,si.onWidget)(),o=this.isSnapshot();(t.some(Boolean)||!s||o)&&(await(0,B.studyMetaInfoRepository)().requestMetaInfo(),this._lollipopSourcesWatcherLoader=new S.AsyncResourceWrapper(i.e(71745).then(i.bind(i,163662))),this._lollipopSourcesWatcherLoader.callFunction((e=>{this._lollipopSourcesWatcher=new e.LollipopSourcesWatcher(this)})))}}_updateDateTimeFormatter(){const e=Kt.dateFormatProperty.value(),t=this.onWidget()?void 0:_i.withWeekdayProperty.value();if(this._dateFormatter=new Zt.DateFormatter(e,t),this.mainSeries().isDWM())this._dateTimeFormatter=new Zt.DateFormatter(e,t),this._timeFormatter=new Nt.TimeFormatter((0,Rt.getHourMinuteFormat)(Bt.timeHoursFormatProperty.value()));else{const i=I.Interval.parse(this.mainSeries().interval()),s=(0,Rt.getTimeFormatForInterval)(i,Bt.timeHoursFormatProperty.value());this._dateTimeFormatter=new jt.DateTimeFormatter({dateFormat:e,withWeekday:t,timeFormat:s,dateTimeSeparator:" "}),this._timeFormatter=new Nt.TimeFormatter(s)}}_invalidationMaskForSource(e,t=J.InvalidationLevel.Light){if(e===this.crossHairSource())return J.InvalidationMask.cursor();if(this._watermarkSource===e)return this._paneInvalidationMask((0,n.ensureNotNull)(this.paneForSource(this.mainSeries())),t);if(-1!==this._allCustomSources.indexOf(e)){const e=new J.InvalidationMask;return e.invalidateAll(t),e}if(!(0,f.isDataSource)(e))return null;if(e.isMultiPaneEnabled())return new J.InvalidationMask(t);const i=this.paneForSource(e);return null!==i?this._paneInvalidationMask(i,t):null}_paneInvalidationMask(e,t=J.InvalidationLevel.Light){const i=new J.InvalidationMask,s=this._panes.indexOf(e);return i.invalidateAllPane(s,t),i}_invalidationMaskForSourcePriceScale(e,t=J.InvalidationLevel.Light){if(!(0,f.isDataSource)(e))return new J.InvalidationMask(t);const i=this.paneForSource(e);if(null===i)return null;let s=e.priceScale();if(null===s)return null;const o=this._panes.indexOf(i);let r=i.priceScalePosition(s);if("overlay"===r){const e=this._panes[o].defaultPriceScale();s=e,r=i.priceScalePosition(e)}const n=i.priceScaleIndex(s,r);if(void 0===n)return null;const a=new J.InvalidationMask;return a.invalidatePriceScale(o,r,n,t),a}_removeCustomSource(e){const t=this._customSourcesMap.get(e);if(void 0===t)return void so.logWarn(`Attempt to remove custom source which does not exist in the model - "${e}"`);so.logNormal(`Removing custom source "${e}"`),this.selectionMacro((e=>{e.removeSourceFromSelection(t)})),this._hoveredSource===t&&this.setHoveredSource(null),this._customSourceBeingMoved===t&&this.setMovingCustomSource(null,null);const i=oo(this._bgCustomSources,t),s=oo(this._fgCustomSources,t),o=oo(this._topmostCustomSources,t),r=oo(this._allCustomSources,t);(0,n.assert)(i||s||o,"Source should be presented in one of the layers"),(0,n.assert)(r,"Source should be presented in the array"),this._customSourcesMap.delete(e), t.destroy()}_updateShowLegendProperty(){const e=this._properties.childs().paneProperties.childs().legendProperties.childs().showLegend,t=this._showLegendProperty;if(e.value())t.setValue(!0);else{for(const e of this._panes){let i=0;for(const s of e.priceDataSources())if(null!==s.statusView()&&(i++,i>=2))return void t.setValue(!1)}t.setValue(!0)}}_pointToPercentPosition(e,t){return{x:e.x/this._timeScale.width(),y:e.y/(0,n.ensureNotNull)((0,n.ensureNotNull)(t.mainDataSource()).priceScale()).height()}}_percentPositionToPoint(e,t){const i=e.x*this._timeScale.width(),s=e.y*(0,n.ensureNotNull)((0,n.ensureNotNull)(t.mainDataSource()).priceScale()).height();return new a.Point(i,s)}_recalcVisibleRangeStudiesImpl(e){var t,i;if(!this.m_mainSeries.isStarted()||!this.m_mainSeries.isCompleted())return void this._visibleRangeStudiesInputs.setValue(null);if(this.timeScale().isEmpty())return;const s=this.timeScale().visibleBarsStrictRange();if(null===s)return;const o=this.m_mainSeries.bars(),r=o.search(s.firstBar(),Ot.PlotRowSearchMode.NearestRight),n=o.search(s.lastBar(),Ot.PlotRowSearchMode.NearestLeft),a=o.lastIndex(),l=r?r.index:void 0,c=n?n.index:void 0,d=l===e.oldStartVisibleIndex,h=c===e.oldEndVisibleIndex,u=[v.RecalcVisibleRangeStudiesReason.SeriesRestart,v.RecalcVisibleRangeStudiesReason.SeriesCompleted,v.RecalcVisibleRangeStudiesReason.StudyCreation].some((t=>e.reasons.has(t)));d&&h&&!u||(e.reasons.clear(),e.oldStartVisibleIndex=void 0!==l?l:NaN,e.oldEndVisibleIndex=void 0!==c?c:NaN,this._visibleRangeStudiesInputs.setValue({firstVisibleBarTime:1e3*(null!==(t=null==r?void 0:r.value[0])&&void 0!==t?t:0),lastVisibleBarTime:1e3*(null!==(i=null==n?void 0:n.value[0])&&void 0!==i?i:0),subscribeRealtime:(null==n?void 0:n.index)===a}))}_recalcColorStudiesImpl(e){var t;const i=this.backgroundColorAtYPercentFromTop(.5),s=this.dark().value()?c.colorsPalette["color-cold-gray-200"]:c.colorsPalette["color-cold-gray-900"],o=i===e.oldBgColor,r=s===e.oldFgColor;if(o&&r&&!e.force)return;e.force=!1,e.oldBgColor=i,e.oldFgColor=s;const n=null!==(t=e.studies)&&void 0!==t?t:this.priceDataSources();e.studies=void 0;for(const e of n)if((0,K.isStudy)(e)){const t=e.metaInfo().inputs.filter(T.isStudyInputDependsOnChartColors),o=e.properties().childs().inputs;t.forEach((e=>{const t=e.id===T.ChartColorDependentStudyInputNames.FgColor?s:i;o.childs()[e.id].setValueSilently(t)})),t.length>0&&o.listeners().fire(o,"")}}_getAllSources(e){const t=[];for(const i of this._panes){const s=i.sourcesByGroup().allWithoutMultipane();for(const i of s)e(i)&&t.push(i)}return t}_invalidateBarColorerCaches(){this.mainSeries().invalidateBarColorerCache()}_addAlertLabelToChart(e){{const t=e.seriesId();if(null===t)return;(0,n.ensureNotNull)(this.alertsWatcher()).addAlert(e,t)}}_removeAlertLabelFromChart(e){(0,n.ensureNotNull)(this.alertsWatcher()).removeAlert(e)}_removeAllAlertLabelsFromChart(){(0,n.ensureNotNull)(this.alertsWatcher()).removeAllAlertLabels()}_updateTimeScale(e){var t,i,s,o;const{index:r,zoffset:n,values:a,indexDiffs:l,baseIndex:c,marks:d,clearFlag:h}=e;if(h){ this._timeScale.reset();for(const e of this.dataSources())null===(t=e.clearData)||void 0===t||t.call(e)}if(l.length>0)for(const e of this.dataSources())null===(i=e.moveData)||void 0===i||i.call(e,l);const u=this._timeScale.indexToTimePoint(this._timeScale.baseIndex()),_=this._timeScale.canNormalize();this._timeScale.update(r,n,a,d);const p=this._timeScale.points().range().value();let m="ChartModel.prototype._updateTimeScale("+r+","+n+","+a.length+","+l.length+","+d.length+","+h+")";if(m+="TimeScale: {first:"+(null!==(s=null==p?void 0:p.firstIndex)&&void 0!==s?s:null)+",last:"+(null!==(o=null==p?void 0:p.lastIndex)&&void 0!==o?o:null)+"}",null===c){this._timeScale.resetBaseIndex();const e=this._timeScale.rightOffset();this._timeScale.setRightOffset(Math.max(e,this._cachedStudiesMaxOffset))}else if(void 0!==c){const e=this._timeScale.indexToTimePoint(c),t=null!==u&&null!==e&&e>u;this._updateBaseIndex(c,t)}if(so.logDebug(m),!_&&_!==this._timeScale.canNormalize())for(const e of this.dataSources())!(0,C.isLineTool)(e)||e.isFixed()||e.isSourceHidden()||e.processHibernate();for(const e of this.dataSources())e.updateAllViews({type:"data-source-change",sourceId:e.id(),clearData:!0});this.recalculateAllPanes((0,G.globalChangeEvent)()),this.lightUpdate()}_getAvailableCurrencies(){return!this.currencyConversionEnabled()||this.isSnapshot()?[]:(0,be.isArray)(this._availableCurrenciesList)?this._availableCurrenciesList:(null!==this._availableCurrenciesList||(this._availableCurrenciesList=this.chartApi().availableCurrencies(),this._availableCurrenciesList.then((e=>{this._destroyed||(this._availableCurrenciesList=e,this.fullUpdate())})).catch((e=>{so.logWarn(`An error occurred while getting currencies config: ${e}`)}))),[])}_getAvailableUnits(){return!this.unitConversionEnabled()||this.isSnapshot()?{}:this._availableUnitsObject instanceof Promise||null===this._availableUnitsObject?(null!==this._availableUnitsObject||(this._availableUnitsObject=this.chartApi().availableUnits(),this._availableUnitsObject.then((e=>{this._destroyed||(this._availableUnitsObject=e,this.fullUpdate())})).catch((e=>{so.logWarn(`An error occurred while getting units config: ${e}`)}))),{}):this._availableUnitsObject}_getAvailablePriceSources(e){const t=this._availablePriceSourcesBySymbol.get(e);if(Array.isArray(t))return t;if((0,be.isPromise)(t))return[];const i=this.chartApi().availablePriceSources(e);return this._availablePriceSourcesBySymbol.set(e,i),i.then((t=>{this._destroyed||(this._availablePriceSourcesBySymbol.set(e,t),this.fullUpdate())})).catch((e=>{so.logWarn(`An error occurred while getting price sources config: ${e}`)})),[]}_clearAvailablePriceSources(){this._availablePriceSourcesBySymbol.clear()}_onSymbolIntervalChanged(){this._symbolIntervalChanged.fire()}_getBackgroundColor(e){const t=this._properties.childs().paneProperties.childs();if(t.backgroundType.value()===yi.ColorType.Gradient){const i=t.backgroundGradientStartColor.value(),s=t.backgroundGradientEndColor.value();return function(e,t,i){if((0, u.getCurrentTheme)().name===ri.StdTheme.Dark&&(0,oi.isOnMobileAppPage)("any")&&(0,u.isStdThemedDefaultValue)("chartProperties.paneProperties.backgroundGradientStartColor",e,ri.StdTheme.Dark)&&(0,u.isStdThemedDefaultValue)("chartProperties.paneProperties.backgroundGradientEndColor",t,ri.StdTheme.Dark))return ni;return i?e:t}(i,s,Boolean(e))}const i=t.background.value();return function(e){if((0,u.getCurrentTheme)().name===ri.StdTheme.Dark&&(0,oi.isOnMobileAppPage)("any")&&(0,u.isStdThemedDefaultValue)("chartProperties.paneProperties.background",e,ri.StdTheme.Dark))return ni;return e}(i)}_getBackgroundCounterColor(){const e=this.backgroundColor().value();return"black"===(0,l.rgbToBlackWhiteString)((0,l.parseRgb)(e),150)?"white":"black"}_updateBackgroundColor(){this._backgroundColor.setValue(this._getBackgroundColor()),this._backgroundTopColor.setValue(this._getBackgroundColor(!0))}_syncCrosshair(e){if(!this._isSettingsExternalPosition){const t=this._undoModel.mainSeries(),i=t.syncModel(),s=this._undoModel.crossHairSource(),o=s.pane;if(null!==i&&null!==o){const r={timeStamp:this._timeScale.points().roughTime(s.index,i.projectTime.bind(i)),syncSourceTarget:i.syncSourceTarget()};o.mainDataSource()===t&&(r.price=s.price,r.symbol=t.symbol());let n=this._lineBeingCreated||null!==this._linePointBeingEdited||Boolean(this._sourcesBeingMoved.length);n=n&&(0,je.drawOnAllCharts)().value(),this._undoModel.syncCrosshair(r,n,e)}this._phantomSourceContainer.onCursorPositionUpdated()}}_gotoTimeImpl(e,t){const i=this.timeScale(),s=this.mainSeries();let o;if(void 0!==e){if(this._scrollingState&&this._scrollingState.deferred.reject(),o=(0,p.createDeferredPromise)(),o.promise.catch((()=>{})),!s.isDWM()){const t=s.symbolInfo();if(null!==t){const i=(0,n.ensureNotNull)(this.timezoneExceptExchange().value()),o=(0,Xt.cal_to_utc)((0,Xt.get_timezone)(i),new Date(e)),r=(0,ki.createTimeToBarTimeAligner)(s.interval(),t)(o);e=(0,Xt.utc_to_cal)((0,Xt.get_timezone)(i),r).getTime()}}this._scrollingState={targetDate:e,deferred:o,centerIfVisible:t.centerIfVisible}}else{if(!this._scrollingState)return so.logError("scrollTo called without an argument"),Promise.reject();e=this._scrollingState.targetDate,o=this._scrollingState.deferred}if(void 0===i.tickMarks().minIndex)return o.resolve(void 0),o.promise;this.stopTimeScaleAnimation();let r=((e,t)=>{if((e=>(0,n.ensureNotNull)(i.tickMarks().indexToTime((0,n.ensureDefined)(i.tickMarks().minIndex))).valueOf()-e)(t)<0){let o=i.tickMarks().nearestIndex(t);const r=s.bars().lastIndex();if(null===r)return null;o=Math.min(o,r);let a=(0,n.ensureNotNull)(i.tickMarks().indexToTime(o)).valueOf();for(;ae.hasDataSource(this.m_mainSeries)))&&(this._studiesWV.setValue(this.allStudies()),this._studiesExcludeInternalWV.setValue(this.allStudies(!0)))}_unmergeAvailable(e){return e===this.m_mainSeries||(0,K.isStudy)(e)&&!e.isLinkedToSeries()&&!(0,Xs.isNonSeriesStudy)(e)&&e.showInObjectTree()}_getExceedingChildStudies(e){var t,i;let s=[];for(let t=0;tr&&n.push(e)),l=(l+1)%s.length}return n}}},607113:(e,t,i)=>{"use strict";var s=i(650151).assert,o=i(890165).ChartModelBase,r=i(713473).isLineTool,n=i(638456).CheckMobile,a=i(572230).InvalidationLevel;i(707957).Delegate;const{globalChangeEvent:l,sourceChangeEvent:c}=i(964824);var d=i(238433).isStudy,h=i(885482),u=i(220843).MainSeriesScaleRatioProperty,_=i(915179).scaleRatio,p=i(849245).StudyInserter,m=i(992543).dateFormatProperty,g=i(827023).timeHoursFormatProperty,S=i(251954),v=i(65541).StudyColorRotatorFactory,f=i(244842),b=i(108039).AppliedTimeFrame,y=f.enabled("fix_left_edge");class C extends o{constructor(e,t,i,s,o,r,n,a,l,c){super(e,t,i,s,o,r,n,a,l,c);var d=this;this._mainSeriesScaleRatioProperty=new u(this),this.m_mainSeries.dataEvents().completed().subscribe(this,function(){if(this._scrollingState&&this.gotoTime(),y&&!this.m_mainSeries.requestMoreDataAvailable()){var e=this.m_mainSeries.bars().first();null!==e&&this._timeScale.setLeftEdgeFix(e.index)}}.bind(this)),this.m_mainSeries.onIntervalChanged().subscribe(this,(function(){this._recalcVRStudiesParams.oldStartVisibleIndex=NaN,this._recalcVRStudiesParams.oldEndVisibleIndex=NaN})),this.m_mainSeries.dataEvents().barReceived().subscribe(this,C.prototype.updateTimeScaleBaseIndex), this._readOnly||(this.m_mainSeries.properties().addChild("priceAxisProperties",this.m_mainSeries.priceScale().properties()),this._properties.paneProperties.legendProperties.showStudyTitles.listeners().subscribe(this,(function(e){e.value()||d._properties.paneProperties.legendProperties.showStudyArguments.setValue(!1)}))),h.hideAllDrawings().subscribe(this,this._onDrawingsVisibilityChanged),h.hideAllIndicators().subscribe(this,this._onIndicatorsVisibilityChanged),this._properties.scalesProperties.listeners().subscribe(this,C.prototype.fullUpdate),this._studyShiftColorStartOffset=void 0,m.subscribe(this,this._updateDateTimeFormatter),g.subscribe(this,this._updateDateTimeFormatter),this.mainSeries().properties().interval.subscribe(this,this._updateDateTimeFormatter),this._updateDateTimeFormatter(),this._studyColorRotatorFactory=new v(this),this._undoModel._chartWidget.onWidget()||this._initAlertsList(),this._dataSourceCollectionChanged.subscribe(this,this._updateShowLegendProperty.bind(this)),this._properties.paneProperties.legendProperties.showLegend.subscribe(this,this._updateShowLegendProperty),this._appliedTimeFrame=new b(this),this.mainSeries().onTimeFrameApplied().subscribe(this,(function(e){var t=null!==e?{res:this.mainSeries().interval(),val:e}:null;this.appliedTimeFrame().setValue(t)}))}applyPreferences(e){for(var t in e)void 0!==this._properties[t]&&"m_mainSeries"!==this._properties[t]&&this._properties[t].mergeAndFire(e[t]);void 0!==e.timeScale&&(this._timeScale.defaultRightOffset().setValue(e.timeScale.defaultRightOffset),this._timeScale.defaultRightOffsetPercentage().setValue(e.timeScale.defaultRightOffsetPercentage),this._timeScale.usePercentageRightOffset().setValue(e.timeScale.usePercentageRightOffset)),this._properties.saveDefaults(),this.m_mainSeries.applyPreferences(e.mainSeries),this.sessions().applyPreferences(e.sessions),this.recalculateAllPanes(l()),this.fullUpdate()}startNotStartedStudies(){if(!this.m_mainSeries.isStarted())throw new Error("Cannot start studies: main series is not started");for(var e=this.dataSources(),t=0;t0),r?{left:0,right:1,totallySlots:i}:{left:1,right:0,totallySlots:i}}return{left:e,right:t,totallySlots:e+t}}setPriceAutoScale(e,t,i){e.setPriceAutoScale(t,i),this.invalidate(this._paneInvalidationMask(e,a.Light))}updateScales(e,t){this._undoModel._chartWidget._updateScalesActions()}mainSeriesScaleRatioProperty(){return this._mainSeriesScaleRatioProperty}mainSeriesScaleRatioPropertyOnChanged(){this._mainSeriesScaleRatioProperty.listeners().fire(this._mainSeriesScaleRatioProperty)}mainSeriesScaleRatio(){return _(this._timeScale,this.m_mainSeries.priceScale())}setMainSeriesScaleRatio(e){this.paneForSource(this.m_mainSeries).applyPriceScaleRatio(this.m_mainSeries.priceScale(),e)}dataSourceForId(e){for(var t,i=0;ithis.removeSource(e))),Array.from(this._customSourcesMap.keys()).forEach(this._removeCustomSource,this),s(0===this._topmostCustomSources.length),s(0===this._fgCustomSources.length),s(0===this._bgCustomSources.length),s(0===this._allCustomSources.length),s(0===this._customSourcesMap.size);for(var e=0;e{"use strict";i.d(t,{sourceNewCurrencyOnPinningToPriceScale:()=>o});var s=i(981107);function o(e,t,i,o){let r=null;if(i.currencyConversionEnabled()&&(0,s.isActingAsSymbolSource)(e)){const s=i.availableCurrencies(),n=t.currency(s),a=e.currency();null!==n&&null!==n.selectedCurrency&&!n.allCurrenciesAreOriginal&&n.selectedCurrency!==a&&(o&&null===a||null!==a&&s.convertible(a))&&(r=n.selectedCurrency)}return r}},949529:(e,t,i)=>{"use strict";i.d(t,{CustomSourceBase:()=>s});class s{constructor(e,t){this._id=e,this._model=t}id(){return this._id}isHoveredEnabled(){return!0}isSelectionEnabled(){return!1}priceScale(){return null}paneViews(e){return[]}labelPaneViews(e){return[]}priceAxisViews(e,t){return[]}updateViewsForPane(e,t){e.containsMainSeries()&&this.updateAllViews(t)}}},992543:(e,t,i)=>{"use strict";i.d(t,{dateFormatProperty:()=>l,restoreDateFormatSettingsValue:()=>c}) ;var s=i(62802),o=i(152633),r=i(958067);const n="date_format";function a(){return s.getValue(n,(0,r.defaultDateFormat)())}const l=(0,o.createPrimitiveProperty)(a());function c(){l.setValue((0,r.defaultDateFormat)()),s.remove(n)}s.onSync.subscribe(null,(()=>l.setValue(a()))),l.subscribe(null,(()=>s.setValue(n,l.value())))},950740:(e,t,i)=>{"use strict";i.d(t,{EnvironmentState:()=>o});var s=i(638456);class o{constructor(e,t=!1){this._shift=!1,this._mod=!1,this._alt=!1,void 0!==e&&(this._shift=Boolean(e.shiftKey),this._mod=Boolean((0,s.isMac)()?e.metaKey:e.ctrlKey),this._alt=Boolean(e.altKey)),this._isApiEvent=t}shift(){return this._shift}mod(){return this._mod}alt(){return this._alt}shiftOnly(){return this._shift&&!this._mod&&!this._alt}modOnly(){return this._mod&&!this._shift&&!this._alt}altOnly(){return this._alt&&!this._shift&&!this._mod}modShift(){return this._shift&&this._mod&&!this._alt}isApiEvent(){return this._isApiEvent}static create(e=!1,t=!1,i=!1){return new o({shiftKey:e,ctrlKey:t,metaKey:t,altKey:i})}}},716714:(e,t,i)=>{"use strict";i.d(t,{TimeFormatter:()=>u,hourMinuteFormat:()=>l,hourMinuteNonZeroSecondFormat:()=>n,hourMinuteSecondFormat:()=>r,hourMinuteSecondMillisecFormat:()=>a,twelveHourMinuteFormat:()=>h,twelveHourMinuteNonZeroSecondFormat:()=>d,twelveHourMinuteSecondFormat:()=>c});var s=i(551775),o=i(702053);const r="%h:%m:%s",n="%h:%m:%s+",a="%h:%m:%s.%ss+",l="%h:%m",c="%h:%m:%s %ampm",d="%h:%m:%s+ %ampm",h="%h:%m %ampm";class u{constructor(e){this._isTwelveHoursFormat=!1,this._valuesAndDelimeters=[];const t=e||r,i=new RegExp("%h|%m|%s\\+|%ss\\+|%ss|%ampm|%s","g");let s=i.exec(t),o=0;for(;null!==s;){const e=s[0];"%ampm"===e&&(this._isTwelveHoursFormat=!0);const r=t.substring(o,s.index);""!==r&&this._valuesAndDelimeters.push(r),this._valuesAndDelimeters.push(e),o=s.index+e.length,s=i.exec(t)}}format(e){return s.customFormatters.timeFormatter?s.customFormatters.timeFormatter.format(e):this._formatTime(e,!1)}formatLocal(e){return s.customFormatters.timeFormatter?s.customFormatters.timeFormatter.formatLocal?s.customFormatters.timeFormatter.formatLocal(e):s.customFormatters.timeFormatter.format(e):this._formatTime(e,!0)}_formatTime(e,t){let i=t?e.getHours():e.getUTCHours();const s=t?e.getMinutes():e.getUTCMinutes(),r=t?e.getSeconds():e.getUTCSeconds(),n=t?e.getMilliseconds():e.getUTCMilliseconds();let a="";this._isTwelveHoursFormat&&(a=i>=12?"PM":"AM",i%=12,i=i||12);let l="",c=!1;for(let e=this._valuesAndDelimeters.length-1;e>=0;e--){const t=this._valuesAndDelimeters[e];let d;switch(t){case"%h":d=(0,o.numberToStringWithLeadingZero)(i,2);break;case"%m":d=(0,o.numberToStringWithLeadingZero)(s,2);break;case"%s+":0!==r?d=(0,o.numberToStringWithLeadingZero)(r,2):(d="",c=!0);break;case"%s":d=(0,o.numberToStringWithLeadingZero)(r,2);break;case"%ss":d=(0,o.numberToStringWithLeadingZero)(n,3);break;case"%ss+":0!==n?d=(0,o.numberToStringWithLeadingZero)(n,3):(d="",c=!0);break;case"%ampm":d=a;break;default:if(c){c=!1;continue}d=t}l=d+l}return l}}},754480:(e,t,i)=>{"use strict";i.d(t,{TimeSpanFormatter:()=>o}) ;var s=i(444372);class o{format(e){const t=e<0;e=Math.abs(e);const o=Math.floor(e/86400);e-=86400*o;const r=Math.floor(e/3600);e-=3600*r;const n=Math.floor(e/60);e-=60*n;let a="";return o&&(a+=o+s.t(null,{context:"dates"},i(297840))+" "),r&&(a+=r+s.t(null,{context:"dates"},i(564302))+" "),n&&(a+=n+s.t(null,{context:"dates"},i(592659))+" "),e&&(a+=e+s.t(null,{context:"dates"},i(222448))+" "),t&&(a="-"+a),a.trim()}}},921692:(e,t,i)=>{"use strict";i.d(t,{FuturesContractExpiration:()=>O,isFuturesContractExpiration:()=>N});var s=i(650151),o=i(996986),r=i(888929),n=i(822914),a=i(195294),l=i(86441),c=i(444372),d=i(246733),h=i(511131),u=i(528474),_=i(458963),p=i(422333),m=i(986837),g=i(315801),S=i(787123),v=i(382778);const f=new Path2D("M.18.24a4.78 4.78 0 0 0 .9 4.36c.15.18.32.34.51.5l.52.4-.52.4a3.8 3.8 0 0 0-.52.5 4.78 4.78 0 0 0-.89 4.36c.04.14.16.24.29.24h6.06c.13 0 .25-.1.29-.24a4.78 4.78 0 0 0-.9-4.36 3.8 3.8 0 0 0-.51-.5l-.52-.4.52-.4c.19-.16.36-.32.52-.5A4.78 4.78 0 0 0 6.82.24C6.78.1 6.66 0 6.53 0H.47C.34 0 .22.1.18.24ZM3.5 4.88l1.23-.97a3 3 0 0 0 1.05-2.48H1.22a3 3 0 0 0 1.05 2.48l1.23.97Z");class b extends v.LollipopRenderer{_drawLollipop(e,t,i){const s=this._data.style;e.save(),e.translate(t.x,t.y),e.scale(i.horizontalPixelRatio,i.verticalPixelRatio),e.beginPath(),e.strokeStyle=s.outerBorderColor,e.lineWidth=1,e.arc(0,0,11,0,2*Math.PI),e.stroke(),e.fillStyle=s.backgroundColor,e.beginPath(),e.arc(0,0,10.5,0,2*Math.PI),e.fill(),e.translate(-3.5,-5.5),e.fillStyle=s.iconColor,e.fill(f,"evenodd"),e.translate(3.5,5.5),s.borderColor&&(e.strokeStyle=s.borderColor,e.lineWidth=1.5,(0,S.setLineStyle)(e,_.LINESTYLE_SOLID),e.beginPath(),e.arc(0,0,9.75,0,2*Math.PI),e.stroke()),e.restore()}}var y=i(760823);const C=c.t(null,void 0,i(401256)),w=c.t(null,void 0,i(911235)),P={dark:{background:(0,a.getHexColorByName)("color-cold-gray-900"),foreground:(0,a.getHexColorByName)("color-cold-gray-450"),foregroundExpired:(0,a.getHexColorByName)("color-ripe-red-500")},light:{background:(0,a.getHexColorByName)("color-white"),foreground:(0,a.getHexColorByName)("color-cold-gray-550"),foregroundExpired:(0,a.getHexColorByName)("color-ripe-red-500")}},T={barLine:{lineStyle:_.LINESTYLE_DASHED,lineWidth:1,strokeStyle:""},lollipop:{width:21,height:21,bottom:2,lineWidth:1.5,strokeStyle:"",backgroundColor:"",fillCircle:!0,fillStyle:"",text:{label:"",strokeStyle:"",font:(0,h.makeFont)(12,p.CHART_FONT_FAMILY,"bold")}},iconColor:"",backgroundColor:"",outerBorderColor:""};class M extends m.LollipopPaneView{constructor(){super(...arguments),this._style=(0,n.default)(T)}renderer(e){return this._invalidated&&(this._createLollipops(e),this._invalidated=!1),this._renderer}getStyle(e){const t=this._model.dark().value()?P.dark:P.light,i=e.expired?t.foregroundExpired:t.foreground,s=t.background,o=this._style;return e.active?(o.backgroundColor=i,o.iconColor=s,o.borderColor=void 0):(o.iconColor=i,o.borderColor=i,o.backgroundColor=e.hovered?(0,u.blendColors)(s,(0,d.applyAlpha)(i,.15)):s),o.outerBorderColor=s,o.barLine.strokeStyle=i,o}_createTooltipContent(e){ const t=this._model.dark().value()?P.dark:P.light,i=e.expired?t.foregroundExpired:t.foreground;return[{type:"common",title:e.expired?w:C,subTitle:e.expiration,tooltipIcon:y.replace(/currentColor/g,i),style:{color:i}}]}_createRendererForLollipop(e,t){return new b(e,new g.HitTestResult(g.HitTarget.Custom,t),this._textWidthCache)}_createLollipops(e){const t=this._source.data();if(null===t||void 0===t.index)return;const i=this._model.timeScale(),s=super._getY(),o=this._model.hoveredSource()===this._source,r=null!==this.getLastClickedLollipopId(),n={id:0,itemIndex:0,basePoint:(0,l.point)(i.indexToCoordinate(t.index),s),hovered:o,active:r,expiration:t.formattedDate,expired:t.expired,visible:!0};this._lollipops[0]=n,super._createRenderers(e)}}var x=i(988124),I=i(276871),A=i(201089),L=i(354950),k=i(65455);const E=(0,A.getLogger)("FutureContractExpiration");let D=0;let B=0;function N(e){return e instanceof O}const R={visible:!0};class O extends o.DataSource{constructor(e){super("futures_contract_expiration"),this._data=null,this._pointsetId=(D+=1,`future_expiration_${D}`),this._pointsetTurnaround=null,this._properties=new L.Property(R),this._onConnectionStateChanged=e=>{e?this._updateData():this._removePointset()},this.setOwnerSource(e.mainSeries()),this._model=e,this._paneView=new M(e,this,this._showTooltip.bind(this));const t=(0,s.ensureNotNull)(e.mainSeries().marketStatusModel().futuresContractExpirationTime());this._expirationUTCTime=t.utcTime().spawn(),this._expired=t.expired().spawn(),this._sessionSpec=t.sessionSpec().spawn(),this._formattedExpirationDate=()=>e.dateFormatter().format(t.utcDayStart()),this._expirationUTCTime.subscribe((()=>{this._removePointset(),this._updateData(),this._paneView.update(),this._model.updateSource(this)})),this._expired.subscribe((()=>{null!==this._data&&(this._data.expired=this._expired.value(),this._paneView.update(),this._model.updateSource(this))}));const i=()=>{this._removePointset(),this._createPointset()};this._destroyPropertyBinder=(0,k.bindProperties)(e.mainSeries().properties().childs().showFuturesContractExpiration,this._properties.childs().visible),e.mainSeries().onIntervalChanged().subscribe(this,i),this._sessionSpec.subscribe(i),e.chartApi().isConnected().subscribe(this._onConnectionStateChanged),this._updateData()}destroy(){this._removePointset(),this._model.mainSeries().onIntervalChanged().unsubscribeAll(this),this._model.chartApi().isConnected().unsubscribe(this._onConnectionStateChanged),this._paneView.destroy(),this._expirationUTCTime.destroy(),this._expired.destroy(),this._sessionSpec.destroy(),this._destroyPropertyBinder(),super.destroy()}lollipopsAtIndex(e){return null===this._data||this._data.index!==e?0:1}name(){return"FuturesContractExpiration"}properties(){return this._properties}state(e){return null}paneViews(e){return[this._paneView]}updateAllViews(e){this._paneView.update()}data(){return this._data}zorder(){return r.sortSourcesPreOrdered.FutureContractExpiration}onClickOutside(e,t){this._paneView.processClickOutside(e,t)}preferNoScale(){return!0} showInObjectTree(){return!1}isSavedInStudyTemplates(){return!1}isRemovedByStudyTemplates(){return!1}copiable(){return!1}hasStateForAlert(){return!1}isSavedInChart(e){return!1}isSpeciallyZOrderedSource(){return!0}isUserDeletable(){return!1}canHaveChildren(){return!1}isIncludedInAutoScale(){return!1}async _showTooltip(e,t,o){const r=this._model,n=this._model.timeScale(),a=[n.onScroll(),n.barSpacingChanged(),r.mainSeries().onSymbolIntervalChanged(),(0,s.ensureNotNull)(r.paneForSource(this)).onSizeChanged()],l=this._paneView.processClickOutside.bind(this._paneView,e),c=this._paneView.clearLastClicked.bind(this._paneView),d=o();if(null===d)return;const{showLollipopTooltip:h}=await Promise.all([i.e(5987),i.e(43387),i.e(5761),i.e(28430),i.e(70428),i.e(4908),i.e(89508),i.e(37132),i.e(14),i.e(36827),i.e(37657),i.e(16600),i.e(36701),i.e(47686),i.e(72100),i.e(48277),i.e(7879),i.e(39118),i.e(35367),i.e(45469),i.e(50442),i.e(82578),i.e(6190),i.e(97821),i.e(75703),i.e(54843),i.e(98295),i.e(90385),i.e(59255),i.e(29571),i.e(69226),i.e(89688),i.e(49039)]).then(i.bind(i,722832));h({items:d,position:t,customCloseSubscriptions:a,onClickOutside:l,onCustomClose:c,showScrollFades:!0})}_updateData(){const e=this._expirationUTCTime.value();if(null===e)return this._data=null,void this._removePointset();this._data={time:e,expired:this._expired.value(),formattedDate:this._formattedExpirationDate()},this._createPointset()}_removePointset(){if(null!==this._pointsetTurnaround){const e=this._model.chartApi();e.isConnected().value()&&e.removePointset(this._pointsetId),this._pointsetTurnaround=null}}_createPointset(){if(null!==this._pointsetTurnaround)return;const e=this._model,t=e.chartApi(),i=this._sessionSpec.value();if(null===this._data||null===i||!t.isConnected().value())return;const o=e.mainSeries();if(null===o.symbolInfo())return;const r=(0,s.ensureNotNull)(e.timezoneExceptExchange().value()),n=x.get_timezone(r);this._pointsetTurnaround=(B+=1,`t${B}`);const a=(0,s.ensureNotNull)(o.seriesSource().symbolInstanceId()),l=(0,I.getServerInterval)(o.interval());let c;const d=this._data.time;if(o.isDWM()){const e=new Date(d);i.alignToSessionStart(e),c=[[x.cal_to_utc(n,e)/1e3,0]]}else c=[[d/1e3,0]];t.createPointset(this._pointsetId,this._pointsetTurnaround,a,l,c,this._onPointsetResponse.bind(this))}_onPointsetResponse(e){if("pointset_error"===e.method){const[t,i]=e.params;return void(t===this._pointsetId&&i===this._pointsetTurnaround&&E.logError("Pointset error"))}const t=e.params;t.customId===this._pointsetId&&null!==this._data&&(this._data.index=0===t.plots.length?void 0:t.plots[0].value[0],this._paneView.update(),this._model.updateSource(this))}}},924788:(e,t,i)=>{"use strict";function s(e){return e&&e.lollipopsAtIndex}i.d(t,{isLollipopDataSource:()=>s})},913984:(e,t,i)=>{"use strict";function s(e){return Boolean(e.showInObjectTree)}i.d(t,{isDataSource:()=>s})},184586:(e,t,i)=>{"use strict";i.d(t,{LatestUpdatesSource:()=>j,isLatestUpdatesSource:()=>G}) ;var s=i(650151),o=i(201089),r=i(996986),n=i(888929),a=i(354950),l=i(65455),c=i(784547),d=i(125226),h=i(822914),u=i(195294),_=i(86441),p=i(444372),m=i(887357),g=i(207678),S=i(528474),v=i(638456),f=i(345848),b=i(396231),y=i(246733),C=i(511131),w=i(458963),P=i(422333),T=i(986837),M=i(315801),x=i(787123),I=i(382778);const A=new Path2D("m7.06 0 .87.77-3.4 4.17H9L1.94 11l-.87-.77 3.4-4.17H0L7.06 0Z");class L extends I.LollipopRenderer{_drawLollipop(e,t,i){const s=this._data.style;e.save(),e.translate(t.x,t.y),e.scale(i.horizontalPixelRatio,i.verticalPixelRatio),e.beginPath(),e.strokeStyle=s.outerBorderColor,e.lineWidth=1,e.arc(0,0,11,0,2*Math.PI),e.stroke(),e.fillStyle=s.backgroundColor,e.beginPath(),e.arc(0,0,10.5,0,2*Math.PI),e.fill(),e.translate(-4.5,-5.5),e.fillStyle=s.iconColor,e.fill(A,"evenodd"),e.translate(4.5,5.5),s.borderColor&&(e.strokeStyle=s.borderColor,e.lineWidth=1.5,(0,x.setLineStyle)(e,w.LINESTYLE_SOLID),e.beginPath(),e.arc(0,0,9.75,0,2*Math.PI),e.stroke()),s.hasUpdatesCircle&&(e.fillStyle=s.hasUpdatesCircle.color,e.strokeStyle=s.hasUpdatesCircle.borderColor,e.lineWidth=2,e.beginPath(),e.arc(9.75*Math.cos(Math.PI/4),9.75*-Math.sin(Math.PI/4),3.5,0,2*Math.PI),e.closePath(),e.fill(),e.stroke()),e.restore()}}var k=i(244230);const E=(0,o.getLogger)("LatestUpdatesProvider"),D={dark:{background:(0,u.getHexColorByName)("color-cold-gray-900"),foreground:(0,u.getHexColorByName)("color-grapes-purple-400"),hasUpdatesCircle:(0,u.getHexColorByName)("color-ripe-red-500")},light:{background:(0,u.getHexColorByName)("color-white"),foreground:(0,u.getHexColorByName)("color-grapes-purple-500"),hasUpdatesCircle:(0,u.getHexColorByName)("color-ripe-red-500")}},B={barLine:{lineStyle:w.LINESTYLE_DASHED,lineWidth:1,strokeStyle:""},lollipop:{width:21,height:21,bottom:2,lineWidth:1.5,strokeStyle:"",backgroundColor:"",fillCircle:!0,fillStyle:"",text:{label:"",strokeStyle:"",font:(0,C.makeFont)(12,P.CHART_FONT_FAMILY,"bold")}},iconColor:"",backgroundColor:"",outerBorderColor:""};async function N(e,t,s){const{openMindsPage:o}=await i.e(20603).then(i.bind(i,337860));o(e,t,s)}const R=p.t(null,void 0,i(857154)),O=p.t(null,void 0,i(923278)),V=p.t(null,void 0,i(998431)),W=p.t(null,void 0,i(413070)),F=p.t(null,void 0,i(620107));class H extends T.LollipopPaneView{constructor(){super(...arguments),this._style=(0,h.default)(B)}renderer(e){return this._source.hideLollipop()?null:(this._invalidated&&(this._createLollipops(e),this._invalidated=!1),this._renderer)}getStyle(e){const t=this._model.dark().value()?D.dark:D.light,i=t.foreground,s=t.background,o=this._style;return e.active?(o.backgroundColor=i,o.iconColor=s,o.borderColor=void 0):(o.iconColor=i,o.borderColor=i,o.backgroundColor=e.hovered?(0,S.blendColors)(s,(0,y.applyAlpha)(i,.15)):s),o.outerBorderColor=s,o.barLine.strokeStyle=i,o.lollipop.incHeight=void 0===e.stack?void 0:25*e.stack,o.hasUpdatesCircle=e.data.hasNewItems?{color:t.hasUpdatesCircle,borderColor:s}:void 0,o}_createTooltipContent(e){var t,s,o,r,n ;const a=this._model.mainSeries().symbol(),l=(this._model.dark().value()?D.dark:D.light).foreground,c=e.data.newsData,d=e.data.mindsData,h=c&&c.items.length>0,u=d&&d.items.length>0;if(!h&&!u)return null;const _=null!==(t=a.split(":")[1])&&void 0!==t?t:a,S={title:h&&u?R:h&&p.t(null,{replace:{symbol:_}},i(588103))||u&&p.t(null,{replace:{symbol:_}},i(883274))||"",tabs:[],tooltipIcon:k.replace(/currentColor/g,l),style:{color:l}};return h&&S.tabs.push({id:"news",name:O,content:{type:"news",items:c.items,clickHandler:(e,t)=>{v.CheckMobile.any()&&this._source.hideTooltip(),async function(e,t,s){e.isExternal||s.preventDefault();try{const o={...e,analyticsData:t.analyticsData},[{TradingViewNewsProviderFetcher:r},{onNewsCardAction:n}]=await Promise.all([Promise.all([i.e(5761),i.e(4343),i.e(36827),i.e(69267),i.e(7818),i.e(90365),i.e(45469),i.e(50442),i.e(74978),i.e(64071),i.e(63841),i.e(11085),i.e(56370)]).then(i.bind(i,619008)),Promise.all([i.e(5761),i.e(4343),i.e(36827),i.e(69267),i.e(7818),i.e(90365),i.e(45469),i.e(50442),i.e(74978),i.e(64071),i.e(63841),i.e(11085),i.e(56370)]).then(i.bind(i,458468))]);n({newsItem:o,newsItems:(await r.instance().fetch({...t.requestProps,client:"web"},3e5)).items,placement:m.NewsWidgetPlacement.Chart})(s)}catch(s){E.logWarn(`An error ocurred while loading news: ${s}`)}}(e,c,t)}},anchor:(null===(o=null===(s=window.widgetbar)||void 0===s?void 0:s.layout)||void 0===o?void 0:o.canOpen())?{text:W,onClick:()=>{var e;this._source.hideTooltip(),null===(e=window.widgetbar)||void 0===e||e.setPage("base"),(0,b.showSymbolNews)(a)},hideInMobileMode:!0}:void 0}),u&&S.tabs.push({id:"minds",name:V,content:{type:"minds",symbol:a,items:d.items,clickHandler:(e,t,i)=>{this._source.hideTooltip(),function(e,t,i,s){var o;window.innerWidth{this._source.hideTooltip(),function(e){var t;window.innerWidtha&&e.isVisible()&&(l+=e.lollipopsAtIndex(t.index));const c={id:0,itemIndex:0, basePoint:(0,_.point)(s.indexToCoordinate(t.index),o),hovered:r,active:n,visible:!0,stack:l,data:t};this._lollipops[0]=c,super._createRenderers(e)}}const z=(0,o.getLogger)("Chart.LatestUpdate"),U={visible:!0};function G(e){return e instanceof j}function q(e){return!e.isSeconds()&&!e.isTicks()}class j extends r.DataSource{constructor(e,t){super("latestUpdates"),this._properties=new a.Property(U),this._items={},this._hasNewItems=!1,this._newsThread=null,this._mindsThread=null,this._hideLollipopTooltipFn=null,this._onMindsHistoryReady=this._onMindsItems.bind(this,void 0),this._onNewsHistoryReady=this._onNewsItems.bind(this,void 0),this.setOwnerSource(e.mainSeries()),this._latestUpdatesDataEnabled=t,this._model=e,this._series=e.mainSeries(),this._paneView=new H(e,this,this._showTooltip.bind(this)),this._series.symbolResolved().subscribe(this,this._onSymbolResolved);const i=this._series.intervalObj();this._isAvailableOnCurrentInterval=q(i),this._series.onIntervalChanged().subscribe(this,this._recalculateAvailabilityOnCurrentInterval),this._destroyPropertyBinder=(0,l.bindProperties)(e.mainSeries().properties().childs().showLastNews,this._properties.childs().visible),this._initializeNewsAndMindsThreads(),this._hideLollipop=(0,c.createWVFromGetterAndSubscriptions)((()=>this._model.isInReplay().value()||!q(this._series.intervalObj())),[this._model.onInReplayStateChanged(),this._series.onIntervalChanged()]),this._hideLollipop.subscribe((()=>this._model.updateSource(this)))}destroy(){this._destroyNewsThread(),this._destroyMindsThread(),this._paneView.destroy(),this._series.symbolResolved().unsubscribeAll(this),this._series.onIntervalChanged().unsubscribeAll(this),this._destroyPropertyBinder(),this._hideLollipop.destroy(),super.destroy()}hideLollipop(){return this._hideLollipop.value()}lollipopsAtIndex(e){var t;return Object.keys(this._items).length>0&&e===(null===(t=this._series.data().last())||void 0===t?void 0:t.index)?1:0}name(){return"LatestUpdatesSource"}data(){const e=this._series.data().last();if(null===e||void 0===Object.keys(this._items).length)return null;const t={index:e.index,hasNewItems:this._hasNewItems};return this._items[0]&&void 0!==this._requestNewsProps&&void 0!==this._newsAnalyticsData&&(t.newsData={items:this._items[0],requestProps:this._requestNewsProps,analyticsData:this._newsAnalyticsData}),this._items[1]&&(t.mindsData={items:this._items[1]}),t}properties(){return this._properties}state(e){return null}paneViews(e){return[this._paneView]}updateAllViews(e){this._paneView.update()}zorder(){return n.sortSourcesPreOrdered.LatestUpdates}onClickOutside(e,t){this._paneView.processClickOutside(e,t)}preferNoScale(){return!0}showInObjectTree(){return!1}isSavedInStudyTemplates(){return!1}isRemovedByStudyTemplates(){return!1}copiable(){return!1}hasStateForAlert(){return!1}isSavedInChart(e){return!1}isSpeciallyZOrderedSource(){return!0}isUserDeletable(){return!1}canHaveChildren(){return!1}isIncludedInAutoScale(){return!1}hideTooltip(){var e;null===(e=this._hideLollipopTooltipFn)||void 0===e||e.call(this), this._hideLollipopTooltipFn=null}async _showTooltip(e,t,o){const r=this._model.timeScale(),n=[r.onScroll(),r.barSpacingChanged(),this._series.onSymbolIntervalChanged(),(0,s.ensureNotNull)(this._model.paneForSource(this)).onSizeChanged()],a=this._paneView.processClickOutside.bind(this._paneView,e),l=this._paneView.clearLastClicked.bind(this._paneView),c=o();if(null===c)return;this._hasNewItems=!1;const{showLollipopTooltipWithTabs:d}=await Promise.all([i.e(5987),i.e(43387),i.e(5761),i.e(28430),i.e(70428),i.e(4908),i.e(89508),i.e(37132),i.e(14),i.e(36827),i.e(37657),i.e(16600),i.e(36701),i.e(47686),i.e(72100),i.e(48277),i.e(7879),i.e(39118),i.e(35367),i.e(45469),i.e(50442),i.e(82578),i.e(6190),i.e(97821),i.e(75703),i.e(54843),i.e(98295),i.e(90385),i.e(59255),i.e(29571),i.e(69226),i.e(89688),i.e(49039)]).then(i.bind(i,480079));this._hideLollipopTooltipFn=d({content:c,position:t,customCloseSubscriptions:n,onClickOutside:a,doNotCloseOn:()=>[document.querySelector('[data-name="news-dialog"]'),document.querySelector('[data-dialog-name="image-dialog"]')].filter((e=>null!==e)),onCustomClose:l,showScrollFades:!0})}async _initializeNewsAndMindsThreads(){if(!this._isAvailableOnCurrentInterval)return void(this._items={});null!==this._series.symbolInfo()&&(this._initializeNewsThread(),this._initializeMindsThread())}async _initializeMindsThread(){if(!this._latestUpdatesDataEnabled.minds)return;const e=(0,s.ensureNotNull)(this._series.symbolInfo());try{const{popularMindsThread:t}=await i.e(12127).then(i.bind(i,121362));this._mindsThread=t({symbol:e.pro_name,limit:3},3e5,3e5),this._mindsThread.newItems().subscribe(this,this._onMindsItems.bind(this,!0)),this._mindsThread.historyReady().value()?this._onMindsItems():this._mindsThread.historyReady().subscribe(this._onMindsHistoryReady,{once:!0})}catch(e){z.logWarn(`An error ocurred while loading minds: ${e}`)}}async _initializeNewsThread(){if(!this._latestUpdatesDataEnabled.news)return;const e=(0,s.ensureNotNull)(this._series.symbolInfo());try{const[{getIsoLanguageCodeFromLanguage:t},{getCardsAnalyticsData:s},{handleNewsProName:o},{newsThread:r}]=await Promise.all([Promise.all([i.e(5761),i.e(4343),i.e(36827),i.e(69267),i.e(7818),i.e(90365),i.e(45469),i.e(50442),i.e(74978),i.e(64071),i.e(63841),i.e(11085),i.e(56370)]).then(i.bind(i,39654)),Promise.all([i.e(5761),i.e(4343),i.e(36827),i.e(69267),i.e(7818),i.e(90365),i.e(45469),i.e(50442),i.e(74978),i.e(64071),i.e(63841),i.e(11085),i.e(56370)]).then(i.bind(i,859409)),Promise.all([i.e(5761),i.e(4343),i.e(36827),i.e(69267),i.e(7818),i.e(90365),i.e(45469),i.e(50442),i.e(74978),i.e(64071),i.e(63841),i.e(11085),i.e(56370)]).then(i.bind(i,470598)),Promise.all([i.e(5761),i.e(4343),i.e(36827),i.e(69267),i.e(7818),i.e(90365),i.e(45469),i.e(50442),i.e(74978),i.e(64071),i.e(63841),i.e(11085),i.e(56370)]).then(i.bind(i,603326))]),n=!!(window.is_authenticated&&(0,d.isFeatureEnabled)("move_chart_news_to_streaming")&&(0,d.isFeatureEnabled)("news_enable_streaming"))||void 0;this._requestNewsProps={lang:t(window.language),symbol:o(e.pro_name,e.type), client:"chart",streaming:n},this._newsAnalyticsData=s(this._requestNewsProps),this._newsThread=r(this._requestNewsProps,3e5,3e5),this._newsThread.newItems().subscribe(this,this._onNewsItems.bind(this,!0)),this._newsThread.historyReady().value()?this._onNewsItems():this._newsThread.historyReady().subscribe(this._onNewsHistoryReady,{once:!0})}catch(e){z.logWarn(`An error ocurred while loading news: ${e}`)}}_onNewsItems(e){const t=this._series.symbolInfo();if(this._isDestroyed||null===t)return;let i=(0,s.ensureNotNull)(this._newsThread).history().slice();i.length>0&&Date.now()-i[0].published>=26784e5&&(i=[]),this._items[0]=i,e&&(this._hasNewItems=!0),Object.keys(this._items).length&&(this._paneView.update(),this._model.updateSource(this))}_onMindsItems(e){const t=this._series.symbolInfo();if(this._isDestroyed||null===t)return;const i=(0,s.ensureNotNull)(this._mindsThread).history().slice();this._items[1]=i,e&&(this._hasNewItems=!0),Object.keys(this._items).length&&(this._paneView.update(),this._model.updateSource(this))}_destroyNewsThread(){this._newsThread&&(this._newsThread.historyReady().unsubscribe(this._onNewsHistoryReady),this._newsThread.newItems().unsubscribeAll(this),this._newsThread.destroy(),this._newsThread=null)}_destroyMindsThread(){this._mindsThread&&(this._mindsThread.historyReady().unsubscribe(this._onMindsHistoryReady),this._mindsThread.newItems().unsubscribeAll(this),this._mindsThread.destroy(),this._mindsThread=null)}_onSymbolResolved(){this._items={},this._destroyNewsThread(),this._destroyMindsThread(),this._initializeNewsAndMindsThreads()}_recalculateAvailabilityOnCurrentInterval(){const e=q(this._series.intervalObj());e!==this._isAvailableOnCurrentInterval&&(this._isAvailableOnCurrentInterval=e,e?this._initializeNewsAndMindsThreads():(this._destroyNewsThread(),this._destroyMindsThread(),this._paneView.update(),this._model.updateSource(this)))}}},391534:(e,t,i)=>{"use strict";i.d(t,{LineToolsGroup:()=>l});var s=i(707957),o=i(401580),r=i(541558);function n(e){return e.properties().visible.value()}function a(e){return!n(e)}class l{constructor(e,t,i){this._instanceId=(0,r.randomHashN)(6),this._onChanged=new s.Delegate,this._lineToolsSet=new Set,this._lineTools=[...e],this._lineToolsSet=new Set(this._lineTools),this._name=new o.WatchedValue(t),this.id=i||(0,r.randomHashN)(6)}instanceId(){return this._instanceId}lineTools(){return this._lineTools}name(){return this._name}setName(e){this._doAndFireOnChange((()=>{this._name.setValue(e)}))}isActualSymbol(){return this._lineTools.length>0&&this._lineTools[0].isActualSymbol()&&this._lineTools[0].isActualCurrency()&&this._lineTools[0].isActualUnit()}symbol(){return this._lineTools[0].symbol()}currencyId(){var e;return null!==(e=this._lineTools[0].properties().childs().currencyId.value())&&void 0!==e?e:null}unitId(){var e;return null!==(e=this._lineTools[0].properties().childs().unitId.value())&&void 0!==e?e:null}sharingMode(){return this._lineTools[0].sharingMode()}share(e){this._lineTools.forEach((t=>t.share(e)))}containsLineTool(e){ return this._lineToolsSet.has(e)}addLineTools(e){this._doAndFireOnChange((t=>{e.forEach((e=>this._lineToolsSet.add(e))),this._lineTools.push(...e),t.push(...e.map((e=>e.id())))}))}excludeLineTool(e){this._doAndFireOnChange((t=>{this._lineToolsSet.delete(e);const i=this._lineTools.indexOf(e);this._lineTools.splice(i,1),t.push(e.id())}))}excludeLineTools(e){this._doAndFireOnChange((t=>{const i=new Set(e);e.forEach((e=>this._lineToolsSet.delete(e))),this._lineTools=this._lineTools.filter((e=>!i.has(e))),t.push(...e.map((e=>e.id())))}))}state(){return{id:this.id,name:this._name.value(),tools:this._lineTools.map((e=>e.id()))}}visibility(){const e=this._lineTools.some(n),t=this._lineTools.some(a);return e&&!t?"Visible":t&&!e?"Invisible":"Partial"}locked(){const e=this._lineTools.some((e=>e.properties().frozen.value())),t=this._lineTools.some((e=>!e.properties().frozen.value()));return e&&!t?"Locked":t&&!e?"Unlocked":"Partial"}isActualInterval(){const e=this._lineTools.some((e=>e.isActualInterval())),t=this._lineTools.some((e=>!e.isActualInterval()));return e&&!t?"IsActualInterval":t&&!e?"IsNotActualInterval":"Partial"}onChanged(){return this._onChanged}static fromState(e,t){const i=[];for(const s of t.tools){const t=e.dataSourceForId(s);null!==t&&i.push(t)}return i.length>0?new l(i,t.name,t.id):null}_doAndFireOnChange(e){const t=[],i=this.visibility(),s=this.locked(),o=this.isActualInterval();e(t),this._onChanged.fire({affectedLineTools:t,visibilityChanged:i!==this.visibility(),lockedChanged:s!==this.locked(),isActualIntervalChanged:o!==this.isActualInterval()})}}},606097:(e,t,i)=>{"use strict";i.d(t,{blobImageFilter:()=>a,checkImageSize:()=>u,generateLink:()=>h,imageIsOversized:()=>c,uploadImage:()=>_});var s=i(743068),o=i(120780),r=i(444372),n=i(201089);function a(e){return"image/png"===e.type||"image/jpeg"===e.type}const l=(0,s.size)({width:2e3,height:2e3});function c(e){return e.width>l.width||e.height>l.height}const d=(0,n.getLogger)("Chart.Uploader");async function h(e){const t=new FormData,i="name"in e?e.name:"image.png";t.append("content_type",e.type),t.append("filename",i),t.append("size",""+e.size);try{const e=await(0,o.fetch)("/charts/uploads/generate-link/",{method:"POST",body:t});if(!e.ok)throw new Error(`Error generating upload link: ${e.status}`);return e.json()}catch(t){throw d.logError(`Error generating upload link: ${t}. blob.type: ${e.type} blob.size: ${e.size} filename: ${i}`),t}}async function u(e){return new Promise(((t,i)=>{const s=new FileReader;s.onload=e=>{var s;const o=new Image;o.src=null===(s=e.target)||void 0===s?void 0:s.result,o.onload=()=>{t(!c(o))},o.onerror=i},s.onerror=i,s.readAsDataURL(e)}))}async function _(e){if(!await u(e))throw new Error(r.t(null,void 0,i(753716)));try{const t=await h(e),i=t.data.fields,s=new FormData;for(const e of Object.keys(i))s.append(e,i[e]);s.append("file",e);const r=await(0,o.fetch)(t.data.url,{method:"POST",body:s});if(r.ok)return t.data.url+t.filepath;throw new Error(`Upload response is not ok: ${r.status}`)}catch(e){ throw new Error(`Error uploading image: ${e.message}`)}}},549621:(e,t,i)=>{"use strict";i.d(t,{LogicalRange:()=>o});var s=i(650151);class o{constructor(e,t){(0,s.assert)(e<=t,"The left value should be greater than or equal to the right value"),this._left=e,this._right=t}left(){return this._left}right(){return this._right}length(){return this._right-this._left+1}contains(e,t){return ethis._right+.5?!0===t&&2:!0!==t||0}before(e){return ethis._right+.5}intersects(e){return!(this.after(e.left())||this.before(e.right()))}equals(e){return this._left===e.left()&&this._right===e.right()}static compare(e,t){return null===e||null===t?e===t:e.equals(t)}}},220843:(e,t,i)=>{"use strict";i.d(t,{MainSeriesScaleRatioProperty:()=>r});var s=i(707957),o=i(428123);class r{constructor(e){this._changed=new s.Delegate,this._model=e}destroy(){this._changed.destroy()}getStepChangeValue(){return.1}getMinValue(){return 1e-7}getMaxValue(){return 99999999}value(){return this._model.mainSeriesScaleRatio()}setValue(e,t){(e!==this.value()||t)&&(this._model.setMainSeriesScaleRatio(e),this._onChanged())}state(){return null}clone(){return new r(this._model)}listeners(){return this._changed}subscribe(e,t){this._changed.subscribe(e,t)}unsubscribe(e,t){this._changed.unsubscribe(e,t)}unsubscribeAll(e){this._changed.unsubscribeAll(e)}storeStateIfUndefined(){return!0}weakReference(){return(0,o.weakReference)(this)}ownership(){return(0,o.ownership)(this)}_onChanged(){this._changed.fire(this,"")}}},189767:(e,t,i)=>{"use strict";i.d(t,{RectangleRenderer:()=>u});var s=i(650151),o=i(86441),r=i(934026),n=i(204652),a=i(246733),l=i(458963),c=i(315801),d=i(787123),h=i(43192);class u extends h.BitmapCoordinatesPaneRenderer{constructor(e,t,i){super(),this._data=null,this._hitTestResult=e||new c.HitTestResult(c.HitTarget.MovePoint),this._backHitTestResult=t||new c.HitTestResult(c.HitTarget.MovePointBackground),this._forceOverrideTransparency=Boolean(i)}setData(e){this._data=e}hitTest(e,t){if(null===this._data||this._data.points.length<2||this._data.nohittest)return null;const i=t.mediaSize.width,s=(0,o.box)(...this._data.points),r=s.min,a=s.max,l=new o.Point(a.x,r.y),c=new o.Point(r.x,a.y),d=this._extendAndHitTestLineSegment(e,r,l,i);if(null!==d)return d;const h=this._extendAndHitTestLineSegment(e,c,a,i);if(null!==h)return h;let u=(0,n.distanceToSegment)(l,a,e);if(u.distance<=3)return this._hitTestResult;if(u=(0,n.distanceToSegment)(r,c,e),u.distance<=3)return this._hitTestResult;if(this._data.middleLine){const t=s.min.add(s.max).scaled(.5),r=this._extendAndHitTestLineSegment(e,new o.Point(s.min.x,t.y),new o.Point(s.max.x,t.y),i);if(null!==r)return r}return this._data.fillBackground?this._hitTestBackground(e,r,a,i):null}getColor(){const e=(0,s.ensure)(this._data);return void 0===e.transparency?e.backcolor:(0,a.generateColor)(e.backcolor,e.transparency,this._forceOverrideTransparency)}_drawImpl(e){if(null===this._data||this._data.points.length<2||this._data.linewidth<=0&&!this._data.fillBackground)return ;const{horizontalPixelRatio:t,verticalPixelRatio:i,bitmapSize:s}=e,{extendLeft:r,extendRight:n,linewidth:a,middleLine:c}=this._data,h=(0,o.box)(...this._data.points),u=this._data.linewidth?Math.max(1,Math.floor(this._data.linewidth*t)):0,_=this._data.fillBackground?this.getColor():void 0,p=Math.max(1,Math.floor(t)),m=r?-a:Math.round(h.min.x*t),g=n?s.width+a:Math.round(h.max.x*t),S=Math.round(h.min.y*i),v=Math.round(h.max.y*i);(0,d.fillRectWithBorder)(e,m,S,g,v,p,void 0===_?void 0:{color:_},0===u?void 0:{color:this._data.color,lineStyle:l.LINESTYLE_SOLID,borderWidth:u,borderMode:"center"},c?{...c,lineWidth:Math.max(1,Math.floor(c.lineWidth*i))}:void 0)}_extendAndHitTestLineSegment(e,t,i,s){const o=this._extendAndClipLineSegment(t,i,s);if(null!==o){if((0,n.distanceToSegment)(o[0],o[1],e).distance<=3)return this._hitTestResult}return null}_extendAndClipLineSegment(e,t,i){const r=(0,s.ensureNotNull)(this._data);if((0,o.equalPoints)(e,t)&&!r.extendLeft&&!r.extendRight)return null;const n=Math.min(e.x,t.x),a=Math.max(e.x,t.x),l=r.extendLeft?0:Math.max(n,0),c=r.extendRight?i:Math.min(a,i);return l>c||c<=0||l>=i?null:[new o.Point(l,e.y),new o.Point(c,t.y)]}_hitTestBackground(e,t,i,s){const n=this._extendAndClipLineSegment(t,i,s);return null!==n&&(0,r.pointInBox)(e,(0,o.box)(n[0],n[1]))?this._backHitTestResult:null}}},993171:(e,t,i)=>{"use strict";i.d(t,{PrePostMarket:()=>v,defaultPrePostMarketPreferences:()=>S});var s=i(195294),o=i(458963),r=i(742391),n=i(949529),a=i(506387);class l extends a.PriceLineAxisView{constructor(e,t){super(),this._model=e,this._source=t}_value(){const e=this._model.mainSeries(),t=e.priceScale(),i=e.firstValue();if(null===i)return{noData:!0};const s=this._source.price(),o=this._source.currentSession();if(null===s||"pre_market"!==o&&"post_market"!==o)return{noData:!0};const r=t.priceToCoordinate(s,i);return{noData:!1,floatCoordinate:r,coordinate:r,color:"",formattedPricePercentage:"",formattedPriceAbsolute:"",formattedPriceIndexedTo100:"",text:"",index:0}}_priceLineColor(e){const t=this._source.properties().childs();return"pre_market"===this._source.currentSession()?t.preMarketColor.value():t.postMarketColor.value()}_lineWidth(){return this._source.properties().childs().lineWidth.value()}_lineStyle(){return this._source.properties().childs().lineStyle.value()}_isVisible(){if(!this._source.canBeVisibleOnSymbolAndInterval()||!this._model.properties().childs().scalesProperties.childs().showPrePostMarketPriceLabel.value())return!1;const e=this._source.price(),t=this._source.currentSession();return null!==e&&("pre_market"===t||"post_market"===t)}}var c=i(444372),d=i(229765),h=i(246733);class u extends d.PriceAxisView{constructor(e,t){super(),this._model=e,this._source=t}_updateRendererData(e,t,s){if(e.visible=!1,t.visible=!1,!this._model.properties().childs().scalesProperties.childs().showPrePostMarketPriceLabel.value())return;const o=this._model.mainSeries(),r=o.priceScale(),n=o.firstValue();if(null===n)return;if(!this._source.canBeVisibleOnSymbolAndInterval())return ;const a=this._source.price(),l=this._source.currentSession();if(null==a||"pre_market"!==l&&"post_market"!==l)return;const d=this._source.properties().childs(),u="pre_market"===l?(0,h.resetTransparency)(d.preMarketColor.value()):(0,h.resetTransparency)(d.postMarketColor.value());e.visible=!0,t.visible=!0,e.text=r.formatPriceAbsolute(a),t.text="pre_market"===l?c.t(null,{context:"market_status"},i(368319)):c.t(null,{context:"market_status"},i(124162)),s.coordinate=r.priceToCoordinate(a,n),s.background=u,s.textColor=this.generateTextColor(u)}}var _=i(955831),p=i(315801);class m extends _.HorizontalLinePaneView{constructor(e,t,i){super(),this._model=e,this._source=t;const s={doubleClickHandler:i,doubleTapHandler:i};this._lineRenderer.setHitTest(new p.HitTestResult(p.HitTarget.Regular,s))}_updateImpl(){const e=this._lineRendererData;e.visible=!1;const t=this._model.mainSeries(),i=this._source.properties().childs();if(!i.visible.value()||!t.isVisible())return;const s=t.priceScale(),o=t.firstValue();if(null===o)return;if(!this._source.canBeVisibleOnSymbolAndInterval())return;const r=this._source.price(),n=this._source.currentSession();null===r||"pre_market"!==n&&"post_market"!==n||(e.visible=!0,e.y=s.priceToCoordinate(r,o),e.linestyle=i.lineStyle.value(),e.linewidth=i.lineWidth.value(),e.color="pre_market"===n?i.preMarketColor.value():i.postMarketColor.value())}}var g=i(964824);const S={visible:!0,lineStyle:o.LINESTYLE_DOTTED,lineWidth:1,preMarketColor:"#fb8c00",postMarketColor:s.colorsPalette["color-tv-blue-500"]};class v extends n.CustomSourceBase{constructor(e,t,i){super(e,t),this._extraHoursPrice=null,this._currentSession="holiday",this._quotesProvider=t.mainSeries().quotesProvider(),this._prePostMarketLinePaneView=new m(t,this,i),this._prePostPriceAxisView=new u(t,this),this._prePostLabelPaneView=new r.PanePriceAxisView(this._prePostPriceAxisView,t.mainSeries(),t),this._prePostPriceLineAxisView=new l(t,this),this._quotesProvider.quotesUpdate().subscribe(this,this._updateQuotes),this._updateQuotes()}destroy(){this._quotesProvider.quotesUpdate().unsubscribeAll(this)}paneViews(e){return this._areViewsAvailableForPane(e)?[this._prePostMarketLinePaneView]:[]}labelPaneViews(e){return this._areViewsAvailableForPane(e)?[this._prePostLabelPaneView]:[]}priceAxisViews(e,t){return this._areViewsAvailableForPane(e)?e.findTargetPriceAxisViews(this,t,[this._prePostPriceAxisView],[this._prePostPriceLineAxisView]):[]}priceScale(){return this._model.mainSeries().priceScale()}updateAllViews(e){this._prePostMarketLinePaneView.update(e),this._prePostPriceAxisView.update(e),this._prePostPriceLineAxisView.update(e),this._prePostLabelPaneView.update(e)}price(){return this._extraHoursPrice}currentSession(){return this._currentSession}canBeVisibleOnSymbolAndInterval(){return this._model.mainSeries().isPrePostMarketPricesAvailableProperty().value()}properties(){return this._model.mainSeries().properties().childs().prePostMarket}_updateQuotes(){const e=this._quotesProvider.quotes();null===e?this._extraHoursPrice=null:(this._extraHoursPrice=e.rtc, void 0!==e.current_session&&(this._currentSession=e.current_session));const t=this._model.mainSeries().properties().childs().prePostMarket.childs().visible.value(),i=this._model.properties().childs().scalesProperties.childs().showPrePostMarketPriceLabel.value();this.canBeVisibleOnSymbolAndInterval()&&(t||i)&&(this.updateAllViews((0,g.sourceChangeEvent)(this.id())),this._model.updateSource(this))}_areViewsAvailableForPane(e){return!this._model.isSnapshot()&&this._model.paneForSource(this._model.mainSeries())===e}}},985139:(e,t,i)=>{"use strict";var s;i.d(t,{PublishedChartsFilter:()=>s}),function(e){e.None="all",e.Following="following",e.Private="private"}(s||(s={}))},922850:(e,t,i)=>{"use strict";i.d(t,{PublishedChartsTimeline:()=>R});var s=i(444372),o=i(62802),r=i.n(o),n=i(838042),a=i(405069),l=i(985139),c=i(201089),d=i(345848),h=i(638456),u=i(337779),_=i(120780),p=i(223124),m=i(853965),g=i(650151),S=i(195294),v=i(542682),f=i(934026),b=i(86441),y=i(315801),C=i(199471);function w(e,t){const{horizontalPixelRatio:i,verticalPixelRatio:s}=t,o=Math.max(1,Math.floor(i)),r=Math.round(e.x*i)+o%2/2;let n=Math.round(e.size*i);(r+n/2)%1!=0&&(n+=1);const a=Math.min(Math.max(1,Math.round(i*e.borderWidth)),n/2);let l;const c=("up"===e.direction?-1:1)*(e.yInverted?-1:1),d=c*(Math.round(e.size*s/2)+o%2);if(void 0!==e.fixedSpaceYPosition){const t=Math.round(e.fixedSpaceYPosition.itemSpacing*s),i=e.fixedSpaceYPosition.order,o=c*(n*i+t*(i+1));l=Math.round(e.fixedSpaceYPosition.basePosition*s)+o+d}else l=Math.round(e.y*s)+d;return{x:r,y:l,size:n,borderWidth:a,tickSize:o}}function P(e,t,i,s){var o;if(e.save(),i&&!s.highlightByAuthor&&(e.globalAlpha=.4),s.mine)!function(e,t,i){const{borderColor:s,backgroundColor:o,doNotFill:r,direction:n,yInverted:a}=i,{x:l,y:c,borderWidth:d,size:h,tickSize:u}=w(i,t);e.strokeStyle=s,e.fillStyle=o,e.lineWidth=d;const _="up"===n!==a?-1:1;let p=Math.round(h/2/Math.tan(Math.PI/6))+u%2/2;(l+p/2)%1!=0&&(p-=1);e.translate(l,c+p/2*_),e.beginPath();const m=d/2;e.moveTo(0,-_*(p-m)),e.lineTo(h/2-m,d/2),e.lineTo(-h/2+m,d/2),e.lineTo(0,-_*(p-d/2)),e.closePath(),r||e.fill();e.stroke()}(e,t,s);else{0,function(e,t,i,s,o){const{borderColor:r,backgroundColor:n,label:a}=i,{x:l,y:c,borderWidth:d,size:h}=w(i,t);e.strokeStyle=r,e.fillStyle=n,e.lineWidth=d,e.beginPath();const u=h/2-d/2;e.arc(l,c,u,0,2*Math.PI,!0),e.closePath(),e.fill(),!1;e.stroke(),!s&&a&&h/2>=7&&(e.textAlign="center",e.textBaseline="middle",e.font=a.font,e.fillStyle=a.fontColor,(0,C.drawScaled)(e,t.horizontalPixelRatio,t.verticalPixelRatio,(()=>{e.fillText(a.text,l/t.horizontalPixelRatio,c/t.verticalPixelRatio)})))}(e,t,s,!1,null===(o=s.image)||void 0===o?void 0:o.imageElement)}e.restore()}class T{constructor(e,t,i,s){this._canvas=null,this._clickHandler=e,this._enterHandler=t,this._leaveHandler=i,this._data=null!=s?s:null}setData(e){this._data=e}hitTest(e,t){if(null===this._data)return null;for(let i=this._data.items.length-1;i>=0;--i){const s=this._hitTestDot(this._data.items[i],e,t);if(s)return s}return null}draw(e,t){this._canvas=e.canvas, null!==this._data&&this._data.items.forEach(P.bind(null,e,t,this._data.highlightByAuthor))}_hitTestDot(e,t,i){const s=new b.Point(e.x,w(e,i).y/i.verticalPixelRatio);if((0,f.pointInCircle)(t,s,Math.max(e.size/2,8))){const t=this._canvas,i=null===t?void 0:{mouseEnterHandler:()=>this._enterHandler(e,s.y,t),mouseLeaveHandler:()=>this._leaveHandler(),clickHandler:i=>this._clickHandler(e,s.y,t,i),tapHandler:i=>this._clickHandler(e,s.y,t,i)};return new y.HitTestResult(y.HitTarget.Regular,{activeItem:e.originalItem.id,...i})}return null}}var M=i(511131),x=i(422333),I=i(431912);const A={green:{border:(0,S.getHexColorByName)("color-minty-green-700"),background:(0,S.getHexColorByName)("color-minty-green-a600")},red:{border:(0,S.getHexColorByName)("color-ripe-red-700"),background:(0,S.getHexColorByName)("color-ripe-red-500")},neutral:{border:(0,S.getHexColorByName)("color-tan-orange-700"),background:(0,S.getHexColorByName)("color-tan-orange-500")},yellow:{border:"#EAC300",background:"#FFD400"},blue:{border:"#047ACE",background:"#0496FF"}};function L(e){var t,i,s,o;return e.hovered||e.highlightByAuthor?null!==(i=null===(t=e.overrideBorderWidth)||void 0===t?void 0:t.hoveredWidth)&&void 0!==i?i:4:null!==(o=null===(s=e.overrideBorderWidth)||void 0===s?void 0:s.width)&&void 0!==o?o:2}const k=(0,c.getLogger)("Chart.PublishedChartsTimeline");class E extends class{constructor(e,t){this._tooltip=null,this._hoveredBarsMarkData=null,this._destroyed=!1,this._invalidated=!0,this._originalData=[],this._source=e,this._model=t,this._renderer=new T(this._onItemClicked.bind(this),this._showItem.bind(this),this._hideItem.bind(this)),this._createTooltipRenderer().then((e=>{this._destroyed?null==e||e.destroy():this._tooltip=e})),e.properties().childs().visible.subscribe(null,(()=>{var e;null===(e=this._tooltip)||void 0===e||e.hide(!0)}))}destroy(){var e;this._destroyed=!0,null===(e=this._tooltip)||void 0===e||e.destroy()}source(){return this._source}update(){this._invalidated=!0}renderer(){return this._invalidated&&(this._updateImpl(),this._invalidated=!1),this._renderer}onClickOutside(e,t){t&&((0,I.isTouchMouseEvent)(t)?t.isTouch:(0,v.isTouchEvent)(t))&&null!==this._tooltip&&!this._tooltip.contains(t.target)&&this._tooltip.hide(!0)}_extractBarMarksRendererItemData(e,t){var i,s;const o=null!==(i=t.overridedTheme)&&void 0!==i?i:A[t.theme],r=this._calculateSize(e,t),n=this._calculateY(e,r,t);return null===this._hoveredBarsMarkData||this._hoveredBarsMarkData.id!==t.id||this._hoveredBarsMarkData.x===t.x&&this._hoveredBarsMarkData.y===Math.round(n)||(null===(s=this._tooltip)||void 0===s||s.hide(!0),this._hoveredBarsMarkData=null),{x:t.x,y:this._calculateY(e,r,t),direction:t.direction,borderColor:o.border,borderWidth:L(t),backgroundColor:o.background,size:r,doNotFill:!t.public,yInverted:t.yInverted,label:void 0===t.label?void 0:{text:t.label,fontColor:t.labelFontColor,font:(0,M.makeFont)(Math.ceil(Math.max(10,Math.min(r/2,20))),x.CHART_FONT_FAMILY,"bold")},originalItem:t}}_onItemClicked(e,t,i,s){s.isTouch&&this._showItem(e,t,i)}async _showItem(e,t,i){ var s;const o=await this._tooltipProps(e);if(null===o)return;const r=this._model.timeScale().barSpacing(),n=this._calculateSize(r,e.originalItem);this._hoveredBarsMarkData={x:e.x,y:Math.round(this._calculateY(r,n,e.originalItem)),id:e.originalItem.id},null===(s=this._tooltip)||void 0===s||s.show({itemSize:n,container:(0,g.ensureNotNull)(i.parentElement),x:e.x,y:t,factoryProps:o,onClickOutside:()=>{var e;return null===(e=this._tooltip)||void 0===e?void 0:e.hide(!0)}})}_hideItem(){var e;null===(e=this._tooltip)||void 0===e||e.hide()}_calculateSize(e,t){return Math.min(553,Math.max(7,t.minSize,.8*e))}_updateImpl(){this._originalData=this._source.getPlatesViewData();const e=this._model.timeScale().barSpacing(),t=this._originalData.map(this._extractBarMarksRendererItemData.bind(this,e));this._renderer.setData({items:t,barSpacing:e,highlightByAuthor:!1})}}{constructor(){super(...arguments),this._profileDataCache=new Map}_extractBarMarksRendererItemData(e,t){const i=super._extractBarMarksRendererItemData(e,t);return{...i,fixedSpaceYPosition:{basePosition:t.y,order:t.order,itemSpacing:.2857142857142857*e},mine:t.mine,borderWidth:t.hovered?i.borderWidth:t.public?1:2,doNotFill:!t.public,direction:t.direction}}async _createTooltipRenderer(){const[{TooltipRenderer:e},{PublishedChartsTimelineTooltip:t}]=await Promise.all([Promise.all([i.e(36827),i.e(7879),i.e(64248),i.e(90385),i.e(70354)]).then(i.bind(i,159217)),Promise.all([i.e(36827),i.e(7879),i.e(64248),i.e(90385),i.e(70354)]).then(i.bind(i,286676))]);return new e(t)}_calculateY(e,t,i){const s=("up"===i.direction?-1:1)*(i.yInverted?-1:1),o=s*(t*i.order+.2857142857142857*t*(i.order+1));return i.y+t/2*s+o}_onItemClicked(e,t,i,s){super._onItemClicked(e,t,i,s),s.isTouch||this.source().showIdea(e.originalItem.id,!1)}async _tooltipProps(e){var t;const i=(0,g.ensureDefined)(e.originalItem.username);let s=this._profileDataCache.get(i);if(void 0===s){try{s=await function(e){return fetch(`/api/v1/user/profile/${e}/?avatars_fallback=true&by=username`).then((e=>e.json()))}(i)}catch(e){return k.logWarn(`An error ocurred while loading profile data: ${e}`),null}this._profileDataCache.set(i,s)}return Promise.resolve({avatarUrl:null===(t=s.avatars)||void 0===t?void 0:t.mid,badges:s.badges,title:(0,g.ensureDefined)(e.originalItem.title),username:i,onTitleClicked:()=>this.source().showIdea(e.originalItem.id,!1)})}}var D=i(888929),B=i(314802);const N=(0,c.getLogger)("Chart.PublishedChartsTimeLine");class R extends n.BarsMarksContainer{constructor(e,t){let i=r().getValue("PublishedChartsTimeline.filter",l.PublishedChartsFilter.None);window.is_authenticated||(i=l.PublishedChartsFilter.None);const s=new m.DefaultProperty({defaultName:"publishedchartstimeline",state:{filter:i}});super(e,s),this.setId("PublishedChartsTimeline"),this._paneView=new E(this,e),this._paneViews=[this._paneView],this._currentRange=null,this._properties.childs().visible.subscribe(this,(()=>{this._getData(this._currentRange)})),s.childs().filter.subscribe(this,(e=>{r().setValue("PublishedChartsTimeline.filter",e.value()), this.clearMarks(),this._getData(this._currentRange)})),this._containsData=e.isSnapshot(),this._containsData&&this._properties.childs().visible.setValue(!0),this.setUserEditEnabled(!1),this._onIdeaClickedHandler=t}destroy(){this._onIdeaClickedHandler=null,this._boundOnMessage&&(a.pushStreamMultiplexer.off("ideas",this._boundOnMessage),a.pushStreamMultiplexer.off("ideas.post",this._boundOnMessage),this._boundOnMessage=null),this._paneView.destroy(),super.destroy()}name(){return"Ideas on chart"}title(){return s.t(null,void 0,i(5400))}zorder(){return D.sortSourcesPreOrdered.BarMarks}paneViews(){return this._model.isInReplay().value()||!this._properties.childs().visible.value()?[]:this._paneViews}showIdea(e,t){var i;const s=this._marks[e];s?((0,d.trackEvent)("GUI","View published idea"),t&&(0,d.trackEvent)("GUI","Ideas navigation arrow"),(0,h.onWidget)()||this._containsData||(0,B.isOnMobileAppPage)("any")?window.open(`${this._getBaseUrl()}${s.published_chart_url||"/v/"+s.image_url+"/"}`):null===(i=this._onIdeaClickedHandler)||void 0===i||i.call(this,{chartId:s.image_url,chartName:s.name,publishedUrl:s.published_chart_url,shortSymbol:s.short_name})):N.logDebug("PublishedChartsTimeline.showIdea: unexpected published chart id")}state(e){const t={type:"BarsMarksContainer",id:this.id(),zorder:this.zorder(),pinnedTooltips:this._pinnedTooltips};return e&&this._properties.childs().visible.value()&&(t.marks=this.getPublishedPlates()),t}restoreData(e,t){null!=e.pinnedTooltips&&(this._pinnedTooltips=e.pinnedTooltips),t&&void 0!==e.marks&&(this._marks=e.marks)}onClickOutside(e,t){this._paneView.onClickOutside(e,t)}_getIndex(e){return this.timeScale().timePointToIndex(e,1)}_initialize(){a.pushStreamMultiplexer&&(this._boundOnMessage=this._onMessage.bind(this),a.pushStreamMultiplexer.on("ideas",this._boundOnMessage),a.pushStreamMultiplexer.on("ideas.post",this._boundOnMessage))}_plateViewData(e){return{title:e.title,user_id:e.user__id,username:e.username,suggested:e.is_hot,mine:e.user__id===window.user.id,public:e.is_public}}_getData(e,t){const i=this._model.mainSeries().properties().childs(),s=this._model.mainSeries().symbolInfo();if(this._currentRange=e,!s||!this._properties.childs().visible.value()&&!t)return Promise.resolve([]);let o=s.base_name.length>1?s.base_name:[s.pro_name];const r=this.roundRange(this._rangeDifference(e));o=(0,u.uniq)(o),o=o.sort();const n=new FormData;n.append("interval",i.interval.value()),n.append("legs",JSON.stringify(o)),n.append("startTickmark",r.start.toString()),n.append("endTickmark",r.end.toString()),n.append("filter",this.properties().childs().filter.value());const a=(0,p.makeCancelable)(new Promise(((e,t)=>{(0,_.fetch)("/charttimeline/",{method:"POST",body:n,headers:new Headers({acccept:"application/json","X-Requested-With":"XMLHttpRequest"})}).then((i=>{i.ok?i.json().then(e):t()})).catch(t)})));return a.promise.then((t=>{t.forEach((e=>{this._marks[e.id]=e})),this._loadedRange=this._rangeUnion(e,this._loadedRange);const i=this._requests.indexOf(a);~i&&this._requests.splice(i,1), this.updateAllViewsAndRepaint()})),this._requests.push(a),a.promise}_onMessage(e,t,i,s){if(this._containsData)return;const o=this._model.mainSeries(),r=o.symbolInfo(),n=r&&r.base_name;if(!n)return;const a=o.properties().childs();e.interval===a.interval.value()&&~n.indexOf(e.pro_symbol)&&(this._marks[e.id]=e,this.updateAllViewsAndRepaint())}_getBaseUrl(){if((0,h.onWidget)()&&window.locale_domains){const e=window.locale||"en",t=window.locale_domains[e]?window.locale_domains[e]:window.locale_domains.en;return t?document.location.protocol+"//"+t:""}return""}}},154765:(e,t,i)=>{"use strict";i.d(t,{replayModeProperty:()=>c});var s=i(62802),o=i(638456),r=i(125226),n=i(152633);const a="replay_mode";function l(){return(0,r.isFeatureEnabled)("multichart_replay")&&!o.CheckMobile.any()?s.getValue(a,"ActiveChart"):"ActiveChart"}const c=(0,n.createPrimitiveProperty)(l());s.onSync.subscribe(null,(()=>c.setValue(l()))),(0,r.isFeatureEnabled)("multichart_replay")&&c.subscribe(null,(()=>s.setValue(a,c.value())))},944876:(e,t,i)=>{"use strict";i.d(t,{allPriceScaleSelectionStrategyInfo:()=>c,createPriceScaleSelectionStrategy:()=>l});var s=i(650151),o=i(444372),r=i(238433);class n{constructor(e){this._priceScalesLimit=8,this._metaInfo=e}metaInfo(){return this._metaInfo}findSuitableScale(e,t,i,s){if(void 0!==s)return this._tryToGetDesiredPriceScale(e,t,s,i);if((0,r.isStudy)(t)){const s=t.metaInfo();if("Volume"===s.shortId&&e.containsMainSeries())return e.createPriceScaleAtPosition("overlay");const o=t.desiredPriceScalePosition();if(null!==o)return this._tryToGetDesiredPriceScale(e,t,o,i);if(void 0!==i&&((0,r.isStudy)(i)||e.isMainPane())&&s.is_price_study)return this._getPriceScaleTheSameAsForSource(i,e)}let o=!1;if((0,r.isStudy)(t)){const i=t.metaInfo().groupingKey;if(void 0!==i){const t=e.model().findNonOverlayStudyWithGroupingKey(i,e);if(null!==t)return this._getPriceScaleTheSameAsForSource(t.study,t.pane)}o=Boolean(t.metaInfo().is_price_study)}else t===e.model().mainSeries()&&(o=!0);if(o){const t=this._findFirstScaleForPriceStudy(e);if(null!==t)return t}return this.createNewPriceScaleIfPossible(e)}canCreateNewPriceScale(e){return e.leftPriceScales().length+e.rightPriceScales().lengthi&&this._priceScaleIsPrice(e.rightPriceScales()[i],t))return e.rightPriceScales()[i];if(e.leftPriceScales().length>i&&this._priceScaleIsPrice(e.leftPriceScales()[i],t))return e.leftPriceScales()[i]}return null}_targetPriceScaleIndex(e,t){if(e.mainSource()===t.mainSeries())return 0}_tryToGetDesiredPriceScale(e,t,i,o){switch(i){case"left": return this.canCreateNewPriceScale(e)?e.createPriceScaleAtPosition("left"):e.createPriceScaleAtPosition("overlay");case"right":return this.canCreateNewPriceScale(e)?e.createPriceScaleAtPosition("right"):e.createPriceScaleAtPosition("overlay");case"as-series":return void 0!==o?(0,s.ensureNotNull)(o.priceScale()):e.isMainPane()?(0,s.ensureNotNull)((0,s.ensureNotNull)(e.mainDataSource()).priceScale()):this.createNewPriceScaleIfPossible(e);case"overlay":return e.createPriceScaleAtPosition("overlay")}}}const a=[{name:"left",title:o.t(null,void 0,i(665323)),ctor:class extends n{constructor(e){super(e)}apply(e){const t=e.model();e.rightPriceScales().slice(0).forEach((i=>e.movePriceScale(i,"left",this._targetPriceScaleIndex(i,t))))}createNewPriceScaleIfPossible(e){return this.canCreateNewPriceScale(e)?e.createPriceScaleAtPosition("left"):e.createPriceScaleAtPosition("overlay")}}},{name:"right",title:o.t(null,void 0,i(214113)),ctor:class extends n{constructor(e){super(e)}apply(e){const t=e.model();e.leftPriceScales().slice(0).forEach((i=>e.movePriceScale(i,"right",this._targetPriceScaleIndex(i,t))))}createNewPriceScaleIfPossible(e){return this.canCreateNewPriceScale(e)?e.createPriceScaleAtPosition("right"):e.createPriceScaleAtPosition("overlay")}}},{name:"auto",title:o.t(null,void 0,i(86951)),ctor:class extends n{constructor(e){super(e)}apply(e){if(e.containsMainSeries()){const t=(0,s.ensureNotNull)((0,s.ensureNotNull)(e.mainDataSource()).priceScale());e.movePriceScale(t,"right",0)}const t=e.model();for(;e.leftPriceScales().length>e.rightPriceScales().length;){const i=e.leftPriceScales()[e.leftPriceScales().length-1];e.movePriceScale(i,"right",this._targetPriceScaleIndex(i,t))}for(;e.rightPriceScales().length-e.leftPriceScales().length>1;){const i=e.rightPriceScales()[e.rightPriceScales().length-1];e.movePriceScale(i,"left",this._targetPriceScaleIndex(i,t))}}createNewPriceScaleIfPossible(e){if(!this.canCreateNewPriceScale(e))return e.createPriceScaleAtPosition("overlay");const t=e.leftPriceScales().lengtht.name===e)));return new t.ctor(t)}function c(){return a}},287790:(e,t,i)=>{"use strict";i.d(t,{restoreShowNewsNotificationSettingsValue:()=>l,showNewsNotificationsProperty:()=>a});var s=i(62802),o=i(152633);const r="show_news_upd_notif";function n(){return s.getBool(r,!1)}const a=(0,o.createPrimitiveProperty)(n());function l(){a.setValue(!1),s.remove(r)}a.subscribe(null,(()=>s.setValue(r,a.value()))),s.onSync.subscribe(null,(()=>a.setValue(n())))},305934:(e,t,i)=>{"use strict";i.d(t,{sourcesAffectState:()=>r});var s=i(713473),o=i(440941);function r(e){return!o.lineToolsDoNotAffectChartInvalidation||e.some((e=>!(0,s.isLineTool)(e)))}},506312:(e,t,i)=>{"use strict";i.d(t,{getFundamentalIdFromScriptIdPart:()=>o});const s=/^STD;Fund_(.*?)(?:_(?:fy|fq|fh|ttm))?$/;function o(e){const t=e.match(s);return t?t[1]:t}},370552:(e,t,i)=>{"use strict";var s;i.d(t,{InsertionErrorCode:()=>s}), function(e){e.StudyCannotBeChild="cannot_be_child",e.StubWasRemoved="stub_was_removed",e.CannotGetMetainfo="cannot_get_metainfo",e.CannotCompilePub="cannot_compile_pub",e.Cancelled="cancelled",e.Unknown="unknown"}(s||(s={}))},65541:(e,t,i)=>{"use strict";i.d(t,{StudyColorRotatorFactory:()=>d});var s=i(195294),o=i(724377),r=i(246733),n=i(238433);const a=["color-sky-blue-400","color-banana-yellow-700","color-deep-blue-500","color-grapes-purple-a700","color-iguana-green-500","color-minty-green-a600","color-ripe-red-a200","color-berry-pink-200","color-tv-blue-a100","color-tan-orange-a200","color-sky-blue-a400","color-deep-blue-a100","color-grapes-purple-400","color-iguana-green-a700","color-minty-green-200","color-ripe-red-200","color-berry-pink-a200","color-ripe-red-500","color-grapes-purple-500","color-deep-blue-400","color-tv-blue-a200","color-sky-blue-500","color-iguana-green-400","color-minty-green-400","color-banana-yellow-600","color-tan-orange-500","color-berry-pink-400","color-ripe-red-300","color-grapes-purple-300","color-deep-blue-300","color-tv-blue-300","color-sky-blue-300","color-iguana-green-300","color-minty-green-300","color-banana-yellow-400","color-tan-orange-300","color-berry-pink-300","color-tan-orange-a700"];class l{constructor(e){this._offset=0,this._offset=e}getColor(e){if(0===this._offset)return e;const t=a[(this._offset-1)%a.length],i=s.colorsPalette[t],n=(0,r.isHexColor)(e)?1:(0,o.parseRgba)(e)[3];return(0,r.generateColor)(i,(0,r.alphaToTransparency)(n))}}class c{constructor(e,t){this._offset=e,this._modelStartOffset=t}getColor(e){if((0,r.isHexColor)(e)){const t=(0,o.parseRgb)(e);return(0,o.rgbToHexString)((0,o.shiftRgb)(t,this._offset,this._modelStartOffset))}{const t=(0,o.parseRgba)(e);return(0,o.rgbaToString)((0,o.shiftRgba)(t,this._offset,this._modelStartOffset))}}}class d{constructor(e){this._chartModel=e}getColorRotator(e){const t=(0,n.studyColorRotationMode)(e);if(null===t)return null;const i=this._calcDefaultColorsOffset(e);switch(t){case"loop":return new l(i);case"shift":{const e=this._chartModel.getStudyShiftColorStartOffset();return new c(i,e)}}}_calcDefaultColorsOffset(e){let t=0;const i=(0,n.useSameColorRotationComparator)(e);return this._chartModel.dataSources().filter(n.isStudy).forEach((s=>{i(e,s.metaInfo())&&t++})),t}}},849245:(e,t,i)=>{"use strict";i.d(t,{StudyInserter:()=>_});var s=i(827147),o=i(526075),r=i(389137),n=i(347710),a=i(42292),l=i(370552),c=i(201089),d=i(7288);const h=(0,c.getLogger)("Chart.Studies.StudyInserter"),u=/^PUB;.*/;class _{constructor(e,t){this._parentSources=[],this._propsState=void 0,this._preferredPriceScale=void 0,this._allowChangeCurrency=!1,this._allowChangeUnit=!1,this._paneSize=void 0,this._forceOverlay=!1,this._inserterImpl=t,this._studyDescriptor=e}setParentSources(e){this._parentSources=e}setPaneSize(e){this._paneSize=e}setPreferredPriceScale(e){this._preferredPriceScale=e}setAllowChangeCurrency(e){this._allowChangeCurrency=e}setAllowChangeUnit(e){this._allowChangeUnit=e}setForceOverlay(e){this._forceOverlay=e}setPropertiesState(e){ this._propsState=e}setTargetPriceScaleMode(e){this._targetPriceScaleMode=e}async insert(e,t,i){var c,_;let p=null;var m;i||(p=void 0!==(m=this._inserterImpl).createStub&&void 0!==m.removeStub?this._inserterImpl.createStub():null);const g=e=>{if(i){const t=(0,s.default)(e)?{error:e}:{error:e.message,editorError:e};i.setStatus({type:d.StudyStatusType.Error,errorDescription:t}),this._inserterImpl.storeFailedStub(i)}};let S,v=!0;try{S=await(0,n.studyMetaInfoRepository)().findById(this._studyDescriptor)}catch(e){h.logWarn(`Cannot get study ${JSON.stringify(this._studyDescriptor)}`);const t=this._studyDescriptor.pineId,i=u.test(t),s=!!(null===(c=null==e?void 0:e.errors)||void 0===c?void 0:c.length);return g(s?{id:t,...e.errors[0]}:"Error: cannot compile script"),i&&s?Promise.reject(l.InsertionErrorCode.CannotCompilePub):Promise.reject(l.InsertionErrorCode.CannotGetMetainfo)}finally{null!==p&&(v=this._inserterImpl.removeStub(p))}if(!v)return Promise.reject(l.InsertionErrorCode.StubWasRemoved);if(void 0!==t&&t.cancelled)return Promise.reject(l.InsertionErrorCode.Cancelled);if(!this._canApplyStudyToParent(S))return g("Error: cannot be child"),Promise.reject(l.InsertionErrorCode.StudyCannotBeChild);const f={...S.defaults.inputs};let b={};if(void 0!==e){const t=o.StudyMetaInfo.getStudyPropertyRootName(S),i=(0,r.clone)((0,a.defaults)(t));(0,r.merge)(f,i.inputs);const s=await e(f,S.inputs,S);b=s.inputs,this._parentSources=null!==(_=s.parentSources)&&void 0!==_?_:[]}if(void 0!==t&&t.cancelled)return Promise.reject(l.InsertionErrorCode.Cancelled);const y=this._insertStudy(S,b,i);return null===y?(g("Error: unknown error"),Promise.reject(l.InsertionErrorCode.Unknown)):(await y.startPromise,y.study)}_insertStudy(e,t,i){return this._inserterImpl.createStudy(e,t,null,i,this._propsState,this._forceOverlay,this._parentSources,this._preferredPriceScale,this._allowChangeCurrency,this._allowChangeUnit,this._paneSize,this._targetPriceScaleMode)}_canApplyStudyToParent(e){return 0===this._parentSources.length||o.StudyMetaInfo.canBeChild(e)}}},459711:(e,t,i)=>{"use strict";i.d(t,{StudyLineToolStub:()=>n,isStudyLineToolStub:()=>r});var s=i(401580),o=i(306682);function r(e){return e instanceof n}class n extends o.StudyStub{constructor(e,t,i){var o;super(e,{...t,ownFirstValue:null},i),this._linkKey=new s.WatchedValue(null!==(o=t.linkKey)&&void 0!==o?o:null)}linkKey(){return this._linkKey}}},167258:(e,t,i)=>{"use strict";var s=i(707957).Delegate;function o(){this._marksByIndex=new Map,this._marksBySpan=[],this.changed=new s,this.minIndex=void 0,this.maxIndex=void 0}o.prototype.reset=function(){this._resetImpl(),this.changed.fire()},o.prototype._resetImpl=function(){this._marksByIndex=new Map,this._marksBySpan=[],this.minIndex=void 0,this.maxIndex=void 0,this._cache=void 0},o.prototype.merge=function(e){if(0!==e.length){var t=e[0].index,i=e[e.length-1].index;t<=this.minIndex&&i>=this.maxIndex&&this._resetImpl();for(var s=this._marksBySpan,o=new Set,r=0;r=this.maxIndex&&this.maxIndex--,this.maxIndex2;){if(1e3*this._marksByIndex.get(t).time===e)return t;if(1e3*this._marksByIndex.get(i).time===e)return i;var s=Math.round((t+i)/2);1e3*this._marksByIndex.get(s).time>e?i=s:t=s}return t},o.prototype.build=function(e,t){var i=Math.ceil(t/e);if(this._maxbar===i&&this._cache)return this._cache;this._maxbar=i;for(var s=[],o=this._marksBySpan.length;o--;)if(this._marksBySpan[o]){var r=s;s=[];for(var n=r.length,a=0,l=this._marksBySpan[o],c=l.length,d=1/0,h=-1/0,u=0;u=i&&p-h>=i&&(s.push(_),h=p)}for(;ae.index>=i&&e.index<=s))}return{marks:t=t.map((function(e){return[e.span,e.time,e.index]})),version:2}},o.prototype.restoreState=function(e){if(this._marksByIndex=new Map,this._marksBySpan=[],this.maxIndex=void 0,this.minIndex=void 0,e&&e.marks&&e.marks.length)if(2===e.version){var t=e.marks.map((function(e){return{span:e[0],time:e[1],index:e[2]}}));this.merge(t)}else this.merge(e.marks)},e.exports.Tickmarks=o},827023:(e,t,i)=>{ "use strict";i.d(t,{restoreTimeHoursFormatSettingsValue:()=>l,timeHoursFormatProperty:()=>a});var s=i(62802),o=i(152633);const r="time_hours_format";function n(){return s.getValue(r,"24-hours")}const a=(0,o.createPrimitiveProperty)(n());function l(){a.setValue("24-hours"),s.remove(r)}s.onSync.subscribe(null,(()=>a.setValue(n()))),a.subscribe(null,(()=>s.setValue(r,a.value())))},440058:(e,t,i)=>{"use strict";i.d(t,{forceTradingObjVisibilityOnScreenshot:()=>d,restoreShowOnScreenshotSettingsValue:()=>c,showOnScreenshotProperty:()=>l});var s=i(62802),o=i(401580),r=i(152633);const n="trading_drawings_on_screenshot";function a(){return s.getBool(n,!1)}const l=(0,r.createPrimitiveProperty)(a());function c(){l.setValue(!1),s.remove(n)}s.onSync.subscribe(null,(()=>l.setValue(a()))),l.subscribe(null,(()=>s.setValue(n,l.value())));const d=new o.WatchedValue(null)},993713:(e,t,i)=>{"use strict";i.d(t,{SetWatchedValueCommand:()=>o});var s=i(142257);class o extends s.UndoCommand{constructor(e,t,i,s=!0){super(i,void 0,s),this._wv=e,this._newValue=t,this._oldValue=e.value()}redo(){this._wv.setValue(this._newValue)}undo(){this._wv.setValue(this._oldValue)}}},744728:(e,t,i)=>{"use strict";i.d(t,{SwapChartsUndoCommand:()=>a});var s=i(444372),o=i(809796),r=i(142257);const n=new o.TranslatedString("swap charts in the Layout",s.t(null,void 0,i(665818)));class a extends r.UndoCommand{constructor(e,t,i){super(n),this._swapper=e,this._from=t,this._to=i}redo(){this._swapper(this._from,this._to)}undo(){this._swapper(this._from,this._to)}}},176019:(e,t,i)=>{"use strict";i.d(t,{createUndoHistory:()=>d});var s=i(650151),o=i(13294),r=i(345297),n=i(993713),a=i(201089),l=i(707957);const c=(0,a.getLogger)("Common.UndoHistory");function d(){const e=[],t=new o.UndoStack,i=new o.UndoStack,a=new l.Delegate;function d(s){if(e.length>0)e[e.length-1].addCommand(s);else{i.clear();const e=t.head(),o=e&&e.text().originalText();e&&e.canMerge(s)?e.merge(s):t.push(s);const r=s.text().originalText();""!==r&&r!==o&&c.logNormal("DO: "+r)}s.executeOnPush()&&s.redo(),e.length||a.fire(h())}function h(){const e=t.head(),s=i.head(),o=void 0===e?void 0:e.text(),r=void 0===s?void 0:s.text();return{enableUndo:!t.isEmpty(),undoCommandCount:t.size(),undoText:void 0!==o?o.translatedText():o,enableRedo:!i.isEmpty(),redoCommandCount:i.size(),redoText:void 0!==r?r.translatedText():r,originalUndoText:void 0!==o?o.originalText():void 0,originalRedoText:void 0!==r?r.originalText():void 0}}return{beginUndoMacro:function(t){const i=new r.UndoMacroCommand(t);return e.push(i),i},clearStack:function(){t.clear(),i.clear(),a.fire(h())},createUndoCheckpoint:function(){return{lastActualCommand:t.isEmpty()?null:t.head()}},endUndoMacro:function(){const t=(0,s.ensureDefined)(e.pop());t.isEmpty()||d(t)},pushUndoCommand:d,redo:function(){if(i.isEmpty())return!1;const e=i.pop();return!!e&&(e.redo(),t.push(e),c.logNormal("REDO: "+e.text().originalText()),a.fire(h()),!0)},redoStack:function(){return i},setWatchedValue:function(e,t,i,s){if(e.value()!==t){const o=new n.SetWatchedValueCommand(e,t,i,!s) ;d(o),o.redo()}},undo:function(){if(t.isEmpty())return!1;const e=t.pop();return!!e&&(e.undo(),i.push(e),c.logNormal("UNDO: "+e.text().originalText()),a.fire(h()),!0)},undoStack:function(){return t},undoToCheckpoint:function(e){for(;!t.isEmpty()&&e.lastActualCommand!==t.head();)t.pop().undo();i.clear(),a.fire(h())},state:h,onChange:function(){return a}}}},345297:(e,t,i)=>{"use strict";i.d(t,{UndoMacroCommand:()=>o});var s=i(142257);class o extends s.UndoCommand{constructor(e){super(e,!1),this._subcommands=[]}addCommand(e){this._subcommands.push(e)}isEmpty(){return 0===this._subcommands.length}redo(){for(let e=0;e=0;e--)this._subcommands[e].undo()}commands(){return this._subcommands}affectsState(){return this._subcommands.some((e=>e.affectsState()))}}},13294:(e,t,i)=>{"use strict";i.d(t,{UndoStack:()=>n});var s=i(142257),o=i(707957);const r=(0,i(201089).getLogger)("Common.UndoStack");class n{constructor(){this._commands=[],this._onChange=new o.Delegate}onChange(){return this._onChange}isEmpty(){return 0===this._commands.length}size(){return this._commands.length}clear(){this.isEmpty()||(this._commands.length=0,this._onChange.fire())}push(e){if(!(e instanceof s.UndoCommand))throw new TypeError("argument must be an instance of UndoCommand");this._commands.push(e),this._onChange.fire(e)}pop(){if(this.isEmpty())return void r.logDebug("pop: undo stack is empty");const e=this._commands.pop();return this._onChange.fire(e),e}head(){if(!this.isEmpty())return this._commands[this._commands.length-1]}}},438907:(e,t,i)=>{"use strict";i.d(t,{sourceNewUnitOnPinningToPriceScale:()=>n,unitConvertibleGroups:()=>r});var s=i(981107),o=i(444331);function r(e,t,i){const s=(0,o.symbolUnitConvertibleGroupsIfExist)(e,!0);if(null!==s)return s;const r=i.unitGroupById(t);return null===r?[]:[r]}function n(e,t,i,o){let n=null;if(i.unitConversionEnabled()&&(0,s.isSymbolSource)(e)){const s=i.availableUnits(),a=t.unit(s),l=e.unit(),c=null===l?[]:r(e.symbolInfo(),l,s);null!==a&&null!==a.selectedUnit&&!a.allUnitsAreOriginal&&a.selectedUnit!==l&&(o&&null===l||null!==l&&s.convertible(l,c))&&(n=a.selectedUnit)}return n}},690142:(e,t,i)=>{"use strict";i.d(t,{restoreWithWeekdaySettingsValue:()=>l,withWeekdayProperty:()=>a});var s=i(62802),o=i(152633);const r="date_format_with_weekday";function n(){return s.getBool(r,!0)}const a=(0,o.createPrimitiveProperty)(n());function l(){a.setValue(!0),s.remove(r)}a.subscribe(null,(()=>s.setValue(r,a.value()))),s.onSync.subscribe(null,(()=>a.setValue(n())))},46955:(e,t,i)=>{"use strict";i.d(t,{moveAfterSource:()=>k,moveBeforeSource:()=>E,newLineToolZOrder:()=>C,newStudyZOrder:()=>w,reorderDataSourcesStateZOrder:()=>f});var s=i(713473),o=i(238433),r=i(440617),n=i(790524),a=i(674981);function l(e){return(0,s.isLineTool)(e)&&!e.isSpeciallyZOrderedSource()}function c(e){return(0,o.isStudy)(e)&&!e.isSpeciallyZOrderedSource()||(0,o.isStudyStub)(e)}function d(e,t){return e.zorder-t.zorder}function h(e,t){(0, n.isMainSeriesState)(e)?e.zorder=0:e.zorder=t}function u(e,t){e.setZorder(t)}function _(e){return e.zorder()}function p(e){return Math.round(1e3*e)/1e3}function m(e,t){const i=Math.max(e,t),s=Math.min(e,t);return Math.max(0,Math.ceil(i)-Math.floor(s)-1)}function g(e,t,i){let s=0;const o=function(e,t){const i=1e3;return Math.abs(t*i-e*i)/i}(t,e);var r;return o>i?(e=Math.trunc(e),s=Math.floor(o/(i+1))):(r=o/(i+1),s=Math.floor(1e3*r)/1e3),{startZOrder:e,zOrderStep:s}}function S(e,t,i,s){let o=e.length,r=t;for(let t=e.length-1;t>=-1;t--)if(-1===t||s(e[t])){const s=t;let n=T(r);if(o-1===s)s>=0&&i(e[s],n);else{const t=m(o,s);let a=0;for(;0===a;){const e=g(r,n,t);r=e.startZOrder,a=e.zOrderStep,0===a&&(n-=1e4,0===n&&(n-=1e4))}let l=o-1;for(;l>s;){const t=p(r-a);i(e[l],t),r=t,l--}s>=0&&i(e[s],n)}r=n,o=s}}function v(e,t,i,s){let o=-1,r=t;for(let t=0;t<=e.length;t++)if(t===e.length||s(e[t])){const s=t;let n=P(r);if(o+1===s)s<=e.length-1&&i(e[s],n);else{const t=m(o,s);let a=0;for(;0===a;){const e=g(r,n,t);r=e.startZOrder,a=e.zOrderStep,0===a&&(n+=1e4,0===n&&(n+=1e4))}let l=o+1;for(;l<=s-1;){const t=p(r+a);i(e[l],t),r=t,l++}s<=e.length-1&&i(e[s],n)}r=n,o=s}}function f(e){!function(e,t,i,s,o,r){let n=null;const a=[];for(const o of e)t(o)?(a.push(o),n=o):(i(o)||s(o))&&a.push(o);a.sort(r),null!==n&&o(n,0);const l=null===n?-1:a.indexOf(n);-1!==l?(S(a.slice(0,l),0,o,i),v(a.slice(l+1),0,o,i)):v(a,0,o,i)}(e,n.isMainSeriesState,n.isStudyState,n.isLineToolState,h,d)}function b(e,t){const i=Math.floor(e/1e4);let s=t.get(i);return void 0===s&&(s=[],t.set(i,s)),s}function y(e,t,i,s,o,r){let n=-1/0,a=1/0,l=-1/0,c=0;const d=new Map;for(let s=0;so(e)-o(t)));let _=T(o(u[0]));const m=P(_),S=g(_,m,u.length+1).zOrderStep;return 0!==S?(u.forEach((e=>{const t=p(_+S);s(e,t),_=t})),p(_+S)):p(m+5e3)}function C(e,t){return y(e,l,c,u,_,t)}function w(e){let t=-1e4;for(const i of e)c(i)&&(t=Math.min(t,i.zorder()-1e4));return 0===t?-1e4:t}function P(e){const t=1e4*Math.ceil(e/1e4);return t===e?t+1e4:t}function T(e){const t=1e4*Math.floor(e/1e4);return t===e?t-1e4:t}function M(e,t,i,s,o,r,n){const l=t.length,{newItems:c,movedItemsStartIndex:d}=i>0?(0,a.moveAfter)(e,t,i-1):(0,a.moveBefore)(e,t,0);let h=!1;for(let t=d;to(e)))?function(e,t,i,s,o,r){let n,a,l=-1,c=-1;0===i?(c=x(e,i+t,s),a=r(e[c])):i+t===e.length?(l=I(e,i-1,s),n=r(e[l])):(l=I(e,i-1,s),n=r(e[l]),c=x(e,i+t,s),a=r(e[c]));if((void 0===n||n<0)&&void 0!==a&&a<=0)S(e.slice(0,c),a,o,s);else if((void 0===a||a>0)&&void 0!==n&&n>=0)v(e.slice(l+1),n,o,s);else{ i+t0)&&void 0!==a&&a>=0){c=a;const e=g(c,void 0!==l?l:P(a),t);c=e.startZOrder,_=e.zOrderStep,h=i,u=h+t,d=1}if(0!==_)for(;h!==u;){const t=p(c+d*_);r(e[h],t),c=t,h+=d}else{const t=e.findIndex((e=>o(e)));-1!==t?(S(e.slice(0,t),0,r,s),v(e.slice(t+1),0,r,s)):v(e,0,r,s)}}(c,l,d,o,s,r,n)}function x(e,t,i){for(;t=0&&i(e[t]);)t--;return Math.max(0,t)}function A(e,t,i,s,o,r,n){const a=e.indexOf(i)+1;M(e,t,a,s,o,r,n)}function L(e,t,i,s,o,r,n){const a=e.indexOf(i);M(e,t,a,s,o,r,n)}function k(e,t,i){A(e,t,i,r.isSeries,c,u,_)}function E(e,t,i){L(e,t,i,r.isSeries,c,u,_)}},937994:(e,t,i)=>{"use strict";function s(e=0){return e<1e3?e:e/1e3}function o(e,t){if(e.length>t){const i=/[\W]+$/g,s=e.substring(0,t),o=s.replace(i,"");return`${o.length?o:s.substring(0,t-1)}…`}return e}i.d(t,{cutString:()=>o,ensureDurationInSeconds:()=>s})},547871:(e,t,i)=>{"use strict";i.d(t,{getAlertsChartActionCreators:()=>s});const s=(0,i(895171).default)((async()=>{const{getCreateAlertAction:e}=await i.e(43853).then(i.bind(i,966238)),{getEditAlertOnLineDataSourceAction:t}=await i.e(43853).then(i.bind(i,330359));return{createAlert:e,editAlertOnLineDataSource:t}}))},976737:(e,t,i)=>{"use strict";i.d(t,{hasUsualAlertPlots:()=>a,isFirstAlertPlotUsual:()=>n});var s=i(440617),o=i(238433),r=i(223284);function n(e){if((0,s.isSeries)(e))return!0;if((0,o.isStudy)(e)&&!(0,o.isStudyStrategy)(e)){const t=(0,r.plotsForAlert)(e.metaInfo(),e.offset.bind(e));return!e.metaInfo().hasAlertFunction&&t.every((e=>"alertcondition"!==e.type))}return!1}function a(e){if((0,s.isSeries)(e))return!0;if((0,o.isStudy)(e)&&!(0,o.isStudyStrategy)(e)){return(0,r.plotsForAlert)(e.metaInfo(),e.offset.bind(e)).some((e=>"alertcondition"!==e.type))}return!1}},678183:(e,t,i)=>{"use strict";var s;i.d(t,{AlertStopReason:()=>s}),function(e){e[e.Auto=0]="Auto",e[e.Manual=1]="Manual",e[e.Expired=2]="Expired",e[e.Created=3]="Created"}(s||(s={}))},992393:(e,t,i)=>{"use strict";i.d(t,{confirmDatasourceRemoving:()=>r});var s=i(444372),o=i(779923);function r(){return new Promise((e=>(0,o.showConfirm)({text:s.t(null,void 0,i(784019)),onConfirm:({dialogClose:t})=>{e(!0),t()},onClose:()=>e(!1)})))}},726778:(e,t,i)=>{"use strict";function s(e){return r().then((t=>t.hasUserAccessToDataSource(e)))}function o(e){return r().then((t=>t.filterAccessibleDataSources(e)))}i.d(t,{filterAccessibleDataSources:()=>o,hasUserAccessToDataSource:()=>s});const r=()=>Promise.all([i.e(68716),i.e(36876),i.e(35047),i.e(98597),i.e(98591),i.e(837),i.e(24951),i.e(89903),i.e(83433),i.e(35698),i.e(10399),i.e(48834),i.e(2227),i.e(56303),i.e(5721),i.e(41793),i.e(83441)]).then(i.bind(i,827019))}, 582665:(e,t,i)=>{"use strict";i.d(t,{bulkRemoveConfirmation:()=>l,bulkRemoveInactiveConfirmation:()=>c,bulkRestartConfirmation:()=>a,bulkStopConfirmation:()=>n,selectedRemoveConfirmation:()=>d});var s=i(444372),o=i(591427),r=i(937994);const n=e=>e?{title:s.t(null,void 0,i(742692)),text:s.t(null,void 0,i(528183))}:{title:s.t(null,void 0,i(73016)),text:s.t(null,void 0,i(343860))},a=e=>e?{title:s.t(null,void 0,i(733946)),text:s.t(null,void 0,i(548111))}:{title:s.t(null,void 0,i(639901)),text:s.t(null,void 0,i(530147))},l=e=>e?{title:s.t(null,void 0,i(830930)),text:s.t(null,void 0,i(764123))}:{title:s.t(null,void 0,i(879698)),text:s.t(null,void 0,i(597411))},c=()=>({title:s.t(null,void 0,i(447537)),text:s.t(null,void 0,i(669387))}),d=e=>{if(1!==e.length)return{title:s.t(null,void 0,i(558519)),text:s.t(null,void 0,i(260920))};const t=e[0],n=(0,o.getAlertDescription)(t);return{title:s.t(null,void 0,i(588511)),text:s.t(null,void 0,i(974834)).format({alert:(0,r.cutString)(n,100)})}}},454984:(e,t,i)=>{"use strict";function s(e,t,i="promise rejected by time-out"){return new Promise(((s,o)=>{const r=setTimeout((()=>o(i)),t);e.then((e=>{clearTimeout(r),s(e)})),e.catch((e=>{clearTimeout(r),o(e)}))}))}i.d(t,{makeTimeLimited:()=>s})},868683:(e,t,i)=>{"use strict";function s(){return Promise.all([i.e(32662),i.e(5987),i.e(98996),i.e(66458),i.e(44597),i.e(19216),i.e(69374),i.e(90385),i.e(62526),i.e(32077)]).then(i.bind(i,880880))}i.d(t,{loadChangeIntervalDialog:()=>s})},230296:(e,t,i)=>{"use strict";i.d(t,{showChangeIntervalDialogAsync:()=>r});var s=i(868683);let o=null;function r(e){const t=o=(0,s.loadChangeIntervalDialog)().then((i=>{t===o&&i.showChangeIntervalDialog(e)}));return t}},277774:(e,t,i)=>{"use strict";function s(e){return Promise.all([i.e(32662),i.e(5987),i.e(98996),i.e(43387),i.e(66458),i.e(5761),i.e(4343),i.e(28430),i.e(70428),i.e(44597),i.e(4908),i.e(70621),i.e(62033),i.e(13633),i.e(19216),i.e(35697),i.e(66233),i.e(28593),i.e(42332),i.e(57876),i.e(20221),i.e(44915),i.e(85150),i.e(90385),i.e(59255),i.e(62526),i.e(68581),i.e(45646),i.e(53549),i.e(64796),i.e(91859)]).then(i.bind(i,533919)).then((t=>t.showGoToDateDialog(e)))}i.d(t,{showGoToDateDialog:()=>s})},703089:(e,t,i)=>{"use strict";async function s(e){(await Promise.all([i.e(29178),i.e(23465),i.e(32662),i.e(43387),i.e(14),i.e(36827),i.e(37657),i.e(33101),i.e(34422),i.e(63244),i.e(92469),i.e(36748),i.e(85317),i.e(49542),i.e(97485),i.e(10890),i.e(55980),i.e(18612),i.e(72153),i.e(90385),i.e(59255),i.e(23127),i.e(99120),i.e(8775),i.e(84450),i.e(42198),i.e(15516),i.e(26066)]).then(i.bind(i,492418))).renderGoToTradingViewReferralDialog(e)}i.d(t,{showGoToTradingViewReferralDialog:()=>s})},663554:(e,t,i)=>{"use strict";i.d(t,{showDeleteStudyTreeConfirm:()=>r});var s=i(444372),o=i(779923);function r(e){(0,o.showConfirm)({title:s.t(null,void 0,i(638154)),text:s.t(null,void 0,i(452003)),onConfirm:({dialogClose:t})=>{e(),t()}})}},568247:(e,t,i)=>{"use strict";function s(e){ Promise.all([i.e(22309),i.e(32662),i.e(5987),i.e(98996),i.e(66458),i.e(5761),i.e(4343),i.e(28430),i.e(70428),i.e(1413),i.e(70621),i.e(89508),i.e(62033),i.e(13633),i.e(16600),i.e(87940),i.e(61576),i.e(10714),i.e(1337),i.e(1707),i.e(18069),i.e(90385),i.e(62526),i.e(44246),i.e(9022),i.e(9374)]).then(i.bind(i,493443)).then((({SymbolInfoDialogImpl:t})=>{t.getInstance().show(e)}))}i.d(t,{showSymbolInfoDialog:()=>s})},625923:e=>{e.exports=''},270068:e=>{e.exports=''},634369:e=>{e.exports=''},748040:e=>{e.exports=''},861814:e=>{e.exports=''},324020:e=>{e.exports=''},421672:e=>{ e.exports=''},553218:e=>{e.exports=''},24165:e=>{e.exports=''},792263:e=>{e.exports=''},262998:e=>{e.exports=''},732140:e=>{e.exports=''},109494:e=>{e.exports=''},792845:e=>{e.exports=''},725230:e=>{e.exports=''},643401:e=>{e.exports=''},212462:e=>{ e.exports=''},527409:e=>{e.exports=''},855824:e=>{e.exports=''},539706:e=>{e.exports=''},760823:e=>{e.exports=''},244230:e=>{e.exports=''},428026:e=>{e.exports=''},437924:e=>{e.exports=''},699875:e=>{ e.exports=''},902872:e=>{e.exports=''},507983:e=>{e.exports=''},139267:e=>{e.exports=''},416911:e=>{e.exports=''},198083:e=>{e.exports=''},472382:e=>{ e.exports=''},706862:e=>{e.exports=''},854190:e=>{e.exports=''},225191:e=>{e.exports=''},593379:e=>{e.exports=''},484959:e=>{ e.exports=''},397874:e=>{e.exports=''},677067:e=>{e.exports=''},439970:e=>{e.exports=''},789795:e=>{e.exports=''},808757:e=>{e.exports=''},786559:e=>{ e.exports=''},80465:e=>{e.exports=''}}]);