/* Minification failed. Returning unminified contents.
(1,1): run-time error CSS1019: Unexpected token, found '!'
(1,2): run-time error CSS1019: Unexpected token, found 'function('
(1,14): run-time error CSS1031: Expected selector, found ')'
(1,14): run-time error CSS1025: Expected comma or open brace, found ')'
(1,160): run-time error CSS1019: Unexpected token, found '('
(1,166): run-time error CSS1031: Expected selector, found 'function('
(1,10924): run-time error CSS1019: Unexpected token, found ')'
(3,1): run-time error CSS1019: Unexpected token, found '('
(3,11): run-time error CSS1031: Expected selector, found '('
(3,11): run-time error CSS1025: Expected comma or open brace, found '('
(7,2): run-time error CSS1019: Unexpected token, found '('
(7,9): run-time error CSS1031: Expected selector, found '('
(816,1): run-time error CSS1019: Unexpected token, found '!'
(816,2): run-time error CSS1019: Unexpected token, found 'function('
(816,11): run-time error CSS1019: Unexpected token, found ')'
(816,12): run-time error CSS1019: Unexpected token, found '{'
(816,13): run-time error CSS1019: Unexpected token, found '"use strict"'
(816,35): run-time error CSS1031: Expected selector, found 'n('
(816,35): run-time error CSS1025: Expected comma or open brace, found 'n('
(816,49): run-time error CSS1031: Expected selector, found 'i('
(816,49): run-time error CSS1025: Expected comma or open brace, found 'i('
(816,289): run-time error CSS1031: Expected selector, found 'o('
(816,289): run-time error CSS1025: Expected comma or open brace, found 'o('
(816,590): run-time error CSS1031: Expected selector, found 's('
(816,590): run-time error CSS1025: Expected comma or open brace, found 's('
(816,949): run-time error CSS1031: Expected selector, found 'a('
(816,949): run-time error CSS1025: Expected comma or open brace, found 'a('
(816,992): run-time error CSS1031: Expected selector, found 'u('
(816,992): run-time error CSS1025: Expected comma or open brace, found 'u('
(816,1200): run-time error CSS1031: Expected selector, found 'f('
(816,1200): run-time error CSS1025: Expected comma or open brace, found 'f('
(816,1322): run-time error CSS1031: Expected selector, found 'h('
(816,1322): run-time error CSS1025: Expected comma or open brace, found 'h('
(816,1446): run-time error CSS1031: Expected selector, found ';'
(816,1446): run-time error CSS1025: Expected comma or open brace, found ';'
(816,1448): run-time error CSS1031: Expected selector, found '='
(816,1448): run-time error CSS1025: Expected comma or open brace, found '='
(816,1524): run-time error CSS1019: Unexpected token, found ','
(816,1541): run-time error CSS1031: Expected selector, found '='
(816,1541): run-time error CSS1025: Expected comma or open brace, found '='
(816,1616): run-time error CSS1019: Unexpected token, found ','
(816,1622): run-time error CSS1031: Expected selector, found '='
(816,1622): run-time error CSS1025: Expected comma or open brace, found '='
(816,1967): run-time error CSS1019: Unexpected token, found ','
(816,1977): run-time error CSS1031: Expected selector, found '='
(816,1977): run-time error CSS1025: Expected comma or open brace, found '='
(816,2065): run-time error CSS1019: Unexpected token, found ','
(816,2074): run-time error CSS1031: Expected selector, found '='
(816,2074): run-time error CSS1025: Expected comma or open brace, found '='
(816,2121): run-time error CSS1019: Unexpected token, found ','
(816,2128): run-time error CSS1031: Expected selector, found '='
(816,2128): run-time error CSS1025: Expected comma or open brace, found '='
(816,2216): run-time error CSS1019: Unexpected token, found ','
(816,2231): run-time error CSS1031: Expected selector, found '='
(816,2231): run-time error CSS1025: Expected comma or open brace, found '='
(816,2294): run-time error CSS1030: Expected identifier, found '|'
(816,2294): run-time error CSS1019: Unexpected token, found '|'
(816,2295): run-time error CSS1019: Unexpected token, found 'function('
(816,2305): run-time error CSS1031: Expected selector, found ')'
(816,2305): run-time error CSS1025: Expected comma or open brace, found ')'
(816,2314): run-time error CSS1019: Unexpected token, found ','
(816,2338): run-time error CSS1031: Expected selector, found '='
(816,2338): run-time error CSS1025: Expected comma or open brace, found '='
(816,2445): run-time error CSS1019: Unexpected token, found ','
(816,2463): run-time error CSS1031: Expected selector, found '='
(816,2463): run-time error CSS1025: Expected comma or open brace, found '='
(816,2493): run-time error CSS1019: Unexpected token, found ','
(816,2520): run-time error CSS1031: Expected selector, found '='
(816,2520): run-time error CSS1025: Expected comma or open brace, found '='
(816,2559): run-time error CSS1019: Unexpected token, found ','
(816,2560): run-time error CSS1019: Unexpected token, found '"undefined"'
(816,2571): run-time error CSS1019: Unexpected token, found '!'
(816,2572): run-time error CSS1019: Unexpected token, found '='
(816,2586): run-time error CSS1031: Expected selector, found '&'
(816,2586): run-time error CSS1025: Expected comma or open brace, found '&'
(817): Scanner error CSS1002: Unterminated string: '*+.\^_`|~]/i.test(t))throw new TypeError("Invalid character in header field name");return t.toLowerCase()}function d(t){return"string"!=typeof t&&(t=String(t)),t}function l(e){var t={next:function(){var t=e.shift();return{done:void 0===t,value:t}}};return r&&(t[Symbol.iterator]=function(){return t}),t}function y(e){this.map={},e instanceof y?e.forEach(function(t,e){this.append(e,t)},this):Array.isArray(e)?e.forEach(function(t){this.append(t[0],t[1])},this):e&&Object.getOwnPropertyNames(e).forEach(function(t){this.append(t,e[t])},this)}function p(t){if(t.bodyUsed)return Promise.reject(new TypeError("Already read"));t.bodyUsed=!0}function b(r){return new Promise(function(t,e){r.onload=function(){t(r.result)},r.onerror=function(){e(r.error)}})}function m(t){var e=new FileReader,r=b(e);return e.readAsArrayBuffer(t),r}function w(t){if(t.slice)return t.slice(0);var e=new Uint8Array(t.byteLength);return e.set(new Uint8Array(t)),e.buffer}function _(){return this.bodyUsed=!1,this._initBody=function(t){if(this._bodyInit=t)if("string"==typeof t)this._bodyText=t;else if(s&&Blob.prototype.isPrototypeOf(t))this._bodyBlob=t;else if(n&&FormData.prototype.isPrototypeOf(t))this._bodyFormData=t;else if(e&&URLSearchParams.prototype.isPrototypeOf(t))this._bodyText=t.toString();else if(o&&s&&a(t))this._bodyArrayBuffer=w(t.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer]);else{if(!o||!ArrayBuffer.prototype.isPrototypeOf(t)&&!u(t))throw new Error("unsupported BodyInit type");this._bodyArrayBuffer=w(t)}else this._bodyText="";this.headers.get("content-type")||("string"==typeof t?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):e&&URLSearchParams.prototype.isPrototypeOf(t)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},s&&(this.blob=function(){var t=p(this);if(t)return t;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?p(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(m)}),this.text=function(){var t=p(this);if(t)return t;if(this._bodyBlob)return function(t){var e=new FileReader,r=b(e);return e.readAsText(t),r}(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(function(t){for(var e=new Uint8Array(t),r=new Array(e.length),n=0;n<e.length;n++)r[n]=String.fromCharCode(e[n]);return r.join("")}(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},n&&(this.formData=function(){return this.text().then(A)}),this.json=function(){return this.text().then(JSON.parse)},this}function v(t,e){var r=(e=e||{}).body;if(t instanceof v){if(t.bodyUsed)throw new TypeError("Already read");this.url=t.url,this.credentials=t.credentials,e.headers||(this.headers=new y(t.headers)),this.method=t.method,this.mode=t.mode,r||null==t._bodyInit||(r=t._bodyInit,t.bodyUsed=!0)}else this.url=String(t);if(this.credentials=e.credentials||this.credentials||"omit",!e.headers&&this.headers||(this.headers=new y(e.headers)),this.method=function(t){var e=t.toUpperCase();return-1<f.indexOf(e)?e:t}(e.method||this.method||"GET"),this.mode=e.mode||this.mode||null,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&r)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(r)}function A(t){var o=new FormData;return t.trim().split("&").forEach(function(t){if(t){var e=t.split("="),r=e.shift().replace(/\+/g," "),n=e.join("=").replace(/\+/g," ");o.append(decodeURIComponent(r),decodeURIComponent(n))}}),o}function T(t,e){e=e||{},this.type="default",this.status="status"in e?e.status:200,this.ok=200<=this.status&&this.status<300,this.statusText="statusText"in e?e.statusText:"OK",this.headers=new y(e.headers),this.url=e.url||"",this._initBody(t)}}("undefined"!=typeof self?self:window)}();
 */
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e(t.TradingView={})}(this,function(t){"use strict";var e=Object.assign||function(t){for(var e,o=1,i=arguments.length;o<i;o++)for(var n in e=arguments[o])Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t};function o(t,i){var n=e({},t);for(var s in i)"object"!=typeof t[s]||null===t[s]||Array.isArray(t[s])?void 0!==i[s]&&(n[s]=i[s]):n[s]=o(t[s],i[s]);return n}var i={mobile:{disabled_features:["left_toolbar","header_widget","timeframes_toolbar","edit_buttons_in_legend","context_menus","control_bar","border_around_the_chart"],enabled_features:[]}},n={width:800,height:500,interval:"D",timezone:"Etc/UTC",container_id:"",library_path:"",locale:"en",widgetbar:{details:!1,watchlist:!1,watchlist_settings:{default_symbols:[]}},overrides:{"mainSeriesProperties.showCountdown":!1},studies_overrides:{},trading_customization:{position:{},order:{}},brokerConfig:{configFlags:{}},fullscreen:!1,autosize:!1,disabled_features:[],enabled_features:[],debug:!1,logo:{},time_frames:[{text:"5y",resolution:"W"},{text:"1y",resolution:"W"},{text:"6m",resolution:"120"},{text:"3m",resolution:"60"},{text:"1m",resolution:"30"},{text:"5d",resolution:"5"},{text:"1d",resolution:"1"}],client_id:"0",user_id:"0",charts_storage_api_version:"1.0",favorites:{intervals:[],chartTypes:[]}};function s(){return"1.15 (internal id 8562c7b8 @ 2019-12-18 11:58:08.555993)"}var r=function(){function t(t){if(this._id="tradingview_"+(1048576*(1+Math.random())|0).toString(16).substring(1),this._ready=!1,this._readyHandlers=[],this._onWindowResize=this._autoResizeChart.bind(this),!t.datafeed)throw new Error("Datafeed is not defined");if(this._options=o(n,t),t.preset){var e=i[t.preset];e?(void 0!==this._options.disabled_features?this._options.disabled_features=this._options.disabled_features.concat(e.disabled_features):this._options.disabled_features=e.disabled_features,void 0!==this._options.enabled_features?this._options.enabled_features=this._options.enabled_features.concat(e.enabled_features):this._options.enabled_features=e.enabled_features):console.warn("Unknown preset: `"+t.preset+"`")}"Dark"===this._options.theme&&void 0===this._options.loading_screen&&(this._options.loading_screen={backgroundColor:"#131722"}),this._create()}return t.prototype.onChartReady=function(t){this._ready?t.call(this):this._readyHandlers.push(t)},t.prototype.headerReady=function(){var t=this;return this._innerWindowLoaded.then(function(){return t._innerWindow().headerReady()})},t.prototype.onGrayedObjectClicked=function(t){this._innerAPI().onGrayedObjectClicked(t)},t.prototype.onShortcut=function(t,e){this._innerWindow().createShortcutAction(t,e)},t.prototype.subscribe=function(t,e){this._innerAPI().subscribe(t,e)},t.prototype.unsubscribe=function(t,e){this._innerAPI().unsubscribe(t,e)},t.prototype.chart=function(t){return this._innerAPI().chart(t)},t.prototype.setLanguage=function(t){this.remove(),this._options.locale=t,this._create()},t.prototype.setSymbol=function(t,e,o){this._innerAPI().changeSymbol(t,e+"",o)},t.prototype.remove=function(){window.removeEventListener("resize",this._onWindowResize),this._readyHandlers.splice(0,this._readyHandlers.length),delete window[this._id],this._iFrame.parentNode&&this._iFrame.parentNode.removeChild(this._iFrame)},t.prototype.closePopupsAndDialogs=function(){this._innerAPI().closePopupsAndDialogs()},t.prototype.selectLineTool=function(t){this._innerAPI().selectLineTool(t)},t.prototype.selectedLineTool=function(){return this._innerAPI().selectedLineTool()},t.prototype.save=function(t){this._innerAPI().saveChart(t)},t.prototype.load=function(t,e){this._innerAPI().loadChart({json:t,extendedData:e})},t.prototype.getSavedCharts=function(t){this._innerAPI().getSavedCharts(t)},t.prototype.loadChartFromServer=function(t){this._innerAPI().loadChartFromServer(t)},t.prototype.saveChartToServer=function(t,e,o){this._innerAPI().saveChartToServer(t,e,o)},t.prototype.removeChartFromServer=function(t,e){this._innerAPI().removeChartFromServer(t,e)},t.prototype.onContextMenu=function(t){this._innerAPI().onContextMenu(t)},t.prototype.createButton=function(t){return this._innerWindow().createButton(t)},t.prototype.showNoticeDialog=function(t){this._innerAPI().showNoticeDialog(t)},t.prototype.showConfirmDialog=function(t){this._innerAPI().showConfirmDialog(t)},t.prototype.showLoadChartDialog=function(){this._innerAPI().showLoadChartDialog()},t.prototype.showSaveAsChartDialog=function(){this._innerAPI().showSaveAsChartDialog()},t.prototype.symbolInterval=function(){return this._innerAPI().getSymbolInterval()},t.prototype.mainSeriesPriceFormatter=function(){return this._innerAPI().mainSeriesPriceFormatter()},t.prototype.getIntervals=function(){return this._innerAPI().getIntervals()},t.prototype.getStudiesList=function(){return this._innerAPI().getStudiesList()},t.prototype.addCustomCSSFile=function(t){this._innerWindow().addCustomCSSFile(t)},t.prototype.applyOverrides=function(t){this._options=o(this._options,{overrides:t}),this._innerWindow().applyOverrides(t)},t.prototype.applyStudiesOverrides=function(t){this._innerWindow().applyStudiesOverrides(t)},t.prototype.watchList=function(){return this._innerAPI().watchlist()},t.prototype.activeChart=function(){return this._innerAPI().activeChart()},t.prototype.chartsCount=function(){return this._innerAPI().chartsCount()},t.prototype.layout=function(){return this._innerAPI().layout()},t.prototype.setLayout=function(t){this._innerAPI().setLayout(t)},t.prototype.layoutName=function(){return this._innerAPI().layoutName()},t.prototype.changeTheme=function(t){this._innerWindow().changeTheme(t)},t.prototype.takeScreenshot=function(){this._innerAPI().takeScreenshot()},t.prototype.lockAllDrawingTools=function(){return this._innerAPI().lockAllDrawingTools()},t.prototype.hideAllDrawingTools=function(){return this._innerAPI().hideAllDrawingTools()},t.prototype.magnetEnabled=function(){return this._innerAPI().magnetEnabled()},t.prototype.magnetMode=function(){return this._innerAPI().magnetMode()},t.prototype.undoRedoState=function(){return this._innerAPI().undoRedoState()},t.prototype._innerAPI=function(){return this._innerWindow().tradingViewApi},t.prototype._innerWindow=function(){return this._iFrame.contentWindow},t.prototype._autoResizeChart=function(){this._options.fullscreen&&(this._iFrame.style.height=window.innerHeight+"px")},t.prototype._create=function(){var t=this,e=this._render(),o=document.getElementById(this._options.container_id);if(null===o)throw new Error("There is no such element - #"+this._options.container_id);o.innerHTML=e,this._iFrame=o.querySelector("#"+this._id);var i=this._iFrame;(this._options.autosize||this._options.fullscreen)&&(i.style.width="100%",this._options.fullscreen||(i.style.height="100%")),window.addEventListener("resize",this._onWindowResize),this._onWindowResize(),this._innerWindowLoaded=new Promise(function(t){var e=function(){i.removeEventListener("load",e,!1),t()};i.addEventListener("load",e,!1)}),this._innerWindowLoaded.then(function(){t._innerWindow().widgetReady(function(){t._ready=!0;for(var e=0,o=t._readyHandlers;e<o.length;e++){var i=o[e];try{i.call(t)}catch(t){console.error(t)}}t._innerWindow().initializationFinished()})})},t.prototype._render=function(){var t=window;if(t[this._id]={datafeed:this._options.datafeed,customFormatters:this._options.customFormatters,brokerFactory:this._options.brokerFactory,overrides:this._options.overrides,studiesOverrides:this._options.studies_overrides,tradingCustomization:this._options.trading_customization,disabledFeatures:this._options.disabled_features,enabledFeatures:this._options.enabled_features,brokerConfig:this._options.brokerConfig,restConfig:this._options.restConfig,favorites:this._options.favorites,logo:this._options.logo,numeric_formatting:this._options.numeric_formatting,rss_news_feed:this._options.rss_news_feed,newsProvider:this._options.news_provider,loadLastChart:this._options.load_last_chart,saveLoadAdapter:this._options.save_load_adapter,loading_screen:this._options.loading_screen,settingsAdapter:this._options.settings_adapter,getCustomIndicators:this._options.custom_indicators_getter},this._options.saved_data)t[this._id].chartContent={json:this._options.saved_data};else if(!Boolean(this._options.symbol))throw new Error("Symbol is not defined");var e=(this._options.library_path||"")+"static/"+encodeURIComponent(this._options.locale)+"-tv-chart.8562c7b8f7bdb50c1f5d.html#symbol="+encodeURIComponent(this._options.symbol||"")+"&interval="+encodeURIComponent(this._options.interval)+(this._options.timeframe?"&timeframe="+encodeURIComponent(this._options.timeframe):"")+(this._options.toolbar_bg?"&toolbarbg="+encodeURIComponent(this._options.toolbar_bg.replace("#","")):"")+(this._options.studies_access?"&studiesAccess="+encodeURIComponent(JSON.stringify(this._options.studies_access)):"")+"&widgetbar="+encodeURIComponent(JSON.stringify(this._options.widgetbar))+(this._options.drawings_access?"&drawingsAccess="+encodeURIComponent(JSON.stringify(this._options.drawings_access)):"")+"&timeFrames="+encodeURIComponent(JSON.stringify(this._options.time_frames))+"&locale="+encodeURIComponent(this._options.locale)+"&uid="+encodeURIComponent(this._id)+"&clientId="+encodeURIComponent(String(this._options.client_id))+"&userId="+encodeURIComponent(String(this._options.user_id))+(this._options.charts_storage_url?"&chartsStorageUrl="+encodeURIComponent(this._options.charts_storage_url):"")+(this._options.charts_storage_api_version?"&chartsStorageVer="+encodeURIComponent(this._options.charts_storage_api_version):"")+(this._options.custom_css_url?"&customCSS="+encodeURIComponent(this._options.custom_css_url):"")+(this._options.auto_save_delay?"&autoSaveDelay="+encodeURIComponent(String(this._options.auto_save_delay)):"")+"&debug="+encodeURIComponent(String(this._options.debug))+(this._options.snapshot_url?"&snapshotUrl="+encodeURIComponent(this._options.snapshot_url):"")+(this._options.timezone?"&timezone="+encodeURIComponent(this._options.timezone):"")+(this._options.study_count_limit?"&studyCountLimit="+encodeURIComponent(String(this._options.study_count_limit)):"")+(this._options.symbol_search_request_delay?"&ssreqdelay="+encodeURIComponent(String(this._options.symbol_search_request_delay)):"")+(this._options.theme?"&theme="+encodeURIComponent(String(this._options.theme)):"");return'<iframe id="'+this._id+'" name="'+this._id+'"  src="'+e+'"'+(this._options.autosize||this._options.fullscreen?"":' width="'+this._options.width+'" height="'+this._options.height+'"')+' frameborder="0" allowTransparency="true" scrolling="no" allowfullscreen style="display:block;"></iframe>'},t}();window.TradingView=window.TradingView||{},window.TradingView.version=s,t.version=s,t.widget=r,Object.defineProperty(t,"__esModule",{value:!0})});

(function (global, factory) {
	typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
	typeof define === 'function' && define.amd ? define(['exports'], factory) :
	(factory((global.Datafeeds = {})));
}(this, (function (exports) { 'use strict';

/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0

THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.

See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */

var extendStatics = Object.setPrototypeOf ||
    ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
    function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } };

function __extends(d, b) {
    extendStatics(d, b);
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}

/**
 * If you want to enable logs from datafeed set it to `true`
 */
var isLoggingEnabled = false;
function logMessage(message) {
    if (isLoggingEnabled) {
        var now = new Date();
        console.log(now.toLocaleTimeString() + "." + now.getMilliseconds() + "> " + message);
    }
}
function getErrorMessage(error) {
    if (error === undefined) {
        return '';
    }
    else if (typeof error === 'string') {
        return error;
    }
    return error.message;
}

var HistoryProvider = /** @class */ (function () {
    function HistoryProvider(datafeedUrl, requester) {
        this._datafeedUrl = datafeedUrl;
        this._requester = requester;
    }
    HistoryProvider.prototype.getBars = function (symbolInfo, resolution, rangeStartDate, rangeEndDate) {
        var _this = this;
        var pmaps = {
            "1": "intraday_1",
            "5": "intraday_5",
            "15": "intraday_15",
            "30": "intraday_30",
            "60": "intraday_60",
            "D": "day",
            "1D": "day",
            "W": "week",
            "1W": "week",
            "M": "month",
            "1M": "month",

        };
        var dtmaps = {
            "1": "INTRA",
            "5": "INTRA",
            "15": "INTRA",
            "30": "INTRA",
            "60": "INTRA",
            "D": "DAILY",
            "1D": "DAILY",
            "W": "DAILY",
            "1W": "DAILY",
            "M": "MONTHLY",
            "1M": "MONTHLY",
        };

        var requestParams = {
            symbol: symbolInfo.ticker || '',
            dt: dtmaps[resolution],
            p: pmaps[resolution],
            ajust: withAdjust,
            from: rangeStartDate,
            to: rangeEndDate,
        };
        return new Promise(function (resolve, reject) {
            _this._requester.sendRequest(_this._datafeedUrl, 'history', requestParams)
                .then(function (response) {
                if (response.s !== 'ok' && response.s !== 'no_data') {
                    reject(response.errmsg);
                    return;
                }
                var bars = [];
                var meta = {
                    noData: false,
                };
                if (response.s === 'no_data') {
                    meta.noData = true;
                    meta.nextTime = response.nextTime;
                }
                else {
                    var volumePresent = response.v !== undefined;
                    var ohlPresent = response.o !== undefined;
                    for (var i = 0; i < response.t.length; ++i) {
                        var barValue = {
                            time: response.t[i] * 1000,
                            close: Number(response.c[i]),
                            open: Number(response.c[i]),
                            high: Number(response.c[i]),
                            low: Number(response.c[i]),
                        };
                        if (ohlPresent) {
                            barValue.open = Number(response.o[i]);
                            barValue.high = Number(response.h[i]);
                            barValue.low = Number(response.l[i]);
                        }
                        if (volumePresent) {
                            barValue.volume = Number(response.v[i]);
                        }
                        bars.push(barValue);
                    }
                }
                resolve({
                    bars: bars,
                    meta: meta,
                });
            })
                .catch(function (reason) {
                var reasonString = getErrorMessage(reason);
                console.warn("HistoryProvider: getBars() failed, error=" + reasonString);
                reject(reasonString);
            });
        });
    };
    return HistoryProvider;
}());

var DataPulseProvider = /** @class */ (function () {
    function DataPulseProvider(historyProvider, updateFrequency) {
        this._subscribers = {};
        this._requestsPending = 0;
        this._historyProvider = historyProvider;
        setInterval(this._updateData.bind(this), updateFrequency);
    }
    DataPulseProvider.prototype.subscribeBars = function (symbolInfo, resolution, newDataCallback, listenerGuid) {
        if (this._subscribers.hasOwnProperty(listenerGuid)) {
            logMessage("DataPulseProvider: already has subscriber with id=" + listenerGuid);
            return;
        }
        this._subscribers[listenerGuid] = {
            lastBarTime: null,
            listener: newDataCallback,
            resolution: resolution,
            symbolInfo: symbolInfo,
        };
        logMessage("DataPulseProvider: subscribed for #" + listenerGuid + " - {" + symbolInfo.name + ", " + resolution + "}");
    };
    DataPulseProvider.prototype.unsubscribeBars = function (listenerGuid) {
        delete this._subscribers[listenerGuid];
        logMessage("DataPulseProvider: unsubscribed for #" + listenerGuid);
    };
    DataPulseProvider.prototype._updateData = function () {
        var this$1 = this;

        var _this = this;
        if (this._requestsPending > 0) {
            return;
        }
        this._requestsPending = 0;
        var _loop_1 = function (listenerGuid) {
            this_1._requestsPending += 1;
            this_1._updateDataForSubscriber(listenerGuid)
                .then(function () {
                _this._requestsPending -= 1;
                logMessage("DataPulseProvider: data for #" + listenerGuid + " updated successfully, pending=" + _this._requestsPending);
            })
                .catch(function (reason) {
                _this._requestsPending -= 1;
                logMessage("DataPulseProvider: data for #" + listenerGuid + " updated with error=" + getErrorMessage(reason) + ", pending=" + _this._requestsPending);
            });
        };
        var this_1 = this;
        for (var listenerGuid in this$1._subscribers) {
            _loop_1(listenerGuid);
        }
    };
    DataPulseProvider.prototype._updateDataForSubscriber = function (listenerGuid) {
        var _this = this;
        var subscriptionRecord = this._subscribers[listenerGuid];
        var rangeEndTime = parseInt((Date.now() / 1000).toString());
        // BEWARE: please note we really need 2 bars, not the only last one
        // see the explanation below. `10` is the `large enough` value to work around holidays
        var rangeStartTime = rangeEndTime - periodLengthSeconds(subscriptionRecord.resolution, 10);
        return this._historyProvider.getBars(subscriptionRecord.symbolInfo, subscriptionRecord.resolution, rangeStartTime, rangeEndTime)
            .then(function (result) {
            _this._onSubscriberDataReceived(listenerGuid, result);
        });
    };
    DataPulseProvider.prototype._onSubscriberDataReceived = function (listenerGuid, result) {
        // means the subscription was cancelled while waiting for data
        if (!this._subscribers.hasOwnProperty(listenerGuid)) {
            logMessage("DataPulseProvider: Data comes for already unsubscribed subscription #" + listenerGuid);
            return;
        }
        var bars = result.bars;
        if (bars.length === 0) {
            return;
        }
        var lastBar = bars[bars.length - 1];
        var subscriptionRecord = this._subscribers[listenerGuid];
        if (subscriptionRecord.lastBarTime !== null && lastBar.time < subscriptionRecord.lastBarTime) {
            return;
        }
        var isNewBar = subscriptionRecord.lastBarTime !== null && lastBar.time > subscriptionRecord.lastBarTime;
        // Pulse updating may miss some trades data (ie, if pulse period = 10 secods and new bar is started 5 seconds later after the last update, the
        // old bar's last 5 seconds trades will be lost). Thus, at fist we should broadcast old bar updates when it's ready.
        if (isNewBar) {
            if (bars.length < 2) {
                throw new Error('Not enough bars in history for proper pulse update. Need at least 2.');
            }
            var previousBar = bars[bars.length - 2];
            subscriptionRecord.listener(previousBar);
        }
        subscriptionRecord.lastBarTime = lastBar.time;
        subscriptionRecord.listener(lastBar);
    };
    return DataPulseProvider;
}());
function periodLengthSeconds(resolution, requiredPeriodsCount) {
    var daysCount = 0;
    if (resolution === 'D' || resolution === '1D') {
        daysCount = requiredPeriodsCount;
    }
    else if (resolution === 'M' || resolution === '1M') {
        daysCount = 31 * requiredPeriodsCount;
    }
    else if (resolution === 'W' || resolution === '1W') {
        daysCount = 7 * requiredPeriodsCount;
    }
    else {
        daysCount = requiredPeriodsCount * parseInt(resolution) / (24 * 60);
    }
    return daysCount * 24 * 60 * 60;
}

var QuotesPulseProvider = /** @class */ (function () {
    function QuotesPulseProvider(quotesProvider) {
        this._subscribers = {};
        this._requestsPending = 0;
        this._quotesProvider = quotesProvider;
        setInterval(this._updateQuotes.bind(this, 1 /* Fast */), 10000 /* Fast */);
        setInterval(this._updateQuotes.bind(this, 0 /* General */), 60000 /* General */);
    }
    QuotesPulseProvider.prototype.subscribeQuotes = function (symbols, fastSymbols, onRealtimeCallback, listenerGuid) {
        this._subscribers[listenerGuid] = {
            symbols: symbols,
            fastSymbols: fastSymbols,
            listener: onRealtimeCallback,
        };
        logMessage("QuotesPulseProvider: subscribed quotes with #" + listenerGuid);
    };
    QuotesPulseProvider.prototype.unsubscribeQuotes = function (listenerGuid) {
        delete this._subscribers[listenerGuid];
        logMessage("QuotesPulseProvider: unsubscribed quotes with #" + listenerGuid);
    };
    QuotesPulseProvider.prototype._updateQuotes = function (updateType) {
        var this$1 = this;

        var _this = this;
        if (this._requestsPending > 0) {
            return;
        }
        var _loop_1 = function (listenerGuid) {
            this_1._requestsPending++;
            var subscriptionRecord = this_1._subscribers[listenerGuid];
            this_1._quotesProvider.getQuotes(updateType === 1 /* Fast */ ? subscriptionRecord.fastSymbols : subscriptionRecord.symbols)
                .then(function (data) {
                _this._requestsPending--;
                if (!_this._subscribers.hasOwnProperty(listenerGuid)) {
                    return;
                }
                subscriptionRecord.listener(data);
                logMessage("QuotesPulseProvider: data for #" + listenerGuid + " (" + updateType + ") updated successfully, pending=" + _this._requestsPending);
            })
                .catch(function (reason) {
                _this._requestsPending--;
                logMessage("QuotesPulseProvider: data for #" + listenerGuid + " (" + updateType + ") updated with error=" + getErrorMessage(reason) + ", pending=" + _this._requestsPending);
            });
        };
        var this_1 = this;
        for (var listenerGuid in this$1._subscribers) {
            _loop_1(listenerGuid);
        }
    };
    return QuotesPulseProvider;
}());

function extractField$1(data, field, arrayIndex, valueIsArray) {
    var value = data[field];
    if (Array.isArray(value) && (!valueIsArray || Array.isArray(value[0]))) {
        return value[arrayIndex];
    }
    return value;
}
var SymbolsStorage = /** @class */ (function () {
    function SymbolsStorage(datafeedUrl, datafeedSupportedResolutions, requester) {
        this._exchangesList = [];
        this._symbolsInfo = {};
        this._symbolsList = [];
        this._datafeedUrl = datafeedUrl;
        this._datafeedSupportedResolutions = datafeedSupportedResolutions;
        this._requester = requester;
        this._readyPromise = this._init();
        this._readyPromise.catch(function (error) {
            // seems it is impossible
            console.error("SymbolsStorage: Cannot init, error=" + error.toString());
        });
    }
    // BEWARE: this function does not consider symbol's exchange
    SymbolsStorage.prototype.resolveSymbol = function (symbolName) {
        var _this = this;
        return this._readyPromise.then(function () {
            var symbolInfo = _this._symbolsInfo[symbolName];
            if (symbolInfo === undefined) {
                return Promise.reject('invalid symbol');
            }
            return Promise.resolve(symbolInfo);
        });
    };
    SymbolsStorage.prototype.searchSymbols = function (searchString, exchange, symbolType, maxSearchResults) {
        var _this = this;
        return this._readyPromise.then(function () {
            var weightedResult = [];
            var queryIsEmpty = searchString.length === 0;
            searchString = searchString.toUpperCase();
            var _loop_1 = function (symbolName) {
                var symbolInfo = _this._symbolsInfo[symbolName];
                if (symbolInfo === undefined) {
                    return "continue";
                }
                if (symbolType.length > 0 && symbolInfo.type !== symbolType) {
                    return "continue";
                }
                if (exchange && exchange.length > 0 && symbolInfo.exchange !== exchange) {
                    return "continue";
                }
                var positionInName = symbolInfo.name.toUpperCase().indexOf(searchString);
                var positionInDescription = symbolInfo.description.toUpperCase().indexOf(searchString);
                if (queryIsEmpty || positionInName >= 0 || positionInDescription >= 0) {
                    var alreadyExists = weightedResult.some(function (item) { return item.symbolInfo === symbolInfo; });
                    if (!alreadyExists) {
                        var weight = positionInName >= 0 ? positionInName : 8000 + positionInDescription;
                        weightedResult.push({ symbolInfo: symbolInfo, weight: weight });
                    }
                }
            };
            for (var _i = 0, _a = _this._symbolsList; _i < _a.length; _i++) {
                var symbolName = _a[_i];
                _loop_1(symbolName);
            }
            var result = weightedResult
                .sort(function (item1, item2) { return item1.weight - item2.weight; })
                .slice(0, maxSearchResults)
                .map(function (item) {
                var symbolInfo = item.symbolInfo;
                return {
                    symbol: symbolInfo.name,
                    full_name: symbolInfo.full_name,
                    description: symbolInfo.description,
                    exchange: symbolInfo.exchange,
                    params: [],
                    type: symbolInfo.type,
                    ticker: symbolInfo.name,
                };
            });
            return Promise.resolve(result);
        });
    };
    SymbolsStorage.prototype._init = function () {
        var this$1 = this;

        var _this = this;
        var promises = [];
        var alreadyRequestedExchanges = {};
        for (var _i = 0, _a = this._exchangesList; _i < _a.length; _i++) {
            var exchange = _a[_i];
            if (alreadyRequestedExchanges[exchange]) {
                continue;
            }
            alreadyRequestedExchanges[exchange] = true;
            promises.push(this$1._requestExchangeData(exchange));
        }
        return Promise.all(promises)
            .then(function () {
            _this._symbolsList.sort();
            logMessage('SymbolsStorage: All exchanges data loaded');
        });
    };
    SymbolsStorage.prototype._requestExchangeData = function (exchange) {
        var _this = this;
        return new Promise(function (resolve, reject) {
            _this._requester.sendRequest(_this._datafeedUrl, 'symbol_info', { group: exchange })
                .then(function (response) {
                try {
                    _this._onExchangeDataReceived(exchange, response);
                }
                catch (error) {
                    reject(error);
                    return;
                }
                resolve();
            })
                .catch(function (reason) {
                logMessage("SymbolsStorage: Request data for exchange '" + exchange + "' failed, reason=" + getErrorMessage(reason));
                resolve();
            });
        });
    };
    SymbolsStorage.prototype._onExchangeDataReceived = function (exchange, data) {
        var this$1 = this;

        var symbolIndex = 0;
        try {
            var symbolsCount = data.symbol.length;
            var tickerPresent = data.ticker !== undefined;
            for (; symbolIndex < symbolsCount; ++symbolIndex) {
                var symbolName = data.symbol[symbolIndex];
                var listedExchange = extractField$1(data, 'exchange-listed', symbolIndex);
                var tradedExchange = extractField$1(data, 'exchange-traded', symbolIndex);
                var fullName = tradedExchange + ':' + symbolName;
                var ticker = tickerPresent ? extractField$1(data, 'ticker', symbolIndex) : symbolName;
                var symbolInfo = {
                    ticker: ticker,
                    name: symbolName,
                    base_name: [listedExchange + ':' + symbolName],
                    full_name: fullName,
                    listed_exchange: listedExchange,
                    exchange: tradedExchange,
                    description: extractField$1(data, 'description', symbolIndex),
                    has_intraday: definedValueOrDefault(extractField$1(data, 'has-intraday', symbolIndex), false),
                    has_no_volume: definedValueOrDefault(extractField$1(data, 'has-no-volume', symbolIndex), false),
                    minmov: extractField$1(data, 'minmovement', symbolIndex) || extractField$1(data, 'minmov', symbolIndex) || 0,
                    minmove2: extractField$1(data, 'minmove2', symbolIndex) || extractField$1(data, 'minmov2', symbolIndex),
                    fractional: extractField$1(data, 'fractional', symbolIndex),
                    pricescale: extractField$1(data, 'pricescale', symbolIndex),
                    type: extractField$1(data, 'type', symbolIndex),
                    session: extractField$1(data, 'session-regular', symbolIndex),
                    timezone: extractField$1(data, 'timezone', symbolIndex),
                    supported_resolutions: definedValueOrDefault(extractField$1(data, 'supported-resolutions', symbolIndex, true), this$1._datafeedSupportedResolutions),
                    force_session_rebuild: extractField$1(data, 'force-session-rebuild', symbolIndex),
                    has_daily: definedValueOrDefault(extractField$1(data, 'has-daily', symbolIndex), true),
                    intraday_multipliers: definedValueOrDefault(extractField$1(data, 'intraday-multipliers', symbolIndex, true), ['1', '5', '15', '30', '60']),
                    has_weekly_and_monthly: extractField$1(data, 'has-weekly-and-monthly', symbolIndex),
                    has_empty_bars: extractField$1(data, 'has-empty-bars', symbolIndex),
                    volume_precision: definedValueOrDefault(extractField$1(data, 'volume-precision', symbolIndex), 0),
                };
                this$1._symbolsInfo[ticker] = symbolInfo;
                this$1._symbolsInfo[symbolName] = symbolInfo;
                this$1._symbolsInfo[fullName] = symbolInfo;
                this$1._symbolsList.push(symbolName);
            }
        }
        catch (error) {
            throw new Error("SymbolsStorage: API error when processing exchange " + exchange + " symbol #" + symbolIndex + " (" + data.symbol[symbolIndex] + "): " + error.message);
        }
    };
    return SymbolsStorage;
}());
function definedValueOrDefault(value, defaultValue) {
    return value !== undefined ? value : defaultValue;
}

function extractField(data, field, arrayIndex) {
    var value = data[field];
    return Array.isArray(value) ? value[arrayIndex] : value;
}
/**
 * This class implements interaction with UDF-compatible datafeed.
 * See UDF protocol reference at https://github.com/tradingview/charting_library/wiki/UDF
 */
var UDFCompatibleDatafeedBase = /** @class */ (function () {
    function UDFCompatibleDatafeedBase(datafeedURL, quotesProvider, requester, updateFrequency) {
        if (updateFrequency === void 0) { updateFrequency = 10 * 1000; }
        var _this = this;
        this._configuration = defaultConfiguration();
        this._symbolsStorage = null;
        this._datafeedURL = datafeedURL;
        this._requester = requester;
        this._historyProvider = new HistoryProvider(datafeedURL, this._requester);
        this._quotesProvider = quotesProvider;
        this._dataPulseProvider = new DataPulseProvider(this._historyProvider, updateFrequency);
        this._quotesPulseProvider = new QuotesPulseProvider(this._quotesProvider);
        this._configurationReadyPromise = this._requestConfiguration()
            .then(function (configuration) {
            if (configuration === null) {
                configuration = defaultConfiguration();
            }
            _this._setupWithConfiguration(configuration);
        });
    }
    UDFCompatibleDatafeedBase.prototype.onReady = function (callback) {
        var _this = this;
        this._configurationReadyPromise.then(function () {
            callback(_this._configuration);
        });
    };
    UDFCompatibleDatafeedBase.prototype.getQuotes = function (symbols, onDataCallback, onErrorCallback) {
        this._quotesProvider.getQuotes(symbols).then(onDataCallback).catch(onErrorCallback);
    };
    UDFCompatibleDatafeedBase.prototype.subscribeQuotes = function (symbols, fastSymbols, onRealtimeCallback, listenerGuid) {
        this._quotesPulseProvider.subscribeQuotes(symbols, fastSymbols, onRealtimeCallback, listenerGuid);
    };
    UDFCompatibleDatafeedBase.prototype.unsubscribeQuotes = function (listenerGuid) {
        this._quotesPulseProvider.unsubscribeQuotes(listenerGuid);
    };
    UDFCompatibleDatafeedBase.prototype.calculateHistoryDepth = function (resolution, resolutionBack, intervalBack) {
        return undefined;
        //if (resolution == "1")
        //{
        //    return {
        //        resolutionBack: 'M',
        //        intervalBack: 24
        //    };
        //}
    };
    UDFCompatibleDatafeedBase.prototype.getMarks = function (symbolInfo, from, to, onDataCallback, resolution) {
        if (!this._configuration.supports_marks) {
            return;
        }
        var requestParams = {
            symbol: symbolInfo.ticker || '',
            from: from,
            to: to,
            resolution: resolution,
            dnews: _dNews,
            lang: _lang,
        };
        this._send('marks', requestParams)
            .then(function (response) {
            if (!Array.isArray(response)) {
                var result = [];
                for (var i = 0; i < response.id.length; ++i) {
                    result.push({
                        id: extractField(response, 'id', i),
                        time: extractField(response, 'time', i),
                        color: extractField(response, 'color', i),
                        text: extractField(response, 'text', i),
                        label: extractField(response, 'label', i),
                        labelFontColor: extractField(response, 'labelFontColor', i),
                        minSize: extractField(response, 'minSize', i),
                    });
                }
                response = result;
            }
            onDataCallback(response);
        })
            .catch(function (error) {
            logMessage("UdfCompatibleDatafeed: Request marks failed: " + getErrorMessage(error));
            onDataCallback([]);
        });
    };
    UDFCompatibleDatafeedBase.prototype.getTimescaleMarks = function (symbolInfo, from, to, onDataCallback, resolution) {
        if (!this._configuration.supports_timescale_marks) {
            return;
        }
        var requestParams = {
            symbol: symbolInfo.ticker || '',
            from: from,
            to: to,
            resolution: resolution,
            dnews: _dNews,
            lang: _lang,
        };
        this._send('timescale_marks', requestParams)
            .then(function (response) {
            if (!Array.isArray(response)) {
                var result = [];
                for (var i = 0; i < response.id.length; ++i) {
                    result.push({
                        id: extractField(response, 'id', i),
                        time: extractField(response, 'time', i),
                        color: extractField(response, 'color', i),
                        label: extractField(response, 'label', i),
                        tooltip: extractField(response, 'tooltip', i),
                    });
                }
                response = result;
            }
            onDataCallback(response);
        })
            .catch(function (error) {
            logMessage("UdfCompatibleDatafeed: Request timescale marks failed: " + getErrorMessage(error));
            onDataCallback([]);
        });
    };
    UDFCompatibleDatafeedBase.prototype.getServerTime = function (callback) {
        if (!this._configuration.supports_time) {
            return;
        }
        this._send('time')
            .then(function (response) {
            var time = parseInt(response);
            if (!isNaN(time)) {
                callback(time);
            }
        })
            .catch(function (error) {
            logMessage("UdfCompatibleDatafeed: Fail to load server time, error=" + getErrorMessage(error));
        });
    };
    UDFCompatibleDatafeedBase.prototype.searchSymbols = function (userInput, exchange, symbolType, onResult) {
        if (this._configuration.supports_search) {
            var params = {
                limit: 30 /* SearchItemsLimit */,
                query: userInput.toUpperCase(),
                type: symbolType,
                exchange: exchange,
            };
            this._send('search', params)
                .then(function (response) {
                if (response.s !== undefined) {
                    logMessage("UdfCompatibleDatafeed: search symbols error=" + response.errmsg);
                    onResult([]);
                    return;
                }
                onResult(response);
            })
                .catch(function (reason) {
                logMessage("UdfCompatibleDatafeed: Search symbols for '" + userInput + "' failed. Error=" + getErrorMessage(reason));
                onResult([]);
            });
        }
        else {
            if (this._symbolsStorage === null) {
                throw new Error('UdfCompatibleDatafeed: inconsistent configuration (symbols storage)');
            }
            this._symbolsStorage.searchSymbols(userInput, exchange, symbolType, 30 /* SearchItemsLimit */)
                .then(onResult)
                .catch(onResult.bind(null, []));
        }
    };
    UDFCompatibleDatafeedBase.prototype.resolveSymbol = function (symbolName, onResolve, onError) {
        logMessage('Resolve requested');
        var _s = symbolName.split(/[:/]/);
        if (_s.length > 1) {
            symbolName = _s[1];
        }

        var resolveRequestStartTime = Date.now();
        function onResultReady(symbolInfo) {
            logMessage("Symbol resolved: " + (Date.now() - resolveRequestStartTime) + "ms");
            onResolve(symbolInfo);
        }
        if (!this._configuration.supports_group_request) {
            var params = {
                symbol: symbolName,
            };
            this._send('symbols', params)
                .then(function (response) {
                if (response.s !== undefined) {
                    onError('unknown_symbol');
                }
                else {
                    onResultReady(response);
                }
            })
                .catch(function (reason) {
                logMessage("UdfCompatibleDatafeed: Error resolving symbol: " + getErrorMessage(reason));
                onError('unknown_symbol');
            });
        }
        else {
            if (this._symbolsStorage === null) {
                throw new Error('UdfCompatibleDatafeed: inconsistent configuration (symbols storage)');
            }
            this._symbolsStorage.resolveSymbol(symbolName).then(onResultReady).catch(onError);
        }
    };
    UDFCompatibleDatafeedBase.prototype.getBars = function (symbolInfo, resolution, rangeStartDate, rangeEndDate, onResult, onError) {
        this._historyProvider.getBars(symbolInfo, resolution, rangeStartDate, rangeEndDate)
            .then(function (result) {
            onResult(result.bars, result.meta);
        })
            .catch(onError);
    };
    UDFCompatibleDatafeedBase.prototype.subscribeBars = function (symbolInfo, resolution, onTick, listenerGuid, onResetCacheNeededCallback) {
        this._dataPulseProvider.subscribeBars(symbolInfo, resolution, onTick, listenerGuid);
    };
    UDFCompatibleDatafeedBase.prototype.unsubscribeBars = function (listenerGuid) {
        this._dataPulseProvider.unsubscribeBars(listenerGuid);
    };
    UDFCompatibleDatafeedBase.prototype._requestConfiguration = function () {
        return this._send('config')
            .catch(function (reason) {
            logMessage("UdfCompatibleDatafeed: Cannot get datafeed configuration - use default, error=" + getErrorMessage(reason));
            return null;
        });
    };
    UDFCompatibleDatafeedBase.prototype._send = function (urlPath, params) {
        if (urlPath == 'config')
            { params = { withNews: (_dNews == "") ? false : true, lang : _lang }; }
        return this._requester.sendRequest(this._datafeedURL, urlPath, params);
    };
    UDFCompatibleDatafeedBase.prototype._setupWithConfiguration = function (configurationData) {
        this._configuration = configurationData;
        if (configurationData.exchanges === undefined) {
            configurationData.exchanges = [];
        }
        if (!configurationData.supports_search && !configurationData.supports_group_request) {
            throw new Error('Unsupported datafeed configuration. Must either support search, or support group request');
        }
        if (configurationData.supports_group_request || !configurationData.supports_search) {
            this._symbolsStorage = new SymbolsStorage(this._datafeedURL, configurationData.supported_resolutions || [], this._requester);
        }
        logMessage("UdfCompatibleDatafeed: Initialized with " + JSON.stringify(configurationData));
    };
    return UDFCompatibleDatafeedBase;
}());
function defaultConfiguration() {
    return {
        supports_search: false,
        supports_group_request: true,
        supported_resolutions: ['1', '5', '15', '30', '60', '1D', '1W', '1M'],
        supports_marks: (_dNews == "") ? false : true,
        supports_timescale_marks: (_dNews == "") ? false : true,
    };
}

var QuotesProvider = /** @class */ (function () {
    function QuotesProvider(datafeedUrl, requester) {
        this._datafeedUrl = datafeedUrl;
        this._requester = requester;
    }
    QuotesProvider.prototype.getQuotes = function (symbols) {
        var _this = this;
        return new Promise(function (resolve, reject) {
            _this._requester.sendRequest(_this._datafeedUrl, 'quotes', { symbols: symbols })
                .then(function (response) {
                if (response.s === 'ok') {
                    resolve(response.d);
                }
                else {
                    reject(response.errmsg);
                }
            })
                .catch(function (error) {
                var errorMessage = getErrorMessage(error);
                logMessage("QuotesProvider: getQuotes failed, error=" + errorMessage);
                reject("network error: " + errorMessage);
            });
        });
    };
    return QuotesProvider;
}());

var Requester = /** @class */ (function () {
    function Requester(headers) {
        if (headers) {
            this._headers = headers;
        }
    }
    Requester.prototype.sendRequest = function (datafeedUrl, urlPath, params) {
        if (params !== undefined) {
            var paramKeys = Object.keys(params);
            if (paramKeys.length !== 0) {
                urlPath += '?';
            }
            urlPath += paramKeys.map(function (key) {
                return encodeURIComponent(key) + "=" + encodeURIComponent(params[key].toString());
            }).join('&');
        }
        logMessage('New request: ' + urlPath);
        // Send user cookies if the URL is on the same origin as the calling script.
        var options = { credentials: 'same-origin' };
        if (this._headers !== undefined) {
            options.headers = this._headers;
        }
        return fetch(datafeedUrl + "/" + urlPath, options)
            .then(function (response) { return response.text(); })
            .then(function (responseTest) { return JSON.parse(responseTest); });
    };
    return Requester;
}());

var UDFCompatibleDatafeed = /** @class */ (function (_super) {
    __extends(UDFCompatibleDatafeed, _super);
    function UDFCompatibleDatafeed(datafeedURL, updateFrequency) {
        if (updateFrequency === void 0) { updateFrequency = 10 * 1000; }
        var _this = this;
        var requester = new Requester();
        var quotesProvider = new QuotesProvider(datafeedURL, requester);
        _this = _super.call(this, datafeedURL, quotesProvider, requester, updateFrequency) || this;
        return _this;
    }
    return UDFCompatibleDatafeed;
}(UDFCompatibleDatafeedBase));

exports.UDFCompatibleDatafeed = UDFCompatibleDatafeed;

Object.defineProperty(exports, '__esModule', { value: true });

})));

!function(){"use strict";function n(){}function i(t){if("object"!=typeof this)throw new TypeError("Promises must be constructed via new");if("function"!=typeof t)throw new TypeError("not a function");this._state=0,this._handled=!1,this._value=void 0,this._deferreds=[],h(t,this)}function o(r,n){for(;3===r._state;)r=r._value;0!==r._state?(r._handled=!0,i._immediateFn(function(){var t=1===r._state?n.onFulfilled:n.onRejected;if(null!==t){var e;try{e=t(r._value)}catch(t){return void a(n.promise,t)}s(n.promise,e)}else(1===r._state?s:a)(n.promise,r._value)})):r._deferreds.push(n)}function s(e,t){try{if(t===e)throw new TypeError("A promise cannot be resolved with itself.");if(t&&("object"==typeof t||"function"==typeof t)){var r=t.then;if(t instanceof i)return e._state=3,e._value=t,void u(e);if("function"==typeof r)return void h(function(t,e){return function(){t.apply(e,arguments)}}(r,t),e)}e._state=1,e._value=t,u(e)}catch(t){a(e,t)}}function a(t,e){t._state=2,t._value=e,u(t)}function u(t){2===t._state&&0===t._deferreds.length&&i._immediateFn(function(){t._handled||i._unhandledRejectionFn(t._value)});for(var e=0,r=t._deferreds.length;e<r;e++)o(t,t._deferreds[e]);t._deferreds=null}function f(t,e,r){this.onFulfilled="function"==typeof t?t:null,this.onRejected="function"==typeof e?e:null,this.promise=r}function h(t,e){var r=!1;try{t(function(t){r||(r=!0,s(e,t))},function(t){r||(r=!0,a(e,t))})}catch(t){if(r)return;r=!0,a(e,t)}}var t,e;t=window,e=setTimeout,i.prototype.catch=function(t){return this.then(null,t)},i.prototype.then=function(t,e){var r=new this.constructor(n);return o(this,new f(t,e,r)),r},i.all=function(t){var a=Array.prototype.slice.call(t);return new i(function(n,o){if(0===a.length)return n([]);var i=a.length;function s(e,t){try{if(t&&("object"==typeof t||"function"==typeof t)){var r=t.then;if("function"==typeof r)return void r.call(t,function(t){s(e,t)},o)}a[e]=t,0==--i&&n(a)}catch(t){o(t)}}for(var t=0;t<a.length;t++)s(t,a[t])})},i.resolve=function(e){return e&&"object"==typeof e&&e.constructor===i?e:new i(function(t){t(e)})},i.reject=function(r){return new i(function(t,e){e(r)})},i.race=function(o){return new i(function(t,e){for(var r=0,n=o.length;r<n;r++)o[r].then(t,e)})},i._immediateFn="function"==typeof setImmediate&&function(t){setImmediate(t)}||function(t){e(t,0)},i._unhandledRejectionFn=function(t){"undefined"!=typeof console&&console&&console.warn("Possible Unhandled Promise Rejection:",t)},i._setImmediateFn=function(t){i._immediateFn=t},i._setUnhandledRejectionFn=function(t){i._unhandledRejectionFn=t},"undefined"!=typeof module&&module.exports?module.exports=i:t.Promise||(t.Promise=i),function(t){if(!t.fetch){var e="URLSearchParams"in t,r="Symbol"in t&&"iterator"in Symbol,s="FileReader"in t&&"Blob"in t&&function(){try{return new Blob,!0}catch(t){return!1}}(),n="FormData"in t,o="ArrayBuffer"in t;if(o)var i=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],a=function(t){return t&&DataView.prototype.isPrototypeOf(t)},u=ArrayBuffer.isView||function(t){return t&&-1<i.indexOf(Object.prototype.toString.call(t))};y.prototype.append=function(t,e){t=c(t),e=d(e);var r=this.map[t];this.map[t]=r?r+","+e:e},y.prototype.delete=function(t){delete this.map[c(t)]},y.prototype.get=function(t){return t=c(t),this.has(t)?this.map[t]:null},y.prototype.has=function(t){return this.map.hasOwnProperty(c(t))},y.prototype.set=function(t,e){this.map[c(t)]=d(e)},y.prototype.forEach=function(t,e){for(var r in this.map)this.map.hasOwnProperty(r)&&t.call(e,this.map[r],r,this)},y.prototype.keys=function(){var r=[];return this.forEach(function(t,e){r.push(e)}),l(r)},y.prototype.values=function(){var e=[];return this.forEach(function(t){e.push(t)}),l(e)},y.prototype.entries=function(){var r=[];return this.forEach(function(t,e){r.push([e,t])}),l(r)},r&&(y.prototype[Symbol.iterator]=y.prototype.entries);var f=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];v.prototype.clone=function(){return new v(this,{body:this._bodyInit})},_.call(v.prototype),_.call(T.prototype),T.prototype.clone=function(){return new T(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new y(this.headers),url:this.url})},T.error=function(){var t=new T(null,{status:0,statusText:""});return t.type="error",t};var h=[301,302,303,307,308];T.redirect=function(t,e){if(-1===h.indexOf(e))throw new RangeError("Invalid status code");return new T(null,{status:e,headers:{location:t}})},t.Headers=y,t.Request=v,t.Response=T,t.fetch=function(o,i){return new Promise(function(r,t){var e=new v(o,i),n=new XMLHttpRequest;n.onload=function(){var t={status:n.status,statusText:n.statusText,headers:function(t){var o=new y;return t.split(/\r?\n/).forEach(function(t){var e=t.split(":"),r=e.shift().trim();if(r){var n=e.join(":").trim();o.append(r,n)}}),o}(n.getAllResponseHeaders()||"")};t.url="responseURL"in n?n.responseURL:t.headers.get("X-Request-URL");var e="response"in n?n.response:n.responseText;r(new T(e,t))},n.onerror=function(){t(new TypeError("Network request failed"))},n.ontimeout=function(){t(new TypeError("Network request failed"))},n.open(e.method,e.url,!0),"include"===e.credentials&&(n.withCredentials=!0),"responseType"in n&&s&&(n.responseType="blob"),e.headers.forEach(function(t,e){n.setRequestHeader(e,t)}),n.send(void 0===e._bodyInit?null:e._bodyInit)})},t.fetch.polyfill=!0}function c(t){if("string"!=typeof t&&(t=String(t)),/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(t))throw new TypeError("Invalid character in header field name");return t.toLowerCase()}function d(t){return"string"!=typeof t&&(t=String(t)),t}function l(e){var t={next:function(){var t=e.shift();return{done:void 0===t,value:t}}};return r&&(t[Symbol.iterator]=function(){return t}),t}function y(e){this.map={},e instanceof y?e.forEach(function(t,e){this.append(e,t)},this):Array.isArray(e)?e.forEach(function(t){this.append(t[0],t[1])},this):e&&Object.getOwnPropertyNames(e).forEach(function(t){this.append(t,e[t])},this)}function p(t){if(t.bodyUsed)return Promise.reject(new TypeError("Already read"));t.bodyUsed=!0}function b(r){return new Promise(function(t,e){r.onload=function(){t(r.result)},r.onerror=function(){e(r.error)}})}function m(t){var e=new FileReader,r=b(e);return e.readAsArrayBuffer(t),r}function w(t){if(t.slice)return t.slice(0);var e=new Uint8Array(t.byteLength);return e.set(new Uint8Array(t)),e.buffer}function _(){return this.bodyUsed=!1,this._initBody=function(t){if(this._bodyInit=t)if("string"==typeof t)this._bodyText=t;else if(s&&Blob.prototype.isPrototypeOf(t))this._bodyBlob=t;else if(n&&FormData.prototype.isPrototypeOf(t))this._bodyFormData=t;else if(e&&URLSearchParams.prototype.isPrototypeOf(t))this._bodyText=t.toString();else if(o&&s&&a(t))this._bodyArrayBuffer=w(t.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer]);else{if(!o||!ArrayBuffer.prototype.isPrototypeOf(t)&&!u(t))throw new Error("unsupported BodyInit type");this._bodyArrayBuffer=w(t)}else this._bodyText="";this.headers.get("content-type")||("string"==typeof t?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):e&&URLSearchParams.prototype.isPrototypeOf(t)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},s&&(this.blob=function(){var t=p(this);if(t)return t;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?p(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(m)}),this.text=function(){var t=p(this);if(t)return t;if(this._bodyBlob)return function(t){var e=new FileReader,r=b(e);return e.readAsText(t),r}(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(function(t){for(var e=new Uint8Array(t),r=new Array(e.length),n=0;n<e.length;n++)r[n]=String.fromCharCode(e[n]);return r.join("")}(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},n&&(this.formData=function(){return this.text().then(A)}),this.json=function(){return this.text().then(JSON.parse)},this}function v(t,e){var r=(e=e||{}).body;if(t instanceof v){if(t.bodyUsed)throw new TypeError("Already read");this.url=t.url,this.credentials=t.credentials,e.headers||(this.headers=new y(t.headers)),this.method=t.method,this.mode=t.mode,r||null==t._bodyInit||(r=t._bodyInit,t.bodyUsed=!0)}else this.url=String(t);if(this.credentials=e.credentials||this.credentials||"omit",!e.headers&&this.headers||(this.headers=new y(e.headers)),this.method=function(t){var e=t.toUpperCase();return-1<f.indexOf(e)?e:t}(e.method||this.method||"GET"),this.mode=e.mode||this.mode||null,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&r)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(r)}function A(t){var o=new FormData;return t.trim().split("&").forEach(function(t){if(t){var e=t.split("="),r=e.shift().replace(/\+/g," "),n=e.join("=").replace(/\+/g," ");o.append(decodeURIComponent(r),decodeURIComponent(n))}}),o}function T(t,e){e=e||{},this.type="default",this.status="status"in e?e.status:200,this.ok=200<=this.status&&this.status<300,this.statusText="statusText"in e?e.statusText:"OK",this.headers=new y(e.headers),this.url=e.url||"",this._initBody(t)}}("undefined"!=typeof self?self:window)}();



var withAdjust = 0;
var withNews = false;
var withDivid = false;
var s_symbol;
var _dNews = "";
var w_dataFeedURL;
var w_updateFrecvency = 30000;
var w_debug;
var w_width;
var w_heigth;
var w_interval;
var w_theme;
var w_custom_css_url;
var w_disabled_features = [];
var w_enabled_features;
var w_supported_resolutions;
var w_timeframe;
var w_time_frames = [];
var w_overrides = {};
var w_withCustomBtnPriceAjust;
var w_withCustomBtnNews;
var w_withCustomBtnDivid;
var _datafeed;
var w_OneYear = false;
var _lang = "ro";
var w_autosize = false;
var w_studies_overrides = {};
var w_withHeader = true;


function initViewChart(_symbol)
{
   
    s_symbol = _symbol;
    widget = window.tvWidget = new TradingView.widget({
        debug: (w_debug == "") ? false : w_debug,
        //fullscreen: true,
        width:(w_width == "") ? "100%" : w_width,
        heigth: (w_heigth == "") ? "100%" : w_heigth,
        symbol: _symbol,
        interval: w_interval,
        container_id: "ChartContainerComplete",
        datafeed: _datafeed,
        theme: (w_theme == "") ? "Light" : w_theme , //'Dark' sau 'Light'
        supports_marks: (_dNews == "") ? false : true,
        supports_timescale_marks: (_dNews == "") ? false : true,
        timezone: "Europe/Athens",
        locale: _lang, 
        library_path: "/charting_library/",
        custom_css_url: w_custom_css_url, // "/Content/tvcharts.css",
        drawings_access: { type: 'black', tools: [{ name: "Regression Trend" }] },
        supported_resolutions: w_supported_resolutions, // ['1', '5', '15', '30', '60', '1D', '1W', '1M', '6M', '12M'],
        timeframe: w_timeframe, // '12M',
        time_frames: w_time_frames, // [{ text: "1d", value: "1D", resolution: "1" },{ text: "1w", value: "1W", resolution: "5" },{ text: "1m", value: "1M", resolution: "60" },{ text:"6m", value: "6M", resolution: "D" },{ text: "1y", value: "1Y", resolution: "D" },],
        autosize: w_autosize,
        enabled_features: w_enabled_features,
        disabled_features: w_disabled_features,
        numeric_formatting: (_lang == "ro") ? { decimal_sign: "," } : { decimal_sign: "." },
        customFormatters: {
            dateFormatter: {
                format: function (date) {
                    if (_lang == "ro")
                        return ("0" + date.getDate()).slice(-2) + '-' + ("0" + (date.getMonth() + 1)).slice(-2) + '-' + date.getFullYear();
                    else
                        return date.getFullYear() + '-' + ("0" + (date.getMonth() + 1)).slice(-2) + '-' + ("0" + date.getDate()).slice(-2);
                }
            }
        },
        overrides: w_overrides, 
       studies_overrides: w_studies_overrides,

    });


    w_withCustomBtnPriceAjust = (w_withCustomBtnPriceAjust == null) ? false : w_withCustomBtnPriceAjust;
    w_withCustomBtnNews = (w_withCustomBtnNews == null) ? false : w_withCustomBtnNews;
    w_withCustomBtnDivid = (w_withCustomBtnDivid == null) ? false : w_withCustomBtnDivid;

    
        w_withHeader = (w_withCustomBtnPriceAjust == true || w_withCustomBtnNews == true || w_withCustomBtnDivid == true);
  
    if (w_withHeader == true) {
        widget.headerReady().then(function () {
                                ww_overrides = {
                        "symbolWatermarkProperties.color": (w_theme == 'Light') ? "rgba(245, 245, 245, 0.9)" : "rgba(47, 50, 65, 1)",
                        "mainSeriesProperties.style": 1,
                        "paneProperties.topMargin": 15,
                        "mainSeriesProperties.candleStyle.barColorsOnPrevClose": true,
                        "mainSeriesProperties.haStyle.barColorsOnPrevClose": true,
                        "mainSeriesProperties.barStyle.barColorsOnPrevClose":true
                    };
            if (w_withCustomBtnPriceAjust == true) {
                var customBtnPriceAjust = widget.createButton();
                customBtnPriceAjust.id = "svgAjust";
                customBtnPriceAjust.addEventListener('click', function () {
                    withAdjust = (withAdjust == 0) ? 1 : 0;
                    w_overrides = ww_overrides;
                    w_withCustomBtnPriceAjust = true;
                    initViewChart(s_symbol);
                    w_withHeader = true;

                });
            }
            if (w_withCustomBtnNews == true) {
                var customBtnNews = widget.createButton();
                customBtnNews.id = "svgNews";
                customBtnNews.addEventListener('click', function () {
                    withNews = (withNews) ? false : true;
                    _dNews = (withNews && withDivid) ? "A" : (withNews) ? "N" : (withDivid ? "D" : "")  // ce fel de stiri
                    _datafeed = new Datafeeds.UDFCompatibleDatafeed(w_dataFeedURL, w_updateFrecvency);
                    w_overrides = ww_overrides;
                    w_withCustomBtnNews = true;
                    initViewChart(s_symbol);
                    w_withHeader = true;
                });
            }
            if (w_withCustomBtnDivid == true) {
                var customBtnDivid = widget.createButton();
                customBtnDivid.id = "svgDivid";
                customBtnDivid.addEventListener('click', function () {
                    withDivid = (withDivid) ? false : true;
                    _dNews = (withNews && withDivid) ? "A" : (withNews) ? "N" : (withDivid ? "D" : "")
                    _datafeed = new Datafeeds.UDFCompatibleDatafeed(w_dataFeedURL, w_updateFrecvency);
                    w_overrides = ww_overrides;
                    w_withCustomBtnDivid = true;
                    initViewChart(s_symbol);
                    w_withHeader = true;
                });
            }
            var tvIframe = document.querySelectorAll("[name^=tradingview_]");
            if (tvIframe.length == 1) {
                var hcompare = $($(tvIframe)[0].contentWindow.document.getElementById('header-toolbar-compare')).find('.js-button-text')
                if (hcompare.length == 1)
                    $(hcompare).text('');

                var hindic = $($(tvIframe)[0].contentWindow.document.getElementById('header-toolbar-indicators')).find('.js-button-text')
                if (hindic.length == 1)
                    $(hindic).text('');

            }
            if (w_withCustomBtnPriceAjust || w_withCustomBtnNews || w_withCustomBtnDivid) {
                AddCustomBtns();
            }
        });
    }
    widget.onChartReady(function () {
        
        widget.subscribe("add_compare", function () {
            widget.applyStudiesOverrides({ "Compare.Plot.color.0": '#' + Math.floor(Math.random() * 16777215).toString(16) });
           
        });

        //if (w_withCustomBtnPriceAjust || w_withCustomBtnNews || w_withCustomBtnDivid) {
        //    AddCustomBtns();
        //}
         //nu sterge
        //if (w_OneYear) {
        //    SetNewRange();
        //    w_OneYear = false;
        //}
        var w_theme2 = (w_theme == 'Dark') ? 'Light' : 'Dark';
        widget.onContextMenu(function () {
            return [
                {
                    position: "top",
                    text: "Change Theme to " + w_theme2 ,
                    click: function () {
                        w_theme = w_theme2;
                        widget.changeTheme(w_theme2);
                        widget.applyOverrides({"symbolWatermarkProperties.color": (w_theme == 'Light') ? "rgba(245, 245, 245, 0.9)" : "rgba(47, 50, 65, 1)" });
                        w_theme2 = (w_theme == 'Dark') ? 'Light' : 'Dark';
                    }
                },
                { text: "-", position: "top" },
                //{ text: "-Objects Tree..." },
            ];
        });

        
    });

    var tvIframe = document.querySelectorAll("[name^=tradingview_]");
    function AddCustomBtns() {
        if (tvIframe.length == 1) {
            if (withAdjust == 0)
                SVGadd("svgAjust", _lang == "ro" ? "Preturi neajustate" : "Unadjusted prices", withAdjust);
            else
                SVGadd("svgAjust", _lang == "ro" ? "Preturi ajustate" :"Adjusted prices", withAdjust);
            SVGadd("svgNews", _lang == "ro" ? "Stiri" : "News", withNews);
            SVGadd("svgDivid", _lang == "ro" ? "Dividende" : "Dividends", withDivid);

            w_OneYear = true;
        }
    }

    function SVGadd(id, title, param) {
        var customBtn = $(tvIframe)[0].contentWindow.document.getElementById(id);
        if ($(customBtn).length == 1) {
            if (param == 1) {
                var _svgContainer = document.createElement("span");
                $(_svgContainer).attr("class", "icon-beK_KS0k-");
                $(_svgContainer).attr("style", "padding-left:10px");
                var _svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
                _svg.setAttributeNS(null, 'viewBox', '0 0 16 8');
                _svg.setAttributeNS(null, 'width', '16');
                _svg.setAttributeNS(null, 'height', '12');
                var _path = document.createElementNS("http://www.w3.org/2000/svg", "path");
                _path.setAttributeNS(null, 'fill', '#2cc1ad');
                _path.setAttributeNS(null, 'd', 'M0 1.475l7.396 6.04.596.485.593-.49L16 1.39 14.807 0 7.393 6.122 8.58 6.12 1.186.08z');
                _svg.appendChild(_path);
                $(customBtn).append($('<div>', { 'class': 'js-button-text text-1sK7vbvh-', 'html': title, 'style': 'color:#2cc1ad' }));
                _svgContainer.appendChild(_svg);
                var _pBtn = $(customBtn).parent();
                $(_pBtn).prepend(_svgContainer);
            }
            else
                $(customBtn).append($('<div>', { 'class': 'js-button-text text-1sK7vbvh-', 'html': title }));
        }
    }

    function SetNewRange() {
        var currentTo = new Date(0);
        var currentTo_n = new Date(currentTo.setUTCSeconds(widget.activeChart().getVisibleRange().to));
        var _newFrom = new Date(currentTo_n.setFullYear(currentTo_n.getFullYear() - 1));

        widget.chart().setVisibleRange({
            from: Date.UTC(_newFrom.getFullYear(), _newFrom.getMonth(), _newFrom.getDate()) / 1000,
            to: widget.activeChart().getVisibleRange().to // Math.round(new Date().getTime() / 1000) 
        });
    }

    function RandomPlotColor()
    {
        return '#' + Math.floor(Math.random() * 16777215).toString(16);
    }
    
}

//$(document).ready(
//    function () {
//        $('#header-toolbar-compare > div.js-button-text').text('');
//        $('#header-toolbar-indicators > div.js-button-text').text('');
//    });


