Files
Miha Kralj 6f0a339c9b fix: resolve build and test errors
- Sar.Quantower.Tests.cs: add missing opening quote on string literal (line 48)
- Exports.cs: rename Correlation.Batch → Correl.Batch (CS0103)
- Ad.Validation.Tests.cs: fix Ooples OutputValues key "Ad" → "Adl"
2026-03-16 12:45:13 -07:00

42 KiB

PineScript Guide: QuanTAlib Indicators for TradingView

"You do not need to understand the math. But the math does not care whether you understand it."

Welcome, Brave Copy-Paster

You are here because you want an indicator on your TradingView chart. Maybe someone on Crypto Twitter posted a screenshot with colored lines and you thought "I need that." Maybe you googled "best RSI Pine Script" at 2 AM. Maybe you clicked a link by accident. All valid paths to enlightenment.

Here is the good news: QuanTAlib provides Pine Script v6 source code for every one of its 393 indicators. Each script is self-contained, tested against the C# reference implementation, and ready to paste into TradingView's Pine Editor. No dependencies. No imports. No subscription to someone's Discord.

Here is the less-good news: the scripts contain actual mathematics. You do not have to read it. But it is there, silently judging.

How to Use a Pine Script (The Short Version)

  1. Find the indicator you want (see tables below)
  2. Click the link to open the .pine file
  3. Copy the entire file contents
  4. Open TradingView. Click "Pine Editor" at the bottom
  5. Delete whatever is in there. Paste the code
  6. Click "Add to chart"
  7. Adjust the inputs in the indicator settings panel

That is it. You have deployed a mathematically rigorous indicator without writing a single line of code. Your ancestors would be proud.

Finding Your Indicator

Every indicator has a .pine file sitting next to its C# implementation and documentation. The folder structure is predictable:

lib/
  trends_IIR/
    ema/
      Ema.cs          ← the actual engine (C#, you can ignore this)
      Ema.md          ← documentation (math, history, validation)
      ema.pine        ← THIS IS WHAT YOU WANT

By category

Pick your category. Find your indicator. Click the .pine link. Copy. Paste. Done.


Core (price transforms)

These turn OHLC data into derived price series. If you do not know what "typical price" means, you probably want close instead.

Indicator What It Does Pine Script
AVGPRICE Average Price avgprice.pine
HA Heikin-Ashi ha.pine
MEDPRICE Median Price medprice.pine
MIDPOINT Rolling Range Midpoint midpoint.pine
MIDPRICE Midpoint Price midprice.pine
TYPPRICE Typical Price typprice.pine
WCLPRICE Weighted Close Price wclprice.pine

Moving Averages: FIR (the "simple" ones)

FIR stands for Finite Impulse Response. It means the average uses a fixed window of bars. SMA is an FIR filter. You have been using FIR filters this whole time.

Indicator What It Does Pine Script
ALMA Arnaud Legoux MA alma.pine
BLMA Blackman Window MA blma.pine
BWMA Bessel-Weighted MA bwma.pine
CONV Convolution MA conv.pine
CRMA Cubic Regression MA crma.pine
DWMA Double Weighted MA dwma.pine
FWMA Fibonacci Weighted MA fwma.pine
GWMA Gaussian Weighted MA gwma.pine
HAMMA Hamming MA hamma.pine
HANMA Hanning MA hanma.pine
HEND Henderson Moving Average hend.pine
HMA Hull MA hma.pine
ILRS Integral of LinReg Slope ilrs.pine
KAISER Kaiser Window MA kaiser.pine
LANCZOS Lanczos (sinc) Window MA lanczos.pine
LSMA Least Squares MA lsma.pine
NLMA Non-Lag MA nlma.pine
NYQMA Nyquist MA nyqma.pine
PARZEN Parzen Window MA parzen.pine
PMA Predictive Moving Average pma.pine
PWMA Pascal Weighted MA pwma.pine
QRMA Quadratic Regression MA qrma.pine
RAIN Rainbow MA rain.pine
RWMA Range Weighted MA rwma.pine
SGMA Savitzky-Golay MA sgma.pine
SINEMA Sine Weighted MA sinema.pine
SMA Simple MA sma.pine
SP15 Spencer's 15-Point MA sp15.pine
SWMA Symmetric Weighted MA swma.pine
TRIMA Triangular MA trima.pine
TSF Time Series Forecast tsf.pine
TUKEY_W Tukey (Tapered Cosine) Window MA tukey_w.pine
WMA Weighted MA wma.pine

Moving Averages: IIR (the "smart" ones)

IIR stands for Infinite Impulse Response. These use recursive feedback: the previous output affects the current output. Generally smoother, lower lag, and harder to understand. The indicator descriptions link to documentation if curiosity ever strikes.

Indicator What It Does Pine Script
ADXVMA ADX Variable MA adxvma.pine
AHRENS Ahrens MA ahrens.pine
CORAL Coral Trend Filter coral.pine
DECYCLER Ehlers Decycler decycler.pine
DEMA Double Exponential MA dema.pine
DSMA Deviation-Scaled MA dsma.pine
EMA Exponential MA ema.pine
FRAMA Ehlers Fractal Adaptive MA frama.pine
GDEMA Generalized DEMA gdema.pine
HEMA Hull Exponential MA hema.pine
HOLT Holt Exponential Smoothing holt.pine
HT_TRENDLINE Ehlers Hilbert Transform Instant Trendline ht_trendline.pine
HWMA Holt-Winters MA hwma.pine
JMA Jurik MA jma.pine
KAMA Kaufman Adaptive MA kama.pine
LEMA Leader EMA lema.pine
LTMA Linear Trend MA ltma.pine
MAMA Ehlers MESA Adaptive MA mama.pine
MAVP Moving Average Variable Period mavp.pine
MCNMA McNicholl EMA mcnma.pine
MGDI McGinley Dynamic mgdi.pine
MMA Modified MA mma.pine
NMA Natural Moving Average nma.pine
QEMA Quadruple Exponential MA qema.pine
REMA Regularized Exponential MA rema.pine
RGMA Recursive Gaussian MA rgma.pine
RMA wildeR MA rma.pine
T3 Tillson T3 MA t3.pine
TEMA Triple Exponential MA tema.pine
TRAMA Trend Regularity Adaptive MA trama.pine
VAMA Volatility Adjusted MA vama.pine
VIDYA Variable Index Dynamic Average vidya.pine
YZVAMA Yang-Zhang Volatility Adjusted MA yzvama.pine
ZLDEMA Zero-Lag Double Exponential MA zldema.pine
ZLEMA Zero-Lag Exponential MA zlema.pine
ZLTEMA Zero-Lag Triple Exponential MA zltema.pine

Filters (signal processing)

These are the heavy artillery. Kalman filters, Butterworth filters, wavelets. If you do not know what a transfer function is, start with the moving averages above and come back when you are ready. No judgment. (Some judgment.)

Indicator What It Does Pine Script
AGC Ehlers Automatic Gain Control agc.pine
ALAGUERRE Ehlers Adaptive Laguerre Filter alaguerre.pine
BAXTERKING Baxter-King Band-Pass Filter baxterking.pine
BESSEL Bessel Filter bessel.pine
BILATERAL Bilateral Filter Bilateral.pine
BPF Bandpass Filter bpf.pine
BUTTER2 Ehlers 2-Pole Butterworth Filter butter2.pine
BUTTER3 Ehlers 3-Pole Butterworth Filter butter3.pine
CFITZ Christiano-Fitzgerald Filter cfitz.pine
CHEBY1 Chebyshev Type I cheby1.pine
CHEBY2 Chebyshev Type II cheby2.pine
EDCF Ehlers Distance Coefficient Filter edcf.pine
ELLIPTIC Elliptic Filter elliptic.pine
GAUSS Gaussian Filter gauss.pine
HANN Hann Filter hann.pine
HP Hodrick-Prescott Filter hp.pine
HPF Ehlers Highpass Filter hpf.pine
KALMAN Kalman Filter kalman.pine
LAGUERRE Ehlers Laguerre Filter laguerre.pine
LMS Least Mean Squares lms.pine
LOESS LOESS Smoothing loess.pine
MODF Modular Filter modf.pine
NOTCH Notch Filter notch.pine
NW Nadaraya-Watson Estimator nw.pine
ONEEURO One Euro Filter oneeuro.pine
RLS Recursive Least Squares rls.pine
RMED Ehlers Recursive Median Filter rmed.pine
ROOFING Ehlers Roofing Filter roofing.pine
SAK Ehlers Swiss Army Knife sak.pine
SGF Savitzky-Golay Filter sgf.pine
SPBF Ehlers Super Passband Filter spbf.pine
SSF2 Ehlers 2-Pole Super Smoother Filter ssf2.pine
SSF3 Ehlers 3-Pole Super Smoother Filter ssf3.pine
USF Ehlers Ultimate Smoother Filter usf.pine
VOSS Ehlers Voss Predictive Filter voss.pine
WAVELET Wavelet Denoising Filter wavelet.pine
WIENER Wiener Filter wiener.pine

Oscillators

Numbers that bounce between limits. Overbought, oversold, divergence. You know the drill.

Indicator What It Does Pine Script
AC Acceleration Oscillator ac.pine
AO Awesome Oscillator ao.pine
APO Absolute Price Oscillator apo.pine
BBB Bollinger %B bbb.pine
BBI Bulls Bears Index bbi.pine
BBS Bollinger Band Squeeze bbs.pine
BRAR Bull-Bear Power Ratio brar.pine
CFO Chande Forecast Oscillator cfo.pine
COPPOCK Coppock Curve coppock.pine
CRSI Connors RSI crsi.pine
CTI Correlation Trend Indicator cti.pine
DECO Ehlers Decycler Oscillator deco.pine
DEM DeMarker Oscillator dem.pine
DOSC Derivative Oscillator dosc.pine
DPO Detrended Price Oscillator dpo.pine
DYMI Dynamic Momentum Index dymi.pine
ER Efficiency Ratio er.pine
ERI Elder Ray Index eri.pine
FI Force Index fi.pine
FISHER Ehlers Fisher Transform fisher.pine
FISHER04 Ehlers Fisher Transform (2004) fisher04.pine
GATOR Williams Gator Oscillator gator.pine
IMI Intraday Momentum Index imi.pine
INERTIA Inertia inertia.pine
KDJ KDJ Indicator kdj.pine
KRI Kairi Relative Index kri.pine
KST Know Sure Thing Oscillator kst.pine
LRSI Ehlers Laguerre RSI lrsi.pine
MARKETFI Market Facilitation Index marketfi.pine
MSTOCH Ehlers MESA Stochastic mstoch.pine
PGO Pretty Good Oscillator pgo.pine
PSL Psychological Line psl.pine
QQE Quantitative Qualitative Estimation qqe.pine
REFLEX Ehlers Reflex reflex.pine
REVERSEEMA Ehlers Reverse EMA reverseema.pine
RVGI Relative Vigor Index rvgi.pine
SMI Stochastic Momentum Index smi.pine
SQUEEZE Squeeze Momentum squeeze.pine
STC Schaff Trend Cycle stc.pine
STOCH Stochastic Oscillator stoch.pine
STOCHF Stochastic Fast stochf.pine
STOCHRSI Stochastic RSI stochrsi.pine
TD_SEQ TD Sequential td_seq.pine
TRENDFLEX Ehlers Trendflex trendflex.pine
TRIX Triple Exponential Average trix.pine
TTM_WAVE TTM Wave ttm_wave.pine
ULTOSC Ultimate Oscillator ultosc.pine
WILLR Williams %R willr.pine

Dynamics (trend strength)

Is there a trend? How strong? These indicators answer that.

Indicator What It Does Pine Script
ADX Average Directional Index adx.pine
ADXR Average Directional Movement Rating adxr.pine
ALLIGATOR Williams Alligator alligator.pine
AMAT Archer Moving Averages Trends amat.pine
AROON Aroon aroon.pine
AROONOSC Aroon Oscillator aroonosc.pine
CHOP Choppiness Index chop.pine
DMX Jurik Directional Movement Index dmx.pine
DX Directional Movement Index dx.pine
GHLA Gann High-Low Activator ghla.pine
HT_TRENDMODE Ehlers Hilbert Transform Trend vs Cycle Mode ht_trendmode.pine
ICHIMOKU Ichimoku Cloud ichimoku.pine
MINUS_DI Minus Directional Indicator minusdi.pine
MINUS_DM Minus Directional Movement minusdm.pine
PFE Polarized Fractal Efficiency pfe.pine
PLUS_DI Plus Directional Indicator plusdi.pine
PLUS_DM Plus Directional Movement plusdm.pine
QSTICK Qstick Indicator qstick.pine
RAVI Chande Range Action Verification Index ravi.pine
SUPER SuperTrend super.pine
TTM_TREND TTM Trend TtmTrend.pine
VHF Vertical Horizontal Filter vhf.pine
VORTEX Vortex Indicator vortex.pine

Momentum

How fast price is moving. Direction matters here.

Indicator What It Does Pine Script
ASI Accumulation Swing Index asi.pine
BIAS Bias / Disparity Index bias.pine
BOP Balance of Power bop.pine
CCI Commodity Channel Index cci.pine
CFB Jurik Composite Fractal Behavior cfb.pine
CMO Chande Momentum Oscillator cmo.pine
MACD Moving Average Convergence Divergence macd.pine
MOM Momentum mom.pine
PMO Price Momentum Oscillator pmo.pine
PPO Percentage Price Oscillator ppo.pine
RS Price Relative Strength rs.pine
ROC Rate of Change roc.pine
ROCP Rate of Change Percentage rocp.pine
ROCR Rate of Change Ratio rocr.pine
RSI Relative Strength Index rsi.pine
RSX Jurik Relative Strength X rsx.pine
SAM Smoothed Adaptive Momentum sam.pine
TSI True Strength Index tsi.pine
VEL Jurik Velocity vel.pine

Volatility

How much price moves. Not direction. Just magnitude.

Indicator What It Does Pine Script
ADR Average Daily Range adr.pine
ATR Average True Range atr.pine
ATRN ATR Normalized atrn.pine
BBW Bollinger Band Width bbw.pine
BBWN Bollinger Band Width Normalized bbwn.pine
BBWP Bollinger Band Width Percentile bbwp.pine
CCV Close-to-Close Volatility ccv.pine
CV Coefficient of Variation cv.pine
CVI Chaikin's Volatility cvi.pine
ETHERM Elder's Thermometer etherm.pine
EWMA Exponential Weighted MA Volatility ewma.pine
GKV Garman-Klass Volatility gkv.pine
HLV High-Low Volatility hlv.pine
HV Historical Volatility hv.pine
JVOLTY Jurik Volatility jvolty.pine
JVOLTYN Jurik Volatility Normalized jvoltyn.pine
MASSI Mass Index massi.pine
NATR Normalized ATR natr.pine
RSV Rogers-Satchell Volatility rsv.pine
RV Realized Volatility rv.pine
RVI Relative Volatility Index rvi.pine
TR True Range tr.pine
UI Ulcer Index ui.pine
VOV Volatility of Volatility vov.pine
VR Volatility Ratio vr.pine
YZV Yang-Zhang Volatility yzv.pine

Volume

What the crowd is doing with their money.

Indicator What It Does Pine Script
AD Accumulation/Distribution Line ad.pine
ADOSC Chaikin A/D Oscillator adosc.pine
AOBV Archer On-Balance Volume aobv.pine
CMF Chaikin Money Flow cmf.pine
EFI Elder's Force Index efi.pine
EOM Ease of Movement eom.pine
EVWMA Elastic Volume Weighted MA evwma.pine
III Intraday Intensity Index iii.pine
KVO Klinger Volume Oscillator kvo.pine
MFI Money Flow Index mfi.pine
NVI Negative Volume Index nvi.pine
OBV On Balance Volume obv.pine
PVD Price Volume Divergence pvd.pine
PVI Positive Volume Index pvi.pine
PVO Percentage Volume Oscillator pvo.pine
PVR Price Volume Rank pvr.pine
PVT Price Volume Trend pvt.pine
TVI Trade Volume Index tvi.pine
TWAP Time Weighted Average Price twap.pine
VA Volume Accumulation va.pine
VF Volume Force vf.pine
VO Volume Oscillator vo.pine
VROC Volume Rate of Change vroc.pine
VWAD Volume Weighted A/D vwad.pine
VWAP Volume Weighted Average Price vwap.pine
VWMA Volume Weighted MA vwma.pine
WAD Williams A/D wad.pine

Channels (bands around price)

Upper band, lower band, sometimes a middle. Price bounces between them. In theory.

Indicator What It Does Pine Script
ABERR Aberration Bands aberr.pine
ACCBANDS Acceleration Bands accbands.pine
APCHANNEL Andrews' Pitchfork apchannel.pine
APZ Adaptive Price Zone apz.pine
ATRBANDS ATR Bands atrbands.pine
BBANDS Bollinger Bands bbands.pine
DC Donchian Channels dc.pine
DECAYCHANNEL Decay Min-Max Channel decaychannel.pine
FCB Fractal Chaos Bands fcb.pine
JBANDS Jurik Volatility Bands Jbands.pine
KC Keltner Channel kc.pine
MAENV Moving Average Envelope maenv.pine
MMCHANNEL Min-Max Channel mmchannel.pine
PC Price Channel pc.pine
REGCHANNEL Regression Channels regchannel.pine
SDCHANNEL Standard Deviation Channel sdchannel.pine
STARCHANNEL Stoller Average Range Channel starchannel.pine
STBANDS Super Trend Bands stbands.pine
UBANDS Ehlers Ultimate Bands ubands.pine
UCHANNEL Ehlers Ultimate Channel uchannel.pine
VWAPBANDS VWAP Bands vwapbands.pine
VWAPSD VWAP with Standard Deviation Bands vwapsd.pine

Cycles

Markets oscillate. These indicators try to measure the oscillation itself — the period, phase, and amplitude of dominant cycles.

Indicator What It Does Pine Script
CCOR Ehlers Correlation Cycle ccor.pine
CCYC Ehlers Cyber Cycle ccyc.pine
CG Ehlers Center of Gravity cg.pine
DSP Ehlers Detrended Synthetic Price dsp.pine
EACP Ehlers Autocorrelation Periodogram eacp.pine
EBSW Ehlers Even Better Sinewave ebsw.pine
HOMOD Ehlers Homodyne Discriminator homod.pine
HT_DCPERIOD Ehlers Hilbert Transform Dominant Cycle Period ht_dcperiod.pine
HT_DCPHASE Ehlers Hilbert Transform Dominant Cycle Phase ht_dcphase.pine
HT_PHASOR Ehlers Hilbert Transform Phasor Components phasor.pine
HT_SINE Ehlers Hilbert Transform SineWave ht_sine.pine
LUNAR Lunar Phase lunar.pine
SOLAR Solar Activity Cycle solar.pine
SSFDSP Ehlers SSF Detrended Synthetic Price ssfdsp.pine

Reversals

Where price might turn around. Pivots, stops, and fractal patterns.

Indicator What It Does Pine Script
CHANDELIER Chandelier Exit chandelier.pine
CKSTOP Chande Kroll Stop ckstop.pine
FRACTALS Williams Fractals fractals.pine
PIVOT Pivot Points pivot.pine
PIVOTCAM Camarilla Pivot Points pivotcam.pine
PIVOTDEM DeMark Pivot Points pivotdem.pine
PIVOTEXT Extended Traditional Pivots pivotext.pine
PIVOTFIB Fibonacci Pivot Points pivotfib.pine
PIVOTWOOD Woodie's Pivot Points pivotwood.pine
SAR Parabolic Stop And Reverse sar.pine
SAREXT Parabolic SAR Extended sarext.pine
SWINGS Swing High/Low Detection swings.pine
TTM_SCALPER TTM Scalper Alert ttmscalper.pine

Forecasts

Predictions. Use with appropriate skepticism.

Indicator What It Does Pine Script
AFIRMA Adaptive FIR MA afirma.pine

Statistics

Quantitative measures of price behavior. Correlation, regression, distribution analysis.

Indicator What It Does Pine Script
ACF Autocorrelation Function acf.pine
BETA Beta Coefficient beta.pine
CMA Cumulative MA cma.pine
COINTEGRATION Cointegration cointegration.pine
CORREL Correlation correl.pine
COVARIANCE Covariance covariance.pine
ENTROPY Shannon Entropy entropy.pine
GEOMEAN Geometric Mean geomean.pine
GRANGER Granger Causality granger.pine
HARMEAN Harmonic Mean harmean.pine
HURST Hurst Exponent hurst.pine
IQR Interquartile Range iqr.pine
JB Jarque-Bera Test jb.pine
KENDALL Kendall Rank Correlation kendall.pine
KURTOSIS Kurtosis kurtosis.pine
LINREG Linear Regression Curve linreg.pine
MEANDEV Mean Absolute Deviation meandev.pine
MEDIAN Rolling Median median.pine
MODE Mode mode.pine
PACF Partial Autocorrelation Function pacf.pine
PERCENTILE Percentile percentile.pine
POLYFIT Polynomial Fitting polyfit.pine
QUANTILE Quantile quantile.pine
SKEW Skewness skew.pine
SPEARMAN Spearman Rank Correlation spearman.pine
STDDEV Standard Deviation stddev.pine
STDERR Standard Error of Regression stderr.pine
SUM Rolling Sum sum.pine
THEIL Theil Index theil.pine
TRIM Trimmed Mean MA trim.pine
VARIANCE Population and Sample Variance variance.pine
WAVG Weighted Average wavg.pine
WINS Winsorized Mean MA wins.pine
ZSCORE Z-score zscore.pine
ZTEST Z-Test ztest.pine

Numerics (transforms and distributions)

Mathematical transforms, derivatives, and probability distributions. The kind of tools a quant reaches for at 3 AM.

Indicator What It Does Pine Script
ACCEL Acceleration accel.pine
BETADIST Beta Distribution betadist.pine
BINOMDIST Binomial Distribution binomdist.pine
CHANGE Percentage Change change.pine
CWT Continuous Wavelet Transform cwt.pine
DECAY Linear Decay decay.pine
DWT Discrete Wavelet Transform dwt.pine
EDECAY Exponential Decay edecay.pine
EXPDIST Exponential Distribution expdist.pine
EXPTRANS Exponential Transform exptrans.pine
FDIST F-Distribution fdist.pine
FFT Fast Fourier Transform fft.pine
GAMMADIST Gamma Distribution gammadist.pine
HIGHEST Rolling Maximum highest.pine
IFFT Inverse Fast Fourier Transform ifft.pine
JERK Jerk jerk.pine
LINEARTRANS Linear Transform lineartrans.pine
LOGNORMDIST Log-Normal Distribution lognormdist.pine
LOGTRANS Logarithmic Transform logtrans.pine
LOWEST Rolling Minimum lowest.pine
NORMALIZE Min-Max Normalization normalize.pine
NORMDIST Normal Distribution normdist.pine
POISSONDIST Poisson Distribution poissondist.pine
RELU Rectified Linear Unit relu.pine
SIGMOID Logistic Function sigmoid.pine
SLOPE First Derivative slope.pine
SQRTTRANS Square Root Transform sqrttrans.pine
TDIST Student's t-Distribution tdist.pine
WEIBULLDIST Weibull Distribution weibulldist.pine

Errors (forecast accuracy metrics)

How wrong was your model? These metrics quantify the answer. Useful for comparing indicator accuracy or building adaptive systems.

Indicator What It Does Pine Script
HUBER Huber Loss huber.pine
LOGCOSH Log-Cosh Loss logcosh.pine
MAAPE Mean Arctangent Absolute Percentage Error maape.pine
MAE Mean Absolute Error mae.pine
MAPD Mean Absolute Percentage Deviation mapd.pine
MAPE Mean Absolute Percentage Error mape.pine
MASE Mean Absolute Scaled Error mase.pine
MDAE Median Absolute Error mdae.pine
MDAPE Median Absolute Percentage Error mdape.pine
ME Mean Error me.pine
MPE Mean Percentage Error mpe.pine
MRAE Mean Relative Absolute Error mrae.pine
MSE Mean Squared Error mse.pine
MSLE Mean Squared Logarithmic Error msle.pine
PSEUDOHUBER Pseudo-Huber Loss pseudohuber.pine
QUANTILELOSS Quantile Loss quantileloss.pine
RAE Relative Absolute Error rae.pine
RMSE Root Mean Squared Error rmse.pine
RMSLE Root Mean Squared Logarithmic Error rmsle.pine
RSE Relative Squared Error rse.pine
RSQUARED Coefficient of Determination rsquared.pine
SMAPE Symmetric Mean Absolute Percentage Error smape.pine
THEILU Theil's U Statistic theilu.pine
TUKEY Tukey Biweight Loss tukeybiweight.pine
WMAPE Weighted Mean Absolute Percentage Error wmape.pine
WRMSE Weighted RMSE wrmse.pine

Anatomy of a QuanTAlib Pine Script

Every script follows the same structure. Understanding this structure is optional but occasionally useful when things do not look right on your chart.

// Licensed under the Apache License, Version 2.0
// © mihakralj
//@version=6
indicator("Exponential Moving Average (EMA)", "EMA", overlay=true)

// ---- The function definition ----
// This is where the math lives. You do not need to touch this.
ema(series float source, simple int period=0, simple float alpha=0) =>
    // ... math happens here ...
    result

// ---- Inputs ----
// These create the settings panel on TradingView
i_period = input.int(10, "Period", minval=1)
i_source = input.source(close, "Source")

// ---- Calculation ----
ema_value = ema(i_source, period=i_period)

// ---- Plot ----
plot(ema_value, "EMA", color=color.yellow, linewidth=2)

The parts that matter to you

  • Inputs section: Change 10 to whatever period you want as the default. Or just use the TradingView settings panel after adding the indicator.
  • Plot section: Change color.yellow to whatever color you prefer. Options include color.red, color.green, color.blue, color.white, color.orange, color.purple.
  • The function: Do not touch this unless you know what you are doing. It was validated against the C# reference implementation. Your modifications will not be validated against anything.

Common Questions

"The indicator shows values from bar 1 — shouldn't there be a warmup gap?"

That is correct behavior. QuanTAlib generates output from the very first bar. A 14-period RSI with only 5 bars uses the best estimate possible given available data. The values become fully converged once enough bars have accumulated, but you never see NaN or blank bars. Other libraries leave gaps. QuanTAlib fills them with mathematically defensible approximations that improve as data accumulates.

"Can I use this in a strategy?"

Yes. Replace indicator(...) with strategy(...) and add your entry/exit logic. The indicator function itself does not change.

"The values differ from TradingView's built-in version"

Possible reasons, in order of likelihood:

  1. Different default parameters. Check the period, source, and any multipliers.
  2. Different warmup handling. QuanTAlib uses exponential compensation from bar 1. TradingView's built-in indicators sometimes use different warmup methods.
  3. You are looking at the wrong indicator. DEMA is not "double EMA period." It is a specific algorithm by Patrick Mulloy.

"I modified the math and now it is broken"

Put the original code back. The math was correct before you edited it.

"Which moving average should I use?"

If you are asking this question, use EMA. It is the Honda Civic of moving averages: reliable, understood by everyone, and good enough for most situations. Come back and explore JMA, KAMA, or T3 when you have a specific problem that EMA does not solve.

"Can I combine multiple indicators?"

Yes. Add multiple scripts to your chart or combine functions within a single script:

//@version=6
indicator("EMA + RSI Combo", overlay=false)

// Calculate both
ema_val = ta.ema(close, 20)     // TradingView built-in
rsi_val = ta.rsi(close, 14)     // TradingView built-in

// Or use QuanTAlib versions by pasting the function definitions
// from their respective .pine files and calling them

plot(rsi_val, "RSI", color=color.purple)
hline(70, "Overbought", color=color.red)
hline(30, "Oversold", color=color.green)

Going Deeper (If You Dare)

Each indicator has a .md documentation file next to its .pine file. These contain:

  • Mathematical formulas (yes, with actual math notation)
  • Historical context (who invented it and why)
  • Performance characteristics
  • Validation against other libraries
  • Common pitfalls

For example: EMA documentation explains the exponential warmup compensator, why it matters, and why most other implementations get the first few values wrong.

You do not have to read any of this. But if you ever wonder why your backtest results differ from someone else's, the answer is probably in there.

The Full Catalog

All 393 indicators with descriptions →

Every indicator in that list has a .pine file. Every .pine file works on TradingView. Every implementation matches the C# reference engine.

Copy responsibly.