Advertisement
Guest User

Untitled

a guest
Feb 21st, 2017
585
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 33.37 KB | None | 0 0
  1.  
  2. /*
  3. This class implements interaction with UDF-compatible datafeed.
  4.  
  5. See UDF protocol reference at
  6. https://github.com/tradingview/charting_library/wiki/UDF
  7. */
  8.  
  9. var Datafeeds = {};
  10.  
  11. Datafeeds.UDFCompatibleDatafeed = function (datafeedURL, updateFrequency, protocolVersion) {
  12.  
  13. this._datafeedURL = datafeedURL;
  14. this._configuration = undefined;
  15.  
  16. this._symbolSearch = null;
  17. this._symbolsStorage = null;
  18. this._barsPulseUpdater = new Datafeeds.DataPulseUpdater(this, updateFrequency || 10 * 1000);
  19. this._quotesPulseUpdater = new Datafeeds.QuotesPulseUpdater(this);
  20. this._protocolVersion = protocolVersion || 2;
  21.  
  22. this._enableLogging = false;
  23. this._initializationFinished = false;
  24. this._callbacks = {};
  25.  
  26. this._initialize();
  27. };
  28.  
  29. Datafeeds.UDFCompatibleDatafeed.prototype.defaultConfiguration = function () {
  30. return {
  31. supports_search: false,
  32. supports_group_request: true,
  33. supported_resolutions: ['1', '5', '15', '30', '60', '1D', '1W', '1M'],
  34. supports_marks: false,
  35. supports_timescale_marks: false
  36. };
  37. };
  38.  
  39. Datafeeds.UDFCompatibleDatafeed.prototype.getServerTime = function (callback) {
  40. if (this._configuration.supports_time) {
  41. this._send(this._datafeedURL + '/time', {})
  42. .done(function (response) {
  43. callback(+response.d);
  44. })
  45. .fail(function () {
  46.  
  47. });
  48. }
  49. };
  50.  
  51. Datafeeds.UDFCompatibleDatafeed.prototype.on = function (event, callback) {
  52.  
  53. if (!this._callbacks.hasOwnProperty(event)) {
  54. this._callbacks[event] = [];
  55. }
  56.  
  57. this._callbacks[event].push(callback);
  58. return this;
  59. };
  60.  
  61. Datafeeds.UDFCompatibleDatafeed.prototype._fireEvent = function (event, argument) {
  62. if (this._callbacks.hasOwnProperty(event)) {
  63. var callbacksChain = this._callbacks[event];
  64. for (var i = 0; i < callbacksChain.length; ++i) {
  65. callbacksChain[i](argument);
  66. }
  67.  
  68. this._callbacks[event] = [];
  69. }
  70. };
  71.  
  72. Datafeeds.UDFCompatibleDatafeed.prototype.onInitialized = function () {
  73. this._initializationFinished = true;
  74. this._fireEvent('initialized');
  75. };
  76.  
  77. Datafeeds.UDFCompatibleDatafeed.prototype._logMessage = function (message) {
  78. if (this._enableLogging) {
  79. var now = new Date();
  80. console.log(now.toLocaleTimeString() + '.' + now.getMilliseconds() + '> ' + message);
  81. }
  82. };
  83.  
  84. Datafeeds.UDFCompatibleDatafeed.prototype._send = function (url, params) {
  85. var request = url;
  86. var data = '';
  87. if (params) {
  88. for (var i = 0; i < Object.keys(params).length; ++i) {
  89. var key = Object.keys(params)[i];
  90. var value = encodeURIComponent(params[key]);
  91. //request += (i == 0 ? "?" : "&") + key + "=" + value;
  92. data += (i == 0 ? "" : ", ") + key + ":" + "'" + value + "'";
  93. }
  94. }
  95.  
  96. this._logMessage("New request: " + request);
  97. return $.ajax({
  98. type: "POST",
  99. url: url,
  100. data: "{" + data + "}",
  101. contentType: "application/json; charset=utf-8",
  102. dataType: "json",
  103. });
  104. }
  105.  
  106. Datafeeds.UDFCompatibleDatafeed.prototype._initialize = function () {
  107.  
  108. var that = this;
  109.  
  110. this._send(this._datafeedURL + '/config')
  111. .done(function (response) {
  112. var configurationData = response.d;
  113. that._setupWithConfiguration(configurationData);
  114. })
  115. .fail(function (reason) {
  116. that._setupWithConfiguration(that.defaultConfiguration());
  117. });
  118. };
  119.  
  120. Datafeeds.UDFCompatibleDatafeed.prototype.onReady = function (callback) {
  121. var that = this;
  122. if (this._configuration) {
  123. setTimeout(function () {
  124. callback(that._configuration);
  125. }, 0);
  126. } else {
  127. this.on('configuration_ready', function () {
  128. callback(that._configuration);
  129. });
  130. }
  131. };
  132.  
  133. Datafeeds.UDFCompatibleDatafeed.prototype._setupWithConfiguration = function (configurationData) {
  134. this._configuration = configurationData;
  135.  
  136. if (!configurationData.exchanges) {
  137. configurationData.exchanges = [];
  138. }
  139.  
  140. // @obsolete; remove in 1.5
  141. var supportedResolutions = configurationData.supported_resolutions || configurationData.supportedResolutions;
  142. configurationData.supported_resolutions = supportedResolutions;
  143.  
  144. // @obsolete; remove in 1.5
  145. var symbolsTypes = configurationData.symbols_types || configurationData.symbolsTypes;
  146. configurationData.symbols_types = symbolsTypes;
  147.  
  148. if (!configurationData.supports_search && !configurationData.supports_group_request) {
  149. throw 'Unsupported datafeed configuration. Must either support search, or support group request';
  150. }
  151.  
  152. if (!configurationData.supports_search) {
  153. this._symbolSearch = new Datafeeds.SymbolSearchComponent(this);
  154. }
  155.  
  156. if (configurationData.supports_group_request) {
  157. // this component will call onInitialized() by itself
  158. this._symbolsStorage = new Datafeeds.SymbolsStorage(this);
  159. } else {
  160. this.onInitialized();
  161. }
  162.  
  163. this._fireEvent('configuration_ready');
  164. this._logMessage('Initialized with ' + JSON.stringify(configurationData));
  165. };
  166.  
  167. // ===============================================================================================================================
  168. // The functions set below is the implementation of JavaScript API.
  169.  
  170. Datafeeds.UDFCompatibleDatafeed.prototype.getMarks = function (symbolInfo, rangeStart, rangeEnd, onDataCallback, resolution) {
  171. if (this._configuration.supports_marks) {
  172. this._send(this._datafeedURL + '/marks', {
  173. symbol: symbolInfo.ticker.toUpperCase(),
  174. from: rangeStart,
  175. to: rangeEnd,
  176. resolution: resolution
  177. })
  178. .done(function (response) {
  179. onDataCallback(JSON.parse(response.d));
  180. })
  181. .fail(function () {
  182. onDataCallback([]);
  183. });
  184. }
  185. };
  186.  
  187. Datafeeds.UDFCompatibleDatafeed.prototype.getTimescaleMarks = function (symbolInfo, rangeStart, rangeEnd, onDataCallback, resolution) {
  188. if (this._configuration.supports_timescale_marks) {
  189. this._send(this._datafeedURL + '/timescale_marks', {
  190. symbol: symbolInfo.ticker.toUpperCase(),
  191. from: rangeStart,
  192. to: rangeEnd,
  193. resolution: resolution
  194. })
  195. .done(function (response) {
  196. onDataCallback(JSON.parse(response.d));
  197. })
  198. .fail(function () {
  199. onDataCallback([]);
  200. });
  201. }
  202. };
  203.  
  204. Datafeeds.UDFCompatibleDatafeed.prototype.searchSymbols = function (searchString, exchange, type, onResultReadyCallback) {
  205. var MAX_SEARCH_RESULTS = 30;
  206.  
  207. if (!this._configuration) {
  208. onResultReadyCallback([]);
  209. return;
  210. }
  211.  
  212. if (this._configuration.supports_search) {
  213.  
  214. this._send(this._datafeedURL + '/search', {
  215. limit: MAX_SEARCH_RESULTS,
  216. query: searchString.toUpperCase(),
  217. type: type,
  218. exchange: exchange
  219. })
  220. .done(function (response) {
  221. var data = response.d;
  222.  
  223. for (var i = 0; i < data.length; ++i) {
  224. if (!data[i].params) {
  225. data[i].params = [];
  226. }
  227. }
  228.  
  229. if (typeof data.s == 'undefined' || data.s != 'error') {
  230. onResultReadyCallback(data);
  231. } else {
  232. onResultReadyCallback([]);
  233. }
  234.  
  235. })
  236. .fail(function (reason) {
  237. onResultReadyCallback([]);
  238. });
  239. } else {
  240.  
  241. if (!this._symbolSearch) {
  242. throw 'Datafeed error: inconsistent configuration (symbol search)';
  243. }
  244.  
  245. var searchArgument = {
  246. searchString: searchString,
  247. exchange: exchange,
  248. type: type,
  249. onResultReadyCallback: onResultReadyCallback
  250. };
  251.  
  252. if (this._initializationFinished) {
  253. this._symbolSearch.searchSymbols(searchArgument, MAX_SEARCH_RESULTS);
  254. } else {
  255.  
  256. var that = this;
  257.  
  258. this.on('initialized', function () {
  259. that._symbolSearch.searchSymbols(searchArgument, MAX_SEARCH_RESULTS);
  260. });
  261. }
  262. }
  263. };
  264.  
  265. Datafeeds.UDFCompatibleDatafeed.prototype._symbolResolveURL = '/symbols';
  266.  
  267. // BEWARE: this function does not consider symbol's exchange
  268. Datafeeds.UDFCompatibleDatafeed.prototype.resolveSymbol = function (symbolName, onSymbolResolvedCallback, onResolveErrorCallback) {
  269.  
  270. var that = this;
  271.  
  272. if (!this._initializationFinished) {
  273. this.on('initialized', function () {
  274. that.resolveSymbol(symbolName, onSymbolResolvedCallback, onResolveErrorCallback);
  275. });
  276.  
  277. return;
  278. }
  279.  
  280. var resolveRequestStartTime = Date.now();
  281. that._logMessage('Resolve requested');
  282.  
  283. function onResultReady(data) {
  284. var postProcessedData = data;
  285. if (that.postProcessSymbolInfo) {
  286. postProcessedData = that.postProcessSymbolInfo(postProcessedData);
  287. }
  288.  
  289. that._logMessage('Symbol resolved: ' + (Date.now() - resolveRequestStartTime));
  290.  
  291. onSymbolResolvedCallback(postProcessedData);
  292. }
  293.  
  294. if (!this._configuration.supports_group_request) {
  295. this._send(this._datafeedURL + this._symbolResolveURL, {
  296. symbol: symbolName ? symbolName.toUpperCase() : ''
  297. })
  298. .done(function (response) {
  299. var data = response.d;
  300.  
  301. if (data.s && data.s != 'ok') {
  302. onResolveErrorCallback('unknown_symbol');
  303. } else {
  304. onResultReady(data);
  305. }
  306. })
  307. .fail(function (reason) {
  308. that._logMessage('Error resolving symbol: ' + JSON.stringify([reason]));
  309. onResolveErrorCallback('unknown_symbol');
  310. });
  311. } else {
  312. if (this._initializationFinished) {
  313. this._symbolsStorage.resolveSymbol(symbolName, onResultReady, onResolveErrorCallback);
  314. } else {
  315. this.on('initialized', function () {
  316. that._symbolsStorage.resolveSymbol(symbolName, onResultReady, onResolveErrorCallback);
  317. });
  318. }
  319. }
  320. };
  321.  
  322. Datafeeds.UDFCompatibleDatafeed.prototype._historyURL = '/history';
  323.  
  324. Datafeeds.UDFCompatibleDatafeed.prototype.getBars = function (symbolInfo, resolution, rangeStartDate, rangeEndDate, onDataCallback, onErrorCallback) {
  325.  
  326. // timestamp sample: 1399939200
  327. if (rangeStartDate > 0 && (rangeStartDate + '').length > 10) {
  328. throw ['Got a JS time instead of Unix one.', rangeStartDate, rangeEndDate];
  329. }
  330.  
  331. var that = this;
  332.  
  333. var requestStartTime = Date.now();
  334.  
  335.  
  336. //Additional Code
  337.  
  338. if (TradingViewResolutionConstant.IsIntraday(resolution)) {
  339. try {
  340. resolution = globalCurrentStockResolution;
  341. }
  342. catch (Ex) {
  343.  
  344. }
  345. }
  346.  
  347.  
  348.  
  349. this._send(this._datafeedURL + this._historyURL, {
  350. symbol: symbolInfo.ticker.toUpperCase(),
  351. resolution: resolution,
  352. from: rangeStartDate,
  353. to: rangeEndDate
  354. })
  355. .done(function (response) {
  356.  
  357. var data = response.d;
  358.  
  359. var nodata = data.s == 'no_data';
  360.  
  361. if (data.s != 'ok' && !nodata) {
  362. if (!!onErrorCallback) {
  363. onErrorCallback(data.s);
  364. }
  365.  
  366. return;
  367. }
  368.  
  369. var bars = [];
  370.  
  371. // data is JSON having format {s: "status" (ok, no_data, error),
  372. // v: [volumes], t: [times], o: [opens], h: [highs], l: [lows], c:[closes], nb: "optional_unixtime_if_no_data"}
  373. var barsCount = nodata ? 0 : data.t.length;
  374.  
  375. var volumePresent = typeof data.v != 'undefined';
  376. var ohlPresent = typeof data.o != 'undefined';
  377.  
  378. for (var i = 0; i < barsCount; ++i) {
  379.  
  380. var barValue = {
  381. time: data.t[i] * 1000,
  382. close: data.c[i]
  383. };
  384.  
  385. if (ohlPresent) {
  386. barValue.open = data.o[i];
  387. barValue.high = data.h[i];
  388. barValue.low = data.l[i];
  389. } else {
  390. barValue.open = barValue.high = barValue.low = barValue.close;
  391. }
  392.  
  393. if (volumePresent) {
  394. barValue.volume = data.v[i];
  395. }
  396.  
  397. bars.push(barValue);
  398. }
  399.  
  400. onDataCallback(bars, { version: that._protocolVersion, noData: nodata, nextTime: data.nb || data.nextTime });
  401. })
  402. .fail(function (arg) {
  403. console.warn(['getBars(): HTTP error', arg]);
  404.  
  405. if (!!onErrorCallback) {
  406. onErrorCallback('network error: ' + JSON.stringify(arg));
  407. }
  408. });
  409. };
  410.  
  411. Datafeeds.UDFCompatibleDatafeed.prototype.subscribeBars = function (symbolInfo, resolution, onRealtimeCallback, listenerGUID) {
  412. this._barsPulseUpdater.subscribeDataListener(symbolInfo, resolution, onRealtimeCallback, listenerGUID);
  413. };
  414.  
  415. Datafeeds.UDFCompatibleDatafeed.prototype.unsubscribeBars = function (listenerGUID) {
  416. this._barsPulseUpdater.unsubscribeDataListener(listenerGUID);
  417. };
  418.  
  419. Datafeeds.UDFCompatibleDatafeed.prototype.calculateHistoryDepth = function (period, resolutionBack, intervalBack) {
  420. };
  421.  
  422. Datafeeds.UDFCompatibleDatafeed.prototype.getQuotes = function (symbols, onDataCallback, onErrorCallback) {
  423. this._send(this._datafeedURL + '/quotes', { symbols: symbols })
  424. .done(function (response) {
  425. var data = JSON.parse(response.d);
  426. if (data.s == 'ok') {
  427. // JSON format is {s: "status", [{s: "symbol_status", n: "symbol_name", v: {"field1": "value1", "field2": "value2", ..., "fieldN": "valueN"}}]}
  428. if (onDataCallback) {
  429. onDataCallback(data.d);
  430. }
  431. } else {
  432. if (onErrorCallback) {
  433. onErrorCallback(data.errmsg);
  434. }
  435. }
  436. })
  437. .fail(function (arg) {
  438. if (onErrorCallback) {
  439. onErrorCallback('network error: ' + arg);
  440. }
  441. });
  442. };
  443.  
  444. Datafeeds.UDFCompatibleDatafeed.prototype.subscribeQuotes = function (symbols, fastSymbols, onRealtimeCallback, listenerGUID) {
  445. this._quotesPulseUpdater.subscribeDataListener(symbols, fastSymbols, onRealtimeCallback, listenerGUID);
  446. };
  447.  
  448. Datafeeds.UDFCompatibleDatafeed.prototype.unsubscribeQuotes = function (listenerGUID) {
  449. this._quotesPulseUpdater.unsubscribeDataListener(listenerGUID);
  450. };
  451.  
  452. // ==================================================================================================================================================
  453. // ==================================================================================================================================================
  454. // ==================================================================================================================================================
  455.  
  456. /*
  457. It's a symbol storage component for ExternalDatafeed. This component can
  458. * interact to UDF-compatible datafeed which supports whole group info requesting
  459. * do symbol resolving -- return symbol info by its name
  460. */
  461. Datafeeds.SymbolsStorage = function (datafeed) {
  462. this._datafeed = datafeed;
  463.  
  464. this._exchangesList = ['NYSE', 'FOREX', 'AMEX'];
  465. this._exchangesWaitingForData = {};
  466. this._exchangesDataCache = {};
  467.  
  468. this._symbolsInfo = {};
  469. this._symbolsList = [];
  470.  
  471. this._requestFullSymbolsList();
  472. };
  473.  
  474. Datafeeds.SymbolsStorage.prototype._requestFullSymbolsList = function () {
  475.  
  476. var that = this;
  477. var datafeed = this._datafeed;
  478.  
  479. for (var i = 0; i < this._exchangesList.length; ++i) {
  480.  
  481. var exchange = this._exchangesList[i];
  482.  
  483. if (this._exchangesDataCache.hasOwnProperty(exchange)) {
  484. continue;
  485. }
  486.  
  487. this._exchangesDataCache[exchange] = true;
  488.  
  489. this._exchangesWaitingForData[exchange] = 'waiting_for_data';
  490.  
  491. //this._datafeed._send(this._datafeed._datafeedURL + '/symbol_info', {
  492. // group: exchange
  493. //})
  494. // .done(function (exchange) {
  495. // return function (response) {
  496. // that._onExchangeDataReceived(exchange, JSON.parse(response));
  497. // that._onAnyExchangeResponseReceived(exchange);
  498. // };
  499. // }(exchange)) //jshint ignore:line
  500. // .fail(function (exchange) {
  501. // return function (reason) {
  502. // that._onAnyExchangeResponseReceived(exchange);
  503. // };
  504. // }(exchange)); //jshint ignore:line
  505. }
  506. };
  507.  
  508. Datafeeds.SymbolsStorage.prototype._onExchangeDataReceived = function (exchangeName, data) {
  509.  
  510. function tableField(data, name, index) {
  511. return data[name] instanceof Array ?
  512. data[name][index] :
  513. data[name];
  514. }
  515.  
  516. try {
  517. for (var symbolIndex = 0; symbolIndex < data.symbol.length; ++symbolIndex) {
  518.  
  519. var symbolName = data.symbol[symbolIndex];
  520. var listedExchange = tableField(data, 'exchange-listed', symbolIndex);
  521. var tradedExchange = tableField(data, 'exchange-traded', symbolIndex);
  522. var fullName = tradedExchange + ':' + symbolName;
  523.  
  524. // This feature support is not implemented yet
  525. // var hasDWM = tableField(data, "has-dwm", symbolIndex);
  526.  
  527. var hasIntraday = tableField(data, 'has-intraday', symbolIndex);
  528.  
  529. var tickerPresent = typeof data.ticker != 'undefined';
  530.  
  531. var symbolInfo = {
  532. name: symbolName,
  533. base_name: [listedExchange + ':' + symbolName],
  534. description: tableField(data, 'description', symbolIndex),
  535. full_name: fullName,
  536. legs: [fullName],
  537. has_intraday: hasIntraday,
  538. has_no_volume: tableField(data, 'has-no-volume', symbolIndex),
  539. listed_exchange: listedExchange,
  540. exchange: tradedExchange,
  541. minmov: tableField(data, 'minmovement', symbolIndex) || tableField(data, 'minmov', symbolIndex),
  542. minmove2: tableField(data, 'minmove2', symbolIndex) || tableField(data, 'minmov2', symbolIndex),
  543. fractional: tableField(data, 'fractional', symbolIndex),
  544. pointvalue: tableField(data, 'pointvalue', symbolIndex),
  545. pricescale: tableField(data, 'pricescale', symbolIndex),
  546. type: tableField(data, 'type', symbolIndex),
  547. session: tableField(data, 'session-regular', symbolIndex),
  548. ticker: tickerPresent ? tableField(data, 'ticker', symbolIndex) : symbolName,
  549. timezone: tableField(data, 'timezone', symbolIndex),
  550. supported_resolutions: tableField(data, 'supported-resolutions', symbolIndex) || this._datafeed.defaultConfiguration().supported_resolutions,
  551. force_session_rebuild: tableField(data, 'force-session-rebuild', symbolIndex) || false,
  552. has_daily: tableField(data, 'has-daily', symbolIndex) || true,
  553. intraday_multipliers: tableField(data, 'intraday-multipliers', symbolIndex) || ['1', '5', '15', '30', '60'],
  554. has_fractional_volume: tableField(data, 'has-fractional-volume', symbolIndex) || false,
  555. has_weekly_and_monthly: tableField(data, 'has-weekly-and-monthly', symbolIndex) || false,
  556. has_empty_bars: tableField(data, 'has-empty-bars', symbolIndex) || false,
  557. volume_precision: tableField(data, 'volume-precision', symbolIndex) || 0
  558. };
  559.  
  560. this._symbolsInfo[symbolInfo.ticker] = this._symbolsInfo[symbolName] = this._symbolsInfo[fullName] = symbolInfo;
  561. this._symbolsList.push(symbolName);
  562. }
  563. }
  564. catch (error) {
  565. throw 'API error when processing exchange `' + exchangeName + '` symbol #' + symbolIndex + ': ' + error;
  566. }
  567. };
  568.  
  569. Datafeeds.SymbolsStorage.prototype._onAnyExchangeResponseReceived = function (exchangeName) {
  570.  
  571. delete this._exchangesWaitingForData[exchangeName];
  572.  
  573. var allDataReady = Object.keys(this._exchangesWaitingForData).length === 0;
  574.  
  575. if (allDataReady) {
  576. this._symbolsList.sort();
  577. this._datafeed._logMessage('All exchanges data ready');
  578. this._datafeed.onInitialized();
  579. }
  580. };
  581.  
  582. // BEWARE: this function does not consider symbol's exchange
  583. Datafeeds.SymbolsStorage.prototype.resolveSymbol = function (symbolName, onSymbolResolvedCallback, onResolveErrorCallback) {
  584. var that = this;
  585.  
  586. setTimeout(function () {
  587. if (!that._symbolsInfo.hasOwnProperty(symbolName)) {
  588. onResolveErrorCallback('invalid symbol');
  589. } else {
  590. onSymbolResolvedCallback(that._symbolsInfo[symbolName]);
  591. }
  592. }, 0);
  593. };
  594.  
  595. // ==================================================================================================================================================
  596. // ==================================================================================================================================================
  597. // ==================================================================================================================================================
  598.  
  599. /*
  600. It's a symbol search component for ExternalDatafeed. This component can do symbol search only.
  601. This component strongly depends on SymbolsDataStorage and cannot work without it. Maybe, it would be
  602. better to merge it to SymbolsDataStorage.
  603. */
  604.  
  605. Datafeeds.SymbolSearchComponent = function (datafeed) {
  606. this._datafeed = datafeed;
  607. };
  608.  
  609. // searchArgument = { searchString, onResultReadyCallback}
  610. Datafeeds.SymbolSearchComponent.prototype.searchSymbols = function (searchArgument, maxSearchResults) {
  611.  
  612. if (!this._datafeed._symbolsStorage) {
  613. throw 'Cannot use local symbol search when no groups information is available';
  614. }
  615.  
  616. var symbolsStorage = this._datafeed._symbolsStorage;
  617.  
  618. var results = []; // array of WeightedItem { item, weight }
  619. var queryIsEmpty = !searchArgument.searchString || searchArgument.searchString.length === 0;
  620. var searchStringUpperCase = searchArgument.searchString.toUpperCase();
  621.  
  622. for (var i = 0; i < symbolsStorage._symbolsList.length; ++i) {
  623. var symbolName = symbolsStorage._symbolsList[i];
  624. var item = symbolsStorage._symbolsInfo[symbolName];
  625.  
  626. if (searchArgument.type && searchArgument.type.length > 0 && item.type != searchArgument.type) {
  627. continue;
  628. }
  629.  
  630. if (searchArgument.exchange && searchArgument.exchange.length > 0 && item.exchange != searchArgument.exchange) {
  631. continue;
  632. }
  633.  
  634. var positionInName = item.name.toUpperCase().indexOf(searchStringUpperCase);
  635. var positionInDescription = item.description.toUpperCase().indexOf(searchStringUpperCase);
  636.  
  637. if (queryIsEmpty || positionInName >= 0 || positionInDescription >= 0) {
  638. var found = false;
  639. for (var resultIndex = 0; resultIndex < results.length; resultIndex++) {
  640. if (results[resultIndex].item == item) {
  641. found = true;
  642. break;
  643. }
  644. }
  645.  
  646. if (!found) {
  647. var weight = positionInName >= 0 ? positionInName : 8000 + positionInDescription;
  648. results.push({ item: item, weight: weight });
  649. }
  650. }
  651. }
  652.  
  653. searchArgument.onResultReadyCallback(
  654. results
  655. .sort(function (weightedItem1, weightedItem2) {
  656. return weightedItem1.weight - weightedItem2.weight;
  657. })
  658. .map(function (weightedItem) {
  659. var item = weightedItem.item;
  660. return {
  661. symbol: item.name,
  662. full_name: item.full_name,
  663. description: item.description,
  664. exchange: item.exchange,
  665. params: [],
  666. type: item.type,
  667. ticker: item.name
  668. };
  669. })
  670. .slice(0, Math.min(results.length, maxSearchResults))
  671. );
  672. };
  673.  
  674. // ==================================================================================================================================================
  675. // ==================================================================================================================================================
  676. // ==================================================================================================================================================
  677.  
  678. /*
  679. This is a pulse updating components for ExternalDatafeed. They emulates realtime updates with periodic requests.
  680. */
  681.  
  682. Datafeeds.DataPulseUpdater = function (datafeed, updateFrequency) {
  683. this._datafeed = datafeed;
  684. this._subscribers = {};
  685.  
  686. this._requestsPending = 0;
  687. var that = this;
  688.  
  689. var update = function () {
  690.  
  691. try {
  692. var iFrameChart = $("#tv_chart_container").children("iframe").contents().find("body")[0];
  693. var marketStateSpanTag = $(iFrameChart).find("span")[64];
  694. var marketState = marketStateSpanTag.innerText;
  695. }
  696. catch (ex) {
  697.  
  698. }
  699.  
  700. if (marketState == 'closed') {
  701. return;
  702. }
  703.  
  704. if (that._requestsPending > 0) {
  705. return;
  706. }
  707.  
  708. for (var listenerGUID in that._subscribers) {
  709. var subscriptionRecord = that._subscribers[listenerGUID];
  710. var resolution = subscriptionRecord.resolution;
  711.  
  712. var datesRangeRight = parseInt((new Date().valueOf()) / 1000);
  713.  
  714. // BEWARE: please note we really need 2 bars, not the only last one
  715. // see the explanation below. `10` is the `large enough` value to work around holidays
  716. var datesRangeLeft = datesRangeRight - that.periodLengthSeconds(resolution, 10);
  717.  
  718. that._requestsPending++;
  719.  
  720. (function (_subscriptionRecord) {
  721.  
  722. that._datafeed.getBars(_subscriptionRecord.symbolInfo, resolution, datesRangeLeft, datesRangeRight, function (bars) {
  723. that._requestsPending--;
  724.  
  725. // means the subscription was cancelled while waiting for data
  726. if (!that._subscribers.hasOwnProperty(listenerGUID)) {
  727. return;
  728. }
  729.  
  730. if (bars.length === 0) {
  731. return;
  732. }
  733.  
  734. var lastBar = bars[bars.length - 1];
  735. if (!isNaN(_subscriptionRecord.lastBarTime) && lastBar.time < _subscriptionRecord.lastBarTime) {
  736. return;
  737. }
  738.  
  739. var subscribers = _subscriptionRecord.listeners;
  740.  
  741. // BEWARE: this one isn't working when first update comes and this update makes a new bar. In this case
  742. // _subscriptionRecord.lastBarTime = NaN
  743. var isNewBar = !isNaN(_subscriptionRecord.lastBarTime) && lastBar.time > _subscriptionRecord.lastBarTime;
  744.  
  745. // 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
  746. // old bar's last 5 seconds trades will be lost). Thus, at fist we should broadcast old bar updates when it's ready.
  747. if (isNewBar) {
  748.  
  749. if (bars.length < 2) {
  750. throw 'Not enough bars in history for proper pulse update. Need at least 2.';
  751. }
  752.  
  753. var previousBar = bars[bars.length - 2];
  754. for (var i = 0; i < subscribers.length; ++i) {
  755. subscribers[i](previousBar);
  756. }
  757. }
  758.  
  759. _subscriptionRecord.lastBarTime = lastBar.time;
  760.  
  761. for (var i = 0; i < subscribers.length; ++i) {
  762. subscribers[i](lastBar);
  763. }
  764. },
  765.  
  766. // on error
  767. function () {
  768. that._requestsPending--;
  769. });
  770. })(subscriptionRecord); //jshint ignore:line
  771.  
  772. }
  773. };
  774.  
  775.  
  776. var realTimeUpdate = function (latestData, timeframe) {
  777.  
  778. //console.log('Chart Data: ' + latestData.StockInfo.StockCode);
  779.  
  780. for (var listenerGUID in that._subscribers) {
  781. var subscriptionRecord = that._subscribers[listenerGUID];
  782. var resolution = subscriptionRecord.resolution;
  783.  
  784. var datesRangeRight = parseInt((new Date().valueOf()) / 1000);
  785.  
  786. // BEWARE: please note we really need 2 bars, not the only last one
  787. // see the explanation below. `10` is the `large enough` value to work around holidays
  788. var datesRangeLeft = datesRangeRight - that.periodLengthSeconds(resolution, 10);
  789.  
  790. if (latestData.StockInfo.StockCode.toUpperCase() ==
  791. subscriptionRecord.symbolInfo.ticker.toUpperCase()) {
  792.  
  793. if (TradingViewResolutionConstant.IsIntraday(resolution) ||
  794. resolution == timeframe) {
  795.  
  796. var barValue = {
  797. time: latestData.StockHistory.DateUnixEpochFormat * 1000,
  798. close: latestData.StockHistory.Last,
  799. open: latestData.StockHistory.Open,
  800. low: latestData.StockHistory.Low,
  801. high: latestData.StockHistory.High
  802. };
  803.  
  804. if (latestData.StockInfo.StockType == 2) {
  805. barValue.volume = latestData.StockHistory.Value;
  806. }
  807. else {
  808. barValue.volume = latestData.StockHistory.Volume;
  809. }
  810.  
  811.  
  812. var subscribers = subscriptionRecord.listeners;
  813.  
  814. subscriptionRecord.lastBarTime = barValue.time;
  815.  
  816. for (var i = 0; i < subscribers.length; ++i) {
  817. subscribers[i](barValue);
  818. }
  819.  
  820. }
  821. }
  822.  
  823.  
  824.  
  825. }
  826. };
  827.  
  828.  
  829.  
  830. try {
  831. stockChartHub.on('sendRealTimeIndividualStockPrice', function (data, timeframe) {
  832. //console.log(data);
  833. realTimeUpdate(data, timeframe);
  834. });
  835.  
  836. //stockChartHub.client.sendRealTimeIndividualStockPrice = function (data, timeframe) {
  837. // realTimeUpdate(data, timeframe);
  838. //};
  839. }
  840. catch (ex) {
  841.  
  842. }
  843.  
  844.  
  845.  
  846.  
  847.  
  848. if (typeof updateFrequency != 'undefined' && updateFrequency > 0) {
  849. //setInterval(update, updateFrequency);
  850. }
  851. };
  852.  
  853. Datafeeds.DataPulseUpdater.prototype.unsubscribeDataListener = function (listenerGUID) {
  854. this._datafeed._logMessage('Unsubscribing ' + listenerGUID);
  855. delete this._subscribers[listenerGUID];
  856. };
  857.  
  858. Datafeeds.DataPulseUpdater.prototype.subscribeDataListener = function (symbolInfo, resolution, newDataCallback, listenerGUID) {
  859.  
  860. this._datafeed._logMessage('Subscribing ' + listenerGUID);
  861.  
  862. var key = symbolInfo.name + ', ' + resolution;
  863.  
  864. if (!this._subscribers.hasOwnProperty(listenerGUID)) {
  865.  
  866. this._subscribers[listenerGUID] = {
  867. symbolInfo: symbolInfo,
  868. resolution: resolution,
  869. lastBarTime: NaN,
  870. listeners: []
  871. };
  872. }
  873.  
  874. this._subscribers[listenerGUID].listeners.push(newDataCallback);
  875. };
  876.  
  877. Datafeeds.DataPulseUpdater.prototype.periodLengthSeconds = function (resolution, requiredPeriodsCount) {
  878. var daysCount = 0;
  879.  
  880. if (resolution == 'D') {
  881. daysCount = requiredPeriodsCount;
  882. } else if (resolution == 'M') {
  883. daysCount = 31 * requiredPeriodsCount;
  884. } else if (resolution == 'W') {
  885. daysCount = 7 * requiredPeriodsCount;
  886. } else {
  887. daysCount = requiredPeriodsCount * resolution / (24 * 60);
  888. }
  889.  
  890. return daysCount * 24 * 60 * 60;
  891. };
  892.  
  893. Datafeeds.QuotesPulseUpdater = function (datafeed) {
  894. this._datafeed = datafeed;
  895. this._subscribers = {};
  896. this._updateInterval = 60 * 1000;
  897. this._fastUpdateInterval = 10 * 1000;
  898. this._requestsPending = 0;
  899.  
  900. var that = this;
  901.  
  902. setInterval(function () {
  903. that._updateQuotes(function (subscriptionRecord) { return subscriptionRecord.symbols; });
  904. }, this._updateInterval);
  905.  
  906. setInterval(function () {
  907. that._updateQuotes(function (subscriptionRecord) { return subscriptionRecord.fastSymbols.length > 0 ? subscriptionRecord.fastSymbols : subscriptionRecord.symbols; });
  908. }, this._fastUpdateInterval);
  909. };
  910.  
  911. Datafeeds.QuotesPulseUpdater.prototype.subscribeDataListener = function (symbols, fastSymbols, newDataCallback, listenerGUID) {
  912. if (!this._subscribers.hasOwnProperty(listenerGUID)) {
  913. this._subscribers[listenerGUID] = {
  914. symbols: symbols,
  915. fastSymbols: fastSymbols,
  916. listeners: []
  917. };
  918. }
  919.  
  920. this._subscribers[listenerGUID].listeners.push(newDataCallback);
  921. };
  922.  
  923. Datafeeds.QuotesPulseUpdater.prototype.unsubscribeDataListener = function (listenerGUID) {
  924. delete this._subscribers[listenerGUID];
  925. };
  926.  
  927. Datafeeds.QuotesPulseUpdater.prototype._updateQuotes = function (symbolsGetter) {
  928. if (this._requestsPending > 0) {
  929. return;
  930. }
  931.  
  932. var that = this;
  933. for (var listenerGUID in this._subscribers) {
  934. this._requestsPending++;
  935.  
  936. var subscriptionRecord = this._subscribers[listenerGUID];
  937. this._datafeed.getQuotes(symbolsGetter(subscriptionRecord),
  938.  
  939. // onDataCallback
  940. (function (subscribers, guid) {
  941. return function (data) {
  942. that._requestsPending--;
  943.  
  944. // means the subscription was cancelled while waiting for data
  945. if (!that._subscribers.hasOwnProperty(guid)) {
  946. return;
  947. }
  948.  
  949. for (var i = 0; i < subscribers.length; ++i) {
  950. subscribers[i](data);
  951. }
  952. };
  953. }(subscriptionRecord.listeners, listenerGUID)), //jshint ignore:line
  954. // onErrorCallback
  955. function (error) {
  956. that._requestsPending--;
  957. }); //jshint ignore:line
  958. }
  959. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement