Overview
The Live Repainting Swing Trading Strategy is a quantitative trading system designed to capture short to medium-term market fluctuations. This strategy combines repainting trendlines with Exponential Moving Averages (EMA) to identify potential trading opportunities. At its core, the strategy excels in its ability to identify swing highs and lows in real-time, simulating how a discretionary trader would continuously adjust their analysis as the chart evolves. The system generates buy signals when a new swing low is detected and sell signals upon the appearance of new swing highs, while implementing a cooldown mechanism to prevent overtrading. Additionally, the strategy is equipped with adjustable stop-loss and take-profit percentage targets to help traders effectively manage risk.
Strategy Principles
The strategy operates based on several key principles:
Swing Point Detection Mechanism: The strategy uses a user-defined lookback length (swingLen) to identify unconfirmed, live swing highs and lows. Through the ta.highestbars and ta.lowestbars functions, the system can determine if the current price constitutes a highest or lowest point within the specified period. This method allows the strategy to "repaint" its analysis as new price data emerges, much like a discretionary trader would.
Entry Logic:
- Buy Condition: When the system detects a new swing low and the cooldown condition is satisfied (at least cooldownBars bars since the last signal), a long position is established at the swing low position.
- Sell Condition: When the system detects a new swing high and the cooldown condition is met, a short position is established at the swing high position.
Exit Strategy: The strategy employs preset Take Profit (TP) and Stop Loss (SL) percentages to manage risk. For long positions, TP is set at entry price * (1+tp_pct) and SL at entry price * (1-sl_pct). For short positions, TP is at entry price * (1-tp_pct) and SL at entry price * (1+sl_pct).
Trend Context: The strategy utilizes an EMA to provide context for market trends. By default, a 50-period EMA is used, which helps determine the overall direction of the market and provides an additional filter for trading decisions.
Live Trendlines: The strategy draws trendlines from the most recently detected swing highs and lows to the current price, offering visual confirmation of price movements. These trendlines automatically update when new swing points form.
Strategy Advantages
Through deep analysis of the code, this strategy offers the following significant advantages:
High Adaptability: Due to its repainting mechanism, the strategy can adapt to real-time market changes, simulating the dynamic thinking process of a discretionary trader. This allows it to maintain a certain level of adaptability across different market conditions.
Visualized Trading Signals: The strategy provides clear visual feedback through distinct graphical markers (such as triangles and circles) and trendlines, enabling traders to intuitively understand market dynamics and signal generation points.
Flexible Risk Management: Users can adjust take-profit and stop-loss percentages according to their risk preferences, achieving personalized risk management strategies.
Overtrading Protection: The cooldown mechanism effectively prevents the system from generating too many signals in a short period, reducing unnecessary trades caused by market noise.
Multi-dimensional Confirmation: By combining swing point detection with EMA trend filtering, the strategy provides multi-layered trade confirmation, which can improve signal quality.
Suitable for Short to Medium-Term Trading: The strategy is particularly well-suited for 5-minute to 1-hour charts for price action traders, making it ideal for real-time analysis and manual trading requiring visual confirmation.
Strategy Risks
Despite its many advantages, the strategy also presents the following potential risks:
Repainting Issue: The core feature of the strategy—"repainting"—is also one of its biggest risks. Since swing points are calculated based on currently available data, backtest results may show "perfect" historical signals that might not have formed or appeared differently in real-time trading.
Choppy Market Risk: In range-bound or choppy markets, the strategy may generate frequent swing highs and lows, potentially leading to excessive trading and consecutive stops even with the cooldown mechanism in place.
Trend Reversal Delay: The strategy relies on historical data to identify swing points, which may result in delayed reactions to sharp trend reversals, leading to late entries or missed opportunities.
Parameter Sensitivity: Strategy performance is highly dependent on parameter settings (such as swing length, EMA period, and cooldown), and inappropriate parameters may lead to overfitting or degraded signal quality.
Fixed Percentage Risk: The strategy uses fixed percentages for take-profit and stop-loss without accounting for changes in market volatility, potentially triggering stops too early during high volatility periods or setting targets too far in low volatility periods.
Strategy Optimization Directions
Based on in-depth analysis of the code, here are several key directions for optimizing this strategy:
Adaptive Parameters: Transform fixed swing lengths and EMA periods into dynamic parameters that automatically adjust based on market volatility. For example, using the Average True Range (ATR) to adjust the sensitivity of swing detection, increasing swing length during higher volatility.
Trend Strength Filtering: Introduce trend strength indicators (such as ADX) and only execute trades aligned with the trend direction when the trend is confirmed to be sufficiently strong, avoiding overtrading in weak trends or choppy markets.
Multi-timeframe Analysis: Integrate trend information from higher timeframes to ensure trade direction aligns with the larger trend, improving win rates.
Volatility-based Risk Management: Replace fixed percentage stops with dynamic stop-loss and take-profit levels based on ATR, making risk management more adaptable to current market conditions.
Entry Optimization: Add additional entry confirmation conditions, such as price relative to EMA, volume confirmation, or momentum indicator signals, to improve entry quality.
Signal Quality Scoring: Develop a scoring system that rates each signal based on multiple factors (such as clarity of the swing point, distance from EMA, recent price action, etc.) and only execute trades on high-quality signals.
Summary
The Live Repainting Swing Trading Strategy represents an innovative technical analysis approach that provides value to short and medium-term traders through dynamic identification of swing highs and lows, combined with EMA trend filtering and clear visual feedback. Its greatest strength lies in its ability to simulate the dynamic decision-making process of a discretionary trader while providing a strict risk management framework.
However, the repainting characteristic of the strategy also carries the risk that backtest results may not align with actual trading performance. To maximize the potential of this strategy, traders should consider implementing the optimization suggestions outlined above, particularly adaptive parameters and volatility-based risk management, to enhance its adaptability across different market conditions.
Overall, this strategy is well-suited for traders who favor price action trading, prefer visual confirmation, and engage in real-time analysis. With appropriate parameter adjustments and risk management, it can be an effective tool for capturing short to medium-term market fluctuations.
Strategy source code
/*backtest
start: 2024-05-13 00:00:00
end: 2025-05-11 08:00:00
period: 1d
basePeriod: 1d
exchanges: [{"eid":"Futures_Binance","currency":"DOGE_USDT"}]
*/
//@version=6
strategy("Live Repainting Swing Strategy (Trendlines + EMA)", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=10)
// === Inputs ===
swingLen = input.int(20, title="Swing Length")
cooldownBars = input.int(10, title="Min Bars Between Swing Signals")
emaLength = input.int(50, title="EMA Length")
sl_pct = input.float(1.0, title="Stop Loss (%)") / 100
tp_pct = input.float(2.0, title="Take Profit (%)") / 100
// === Indicators
ema = ta.ema(close, emaLength)
plot(ema, color=color.orange, title="EMA")
// === Live (repainting) swing detection
isSwingHigh = ta.highestbars(high, swingLen) == 0
isSwingLow = ta.lowestbars(low, swingLen) == 0
// === Cooldown logic
var int lastSignalBar = na
canTrigger = na(lastSignalBar) or (bar_index - lastSignalBar > cooldownBars)
buySignal = isSwingLow and canTrigger
sellSignal = isSwingHigh and canTrigger
if buySignal or sellSignal
lastSignalBar := bar_index
// === Orders
if buySignal
strategy.entry("BUY", strategy.long)
if sellSignal
strategy.entry("SELL", strategy.short)
// === TP/SL Levels
tpLong = strategy.position_avg_price * (1 + tp_pct)
slLong = strategy.position_avg_price * (1 - sl_pct)
tpShort = strategy.position_avg_price * (1 - tp_pct)
slShort = strategy.position_avg_price * (1 + sl_pct)
strategy.exit("TP/SL BUY", from_entry="BUY", limit=tpLong, stop=slLong)
strategy.exit("TP/SL SELL", from_entry="SELL", limit=tpShort, stop=slShort)
// === TP Hit Detection
tpHitLong = strategy.position_size > 0 and high >= tpLong
tpHitShort = strategy.position_size < 0 and low <= tpShort
// === Clean Markers (No text)
plotshape(buySignal, location=location.belowbar, style=shape.triangleup, color=color.green, size=size.small)
plotshape(sellSignal, location=location.abovebar, style=shape.triangledown, color=color.red, size=size.small)
plotshape(tpHitLong, location=location.abovebar, style=shape.circle, color=color.lime, size=size.tiny)
plotshape(tpHitShort, location=location.belowbar, style=shape.circle, color=color.orange, size=size.tiny)
// === Live Trendlines from last swing high/low
var float lastSwingLow = na
var float lastSwingHigh = na
var int lastLowBar = na
var int lastHighBar = na
if isSwingLow
lastSwingLow := low
lastLowBar := bar_index
if isSwingHigh
lastSwingHigh := high
lastHighBar := bar_index
var line lowTrend = na
var line highTrend = na
Strategy parameters
The original address: Live Repainting Swing Trading Strategy: Combined Trendline and EMA Price Action Capture System
Repainting trendlines and EMAs? Now that's some next-level market mind-reading! 🔮 Love how this strategy basically says 'trust me bro' to price action. Just promise me it won't redraw signals like a toddler with an Etch A Sketch. Solid swing logic—but if it starts predicting my ex's mixed signals this accurately, we might have a problem.