Moving Average & Trend Patterns
MA Cluster Trend Strategy
Tags: trend, ma, slope, alignment, futures, multi_condition
Functions: sma, ts_delta, NoPosition, HasPosition
Description: Enters only while flat when the 7, 25, and 99-period moving averages align and cluster (narrow gap), with matching short-term MA slopes. Holds one directional position and closes it only when that direction's MA25 exit condition is met.
Code:
# Calculate MAs
ma7 = sma(close, 7)
ma25 = sma(close, 25)
ma99 = sma(close, 99)
# Calculate Slopes (Change over 3 bars)
slope7 = ts_delta(ma7, 3)
slope25 = ts_delta(ma25, 3)
# Alignment Condition: 7 > 25 > 99
aligned_long = (ma7 > ma25) & (ma25 > ma99)
aligned_short = (ma7 < ma25) & (ma25 < ma99)
# Cluster Condition: Relative gap is small (< 1.5%)
gap1 = (ma7 - ma25).abs() / ma25
gap2 = (ma25 - ma99).abs() / ma99
clustered = (gap1 < 0.015) & (gap2 < 0.015)
# Entry Logic
long_cond = aligned_long & clustered & (slope7 > 0) & (slope25 > 0)
short_cond = aligned_short & clustered & (slope7 < 0) & (slope25 < 0)
# Exit Logic (Close breaking MA25)
exit_long = close < ma25
exit_short = close > ma25
emit(long_cond, entry(context["ticker"], "LONG", Weight(1.0), when=NoPosition(), label="MA_CLUSTER"))
emit(short_cond, entry(context["ticker"], "SHORT", Weight(1.0), when=NoPosition(), label="MA_CLUSTER"))
# Exit specific positions
emit(exit_long, exit_position(context["ticker"], when=HasPosition(side="LONG"), label="MA_CLUSTER"))
emit(exit_short, exit_position(context["ticker"], when=HasPosition(side="SHORT"), label="MA_CLUSTER"))
Golden Cross with ADX Filter
Tags: trend, crossover, filter, adx, golden_cross
Functions: sma, adx, cross_over
Description: Enters on an SMA 50/200 golden cross only when ADX is above 25, preventing losses in sideways markets.
Code:
ma_fast = sma(close, 50)
ma_slow = sma(close, 200)
trend_strength = adx(high, low, close, 14)
# Conditions
golden_cross = (ma_fast > ma_slow) & (ma_fast.shift(1) <= ma_slow.shift(1))
strong_trend = trend_strength > 25
# Entry
long_cond = golden_cross & strong_trend
# Exit: Death Cross
exit_cond = (ma_fast < ma_slow) & (ma_fast.shift(1) >= ma_slow.shift(1))
emit(long_cond, entry(context["ticker"], "LONG", Weight(1.0), label="GC_TREND"))
emit(exit_cond, exit_position(context["ticker"]))
Slope-based Trend Following
Tags: trend, linear_regression, slope, angle
Functions: linear_reg_slope
Description: Enters when the linear regression slope is positive and increasing, signaling an accelerating uptrend.
Code:
# Calculate Linear Regression Slope (20 period)
lr_slope = linear_reg_slope(close, 20)
# Entry: Slope is positive and increasing
long_cond = (lr_slope > 0) & (lr_slope > lr_slope.shift(1))
# Exit: Slope turns negative
exit_cond = lr_slope < 0
emit(long_cond, entry(context["ticker"], "LONG", Weight(1.0), label="LR_SLOPE"))
emit(exit_cond, exit_position(context["ticker"]))