Files
ai/charting_library/bundles/price-alerts-dispatcher.416bae3f764ba35699c2.js
2023-02-02 13:31:14 +00:00

50 lines
147 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

(self.webpackChunktradingview=self.webpackChunktradingview||[]).push([[8158],{24993:(e,t,n)=>{"use strict";var r;n.d(t,{AlertEditorAbortReason:()=>r}),function(e){e.AlertIsInvalid="alert-is-invalid",e.AlertsMaintenance="alerts-maintenance",e.ChartModelNotFound="chart-model-not-found",e.IsAlreadyPresent="is-already-present",e.MainSeriesIsATR="main-series-is-atr",e.MainSeriesIsInReplay="main-series-is-in-replay",e.MainSeriesIsOffline="main-series-is-offline",e.SourceIsDangerous="source-is-dangerous",e.SymbolInfoTimeout="symbol-info-timeout",e.SymbolIsInvalid="symbol-is-invalid",e.SymbolCurrencyConverted="symbol-currency-converted",e.SymbolUnitConverted="symbol-unit-converted",e.SymbolCurrencyAndUnitConverted="symbol-currency-and-unit-converted",e.SymbolIsEconomics="symbol-is-economics",e.UnsupportedResolution="unsupported-resolution",e.ManualAbort="manual-abort",e.MisleadingPriceScale="misleading-price-scale"}(r||(r={}))},99486:(e,t,n)=>{"use strict";n.d(t,{getAlertDialogType:()=>p,shouldAbortAlertEditor:()=>h,showAbortExplainingDialog:()=>m});var r=n(28353),i=n(3615),o=n(24993),s=n(16654),a=n(37667),l=n(82992),c=n(26187),u=n(22822),d=n(51712),_=n(39193);function p(e){return e.alert?e.type||"edit_alert":"create_alert"}function h(e){var t;if(_.alertsMaintenanceTracker.value())return o.AlertEditorAbortReason.AlertsMaintenance;if(!e.alert&&!e.dataSourceHub)return o.AlertEditorAbortReason.ChartModelNotFound;if(!c.alertEditorInvocationHandler.isAllowedToInvoke(e))return o.AlertEditorAbortReason.IsAlreadyPresent;const n=null===(t=e.dataSourceHub)||void 0===t?void 0:t.mainSeries();if(n&&f(n))return o.AlertEditorAbortReason.MainSeriesIsOffline;if(n&&function(e){return e.status()===s.STATUS_INVALID_SYMBOL}(n))return o.AlertEditorAbortReason.SymbolIsInvalid;if(n&&n.isConvertedToOtherCurrency()&&n.isConvertedToOtherUnit())return o.AlertEditorAbortReason.SymbolCurrencyAndUnitConverted;if(n&&n.isConvertedToOtherCurrency())return o.AlertEditorAbortReason.SymbolCurrencyConverted;if(n&&n.isConvertedToOtherUnit())return o.AlertEditorAbortReason.SymbolUnitConverted;const r=p(e);if("create_alert"===r&&n&&function(e){var t;return"ATR"===(null===(t=e.stateForAlert().styleInputs)||void 0===t?void 0:t.style)}(n))return o.AlertEditorAbortReason.MainSeriesIsATR;if("create_alert"===r&&n&&function(e){return e.isInReplay()}(n))return o.AlertEditorAbortReason.MainSeriesIsInReplay;if("create_alert"===r&&n&&function(e){return(0,a.isEconomicSymbol)(e.symbolInfo())}(n))return o.AlertEditorAbortReason.SymbolIsEconomics;const i=n?n.interval():l.linking.interval.value();return"create_alert"!==r||(0,u.canPlaceAlertOnResolution)(i)?null:o.AlertEditorAbortReason.UnsupportedResolution}function f(e){return e.status()===s.STATUS_OFFLINE}function m(e,t){if(g.has(e))return;g.add(e);const n=()=>g.delete(e),s=function(e){return new Map([[o.AlertEditorAbortReason.UnsupportedResolution,"alertsOnSeconds"]]).get(e)||null}(e);if(s)return void(0,d.reloginOrGoPro)({feature:s,actionAfterClose:n});const a=function(e,t){
const n=r.t("Oops!"),i=r.t("Alert editor could not be initialized"),s=r.t("Ok");return new Map([[o.AlertEditorAbortReason.AlertsMaintenance,{title:r.t("Alerts maintenance"),text:r.t("We are doing some brief daily maintenance. Alerts will be back really soon, thanks for your patience!"),buttonText:s}],[o.AlertEditorAbortReason.MainSeriesIsOffline,{title:n,text:("create_alert"===t?r.t("Cannot create an alert while offline"):r.t("Cannot edit an alert while offline"))+". "+r.t("Please check your internet connection")+".",buttonText:s}],[o.AlertEditorAbortReason.SymbolIsInvalid,{title:n,text:"create_alert"===t?r.t("Can't create alert on invalid symbol"):r.t("Can't edit alert on invalid symbol"),buttonText:s}],[o.AlertEditorAbortReason.SymbolCurrencyAndUnitConverted,{title:r.t("Both the currency and the unit have been converted!"),text:"create_alert"===t?r.t("It's not currently possible to create alerts on such a scale."):r.t("It's not currently possible to edit alerts on such a scale."),buttonText:r.t("Got it")}],[o.AlertEditorAbortReason.SymbolCurrencyConverted,{title:r.t("A converted currency has been detected!"),text:"create_alert"===t?r.t("It's not currently possible to create alerts for this type of symbol."):r.t("It's not currently possible to edit alerts for this type of symbol."),buttonText:r.t("Got it")}],[o.AlertEditorAbortReason.SymbolUnitConverted,{title:r.t("A converted unit has been detected!"),text:"create_alert"===t?r.t("It's not currently possible to create alerts for this type of symbol."):r.t("It's not currently possible to edit alerts for this type of symbol."),buttonText:r.t("Got it")}],[o.AlertEditorAbortReason.SymbolIsEconomics,{title:r.t("Dang-it Wrong symbol type!"),text:r.t("Alerts aren't available right now for economics symbols."),buttonText:r.t("Got it")}],[o.AlertEditorAbortReason.MainSeriesIsATR,{title:r.t("Alert cannot be set on an ATR-based chart"),text:r.t("Your alert won't trigger the way you expect it to! Inputs for ATR-based charts are recalculated each time you open a chart and are generally dependent on time. Please use the traditional chart type to set an alert with a static box size."),buttonText:s}],[o.AlertEditorAbortReason.MainSeriesIsInReplay,{title:r.t("Oops Replay Mode!"),text:r.t("Alerts are not currently available in replay mode."),buttonText:r.t("Got it")}]]).get(e)||{title:n,text:i,buttonText:s}}(e,t);(0,i.showWarning)({...a,onClose:n})}const g=new Set},64021:(e,t,n)=>{"use strict";n.d(t,{FormattersSerializer:()=>c});var r=n(97098),i=n(67802),o=n(26811);class s{constructor(e){this.type="quoteSessionPrice",this.reset(e)}state(){return this._priceFormatter.state()}reset(e){this._priceFormatter=e||new r.PriceFormatter(100,1,!1)}update(e,t){const n=null!=t.pricescale||null!=t.minmov||null!=t.fractional||null!=t.minmove2,i=null!=e.pricescale&&null!=e.minmov&&null!=e.fractional&&null!=e.minmove2;n&&i&&(this._priceFormatter=new r.PriceFormatter(e.pricescale,e.minmov,e.fractional||!1,e.minmove2))}format(e,t,n){return this._priceFormatter.format(e,t,n)}
hasForexAdditionalPrecision(){return this._priceFormatter.hasForexAdditionalPrecision()}static serialize(e){return e.state()}static deserialize(e){const t=new r.PriceFormatter(e.priceScale,e.minMove,e.fractional,e.minMove2);return new s(t)}}var a=n(88537);const l={price:r.PriceFormatter,volume:i.VolumeFormatter,percentage:o.PercentageFormatter,quoteSessionPrice:s};var c;!function(e){e.serialize=function(e){const t=(0,a.ensureDefined)(l[e.type]);return{type:e.type,state:t.serialize(e)}},e.deserialize=function(e){return(0,a.ensureDefined)(l[e.type]).deserialize(e.state)}}(c||(c={}))},95379:e=>{"use strict";function t(e){var t=JSON.stringify(e);return t=t.replace(/'/g,"\\'")}e.exports={formatCallstudyArg:t,prepareCallStudyArgs:function(e,n){var r={};if(n.isTVScript){var i=n.defaults.inputs.text;r.text=(void 0).patchILTemplate(i,n,e)}else for(var o=Object.keys(e),s=o.length-1;s>=0;s--){var a=o[s],l=e[a]?e[a].id:null;l&&e[l]&&(r[l]=e[l])}return t(r)}}},99543:(e,t,n)=>{"use strict";var r=n(2872),i=n(23127),o=n(28353).t,s=n(88537).assert,a=n(51768).trackEvent,l=n(21097).TVXWindowEvents,c=n(98125).getLogger("Pine.ScriptLib"),u=n(52485).telemetry,d=n(76422),_={fast:["delete","get","is_auth_to_get","is_auth_to_write","parse_title","rename","lib_list"],medium:["list","eval_pine_ex","translate_light"],slow:["process_legacy","publish","save","translate","translate_source","gen_alert"]};var p={};function h(){p._cache={}}p._isAuthCache=new h,p._pineDeleted=new r,l.on("TVScriptModified",(function(e){p.clearSavedScriptsCache(),p.scriptUpdater()&&p.scriptUpdater().onTVScriptModified(JSON.parse(e))})),l.on("TVScriptDeleted",(function(e){p.clearAllCaches(),p.scriptUpdater()&&p.scriptUpdater().onTVScriptDeleted(JSON.parse(e))})),l.on("TVScriptRenamed",(function(e){p.clearSavedScriptsCache(),p.scriptUpdater()&&p.scriptUpdater().onTVScriptRenamed(JSON.parse(e))})),l.on("TVScriptLegacyPineProcessed",(function(e){p.clearSavedScriptsCache(),p.scriptUpdater()&&p.scriptUpdater().onTVScriptLegacyPineProcessed(JSON.parse(e))})),p.PINE_FACADE_URL=function(){return window.PINE_URL},p.onPineDeleted=function(){return p._pineDeleted},p._pineFacadeAjax=function(e,t,n,r){c.logNormal("Requesting pine facade scripts, url: "+t);var o=function(e,t){for(var n=Object.keys(_),r=0;r<n.length;r++){var i=_[n[r]].filter((function(t){return-1!==e.indexOf(t)}));if(Boolean(i.length))return n[r]}return!1}(t),s=Date.now(),a=r?void 0:{withCredentials:!0};return i.ajax({url:p.PINE_FACADE_URL()+t,type:e,data:n||{},dataType:"json",xhrFields:a}).done((function(){var e=Date.now()-s;u.sendReport("pine",o+"_group_time_frame",{value:e}),u.sendReport("pine",o+"_group_ok"),c.logNormal("Requesting pine facade scripts finished, url: "+t)})).fail((function(){var e=Date.now()-s;u.sendReport("pine",o+"_group_time_frame",{value:e}),u.sendReport("pine",o+"_group_error"),c.logError("Requesting pine facade scripts failed, url: "+t)}))},p.convertScript=function(e,t){var n=i.Deferred(),r={source:e,version_to:t};return p._pineFacadeAjax("POST","/convert/",r).done((function(e,t,r){
e.error?n.reject(p._readableError(e.error)):n.resolve(e)})).fail((function(e,t,r){p._anyRequestAsyncFail(n,e)})),n.promise()},p.translateScriptAsync=function(e,t,n,r){a("Pine","ScriptLib.translateScript"),r=!!r;var o=i.Deferred(),s="/translate_source/"+encodeURIComponent(t)+"/?is_pine_ex="+r,l={user_name:window.user&&window.user.username,source:e,inputs:JSON.stringify(n||{})};return p._pineFacadeAjax("POST",s,l).done((function(e,t,n){p._translateScriptAsyncDone(o,e)})).fail((function(e,t,n){p._anyRequestAsyncFail(o,e)})),o.promise()},p.translateScriptAsync2=function(e,t){c.logNormal("translateScriptAsync2, pineId="+e+" pineVersion="+t),a("Pine","ScriptLib.translateScript");var n=i.Deferred(),r=0!==e.indexOf("USER"),o=window.user&&window.user.username,s="?user_name="+encodeURIComponent(o),u="/translate/"+encodeURIComponent(e)+"/"+t+"/";return r||null==o||(u+=s),p._pineFacadeAjax("GET",u,void 0,r).done((function(e,r,i){if(p._translateScriptAsyncDone(n,e),t<0){p.clearSavedScriptsCache();var o={scriptMetaInfo:e.result.metaInfo};l.emit("TVScriptLegacyPineProcessed",JSON.stringify(o)),d.emit("TVScriptLegacyPineProcessed",o),setTimeout((function(){o.isSelfCall=!0,null!=p.scriptUpdater()&&p.scriptUpdater().onTVScriptLegacyPineProcessed(o)}),0)}})).fail((function(e,t,r){p._anyRequestAsyncFail(n,e)})),n.promise()},p._translateScriptAsyncDone=function(e,t){if(t.error)e.reject(p._readableError(t.error));else if(t.success)e.resolve(t.result.metaInfo,t.result.IL);else{var n=t.result?t.result.metaInfo:null;e.reject(t.reason,n)}},p._saveScriptAsyncDone=function(e,t){if(t.error)e.reject(p._readableError(t.error));else if(t.success)e.resolve(t.result.metaInfo);else{var n=t.result?t.result.metaInfo:null;e.resolve(n,t.reason)}},p._generateAlertAsyncDone=function(e,t){if(t.error)e.reject(p._readableError(t.error));else if(t.success)e.resolve(t.result.metaInfo,t.result.IL,t.result.inputs||null,t.result.gen_alert_data||null);else{var n=t.result?t.result.metaInfo:null;e.reject(t.reason,n)}},p._readableError=function(e,t){return t},p._anyRequestAsyncFail=function(e,t){0===p.PINE_FACADE_URL().indexOf("http")&&c.logError(t.responseText),e.reject(p._readableError(t.status,t.statusText))},p.isAuthToWritePineScript=function(e){var t="write_"+e,n=p._isAuthCache.getPromise(t);if(null!==n)return n;a("Pine","ScriptLib.isAuthToWritePineScript");var r=i.Deferred(),o="/is_auth_to_write/"+encodeURIComponent(e);return p._pineFacadeAjax("GET",o).done((function(e,t,n){r.resolve(e)})).fail((function(e,t,n){p._anyRequestAsyncFail(r,e)})),p._isAuthCache.setPromise(t,r.promise())},p.isAuthToGetPineSourceCode=function(e,t){var n="get_"+e+"_"+t,r=p._isAuthCache.getPromise(n);if(null!==r)return r;a("Pine","ScriptLib.isAuthToGetPineSourceCode");var o=i.Deferred(),s="/is_auth_to_get/"+encodeURIComponent(e)+"/"+t;return p._pineFacadeAjax("GET",s).done((function(e,t,n){o.resolve(e)})).fail((function(e,t,n){p._anyRequestAsyncFail(o,e)})),p._isAuthCache.setPromise(n,o.promise())},h.prototype.getPromise=function(e){var t=p._cache[e]
;return void 0===t?null:void 0!==t.value?i.Deferred().resolve(t.value):void 0!==t.promise?t.promise:null},h.prototype.setPromise=function(e,t){return p._cache[e]={promise:t},t.done((function(t){p._cache[e]={value:t}})).fail((function(t){delete p._cache[e]})),t},p.getPineSourceCode=function(e,t,n){a("Pine","ScriptLib.getPineSourceCode");var r=i.Deferred(),o="?no_4xx="+!!n,s="/get/"+encodeURIComponent(e)+"/"+t+o;return p._pineFacadeAjax("GET",s).done((function(e,t,n){!1===e.success?r.reject(e.reason):r.resolve(e)})).fail((function(e,t,n){p._anyRequestAsyncFail(r,e)})),r.promise()},p.saveNewDraft=function(e){a("Pine","ScriptLib.saveNewDraft");var t=i.Deferred();if(null==e||""===e)return t.reject(o("Cannot save empty source code"));var n=window.user&&window.user.username,r="/save/new_draft/?user_name="+encodeURIComponent(n)+"&allow_use_existing_draft=true",s={source:e};return p._pineFacadeAjax("POST",r,s).done((function(e,n,r){p._translateScriptAsyncDone(t,e)})).fail((function(e,n,r){p._anyRequestAsyncFail(t,e)})),t.promise()},p.saveNextDraft=function(e,t,n){a("Pine","ScriptLib.saveNextDraft");var r=i.Deferred();if(null==t||""===t)return r.reject(o("Cannot save empty source code"));var s=window.user&&window.user.username,l=(n=!!n,"/save/next_draft/"+encodeURIComponent(e)+"/?user_name="+encodeURIComponent(s)+"&allow_create_new="+n),c={source:t};return p._pineFacadeAjax("POST",l,c).done((function(e,t,n){p._translateScriptAsyncDone(r,e)})).fail((function(e,t,n){p._anyRequestAsyncFail(r,e)})),r.promise()},p.processLegacy=function(e,t){a("Pine","ScriptLib.processLegacy");var n=i.Deferred(),r=window.user&&window.user.username,o="/process_legacy/"+encodeURIComponent(e)+"/?user_name="+encodeURIComponent(r),s={};return null!=t&&""!==t&&(s.source=t),p._pineFacadeAjax("POST",o,s).done((function(e,t,r){p._translateScriptAsyncDone(n,e)})).fail((function(e,t,r){p._anyRequestAsyncFail(n,e)})),n.promise()},p.generateAlert=function(e){a("Pine","ScriptLib.generateAlert");var t=i.Deferred(),n=window.user&&window.user.username,r="/gen_alert/?user_name="+encodeURIComponent(n),o={alert_info:e},s=Date.now();return p._pineFacadeAjax("POST",r,o).done((function(e,n,r){u.sendReport("alerts","compilation_ok"),p._generateAlertAsyncDone(t,e)})).fail((function(e,n,r){u.sendReport("alerts","compilation_error"),p._anyRequestAsyncFail(t,e)})).always((function(){var e=Date.now()-s;u.sendReport("alerts","compilation_time_frame",{value:e})})),t.promise()},p.parseScriptTitleAsync=function(e){a("Pine","ScriptLib.parseScriptTitle");var t=i.Deferred();if(null==e||""===e)return t.reject(o("Cannot save empty source code"));var n={user_name:window.user&&window.user.username,source:e};return p._pineFacadeAjax("POST","/parse_title/",n).done((function(e,n,r){e.error?t.reject(p._readableError(e.error)):e.success?t.resolve(e.result):t.reject(e.reason)})).fail((function(e){p._anyRequestAsyncFail(t,e)})),t.promise()},p.evalMetaInfoExprsAsync=function(e,t){a("Pine","ScriptLib.evalMetaInfoExprs");var n=i.Deferred(),r={username:window.user&&window.user.username,source:e,
inputs:JSON.stringify(t||{})};return p._pineFacadeAjax("POST","/eval_pine_ex/",r).done((function(e,t,r){e.error?n.reject(p._readableError(e.error)):e.success?n.resolve(e.result):n.reject(e.reason)})).fail((function(e){p._anyRequestAsyncFail(n,e)})),n.promise()},p.patchPropertiesAsync=function(e,t,n){return c.logNormal("patchPropertiesAsync"),new Promise((function(r,i){if(t.TVScriptMetaInfoExprs){var o=t.TVScriptMetaInfoExprs.tree,a=t.TVScriptMetaInfoExprs.patchMap;p.evalMetaInfoExprsAsync(o,n).done((function(t){for(var n=t.rootValues,i=Object.keys(a),o=0;o<i.length;o++){var l=i[o],c=n[a[l]],u=l.split(".");"defaults"===u[0]&&u.splice(0,1),s(u.length>1,"Unexpectedly short json path");for(var d=e,_=0;_<u.length-1;++_)d=d[u[_]];d[u[u.length-1]].setValue(c)}r(e)})).fail((function(e){i(e)}))}else r(e)}))},p.scriptUpdater=function(){return window.scriptUpdater},p.clearAllCaches=function(){p.clearIsAuthToCaches(),p.clearSavedScriptsCache()},p.clearIsAuthToCaches=function(e){e?Object.keys(p._cache).filter((function(t){return t.indexOf(e)>=0})).forEach((function(e){delete p._cache[e]})):p._isAuthCache=new h},p.clearSavedScriptsCache=function(e){delete p._userScriptsDfd},p.requestUserScripts=function(e){if(a("Pine","ScriptLib.requestUserScripts"),window.is_authenticated){if(!p._userScriptsDfd){p._userScriptsDfd=i.Deferred();var t=p._userScriptsDfd;p._pineFacadeAjax("GET","/list?filter=saved").done((function(e,n,r){t.resolve(e)})).fail((function(e){p._anyRequestAsyncFail(t,e)}))}t=p._userScriptsDfd}else t=i.Deferred().resolve([]);return"function"==typeof e&&t.done(e),t.promise()},p.setUserScripts=function(e){p._userScriptsDfd||(p._userScriptsDfd=i.Deferred().resolve(e))},p.requestUserPublishedScripts=function(e,t){if(a("Pine","ScriptLib.requestUserPublishedScripts"),window.is_authenticated){if(t||!p._userPublishedScriptsDfd){p._userPublishedScriptsDfd=i.Deferred();var n=p._userPublishedScriptsDfd;p._pineFacadeAjax("GET","/list?filter=published").done((function(e,t,r){n.resolve(e)})).fail((function(e){p._anyRequestAsyncFail(n,e)}))}n=p._userPublishedScriptsDfd}else n=i.Deferred().resolve([]);return"function"==typeof e&&n.done(e),n.promise()},p.requestPineEditorNewTemplateScripts=function(e){a("Pine","ScriptLib.requestPineEditorNewTemplateScripts");var t=i.Deferred();return p._pineFacadeAjax("GET","/list/?filter=template",void 0,!0).done((function(e,n,r){t.resolve(e)})).fail((function(e){p._anyRequestAsyncFail(t,e)})),"function"==typeof e&&t.done(e),t.promise()},p.requestInfoForScripts=function(e){return Promise.all([p._pineFacadeAjax("GET","/list?filter=saved"),p._pineFacadeAjax("GET","/list?filter=addon",void 0,!0)]).then((function(t){var n=t[0],r=t[1];return n.concat(r).filter((function(t){return e.includes(t.scriptIdPart)}))}))},p.requestBuiltinScripts=function(){a("Pine","ScriptLib.requestBuiltinScripts"),c.logNormal("Request built-in scripts");var e=i.Deferred();return p._pineFacadeAjax("GET","/list/?filter=standard",void 0,!0).done((function(t,n,r){c.logNormal("Request built-in scripts finished"),e.resolve(t)
})).fail((function(t){c.logWarn("Request built-in scripts finished with fail"),p._anyRequestAsyncFail(e,t)})),e.promise()},p.requestBuiltinAndUserScripts=function(){a("Pine","ScriptLib.requestBuiltinAndUserScripts"),c.logNormal("Request built-in and user scripts");var e,t=window.user&&window.user.username,n={},r=new Promise((function(t,r){e=t,n.reject=r}));return Promise.all([p._pineFacadeAjax("GET","/list?filter=saved&user_name="+encodeURIComponent(t),void 0,!1),p._pineFacadeAjax("GET","/list?filter=standard",void 0,!0)]).then((function(t){c.logNormal("Request built-in and user scripts finished");var n=t[0],r=t[1];e(n.concat(r))})).catch((function(e){c.logWarn("Request built-in and user scripts finished with fail"),p._anyRequestAsyncFail(n,e)})),r},p.requestCandlestickScripts=function(){var e;a("Pine","ScriptLib.requestCandlestickScripts"),c.logNormal("Request candlestick scripts");var t={},n=new Promise((function(n,r){e=n,t.reject=r}));return p._pineFacadeAjax("GET","/list?filter=candlestick",void 0,!0).done((function(t){c.logNormal("Request candlestick scripts finished"),e(t)})).fail((function(e){c.logWarn("Request candlestick scripts finished with fail"),p._anyRequestAsyncFail(t,e)})),n};var f={time:-1/0,request:null};p.requestFundamentalScripts=function(){if(f.time+6e5>Date.now()&&null!==f.request)return c.logNormal("Return fundamentals from cache"),f.request;c.logNormal("Request fundamental scripts");var e=p._pineFacadeAjax("GET","/list?filter=fundamental",void 0,!1);return e.then((function(e){c.logNormal("Request fundamental scripts finished")})),e.fail((function(e){c.logWarn("Request fundamental scripts finished with fail, resetting cache"),f.request=null})),f.time=Date.now(),f.request=Promise.resolve(e.promise()),f.request},p.requestPineAddons=function(e){a("Pine","ScriptLib.requestPineAddons");var t=i.Deferred();return p._pineFacadeAjax("GET","/list?filter=addon&pine_id_prefix="+e).done((function(e){t.resolve(e)})).fail((function(e){p._anyRequestAsyncFail(t,e)})),t},p._updateAliveScriptInstances=function(e,t){var n={};n.scriptMetaInfo=e.result.metaInfo,n.scriptVersionToUpdate=t,l.emit("TVScriptModified",JSON.stringify(n)),d.emit("TVScriptModified",n),setTimeout((function(){n.isSelfCall=!0,null!=p.scriptUpdater()&&p.scriptUpdater().onTVScriptModified(n)}),0)},p.saveNew=function(e,t,n,r){a("Pine","ScriptLib.saveNew");var s=i.Deferred();if(null==e||""===e)return s.reject(o("Cannot save empty source code"));var l=window.user&&window.user.username,c=n?"&allow_overwrite=true":"",u="/save/new/?name="+encodeURIComponent(t)+"&user_name="+encodeURIComponent(l)+c,d={source:e};return p._pineFacadeAjax("POST",u,d).done((function(e,t,n){p.clearSavedScriptsCache(),p._updateAliveScriptInstances(e,r),p._saveScriptAsyncDone(s,e)})).fail((function(e,t,n){p._anyRequestAsyncFail(s,e)})),s.promise()},p.saveNext=function(e,t,n,r,s){a("Pine","ScriptLib.saveNext");var l=null!=n?"&name="+encodeURIComponent(n):"",c=i.Deferred();if(null==t||""===t)return c.reject(o("Cannot save empty source code"))
;var u=window.user&&window.user.username,d="/save/next/"+encodeURIComponent(e)+"/?user_name="+encodeURIComponent(u)+"&allow_create_new="+!!s+l,_={source:t};return p._pineFacadeAjax("POST",d,_).done((function(e,t,n){p.clearSavedScriptsCache(),p._updateAliveScriptInstances(e,r),p._saveScriptAsyncDone(c,e)})).fail((function(e,t,n){p._anyRequestAsyncFail(c,e)})),c.promise()},p.deletePine=function(e){a("Pine","ScriptLib.deletePine");var t=i.Deferred(),n=window.user&&window.user.username,r="/delete/"+encodeURIComponent(e)+"/?user_name="+encodeURIComponent(n);return p._pineFacadeAjax("POST",r).done((function(n,r,i){p.clearIsAuthToCaches(e),p.clearSavedScriptsCache(),t.resolve(n);var o={scriptIdPart:e};l.emit("TVScriptDeleted",JSON.stringify(o)),d.emit("TVScriptDeleted",o),setTimeout((function(){o.isSelfCall=!0,null!=p.scriptUpdater()&&p.scriptUpdater().onTVScriptDeleted(o),p._pineDeleted.fire(e)}),0)})).fail((function(e,n,r){p._anyRequestAsyncFail(t,e)})),t.promise()},p.renamePine=function(e,t,n){a("Pine","ScriptLib.renamePine");var r=i.Deferred(),o=window.user&&window.user.username,s="/rename/"+encodeURIComponent(e)+"/?name="+encodeURIComponent(t)+"&user_name="+encodeURIComponent(o)+"&force="+encodeURIComponent(!!n);return p._pineFacadeAjax("POST",s).done((function(n,i,o){p.clearSavedScriptsCache();var s={scriptIdPart:e,scriptName:t};l.emit("TVScriptRenamed",JSON.stringify(s)),d.emit("TVScriptRenamed",s),setTimeout((function(){s.isSelfCall=!0,null!=p.scriptUpdater()&&p.scriptUpdater().onTVScriptRenamed(s)}),0),r.resolve(n)})).fail((function(e,t,n){p._anyRequestAsyncFail(r,e)})),r.promise()},p.publishNew=function(e,t){a("Pine","ScriptLib.publishNew");var n=i.Deferred(),r=window.user&&window.user.username,o="/publish/new/?access="+encodeURIComponent(t)+"&user_name="+encodeURIComponent(r),s={source:e};return p._pineFacadeAjax("POST",o,s).done((function(e,t,r){e.success?(p.clearSavedScriptsCache(),n.resolve(e)):n.reject(e.reason)})).fail((function(e,t,r){p._anyRequestAsyncFail(n,e)})),n.promise()},p.publishNext=function(e,t){c.logNormal("ScriptLib.publishNext","pine"),a("Pine","ScriptLib.publishNext");var n=i.Deferred(),r=window.user&&window.user.username,o="/publish/next/"+encodeURIComponent(t)+"?user_name="+encodeURIComponent(r),s={source:e};return p._pineFacadeAjax("POST",o,s).done((function(e,t,r){p.clearSavedScriptsCache(),e.success||n.reject(e.reason),n.resolve(e)})).fail((function(e,t,r){p._anyRequestAsyncFail(n,e)})),n.promise()},p.lightTranslate=function(e,t){return c.logNormal("ScriptLib.lightTranslate","pine"),a("Pine","ScriptLib.lightTranslate"),new Promise((function(n,r){var i=window.user&&window.user.username,o="/translate_light/?user_name="+encodeURIComponent(i);t&&(o+="&pine_id="+encodeURIComponent(t));var s={source:e};p._pineFacadeAjax("POST",o,s).done((function(e,t,i){if(e.success)n(e.result);else{var o=e.result&&e.result.reason||e.reason;r(o)}})).fail((function(e,t,n){p._anyRequestAsyncFail({reject:r},e)}))}))},p.getLibList=function(e,t,n){return c.logNormal("ScriptLib.getLibList","pine"),
a("Pine","ScriptLib.getLibList"),new Promise((function(r,i){var o="/lib_list?lib_id_prefix="+encodeURIComponent(e);t&&(o+="&ignore_cache=true"),n&&(o+="&ignore_case=true"),p._pineFacadeAjax("GET",o).done((function(e,t,n){r(e)})).fail((function(e,t,n){p._anyRequestAsyncFail({reject:i},e)}))}))},p.getExistingLibraryInfo=async function(e){try{const t=await p.getLibList(e+"/last",!0,!0);if(!t.length)return null;const n=t[0];return{scriptIdPart:n.scriptIdPart,chartId:n.chartId,version:n.version}}catch(e){return null}},loginStateChange.subscribe(p,p.clearAllCaches),e.exports=p},83050:(e,t,n)=>{"use strict";n.r(t),n.d(t,{collectDepsForAlert:()=>g,dependenciesForAlerts:()=>S,idForAlert:()=>f,patchChildIdInInputs:()=>h,plotsForAlert:()=>m});var r=n(88537),i=n(98125),o=n(85619);var s=Array.isArray||function(e){return"[object Array]"==={}.toString.call(e)},a=Object.keys||function(e){var t=Object.prototype.hasOwnProperty||function(){return!0},n=[];for(var r in e)t.call(e,r)&&n.push(r);return n},l=n(88145),c=n(67072),u=n.n(c),d=n(50993),_=n(80643);const p=(0,i.getLogger)("Chart.Study");function h(e,t,n){void 0!==t&&void 0!==n&&n.forEach(n=>{const r=e[n];if("string"==typeof r){const i=r.split("$")[1];e[n]=t+(void 0===i?"":"$"+i)}else if((0,_.isObject)(r)&&"source"===r.t){const e=r.v.split("$")[1];r.v=t+(void 0===e?"":"$"+e)}else p.logError("Cannot patch source input, its type is not source: "+JSON.stringify(r))})}function f(e,t,n){return(0,o.hash)(e+function(e,t){t||(t={}),"function"==typeof t&&(t={cmp:t});var n=t.space||"";"number"==typeof n&&(n=Array(n+1).join(" "));var r,i="boolean"==typeof t.cycles&&t.cycles,o=t.replacer||function(e,t){return t},l=t.cmp&&(r=t.cmp,function(e){return function(t,n){var i={key:t,value:e[t]},o={key:n,value:e[n]};return r(i,o)}}),c=[];return function e(t,r,u,d){var _=n?"\n"+new Array(d+1).join(n):"",p=n?": ":":";if(u&&u.toJSON&&"function"==typeof u.toJSON&&(u=u.toJSON()),void 0!==(u=o.call(t,r,u))){if("object"!=typeof u||null===u)return JSON.stringify(u);if(s(u)){for(var h=[],f=0;f<u.length;f++){var m=e(u,f,u[f],d+1)||JSON.stringify(null);h.push(_+n+m)}return"["+h.join(",")+_+"]"}if(-1!==c.indexOf(u)){if(i)return JSON.stringify("__cycle__");throw new TypeError("Converting circular structure to JSON")}c.push(u);var g=a(u).sort(l&&l(u));for(h=[],f=0;f<g.length;f++){var S=e(u,r=g[f],u[r],d+1);if(S){var y=JSON.stringify(r)+p+S;h.push(_+n+y)}}return c.splice(c.indexOf(u),1),"{"+h.join(",")+_+"}"}}({"":e},"",e,0)}(t)+(null!=n?n:"")).toString()}function m(e,t,n){const i=[d.isLinePlot,d.isShapesPlot,d.isCharsPlot,d.isArrowsPlot,d.isOhlcPlot,d.isAlertConditionPlot];return e.plots.map((e,t)=>({...e,pinePlotIndex:t})).filter(e=>!(void 0!==n&&!n.includes(e.id))&&i.some(t=>t(e))).map(n=>{const i={id:n.id,type:n.type,pinePlotIndex:n.pinePlotIndex,offset:t(n.id)};if(e.styles&&void 0!==e.styles[n.id]){const t=(0,r.ensureDefined)((0,r.ensureDefined)(e.styles)[n.id]);i.title=t.title||"",i.text=t.text||""}return(0,d.isOhlcPlot)(n)&&n.target&&e.ohlcPlots&&e.ohlcPlots[n.target]&&(i.ohlcTitle=(0,r.ensureDefined)((0,
r.ensureDefined)(e.ohlcPlots)[n.target]).title),i})}function g(e,t){const n=[];let i,o;for(let r=e.length-1;r>=0;r--){const s=e[r],a=(0,l.extractStudyId)(s.metaInfo().id),c=u().getStudyIdWithLatestVersion(s.metaInfo());o=s.inputsForAlertState();h(o,i,s.metaInfo().inputs.filter(e=>"source"===e.type).map(e=>e.id));const d=Object.assign({},o);s.metaInfo().isTVScript&&delete d.text;const _=f(a,d,t);n.push({id:_,study:c,inputs:o}),i=_}return{idForAlert:(0,r.ensureDefined)(i),inputsForAlert:(0,r.ensureDefined)(o),studyDependencies:n.reverse()}}function S(e,t){throw new Error("Not implemented")}},47806:(e,t,n)=>{"use strict";n.d(t,{AlertConditionTokenMapType:()=>r,getAlertConditionTokenMap:()=>l});n(94419);var r,i=n(28353),o=n(88537);!function(e){e[e.MainSeries=0]="MainSeries",e[e.Study=1]="Study",e[e.PineScript=2]="PineScript",e[e.Strategy=3]="Strategy",e[e.PineScriptAlertFunction=4]="PineScriptAlertFunction"}(r||(r={}));const s=(0,i.t)("Upper Bound: {alertChannelUpperBoundaryTitle}, Lower Bound: {alertChannelLowerBoundaryTitle}"),a=e=>(0,i.t)("in {count} bar",{plural:"in {count} bars",count:e}).format({count:e.toString()});function l(e){const t=(0,o.ensureDefined)(e.get("extra")),n=t.getAlertSeries(),i=t.conditionData();if("alerts"===i.type)return{type:r.PineScriptAlertFunction,scriptTitle:n.title({short:!0}),isStrategy:"StudyStrategy"===n.type()};if("StudyStrategy"===n.type())return{type:r.Strategy,strategyTitle:n.title()};if(["pine_script","pine_alertcondition_plot"].includes(i.type))return{type:r.PineScript,conditionTitle:i.title,conditionMessage:i.message};const l=e.getFormatter();function c(e){const t=e.getPlots();return e.title({formatter:l,withPlotTitle:t&&t.length>1})}let u="";switch(i.type){case"moving":const e=t.movingValue(),n=t.movingPeriod();u=i.percents?`${e}% ${a(n)}`:`${l?l.format(e):e} ${a(n)}`;break;case"comparison":if(i.isChannel){const e=c(t.getUpperBand()),n=c(t.getLowerBand());u=`(${s.format({alertChannelUpperBoundaryTitle:e,alertChannelLowerBoundaryTitle:n})})`}else u=c(t.getBand())}const d=t.getMainSeries(),_=d?d.title({withInterval:!e.get("crossInterval")}):e.shortSymbol();return{conditionTitle:i.descriptionTitle||i.title,conditionOptions:u,..."MainSeries"===n.type()?{type:r.MainSeries,alertSeries:_}:{type:r.Study,alertSeries:n.title(),mainSeries:_}}}},26187:(e,t,n)=>{"use strict";n.d(t,{alertEditorInvocationHandler:()=>l});var r=n(52714),i=n.n(r),o=n(99486),s=n(88537);class a{constructor(){this._state=new(i())(!1)}subscribe(e){this._state.subscribe(e)}unsubscribe(e){this._state.unsubscribe(e)}value(){return this._state.value()}abort(){this._state.setValue(!0)}}const l=new class{constructor(){this._dialogInvocations=new(i())(new Map)}getDialogInvocations(){return this._dialogInvocations}isAllowedToInvoke(e){return e.silent||!this._dialogInvocations.value().has(c(e))}lockInvocation(e){if(e.silent)return{unlockInvocation:()=>{}};const t=c(e),n=new a,r=new Map(this._dialogInvocations.value());return r.set(t,n),this._dialogInvocations.setValue(r),{abortSignal:n,unlockInvocation:()=>{
const e=new Map(this._dialogInvocations.value());e.delete(t),this._dialogInvocations.setValue(e)}}}};function c(e){return"create_alert"===(0,o.getAlertDialogType)(e)?-1:(0,s.ensureDefined)(e.alert).id}},21088:(e,t,n)=>{"use strict";n.d(t,{AlertExtraUpdateScheduler:()=>a});var r=n(87341),i=n(16509);const o=(0,n(98125).getLogger)("Alerts.ExtraUpdateScheduler"),s=clearTimeout;class a{constructor(){this._queue=new Map,this._taskHandle=null}scheduleUpdate(e){this._queue.set(e.id,e),this._maybeScheduleTask()}cancelUpdate(e){this._queue.delete(e),null!==this._taskHandle&&0===this._queue.size&&(s(this._taskHandle),this._taskHandle=null)}cancelAllUpdates(){this._queue.clear(),null!==this._taskHandle&&(s(this._taskHandle),this._taskHandle=null)}_maybeScheduleTask(){null===this._taskHandle&&0!==this._queue.size&&(this._taskHandle=setTimeout(async()=>{const e=this._queue.values().next().value;e&&(this._queue.delete(e.id),await function(e){return o.logDebug("Sending extra update request for alert "+e.id),(0,r.sendRequest)({method:"update_extra",params:(0,i.client2serverParams)(e)}).then(()=>o.logDebug("Extra has been updated successfully for alert "+e.id),t=>o.logWarn(`Could not update extra for alert ${e.id}: ${t}`))}(e)),this._taskHandle=null,this._maybeScheduleTask()},1e3))}}},35908:(e,t,n)=>{"use strict";function r(e=0){return e<1e3?e:e/1e3}function i(e,t){if(e.length>t){const n=/[\W]+$/g,r=e.substring(0,t),i=r.replace(n,"");return(i.length?i:r.substring(0,t-1))+"…"}return e}n.d(t,{ensureDurationInSeconds:()=>r,cutString:()=>i})},39193:(e,t,n)=>{"use strict";n.d(t,{alertsMaintenanceTracker:()=>s});var r=n(52714),i=n.n(r),o=n(76266);const s=new class{constructor(){this._state=new(i())((0,o.isFeatureEnabled)("alerts-maintenance"))}value(){return this._state.value()}subscribe(e){this._state.subscribe(e)}unsubscribe(e){this._state.unsubscribe(e)}sync(){this._state.setValue((0,o.isFeatureEnabled)("alerts-maintenance"))}}},53371:(e,t,n)=>{"use strict";var r;n.d(t,{DataSourceDangerReason:()=>r}),function(e){e.Spread="spread",e.PineRepainting="pine-repainting",e.CryptoCap="cryptocap"}(r||(r={}))},86811:(e,t,n)=>{"use strict";function r(e){return o().then(t=>t.hasUserAccessToDataSource(e))}function i(e){return o().then(t=>t.filterAccessibleDataSources(e))}n.d(t,{hasUserAccessToDataSource:()=>r,filterAccessibleDataSources:()=>i});const o=()=>n.e(3441).then(n.bind(n,57467))},78356:(e,t,n)=>{"use strict";n.d(t,{getAlertType:()=>o});const r=new Set(["study_Overlay","study_Compare","StudyStrategy"]);function i({type:e}){return!r.has(e)&&e.toLowerCase().startsWith("study")}function o(e){if(e.isDrawing())return"drawing";const t=e.get("extra"),n=null==t?void 0:t.alertSeries();return n&&t?n.isTVScriptStrategy?"strategy":t.bandsArray("object").some(i)?"indicator":"price":"price"}},84709:(e,t,n)=>{"use strict";var r=n(68647),i=n(55532),o=n(98125).getLogger("Alerts.Price.Abstract"),s=n(9315).getTranslatedResolution,a=n(82029),l=n(62820),c=r.Model.extend({constructor:function(e,t){e=this._prepareToSet(e,!0),r.Model.call(this,e,t)},
_prepareToSet:function(e,t){var n,r,i;if(e)for(n in e)e.hasOwnProperty(n)&&(r=e[n],"function"==typeof this[i="_prepareToSet_"+n]&&(e[n]=this[i](r,e,t)));return e},destroy:function(){this.stopListening(),this.trigger("destroy",this)},save:function(){o.logError("[Alerts] Use disaptcher to save")},shortSymbol:function(e){return a?a.shortName(e||this.get("symbol")||""):(o.logWarn("[Alerts] can't get short symbol"),e)},resolutionReadable:function(e){return(e=e||this.get("resolution"))?s(e):""},title:function(e){var t;return t=e?this.get("symbol"):this.shortSymbol(),this.get("crossInterval")||(t=l.isRtl()?t+" "+l.forceRTLStr(" ,"+this.resolutionReadable()):t+", "+this.resolutionReadable()),t},_formatDate:function(e){return i(e||new Date).format("MMM D LTS")}});e.exports=c},2495:(e,t,n)=>{"use strict";var r=n(28353).t,i=n(62591).isStudyStateForAlertType,o=n(50993),s=n(40264).generateTitleForGui,a=n(98125).getLogger("Alerts.Band"),l=n(37667),c=n(62820);TradingView="object"==typeof n.g?n.g.TradingView:TradingView||{};var u={create:function(e){var t,n=e||{},r=n.type;if("MainSeries"===r)t=_;else if(i(r,!0))t=p;else if("Value"===r)t=h;else{if(!/^LineTool.*/i.test(r))return a.logError("Unknown alert band type "+r),null;t=f}return new t(n)}};function d(e){this._band=e||{}}function _(){d.apply(this,arguments)}function p(){d.apply(this,arguments)}function h(){d.apply(this,arguments)}function f(){d.apply(this,arguments)}d.prototype.id=function(){return this._band.id},d.prototype.type=function(){return this._band.type},d.prototype.title=function(){return this._band.title},d.prototype.hasPlots=function(){return this._band.plots&&this._band.plots.length},d.prototype.getActualSymbol=function(){return this._band.actualSymbol},d.prototype.getSymbolString=function(){return this._band.symbolString},d.prototype.getPlotTitle=function(e){return e.title?e.title:o.isOhlcOpenPlot(e)?e.ohlcTitle+" "+r("Open"):o.isOhlcHighPlot(e)?e.ohlcTitle+" "+r("High"):o.isOhlcLowPlot(e)?e.ohlcTitle+" "+r("Low"):o.isOhlcClosePlot(e)?e.ohlcTitle+" "+r("Close"):"vol"===e.id?r("Volume"):"vol_ma"===e.id?r("Volume MA"):"open"===e.id?r("Open"):"high"===e.id?r("High"):"low"===e.id?r("Low"):"close"===e.id?r("Close"):e.id},d.prototype.getPlots=function(e){var t=e||{};if(!this._band.plots||!this._band.plots.length)return this._band.plots;if("inputSelect"===t.format){var n=-1;return this._band.plots.map((function(e){return{value:++n,title:this.getPlotTitle(e)}}),this)}return this._band.plots},d.prototype.hasUsualPlots=function(){var e=this._band.plots;return!e||e.filter(o.isAlertConditionPlot).length<e.length},d.prototype.getInputs=function(){return{}},inherit(_,d),_.prototype.title=function(e){var t=n(82029),r=e||{},i=!!r.withInterval,o=this._band.actualSymbol;return t&&(o=t.shortName(o)),s({symbol:o,interval:i?this._band.interval:null,style:this._band.style,inputs:this._band.styleInputs||{},boxSize:this._band.boxSize,reversalAmount:this._band.reversalAmount,sessionDescription:r.sessionDescription})},_.prototype.getInterval=function(){return this._band.interval},
_.prototype.getStyle=function(){return this._band.style},_.prototype.getStyleInputs=function(){return this._band.styleInputs},_.prototype.isRangeBasedStyle=function(){return l.isRangeBasedStyle(this._band.style)},_.prototype.isSpread=function(){return this._band.isSpread},_.prototype.sessionId=function(){return this._band.sessionId},_.prototype.sessionDescription=function(){return this._band.sessionDescription},_.prototype.getDividendsAdjustment=function(){return this._band.dividendsAdjustment},_.prototype.getBackAdjustment=function(){return this._band.backAdjustment},_.prototype.getSettlementAsClose=function(){return this._band.settlementAsClose},inherit(p,d),p.prototype.title=function(e){var t,n,i,o=e||{},s=o.withPlotTitle,a=this._band;return o.short&&a.shortTitle?t=a.shortTitle:a.title?t=a.title:(t=a.shortDescription||"Study",n=[],Object.keys(a.inputs).forEach((function(e){var t=a.inputs[e]&&a.inputs[e].id;t&&!a.inputs[e].isHidden&&void 0!==a.inputs[t]&&n.push(a.inputs[t])})),n.length&&(t+=" ("+n.join(", ")+")")),s&&(i=this.selectedPlot())&&(t+=" "+(i.title||r("Untitled Plot"))),c.isRtl()&&(t=c.forceLTRStr(t)),t},p.prototype.selectedPlot=function(){var e=this._band;return void 0===e.plotIndex?null:this.getPlots().filter((function(t){return t.value===e.plotIndex}))[0]||null},p.prototype.getInputs=function(){return this._band.inputs||{}},p.prototype.isTVLibrary=function(){return this._band.isTVLibrary||!1},inherit(h,d),h.prototype.title=function(e){var t=this._band.value||0;return e.formatter?e.formatter.format(parseFloat(t)):parseFloat(t).toString()},inherit(f,d),e.exports.AlertBandAbstract=d,e.exports.AlertBandValue=h,e.exports.AlertBandStudy=p,e.exports.alertBandFactory=u},37387:(e,t,n)=>{"use strict";var r=n(23127),i=n(28353).t,o=function(){function e(e,t){return t.id||(t.id=e),t}for(var t,n={cross:{title:i("Crossing"),type:"comparison"},crosses_from_below:{title:i("Crossing Up"),type:"comparison"},crosses_from_above:{title:i("Crossing Down"),type:"comparison"},above:{title:i("Greater Than"),type:"comparison"},below:{title:i("Less Than"),type:"comparison"},enters_channel:{title:i("Entering Channel"),isChannel:!0,type:"comparison"},leaves_channel:{title:i("Exiting Channel"),isChannel:!0,type:"comparison"},inside_channel:{title:i("Inside Channel"),isChannel:!0,type:"comparison"},outside_channel:{title:i("Outside Channel"),isChannel:!0,type:"comparison"},moving_up:{title:i("Moving Up"),type:"moving"},moving_down:{title:i("Moving Down"),type:"moving"},moving_up_percents:{title:i("Moving Up %"),descriptionTitle:i("Moving Up"),type:"moving",percents:!0},moving_down_percents:{title:i("Moving Down %"),descriptionTitle:i("Moving Down"),type:"moving",percents:!0}},o=Object.keys(n),s=o.length-1;s>=0;s--)e(t=o[s],n[t]);function a(t){var i,o,s,a,l,c,u={};t&&t.getStrategy()?o=t.prepareAlertConditions():(s=t&&t.drawing(),o=!t||t.getAlertSeries().hasUsualPlots()?n:{},s?c="LineToolVertLine"===s.type?function(e){return"cross"===e.id}:1===s.plots.length?function(e){return!e.isChannel}:2===s.plots.length?function(e){
return!!e.isChannel}:function(e){return"comparsion"===e.type}:t&&(t.hasAlertCondition()||t.hasAlertFunction())&&(o=r.extend(!0,{},o,t.prepareAlertConditions()))),i=Object.keys(o);for(var d=0;d<i.length;d++)e(l=i[d],a=o[l]),c&&!c(a)||(u[l]=a);return u}return t=null,{get:a,getData:function(e,t){var r;return(r=t?a(t)[e]:n[e])&&!r.id&&(r.id=e),r},defaults:function(e){return void 0!==e?n[e]:n},ordered:function(e,t){var n,r=a(e),i=["cross","crosses_from_below","crosses_from_above","above","below","enters_channel","leaves_channel","inside_channel","outside_channel","moving_up","moving_down","moving_up_percents","moving_down_percents"],o=["strategy_and_alerts","strategy","alerts"],s=[],l=Object.keys(r);t=t||{};for(var c=[],u=l.length-1;u>=0;u--){var d=r[l[u]];o.includes(d.type)&&c.push(d)}c.sort((function(e,t){return o.indexOf(e.id)-o.indexOf(t.id)})),c.length>0&&s.push(c);var _=[];for(u=l.length-1;u>=0;u--){d=r[l[u]];["pine_script","pine_alertcondition_plot"].includes(d.type)&&_.push(d)}_.sort((function(e,t){return e.title.localeCompare(t.title)})),_.length>0&&s.push(_);var p=e&&e.alertSeries&&e.alertSeries();if(!(p&&p.plots&&0===p.plots.length)){var h=[];for(u=0;u<i.length;u++)n=i[u],r.hasOwnProperty(n)&&h.push(r[n]);h.length>0&&s.push(h)}return t.isGrouped?s:s.flat()}}}();TradingView.AlertConditions=o,e.exports=o},82413:(e,t,n)=>{"use strict";var r=n(84709).extend({_prepareToSet_fireTime:function(e){return new Date(1e3*e)},_prepareToSet_barTime:function(e){return new Date(1e3*e)},_prepareToSet_alertId:function(e){return parseInt(e)},fireTimeReadable:function(){return this._formatDate(this.get("fireTime"))},fireTimeUnix:function(){return Math.round(this.get("fireTime").getTime()/1e3)}});e.exports=r},7298:(e,t,n)=>{"use strict";n.d(t,{AlertExtra:()=>m});var r=n(28353).t,i=n(98125).getLogger("Alerts.Extra"),o=n(98619).deepCopy,s=n(50993).isAlertConditionPlot,a=n(16654).STYLE_HEIKEN_ASHI,l=n(11372).cleanButAmpersand,c=n(28789).regExpEscape,u=n(62591),d=u.isStudyStateForAlertType,_=u.StateForAlertType;TradingView="object"==typeof n.g?n.g.TradingView:TradingView||{},"function"!=typeof TradingView.merge&&(TradingView.merge=function(e,t){for(var n in t)"object"==typeof t[n]&&e.hasOwnProperty(n)?TradingView.merge(e[n],t[n]):e[n]=t[n];return e});var p=n(37387),h=n(2495).alertBandFactory,f=n(52714);function m(e){this._data={},this.crossInterval=new f,this.update(e)}m.VERSION=22,m.prototype.update=function(e){return e=this._prepareExtraObject(e),m._isValidExtra(e)?(this._data=e||{},this._updateCrossInterval()):i.logError("Wrong alert extra"),this},m.prototype.addDatasourse=function(e,t){this._addDatasourseToJson(this._data,e,t)},m.prototype._addDatasourseToJson=function(e,t,n){(n||e.condition[t])&&(e.condition[t]={id:n.id,plotIndex:n.plotIndex},e.statesForAlert[n.id]=n,n.plotIndex&&delete e.statesForAlert[n.id].plotIndex)},m.prototype.getDependencies=function(){var e={};for(var t in this._data.statesForAlert)if(this._data.statesForAlert.hasOwnProperty(t)){var n=this._data.statesForAlert[t]
;d(n.type,!0)&&null!=n.studyDependencies&&n.studyDependencies.forEach((function(t){e[t.id]=t}))}return Object.keys(e).map((function(t){return e[t]})).map((function(e){return e.study=e.study.replace(/(\d)$/,"$1!"),e}))},m.prototype.updateDataSourseStates=function(){var e=this,t=this.getAvailableBands().map((function(t){return e._data.condition[t]})).filter((function(e){return!!e})).map((function(e){return e.id}));Object.keys(e._data.statesForAlert).filter((function(e){return t.indexOf(e)<0})).forEach((function(t){delete e._data.statesForAlert[t]}))},m.prototype._prepareExtraObject=function(e){if("string"==typeof e?e=JSON.parse(e):e instanceof m&&(e=e.toJSON()),m._isValidExtra(e))return e;var t=function(t){var n=p.defaults(e.conditionId||"cross");this._addDatasourseToJson(t,"mainSeries",e.mainSeries),this._addDatasourseToJson(t,"alertSeries",e.alertSeries),"moving"===n.type?(t.condition.movValue=Number(e.value),t.condition.movPeriod=Number(e.period)):"comparison"===n.type&&n.isChannel?(this._addDatasourseToJson(t,"upperBand",e.upperBand),this._addDatasourseToJson(t,"lowerBand",e.lowerBand)):"comparison"!==n.type||n.isChannel?["pine_script","pine_alertcondition_plot","strategy"].includes(n.type)||i.logError("[Alerts] Unknown condition type: "+n.type):this._addDatasourseToJson(t,"band",e.band)}.bind(this),n={version:m.VERSION,condition:{id:e.conditionId,fireInfo:e.fireInfo},statesForAlert:{}};return t(n),n},m.prototype.isValid=function(){return m._isValidExtra(this._data)},m._isValidExtra=function(e){var t=!!("object"==typeof e&&null!==e&&e.version>=m.VERSION&&e.statesForAlert&&e.condition&&e.condition.id&&e.condition.alertSeries&&e.condition.fireInfo&&(e.condition.fireInfo.type||e.condition.fireInfo.frequency));if(!t)return t;var n=Object.keys(e.statesForAlert);t=(t=t&&n.indexOf(e.condition.alertSeries.id)>=0)&&(!e.condition.mainSeries||n.indexOf(e.condition.mainSeries.id)>=0);var r=p.defaults(e.condition.id);r&&"comparison"===r.type&&!r.isChannel?t=(t=t&&!!e.condition.band)&&n.indexOf(e.condition.band.id)>=0:r&&"comparison"===r.type&&r.isChannel?t=(t=(t=(t=t&&!!e.condition.upperBand)&&!!e.condition.lowerBand)&&n.indexOf(e.condition.upperBand.id)>=0)&&n.indexOf(e.condition.lowerBand.id)>=0:r&&"moving"===r.type&&(t=(t=t&&!!e.condition.movPeriod)&&!!e.condition.movValue);const i=S(Object.values(e.statesForAlert));return i&&i.type!==_.StudyLineTool&&(t=t&&function(e){if(!Array.isArray(e))return!1;return e.every(e=>"number"==typeof e||"object"==typeof e&&g.every(([t,n])=>typeof e[t]===n))}(i.plots)),t},m.prototype._prepareToJSON=function(){for(var e=this.bandsObject(),t=Object.keys(e),n=0;n<t.length;n++){var r=e[t[n]];TradingView.isExistent(r.value)&&(r.value=String(r.value))}},m.prototype.toJSON=function(){return this._prepareToJSON(),o(this._data)},m.prototype.toGenAlertJSON=function(e){const t=this._patchDescription(e),n=this.toJSON();return n.message=t,n},m.prototype.state=m.prototype.toJSON,m.prototype.conditionData=function(){var e=this._data&&this._data.condition&&this._data.condition.id;if(e)return p.getData(e,this)
},m.prototype.bandsObject=function(e){return this._data.statesForAlert},m.prototype.bandsArray=function(e){var t=this;e=e||"object";return this.getAvailableBands().map((function(n){return t._getSomeBand(n,e)})).filter((function(e){return!!e}))},m.prototype.price=function(e){var t=this,n=t.conditionData();if(!n||"comparison"!==n.type)return null;function r(e,n){var r=t._getSomeBand(e,"object");r&&"Value"===r.type&&void 0!==n&&(r.value=parseFloat(n),t[e](r))}function i(e){var n=t._getSomeBand(e,"object");return n&&!isNaN(n.value)&&void 0!==n.value&&null!==n.value?parseFloat(n.value):null}if(void 0!==e&&(t.conditionData().isChannel?(r("upperBand",e.upperBand||e.upper),r("lowerBand",e.lowerBand||e.lower)):r("band",e.band||e),this._updateCrossInterval()),t.conditionData().isChannel){var o=i("upperBand"),s=i("lowerBand");return null===o||null===s?null:{upper:o,lower:s}}return i("band")},m.prototype.conditionId=function(e,t){if(void 0!==e){this._data.condition.id=e;var n=p.get(this)[e];if(n&&"pine_alertcondition_plot"===n.type){var r=this.alertSeries();r.plotIndex=n.plotIndex,this.alertSeries(r)}t||this._updateCrossInterval()}return this._data.condition.id};m.prototype._patchDescription=function(e){try{const t=["ohlc_open","ohlc_high","ohlc_low","ohlc_close","ohlc_colorer"],n=this.getAlertSeries().getPlots();if(n&&n.length>0){n.filter(e=>"alertcondition"!==e.type).forEach((n,r)=>{if(!t.includes(n.type)){const t=new RegExp(`{{plot\\("${c(l(n.title,!0))}"\\)}}`,"gm");e=e.replace(t,`{{plot_${r}}}`)}});for(let t=n.length;t<=20;t++)e=e.replace(`{{plot_${t}}}`,"null")}}catch(e){i.logError("AlertExtra._patchDescription error: "+e)}return e},m.prototype.getAvailableConditionParams=function(e){return["movPeriod","movValue"]},m.prototype.getAvailableOptionalBands=function(e){return["band","lowerBand","upperBand"]},m.prototype.getAvailableBands=function(e){return["band","lowerBand","upperBand","alertSeries","mainSeries"]},m.prototype.getAvailableOptionalConditions=function(e){return this.getAvailableOptionalBands().concat(this.getAvailableOptionalBands())},m.prototype.clearOptionalConditions=function(e){var t=this;this.getAvailableOptionalConditions().forEach((function(e){delete t._data.condition[e]})),this.updateDataSourseStates(),e||this._updateCrossInterval()},m.prototype.alertSeries=function(e,t){return void 0!==e&&(this.addDatasourse("alertSeries",e),this.updateDataSourseStates(),t||this._updateCrossInterval(),this.setValidConditionId()),this._getSomeBand("alertSeries","object")},m.prototype.getAlertSeries=function(e){return this._getSomeBand("alertSeries",e)},m.prototype.mainSeries=function(e,t){return void 0!==e&&(this.addDatasourse("mainSeries",e),this.updateDataSourseStates(),t||this._updateCrossInterval()),this._getSomeBand("mainSeries","object")},m.prototype.getMainSeries=function(e){return this._getSomeBand("mainSeries",e)},m.prototype._getSomeBand=function(e,t){var n,r=t||"model",i=this._data.condition[e];if(i)return n=TradingView.merge(this._data.statesForAlert[i.id],i),"object"===r?TradingView.merge({},n):h.create(n)},
m.prototype.upperBand=function(e,t){return void 0!==e&&(this.addDatasourse("upperBand",e),delete this._data.condition.band,this.updateDataSourseStates(),t||this._updateCrossInterval()),this._getSomeBand("upperBand","object")},m.prototype.getUpperBand=function(e){return this._getSomeBand("upperBand",e)},m.prototype.lowerBand=function(e,t){return void 0!==e&&(this.addDatasourse("lowerBand",e),delete this._data.condition.band,this.updateDataSourseStates(),t||this._updateCrossInterval()),this._getSomeBand("lowerBand","object")},m.prototype.getLowerBand=function(e){return this._getSomeBand("lowerBand",e)},m.prototype.band=function(e,t){return void 0!==e&&(this.addDatasourse("band",e),delete this._data.condition.upperBand,delete this._data.condition.lowerBand,this.updateDataSourseStates(),t||this._updateCrossInterval()),this._getSomeBand("band","object")},m.prototype.getBand=function(e){return this._getSomeBand("band",e)},m.prototype.value=function(e,t){return void 0!==e&&(this._data.condition.movValue=Number(e),t||this._updateCrossInterval()),this._data.condition.movValue},m.prototype.movingValue=m.prototype.value,m.prototype.period=function(e,t){return void 0!==e&&(this._data.condition.movPeriod=Number(e),t||this._updateCrossInterval()),this._data.condition.movPeriod},m.prototype.movingPeriod=m.prototype.period,m.prototype._updateCrossInterval=function(){var e=this.getAlertSeries(),t=null!==this.price()&&e&&"MainSeries"===e.type()&&!(e.isRangeBasedStyle()||e.getStyle()===a)&&!e.isSpread();this.crossInterval.setValue(t)},m.prototype.frequency=function(e){return-1!==["once","on_first_fire","on_bar_close","60"].indexOf(e)&&(this._data.condition.fireInfo.frequency=e),this._data.condition.fireInfo.frequency},m.prototype.hasAlertCondition=function(){var e=this.alertSeries();return Boolean(e.plots&&e.plots.some(s)||e.alerts&&e.alerts.conditions)},m.prototype.hasAlertFunction=function(){return Boolean(this.alertSeries().hasAlertFunction)},m.prototype.prepareAlertConditions=function(){var e=this.alertSeries(),t={};if(!e)return t;const n=Boolean(e.isTVScriptStrategy),i=Boolean(e.hasAlertFunction);if(n&&i)return{strategy_and_alerts:{type:"strategy_and_alerts",title:r("Order fills and alert() function calls")},strategy:{type:"strategy",title:r("Order fills only")},alerts:{type:"alerts",title:r("alert() function calls only")}};if(n)return{strategy:{title:null,type:"strategy"}};if(i&&Object.assign(t,{alerts:{type:"alerts",title:r("Any alert() function call")}}),e.plots)for(var o=0;o<e.plots.length;o++){var a=e.plots[o];if(s(a))t["alertplot_"+o]={title:a.title,message:a.text,type:"pine_alertcondition_plot",plotIndex:o}}if(e.alerts&&e.alerts.conditions)for(var l in e.alerts.conditions)t[l]=e.alerts.conditions[l],t[l].type="pine_script";return t},m.prototype.drawing=function(e){if(e&&e.canHasAlert()){var t=e.stateForAlert(),n=t.plots,r=!!this.conditionData().isChannel;if((1===n.length?!r:r)&&"comparison"===this.conditionData().type)if(1===n.length){var o={};(o=TradingView.merge(o,t)).plotIndex=0,this.band(o)}else{var s={},a={}
;(s=TradingView.merge(s,t)).plotIndex=0,this.upperBand(s),(a=TradingView.merge(a,t)).plotIndex=1,this.lowerBand(a)}else i.logError("[Alerts] Can't set drawing to alert with current condition")}return S(this.bandsArray())},m.prototype.getStrategy=function(){for(var e=this.bandsArray(),t=0;t<e.length;t++){if(e[t].isTVScriptStrategy)return e[t]}return null},m.prototype.setValidConditionId=function(){var e=this.conditionId(),t=p.get(this);t[e]||this.conditionId(Object.keys(t)[0])},m.prototype.verticalLine=function(){var e=this.drawing();return e&&1===e.plots.length&&e.plots[0].offset1&&e.plots[0].offset1===e.plots[0].offset2?e:null};const g=Object.entries({timestamp:"number",offset1:"number",offset2:"number",price1:"number",price2:"number",extendBackward:"boolean",extendForward:"boolean"});function S(e){return e.find(e=>e.type===_.StudyLineTool||/^LineTool.*/i.test(e.type))||null}TradingView.AlertExtra=m},71021:(e,t,n)=>{"use strict";var r=n(7298).AlertExtra,i=n(62591).isStudyStateForAlertType,o=n(67072),s=n(31752),a=n(88145).extractStudyId,l=n(14905).extractPineId,c=n(95379).prepareCallStudyArgs,u=n(9423),d=n(98125).getLogger("Alerts.Versioning"),_=n(99543),p=n(83050);const{hash:h}=n(85619);var f=n(37387),m=n(37667),g=n(53371).DataSourceDangerReason,S=n(21088).AlertExtraUpdateScheduler,y=n(76266).isFeatureEnabled;function v(){this._extraUpdateScheduler=new S}v.version_10_tv_6611_1a_refactoring=10,v.version_11_tv_6611_1b_refactoring=11,v.version_12_tv_6888_fix_plot_index=12,v.version_13_tv_4164_source_code_protection=13,v.version_14_tv_4164_source_code_protection_fix=14,v.version_15_tv_8068_fix_main_series_resolution=15,v.version_16_jv_298_remove_callstudy=16,v.version_17_jv_646_fix_mixed_inputs=17,v.version_18_tv_10636_price_format=18,v.version_19_tv_11267_fix_frequency_options=19,v.version_20_tv_14463_extract_dividends_adjustment_from_symbol_string=20,v.version_21_tv_14886_add_alert_dangerous_source_check=21,v.version_22_tv_23957_remove_text_input_from_pine_studies=22,v.prototype.migrate=function(e,t){var n;if(t=Object.assign({sendExtraUpdate:y("alerts-send-extra-update")},t),!e||!e.extra)return Promise.resolve(e);if((n=JSON.parse(e.extra))&&!Object.keys(n).length&&n.constructor===Object)return delete e.extra,Promise.resolve(e);var i=Promise.resolve(e),o=null==n.version||n.version<r.VERSION;return o&&(i=this._patchAlert(n,e)),i=i.then(function(e){var n=JSON.parse(e.extra);return n.version<r.VERSION?d.logError("Alert version is less than current"):n.version>r.VERSION?d.logNormal("Alert version is greater than current"):o&&t.sendExtraUpdate&&this._extraUpdateScheduler.scheduleUpdate({id:e.id,instanceId:e.instanceId,extra:e.extra}),e}.bind(this))},v.prototype._patchAlert=function(e,t){var n=this;e.version||(e.version=1);var r=e.version;r<v.version_10_tv_6611_1a_refactoring&&(e.condition.mainSeries=this._patchBand_to10(e.condition.mainSeries,t.symbol),e.condition.options.band&&(e.condition.options.band=this._patchBand_to10(e.condition.options.band,t.symbol)),
e.condition.options.upperBand&&(e.condition.options.upperBand=this._patchBand_to10(e.condition.options.upperBand,t.symbol)),e.condition.options.lowerBand&&(e.condition.options.lowerBand=this._patchBand_to10(e.condition.options.lowerBand,t.symbol)),e.version=v.version_10_tv_6611_1a_refactoring),r<v.version_11_tv_6611_1b_refactoring&&(e=this._patchExtra_to11(e)),r<v.version_12_tv_6888_fix_plot_index&&(e=this._patchExtra_to12(e)),r<v.version_13_tv_4164_source_code_protection&&(e=this._patchExtra_to13(e,t)),r<v.version_14_tv_4164_source_code_protection_fix&&(e=this._patchExtra_to14(e,t)),r<v.version_15_tv_8068_fix_main_series_resolution&&(e=this._patchExtra_to15(e,t)),t.extra=JSON.stringify(e);var i=Promise.resolve(t);return r<v.version_16_jv_298_remove_callstudy&&(i=i.then((function(e){return n._patchAlert_to16(e)}))),r<v.version_17_jv_646_fix_mixed_inputs&&(i=i.then((function(e){var t=JSON.parse(e.extra),r=n._patchExtra_to17(t);return e.extra=JSON.stringify(r),e}))),r<v.version_18_tv_10636_price_format&&(i=i.then((function(e){var t=JSON.parse(e.extra),r=n._patchExtra_to18(t);return e.extra=JSON.stringify(r),e}))),r<v.version_19_tv_11267_fix_frequency_options&&(i=i.then((function(e){return n._patchAlert_to19(e)}))),r<v.version_20_tv_14463_extract_dividends_adjustment_from_symbol_string&&(i=i.then((function(e){var t=JSON.parse(e.extra),r=n._patchExtra_to20(t);return e.extra=JSON.stringify(r),e}))),r<v.version_21_tv_14886_add_alert_dangerous_source_check&&(i=i.then((function(e){var t=JSON.parse(e.extra),r=n._patchExtra_to21(t);return e.extra=JSON.stringify(r),e}))),r<v.version_22_tv_23957_remove_text_input_from_pine_studies&&(i=i.then((function(e){var t=JSON.parse(e.extra),r=n._patchExtra_to22(t);return e.extra=JSON.stringify(r),e}))),i},v.prototype.cancelPossibleExtraUpdate=function(e){this._extraUpdateScheduler.cancelUpdate(e)},v.prototype.cancelAllPossibleExtraUpdates=function(){this._extraUpdateScheduler.cancelAllUpdates()},v.prototype._patchBand_to10=function(e,t){return e=this._patchBand_to10_callStudyArgs(e),e=this._patchBand_to10_stateForAlert(e,t)},v.prototype._patchBand_to10_callStudyArgs=function(e){var t=e&&"Study"===e.type,n=t&&(e.alertsData||{}).callStudyArgs,r=t&&e.metaInfo&&e.state&&e.state.inputs;return t&&!n&&r?(e.alertsData||(e.alertsData={}),e.alertsData.callStudyArgs=c(e.state.inputs,e.metaInfo),e):e},v.prototype._patchBand_to10_stateForAlert=function(e,t){var n,r;if(!e)return e;if(r=!e.state,"MainSeries"!==(n=e.type)||r){if(i(n,!1)&&!r){var o=e.metaInfo.plots.map((function(t){var n={id:t.id,type:t.type,offset:e.data.completePlotOffsets[t.id]};return e.metaInfo.styles&&void 0!==e.metaInfo.styles[t.id]&&(n.title=e.metaInfo.styles[t.id].title||""),t.target&&e.metaInfo.ohlcPlots&&e.metaInfo.ohlcPlots[t.target]&&(n.ohlcTitle=e.metaInfo.ohlcPlots[t.target].title),n}));return{id:e.id,uniqueId:e.uniqueId,type:e.type,title:"",shortDescription:e.state.shortDescription||"Study",fullId:e.metaInfo.fullId,isTVScript:!!e.metaInfo.isTVScript,plots:o,inputs:e.state.inputs,alerts:e.metaInfo.alerts,
callStudyArgs:e.alertsData.callStudyArgs,plotIndex:e.plotIndex,plotOffset:e.plotOffset}}return e}return{id:e.id,uniqueId:e.uniqueId,type:e.type,proSymbol:e.state.symbol||t,actualSymbol:t,interval:e.state.interval,style:e.state.style,styleInputs:function(){var t={0:"bar",1:"candle",2:"line",3:"area",4:"renko",5:"kagi",6:"pnf",7:"pb",8:"ha",9:"hollowCandle"}[e.state.style];if(t){var n=e.state[t+"Style"];if(n)return n.inputs}}(),sessionId:e.state.sessionId,boxSize:e.boxSize,reversalAmount:e.reversalAmount}},v.prototype._patchExtra_to11=function(e){var t=function(e,t,n){n.id=n.id||u.randomHashN(6),e.condition[t]={id:n.id,plotIndex:n.plotIndex},e.statesForAlert[n.id]=n},n={version:v.version_11_tv_6611_1b_refactoring,condition:{id:e.condition.id,fireInfo:{frequency:e.frequency||"once"},movPeriod:e.condition.options.period,movValue:e.condition.options.value},statesForAlert:{}};t(n,"alertSeries",e.condition.mainSeries);return["band","upperBand","lowerBand"].filter((function(t){return!!e.condition.options[t]})).forEach((function(r){t(n,r,e.condition.options[r])})),n},v.prototype._patchExtra_to12=function(e){return["alertSeries","band","upperBand","lowerBand"].filter((function(t){return!!e.condition[t]&&void 0!==e.condition[t].plotIndex})).map((function(t){var n=e.condition[t];return{state:e.statesForAlert[n.id],plotIndex:n.plotIndex}})).filter((function(e){return!!e.state.plots})).forEach((function(e){var t=e.state.plots[e.plotIndex];null==t||"object"!=typeof t&&"function"!=typeof t||void 0===t.pinePlotIndex&&(t.pinePlotIndex=e.plotIndex)})),e.version=v.version_12_tv_6888_fix_plot_index,e},v.prototype._patchExtra_to13=function(e,t){var n=e;if(!e.condition.mainSeries){if("MainSeries"===e.statesForAlert[e.condition.alertSeries.id].type)n.condition.mainSeries=n.condition.alertSeries;else{var r=u.randomHashN(6);n.condition.mainSeries={id:r},n.statesForAlert[r]={id:r}}n.statesForAlert[n.condition.mainSeries.id].symbolString=t.symbol}for(var i in e.statesForAlert){var s=e.statesForAlert[i];s.fullId&&(s.scriptIdPart=o.parseIdString(s.fullId).shortId.split("$")[1])}return n.version=v.version_13_tv_4164_source_code_protection,n},v.prototype._patchExtra_to14=function(e,t){var n=e;return e.condition.mainSeries||("MainSeries"===e.statesForAlert[e.condition.alertSeries.id].type?n.condition.mainSeries=n.condition.alertSeries:(n.condition.mainSeries={id:u.randomHashN(6)},n.statesForAlert[n.condition.mainSeries.id]={})),null==n.statesForAlert[n.condition.mainSeries.id].symbolString&&(n.statesForAlert[n.condition.mainSeries.id].symbolString=t.symbol),n.version=v.version_14_tv_4164_source_code_protection_fix,n},v.prototype._patchExtra_to15=function(e,t){var n=e;return null==n.statesForAlert[n.condition.mainSeries.id].interval&&(n.statesForAlert[n.condition.mainSeries.id].interval=t.resolution),n.version=v.version_15_tv_8068_fix_main_series_resolution,n},v.prototype._patchAlert_to16=function(e){var t=JSON.parse(e.extra);function n(e){return e.replace(/tv-scripting-1!?$/,"tv-scripting-88")}function r(t){return(r=t,i=o.cutDollarHash(r.fullId),
s=v._recoverFullInputs(r.fullId,r.pineId,r.pineVersion,r.inputs).then((function(e){return{id:p.idForAlert(a(r.fullId),e),study:n(i),inputs:e}})),l=new Promise((function(e,t){var i=JSON.parse(r.callStudyDependencies||"[]").map((function(e){return v._recoverFullInputs(null,e.scriptIdPart,e.scriptVersion,e.inputs).then((function(t){return{id:e.id,study:n(e.study),inputs:t}}))}));Promise.all(i).then((function(t){e(t)}),t)})),s.then((function(e){return l.then((function(t){return[e].concat(t)}))}))).then((function(n){t.studyDependencies=n;var r=n[0];t.id=r.id,t.uniqueId=t.id,e.scriptDeps=e.scriptDeps.concat(n)}));var r,i,s,l}e.scriptDeps=[];var s=[];for(var l in t.statesForAlert)if(t.statesForAlert.hasOwnProperty(l)){var c=t.statesForAlert[l];if("MainSeries"===c.type)c.id=h(c.symbolString+c.interval).toString(),c.uniqueId=c.id;else if(i(c.type,!1)){var u=r(c);s.push(u)}else/^LineTool.*/i.test(c.type)&&(c.id=c.uniqueId)}return Promise.all(s).then((function(){return function(e){var t={},n={};Object.keys(e.statesForAlert).forEach((function(r){var i=e.statesForAlert[r].id;t[r]=i,n[i]=e.statesForAlert[r]})),Object.keys(e.condition).filter((function(n){return null!=e.condition[n].id&&null!=t[e.condition[n].id]})).forEach((function(n){e.condition[n].id=t[e.condition[n].id]})),e.statesForAlert=n}(t),t.version=v.version_16_jv_298_remove_callstudy,e.extra=JSON.stringify(t),e}))},v.prototype.patchAlert_to16_forTestsOnly=v.prototype._patchAlert_to16,v.prototype._patchExtra_to17=function(e){for(var t in e.statesForAlert)if(e.statesForAlert.hasOwnProperty(t)){var n=e.statesForAlert[t],r=n.inputs;if(null!=r&&(n.inputs=s.splitInputs(r).obj),null!=n.studyDependencies)for(var i=0;i<n.studyDependencies.length;i++){var o=n.studyDependencies[i];o.inputs=s.splitInputs(o.inputs).obj}}return e.version=v.version_17_jv_646_fix_mixed_inputs,e},v.prototype.patchExtra_to17_forTestsOnly=v.prototype._patchExtra_to17,v._recoverFullInputs=function(e,t,n,r){if(t=t||e&&l(e)||r.pineId,n=n||r.pineVersion||"-1",null==t)return Promise.resolve(r);var i=_.translateScriptAsync2(t,n);return new Promise((function(e,t){i.then(e,t)})).catch((function(e){if("-1"===n&&t.startsWith("USER")){var i=function(e){var t={};return Object.keys(e).forEach((function(n){var r,i=e[n];n.startsWith("in_")?(r=["open","high","low","close","hl2","hlc3","ohlc4"].indexOf(i)>0||/.*\$\d+/.test(i)?"source":"string"==typeof i?"string":"boolean"==typeof i?"bool":"float",t[n]={f:!0,v:i,t:r}):t[n]=i})),t}(r);return d.logNormal("A very rare case: alert on legacy script that was never resaved. Trying to guess input types \n\t"+JSON.stringify(r)+" -> "+JSON.stringify(i)),i}return d.logError("Alert migration failed, inputs cannot be migrated: "+JSON.stringify(e)),Promise.reject(e)})).then((function(e){return TVScript.patchInputs(e.inputs,r)}))},v.prototype._patchExtra_to18=function(e){var t,n={},r=f.getData(e.condition.id);if(r&&"comparison"===r.type)if(r.isChannel){var i=e.statesForAlert[e.condition.upperBand.id],o=e.statesForAlert[e.condition.lowerBand.id]
;"Value"===i.type?t=i.value:"Value"===o.type&&(t=o.value)}else{var s=e.statesForAlert[e.condition.band.id];"Value"===s.type&&(t=s.value)}if(t&&-1!==(t=t.toString().replace(/^-/,"")).indexOf(".")){var a=t.replace(/^\d+\./,"").length,l=Math.pow(10,a);n.priceScale=l}var c=e.condition.alertSeries.id;return e.statesForAlert[c].formatter={type:"price",state:n},e.version=v.version_18_tv_10636_price_format,e},v.prototype._patchAlert_to19=function(e){var t=JSON.parse(e.extra),n=e.autoDeactivation,r=t.condition.fireInfo.frequency,i=t.statesForAlert[t.condition.mainSeries.id],o=["band","lowerBand","upperBand"].map((function(e){var n=t.condition[e];return n&&t.statesForAlert[n.id]})).filter((function(e){return!!e})).filter((function(e){return"LineToolVertLine"===e.type})).length>0,s=m.hasProjection(i.style),a=e.crossInterval,l=[];function c(e){return-1!==l.indexOf(e)}return o?l.push("once"):(a||s||(l.push("once"),l.push("60"),l.push("on_bar_close")),s?l.push("on_bar_close"):l.push("on_first_fire")),"once_per_bar"===r&&(r="on_first_fire"),"once"!==r||c("once")||(n=!0,r=l[0]),"once"!==r&&n&&(r=l[0]),"once"!==r&&o&&(n=!0,r="once"),"on_bar_close"===r&&!c("on_bar_close")&&c("on_first_fire")&&(r="on_first_fire"),e.autoDeactivation=n,t.condition.fireInfo.frequency=r,t.version=v.version_19_tv_11267_fix_frequency_options,e.extra=JSON.stringify(t),e},v.prototype._patchExtra_to20=function(e){var t=e.condition.mainSeries,n=e.statesForAlert,r=t&&n&&n[t.id];if(r){var i=r.symbolString;if(i&&0===i.indexOf("=")){var o=i.slice(1);"dividends"===(o=JSON.parse(o)).adjustment?r.dividendsAdjustment=!0:"splits"===o.adjustment&&(r.dividendsAdjustment=!1)}}return e.version=v.version_20_tv_14463_extract_dividends_adjustment_from_symbol_string,e},v.prototype.patchExtra_to20_forTestsOnly=v.prototype._patchExtra_to20,v.prototype._patchExtra_to21=function(e){var t=e.statesForAlert;for(var n in t)if(t.hasOwnProperty(n)){var r=t[n];r.isSpread&&(r.dangerReason=g.Spread)}return e.version=v.version_21_tv_14886_add_alert_dangerous_source_check,e},v.prototype._patchExtra_to22=function(e){var t=e.statesForAlert,n=!0;for(var r in t){if(t.hasOwnProperty(r))if(("Study"===(s=t[r]).type||"StudyStrategy"===s.type)&&s.isTVScript&&1!==s.studyDependencies.length){n=!1;break}}if(n){var i={},o={};for(var r in t){var s;if(t.hasOwnProperty(r))if("Study"!==(s=t[r]).type&&"StudyStrategy"!==s.type||!s.isTVScript)i[r]=s;else{var l=s.uniqueId,c=Object.assign({},s.inputs);s.isTVScript&&delete c.text;var u=p.idForAlert(a(s.fullId),c);s.id=u,s.uniqueId=u,s.studyDependencies[0].id=u,i[u]=s,o[l]=u}}e.statesForAlert=i,e.condition.alertSeries.id=o[e.condition.alertSeries.id]||e.condition.alertSeries.id,e.condition.band&&(e.condition.band.id=o[e.condition.band.id]||e.condition.band.id),e.condition.upperBand&&(e.condition.upperBand.id=o[e.condition.upperBand.id]||e.condition.upperBand.id),e.condition.lowerBand&&(e.condition.lowerBand.id=o[e.condition.lowerBand.id]||e.condition.lowerBand.id)}return e.version=v.version_22_tv_23957_remove_text_input_from_pine_studies,e},e.exports={
AlertVersioning:v}},25531:(e,t,n)=>{"use strict";var r=n(25977),i=n(23127),o=n(84709),s=n(7298).AlertExtra,a=n(64021).FormattersSerializer,l=n(82520).AlertFrequencyController,c=n(9315).getServerInterval,u=n(35908).ensureDurationInSeconds,d=n(47806).getAlertConditionTokenMap,_=n(12444).getAlertDefaultDescription,p=n(28995).getAlertDefaultName,h=n(78356).getAlertType,f=["crossInterval","autoDeactivation","description","sendEmail","expired","extra","showPopup","resolution","script","scriptDeps","sendSms","sendPush","playSound","soundDuration","soundFile","symbol","noExpiration","symbolInternal","webhookUrl","name","alertType"],m=f.concat(["id"]),g=o.extend({constructor:function(e,t){var n={};["autoDeactivation","frequency","extra","crossInterval","alertType"].forEach((function(t){e.hasOwnProperty(t)&&(n[t]=e[t],delete e[t])})),r.isEmpty(n)||(this.__delayedInitAttrs=n),e.version=e.version||s.VERSION,o.call(this,e,t),this.frequencyController=new l(this)},initialize:function(){var e=this;function t(t){e.set("crossInterval",!!t)}this.on("change:extra",(function(e,n,r){n&&(n.crossInterval.unsubscribe(t),n.crossInterval.subscribe(t),e.set("crossInterval",n.crossInterval.value()),e.syncAlertType())})).on("change:crossInterval",(function(e,t,n){var r=e.get("extra");t?e.set("resolution","1"):r&&r.mainSeries()&&e.set("resolution",r.mainSeries().interval)})).on("destroy",(function(){TVSettings.remove(e.TVSettingsPropertiesKey(e.id))})),this.__delayedInitAttrs&&(this.set(this.__delayedInitAttrs),delete this.__delayedInitAttrs)},set:function(e,t,n){var r;return null==e?this:(n=n||{}).noPrepare?o.prototype.set.call(this,e,t,n):("object"==typeof e?(r=e,n=t):(r={})[e]=t,r=this._prepareToSet(r),o.prototype.set.call(this,r,n))},_prepareToSet_soundDuration:function(e){e=parseInt(e);return isNaN(e)&&(e=0),u(e)},_prepareToSet_expired:function(e){return e instanceof Date?e:new Date(1e3*e)},_prepareToSet_extra:function(e){var t=this.get("extra"),n=e&&!(e instanceof s);return t&&e?e=t.update(e):n?(e=new s(e),this.set("scriptDeps",e.getDependencies())):e||(e=null),e},_prepareToSet_symbolInternal:function(e){if(e)return e},_prepareToSet_alertType:function(e){return"undefined"===e?h(this):e},isPrice:function(){return null!==(this.get("extra")?this.get("extra").price():null)},isDrawing:function(){return!(!this.get("extra")||!this.get("extra").drawing())},isMoving:function(){return this.get("extra")&&"moving"===(this.get("extra").conditionData()||{}).type},isOHLC:function(){var e=this.get("extra");if(e&&e.alertSeries())return"MainSeries"===e.alertSeries().type},isRangeBasedStyle:function(){var e=this.get("extra"),t=e&&e.getMainSeries();return!(!t||"MainSeries"!==t.type()||!t.isRangeBasedStyle())},isComplexSymbol:function(){var e=this.get("symbolInternal");return e!==this.get("symbol")&&e},isPine:function(){var e=this.get("extra"),t=e&&e.alertSeries();return t&&t.alerts},expiredUnix:function(){return Math.round(this.get("expired").getTime()/1e3)},defaultDescription:function(){return _(d(this))},defaultName:function(){return p(d(this))},
setDefaultDescription:function(){this.set("description",this.defaultDescription())},state:function(){return this.toJSON()},toJSON:function(){var e,t,n={};for(e in this.attributes)this.attributes.hasOwnProperty(e)&&(t=this.attributes[e],n[e]=t&&"function"==typeof t.toJSON?t.toJSON():t);return n.expired&&(n.expired=this.expiredUnix()),n},prepareToSend:function(){this.syncAlertType(),this.syncScriptDeps();for(var e,t,n=this.toJSON(),r={},i=m.length-1;i>=0;i--)void 0!==(t=n[e=m[i]])&&(r[e]=t),"resolution"===e&&(r[e]=c(t));return r.playSound||(delete r.soundDuration,delete r.soundFile),r.name||delete r.name,r.extra&&(r.extra=JSON.stringify(r.extra)),r},getLocalClone:function(){var e=this.toJSON(),t=f.reduce((function(t,n){return e.hasOwnProperty(n)&&(t[n]=e[n]),t}),{});return new g(t)},saveState:function(){this._oldState=this.state()},restoreState:function(e,t){!(e=e||this._oldState||{}).extra||e.extra instanceof s||(e.extra=new s(e.extra),e.scriptDeps=e.extra.getDependencies()),this.set(e),t||delete this._oldState},getSavedState:function(){var e;return this._oldState&&(e=i.extend({},this._oldState)).extra&&(e.extra=new s(e.extra),e.scriptDeps=e.extra.getDependencies()),e},createTimeFormatted:function(){var e=this.get("createTime");return e?this._formatDate(1e3*e):null},fireTimeFormatted:function(){var e=this.get("fireTime");return e?this._formatDate(1e3*e):null},TVSettingsPropertiesKey:function(){return e=this.id,"chartproperties.alertsProperties."+(e=parseInt(e));var e},getFormatter:function(){var e=this.get("extra");if(e){var t=e.alertSeries();if(t.formatter)return a.deserialize(t.formatter)}return null},syncAlertType:function(){this.set("alertType",h(this))},syncScriptDeps:function(){var e=this.get("extra").getDependencies();this.set("scriptDeps",e)}});e.exports.Alert=g},62591:(e,t,n)=>{"use strict";var r;function i(e,t){let n="Study"===e||e===r.StudyLineTool||/^study_\w+/.test(e);return t&&(n=n||"StudyStrategy"===e),n}n.r(t),n.d(t,{StateForAlertType:()=>r,isStudyStateForAlertType:()=>i}),function(e){e.StudyLineTool="StudyLineTool"}(r||(r={}))},16509:(e,t)=>{var n={active:"active",aid:"alertId",alerts:"alerts",bar_time:"barTime",create_t:"createTime",cross_int:"crossInterval",deact:"autoDeactivation",desc:"description",email:"sendEmail",error:"error",events:"events",exp:"expired",fire_time:"fireTime",inc_cross_int:"includeCrossInterval",inf_exp:"noExpiration",internal_sym:"symbolInternal",popup:"showPopup",reason:"reason",res:"resolution",script_deps:"scriptDeps",script:"script",sms:"sendSms",snd:"playSound",push:"sendPush",snd_duration:"soundDuration",snd_file:"soundFile",sort_by:"sortBy",sort_dir:"sortDirection",start_t:"startTime",stop_t:"stopTime",stop:"stopReason",sym:"symbol",web_hook:"webhookUrl",inst_id:"instanceId",name:"name",alert_type:"alertType"},r=function(){var e={};return Object.keys(n).forEach((function(t){e[n[t]]=t})),e}();function i(e,t){var n={};return e?(Object.keys(e).forEach((function(r){var i=t(r),o=e[r];n[i]=o})),n):e}t.server2clientParams=function(e){return i(e,(function(e){return n[e]||e}))
},t.client2serverParams=function(e){return i(e,(function(e){return r[e]||e}))}},82520:(e,t,n)=>{"use strict";n.d(t,{AlertFrequencyController:()=>a});var r=n(37667),i=n(98125),o=n(80643);const s=(0,i.getLogger)("Alerts.Price.FrequencyController");class a{constructor(e){this._alert=e,e.on("change:autoDeactivation",(e,t)=>{const n=e.get("frequency");if(this._isFireRateValid({frequency:n,autoDeactivation:t}))return;const r=this._getValidFireRate({autoDeactivation:t});r?e.set("frequency",r.frequency):(s.logError(`Set invalid autoDeactivation: ${t}. Available: ${JSON.stringify(this.getAvailable())}`),this._setAnyValidFireRate())}),e.on("change:frequency",(e,t)=>{this._putFrequencyToExtra();const n=e.get("autoDeactivation");if(this._isFireRateValid({frequency:t,autoDeactivation:n}))return;const r=this._getValidFireRate({frequency:t});r?e.set("autoDeactivation",r.autoDeactivation):(s.logError(`Set invalid frequency: ${t}. Available: ${JSON.stringify(this.getAvailable())}`),this._setAnyValidFireRate())})}getAvailable(){const e=this._alert.get("extra");return(null===(t=null==e?void 0:e.alertSeries())||void 0===t?void 0:t.isTVScriptStrategy)||"alerts"===(null==e?void 0:e.conditionId())?[{autoDeactivation:!1,frequency:"60"}]:(()=>{var t;return Boolean(this._alert.isDrawing()&&"LineToolVertLine"===(null===(t=null==e?void 0:e.drawing())||void 0===t?void 0:t.type))})()?[{autoDeactivation:!0,frequency:"on_first_fire"}]:(()=>this._alert.get("crossInterval"))()?[{autoDeactivation:!0,frequency:"on_first_fire"},{autoDeactivation:!1,frequency:"on_first_fire"}]:(()=>{var t,n;return[null===(t=null==e?void 0:e.alertSeries())||void 0===t?void 0:t.style,null===(n=null==e?void 0:e.mainSeries())||void 0===n?void 0:n.style].filter(o.isInteger).some(r.hasProjection)})()?[{autoDeactivation:!0,frequency:"on_bar_close"},{autoDeactivation:!1,frequency:"on_bar_close"}]:[{autoDeactivation:!0,frequency:"once"},{autoDeactivation:!1,frequency:"on_first_fire"},{autoDeactivation:!1,frequency:"on_bar_close"},{autoDeactivation:!1,frequency:"60"}];var t}switchFrequencies(){const e=this._alert,t=e.get("frequency"),n=e.get("autoDeactivation");if(!0===n){const t=this._getValidFireRate({autoDeactivation:!0});if(t)return void e.set({autoDeactivation:t.autoDeactivation,frequency:t.frequency})}if(!1===n&&"on_first_fire"===t){const t="60",n=this._getValidFireRate({frequency:t});if(n)return void e.set({autoDeactivation:n.autoDeactivation,frequency:t})}if(!1===n){const t=this._getValidFireRate({autoDeactivation:!1});if(t)return void e.set({autoDeactivation:t.autoDeactivation,frequency:t.frequency})}this._isFireRateValid({frequency:t,autoDeactivation:n})||this._setAnyValidFireRate()}_putFrequencyToExtra(){const e=this._alert.get("extra");e&&e.frequency(this._alert.get("frequency"))}_isFireRateValid(e){return this.getAvailable().some(t=>t.frequency===e.frequency&&t.autoDeactivation===e.autoDeactivation)}_getValidFireRate(e){const[t,n]=Object.entries(e)[0],r=this.getAvailable().find(e=>e[t]===n);return void 0===r?null:r}_setAnyValidFireRate(){const e=this.getAvailable()[0]
;this._alert.set({frequency:e.frequency,autoDeactivation:e.autoDeactivation}),this._putFrequencyToExtra()}}},22822:(e,t,n)=>{"use strict";n.d(t,{canPlaceAlertOnResolution:()=>s});var r=n(29823),i=n(33550),o=n(62867);function s(e){return!r.Interval.isSeconds(e)||(0,i.enabled)(o.ProductFeatures.ALERTS_ON_SECONDS)}},60993:(e,t,n)=>{"use strict";n.r(t),n.d(t,{AlertsDispatcher:()=>$,prepareAlertsModels:()=>Z});var r=n(28353),i=n(99486),o=n(8859),s=n(24993),a=n(86811),l=n(98125),c=n(26187),u=n(39193);const d=(0,l.getLogger)("Alerts.Price.InvokeAlertEditor");function _(e){u.alertsMaintenanceTracker.sync();const t=(0,i.shouldAbortAlertEditor)(e);if(null!==t)return t!==s.AlertEditorAbortReason.IsAlreadyPresent&&(0,i.showAbortExplainingDialog)(t,(0,i.getAlertDialogType)(e)),d.logWarn("Aborted: "+t),void(e.onAborted&&e.onAborted(t));const{unlockInvocation:r,abortSignal:a}=c.alertEditorInvocationHandler.lockInvocation(e);Promise.all([n.e(273).then(n.t.bind(n,79540,19)),(0,o.getPriceAlertsDispatcher)(),p(e,r,a)]).then(e=>{const[t,n,r]=e;new t.AlertEditor(n,r)},r)}function p(e,t,n){return(e.series?(0,a.hasUserAccessToDataSource)(e.series):Promise.resolve(!0)).then(r=>{const i=e.onDestroy,o={...e,abortSignal:n,onDestroy:()=>{t(),i&&i()}};return r||(delete o.series,delete o.value),o})}var h=n(82413),f=n.n(h),m=n(71021),g=n(25531),S=n(99543),y=n.n(S),v=n(16654),A=n(93119),T=n.n(A),E=n(51768),b=n(33550),C=n(62867),R=n(87341),w=n(16509),I=n(52485),P=(n(51872),n(12620));const D={max_alerts_count_exceeded:"alerts",max_primitive_alerts_count_exceeded:"primitiveAlerts",max_complex_alerts_count_exceeded:"complexAlerts"};function O(e="max_alerts_count_exceeded"){(0,P.createGoProDialog)({feature:D[e]})}function x(){(0,P.createGoProDialog)({feature:"alertsNoExpiration"})}function N(){(0,i.showAbortExplainingDialog)(s.AlertEditorAbortReason.AlertsMaintenance)}var L=n(72781),M=n(3615);var F=n(22822),U=n(21097),k=n(55306),B=n(2872),V=n.n(B),q=n(44182);function H(e){return!e.isDrawing()}var Y=n(35908);var j=n(68647),W=n(23127);const J="cancelled: new alert already generating",G=(0,l.getLogger)("Alerts.Price.Dispatcher");function $(){this._loading={},this._alertVersioning=new m.AlertVersioning,this._lastGenIds={},this._onPushStreamMessage=new(V()),this._onPushStreamStatusChanged=e=>{e===q.ConnectionStatus.Open&&this._onPushStreamMessage.fire({source:"host",data:{m:"pushstream_ready"}})},this._onMessage=this._onMessage.bind(this),this.alerts=new(j.Collection.extend({model:g.Alert})),this.events=new(j.Collection.extend({comparator:function(e,t){var n=e.get("fireTime"),r=t.get("fireTime");return n&&r?r-n:n?r?void 0:1:-1},model:f()})),this._attachHandlers()}function K(e){e.forEach(e=>e.set("selected",!1))}function X(e,t){e.forEach(e=>{e!==t&&e.set("selected",!1)})}function z(e){const t=new Date;e.get("expired")<t&&(t.setMonth(t.getMonth()+1),e.set("expired",t))}function Z(e,t){return Promise.all(e.map((function(e){const r=e.id,i=(0,w.server2clientParams)(e)
;return t(i).catch(n("Migration failed",r)).then(e=>e&&new g.Alert(e)).catch(n("Alert creation failed",r))}))).then(e=>e.filter(e=>null!==e));function n(e,t){return n=>(G.logError(`${e}. Alert ID: ${t}. Error: ${n}`),null)}}function Q(e,t){e.script=t.IL,t.inputs&&(e.inputs=t.inputs),t.genAlertData&&(e.gen_alert_data=t.genAlertData)}function ee(e,...t){"function"==typeof e&&e.apply(this,t)}$.checkProPermissions=function(e){return e.get("noExpiration")&&!(0,b.enabled)(C.ProductFeatures.ALERTS_NO_EXPIRATION)?(x(),!1):"string"!=typeof e.get("webhookUrl")||(0,b.enabled)(C.ProductFeatures.ALERTS_WEBHOOK)?!!(0,F.canPlaceAlertOnResolution)(e.get("resolution"))||((0,P.createGoProDialog)({feature:"alertsOnSeconds"}),!1):((0,k.showGoProAlertsWebhookDialog)(),!1)},$.getAnalyticsHeaders=function(e,t){return{"X-Analytics-Price-Alert-Condition":String(e),"X-Analytics-Price-Alert-Action-Source":String(t)}},$.prototype._onLoginStateChange=function(){is_authenticated?this._refreshPushStream():(this.alerts.reset(),this.events.reset(),this._alertVersioning.cancelAllPossibleExtraUpdates()),this._fullListWasRequested=!1},$.prototype._attachHandlers=function(){var e=this;function t(t){var n=e.chartWidget(),r=n&&n.hasModel()?n.model():null;if(r){var i=r.selection().dataSources().some((function(e){return e.hasAlert.value()&&e.alertId()===t.id}));t.set("selected",i)}}loginStateChange.subscribe(this,this._onLoginStateChange.bind(this)),this._onLoginStateChange(!0),e.alerts.on("add",n=>{t(n),function(t){if(t.isDrawing()&&e._chartWidgetCollection){var n=t.get("extra").drawing();e._chartWidgetCollection.getAll().forEach((function(e){e.applyAlertIdByExternalSource(n.id,t.id)}))}}(n)}).on("change:selected",(t,n,r)=>{if(n){var i=e.alerts;K(e.events),X(i,t)}}).on("change:id",t).on("destroy",t=>{t.isNew()||e.events.where({alertId:t.id}).forEach((function(e){e.destroy()}))}),e.events.on("change:selected",(t,n,r)=>{var i=e.events.models;n&&(K(e.alerts),X(i,t))}),e.alerts.on("change:id",t=>{let n=!1;for(const r of e.alerts.models)r.id===t.id&&(n?G.logWarn(`Two alerts share the same id ${t.id}, which may lead to undefined behaviour`):n=!0)}),U.TVXWindowEvents.on("alertevents-deleted",e=>{""===e?this.events.reset():this.events.remove(JSON.parse(e))})},$.prototype._refreshPushStream=function(){T().off("alert",this._onMessage),T().offStatus(this._onPushStreamStatusChanged),is_authenticated&&(T().on("alert",this._onMessage),T().onPrivateStatus(this._onPushStreamStatusChanged))},$.prototype._onMessage=function(e){var t,n,r,i,o,s=this;if(e)switch(G.logNormal(e),n=JSON.parse(e),this._onPushStreamMessage.fire({source:"alert",data:n}),t="new_alerts"===(r=n.m)?n.p.alerts.map(w.server2clientParams):(0,w.server2clientParams)(n.p),r){case"alert_running":s._alertVersioning.cancelPossibleExtraUpdate(t.id),s._alertVersioning.migrate(t).then((function(e){(i=s.alerts.get(e.id))?i.set(e):s.alerts.add(e,{at:0})}));break;case"new_alerts":for(const e of t)s.alerts.add(e);break;case"alert_stopped":if(i=s.alerts.get(t.id)){var a={active:!1,stopReason:t.stopReason,error:t.error}
;i.set(a)}break;case"alert_deleted":if(s._alertVersioning.cancelPossibleExtraUpdate(t.id),i=s.alerts.get(t.id)){const e=s.chartWidget();if(i.isDrawing()&&e){var l=i.get("extra").drawing();e.deleteAlertByExternalSource(l.id,i.id)}i.destroy()}break;case"event":{o=new(f())({...t}),s.events.add(o),o.trigger("fired",o),o.trigger("fired:online",o);const e=s.alerts.get(t.alertId);void 0!==e&&(e.set({fireTime:t.fireTime}),e.trigger("fired",e))}}},$.prototype.cloneAlert=function(e,t={}){if(!H(e))return"function"==typeof t.error&&t.error("Cannot clone alert"),void("function"==typeof t.complete&&t.complete());const n=e.getLocalClone();z(n),this.alerts.add(n),this.createAlert(n,{...t,eventName:"clone"})},$.prototype.detachAlert=function(e){var t=this.alerts.get(e);t&&t.destroy()},$.prototype.createLocalAlert=function(e,t){var n;return t&&function(e){if(!e)throw new Error("Can't create alert. 'params' is required");for(var t=["symbol","resolution","expired","autoDeactivation","sendEmail","sendSms","showPopup","playSound","description","script"],n=[],r=t.length-1;r>=0;r--){var i=t[r];i in e||n.push(i)}n.length&&G.logError("[Alerts] Can't create alert. "+n.join(" ,")+(1===n.length?" is":" are")+" required")}(e),n=new g.Alert(e),this.alerts.add(n),n},$.prototype.createAlert=function(e,t={}){const n=this;function r(e,n){"function"==typeof t.complete&&t.complete(),"function"==typeof t.error&&t.error(e,n)}if(e instanceof g.Alert){if($.checkProPermissions(e)){var i=Date.now(),o=e.prepareToSend();return n._generateScriptWithCancellation(e).then((function(r){return Q(o,r),n.sendRequest({headers:$.getAnalyticsHeaders(e.get("extra").conditionId(),t.actionSource),method:"create_alert",params:o,success:function(r){r=(0,w.server2clientParams)(r||{});const i=n.alerts.get(r.id);i?(n.alerts.remove(e),e=i):(r.active=!0,e.set(r)),n._gaTrackEvent(t.eventName||"create",e,t.eventLabel),"function"==typeof t.success&&t.success(e)},complete:function(){var n=Date.now()-i;I.telemetry.sendReport("alerts","full_time_frame",{value:n}),"function"==typeof t.complete&&t.complete(e)},error:t.error}).catch(()=>{})})).catch((function(e){if(e===J)return G.logNormal("Alert generation is cancelled because next alert generation is started"),J;"function"==typeof t.error&&t.error("Can't generate source code: "+e),"function"==typeof t.complete&&t.complete()}))}r("cannot create alert with current pro plan",!0)}else r("'alert' should be instance of Alert")},$.prototype.stopAlert=function(e,t={}){const n=this;let r,i;e instanceof g.Alert?(r=e,i=r.get("id")):(i=e,r=n.alerts.get(i)),i?n.sendRequest({method:"stop_alert",params:{id:i},success:function(){n._gaTrackEvent("stop"),r&&r.set("active",!1),"function"==typeof t.success&&t.success()},error:t.error,complete:t.complete}):G.logError("Alert id is required to stop alert")},$.prototype.stopAllAlerts=function(e={}){const t=this,n={cross_int:!0};let i;e.symbol&&(n.symbol=e.symbol),e.resolution&&(n.resolution=e.resolution),e.showConfirm&&(i=e.symbol||e.resolution?{title:(0,r.t)("Stop filtered alerts"),text:(0,
r.t)("Need a quick break from filtered alerts?")}:{title:(0,r.t)("Stop all alerts"),text:(0,r.t)("Need a quick break from your alerts?")}),t.sendRequest({method:"stop_all",params:n,success:function(){t._gaTrackEvent("stop_all"),t.alerts.each((function(e){n.symbol&&n.symbol!==e.get("symbol")||n.resolution&&n.resolution!==e.get("resolution")||e.set("active",!1)})),"function"==typeof e.success&&e.success()},confirmation:i,error:e.error,complete:e.complete})},$.prototype.deleteAlert=function(e,t={}){const n=this;let i,o,s;if(e instanceof g.Alert?(o=e,s=o.get("id")):(s=e,o=n.alerts.get(s)),o&&o.isNew())return o.destroy(),void("function"==typeof t.complete&&t.complete());if(s){if(t.showConfirm){const e=(a=o?o.title():s,(0,Y.cutString)(a,100)),t=(0,r.t)("Do you really want to delete your alert '{alert}'?").format({alert:e});i={title:(0,r.t)("Delete alert"),text:t}}var a;n.sendRequest({method:"delete_alert",params:{id:s},success:function(){n._gaTrackEvent("delete"),"function"==typeof t.success&&t.success(),o&&o.destroy()},error:t.error,cancel:t.cancel,complete:t.complete,confirmation:i})}else G.logError("Alert id is required to delete alert")},$.prototype.deleteAllAlerts=function(e={}){const t=this,n={crossInterval:!0};let i;e.symbol&&(n.symbol=e.symbol),e.resolution&&(n.resolution=e.resolution),"boolean"==typeof e.active&&(n.active=e.active),e.showConfirm&&(i=!1===n.active?{title:(0,r.t)("Delete inactive alerts"),text:(0,r.t)("Lets delete your inactive alerts and make new ones?")}:n.active||n.symbol||n.resolution?{title:(0,r.t)("Delete filtered alerts"),text:(0,r.t)("Do you really want to delete filtered alerts?")}:{title:(0,r.t)("Delete all alerts"),text:(0,r.t)("Ready to delete your alerts and start over?")}),t.sendRequest({method:"delete_all",params:n,success:function(){var r,i={};for(t._gaTrackEvent("delete_all"),n.symbol&&(i.symbol=n.symbol),n.resolution&&(i.resolution=n.resolution),"boolean"==typeof n.active&&(i.active=n.active),r=t.alerts.findWhere(i);r;)r.destroy(),r=t.alerts.findWhere(i);"function"==typeof e.success&&e.success()},error:e.error,complete:e.complete,confirmation:i})},$.prototype.restartAlert=function(e,t={}){const n=this;let r,i;if(e instanceof g.Alert?r=e:(i=e,r=n.alerts.get(i)),r){if(z(r),!$.checkProPermissions(r))return"function"==typeof t.complete&&t.complete(),void("function"==typeof t.error&&t.error("cannot restart alert with current pro plan",!0));var o=Date.now(),s=r.prepareToSend();return n._generateScriptWithCancellation(r).then((function(e){return Q(s,e),n.sendRequest({headers:$.getAnalyticsHeaders(r.get("extra").conditionId(),t.actionSource),method:"restart_alert",params:s,success:function(){n._gaTrackEvent("restart",r),r.set("active",!0),"function"==typeof t.success&&t.success(r)},complete:function(){var e=Date.now()-o;I.telemetry.sendReport("alerts","full_time_frame",{value:e}),"function"==typeof t.complete&&t.complete(r)},error:t.error}).catch(()=>{})})).catch((function(e){if(e===J)return G.logNormal("Alert generation is cancelled because next alert generation is started"),J
;"function"==typeof t.error&&t.error("Can't generate alert source code for alert #"+i)}))}n.requestAlert(i,{success:function(e){e?n.restartAlert(e,t):("function"==typeof t.error&&t.error("Can't find alert "+i),"function"==typeof t.complete&&t.complete())}})},$.prototype._generateScriptWithCancellation=function(e){var t=this;null==t._lastGenIds[e.cid]&&(t._lastGenIds[e.cid]=0),t._lastGenIds[e.cid]++;var n=t._lastGenIds[e.cid];return new Promise((function(t,n){const r=e.get("extra");let i=null,o="";if(r.isValid()?(i=r.toGenAlertJSON(e.get("description")),null===i&&(o="Can't generate alert JSON")):o="Can't generate alert on invalid AlertExtra",o)return G.logError(o),void n(o);y().generateAlert(JSON.stringify(i)).then((function(e,n,r,i){t({IL:n,inputs:r,genAlertData:i})}),n)})).then((function(r){return t._lastGenIds[e.cid]!==n?Promise.reject(J):(e.set("script",r.IL),r)}))},$.prototype.restartAllAlerts=function(e={}){const t=this,n={crossInterval:!0};let i;e.symbol&&(n.symbol=e.symbol),e.resolution&&(n.resolution=e.resolution),"boolean"==typeof e.active&&(n.active=e.active),e.showConfirm&&(i=e.symbol||e.resolution?{title:(0,r.t)("Restart filtered alerts"),text:(0,r.t)("Ready to bring filtered alerts back to life?")}:{title:(0,r.t)("Restart all inactive alerts"),text:(0,r.t)("Ready to bring your alerts back to life?")});t.alerts.every($.checkProPermissions)&&t.sendRequest({method:"restart_all",params:n,success:function(){t._gaTrackEvent("restart_all"),t.alerts.each((function(e){n.symbol&&n.symbol!==e.get("symbol")||n.resolution&&n.resolution!==e.get("resolution")||e.set("active",!0)})),"function"==typeof e.success&&e.success()},error:e.error,complete:e.complete,confirmation:i})},$.prototype.requestAlert=function(e,t={}){const n=this,r=parseInt(e);function i(e){var i=n.alerts.get(r)||null;return(i||e)&&("function"==typeof t.success&&t.success(i),"function"==typeof t.complete&&t.complete()),!!i}function o(){n.sendRequest({method:"get_alert",preventMaintenanceDialog:!0,params:{id:r},success:function(e){var r,i=e.alert;i=(0,w.server2clientParams)(i),n._alertVersioning.migrate(i).then((function(e){r=new g.Alert(e),n.alerts.add(r),"function"==typeof t.success&&t.success(r)})).catch((function(e){"function"==typeof t.error&&t.error(e)}))},complete:t.complete,error:function(n){"function"==typeof t.error?t.error(n):G.logError("Error in getting alert "+e+(n?": "+n:""))}})}!0===t.fromCache?i(!0):!1===t.fromCache?o():i()||o()},$.prototype.getAlertSync=function(e){return this.alerts.get(e)||null},$.prototype.ensureFullAlertsList=async function(e={}){try{if(window.is_authenticated||(this._fullListWasRequested=!0),this._fullListWasRequested)return void ee(e.success);const t=await this.sendRequest({method:"list_alerts",preventMaintenanceDialog:!0,params:{limit:2e3}});if(!t.alerts||!Array.isArray(t.alerts))throw new Error("Not valid params in alert list response");const n=await Z(t.alerts,e=>this._alertVersioning.migrate(e));this.alerts.set(n),this._fullListWasRequested=!0,ee(e.success)}catch(t){const n=String(t);throw G.logError(n),
ee(e.error,n),t}finally{ee(e.complete)}},$.prototype.requestEventList=function(e={}){const t=this,n={sym:e.symbol,res:e.resolution&&e.resolution.toString?e.resolution.toString():void 0,limit:e.limit,before:e.before,inc_cross_int:void 0===e.includeCrossInterval||e.includeCrossInterval};e.aid&&(n.aid=e.aid),e.aids&&(n.aids=e.aids),this.sendRequest({method:"list_events",preventMaintenanceDialog:!0,params:n,success:function(n){let r=n.events;r&&W.isArray(r)?(r=W.map(r,(function(e){const n=new(f())((0,w.server2clientParams)(e));return t.events.add(n),n})),"function"==typeof e.success&&e.success(r)):console.warn("[Alerts] Not valid params in event list response")},error:e.error,complete:e.complete})},$.prototype.deleteEvents=function(e={}){const t=e.ids;if(t&&0===t.length)return n(),void("function"==typeof e.complete&&e.complete());function n(){"function"==typeof e.success&&e.success()}this.sendRequest({method:"delete_events",params:t?{ids:t}:void 0,success:()=>{t?this.events.remove(t):this.events.reset(),U.TVXWindowEvents.emit("alertevents-deleted",t?JSON.stringify(t):""),n()},error:e.error,complete:e.complete})},$.prototype.stopAlerts=function(e){const{ids:t,success:n,confirmation:r,error:i,complete:o}=e;if(0===t.length)return ee(n),void ee(o);this.sendRequest({method:"stop_alerts",params:{ids:t},success:()=>{this._gaTrackEvent("stop_alerts");for(const e of t){const t=this.alerts.get(e);t&&t.set("active",!1)}ee(n)},error:i,complete:o,confirmation:r})},$.prototype.restartAlerts=function(e){const{ids:t,confirmation:n,success:r,error:i,complete:o}=e;if(0===t.length)return ee(r),void ee(o);const s=[];for(const e of t){const t=this.alerts.get(e);t&&s.push(t)}if(!s.every($.checkProPermissions))return ee(i,"Cannot restart alerts with current pro plan"),void ee(o);this.sendRequest({method:"restart_alerts",params:{ids:t},success:()=>{this._gaTrackEvent("restart_alerts");for(const e of s)e.set("active",!0);ee(r)},error:e=>{e in D&&O(e),ee(i)},complete:o,confirmation:n})},$.prototype.cloneAlerts=function(e){const{success:t,error:n,complete:r}=e,i=e.ids.filter(e=>{const t=this.alerts.get(e);return Boolean(t&&H(t))});if(0===i.length)return ee(t),void ee(r);this.sendRequest({method:"clone_alerts",params:{ids:i},success:()=>{this._gaTrackEvent("clone_alerts"),ee(t)},error:n,complete:r})},$.prototype.deleteAlerts=function(e){const{ids:t,confirmation:n,success:r,error:i,complete:o}=e;if(0===t.length)return ee(r),void ee(o);this.sendRequest({method:"delete_alerts",params:{ids:t},success:()=>{this._gaTrackEvent("delete_alerts");for(const e of t){const t=this.alerts.get(e);t&&t.destroy()}ee(r)},error:i,complete:o,confirmation:n})},$.prototype.sendRequest=function(e){const t=e.method,i=(0,w.client2serverParams)(e.params);if(function(e,t){if(["create_alert","restart_alert"].includes(e)){var n=t.extra&&JSON.parse(t.extra),r=n&&n.condition;["strategy","alerts","strategy_and_alerts"].includes(r.id)&&(t.ns_only_fire=!0)}}(t,i),u.alertsMaintenanceTracker.sync(),u.alertsMaintenanceTracker.value())return a("maintenance"),l(),
Promise.reject("maintenance");if(e.confirmation){const{title:t,text:n}=e.confirmation;return new Promise((function(i,s){(0,M.showConfirm)({title:t||(0,r.t)("Alert"),text:n,onConfirm:({dialogClose:e})=>{const t=o();return t.then((function(t){return e(),t})).catch((function(e){return e})),i(t),t},onClose:()=>{"function"==typeof e.cancel&&e.cancel(),l()}})}))}return o();function o(){const n=(0,R.sendRequest)({method:t,params:i,noCache:e.noCache,headers:e.headers});return n.then(s,a),n}function s(t){if("function"==typeof e.success){var n=(0,w.server2clientParams)(t);e.success(n)}return l(),n}function a(t){var r=!1;return t in D?(O(t),r=!0):"max_total_alerts_count_exceeded"===t?(Promise.all([n.e(5514),n.e(2888),n.e(8463),n.e(8844),n.e(5399),n.e(9961),n.e(7232),n.e(3091)]).then(n.bind(n,94197)).then(e=>e.showWarningAlertsMaxTotalCountExceededImpl()),r=!0):"pro_plan_expired"===t?(x(),r=!0):"maintenance"===t&&(e.preventMaintenanceDialog||(setTimeout(N,0),r=!0)),"function"==typeof e.error?e.error(t,r):"maintenance"===t?G.logNormal("Alerts maintenance"):t&&G.logError("Reason: "+t),l(),t}function l(){"function"==typeof e.complete&&e.complete()}},$.prototype.setChartWidgetCollection=function(e){this._chartWidgetCollection=e},$.prototype.chartWidget=function(){var e=null;return this._chartWidgetCollection&&(e=this._chartWidgetCollection.activeChartWidget.value()||null),e},$.prototype.removeAlertFromAllChartsSilently=function(e,t){this._chartWidgetCollection&&this._chartWidgetCollection.getAll().forEach((function(n){n.deleteAlertByExternalSource(e,t)}))},$.prototype._gaTrackEvent=function(e,t,n){var r;(0,E.trackEvent)("alert",e,n),"create"===e&&t instanceof g.Alert&&(r=t.get("extra"),(0,E.trackEvent)("alert","create__style",function(e){var t=e&&e.getMainSeries(),n=t&&t.getStyle&&t.getStyle();return n&&v.STYLE_SHORT_NAMES.hasOwnProperty(n)?v.STYLE_SHORT_NAMES[n]:"unknown"}(r)),(0,E.trackEvent)("alert","create__condition",function(e){var t=e.conditionId();return e.prepareAlertConditions()[t]&&(t="pine_condition"),t||"unknown"}(r)),(0,E.trackEvent)("alert","create__frequency",t.get("frequency")||"unknown"),t.isPrice()?(0,E.trackEvent)("alert","create__on","price"):t.isDrawing()?(0,E.trackEvent)("alert","create__on","drawing"):t.isMoving()?(0,E.trackEvent)("alert","create__on","moving"):r.band()||r.upperBand()||r.lowerBand()?(0,E.trackEvent)("alert","create__on","study"):(0,E.trackEvent)("alert","create__on","unknown"))},$.prototype.getAlertDialogInvocations=function(){return c.alertEditorInvocationHandler.getDialogInvocations()},$.prototype.openCreateDialog=function(e){_({type:"create_alert",...e})},$.prototype.openEditDialog=function(e,t={}){const n=this;let i,o;const a=e=>t.onAborted&&t.onAborted(e);!t.dataSourceHub&&n.chartWidget()&&(t.dataSourceHub=n.chartWidget().model().model()),e instanceof g.Alert?i=e:(o=e,i=n.alerts.get(o)),i?_(t=W.extend(t,{alert:i,type:"edit_alert"})):o?n.requestAlert(o,{success:function(e){n.openEditDialog(e,t)},error:function(e){"not_exists"===e&&(0,L.showNoticeDialog)({type:"modal",title:(0,
r.t)("Alert"),content:(0,r.t)("Alert does not exist.")}),"function"==typeof t.error&&t.error(e),a(s.AlertEditorAbortReason.AlertIsInvalid)}}):(console.error("[Alerts] alert id is required to edit alert"),a(s.AlertEditorAbortReason.AlertIsInvalid))},$.prototype.subscribeToPushStream=function(e){this._onPushStreamMessage.subscribe(null,e)},$.prototype.unsubscribeFromPushStream=function(e){e?this._onPushStreamMessage.unsubscribe(null,e):this._onPushStreamMessage.unsubscribeAll(null)}},87341:(e,t,n)=>{"use strict";n.d(t,{sendRequest:()=>g,sendRequestImmediately:()=>S});var r=n(67337),i=n(98125);const o=(0,i.getLogger)("Alerts.Price.RequestCache");var s;function a(e,t=""){o.logDebug(`${e} ${t}`)}!function(e){const t={};function n(e){const n=i(e);return t[n]&&a("got from cache",n),t[n]?t[n].self:null}function r(e,n=!1){const r=i(e),o=t[r];if(o)if(n)o.clearCacheTimeoutId&&clearTimeout(o.clearCacheTimeoutId),delete t[r],a("removed immediately",r);else{const e=5e3;o.clearCacheTimeoutId=setTimeout(()=>{delete t[r],a("removed timeout",r)},e)}}function i(e){return JSON.stringify(e)}e.set=function(e,o){const s=i(e);n(e)&&r(e,!0),t[s]={self:o},a("added",s),o.then(t=>(r(e),t)).catch(t=>(r(e,!0),t))},e.get=n,e.isCachable=function(e){return"list_alerts"===e.method||"list_events"===e.method}}(s||(s={}));var l=n(9423);const c=(0,i.getLogger)("Alerts.Price.MergedGetAlertsRequrest");var u;function d(e,t){const n=t?JSON.stringify(t):"";c.logDebug(`${e} ${n}`)}!function(e){const t={};let n=null,r=null;function i(e){delete t[e],Object.keys(t).length||(r=null,n=null)}e.isMergable=function(e){return"get_alert"===e.method||"get_alerts"===e.method},e.mergeRequest=function(e){const o=(0,l.guid)(),s=new Promise((t,i)=>{d("personal promise - creating",e),function(e){let t=[];"id"in e.params?t=[e.params.id]:"ids"in e.params&&(t=e.params.ids);r?r.params.ids=r.params.ids.concat(t):r={method:"get_alerts",params:{ids:t}}}(e),function(){n||(d("merged promise - creating"),n=new Promise((e,t)=>{setTimeout(()=>{r?(d("send request to server - timeout"),S(r).then(t=>{e(t)}).catch(t)):t("No data to send request")},500)}),n.then(e=>d("merged promise - resolved")),n.catch(e=>d("merged promise - rejected")));return n}().then(n=>{const r=function(e,t){const n=t.alerts||[];let r=null;if("get_alert"===e.method){const t=n.filter(t=>t.id===e.params.id)[0];t&&(r={alert:t})}else if("get_alerts"===e.method){const t=e.params.ids,i=[];for(let e=t.length-1;e>=0;e--){const r=t[e];for(let e=n.length-1;e>=0;e--){const t=n[e];if(t.id===r){i.push(t);break}}}i.length&&(r={alerts:i})}return r}(e,n);r?(d("personal promise - resolved",e),t(r)):(d("personal promise - rejected",e),i("not_exists"))}).catch(i)});return s.then(e=>(i(o),e)).catch(e=>(i(o),e)),function(e,n){t[e]=n}(o,s),s}}(u||(u={}));var _=n(52485),p=n(85198);const h=(0,i.getLogger)("Alerts.Price.Request"),f=window.initData.price_alerts_url||"";r.enabled("alerts")&&!f&&h.logError("Url not passed")
;const m=new Set(["create_alert","stop_alert","stop_all","restart_alert","restart_all","delete_alert","delete_all","delete_events","update_extra","restart_alerts","stop_alerts","clone_alerts","delete_alerts"]);function g(e){if(e.method&&m.has(e.method)){const t=Object.assign({},e.params);e.params&&"extra"in e.params&&(t.extra=JSON.parse(e.params.extra)),h.logNormal(JSON.stringify({m:e.method,p:t}))}if(u.isMergable(e))return u.mergeRequest(e);if(s.isCachable(e)){let t=s.get(e);return t||(t=S(e),s.set(e,t)),t}return S(e)}function S(e){if(!f)return Promise.reject("no_alerts_url");if(!window.is_authenticated)return Promise.reject("not_authenticated");const t=e.method,n={body:JSON.stringify({m:t,p:e.params}),credentials:"include",method:"POST",headers:e.headers},r=(new Date).getTime(),i=`${f}?log_username=${window.user.username}&log_method=${t}`;return(0,p.fetch)(i,n,{logBodyOnError:!0}).then(e=>{_.telemetry.sendReport("alerts","api_http_status",{value:e.status});const t=(new Date).getTime()-r;return _.telemetry.sendReport("alerts","api_time_frame",{value:t}),e.json()}).then(e=>"success"===e.m?e.p:"error"===e.m?Promise.reject(e.p.reason||"Unexpected server response"):Promise.reject("Unexpected server response")).catch(e=>e instanceof Error?Promise.reject("Failed to fetch price-alerts: "+e):Promise.reject(e))}},12444:(e,t,n)=>{"use strict";n.d(t,{getAlertDefaultDescription:()=>a});n(94419);var r=n(28353),i=n(47806);const o=(0,r.t)("{alertSeries} {alertCondition} {alertConditionOptions} on {chartSeries}"),s=(0,r.t)("{strategyName}: order {{strategy.order.action}} @ {{strategy.order.contracts}} filled on {{ticker}}. New strategy position is {{strategy.position_size}}");function a(e){switch(e.type){case i.AlertConditionTokenMapType.MainSeries:return`${e.alertSeries} ${e.conditionTitle} ${e.conditionOptions}`;case i.AlertConditionTokenMapType.Study:return o.format({alertSeries:e.alertSeries,chartSeries:e.mainSeries,alertCondition:e.conditionTitle,alertConditionOptions:e.conditionOptions});case i.AlertConditionTokenMapType.PineScript:return e.conditionMessage;case i.AlertConditionTokenMapType.PineScriptAlertFunction:return"";case i.AlertConditionTokenMapType.Strategy:return s.format({strategyName:e.strategyTitle})}}},28995:(e,t,n)=>{"use strict";n.d(t,{getAlertDefaultName:()=>u});n(94419);var r,i=n(28353),o=n(47806);!function(e){e.DrawingIconColor="rgba( 170, 170, 170, 1)",e[e.NameLengthLimit=300]="NameLengthLimit"}(r||(r={}));const s=(0,i.t)("{title}: Any alert() function call"),a=(0,i.t)("{title}: alert() function calls only"),l=r.NameLengthLimit-d(s),c=r.NameLengthLimit-d(a);function u(e){switch(e.type){case o.AlertConditionTokenMapType.MainSeries:case o.AlertConditionTokenMapType.Study:case o.AlertConditionTokenMapType.PineScript:case o.AlertConditionTokenMapType.Strategy:return"";case o.AlertConditionTokenMapType.PineScriptAlertFunction:const t=e.scriptTitle;let n,r;return e.isStrategy?(n=a,r=t.length>c?_(t,c):t):(n=s,r=t.length>l?_(t,l):t),n.format({title:r})}}function d(e){return e.replace("{title}","").length}
function _(e,t){return e.substring(0,t-"…".length)+"…"}},44182:(e,t,n)=>{"use strict";var r;n.d(t,{ConnectionStatus:()=>r}),function(e){e[e.Closed=0]="Closed",e[e.Connecting=1]="Connecting",e[e.Open=2]="Open"}(r||(r={}))},78540:(e,t,n)=>{"use strict";var r;n.d(t,{BillingCycle:()=>r}),function(e){e.Monthly="m",e.ThreeMonths="3m",e.OneYear="y",e.TwoYears="2y"}(r||(r={}))},46198:(e,t,n)=>{"use strict";var r,i,o;n.d(t,{ProPlans:()=>r}),function(e){e.Free="free",e.Pro="pro",e.ProTrial="pro_trial",e.ProRealtime="pro_realtime",e.ProRealtimeTrial="pro_realtime_trial",e.ProPremium="pro_premium",e.ProPremiumTrial="pro_premium_trial",e.ProMiniAlerts="pro_mini_alerts",e.ProMiniAds="pro_mini_ads",e.ProMiniLayouts="pro_mini_layouts",e.ProEdu="pro_edu"}(r||(r={})),function(e){e.Platinum="platinum",e.Gold="gold",e.Silver="silver",e.Free="free"}(i||(i={})),function(e){e[e.Platinum=3]="Platinum",e[e.Gold=2]="Gold",e[e.Silver=1]="Silver",e[e.Free=0]="Free"}(o||(o={}))},12620:(e,t,n)=>{"use strict";n.d(t,{createGoProDialog:()=>s});const r=new Set,i=[],o=new Promise(e=>{window.addEventListener("load",()=>{setTimeout(()=>{e()},3e3)}),setTimeout(()=>{e()},3e3)});async function s(e){var t;if(await o,i.forEach(t=>{t(e.feature)}),r.has(e.feature))return;const s=await Promise.all([n.e(5514),n.e(9129),n.e(2888),n.e(4956),n.e(8844),n.e(9961),n.e(5380),n.e(5733),n.e(1e3),n.e(5246)]).then(n.bind(n,61494));await(null===(t=window.pro)||void 0===t?void 0:t.ensureValidShopConf()),s.renderGoproDialog(e)}window.TradingView.createGoProDialog=s},72781:(e,t,n)=>{"use strict";n.d(t,{createNoticeDialog:()=>o,showNoticeDialog:()=>s});var r=n(28353);const i={width:400,destroyOnClose:!0,title:(0,r.t)("Notification"),content:(0,r.t)("You are notified"),contentWrapTemplate:'<div class="tv-dialog__section tv-dialog__section--no-border"><div class="tv-text"><p></p></div></div>',actionsWrapTemplate:'<div class="tv-dialog__section tv-dialog__section--actions tv-dialog__section--no-border">',actions:[{name:"ok",type:"primary",text:(0,r.t)("Ok"),method:"close",key:[13,32]}]};async function o(e){return(await Promise.all([n.e(509),n.e(3118),n.e(1729),n.e(6708),n.e(1536),n.e(7678),n.e(4834)]).then(n.bind(n,89725))).createDialog({...i,...e})}function s(e){o(e).then(e=>e.open())}},55306:(e,t,n)=>{"use strict";n.d(t,{showGoProAlertsWebhookDialog:()=>i});var r=n(12620);function i(){(0,r.createGoProDialog)({feature:"alertsWebhook"})}},84303:(e,t,n)=>{"use strict";n.d(t,{showSignModal:()=>i});let r=()=>!1;async function i(e){if(window.TVD&&window.TVD.signIn)return window.TVD.signIn(e);{const t=await Promise.all([n.e(5514),n.e(509),n.e(3118),n.e(5708),n.e(9570),n.e(5995),n.e(1536),n.e(6123)]).then(n.bind(n,14153));return r=t.isSignModalOpen,t.showSignModal(e)}}},55532:(e,t,n)=>{"use strict";var r=n(28353).t;n(94419);var i=n(24951),o=n(84917),s=o.WeekDays,a=o.Months,l=n(967),c=l.monthsFullNames,u=l.monthsShortNames,d=l.weekDaysFullNames,_=l.weekDaysShortNames,p=l.weekDaysMiniNames;window.language&&(i.locale(window.language,{
months:[c[a.JANUARY],c[a.FEBRUARY],c[a.MARCH],c[a.APRIL],c[a.MAY],c[a.JUNE],c[a.JULY],c[a.AUGUST],c[a.SEPTEMBER],c[a.OCTOBER],c[a.NOVEMBER],c[a.DECEMBER]],monthsShort:[u[a.JANUARY],u[a.FEBRUARY],u[a.MARCH],u[a.APRIL],u[a.MAY],u[a.JUNE],u[a.JULY],u[a.AUGUST],u[a.SEPTEMBER],u[a.OCTOBER],u[a.NOVEMBER],u[a.DECEMBER]],weekdays:[d[s.SUNDAY],d[s.MONDAY],d[s.TUESDAY],d[s.WEDNESDAY],d[s.THURSDAY],d[s.FRIDAY],d[s.SATURDAY]],weekdaysShort:[_[s.SUNDAY],_[s.MONDAY],_[s.TUESDAY],_[s.WEDNESDAY],_[s.THURSDAY],_[s.FRIDAY],_[s.SATURDAY]],weekdaysMin:[p[s.SUNDAY],p[s.MONDAY],p[s.TUESDAY],p[s.WEDNESDAY],p[s.THURSDAY],p[s.FRIDAY],p[s.SATURDAY]],longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"MMM D",l:"M/D/YYYY",LL:"MMM D, YYYY",ll:"MMM D LT",LLL:"LT - LL",lll:"MMM D, YYYY LT",LLLL:"ddd D MMMM YYYY LT",llll:"ddd D MMM YYYY LT"},calendar:{sameDay:r("{specialSymbolOpen}Today at{specialSymbolClose} {dayTime}").format({specialSymbolOpen:"[",specialSymbolClose:"]",dayTime:"LT"}),nextDay:r("{specialSymbolOpen}Tomorrow at{specialSymbolClose} {dayTime}").format({specialSymbolOpen:"[",specialSymbolClose:"]",dayTime:"LT"}),nextWeek:r("{dayName} {specialSymbolOpen}at{specialSymbolClose} {dayTime}").format({specialSymbolOpen:"[",specialSymbolClose:"]",dayTime:"LT",dayName:"dddd"}),lastDay:r("{specialSymbolOpen}Yesterday at{specialSymbolClose} {dayTime}").format({specialSymbolOpen:"[",specialSymbolClose:"]",dayTime:"LT"}),lastWeek:r("{specialSymbolOpen}Last{specialSymbolClose} {dayName} {specialSymbolOpen}at{specialSymbolClose} {dayTime}").format({specialSymbolOpen:"[",specialSymbolClose:"]",dayTime:"LT",dayName:"dddd"}),sameElse:"L"},relativeTime:{future:function(e){return e===r("just now")?e:r("in %s",{context:"time_range"}).replace("%s",e)},past:function(e){return e===r("just now")?e:r("%s ago",{context:"time_range"}).replace("%s",e)},s:r("just now"),m:function(e){return r("%d minute",{plural:"%d minutes",count:e}).replace("%d",e)},mm:function(e){return r("%d minute",{plural:"%d minutes",count:e}).replace("%d",e)},h:r("an hour"),hh:function(e){return r("%d hour",{plural:"%d hours",count:e}).replace("%d",e)},d:r("a day"),dd:function(e){return r("%d day",{plural:"%d days",count:e}).replace("%d",e)},M:r("a month"),MM:function(e){return r("%d month",{plural:"%d months",count:e}).replace("%d",e)},y:r("a year"),yy:function(e){return r("%d year",{plural:"%d years",count:e}).replace("%d",e)}},week:{dow:1,doy:4}}),i.locale(window.language)),e.exports=i},53402:(e,t,n)=>{"use strict";n.r(t),n.d(t,{TRIAL_SUFFIX:()=>s,EA_SUFFIX:()=>a,CUSTOM_SUFFIX:()=>l,billingCycleToTimeUnit:()=>c,getReadableCycle:()=>u,getReadableNumericCycle:()=>d,billingPeriodText:()=>_,isEarlyAccess:()=>p,isTrialProduct:()=>h,getProductForTrial:()=>f,getDiscountFromEarlyAccess:()=>m,toEarlyAccess:()=>g,humanizeProPlan:()=>S,humanizeCardPlan:()=>y,getAmountOfDaysForBillingCycle:()=>v,countDiscountByBillingCycle:()=>A,billingCycleToMonth:()=>T,round2:()=>E,round0:()=>b,floor0:()=>C,round2or0:()=>R,round1or0:()=>w,roundMinimal:()=>I,getPlanName:()=>P});n(94419)
;var r=n(28353),i=n(46198),o=n(78540);const s="_trial",a="_discount",l="_custom";function c(e){return{y:(0,r.t)("year",{plural:"years",count:1}),m:(0,r.t)("month",{plural:"months",count:1}),"3m":(0,r.t)("three months"),"2y":(0,r.t)("two years")}[e]}function u(e){return{m:(0,r.t)("monthly"),y:(0,r.t)("annually"),"3m":(0,r.t)("3 months"),"2y":(0,r.t)("2-year")}[e]||""}function d(e){return{[o.BillingCycle.Monthly]:(0,r.t)("monthly"),[o.BillingCycle.OneYear]:(0,r.t)("1 year"),[o.BillingCycle.ThreeMonths]:(0,r.t)("3 months"),[o.BillingCycle.TwoYears]:(0,r.t)("2 years")}[e]||""}function _(e){var t;return null!==(t={y:(0,r.t)("Billed every year."),m:(0,r.t)("Billed every month."),"2y":(0,r.t)("Billed every two years.")}[e])&&void 0!==t?t:""}function p(e){return/\d{0,2}_discount$/.test(e)}function h(e){return new RegExp(s+"$").test(e)}function f(e){return e.split(s)[0]}function m(e){const t=e.match(new RegExp("^(d{0,2})"+a+"$"));return t?+t[1]||50:0}function g(e,t){return`${e}_${t}${a}`}function S(e,t){let n=e;switch(e){case i.ProPlans.Pro:n="Pro";break;case i.ProPlans.ProRealtime:n="Pro+";break;case i.ProPlans.ProPremium:n="Premium";break;case i.ProPlans.ProMiniAds:case i.ProPlans.ProMiniLayouts:case i.ProPlans.ProMiniAlerts:n=(0,r.t)("1-feature");break;case i.ProPlans.ProEdu:n=(0,r.t)("Rookie")}return t&&(n+=" "+(0,r.t)("trial")),n}function y(e){let t=e;switch(e){case i.ProPlans.Pro:t="Pro";break;case i.ProPlans.ProRealtime:t="Pro+";break;case i.ProPlans.ProPremium:t="Premium";break;case i.ProPlans.Free:t="Basic"}return t}function v(e){switch(e){case o.BillingCycle.TwoYears:return 730;case o.BillingCycle.OneYear:return 365;case o.BillingCycle.ThreeMonths:return 90;case o.BillingCycle.Monthly:return 30;default:return 1}}function A(e,t,n){return Math.round((t-e)*T(n))}function T(e){switch(e){case o.BillingCycle.TwoYears:return 24;case o.BillingCycle.OneYear:return 12;default:return 1}}function E(e){return(Math.round(100*e)/100).toFixed(2)}function b(e){const t=Math.round(100*e)/100;return Math.round(t).toFixed(0)}function C(e){return Math.floor(e).toString()}function R(e){const t=Math.round(100*e)/100,n=Math.round(t);return Math.abs(t-n)>0?t.toFixed(2):n.toFixed(0)}function w(e){return Number.isInteger(e)?e.toFixed(0):(Math.round(10*e)/10).toFixed(1)}function I(e){const t=Math.round(100*e)/100,n=Math.round(10*e)/10,r=Math.round(t);return Math.abs(t-r)>0?Math.abs(t-n)>0?t.toFixed(2):n.toFixed(1):r.toFixed(0)}function P(e){const t=(0,r.t)("{proPlanName} Trial");if(h(e)){const n=S(f(e));return t.format({proPlanName:n})}return S(e)}},85619:(e,t,n)=>{"use strict";function r(e){let t,n=0;if(0===e.length)return n;for(var r=0;r<e.length;r++)t=e.charCodeAt(r),n=(n<<5)-n+t,n&=n;return n}n.r(t),n.d(t,{hash:()=>r})},967:(e,t,n)=>{"use strict";n.r(t),n.d(t,{monthsFullNames:()=>o,monthsShortNames:()=>s,weekDaysFullNames:()=>a,weekDaysShortNames:()=>l,weekDaysMiniNames:()=>c});var r=n(28353),i=n(84917);const o={[i.Months.JANUARY]:(0,r.t)("January"),[i.Months.FEBRUARY]:(0,r.t)("February"),[i.Months.MARCH]:(0,r.t)("March"),
[i.Months.APRIL]:(0,r.t)("April"),[i.Months.MAY]:(0,r.t)("May"),[i.Months.JUNE]:(0,r.t)("June"),[i.Months.JULY]:(0,r.t)("July"),[i.Months.AUGUST]:(0,r.t)("August"),[i.Months.SEPTEMBER]:(0,r.t)("September"),[i.Months.OCTOBER]:(0,r.t)("October"),[i.Months.NOVEMBER]:(0,r.t)("November"),[i.Months.DECEMBER]:(0,r.t)("December")},s={[i.Months.JANUARY]:(0,r.t)("Jan"),[i.Months.FEBRUARY]:(0,r.t)("Feb"),[i.Months.MARCH]:(0,r.t)("Mar"),[i.Months.APRIL]:(0,r.t)("Apr"),[i.Months.MAY]:(0,r.t)("May",{context:"short"}),[i.Months.JUNE]:(0,r.t)("Jun"),[i.Months.JULY]:(0,r.t)("Jul"),[i.Months.AUGUST]:(0,r.t)("Aug"),[i.Months.SEPTEMBER]:(0,r.t)("Sep"),[i.Months.OCTOBER]:(0,r.t)("Oct"),[i.Months.NOVEMBER]:(0,r.t)("Nov"),[i.Months.DECEMBER]:(0,r.t)("Dec")},a={[i.WeekDays.SUNDAY]:(0,r.t)("Sunday"),[i.WeekDays.MONDAY]:(0,r.t)("Monday"),[i.WeekDays.TUESDAY]:(0,r.t)("Tuesday"),[i.WeekDays.WEDNESDAY]:(0,r.t)("Wednesday"),[i.WeekDays.THURSDAY]:(0,r.t)("Thursday"),[i.WeekDays.FRIDAY]:(0,r.t)("Friday"),[i.WeekDays.SATURDAY]:(0,r.t)("Saturday")},l={[i.WeekDays.SUNDAY]:(0,r.t)("Sun"),[i.WeekDays.MONDAY]:(0,r.t)("Mon"),[i.WeekDays.TUESDAY]:(0,r.t)("Tue"),[i.WeekDays.WEDNESDAY]:(0,r.t)("Wed"),[i.WeekDays.THURSDAY]:(0,r.t)("Thu"),[i.WeekDays.FRIDAY]:(0,r.t)("Fri"),[i.WeekDays.SATURDAY]:(0,r.t)("Sat")},c={[i.WeekDays.SUNDAY]:(0,r.t)("Su",{context:"day_of_week"}),[i.WeekDays.MONDAY]:(0,r.t)("Mo",{context:"day_of_week"}),[i.WeekDays.TUESDAY]:(0,r.t)("Tu",{context:"day_of_week"}),[i.WeekDays.WEDNESDAY]:(0,r.t)("We",{context:"day_of_week"}),[i.WeekDays.THURSDAY]:(0,r.t)("Th",{context:"day_of_week"}),[i.WeekDays.FRIDAY]:(0,r.t)("Fr",{context:"day_of_week"}),[i.WeekDays.SATURDAY]:(0,r.t)("Sa",{context:"day_of_week"})}},33550:(e,t,n)=>{"use strict";n.d(t,{enabled:()=>l,getConfig:()=>c})
;const r=JSON.parse('{"free":{"CHART_STORAGE":{"limit":1},"MULTIPLE_CHARTS":{"limit":1},"INDICATORS_ON_CHART":{"limit":3},"HISTORICAL_BARS":{"limit":5},"STUDY_ON_STUDY":{"limit":270,"child_limit":1},"SERVER_SIDE_ALERTS":{"limit":1},"SCREENER_ALERTS":{"limit":1},"SCREENER_INTERVALS":{"interval":["1D","1W","1M"]},"STUDY_TEMPLATES":{"limit":1},"SIMULTANEOUS_CONNECTIONS":{"limit":1},"IDEA_SOCIAL_LINKS":{"socials":["Twitter","Youtube"]}},"__legacy_pro":{"CHART_STORAGE":{"limit":99999},"MULTIPLE_CHARTS":{"limit":8},"CUSTOM_INTERVALS":{},"MULTIPLE_WATCHLISTS":{},"IMPORT_WATCHLISTS":{},"EXPORT_WATCHLISTS":{},"INDICATORS_ON_CHART":{"limit":99999},"HISTORICAL_BARS":{"limit":10},"TV_VOLUMEBYPRICE":{"study_packages":["tv-volumebyprice"]},"STUDY_ON_STUDY":{"limit":270,"child_limit":99999},"TICK_BY_TICK_PUSH_DATA":{},"SERVER_SIDE_ALERTS":{"limit":20},"SCREENER_ALERTS":{"limit":99999},"SCREENER_AUTO_REFRESH":{},"SCREENER_EXPORT_DATA":{},"SCREENER_INTERVALS":{"interval":["1m","5m","15m","30m","1h","2h","4h","1D","1W","1M"]},"NO_SPONSORED_ADS":{},"STUDY_TEMPLATES":{"limit":99999},"SIMULTANEOUS_CONNECTIONS":{"limit":1},"IDC_AVAILABLE_DELAY":{},"STATUS":{"disable_on_trial":true},"MULTIFLAGGED_SYMBOLS_LISTS":{},"BAR_REPLAY_INTRADAY":{},"SHOWS":{"disable_on_trial":true},"ALERTS_WEBHOOK":{},"DEEP_FUNDAMENTALS_HISTORY":{},"IDEA_SOCIAL_LINKS":{"socials":["Twitter","Youtube"]},"EXTENDED_SOCIAL_LINKS":{"socials":["Facebook","Instagram"],"disable_on_trial":true},"MULTI_MONITOR":{},"PUBLISH_PROTECTED_SCRIPTS":{"disable_on_trial":true}},"__legacy_pro_realtime":{"extends":"__legacy_pro","TV_PROSTUDIES":{"study_packages":["tv-prostudies"]},"SERVER_SIDE_ALERTS":{"limit":1000},"CAN_EDIT_PUBLIC_CHATS":{"disable_on_trial":true},"EXPORT_CHART_DATA":{},"CUSTOM_FORMULAS":{},"INTRADAY_EXOTIC_CHARTS":{}},"__legacy_pro_premium":{"extends":"__legacy_pro_realtime","USE_BAR_MAGNIFIER":{},"HISTORICAL_BARS":{"limit":20},"IDEA_SIGNATURE":{"disable_on_trial":true},"PROFILE_WEBSITE_FIELD":{"disable_on_trial":true},"ALERTS_NO_EXPIRATION":{},"PUBLISH_INVITE_ONLY_SCRIPTS":{"disable_on_trial":true},"EXPORT_CHART_DATA":{},"DEEP_HISTORY_BACKTEST":{},"ALERTS_ON_SECONDS":{},"PERMANENT_STREAM_RECORDS":{},"EXTENDED_SOCIAL_LINKS":{"socials":["Facebook","Instagram","Website"],"disable_on_trial":true},"SECONDS_INTERVALS":{}},"pro":{"CHART_STORAGE":{"limit":5},"MULTIPLE_CHARTS":{"limit":2},"CUSTOM_INTERVALS":{},"MULTIPLE_WATCHLISTS":{},"IMPORT_WATCHLISTS":{},"EXPORT_WATCHLISTS":{},"INDICATORS_ON_CHART":{"limit":5},"HISTORICAL_BARS":{"limit":10},"TV_VOLUMEBYPRICE":{"study_packages":["tv-volumebyprice"]},"STUDY_ON_STUDY":{"limit":270,"child_limit":1},"TICK_BY_TICK_PUSH_DATA":{},"SERVER_SIDE_ALERTS":{"limit":20},"SCREENER_ALERTS":{"limit":99999},"SCREENER_AUTO_REFRESH":{},"SCREENER_EXPORT_DATA":{},"SCREENER_INTERVALS":{"interval":["1m","5m","15m","30m","1h","2h","4h","1D","1W","1M"]},"NO_SPONSORED_ADS":{},"STUDY_TEMPLATES":{"limit":99999},"SIMULTANEOUS_CONNECTIONS":{"limit":1},"IDC_AVAILABLE_DELAY":{},"STATUS":{"disable_on_trial":true},"BAR_REPLAY_INTRADAY":{},"MULTIFLAGGED_SYMBOLS_LISTS":{},"SHOWS":{"disable_on_trial":true},"ALERTS_WEBHOOK":{},"DEEP_FUNDAMENTALS_HISTORY":{},"PUBLISH_PROTECTED_SCRIPTS":{"disable_on_trial":true},"IDEA_SOCIAL_LINKS":{"socials":["Twitter","Youtube"]},"EXTENDED_SOCIAL_LINKS":{"socials":["Facebook","Instagram"],"disable_on_trial":true},"MULTI_MONITOR":{}},"pro_realtime":{"extends":"pro","CHART_STORAGE":{"limit":10},"MULTIPLE_CHARTS":{"limit":4},"INDICATORS_ON_CHART":{"limit":10},"TV_PROSTUDIES":{"study_packages":["tv-prostudies"]},"STUDY_ON_STUDY":{"limit":270,"child_limit":9},"SERVER_SIDE_ALERTS":{"limit":100},"CAN_EDIT_PUBLIC_CHATS":{"disable_on_trial":true},"SIMULTANEOUS_CONNECTIONS":{"limit":2},"EXPORT_CHART_DATA":{},"CUSTOM_FORMULAS":{},"INTRADAY_EXOTIC_CHARTS":{}},"pro_premium":{"extends":"pro_realtime","USE_BAR_MAGNIFIER":{},"CHART_STORAGE":{"limit":99999},"MULTIPLE_CHARTS":{"limit":8},"INDICATORS_ON_CHART":{"limit":25},"HISTORICAL_BARS":{"limit":20},"STUDY_ON_STUDY":{"limit":270,"child_limit":24},"SERVER_SIDE_ALERTS":{"limit":400},"SIMULTANEOUS_CONNECTIONS":{"limit":5},"IDEA_SIGNATURE":{"disable_on_trial":true},"PROFILE_WEBSITE_FIELD":{"disable_on_trial":true},"ALERTS_NO_EXPIRATION":{},"PUBLISH_INVITE_ONLY_SCRIPTS":{"disable_on_trial":true},"EXPORT_CHART_DATA":{},"DEEP_HISTORY_BACKTEST":{},"ALERTS_ON_SECONDS":{},"PERMANENT_STREAM_RECORDS":{},"EXTENDED_SOCIAL_LINKS":{"socials":["Facebook","Instagram","Website"],"disable_on_trial":true},"SECONDS_INTERVALS":{}},"pro_mini_alerts":{"extends":"free","SERVER_SIDE_ALERTS":{"limit":30},"SCREENER_ALERTS":{"limit":99999},"SHOWS":{"disable_on_trial":true},"IDC_AVAILABLE_DELAY":{},"DEEP_FUNDAMENTALS_HISTORY":{}},"pro_mini_ads":{"extends":"free","NO_SPONSORED_ADS":{},"SHOWS":{"disable_on_trial":true},"IDC_AVAILABLE_DELAY":{},"DEEP_FUNDAMENTALS_HISTORY":{}},"pro_mini_layouts":{"extends":"free","MULTIPLE_CHARTS":{"limit":8},"SHOWS":{"disable_on_trial":true},"IDC_AVAILABLE_DELAY":{},"DEEP_FUNDAMENTALS_HISTORY":{}},"pro_edu":{"extends":"free","CHART_STORAGE":{"limit":3},"MULTIPLE_CHARTS":{"limit":2},"MULTIPLE_WATCHLISTS":{},"IMPORT_WATCHLISTS":{},"EXPORT_WATCHLISTS":{},"TICK_BY_TICK_PUSH_DATA":{},"SERVER_SIDE_ALERTS":{"limit":5},"SCREENER_ALERTS":{"limit":99999},"SHOWS":{"disable_on_trial":true},"IDC_AVAILABLE_DELAY":{},"DEEP_FUNDAMENTALS_HISTORY":{}}}'),i=JSON.parse('{"cme":{"INDICATORS_ON_CHART":{"limit":99999}},"bovespa":{"INDICATORS_ON_CHART":{"limit":99999}},"qecomqa":{"INDICATORS_ON_CHART":{"limit":99999}}}')
;var o=n(62867),s=n(46198),a=n(53402);function l(e,t,n){let r=window.user;n&&(r=n);const i=c(e,t,r);return!!i&&!(i[o.ProductFeatures.DISABLE_ON_TRIAL]&&(!r||r.is_trial))}function c(e,t,n){var o;let l=function e(t){const n=r[t];return n?n.extends?Object.assign({},e(n.extends),n):n:null}(t||function(e){let t=window.user;e&&(t=e);let n=(null==t?void 0:t.pro_plan)||s.ProPlans.Free;const r=n!==s.ProPlans.Free&&!(0,a.isTrialProduct)(n);return r||(n=(0,a.getProductForTrial)(n)),r&&t&&!t.is_pro_limited&&!t.new_pro_product_line&&(n="__legacy_"+n),n}(n));if(!l)return null;const c=null===(o=window.TradingView)||void 0===o?void 0:o.widgetCustomer;return c&&i[c]&&(l=Object.assign({},l,i[c])),l&&l[e]||null}},62867:(e,t,n)=>{"use strict";var r;n.d(t,{ProductFeatures:()=>r}),function(e){e.DISABLE_ON_TRIAL="disable_on_trial",e.CUSTOM_INTERVALS="CUSTOM_INTERVALS",e.CHART_STORAGE="CHART_STORAGE",e.MULTIPLE_CHARTS="MULTIPLE_CHARTS",e.MULTIPLE_WATCHLISTS="MULTIPLE_WATCHLISTS",e.IMPORT_WATCHLISTS="IMPORT_WATCHLISTS",e.EXPORT_WATCHLISTS="EXPORT_WATCHLISTS",e.INDICATORS_ON_CHART="INDICATORS_ON_CHART",e.STUDY_ON_STUDY="STUDY_ON_STUDY",e.TICK_BY_TICK_PUSH_DATA="TICK_BY_TICK_PUSH_DATA",e.SERVER_SIDE_ALERTS="SERVER_SIDE_ALERTS",e.PUBLISH_INVITE_ONLY_SCRIPTS="PUBLISH_INVITE_ONLY_SCRIPTS",e.PUBLISH_PROTECTED_SCRIPTS="PUBLISH_PROTECTED_SCRIPTS",e.SCREENER_ALERTS="SCREENER_ALERTS",e.SCREENER_AUTO_REFRESH="SCREENER_AUTO_REFRESH",e.SCREENER_EXPORT_DATA="SCREENER_EXPORT_DATA",e.SCREENER_INTERVALS="SCREENER_INTERVALS",e.SIMULTANEOUS_CONNECTIONS="SIMULTANEOUS_CONNECTIONS",e.STUDY_TEMPLATES="STUDY_TEMPLATES",e.CAN_EDIT_PUBLIC_CHATS="CAN_EDIT_PUBLIC_CHATS",e.NO_SPONSORED_ADS="NO_SPONSORED_ADS",e.IDC_AVAILABLE_DELAY="IDC_AVAILABLE_DELAY",e.STATUS="STATUS",e.ALERTS_NO_EXPIRATION="ALERTS_NO_EXPIRATION",e.MULTIFLAGGED_SYMBOLS_LISTS="MULTIFLAGGED_SYMBOLS_LISTS",e.BAR_REPLAY_INTRADAY="BAR_REPLAY_INTRADAY",e.TV_VOLUMEBYPRICE="TV_VOLUMEBYPRICE",e.ALERTS_WEBHOOK="ALERTS_WEBHOOK",e.DEEP_FUNDAMENTALS_HISTORY="DEEP_FUNDAMENTALS_HISTORY",e.EXPORT_CHART_DATA="EXPORT_CHART_DATA",e.ALERTS_ON_SECONDS="ALERTS_ON_SECONDS",e.PERMANENT_STREAM_RECORDS="PERMANENT_STREAM_RECORDS",e.IDEA_SOCIAL_LINKS="IDEA_SOCIAL_LINKS",e.EXTENDED_SOCIAL_LINKS="EXTENDED_SOCIAL_LINKS",e.DEEP_HISTORY_BACKTEST="DEEP_HISTORY_BACKTEST",e.USE_BAR_MAGNIFIER="USE_BAR_MAGNIFIER"}(r||(r={}))},51712:(e,t,n)=>{"use strict";n.d(t,{reloginOrGoPro:()=>d,runOrGoPro:()=>u});var r=n(20120),i=n(12620),o=n(33550),s=n(62867);function a(e,t,n){return t.value||(0,o.enabled)(e,n)}function l(e,t,n){switch(e){case s.ProductFeatures.SCREENER_INTERVALS:return function(e,t){const n=(0,o.getConfig)(s.ProductFeatures.SCREENER_INTERVALS,t);return!(!n||!n.interval)&&n.interval.includes(e.interval)}(t,n);case s.ProductFeatures.SCREENER_AUTO_REFRESH:return a(s.ProductFeatures.SCREENER_AUTO_REFRESH,t,n);case s.ProductFeatures.ALERTS_NO_EXPIRATION:return a(s.ProductFeatures.ALERTS_NO_EXPIRATION,t,n);default:return(0,o.enabled)(e,n)}}var c=n(84303);async function u(e,t,n,o={}){const s=window.is_authenticated
;window.is_authenticated&&window.user.is_pro&&await(0,r.syncUserData)("gopro"),s===window.is_authenticated?function(e,t,n,r){l(t,r)?e():(0,i.createGoProDialog)(n)}(e,t,n,o):(0,c.showSignModal)({source:n.goproSource,feature:n.feature,signinSuccess:e})}async function d(e){const t=window.is_authenticated;window.is_authenticated&&window.user.is_pro&&await(0,r.syncUserData)("gopro"),t===window.is_authenticated?(0,i.createGoProDialog)(e):(0,c.showSignModal)({source:e.goproSource,feature:e.feature})}},76266:(e,t,n)=>{"use strict";var r=n(11417).TVLocalStorage,i=n(2872);n(49483);var o=new i;TradingView.FeatureToggle={force_prefix:"forcefeaturetoggle.",onChanged:new i,enableFeature:function(e){r.setItem(this.force_prefix+e,"true"),o.fire(e)},disableFeature:function(e){r.setItem(this.force_prefix+e,"false"),o.fire(e)},resetFeature:function(e){r.removeItem(this.force_prefix+e),o.fire(e)},onFeaturesStateChanged:function(){return o}},TradingView.isFeatureEnabled=function(e){function t(e){try{var t=(void 0)(e+function(){if(window.user&&window.user.id)return window.user.id;var e=r.getItem("featuretoggle_seed");return null!==e||(e=Math.floor(1e6*Math.random()),r.setItem("featuretoggle_seed",e)),e}());return new DataView(t).getUint32(0,!0)/4294967296}catch(e){return.5}}return function(n){return!("local"!==window.environment||!function(e){var t=new RegExp("broker_[A-Z]+[a-zA-Z0-9_]+_dev","g"),n=new RegExp("hide_[A-Z]+[a-zA-Z0-9_]+_on_ios","g"),r=new RegExp("hide_[A-Z]+[a-zA-Z0-9_]+_on_android","g"),i=new RegExp("hide_[A-Z]+[a-zA-Z0-9_]+_on_mobile_web","g")
;return-1===["remove_note_tab_from_bottom_panel","broker_FXCM_token_v2","broker_TRADESTATION_V3","broker_TRADOVATE_dev","black_friday_mainpage","black_friday_popup","datawindow","trading-fast-renew-oauth-token","switching_trial_year_to_month_disabled","switching_year_to_month_disabled","default_year_billing_cycle_switcher","marketing-analytics","google-ads","visible_address_fields_by_default","slow-support-warning","hide-trading-floating-toolbar","tvcoins_donations","save-short-streams","details_disable_bid_ask","vat_disabled","pro_plan_upgrades_disabled","pro_plan_downgrades_disabled","unit_conversion","disable_recaptcha_on_signup","braintree-order-one-click-dropdown","braintree-trial-implementation","braintree-gopro-in-order-dialog","braintree-apple-pay","braintree-google-pay","braintree-apple-pay-trial","braintree-google-pay-trial","hide_gopro_popup_upgrade_button","yandex_metric_enabled","broker_id_session","remove_line_tools_from_content","do_not_save_shared_line_tools_to_charts","save_shared_line_tools","chart_storage_with_broker_name","do_not_invalidate_chart_on_changing_line_tools","log_removing_line_tools_group","oanda-european-accounts-warning","mobile_show_bottom_panel","disable_save_settings","desktop_version_notification_enabled","favorites-in-broker-dropdown","streams_stats_profile","hide_ecomonic_events","aggregating_page_pings","mobile_trading_web","mobile_trading_ios","mobile_trading_android","hide_real_brokers_on_mobile","enable_trading_server_logger","percentage_values_for_percentage_scale","hide_ranges_label_colors","disable_user_specific_encryption","remove_scale_settings_from_menu","enable_deep_history_backtesting","show_checkbox_of_house_rules_to_idea_and_script","enable_partner_program","disable_phone_verification_sms","no_overlap_mode_enabled","collapse_pane_buttons_when_connected_to_broker","enable_new_execution_style","test_minds_connections","ftx_request_server_logger","trading_request_server_logger","show_symbol_chart_type_switcher","ecommpay_ru","hide_ideas_on_chart","RU_SF_disable","RU_VOR_disable","show_continuous_contract_switches","hide_sync_time","enable_new_custom_public_chats","bottom_panel_track_events"].indexOf(e)&&-1===e.indexOf("-maintenance")&&!1===t.test(e)&&!1===n.test(e)&&!1===r.test(e)&&!1===i.test(e)}(n))||(!e[n]||-1!==e[n])&&(!!("true"===r.getItem(TradingView.FeatureToggle.force_prefix+n)||window.is_authenticated&&"undefined"!=typeof user&&user.settings&&"true"===user.settings[TradingView.FeatureToggle.force_prefix+n])||!("false"===r.getItem(TradingView.FeatureToggle.force_prefix+n)||window.is_authenticated&&"undefined"!=typeof user&&user.settings&&"false"===user.settings[TradingView.FeatureToggle.force_prefix+n])&&(!!e[n]&&(1===e[n]||t(n)<=e[n])))}}(window.featureToggleState||{}),t.FeatureToggle=TradingView.FeatureToggle,t.isFeatureEnabled=TradingView.isFeatureEnabled,t.onFeaturesStateChanged=TradingView.FeatureToggle.onFeaturesStateChanged.bind(TradingView.FeatureToggle)},93119:(e,t,n)=>{"use strict"
;var r=n(9423),i=n(21097).TVXWindowEvents,o=n(51768).trackEvent,s=n(11417).TVLocalStorage,a=n(50975).PushStream,l=n(44182).ConnectionStatus,c=n(52485).telemetry,u=n(98125),d=u.getLogger,_=u.getRawLogHistory,p=d("PushStreamMultiplexer"),h=function(){var e,t=null,n=null,u={},d={},h=[],f=null,m="multiplexer-bc-",g="pushStreamMultiplexerState.",S=l.Closed,y=l.Closed,v=!1,A={_codeParams:function(e){return(e=Array.prototype.slice.call(e)).push((new Date).getTime()),JSON.stringify(e)},_decodeParams:function(e){var t=JSON.parse(e);return t.pop(),t},guid:r.guid(),_init:function(){if(this._needInstantiating())this._instantiatePushStream();else{var e=this._decodeConnectionStatus(s.getItem(this._connectionStatusKey));S=e[0],y=e[1]}setTimeout((function(){A.isConnected()||(p.logNormal("Not connected for a while after init..."),o("pushstream","not connected after init",navigator.userAgent))}),A._activityTimeout)},_instantiatePushStream:function(e){this._setMark(),t&&(o("PushstreamDoublePublic",window.user&&window.user.username||"Guest",navigator.userAgent),t.disconnect()),(t=new a(this._dispatchMessage.bind(this),{url:window.PUSHSTREAM_URL,urlPath:"message-pipe-ws"})).connectionStatus().subscribe(function(e){this._dispatchStatusChange(e,y)}.bind(this)),n&&(o("PushstreamDoublePrivate",window.user&&window.user.username||"Guest",navigator.userAgent),n.disconnect()),(n=new a(this._dispatchMessage.bind(this),{url:window.PUSHSTREAM_URL,urlPath:"message-pipe-ws"})).connectionStatus().subscribe(function(e){this._dispatchStatusChange(S,e)}.bind(this)),this.on("pushstream_set_user_channel",function(e){this._setUserChannel(e)}.bind(this)),this._connectChannels(e)},_destructPushStream:function(){var e=t;t=null,e.disconnect(),e=n,n=null,e.disconnect(),this._dispatchStatusChangeFromOther(s.getItem(this._connectionStatusKey))},_activityTimeout:5e3,_delayTimeout:2e4,_pulseActivity:function(){this.ownPushStream()?this._lostOwn()?(p.logNormal("Lost own pushstream connection"),c.sendReport("site","pushstream_lost_own"),this._destructPushStream()):this._setMark():this._needInstantiating()&&!v&&(p.logNormal("Creating pushstream connection, because other tab lost it"),c.sendReport("site","pushstream_pick_up"),this._instantiatePushStream(this.getChannels()))},_markName:g+"mark",_lostOwn:function(){var e=s.getItem(this._markName);return!!e&&(e=this._decodeParams(e))[0]!==this.guid},_getMark:function(){return this._decodeParams(s.getItem(this._markName))},_setMark:function(){s.setItem(this._markName,this._codeParams([this.guid,(new Date).getTime()]))},_unsetMark:function(){s.setItem(this._markName,"")},_needInstantiating:function(){var e=s.getItem(this._markName);if(e){var t=(e=this._decodeParams(e))[1];return(new Date).getTime()-t>this._delayTimeout}return!0},_onRequestRecreate:function(e){if(!this.ownPushStream()&&this._needInstantiating()){var t=this._decodeParams(e)[0];p.logNormal("Creating pushstream connection after recreate request"),this._instantiatePushStream(t)}},_onUnload:function(){this.ownPushStream()&&(this._unsetMark(),
this._sendRecreateRequest())},_getChannels:function(){return t.getChannels().concat(n.getChannels())},_channelsName:g+"channels",_getChannelsFromStorage:function(){var e=s.getItem(this._channelsName);return e?JSON.parse(e):[]},getChannels:function(){return this.ownPushStream()?this._getChannels():this._getChannelsFromStorage()},_storeChannels:function(){s.setItem(this._channelsName,JSON.stringify(this._getChannels()))},_sendRecreateRequest:function(){var e=this._getChannels();i.emit(this._xEventRecreate,this._codeParams([e]))},ownPushStream:function(){return!!t||!!n},pushStream:function(){if(!this.ownPushStream())throw new Error("Not own PushStream");return t},isConnected:function(){return S>0},status:function(){return S||l.Closed},statusPrivate:function(){return y||l.Closed},_userChannel:function(e){return"private_"+e},userChannel:function(){if(!f)throw new Error("No user channel");return this._userChannel(f)},_xEventRecreate:m+"recreate",_xEventSend:m+"send",_xEventChannelAdd:m+"channelAdd",_xEventChannelRemove:m+"channelRemove",_xEventRequiredChannels:m+"requirech",_xEventConnectionStatus:m+"connectionStatus",_xEventReconnectCommand:m+"reconnectCommand",_xEventRequestLogs:m+"requestLogs",_xEventShareLogs:m+"shareLogs",_shareLogsKey:g+"shareLogs",_connectionStatusKey:g+"connectionStatus",_addChannel:function(e){var r=e.startsWith("private_")?n:t;r.hasChannel(e)||(r.addChannel(e),this._storeChannels())},addChannel:function(e){this.ownPushStream()?this._addChannel(e):i.emit(this._xEventChannelAdd,this._codeParams([e]))},_addChannelFromOther:function(e){var t=this._decodeParams(e)[0];this.ownPushStream()&&this._addChannel(t)},_removeChannel:function(e){var r=e.startsWith("private_")?n:t;r.hasChannel(e)&&(r.removeChannel(e),this._storeChannels())},removeChannel:function(e){this.ownPushStream()?this._removeChannel(e):i.emit(this._xEventChannelRemove,this._codeParams([e]))},_removeChannelFromOther:function(e){var t=this._decodeParams(e)[0];this.ownPushStream()&&this._removeChannel(t)},_connectChannels:function(e){t.addChannel("public"),void 0!==e&&e.length>0&&e.forEach((function(e){e.startsWith("private_")||t.hasChannel(e)||t.addChannel(e)})),"is_authenticated"in window?this._connectUserChannelInitial(!0):window.loginStateChange&&loginStateChange.subscribe(this,this._connectUserChannelInitial),t.connect()},_connectUserChannelInitial:function(e){e&&(is_authenticated?(f=user.private_channel,n.addChannel(this.userChannel()),n.connect()):f=null)},_changeLoginState:function(e){e||(is_authenticated?(f=user.private_channel,this.ownPushStream()&&(this._addChannel(this.userChannel()),n.connect())):(this.ownPushStream()&&(this._removeChannel(this.userChannel()),n.disconnect()),f=null))},_setUserChannel:function(e){p.logNormal("Set user channel "+e),e!==f&&(this.ownPushStream()&&f&&this._removeChannel(this.userChannel()),f=e,this.ownPushStream()&&f&&this._addChannel(this.userChannel()))},_dispatchStatusChange:function(e,t){this._dispatchStatusChangeToOthers(e,t),this._dispatchStatusChangeToSelf(e,t)},
_dispatchStatusChangeToSelf:function(e,t){e!==S&&(S=e,this._callStatusHandlers(e,!1)),t!==y&&(y=t,this._callStatusHandlers(t,!0))},_callStatusHandlers:function(e,t){p.logNormal("Connection status change: "+e+", private "+t),c.sendReport("site","pushstream_status_change"),h.forEach((function(n){n.isPrivate===t&&n.handler(e)}))},_decodeConnectionStatus:function(e){var t=parseInt(e,10);return isNaN(t)?this._decodeParams(e):[t,t]},_dispatchStatusChangeFromOther:function(e){var t=this._decodeConnectionStatus(e),n=t[0],r=t[1];this.ownPushStream()||this._dispatchStatusChangeToSelf(n,r)},_dispatchStatusChangeToOthers:function(e,t){if(this.ownPushStream()){var n=this._codeParams([e,t]);s.setItem(this._connectionStatusKey,n),i.emit(this._xEventConnectionStatus,n)}},_dispatchMessage:function(e,t,n){this._dispatchMessageToOthers(e,t,n),this._dispatchMessageToSelf(e,t,n,!1)},_dispatchMessageToSelf:function(e,t,n,r){n=e.channel,e=e.content,this._emit(e,t,n,r)},_dispatchMessageToOthers:function(e,t,n){var r=[e,t,n,(new Date).getTime()];i.emit(this._xEventSend,this._codeParams(r))},_dispatchMessageFromOther:function(e){if(!this.ownPushStream()){var t=this._decodeParams(e),n=t[0],r=t[1],i=t[2];this._dispatchMessageToSelf(n,r,i,!0)}},_isSpecialChannel:function(e){return/\*/.test(e)},_emit:function(e,t,n,r){function i(i){i.call(this,e,t,n,r)}for(var o in u[n]&&u[n].forEach(i,this),d){var s="^"+o.replace(/\*/g,".*?")+"$";new RegExp(s).test(n)&&d[o].forEach(i,this)}},on:function(e,t){var n=this._isSpecialChannel(e)?d:u;n[e]||(n[e]=[]),n[e].push(t)},off:function(e,t){var n=this._isSpecialChannel(e)?d:u;switch(arguments.length){case 0:u={},d={};break;case 1:n[e]&&delete n[e];break;default:if(n[e]){var r=n[e].indexOf(t);~r&&n[e].splice(r,1)}}},onStatus:function(e){h.push({handler:e,isPrivate:!1}),setTimeout((function(){e(S)}),0)},onPrivateStatus:function(e){h.push({handler:e,isPrivate:!0}),setTimeout((function(){e(y)}),0)},offStatus:function(e){h=h.filter((function(t){return t.handler!==e}))},forceConnect:function(){v=!1,p.logNormal("Creating pushstream connection after force connect"),this.ownPushStream()?(t.disconnect(),n.disconnect(),this._instantiatePushStream(this.getChannels())):this._needInstantiating()?this._instantiatePushStream():i.emit(this._xEventReconnectCommand,{})},disconnect:function(){this.ownPushStream()&&(this._destructPushStream(),this._unsetMark(),v=!0)},_dispatchReconnectCommandFromOther:function(){this.ownPushStream()&&this.forceConnect()},_getOwnLogs:function(e){if(this.ownPushStream()){var t=_(e,"PushStreamMultiplexer"),n=this.pushStream().getLogs();return[].concat(t,n)}return[]},_onRequestLogs:function(e){if(this.ownPushStream()){var t=this._getOwnLogs(e),n="";try{n=JSON.stringify(t)}catch(e){p.logError("Failed to stringify own pushstream logs")}s.setItem(this._shareLogsKey,n),i.emit(this._xEventShareLogs,n)}},getLogs:function(e){return new Promise(function(t){var n=setTimeout(function(){var e=s.getItem(this._shareLogsKey);t(null!==e?JSON.parse(e):[])}.bind(this),1e3),r=function(e){var o
;i.off(this._xEventShareLogs,r),i.emit(this._xEventShareLogs,""),clearTimeout(n);try{o=JSON.parse(e)}catch(e){o=[],p.logError("Failed to parse logs received from master tab")}t(o)}.bind(this);this.ownPushStream()?t(this._getOwnLogs(e)):(i.on(this._xEventShareLogs,r),i.emit(this._xEventRequestLogs))}.bind(this))}};return A._init(),window.addEventListener("unload",A._onUnload.bind(A)),i.on(A._xEventRecreate,A._onRequestRecreate.bind(A)),i.on(A._xEventSend,A._dispatchMessageFromOther.bind(A)),i.on(A._xEventChannelAdd,A._addChannelFromOther.bind(A)),i.on(A._xEventChannelRemove,A._removeChannelFromOther.bind(A)),i.on(A._xEventConnectionStatus,A._dispatchStatusChangeFromOther.bind(A)),i.on(A._xEventReconnectCommand,A._dispatchReconnectCommandFromOther.bind(A)),i.on(A._xEventRequestLogs,A._onRequestLogs.bind(A)),e=function(){window.loginStateChange&&loginStateChange.subscribe(A,A._changeLoginState)},"loading"!==document.readyState?e():document.addEventListener("DOMContentLoaded",e),setInterval(A._pulseActivity.bind(A),A._activityTimeout),A._pulseActivity(),A}();e.exports=h},50975:(e,t,n)=>{"use strict";n.d(t,{PushStream:()=>f});var r=n(88537),i=n(98125),o=n(44182);var s=n(52714),a=n.n(s),l=n(2872),c=n.n(l),u=n(8128);const d=(0,i.getLogger)("PersistentWebsocketTransport");class _ extends class{constructor(e,t,n){this._url="",this._socket=null,this._reconnectCount=0,this._onlineCancellationToken=null,this._connectionStatus=new(a())(o.ConnectionStatus.Closed),this._socketCloseHandler=this._onCloseCallback.bind(this),this._socketErrorHandler=this._onErrorCallback.bind(this),this._socketOpenHandler=this._onOpenCallback.bind(this),this._socketMessageHandler=this._onMessageCallback.bind(this),this._maxReconnectReachedEventDelegate=new(c()),this._shouldReconnect=!0,this._maxReconnectCount=null,this._reconnectTimeoutId=0,this._connectAbortController=null,this._tryReconnect=()=>{if(this._disconnect(),this._shouldReconnect){const e=this._getReconnectTimeout();this._logger.logNormal(`Sleeping some time before reconnect ${e}ms`),this._reconnectTimeoutId=setTimeout(this._tryReconnectImpl.bind(this),e)}else this._logger.logNormal("Skip reconnecting because of shouldReconnect state")},this._onOfflineHandler=()=>{this._removeOnOfflineListener(),this._logger.logInfo("Network status changed to offline - trying to reconnect"),this._tryReconnect()},this._logger=t,this._messageHandler=e,this._closeHandler=n,window.addEventListener("unload",()=>{t.logNormal("Unload event comes - disconnecting without reconnect after that..."),this._shouldReconnect=!1,this._disconnect()},!1)}setUrl(e){if(this._url===e)return;const t=this._connectionStatus.value()!==o.ConnectionStatus.Closed;t&&this._disconnect(),this._url=e,t&&this.connect()}url(){return this._url}connect(){this._connectImpl()}setMaxReconnectCount(e){this._maxReconnectCount=e}connectionStatus(){return this._connectionStatus.readonly()}disconnect(){this._shouldReconnect=!1,this._disconnect()}maxReconnectReachedEvent(){return this._maxReconnectReachedEventDelegate}
async _prepareParamsForConnection(e){}_disconnect(){var e;null===(e=this._connectAbortController)||void 0===e||e.abort(),this._connectAbortController=null,clearTimeout(this._reconnectTimeoutId),this._reconnectTimeoutId=0,this._connectionStatus.value()!==o.ConnectionStatus.Closed?this._socket?(this._logger.logNormal(`Closing connection to: ${this._socket.url}, currentStatus: ${o.ConnectionStatus[this._connectionStatus.value()]}`),this._disconnectTransport()):this._logger.logNormal("Disconnecting without socket - probably within preparing, it should be already scheduled for aborting"):this._logger.logNormal("Attempt to close connection but it is closed already")}_onErrorCallback(){this._logger.logInfo("Connection is closed by error"),this._tryReconnect()}_onCloseCallback(e){var t;this._logger.logInfo(`Connection is closed - code=${e.code} msg=${e.reason}`),null===(t=this._closeHandler)||void 0===t||t.call(this,e),this._tryReconnect()}_tryReconnectImpl(){return null!==this._maxReconnectCount&&this._reconnectCount===this._maxReconnectCount?(this._logger.logWarn("Maximum attempts to reconnect to websocket reached"),void this._maxReconnectReachedEventDelegate.fire()):(this._reconnectCount+=1,this._logger.logInfo("Reconnecting count: "+this._reconnectCount),navigator.onLine?(this._logger.logInfo("Network status: online - trying to connect"),void this.connect()):(this._logger.logInfo("Network status: offline - wait until online"),void(this._onlineCancellationToken=function(e){let t=e;const n=()=>{window.removeEventListener("online",n),t&&t()};return window.addEventListener("online",n),()=>{t=null}}(()=>{this._logger.logInfo("Network status changed to online - trying to connect"),this.connect()}))))}_onOpenCallback(){this._logger.logNormal("Connection opened"),this._reconnectCount=0,this._connectionStatus.setValue(o.ConnectionStatus.Open)}_onMessageCallback(e){this._messageHandler(e.data)}_getReconnectTimeout(){return this._reconnectCount<5?300:5e3}_setOnOfflineListener(){window.addEventListener("offline",this._onOfflineHandler)}_removeOnOfflineListener(){window.removeEventListener("offline",this._onOfflineHandler)}async _connectImpl(){if(this._connectionStatus.value()!==o.ConnectionStatus.Closed)return void this._logger.logNormal("Attempt to open connection but it is not closed");this._socket&&(this._logger.logError("Something went wrong - code 0x2"),this.disconnect()),this._onlineCancellationToken&&(this._onlineCancellationToken(),this._onlineCancellationToken=null),this._logger.logNormal("Connecting to "+this._url),this._shouldReconnect=!0,this._connectAbortController=new AbortController;const e=this._connectAbortController.signal;try{if(this._connectionStatus.setValue(o.ConnectionStatus.Connecting),await this._prepareParamsForConnection(e),e.aborted)throw(0,u.createAbortError)();this._socket=this._createNativeTransport(this._url),this._setOnOfflineListener()}catch(e){this._connectionStatus.setValue(o.ConnectionStatus.Closed),(0,u.skipAbortError)(e)}finally{this._connectAbortController=null}}}{constructor(e,t){super(e,d,t)
}sendMessage(e){this._connectionStatus.value()===o.ConnectionStatus.Open?this._socket?this._socket.send(e):d.logError("Something went wrong - code 0x3"):d.logWarn("Attempt to send message but connection is not opened")}_createNativeTransport(e){const t=new WebSocket(e);return t.binaryType="arraybuffer",t.addEventListener("error",this._socketErrorHandler),t.addEventListener("close",this._socketCloseHandler),t.addEventListener("open",this._socketOpenHandler),t.addEventListener("message",this._socketMessageHandler),t}_disconnectTransport(){if(null===this._socket)return;this._socket.removeEventListener("error",this._socketErrorHandler),this._socket.removeEventListener("close",this._socketCloseHandler),this._socket.removeEventListener("open",this._socketOpenHandler),this._socket.removeEventListener("message",this._socketMessageHandler),this._removeOnOfflineListener();const e=this._socket;this._socket=null,this._connectionStatus.setValue(o.ConnectionStatus.Closed),e.readyState!==WebSocket.CLOSED&&e.close()}}var p=n(52485);const h=(0,i.getLogger)("PushStream");class f{constructor(e,t){this._channels=[],this._transport=new _(this._onPushStreamMessage.bind(this),this._onPushStreamClose.bind(this)),this._settings=t,this._messageHandler=e}addChannel(e){(0,r.assert)(!this.hasChannel(e),"Channel already subscribed"),h.logNormal("Adding channel "+e),this._channels.push(e),this._transport.setUrl(this._generateUrl())}removeChannel(e){const t=this._channels.indexOf(e);(0,r.assert)(-1!==t,"There is no that channel"),h.logNormal("Removing channel "+e),this._channels.splice(t,1),this._transport.setUrl(this._generateUrl())}getChannels(){return this._channels}hasChannel(e){return-1!==this._channels.indexOf(e)}connectionStatus(){return this._transport.connectionStatus()}connect(){(0,r.assert)(0!==this._channels.length,"There is no channels"),this._transport.connect()}disconnect(){this._transport.disconnect()}sendMessage(e){this._transport.sendMessage(e)}getLogs(e){return(0,i.getRawLogHistory)(e,"PushStream")}_onPushStreamMessage(e){if("string"!=typeof e)throw new Error("Wrong message type, expected string");const t=JSON.parse(e),n=t.id,r=t.channel;-2===n?h.logWarn("Received unexpected message: about removed the channel"):n>0&&(h.logDebug(`Received message: id="${n}" channel="${r}"`),this._messageHandler(t.text,n,r))}_onPushStreamClose(e){1005===e.code&&p.telemetry.sendChartReport("websocket_code_1005")}_generateUrl(){const e=this._channels.join("/");return`${this._settings.url}/${this._settings.urlPath}/${e}`}}},20120:(e,t,n)=>{"use strict";n.d(t,{syncUserData:()=>c,syncUserConversionData:()=>u});var r=n(98125),i=n(51768),o=n(85198);const s=(0,r.getLogger)("User.Sync");function a(e){return`${e}_${window.user&&window.user.username||""}`}function l(e,t,n){n!==window.user.pro_plan&&(window.user.pro_plan=n,window.user.is_pro=Boolean(n),(0,i.trackEvent)("Sync User Data","Different Pro Plan",a(e))),t!==window.is_authenticated&&(window.is_authenticated=t,window.loginStateChange.fire(),(0,i.trackEvent)("Sync User Data","Different Auth",a(e)))}
async function c(e){try{const t=await n.e(254).then(n.bind(n,60347));l(e,!0,(await t.getMe()).pro_plan)}catch(t){!function(e,t){"not_authenticated"===t.type?l(e,!1,void 0):s.logError(t.message)}(e,t)}}async function u(e){const t=await(0,o.fetch)("/gopro/"),n=await t.json();return l(e,n.is_authenticated,n.user.pro_plan),n}},52485:(e,t,n)=>{"use strict";n.d(t,{telemetry:()=>d});var r=n(2872),i=n.n(r),o=n(85198),s=n(49483),a=n(84015);n(51872);const l=(0,n(98125).getLogger)("Common.Telemetry"),c={default:15e3,site:3e5},u=["before_websocket_connection_time_frame","websocket_connection_time_frame","first_series_full_time_frame","page_full_load_time_frame","page_load_time_frame"];const d=new class{constructor(){this.reportSent=new(i()),this.timeCounters={series:{marks:[]},study:{},pine:{}},this._timeoutIds={},this._commonAdditionalData={cluster:null,userId:"0"},this._reportStash={}}setSessionInfo(e){const t=this._parseCluster(e);null!==t&&(this._commonAdditionalData.cluster=t)}sendReport(e,t,n){var r;if(!this._isAbleToSendReport(t))return;const i=this._getSubserviceType(e),o=this._getHost(e,i);if(null!==o){if(n=void 0===n?{count:1}:n,this._addReportToStash(n,t,o),!this._timeoutIds[e]){const t=null!==(r=c[e])&&void 0!==r?r:c.default;this._timeoutIds[e]=setTimeout(this._sendTelemetryToService.bind(this,e,o),t)}}else l.logError(`Unable to get host for counter: ${t}, metric type: ${e}, serivce type: ${i}`)}sendChartReport(e,t,n=!0){this._sendServiceSpecifiedReport("charts",e,t,n)}sendLineToolsStorageReport(e,t,n=!0){this._sendServiceSpecifiedReport("line_tools_storage",e,t,n)}_sendServiceSpecifiedReport(e,t,n,r=!0){this._updateUserInfo(),n=void 0===n?{count:1}:n,r&&(n=this._appendCommonAdditionalInfo(n,["cluster","userId"])),this.sendReport(e,t,n)}_updateUserInfo(){const e="user"in window&&"id"in window.user?window.user.id:"0";this._commonAdditionalData.userId=String(e)}_isAbleToSendReport(e){const t=window.TELEMETRY_HOSTS,n=u.includes(e),r=Boolean(window.TradingView.onChartPage||(0,s.onWidget)());return t&&(!n||r)}_sendTelemetryToService(e,t){if(this._reportStash.hasOwnProperty(t)){const e=this._cropParams(this._reportStash[t]),n=this._renameAllParams(e),r={event:"report_stash",params:this._cleanAllParams(n)};l.logDebug(`Report to host: ${t}; stash: ${JSON.stringify(this._reportStash[t])}`),this.reportSent.fire(this._reportStash[t]),delete this._reportStash[t],(0,o.fetch)(t+"/report",{method:"POST",body:JSON.stringify(r)})}this._timeoutIds[e]=null}_getHost(e,t){const n=window.TELEMETRY_HOSTS,r=n[e]&&n[e][t];return Boolean(r)?r:null}_getSubserviceType(e){if(!["charts","site"].includes(e))return"all";let t="free";const n=window.user.is_pro;return"charts"===e&&(0,a.isOnMobileAppPage)("old")?t=n?"ios_pro":"ios_free":"charts"===e&&(0,a.isOnMobileAppPage)("new")?t=n?"android_pro":"android_free":(0,s.onWidget)()?t="widget":n&&(t="pro"),t}_parseCluster(e){let t;try{t=JSON.parse(e).session_id}catch(e){return l.logError("Could not parse cluster id (session id)"),null}const n=/(.*@)(.*)/gi.exec(t);return null!==n&&n.length>=3?n[2]:null}
_appendCommonAdditionalInfo(e,t){return t.forEach(t=>{t in this._commonAdditionalData&&(e.additional=e.additional||{},e.additional[t]=this._commonAdditionalData[t])}),e}_cropParams(e){var t;for(const n in e)e.hasOwnProperty(n)&&e[n].length>1e3&&(e.too_much_metrics_frame=null!==(t=e.too_much_metrics_frame)&&void 0!==t?t:[],e.too_much_metrics_frame.push({value:e[n].length,additional:{event:n}}),delete e[n]);return e}_renameAllParams(e){const t={};for(const n in e)e.hasOwnProperty(n)&&(t[n]=[],e[n].forEach(e=>{t[n].push(this._renameEntryParams(e))}));return t}_renameEntryParams(e){const t={count:"c",value:"v",text:"t",additional:"a"};return Object.keys(e).reduce((n,r)=>(n[t[r]]=e[r],n),{})}_cleanAllParams(e){const t={};for(const n in e)if(e.hasOwnProperty(n)){t[n]=[];const r={c:0};e[n].forEach(e=>{const i=this._cleanEntryParams(e),o=Object.keys(i).length;1===o&&void 0!==i.c?r.c+=i.c:o>0&&t[n].push(i)}),r.c>0&&t[n].push(r),0===t[n].length&&delete t[n]}return t}_cleanEntryParams(e){const t=Object.keys(e).reduce((t,n)=>"c"!==n&&"t"!==n||e[n]?(t[n]=e[n],t):t,{});return"c"in t||"v"in t||"t"in t?t:{}}_addReportToStash(e,t,n){n in this._reportStash||(this._reportStash[n]={}),t in this._reportStash[n]||(this._reportStash[n][t]=[]),Object.keys(e).length>0&&this._reportStash[n][t].push(e)}}}}]);