21 using System.Collections.Generic;
31 public partial class QCAlgorithm
33 private readonly List<Func<IBaseData, decimal>> _quoteRequiredFields =
new() {
49 [Obsolete(
"Please use Settings.AutomaticIndicatorWarmUp")]
74 Resolution? resolution =
null, Func<IBaseData, TradeBar> selector =
null)
77 var accelerationBands =
new AccelerationBands(name, period, width, movingAverageType);
78 InitializeIndicator(accelerationBands, resolution, selector, symbol);
80 return accelerationBands;
95 InitializeIndicator(accumulationDistribution, resolution, selector, symbol);
97 return accumulationDistribution;
114 InitializeIndicator(accumulationDistributionOscillator, resolution, selector, symbol);
116 return accumulationDistributionOscillator;
132 public Alpha A(
Symbol target,
Symbol reference,
int alphaPeriod = 1,
int betaPeriod = 252,
Resolution? resolution =
null, decimal? riskFreeRate =
null, Func<IBaseData, IBaseDataBar> selector =
null)
134 var baseBame = riskFreeRate.HasValue ? $
"A({alphaPeriod},{betaPeriod},{riskFreeRate})" : $
"A({alphaPeriod},{betaPeriod})";
142 var alpha =
new Alpha(name, target, reference, alphaPeriod, betaPeriod, riskFreeRateModel);
143 InitializeIndicator(alpha, resolution, selector, target, reference);
161 InitializeIndicator(averageRange, resolution, selector, symbol);
178 Resolution? resolution =
null, Func<IBaseData, decimal> selector =
null)
180 var name =
CreateIndicatorName(symbol, $
"ARIMA({arOrder},{diffOrder},{maOrder},{period})", resolution);
182 InitializeIndicator(arimaIndicator, resolution, selector, symbol);
184 return arimaIndicator;
201 InitializeIndicator(averageDirectionalIndex, resolution, selector, symbol);
203 return averageDirectionalIndex;
218 var name =
CreateIndicatorName(symbol, $
"AO({fastPeriod},{slowPeriod},{type})", resolution);
219 var awesomeOscillator =
new AwesomeOscillator(name, fastPeriod, slowPeriod, type);
220 InitializeIndicator(awesomeOscillator, resolution, selector, symbol);
222 return awesomeOscillator;
238 InitializeIndicator(averageDirectionalMovementIndexRating, resolution, selector, symbol);
240 return averageDirectionalMovementIndexRating;
262 InitializeIndicator(arnaudLegouxMovingAverage, resolution, selector, symbol);
264 return arnaudLegouxMovingAverage;
282 InitializeIndicator(absolutePriceOscillator, resolution, selector, symbol);
284 return absolutePriceOscillator;
298 return AROON(symbol, period, period, resolution, selector);
315 InitializeIndicator(aroonOscillator, resolution, selector, symbol);
317 return aroonOscillator;
335 InitializeIndicator(averageTrueRange, resolution, selector, symbol);
337 return averageTrueRange;
354 InitializeIndicator(augenPriceSpike, resolution, selector, symbol);
356 return augenPriceSpike;
371 Resolution? resolution =
null, Func<IBaseData, decimal> selector =
null)
374 var bollingerBands =
new BollingerBands(name, period, k, movingAverageType);
375 InitializeIndicator(bollingerBands, resolution, selector, symbol);
377 return bollingerBands;
394 var beta =
new Beta(name, target, reference, period);
395 InitializeIndicator(beta, resolution, selector, target, reference);
413 InitializeIndicator(balanceOfPower, resolution, selector, symbol);
415 return balanceOfPower;
430 Func<IBaseData, decimal> selector =
null)
432 var name =
CreateIndicatorName(symbol, $
"CC({shortRocPeriod},{longRocPeriod},{lwmaPeriod})", resolution);
433 var coppockCurve =
new CoppockCurve(name, shortRocPeriod, longRocPeriod, lwmaPeriod);
434 InitializeIndicator(coppockCurve, resolution, selector, symbol);
454 var correlation =
new Correlation(name, target, reference, period, correlationType);
455 InitializeIndicator(correlation, resolution, selector, target, reference);
475 InitializeIndicator(commodityChannelIndex, resolution, selector, symbol);
477 return commodityChannelIndex;
494 InitializeIndicator(indicator, resolution, selector, symbol);
513 var name =
CreateIndicatorName(symbol, $
"CKS({atrPeriod},{atrMult},{period})", resolution);
514 var indicator =
new ChandeKrollStop(name, atrPeriod, atrMult, period, movingAverageType);
515 InitializeIndicator(indicator, resolution, selector, symbol);
532 InitializeIndicator(chaikinMoneyFlow, resolution, selector, symbol);
534 return chaikinMoneyFlow;
551 InitializeIndicator(chandeMomentumOscillator, resolution, selector, symbol);
553 return chandeMomentumOscillator;
571 var name =
CreateIndicatorName(symbol, $
"CRSI({rsiPeriod},{rsiPeriodStreak},{lookBackPeriod})", resolution);
573 InitializeIndicator(connorsRelativeStrengthIndex, resolution, selector, symbol);
574 return connorsRelativeStrengthIndex;
592 InitializeIndicator(deMarkerIndicator, resolution, selector, symbol);
593 return deMarkerIndicator;
606 [DocumentationAttribute(Indicators)]
610 var donchianChannel =
new DonchianChannel(name, upperPeriod, lowerPeriod);
611 InitializeIndicator(donchianChannel, resolution, selector, symbol);
613 return donchianChannel;
628 return DCH(symbol, period, period, resolution, selector);
644 public Delta D(
Symbol symbol,
Symbol mirrorOption =
null, decimal? riskFreeRate =
null, decimal? dividendYield =
null,
647 var name = InitializeOptionIndicator<Delta>(symbol, out var riskFreeRateModel, out var dividendYieldModel, riskFreeRate, dividendYield, optionModel, resolution);
649 var delta =
new Delta(name, symbol, riskFreeRateModel, dividendYieldModel, mirrorOption, optionModel, ivModel);
650 InitializeOptionIndicator(delta, resolution, symbol, mirrorOption);
670 return D(symbol, mirrorOption, riskFreeRate, dividendYield, optionModel, ivModel, resolution);
686 InitializeIndicator(doubleExponentialMovingAverage, resolution, selector, symbol);
688 return doubleExponentialMovingAverage;
703 public DerivativeOscillator DO(
Symbol symbol,
int rsiPeriod,
int smoothingRsiPeriod,
int doubleSmoothingRsiPeriod,
int signalLinePeriod,
Resolution? resolution =
null, Func<IBaseData, decimal> selector =
null)
705 var name =
CreateIndicatorName(symbol, $
"DO({rsiPeriod},{smoothingRsiPeriod},{doubleSmoothingRsiPeriod},{signalLinePeriod})", resolution);
706 var derivativeOscillator =
new DerivativeOscillator(name, rsiPeriod, smoothingRsiPeriod, doubleSmoothingRsiPeriod, signalLinePeriod);
707 InitializeIndicator(derivativeOscillator, resolution, selector, symbol);
709 return derivativeOscillator;
725 InitializeIndicator(detrendedPriceOscillator, resolution, selector, symbol);
727 return detrendedPriceOscillator;
760 InitializeIndicator(exponentialMovingAverage, resolution, selector, symbol);
762 return exponentialMovingAverage;
780 InitializeIndicator(easeOfMovementValue, resolution, selector, symbol);
782 return easeOfMovementValue;
797 var resolution = GetSubscription(symbol).
Resolution;
816 RegisterIndicator<IBaseData>(symbol, filteredIdentity, resolution, selector);
817 return filteredIdentity;
833 var name = Invariant($
"{symbol}({fieldName ?? "close
"}_{resolution})");
835 RegisterIndicator<IBaseData>(symbol, filteredIdentity,
ResolveConsolidator(symbol, resolution), selector);
836 return filteredIdentity;
853 var indicator =
new ForceIndex(name, period, type);
854 InitializeIndicator(indicator, resolution, selector, symbol);
873 InitializeIndicator(fisherTransform, resolution, selector, symbol);
875 return fisherTransform;
894 InitializeIndicator(fractalAdaptiveMovingAverage, resolution, selector, symbol);
896 return fractalAdaptiveMovingAverage;
912 public Gamma G(
Symbol symbol,
Symbol mirrorOption =
null, decimal? riskFreeRate =
null, decimal? dividendYield =
null,
915 var name = InitializeOptionIndicator<Gamma>(symbol, out var riskFreeRateModel, out var dividendYieldModel, riskFreeRate, dividendYield, optionModel, resolution);
917 var gamma =
new Gamma(name, symbol, riskFreeRateModel, dividendYieldModel, mirrorOption, optionModel, ivModel);
918 InitializeOptionIndicator(gamma, resolution, symbol, mirrorOption);
938 return G(symbol, mirrorOption, riskFreeRate, dividendYield, optionModel, ivModel, resolution);
953 InitializeIndicator(heikinAshi, resolution, selector, symbol);
974 InitializeIndicator(hurstExponent, resolution, selector, symbol);
975 return hurstExponent;
993 public HilbertTransform HT(
Symbol symbol,
int length, decimal inPhaseMultiplicationFactor, decimal quadratureMultiplicationFactor,
Resolution? resolution =
null, Func<IBaseData, decimal> selector =
null)
995 var name =
CreateIndicatorName(symbol, $
"HT({length}, {inPhaseMultiplicationFactor}, {quadratureMultiplicationFactor})", resolution);
996 var hilbertTransform =
new HilbertTransform(length, inPhaseMultiplicationFactor, quadratureMultiplicationFactor);
997 InitializeIndicator(hilbertTransform, resolution, selector, symbol);
999 return hilbertTransform;
1015 InitializeIndicator(hullMovingAverage, resolution, selector, symbol);
1017 return hullMovingAverage;
1033 InitializeIndicator(indicator, resolution, selector, symbol);
1054 int senkouADelayPeriod,
int senkouBDelayPeriod,
Resolution? resolution =
null, Func<IBaseData, TradeBar> selector =
null)
1056 var name =
CreateIndicatorName(symbol, $
"ICHIMOKU({tenkanPeriod},{kijunPeriod},{senkouAPeriod},{senkouBPeriod},{senkouADelayPeriod},{senkouBDelayPeriod})", resolution);
1057 var ichimokuKinkoHyo =
new IchimokuKinkoHyo(name, tenkanPeriod, kijunPeriod, senkouAPeriod, senkouBPeriod, senkouADelayPeriod, senkouBDelayPeriod);
1058 InitializeIndicator(ichimokuKinkoHyo, resolution, selector, symbol);
1060 return ichimokuKinkoHyo;
1074 var resolution = GetSubscription(symbol).
Resolution;
1075 return Identity(symbol, resolution, selector, fieldName);
1092 InitializeIndicator(identity, resolution, selector, symbol);
1106 public Identity Identity(
Symbol symbol, TimeSpan resolution, Func<IBaseData, decimal> selector =
null,
string fieldName =
null)
1108 var name = Invariant($
"{symbol}({fieldName ?? "close
"},{resolution})");
1129 var name = InitializeOptionIndicator<ImpliedVolatility>(symbol, out var riskFreeRateModel, out var dividendYieldModel, riskFreeRate, dividendYield, optionModel, resolution);
1131 var iv =
new ImpliedVolatility(name, symbol, riskFreeRateModel, dividendYieldModel, mirrorOption, optionModel);
1132 InitializeOptionIndicator(iv, resolution, symbol, mirrorOption);
1147 return KAMA(symbol, period, 2, 30, resolution, selector);
1163 var name =
CreateIndicatorName(symbol, $
"KAMA({period},{fastEmaPeriod},{slowEmaPeriod})", resolution);
1165 InitializeIndicator(kaufmanAdaptiveMovingAverage, resolution, selector, symbol);
1167 return kaufmanAdaptiveMovingAverage;
1184 InitializeIndicator(kaufmanEfficiencyRatio, resolution, selector, symbol);
1186 return kaufmanEfficiencyRatio;
1204 var keltnerChannels =
new KeltnerChannels(name, period, k, movingAverageType);
1205 InitializeIndicator(keltnerChannels, resolution, selector, symbol);
1207 return keltnerChannels;
1222 var logReturn =
new LogReturn(name, period);
1223 InitializeIndicator(logReturn, resolution, selector, symbol);
1241 InitializeIndicator(leastSquaresMovingAverage, resolution, selector, symbol);
1243 return leastSquaresMovingAverage;
1260 InitializeIndicator(linearWeightedMovingAverage, resolution, selector, symbol);
1262 return linearWeightedMovingAverage;
1279 var name =
CreateIndicatorName(symbol, $
"MACD({fastPeriod},{slowPeriod},{signalPeriod})", resolution);
1281 InitializeIndicator(movingAverageConvergenceDivergence, resolution, selector, symbol);
1283 return movingAverageConvergenceDivergence;
1299 InitializeIndicator(meanAbsoluteDeviation, resolution, selector, symbol);
1301 return meanAbsoluteDeviation;
1319 InitializeIndicator(mesaAdaptiveMovingAverage, resolution, selector, symbol);
1320 return mesaAdaptiveMovingAverage;
1338 var marketProfile =
new VolumeProfile(name, period, valueAreaVolumePercentage, priceRangeRoundOff);
1339 InitializeIndicator(marketProfile, resolution, selector, symbol);
1341 return marketProfile;
1356 public TimeProfile TP(
Symbol symbol,
int period = 2, decimal valueAreaVolumePercentage = 0.70m, decimal priceRangeRoundOff = 0.05m,
Resolution resolution =
Resolution.Daily, Func<IBaseData, TradeBar> selector =
null)
1359 var marketProfile =
new TimeProfile(name, period, valueAreaVolumePercentage, priceRangeRoundOff);
1360 InitializeIndicator(marketProfile, resolution, selector, symbol);
1362 return marketProfile;
1378 InitializeIndicator(timeSeriesForecast, resolution, selector, symbol);
1380 return timeSeriesForecast;
1396 var maximum =
new Maximum(name, period);
1399 if (selector ==
null)
1401 var subscription = GetSubscription(symbol);
1402 if (typeof(
TradeBar).IsAssignableFrom(subscription.Type))
1405 selector = x => ((
TradeBar)x).High;
1409 InitializeIndicator(maximum, resolution, selector, symbol);
1427 InitializeIndicator(moneyFlowIndex, resolution, selector, symbol);
1429 return moneyFlowIndex;
1446 var massIndex =
new MassIndex(name, emaPeriod, sumPeriod);
1447 InitializeIndicator(massIndex, resolution, selector, symbol);
1464 var midPoint =
new MidPoint(name, period);
1465 InitializeIndicator(midPoint, resolution, selector, symbol);
1482 var midPrice =
new MidPrice(name, period);
1483 InitializeIndicator(midPrice, resolution, selector, symbol);
1501 var minimum =
new Minimum(name, period);
1504 if (selector ==
null)
1506 var subscription = GetSubscription(symbol);
1507 if (typeof(
TradeBar).IsAssignableFrom(subscription.Type))
1514 InitializeIndicator(minimum, resolution, selector, symbol);
1531 var momentum =
new Momentum(name, period);
1532 InitializeIndicator(momentum, resolution, selector, symbol);
1549 var name =
CreateIndicatorName(symbol, $
"MOMERSION({minPeriod},{fullPeriod})", resolution);
1551 InitializeIndicator(momersion, resolution, selector, symbol);
1570 InitializeIndicator(momentumPercent, resolution, selector, symbol);
1572 return momentumPercent;
1588 InitializeIndicator(normalizedAverageTrueRange, resolution, selector, symbol);
1590 return normalizedAverageTrueRange;
1607 InitializeIndicator(onBalanceVolume, resolution, selector, symbol);
1609 return onBalanceVolume;
1626 var pivotPointsHighLow =
new PivotPointsHighLow(name, lengthHigh, lengthLow, lastStoredValues);
1627 InitializeIndicator(pivotPointsHighLow, resolution, selector, symbol);
1629 return pivotPointsHighLow;
1647 InitializeIndicator(percentagePriceOscillator, resolution, selector, symbol);
1649 return percentagePriceOscillator;
1665 var name =
CreateIndicatorName(symbol, $
"PSAR({afStart},{afIncrement},{afMax})", resolution);
1667 InitializeIndicator(parabolicStopAndReverse, resolution, selector, symbol);
1669 return parabolicStopAndReverse;
1686 InitializeIndicator(regressionChannel, resolution, selector, symbol);
1688 return regressionChannel;
1704 InitializeIndicator(relativeMovingAverage, resolution, selector, symbol);
1706 return relativeMovingAverage;
1724 InitializeIndicator(rateOfChange, resolution, selector, symbol);
1726 return rateOfChange;
1743 InitializeIndicator(rateOfChangePercent, resolution, selector, symbol);
1745 return rateOfChangePercent;
1761 InitializeIndicator(rateOfChangeRatio, resolution, selector, symbol);
1763 return rateOfChangeRatio;
1781 InitializeIndicator(relativeStrengthIndex, resolution, selector, symbol);
1783 return relativeStrengthIndex;
1800 InitializeIndicator(relativeVigorIndex, resolution, selector, symbol);
1802 return relativeVigorIndex;
1821 return relativeDailyVolume;
1837 public Rho R(
Symbol symbol,
Symbol mirrorOption =
null, decimal? riskFreeRate =
null, decimal? dividendYield =
null,
1840 var name = InitializeOptionIndicator<Rho>(symbol, out var riskFreeRateModel, out var dividendYieldModel, riskFreeRate, dividendYield, optionModel, resolution);
1842 var rho =
new Rho(name, symbol, riskFreeRateModel, dividendYieldModel, mirrorOption, optionModel, ivModel);
1843 InitializeOptionIndicator(rho, resolution, symbol, mirrorOption);
1863 return R(symbol, mirrorOption, riskFreeRate, dividendYield, optionModel, ivModel, resolution);
1881 Resolution? resolution =
null, Func<IBaseData, decimal> selector =
null)
1883 var name =
CreateIndicatorName(symbol, $
"SRSI({rsiPeriod},{stochPeriod},{kSmoothingPeriod},{dSmoothingPeriod})", resolution);
1885 InitializeIndicator(indicator, resolution, selector, symbol);
1900 Resolution? resolution =
null, Func<IBaseData, IBaseDataBar> selector =
null)
1903 var strend =
new SuperTrend(name, period, multiplier, movingAverageType);
1904 InitializeIndicator(strend, resolution, selector, symbol);
1923 var baseBame = riskFreeRate.HasValue ? $
"SR({sharpePeriod},{riskFreeRate})" : $
"SR({sharpePeriod})";
1929 var sharpeRatio =
new SharpeRatio(name, sharpePeriod, riskFreeRateModel);
1930 InitializeIndicator(sharpeRatio, resolution, selector, symbol);
1947 var name =
CreateIndicatorName(symbol, $
"SORTINO({sortinoPeriod},{minimumAcceptableReturn})", resolution);
1948 var sortinoRatio =
new SortinoRatio(name, sortinoPeriod, minimumAcceptableReturn);
1949 InitializeIndicator(sortinoRatio, resolution, selector, symbol);
1951 return sortinoRatio;
1968 decimal keltnerMultiplier = 1.5m,
Resolution? resolution =
null, Func<IBaseData, IBaseDataBar> selector =
null)
1970 var name =
CreateIndicatorName(symbol, $
"SM({bollingerPeriod}, {bollingerMultiplier}, {keltnerPeriod}, {keltnerMultiplier})", resolution);
1971 var squeezeMomentum =
new SqueezeMomentum(name, bollingerPeriod, bollingerMultiplier, keltnerPeriod, keltnerMultiplier);
1972 InitializeIndicator(squeezeMomentum, resolution, selector, symbol);
1973 return squeezeMomentum;
1990 InitializeIndicator(simpleMovingAverage, resolution, selector, symbol);
1992 return simpleMovingAverage;
2010 var name =
CreateIndicatorName(symbol, $
"STC({cyclePeriod},{fastPeriod},{slowPeriod})", resolution);
2011 var schaffTrendCycle =
new SchaffTrendCycle(name, cyclePeriod, fastPeriod, slowPeriod, movingAverageType);
2012 InitializeIndicator(schaffTrendCycle, resolution, selector, symbol);
2014 return schaffTrendCycle;
2032 InitializeIndicator(indicator, resolution, selector, symbol);
2049 InitializeIndicator(standardDeviation, resolution, selector, symbol);
2051 return standardDeviation;
2067 var name =
CreateIndicatorName(symbol, $
"TDD({period},{minimumAcceptableReturn})", resolution);
2069 InitializeIndicator(targetDownsideDeviation, resolution, selector, symbol);
2071 return targetDownsideDeviation;
2086 Func<IBaseData, TradeBar> selector =
null)
2089 var stochastic =
new Stochastic(name, period, kPeriod, dPeriod);
2090 InitializeIndicator(stochastic, resolution, selector, symbol);
2106 return STO(symbol, period, period, 3, resolution, selector);
2123 InitializeIndicator(premierStochasticOscillator, resolution, selector, symbol);
2124 return premierStochasticOscillator;
2139 var sum =
new Sum(name, period);
2140 InitializeIndicator(sum, resolution, selector, symbol);
2160 var swissArmyKnife =
new SwissArmyKnife(name, period, delta, tool);
2161 InitializeIndicator(swissArmyKnife, resolution, selector, symbol);
2163 return swissArmyKnife;
2179 public Theta T(
Symbol symbol,
Symbol mirrorOption =
null, decimal? riskFreeRate =
null, decimal? dividendYield =
null,
2182 var name = InitializeOptionIndicator<Theta>(symbol, out var riskFreeRateModel, out var dividendYieldModel, riskFreeRate, dividendYield, optionModel, resolution);
2184 var theta =
new Theta(name, symbol, riskFreeRateModel, dividendYieldModel, mirrorOption, optionModel, ivModel);
2185 InitializeOptionIndicator(theta, resolution, symbol, mirrorOption);
2205 return T(symbol, mirrorOption, riskFreeRate, dividendYield, optionModel, ivModel, resolution);
2221 var t3MovingAverage =
new T3MovingAverage(name, period, volumeFactor);
2222 InitializeIndicator(t3MovingAverage, resolution, selector, symbol);
2224 return t3MovingAverage;
2240 InitializeIndicator(tripleExponentialMovingAverage, resolution, selector, symbol);
2242 return tripleExponentialMovingAverage;
2261 var name =
CreateIndicatorName(symbol, $
"TSI({longTermPeriod},{shortTermPeriod},{signalPeriod})", resolution);
2262 var trueStrengthIndex =
new TrueStrengthIndex(name, longTermPeriod, shortTermPeriod, signalPeriod, signalType);
2263 InitializeIndicator(trueStrengthIndex, resolution, selector, symbol);
2265 return trueStrengthIndex;
2280 InitializeIndicator(trueRange, resolution, selector, symbol);
2298 InitializeIndicator(triangularMovingAverage, resolution, selector, symbol);
2300 return triangularMovingAverage;
2315 var trix =
new Trix(name, period);
2316 InitializeIndicator(trix, resolution, selector, symbol);
2334 var name =
CreateIndicatorName(symbol, $
"ULTOSC({period1},{period2},{period3})", resolution);
2336 InitializeIndicator(ultimateOscillator, resolution, selector, symbol);
2338 return ultimateOscillator;
2354 public Vega V(
Symbol symbol,
Symbol mirrorOption =
null, decimal? riskFreeRate =
null, decimal? dividendYield =
null,
2357 var name = InitializeOptionIndicator<Vega>(symbol, out var riskFreeRateModel, out var dividendYieldModel, riskFreeRate, dividendYield, optionModel, resolution);
2359 var vega =
new Vega(name, symbol, riskFreeRateModel, dividendYieldModel, mirrorOption, optionModel, ivModel);
2360 InitializeOptionIndicator(vega, resolution, symbol, mirrorOption);
2377 InitializeIndicator(variableIndexDynamicAverage, resolution, selector, symbol);
2379 return variableIndexDynamicAverage;
2391 [Obsolete(
"'VAR' is obsolete please use 'V' instead")]
2394 return V(symbol, period, resolution, selector);
2409 var variance =
new Variance(name, period);
2410 InitializeIndicator(variance, resolution, selector, symbol);
2427 var valueAtRisk =
new ValueAtRisk(name, period, confidenceLevel);
2428 InitializeIndicator(valueAtRisk, resolution, selector, symbol);
2447 InitializeIndicator(volumeWeightedAveragePriceIndicator, resolution, selector, symbol);
2449 return volumeWeightedAveragePriceIndicator;
2464 return intradayVwap;
2481 InitializeIndicator(indicator, resolution, selector, symbol);
2498 var indicator =
new Vortex(name, period);
2499 InitializeIndicator(indicator, resolution, selector, symbol);
2518 InitializeIndicator(williamsPercentR, resolution, selector, symbol);
2520 return williamsPercentR;
2538 InitializeIndicator(wilderMovingAverage, resolution, selector, symbol);
2540 return wilderMovingAverage;
2555 Func<IBaseData, TradeBar> selector =
null)
2559 InitializeIndicator(si, resolution, selector, symbol);
2576 Func<IBaseData, TradeBar> selector =
null)
2580 InitializeIndicator(asi, resolution, selector, symbol);
2595 return TRIN(symbols.ToArray(), resolution, selector);
2610 foreach (var symbol
in symbols)
2614 InitializeIndicator(trin, resolution, selector, symbols);
2631 foreach (var symbol
in symbols)
2635 InitializeIndicator(adr, resolution, selector, symbols.ToArray());
2652 foreach (var symbol
in symbols)
2656 InitializeIndicator(advr, resolution, selector, symbols.ToArray());
2673 foreach (var symbol
in symbols)
2677 InitializeIndicator(adDiff, resolution, selector, symbols.ToArray());
2695 InitializeIndicator(indicator, resolution, selector, symbol);
2711 return MOSC(symbols.ToArray(), fastPeriod, slowPeriod, resolution, selector);
2728 foreach (var symbol
in symbols)
2732 InitializeIndicator(mosc, resolution, selector, symbols);
2749 return MSI(symbols.ToArray(), fastPeriod, slowPeriod, resolution, selector);
2766 foreach (var symbol
in symbols)
2770 InitializeIndicator(msi, resolution, selector, symbols);
2790 InitializeIndicator(indicator, resolution, selector, symbol);
2809 InitializeIndicator(zeroLagExponentialMovingAverage, resolution, selector, symbol);
2811 return zeroLagExponentialMovingAverage;
2839 if (!resolution.HasValue && symbolIsNotEmpty)
2841 resolution = GetSubscription(symbol).
Resolution;
2844 var res =
string.Empty;
2871 throw new ArgumentOutOfRangeException(nameof(resolution), resolution,
"resolution parameter is out of range.");
2874 var parts =
new List<string>();
2876 if (symbolIsNotEmpty)
2882 return Invariant($
"{type}({string.Join("_
", parts)})").Replace(
")(",
",");
2902 .ThenBy(x => x.TickType)
2906 subscription = subscriptions.FirstOrDefault(x => tickType ==
null || tickType == x.TickType);
2907 if (subscription ==
null)
2910 subscription = subscriptions.First();
2913 catch (InvalidOperationException)
2916 throw new Exception($
"Please register to receive data for symbol \'{symbol}\' using the AddSecurity() function.");
2918 return subscription;
2929 [DocumentationAttribute(ConsolidatingData)]
2930 [DocumentationAttribute(Indicators)]
2964 selector = selector ?? (x => x.Value);
2966 RegisterConsolidator(symbol, consolidator,
null, indicator);
2971 var value = selector(consolidated);
2972 indicator.Update(
new IndicatorDataPoint(consolidated.Symbol, consolidated.EndTime, value));
3037 var selectorToUse = selector ?? (x => (
T)x);
3039 RegisterConsolidator(symbol, consolidator,
null, indicator);
3042 var type = typeof(
T);
3043 if (!type.IsAssignableFrom(consolidator.
OutputType))
3049 selectorToUse = consolidated => (
T)(
object)
new IndicatorDataPoint(consolidated.Symbol, consolidated.EndTime, consolidated.Value);
3053 throw new ArgumentException($
"Type mismatch found between consolidator and indicator for symbol: {symbol}." +
3054 $
"Consolidator outputs type {consolidator.OutputType.Name} but indicator expects input type {type.Name}"
3062 var value = selectorToUse(consolidated);
3063 indicator.Update(value);
3086 foreach (var consolidator
in indicator.Consolidators)
3091 indicator.Consolidators.Clear();
3119 if (AssertIndicatorHasWarmupPeriod(indicator))
3136 var history = GetIndicatorWarmUpHistory(
new[] { symbol }, indicator, period, out var identityConsolidator);
3137 if (history == Enumerable.Empty<
Slice>())
return;
3140 selector ??= (x => x.Value);
3142 Action<IBaseData> onDataConsolidated = bar =>
3145 indicator.Update(input);
3148 WarmUpIndicatorImpl(symbol, period, onDataConsolidated, history, identityConsolidator);
3178 if (AssertIndicatorHasWarmupPeriod(indicator))
3196 var history = GetIndicatorWarmUpHistory(
new[] { symbol }, indicator, period, out var identityConsolidator);
3197 if (history == Enumerable.Empty<
Slice>())
return;
3200 selector ??= (x => (
T)x);
3203 Action<T> onDataConsolidated = bar =>
3205 indicator.Update(selector(bar));
3208 WarmUpIndicatorImpl(symbol, period, onDataConsolidated, history, identityConsolidator);
3211 private IEnumerable<Slice> GetIndicatorWarmUpHistory(IEnumerable<Symbol> symbols,
IIndicator indicator, TimeSpan timeSpan, out
bool identityConsolidator)
3213 identityConsolidator =
false;
3214 if (!AssertIndicatorHasWarmupPeriod(indicator))
3216 return Enumerable.Empty<
Slice>();
3222 var resolution = timeSpan.ToHigherResolutionEquivalent(
false);
3224 identityConsolidator = resolution.ToTimeSpan() == timeSpan;
3225 var resolutionTicks = resolution.ToTimeSpan().
Ticks;
3226 if (resolutionTicks != 0)
3228 periods *= (int)(timeSpan.Ticks / resolutionTicks);
3233 return History(symbols, periods, resolution, dataNormalizationMode: GetIndicatorHistoryDataNormalizationMode(indicator));
3235 catch (ArgumentException e)
3237 Debug($
"{indicator.Name} could not be warmed up. Reason: {e.Message}");
3240 return Enumerable.Empty<
Slice>();
3243 private bool AssertIndicatorHasWarmupPeriod(
IIndicator indicator)
3247 if (!_isEmitWarmupInsightWarningSent)
3249 Debug($
"Warning: the 'WarmUpIndicator' feature only works with indicators which inherit from '{nameof(IIndicatorWarmUpPeriodProvider)}'" +
3250 $
" and define a warm up period, setting property 'WarmUpPeriod' with a value > 0." +
3251 $
" The provided indicator of type '{indicator.GetType().Name}' will not be warmed up.");
3252 _isEmitWarmupInsightWarningSent =
true;
3259 private void WarmUpIndicatorImpl<T>(
Symbol symbol, TimeSpan period, Action<T> handler, IEnumerable<Slice> history,
bool identityConsolidator)
3265 consolidator =
Consolidate(symbol, period, handler);
3269 if (identityConsolidator)
3271 period = TimeSpan.Zero;
3274 var providedType = typeof(
T);
3275 if (providedType.IsAbstract)
3284 .ThenBy(tuple => tuple.Item2).First();
3297 var consolidatorInputType = consolidator.
InputType;
3299 foreach (var slice
in history)
3301 if (slice.TryGet(consolidatorInputType, symbol, out var data))
3304 consolidator.
Update(lastBar);
3309 if (lastBar !=
null)
3311 DateTime currentTime;
3312 if (
Securities.TryGetValue(symbol, out var security))
3314 currentTime = security.LocalTime;
3319 currentTime =
UtcTime.ConvertFromUtc(exchangeHours.TimeZone);
3322 consolidator.
Scan(currentTime);
3335 [DocumentationAttribute(ConsolidatingData)]
3336 [DocumentationAttribute(Indicators)]
3368 if (period.Ticks == 0)
3370 return CreateIdentityConsolidator(consolidatorInputType);
3375 if (typeof(
TradeBar).IsAssignableFrom(consolidatorInputType))
3382 if (typeof(
QuoteBar).IsAssignableFrom(consolidatorInputType))
3389 if (typeof(
Tick).IsAssignableFrom(consolidatorInputType))
3405 if (typeof(
DynamicData).IsAssignableFrom(consolidatorInputType))
3482 return Consolidate(symbol, period, tickType, handler);
3498 return Consolidate(symbol,
null, tickType, handler,
null, period);
3514 return Consolidate(symbol,
null, tickType, handler, period,
null);
3559 return Consolidate(symbol, calendar, tickType, handler);
3575 return Consolidate(symbol, calendar, tickType, handler,
null,
null);
3590 return IndicatorHistory(indicator,
new[] { symbol }, period, resolution, selector);
3606 if (warmupPeriod > 0 && period > 0)
3610 var history =
History(symbols, period + warmupPeriod, resolution, dataNormalizationMode: GetIndicatorHistoryDataNormalizationMode(indicator));
3627 return IndicatorHistory(indicator,
new[] { symbol }, period, resolution, selector);
3644 if (warmupPeriod > 0 && period > 0)
3648 var history =
History(symbols, period + warmupPeriod, resolution, dataNormalizationMode: GetIndicatorHistoryDataNormalizationMode(indicator));
3664 return IndicatorHistory(indicator,
new[] { symbol }, span, resolution, selector);
3711 return IndicatorHistory(indicator,
new[] { symbol }, span, resolution, selector);
3727 var history =
History(symbols, GetIndicatorAdjustedHistoryStart(indicator, symbols, start, end, resolution), end, resolution, dataNormalizationMode: GetIndicatorHistoryDataNormalizationMode(indicator));
3744 return IndicatorHistory(indicator,
new[] { symbol }, start, end, resolution, selector);
3761 return IndicatorHistory(indicator,
new[] { symbol }, start, end, resolution, selector);
3778 var history =
History(symbols, GetIndicatorAdjustedHistoryStart(indicator, symbols, start, end, resolution), end, resolution, dataNormalizationMode: GetIndicatorHistoryDataNormalizationMode(indicator));
3791 selector ??= (x => x.Value);
3792 return IndicatorHistory(indicator, history, (bar) => indicator.Update(
new IndicatorDataPoint(bar.Symbol, bar.EndTime, selector(bar))), GetDataTypeFromSelector(selector));
3805 selector ??= (x => (
T)x);
3806 return IndicatorHistory(indicator, history, (bar) => indicator.Update(selector(bar)));
3816 var consolidator =
CreateConsolidator(symbol, calendar, tickType, period, resolution, typeof(
T));
3817 if (handler !=
null)
3820 consolidator.DataConsolidated += (sender, consolidated) => handler((
T)consolidated);
3823 RegisterConsolidator(symbol, consolidator, tickType, indicatorBase:
null);
3825 return consolidator;
3831 var subscription = GetSubscription(symbol, tickType);
3835 if (period.HasValue && period.Value < subscription.Increment || resolution.HasValue && resolution.Value < subscription.Resolution)
3837 throw new ArgumentException($
"Unable to create {symbol} consolidator because {symbol} is registered for " +
3838 Invariant($
"{subscription.Resolution.ToStringInvariant()} data. Consolidators require higher resolution data to produce lower resolution data.")
3843 if (calendar !=
null)
3846 consolidator =
CreateConsolidator(calendar, subscription.Type, subscription.TickType);
3851 if (!period.HasValue && !resolution.HasValue)
3853 period = subscription.Increment;
3856 if (period.HasValue && period.Value == subscription.Increment || resolution.HasValue && resolution.Value == subscription.Resolution)
3858 consolidator = CreateIdentityConsolidator(subscription.Type);
3862 if (resolution.HasValue)
3868 period = resolution.Value.ToTimeSpan();
3870 consolidator ??=
CreateConsolidator(period.Value, subscription.Type, subscription.TickType);
3874 if (consolidatorType !=
null && !consolidatorType.IsAssignableFrom(consolidator.
OutputType))
3876 throw new ArgumentException(
3877 $
"Unable to consolidate with the specified handler because the consolidator's output type " +
3878 $
"is {consolidator.OutputType.Name} but the handler's input type is {subscription.Type.Name}.");
3880 return consolidator;
3887 if (typeof(
TradeBar).IsAssignableFrom(consolidatorInputType))
3894 if (typeof(
QuoteBar).IsAssignableFrom(consolidatorInputType))
3901 if (typeof(
Tick).IsAssignableFrom(consolidatorInputType))
3911 if (typeof(
DynamicData).IsAssignableFrom(consolidatorInputType))
3923 private static IDataConsolidator CreateIdentityConsolidator(Type consolidatorInputType)
3925 if (typeof(
TradeBar).IsAssignableFrom(consolidatorInputType))
3929 else if (typeof(
QuoteBar).IsAssignableFrom(consolidatorInputType))
3933 else if (typeof(
Tick).IsAssignableFrom(consolidatorInputType))
3937 else if (typeof(
DynamicData).IsAssignableFrom(consolidatorInputType))
3948 Func<IBaseData, decimal> selector =
null, params
Symbol[] symbols)
3950 var dataType = GetDataTypeFromSelector(selector);
3951 foreach (var symbol
in symbols)
3963 Func<IBaseData, T> selector =
null, params
Symbol[] symbols)
3966 foreach (var symbol
in symbols)
3981 var symbols =
new List<Symbol> { symbol, symbol.Underlying };
3982 if (mirrorOption !=
null)
3985 symbols.Add(mirrorOption);
3999 $
"{typeof(T).Name}({riskFreeRate},{dividendYield},{OptionIndicatorBase.GetOptionModel(optionModel, symbol.ID.OptionStyle)})",
4002 riskFreeRateModel = riskFreeRate.HasValue
4007 if (dividendYield.HasValue)
4022 indicatorBase?.Consolidators.Add(consolidator);
4028 private DateTime GetIndicatorAdjustedHistoryStart(
IndicatorBase indicator, IEnumerable<Symbol> symbols, DateTime start, DateTime end,
Resolution? resolution =
null)
4031 if (warmupPeriod != 0)
4034 if (warmupPeriod > 0)
4038 var adjustedStart = _historyRequestFactory.
GetStartTimeAlgoTz(request.StartTimeUtc, request.Symbol, warmupPeriod, request.Resolution,
4039 request.ExchangeHours, request.DataTimeZone, request.DataType, request.IncludeExtendedMarketHours);
4040 if (adjustedStart < start)
4042 start = adjustedStart;
4058 return dataNormalizationMode;
4067 var indicatorType = indicator.GetType();
4069 var indicatorsDataPointPerProperty = indicatorType.GetProperties()
4070 .Where(x => x.PropertyType.IsGenericType && x.Name !=
"Consolidators" && x.Name !=
"Window")
4075 var indicatorsDataPointsByTime =
new List<IndicatorDataPoints>();
4076 var lastConsumedTime = DateTime.MinValue;
4080 if (newInputPoint ==
null || lastConsumedTime == newInputPoint.
EndTime)
4084 lastConsumedTime = newInputPoint.
EndTime;
4088 for (var i = 0; i < indicatorsDataPointPerProperty.Count; i++)
4090 var newPoint = indicatorsDataPointPerProperty[i].UpdateValue();
4097 if (!indicator.IsReady)
4102 if (lastPoint ==
null || lastPoint.
Time != newInputPoint.
Time)
4107 consumeLastPoint(newInputPoint);
4109 lastPoint = newInputPoint;
4113 indicator.Updated += callback;
4117 history.PushThrough(bar => updateIndicator(bar), dataType);
4122 foreach (var dataDictionary
in history.Get<
T>())
4124 foreach (var dataPoint
in dataDictionary.Values)
4126 updateIndicator(dataPoint);
4131 consumeLastPoint(lastPoint);
4132 indicator.Updated -= callback;
4134 return new IndicatorHistory(indicatorsDataPointsByTime, indicatorsDataPointPerProperty,
4136 () =>
PandasConverter.GetIndicatorDataFrame(indicatorsDataPointPerProperty.Select(x =>
new KeyValuePair<
string, List<IndicatorDataPoint>>(x.Name, x.Values))),
4137 isThreadSafe:
false));
4140 private Type GetDataTypeFromSelector(Func<IBaseData, decimal> selector)
4142 Type dataType =
null;
4143 if (_quoteRequiredFields.Any(x => ReferenceEquals(selector, x)))
4147 else if (ReferenceEquals(selector, Field.Volume))