language
stringclasses 6
values | original_string
stringlengths 25
887k
| text
stringlengths 25
887k
|
---|---|---|
JavaScript | function bestsignal(bestsignals, terminateAt, scores, signal_strategy, latest) {
const cost = getStrategyCost(signal_strategy, latest);
if (scores[signal_strategy])
return scores[signal_strategy].then(score => ({score, cost, revisited: true}));
logger.debug("bestsignal", latest.label || '\b', signal_strategy);
const regex = new RegExp('\\b' + latest.signal_variable + '\\b','g');
const token = signal_strategy.split(' ').find(token => regex.exec(token));
const sign = token && token.replace(regex, '');
const label = sign && latest.label ? sign + ' ' + latest.label : sign || latest.label;
const optimize_termination = latest.optimize_termination || terminateAt &&
moment.duration(Math.floor((terminateAt - Date.now())/1000)*1000).toISOString() || undefined;
const promise = bestsignals(_.defaults({
label: label,
solution_count: null,
optimize_termination: optimize_termination,
variables: _.defaults({
[latest.strategy_variable]: signal_strategy
}, latest.variables)
}, latest)).then(best => {
return merge({
variables:{
[latest.strategy_variable]: signal_strategy
},
strategy_variable: latest.strategy_variable,
cost: cost
}, best);
});
scores[signal_strategy] = promise.then(best => best.score);
return promise;
} | function bestsignal(bestsignals, terminateAt, scores, signal_strategy, latest) {
const cost = getStrategyCost(signal_strategy, latest);
if (scores[signal_strategy])
return scores[signal_strategy].then(score => ({score, cost, revisited: true}));
logger.debug("bestsignal", latest.label || '\b', signal_strategy);
const regex = new RegExp('\\b' + latest.signal_variable + '\\b','g');
const token = signal_strategy.split(' ').find(token => regex.exec(token));
const sign = token && token.replace(regex, '');
const label = sign && latest.label ? sign + ' ' + latest.label : sign || latest.label;
const optimize_termination = latest.optimize_termination || terminateAt &&
moment.duration(Math.floor((terminateAt - Date.now())/1000)*1000).toISOString() || undefined;
const promise = bestsignals(_.defaults({
label: label,
solution_count: null,
optimize_termination: optimize_termination,
variables: _.defaults({
[latest.strategy_variable]: signal_strategy
}, latest.variables)
}, latest)).then(best => {
return merge({
variables:{
[latest.strategy_variable]: signal_strategy
},
strategy_variable: latest.strategy_variable,
cost: cost
}, best);
});
scores[signal_strategy] = promise.then(best => best.score);
return promise;
} |
JavaScript | function countOperands(strategy_expr) {
return strategy_expr.split(' OR ').reduce((count, operand) => {
return count + operand.split(' AND ').length;
}, 0);
} | function countOperands(strategy_expr) {
return strategy_expr.split(' OR ').reduce((count, operand) => {
return count + operand.split(' AND ').length;
}, 0);
} |
JavaScript | function evaluate(bestsignals, scores, strategy, latest) {
if (!strategy) return Promise.resolve(null);
else if (scores[strategy]) return scores[strategy];
else return scores[strategy] = bestsignals(_.defaults({
solution_count: null,
signals: [],
signalset: [],
variables: _.defaults({
[latest.strategy_variable]: strategy
}, latest.variables)
}, latest)).then(best => best.score);
} | function evaluate(bestsignals, scores, strategy, latest) {
if (!strategy) return Promise.resolve(null);
else if (scores[strategy]) return scores[strategy];
else return scores[strategy] = bestsignals(_.defaults({
solution_count: null,
signals: [],
signalset: [],
variables: _.defaults({
[latest.strategy_variable]: strategy
}, latest.variables)
}, latest)).then(best => best.score);
} |
JavaScript | async function moreStrategies(prng, evaluate, parser, max_operands, latest) {
const strategy_var = latest.strategy_variable;
const strategy = await parser(latest.variables[strategy_var]);
const signal_var = latest.signal_variable;
if (!strategy.legs.length || signal_var == strategy.expr) { // initial signal
if (latest.follow_signals_only) return Promise.resolve([signal_var]);
else return Promise.resolve(invert(signal_var));
}
expect(latest).to.have.property('score');
expect(strategy.legs).to.have.lengthOf(1);
const leg = _.last(strategy.legs);
const comparisons = leg.comparisons;
const signal = leg.signal;
const isolations = leg.comparisons.map((cmp, j) => {
return spliceExpr(comparisons, j, 1).concat(signal.expr).join(' AND ');
});
return Promise.all(isolations.map(isolation => evaluate(isolation, latest)))
.then(scores => scores.map(score => latest.score - score))
.then(contributions => { // change comparator
const room = !latest.disjunctions_only && max_operands &&
max_operands > countOperands(strategy.expr);
const cmpIdx = chooseContribution(prng, latest.conjunction_cost, contributions, room ? 2 : 1);
return Promise.resolve(contributions[cmpIdx]).then(contrib => {
if (cmpIdx < comparisons.length)
logger.debug("Strategize", latest.label || '\b', "contrib",
comparisons[cmpIdx].expr, contrib);
if (cmpIdx > comparisons.length || !room && cmpIdx == comparisons.length) {
// replace reference signal
const needle = signal.variable || signal.expr;
const follow = createReplacer({[needle]: signal_var})(leg.expr);
if (latest.follow_signals_only) return [follow];
else return [
follow,
leg.expr.replace(new RegExp('-' + needle + '\\b','g'), signal_var)
.replace(new RegExp('\\b' + needle + '\\b','g'), '-' + signal_var)
];
} else { // add or replace comparison
return listComparators(latest).map(comparator => {
const expr = comparator(signal_var, signal.variable || signal.expr);
return spliceExpr(comparisons, cmpIdx, 1, expr).concat(signal.expr).join(' AND ');
});
}
}).then(strategies => {
if (max_operands && countOperands(strategies[0]) > max_operands) return [];
else return strategies;
}).then(strategies => {
if (cmpIdx < contributions.length && contributions[cmpIdx] < latest.conjunction_cost) {
const dropped = spliceExpr(comparisons, cmpIdx, 1).concat(signal.expr).join(' AND ');
return strategies.concat(dropped); // also try dropping the under performing comparison
}
return strategies;
});
});
} | async function moreStrategies(prng, evaluate, parser, max_operands, latest) {
const strategy_var = latest.strategy_variable;
const strategy = await parser(latest.variables[strategy_var]);
const signal_var = latest.signal_variable;
if (!strategy.legs.length || signal_var == strategy.expr) { // initial signal
if (latest.follow_signals_only) return Promise.resolve([signal_var]);
else return Promise.resolve(invert(signal_var));
}
expect(latest).to.have.property('score');
expect(strategy.legs).to.have.lengthOf(1);
const leg = _.last(strategy.legs);
const comparisons = leg.comparisons;
const signal = leg.signal;
const isolations = leg.comparisons.map((cmp, j) => {
return spliceExpr(comparisons, j, 1).concat(signal.expr).join(' AND ');
});
return Promise.all(isolations.map(isolation => evaluate(isolation, latest)))
.then(scores => scores.map(score => latest.score - score))
.then(contributions => { // change comparator
const room = !latest.disjunctions_only && max_operands &&
max_operands > countOperands(strategy.expr);
const cmpIdx = chooseContribution(prng, latest.conjunction_cost, contributions, room ? 2 : 1);
return Promise.resolve(contributions[cmpIdx]).then(contrib => {
if (cmpIdx < comparisons.length)
logger.debug("Strategize", latest.label || '\b', "contrib",
comparisons[cmpIdx].expr, contrib);
if (cmpIdx > comparisons.length || !room && cmpIdx == comparisons.length) {
// replace reference signal
const needle = signal.variable || signal.expr;
const follow = createReplacer({[needle]: signal_var})(leg.expr);
if (latest.follow_signals_only) return [follow];
else return [
follow,
leg.expr.replace(new RegExp('-' + needle + '\\b','g'), signal_var)
.replace(new RegExp('\\b' + needle + '\\b','g'), '-' + signal_var)
];
} else { // add or replace comparison
return listComparators(latest).map(comparator => {
const expr = comparator(signal_var, signal.variable || signal.expr);
return spliceExpr(comparisons, cmpIdx, 1, expr).concat(signal.expr).join(' AND ');
});
}
}).then(strategies => {
if (max_operands && countOperands(strategies[0]) > max_operands) return [];
else return strategies;
}).then(strategies => {
if (cmpIdx < contributions.length && contributions[cmpIdx] < latest.conjunction_cost) {
const dropped = spliceExpr(comparisons, cmpIdx, 1).concat(signal.expr).join(' AND ');
return strategies.concat(dropped); // also try dropping the under performing comparison
}
return strategies;
});
});
} |
JavaScript | function chooseContribution(prng, threshold, contributions, extra) {
const items = contributions.map((contrib, i) => ({
p: i,
contrib: contrib
}));
const byContrib = _.sortBy(items, 'contrib');
if (byContrib.length && byContrib[0].contrib < threshold) return byContrib[0].p;
const idx = choose(prng, byContrib.length, extra);
if (byContrib[idx]) return byContrib[idx].p;
else return idx;
} | function chooseContribution(prng, threshold, contributions, extra) {
const items = contributions.map((contrib, i) => ({
p: i,
contrib: contrib
}));
const byContrib = _.sortBy(items, 'contrib');
if (byContrib.length && byContrib[0].contrib < threshold) return byContrib[0].p;
const idx = choose(prng, byContrib.length, extra);
if (byContrib[idx]) return byContrib[idx].p;
else return idx;
} |
JavaScript | function choose(prng, max, extra) {
const t = 1.5;
if (max+extra < 1) return 0;
let weights = _.range(max).map(i => Math.pow(i + 1, -t));
if (extra) {
weights = weights.concat(_.range(extra).map(i => Math.pow(weights.length +2 +i, -t)));
}
let target = prng() * weights.reduce((a,b) => a + b);
for (let i=0; i<weights.length; i++) {
if (target < weights[i]) return i;
else target -= weights[i];
}
throw Error();
} | function choose(prng, max, extra) {
const t = 1.5;
if (max+extra < 1) return 0;
let weights = _.range(max).map(i => Math.pow(i + 1, -t));
if (extra) {
weights = weights.concat(_.range(extra).map(i => Math.pow(weights.length +2 +i, -t)));
}
let target = prng() * weights.reduce((a,b) => a + b);
for (let i=0; i<weights.length; i++) {
if (target < weights[i]) return i;
else target -= weights[i];
}
throw Error();
} |
JavaScript | function listComparators(options) {
const follow = [
_.extend((a,b)=>`${a}=${b}`, {operator: 'EQUALS'}),
_.extend((a,b)=>`${a}!=-${b}`, {operator: 'NOT_EQUALS'})
];
if (options && options.follow_signals_only) return follow;
const direct = [
_.extend((a,b)=>`${a}=-${b}`, {operator: 'EQUALS'}),
_.extend((a,b)=>`${a}=0`, {operator: 'EQUALS'}),
_.extend((a,b)=>`${a}!=${b}`, {operator: 'NOT_EQUALS'}),
_.extend((a,b)=>`${a}!=0`, {operator: 'NOT_EQUALS'})
];
if (options && !options.directional) return follow.concat(direct);
const relative = [
_.extend((a,b)=>`${a}<0`, {operator: 'LESS_THAN'}),
_.extend((a,b)=>`${a}>0`, {operator: 'GREATER_THAN'}),
_.extend((a,b)=>`${a}>=0`, {operator: 'NOT_LESS_THAN'}),
_.extend((a,b)=>`${a}<=0`, {operator: 'NOT_GREATER_THAN'})
];
return follow.concat(direct, relative);
} | function listComparators(options) {
const follow = [
_.extend((a,b)=>`${a}=${b}`, {operator: 'EQUALS'}),
_.extend((a,b)=>`${a}!=-${b}`, {operator: 'NOT_EQUALS'})
];
if (options && options.follow_signals_only) return follow;
const direct = [
_.extend((a,b)=>`${a}=-${b}`, {operator: 'EQUALS'}),
_.extend((a,b)=>`${a}=0`, {operator: 'EQUALS'}),
_.extend((a,b)=>`${a}!=${b}`, {operator: 'NOT_EQUALS'}),
_.extend((a,b)=>`${a}!=0`, {operator: 'NOT_EQUALS'})
];
if (options && !options.directional) return follow.concat(direct);
const relative = [
_.extend((a,b)=>`${a}<0`, {operator: 'LESS_THAN'}),
_.extend((a,b)=>`${a}>0`, {operator: 'GREATER_THAN'}),
_.extend((a,b)=>`${a}>=0`, {operator: 'NOT_LESS_THAN'}),
_.extend((a,b)=>`${a}<=0`, {operator: 'NOT_GREATER_THAN'})
];
return follow.concat(direct, relative);
} |
JavaScript | function spliceExpr(array, start, deleteCount, ...items) {
const exprs = array.map(item => item.expr);
exprs.splice.apply(exprs, _.rest(arguments));
return exprs;
} | function spliceExpr(array, start, deleteCount, ...items) {
const exprs = array.map(item => item.expr);
exprs.splice.apply(exprs, _.rest(arguments));
return exprs;
} |
JavaScript | async function combine(signals, options) {
const strategy_var = options.strategy_variable;
const best = signals[strategy_var];
if (!best.variables[strategy_var]) return null;
const variables = (await getReferences(best.variables, options))[strategy_var];
const used = _.intersection(variables, _.keys(signals));
const replacement = {};
const result = await used.reduce(async(promise, variable) => {
const combined = await promise;
const solution = signals[variable];
if (!solution || strategy_var == variable)
return combined; // not created here or leg variable
const formatted = await formatSolution(solution, merge(options, combined));
delete formatted.variables[formatted.strategy_variable];
replacement[variable] = formatted.solution_variable;
return merge(combined, _.omit(formatted, 'solution_variable', 'signal_variable'));
}, {});
const combined_strategy = await new Parser({substitutions:replacement}).parse(best.variables[strategy_var]);
return merge(result, {
score: best.score,
cost: best.cost,
variables: {
[strategy_var]: combined_strategy
},
strategy_variable: strategy_var
});
} | async function combine(signals, options) {
const strategy_var = options.strategy_variable;
const best = signals[strategy_var];
if (!best.variables[strategy_var]) return null;
const variables = (await getReferences(best.variables, options))[strategy_var];
const used = _.intersection(variables, _.keys(signals));
const replacement = {};
const result = await used.reduce(async(promise, variable) => {
const combined = await promise;
const solution = signals[variable];
if (!solution || strategy_var == variable)
return combined; // not created here or leg variable
const formatted = await formatSolution(solution, merge(options, combined));
delete formatted.variables[formatted.strategy_variable];
replacement[variable] = formatted.solution_variable;
return merge(combined, _.omit(formatted, 'solution_variable', 'signal_variable'));
}, {});
const combined_strategy = await new Parser({substitutions:replacement}).parse(best.variables[strategy_var]);
return merge(result, {
score: best.score,
cost: best.cost,
variables: {
[strategy_var]: combined_strategy
},
strategy_variable: strategy_var
});
} |
JavaScript | async function formatSolution(solution, options, suffix) {
const parser = createReplacer({});
const signal = solution.variables[solution.signal_variable];
const existing = _.keys(options.variables)
.filter(name => name.indexOf(signal) === 0)
.map(name => name.substring(signal.length));
const formatted = await existing.reduce(async(promise, id) => {
const already = await promise;
if (already) return already;
const formatted = await formatSolutionWithId(solution, options, id);
if (signalConflicts(parser, formatted, options)) return null;
else return formatted;
}, null);
if (formatted) return formatted; // reuse existing signal
for (let id_num=10; id_num < 100; id_num++) {
const id = (suffix || '') + id_num.toString(36).toUpperCase();
if (!~existing.indexOf(id)) {
const formatted = await formatSolutionWithId(solution, options, id);
if (!signalConflicts(parser, formatted, options)) return formatted;
}
}
throw Error(`Could not determine reasonable signal name for ${signal}`);
} | async function formatSolution(solution, options, suffix) {
const parser = createReplacer({});
const signal = solution.variables[solution.signal_variable];
const existing = _.keys(options.variables)
.filter(name => name.indexOf(signal) === 0)
.map(name => name.substring(signal.length));
const formatted = await existing.reduce(async(promise, id) => {
const already = await promise;
if (already) return already;
const formatted = await formatSolutionWithId(solution, options, id);
if (signalConflicts(parser, formatted, options)) return null;
else return formatted;
}, null);
if (formatted) return formatted; // reuse existing signal
for (let id_num=10; id_num < 100; id_num++) {
const id = (suffix || '') + id_num.toString(36).toUpperCase();
if (!~existing.indexOf(id)) {
const formatted = await formatSolutionWithId(solution, options, id);
if (!signalConflicts(parser, formatted, options)) return formatted;
}
}
throw Error(`Could not determine reasonable signal name for ${signal}`);
} |
JavaScript | function signalConflicts(parser, s1, s2) {
const params = _.intersection(_.keys(s1.parameters), _.keys(s2.parameters));
const vars = _.intersection(_.keys(s1.variables), _.keys(s2.variables));
const varnames = _.without(vars, s1.strategy_variable);
const cmp = (a, b) => name => a[name] != b[name] && parser(a[name]) != parser(b[name]);
return params.find(cmp(s1.parameters, s2.parameters)) ||
varnames.find(cmp(s1.variables, s2.variables));
} | function signalConflicts(parser, s1, s2) {
const params = _.intersection(_.keys(s1.parameters), _.keys(s2.parameters));
const vars = _.intersection(_.keys(s1.variables), _.keys(s2.variables));
const varnames = _.without(vars, s1.strategy_variable);
const cmp = (a, b) => name => a[name] != b[name] && parser(a[name]) != parser(b[name]);
return params.find(cmp(s1.parameters, s2.parameters)) ||
varnames.find(cmp(s1.variables, s2.variables));
} |
JavaScript | async function formatSolutionWithId(solution, options, id) {
const signal = solution.signal_variable;
const fixed = _.extend({}, options.parameters, options.variables);
const values = _.extend({}, solution.variables, solution.parameters);
const conflicts = _.reduce(values, (conflicts, value, name) => {
if (fixed[name] != value && _.has(fixed, name))
conflicts.push(name);
return conflicts;
}, _.keys(solution.parameters));
const references = await getReferences(values, options);
const local = [signal].concat(references[signal]);
const overlap = references[signal].filter(name => ~conflicts.indexOf(name) ||
_.intersection(conflicts, references[name]).length);
const replacement = _.object(overlap, overlap.map(name => name + id));
const replacer = createReplacer(replacement);
const rename = (object, value, name) => _.extend(object, {[replacement[name] || name]: value});
const parser = new Parser({substitutions:{
[signal]: solution.variables[signal]
}});
const strategy = await parser.parse(solution.variables[solution.strategy_variable]);
const eval_validity = replacer(_.compact(_.flatten([solution.eval_validity])));
const variables = _.omit(_.pick(solution.variables, local), signal, options.leg_variable)
return _.omit({
score: solution.score,
cost: solution.cost,
signal_variable: signal,
solution_variable: replacement[solution.variables[signal]] || solution.variables[signal],
strategy_variable: solution.strategy_variable,
variables: replacer(_.extend(variables, {
[solution.strategy_variable]: strategy
})),
parameters: _.reduce(_.pick(solution.parameters, local), rename, {}),
pad_leading: !options.pad_leading && solution.pad_leading ||
solution.pad_leading > options.pad_leading ? solution.pad_leading : undefined,
}, value => value == null);
} | async function formatSolutionWithId(solution, options, id) {
const signal = solution.signal_variable;
const fixed = _.extend({}, options.parameters, options.variables);
const values = _.extend({}, solution.variables, solution.parameters);
const conflicts = _.reduce(values, (conflicts, value, name) => {
if (fixed[name] != value && _.has(fixed, name))
conflicts.push(name);
return conflicts;
}, _.keys(solution.parameters));
const references = await getReferences(values, options);
const local = [signal].concat(references[signal]);
const overlap = references[signal].filter(name => ~conflicts.indexOf(name) ||
_.intersection(conflicts, references[name]).length);
const replacement = _.object(overlap, overlap.map(name => name + id));
const replacer = createReplacer(replacement);
const rename = (object, value, name) => _.extend(object, {[replacement[name] || name]: value});
const parser = new Parser({substitutions:{
[signal]: solution.variables[signal]
}});
const strategy = await parser.parse(solution.variables[solution.strategy_variable]);
const eval_validity = replacer(_.compact(_.flatten([solution.eval_validity])));
const variables = _.omit(_.pick(solution.variables, local), signal, options.leg_variable)
return _.omit({
score: solution.score,
cost: solution.cost,
signal_variable: signal,
solution_variable: replacement[solution.variables[signal]] || solution.variables[signal],
strategy_variable: solution.strategy_variable,
variables: replacer(_.extend(variables, {
[solution.strategy_variable]: strategy
})),
parameters: _.reduce(_.pick(solution.parameters, local), rename, {}),
pad_leading: !options.pad_leading && solution.pad_leading ||
solution.pad_leading > options.pad_leading ? solution.pad_leading : undefined,
}, value => value == null);
} |
JavaScript | function createReplacer(replacement) {
const parser = new Parser();
const map = name => replacement[name] || name;
const replacer = new Parser({
variable(name) {
return map(name);
},
expression(expr, name, args) {
if (!rolling.has(name)) return name + '(' + args.join(',') + ')';
const margs = args.map(arg => {
if (!_.isString(arg) || '"' != arg.charAt(0)) return arg;
return JSON.stringify(parser.parse(replacer.parse(JSON.parse(arg))));
});
return name + '(' + margs.join(',') + ')';
}
});
return function(expr) {
const parsed = parser.parse(replacer.parse(expr));
if (_.isArray(expr) || _.isString(expr)) return parsed;
return _.object(_.keys(parsed).map(map), _.values(parsed));
};
} | function createReplacer(replacement) {
const parser = new Parser();
const map = name => replacement[name] || name;
const replacer = new Parser({
variable(name) {
return map(name);
},
expression(expr, name, args) {
if (!rolling.has(name)) return name + '(' + args.join(',') + ')';
const margs = args.map(arg => {
if (!_.isString(arg) || '"' != arg.charAt(0)) return arg;
return JSON.stringify(parser.parse(replacer.parse(JSON.parse(arg))));
});
return name + '(' + margs.join(',') + ')';
}
});
return function(expr) {
const parsed = parser.parse(replacer.parse(expr));
if (_.isArray(expr) || _.isString(expr)) return parsed;
return _.object(_.keys(parsed).map(map), _.values(parsed));
};
} |
JavaScript | async function chooseVariable(prefix, options) {
const references = await getReferences(merge(options.columns, options.variables), options);
const portfolioCols = _.flatten(_.flatten([options.portfolio]).map(portfolio => _.keys(portfolio.columns)));
const variables = _.uniq(_.keys(references).concat(_.flatten(_.values(references)), portfolioCols));
if (!~variables.indexOf(prefix)) return prefix;
let i = 0;
while (~variables.indexOf(prefix + i)) i++;
return prefix + i;
} | async function chooseVariable(prefix, options) {
const references = await getReferences(merge(options.columns, options.variables), options);
const portfolioCols = _.flatten(_.flatten([options.portfolio]).map(portfolio => _.keys(portfolio.columns)));
const variables = _.uniq(_.keys(references).concat(_.flatten(_.values(references)), portfolioCols));
if (!~variables.indexOf(prefix)) return prefix;
let i = 0;
while (~variables.indexOf(prefix + i)) i++;
return prefix + i;
} |
JavaScript | function fetchOptionsFactory(fetch, offline, read_only) {
const dir = config('cache_dir') || path.resolve(config('prefix'), config('default_cache_dir'));
let markets = config('markets');
const memoizeFirstLookup = _.memoize((symbol, market) => {
return readInfo(dir, symbol, market, offline).catch(async(err) => {
if (offline) return guessSecurityOptions(markets, symbol, market, err);
else return fetch({
interval: 'contract',
symbol: symbol,
market: market
}).then(matches => _.first(matches))
.then(security => {
if (!security) throw Error("Unknown symbol: " + (market ? symbol + '.' + market : market));
else if (security.symbol == symbol && read_only) return security;
else if (security.symbol == symbol) return saveInfo(dir, symbol, market, security);
else throw Error("Unknown symbol: " + symbol + ", but " + security.symbol + " is known");
});
});
}, (symbol, market) => {
return market ? symbol + ' ' + market : symbol;
});
return function(options) {
expect(options).to.have.property('symbol');
const symbol = options.symbol;
const market = options.market;
return memoizeFirstLookup(symbol, market).catch(e => {
logger.trace("Lookup failed, resetting: ", e);
markets = config('markets');
memoizeFirstLookup.cache = {};
return memoizeFirstLookup(symbol, market);
});
};
} | function fetchOptionsFactory(fetch, offline, read_only) {
const dir = config('cache_dir') || path.resolve(config('prefix'), config('default_cache_dir'));
let markets = config('markets');
const memoizeFirstLookup = _.memoize((symbol, market) => {
return readInfo(dir, symbol, market, offline).catch(async(err) => {
if (offline) return guessSecurityOptions(markets, symbol, market, err);
else return fetch({
interval: 'contract',
symbol: symbol,
market: market
}).then(matches => _.first(matches))
.then(security => {
if (!security) throw Error("Unknown symbol: " + (market ? symbol + '.' + market : market));
else if (security.symbol == symbol && read_only) return security;
else if (security.symbol == symbol) return saveInfo(dir, symbol, market, security);
else throw Error("Unknown symbol: " + symbol + ", but " + security.symbol + " is known");
});
});
}, (symbol, market) => {
return market ? symbol + ' ' + market : symbol;
});
return function(options) {
expect(options).to.have.property('symbol');
const symbol = options.symbol;
const market = options.market;
return memoizeFirstLookup(symbol, market).catch(e => {
logger.trace("Lookup failed, resetting: ", e);
markets = config('markets');
memoizeFirstLookup.cache = {};
return memoizeFirstLookup(symbol, market);
});
};
} |
JavaScript | parseCriteriaList(exprs) {
if (_.isEmpty(exprs)) return [];
if (!_.isArray(exprs) && !_.isString(exprs)) expect(exprs).to.be.a('string');
const list = _.isArray(exprs) ?
_.flatten(exprs.map(val=>parseExpressions(val, subs)), true) :
parseExpressions(exprs, subs);
let i=0;
while (i<list.length) {
const expr = list[i];
if (_.first(expr) != 'AND') i++;
else list.splice(i, 1, expr[1], expr[2]);
}
const parsed = list.map(expr => {
return invokeHandler(_handlers, expr);
});
if (parsed.some(isPromise)) return Promise.all(parsed);
else return parsed;
} | parseCriteriaList(exprs) {
if (_.isEmpty(exprs)) return [];
if (!_.isArray(exprs) && !_.isString(exprs)) expect(exprs).to.be.a('string');
const list = _.isArray(exprs) ?
_.flatten(exprs.map(val=>parseExpressions(val, subs)), true) :
parseExpressions(exprs, subs);
let i=0;
while (i<list.length) {
const expr = list[i];
if (_.first(expr) != 'AND') i++;
else list.splice(i, 1, expr[1], expr[2]);
}
const parsed = list.map(expr => {
return invokeHandler(_handlers, expr);
});
if (parsed.some(isPromise)) return Promise.all(parsed);
else return parsed;
} |
JavaScript | function parseVariables(exprs) {
if (!exprs) return {};
const variables = _.mapObject(_.pick(exprs, (val,key)=>val!=key), val => parseExpression(val));
const handlers = {
constant(value) {
return [];
},
variable(name) {
if (variables[name]) return [name];
else return [];
},
expression(expr, name, args) {
return _.uniq(_.flatten(args, true));
}
};
const references = _.mapObject(variables, (expr, name) => {
const reference = invokeHandler(handlers, expr);
if (!_.contains(reference, name)) return reference;
else throw Error("Expression cannot reference itself: " + name);
});
while (_.reduce(references, (more, reference, name) => {
if (!reference.length) return more;
const second = _.uniq(_.flatten(reference.map(ref => references[ref]), true));
if (_.contains(second, name)) throw Error("Circular Reference " + name);
variables[name] = inline(variables[name], variables);
references[name] = second;
return more || second.length;
}, false));
return variables;
} | function parseVariables(exprs) {
if (!exprs) return {};
const variables = _.mapObject(_.pick(exprs, (val,key)=>val!=key), val => parseExpression(val));
const handlers = {
constant(value) {
return [];
},
variable(name) {
if (variables[name]) return [name];
else return [];
},
expression(expr, name, args) {
return _.uniq(_.flatten(args, true));
}
};
const references = _.mapObject(variables, (expr, name) => {
const reference = invokeHandler(handlers, expr);
if (!_.contains(reference, name)) return reference;
else throw Error("Expression cannot reference itself: " + name);
});
while (_.reduce(references, (more, reference, name) => {
if (!reference.length) return more;
const second = _.uniq(_.flatten(reference.map(ref => references[ref]), true));
if (_.contains(second, name)) throw Error("Circular Reference " + name);
variables[name] = inline(variables[name], variables);
references[name] = second;
return more || second.length;
}, false));
return variables;
} |
JavaScript | function mkdirp(dirname) {
return new Promise((present, absent) => {
fs.access(dirname, fs.F_OK, err => err ? absent(err) : present(dirname));
}).catch(async absent => {
if (absent.code != 'ENOENT') throw absent;
const parent = path.dirname(dirname);
if (parent != dirname) await mkdirp(parent);
return util.promisify(fs.mkdir)(dirname)
.catch(err => {
if (err.code == 'EEXIST') return dirname;
else throw err;
});
});
} | function mkdirp(dirname) {
return new Promise((present, absent) => {
fs.access(dirname, fs.F_OK, err => err ? absent(err) : present(dirname));
}).catch(async absent => {
if (absent.code != 'ENOENT') throw absent;
const parent = path.dirname(dirname);
if (parent != dirname) await mkdirp(parent);
return util.promisify(fs.mkdir)(dirname)
.catch(err => {
if (err.code == 'EEXIST') return dirname;
else throw err;
});
});
} |
JavaScript | async function help(optimize) {
const help = _.first(await optimize({info: 'help'}));
return [{
name: 'bestsignals',
usage: 'bestsignals(options)',
description: "Searches possible signal parameters to find the highest score",
properties: ['signal_variable', 'variables'].concat(help.properties),
options: _.extend({}, help.options, {
signals: {
usage: '[<variable name>,..]',
description: "Array of variable names that should be tested as signals"
},
signal_variable: {
usage: '<variable name>',
description: "The variable name to use when testing various signals"
},
signalset: {
usage: '[<signalset>,..]',
description: "Array of signal sets that include array of signals (variable names), hash of variables, default parameters, and possible parameter_values"
}
})
}];
} | async function help(optimize) {
const help = _.first(await optimize({info: 'help'}));
return [{
name: 'bestsignals',
usage: 'bestsignals(options)',
description: "Searches possible signal parameters to find the highest score",
properties: ['signal_variable', 'variables'].concat(help.properties),
options: _.extend({}, help.options, {
signals: {
usage: '[<variable name>,..]',
description: "Array of variable names that should be tested as signals"
},
signal_variable: {
usage: '<variable name>',
description: "The variable name to use when testing various signals"
},
signalset: {
usage: '[<signalset>,..]',
description: "Array of signal sets that include array of signals (variable names), hash of variables, default parameters, and possible parameter_values"
}
})
}];
} |
JavaScript | async function bestsignals(optimize, options) {
const signals = _.flatten(await Promise.all(getSignalSets(options).map(async(options, set) => {
const signals = _.isString(options.signals) ? options.signals.split(',') :
_.isEmpty(options.signals) ? ['signal'] :options.signals;
expect(options).to.have.property('parameter_values');
expect(options).to.have.property('signals');
const all_signals = _.flatten(await Promise.all(signals.map(signal => {
return bestsignal(optimize, signal, options);
})));
const count = options.solution_count || 1;
const rev_signals = _.sortBy(all_signals, 'score').slice(-count).reverse();
if (!options.signalset) return rev_signals;
const signalset = _.isArray(options.signalset) ?
[options.signalset[set]] : options.signalset;
return rev_signals.map(signal => merge(options, signal, {signalset}));
})));
const count = options.solution_count || 1;
const solutions = _.sortBy(signals, 'score').slice(-count).reverse();
if (options.solution_count)
return Promise.all(solutions.map(solution => formatSignal(solution, options)));
else return formatSignal(_.first(solutions), options);
} | async function bestsignals(optimize, options) {
const signals = _.flatten(await Promise.all(getSignalSets(options).map(async(options, set) => {
const signals = _.isString(options.signals) ? options.signals.split(',') :
_.isEmpty(options.signals) ? ['signal'] :options.signals;
expect(options).to.have.property('parameter_values');
expect(options).to.have.property('signals');
const all_signals = _.flatten(await Promise.all(signals.map(signal => {
return bestsignal(optimize, signal, options);
})));
const count = options.solution_count || 1;
const rev_signals = _.sortBy(all_signals, 'score').slice(-count).reverse();
if (!options.signalset) return rev_signals;
const signalset = _.isArray(options.signalset) ?
[options.signalset[set]] : options.signalset;
return rev_signals.map(signal => merge(options, signal, {signalset}));
})));
const count = options.solution_count || 1;
const solutions = _.sortBy(signals, 'score').slice(-count).reverse();
if (options.solution_count)
return Promise.all(solutions.map(solution => formatSignal(solution, options)));
else return formatSignal(_.first(solutions), options);
} |
JavaScript | async function bestsignal(optimize, signal, options) {
const pnames = await getParameterNames(signal, options);
const pvalues = pnames.map(name => options.parameter_values[name]);
const signal_variable = options.signal_variable || 'signal';
const signal_vars = signal_variable != signal ? {[signal_variable]: signal} : {};
const solutions = await optimize(_.defaults({
label: signal + (options.label ? ' ' + options.label : ''),
solution_count: options.solution_count || 1,
variables: _.defaults(signal_vars, options.variables),
parameter_values: _.object(pnames, pvalues)
}, options));
return solutions.map((solution, i) => _.defaults({
score: solution.score,
signal_variable: signal_variable,
variables: _.defaults({[signal_variable]: signal}, options.variables),
parameters: solution.parameters,
parameter_values: _.object(pnames, pvalues)
}, options));
} | async function bestsignal(optimize, signal, options) {
const pnames = await getParameterNames(signal, options);
const pvalues = pnames.map(name => options.parameter_values[name]);
const signal_variable = options.signal_variable || 'signal';
const signal_vars = signal_variable != signal ? {[signal_variable]: signal} : {};
const solutions = await optimize(_.defaults({
label: signal + (options.label ? ' ' + options.label : ''),
solution_count: options.solution_count || 1,
variables: _.defaults(signal_vars, options.variables),
parameter_values: _.object(pnames, pvalues)
}, options));
return solutions.map((solution, i) => _.defaults({
score: solution.score,
signal_variable: signal_variable,
variables: _.defaults({[signal_variable]: signal}, options.variables),
parameters: solution.parameters,
parameter_values: _.object(pnames, pvalues)
}, options));
} |
JavaScript | async function formatSignal(signalset, options) {
const signal = signalset.signal_variable;
const vars = _.extend({}, signalset.variables, signalset.parameters);
const references = await getReferences(vars, options);
const local = [signal].concat(references[signal]);
return _.omit({
score: signalset.score,
signal_variable: signalset.signal_variable,
variables: _.pick(signalset.variables, local),
parameters: _.pick(signalset.parameters, local),
pad_leading: signalset.pad_leading ? signalset.pad_leading : undefined
}, value => value == null);
} | async function formatSignal(signalset, options) {
const signal = signalset.signal_variable;
const vars = _.extend({}, signalset.variables, signalset.parameters);
const references = await getReferences(vars, options);
const local = [signal].concat(references[signal]);
return _.omit({
score: signalset.score,
signal_variable: signalset.signal_variable,
variables: _.pick(signalset.variables, local),
parameters: _.pick(signalset.parameters, local),
pad_leading: signalset.pad_leading ? signalset.pad_leading : undefined
}, value => value == null);
} |
JavaScript | function readHash(opts) {
const data = JSON.stringify(opts);
const hash = crypto.createHash('sha256');
return hash.update(data).digest('base64');
} | function readHash(opts) {
const data = JSON.stringify(opts);
const hash = crypto.createHash('sha256');
return hash.update(data).digest('base64');
} |
JavaScript | function sweep(cache, initialCount, poolSize) {
const started = Date.now();
const access = cache.hit + cache.miss - cache.access;
const added = cache.added - cache.removed;
return reduceEntries(cache, (count, entry) => {
if (entry.marked)
return deleteEntry(cache.baseDir, entry)
.catch(err => logger.debug("Could not remove", entry, err))
.then(() => count);
else
return writeEntryMetadata(cache, _.extend(entry, {age: entry.age+1}))
.then(() => count + 1)
.catch(err => logger.debug("Could not update", entry, err) || count);
}, 0).then(count => {
const removed = initialCount - count + cache.added - cache.removed;
if (removed > 0) {
const elapse = moment.duration(Date.now() - started);
if (elapse.asSeconds() > 1)
logger.log("Sweep removed", removed, "of", removed+count, "in", elapse.asSeconds()+'s');
}
_.extend(cache, {
removed: initialCount - count + cache.added,
access: cache.hit + cache.miss
});
if (poolSize && count > poolSize)
return mark(cache, count, poolSize);
if (!poolSize && access && added > removed)
return mark(cache, count, Math.min(access, Math.max(initialCount, added)));
});
} | function sweep(cache, initialCount, poolSize) {
const started = Date.now();
const access = cache.hit + cache.miss - cache.access;
const added = cache.added - cache.removed;
return reduceEntries(cache, (count, entry) => {
if (entry.marked)
return deleteEntry(cache.baseDir, entry)
.catch(err => logger.debug("Could not remove", entry, err))
.then(() => count);
else
return writeEntryMetadata(cache, _.extend(entry, {age: entry.age+1}))
.then(() => count + 1)
.catch(err => logger.debug("Could not update", entry, err) || count);
}, 0).then(count => {
const removed = initialCount - count + cache.added - cache.removed;
if (removed > 0) {
const elapse = moment.duration(Date.now() - started);
if (elapse.asSeconds() > 1)
logger.log("Sweep removed", removed, "of", removed+count, "in", elapse.asSeconds()+'s');
}
_.extend(cache, {
removed: initialCount - count + cache.added,
access: cache.hit + cache.miss
});
if (poolSize && count > poolSize)
return mark(cache, count, poolSize);
if (!poolSize && access && added > removed)
return mark(cache, count, Math.min(access, Math.max(initialCount, added)));
});
} |
JavaScript | function mark(cache, count, poolSize) {
const size = count - poolSize;
if (size <= 0) return Promise.resolve();
return reduceEntries(cache, (oldest, entry) => {
if (oldest.length < size || entry.age > _.first(oldest).age) {
oldest.splice(_.sortedIndex(oldest, entry, 'age'), 0, entry);
}
if (oldest.length > size) {
oldest.shift();
}
return oldest;
}, []).then(oldest => Promise.all(oldest.map(entry => {
return writeEntryMetadata(cache, _.extend(entry, {marked: true}));
})));
} | function mark(cache, count, poolSize) {
const size = count - poolSize;
if (size <= 0) return Promise.resolve();
return reduceEntries(cache, (oldest, entry) => {
if (oldest.length < size || entry.age > _.first(oldest).age) {
oldest.splice(_.sortedIndex(oldest, entry, 'age'), 0, entry);
}
if (oldest.length > size) {
oldest.shift();
}
return oldest;
}, []).then(oldest => Promise.all(oldest.map(entry => {
return writeEntryMetadata(cache, _.extend(entry, {marked: true}));
})));
} |
JavaScript | function reduceEntries(cache, cb, initial) {
return lock(cache, () => flock(cache, () => new Promise(cb => {
fs.readdir(cache.baseDir, (err, files) => cb(err ? [] : files));
}).then(dirs => dirs.map(dir => path.resolve(cache.baseDir, dir)))
.then(dirs => dirs.reduce((memo, dir) => memo.then(memo => new Promise(cb => {
fs.readdir(dir, (err, files) => cb(err ? [] : files));
}).then(files => files.filter(isMetadata))
.then(files => files.map(file => path.resolve(dir, file)))
.then(files => files.reduce((memo, file) => memo.then(memo => {
return readEntryMetadata(file).then(entry => {
if (entry) return cb(memo, entry);
else return deleteEntryFile(file).then(() => memo);
});
}), Promise.resolve(memo)))), Promise.resolve(initial)))));
} | function reduceEntries(cache, cb, initial) {
return lock(cache, () => flock(cache, () => new Promise(cb => {
fs.readdir(cache.baseDir, (err, files) => cb(err ? [] : files));
}).then(dirs => dirs.map(dir => path.resolve(cache.baseDir, dir)))
.then(dirs => dirs.reduce((memo, dir) => memo.then(memo => new Promise(cb => {
fs.readdir(dir, (err, files) => cb(err ? [] : files));
}).then(files => files.filter(isMetadata))
.then(files => files.map(file => path.resolve(dir, file)))
.then(files => files.reduce((memo, file) => memo.then(memo => {
return readEntryMetadata(file).then(entry => {
if (entry) return cb(memo, entry);
else return deleteEntryFile(file).then(() => memo);
});
}), Promise.resolve(memo)))), Promise.resolve(initial)))));
} |
JavaScript | function flock(cache, cb) {
const lock_file = path.resolve(cache.baseDir, ".~lock.pid");
const cleanup = () => deleteFile(cache.baseDir, lock_file);
return awriter.mkdirp(cache.baseDir).then(() => aquireLock(cache, lock_file))
.then(() => Promise.resolve(cb())
.then(result => cleanup().then(() => result),
error => cleanup().then(() => {
throw error;
})));
} | function flock(cache, cb) {
const lock_file = path.resolve(cache.baseDir, ".~lock.pid");
const cleanup = () => deleteFile(cache.baseDir, lock_file);
return awriter.mkdirp(cache.baseDir).then(() => aquireLock(cache, lock_file))
.then(() => Promise.resolve(cb())
.then(result => cleanup().then(() => result),
error => cleanup().then(() => {
throw error;
})));
} |
JavaScript | function aquireLock(cache, lock_file) {
return attemptLock(lock_file).catch(err => new Promise((locked, error) => {
if (cache.closed) return error(Error(`Process ${process.pid} could not aquire lock ${lock_file}`));
logger.log(err.message);
let watcher;
const cleanup = () => {
if (watcher) watcher.close();
cache.removeListener('close', onclose);
};
const onclose = () => {
cleanup();
error(Error(`Process ${process.pid} could not aquire lock in time ${lock_file}`));
};
cache.on('close', onclose);
watcher = fs.watch(lock_file, {persistent:false}, () => attemptLock(lock_file).then(() => {
cleanup();
locked();
}, err => logger.log(err.message))).on('error', err =>{
cleanup();
error(err);
});
})).catch(err => {
if (cache.closed) throw err;
logger.debug("Could not watch file", lock_file, err);
// watcher could not be created (file deleted?), try again
return aquireLock(cache, lock_file);
});
} | function aquireLock(cache, lock_file) {
return attemptLock(lock_file).catch(err => new Promise((locked, error) => {
if (cache.closed) return error(Error(`Process ${process.pid} could not aquire lock ${lock_file}`));
logger.log(err.message);
let watcher;
const cleanup = () => {
if (watcher) watcher.close();
cache.removeListener('close', onclose);
};
const onclose = () => {
cleanup();
error(Error(`Process ${process.pid} could not aquire lock in time ${lock_file}`));
};
cache.on('close', onclose);
watcher = fs.watch(lock_file, {persistent:false}, () => attemptLock(lock_file).then(() => {
cleanup();
locked();
}, err => logger.log(err.message))).on('error', err =>{
cleanup();
error(err);
});
})).catch(err => {
if (cache.closed) throw err;
logger.debug("Could not watch file", lock_file, err);
// watcher could not be created (file deleted?), try again
return aquireLock(cache, lock_file);
});
} |
JavaScript | function attemptLock(lock_file) {
return new Promise((locked, notlocked) => {
fs.writeFile(lock_file, process.pid, {flag:'wx'}, err => err ? notlocked(err) : locked());
}).catch(werr => new Promise((ready, error) => {
logger.trace("Could not aquire lock", werr);
fs.readFile(lock_file, 'utf8', (err, data) => err ? error(err) : ready(data));
}).then(pid => {
if (pid) process.kill(pid, 0);
return pid;
}).then(pid => {
if (!pid) throw Error(`Process ${process.pid} could not create lock ${lock_file}`);
// the process with the lock_file is still running
throw Error(`Process ${process.pid} is waiting for ${pid} to finish sweeping`);
}, err => new Promise(ready => {
fs.unlink(lock_file, ready);
}).then(() => attemptLock(lock_file), err => {
const msg = `Process ${process.pid} is trying to lock ${lock_file}`;
logger.debug(msg, err);
throw Error(msg);
})));
} | function attemptLock(lock_file) {
return new Promise((locked, notlocked) => {
fs.writeFile(lock_file, process.pid, {flag:'wx'}, err => err ? notlocked(err) : locked());
}).catch(werr => new Promise((ready, error) => {
logger.trace("Could not aquire lock", werr);
fs.readFile(lock_file, 'utf8', (err, data) => err ? error(err) : ready(data));
}).then(pid => {
if (pid) process.kill(pid, 0);
return pid;
}).then(pid => {
if (!pid) throw Error(`Process ${process.pid} could not create lock ${lock_file}`);
// the process with the lock_file is still running
throw Error(`Process ${process.pid} is waiting for ${pid} to finish sweeping`);
}, err => new Promise(ready => {
fs.unlink(lock_file, ready);
}).then(() => attemptLock(lock_file), err => {
const msg = `Process ${process.pid} is trying to lock ${lock_file}`;
logger.debug(msg, err);
throw Error(msg);
})));
} |
JavaScript | function createCacheEntry(cache, hash, fn, options, cb) {
expect(hash).to.be.a('string');
const miss = {
hash: hash,
age: 0,
marked: false,
version: major_version,
label: options.label,
promise: new Promise(cb => cb(fn(options))).then(result => {
const opts = _.omit(options, _.isUndefined);
return writePendingEntryResult(cache, miss, opts, result);
}).then(result => {
removePendingEntry(cache, miss);
cache.added++;
return cb(result);
}, err => {
removePendingEntry(cache, miss);
throw err;
})
};
const array = (cache.pending[hash] || []);
array.unshift(miss);
cache.pending[hash] = array;
return miss.promise;
} | function createCacheEntry(cache, hash, fn, options, cb) {
expect(hash).to.be.a('string');
const miss = {
hash: hash,
age: 0,
marked: false,
version: major_version,
label: options.label,
promise: new Promise(cb => cb(fn(options))).then(result => {
const opts = _.omit(options, _.isUndefined);
return writePendingEntryResult(cache, miss, opts, result);
}).then(result => {
removePendingEntry(cache, miss);
cache.added++;
return cb(result);
}, err => {
removePendingEntry(cache, miss);
throw err;
})
};
const array = (cache.pending[hash] || []);
array.unshift(miss);
cache.pending[hash] = array;
return miss.promise;
} |
JavaScript | function removePendingEntry(cache, entry) {
const array = cache.pending[entry.hash];
const idx = array.indexOf(entry);
if (idx < 0) throw Error(`Pending entry is missing: ${JSON.stringify(entry)}`);
if (array.length == 1) delete cache.pending[entry.hash];
else array.splice(idx, 1);
} | function removePendingEntry(cache, entry) {
const array = cache.pending[entry.hash];
const idx = array.indexOf(entry);
if (idx < 0) throw Error(`Pending entry is missing: ${JSON.stringify(entry)}`);
if (array.length == 1) delete cache.pending[entry.hash];
else array.splice(idx, 1);
} |
JavaScript | function readEntryMetadata(file) {
return new Promise((ready, error) => {
fs.readFile(file, 'utf8', (err, data) => err ? error(err) : ready(data));
}).then(data => JSON.parse(data))
.catch(err => logger.debug("Could not read", file, err));
} | function readEntryMetadata(file) {
return new Promise((ready, error) => {
fs.readFile(file, 'utf8', (err, data) => err ? error(err) : ready(data));
}).then(data => JSON.parse(data))
.catch(err => logger.debug("Could not read", file, err));
} |
JavaScript | function readEntryOptions(baseDir, entry) {
const file = path.resolve(getDir(baseDir, entry.hash), entry.options);
return new Promise((ready, error) => {
fs.readFile(file, (err, data) => err ? error(err) : ready(data));
}).then(JSON.parse.bind(JSON));
} | function readEntryOptions(baseDir, entry) {
const file = path.resolve(getDir(baseDir, entry.hash), entry.options);
return new Promise((ready, error) => {
fs.readFile(file, (err, data) => err ? error(err) : ready(data));
}).then(JSON.parse.bind(JSON));
} |
JavaScript | function readEntryResult(baseDir, entry) {
const file = path.resolve(getDir(baseDir, entry.hash), entry.result);
if (entry.type == 'csv') {
return new Promise((ready, error) => {
const objects = [];
csv.parseStream(fs.createReadStream(file).on('error', error), {headers : true, ignoreEmpty: true})
.on('error', error)
.on('data', function(data) {
try {
objects.push(_.mapObject(data, value => _.isFinite(value) ? +value : value));
} catch (e) {
this.emit('error', e);
}
})
.on('end', () => ready(objects));
});
} else if (entry.type == 'json') {
return new Promise((ready, error) => {
fs.readFile(file, (err, data) => err ? error(err) : ready(data));
}).then(JSON.parse.bind(JSON));
} else {
throw Error(`Unknown cache entry type: ${JSON.stringify(entry)}`);
}
} | function readEntryResult(baseDir, entry) {
const file = path.resolve(getDir(baseDir, entry.hash), entry.result);
if (entry.type == 'csv') {
return new Promise((ready, error) => {
const objects = [];
csv.parseStream(fs.createReadStream(file).on('error', error), {headers : true, ignoreEmpty: true})
.on('error', error)
.on('data', function(data) {
try {
objects.push(_.mapObject(data, value => _.isFinite(value) ? +value : value));
} catch (e) {
this.emit('error', e);
}
})
.on('end', () => ready(objects));
});
} else if (entry.type == 'json') {
return new Promise((ready, error) => {
fs.readFile(file, (err, data) => err ? error(err) : ready(data));
}).then(JSON.parse.bind(JSON));
} else {
throw Error(`Unknown cache entry type: ${JSON.stringify(entry)}`);
}
} |
JavaScript | function writeEntryMetadata(cache, entry) {
const dir = getDir(cache.baseDir, entry.hash);
const file = path.resolve(dir, entry.metadata);
return writeObject(cache, file, entry);
} | function writeEntryMetadata(cache, entry) {
const dir = getDir(cache.baseDir, entry.hash);
const file = path.resolve(dir, entry.metadata);
return writeObject(cache, file, entry);
} |
JavaScript | function deleteEntry(baseDir, entry) {
if (!entry.metadata) return Promise.resolve(); // already deleted
const dir = getDir(baseDir, entry.hash);
return Promise.all([
deleteFile(dir, entry.metadata),
deleteFile(dir, entry.options),
deleteFile(dir, entry.result)
]).then(() => new Promise((ready, error) => {
fs.readdir(dir, (err, files) => err ? error(err) : ready(files));
})).then(files => files.length || new Promise((ready, error) => {
fs.rmdir(dir, err => err ? error(err) : ready());
})).then(() => {
entry.marked = true;
entry.file = null;
entry.metadata = null;
return entry;
});
} | function deleteEntry(baseDir, entry) {
if (!entry.metadata) return Promise.resolve(); // already deleted
const dir = getDir(baseDir, entry.hash);
return Promise.all([
deleteFile(dir, entry.metadata),
deleteFile(dir, entry.options),
deleteFile(dir, entry.result)
]).then(() => new Promise((ready, error) => {
fs.readdir(dir, (err, files) => err ? error(err) : ready(files));
})).then(files => files.length || new Promise((ready, error) => {
fs.rmdir(dir, err => err ? error(err) : ready());
})).then(() => {
entry.marked = true;
entry.file = null;
entry.metadata = null;
return entry;
});
} |
JavaScript | function deleteEntryFile(file) {
const prefix = path.basename(file, 'entry.json');
return new Promise((ready, error) => {
const dir = path.dirname(file);
fs.readdir(dir, (err, files) => err ? error(err) : ready(files));
}).then(files => Promise.all(files.map(file => {
if (file.indexOf(prefix) === 0) return deleteFile(dir, file)
.catch(err => logger.debug("Could not delete corupt file", file));
})));
} | function deleteEntryFile(file) {
const prefix = path.basename(file, 'entry.json');
return new Promise((ready, error) => {
const dir = path.dirname(file);
fs.readdir(dir, (err, files) => err ? error(err) : ready(files));
}).then(files => Promise.all(files.map(file => {
if (file.indexOf(prefix) === 0) return deleteFile(dir, file)
.catch(err => logger.debug("Could not delete corupt file", file));
})));
} |
JavaScript | function deleteFile(dir, filename) {
return new Promise((ready, error) => {
const file = path.resolve(dir, filename);
fs.unlink(file, err => err ? error(err) : ready());
});
} | function deleteFile(dir, filename) {
return new Promise((ready, error) => {
const file = path.resolve(dir, filename);
fs.unlink(file, err => err ? error(err) : ready());
});
} |
JavaScript | function helpSettings() {
return [{
name: 'broker',
usage: 'broker(settings)',
description: "Information needed to identify the broker account",
options: {
simulation: {
usage: '<string>',
description: "The stored simulation instance to use"
}
}
}];
} | function helpSettings() {
return [{
name: 'broker',
usage: 'broker(settings)',
description: "Information needed to identify the broker account",
options: {
simulation: {
usage: '<string>',
description: "The stored simulation instance to use"
}
}
}];
} |
JavaScript | function helpOptions() {
return Promise.resolve([{
name: 'balances',
usage: 'broker(options)',
description: "List a summary of current account balances",
properties: [
'asof', 'currency', 'rate', 'net', 'settled'
],
options: {
action: {
usage: '<string>',
values: ['balances']
},
asof: {
usage: '<dateTime>',
description: "The date and time of the balances to return"
},
begin: {
usage: '<dateTime>',
description: "Include historic balances since given dateTime, but before given asof"
}
}
}, {
name: 'positions',
usage: 'broker(options)',
description: "List a summary of recent trades and their effect on the account position",
properties: [
'asof', 'action', 'quant', 'position', 'traded_at', 'traded_price', 'price',
'sales', 'purchases', 'dividend', 'commission', 'mtm', 'value',
'symbol', 'market', 'currency', 'security_type', 'multiplier'
],
options: {
action: {
usage: '<string>',
values: ['positions']
},
asof: {
usage: '<dateTime>',
description: "The date and time of the positions to return"
},
begin: {
usage: '<dateTime>',
description: "Include historic positions since given dateTime, but before given asof"
}
}
}, {
name: 'orders',
usage: 'broker(options)',
description: "List a summary of open orders",
properties: [
'posted_at', 'asof', 'action', 'quant', 'order_type', 'limit', 'stop', 'offset', 'traded_price', 'tif', 'status',
'order_ref', 'attach_ref', 'symbol', 'market', 'security_type', 'currency', 'multiplier',
'condition'
],
options: {
action: {
usage: '<string>',
values: ['orders']
},
asof: {
usage: '<dateTime>',
description: "The date and time of workings orders to return"
},
begin: {
usage: '<dateTime>',
description: "Include historic orders since given dateTime, but before given asof"
}
}
}, {
name: 'transfer',
usage: 'broker(options)',
description: "Add the quant to the current balance",
properties: [
'asof', 'action', 'quant', 'currency'
],
options: {
action: {
usage: '<string>',
values: ['deposit', 'withdraw']
},
asof: {
usage: '<dateTime>',
description: "The date and time to advance the clock to before transfering funds"
}
}
}, {
name: 'reset',
usage: 'broker(options)',
description: "Resets the store, earasing all the history",
properties: [],
options: {
action: {
usage: '<string>',
values: ['reset']
}
}
}, {
name: 'submit',
usage: 'broker(options)',
description: "Transmit order for trading",
properties: [
'posted_at', 'asof', 'action', 'quant', 'order_type', 'limit', 'stop', 'offset', 'tif', 'status',
'order_ref', 'attach_ref', 'symbol', 'market', 'security_type', 'currency', 'multiplier',
'condition'
],
options: {
action: {
usage: '<string>',
values: ['BUY', 'SELL', 'OCA', 'cancel']
},
asof: {
usage: '<dateTime>',
description: "The date and time to advance the clock to before submitting the order"
},
quant: {
usage: '<positive-integer>',
description: "The number of shares or contracts to buy or sell"
},
order_type: {
usage: '<order-type>',
values: ['MKT', 'MIT', 'MOO', 'MOC', 'LMT', 'LOO', 'LOC', 'STP']
},
limit: {
usage: '<limit-price>',
descirption: "The limit price for orders of type LMT"
},
stop: {
usage: '<aux-price>',
description: "Stop limit price for STP orders"
},
offset: {
usage: '<price-offset>',
description: "Pegged and snap order offset"
},
condition: {},
tif: {
usage: '<time-in-forced>',
values: ['GTC', 'DAY', 'IOC']
},
order_ref: {
usage: '<string>',
description: "The order identifier that is unique among working orders"
},
attach_ref: {
usage: '<string>',
description: "The order_ref of the parent order that must be filled before this order or a common identifier for orders in the same one-cancels-all (OCA) group."
},
attached: {
usage: '[...orders]',
description: "Submit attached parent/child orders together or OCA group of orders"
},
symbol: {
usage: '<string>',
description: "The symbol of the contract to be traded, omit for OCA and bag orders"
},
market: {
usage: '<string>',
description: "The market of the contract (might also be the name of the exchange)"
},
security_type: {
values: ['STK', 'FUT', 'OPT']
},
currency: {
usage: '<string>',
values: ['EUR', 'GBP', 'AUD', 'NZD', 'USD', 'CAD', 'CHF', 'JPY']
},
multiplier: {
usage: '<number>',
description: "The value of a single unit of change in price"
}
}
}]);
} | function helpOptions() {
return Promise.resolve([{
name: 'balances',
usage: 'broker(options)',
description: "List a summary of current account balances",
properties: [
'asof', 'currency', 'rate', 'net', 'settled'
],
options: {
action: {
usage: '<string>',
values: ['balances']
},
asof: {
usage: '<dateTime>',
description: "The date and time of the balances to return"
},
begin: {
usage: '<dateTime>',
description: "Include historic balances since given dateTime, but before given asof"
}
}
}, {
name: 'positions',
usage: 'broker(options)',
description: "List a summary of recent trades and their effect on the account position",
properties: [
'asof', 'action', 'quant', 'position', 'traded_at', 'traded_price', 'price',
'sales', 'purchases', 'dividend', 'commission', 'mtm', 'value',
'symbol', 'market', 'currency', 'security_type', 'multiplier'
],
options: {
action: {
usage: '<string>',
values: ['positions']
},
asof: {
usage: '<dateTime>',
description: "The date and time of the positions to return"
},
begin: {
usage: '<dateTime>',
description: "Include historic positions since given dateTime, but before given asof"
}
}
}, {
name: 'orders',
usage: 'broker(options)',
description: "List a summary of open orders",
properties: [
'posted_at', 'asof', 'action', 'quant', 'order_type', 'limit', 'stop', 'offset', 'traded_price', 'tif', 'status',
'order_ref', 'attach_ref', 'symbol', 'market', 'security_type', 'currency', 'multiplier',
'condition'
],
options: {
action: {
usage: '<string>',
values: ['orders']
},
asof: {
usage: '<dateTime>',
description: "The date and time of workings orders to return"
},
begin: {
usage: '<dateTime>',
description: "Include historic orders since given dateTime, but before given asof"
}
}
}, {
name: 'transfer',
usage: 'broker(options)',
description: "Add the quant to the current balance",
properties: [
'asof', 'action', 'quant', 'currency'
],
options: {
action: {
usage: '<string>',
values: ['deposit', 'withdraw']
},
asof: {
usage: '<dateTime>',
description: "The date and time to advance the clock to before transfering funds"
}
}
}, {
name: 'reset',
usage: 'broker(options)',
description: "Resets the store, earasing all the history",
properties: [],
options: {
action: {
usage: '<string>',
values: ['reset']
}
}
}, {
name: 'submit',
usage: 'broker(options)',
description: "Transmit order for trading",
properties: [
'posted_at', 'asof', 'action', 'quant', 'order_type', 'limit', 'stop', 'offset', 'tif', 'status',
'order_ref', 'attach_ref', 'symbol', 'market', 'security_type', 'currency', 'multiplier',
'condition'
],
options: {
action: {
usage: '<string>',
values: ['BUY', 'SELL', 'OCA', 'cancel']
},
asof: {
usage: '<dateTime>',
description: "The date and time to advance the clock to before submitting the order"
},
quant: {
usage: '<positive-integer>',
description: "The number of shares or contracts to buy or sell"
},
order_type: {
usage: '<order-type>',
values: ['MKT', 'MIT', 'MOO', 'MOC', 'LMT', 'LOO', 'LOC', 'STP']
},
limit: {
usage: '<limit-price>',
descirption: "The limit price for orders of type LMT"
},
stop: {
usage: '<aux-price>',
description: "Stop limit price for STP orders"
},
offset: {
usage: '<price-offset>',
description: "Pegged and snap order offset"
},
condition: {},
tif: {
usage: '<time-in-forced>',
values: ['GTC', 'DAY', 'IOC']
},
order_ref: {
usage: '<string>',
description: "The order identifier that is unique among working orders"
},
attach_ref: {
usage: '<string>',
description: "The order_ref of the parent order that must be filled before this order or a common identifier for orders in the same one-cancels-all (OCA) group."
},
attached: {
usage: '[...orders]',
description: "Submit attached parent/child orders together or OCA group of orders"
},
symbol: {
usage: '<string>',
description: "The symbol of the contract to be traded, omit for OCA and bag orders"
},
market: {
usage: '<string>',
description: "The market of the contract (might also be the name of the exchange)"
},
security_type: {
values: ['STK', 'FUT', 'OPT']
},
currency: {
usage: '<string>',
values: ['EUR', 'GBP', 'AUD', 'NZD', 'USD', 'CAD', 'CHF', 'JPY']
},
multiplier: {
usage: '<number>',
description: "The value of a single unit of change in price"
}
}
}]);
} |
JavaScript | function helpInfo(broker, collect) {
return Promise.all([collect, broker]).then(_.flatten)
.then(list => list.reduce((help, delegate) => {
return _.extend(help, {options: _.extend({}, delegate.options, help.options)});
}, {
name: 'replicate',
usage: 'replicate(options)',
description: "Changes workers orders to align with orders in result",
properties: ['action', 'quant', 'order_type', 'limit', 'stop', 'tif', 'symbol', 'market', 'currency', 'security_type', 'multiplier', 'order_ref', 'attach_ref'],
options: {
markets: {
usage: '[<market>]',
description: "Array of markets of positions that should be closed if no desired position exists"
},
currency: {
usage: '<currency>',
description: "The currency used in parameters, such as 'initial_deposit'"
},
quant_threshold: {
usage: '<integer>',
description: "Minimum quantity of shares/contracts that must change to generate an adjustment order"
},
quant_threshold_percent: {
usage: '<decimal>',
description: "Minimum quantity, relative to current position, that must change to generate an adjustment order"
},
default_order_type: {
usage: '<order_type>',
description: "Default order type to close unexpected positions, defaults to MKT"
},
default_multiplier: {
usage: '<number>',
description: "Default value multiplier defaults to 1"
},
minTick: {
usage: '<decimal>',
description: "The default minimun increment passed to broker"
},
input_orders: {
usage: '[{orders}...]',
descirption: "History of orders to use instead of strategy"
},
working_duration: {
usage: '<duration>,..',
description: "Offset of now to begin by these comma separated durations or to values"
},
close_unknown: {
usage: 'true',
description: "Close unknown positions in known markets"
},
dry_run: {
usage: 'true',
description: "If working orders should not be changed, only reported"
},
force: {
usage: 'true',
description: "If live positions, that have been changed more recently, should also be adjusted"
},
working_orders_only: {
usage: 'true',
description: "Don't try to align positions sizes, only submit working orders"
},
exclude_working_orders: {
usage: 'true',
description: "Only update positions sizes, don't submit/update working orders"
},
ignore_errors: {
usage: 'true',
description: "Return the orders even if some failed to submit or validate"
}
}
})).then(help => [help]);
} | function helpInfo(broker, collect) {
return Promise.all([collect, broker]).then(_.flatten)
.then(list => list.reduce((help, delegate) => {
return _.extend(help, {options: _.extend({}, delegate.options, help.options)});
}, {
name: 'replicate',
usage: 'replicate(options)',
description: "Changes workers orders to align with orders in result",
properties: ['action', 'quant', 'order_type', 'limit', 'stop', 'tif', 'symbol', 'market', 'currency', 'security_type', 'multiplier', 'order_ref', 'attach_ref'],
options: {
markets: {
usage: '[<market>]',
description: "Array of markets of positions that should be closed if no desired position exists"
},
currency: {
usage: '<currency>',
description: "The currency used in parameters, such as 'initial_deposit'"
},
quant_threshold: {
usage: '<integer>',
description: "Minimum quantity of shares/contracts that must change to generate an adjustment order"
},
quant_threshold_percent: {
usage: '<decimal>',
description: "Minimum quantity, relative to current position, that must change to generate an adjustment order"
},
default_order_type: {
usage: '<order_type>',
description: "Default order type to close unexpected positions, defaults to MKT"
},
default_multiplier: {
usage: '<number>',
description: "Default value multiplier defaults to 1"
},
minTick: {
usage: '<decimal>',
description: "The default minimun increment passed to broker"
},
input_orders: {
usage: '[{orders}...]',
descirption: "History of orders to use instead of strategy"
},
working_duration: {
usage: '<duration>,..',
description: "Offset of now to begin by these comma separated durations or to values"
},
close_unknown: {
usage: 'true',
description: "Close unknown positions in known markets"
},
dry_run: {
usage: 'true',
description: "If working orders should not be changed, only reported"
},
force: {
usage: 'true',
description: "If live positions, that have been changed more recently, should also be adjusted"
},
working_orders_only: {
usage: 'true',
description: "Don't try to align positions sizes, only submit working orders"
},
exclude_working_orders: {
usage: 'true',
description: "Only update positions sizes, don't submit/update working orders"
},
ignore_errors: {
usage: 'true',
description: "Return the orders even if some failed to submit or validate"
}
}
})).then(help => [help]);
} |
JavaScript | function wrapBroker(broker, brokerHelp, settings) {
if (!brokerHelp.some(info => ~(((info.options||{}).action||{}).values||[]).indexOf('watch')))
return broker; // broker does not support order watching
const timeout = settings.timeout || 1000;
return _.extendOwn(async(options) => {
if (options.action != 'BUY' && options.action != 'SELL')
return broker(options);
const orders = await broker(options);
if (!orders.some(ord => ord.status == 'pending')) return orders;
else return Promise.all(orders.map(ord => {
if (ord.status != 'pending' || !ord.order_ref) return ord;
else return broker({..._.omit(options, 'quant'), ..._.omit(ord, 'quant'), action: 'watch', timeout});
})).then(_.flatten);
}, broker);
} | function wrapBroker(broker, brokerHelp, settings) {
if (!brokerHelp.some(info => ~(((info.options||{}).action||{}).values||[]).indexOf('watch')))
return broker; // broker does not support order watching
const timeout = settings.timeout || 1000;
return _.extendOwn(async(options) => {
if (options.action != 'BUY' && options.action != 'SELL')
return broker(options);
const orders = await broker(options);
if (!orders.some(ord => ord.status == 'pending')) return orders;
else return Promise.all(orders.map(ord => {
if (ord.status != 'pending' || !ord.order_ref) return ord;
else return broker({..._.omit(options, 'quant'), ..._.omit(ord, 'quant'), action: 'watch', timeout});
})).then(_.flatten);
}, broker);
} |
JavaScript | async function replicate(broker, collect, lookup, options) {
const check = interrupt();
const begin = options.begin || options.working_duration && formatDate(moment.defaultFormat, {
duration: options.working_duration,
negative_duration: true,
now: options.now
}) || options.now;
const desired = await getDesiredPositions(broker, collect, lookup, begin, options);
const des_working = _.reduce(desired, (refs, pos) => Object.assign(refs, pos.working, pos.realized.working||{}), {});
const [broker_balances, broker_positions, broker_orders] = await Promise.all([
broker({action: 'balances', now: options.now}),
broker({action: 'positions', now: options.now}),
broker({action: 'orders', now: options.now})
]);
const actual = getActualPositions(broker_positions, broker_orders, des_working, begin);
logger.debug("replicate actual", ...Object.keys(actual));
const portfolio = _.uniq(Object.keys(desired).concat(getPortfolio(options.markets, options))).sort();
const margin_acct = !broker_balances.every(bal => bal.margin == null);
_.forEach(actual, (w, contract) => {
if (!desired[contract] && +w.position && !~portfolio.indexOf(contract) &&
(!options.markets || ~options.markets.indexOf(w.market)) &&
(w.currency == options.currency || margin_acct)) {
logger.warn("Unknown position", options.label || '', w.position, w.symbol, w.market);
if (options.close_unknown) {
portfolio.push(contract);
desired[contract] = {
position:0, asof: begin,
..._.pick(w,
'symbol', 'market', 'currency', 'security_type', 'multiplier', 'minTick'
),
working: {},
realized: {}
};
}
}
});
logger.trace("replicate portfolio", ...portfolio);
const replicateContract = replicateContracts(desired, begin, options);
const order_changes = portfolio.reduce((order_changes, contract) => {
const [, symbol, market] = contract.match(/^(.+)\W(\w+)$/);
return order_changes.concat(replicateContract(actual[`${symbol}.${market}`] || {symbol, market}));
}, []);
await check();
logger.trace("replicate", options.label || '', "submit orders", ...order_changes);
const updated_orders = updateComboOrders(broker_orders, actual, replicateContract, order_changes, options);
const attached_orders = attachOrders(broker_orders, updated_orders, options);
const pending_orders = combineOrders(broker_orders, attached_orders, options);
return submitOrders(broker, pending_orders, options);
} | async function replicate(broker, collect, lookup, options) {
const check = interrupt();
const begin = options.begin || options.working_duration && formatDate(moment.defaultFormat, {
duration: options.working_duration,
negative_duration: true,
now: options.now
}) || options.now;
const desired = await getDesiredPositions(broker, collect, lookup, begin, options);
const des_working = _.reduce(desired, (refs, pos) => Object.assign(refs, pos.working, pos.realized.working||{}), {});
const [broker_balances, broker_positions, broker_orders] = await Promise.all([
broker({action: 'balances', now: options.now}),
broker({action: 'positions', now: options.now}),
broker({action: 'orders', now: options.now})
]);
const actual = getActualPositions(broker_positions, broker_orders, des_working, begin);
logger.debug("replicate actual", ...Object.keys(actual));
const portfolio = _.uniq(Object.keys(desired).concat(getPortfolio(options.markets, options))).sort();
const margin_acct = !broker_balances.every(bal => bal.margin == null);
_.forEach(actual, (w, contract) => {
if (!desired[contract] && +w.position && !~portfolio.indexOf(contract) &&
(!options.markets || ~options.markets.indexOf(w.market)) &&
(w.currency == options.currency || margin_acct)) {
logger.warn("Unknown position", options.label || '', w.position, w.symbol, w.market);
if (options.close_unknown) {
portfolio.push(contract);
desired[contract] = {
position:0, asof: begin,
..._.pick(w,
'symbol', 'market', 'currency', 'security_type', 'multiplier', 'minTick'
),
working: {},
realized: {}
};
}
}
});
logger.trace("replicate portfolio", ...portfolio);
const replicateContract = replicateContracts(desired, begin, options);
const order_changes = portfolio.reduce((order_changes, contract) => {
const [, symbol, market] = contract.match(/^(.+)\W(\w+)$/);
return order_changes.concat(replicateContract(actual[`${symbol}.${market}`] || {symbol, market}));
}, []);
await check();
logger.trace("replicate", options.label || '', "submit orders", ...order_changes);
const updated_orders = updateComboOrders(broker_orders, actual, replicateContract, order_changes, options);
const attached_orders = attachOrders(broker_orders, updated_orders, options);
const pending_orders = combineOrders(broker_orders, attached_orders, options);
return submitOrders(broker, pending_orders, options);
} |
JavaScript | function updateActual(desired, actual, options) {
const quant_threshold = getQuantThreshold(actual, options);
const desired_adjustment = desired.position - actual.position >= quant_threshold ? {
action: 'BUY',
quant: (desired.position - actual.position).toString(),
...(((desired.adjustment||{action:'n/a'}).action||'BUY') == 'BUY' ? {
...desired.adjustment,
action: 'BUY'
} : {
order_type: options.default_order_type || 'MKT', tif: 'DAY',
..._.pick(desired, 'symbol', 'market', 'currency', 'security_type', 'multiplier', 'minTick')
})
} : actual.position - desired.position >= quant_threshold ? {
action: 'SELL',
quant: (actual.position - desired.position).toString(),
...(((desired.adjustment||{action:'n/a'}).action||'SELL') == 'SELL' ? {
...desired.adjustment,
action: 'SELL'
} : {
order_type: options.default_order_type || 'MKT', tif: 'DAY',
..._.pick(desired, 'symbol', 'market', 'currency', 'security_type', 'multiplier', 'minTick')
})
} : null;
const adjustments = orderReplacements(actual.adjustment, desired_adjustment, 0, options)
.filter(ord => ord.action == 'cancel' || !options.working_orders_only);
const adjusting_order = !adjustments.length ? actual.adjustment :
_.first(adjustments.filter(ord => ord.action != 'cancel'));
const adjust_position = !adjusting_order ? 0 :
adjusting_order.action == 'BUY' ? +adjusting_order.quant :
adjusting_order.action == 'SELL' ? -adjusting_order.quant : 0;
const target_position = actual.position + + adjust_position;
const pos_offset = target_position - desired.position;
const stoplosses = orderReplacements(actual.stoploss, desired.stoploss, pos_offset, options);
const working_refs = _.union(Object.keys(desired.working), Object.keys(actual.working));
const working = working_refs.reduce((orders, ref) => {
return orders.concat(orderReplacements(actual.working[ref], desired.working[ref], pos_offset, options));
}, stoplosses);
const cancelled = adjustments.concat(working).filter(ord => ord.action == 'cancel');
const pending = working.filter(ord => ord.action != 'cancel');
const adjustment_order = _.first(adjustments.filter(ord => ord.action != 'cancel'));
const realized_offset = actual.position - desired.realized.position;
const transition_stoploss = adjustment_order && desired.realized.stoploss ?
orderReplacements(actual.stoploss, desired.realized.stoploss, realized_offset, options) : [];
const transition_refs = _.union(Object.keys(desired.realized.working||{}), Object.keys(actual.working));
const transition = adjustment_order ? transition_refs.reduce((orders, ref) => {
const drw = (desired.realized.working||{})[ref];
return orders.concat(orderReplacements(actual.working[ref], drw, realized_offset, options));
}, transition_stoploss) : [];
const adjustment_pending = adjustment_order || actual.position != desired.position;
const working_targets = [].concat(
!actual.stoploss && desired.stoploss || [],
Object.values(_.omit(desired.working, Object.keys(actual.working)))
).map(ord => {
if (ord.action == 'BUY') return +desired.position + +ord.quant;
else if (ord.action == 'SELL') return +desired.position - +ord.quant;
});
if (!options.force && !actual.adjustment && actual.traded_at &&
moment(desired.asof).isBefore(actual.traded_at) &&
working_targets.some(trg => trg != null && Math.abs(+actual.position - trg) < quant_threshold)) {
// working position has since advanced to target (stoploss?)
logger.warn(`Working ${desired.attach_ref} position has since been changed ${actual.traded_at}`, options.label || '');
logger.debug("replicate", "actual", actual);
return cancelled;
} else if (options.exclude_working_orders) {
return adjustments;
} else if (adjustment_pending && (desired.realized.stoploss || !_.isEmpty(desired.realized.working))) {
// keep existing transition orders (i.e. stoploss), and don't submit new working orders
return transition.concat(adjustments);
} else if (adjustment_order && pending.length) {
// submit new orders attached as child orders to the adjustment order
return cancelled.concat({...adjustment_order, attached:pending});
} else if (adjustment_order) {
return cancelled.concat(adjustment_order);
} else if (pending.length) {
return cancelled.concat(pending);
} else {
return cancelled;
}
} | function updateActual(desired, actual, options) {
const quant_threshold = getQuantThreshold(actual, options);
const desired_adjustment = desired.position - actual.position >= quant_threshold ? {
action: 'BUY',
quant: (desired.position - actual.position).toString(),
...(((desired.adjustment||{action:'n/a'}).action||'BUY') == 'BUY' ? {
...desired.adjustment,
action: 'BUY'
} : {
order_type: options.default_order_type || 'MKT', tif: 'DAY',
..._.pick(desired, 'symbol', 'market', 'currency', 'security_type', 'multiplier', 'minTick')
})
} : actual.position - desired.position >= quant_threshold ? {
action: 'SELL',
quant: (actual.position - desired.position).toString(),
...(((desired.adjustment||{action:'n/a'}).action||'SELL') == 'SELL' ? {
...desired.adjustment,
action: 'SELL'
} : {
order_type: options.default_order_type || 'MKT', tif: 'DAY',
..._.pick(desired, 'symbol', 'market', 'currency', 'security_type', 'multiplier', 'minTick')
})
} : null;
const adjustments = orderReplacements(actual.adjustment, desired_adjustment, 0, options)
.filter(ord => ord.action == 'cancel' || !options.working_orders_only);
const adjusting_order = !adjustments.length ? actual.adjustment :
_.first(adjustments.filter(ord => ord.action != 'cancel'));
const adjust_position = !adjusting_order ? 0 :
adjusting_order.action == 'BUY' ? +adjusting_order.quant :
adjusting_order.action == 'SELL' ? -adjusting_order.quant : 0;
const target_position = actual.position + + adjust_position;
const pos_offset = target_position - desired.position;
const stoplosses = orderReplacements(actual.stoploss, desired.stoploss, pos_offset, options);
const working_refs = _.union(Object.keys(desired.working), Object.keys(actual.working));
const working = working_refs.reduce((orders, ref) => {
return orders.concat(orderReplacements(actual.working[ref], desired.working[ref], pos_offset, options));
}, stoplosses);
const cancelled = adjustments.concat(working).filter(ord => ord.action == 'cancel');
const pending = working.filter(ord => ord.action != 'cancel');
const adjustment_order = _.first(adjustments.filter(ord => ord.action != 'cancel'));
const realized_offset = actual.position - desired.realized.position;
const transition_stoploss = adjustment_order && desired.realized.stoploss ?
orderReplacements(actual.stoploss, desired.realized.stoploss, realized_offset, options) : [];
const transition_refs = _.union(Object.keys(desired.realized.working||{}), Object.keys(actual.working));
const transition = adjustment_order ? transition_refs.reduce((orders, ref) => {
const drw = (desired.realized.working||{})[ref];
return orders.concat(orderReplacements(actual.working[ref], drw, realized_offset, options));
}, transition_stoploss) : [];
const adjustment_pending = adjustment_order || actual.position != desired.position;
const working_targets = [].concat(
!actual.stoploss && desired.stoploss || [],
Object.values(_.omit(desired.working, Object.keys(actual.working)))
).map(ord => {
if (ord.action == 'BUY') return +desired.position + +ord.quant;
else if (ord.action == 'SELL') return +desired.position - +ord.quant;
});
if (!options.force && !actual.adjustment && actual.traded_at &&
moment(desired.asof).isBefore(actual.traded_at) &&
working_targets.some(trg => trg != null && Math.abs(+actual.position - trg) < quant_threshold)) {
// working position has since advanced to target (stoploss?)
logger.warn(`Working ${desired.attach_ref} position has since been changed ${actual.traded_at}`, options.label || '');
logger.debug("replicate", "actual", actual);
return cancelled;
} else if (options.exclude_working_orders) {
return adjustments;
} else if (adjustment_pending && (desired.realized.stoploss || !_.isEmpty(desired.realized.working))) {
// keep existing transition orders (i.e. stoploss), and don't submit new working orders
return transition.concat(adjustments);
} else if (adjustment_order && pending.length) {
// submit new orders attached as child orders to the adjustment order
return cancelled.concat({...adjustment_order, attached:pending});
} else if (adjustment_order) {
return cancelled.concat(adjustment_order);
} else if (pending.length) {
return cancelled.concat(pending);
} else {
return cancelled;
}
} |
JavaScript | function sameSignal(a, b, threshold) {
if (!a || !b) return false;
else if (!isMatch(b, _.pick(a, 'action', 'order_type', 'tif'))) return false;
else if (Math.abs(a.quant - b.quant) > (threshold || 0)) return false;
else if (a.limit && b.limit && a.limit != b.limit || !+a.limit != !+b.limit) return false;
else if (a.offset && b.offset && a.offset != b.offset || !+a.offset != !+b.offset) return false;
else if (a.stop && b.stop && a.stop != b.stop || !+a.stop != !+b.stop) return false;
else if (a.condition && b.condition && a.condition != b.condition || !+a.condition != !+b.condition) return false;
else return true;
} | function sameSignal(a, b, threshold) {
if (!a || !b) return false;
else if (!isMatch(b, _.pick(a, 'action', 'order_type', 'tif'))) return false;
else if (Math.abs(a.quant - b.quant) > (threshold || 0)) return false;
else if (a.limit && b.limit && a.limit != b.limit || !+a.limit != !+b.limit) return false;
else if (a.offset && b.offset && a.offset != b.offset || !+a.offset != !+b.offset) return false;
else if (a.stop && b.stop && a.stop != b.stop || !+a.stop != !+b.stop) return false;
else if (a.condition && b.condition && a.condition != b.condition || !+a.condition != !+b.condition) return false;
else return true;
} |
JavaScript | function sortOrders(orders) {
if (orders.length < 2) return orders;
const order_refs = _.indexBy(orders.filter(ord => ord.order_ref), 'order_ref');
const target_orders = orders.filter(ord => !order_refs[ord.attach_ref] || ord.order_ref == ord.attach_ref);
const working = [].concat(target_orders.filter(isStopOrder), target_orders.filter(ord => !isStopOrder(ord)));
if (!working.length) throw Error(`Could not sort array ${JSON.stringify(orders)}`);
return working.concat(sortOrders(_.difference(orders, working)));
} | function sortOrders(orders) {
if (orders.length < 2) return orders;
const order_refs = _.indexBy(orders.filter(ord => ord.order_ref), 'order_ref');
const target_orders = orders.filter(ord => !order_refs[ord.attach_ref] || ord.order_ref == ord.attach_ref);
const working = [].concat(target_orders.filter(isStopOrder), target_orders.filter(ord => !isStopOrder(ord)));
if (!working.length) throw Error(`Could not sort array ${JSON.stringify(orders)}`);
return working.concat(sortOrders(_.difference(orders, working)));
} |
JavaScript | async function help(quote) {
const help = _.first(await quote({info:'help'}));
return [{
name: 'collect',
usage: 'collect(options)',
description: "Evaluates columns using historic security data",
properties: help.properties,
options: _.extend({}, _.omit(help.options, ['symbol','market','pad_begin','pad_end']), {
portfolio: {
usage: 'symbol.market,..',
description: "Sets the set of securities or nested protfolios to collect data on"
},
filter: {
usage: '<expression>',
description: "An expression (possibly of an rolling function) of each included security bar that must be true to be included in the result. The result of these expressions have no impact on rolling functions, unlike criteria, which is applied earlier."
},
precedence: {
usage: '<expression>',
description: "The order that securities should be checked for inclusion in the result. A comma separated list of expressions can be provided and each may be wrapped in a DESC function to indicate the order should be reversed."
},
order: {
usage: '<expression>,..',
description: "The order that the output should be sorted by. A comma separated list of expressions can be provided and each may be wrapped in a DESC function to indicate the order should be reversed."
},
pad_leading: {
usage: '<number of workdays>',
description: "Number of workdays (Mon-Fri) to processes before the result (as a warm up)"
},
reset_every: {
usage: 'P1Y',
description: "Sets the duration that collect should run before resetting any preceeding values"
},
head: {
usage: '<number of rows>',
description: "Limits the rows in the result to the given first few"
},
tail: {
usage: '<number of rows>',
description: "Include the given last few rows in the result"
},
id: {
description: "Unique alphanumeric identifier among its peers (optional)"
}
})
}];
} | async function help(quote) {
const help = _.first(await quote({info:'help'}));
return [{
name: 'collect',
usage: 'collect(options)',
description: "Evaluates columns using historic security data",
properties: help.properties,
options: _.extend({}, _.omit(help.options, ['symbol','market','pad_begin','pad_end']), {
portfolio: {
usage: 'symbol.market,..',
description: "Sets the set of securities or nested protfolios to collect data on"
},
filter: {
usage: '<expression>',
description: "An expression (possibly of an rolling function) of each included security bar that must be true to be included in the result. The result of these expressions have no impact on rolling functions, unlike criteria, which is applied earlier."
},
precedence: {
usage: '<expression>',
description: "The order that securities should be checked for inclusion in the result. A comma separated list of expressions can be provided and each may be wrapped in a DESC function to indicate the order should be reversed."
},
order: {
usage: '<expression>,..',
description: "The order that the output should be sorted by. A comma separated list of expressions can be provided and each may be wrapped in a DESC function to indicate the order should be reversed."
},
pad_leading: {
usage: '<number of workdays>',
description: "Number of workdays (Mon-Fri) to processes before the result (as a warm up)"
},
reset_every: {
usage: 'P1Y',
description: "Sets the duration that collect should run before resetting any preceeding values"
},
head: {
usage: '<number of rows>',
description: "Limits the rows in the result to the given first few"
},
tail: {
usage: '<number of rows>',
description: "Include the given last few rows in the result"
},
id: {
description: "Unique alphanumeric identifier among its peers (optional)"
}
})
}];
} |
JavaScript | async function checkCircularVariableReference(fields, options) {
const variables = _.extend({}, getColumnVariables(fields, options), options.variables);
const references = await getReferences(variables);
_.each(references, (reference, name) => {
if (_.contains(reference, name)) {
const path = _.sortBy(_.keys(references).filter(n => _.contains(references[n], n) && _.contains(references[n], name)));
throw Error(`Circular variable reference ${path.join(',')}: ${variables[name]} in ${options.label}`);
}
});
} | async function checkCircularVariableReference(fields, options) {
const variables = _.extend({}, getColumnVariables(fields, options), options.variables);
const references = await getReferences(variables);
_.each(references, (reference, name) => {
if (_.contains(reference, name)) {
const path = _.sortBy(_.keys(references).filter(n => _.contains(references[n], n) && _.contains(references[n], name)));
throw Error(`Circular variable reference ${path.join(',')}: ${variables[name]} in ${options.label}`);
}
});
} |
JavaScript | function compactPortfolio(fields, begin, end, options) {
const portfolio = options.portfolio;
const array = _.isArray(portfolio) ? portfolio :
_.isObject(portfolio) ? [portfolio] :
_.isString(portfolio) ? portfolio.split(/\s*,\s*/) :
expect(portfolio).to.be.a('string');
const leading = !options.pad_leading ? begin :
common('WORKDAY', [_.constant(begin), _.constant(-options.pad_leading)])();
const mbegin = moment(leading);
const mend = moment(end || options.now);
const compacted = _.compact(array.map((subcollect, idx) => {
if (!_.isObject(subcollect)) return subcollect;
const sbegin = subcollect.begin && moment(subcollect.begin);
const send = subcollect.end && moment(subcollect.end);
if (send && !send.isAfter(mbegin) || sbegin && !sbegin.isBefore(mend)) return null;
const begin = sbegin && mbegin.isBefore(sbegin) ? sbegin.format() : mbegin.format();
const end = send && mend.isAfter(send) ? send.format() : options.end ? mend.format() : undefined;
const compact = compactPortfolio(fields, begin, end, {...subcollect, now: options.now});
if (compact.id != null) return compact;
else return _.extend({id: 'c' + idx}, compact);
}));
if (array.every((item, i) => item == compacted[i])) return options;
const before = _.uniq(_.flatten(array.map(subcollect => _.keys(subcollect.columns))));
const after = _.uniq(_.flatten(compacted.map(subcollect => _.keys(subcollect.columns))));
const missing = _.difference(before, after, _.keys(options.variables), _.keys(options.parameters), fields);
const params = _.object(missing, missing.map(v => null));
return _.defaults({
portfolio: compacted,
parameters: _.defaults({}, options.parameters, params)
}, options);
} | function compactPortfolio(fields, begin, end, options) {
const portfolio = options.portfolio;
const array = _.isArray(portfolio) ? portfolio :
_.isObject(portfolio) ? [portfolio] :
_.isString(portfolio) ? portfolio.split(/\s*,\s*/) :
expect(portfolio).to.be.a('string');
const leading = !options.pad_leading ? begin :
common('WORKDAY', [_.constant(begin), _.constant(-options.pad_leading)])();
const mbegin = moment(leading);
const mend = moment(end || options.now);
const compacted = _.compact(array.map((subcollect, idx) => {
if (!_.isObject(subcollect)) return subcollect;
const sbegin = subcollect.begin && moment(subcollect.begin);
const send = subcollect.end && moment(subcollect.end);
if (send && !send.isAfter(mbegin) || sbegin && !sbegin.isBefore(mend)) return null;
const begin = sbegin && mbegin.isBefore(sbegin) ? sbegin.format() : mbegin.format();
const end = send && mend.isAfter(send) ? send.format() : options.end ? mend.format() : undefined;
const compact = compactPortfolio(fields, begin, end, {...subcollect, now: options.now});
if (compact.id != null) return compact;
else return _.extend({id: 'c' + idx}, compact);
}));
if (array.every((item, i) => item == compacted[i])) return options;
const before = _.uniq(_.flatten(array.map(subcollect => _.keys(subcollect.columns))));
const after = _.uniq(_.flatten(compacted.map(subcollect => _.keys(subcollect.columns))));
const missing = _.difference(before, after, _.keys(options.variables), _.keys(options.parameters), fields);
const params = _.object(missing, missing.map(v => null));
return _.defaults({
portfolio: compacted,
parameters: _.defaults({}, options.parameters, params)
}, options);
} |
JavaScript | async function parseNeededColumns(fields, options) {
const varnames = await getVariables(fields, options);
const normalizer = createNormalizeParser(varnames, options);
const columns_values = Object.values(options.columns).map(expr => normalizer.parse(expr || 'NULL()'));
const columns = _.object(Object.keys(options.columns), await Promise.all(columns_values));
const conflicts = _.intersection(_.keys(_.omit(columns, (v, k) => v==k)),
_.union(fields, _.keys(options.variables))
);
const masked = _.object(conflicts, conflicts.map(name => {
if (!~conflicts.indexOf(columns[name])) return columns[name];
let seq = 2;
while (~conflicts.indexOf(name + seq)) seq++;
return name + seq;
}));
const result = [];
const needed = _.reduce(options.columns, (needed, expr, key) => {
const value = columns[key];
needed[masked[key] || key] = value;
result.push([masked[key] || key, value]);
return needed;
}, {});
const variables = await varnames.reduce(async(promise, name) => {
const variables = await promise;
if (_.has(options.variables, name)) {
variables[name] = await normalizer.parse(options.variables[name]);
result.push([name, variables[name]]);
} else if (!_.has(needed, name) && !_.has(variables, name) && ~fields.indexOf(name)) {
variables[name] = name; // pass through fields used in rolling functions
result.push([name, variables[name]]);
}
return variables;
}, {});
const filterOrder = await normalizer.parseCriteriaList(_.flatten(_.compact([
options.filter, options.order
]), true));
const isVariablePresent = new Parser({
constant(value) {
return false;
},
variable(name) {
return true;
},
expression(expr, name, args) {
if (rolling.has(name) && rolling.getVariables(expr, options).length) return true;
else return args.find(_.identity) || false;
}
}).parse;
const filterOrder_isVariablePresent = await Promise.all(filterOrder.map(async(expr) => {
if (needed[expr] || variables[expr]) return false;
else return isVariablePresent(expr);
}));
const neededFilterOrder = filterOrder.filter((expr, i) => filterOrder_isVariablePresent[i]);
return result.concat(_.zip(neededFilterOrder, neededFilterOrder));
} | async function parseNeededColumns(fields, options) {
const varnames = await getVariables(fields, options);
const normalizer = createNormalizeParser(varnames, options);
const columns_values = Object.values(options.columns).map(expr => normalizer.parse(expr || 'NULL()'));
const columns = _.object(Object.keys(options.columns), await Promise.all(columns_values));
const conflicts = _.intersection(_.keys(_.omit(columns, (v, k) => v==k)),
_.union(fields, _.keys(options.variables))
);
const masked = _.object(conflicts, conflicts.map(name => {
if (!~conflicts.indexOf(columns[name])) return columns[name];
let seq = 2;
while (~conflicts.indexOf(name + seq)) seq++;
return name + seq;
}));
const result = [];
const needed = _.reduce(options.columns, (needed, expr, key) => {
const value = columns[key];
needed[masked[key] || key] = value;
result.push([masked[key] || key, value]);
return needed;
}, {});
const variables = await varnames.reduce(async(promise, name) => {
const variables = await promise;
if (_.has(options.variables, name)) {
variables[name] = await normalizer.parse(options.variables[name]);
result.push([name, variables[name]]);
} else if (!_.has(needed, name) && !_.has(variables, name) && ~fields.indexOf(name)) {
variables[name] = name; // pass through fields used in rolling functions
result.push([name, variables[name]]);
}
return variables;
}, {});
const filterOrder = await normalizer.parseCriteriaList(_.flatten(_.compact([
options.filter, options.order
]), true));
const isVariablePresent = new Parser({
constant(value) {
return false;
},
variable(name) {
return true;
},
expression(expr, name, args) {
if (rolling.has(name) && rolling.getVariables(expr, options).length) return true;
else return args.find(_.identity) || false;
}
}).parse;
const filterOrder_isVariablePresent = await Promise.all(filterOrder.map(async(expr) => {
if (needed[expr] || variables[expr]) return false;
else return isVariablePresent(expr);
}));
const neededFilterOrder = filterOrder.filter((expr, i) => filterOrder_isVariablePresent[i]);
return result.concat(_.zip(neededFilterOrder, neededFilterOrder));
} |
JavaScript | function createNormalizeParser(variables, options) {
return new Parser({
substitutions: getSubstitutions(variables, options),
expression(expr, name, args) {
if (name == 'DESC' || name == 'ASC') return _.first(args);
else return expr;
}
});
} | function createNormalizeParser(variables, options) {
return new Parser({
substitutions: getSubstitutions(variables, options),
expression(expr, name, args) {
if (name == 'DESC' || name == 'ASC') return _.first(args);
else return expr;
}
});
} |
JavaScript | function stringify(value) {
if (value == null) return 'NULL()';
else if (typeof value != 'object') return JSON.stringify(value);
else if (value instanceof Big) return value.toString();
else throw Error("Must be a number, string, or null: " + value);
} | function stringify(value) {
if (value == null) return 'NULL()';
else if (typeof value != 'object') return JSON.stringify(value);
else if (value instanceof Big) return value.toString();
else throw Error("Must be a number, string, or null: " + value);
} |
JavaScript | function createColumnParser(columns, options) {
const inline = createInlineParser(columns, options);
const parsedColumns = {};
const parser = new Parser({
substitutions: getSubstitutions(_.keys(columns), options),
constant(value) {
return {complex: false, columns: {}};
},
async variable(name) {
if (!columns[name] || columns[name]==name)
return {complex: false, columns: {[name]: name}};
parsedColumns[name] = parsedColumns[name] || await parser.parse(columns[name]);
if (parsedColumns[name].complex)
return {complex: true, columns: {}}; // can't include complex variables
else return {complex: false, columns: {}}; // parse column later
},
async expression(expr, name, args) {
const order = name == 'DESC' || name == 'ASC';
const complex = _.some(args, arg => arg.complex);
const nested = {
complex: true,
columns: _.pluck(args, 'columns').reduce((a,b)=>_.extend(a,b), {})
};
if (Quoting.has(name)) return {complex: true, columns: {}};
else if (order || rolling.has(name) || complex) return nested;
const inlined = await inline(expr);
if (common.has(name) && inlined.length > 512) return nested;
else return {complex: false, columns: {[expr]: inlined}}; // lookback
}
});
return parser;
} | function createColumnParser(columns, options) {
const inline = createInlineParser(columns, options);
const parsedColumns = {};
const parser = new Parser({
substitutions: getSubstitutions(_.keys(columns), options),
constant(value) {
return {complex: false, columns: {}};
},
async variable(name) {
if (!columns[name] || columns[name]==name)
return {complex: false, columns: {[name]: name}};
parsedColumns[name] = parsedColumns[name] || await parser.parse(columns[name]);
if (parsedColumns[name].complex)
return {complex: true, columns: {}}; // can't include complex variables
else return {complex: false, columns: {}}; // parse column later
},
async expression(expr, name, args) {
const order = name == 'DESC' || name == 'ASC';
const complex = _.some(args, arg => arg.complex);
const nested = {
complex: true,
columns: _.pluck(args, 'columns').reduce((a,b)=>_.extend(a,b), {})
};
if (Quoting.has(name)) return {complex: true, columns: {}};
else if (order || rolling.has(name) || complex) return nested;
const inlined = await inline(expr);
if (common.has(name) && inlined.length > 512) return nested;
else return {complex: false, columns: {[expr]: inlined}}; // lookback
}
});
return parser;
} |
JavaScript | function createInlineParser(columns, options) {
const incols = {};
const inline = new Parser({
substitutions: getSubstitutions(_.keys(columns), options),
constant(value) {
return _.constant(value);
},
async variable(name) {
if (!columns[name] || columns[name]==name) return name;
else return incols[name] = incols[name] || await inline.parse(columns[name]);
},
expression(expr, name, args) {
if (common.has(name) && args.every(_.isFunction))
return common(name, args, options);
const values = args.map(arg => _.isFunction(arg) ? stringify(arg()) : arg);
return name + '(' + values.join(',') + ')';
}
});
const formatter = new Parser();
return async function(expr) {
const parsed = await inline.parse(expr);
return formatter.parse(_.isFunction(parsed) ? stringify(parsed()) : parsed);
};
} | function createInlineParser(columns, options) {
const incols = {};
const inline = new Parser({
substitutions: getSubstitutions(_.keys(columns), options),
constant(value) {
return _.constant(value);
},
async variable(name) {
if (!columns[name] || columns[name]==name) return name;
else return incols[name] = incols[name] || await inline.parse(columns[name]);
},
expression(expr, name, args) {
if (common.has(name) && args.every(_.isFunction))
return common(name, args, options);
const values = args.map(arg => _.isFunction(arg) ? stringify(arg()) : arg);
return name + '(' + values.join(',') + ')';
}
});
const formatter = new Parser();
return async function(expr) {
const parsed = await inline.parse(expr);
return formatter.parse(_.isFunction(parsed) ? stringify(parsed()) : parsed);
};
} |
JavaScript | function createParser(quoting, columns, cached, options) {
const pCols = {};
const parser = new Parser({
substitutions: getSubstitutions(_.keys(columns), options),
constant(value) {
return positions => value;
},
async variable(name) {
if (columns[name] && name!=columns[name])
return pCols[name] = pCols[name] || await parser.parse(columns[name]);
// [{"USD.CAD": {"close": 1.00}}]
else return ctx => {
const last = _.last(ctx);
const last_key = _.last(Object.keys(last));
return last[last_key][name];
};
},
expression(expr, name, args) {
if (_.contains(cached, expr))
return ctx => {
const last = _.last(ctx);
const last_key = _.last(Object.keys(last));
return last[last_key][expr];
};
else {
const fn = common(name, args, options) ||
rolling(expr, name, args, options) ||
quoting(expr, name, args, options);
if (fn) return fn;
else return () => {
throw Error("Only common and rolling functions can be used here: " + expr);
};
}
}
});
return parser;
} | function createParser(quoting, columns, cached, options) {
const pCols = {};
const parser = new Parser({
substitutions: getSubstitutions(_.keys(columns), options),
constant(value) {
return positions => value;
},
async variable(name) {
if (columns[name] && name!=columns[name])
return pCols[name] = pCols[name] || await parser.parse(columns[name]);
// [{"USD.CAD": {"close": 1.00}}]
else return ctx => {
const last = _.last(ctx);
const last_key = _.last(Object.keys(last));
return last[last_key][name];
};
},
expression(expr, name, args) {
if (_.contains(cached, expr))
return ctx => {
const last = _.last(ctx);
const last_key = _.last(Object.keys(last));
return last[last_key][expr];
};
else {
const fn = common(name, args, options) ||
rolling(expr, name, args, options) ||
quoting(expr, name, args, options);
if (fn) return fn;
else return () => {
throw Error("Only common and rolling functions can be used here: " + expr);
};
}
}
});
return parser;
} |
JavaScript | async function promiseColumns(parser, columns, options) {
const map = await parser.parse(columns);
return Promise.all(_.values(map))
.then(values => _.object(_.keys(map), values))
.then(columns => {
const indexCol = options.indexCol;
const symbolCol = options.symbolCol;
const marketCol = options.marketCol;
const temporalCol = options.temporalCol;
if (!columns[indexCol]) return columns;
// nested collect pass through these columns as-is
columns[indexCol] = ctx => _.last(_.values(_.last(ctx)))[indexCol];
columns[symbolCol] = ctx => _.last(_.values(_.last(ctx)))[symbolCol];
columns[marketCol] = ctx => _.last(_.values(_.last(ctx)))[marketCol];
columns[temporalCol] = ctx => _.last(_.values(_.last(ctx)))[temporalCol];
return columns;
});
} | async function promiseColumns(parser, columns, options) {
const map = await parser.parse(columns);
return Promise.all(_.values(map))
.then(values => _.object(_.keys(map), values))
.then(columns => {
const indexCol = options.indexCol;
const symbolCol = options.symbolCol;
const marketCol = options.marketCol;
const temporalCol = options.temporalCol;
if (!columns[indexCol]) return columns;
// nested collect pass through these columns as-is
columns[indexCol] = ctx => _.last(_.values(_.last(ctx)))[indexCol];
columns[symbolCol] = ctx => _.last(_.values(_.last(ctx)))[symbolCol];
columns[marketCol] = ctx => _.last(_.values(_.last(ctx)))[marketCol];
columns[temporalCol] = ctx => _.last(_.values(_.last(ctx)))[temporalCol];
return columns;
});
} |
JavaScript | async function reduceInterval(dataset, temporal, cb, memo) {
const check = interrupt();
while (dataset.some(list => list.length)) {
await check();
const ending = _.first(_.compact(_.pluck(dataset.map(list => _.first(list)), temporal)).sort());
const points = dataset.reduce((result,list) => {
while (list.length && _.first(list)[temporal] == ending) {
result.push(list.shift());
}
return result;
}, []);
memo = await cb(memo, points);
}
return memo;
} | async function reduceInterval(dataset, temporal, cb, memo) {
const check = interrupt();
while (dataset.some(list => list.length)) {
await check();
const ending = _.first(_.compact(_.pluck(dataset.map(list => _.first(list)), temporal)).sort());
const points = dataset.reduce((result,list) => {
while (list.length && _.first(list)[temporal] == ending) {
result.push(list.shift());
}
return result;
}, []);
memo = await cb(memo, points);
}
return memo;
} |
JavaScript | function isOptionsMarketHoliday(date) {
if (isNewYearsDay(date)) return true;
if (isMartinLutherKingDay(date)) return true;
if (isWashingtonsBirthday(date)) return true;
if (isGoodFriday(date)) return true;
if (isMemorialDay(date)) return true;
if (isIndependenceDay(date)) return true;
if (isLaborDay(date)) return true;
if (isThanksgiving(date)) return true;
if (isChristmasDay(date)) return true;
else return false;
} | function isOptionsMarketHoliday(date) {
if (isNewYearsDay(date)) return true;
if (isMartinLutherKingDay(date)) return true;
if (isWashingtonsBirthday(date)) return true;
if (isGoodFriday(date)) return true;
if (isMemorialDay(date)) return true;
if (isIndependenceDay(date)) return true;
if (isLaborDay(date)) return true;
if (isThanksgiving(date)) return true;
if (isChristmasDay(date)) return true;
else return false;
} |
JavaScript | function parseSplit(stock_splits) {
if (!stock_splits) return Big(1);
const splits = ~stock_splits.indexOf('/') ?
stock_splits.split('/').reverse() : stock_splits.split(':');
// TRI.TO 2018-11-27 Stock Splits of 1/0
if (!+splits[0] || !+splits[1]) return Big(1);
else return Big(splits[0]).div(splits[1]);
} | function parseSplit(stock_splits) {
if (!stock_splits) return Big(1);
const splits = ~stock_splits.indexOf('/') ?
stock_splits.split('/').reverse() : stock_splits.split(':');
// TRI.TO 2018-11-27 Stock Splits of 1/0
if (!+splits[0] || !+splits[1]) return Big(1);
else return Big(splits[0]).div(splits[1]);
} |
JavaScript | function help(fetch) {
return fetch({info:'help'})
.then(help => _.indexBy(help, 'name'))
.then(help => _.pick(help, ['lookup', 'interday', 'intraday'])).then(help => {
const downstream = _.reduce(help, (downstream, help) => _.extend(downstream, help.options), {});
const variables = Periods.values.reduce((variables, interval) => {
const fields = interval.charAt(0) != 'm' ? help.interday.properties :
help.intraday ? help.intraday.properties : [];
return variables.concat(fields.map(field => interval + '.' + field));
}, ['ending', 'currency'].concat(help.lookup.properties));
return [{
name: 'quote',
usage: 'quote(options)',
description: "Formats historic data into provided columns",
properties: variables,
options: _.extend({}, _.omit(downstream, help.lookup.properties), {
label: downstream.label,
symbol: downstream.symbol,
market: downstream.market,
begin: downstream.begin,
end: downstream.end,
interval: downstream.interval,
columns: {
type: 'map',
usage: '<expression>',
description: "Column expression included in the output. The expression can be any combination of field, constants, and function calls connected by an operator or operators.",
seeAlso: ['expression', 'common-functions', 'lookback-functions', 'indicator-functions', 'rolling-functions']
},
criteria: {
usage: '<expression>',
description: "An expression (possibly of an rolling function) of each included security bar that must be true to be included in the result.",
seeAlso: ['expression', 'common-functions', 'lookback-functions', 'indicator-functions', 'rolling-functions']
},
parameters: {
type: 'map',
usage: 'string|number',
description: "Parameter used to help compute a column. The value must be a constant literal.",
seeAlso: ['columns']
},
variables: {
type: 'map',
usage: '<expression>',
description: "Variable used to help compute a column. The expression can be any combination of field, constants, and function calls connected by an operator or operators.",
seeAlso: ['expression', 'common-functions', 'lookback-functions', 'indicator-functions', 'rolling-functions']
},
pad_begin: {
usage: '<number of bar>',
description: "Sets the number of additional rows to include before the begin date (might be less)"
},
pad_end: {
usage: '<number of bar>',
description: "Sets the number of additional rows to include after the end date (might be less)"
},
now: {
usage: '<timestamp>',
description: "The current date/time this request is started"
},
offline: {
usage: 'true',
description: "If only the local data should be used in the computation"
},
update: {
usage: 'true',
description: "If the system should (re)fetch the last bar"
},
read_only: {
usage: 'true',
descirption: "If only precomputed lookback and indicator function should be used"
},
transient: {
usage: 'true',
description: "If no computed columns should be persisted to disk. Useful when evaluating expressions, over a short time period, that might not be evaluated again."
},
fast_arithmetic: {
usage: 'true',
description: "If native double-precision numeric operators should be used with fractional errors"
}
})
}];
});
} | function help(fetch) {
return fetch({info:'help'})
.then(help => _.indexBy(help, 'name'))
.then(help => _.pick(help, ['lookup', 'interday', 'intraday'])).then(help => {
const downstream = _.reduce(help, (downstream, help) => _.extend(downstream, help.options), {});
const variables = Periods.values.reduce((variables, interval) => {
const fields = interval.charAt(0) != 'm' ? help.interday.properties :
help.intraday ? help.intraday.properties : [];
return variables.concat(fields.map(field => interval + '.' + field));
}, ['ending', 'currency'].concat(help.lookup.properties));
return [{
name: 'quote',
usage: 'quote(options)',
description: "Formats historic data into provided columns",
properties: variables,
options: _.extend({}, _.omit(downstream, help.lookup.properties), {
label: downstream.label,
symbol: downstream.symbol,
market: downstream.market,
begin: downstream.begin,
end: downstream.end,
interval: downstream.interval,
columns: {
type: 'map',
usage: '<expression>',
description: "Column expression included in the output. The expression can be any combination of field, constants, and function calls connected by an operator or operators.",
seeAlso: ['expression', 'common-functions', 'lookback-functions', 'indicator-functions', 'rolling-functions']
},
criteria: {
usage: '<expression>',
description: "An expression (possibly of an rolling function) of each included security bar that must be true to be included in the result.",
seeAlso: ['expression', 'common-functions', 'lookback-functions', 'indicator-functions', 'rolling-functions']
},
parameters: {
type: 'map',
usage: 'string|number',
description: "Parameter used to help compute a column. The value must be a constant literal.",
seeAlso: ['columns']
},
variables: {
type: 'map',
usage: '<expression>',
description: "Variable used to help compute a column. The expression can be any combination of field, constants, and function calls connected by an operator or operators.",
seeAlso: ['expression', 'common-functions', 'lookback-functions', 'indicator-functions', 'rolling-functions']
},
pad_begin: {
usage: '<number of bar>',
description: "Sets the number of additional rows to include before the begin date (might be less)"
},
pad_end: {
usage: '<number of bar>',
description: "Sets the number of additional rows to include after the end date (might be less)"
},
now: {
usage: '<timestamp>',
description: "The current date/time this request is started"
},
offline: {
usage: 'true',
description: "If only the local data should be used in the computation"
},
update: {
usage: 'true',
description: "If the system should (re)fetch the last bar"
},
read_only: {
usage: 'true',
descirption: "If only precomputed lookback and indicator function should be used"
},
transient: {
usage: 'true',
description: "If no computed columns should be persisted to disk. Useful when evaluating expressions, over a short time period, that might not be evaluated again."
},
fast_arithmetic: {
usage: 'true',
description: "If native double-precision numeric operators should be used with fractional errors"
}
})
}];
});
} |
JavaScript | async function quote(fetch, store, fields, options) {
try {
if (options.columns) expect(options.columns).not.to.have.property('length'); // not array like
if (options.variables) expect(options.variables).not.to.have.property('length'); // not array like
if (options.parameters) expect(options.parameters).not.to.have.property('length'); // not array like
const exprMap = await parseWarmUpMap(fields, options);
const cached = _.mapObject(exprMap, _.keys);
const intervals = Periods.sort(_.keys(exprMap));
if (_.isEmpty(intervals)) throw Error("At least one column need to reference an interval fields");
const criteria = await parseCriteriaMap(options.criteria, fields, cached, intervals, options);
const interval = intervals[0];
intervals.forEach(interval => expect(interval).to.be.oneOf(Periods.values));
return store.open(options.symbol, (err, db) => {
if (err) throw err;
const quoteBars = fetchBars.bind(this, fetch, db, fields);
return inlinePadBegin(quoteBars, interval, options)
.then(options => inlinePadEnd(quoteBars, interval, options))
.then(options => mergeBars(quoteBars, exprMap, criteria, options));
}).then(signals => formatColumns(fields, signals, options));
} catch (e) {
logger.debug(e);
throw Error((e.message || e) + " for " + options.symbol);
}
} | async function quote(fetch, store, fields, options) {
try {
if (options.columns) expect(options.columns).not.to.have.property('length'); // not array like
if (options.variables) expect(options.variables).not.to.have.property('length'); // not array like
if (options.parameters) expect(options.parameters).not.to.have.property('length'); // not array like
const exprMap = await parseWarmUpMap(fields, options);
const cached = _.mapObject(exprMap, _.keys);
const intervals = Periods.sort(_.keys(exprMap));
if (_.isEmpty(intervals)) throw Error("At least one column need to reference an interval fields");
const criteria = await parseCriteriaMap(options.criteria, fields, cached, intervals, options);
const interval = intervals[0];
intervals.forEach(interval => expect(interval).to.be.oneOf(Periods.values));
return store.open(options.symbol, (err, db) => {
if (err) throw err;
const quoteBars = fetchBars.bind(this, fetch, db, fields);
return inlinePadBegin(quoteBars, interval, options)
.then(options => inlinePadEnd(quoteBars, interval, options))
.then(options => mergeBars(quoteBars, exprMap, criteria, options));
}).then(signals => formatColumns(fields, signals, options));
} catch (e) {
logger.debug(e);
throw Error((e.message || e) + " for " + options.symbol);
}
} |
JavaScript | async function parseWarmUpMap(fields, options) {
const exprs = _.compact(_.flatten([
_.compact(_.values(options.columns)), options.criteria
]));
if (!exprs.length && !options.interval) return {day:{}};
else if (!exprs.length) return {[options.interval]:{}};
const p = createParser(fields, {}, options);
const parser = new Parser({
substitutions: getVariables(fields, options),
constant(value) {
return {warmUpLength: 0};
},
variable(name) {
if (!~name.indexOf('.')) return {warmUpLength: 0};
else return {[name.substring(0, name.indexOf('.'))]: {}, warmUpLength: 0};
},
async expression(expr, name, args) {
const fn = await p.parse(expr);
const args_inters = _.without(_.flatten(args.map(_.keys), true), 'warmUpLength');
const inters = Periods.sort(_.uniq(args_inters.concat(fn.intervals || [])));
const map = _.object(inters, inters.map(interval => {
return _.extend.apply(_, _.compact(_.pluck(args, interval)));
}));
map.warmUpLength = _.max([0].concat(_.pluck(args, 'warmUpLength')));
if (fn.warmUpLength>map.warmUpLength && fn.sideEffect)
throw Error("Cannot use lookback function " + name + " with side effects: " + expr);
if (_.size(fn.intervals)!=1 || fn.warmUpLength==map.warmUpLength || !_.isFinite(fn.warmUpLength))
return map;
return {[_.first(fn.intervals)]: {[expr]: fn}, warmUpLength: fn.warmUpLength};
}
});
const values = (await parser.parse(exprs)).map(o => _.omit(o, 'warmUpLength'));
const intervals = Periods.sort(_.uniq(_.flatten(values.map(_.keys), true)));
return _.object(intervals, intervals.map(interval => {
return _.extend.apply(_, _.compact(_.pluck(values, interval)));
}));
} | async function parseWarmUpMap(fields, options) {
const exprs = _.compact(_.flatten([
_.compact(_.values(options.columns)), options.criteria
]));
if (!exprs.length && !options.interval) return {day:{}};
else if (!exprs.length) return {[options.interval]:{}};
const p = createParser(fields, {}, options);
const parser = new Parser({
substitutions: getVariables(fields, options),
constant(value) {
return {warmUpLength: 0};
},
variable(name) {
if (!~name.indexOf('.')) return {warmUpLength: 0};
else return {[name.substring(0, name.indexOf('.'))]: {}, warmUpLength: 0};
},
async expression(expr, name, args) {
const fn = await p.parse(expr);
const args_inters = _.without(_.flatten(args.map(_.keys), true), 'warmUpLength');
const inters = Periods.sort(_.uniq(args_inters.concat(fn.intervals || [])));
const map = _.object(inters, inters.map(interval => {
return _.extend.apply(_, _.compact(_.pluck(args, interval)));
}));
map.warmUpLength = _.max([0].concat(_.pluck(args, 'warmUpLength')));
if (fn.warmUpLength>map.warmUpLength && fn.sideEffect)
throw Error("Cannot use lookback function " + name + " with side effects: " + expr);
if (_.size(fn.intervals)!=1 || fn.warmUpLength==map.warmUpLength || !_.isFinite(fn.warmUpLength))
return map;
return {[_.first(fn.intervals)]: {[expr]: fn}, warmUpLength: fn.warmUpLength};
}
});
const values = (await parser.parse(exprs)).map(o => _.omit(o, 'warmUpLength'));
const intervals = Periods.sort(_.uniq(_.flatten(values.map(_.keys), true)));
return _.object(intervals, intervals.map(interval => {
return _.extend.apply(_, _.compact(_.pluck(values, interval)));
}));
} |
JavaScript | async function parseCriteriaMap(criteria, fields, cached, intervals, options) {
const list = await createParser(fields, cached, options).parseCriteriaList(criteria);
const group = list.reduce((m, fn) => {
const interval = _.first(fn.intervals);
if (m[interval]) {
m[interval] = m[interval].concat([fn]);
return m;
} else return _.extend(m, {
[interval]: [fn]
});
}, {});
_.reduceRight(intervals, (ar, interval) => {
if (!group[interval]) return group[interval] = ar;
return group[interval] = group[interval].concat(ar);
}, []);
return _.mapObject(group, (list, interval) => {
return bars => _.every(list, fn => fn(bars));
});
} | async function parseCriteriaMap(criteria, fields, cached, intervals, options) {
const list = await createParser(fields, cached, options).parseCriteriaList(criteria);
const group = list.reduce((m, fn) => {
const interval = _.first(fn.intervals);
if (m[interval]) {
m[interval] = m[interval].concat([fn]);
return m;
} else return _.extend(m, {
[interval]: [fn]
});
}, {});
_.reduceRight(intervals, (ar, interval) => {
if (!group[interval]) return group[interval] = ar;
return group[interval] = group[interval].concat(ar);
}, []);
return _.mapObject(group, (list, interval) => {
return bars => _.every(list, fn => fn(bars));
});
} |
JavaScript | function createParser(fields, cached, options) {
return new Parser({
substitutions: getVariables(fields, options),
constant(value) {
return () => value;
},
variable(name) {
if (_.contains(['symbol', 'market', 'ending'], name))
return ctx => _.last(ctx)[name];
else if (!~name.indexOf('.') && ~fields.indexOf(name))
return _.constant(options[name]);
else if (!~name.indexOf('.'))
throw Error("Unknown field: " + name);
const interval = name.substring(0, name.indexOf('.'));
expect(interval).to.be.oneOf(Periods.values);
const lname = name.substring(name.indexOf('.')+1);
return _.extend(ctx => {
if (!ctx.length) return undefined;
const last = ctx[ctx.length -1];
const obj = last[interval];
return obj ? obj[lname] : undefined;
}, {
intervals: [interval]
});
},
expression(expr, name, args) {
const fn = common(name, args, options) ||
lookback(name, args, options) ||
indicator(name, args, options);
if (!fn) throw Error("Unknown function: " + name);
const interval =_.first(fn.intervals);
if (!_.contains(cached[interval], expr)) return fn;
else return _.extend(ctx => {
const obj = _.last(ctx)[interval];
return obj ? obj[expr] : undefined;
}, {
intervals: fn.intervals
});
}
});
} | function createParser(fields, cached, options) {
return new Parser({
substitutions: getVariables(fields, options),
constant(value) {
return () => value;
},
variable(name) {
if (_.contains(['symbol', 'market', 'ending'], name))
return ctx => _.last(ctx)[name];
else if (!~name.indexOf('.') && ~fields.indexOf(name))
return _.constant(options[name]);
else if (!~name.indexOf('.'))
throw Error("Unknown field: " + name);
const interval = name.substring(0, name.indexOf('.'));
expect(interval).to.be.oneOf(Periods.values);
const lname = name.substring(name.indexOf('.')+1);
return _.extend(ctx => {
if (!ctx.length) return undefined;
const last = ctx[ctx.length -1];
const obj = last[interval];
return obj ? obj[lname] : undefined;
}, {
intervals: [interval]
});
},
expression(expr, name, args) {
const fn = common(name, args, options) ||
lookback(name, args, options) ||
indicator(name, args, options);
if (!fn) throw Error("Unknown function: " + name);
const interval =_.first(fn.intervals);
if (!_.contains(cached[interval], expr)) return fn;
else return _.extend(ctx => {
const obj = _.last(ctx)[interval];
return obj ? obj[expr] : undefined;
}, {
intervals: fn.intervals
});
}
});
} |
JavaScript | function inlinePadBegin(quoteBars, interval, opts) {
const options = formatBeginEnd(opts);
if (!options.pad_begin) return Promise.resolve(options);
else return quoteBars({}, _.defaults({
interval: interval,
end: options.begin,
pad_end: 0
}, options)).then(bars => {
if (!bars.length) return options;
const start = _.sortedIndex(bars, {ending: options.begin}, 'ending');
const i = Math.max(start - options.pad_begin, 0);
return _.defaults({
pad_begin: Math.max(+options.pad_begin - start, 0),
begin: bars[i].ending
}, options);
});
} | function inlinePadBegin(quoteBars, interval, opts) {
const options = formatBeginEnd(opts);
if (!options.pad_begin) return Promise.resolve(options);
else return quoteBars({}, _.defaults({
interval: interval,
end: options.begin,
pad_end: 0
}, options)).then(bars => {
if (!bars.length) return options;
const start = _.sortedIndex(bars, {ending: options.begin}, 'ending');
const i = Math.max(start - options.pad_begin, 0);
return _.defaults({
pad_begin: Math.max(+options.pad_begin - start, 0),
begin: bars[i].ending
}, options);
});
} |
JavaScript | function formatBeginEnd(options) {
const tz = options.tz;
const now = moment.tz(options.now, tz);
const eod = moment(now).endOf('day');
const begin = options.begin ? moment.tz(options.begin, tz) : eod;
const oend = options.end && moment.tz(options.end, tz);
const end = !oend || eod.isBefore(oend) ? eod : oend; // limit end to end of today
const pad_begin = options.pad_begin ? +options.pad_begin :
options.begin ? 0 : 100;
const pad_end = end && options.pad_end || 0;
if (!begin.isValid())
throw Error("Begin date is not valid " + options.begin);
if (end && !end.isValid())
throw Error("End date is not valid " + options.end);
return _.defaults({
now: now.format(options.ending_format),
begin: begin.format(options.ending_format),
pad_begin: pad_begin,
end: end && end.format(options.ending_format),
pad_end: pad_end
}, options);
} | function formatBeginEnd(options) {
const tz = options.tz;
const now = moment.tz(options.now, tz);
const eod = moment(now).endOf('day');
const begin = options.begin ? moment.tz(options.begin, tz) : eod;
const oend = options.end && moment.tz(options.end, tz);
const end = !oend || eod.isBefore(oend) ? eod : oend; // limit end to end of today
const pad_begin = options.pad_begin ? +options.pad_begin :
options.begin ? 0 : 100;
const pad_end = end && options.pad_end || 0;
if (!begin.isValid())
throw Error("Begin date is not valid " + options.begin);
if (end && !end.isValid())
throw Error("End date is not valid " + options.end);
return _.defaults({
now: now.format(options.ending_format),
begin: begin.format(options.ending_format),
pad_begin: pad_begin,
end: end && end.format(options.ending_format),
pad_end: pad_end
}, options);
} |
JavaScript | function inlinePadEnd(quoteBars, interval, options) {
if (!options.pad_end) return Promise.resolve(options);
else return quoteBars({}, _.defaults({
interval: interval,
pad_begin: 0,
begin: options.end
}, options)).then(bars => {
if (!bars.length) return options;
const idx = _.sortedIndex(bars, {ending: options.end}, 'ending');
const start = idx && bars[idx].ending == options.end ? idx : idx -1;
const i = Math.min(start + options.pad_end, bars.length-1);
return _.defaults({
pad_end: Math.max(+options.pad_end + start - i, 0),
end: bars[i].ending
}, options);
});
} | function inlinePadEnd(quoteBars, interval, options) {
if (!options.pad_end) return Promise.resolve(options);
else return quoteBars({}, _.defaults({
interval: interval,
pad_begin: 0,
begin: options.end
}, options)).then(bars => {
if (!bars.length) return options;
const idx = _.sortedIndex(bars, {ending: options.end}, 'ending');
const start = idx && bars[idx].ending == options.end ? idx : idx -1;
const i = Math.min(start + options.pad_end, bars.length-1);
return _.defaults({
pad_end: Math.max(+options.pad_end + start - i, 0),
end: bars[i].ending
}, options);
});
} |
JavaScript | function mergeBars(quoteBars, exprMap, criteria, options) {
const intervals = _.keys(exprMap);
return intervals.reduceRight((promise, interval) => {
return promise.then(signals => Promise.all(signals.map(signal => {
const entry = signal.points ? _.first(signal.points) : {ending: options.begin};
const end = signal.exit ? signal.exit.ending : options.end;
const opts = _.defaults({
interval: interval,
begin: options.begin < entry.ending ? entry.ending : options.begin,
end: options.end && options.end < end ? options.end : end && end
}, options);
return quoteBars(exprMap[interval], opts)
.then(bars => createPoints(bars, opts))
.then(intraday => {
const points = signal.points ? signal.points.slice(0) : [];
if (signal.exit) points.push(signal.exit);
points.reduceRight((stop, point, idx) => {
const start = _.sortedIndex(intraday, point, 'ending');
const lt = start < intraday.length;
const last = idx == points.length-1;
if (start > 0 && lt && intraday[start].ending != point.ending || !lt && !last) {
const item = _.defaults({ending: point.ending}, intraday[start -1]);
intraday.splice(start, 0, item);
stop++;
}
for (let j=start; j<stop; j++) {
_.defaults(intraday[j], point);
}
return start;
}, intraday.length);
return intraday;
}).then(points => readSignals(points, entry, signal.exit, criteria[interval]));
}))).then(signalsMap => {
return signalsMap.reduce((result, signals) => {
while (result.length && signals.length && _.first(_.first(signals).points).ending <= _.last(_.last(result).points).ending) {
// remove overlap
if (_.first(signals).points.length == 1) signals.shift();
else _.first(signals).points.shift();
}
return result.concat(signals);
}, []);
});
}, Promise.resolve([{}])).then(signals => {
if (signals.length && options.begin > _.first(_.first(signals).points).ending) {
if (_.first(signals).points.length == 1) signals.shift();
else _.first(signals).points = _.first(signals).points.slice(1);
}
return signals.reduce((points, signal) => {
return points.concat(signal.points);
}, []);
});
} | function mergeBars(quoteBars, exprMap, criteria, options) {
const intervals = _.keys(exprMap);
return intervals.reduceRight((promise, interval) => {
return promise.then(signals => Promise.all(signals.map(signal => {
const entry = signal.points ? _.first(signal.points) : {ending: options.begin};
const end = signal.exit ? signal.exit.ending : options.end;
const opts = _.defaults({
interval: interval,
begin: options.begin < entry.ending ? entry.ending : options.begin,
end: options.end && options.end < end ? options.end : end && end
}, options);
return quoteBars(exprMap[interval], opts)
.then(bars => createPoints(bars, opts))
.then(intraday => {
const points = signal.points ? signal.points.slice(0) : [];
if (signal.exit) points.push(signal.exit);
points.reduceRight((stop, point, idx) => {
const start = _.sortedIndex(intraday, point, 'ending');
const lt = start < intraday.length;
const last = idx == points.length-1;
if (start > 0 && lt && intraday[start].ending != point.ending || !lt && !last) {
const item = _.defaults({ending: point.ending}, intraday[start -1]);
intraday.splice(start, 0, item);
stop++;
}
for (let j=start; j<stop; j++) {
_.defaults(intraday[j], point);
}
return start;
}, intraday.length);
return intraday;
}).then(points => readSignals(points, entry, signal.exit, criteria[interval]));
}))).then(signalsMap => {
return signalsMap.reduce((result, signals) => {
while (result.length && signals.length && _.first(_.first(signals).points).ending <= _.last(_.last(result).points).ending) {
// remove overlap
if (_.first(signals).points.length == 1) signals.shift();
else _.first(signals).points.shift();
}
return result.concat(signals);
}, []);
});
}, Promise.resolve([{}])).then(signals => {
if (signals.length && options.begin > _.first(_.first(signals).points).ending) {
if (_.first(signals).points.length == 1) signals.shift();
else _.first(signals).points = _.first(signals).points.slice(1);
}
return signals.reduce((points, signal) => {
return points.concat(signal.points);
}, []);
});
} |
JavaScript | async function readSignals(points, entry, exit, criteria) {
if (!points.length) return [];
const check = interrupt();
let start = _.sortedIndex(points, entry, 'ending');
if (start > 0 && (start == points.length || entry.ending < points[start].ending))
start--;
if (!criteria && exit) return [{
points: points.slice(start, points.length -1),
exit: _.last(points)
}];
else if (!criteria) return [{
points: points.slice(start)
}];
let e = 0;
const signals = [];
criteria = criteria || _.constant(true);
await points.slice(start).reduce(async(pactive, point, i) => {
await check();
const active = await pactive;
const to = start + i;
const keep = criteria(points.slice(active ? e : to, to+1)) ||
active && e != to && criteria(points.slice(to, to+1));
if (keep) {
if (active) { // extend
_.last(signals).points = points.slice(start + e, start + i +1);
} else { // reset
e = i;
signals.push({points: [point]});
}
} else if (active) {
_.last(signals).exit = point;
}
return keep;
}, Promise.resolve(false));
if (exit && signals.length && !_.last(signals).exit) {
if (_.last(_.last(signals).points).ending < exit.ending) _.last(signals).exit = exit;
else if (_.last(signals).points.length == 1) signals.pop();
else _.last(signals).exit = _.last(signals).points.pop();
}
return signals;
} | async function readSignals(points, entry, exit, criteria) {
if (!points.length) return [];
const check = interrupt();
let start = _.sortedIndex(points, entry, 'ending');
if (start > 0 && (start == points.length || entry.ending < points[start].ending))
start--;
if (!criteria && exit) return [{
points: points.slice(start, points.length -1),
exit: _.last(points)
}];
else if (!criteria) return [{
points: points.slice(start)
}];
let e = 0;
const signals = [];
criteria = criteria || _.constant(true);
await points.slice(start).reduce(async(pactive, point, i) => {
await check();
const active = await pactive;
const to = start + i;
const keep = criteria(points.slice(active ? e : to, to+1)) ||
active && e != to && criteria(points.slice(to, to+1));
if (keep) {
if (active) { // extend
_.last(signals).points = points.slice(start + e, start + i +1);
} else { // reset
e = i;
signals.push({points: [point]});
}
} else if (active) {
_.last(signals).exit = point;
}
return keep;
}, Promise.resolve(false));
if (exit && signals.length && !_.last(signals).exit) {
if (_.last(_.last(signals).points).ending < exit.ending) _.last(signals).exit = exit;
else if (_.last(signals).points.length == 1) signals.pop();
else _.last(signals).exit = _.last(signals).points.pop();
}
return signals;
} |
JavaScript | function fetchBars(fetch, db, fields, expressions, options) {
const warmUpLength = _.max(_.pluck(_.values(expressions), 'warmUpLength').concat([0]));
const name = getCollectionName(options);
return db.collection(name).then(collection => {
return readBlocks(fetch, fields, collection, warmUpLength, expressions, options)
.then(tables => trimTables(tables, options));
}).catch(err => {
if (!options.offline && !options.read_only) throw err;
else return db.flushCache().then(() => {
throw Error("Couldn't read needed data, try again without offline/read_only flag " + err.message);
});
});
} | function fetchBars(fetch, db, fields, expressions, options) {
const warmUpLength = _.max(_.pluck(_.values(expressions), 'warmUpLength').concat([0]));
const name = getCollectionName(options);
return db.collection(name).then(collection => {
return readBlocks(fetch, fields, collection, warmUpLength, expressions, options)
.then(tables => trimTables(tables, options));
}).catch(err => {
if (!options.offline && !options.read_only) throw err;
else return db.flushCache().then(() => {
throw Error("Couldn't read needed data, try again without offline/read_only flag " + err.message);
});
});
} |
JavaScript | function fetchNeededBlocks(fetch, fields, collection, warmUpLength, start, stop, now, options) {
const blocks = getBlocks(warmUpLength, start, stop, options.transient, options);
const future = !stop.isBefore(now);
const current = future || _.last(getBlocks(warmUpLength, now, now, false, options));
const latest = future || _.contains(blocks, current);
if (options.offline || !blocks.length) return Promise.resolve(blocks);
else return collection.lockWith(blocks, blocks => {
const store_ver = getStorageVersion(collection);
return fetchBlocks(fetch, fields, options, collection, store_ver, stop.format(), now, blocks, latest);
});
} | function fetchNeededBlocks(fetch, fields, collection, warmUpLength, start, stop, now, options) {
const blocks = getBlocks(warmUpLength, start, stop, options.transient, options);
const future = !stop.isBefore(now);
const current = future || _.last(getBlocks(warmUpLength, now, now, false, options));
const latest = future || _.contains(blocks, current);
if (options.offline || !blocks.length) return Promise.resolve(blocks);
else return collection.lockWith(blocks, blocks => {
const store_ver = getStorageVersion(collection);
return fetchBlocks(fetch, fields, options, collection, store_ver, stop.format(), now, blocks, latest);
});
} |
JavaScript | function readComputedBlocks(collection, warmUpLength, blocks, begin, expressions, options) {
const check = interrupt();
if (_.isEmpty(expressions))
return Promise.all(blocks.map(block => collection.readFrom(block)));
const dataPoints = _.object(blocks, []);
return collection.lockWith(blocks, blocks => blocks.reduce((promise, block, i, blocks) => {
const last = _.last(collection.tailOf(block));
if (!last || begin > last.ending)
return promise; // warmUp blocks are not evaluated
const missing = _.difference(_.keys(expressions), collection.columnsOf(block));
if (!missing.length) return promise;
else if (options.read_only && !options.transient)
throw Error("Missing " + _.first(missing) + " try again without the read_only flag");
return promise.then(dataBlocks => {
const warmUpBlocks = blocks.slice(0, i);
warmUpBlocks.forEach(block => {
if (!dataBlocks[block])
dataBlocks[block] = collection.readFrom(block);
});
if (!dataBlocks[block])
dataBlocks[block] = collection.readFrom(block);
return Promise.all(blocks.slice(0, i+1).map(block => {
if (dataPoints[block]) return dataPoints[block];
else return dataPoints[block] = dataBlocks[block].then(bars => createPoints(bars, options));
})).then(async(results) => {
const dataSize = results.reduce((size,result) => size + result.length, 0);
const warmUpRecords = dataSize - _.last(results).length;
const bars = await Promise.all(_.last(results).map(async(point, i, points) => {
let bar = point[options.interval];
if (options.transient) {
if (points[i+1] && points[i+1].ending < options.begin)
return bar;
if (options.end && points[i-1] && points[i-1].ending > options.end)
return bar;
bar = _.clone(bar);
}
const ret = _.extend(bar, _.object(missing, missing.map(expr => {
const end = warmUpRecords + i;
const start = Math.max(end - expressions[expr].warmUpLength, 0);
return expressions[expr](flattenSlice(results, start, end+1));
})));
await check();
return ret;
}));
dataBlocks[block] = bars;
await check();
return collection.writeTo(bars, block).then(() => {
const value = collection.propertyOf(block, 'warmUpBlocks') || [];
const blocks = _.union(value, warmUpBlocks).sort();
return collection.propertyOf(block, 'warmUpBlocks', blocks);
}).then(() => dataBlocks);
});
});
}, Promise.resolve(_.object(blocks, [])))).then(dataBlocks => {
return Promise.all(blocks.map(block => dataBlocks[block] || collection.readFrom(block)));
});
} | function readComputedBlocks(collection, warmUpLength, blocks, begin, expressions, options) {
const check = interrupt();
if (_.isEmpty(expressions))
return Promise.all(blocks.map(block => collection.readFrom(block)));
const dataPoints = _.object(blocks, []);
return collection.lockWith(blocks, blocks => blocks.reduce((promise, block, i, blocks) => {
const last = _.last(collection.tailOf(block));
if (!last || begin > last.ending)
return promise; // warmUp blocks are not evaluated
const missing = _.difference(_.keys(expressions), collection.columnsOf(block));
if (!missing.length) return promise;
else if (options.read_only && !options.transient)
throw Error("Missing " + _.first(missing) + " try again without the read_only flag");
return promise.then(dataBlocks => {
const warmUpBlocks = blocks.slice(0, i);
warmUpBlocks.forEach(block => {
if (!dataBlocks[block])
dataBlocks[block] = collection.readFrom(block);
});
if (!dataBlocks[block])
dataBlocks[block] = collection.readFrom(block);
return Promise.all(blocks.slice(0, i+1).map(block => {
if (dataPoints[block]) return dataPoints[block];
else return dataPoints[block] = dataBlocks[block].then(bars => createPoints(bars, options));
})).then(async(results) => {
const dataSize = results.reduce((size,result) => size + result.length, 0);
const warmUpRecords = dataSize - _.last(results).length;
const bars = await Promise.all(_.last(results).map(async(point, i, points) => {
let bar = point[options.interval];
if (options.transient) {
if (points[i+1] && points[i+1].ending < options.begin)
return bar;
if (options.end && points[i-1] && points[i-1].ending > options.end)
return bar;
bar = _.clone(bar);
}
const ret = _.extend(bar, _.object(missing, missing.map(expr => {
const end = warmUpRecords + i;
const start = Math.max(end - expressions[expr].warmUpLength, 0);
return expressions[expr](flattenSlice(results, start, end+1));
})));
await check();
return ret;
}));
dataBlocks[block] = bars;
await check();
return collection.writeTo(bars, block).then(() => {
const value = collection.propertyOf(block, 'warmUpBlocks') || [];
const blocks = _.union(value, warmUpBlocks).sort();
return collection.propertyOf(block, 'warmUpBlocks', blocks);
}).then(() => dataBlocks);
});
});
}, Promise.resolve(_.object(blocks, [])))).then(dataBlocks => {
return Promise.all(blocks.map(block => dataBlocks[block] || collection.readFrom(block)));
});
} |
JavaScript | function createPoints(bars, options) {
return bars.map(bar => ({
ending: bar.ending,
symbol: options.symbol,
market: options.market,
[options.interval]: bar
}));
} | function createPoints(bars, options) {
return bars.map(bar => ({
ending: bar.ending,
symbol: options.symbol,
market: options.market,
[options.interval]: bar
}));
} |
JavaScript | function trimTables(tables, options) {
const begin = parseBegin(new Periods(options), options).format(options.ending_format);
const dataset = tables.filter(table => table.length);
if (!dataset.length) return [];
while (dataset.length > 1 && _.first(dataset[1]).ending < begin) {
dataset.shift();
}
let bars = _.flatten(dataset, true);
if (!bars.length) return bars;
const formatB = options.begin;
let from = _.sortedIndex(bars, {ending: formatB}, 'ending');
if (from == bars.length || from > 0 && formatB < bars[from].ending)
from--; // include prior value for criteria
const start = Math.min(Math.max(from - options.pad_begin, 0), bars.length -1);
bars = bars.slice(start);
if (!bars.length || !options.end) return bars;
const formatE = options.end;
let to = _.sortedIndex(bars, {ending: formatE}, 'ending');
if (to < bars.length && formatE != bars[to].ending) to--;
const stop = Math.min(Math.max(to + options.pad_end +1, 0), bars.length);
return bars.slice(0, stop);
} | function trimTables(tables, options) {
const begin = parseBegin(new Periods(options), options).format(options.ending_format);
const dataset = tables.filter(table => table.length);
if (!dataset.length) return [];
while (dataset.length > 1 && _.first(dataset[1]).ending < begin) {
dataset.shift();
}
let bars = _.flatten(dataset, true);
if (!bars.length) return bars;
const formatB = options.begin;
let from = _.sortedIndex(bars, {ending: formatB}, 'ending');
if (from == bars.length || from > 0 && formatB < bars[from].ending)
from--; // include prior value for criteria
const start = Math.min(Math.max(from - options.pad_begin, 0), bars.length -1);
bars = bars.slice(start);
if (!bars.length || !options.end) return bars;
const formatE = options.end;
let to = _.sortedIndex(bars, {ending: formatE}, 'ending');
if (to < bars.length && formatE != bars[to].ending) to--;
const stop = Math.min(Math.max(to + options.pad_end +1, 0), bars.length);
return bars.slice(0, stop);
} |
JavaScript | async function formatColumns(fields, points, options) {
if (!points.length) return [];
const props = _.mapObject(_.pick(_.first(points), _.isObject), _.keys);
const fieldCols = _.mapObject(props, (props, interval) => {
const keys = props.filter(field => field.match(/^\w+$/));
const values = keys.map(field => interval + '.' + field);
return _.object(keys, values);
}); // {interval: {field: "$interval.$field"}}
const columns = options.columns ? options.columns :
_.size(props) == 1 ? _.first(_.values(fieldCols)) :
_.reduce(fieldCols, (map, fieldCols) => {
return _.defaults(map, _.object(_.values(fieldCols), _.values(fieldCols)));
}, {});
const map = await createParser(fields, props, options).parse(_.mapObject(columns, valOrNull));
return points.map(point => _.mapObject(map, expr => expr([point])));
} | async function formatColumns(fields, points, options) {
if (!points.length) return [];
const props = _.mapObject(_.pick(_.first(points), _.isObject), _.keys);
const fieldCols = _.mapObject(props, (props, interval) => {
const keys = props.filter(field => field.match(/^\w+$/));
const values = keys.map(field => interval + '.' + field);
return _.object(keys, values);
}); // {interval: {field: "$interval.$field"}}
const columns = options.columns ? options.columns :
_.size(props) == 1 ? _.first(_.values(fieldCols)) :
_.reduce(fieldCols, (map, fieldCols) => {
return _.defaults(map, _.object(_.values(fieldCols), _.values(fieldCols)));
}, {});
const map = await createParser(fields, props, options).parse(_.mapObject(columns, valOrNull));
return points.map(point => _.mapObject(map, expr => expr([point])));
} |
JavaScript | function fetchBlocks(fetch, fields, options, collection, store_ver, stop, now, blocks, latest_blocks) {
const cmsg = "Incomplete data try again without the read_only flag";
const pmsg = "or without the read_only flag";
const fetchComplete = options.read_only ? () => Promise.reject(Error(cmsg)) :
fetchCompleteBlock.bind(this, fetch, options, collection, store_ver, now);
const fetchPartial = options.read_only ? () => Promise.reject(Error(pmsg)) :
fetchPartialBlock.bind(this, fetch, fields, options, collection, now);
return Promise.all(blocks.map((block, i, blocks) => {
const latest = i == blocks.length -1 && latest_blocks;
if (!collection.exists(block))
return fetchComplete(block, latest);
if (collection.propertyOf(block, 'ending_format') != options.ending_format ||
collection.propertyOf(block, 'version') != store_ver ||
collection.propertyOf(block, 'salt') != options.salt ||
collection.propertyOf(block, 'tz') != options.tz)
return fetchComplete(block, latest);
const tail = collection.tailOf(block);
if (collection.propertyOf(block, 'complete'))
return; // no need to update complete blocks
if (!collection.sizeOf(block))
return fetchComplete(block, latest);
if (options.update || i < blocks.length -1 || (_.last(tail).asof || _.last(tail).ending) <= stop) {
if (!options.update && isMarketClosed(_.last(tail), now, options)) return;
if (!now.isAfter(collection.propertyOf(block, 'asof') || _.last(tail).ending))
return; // already updated it
return fetchPartial(block, _.first(tail).ending, latest).catch(error => {
if (stop) logger.debug("Need to fetch", _.last(tail).ending);
logger.trace("Fetch failed", error);
throw Error(`Fetch failed in ${collection.filenameOf(block)} try using the offline flag: ${error.message}`);
});
}
})).then(results => {
if (!_.contains(results, 'incompatible')) return blocks;
logger.log("Replacing all stored quotes for", options.symbol, options.market);
const store_ver = createStorageVersion();
return fetchBlocks(fetch, fields, options, collection, store_ver, stop, now, blocks, latest_blocks);
});
} | function fetchBlocks(fetch, fields, options, collection, store_ver, stop, now, blocks, latest_blocks) {
const cmsg = "Incomplete data try again without the read_only flag";
const pmsg = "or without the read_only flag";
const fetchComplete = options.read_only ? () => Promise.reject(Error(cmsg)) :
fetchCompleteBlock.bind(this, fetch, options, collection, store_ver, now);
const fetchPartial = options.read_only ? () => Promise.reject(Error(pmsg)) :
fetchPartialBlock.bind(this, fetch, fields, options, collection, now);
return Promise.all(blocks.map((block, i, blocks) => {
const latest = i == blocks.length -1 && latest_blocks;
if (!collection.exists(block))
return fetchComplete(block, latest);
if (collection.propertyOf(block, 'ending_format') != options.ending_format ||
collection.propertyOf(block, 'version') != store_ver ||
collection.propertyOf(block, 'salt') != options.salt ||
collection.propertyOf(block, 'tz') != options.tz)
return fetchComplete(block, latest);
const tail = collection.tailOf(block);
if (collection.propertyOf(block, 'complete'))
return; // no need to update complete blocks
if (!collection.sizeOf(block))
return fetchComplete(block, latest);
if (options.update || i < blocks.length -1 || (_.last(tail).asof || _.last(tail).ending) <= stop) {
if (!options.update && isMarketClosed(_.last(tail), now, options)) return;
if (!now.isAfter(collection.propertyOf(block, 'asof') || _.last(tail).ending))
return; // already updated it
return fetchPartial(block, _.first(tail).ending, latest).catch(error => {
if (stop) logger.debug("Need to fetch", _.last(tail).ending);
logger.trace("Fetch failed", error);
throw Error(`Fetch failed in ${collection.filenameOf(block)} try using the offline flag: ${error.message}`);
});
}
})).then(results => {
if (!_.contains(results, 'incompatible')) return blocks;
logger.log("Replacing all stored quotes for", options.symbol, options.market);
const store_ver = createStorageVersion();
return fetchBlocks(fetch, fields, options, collection, store_ver, stop, now, blocks, latest_blocks);
});
} |
JavaScript | async function fetchCompleteBlock(fetch, options, collection, store_ver, now, block, latest) {
const records = await fetch(blockOptions(block, options));
await collection.replaceWith(records, block);
await collection.propertyOf(block, 'complete', !latest);
await collection.propertyOf(block, 'version', store_ver);
await collection.propertyOf(block, 'tz', options.tz);
await collection.propertyOf(block, 'salt', options.salt);
await collection.propertyOf(block, 'ending_format', options.ending_format);
await collection.propertyOf(block, 'asof', now.format(options.ending_format));
} | async function fetchCompleteBlock(fetch, options, collection, store_ver, now, block, latest) {
const records = await fetch(blockOptions(block, options));
await collection.replaceWith(records, block);
await collection.propertyOf(block, 'complete', !latest);
await collection.propertyOf(block, 'version', store_ver);
await collection.propertyOf(block, 'tz', options.tz);
await collection.propertyOf(block, 'salt', options.salt);
await collection.propertyOf(block, 'ending_format', options.ending_format);
await collection.propertyOf(block, 'asof', now.format(options.ending_format));
} |
JavaScript | function blockOptions(block, options) {
const m = options.interval.match(/^m(\d+)$/);
if (block == options.interval) {
const begin = moment.tz('1990-01-01', options.tz);
return _.defaults({
begin: begin.format(options.ending_format),
end: null
}, options);
} else if ('day' == options.interval) {
const begin = moment.tz(block + '-01-01', options.tz);
const end = moment.tz((5+block) + '-01-01', options.tz);
return _.defaults({
begin: begin.format(options.ending_format),
end: end.format(options.ending_format)
}, options);
} else if (+m[1] >= 15) {
const begin = moment.tz(block + '-01', options.tz);
const end = moment(begin).add(1, 'months');
return _.defaults({
begin: begin.format(options.ending_format),
end: end.format(options.ending_format)
}, options);
} else if (+m[1] >= 5) {
const split = block.split('-');
const year = split[0];
const week = +split[1];
const begin = moment.tz(year + '-01-01', options.tz).week(week).startOf('week');
const end = moment(begin).add(1, 'week');
return _.defaults({
begin: begin.format(options.ending_format),
end: end.format(options.ending_format)
}, options);
} else {
const begin = moment.tz(block, options.tz);
const end = moment(begin).add(1, 'day');
return _.defaults({
begin: begin.format(options.ending_format),
end: end.format(options.ending_format)
}, options);
}
} | function blockOptions(block, options) {
const m = options.interval.match(/^m(\d+)$/);
if (block == options.interval) {
const begin = moment.tz('1990-01-01', options.tz);
return _.defaults({
begin: begin.format(options.ending_format),
end: null
}, options);
} else if ('day' == options.interval) {
const begin = moment.tz(block + '-01-01', options.tz);
const end = moment.tz((5+block) + '-01-01', options.tz);
return _.defaults({
begin: begin.format(options.ending_format),
end: end.format(options.ending_format)
}, options);
} else if (+m[1] >= 15) {
const begin = moment.tz(block + '-01', options.tz);
const end = moment(begin).add(1, 'months');
return _.defaults({
begin: begin.format(options.ending_format),
end: end.format(options.ending_format)
}, options);
} else if (+m[1] >= 5) {
const split = block.split('-');
const year = split[0];
const week = +split[1];
const begin = moment.tz(year + '-01-01', options.tz).week(week).startOf('week');
const end = moment(begin).add(1, 'week');
return _.defaults({
begin: begin.format(options.ending_format),
end: end.format(options.ending_format)
}, options);
} else {
const begin = moment.tz(block, options.tz);
const end = moment(begin).add(1, 'day');
return _.defaults({
begin: begin.format(options.ending_format),
end: end.format(options.ending_format)
}, options);
}
} |
JavaScript | function helpSettings() {
return [{
name: 'broker',
usage: 'broker(settings)',
description: "Information needed to identify the broker account",
options: {
account: {
usage: '<string>',
description: "IB account and/or model"
},
transmit: {
usage: 'true|false',
description: "If the system should transmit orders automatically for execution, otherwise wait for manual transmition via TWS user interface"
},
local_accounts: {
usage: '[<stirng>,...]',
description: "An array of accounts that can be used with this broker"
}
}
}];
} | function helpSettings() {
return [{
name: 'broker',
usage: 'broker(settings)',
description: "Information needed to identify the broker account",
options: {
account: {
usage: '<string>',
description: "IB account and/or model"
},
transmit: {
usage: 'true|false',
description: "If the system should transmit orders automatically for execution, otherwise wait for manual transmition via TWS user interface"
},
local_accounts: {
usage: '[<stirng>,...]',
description: "An array of accounts that can be used with this broker"
}
}
}];
} |
JavaScript | function helpOptions() {
const order_properties = {
quant: {
usage: '<positive-integer>',
description: "The number of shares or contracts to buy or sell"
},
order_type: {
usage: '<order-type>',
values: ['MKT', 'MIT', 'MOO', 'MOC', 'LMT', 'LOO', 'LOC', 'STP']
},
limit: {
usage: '<limit-price>',
descirption: "The limit price for orders of type LMT"
},
stop: {
usage: '<aux-price>',
description: "Stop limit price for STP orders"
},
offset: {
usage: '<price-offset>',
description: "Pegged and snap order offset"
},
tif: {
usage: '<time-in-forced>',
values: ['GTC', 'DAY', 'IOC']
},
extended_hours: {
usage: 'true',
values: ['true'],
description: "If set, Allows orders to also trigger or fill outside of regular trading hours."
},
condition: {
usage: 'symbol=<sym>;market=<mkt>;isMore=<true|false>;price=<number>;type=Price',
description: "TWS API OrderCondition objects with symbol/market instead of conId"
},
order_ref: {
usage: '<string>',
description: "The order identifier that is unique among working orders"
},
attach_ref: {
usage: '<string>',
description: "The order_ref of the parent order that must be filled before this order or a common identifier for orders in the same one-cancels-all (OCA) group."
},
attached: {
usage: '[{order},...]',
description: "Submit attached parent/child orders together or OCA group of orders"
},
symbol: {
usage: '<string>',
description: "The symbol of the contract to be traded, omit for OCA and bag orders"
},
market: {
usage: '<string>',
description: "The market of the contract (might also be the name of the exchange)"
},
security_type: {
values: ['STK', 'FUT', 'OPT']
},
currency: {
usage: '<string>',
values: ['EUR', 'GBP', 'AUD', 'NZD', 'USD', 'CAD', 'CHF', 'JPY']
},
multiplier: {
usage: '<number>',
description: "The value of a single unit of change in price"
},
minTick: {
usage: '<decimal>',
description: "The minimum increment at the current price level (used by SNAP STK)"
}
};
return Promise.resolve([{
name: 'balances',
usage: 'broker(options)',
description: "List a summary of current account balances",
properties: [
'asof', 'acctNumber', 'currency', 'rate',
'net', 'settled', 'accrued', 'realized', 'unrealized', 'margin'
],
options: {
action: {
usage: '<string>',
values: [
'balances'
]
},
now: {
usage: '<dateTime>',
description: "Overrides the system clock"
},
asof: {
usage: '<dateTime>',
description: "Currency balances at a particular point in time (if available)"
},
begin: {
usage: '<dateTime>',
description: "Include historic balances since given dateTime, but before given asof"
}
}
}, {
name: 'positions',
usage: 'broker(options)',
description: "List a summary of recent trades and their effect on the account position",
properties: [
'asof', 'acctNumber', 'action', 'quant', 'position', 'traded_at', 'traded_price', 'price',
'sales', 'purchases', 'dividend', 'commission', 'mtm', 'value',
'symbol', 'market', 'currency', 'security_type', 'multiplier',
'trading_class', 'industry', 'category', 'subcategory', 'under_symbol', 'under_market'
],
options: {
action: {
usage: '<string>',
values: [
'positions'
]
},
now: {
usage: '<dateTime>',
description: "Overrides the system clock"
},
asof: {
usage: '<dateTime>',
description: "Positions at a particular point in time (if available)"
},
begin: {
usage: '<dateTime>',
description: "Include historic balances since given dateTime, but before given asof"
}
}
}, {
name: 'orders',
usage: 'broker(options)',
description: "List a summary of open orders",
properties: [
'posted_at', 'asof', 'traded_at', 'action', 'quant', 'order_type', 'limit', 'stop', 'offset',
'traded_price', 'tif', 'extended_hours', 'status',
'order_ref', 'attach_ref', 'acctNumber',
'symbol', 'market', 'currency', 'security_type', 'multiplier',
'condition'
],
options: {
action: {
usage: '<string>',
values: [
'orders'
]
},
now: {
usage: '<dateTime>',
description: "Overrides the system clock"
},
asof: {
usage: '<dateTime>',
description: "Open orders at a particular point in time (if available)"
},
begin: {
usage: '<dateTime>',
description: "Include historic balances since given dateTime, but before given asof"
}
}
}, {
name: 'submit',
usage: 'broker(options)',
description: "Transmit order for trading",
properties: [
'posted_at', 'asof', 'action', 'quant', 'order_type', 'limit', 'stop', 'offset',
'tif', 'extended_hours', 'status',
'order_ref', 'attach_ref', 'symbol', 'market', 'security_type', 'currency', 'multiplier',
'condition'
],
options: {
action: {
usage: '<string>',
values: ['BUY', 'SELL', 'OCA']
},
...order_properties
}
}, {
name: 'cancel',
usage: 'broker(options)',
description: "Cancels a working order",
properties: [
'posted_at', 'asof', 'action', 'quant', 'order_type', 'limit', 'stop', 'offset',
'tif', 'extended_hours', 'status',
'order_ref', 'attach_ref', 'symbol', 'market', 'security_type', 'currency', 'multiplier',
'condition'
],
options: {
action: {
usage: '<string>',
values: ['cancel']
},
...order_properties
}
}, {
name: 'watch',
usage: 'broker(options)',
description: "Waits until a working order has changed from the given properties or a timeout",
properties: [
'posted_at', 'asof', 'action', 'quant', 'order_type', 'limit', 'stop', 'offset',
'tif', 'extended_hours', 'status',
'order_ref', 'attach_ref', 'symbol', 'market', 'security_type', 'currency', 'multiplier',
'condition'
],
options: {
action: {
usage: '<string>',
values: ['watch']
},
timeout: {
usage: '<milliseconds>',
description: "Number of milliseconds to wait for a working order to change"
},
status: {
usage: 'pending|working',
values: ['pending', 'working'],
description: "Stop watching order when order state is different from given"
},
..._.pick(order_properties, 'order_ref', 'quant', 'limit', 'stop', 'offset', 'tif')
}
}]);
} | function helpOptions() {
const order_properties = {
quant: {
usage: '<positive-integer>',
description: "The number of shares or contracts to buy or sell"
},
order_type: {
usage: '<order-type>',
values: ['MKT', 'MIT', 'MOO', 'MOC', 'LMT', 'LOO', 'LOC', 'STP']
},
limit: {
usage: '<limit-price>',
descirption: "The limit price for orders of type LMT"
},
stop: {
usage: '<aux-price>',
description: "Stop limit price for STP orders"
},
offset: {
usage: '<price-offset>',
description: "Pegged and snap order offset"
},
tif: {
usage: '<time-in-forced>',
values: ['GTC', 'DAY', 'IOC']
},
extended_hours: {
usage: 'true',
values: ['true'],
description: "If set, Allows orders to also trigger or fill outside of regular trading hours."
},
condition: {
usage: 'symbol=<sym>;market=<mkt>;isMore=<true|false>;price=<number>;type=Price',
description: "TWS API OrderCondition objects with symbol/market instead of conId"
},
order_ref: {
usage: '<string>',
description: "The order identifier that is unique among working orders"
},
attach_ref: {
usage: '<string>',
description: "The order_ref of the parent order that must be filled before this order or a common identifier for orders in the same one-cancels-all (OCA) group."
},
attached: {
usage: '[{order},...]',
description: "Submit attached parent/child orders together or OCA group of orders"
},
symbol: {
usage: '<string>',
description: "The symbol of the contract to be traded, omit for OCA and bag orders"
},
market: {
usage: '<string>',
description: "The market of the contract (might also be the name of the exchange)"
},
security_type: {
values: ['STK', 'FUT', 'OPT']
},
currency: {
usage: '<string>',
values: ['EUR', 'GBP', 'AUD', 'NZD', 'USD', 'CAD', 'CHF', 'JPY']
},
multiplier: {
usage: '<number>',
description: "The value of a single unit of change in price"
},
minTick: {
usage: '<decimal>',
description: "The minimum increment at the current price level (used by SNAP STK)"
}
};
return Promise.resolve([{
name: 'balances',
usage: 'broker(options)',
description: "List a summary of current account balances",
properties: [
'asof', 'acctNumber', 'currency', 'rate',
'net', 'settled', 'accrued', 'realized', 'unrealized', 'margin'
],
options: {
action: {
usage: '<string>',
values: [
'balances'
]
},
now: {
usage: '<dateTime>',
description: "Overrides the system clock"
},
asof: {
usage: '<dateTime>',
description: "Currency balances at a particular point in time (if available)"
},
begin: {
usage: '<dateTime>',
description: "Include historic balances since given dateTime, but before given asof"
}
}
}, {
name: 'positions',
usage: 'broker(options)',
description: "List a summary of recent trades and their effect on the account position",
properties: [
'asof', 'acctNumber', 'action', 'quant', 'position', 'traded_at', 'traded_price', 'price',
'sales', 'purchases', 'dividend', 'commission', 'mtm', 'value',
'symbol', 'market', 'currency', 'security_type', 'multiplier',
'trading_class', 'industry', 'category', 'subcategory', 'under_symbol', 'under_market'
],
options: {
action: {
usage: '<string>',
values: [
'positions'
]
},
now: {
usage: '<dateTime>',
description: "Overrides the system clock"
},
asof: {
usage: '<dateTime>',
description: "Positions at a particular point in time (if available)"
},
begin: {
usage: '<dateTime>',
description: "Include historic balances since given dateTime, but before given asof"
}
}
}, {
name: 'orders',
usage: 'broker(options)',
description: "List a summary of open orders",
properties: [
'posted_at', 'asof', 'traded_at', 'action', 'quant', 'order_type', 'limit', 'stop', 'offset',
'traded_price', 'tif', 'extended_hours', 'status',
'order_ref', 'attach_ref', 'acctNumber',
'symbol', 'market', 'currency', 'security_type', 'multiplier',
'condition'
],
options: {
action: {
usage: '<string>',
values: [
'orders'
]
},
now: {
usage: '<dateTime>',
description: "Overrides the system clock"
},
asof: {
usage: '<dateTime>',
description: "Open orders at a particular point in time (if available)"
},
begin: {
usage: '<dateTime>',
description: "Include historic balances since given dateTime, but before given asof"
}
}
}, {
name: 'submit',
usage: 'broker(options)',
description: "Transmit order for trading",
properties: [
'posted_at', 'asof', 'action', 'quant', 'order_type', 'limit', 'stop', 'offset',
'tif', 'extended_hours', 'status',
'order_ref', 'attach_ref', 'symbol', 'market', 'security_type', 'currency', 'multiplier',
'condition'
],
options: {
action: {
usage: '<string>',
values: ['BUY', 'SELL', 'OCA']
},
...order_properties
}
}, {
name: 'cancel',
usage: 'broker(options)',
description: "Cancels a working order",
properties: [
'posted_at', 'asof', 'action', 'quant', 'order_type', 'limit', 'stop', 'offset',
'tif', 'extended_hours', 'status',
'order_ref', 'attach_ref', 'symbol', 'market', 'security_type', 'currency', 'multiplier',
'condition'
],
options: {
action: {
usage: '<string>',
values: ['cancel']
},
...order_properties
}
}, {
name: 'watch',
usage: 'broker(options)',
description: "Waits until a working order has changed from the given properties or a timeout",
properties: [
'posted_at', 'asof', 'action', 'quant', 'order_type', 'limit', 'stop', 'offset',
'tif', 'extended_hours', 'status',
'order_ref', 'attach_ref', 'symbol', 'market', 'security_type', 'currency', 'multiplier',
'condition'
],
options: {
action: {
usage: '<string>',
values: ['watch']
},
timeout: {
usage: '<milliseconds>',
description: "Number of milliseconds to wait for a working order to change"
},
status: {
usage: 'pending|working',
values: ['pending', 'working'],
description: "Stop watching order when order state is different from given"
},
..._.pick(order_properties, 'order_ref', 'quant', 'limit', 'stop', 'offset', 'tif')
}
}]);
} |
JavaScript | function adj(bars) {
const last = _.last(bars);
if (!last || !last.adj_close) return bars;
const norm = +last.adj_close ? Big(last.close).div(last.adj_close || last.close) : 1;
return bars.map(bar => {
const scale = +bar.close ? Big(bar.adj_close || bar.close).div(bar.close).times(norm) : norm;
if (Big(scale).minus(1).abs().lt(0.0000001)) return bar;
else return _.defaults({
open: +Big(bar.open||0).times(scale),
high: +Big(bar.high||0).times(scale),
low: +Big(bar.low||0).times(scale),
close: +Big(bar.close||0).times(scale)
}, bar);
});
} | function adj(bars) {
const last = _.last(bars);
if (!last || !last.adj_close) return bars;
const norm = +last.adj_close ? Big(last.close).div(last.adj_close || last.close) : 1;
return bars.map(bar => {
const scale = +bar.close ? Big(bar.adj_close || bar.close).div(bar.close).times(norm) : norm;
if (Big(scale).minus(1).abs().lt(0.0000001)) return bar;
else return _.defaults({
open: +Big(bar.open||0).times(scale),
high: +Big(bar.high||0).times(scale),
low: +Big(bar.low||0).times(scale),
close: +Big(bar.close||0).times(scale)
}, bar);
});
} |
JavaScript | function helpSettings() {
return [{
name: 'broker',
usage: 'broker(settings)',
description: "Information needed to identify the broker account",
options: {
systemid: {
usage: '<integer>',
description: "The Collective2 system identifier"
},
c2_multipliers: {
usage: '{c2_symbol: <number>}',
description: "A hash of collective2 symbols to their Value 1 Pt (if not 1)"
}
}
}];
} | function helpSettings() {
return [{
name: 'broker',
usage: 'broker(settings)',
description: "Information needed to identify the broker account",
options: {
systemid: {
usage: '<integer>',
description: "The Collective2 system identifier"
},
c2_multipliers: {
usage: '{c2_symbol: <number>}',
description: "A hash of collective2 symbols to their Value 1 Pt (if not 1)"
}
}
}];
} |
JavaScript | function helpOptions() {
return Promise.resolve([{
name: 'balances',
usage: 'broker(options)',
description: "List a summary of current account balances",
properties: [
'asof', 'currency', 'rate', 'net'
],
options: {
action: {
usage: '<string>',
values: [
'balances'
]
},
asof: {
usage: '<dateTime>',
description: "The date and time of the balances to return"
},
begin: {
usage: '<dateTime>',
description: "Include summary of position changes since this dateTime"
}
}
}, {
name: 'positions',
usage: 'broker(options)',
description: "List a summary of recent trades and their effect on the account position",
properties: [
'asof', 'action', 'quant', 'position', 'traded_at', 'traded_price', 'price',
'sales', 'purchases', 'dividend', 'commission', 'mtm', 'value',
'symbol', 'market', 'currency', 'security_type', 'multiplier'
],
options: {
action: {
usage: '<string>',
values: [
'positions'
]
},
asof: {
usage: '<dateTime>',
description: "The date and time of the positions to return"
},
begin: {
usage: '<dateTime>',
description: "Include summary of position changes since this dateTime"
}
}
}, {
name: 'orders',
usage: 'broker(options)',
description: "List a summary of open orders",
properties: [
'posted_at', 'asof', 'action', 'quant', 'order_type', 'limit', 'stop', 'traded_price', 'tif', 'status',
'order_ref', 'attach_ref', 'symbol', 'market', 'currency', 'security_type', 'multiplier'
],
options: {
action: {
usage: '<string>',
values: [
'orders'
]
},
asof: {
usage: '<dateTime>',
description: "The date and time of workings orders to return"
},
begin: {
usage: '<dateTime>',
description: "Include summary of position changes since this dateTime"
}
}
}, {
name: 'submit',
usage: 'broker(options)',
description: "Transmit order for trading",
properties: [
'posted_at', 'asof', 'traded_at', 'action', 'quant', 'order_type', 'limit', 'stop', 'tif', 'status',
'order_ref', 'attach_ref', 'symbol', 'market', 'currency', 'security_type', 'multiplier'
],
options: {
action: {
usage: '<string>',
values: ['BUY', 'SELL', 'cancel']
},
traded_at: {
usage: '<dateTime>',
description: "The date and time of the collective2 parkUntil value"
},
quant: {
usage: '<positive-integer>',
description: "The number of shares or contracts to buy or sell"
},
order_type: {
usage: '<order-type>',
values: ['MKT', 'LMT', 'STP']
},
limit: {
usage: '<limit-price>',
descirption: "The limit price for orders of type LMT"
},
stop: {
usage: '<aux-price>',
description: "Stop limit price for STP orders"
},
tif: {
usage: '<time-in-forced>',
values: ['GTC', 'DAY', 'IOC']
},
order_ref: {
usage: '<string>',
description: "The order identifier that is unique among working orders"
},
attach_ref: {
usage: '<string>',
description: "The order_ref of the parent order that must be filled before this order"
},
attached: {
usage: '[...orders]',
description: "Submit attached parent/child orders together"
},
symbol: {
usage: '<string>',
description: "The symbol of the contract to be traded, omit for OCA and bag orders"
},
market: {
usage: '<string>',
description: "The market of the contract (might also be the name of the exchange)"
},
security_type: {
values: ['STK', 'FUT', 'OPT']
},
currency: {
usage: '<string>',
values: ['USD']
},
multiplier: {
usage: '<number>',
description: "The value of a single unit of change in price"
}
}
}]);
} | function helpOptions() {
return Promise.resolve([{
name: 'balances',
usage: 'broker(options)',
description: "List a summary of current account balances",
properties: [
'asof', 'currency', 'rate', 'net'
],
options: {
action: {
usage: '<string>',
values: [
'balances'
]
},
asof: {
usage: '<dateTime>',
description: "The date and time of the balances to return"
},
begin: {
usage: '<dateTime>',
description: "Include summary of position changes since this dateTime"
}
}
}, {
name: 'positions',
usage: 'broker(options)',
description: "List a summary of recent trades and their effect on the account position",
properties: [
'asof', 'action', 'quant', 'position', 'traded_at', 'traded_price', 'price',
'sales', 'purchases', 'dividend', 'commission', 'mtm', 'value',
'symbol', 'market', 'currency', 'security_type', 'multiplier'
],
options: {
action: {
usage: '<string>',
values: [
'positions'
]
},
asof: {
usage: '<dateTime>',
description: "The date and time of the positions to return"
},
begin: {
usage: '<dateTime>',
description: "Include summary of position changes since this dateTime"
}
}
}, {
name: 'orders',
usage: 'broker(options)',
description: "List a summary of open orders",
properties: [
'posted_at', 'asof', 'action', 'quant', 'order_type', 'limit', 'stop', 'traded_price', 'tif', 'status',
'order_ref', 'attach_ref', 'symbol', 'market', 'currency', 'security_type', 'multiplier'
],
options: {
action: {
usage: '<string>',
values: [
'orders'
]
},
asof: {
usage: '<dateTime>',
description: "The date and time of workings orders to return"
},
begin: {
usage: '<dateTime>',
description: "Include summary of position changes since this dateTime"
}
}
}, {
name: 'submit',
usage: 'broker(options)',
description: "Transmit order for trading",
properties: [
'posted_at', 'asof', 'traded_at', 'action', 'quant', 'order_type', 'limit', 'stop', 'tif', 'status',
'order_ref', 'attach_ref', 'symbol', 'market', 'currency', 'security_type', 'multiplier'
],
options: {
action: {
usage: '<string>',
values: ['BUY', 'SELL', 'cancel']
},
traded_at: {
usage: '<dateTime>',
description: "The date and time of the collective2 parkUntil value"
},
quant: {
usage: '<positive-integer>',
description: "The number of shares or contracts to buy or sell"
},
order_type: {
usage: '<order-type>',
values: ['MKT', 'LMT', 'STP']
},
limit: {
usage: '<limit-price>',
descirption: "The limit price for orders of type LMT"
},
stop: {
usage: '<aux-price>',
description: "Stop limit price for STP orders"
},
tif: {
usage: '<time-in-forced>',
values: ['GTC', 'DAY', 'IOC']
},
order_ref: {
usage: '<string>',
description: "The order identifier that is unique among working orders"
},
attach_ref: {
usage: '<string>',
description: "The order_ref of the parent order that must be filled before this order"
},
attached: {
usage: '[...orders]',
description: "Submit attached parent/child orders together"
},
symbol: {
usage: '<string>',
description: "The symbol of the contract to be traded, omit for OCA and bag orders"
},
market: {
usage: '<string>',
description: "The market of the contract (might also be the name of the exchange)"
},
security_type: {
values: ['STK', 'FUT', 'OPT']
},
currency: {
usage: '<string>',
values: ['USD']
},
multiplier: {
usage: '<number>',
description: "The value of a single unit of change in price"
}
}
}]);
} |
JavaScript | TOD(opts, calc) {
const dayLength = getDayLength(opts);
return _.extend(bars => {
if (_.isEmpty(bars))
return calc(bars);
const start = "2000-01-01T".length;
let step = Math.round(dayLength/2);
let last = bars.length -1;
const filtered = [_.last(bars)];
let suffix = _.last(bars).ending.substring(start);
while (filtered.length <= calc.warmUpLength) {
if (last >= step && bars[last - step].ending.substring(start) == suffix) {
filtered.push(bars[last - step]);
last -= step;
} else {
let idx, formatted;
const iter = moment.tz(bars[last].ending, opts.tz);
do {
iter.subtract(1, 'day');
formatted = iter.format(opts.ending_format);
idx = _.sortedIndex(bars, {ending: formatted}, 'ending');
} while (bars[idx].ending != formatted && formatted > bars[0].ending);
if (bars[idx].ending != formatted) break;
filtered.push(bars[idx]);
suffix = formatted.substring(start);
step = last - idx;
last = idx;
}
}
return calc(filtered.reverse());
}, {
fields: ['ending'],
warmUpLength: (calc.warmUpLength +1) * dayLength
});
} | TOD(opts, calc) {
const dayLength = getDayLength(opts);
return _.extend(bars => {
if (_.isEmpty(bars))
return calc(bars);
const start = "2000-01-01T".length;
let step = Math.round(dayLength/2);
let last = bars.length -1;
const filtered = [_.last(bars)];
let suffix = _.last(bars).ending.substring(start);
while (filtered.length <= calc.warmUpLength) {
if (last >= step && bars[last - step].ending.substring(start) == suffix) {
filtered.push(bars[last - step]);
last -= step;
} else {
let idx, formatted;
const iter = moment.tz(bars[last].ending, opts.tz);
do {
iter.subtract(1, 'day');
formatted = iter.format(opts.ending_format);
idx = _.sortedIndex(bars, {ending: formatted}, 'ending');
} while (bars[idx].ending != formatted && formatted > bars[0].ending);
if (bars[idx].ending != formatted) break;
filtered.push(bars[idx]);
suffix = formatted.substring(start);
step = last - idx;
last = idx;
}
}
return calc(filtered.reverse());
}, {
fields: ['ending'],
warmUpLength: (calc.warmUpLength +1) * dayLength
});
} |
JavaScript | function unregister(self) {
self.closed = true;
const idx = references.indexOf(self);
if (idx < 0) return Promise.resolve();
references.splice(idx, 1)
return instance_lock = instance_lock.catch(_.noop).then(() => {
if (references.length) return Promise.resolve();
else return releaseInstance();
});
} | function unregister(self) {
self.closed = true;
const idx = references.indexOf(self);
if (idx < 0) return Promise.resolve();
references.splice(idx, 1)
return instance_lock = instance_lock.catch(_.noop).then(() => {
if (references.length) return Promise.resolve();
else return releaseInstance();
});
} |
JavaScript | function sharedInstance(options, settings) {
last_used = elapsed_time;
if (shared_instance) return shared_instance(options);
else return instance_lock = instance_lock.catch(_.noop).then(() => {
if (shared_instance) return shared_instance(options);
shared_instance = createInstance(settings);
instance_timer = setInterval(() => {
if (last_used < elapsed_time++) {
releaseInstance().catch(logger.error);
}
}, settings.timeout || 600000).unref();
return shared_instance(options);
});
} | function sharedInstance(options, settings) {
last_used = elapsed_time;
if (shared_instance) return shared_instance(options);
else return instance_lock = instance_lock.catch(_.noop).then(() => {
if (shared_instance) return shared_instance(options);
shared_instance = createInstance(settings);
instance_timer = setInterval(() => {
if (last_used < elapsed_time++) {
releaseInstance().catch(logger.error);
}
}, settings.timeout || 600000).unref();
return shared_instance(options);
});
} |
JavaScript | function generatePage(dir, args) {
const handle = args[3];
const page = `${dir}/${handle}.js`;
if (fs.existsSync(page)) {
console.log(`${page} already exists`);
} else {
fs.writeFileSync(page, createPageTemplate(handle), err => {
if (err) throw err;
console.log(`${page} was successfully created!`);
});
}
} | function generatePage(dir, args) {
const handle = args[3];
const page = `${dir}/${handle}.js`;
if (fs.existsSync(page)) {
console.log(`${page} already exists`);
} else {
fs.writeFileSync(page, createPageTemplate(handle), err => {
if (err) throw err;
console.log(`${page} was successfully created!`);
});
}
} |
JavaScript | canRead(oh) {
var result = false;
try {
var parsed = this._parser.parse(oh);
if(parsed != null) {
result = true;
}
}
catch(e) {;}
return result;
} | canRead(oh) {
var result = false;
try {
var parsed = this._parser.parse(oh);
if(parsed != null) {
result = true;
}
}
catch(e) {;}
return result;
} |
JavaScript | addWeekday(wd) {
if(!this._weekdays.contains(wd) && !this._wdOver.contains(wd)) {
this._weekdays.push(wd);
this._weekdays = this._weekdays.sort();
}
} | addWeekday(wd) {
if(!this._weekdays.contains(wd) && !this._wdOver.contains(wd)) {
this._weekdays.push(wd);
this._weekdays = this._weekdays.sort();
}
} |
JavaScript | addOverwrittenWeekday(wd) {
if(!this._wdOver.contains(wd) && !this._weekdays.contains(wd)) {
this._wdOver.push(wd);
this._wdOver = this._wdOver.sort();
}
} | addOverwrittenWeekday(wd) {
if(!this._wdOver.contains(wd) && !this._weekdays.contains(wd)) {
this._wdOver.push(wd);
this._wdOver = this._wdOver.sort();
}
} |
JavaScript | _removeInterval(typical, weekdays, times) {
if(weekdays.from <= weekdays.to) {
for(let wd=weekdays.from; wd <= weekdays.to; wd++) {
this._removeIntervalWd(typical, times, wd);
}
}
else {
for(let wd=weekdays.from; wd <= 6; wd++) {
this._removeIntervalWd(typical, times, wd);
}
for(let wd=0; wd <= weekdays.to; wd++) {
this._removeIntervalWd(typical, times, wd);
}
}
} | _removeInterval(typical, weekdays, times) {
if(weekdays.from <= weekdays.to) {
for(let wd=weekdays.from; wd <= weekdays.to; wd++) {
this._removeIntervalWd(typical, times, wd);
}
}
else {
for(let wd=weekdays.from; wd <= 6; wd++) {
this._removeIntervalWd(typical, times, wd);
}
for(let wd=0; wd <= weekdays.to; wd++) {
this._removeIntervalWd(typical, times, wd);
}
}
} |
JavaScript | _removeIntervalWd(typical, times, wd) {
//Interval during day
if(times.to >= times.from) {
typical.removeInterval(
new Interval(wd, wd, times.from, times.to)
);
}
//Interval during night
else {
//Everyday except sunday
if(wd < 6) {
typical.removeInterval(
new Interval(wd, wd+1, times.from, times.to)
);
}
//Sunday
else {
typical.removeInterval(
new Interval(wd, wd, times.from, 24*60)
);
typical.removeInterval(
new Interval(0, 0, 0, times.to)
);
}
}
} | _removeIntervalWd(typical, times, wd) {
//Interval during day
if(times.to >= times.from) {
typical.removeInterval(
new Interval(wd, wd, times.from, times.to)
);
}
//Interval during night
else {
//Everyday except sunday
if(wd < 6) {
typical.removeInterval(
new Interval(wd, wd+1, times.from, times.to)
);
}
//Sunday
else {
typical.removeInterval(
new Interval(wd, wd, times.from, 24*60)
);
typical.removeInterval(
new Interval(0, 0, 0, times.to)
);
}
}
} |
JavaScript | _addInterval(typical, weekdays, times) {
//Check added interval are OK for days
if(typical instanceof Day) {
if(weekdays.from != 0 || (weekdays.to != 0 && times.from <= times.to)) {
weekdays = Object.assign({}, weekdays);
weekdays.from = 0;
weekdays.to = (times.from <= times.to) ? 0 : 1;
}
}
if(weekdays.from <= weekdays.to) {
for(let wd=weekdays.from; wd <= weekdays.to; wd++) {
this._addIntervalWd(typical, times, wd);
}
}
else {
for(let wd=weekdays.from; wd <= 6; wd++) {
this._addIntervalWd(typical, times, wd);
}
for(let wd=0; wd <= weekdays.to; wd++) {
this._addIntervalWd(typical, times, wd);
}
}
} | _addInterval(typical, weekdays, times) {
//Check added interval are OK for days
if(typical instanceof Day) {
if(weekdays.from != 0 || (weekdays.to != 0 && times.from <= times.to)) {
weekdays = Object.assign({}, weekdays);
weekdays.from = 0;
weekdays.to = (times.from <= times.to) ? 0 : 1;
}
}
if(weekdays.from <= weekdays.to) {
for(let wd=weekdays.from; wd <= weekdays.to; wd++) {
this._addIntervalWd(typical, times, wd);
}
}
else {
for(let wd=weekdays.from; wd <= 6; wd++) {
this._addIntervalWd(typical, times, wd);
}
for(let wd=0; wd <= weekdays.to; wd++) {
this._addIntervalWd(typical, times, wd);
}
}
} |
JavaScript | _addIntervalWd(typical, times, wd) {
//Interval during day
if(times.to >= times.from) {
typical.addInterval(
new Interval(wd, wd, times.from, times.to)
);
}
//Interval during night
else {
//Everyday except sunday
if(wd < 6) {
typical.addInterval(
new Interval(wd, wd+1, times.from, times.to)
);
}
//Sunday
else {
typical.addInterval(
new Interval(wd, wd, times.from, 24*60)
);
typical.addInterval(
new Interval(0, 0, 0, times.to)
);
}
}
} | _addIntervalWd(typical, times, wd) {
//Interval during day
if(times.to >= times.from) {
typical.addInterval(
new Interval(wd, wd, times.from, times.to)
);
}
//Interval during night
else {
//Everyday except sunday
if(wd < 6) {
typical.addInterval(
new Interval(wd, wd+1, times.from, times.to)
);
}
//Sunday
else {
typical.addInterval(
new Interval(wd, wd, times.from, 24*60)
);
typical.addInterval(
new Interval(0, 0, 0, times.to)
);
}
}
} |
JavaScript | _tokenize(block) {
let result = block.trim().split(' ');
let position = result.indexOf("");
while( ~position ) {
result.splice(position, 1);
position = result.indexOf("");
}
return result;
} | _tokenize(block) {
let result = block.trim().split(' ');
let position = result.indexOf("");
while( ~position ) {
result.splice(position, 1);
position = result.indexOf("");
}
return result;
} |
JavaScript | removeIntervalsDuringDay(day) {
let interval, itLength = this._intervals.length, dayDiff;
for(let i=0; i < itLength; i++) {
interval = this._intervals[i];
if(interval != undefined) {
//If interval over given day
if(interval.getStartDay() <= day && interval.getEndDay() >= day) {
dayDiff = interval.getEndDay() - interval.getStartDay();
//Avoid deletion if over night interval
if(dayDiff > 1 || dayDiff == 0 || interval.getStartDay() == day || interval.getFrom() <= interval.getTo()) {
//Create new interval if several day
if(interval.getEndDay() - interval.getStartDay() >= 1 && interval.getFrom() <= interval.getTo()) {
if(interval.getStartDay() < day) {
this.addInterval(new Interval(interval.getStartDay(), day-1, interval.getFrom(), 24*60));
}
if(interval.getEndDay() > day) {
this.addInterval(new Interval(day+1, interval.getEndDay(), 0, interval.getTo()));
}
}
//Delete
this.removeInterval(i);
}
}
}
}
} | removeIntervalsDuringDay(day) {
let interval, itLength = this._intervals.length, dayDiff;
for(let i=0; i < itLength; i++) {
interval = this._intervals[i];
if(interval != undefined) {
//If interval over given day
if(interval.getStartDay() <= day && interval.getEndDay() >= day) {
dayDiff = interval.getEndDay() - interval.getStartDay();
//Avoid deletion if over night interval
if(dayDiff > 1 || dayDiff == 0 || interval.getStartDay() == day || interval.getFrom() <= interval.getTo()) {
//Create new interval if several day
if(interval.getEndDay() - interval.getStartDay() >= 1 && interval.getFrom() <= interval.getTo()) {
if(interval.getStartDay() < day) {
this.addInterval(new Interval(interval.getStartDay(), day-1, interval.getFrom(), 24*60));
}
if(interval.getEndDay() > day) {
this.addInterval(new Interval(day+1, interval.getEndDay(), 0, interval.getTo()));
}
}
//Delete
this.removeInterval(i);
}
}
}
}
} |
JavaScript | copyIntervals(intervals) {
this._intervals = [];
for(let i=0; i < intervals.length; i++) {
if(intervals[i] != undefined) {
this._intervals.push(intervals[i].clone());
}
}
} | copyIntervals(intervals) {
this._intervals = [];
for(let i=0; i < intervals.length; i++) {
if(intervals[i] != undefined) {
this._intervals.push(intervals[i].clone());
}
}
} |
JavaScript | day(startDay, startMonth, endDay, endMonth) {
if(startDay == null || startMonth == null) {
throw Error("Start day and month can't be null");
}
this._start = { day: startDay, month: startMonth };
this._end = (endDay != null && endMonth != null && (endDay != startDay || endMonth != startMonth)) ? { day: endDay, month: endMonth } : null;
this._type = "day";
return this;
} | day(startDay, startMonth, endDay, endMonth) {
if(startDay == null || startMonth == null) {
throw Error("Start day and month can't be null");
}
this._start = { day: startDay, month: startMonth };
this._end = (endDay != null && endMonth != null && (endDay != startDay || endMonth != startMonth)) ? { day: endDay, month: endMonth } : null;
this._type = "day";
return this;
} |
JavaScript | week(startWeek, endWeek) {
if(startWeek == null) {
throw Error("Start week can't be null");
}
this._start = { week: startWeek };
this._end = (endWeek != null && endWeek != startWeek) ? { week: endWeek } : null;
this._type = "week";
return this;
} | week(startWeek, endWeek) {
if(startWeek == null) {
throw Error("Start week can't be null");
}
this._start = { week: startWeek };
this._end = (endWeek != null && endWeek != startWeek) ? { week: endWeek } : null;
this._type = "week";
return this;
} |
JavaScript | month(startMonth, endMonth) {
if(startMonth == null) {
throw Error("Start month can't be null");
}
this._start = { month: startMonth };
this._end = (endMonth != null && endMonth != startMonth) ? { month: endMonth } : null;
this._type = "month";
return this;
} | month(startMonth, endMonth) {
if(startMonth == null) {
throw Error("Start month can't be null");
}
this._start = { month: startMonth };
this._end = (endMonth != null && endMonth != startMonth) ? { month: endMonth } : null;
this._type = "month";
return this;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.