Indicators

A library of functions for filtering and retrieving information of price curves, from traditional technical analysis up to more advanced transformation and statistics function: moving averages, oscillators, bands, momentum, strength indices, linear regression, Hilbert transforms, Ehlers indicators, and spectral analysis.

The indicators are listed in alphabetical order. Traditional indicators use the TA-Lib indicator library by Mario Fortier (www.ta-lib.org) that has established itself as a standard. Information about the usage, the algorithms, and the source code of the TA-Lib indicators can be found online at www.tadoc.org; the source is also included in the Zorro/Source folder. The source code of most other indicators and analysis functions can be found in Zorro/include/indicators.c. Spectral filters and amplitude/frequency analysis functions are listed in the spectral library. Classical candle patterns can be found in the pattern library.

AC(vars Data): var

Accelerator Oscillator; the difference of the AO indicator (see below) and its 5-bar simple moving average (SMA). Believed to indicate acceleration and deceleration of a 'market driving force' (whatever that means). For Data normally a MedPrice or price series is used. Source code in indicators.c.

ADO(): var

Accumulation/Distribution Oscillator: ((Close-Low)-(High-Close))/(High-Low). Ranges from -1 when the close is the low of the bar, to +1 when it's the high. Supposed to gauge supply and demand by determining whether traders are generally "accumulating" (buying) or "distributing" (selling). This indicator was published in many individual variants to the formula, but none of them seems any better than the other. Uses the current asset price series. Source code in indicators.c.

ADX(int TimePeriod): var

Average Directional Movement Index. Moving average of the DX indicator (see below). Uses the current asset price series. Does not support TimeFrame. The returned values range from 0 to 100.

ADXR(int TimePeriod): var

Average Directional Movement Index Rating. The average of the current ADX and the ADX from TimePeriod bars ago. Uses the current asset price series. Does not support TimeFrame.

Alligator(vars Data): var

Alligator Indicator. Consist of three lines: blue = SMA(13) delayed by 5 bars; red: SMA(8) delayed by 2 bars; green: SMA(5). Indicates a down trend with lines in the order blue-red-green (top to bottom), and an uptrend with green-red-blue. The closer the Alligator’s lines move, the weaker the trend gets and vice versa. Does not contain the additional 3 bars lag of the original Alligator algorithm (use Data+3 for that). For Data normally the high/low average (MedPrice series) is used. Result in rRed, rGreen, rBlue. Source code in indicators.c.

ALMA(vars Data, int TimePeriod, int Sigma, var Offset): var

ALMA(vars Data, int TimePeriod): var

Arnaud Legoux Moving Average. Based on a Gaussian distribution with a bias towards the begin of the Data series (i.e. more recent prices). Parameters: Sigma (distribution width, default 6); Offset (bias factor, default 0.85). Source code in indicators.c.

AO(vars Data): var

Awesome Oscillator; simply the difference of a 5-bar and a 34-bar SMA. For Data normally a MedPrice or price series is used. Source code in indicators.c.

APO(vars Data, int FastPeriod, int SlowPeriod, int MAType): var

Absolute Price Oscillator; a more general version of the AO. Returns the difference between two moving averages. Parameters: FastPeriod (Number of period for the fast MA), SlowPeriod (Number of period for the slow MA), MAType (Type of Moving Average).

Aroon(int TimePeriod): var

Aroon indicator. Consists of two lines (Up and Down) that measure how long it has been since the highest high/lowest low has occurred within the time period. Uses the current asset price series. Does not support TimeFrame. Result in rAroonDown, rAroonUp.

AroonOsc(int TimePeriod): var

Aroon Oscillator. Calculated by subtracting the Aroon Down from the Aroon Up. The return value will oscillate between +100 and -100. Uses the current asset price series. Does not support TimeFrame.

ATR(int TimePeriod): var

Average True Range. A measure of price volatility; useful for calculating stop loss or profit target distances. Formula: ATR = (ATR1 * (TimePeriod-1) + max(High,Close)-min(Low,Close)) / TimePeriod, where ATR1 is the ATR from the last bar. Uses the current asset prices. The function internally creates series when TimeFrame is > 1, and must then be called in a fixed order in the script. See also: Volatility, CVolatilty, TrueRange, ATRS.

ATR(vars Open, vars High, vars Low, vars Close, int TimePeriod): var

Average True Range from arbitrary price series, with arbitrary offset and time frame.

ATRS(int TimePeriod): var

Simple Average True Range. SMA of the TrueRange over the TimePeriod, using the current asset price series. A measure of price volatility, simpler to calculate than the ATR, but adapting slow to volatility changes and thus less suited for stop loss / profit targets. Used by the MT4 platform instead of the real ATR. Does not support TimeFrame. Source code in indicators.c.

AvgPrice(): var

Average Price. Simply (Open+High+Low+Close)/4 with the current asset price series.

BBands(vars Data, int TimePeriod, var NbDevUp, var NbDevDn, int MAType)

Bollinger Bands. Consist of three lines; the middle band is a simple moving average (generally 20 periods) of the typical price (TP). The upper and lower bands are n standard deviations (generally 2) above and below the middle band. The bands widen and narrow when the volatility of the price is higher or lower, respectively. Bollinger Bands indicate when the price has become relatively high or low, which is signaled through the touch or minor penetration of the upper or lower line. Result in rRealUpperBand, rRealMiddleBand, rRealLowerBand. Parameters: NbDevUp (Deviation multiplier for upper band), NbDevDn (Deviation multiplier for lower band), MAType (Type of Moving Average). Example in Indicatortest.c.

BBOsc(vars Data, int TimePeriod, var NbDev, int MAType): var

Bollinger Bands Oscillator; the percentage of the current value of the series within the Bollinger Bands.

Beta(vars Data, vars Data2, int TimePeriod): var

Beta value. A measure of a single asset's prices versus the overall market index. The asset price is given in Data and the market prices are given in Data2. The algorithm calculates the change between prices in both series and then 'plots' these changes as points in the Euclidean plane. The x value of any point is the Data2 (market) change and the y value is the Data (asset) change. The beta value is the slope of a linear regression line through these points. A beta of 1 is simple the line y=x, so the asset varies percisely with the market. A beta of less than one means the asset varies less than the market and a beta of more than one means the asset varies more than the market.

BOP(): var

Balance Of Power; simply (Close - Open)/(High - Low). Uses the current asset price series.

CCI(int TimePeriod): var

Commodity Channel Index. Variation of the price from its statistical mean, typically oscillates between +/-100. Uses the current asset price series. Does not support TimeFrame.

CI(int TimePeriod): var

Choppiness Index; measures single bar volatility in relation to the volatility of the past TimePeriod in a 1..100 range. Uses the current asset price series. Does not support TimeFrame.

ChandelierLong(int TimePeriod, var Multiplier): var

ChandelierShort(int TimePeriod, var Multiplier): var

Chandelier exit; the highest price of TimePeriod minus the ATR multiplied with Multiplier. Normally used as a trailing Stop Loss, for keeping trades in a trend and preventing an early exit as long as the trend continues. Source code in indicators.c. Does not support TimeFrame. Example in the TMF chapter.

CGOsc(vars Data, int TimePeriod): var

Center of Gravity oscillator, by John Ehlers; computes the deviation of prices from their center within the TimePeriod. Can be used to identify price turning points with almost zero lag. Source code in indicators.c.

Chikou(int Shift): var

Chikou line belonging to the Ichimoku indicator; simply the Close shifted forward by Shift (optional; default = 26). Uses the current asset price series. Source code in indicators.c.

CMO(vars Data, int TimePeriod): var

Chande Momentum Oscillator. Similar to the RSI, but divides the total data movement by the net movement ((up - down) / (up + down)).

Coral(vars Data): var

Coral Indicator, simply a T3 with TimePeriod = 60 and VolumeFactor = 0.4.

Correlation(vars Data1, vars Data2, int TimePeriod): var

Pearson's correlation coefficient between two data series over the given TimePeriod, in the range between -1..+1. A coefficient of +1.0, a "perfect positive correlation," means that changes in Data2 cause identical changes in Data1 (e.g., a change in the indicator will result in an identical change in the asset price). A coefficient of -1.0, a "perfect negative correlation," means that changes in Data2 cause identical changes in Data1, but in the opposite direction. A coefficient of zero means there is no relationship between the two series and that a change in Data2 will have no effect on Data1. This function can be also used to get the autocorrelation of a series by calculating the correlation coefficient between the original series and the same series lagged by one or two bars (series+1 or series+2).

Covariance(vars Data1, vars Data2, int TimePeriod): var

Covariance between two data series. Can be used to generate a covariance matrix f.i. for the markowitz efficient frontier calculation.

DChannel(int TimePeriod)

Donchian Channel; the minimum and maximum value of the priceHigh() and priceLow functions over the time period. Basis of the famous Turtle Trading System. Uses the current asset price series. Does not support TimeFrame. Result in rRealUpperBand, rRealLowerBand.

DCOsc(vars Data, int TimePeriod): var

Donchian Channel Oscillator; the percentage of the current Data value within the Donchian Channel. Uses the current asset and current TimeFrame.

Decycle(vars Data, int CutOffPeriod): var

Ehlers' Decycler, a low-lag trend indicator; simply Data - HighPass2(Data,CutOffPeriod). Removes all cycles below CutOffPeriod from the Data series and keeps the trend. The function internally creates series and thus must be called in a fixed order in the script. Source code in indicators.c.

DEMA(vars Data, int TimePeriod): var

Double Exponential Moving Average.

DPO(vars Data, int TimePeriod): var

Detrended Price Oscillator; believed to detect early changes in price direction. DPO = Data[0] - SMA(Data[n/2+1],n), where n is the TimePeriod. Source code in indicators.c.

DX(int TimePeriod): var

Directional Movement Index by Welles Wilder (who, by the way, discovered that "the interaction of sun, moon, and earth is the basis of all market movement". In case that sun, moon, and earth suddenly refrain from moving the market, he also invented some traditional indicators). The DX is believed to indicate trend strength. The values range from 0 to 100, but rarely get above 60. The DX uses the current asset price series and does not support TimeFrame. Formula: DX = 100 * abs(PlusDI-MinusDI) / (PlusDI+MinusDI). For PlusDI and MinusDI see the description below.

EMA(vars Data, int TimePeriod): var

EMA(vars Data, var alpha): var

Exponential Moving Average. Emphasizes more recent data values. It uses the formula EMA = alpha * data + (1-alpha) * EMA1, where alpha is a recursion factor between 0 .. 1 that is calculated from 2.0/(TimePeriod+1), and EMA1 is the previous EMA value. The smaller alpha is, the higher is the smoothing effect of the EMA formula. Both EMA functions use slightly different algorithms. The first (using a TimePeriod) does not create a series, is slower, and requires a Data length of TimePeriod+UnstablePeriod+1. The second (using alpha) creates an internal series, needs only a Data length of 2 and is much faster.

Fisher(vars Data): var

Fisher Transform; transforms a normalized Data series to a normal distributed range. The return value has no theoretical limit, but most values are between -1 .. +1. All Data values must be in the -1 .. +1 range, f.i. by normalizing with the AGC, Normalize, or cdf function. The minimum Data length is 1. Source available in indicators.c.

FisherInv(vars Data): var

Inverse Fisher Transform; compresses the Data series to be between -1 and +1. The minimum length of the Data series is 1. Source available in indicators.c.

FisherN(vars Data, int TimePeriod): var

Fisher Transform with normalizing; normalizes the Data series with the given TimePeriod and then transforms it to a normal distributed range. Similar to a Normalize filter (see below), but more selective due to the normal distribution of the output. The return value has no theoretical limit, but most values are in the -1.5 .. +1.5 range. The minimum length of the Data series is equal to TimePeriod. The function internally creates series and thus must be called in a fixed order in the script. Source available in indicators.c.

FractalDimension(vars Data, int TimePeriod): var

Fractal dimension of the Data series, by John Ehlers; normally 1..2. Smaller values mean more 'jaggies'. Can be used to detect the current market regime or to adapt moving averages to the fluctuations of a price series. Source available in indicators.c.

FractalHigh(vars Data, int TimePeriod): var

Fractal High, an indicator by Bill Williams, believed to signal when the market reverses (has nothing to do with fractals). Returns the highest Data value when it is in the center of the TimePeriod, otherwise 0.

FractalLow(vars Data, int TimePeriod): var

Fractal Low. Returns the lowest Data value when it is in the center of the TimePeriod, otherwise 0.

Gauss(vars Data, int TimePeriod): var

Gauss Filter, returns a weighted average of the data within the given time period, with the weight curve equal to the Gauss Normal Distribution. Useful for removing noise by smoothing raw data. The minimum length of the Data series is equal to TimePeriod, the lag is half the TimePeriod.

HAOpen(): var

HAClose(): var

HAHigh(): var

HALow(): var

Haiken Ashi prices, based on the current asset prices. Source code in indicators.c. Alternatively, the price curve can be converted to Haiken Ashi bars using the bar function.

HH(int TimePeriod, int Offset): var

Highest value of the priceHigh function over the TimePeriod ending with Offset (default 0). F.i. HH(3) returns the highest price of the last 3 bars. Uses the current asset preice series. Does not support TimeFrame; for multiple time frames, use MaxVal(High+Offset,Period) with a time synchronized High series instead. See also dayHigh.

HMA(vars Data, int TimePeriod): var

Hull Moving Average by Alan Hull; attempts to address lag as well as to smooth out some choppiness. Formula:HMA(n) = WMA(2*WMA(n/2) – WMA(n)),sqrt(n)). The function internally creates a series and thus must be called in a fixed order in the script. Source code in indicators.c.

HTDcPeriod(vars Data): var

Hilbert Transform - Dominant Cycle Period, developed by John Ehlers. Hilbert transform algorithms are explained in Ehler's book "Rocket Science for Traders" (see book list). This function is equivalent, but less accurate than the DominantPeriod function.

HTDcPhase(vars Data): var

Hilbert Transform - Dominant Cycle Phase.

HTPhasor(vars Data): var

Hilbert Transform - Phasor Components. Result in rInPhase, rQuadrature.

HTSine(vars Data): var

Hilbert Transform - SineWave. Result in rSine, rLeadSine.

HTTrendline(vars Data): var

Hilbert Transform - Instantaneous Trendline.

HTTrendMode(vars Data): int

Hilbert Transform trend indicator - returns 1 for Trend Mode, 0 for Cycle Mode.

Hurst (vars Data, int TimePeriod): var

Hurst exponent of the Data series; between 0..1. The Hurst exponent measures the 'memory' of a series. It quantifies the autocorrelation, i.e. the tendency either to revert to the mean (Hurst < 0.5) or to continue trending in a direction (Hurst > 0.5). This way the Hurst exponent can detect if the market is in a trending state. The TimePeriod window (minimum 20) must have sufficient length to catch the long-term trend. The function internally creates a series and thus must be called in a fixed order in the script. Source available in indicators.c.

Ichimoku()

Ichimoku(int PeriodTenkan, int PeriodKijun, int PeriodSenkou, int Offset)

Ichimoku Kinko Hyo indicator. Invented by the journalist Goichi Hosoda in 1930. A mix of the medium prices of 3 time periods; believed to give deep insight into market trends due to its enormous number of colorful lines. Offset (default 0) determines the bar for calculating the indicator. Returns 4 variables:

rTenkan = (HH+LL)/2 with PeriodTenkan (default 9)
rKijun = (HH+LL)/2 with PeriodKijun (default 26)
rSenkouA = (rTenkan+rKijun)/2, shifted forward by PeriodKijun. Forms a "cloud band" with rSenkouB.
rSenkouB = (HH+LL)/2 with PeriodSenkou (default 52), shifted forward by PeriodKijun

Another line belonging to the Ichimoku, the Chikou line, is future peeking and calculated separately. Uses the current asset price series. The function internally creates series when TimeFrame is > 1, and must then be called in a fixed order in the script. Source code in indicators.c.

IBS(): var

Internal Bar Strength; simply (Close - Low)/(High - Low). Uses the current asset price series.

KAMA(vars Data, int TimePeriod): var

Kaufman Adaptive Moving Average. An exponential moving average adjusted by price volatility, so its time period becomes shorter when volatility is high.

Keltner(vars Data, int TimePeriod, var Factor): var

Keltner Channel, by Charles Keltner. A Simple Moving Average - SMA(Data,TimePeriod) - with side bands in the distance Factor * ATRS(TimePeriod). Results in rRealUpperBand, rRealMiddleBand, rRealLowerBand. Source code in indicators.c.

Laguerre(vars Data, var alpha): var

4-element Laguerre filter. Used for smoothing data similar to an EMA, but with less lag and a wide tuning range given by the smoothing factor alpha (0..1). The low frequency components are delayed much more than the high frequency components, which enables very smooth filters with only a short amount of data. The minimum length of the Data series is 1, the minimum lookback period is 4. The function internally creates series and thus must be called in a fixed order in the script. Source available in indicators.c.

LinearReg(vars Data, int TimePeriod): var

Linear Regression, also known as the "least squares method" or "best fit." Linear Regression attempts to fit a straight trendline between several data points in such a way that the distance between each data point and the trendline is minimized. For each point, the straight line over the specified previous bar period is determined in terms of y = b + m*x. The LinearReg function returns b+m*(TimePeriod-1). For higher order regression, use the polyfit / polynom functions. For logistic regression with multiple variables, use the advise(PERCEPTRON,...) function.

LinearRegAngle(vars Data, int TimePeriod): var

Linear Regression Angle. Returns m converted to degrees. Due to the different x and y units of a price chart, the angle is normally of little use, except maybe for Gann followers.

LinearRegIntercept(vars Data, int TimePeriod): var

Linear Regression Intercept. Returns b.

LinearRegSlope(vars Data, int TimePeriod): var

Linear Regression Slope. Returns m as price difference per bar.

LL(int TimePeriod, int Offset): var

Lowest value of the priceLow function over the TimePeriod ending with Offset (default 0). F.i. LL(3,10) returns the lowest price between the last 10 and the last 13 bars. Uses the current asset price series. Does not support TimeFrame; for multiple time frames, use MinVal(Low+Offset,Period) with a time synchronized Low series instead. See also dayLow.

MACD(vars Data, int FastPeriod, int SlowPeriod, int SignalPeriod)

Moving Average Convergence/Divergence. The MACD is an intermediate-term trend indicator, created by subtracting a 26-period Exponential Moving Average (EMA, see above) from a 12-period EMA. A nine-period EMA is then applied to the MACD result to create a 'signal line'. A MACD Histogram line is finally created from the difference of the MACD to its signal line. It is believed that the zero crossing of the histogram from below is a buy signal, zero crossing from above a sell signal. The formula is:
 
rMACD = EMA(Data,FastPeriod)-EMA(Data,SlowPeriod);
rMACDSignal = EMA(rMACD,SignalPeriod);
rMACDHist = rMACD - rMACDSignal;

 
Results in rMACD, rMACDSignal, rMACDHist. Returns: rMACD. Parameters: FastPeriod (time period for the fast MA), SlowPeriod (time period for the slow MA), SignalPeriod (time period for smoothing the signal line).

MACDExt(vars Data, int FastPeriod, int FastMAType, int SlowPeriod, int SlowMAType, int SignalPeriod, int SignalMAType)

MACD with controllable MA type. Result in rMACD, rMACDSignal, rMACDHist. Parameters: FastPeriod (time period for the fast MA), FastMAType (Type of Moving Average for fast MA), SlowPeriod (time period for the slow MA), SlowMAType (Type of Moving Average for slow MA), SignalPeriod (time period for smoothing the signal line), SignalMAType (Type of Moving Average for signal line).

MACDFix(vars Data, int SignalPeriod)

Moving Average Convergence/Divergence Fix 12/26. Result in rMACD, rMACDSignal, rMACDHist. Parameters: SignalPeriod (time period for smoothing the signal line).

MAMA(vars Data, var FastLimit, var SlowLimit)

MESA Adaptive Moving Average, developed by John Ehlers (see links). Result in rMAMA, rFAMA. Parameters: FastLimit (Upper limit use in the adaptive algorithm), SlowLimit (Lower limit use in the adaptive algorithm).

MaxVal(vars Data, int TimePeriod): var

Highest value over a specified period.

MaxIndex(vars Data, int TimePeriod): int

Index of highest value over a specified period. 0 = highest value is at current bar, 1 = at one bar ago, and so on.

Median(vars Data, int TimePeriod): var

Median Filter; sorts the elements of the Data series and returns their middle value within the given time period. Useful for removing noise spikes by eliminating extreme values. The minimum length of the Data series is equal to TimePeriod, the lag is half the TimePeriod. See also Percentile.

MedPrice(): var

Center price; simply the center point (High+Low)/2 of the current candle. For the mean price - the average of all price ticks of the candle - use price().

MidPoint(vars Data, int TimePeriod): var

MidPoint over period. Simply (highest value + lowest value)/2.

MidPrice(int TimePeriod): var

Midpoint price over period. Simply (highest high + lowest low)/2 of the current asset price series. Does not support TimeFrame.

MinusDI(int TimePeriod): var

MinusDI(vars Open, vars High, vars Low, vars Close, int TimePeriod): var

Minus Directional Indicator, a part of the DX indicator. If the function is not called with different price series, the current asset price series is used.

MinusDM(int TimePeriod): var

MinusDM(vars Open, vars High, vars Low, vars Close, int TimePeriod): var

Minus Directional Movement, two versions. If the function is not called with different price series, the current asset price series is used.

MinVal(vars Data, int TimePeriod): var

Lowest value over a specified period.

MinIndex(vars Data, int TimePeriod): int

Index of lowest value over a specified period. 0 = lowest value is at current bar, 1 = at one bar ago, and so on.

MinMax(vars Data, int TimePeriod): var

Lowest and highest values and their indices over a specified period. Result in rMin, rMax, rMinIdx, rMaxIdx.

MinMaxIndex(vars Data, int TimePeriod): int

Indexes of lowest and highest values over a specified period. Result in rMinIdx, rMaxIdx. 0 = current bar, 1 = one bar ago, and so on.

MMI(vars Data, int TimePeriod): var

Market Meanness Index by Financial Hacker. Measures the meanness of the market, i.e. its mean reversal tendency, in a 0..100% range. Random numbers have a MMI of 75%. Real prices are more or less autocorrelated, so the probability of a real price series to revert to the mean is less than 75%, but normally more than 50%. The higher it is, the 'meaner' is the market. The Market Meanness Index can determine when trend following systems will become more profitable (MMI is falling) or less profitable (MMI is rising), and thus prevent losses in unprofitable periods. Source code in indicators.c.

Mom(vars Data, int TimePeriod): var

Momentum. Simply Data[0] - Data[TimePeriod]. See also diff.

Moment(vars Data, int TimePeriod, int N): var

The statistical moment N (1..4) of the Data series section given by TimePeriod. The first moment is the mean, the second is the variance, third is skewness, and fourth ist kurtosis. Source available in indicators.c.

MovingAverage(vars Data, int TimePeriod, int MAType): var

Moving average. Parameters: MAType (Type of Moving Average, see remarks).

MovingAverageVariablePeriod(vars Data, vars Periods, int MinPeriod, int MaxPeriod, int MAType): var

Moving average with variable period given by the Periods series. Parameters: MinPeriod (Value less than minimum will be changed to Minimum period), MaxPeriod (Value higher than maximum will be changed to Maximum period), MAType (Type of Moving Average, see remarks).

NATR(int TimePeriod): var

Normalized Average True Range, by John Forman. Similar to the ATR, except it is being normalized as follows: NATR = 100 * ATR(TimePeriod) / Close. Uses the current asset price series. Does not support TimeFrame.

Normalize(vars Data, int TimePeriod): var

Transforms the Data series to the -1...+1 range within the given TimePeriod. Similar to the AGC function, but does not differentiate between attack and decay. The minimum length of the Data series is equal to TimePeriod. Source available in indicators.c. See also scale.

NumInRange(vars Low, vars High, var Min, var Max, int Length): var

Number of data ranges, given by their Low and High values, that lie completely inside the interval from Min to Max within the given Length. Can be used to calculate the distribution of prices or candles. Low and High can be set to the same value for counting all values in the interval, or swapped for counting all candles that touch the interval. Range = 1..TimePeriod. Source available in indicators.c.

NumRiseFall(vars Data, int TimePeriod): var

Length of the current sequence of rising or falling values in the Data array, back to the given TimePeriod. For a rising sequence its length is returned, for a falling sequence the negative length. Range = 1..TimePeriod resp. -1..-TimePeriod. Source available in indicators.c. See the RandomWalk script and the Strategy chapter for an example. Source available in indicators.c.

NumWhiteBlack(var Body, int Offset, int TimePeriod): var

Number of white minus black candles in the given TimePeriod. Offset is the distance to the current bar (0 = current bar), Body is the minimum length of a candle to be counted. Source available in indicators.c.

Percentile(vars Data, int Length, var Percent): var

Returns the given percentile of the Data series with given Length; f.i. Percent = 95 returns the Data value that is above 95% of all other values. Percent = 50 returns the Median of the Data series. For calculating the percentage of a given percentile value, use the NumInRange function and count the elements below the percentile.

PlusDI(int TimePeriod): var

PlusDI(vars Open, vars High, vars Low, vars Close, int TimePeriod): var

Plus Directional Indicator, a part of the DX indicato, two versions. In the first version the current asset price series is used.

PlusDM(int TimePeriod): var

PlusDM(vars Open, vars High, vars Low, vars Close, int TimePeriod): var

Plus Directional Movement, two versions. In the first version the current asset price series is used.

PPO(vars Data, int FastPeriod, int SlowPeriod, int MAType): var

Percentage Price Oscillator. Parameters: FastPeriod (Number of period for the fast MA), SlowPeriod (Number of period for the slow MA), MAType (Type of Moving Average).

ProfitFactor(vars Data, int Length): var

Returns the profit factor of the Data series. The profit factor is the ratio of the sum of positive returns (i.e. Data[i-1] > Data[i]) to the sum of negative returns (i.e. Data[i-1] < Data[i]). The returned value is clipped to the 0.1...10 range. Its reciprocal must be used when the Data array is in not in series order, but in chronological order, as wins and losses are then swapped. Source available in indicators.c.

ROC(vars Data, int TimePeriod): var

Rate of change, 100 scale: ((price-prevPrice)/prevPrice)*100.

ROCP(vars Data, int TimePeriod): var

Rate of change Percentage: (price-prevPrice)/prevPrice. See also diff.

ROCR(vars Data, int TimePeriod): var

Rate of change ratio: (price/prevPrice).

ROCL(vars Data, int TimePeriod): var

Logarithmic return: log(price/prevPrice).

ROCR100(vars Data, int TimePeriod): var

Rate of change ratio, 100 scale: (price/prevPrice)*100.

Roof(vars Data, int CutoffLow, int CutoffHigh): var

Ehler's roofing filter, prepares the Data series for further computation by removing trend and noise. Applies a 2-pole highpass filter followed by the Smooth filter. Recommended values for the low and high cutoff periods are 10 and 50. The minimum length of the Data series is 2. The function internally creates series and thus must be called in a fixed order in the script. Source available in indicators.c.

RSI(vars Data, int TimePeriod): var

Relative Strength Index, by Welles Wilder. Ratio of the recent upwards data movement to the total data movement; range 0..100. The RSI is believed to indicate overbought/oversold conditions when the value is over 70/below 30. Formula: RSI = 100 * Up/(Up+Dn), where Up = EMA(max(0,Data[0]-Data[1]),TimePeriod) and Dn = EMA(max(0,Data[1]-Data[0]),TimePeriod).

RVI(int TimePeriod): var

Relative Vigor Index, by John Ehlers. Ratio of price change to the total price range: (C-O)/(H-L), averaged over the time period and smoothed with a FIR filter. Oscillates between -1 and 1. The function internally creates a series and thus must be called in a fixed order in the script. Source code in indicators.c.

SAR(var Step, var Min, var Max): var

Parabolic SAR, by Welles Wilder. The SAR runs above or below the price curve, depending on the current trend; each price curve crossing is believed to indicate a trend change. Parameters: Step (acceleration factor increment, normally 0.02), Min (acceleration factor minimum value, normally 0.02), Max (acceleration factor maximum value, normally 0.2). SAR is a recursive function that depends on the direction of the initial price candle; for consistent values the LookBack period should be long enough to contain at least one price curve crossing. Uses the current asset prices. The function internally creates a series and thus must be called in a fixed order in the script. Source code in indicators.c, example in Indicatortest.c.

ShannonGain(vars Data, int TimePeriod): var

Expected logarithmic gain rate of the Data series in the range of about +/-0.0005. The gain rate is derived from the Shannon probability P = (1 + Mean(Gain) / RootMeanSquare(Gain)) / 2, which is the likeliness of a rise or fall of a high entropy data series in the next bar period. A positive gain rate indicates that the series is more likely to rise, a negative gain rate indicates that it is more likely to fall. The zero crossover could be used for a trade signal. Algorithm by John Conover. Source available in indicators.c.

ShannonEntropy(vars Data, int Length, int PatternSize): var

Entropy of patterns in the Data series, in bit; can be used to determine the 'randomness' of the data. PatternSize (2..8) determines the partitioning of the data into patterns of up to 8 bit. Each Data value is either higher than the previous value, or it is not; this is a binary information and constitutes one bit of the pattern. The more random the patterns are distributed, the higher is the Shannon entropy. Totally random data has a Shannon entropy identical to the pattern size. Algorithm explained on the Financial Hacker blog; source available in indicators.c.

SIROC(vars Data, int TimePeriod, int EMAPeriod): var

Smoothed Rate of Change (S-RoC) by Fred G Schutzman. Differs from the ROC (see above) in that it is based on the exponential moving average (EMA) of the Data series. Believed to indicate the strength of a trend by determining if the trend is accelerating or decelerating. Formula: (Current EMA - Previous EMA)/(Previous EMA) x 100. Source code in indicators.c.

SMA(vars Data, int TimePeriod): var

Simple Moving Average; the mean of the data, i.e. the sum divided by the time period. Use Moment when long time periods are required.

Smooth(vars Data, int CutoffPeriod): var

Ehler's super-smoothing filter, a 2-pole Butterworth filter combined with a SMA that suppresses the Nyquist frequency. Can be used as a low-lag universal filter for removing noise from price data. The minimum length of the Data series is 2. The function internally creates series and thus must be called in a fixed order in the script. Source available in indicators.c.

SMom(vars Data, int TimePeriod, int CutoffPeriod): var

Smoothed Momentum by John Ehlers; indicates the long term trend direction. TimePeriod is the momentum period, CutoffPeriod is a Butterworth filter constant for lowpass filtering the momentum. Source code in indicators.c.

Spearman(vars Data, int TimePeriod): var

Spearman's rank correlation coefficient; correlation between the original Data series and the same series sorted in ascending order within TimePeriod (1..256). Returns the similarity to a steadily rising series and can be used to determine trend intensity and turning points. Range = -1..+1, lag = TimePeriod/2. For usage and details, see Stocks & Commodities magazine 2/2011. Source available in indicators.c.

StdDev(vars Data, int TimePeriod): var

Standard Deviation of the Data series in the time period, from the ta-lib. Use the square root of the second Moment when high accuracy or long time periods are required.

Stoch(int FastK_Period, int SlowK_Period, int SlowK_MAType, int SlowD_Period, int SlowD_MAType)

Stochastic Oscillator (unrelated to stochastics, but its inventor, George Lane, looked for a fancy name). Measures where the Close price is in relation to the recent trading range. Formula: FastK = 100 * (Close-LL)/(HH-LL); SlowK = MA(FastK); SlowD = MA(SlowK). Uses the current asset price series and does not support TimeFrame. Result in rSlowK, rSlowD. Some traders believe that the SlowK crossing above SlowD is a buy signal; others believe they should buy when SlowD is below 20 and sell when it is above 80. Parameters:
FastK_Period
- Time period for the HH and LL to generate the FastK value, usually 14.
SlowK_Period - Time period for smoothing FastK to generate rSlowK; usually 3.
SlowK_MAType - Type of Moving Average for Slow-K, usually MAType_EMA.
SlowD_Period - Time period for smoothing rSlowK to generate rSlowD, usually 3.
SlowD_MAType - Type of Moving Average for Slow-D, usually MAType_EMA.

StochEhlers(vars Data, int TimePeriod, int CutOffLow, int CutOffHigh): var

Predictive stochastic oscillator by John Ehlers. Measures where the Data value is in relation to its range within TimePeriod. The data runs through a 2-pole highpass filter with period CutOffHigh and through a Butterworth lowpass filter with period CutOffLow. Indicator algorithm explained in Ehler's "Predictive Indicators" paper; usage example in the Ehlers script. Source code in indicators.c. The function internally creates series and thus must be called in a fixed order in the script.

StochF(int FastK_Period, int FastD_Period, int FastD_MAType): var

Stochastic Fast. Measures where the Close price is in relation to the recent trading range; Formula: Fast-K = 100 * (Close-LL)/(HH-LL); Fast-D = MA(Fast-K). Uses the current asset price series. Does not support TimeFrame. Result in rFastK, rFastD. Returns: FastK. Parameters:
FastK_Period
(Time period for the HH and LL of Fast-K, usually 14),
FastD_Period
(Moving Average Period for Fast-D; usually 3),
FastD_MAType
(Type of Moving Average for Fast-D, usually MAType_EMA).

StochRSI(vars Data, int TimePeriod, int FastK_Period, int FastD_Period, int FastD_MAType): var

Stochastic Relative Strength Index (RSI). Result in rFastK, rFastD. Returns: FastK. Parameters:
FastK_Period
(Time period for building the Fast-K line),
FastD_Period
(Smoothing for making the Fast-D line. Usually set to 3),
FastD_MAType
(Type of Moving Average for Fast-D).

Sum(vars Data, int TimePeriod): var

Sum of all Data elements in the time period.

T3(vars Data, int TimePeriod, var VFactor): var

An extremely smoothed Moving Average by Tim Tillson. Uses a weighted sum of multiple EMAs. Parameters: VFactor (Volume Factor, normally 0.7).

TEMA(vars Data, int TimePeriod): var

Triple Exponential Moving Average by Patrick Mulloy, calculated from (3xEMA)-(3xEMA of EMA)+(EMA of EMA of EMA).

Trima(vars Data, int TimePeriod): var

Triangular Moving Average (also known under the name TMA); a form of Weighted Moving Average where the weights are assigned in a triangular pattern. F.i. the weights for a 7 period Triangular Moving Average would be 1, 2, 3, 4, 3, 2, 1. This gives more weight to the middle of the time series. It causes better smoothing, but greater lag.

Trix(vars Data, int TimePeriod): var

1-day Rate-Of-Change (see ROC) of a Triple EMA (see TEMA).

TrueRange(): var

True Range (TR); max(High[0],Close[1])-min(Low[0],Close[1]) of the current asset price series. See also ATR, ATRS.

TSF(vars Data, int TimePeriod): var

Time Series Forecast. Returns b + m*(TimePeriod), i.e. the Linear Regression forecast for the next bar.

TSI(vars Data, int TimePeriod): var

Trend Strength Index, an indicator by Frank Hassler who believed that it identifies trend strength. A high TSI value (above ~ 1.65) indicates that short-term trend continuation is more likely than short-term trend reversal. The function internally creates series and thus must be called in a fixed order in the script.

TypPrice(): var

Typical Price. Simply (High + Low + Close)/3. Uses the current asset price series.

UltOsc(int TimePeriod1, int TimePeriod2, int TimePeriod3): var

Ultimate Oscillator. Parameters: TimePeriod1 (Number of bars for 1st period.), TimePeriod2 (Number of bars for 2nd period), TimePeriod3 (Number of bars for 3rd period). Uses the current asset price series. Does not support TimeFrame.

UO(vars Data, int CutOff): var

Universal oscillator by John Ehlers, from S&C Magazine 1/2015. Removes white noise from the data, smoothes it and runs it through the AGC filter. Detects trend reversals very early. Output in the -1..+1 range. Source code in indicators.c. The function internally creates series and thus must be called in a fixed order in the script.

Variance(vars Data, int TimePeriod): var

Variance of the Data series in the time period, from the ta-lib. Use Moment when high accuracy or long time periods are required.

Volatility(vars Data, int TimePeriod): var

Annualized volatility of the Data series; standard deviation of the log returns, multiplied with the square root of time frames in a year. This is the standard measure of volatility used for financial models, such as the Black-Scholes model. The function internally creates series and thus must be called in a fixed order in the script. Source code in indicators.c.

VolatilityC(int TimePeriod, int EMAPeriod): var

Chaikin Volatility indicator by Marc Chaikin; measures volatility in percent as momentum of the smoothed difference between High and Low. An increase in the Chaikin Volatility indicates that a bottom is approaching, a decrease indicates that a top is approaching. TimePeriod is the period of the momentum (normally 10), EMAPeriod determines the smoothing (also, normally 10). Uses the current asset price series. The function internally creates series and thus must be called in a fixed order in the script. Source code in indicators.c.

VolatilityMM(vars Data, int TimePeriod, int EMAPeriod): var

Min/Max volatility of the Data series; the difference of MaxVal and MinVal in the time period, smoothed by an EMA (set EMAPeriod = 0 for not smoothing). The function internally creates a series when EMAPeriod > 0, and then must be called in a fixed order in the script. Source available in indicators.c. For the volatility of price candles, use ATR or ATRS.

VolatilityOV(int Days): var

Annualized volatility of the current asset, calculated over the given number of Days (usually 20). Empirical formula used by some options software packages (OptionsVue™) for estimating the values of options, alternatively to Volatility(). Source code in options.c, which must be included for using this indicator.

WCLPrice(): var

Weighted Close Price. Uses the current asset price series.

WillR(int TimePeriod): var

Williams' Percent Range. Formula: -100* (HH-Close)/(HH-LL). Uses the current asset price series. Does not support TimeFrame.

WMA(vars Data, int TimePeriod): var

Linear Weighted Moving Average; the weight of every bar decreases linearly with its age.

ZigZag(vars Data, var Depth, int Length, int Color): var

ZigZag indicator; converts the Data series into alternating straight trend lines with at least the given Depth and Length. Non-predictive; can only identify trends in hindsight. Returned: rSlope (the slope of the last identified trend line; upwards trends have a positive slope, downwards trends a negative slope); rPeak (the bar offset of the last identified peak); rSign (1 if the last peak was a top, -1 if the last peak was a bottom); rLength (the number of bars of the last trend line ending with rPeak). If a nonzero Color is given, the trend lines are plotted in the chart. Source code in indicators.c, example in Indicatortest.c. The function internally creates series and thus must be called in a fixed order in the script.

ZMA(vars Data, int TimePeriod): var

Zero-lag Moving Average by John Ehlers; smoothes the Data series with an Exponential Moving Average (EMA) and applies an error correction term for compensating the lag. The function internally creates a series and thus must be called in a fixed order in the script. Source in indicators.c.
 

Standard parameters:

TimePeriod The number of bars for the time period of the function, if any; or 0 for using a default period.
MAType The type of the moving average used by the function: MAType_SMA (default), MAType_EMA, MAType_WMA, MAType_DEMA, MAType_TEMA, MAType_TRIMA, MAType_KAMA, MAType_MAMA, MAType_T3.
Data A data series, often directly derived from the price functions price(), priceClose() etc.. Alternatively a user created series or any other double float array with the given minimum length can be used. If not mentioned otherwise, the minimum length of the Data series is TimePeriod. Some functions require a second data array Data2.
Open, High,
Low, Close
Price data series can be explicitly given for some indicators, for using price series generated from a different asset or with a different TimeFrame. Otherwise the prices of the current asset with a time frame equivalent to the bar period are used.

Returns:

Price variation or percentage, dependent on the function, for the current bar.

Usage example:

MACD(Price,12,26,9) calculates the standard MACD for the given Price series. The results are stored in the global variables rMACD, rMACDSignal, and rMACDHistory.

Remarks:

Examples:

// plot some indicators
function run()
{
  set(PLOTNOW);
  var* Price = series(price());

// plot Bollinger bands BBands(Price,30,2,2,MAType_SMA);
plot("Bollinger1",rRealUpperBand,BAND1,0x00CC00);
plot("Bollinger2",rRealLowerBand,BAND2,0xCC00FF00);
plot("SAR",SAR(0.02,0.02,0.2),DOT,RED);
ZigZag(Price,20*PIP,5,BLUE);

// plot some other indicators
plot("ATR (PIP)",ATR(20)/PIP,NEW,RED);
plot("Doji",CDLDoji(),NEW+BARS,BLUE);
plot("FractalDim",FractalDimension(Price,30),NEW,RED);
plot("ShannonGain",ShannonGain(Price,40),NEW,RED);
}
// compare the impulse responses of some low-lag MAs 
function run()
{
  set(PLOTNOW);	
  BarPeriod = 60;
  MaxBars = 500;
  LookBack = 150;
  asset(""); // dummy asset
  ColorUp = ColorDn = 0; // don't plot a price curve
PlotWidth = 800; PlotHeight1 = 400; vars Impulse = series(1-genSquare(400,400)); int Period = 50; plot("Impulse",Impulse[0],0,GREY); plot("SMA",SMA(Impulse,Period),0,BLACK); plot("EMA",EMA(Impulse,Period),0,0x800080); plot("ALMA",ALMA(Impulse,Period),0,0x008000); // best representation of the impulse plot("Hull MA",HMA(Impulse,Period),0,0x00FF00); plot("Zero-Lag MA",ZMA(Impulse,Period),0,0x00FFFF); // fastest MA with no overshoot plot("Decycle",Decycle(Impulse,Period),0,0xFF00FF); // fastest MA with some overshoot plot("LowPass",LowPass(Impulse,Period),0,0xFF0000); plot("Smooth",Smooth(Impulse,Period),0,0x0000FF); }

See also:

Technical analysis, spectral filters, candle patterns, machine learning

► latest version online