Strategy · Pine Script v6 · On the chart

Aurora KAMA Trend

by ZhijuCen

This strategy plots Kaufman's Adaptive Moving Average on the price chart and trades when that average rises or falls for a set number of bars.

View on GitHub

GitHub stars2on the repository
Pine versionv6current
Lines of code179
Settings15inputs
LicenceMIT
Last update2 weeks ago12 Oct 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new strategy, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart. The trades and results appear in the Strategy Tester tab; adjust the settings with the gear icon.

Source Code

179 lines of Pine Script v6 from skills/mql5-from-pinescript/assets/pine-scripts/aurora-kama.pine, published under MIT. Keep the author's credit and licence lines when you reuse it.

aurora-kama.pine
//@version=6
strategy(
     "Aurora KAMA Trend",
     shorttitle          = "Aurora-KAMA",
     overlay              = true,
     initial_capital      = 10000,
     default_qty_type     = strategy.percent_of_equity,
     default_qty_value    = 25,
     commission_type      = strategy.commission.percent,
     commission_value     = 0.05,
     slippage              = 1,
     pyramiding            = 1,
     calc_on_order_fills   = false,
     max_labels_count      = 500
     )

//#region --- Inputs ---

string G1 = "KAMA Settings"
float  src         = input.source(close, "Source",              group = G1)
int    kamaLen     = input.int(10, "Efficiency Ratio Length", minval = 2, group = G1)
int    fastLen     = input.int(2,  "Fast EMA Length",         minval = 1, group = G1)
int    slowLen     = input.int(30, "Slow EMA Length",         minval = 1, group = G1)

string G2 = "Trend Confirmation"
int    risingLen   = input.int(3, "KAMA Rising Persistence (bars)",  minval = 1, group = G2)
int    fallingLen  = input.int(3, "KAMA Falling Persistence (bars)", minval = 1, group = G2)
bool   useSmaFilter = input.bool(true, "Use Long-Term Trend Filter", group = G2)
int    smaLen       = input.int(200, "Trend Filter SMA Length",      group = G2)

string G3 = "Trade Management"
string direction    = input.string("Long and Short", "Trade Direction",
     options = ["Long", "Short", "Long and Short"], group = G3)
int    barsBetween  = input.int(5, "Minimum Bars Between Entries", minval = 0, group = G3)

string G4 = "Risk Management"
bool   useStop       = input.bool(true,  "Use Fixed Stop Loss %",   group = G4)
float  stopPct       = input.float(4.0, "Stop Loss %", minval = 0.1, group = G4)
bool   useTrail      = input.bool(true,  "Use Delayed Trailing Stop", group = G4)
float  trailPct      = input.float(6.0, "Trailing Stop %",      minval = 0.1, group = G4)
int    trailDelay    = input.int(5, "Delay Trailing by N Bars", minval = 0, group = G4)

//#endregion


//#region --- KAMA calculation ---

// @function Kaufman's Adaptive Moving Average
// @param source   Price series to smooth
// @param len      Lookback used to calculate the Efficiency Ratio
// @param fLen     Fastest EMA length, used when price is trending strongly
// @param sLen     Slowest EMA length, used when price is choppy/noisy
// @returns        The adaptive moving average value
kama(float source, int len, int fLen, int sLen) =>
    float change     = math.abs(source - source[len])
    float volatility = math.sum(math.abs(source - source[1]), len)
    float er         = volatility != 0 ? change / volatility : 0.0
    float fastSC      = 2.0 / (fLen + 1)
    float slowSC       = 2.0 / (sLen + 1)
    float sc          = math.pow(er * (fastSC - slowSC) + slowSC, 2)
    var float result  = na
    result := na(result[1]) ? source : result[1] + sc * (source - result[1])
    result

float kamaVal = kama(src, kamaLen, fastLen, slowLen)
float trendSma = ta.sma(close, smaLen)

//#endregion


//#region --- Signal logic ---

bool kamaRising  = ta.rising(kamaVal, risingLen)
bool kamaFalling = ta.falling(kamaVal, fallingLen)

bool longTrendOk  = not useSmaFilter or close > trendSma
bool shortTrendOk = not useSmaFilter or close < trendSma

bool allowLong  = direction == "Long"  or direction == "Long and Short"
bool allowShort = direction == "Short" or direction == "Long and Short"

var int lastTradeBar = na
bool cooldownOk = na(lastTradeBar) or (bar_index - lastTradeBar >= barsBetween)

bool longSignal  = kamaRising  and longTrendOk  and allowLong  and cooldownOk
bool shortSignal = kamaFalling and shortTrendOk and allowShort and cooldownOk

//#endregion


//#region --- Orders ---

bool longEntry  = false
bool shortEntry = false

if longSignal and strategy.position_size <= 0
    strategy.close("Short")
    strategy.entry("Long", strategy.long)
    lastTradeBar := bar_index
    longEntry := true

if shortSignal and strategy.position_size >= 0
    strategy.close("Long")
    strategy.entry("Short", strategy.short)
    lastTradeBar := bar_index
    shortEntry := true

// --- Risk management: stop loss + delayed trailing stop ---
bool  inPosition     = strategy.opentrades > 0
int   barsInPosition = inPosition ? bar_index - strategy.opentrades.entry_bar_index(0) : 0
bool  trailArmed     = inPosition and barsInPosition >= trailDelay

float stopDist  = strategy.position_avg_price * stopPct  / 100
float trailDist = strategy.position_avg_price * trailPct / 100

if strategy.position_size > 0
    strategy.exit(
         "Exit Long", from_entry = "Long",
         stop         = useStop  ? strategy.position_avg_price - stopDist  : na,
         trail_points  = (useTrail and trailArmed) ? trailDist / syminfo.mintick : na,
         trail_offset  = (useTrail and trailArmed) ? trailDist / syminfo.mintick : na
         )

if strategy.position_size < 0
    strategy.exit(
         "Exit Short", from_entry = "Short",
         stop         = useStop  ? strategy.position_avg_price + stopDist  : na,
         trail_points  = (useTrail and trailArmed) ? trailDist / syminfo.mintick : na,
         trail_offset  = (useTrail and trailArmed) ? trailDist / syminfo.mintick : na
         )

// --- Close markers ---
bool posJustClosed = strategy.position_size[1] != 0 and strategy.position_size == 0
bool wasShort = strategy.position_size[1] < 0
bool wasLong  = strategy.position_size[1] > 0

bool closedFromShort = posJustClosed and wasShort
bool closedFromLong  = posJustClosed and wasLong

//#endregion


//#region --- Visuals ---

// KAMA line, colored by trend direction, with a red/green glow filling the
// gap between KAMA and price. Glow intensity scales with the distance
// between the two, so bigger separations glow brighter.
color kamaColor = kamaRising ? #00e676 : kamaFalling ? #ff5252 : color.gray

plotKama  = plot(kamaVal, "KAMA", color = kamaColor, linewidth = 2)
plotClose = plot(close, "Close", display = display.none)

fill(plotKama, plotClose, math.max(kamaVal, close), kamaVal,
     color.new(#00e676, 80), color.new(#00e676, 60), title = "Bullish Glow")
fill(plotKama, plotClose, kamaVal, math.min(kamaVal, close),
     color.new(#ff5252, 60), color.new(#ff5252, 80), title = "Bearish Glow")

// Long-term trend SMA rendered as a layered glow (stacked, semi-transparent
// lines behind a crisp core line), colored gold when rising and amber when falling.
float smaSlope     = ta.change(trendSma, 5)
color smaCoreColor = useSmaFilter ? (smaSlope > 0 ? #ffd600 : smaSlope < 0 ? #ff9100 : #ffe082) : na

plot(useSmaFilter ? trendSma : na, "SMA Glow Outer", color = color.new(smaCoreColor, 88), linewidth = 6)
plot(useSmaFilter ? trendSma : na, "SMA Glow Mid",   color = color.new(smaCoreColor, 72), linewidth = 4)
plot(useSmaFilter ? trendSma : na, "SMA Glow Inner",  color = color.new(smaCoreColor, 45), linewidth = 2)
plot(useSmaFilter ? trendSma : na, "SMA Core",        color = smaCoreColor,               linewidth = 1)

// Entry markers: triangles at long/short entries.
// Exit markers: gray X's where a position was closed.
plotshape(longEntry,  "Buy",  style = shape.triangleup,   location = location.belowbar,
     color = #00e676, size = size.tiny)
plotshape(shortEntry, "Sell", style = shape.triangledown, location = location.abovebar,
     color = #ff5252, size = size.tiny)
plotshape(closedFromLong,  "Exit Long",  style = shape.xcross, location = location.abovebar,
     color = color.new(color.gray, 20), size = size.tiny)
plotshape(closedFromShort, "Exit Short", style = shape.xcross, location = location.belowbar,
     color = color.new(color.gray, 20), size = size.tiny)

//#endregion

Overview

Longs require the close above an optional long-term simple moving average; shorts require the close below it. Direction, a minimum bar gap between entries, and percent-of-equity sizing are configurable. A fixed percentage stop and a delayed trailing stop are enabled by default. The script excerpt ends before the final order calls.

Details

Published by

ZhijuCen on GitHub

Type

Strategy, Pine Script v6

Draws

On the price chart

Category

Trend, Moving averages

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Sourcesourceclosesrc
Efficiency Ratio Lengthint10kamaLen
Fast EMA Lengthint2fastLen
Slow EMA Lengthint30slowLen
KAMA Rising Persistence (bars)int3risingLen
KAMA Falling Persistence (bars)int3fallingLen
Use Long-Term Trend FilterbooltrueuseSmaFilter
Trend Filter SMA Lengthint200smaLen
Trade DirectionstringLong and Shortdirection
Minimum Bars Between Entriesint5barsBetween
Use Fixed Stop Loss %booltrueuseStop
Stop Loss %float4.0stopPct
Show all 15 settings
SettingTypeDefaultVariable
Use Delayed Trailing StopbooltrueuseTrail
Trailing Stop %float6.0trailPct
Delay Trailing by N Barsint5trailDelay
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

Doge SMA

by hackingthemarkets
474 stars

Doge SMA is a long-only moving-average crossover strategy drawn on the price chart. It calculates a fast and a slow simple moving average of close and enters a long position when the fast average crosses above the slow average, but only inside a user-defined s

Strategy v4 TrendMoving averages
Updated 4 years ago · None stated GitHub repository of Doge SMA

This strategy calculates and plots a fast Exponential Moving Average (EMA) and a slow EMA directly on the main price chart. It enters long trades when the fast EMA crosses above the slow EMA and exits when the fast EMA crosses below the slow EMA. Inputs allow

Strategy v6 TrendMoving averages
Updated today · AGPL-3.0 GitHub repository of Forven S01508 — Simple EMA20/50 Cross
330 stars

2 EMA/SMA + RSI Strategy [Alorse] combines three configurable moving averages with a short-period Relative Strength Index filter. It plots fast, slow, and trend moving averages on the price chart. Long entries trigger when the fast moving average is above the

Strategy v4 TrendOscillators & momentum
Updated 2 months ago · None stated GitHub repository of 2 EMA/SMA + RSI Strategy [Alorse]

Acrypto - Weighted Strategy

by AlbertoCuadra
318 stars

This strategy plots on the price chart and opens long or short positions when a weighted score from MACD, Stochastic RSI, RSI, Supertrend and a moving-average crossover exceeds a user-set trigger. Each component has its own weight and candle delay. Entries can

Strategy v5 TrendOscillators & momentum
Updated 3 years ago · Custom licence GitHub repository of Acrypto - Weighted Strategy
257 stars

This strategy calculates dynamic support and resistance levels using pivot highs and lows alongside a custom smoothed trend filter and a 3-period EMA. It identifies entry opportunities when price breaks out relative to the trend filter and short-term EMA cross

Strategy v5 TrendSupport & resistance Repaints
Updated 6 weeks ago · None stated GitHub repository of 30s - ES 1m Strategy Candle Bar

More strategys

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers