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);
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 InitializeIndicator(deMarkerIndicator, resolution, selector, symbol);
572 return deMarkerIndicator;
585 [DocumentationAttribute(Indicators)]
589 var donchianChannel =
new DonchianChannel(name, upperPeriod, lowerPeriod);
590 InitializeIndicator(donchianChannel, resolution, selector, symbol);
592 return donchianChannel;
607 return DCH(symbol, period, period, resolution, selector);
623 public Delta D(
Symbol symbol,
Symbol mirrorOption =
null, decimal? riskFreeRate =
null, decimal? dividendYield =
null,
626 var name = InitializeOptionIndicator<Delta>(symbol, out var riskFreeRateModel, out var dividendYieldModel, riskFreeRate, dividendYield, optionModel, resolution);
628 var delta =
new Delta(name, symbol, riskFreeRateModel, dividendYieldModel, mirrorOption, optionModel, ivModel);
629 InitializeOptionIndicator(delta, resolution, symbol, mirrorOption);
649 return D(symbol, mirrorOption, riskFreeRate, dividendYield, optionModel, ivModel, resolution);
665 InitializeIndicator(doubleExponentialMovingAverage, resolution, selector, symbol);
667 return doubleExponentialMovingAverage;
682 public DerivativeOscillator DO(
Symbol symbol,
int rsiPeriod,
int smoothingRsiPeriod,
int doubleSmoothingRsiPeriod,
int signalLinePeriod,
Resolution? resolution =
null, Func<IBaseData, decimal> selector =
null)
684 var name =
CreateIndicatorName(symbol, $
"DO({rsiPeriod},{smoothingRsiPeriod},{doubleSmoothingRsiPeriod},{signalLinePeriod})", resolution);
685 var derivativeOscillator =
new DerivativeOscillator(name, rsiPeriod, smoothingRsiPeriod, doubleSmoothingRsiPeriod, signalLinePeriod);
686 InitializeIndicator(derivativeOscillator, resolution, selector, symbol);
688 return derivativeOscillator;
704 InitializeIndicator(detrendedPriceOscillator, resolution, selector, symbol);
706 return detrendedPriceOscillator;
739 InitializeIndicator(exponentialMovingAverage, resolution, selector, symbol);
741 return exponentialMovingAverage;
759 InitializeIndicator(easeOfMovementValue, resolution, selector, symbol);
761 return easeOfMovementValue;
776 var resolution = GetSubscription(symbol).
Resolution;
795 RegisterIndicator<IBaseData>(symbol, filteredIdentity, resolution, selector);
796 return filteredIdentity;
812 var name = Invariant($
"{symbol}({fieldName ?? "close
"}_{resolution})");
814 RegisterIndicator<IBaseData>(symbol, filteredIdentity,
ResolveConsolidator(symbol, resolution), selector);
815 return filteredIdentity;
832 var indicator =
new ForceIndex(name, period, type);
833 InitializeIndicator(indicator, resolution, selector, symbol);
852 InitializeIndicator(fisherTransform, resolution, selector, symbol);
854 return fisherTransform;
873 InitializeIndicator(fractalAdaptiveMovingAverage, resolution, selector, symbol);
875 return fractalAdaptiveMovingAverage;
891 public Gamma G(
Symbol symbol,
Symbol mirrorOption =
null, decimal? riskFreeRate =
null, decimal? dividendYield =
null,
894 var name = InitializeOptionIndicator<Gamma>(symbol, out var riskFreeRateModel, out var dividendYieldModel, riskFreeRate, dividendYield, optionModel, resolution);
896 var gamma =
new Gamma(name, symbol, riskFreeRateModel, dividendYieldModel, mirrorOption, optionModel, ivModel);
897 InitializeOptionIndicator(gamma, resolution, symbol, mirrorOption);
917 return G(symbol, mirrorOption, riskFreeRate, dividendYield, optionModel, ivModel, resolution);
932 InitializeIndicator(heikinAshi, resolution, selector, symbol);
952 public HilbertTransform HT(
Symbol symbol,
int length, decimal inPhaseMultiplicationFactor, decimal quadratureMultiplicationFactor,
Resolution? resolution =
null, Func<IBaseData, decimal> selector =
null)
954 var name =
CreateIndicatorName(symbol, $
"HT({length}, {inPhaseMultiplicationFactor}, {quadratureMultiplicationFactor})", resolution);
955 var hilbertTransform =
new HilbertTransform(length, inPhaseMultiplicationFactor, quadratureMultiplicationFactor);
956 InitializeIndicator(hilbertTransform, resolution, selector, symbol);
958 return hilbertTransform;
974 InitializeIndicator(hullMovingAverage, resolution, selector, symbol);
976 return hullMovingAverage;
992 InitializeIndicator(indicator, resolution, selector, symbol);
1013 int senkouADelayPeriod,
int senkouBDelayPeriod,
Resolution? resolution =
null, Func<IBaseData, TradeBar> selector =
null)
1015 var name =
CreateIndicatorName(symbol, $
"ICHIMOKU({tenkanPeriod},{kijunPeriod},{senkouAPeriod},{senkouBPeriod},{senkouADelayPeriod},{senkouBDelayPeriod})", resolution);
1016 var ichimokuKinkoHyo =
new IchimokuKinkoHyo(name, tenkanPeriod, kijunPeriod, senkouAPeriod, senkouBPeriod, senkouADelayPeriod, senkouBDelayPeriod);
1017 InitializeIndicator(ichimokuKinkoHyo, resolution, selector, symbol);
1019 return ichimokuKinkoHyo;
1033 var resolution = GetSubscription(symbol).
Resolution;
1034 return Identity(symbol, resolution, selector, fieldName);
1051 InitializeIndicator(identity, resolution, selector, symbol);
1065 public Identity Identity(
Symbol symbol, TimeSpan resolution, Func<IBaseData, decimal> selector =
null,
string fieldName =
null)
1067 var name = Invariant($
"{symbol}({fieldName ?? "close
"},{resolution})");
1088 var name = InitializeOptionIndicator<ImpliedVolatility>(symbol, out var riskFreeRateModel, out var dividendYieldModel, riskFreeRate, dividendYield, optionModel, resolution);
1090 var iv =
new ImpliedVolatility(name, symbol, riskFreeRateModel, dividendYieldModel, mirrorOption, optionModel);
1091 InitializeOptionIndicator(iv, resolution, symbol, mirrorOption);
1106 return KAMA(symbol, period, 2, 30, resolution, selector);
1122 var name =
CreateIndicatorName(symbol, $
"KAMA({period},{fastEmaPeriod},{slowEmaPeriod})", resolution);
1124 InitializeIndicator(kaufmanAdaptiveMovingAverage, resolution, selector, symbol);
1126 return kaufmanAdaptiveMovingAverage;
1143 InitializeIndicator(kaufmanEfficiencyRatio, resolution, selector, symbol);
1145 return kaufmanEfficiencyRatio;
1163 var keltnerChannels =
new KeltnerChannels(name, period, k, movingAverageType);
1164 InitializeIndicator(keltnerChannels, resolution, selector, symbol);
1166 return keltnerChannels;
1181 var logReturn =
new LogReturn(name, period);
1182 InitializeIndicator(logReturn, resolution, selector, symbol);
1200 InitializeIndicator(leastSquaresMovingAverage, resolution, selector, symbol);
1202 return leastSquaresMovingAverage;
1219 InitializeIndicator(linearWeightedMovingAverage, resolution, selector, symbol);
1221 return linearWeightedMovingAverage;
1238 var name =
CreateIndicatorName(symbol, $
"MACD({fastPeriod},{slowPeriod},{signalPeriod})", resolution);
1240 InitializeIndicator(movingAverageConvergenceDivergence, resolution, selector, symbol);
1242 return movingAverageConvergenceDivergence;
1258 InitializeIndicator(meanAbsoluteDeviation, resolution, selector, symbol);
1260 return meanAbsoluteDeviation;
1278 var marketProfile =
new VolumeProfile(name, period, valueAreaVolumePercentage, priceRangeRoundOff);
1279 InitializeIndicator(marketProfile, resolution, selector, symbol);
1281 return marketProfile;
1296 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)
1299 var marketProfile =
new TimeProfile(name, period, valueAreaVolumePercentage, priceRangeRoundOff);
1300 InitializeIndicator(marketProfile, resolution, selector, symbol);
1302 return marketProfile;
1318 InitializeIndicator(timeSeriesForecast, resolution, selector, symbol);
1320 return timeSeriesForecast;
1336 var maximum =
new Maximum(name, period);
1339 if (selector ==
null)
1341 var subscription = GetSubscription(symbol);
1342 if (typeof(
TradeBar).IsAssignableFrom(subscription.Type))
1345 selector = x => ((
TradeBar)x).High;
1349 InitializeIndicator(maximum, resolution, selector, symbol);
1367 InitializeIndicator(moneyFlowIndex, resolution, selector, symbol);
1369 return moneyFlowIndex;
1386 var massIndex =
new MassIndex(name, emaPeriod, sumPeriod);
1387 InitializeIndicator(massIndex, resolution, selector, symbol);
1404 var midPoint =
new MidPoint(name, period);
1405 InitializeIndicator(midPoint, resolution, selector, symbol);
1422 var midPrice =
new MidPrice(name, period);
1423 InitializeIndicator(midPrice, resolution, selector, symbol);
1441 var minimum =
new Minimum(name, period);
1444 if (selector ==
null)
1446 var subscription = GetSubscription(symbol);
1447 if (typeof(
TradeBar).IsAssignableFrom(subscription.Type))
1454 InitializeIndicator(minimum, resolution, selector, symbol);
1471 var momentum =
new Momentum(name, period);
1472 InitializeIndicator(momentum, resolution, selector, symbol);
1489 var name =
CreateIndicatorName(symbol, $
"MOMERSION({minPeriod},{fullPeriod})", resolution);
1491 InitializeIndicator(momersion, resolution, selector, symbol);
1510 InitializeIndicator(momentumPercent, resolution, selector, symbol);
1512 return momentumPercent;
1528 InitializeIndicator(normalizedAverageTrueRange, resolution, selector, symbol);
1530 return normalizedAverageTrueRange;
1547 InitializeIndicator(onBalanceVolume, resolution, selector, symbol);
1549 return onBalanceVolume;
1566 var pivotPointsHighLow =
new PivotPointsHighLow(name, lengthHigh, lengthLow, lastStoredValues);
1567 InitializeIndicator(pivotPointsHighLow, resolution, selector, symbol);
1569 return pivotPointsHighLow;
1587 InitializeIndicator(percentagePriceOscillator, resolution, selector, symbol);
1589 return percentagePriceOscillator;
1605 var name =
CreateIndicatorName(symbol, $
"PSAR({afStart},{afIncrement},{afMax})", resolution);
1607 InitializeIndicator(parabolicStopAndReverse, resolution, selector, symbol);
1609 return parabolicStopAndReverse;
1626 InitializeIndicator(regressionChannel, resolution, selector, symbol);
1628 return regressionChannel;
1644 InitializeIndicator(relativeMovingAverage, resolution, selector, symbol);
1646 return relativeMovingAverage;
1664 InitializeIndicator(rateOfChange, resolution, selector, symbol);
1666 return rateOfChange;
1683 InitializeIndicator(rateOfChangePercent, resolution, selector, symbol);
1685 return rateOfChangePercent;
1701 InitializeIndicator(rateOfChangeRatio, resolution, selector, symbol);
1703 return rateOfChangeRatio;
1721 InitializeIndicator(relativeStrengthIndex, resolution, selector, symbol);
1723 return relativeStrengthIndex;
1740 InitializeIndicator(relativeVigorIndex, resolution, selector, symbol);
1742 return relativeVigorIndex;
1761 return relativeDailyVolume;
1777 public Rho R(
Symbol symbol,
Symbol mirrorOption =
null, decimal? riskFreeRate =
null, decimal? dividendYield =
null,
1780 var name = InitializeOptionIndicator<Rho>(symbol, out var riskFreeRateModel, out var dividendYieldModel, riskFreeRate, dividendYield, optionModel, resolution);
1782 var rho =
new Rho(name, symbol, riskFreeRateModel, dividendYieldModel, mirrorOption, optionModel, ivModel);
1783 InitializeOptionIndicator(rho, resolution, symbol, mirrorOption);
1803 return R(symbol, mirrorOption, riskFreeRate, dividendYield, optionModel, ivModel, resolution);
1821 Resolution? resolution =
null, Func<IBaseData, decimal> selector =
null)
1823 var name =
CreateIndicatorName(symbol, $
"SRSI({rsiPeriod},{stochPeriod},{kSmoothingPeriod},{dSmoothingPeriod})", resolution);
1825 InitializeIndicator(indicator, resolution, selector, symbol);
1840 Resolution? resolution =
null, Func<IBaseData, IBaseDataBar> selector =
null)
1843 var strend =
new SuperTrend(name, period, multiplier, movingAverageType);
1844 InitializeIndicator(strend, resolution, selector, symbol);
1863 var baseBame = riskFreeRate.HasValue ? $
"SR({sharpePeriod},{riskFreeRate})" : $
"SR({sharpePeriod})";
1869 var sharpeRatio =
new SharpeRatio(name, sharpePeriod, riskFreeRateModel);
1870 InitializeIndicator(sharpeRatio, resolution, selector, symbol);
1887 var name =
CreateIndicatorName(symbol, $
"SORTINO({sortinoPeriod},{minimumAcceptableReturn})", resolution);
1888 var sortinoRatio =
new SortinoRatio(name, sortinoPeriod, minimumAcceptableReturn);
1889 InitializeIndicator(sortinoRatio, resolution, selector, symbol);
1891 return sortinoRatio;
1909 InitializeIndicator(simpleMovingAverage, resolution, selector, symbol);
1911 return simpleMovingAverage;
1929 var name =
CreateIndicatorName(symbol, $
"STC({cyclePeriod},{fastPeriod},{slowPeriod})", resolution);
1930 var schaffTrendCycle =
new SchaffTrendCycle(name, cyclePeriod, fastPeriod, slowPeriod, movingAverageType);
1931 InitializeIndicator(schaffTrendCycle, resolution, selector, symbol);
1933 return schaffTrendCycle;
1951 InitializeIndicator(indicator, resolution, selector, symbol);
1968 InitializeIndicator(standardDeviation, resolution, selector, symbol);
1970 return standardDeviation;
1986 var name =
CreateIndicatorName(symbol, $
"TDD({period},{minimumAcceptableReturn})", resolution);
1988 InitializeIndicator(targetDownsideDeviation, resolution, selector, symbol);
1990 return targetDownsideDeviation;
2005 Func<IBaseData, TradeBar> selector =
null)
2008 var stochastic =
new Stochastic(name, period, kPeriod, dPeriod);
2009 InitializeIndicator(stochastic, resolution, selector, symbol);
2025 return STO(symbol, period, period, 3, resolution, selector);
2042 InitializeIndicator(premierStochasticOscillator, resolution, selector, symbol);
2043 return premierStochasticOscillator;
2058 var sum =
new Sum(name, period);
2059 InitializeIndicator(sum, resolution, selector, symbol);
2079 var swissArmyKnife =
new SwissArmyKnife(name, period, delta, tool);
2080 InitializeIndicator(swissArmyKnife, resolution, selector, symbol);
2082 return swissArmyKnife;
2098 public Theta T(
Symbol symbol,
Symbol mirrorOption =
null, decimal? riskFreeRate =
null, decimal? dividendYield =
null,
2101 var name = InitializeOptionIndicator<Theta>(symbol, out var riskFreeRateModel, out var dividendYieldModel, riskFreeRate, dividendYield, optionModel, resolution);
2103 var theta =
new Theta(name, symbol, riskFreeRateModel, dividendYieldModel, mirrorOption, optionModel, ivModel);
2104 InitializeOptionIndicator(theta, resolution, symbol, mirrorOption);
2124 return T(symbol, mirrorOption, riskFreeRate, dividendYield, optionModel, ivModel, resolution);
2140 var t3MovingAverage =
new T3MovingAverage(name, period, volumeFactor);
2141 InitializeIndicator(t3MovingAverage, resolution, selector, symbol);
2143 return t3MovingAverage;
2159 InitializeIndicator(tripleExponentialMovingAverage, resolution, selector, symbol);
2161 return tripleExponentialMovingAverage;
2180 var name =
CreateIndicatorName(symbol, $
"TSI({longTermPeriod},{shortTermPeriod},{signalPeriod})", resolution);
2181 var trueStrengthIndex =
new TrueStrengthIndex(name, longTermPeriod, shortTermPeriod, signalPeriod, signalType);
2182 InitializeIndicator(trueStrengthIndex, resolution, selector, symbol);
2184 return trueStrengthIndex;
2199 InitializeIndicator(trueRange, resolution, selector, symbol);
2217 InitializeIndicator(triangularMovingAverage, resolution, selector, symbol);
2219 return triangularMovingAverage;
2234 var trix =
new Trix(name, period);
2235 InitializeIndicator(trix, resolution, selector, symbol);
2253 var name =
CreateIndicatorName(symbol, $
"ULTOSC({period1},{period2},{period3})", resolution);
2255 InitializeIndicator(ultimateOscillator, resolution, selector, symbol);
2257 return ultimateOscillator;
2273 public Vega V(
Symbol symbol,
Symbol mirrorOption =
null, decimal? riskFreeRate =
null, decimal? dividendYield =
null,
2276 var name = InitializeOptionIndicator<Vega>(symbol, out var riskFreeRateModel, out var dividendYieldModel, riskFreeRate, dividendYield, optionModel, resolution);
2278 var vega =
new Vega(name, symbol, riskFreeRateModel, dividendYieldModel, mirrorOption, optionModel, ivModel);
2279 InitializeOptionIndicator(vega, resolution, symbol, mirrorOption);
2296 InitializeIndicator(variableIndexDynamicAverage, resolution, selector, symbol);
2298 return variableIndexDynamicAverage;
2310 [Obsolete(
"'VAR' is obsolete please use 'V' instead")]
2313 return V(symbol, period, resolution, selector);
2328 var variance =
new Variance(name, period);
2329 InitializeIndicator(variance, resolution, selector, symbol);
2346 var valueAtRisk =
new ValueAtRisk(name, period, confidenceLevel);
2347 InitializeIndicator(valueAtRisk, resolution, selector, symbol);
2366 InitializeIndicator(volumeWeightedAveragePriceIndicator, resolution, selector, symbol);
2368 return volumeWeightedAveragePriceIndicator;
2383 return intradayVwap;
2400 InitializeIndicator(indicator, resolution, selector, symbol);
2417 var indicator =
new Vortex(name, period);
2418 InitializeIndicator(indicator, resolution, selector, symbol);
2437 InitializeIndicator(williamsPercentR, resolution, selector, symbol);
2439 return williamsPercentR;
2457 InitializeIndicator(wilderMovingAverage, resolution, selector, symbol);
2459 return wilderMovingAverage;
2474 Func<IBaseData, TradeBar> selector =
null)
2478 InitializeIndicator(si, resolution, selector, symbol);
2495 Func<IBaseData, TradeBar> selector =
null)
2499 InitializeIndicator(asi, resolution, selector, symbol);
2514 return TRIN(symbols.ToArray(), resolution, selector);
2529 foreach (var symbol
in symbols)
2533 InitializeIndicator(trin, resolution, selector, symbols);
2550 foreach (var symbol
in symbols)
2554 InitializeIndicator(adr, resolution, selector, symbols.ToArray());
2571 foreach (var symbol
in symbols)
2575 InitializeIndicator(advr, resolution, selector, symbols.ToArray());
2592 foreach (var symbol
in symbols)
2596 InitializeIndicator(adDiff, resolution, selector, symbols.ToArray());
2614 InitializeIndicator(indicator, resolution, selector, symbol);
2630 return MOSC(symbols.ToArray(), fastPeriod, slowPeriod, resolution, selector);
2647 foreach (var symbol
in symbols)
2651 InitializeIndicator(mosc, resolution, selector, symbols);
2668 return MSI(symbols.ToArray(), fastPeriod, slowPeriod, resolution, selector);
2685 foreach (var symbol
in symbols)
2689 InitializeIndicator(msi, resolution, selector, symbols);
2709 InitializeIndicator(indicator, resolution, selector, symbol);
2728 InitializeIndicator(zeroLagExponentialMovingAverage, resolution, selector, symbol);
2730 return zeroLagExponentialMovingAverage;
2758 if (!resolution.HasValue && symbolIsNotEmpty)
2760 resolution = GetSubscription(symbol).
Resolution;
2763 var res =
string.Empty;
2790 throw new ArgumentOutOfRangeException(nameof(resolution), resolution,
"resolution parameter is out of range.");
2793 var parts =
new List<string>();
2795 if (symbolIsNotEmpty)
2801 return Invariant($
"{type}({string.Join("_
", parts)})").Replace(
")(",
",");
2821 .ThenBy(x => x.TickType)
2825 subscription = subscriptions.FirstOrDefault(x => tickType ==
null || tickType == x.TickType);
2826 if (subscription ==
null)
2829 subscription = subscriptions.First();
2832 catch (InvalidOperationException)
2835 throw new Exception($
"Please register to receive data for symbol \'{symbol}\' using the AddSecurity() function.");
2837 return subscription;
2848 [DocumentationAttribute(ConsolidatingData)]
2849 [DocumentationAttribute(Indicators)]
2883 selector = selector ?? (x => x.Value);
2885 RegisterConsolidator(symbol, consolidator,
null, indicator);
2890 var value = selector(consolidated);
2891 indicator.Update(
new IndicatorDataPoint(consolidated.Symbol, consolidated.EndTime, value));
2956 var selectorToUse = selector ?? (x => (
T)x);
2958 RegisterConsolidator(symbol, consolidator,
null, indicator);
2961 var type = typeof(
T);
2962 if (!type.IsAssignableFrom(consolidator.
OutputType))
2968 selectorToUse = consolidated => (
T)(
object)
new IndicatorDataPoint(consolidated.Symbol, consolidated.EndTime, consolidated.Value);
2972 throw new ArgumentException($
"Type mismatch found between consolidator and indicator for symbol: {symbol}." +
2973 $
"Consolidator outputs type {consolidator.OutputType.Name} but indicator expects input type {type.Name}"
2981 var value = selectorToUse(consolidated);
2982 indicator.Update(value);
3005 foreach (var consolidator
in indicator.Consolidators)
3010 indicator.Consolidators.Clear();
3038 if (AssertIndicatorHasWarmupPeriod(indicator))
3055 var history = GetIndicatorWarmUpHistory(
new[] { symbol }, indicator, period, out var identityConsolidator);
3056 if (history == Enumerable.Empty<
Slice>())
return;
3059 selector ??= (x => x.Value);
3061 Action<IBaseData> onDataConsolidated = bar =>
3064 indicator.Update(input);
3067 WarmUpIndicatorImpl(symbol, period, onDataConsolidated, history, identityConsolidator);
3097 if (AssertIndicatorHasWarmupPeriod(indicator))
3115 var history = GetIndicatorWarmUpHistory(
new[] { symbol }, indicator, period, out var identityConsolidator);
3116 if (history == Enumerable.Empty<
Slice>())
return;
3119 selector ??= (x => (
T)x);
3122 Action<T> onDataConsolidated = bar =>
3124 indicator.Update(selector(bar));
3127 WarmUpIndicatorImpl(symbol, period, onDataConsolidated, history, identityConsolidator);
3130 private IEnumerable<Slice> GetIndicatorWarmUpHistory(IEnumerable<Symbol> symbols,
IIndicator indicator, TimeSpan timeSpan, out
bool identityConsolidator)
3132 identityConsolidator =
false;
3133 if (!AssertIndicatorHasWarmupPeriod(indicator))
3135 return Enumerable.Empty<
Slice>();
3141 var resolution = timeSpan.ToHigherResolutionEquivalent(
false);
3143 identityConsolidator = resolution.ToTimeSpan() == timeSpan;
3144 var resolutionTicks = resolution.ToTimeSpan().
Ticks;
3145 if (resolutionTicks != 0)
3147 periods *= (int)(timeSpan.Ticks / resolutionTicks);
3152 return History(symbols, periods, resolution, dataNormalizationMode: GetIndicatorHistoryDataNormalizationMode(indicator));
3154 catch (ArgumentException e)
3156 Debug($
"{indicator.Name} could not be warmed up. Reason: {e.Message}");
3159 return Enumerable.Empty<
Slice>();
3162 private bool AssertIndicatorHasWarmupPeriod(
IIndicator indicator)
3166 if (!_isEmitWarmupInsightWarningSent)
3168 Debug($
"Warning: the 'WarmUpIndicator' feature only works with indicators which inherit from '{nameof(IIndicatorWarmUpPeriodProvider)}'" +
3169 $
" and define a warm up period, setting property 'WarmUpPeriod' with a value > 0." +
3170 $
" The provided indicator of type '{indicator.GetType().Name}' will not be warmed up.");
3171 _isEmitWarmupInsightWarningSent =
true;
3178 private void WarmUpIndicatorImpl<T>(
Symbol symbol, TimeSpan period, Action<T> handler, IEnumerable<Slice> history,
bool identityConsolidator)
3184 consolidator =
Consolidate(symbol, period, handler);
3188 if (identityConsolidator)
3190 period = TimeSpan.Zero;
3193 var providedType = typeof(
T);
3194 if (providedType.IsAbstract)
3203 .ThenBy(tuple => tuple.Item2).First();
3216 var consolidatorInputType = consolidator.
InputType;
3218 foreach (var slice
in history)
3220 if (slice.TryGet(consolidatorInputType, symbol, out var data))
3223 consolidator.
Update(lastBar);
3228 if (lastBar !=
null)
3243 [DocumentationAttribute(ConsolidatingData)]
3244 [DocumentationAttribute(Indicators)]
3276 if (period.Ticks == 0)
3278 return CreateIdentityConsolidator(consolidatorInputType);
3283 if (typeof(
TradeBar).IsAssignableFrom(consolidatorInputType))
3290 if (typeof(
QuoteBar).IsAssignableFrom(consolidatorInputType))
3297 if (typeof(
Tick).IsAssignableFrom(consolidatorInputType))
3313 if (typeof(
DynamicData).IsAssignableFrom(consolidatorInputType))
3390 return Consolidate(symbol, period, tickType, handler);
3406 return Consolidate(symbol,
null, tickType, handler,
null, period);
3422 return Consolidate(symbol,
null, tickType, handler, period,
null);
3467 return Consolidate(symbol, calendar, tickType, handler);
3483 return Consolidate(symbol, calendar, tickType, handler,
null,
null);
3498 return IndicatorHistory(indicator,
new[] { symbol }, period, resolution, selector);
3514 if (warmupPeriod > 0 && period > 0)
3518 var history =
History(symbols, period + warmupPeriod, resolution, dataNormalizationMode: GetIndicatorHistoryDataNormalizationMode(indicator));
3535 return IndicatorHistory(indicator,
new[] { symbol }, period, resolution, selector);
3552 if (warmupPeriod > 0 && period > 0)
3556 var history =
History(symbols, period + warmupPeriod, resolution, dataNormalizationMode: GetIndicatorHistoryDataNormalizationMode(indicator));
3572 return IndicatorHistory(indicator,
new[] { symbol }, span, resolution, selector);
3619 return IndicatorHistory(indicator,
new[] { symbol }, span, resolution, selector);
3635 var history =
History(symbols, GetIndicatorAdjustedHistoryStart(indicator, symbols, start, end, resolution), end, resolution, dataNormalizationMode: GetIndicatorHistoryDataNormalizationMode(indicator));
3652 return IndicatorHistory(indicator,
new[] { symbol }, start, end, resolution, selector);
3669 return IndicatorHistory(indicator,
new[] { symbol }, start, end, resolution, selector);
3686 var history =
History(symbols, GetIndicatorAdjustedHistoryStart(indicator, symbols, start, end, resolution), end, resolution, dataNormalizationMode: GetIndicatorHistoryDataNormalizationMode(indicator));
3699 selector ??= (x => x.Value);
3700 return IndicatorHistory(indicator, history, (bar) => indicator.Update(
new IndicatorDataPoint(bar.Symbol, bar.EndTime, selector(bar))), GetDataTypeFromSelector(selector));
3713 selector ??= (x => (
T)x);
3714 return IndicatorHistory(indicator, history, (bar) => indicator.Update(selector(bar)));
3724 var consolidator =
CreateConsolidator(symbol, calendar, tickType, period, resolution, typeof(
T));
3725 if (handler !=
null)
3728 consolidator.DataConsolidated += (sender, consolidated) => handler((
T)consolidated);
3731 RegisterConsolidator(symbol, consolidator, tickType, indicatorBase:
null);
3733 return consolidator;
3739 var subscription = GetSubscription(symbol, tickType);
3743 if (period.HasValue && period.Value < subscription.Increment || resolution.HasValue && resolution.Value < subscription.Resolution)
3745 throw new ArgumentException($
"Unable to create {symbol} consolidator because {symbol} is registered for " +
3746 Invariant($
"{subscription.Resolution.ToStringInvariant()} data. Consolidators require higher resolution data to produce lower resolution data.")
3751 if (calendar !=
null)
3754 consolidator =
CreateConsolidator(calendar, subscription.Type, subscription.TickType);
3759 if (!period.HasValue && !resolution.HasValue)
3761 period = subscription.Increment;
3764 if (period.HasValue && period.Value == subscription.Increment || resolution.HasValue && resolution.Value == subscription.Resolution)
3766 consolidator = CreateIdentityConsolidator(subscription.Type);
3770 if (resolution.HasValue)
3776 period = resolution.Value.ToTimeSpan();
3778 consolidator ??=
CreateConsolidator(period.Value, subscription.Type, subscription.TickType);
3782 if (consolidatorType !=
null && !consolidatorType.IsAssignableFrom(consolidator.
OutputType))
3784 throw new ArgumentException(
3785 $
"Unable to consolidate with the specified handler because the consolidator's output type " +
3786 $
"is {consolidator.OutputType.Name} but the handler's input type is {subscription.Type.Name}.");
3788 return consolidator;
3795 if (typeof(
TradeBar).IsAssignableFrom(consolidatorInputType))
3802 if (typeof(
QuoteBar).IsAssignableFrom(consolidatorInputType))
3809 if (typeof(
Tick).IsAssignableFrom(consolidatorInputType))
3819 if (typeof(
DynamicData).IsAssignableFrom(consolidatorInputType))
3831 private static IDataConsolidator CreateIdentityConsolidator(Type consolidatorInputType)
3833 if (typeof(
TradeBar).IsAssignableFrom(consolidatorInputType))
3837 else if (typeof(
QuoteBar).IsAssignableFrom(consolidatorInputType))
3841 else if (typeof(
Tick).IsAssignableFrom(consolidatorInputType))
3845 else if (typeof(
DynamicData).IsAssignableFrom(consolidatorInputType))
3856 Func<IBaseData, decimal> selector =
null, params
Symbol[] symbols)
3858 var dataType = GetDataTypeFromSelector(selector);
3859 foreach (var symbol
in symbols)
3871 Func<IBaseData, T> selector =
null, params
Symbol[] symbols)
3874 foreach (var symbol
in symbols)
3889 var symbols =
new List<Symbol> { symbol, symbol.Underlying };
3890 if (mirrorOption !=
null)
3893 symbols.Add(mirrorOption);
3907 $
"{typeof(T).Name}({riskFreeRate},{dividendYield},{OptionIndicatorBase.GetOptionModel(optionModel, symbol.ID.OptionStyle)})",
3910 riskFreeRateModel = riskFreeRate.HasValue
3915 if (dividendYield.HasValue)
3930 indicatorBase?.Consolidators.Add(consolidator);
3936 private DateTime GetIndicatorAdjustedHistoryStart(
IndicatorBase indicator, IEnumerable<Symbol> symbols, DateTime start, DateTime end,
Resolution? resolution =
null)
3939 if (warmupPeriod != 0)
3942 if (warmupPeriod > 0)
3946 var adjustedStart = _historyRequestFactory.
GetStartTimeAlgoTz(request.StartTimeUtc, request.Symbol, warmupPeriod, request.Resolution,
3947 request.ExchangeHours, request.DataTimeZone, request.DataType, request.IncludeExtendedMarketHours);
3948 if (adjustedStart < start)
3950 start = adjustedStart;
3966 return dataNormalizationMode;
3975 var indicatorType = indicator.GetType();
3977 var indicatorsDataPointPerProperty = indicatorType.GetProperties()
3978 .Where(x => x.PropertyType.IsGenericType && x.Name !=
"Consolidators" && x.Name !=
"Window")
3983 var indicatorsDataPointsByTime =
new List<IndicatorDataPoints>();
3984 var lastConsumedTime = DateTime.MinValue;
3988 if (newInputPoint ==
null || lastConsumedTime == newInputPoint.
EndTime)
3992 lastConsumedTime = newInputPoint.
EndTime;
3996 for (var i = 0; i < indicatorsDataPointPerProperty.Count; i++)
3998 var newPoint = indicatorsDataPointPerProperty[i].UpdateValue();
4005 if (!indicator.IsReady)
4010 if (lastPoint ==
null || lastPoint.
Time != newInputPoint.
Time)
4015 consumeLastPoint(newInputPoint);
4017 lastPoint = newInputPoint;
4021 indicator.Updated += callback;
4025 history.PushThrough(bar => updateIndicator(bar), dataType);
4030 foreach (var dataDictionary
in history.Get<
T>())
4032 foreach (var dataPoint
in dataDictionary.Values)
4034 updateIndicator(dataPoint);
4039 consumeLastPoint(lastPoint);
4040 indicator.Updated -= callback;
4042 return new IndicatorHistory(indicatorsDataPointsByTime, indicatorsDataPointPerProperty,
4044 () =>
PandasConverter.GetIndicatorDataFrame(indicatorsDataPointPerProperty.Select(x =>
new KeyValuePair<
string, List<IndicatorDataPoint>>(x.Name, x.Values))),
4045 isThreadSafe:
false));
4048 private Type GetDataTypeFromSelector(Func<IBaseData, decimal> selector)
4050 Type dataType =
null;
4051 if (_quoteRequiredFields.Any(x => ReferenceEquals(selector, x)))
4055 else if (ReferenceEquals(selector, Field.Volume))