OPEN-SOURCE SCRIPT
Fractional EMA Cross Backtest Strategy

Fractional EMA Cross Backtest Strategy
This strategy is a configurable EMA crossover backtesting framework designed to evaluate two-EMA and sequential three-EMA crossover structures across different symbols and chart timeframes.
Unlike Pine Script's native ta.ema() function, which requires integer lengths, this script calculates exponential moving averages using the standard smoothing factor:
Alpha = 2 / (Length + 1)
This allows the user to test fractional EMA periods such as 13 / 48.5, as well as conventional integer combinations.
Entry logic
The strategy supports two operating modes.
Two-EMA mode
When EMA 3 is disabled:
Long setup: Fast EMA crosses above the Intermediate EMA.
Short setup: Fast EMA crosses below the Intermediate EMA.
A trade is submitted only when there is no existing open position. Opposite signals do not reverse an active trade.
Three-EMA mode
When EMA 3 is enabled, the strategy uses a sequential crossover structure rather than requiring all three averages to cross on the same bar.
Long sequence:
Fast EMA crosses above Intermediate EMA.
The long sequence becomes armed.
Intermediate EMA subsequently crosses above Slow EMA.
That second crossover becomes the final Long entry trigger.
Short sequence:
Fast EMA crosses below Intermediate EMA.
The short sequence becomes armed.
Intermediate EMA subsequently crosses below Slow EMA.
That second crossover becomes the final Short entry trigger.
If the Fast EMA crosses back through the Intermediate EMA before the second stage occurs, the pending sequence is cancelled.
The chart's Cross 01 marker represents the effective entry signal used by the strategy. With two EMAs, it is plotted at the Fast/Intermediate crossover. With three EMAs, it is plotted at the Intermediate/Slow crossover that completes the sequence.
Order execution
The strategy uses:
Initial capital: USD 3,000
Default position size: 10% of equity
Pyramiding: 0
Fixed commission: USD 0.10 per order
process_orders_on_close = false
calc_on_order_fills = true
calc_on_every_tick = true
Because process_orders_on_close is disabled, a historical market entry generated on a confirmed crossover bar is normally filled on the next available tick, typically the opening price of the following chart bar.
Recalculation after order fills is enabled so that the strategy can initialize its stop, target, risk, TRIM level and trade state from the actual simulated fill price. Tick-by-tick recalculation is enabled for real-time responsiveness. Historical strategy results are still constrained by the price information available in the chart's historical bars.
Risk management
Risk per trade is expressed as a percentage of strategy equity and is configurable up to 2%.
Default:
Risk per trade: 1%
Target: 3.5R
Minimum configurable target: 2R
After an entry is filled, the strategy calculates the initial monetary risk and derives the corresponding stop distance from the simulated position size.
For Long positions:
Stop is placed below the entry.
Target is placed above the entry according to the selected R multiple.
For Short positions:
Stop is placed above the entry.
Target is placed below the entry.
Position sizing and risk percentage are separate concepts in this implementation. The strategy uses 10% of equity as the position allocation, while the selected risk percentage determines the monetary risk used to calculate the stop distance.
TRIM
The script includes a visual TRIM reference.
Default TRIM level:
75% of the distance from Entry to Target
TRIM is informational only and does not reduce the position.
If price gaps beyond the calculated TRIM level, the bar's opening price is used as the visual TRIM execution reference.
Maximum holding time
A configurable maximum holding period is included, with a default of 30 sessions.
Positions that remain open beyond this limit are closed using a TIME EXIT.
Trade classification
Closed trades are classified as:
TARGET
STOP
TIME EXIT
Backtest statistics
The table reports:
Closed trades
Wins
Losses
Win Rate
Profit Factor
Expectancy in R
Net P&L
ROI
Maximum Drawdown
Average Holding Time
Target Exits
Stop Exits
Time Exits
Realized R is calculated as:
Realized R = Trade Profit / Initial Risk Cash
The script also displays an R-distribution table using the following buckets:
<= -1.0R
-0.5R
0.0R
+0.5R
+1.0R
+1.5R
+2.0R
+2.5R
+3.0R
= +3.5R
A statistical summary includes:
Mean R
Sample Standard Deviation
Sample confidence
The script classifies the number of closed trades as:
Below 50: LOW
50 to 99: PRELIM.
100 or more: VALID
These labels refer only to sample size. They are not a statement about the quality, profitability or future reliability of the strategy.
How to use
Start by selecting the EMA lengths you want to test.
Example two-EMA configuration:
13 / 48.5
Example three-EMA configuration:
13 / 48.5 / 200
Then evaluate the strategy across different symbols, market regimes and timeframes. The strategy is not restricted to a specific chart timeframe.
Comparisons should be made using sufficiently large datasets and consistent assumptions for commission, position sizing, risk and holding time.
Originality
The main purpose of this script is not simply to reproduce a standard EMA crossover. It combines fractional EMA calculation, optional sequential three-EMA crossover logic, fixed monetary-risk modeling, visual TRIM tracking, time-based exits, realized-R classification, R-distribution analysis and sample-dispersion statistics within a single modular backtesting framework.
The entry logic is intentionally separated from the fixed strategy engine so that different crossover configurations can be tested without rebuilding the risk-management and statistical framework.
Limitations
Backtest results are hypothetical and depend on the selected symbol, timeframe, available historical data, market liquidity and TradingView's broker emulator.
Historical bars do not contain complete tick-by-tick price paths unless additional lower-timeframe information is available to the broker emulator. Stop, target and gap behavior should therefore be interpreted as simulated historical execution rather than actual fills.
The strategy does not model slippage beyond the configured commission.
A parameter combination that performed well historically may not perform similarly in future market conditions.
This script is intended for research, education and strategy testing. It is not financial advice and does not constitute a recommendation to buy or sell any security.
This strategy is a configurable EMA crossover backtesting framework designed to evaluate two-EMA and sequential three-EMA crossover structures across different symbols and chart timeframes.
Unlike Pine Script's native ta.ema() function, which requires integer lengths, this script calculates exponential moving averages using the standard smoothing factor:
Alpha = 2 / (Length + 1)
This allows the user to test fractional EMA periods such as 13 / 48.5, as well as conventional integer combinations.
Entry logic
The strategy supports two operating modes.
Two-EMA mode
When EMA 3 is disabled:
Long setup: Fast EMA crosses above the Intermediate EMA.
Short setup: Fast EMA crosses below the Intermediate EMA.
A trade is submitted only when there is no existing open position. Opposite signals do not reverse an active trade.
Three-EMA mode
When EMA 3 is enabled, the strategy uses a sequential crossover structure rather than requiring all three averages to cross on the same bar.
Long sequence:
Fast EMA crosses above Intermediate EMA.
The long sequence becomes armed.
Intermediate EMA subsequently crosses above Slow EMA.
That second crossover becomes the final Long entry trigger.
Short sequence:
Fast EMA crosses below Intermediate EMA.
The short sequence becomes armed.
Intermediate EMA subsequently crosses below Slow EMA.
That second crossover becomes the final Short entry trigger.
If the Fast EMA crosses back through the Intermediate EMA before the second stage occurs, the pending sequence is cancelled.
The chart's Cross 01 marker represents the effective entry signal used by the strategy. With two EMAs, it is plotted at the Fast/Intermediate crossover. With three EMAs, it is plotted at the Intermediate/Slow crossover that completes the sequence.
Order execution
The strategy uses:
Initial capital: USD 3,000
Default position size: 10% of equity
Pyramiding: 0
Fixed commission: USD 0.10 per order
process_orders_on_close = false
calc_on_order_fills = true
calc_on_every_tick = true
Because process_orders_on_close is disabled, a historical market entry generated on a confirmed crossover bar is normally filled on the next available tick, typically the opening price of the following chart bar.
Recalculation after order fills is enabled so that the strategy can initialize its stop, target, risk, TRIM level and trade state from the actual simulated fill price. Tick-by-tick recalculation is enabled for real-time responsiveness. Historical strategy results are still constrained by the price information available in the chart's historical bars.
Risk management
Risk per trade is expressed as a percentage of strategy equity and is configurable up to 2%.
Default:
Risk per trade: 1%
Target: 3.5R
Minimum configurable target: 2R
After an entry is filled, the strategy calculates the initial monetary risk and derives the corresponding stop distance from the simulated position size.
For Long positions:
Stop is placed below the entry.
Target is placed above the entry according to the selected R multiple.
For Short positions:
Stop is placed above the entry.
Target is placed below the entry.
Position sizing and risk percentage are separate concepts in this implementation. The strategy uses 10% of equity as the position allocation, while the selected risk percentage determines the monetary risk used to calculate the stop distance.
TRIM
The script includes a visual TRIM reference.
Default TRIM level:
75% of the distance from Entry to Target
TRIM is informational only and does not reduce the position.
If price gaps beyond the calculated TRIM level, the bar's opening price is used as the visual TRIM execution reference.
Maximum holding time
A configurable maximum holding period is included, with a default of 30 sessions.
Positions that remain open beyond this limit are closed using a TIME EXIT.
Trade classification
Closed trades are classified as:
TARGET
STOP
TIME EXIT
Backtest statistics
The table reports:
Closed trades
Wins
Losses
Win Rate
Profit Factor
Expectancy in R
Net P&L
ROI
Maximum Drawdown
Average Holding Time
Target Exits
Stop Exits
Time Exits
Realized R is calculated as:
Realized R = Trade Profit / Initial Risk Cash
The script also displays an R-distribution table using the following buckets:
<= -1.0R
-0.5R
0.0R
+0.5R
+1.0R
+1.5R
+2.0R
+2.5R
+3.0R
= +3.5R
A statistical summary includes:
Mean R
Sample Standard Deviation
Sample confidence
The script classifies the number of closed trades as:
Below 50: LOW
50 to 99: PRELIM.
100 or more: VALID
These labels refer only to sample size. They are not a statement about the quality, profitability or future reliability of the strategy.
How to use
Start by selecting the EMA lengths you want to test.
Example two-EMA configuration:
13 / 48.5
Example three-EMA configuration:
13 / 48.5 / 200
Then evaluate the strategy across different symbols, market regimes and timeframes. The strategy is not restricted to a specific chart timeframe.
Comparisons should be made using sufficiently large datasets and consistent assumptions for commission, position sizing, risk and holding time.
Originality
The main purpose of this script is not simply to reproduce a standard EMA crossover. It combines fractional EMA calculation, optional sequential three-EMA crossover logic, fixed monetary-risk modeling, visual TRIM tracking, time-based exits, realized-R classification, R-distribution analysis and sample-dispersion statistics within a single modular backtesting framework.
The entry logic is intentionally separated from the fixed strategy engine so that different crossover configurations can be tested without rebuilding the risk-management and statistical framework.
Limitations
Backtest results are hypothetical and depend on the selected symbol, timeframe, available historical data, market liquidity and TradingView's broker emulator.
Historical bars do not contain complete tick-by-tick price paths unless additional lower-timeframe information is available to the broker emulator. Stop, target and gap behavior should therefore be interpreted as simulated historical execution rather than actual fills.
The strategy does not model slippage beyond the configured commission.
A parameter combination that performed well historically may not perform similarly in future market conditions.
This script is intended for research, education and strategy testing. It is not financial advice and does not constitute a recommendation to buy or sell any security.
Açık kaynak kodlu komut dosyası
Gerçek TradingView ruhuyla, bu komut dosyasının mimarı, yatırımcıların işlevselliğini inceleyip doğrulayabilmesi için onu açık kaynaklı hale getirdi. Yazarı tebrik ederiz! Ücretsiz olarak kullanabilseniz de, kodu yeniden yayınlamanın Topluluk Kurallarımıza tabi olduğunu unutmayın.
Setup + Risk Management + 1% better daily = Consistency. 📈
Feragatname
Bilgiler ve yayınlar, TradingView tarafından sağlanan veya onaylanan finansal, yatırım, alım satım veya diğer türden tavsiye veya öneriler anlamına gelmez ve teşkil etmez. Kullanım Koşulları bölümünde daha fazlasını okuyun.
Açık kaynak kodlu komut dosyası
Gerçek TradingView ruhuyla, bu komut dosyasının mimarı, yatırımcıların işlevselliğini inceleyip doğrulayabilmesi için onu açık kaynaklı hale getirdi. Yazarı tebrik ederiz! Ücretsiz olarak kullanabilseniz de, kodu yeniden yayınlamanın Topluluk Kurallarımıza tabi olduğunu unutmayın.
Setup + Risk Management + 1% better daily = Consistency. 📈
Feragatname
Bilgiler ve yayınlar, TradingView tarafından sağlanan veya onaylanan finansal, yatırım, alım satım veya diğer türden tavsiye veya öneriler anlamına gelmez ve teşkil etmez. Kullanım Koşulları bölümünde daha fazlasını okuyun.