Sovereign Trend Strategy [JOAT]Sovereign Trend Strategy
Introduction
The Sovereign Trend Strategy is a systematic, rules-based trend-following strategy built on the SMEMA (SMA of EMA) crossover engine — a double-smoothed moving average system that removes the erratic noise of raw EMA crossovers while remaining faster to respond than pure SMA systems. It enters long and short trades on SMEMA fast/slow crossovers, applies four optional confirmation filters (ADX, RSI, volatility ratio, and baseline), and manages each trade through a full exit framework: stop loss, two take-profit levels with partial close at TP1, a dynamic trailing stop, a trend-reversal exit, and a maximum bars cap that forces turnover.
This is a strategy designed to trade constantly — the default configuration is tuned for maximum trade frequency across all assets and timeframes, with all optional filters disabled so that every valid SMEMA crossover generates a signal. Traders seeking higher-quality entries can enable the ADX, RSI, baseline, or volatility filters individually to raise the bar.
Core Concepts
SMEMA — Double-Smoothed Moving Average Engine
The SMEMA construction applies a simple moving average on top of an exponential moving average, producing a line that is more responsive than a plain SMA but smoother than a raw EMA:
smema(float src, int len) =>
ta.sma(ta.ema(src, len), len)
float fast = smema(close, smFast)
float slow = smema(close, smSlow)
float baseline = smema(close, smBase)
Three SMEMA lines are computed: a fast line (default length 2), a slow line (default length 5), and a longer baseline (default length 15). Crossovers between fast and slow generate the entry signals. The baseline provides an optional directional filter when enabled.
Entry Conditions
Long entries fire when the fast SMEMA crosses above the slow SMEMA with all active filters passing:
bool xUp = ta.crossover(fast, slow)
bool longOk = xUp and adxOk and rsiLongOk and volOk and baseOk
and warmed and inDateRange and barstate.isconfirmed and doLong
Short entries mirror this on downward crossovers. Entries only fire when there are no open trades (pyramiding disabled), ensuring clean one-trade-at-a-time management.
Trade Management Framework
Each trade uses ATR-based levels calculated at entry:
| Level | Default Multiplier | Purpose |
|-------|-------------------|---------|
| Stop Loss | 1.8× ATR | Full position stop |
| TP1 | 2.5× ATR | 50% partial close, breakeven stop move |
| TP2 | 4.5× ATR | Full position close |
| Trailing Stop | 1.5× ATR | Activated after TP1 hit |
After TP1 triggers, the stop-loss is moved to the entry price (breakeven). The trailing stop then follows price by 1.5× ATR, locking in profit while letting the remaining position run toward TP2. This staged approach captures quick-reaction profits at TP1 and rides momentum toward TP2.
Six Exit Paths
// Priority order for long exits:
// 1. Stop Loss — low <= entrySL
// 2. TP1 — high >= entryTP1 (50% partial, breakeven stop set)
// 3. TP2 — high >= entryTP2 (full close after TP1 hit)
// 4. Trailing — low <= trlStop (after TP1 hit)
// 5. Reversal — fast SMEMA crosses below slow (xDn confirmed)
// 6. Max Bars — barsInTrd >= maxBars
The max bars exit (default 10) is particularly important for trade frequency — it guarantees no position is held longer than 10 bars regardless of whether any other exit triggers, creating rapid capital recycling and enabling 100+ trade sample sizes even on daily timeframes.
Optional Confirmation Filters
All four filters are disabled by default and can be enabled individually:
ADX Filter — requires ADX above a minimum threshold before entry. Prevents entries in ranging, low-momentum markets.
RSI Filter — requires RSI above the bull minimum for longs (default 52) or below the bear maximum for shorts (default 48). Confirms momentum alignment with direction.
Volatility Ratio Filter — requires current ATR to be at least a configurable fraction of its own SMA. Filters out squeeze conditions where ATR is compressed.
Baseline Filter — requires close to be above the baseline SMEMA for longs and below for shorts. Adds a medium-term trend confirmation layer.
Strategy Parameters (Backtesting Standards)
Initial capital: $10,000 (realistic for the average retail trader)
Position size: 100% of equity (maximizes trade count visibility in backtest)
Commission: 0.05% per side (appropriate for most spot and futures markets)
Slippage: 2 ticks (conservative estimate for liquid instruments)
Pyramiding: 0 (no compounding positions)
Features
SMEMA fast/slow crossover entry engine with three configurable period lengths
Full trade management: ATR-based SL, TP1 (50% partial), TP2 (full), trailing stop, reversal exit, max bars exit
Breakeven stop migration to entry price after TP1 hit
Four optional confirmation filters: ADX, RSI, volatility ratio, and SMEMA baseline
Long-only, short-only, or both directions configurable
Date range filter for restricted backtesting windows
Live SL, TP1, and TP2 dashed lines drawn on the chart while a trade is open
SMEMA ribbon fill between fast and slow lines, colored by crossover direction
▲ LONG / ▼ SHORT signal labels at every entry signal
Dashboard: position, SMEMA cross direction, ADX, RSI, vol ratio, trade count, win rate, net P&L, bars in trade, settings summary
Alerts for long entry and short entry signals
Webhook JSON alert format
Watermark
Input Parameters
SMEMA Engine
Fast SMEMA Length — period for the fast crossover line (default 2)
Slow SMEMA Length — period for the slow crossover line (default 5)
Baseline SMEMA — period for the optional trend baseline (default 15)
Trend Filter
ADX Length — period for ADX / DMI calculation (default 14)
Min ADX — minimum ADX value required before entry (default 18)
Enable ADX Filter — master toggle (default off)
RSI Filter
RSI Length — period for RSI calculation (default 14)
RSI Bull Min — minimum RSI for long entries (default 52)
RSI Bear Max — maximum RSI for short entries (default 48)
Enable RSI Filter — master toggle (default off)
Volatility Filter
ATR Length — lookback for ATR (default 14)
ATR Smooth — lookback for the ATR average used in ratio (default 20)
Min Vol Ratio — ATR/AvgATR minimum threshold (default 0.8)
Enable Vol Ratio Filter — master toggle (default off)
Baseline Filter
Enable Baseline Filter — when on, requires close above baseline for longs and below for shorts (default off)
Trade Management
Stop-Loss ATR Mult — distance of initial stop from entry in ATR units (default 1.8)
TP1 ATR Mult — distance of first take-profit from entry (default 2.5)
TP2 ATR Mult — distance of second take-profit from entry (default 4.5)
Use Trailing Stop — enables dynamic trailing after TP1 (default on)
Trailing Stop ATR Mult — trail distance in ATR units (default 1.5)
Max Bars in Trade — maximum bars before forced exit (default 10)
Trade Direction
Allow Long Trades — toggles long entry signals (default on)
Allow Short Trades — toggles short entry signals (default on)
Date Range
Enable Date Filter — restricts backtesting to a specific window
From Date / To Date — start and end of the active period
Visuals
Bull Color — cyan default for upside elements
Bear Color — red default for downside elements
Neutral Color — gray for baseline and neutral dashboard text
Show Dashboard — live performance and settings panel
Show Watermark
Show Signal Labels — ▲ LONG / ▼ SHORT markers on entry bars
Show SMEMA Bands — toggles the ribbon and three SMEMA line plots
How to Use
Add the strategy to any chart. The default settings are tuned for high trade frequency — no filters enabled, fast periods of 2/5, max bars 10.
Run the Strategy Tester to review backtest performance. Check that the trade count is above 100 on your chosen timeframe and symbol before drawing any performance conclusions.
To increase signal quality at the cost of trade frequency, enable filters one at a time: start with the ADX filter to eliminate ranging entries, then add RSI if you want additional momentum confirmation.
Use the SL/TP dashed lines drawn on-chart during live trades to monitor your risk levels visually in real time.
Set the Long Entry and Short Entry alerts to receive notifications. Use Webhook JSON format to route signals to automation platforms.
Adjust the ATR multipliers to fit the volatility profile of your market. Higher-volatility assets like altcoins benefit from wider stops (2.0–2.5×) and wider TP levels. Lower-volatility assets like indices may work better with tighter parameters.
The Max Bars in Trade parameter is the most powerful lever for trade frequency. Reducing it to 5–7 generates very high trade counts. Increasing it to 20–40 gives trades more room to develop but reduces total trade count.
Indicator Limitations
SMEMA crossovers are inherently lagging — by definition, the crossover confirms a direction change after it has already begun. In fast-moving markets this means entries will not be at the exact turning point.
The default configuration (all filters off, max bars 10) optimizes for trade count and sample size rather than highest possible win rate. Enabling filters will reduce trade count but may improve per-trade quality — test thoroughly on your symbol and timeframe before live use.
The 100% equity position sizing in the backtest is chosen to keep commission effects proportional and performance metrics visible at small capital sizes. This does not represent a recommendation to risk your entire account on any trade.
Backtested results are not a guarantee of future performance. Past performance under any parameters does not imply future results.
The strategy uses `calc_on_every_tick=false` — all orders execute at bar close, which is more realistic than tick-by-tick simulation but means intrabar SL/TP wicks may not be captured accurately in the backtest.
Originality Statement
The Sovereign Trend Strategy is an original Pine Script v6 strategy publication. The SMEMA (SMA of EMA) double-smoothing construction is an original baseline engineering choice that produces a distinct crossover behavior not replicated by standard EMA or SMA crossover systems. The six-path exit framework, the staged TP1/breakeven/trailing/TP2 management sequence, and the modular optional filter architecture are original design decisions. The strategy.position_size derivation of position state (avoiding the Pine Script v6 timing bug with strategy.opentrades and manual boolean flags) is an original technical solution developed for this publication.
Disclaimer
This is a backtested strategy provided for educational purposes only. It does not constitute financial advice or a recommendation to trade any specific instrument. All trading involves risk of capital loss. Backtested performance does not guarantee future results. Commission, slippage, and real-world execution conditions will differ from backtest simulations. Always perform your own analysis and consult a licensed financial professional before trading with real capital.
-Made with passion by jackofalltrades
Strategy

Volatility Targeting: Single Asset [BackQuant]Volatility Targeting: Single Asset
An educational example that demonstrates how volatility targeting can scale exposure up or down on one symbol, then applies a simple EMA cross for long or short direction and a higher timeframe style regime filter to gate risk. It builds a synthetic equity curve and compares it to buy and hold and a benchmark.
Important disclaimer
This script is a concept and education example only . It is not a complete trading system and it is not meant for live execution. It does not model many real world constraints, and its equity curve is only a simplified simulation. If you want to trade any idea like this, you need a proper strategy() implementation, realistic execution assumptions, and robust backtesting with out of sample validation.
Single asset vs the full portfolio concept
This indicator is the single asset, long short version of the broader volatility targeted momentum portfolio concept. The original multi asset concept and full portfolio implementation is here:
That portfolio script is about allocating across multiple assets with a portfolio view. This script is intentionally simpler and focuses on one symbol so you can clearly see how volatility targeting behaves, how the scaling interacts with trend direction, and what an equity curve comparison looks like.
What this indicator is trying to demonstrate
Volatility targeting is a risk scaling framework. The core idea is simple:
If realized volatility is low relative to a target, you can scale position size up so the strategy behaves like it has a stable risk budget.
If realized volatility is high relative to a target, you scale down to avoid getting blown around by the market.
Instead of always being 1x long or 1x short, exposure becomes dynamic. This is often used in risk parity style systems, trend following overlays, and volatility controlled products.
This script combines that risk scaling with a simple trend direction model:
Fast and slow EMA cross determines whether the strategy is long or short.
A second, longer EMA cross acts as a regime filter that decides whether the system is ACTIVE or effectively in CASH.
An equity curve is built from the scaled returns so you can visualize how the framework behaves across regimes.
How the logic works step by step
1) Returns and simple momentum
The script uses log returns for the base return stream:
ret = log(price / price )
It also computes a simple momentum value:
mom = price / price - 1
In this version, momentum is mainly informational since the directional signal is the EMA cross. The lookback input is shared with volatility estimation to keep the concept compact.
2) Realized volatility estimation
Realized volatility is estimated as the standard deviation of returns over the lookback window, then annualized:
vol = stdev(ret, lookback) * sqrt(tradingdays)
The Trading Days/Year input controls annualization:
252 is typical for traditional markets.
365 is typical for crypto since it trades daily.
3) Volatility targeting multiplier
Once realized vol is estimated, the script computes a scaling factor that tries to push realized volatility toward the target:
volMult = targetVol / vol
This is then clamped into a reasonable range:
Minimum 0.1 so exposure never goes to zero just because vol spikes.
Maximum 5.0 so exposure is not allowed to lever infinitely during ultra low volatility periods.
This clamp is one of the most important “sanity rails” in any volatility targeted system. Without it, very low volatility regimes can create unrealistic leverage.
4) Scaled return stream
The per bar return used for the equity curve is the raw return multiplied by the volatility multiplier:
sr = ret * volMult
Think of this as the return you would have earned if you scaled exposure to match the volatility budget.
5) Long short direction via EMA cross
Direction is determined by a fast and slow EMA cross on price:
If fast EMA is above slow EMA, direction is long.
If fast EMA is below slow EMA, direction is short.
This produces dir as either +1 or -1. The scaled return stream is then signed by direction:
avgRet = dir * sr
So the strategy return is volatility targeted and directionally flipped depending on trend.
6) Regime filter: ACTIVE vs CASH
A second EMA pair acts as a top level regime filter:
If fast regime EMA is above slow regime EMA, the system is ACTIVE.
If fast regime EMA is below slow regime EMA, the system is considered CASH, meaning it does not compound equity.
This is designed to reduce participation in long bear phases or low quality environments, depending on how you set the regime lengths. By default it is a classic 50 and 200 EMA cross structure.
Important detail, the script applies regime_filter when compounding equity, meaning it uses the prior bar regime state to avoid ambiguous same bar updates.
7) Equity curve construction
The script builds a synthetic equity curve starting from Initial Capital after Start Date . Each bar:
If regime was ACTIVE on the previous bar, equity compounds by (1 + netRet).
If regime was CASH, equity stays flat.
Fees are modeled very simply as a per bar penalty on returns:
netRet = avgRet - (fee_rate * avgRet)
This is not realistic execution modeling, it is just a simple turnover penalty knob to show how friction can reduce compounded performance. Real backtesting should model trade based costs, spreads, funding, and slippage.
Benchmark and buy and hold comparison
The script pulls a benchmark symbol via request.security and builds a buy and hold equity curve starting from the same date and initial capital. The buy and hold curve is based on benchmark price appreciation, not the strategy’s asset price, so you can compare:
Strategy equity on the chart symbol.
Buy and hold equity for the selected benchmark instrument.
By default the benchmark is TVC:SPX, but you can set it to anything, for crypto you might set it to BTC, or a sector index, or a dominance proxy depending on your study.
What it plots
If enabled, the indicator plots:
Strategy Equity as a line, colored by recent direction of equity change, using Positive Equity Color and Negative Equity Color .
Buy and Hold Equity for the chosen benchmark as a line.
Optional labels that tag each curve on the right side of the chart.
This makes it easy to visually see when volatility targeting and regime gating change the shape of the equity curve relative to a simple passive hold.
Metrics table explained
If Show Metrics Table is enabled, a table is built and populated with common performance statistics based on the simulated daily returns of the strategy equity curve after the start date. These include:
Net Profit (%) total return relative to initial capital.
Max DD (%) maximum drawdown computed from equity peaks, stored over time.
Win Rate percent of positive return bars.
Annual Mean Returns (% p/y) mean daily return annualized.
Annual Stdev Returns (% p/y) volatility of daily returns annualized.
Variance of annualized returns.
Sortino Ratio annualized return divided by downside deviation, using negative return stdev.
Sharpe Ratio risk adjusted return using the risk free rate input.
Omega Ratio positive return sum divided by negative return sum.
Gain to Pain total return sum divided by absolute loss sum.
CAGR (% p/y) compounded annual growth rate based on time since start date.
Portfolio Alpha (% p/y) alpha versus benchmark using beta and the benchmark mean.
Portfolio Beta covariance of strategy returns with benchmark returns divided by benchmark variance.
Skewness of Returns actually the script computes a conditional value based on the lower 5 percent tail of returns, so it behaves more like a simple CVaR style tail loss estimate than classic skewness.
Important note, these are calculated from the synthetic equity stream in an indicator context. They are useful for concept exploration, but they are not a substitute for professional backtesting where trade timing, fills, funding, and leverage constraints are accurately represented.
How to interpret the system conceptually
Vol targeting effect
When volatility rises, volMult falls, so the strategy de risks and the equity curve typically becomes smoother. When volatility compresses, volMult rises, so the system takes more exposure and tries to maintain a stable risk budget.
This is why volatility targeting is often used as a “risk equalizer”, it can reduce the “biggest drawdowns happen only because vol expanded” problem, at the cost of potentially under participating in explosive upside if volatility rises during a trend.
Long short directional effect
Because direction is an EMA cross:
In strong trends, the direction stays stable and the scaled return stream compounds in that trend direction.
In choppy ranges, the EMA cross can flip and create whipsaws, which is where fees and regime filtering matter most.
Regime filter effect
The 50 and 200 style filter tries to:
Keep the system active in sustained up regimes.
Reduce exposure during long down regimes or extended weakness.
It will always be late at turning points, by design. It is a slow filter meant to reduce deep participation, not to catch bottoms.
Common applications
This script is mainly for understanding and research, but conceptually, volatility targeting overlays are used for:
Risk budgeting normalize risk so your exposure is not accidentally huge in high vol regimes.
System comparison see how a simple trend model behaves with and without vol scaling.
Parameter exploration test how target volatility, lookback length, and regime lengths change the shape of equity and drawdowns.
Framework building as a reference blueprint before implementing a proper strategy() version with trade based execution logic.
Tuning guidance
Lookback lower values react faster to vol shifts but can create unstable scaling, higher values smooth scaling but react slower to regime changes.
Target volatility higher targets increase exposure and drawdown potential, lower targets reduce exposure and usually lower drawdowns, but can under perform in strong trends.
Signal EMAs tighter EMAs increase trade frequency, wider EMAs reduce churn but react slower.
Regime EMAs slower regime filters reduce false toggles but will miss early trend transitions.
Fees if you crank this up you will see how sensitive higher turnover parameter sets are to friction.
Final note
This is a compact educational demonstration of a volatility targeted, long short single asset framework with a regime gate and a synthetic equity curve. If you want a production ready implementation, the correct next step is to convert this concept into a strategy() script, add realistic execution and cost modeling, test across multiple timeframes and market regimes, and validate out of sample before making any decision based on the results.
Indicator

Indicator

Macd Divergence + MTF EMA MACD Divergence + Multi Time Frame EMA
This Strategy uses 3 indicators: the Macd and two emas in different time frames
The configuration of the strategy is:
Macd standar configuration (12, 26, 9) in 1H resolution
10 periods ema, in 1H resolution
5 periods ema, in 15 minutes resolution
We use the two emas to filter for long and short positions.
If 15 minutes ema is above 1H ema, we look for long positions
If 15 minutes ema is below 1H ema, we look for short positions
We can use an aditional filter using a 100 days ema, so when the 15' and 1H emas are above the daily ema we take long positions
Using this filter improves the strategy
We wait for Macd indicator to form a divergence between histogram and price
If we have a bullish divergence, and 15 minutes ema is above 1H ema, we wait for macd line to cross above signal line and we open a long position
If we have a bearish divergence, and 15 minutes ema is below 1H ema, we wait for macd line to cross below signal line and we open a short position
We close both position after a cross in the oposite direction of macd line and signal line
Also we can configure a Take profit parameter and a trailing stop loss Strategy

Strategy

Strategy
