mirror of
https://github.com/mihakralj/QuanTAlib.git
synced 2026-08-08 14:07:44 +00:00
86fe32a682
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com> Co-authored-by: aider (openrouter/anthropic/claude-sonnet-4) <aider@aider.chat> Co-authored-by: Warp <agent@warp.dev>
43 lines
1.4 KiB
Plaintext
43 lines
1.4 KiB
Plaintext
// The MIT License (MIT)
|
|
// © mihakralj
|
|
//@version=6
|
|
indicator("Exponential Moving Average (EMA)", "EMA", overlay=true)
|
|
|
|
//@function Calculates EMA using exponential smoothing with compensator
|
|
//@doc https://github.com/mihakralj/pinescript/blob/main/indicators/trends_IIR/ema.md
|
|
//@param source Series to calculate EMA from
|
|
//@param period Lookback period for EMA calculation
|
|
//@param alpha Optional smoothing factor (overrides period if provided)
|
|
//@returns EMA value from first bar with proper compensation
|
|
//@optimized Uses exponential warmup compensator for O(1) complexity and valid output from bar 1
|
|
ema(series float source, simple int period=0, simple float alpha=0) =>
|
|
if alpha <= 0 and period <= 0
|
|
runtime.error("Alpha or period must be provided")
|
|
float a = alpha > 0 ? alpha : 2.0 / (period + 1)
|
|
float beta = 1.0 - a
|
|
var bool warmup = true
|
|
var float e = 1.0
|
|
var float ema = 0.0
|
|
var float result = source
|
|
ema := a * (source - ema) + ema
|
|
if warmup
|
|
e *= beta
|
|
float c = 1.0 / (1.0 - e)
|
|
result := c * ema
|
|
warmup := e > 1e-10
|
|
else
|
|
result := ema
|
|
result
|
|
|
|
// ---------- Main loop ----------
|
|
|
|
// Inputs
|
|
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)
|