You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This is a sample implementation of UDF-compatible datafeed wrapper for Quandl (historical data) and yahoo.finance (quotes).
Some algorithms may be incorrect because it's rather an UDF implementation sample
then a proper datafeed implementation.
*/
/* global require /
/ global console /
/ global exports /
/ global process */
"use strict";
var version = '2.0.2';
var https = require("https");
var http = require("http");
// this cache is intended to reduce number of requests to Quandl
setInterval(function () {
quandlCache = {};
console.warn(dateForLogs() + 'Quandl cache invalidated');
}, quandlCacheCleanupTime);
function dateForLogs() {
return (new Date()).toISOString() + ': ';
}
var defaultResponseHeader = {
"Content-Type": "text/plain",
'Access-Control-Allow-Origin': '*'
};
function sendJsonResponse(response, jsonData) {
response.writeHead(200, defaultResponseHeader);
response.write(JSON.stringify(jsonData));
response.end();
}
function dateToYMD(date) {
var obj = new Date(date);
var year = obj.getFullYear();
var month = obj.getMonth() + 1;
var day = obj.getDate();
return year + "-" + month + "-" + day;
}
var quandlKeys = process.env.QUANDL_API_KEY.split(','); // you should create a free account on quandl.com to get this key, you can set some keys concatenated with a comma
var invalidQuandlKeys = [];
function getValidQuandlKey() {
for (var i = 0; i < quandlKeys.length; i++) {
var key = quandlKeys[i];
if (invalidQuandlKeys.indexOf(key) === -1) {
return key;
}
}
return null;
}
function markQuandlKeyAsInvalid(key) {
if (invalidQuandlKeys.indexOf(key) !== -1) {
return;
}
function httpGet(datafeedHost, path, callback) {
var options = {
host: datafeedHost,
path: path
};
function onDataCallback(response) {
var result = '';
response.on('data', function (chunk) {
result += chunk;
});
response.on('end', function () {
if (response.statusCode !== 200) {
callback({ status: 'ERR_STATUS_CODE', errmsg: response.statusMessage || '' });
return;
}
callback({ status: 'ok', data: result });
});
}
var req = https.request(options, onDataCallback);
req.on('socket', function (socket) {
socket.setTimeout(5000);
socket.on('timeout', function () {
console.log(dateForLogs() + 'timeout');
req.abort();
});
});
req.on('error', function (e) {
callback({ status: 'ERR_SOCKET', errmsg: e.message || '' });
});
req.end();
}
function convertQuandlHistoryToUDFFormat(data) {
function parseDate(input) {
var parts = input.split('-');
return Date.UTC(parts[0], parts[1] - 1, parts[2]);
}
function columnIndices(columns) {
var indices = {};
for (var i = 0; i < columns.length; i++) {
indices[columns[i].name] = i;
}
return indices;
}
console.log(data);
var result = {
t: [],
c: [],
o: [],
h: [],
l: [],
v: [],
s: "ok"
};
try {
var json = JSON.parse(data);
var datatable = json.datatable;
var idx = columnIndices(datatable.columns);
datatable.data.forEach(function (row) {
result.t.push(parseDate(row[idx.date]) / 1000);
result.o.push(row[idx.open]);
result.h.push(row[idx.high]);
result.l.push(row[idx.low]);
result.c.push(row[idx.close]);
result.v.push(row[idx.volume]);
});
} catch (error) {
return null;
}
return result;
}
function MyConvertQuandlHistoryToUDFFormat(data) {
function parseDate(input) {
var parts = input.split('-');
return Date.UTC(parts[0], parts[1] - 1, parts[2]);
}
function columnIndices(columns) {
var indices = {};
for (var i = 0; i < columns.length; i++) {
indices[columns[i].name] = i;
}
return indices;
}
//console.log(data);
var result = {
t: [],
c: [],
o: [],
h: [],
l: [],
v: [],
s: "ok"
};
try {
var json = JSON.parse(data);
var datatable = json.dataset;
//var idx = columnIndices(datatable.column_names);
//console.log(idx);
datatable.data.forEach(function (row) {
result.t.push(parseDate(row[0]) / 1000);
result.o.push(row[1]);
result.h.push(row[2]);
result.l.push(row[3]);
result.c.push(row[4]);
result.v.push(row[5]);
});
} catch (error) {
return null;
}
return result;
RequestProcessor.prototype._sendMarks = function (response) {
var now = new Date();
now = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())) / 1000;
var day = 60 * 60 * 24;
var marks = {
id: [0, 1, 2, 3, 4, 5],
time: [now, now - day * 4, now - day * 7, now - day * 7, now - day * 15, now - day * 30],
color: ["red", "blue", "green", "red", "blue", "green"],
text: ["Today", "4 days back", "7 days back + Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", "7 days back once again", "15 days back", "30 days back"],
label: ["A", "B", "CORE", "D", "EURO", "F"],
labelFontColor: ["white", "white", "red", "#FFFFFF", "white", "#000"],
minSize: [14, 28, 7, 40, 7, 14]
};
response.writeHead(200, defaultResponseHeader);
response.write(JSON.stringify(marks));
response.end();
};
RequestProcessor.prototype._sendTime = function (response) {
var now = new Date();
response.writeHead(200, defaultResponseHeader);
response.write(Math.floor(now / 1000) + '');
response.end();
};
RequestProcessor.prototype._sendTimescaleMarks = function (response) {
var now = new Date();
now = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())) / 1000;
var day = 60 * 60 * 24;
var marks = [
{
id: "tsm1",
time: now,
color: "red",
label: "A",
tooltip: ""
},
{
id: "tsm2",
time: now - day * 4,
color: "blue",
label: "D",
tooltip: ["Dividends: $0.56", "Date: " + new Date((now - day * 4) * 1000).toDateString()]
},
{
id: "tsm3",
time: now - day * 7,
color: "green",
label: "D",
tooltip: ["Dividends: $3.46", "Date: " + new Date((now - day * 7) * 1000).toDateString()]
},
{
id: "tsm4",
time: now - day * 15,
color: "#999999",
label: "E",
tooltip: ["Earnings: $3.44", "Estimate: $3.60"]
},
{
id: "tsm7",
time: now - day * 30,
color: "red",
label: "E",
tooltip: ["Earnings: $5.40", "Estimate: $5.00"]
},
];
response.writeHead(200, defaultResponseHeader);
response.write(JSON.stringify(marks));
response.end();
};
RequestProcessor.prototype._sendSymbolSearchResults = function (query, type, exchange, maxRecords, response) {
if (!maxRecords) {
throw "wrong_query";
}
var result = this._symbolsDatabase.search(query, type, exchange, maxRecords);
response.writeHead(200, defaultResponseHeader);
response.write(JSON.stringify(result));
response.end();
};
RequestProcessor.prototype._prepareSymbolInfo = function (symbolName) {
var symbolInfo = this._symbolsDatabase.symbolInfo(symbolName);
`/*
This file is a node.js module.
*/
/* global require /
/ global console /
/ global exports /
/ global process */
"use strict";
var version = '2.0.2';
var https = require("https");
var http = require("http");
var quandlCache = {};
var quandlCacheCleanupTime = 3 * 60 * 60 * 1000; // 3 hours
var quandlKeysValidateTime = 15 * 60 * 1000; // 15 minutes
var yahooFailedStateCacheTime = 3 * 60 * 60 * 1000; // 3 hours;
var quandlMinimumDate = '1970-01-01';
// this cache is intended to reduce number of requests to Quandl
setInterval(function () {
quandlCache = {};
console.warn(dateForLogs() + 'Quandl cache invalidated');
}, quandlCacheCleanupTime);
function dateForLogs() {
return (new Date()).toISOString() + ': ';
}
var defaultResponseHeader = {
"Content-Type": "text/plain",
'Access-Control-Allow-Origin': '*'
};
function sendJsonResponse(response, jsonData) {
response.writeHead(200, defaultResponseHeader);
response.write(JSON.stringify(jsonData));
response.end();
}
function dateToYMD(date) {
var obj = new Date(date);
var year = obj.getFullYear();
var month = obj.getMonth() + 1;
var day = obj.getDate();
return year + "-" + month + "-" + day;
}
var quandlKeys = process.env.QUANDL_API_KEY.split(','); // you should create a free account on quandl.com to get this key, you can set some keys concatenated with a comma
var invalidQuandlKeys = [];
function getValidQuandlKey() {
for (var i = 0; i < quandlKeys.length; i++) {
var key = quandlKeys[i];
if (invalidQuandlKeys.indexOf(key) === -1) {
return key;
}
}
return null;
}
function markQuandlKeyAsInvalid(key) {
if (invalidQuandlKeys.indexOf(key) !== -1) {
return;
}
}
function sendError(error, response) {
response.writeHead(200, defaultResponseHeader);
response.write("{"s":"error","errmsg":"" + error + ""}");
response.end();
}
function httpGet(datafeedHost, path, callback) {
var options = {
host: datafeedHost,
path: path
};
}
function convertQuandlHistoryToUDFFormat(data) {
function parseDate(input) {
var parts = input.split('-');
return Date.UTC(parts[0], parts[1] - 1, parts[2]);
}
}
function MyConvertQuandlHistoryToUDFFormat(data) {
function parseDate(input) {
var parts = input.split('-');
return Date.UTC(parts[0], parts[1] - 1, parts[2]);
}
}
function convertYahooQuotesToUDFFormat(tickersMap, data) {
if (!data.query || !data.query.results) {
var errmsg = "ERROR: empty quotes response: " + JSON.stringify(data);
console.log(dateForLogs() + errmsg);
return {
s: "error",
errmsg: errmsg
};
}
}
function proxyRequest(controller, options, response) {
controller.request(options, function (res) {
var result = '';
}
function RequestProcessor(symbolsDatabase) {
this._symbolsDatabase = symbolsDatabase;
this._failedYahooTime = {};
}
function filterDataPeriod(data, fromSeconds, toSeconds) {
if (!data || !data.t) {
return data;
}
}
RequestProcessor.prototype._sendConfig = function (response) {
};
RequestProcessor.prototype._sendMarks = function (response) {
var now = new Date();
now = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())) / 1000;
var day = 60 * 60 * 24;
};
RequestProcessor.prototype._sendTime = function (response) {
var now = new Date();
response.writeHead(200, defaultResponseHeader);
response.write(Math.floor(now / 1000) + '');
response.end();
};
RequestProcessor.prototype._sendTimescaleMarks = function (response) {
var now = new Date();
now = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())) / 1000;
var day = 60 * 60 * 24;
};
RequestProcessor.prototype._sendSymbolSearchResults = function (query, type, exchange, maxRecords, response) {
if (!maxRecords) {
throw "wrong_query";
}
};
RequestProcessor.prototype._prepareSymbolInfo = function (symbolName) {
var symbolInfo = this._symbolsDatabase.symbolInfo(symbolName);
};
RequestProcessor.prototype._sendSymbolInfo = function (symbolName, response) {
var info = this._prepareSymbolInfo(symbolName);
};
RequestProcessor.prototype._sendSymbolHistory = function (symbol, startDateTimestamp, endDateTimestamp, resolution, response) {
function sendResult(content) {
var header = Object.assign({}, defaultResponseHeader);
header["Content-Length"] = content.length;
response.writeHead(200, header);
response.write(content, null, function () {
response.end();
});
}
};
RequestProcessor.prototype._quotesQuandlWorkaround = function (tickersMap) {
var from = quandlMinimumDate;
var to = dateToYMD(Date.now());
};
RequestProcessor.prototype._sendQuotes = function (tickersString, response) {
var tickersMap = {}; // maps YQL symbol to ticker
};
RequestProcessor.prototype._sendNews = function (symbol, response) {
var options = {
host: "feeds.finance.yahoo.com",
path: "/rss/2.0/headline?s=" + symbol + "®ion=US&lang=en-US"
};
};
RequestProcessor.prototype._sendFuturesmag = function (response) {
var options = {
host: "www.futuresmag.com",
path: "/rss/all"
};
};
RequestProcessor.prototype.processRequest = function (action, query, response) {
try {
if (action === "/config") {
this._sendConfig(response);
}
else if (action === "/symbols" && !!query["symbol"]) {
this._sendSymbolInfo(query["symbol"], response);
}
else if (action === "/search") {
this._sendSymbolSearchResults(query["query"], query["type"], query["exchange"], query["limit"], response);
}
else if (action === "/history") {
this._sendSymbolHistory(query["symbol"], query["from"], query["to"], query["resolution"].toLowerCase(), response);
}
else if (action === "/quotes") {
this._sendQuotes(query["symbols"], response);
}
else if (action === "/marks") {
this._sendMarks(response);
}
else if (action === "/time") {
this._sendTime(response);
}
else if (action === "/timescale_marks") {
this._sendTimescaleMarks(response);
}
else if (action === "/news") {
this._sendNews(query["symbol"], response);
}
else if (action === "/futuresmag") {
this._sendFuturesmag(response);
} else {
response.writeHead(200, defaultResponseHeader);
response.write('Datafeed version is ' + version +
'\nValid keys count is ' + String(quandlKeys.length - invalidQuandlKeys.length) +
'\nCurrent key is ' + (getValidQuandlKey() || '').slice(0, 3) +
(invalidQuandlKeys.length !== 0 ? '\nInvalid keys are ' + invalidQuandlKeys.reduce(function(prev, cur) { return prev + cur.slice(0, 3) + ','; }, '') : ''));
response.end();
}
}
catch (error) {
sendError(error, response);
console.error('Exception: ' + error);
}
};
exports.RequestProcessor = RequestProcessor;
`
I think i make all the charges work for NSE data from quandl, but i am getting nothing on TV graph
The text was updated successfully, but these errors were encountered: