Fractional EMA Cross Backtest Strategy by Yesid_Correa_Cano

By Yesid_Correa_Cano

Performance Metrics

Description

Fractional EMA Cross Backtest StrategyThis 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 logicThe strategy supports two operating modes.Two-EMA modeWhen 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 modeWhen 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 executionThe strategy uses:Initial capital: USD 3,000Default position size: 10% of equityPyramiding: 0Fixed commission: USD 0.10 per orderprocess_orders_on_close = falsecalc_on_order_fills = truecalc_on_every_tick = trueBecause 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 managementRisk per trade is expressed as a percentage of strategy equity and is configurable up to 2%.Default:Risk per trade: 1%Target: 3.5RMinimum configurable target: 2RAfter 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.TRIMThe script includes a visual TRIM reference.Default TRIM level:75% of the distance from Entry to TargetTRIM 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 timeA 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 classificationClosed trades are classified as:TARGETSTOPTIME EXITBacktest statisticsThe table reports:Closed tradesWinsLossesWin RateProfit FactorExpectancy in RNet P&LROIMaximum DrawdownAverage Holding TimeTarget ExitsStop ExitsTime ExitsRealized R is calculated as:Realized R = Trade Profit / Initial Risk CashThe script also displays an R-distribution table using the following buckets:<= -1.0R-0.5R0.0R+0.5R+1.0R+1.5R+2.0R+2.5R+3.0R= +3.5RA statistical summary includes:Mean RSample Standard DeviationSample confidenceThe script classifies the number of closed trades as:Below 50: LOW50 to 99: PRELIM.100 or more: VALIDThese labels refer only to sample size. They are not a statement about the quality, profitability or future reliability of the strategy.How to useStart by selecting the EMA lengths you want to test.Example two-EMA configuration:13 / 48.5Example three-EMA configuration:13 / 48.5 / 200Then 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.OriginalityThe 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.LimitationsBacktest 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.

Browse all 5,900+ TradingView Pine Script strategies

View on TradingView