old-datafeed.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840
  1. 'use strict';
  2. /*
  3. This class implements interaction with UDF-compatible datafeed.
  4. See UDF protocol reference at
  5. https://github.com/tradingview/charting_library/wiki/UDF
  6. */
  7. function parseJSONorNot(mayBeJSON) {
  8. if (typeof mayBeJSON === 'string') {
  9. return JSON.parse(mayBeJSON);
  10. } else {
  11. return mayBeJSON;
  12. }
  13. }
  14. var Datafeeds = {};
  15. Datafeeds.UDFCompatibleDatafeed = function(datafeedURL, updateFrequency) {
  16. this._datafeedURL = datafeedURL;
  17. this._configuration = undefined;
  18. this._symbolSearch = null;
  19. this._symbolsStorage = null;
  20. this._barsPulseUpdater = new Datafeeds.DataPulseUpdater(this, updateFrequency || 10 * 1000);
  21. this._quotesPulseUpdater = new Datafeeds.QuotesPulseUpdater(this);
  22. this._enableLogging = false;
  23. this._initializationFinished = false;
  24. this._callbacks = {};
  25. this._initialize();
  26. };
  27. Datafeeds.UDFCompatibleDatafeed.prototype.defaultConfiguration = function() {
  28. return {
  29. supports_search: false,
  30. supports_group_request: true,
  31. supported_resolutions: ['1', '5', '15', '30', '60', '1D', '1W', '1M'],
  32. supports_marks: false,
  33. supports_timescale_marks: false
  34. };
  35. };
  36. Datafeeds.UDFCompatibleDatafeed.prototype.getServerTime = function(callback) {
  37. if (this._configuration.supports_time) {
  38. this._send(this._datafeedURL + '/time', {})
  39. .done(function(response) {
  40. callback(+response);
  41. })
  42. .fail(function() {
  43. });
  44. }
  45. };
  46. Datafeeds.UDFCompatibleDatafeed.prototype.on = function(event, callback) {
  47. if (!this._callbacks.hasOwnProperty(event)) {
  48. this._callbacks[event] = [];
  49. }
  50. this._callbacks[event].push(callback);
  51. return this;
  52. };
  53. Datafeeds.UDFCompatibleDatafeed.prototype._fireEvent = function(event, argument) {
  54. if (this._callbacks.hasOwnProperty(event)) {
  55. var callbacksChain = this._callbacks[event];
  56. for (var i = 0; i < callbacksChain.length; ++i) {
  57. callbacksChain[i](argument);
  58. }
  59. this._callbacks[event] = [];
  60. }
  61. };
  62. Datafeeds.UDFCompatibleDatafeed.prototype.onInitialized = function() {
  63. this._initializationFinished = true;
  64. this._fireEvent('initialized');
  65. };
  66. Datafeeds.UDFCompatibleDatafeed.prototype._logMessage = function(message) {
  67. if (this._enableLogging) {
  68. var now = new Date();
  69. console.log(now.toLocaleTimeString() + '.' + now.getMilliseconds() + '> ' + message);
  70. }
  71. };
  72. Datafeeds.UDFCompatibleDatafeed.prototype._send = function(url, params) {
  73. var request = url;
  74. if (params) {
  75. for (var i = 0; i < Object.keys(params).length; ++i) {
  76. var key = Object.keys(params)[i];
  77. var value = encodeURIComponent(params[key]);
  78. request += (i === 0 ? '?' : '&') + key + '=' + value;
  79. }
  80. }
  81. this._logMessage('New request: ' + request);
  82. return $.ajax({
  83. type: 'GET',
  84. url: request,
  85. contentType: 'text/plain'
  86. });
  87. };
  88. Datafeeds.UDFCompatibleDatafeed.prototype._initialize = function() {
  89. var that = this;
  90. this._send(this._datafeedURL + '/config')
  91. .done(function(response) {
  92. var configurationData = parseJSONorNot(response);
  93. that._setupWithConfiguration(configurationData);
  94. })
  95. .fail(function(reason) {
  96. that._setupWithConfiguration(that.defaultConfiguration());
  97. });
  98. };
  99. Datafeeds.UDFCompatibleDatafeed.prototype.onReady = function(callback) {
  100. var that = this;
  101. if (this._configuration) {
  102. setTimeout(function() {
  103. callback(that._configuration);
  104. }, 0);
  105. } else {
  106. this.on('configuration_ready', function() {
  107. callback(that._configuration);
  108. });
  109. }
  110. };
  111. Datafeeds.UDFCompatibleDatafeed.prototype._setupWithConfiguration = function(configurationData) {
  112. this._configuration = configurationData;
  113. if (!configurationData.exchanges) {
  114. configurationData.exchanges = [];
  115. }
  116. // @obsolete; remove in 1.5
  117. var supportedResolutions = configurationData.supported_resolutions || configurationData.supportedResolutions;
  118. configurationData.supported_resolutions = supportedResolutions;
  119. // @obsolete; remove in 1.5
  120. var symbolsTypes = configurationData.symbols_types || configurationData.symbolsTypes;
  121. configurationData.symbols_types = symbolsTypes;
  122. if (!configurationData.supports_search && !configurationData.supports_group_request) {
  123. throw new Error('Unsupported datafeed configuration. Must either support search, or support group request');
  124. }
  125. if (!configurationData.supports_search) {
  126. this._symbolSearch = new Datafeeds.SymbolSearchComponent(this);
  127. }
  128. if (configurationData.supports_group_request) {
  129. // this component will call onInitialized() by itself
  130. this._symbolsStorage = new Datafeeds.SymbolsStorage(this);
  131. } else {
  132. this.onInitialized();
  133. }
  134. this._fireEvent('configuration_ready');
  135. this._logMessage('Initialized with ' + JSON.stringify(configurationData));
  136. };
  137. // ===============================================================================================================================
  138. // The functions set below is the implementation of JavaScript API.
  139. Datafeeds.UDFCompatibleDatafeed.prototype.getMarks = function(symbolInfo, rangeStart, rangeEnd, onDataCallback, resolution) {
  140. if (this._configuration.supports_marks) {
  141. this._send(this._datafeedURL + '/marks', {
  142. symbol: symbolInfo.ticker.toUpperCase(),
  143. from: rangeStart,
  144. to: rangeEnd,
  145. resolution: resolution
  146. })
  147. .done(function(response) {
  148. onDataCallback(parseJSONorNot(response));
  149. })
  150. .fail(function() {
  151. onDataCallback([]);
  152. });
  153. }
  154. };
  155. Datafeeds.UDFCompatibleDatafeed.prototype.getTimescaleMarks = function(symbolInfo, rangeStart, rangeEnd, onDataCallback, resolution) {
  156. if (this._configuration.supports_timescale_marks) {
  157. this._send(this._datafeedURL + '/timescale_marks', {
  158. symbol: symbolInfo.ticker.toUpperCase(),
  159. from: rangeStart,
  160. to: rangeEnd,
  161. resolution: resolution
  162. })
  163. .done(function(response) {
  164. onDataCallback(parseJSONorNot(response));
  165. })
  166. .fail(function() {
  167. onDataCallback([]);
  168. });
  169. }
  170. };
  171. Datafeeds.UDFCompatibleDatafeed.prototype.searchSymbols = function(searchString, exchange, type, onResultReadyCallback) {
  172. var MAX_SEARCH_RESULTS = 30;
  173. if (!this._configuration) {
  174. onResultReadyCallback([]);
  175. return;
  176. }
  177. if (this._configuration.supports_search) {
  178. this._send(this._datafeedURL + '/search', {
  179. limit: MAX_SEARCH_RESULTS,
  180. query: searchString.toUpperCase(),
  181. type: type,
  182. exchange: exchange
  183. })
  184. .done(function(response) {
  185. var data = parseJSONorNot(response);
  186. for (var i = 0; i < data.length; ++i) {
  187. if (!data[i].params) {
  188. data[i].params = [];
  189. }
  190. data[i].exchange = data[i].exchange || '';
  191. }
  192. if (typeof data.s == 'undefined' || data.s !== 'error') {
  193. onResultReadyCallback(data);
  194. } else {
  195. onResultReadyCallback([]);
  196. }
  197. })
  198. .fail(function(reason) {
  199. onResultReadyCallback([]);
  200. });
  201. } else {
  202. if (!this._symbolSearch) {
  203. throw new Error('Datafeed error: inconsistent configuration (symbol search)');
  204. }
  205. var searchArgument = {
  206. searchString: searchString,
  207. exchange: exchange,
  208. type: type,
  209. onResultReadyCallback: onResultReadyCallback
  210. };
  211. if (this._initializationFinished) {
  212. this._symbolSearch.searchSymbols(searchArgument, MAX_SEARCH_RESULTS);
  213. } else {
  214. var that = this;
  215. this.on('initialized', function() {
  216. that._symbolSearch.searchSymbols(searchArgument, MAX_SEARCH_RESULTS);
  217. });
  218. }
  219. }
  220. };
  221. Datafeeds.UDFCompatibleDatafeed.prototype._symbolResolveURL = '/symbols';
  222. // BEWARE: this function does not consider symbol's exchange
  223. Datafeeds.UDFCompatibleDatafeed.prototype.resolveSymbol = function(symbolName, onSymbolResolvedCallback, onResolveErrorCallback) {
  224. var that = this;
  225. if (!this._initializationFinished) {
  226. this.on('initialized', function() {
  227. that.resolveSymbol(symbolName, onSymbolResolvedCallback, onResolveErrorCallback);
  228. });
  229. return;
  230. }
  231. var resolveRequestStartTime = Date.now();
  232. that._logMessage('Resolve requested');
  233. function onResultReady(data) {
  234. var postProcessedData = data;
  235. if (that.postProcessSymbolInfo) {
  236. postProcessedData = that.postProcessSymbolInfo(postProcessedData);
  237. }
  238. that._logMessage('Symbol resolved: ' + (Date.now() - resolveRequestStartTime));
  239. onSymbolResolvedCallback(postProcessedData);
  240. }
  241. if (!this._configuration.supports_group_request) {
  242. this._send(this._datafeedURL + this._symbolResolveURL, {
  243. symbol: symbolName ? symbolName.toUpperCase() : ''
  244. })
  245. .done(function(response) {
  246. var data = parseJSONorNot(response);
  247. if (data.s && data.s !== 'ok') {
  248. onResolveErrorCallback('unknown_symbol');
  249. } else {
  250. onResultReady(data);
  251. }
  252. })
  253. .fail(function(reason) {
  254. that._logMessage('Error resolving symbol: ' + JSON.stringify([reason]));
  255. onResolveErrorCallback('unknown_symbol');
  256. });
  257. } else {
  258. if (this._initializationFinished) {
  259. this._symbolsStorage.resolveSymbol(symbolName, onResultReady, onResolveErrorCallback);
  260. } else {
  261. this.on('initialized', function() {
  262. that._symbolsStorage.resolveSymbol(symbolName, onResultReady, onResolveErrorCallback);
  263. });
  264. }
  265. }
  266. };
  267. Datafeeds.UDFCompatibleDatafeed.prototype._historyURL = '/history';
  268. Datafeeds.UDFCompatibleDatafeed.prototype.getBars = function(symbolInfo, resolution, rangeStartDate, rangeEndDate, onDataCallback, onErrorCallback) {
  269. // timestamp sample: 1399939200
  270. if (rangeStartDate > 0 && (rangeStartDate + '').length > 10) {
  271. throw new Error(['Got a JS time instead of Unix one.', rangeStartDate, rangeEndDate]);
  272. }
  273. this._send(this._datafeedURL + this._historyURL, {
  274. symbol: symbolInfo.ticker.toUpperCase(),
  275. resolution: resolution,
  276. from: rangeStartDate,
  277. to: rangeEndDate
  278. })
  279. .done(function(response) {
  280. var data = parseJSONorNot(response);
  281. var nodata = data.s === 'no_data';
  282. if (data.s !== 'ok' && !nodata) {
  283. if (!!onErrorCallback) {
  284. onErrorCallback(data.s);
  285. }
  286. return;
  287. }
  288. var bars = [];
  289. // data is JSON having format {s: "status" (ok, no_data, error),
  290. // v: [volumes], t: [times], o: [opens], h: [highs], l: [lows], c:[closes], nb: "optional_unixtime_if_no_data"}
  291. var barsCount = nodata ? 0 : data.t.length;
  292. var volumePresent = typeof data.v != 'undefined';
  293. var ohlPresent = typeof data.o != 'undefined';
  294. for (var i = 0; i < barsCount; ++i) {
  295. var barValue = {
  296. time: data.t[i] * 1000,
  297. close: data.c[i]
  298. };
  299. if (ohlPresent) {
  300. barValue.open = data.o[i];
  301. barValue.high = data.h[i];
  302. barValue.low = data.l[i];
  303. } else {
  304. barValue.open = barValue.high = barValue.low = barValue.close;
  305. }
  306. if (volumePresent) {
  307. barValue.volume = data.v[i];
  308. }
  309. bars.push(barValue);
  310. }
  311. onDataCallback(bars, { noData: nodata, nextTime: data.nb || data.nextTime });
  312. })
  313. .fail(function(arg) {
  314. console.warn(['getBars(): HTTP error', arg]);
  315. if (!!onErrorCallback) {
  316. onErrorCallback('network error: ' + JSON.stringify(arg));
  317. }
  318. });
  319. };
  320. Datafeeds.UDFCompatibleDatafeed.prototype.subscribeBars = function(symbolInfo, resolution, onRealtimeCallback, listenerGUID, onResetCacheNeededCallback) {
  321. this._barsPulseUpdater.subscribeDataListener(symbolInfo, resolution, onRealtimeCallback, listenerGUID, onResetCacheNeededCallback);
  322. };
  323. Datafeeds.UDFCompatibleDatafeed.prototype.unsubscribeBars = function(listenerGUID) {
  324. this._barsPulseUpdater.unsubscribeDataListener(listenerGUID);
  325. };
  326. Datafeeds.UDFCompatibleDatafeed.prototype.calculateHistoryDepth = function(period, resolutionBack, intervalBack) {
  327. };
  328. Datafeeds.UDFCompatibleDatafeed.prototype.getQuotes = function(symbols, onDataCallback, onErrorCallback) {
  329. this._send(this._datafeedURL + '/quotes', { symbols: symbols })
  330. .done(function(response) {
  331. var data = parseJSONorNot(response);
  332. if (data.s === 'ok') {
  333. // JSON format is {s: "status", [{s: "symbol_status", n: "symbol_name", v: {"field1": "value1", "field2": "value2", ..., "fieldN": "valueN"}}]}
  334. if (onDataCallback) {
  335. onDataCallback(data.d);
  336. }
  337. } else {
  338. if (onErrorCallback) {
  339. onErrorCallback(data.errmsg);
  340. }
  341. }
  342. })
  343. .fail(function(arg) {
  344. if (onErrorCallback) {
  345. onErrorCallback('network error: ' + arg);
  346. }
  347. });
  348. };
  349. Datafeeds.UDFCompatibleDatafeed.prototype.subscribeQuotes = function(symbols, fastSymbols, onRealtimeCallback, listenerGUID) {
  350. this._quotesPulseUpdater.subscribeDataListener(symbols, fastSymbols, onRealtimeCallback, listenerGUID);
  351. };
  352. Datafeeds.UDFCompatibleDatafeed.prototype.unsubscribeQuotes = function(listenerGUID) {
  353. this._quotesPulseUpdater.unsubscribeDataListener(listenerGUID);
  354. };
  355. // ==================================================================================================================================================
  356. // ==================================================================================================================================================
  357. // ==================================================================================================================================================
  358. /*
  359. It's a symbol storage component for ExternalDatafeed. This component can
  360. * interact to UDF-compatible datafeed which supports whole group info requesting
  361. * do symbol resolving -- return symbol info by its name
  362. */
  363. Datafeeds.SymbolsStorage = function(datafeed) {
  364. this._datafeed = datafeed;
  365. this._exchangesList = ['NYSE', 'FOREX', 'AMEX'];
  366. this._exchangesWaitingForData = {};
  367. this._exchangesDataCache = {};
  368. this._symbolsInfo = {};
  369. this._symbolsList = [];
  370. this._requestFullSymbolsList();
  371. };
  372. Datafeeds.SymbolsStorage.prototype._requestFullSymbolsList = function() {
  373. var that = this;
  374. for (var i = 0; i < this._exchangesList.length; ++i) {
  375. var exchange = this._exchangesList[i];
  376. if (this._exchangesDataCache.hasOwnProperty(exchange)) {
  377. continue;
  378. }
  379. this._exchangesDataCache[exchange] = true;
  380. this._exchangesWaitingForData[exchange] = 'waiting_for_data';
  381. this._datafeed._send(this._datafeed._datafeedURL + '/symbol_info', {
  382. group: exchange
  383. })
  384. .done((function(exchange) {
  385. return function(response) {
  386. that._onExchangeDataReceived(exchange, parseJSONorNot(response));
  387. that._onAnyExchangeResponseReceived(exchange);
  388. };
  389. })(exchange))
  390. .fail((function(exchange) {
  391. return function(reason) {
  392. that._onAnyExchangeResponseReceived(exchange);
  393. };
  394. })(exchange));
  395. }
  396. };
  397. Datafeeds.SymbolsStorage.prototype._onExchangeDataReceived = function(exchangeName, data) {
  398. function tableField(data, name, index) {
  399. return data[name] instanceof Array ?
  400. data[name][index] :
  401. data[name];
  402. }
  403. try {
  404. for (var symbolIndex = 0; symbolIndex < data.symbol.length; ++symbolIndex) {
  405. var symbolName = data.symbol[symbolIndex];
  406. var listedExchange = tableField(data, 'exchange-listed', symbolIndex);
  407. var tradedExchange = tableField(data, 'exchange-traded', symbolIndex);
  408. var fullName = tradedExchange + ':' + symbolName;
  409. // This feature support is not implemented yet
  410. // var hasDWM = tableField(data, "has-dwm", symbolIndex);
  411. var hasIntraday = tableField(data, 'has-intraday', symbolIndex);
  412. var tickerPresent = typeof data.ticker != 'undefined';
  413. var symbolInfo = {
  414. name: symbolName,
  415. base_name: [listedExchange + ':' + symbolName],
  416. description: tableField(data, 'description', symbolIndex),
  417. full_name: fullName,
  418. legs: [fullName],
  419. has_intraday: hasIntraday,
  420. has_no_volume: tableField(data, 'has-no-volume', symbolIndex),
  421. listed_exchange: listedExchange,
  422. exchange: tradedExchange,
  423. minmov: tableField(data, 'minmovement', symbolIndex) || tableField(data, 'minmov', symbolIndex),
  424. minmove2: tableField(data, 'minmove2', symbolIndex) || tableField(data, 'minmov2', symbolIndex),
  425. fractional: tableField(data, 'fractional', symbolIndex),
  426. pointvalue: tableField(data, 'pointvalue', symbolIndex),
  427. pricescale: tableField(data, 'pricescale', symbolIndex),
  428. type: tableField(data, 'type', symbolIndex),
  429. session: tableField(data, 'session-regular', symbolIndex),
  430. ticker: tickerPresent ? tableField(data, 'ticker', symbolIndex) : symbolName,
  431. timezone: tableField(data, 'timezone', symbolIndex),
  432. supported_resolutions: tableField(data, 'supported-resolutions', symbolIndex) || this._datafeed.defaultConfiguration().supported_resolutions,
  433. force_session_rebuild: tableField(data, 'force-session-rebuild', symbolIndex) || false,
  434. has_daily: tableField(data, 'has-daily', symbolIndex) || true,
  435. intraday_multipliers: tableField(data, 'intraday-multipliers', symbolIndex) || ['1', '5', '15', '30', '60'],
  436. has_fractional_volume: tableField(data, 'has-fractional-volume', symbolIndex) || false,
  437. has_weekly_and_monthly: tableField(data, 'has-weekly-and-monthly', symbolIndex) || false,
  438. has_empty_bars: tableField(data, 'has-empty-bars', symbolIndex) || false,
  439. volume_precision: tableField(data, 'volume-precision', symbolIndex) || 0
  440. };
  441. this._symbolsInfo[symbolInfo.ticker] = this._symbolsInfo[symbolName] = this._symbolsInfo[fullName] = symbolInfo;
  442. this._symbolsList.push(symbolName);
  443. }
  444. } catch (error) {
  445. throw new Error('API error when processing exchange `' + exchangeName + '` symbol #' + symbolIndex + ': ' + error);
  446. }
  447. };
  448. Datafeeds.SymbolsStorage.prototype._onAnyExchangeResponseReceived = function(exchangeName) {
  449. delete this._exchangesWaitingForData[exchangeName];
  450. var allDataReady = Object.keys(this._exchangesWaitingForData).length === 0;
  451. if (allDataReady) {
  452. this._symbolsList.sort();
  453. this._datafeed._logMessage('All exchanges data ready');
  454. this._datafeed.onInitialized();
  455. }
  456. };
  457. // BEWARE: this function does not consider symbol's exchange
  458. Datafeeds.SymbolsStorage.prototype.resolveSymbol = function(symbolName, onSymbolResolvedCallback, onResolveErrorCallback) {
  459. var that = this;
  460. setTimeout(function() {
  461. if (!that._symbolsInfo.hasOwnProperty(symbolName)) {
  462. onResolveErrorCallback('invalid symbol');
  463. } else {
  464. onSymbolResolvedCallback(that._symbolsInfo[symbolName]);
  465. }
  466. }, 0);
  467. };
  468. // ==================================================================================================================================================
  469. // ==================================================================================================================================================
  470. // ==================================================================================================================================================
  471. /*
  472. It's a symbol search component for ExternalDatafeed. This component can do symbol search only.
  473. This component strongly depends on SymbolsDataStorage and cannot work without it. Maybe, it would be
  474. better to merge it to SymbolsDataStorage.
  475. */
  476. Datafeeds.SymbolSearchComponent = function(datafeed) {
  477. this._datafeed = datafeed;
  478. };
  479. // searchArgument = { searchString, onResultReadyCallback}
  480. Datafeeds.SymbolSearchComponent.prototype.searchSymbols = function(searchArgument, maxSearchResults) {
  481. if (!this._datafeed._symbolsStorage) {
  482. throw new Error('Cannot use local symbol search when no groups information is available');
  483. }
  484. var symbolsStorage = this._datafeed._symbolsStorage;
  485. var results = []; // array of WeightedItem { item, weight }
  486. var queryIsEmpty = !searchArgument.searchString || searchArgument.searchString.length === 0;
  487. var searchStringUpperCase = searchArgument.searchString.toUpperCase();
  488. for (var i = 0; i < symbolsStorage._symbolsList.length; ++i) {
  489. var symbolName = symbolsStorage._symbolsList[i];
  490. var item = symbolsStorage._symbolsInfo[symbolName];
  491. if (searchArgument.type && searchArgument.type.length > 0 && item.type !== searchArgument.type) {
  492. continue;
  493. }
  494. if (searchArgument.exchange && searchArgument.exchange.length > 0 && item.exchange !== searchArgument.exchange) {
  495. continue;
  496. }
  497. var positionInName = item.name.toUpperCase().indexOf(searchStringUpperCase);
  498. var positionInDescription = item.description.toUpperCase().indexOf(searchStringUpperCase);
  499. if (queryIsEmpty || positionInName >= 0 || positionInDescription >= 0) {
  500. var found = false;
  501. for (var resultIndex = 0; resultIndex < results.length; resultIndex++) {
  502. if (results[resultIndex].item === item) {
  503. found = true;
  504. break;
  505. }
  506. }
  507. if (!found) {
  508. var weight = positionInName >= 0 ? positionInName : 8000 + positionInDescription;
  509. results.push({ item: item, weight: weight });
  510. }
  511. }
  512. }
  513. searchArgument.onResultReadyCallback(
  514. results
  515. .sort(function(weightedItem1, weightedItem2) {
  516. return weightedItem1.weight - weightedItem2.weight;
  517. })
  518. .map(function(weightedItem) {
  519. var item = weightedItem.item;
  520. return {
  521. symbol: item.name,
  522. full_name: item.full_name,
  523. description: item.description,
  524. exchange: item.exchange,
  525. params: [],
  526. type: item.type,
  527. ticker: item.name
  528. };
  529. })
  530. .slice(0, Math.min(results.length, maxSearchResults))
  531. );
  532. };
  533. // ==================================================================================================================================================
  534. // ==================================================================================================================================================
  535. // ==================================================================================================================================================
  536. /*
  537. This is a pulse updating components for ExternalDatafeed. They emulates realtime updates with periodic requests.
  538. */
  539. Datafeeds.DataPulseUpdater = function(datafeed, updateFrequency) {
  540. this._datafeed = datafeed;
  541. this._subscribers = {};
  542. this._requestsPending = 0;
  543. var that = this;
  544. var update = function() {
  545. if (that._requestsPending > 0) {
  546. return;
  547. }
  548. for (var listenerGUID in that._subscribers) {
  549. var subscriptionRecord = that._subscribers[listenerGUID];
  550. var resolution = subscriptionRecord.resolution;
  551. var datesRangeRight = parseInt((new Date().valueOf()) / 1000);
  552. // BEWARE: please note we really need 2 bars, not the only last one
  553. // see the explanation below. `10` is the `large enough` value to work around holidays
  554. var datesRangeLeft = datesRangeRight - that.periodLengthSeconds(resolution, 10);
  555. that._requestsPending++;
  556. (function(_subscriptionRecord) { // eslint-disable-line
  557. that._datafeed.getBars(_subscriptionRecord.symbolInfo, resolution, datesRangeLeft, datesRangeRight, function(bars) {
  558. that._requestsPending--;
  559. // means the subscription was cancelled while waiting for data
  560. if (!that._subscribers.hasOwnProperty(listenerGUID)) {
  561. return;
  562. }
  563. if (bars.length === 0) {
  564. return;
  565. }
  566. var lastBar = bars[bars.length - 1];
  567. if (!isNaN(_subscriptionRecord.lastBarTime) && lastBar.time < _subscriptionRecord.lastBarTime) {
  568. return;
  569. }
  570. var subscribers = _subscriptionRecord.listeners;
  571. // BEWARE: this one isn't working when first update comes and this update makes a new bar. In this case
  572. // _subscriptionRecord.lastBarTime = NaN
  573. var isNewBar = !isNaN(_subscriptionRecord.lastBarTime) && lastBar.time > _subscriptionRecord.lastBarTime;
  574. // 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
  575. // old bar's last 5 seconds trades will be lost). Thus, at fist we should broadcast old bar updates when it's ready.
  576. if (isNewBar) {
  577. if (bars.length < 2) {
  578. throw new Error('Not enough bars in history for proper pulse update. Need at least 2.');
  579. }
  580. var previousBar = bars[bars.length - 2];
  581. for (var i = 0; i < subscribers.length; ++i) {
  582. subscribers[i](previousBar);
  583. }
  584. }
  585. _subscriptionRecord.lastBarTime = lastBar.time;
  586. for (var i = 0; i < subscribers.length; ++i) {
  587. subscribers[i](lastBar);
  588. }
  589. },
  590. // on error
  591. function() {
  592. that._requestsPending--;
  593. });
  594. })(subscriptionRecord);
  595. }
  596. };
  597. if (typeof updateFrequency != 'undefined' && updateFrequency > 0) {
  598. setInterval(update, updateFrequency);
  599. }
  600. };
  601. Datafeeds.DataPulseUpdater.prototype.unsubscribeDataListener = function(listenerGUID) {
  602. this._datafeed._logMessage('Unsubscribing ' + listenerGUID);
  603. delete this._subscribers[listenerGUID];
  604. };
  605. Datafeeds.DataPulseUpdater.prototype.subscribeDataListener = function(symbolInfo, resolution, newDataCallback, listenerGUID) {
  606. this._datafeed._logMessage('Subscribing ' + listenerGUID);
  607. if (!this._subscribers.hasOwnProperty(listenerGUID)) {
  608. this._subscribers[listenerGUID] = {
  609. symbolInfo: symbolInfo,
  610. resolution: resolution,
  611. lastBarTime: NaN,
  612. listeners: []
  613. };
  614. }
  615. this._subscribers[listenerGUID].listeners.push(newDataCallback);
  616. };
  617. Datafeeds.DataPulseUpdater.prototype.periodLengthSeconds = function(resolution, requiredPeriodsCount) {
  618. var daysCount = 0;
  619. if (resolution === 'D') {
  620. daysCount = requiredPeriodsCount;
  621. } else if (resolution === 'M') {
  622. daysCount = 31 * requiredPeriodsCount;
  623. } else if (resolution === 'W') {
  624. daysCount = 7 * requiredPeriodsCount;
  625. } else {
  626. daysCount = requiredPeriodsCount * resolution / (24 * 60);
  627. }
  628. return daysCount * 24 * 60 * 60;
  629. };
  630. Datafeeds.QuotesPulseUpdater = function(datafeed) {
  631. this._datafeed = datafeed;
  632. this._subscribers = {};
  633. this._updateInterval = 60 * 1000;
  634. this._fastUpdateInterval = 10 * 1000;
  635. this._requestsPending = 0;
  636. var that = this;
  637. setInterval(function() {
  638. that._updateQuotes(function(subscriptionRecord) { return subscriptionRecord.symbols; });
  639. }, this._updateInterval);
  640. setInterval(function() {
  641. that._updateQuotes(function(subscriptionRecord) { return subscriptionRecord.fastSymbols.length > 0 ? subscriptionRecord.fastSymbols : subscriptionRecord.symbols; });
  642. }, this._fastUpdateInterval);
  643. };
  644. Datafeeds.QuotesPulseUpdater.prototype.subscribeDataListener = function(symbols, fastSymbols, newDataCallback, listenerGUID) {
  645. if (!this._subscribers.hasOwnProperty(listenerGUID)) {
  646. this._subscribers[listenerGUID] = {
  647. symbols: symbols,
  648. fastSymbols: fastSymbols,
  649. listeners: []
  650. };
  651. }
  652. this._subscribers[listenerGUID].listeners.push(newDataCallback);
  653. };
  654. Datafeeds.QuotesPulseUpdater.prototype.unsubscribeDataListener = function(listenerGUID) {
  655. delete this._subscribers[listenerGUID];
  656. };
  657. Datafeeds.QuotesPulseUpdater.prototype._updateQuotes = function(symbolsGetter) {
  658. if (this._requestsPending > 0) {
  659. return;
  660. }
  661. var that = this;
  662. for (var listenerGUID in this._subscribers) {
  663. this._requestsPending++;
  664. var subscriptionRecord = this._subscribers[listenerGUID];
  665. this._datafeed.getQuotes(symbolsGetter(subscriptionRecord),
  666. // onDataCallback
  667. (function(subscribers, guid) { // eslint-disable-line
  668. return function(data) {
  669. that._requestsPending--;
  670. // means the subscription was cancelled while waiting for data
  671. if (!that._subscribers.hasOwnProperty(guid)) {
  672. return;
  673. }
  674. for (var i = 0; i < subscribers.length; ++i) {
  675. subscribers[i](data);
  676. }
  677. };
  678. }(subscriptionRecord.listeners, listenerGUID)),
  679. // onErrorCallback
  680. function(error) {
  681. that._requestsPending--;
  682. });
  683. }
  684. };
  685. if (typeof module !== 'undefined' && module && module.exports) {
  686. module.exports = {
  687. UDFCompatibleDatafeed: Datafeeds.UDFCompatibleDatafeed,
  688. };
  689. }