Table of Contents
When it comes to trading, simplicity often beats complexity. A well-structured yet straightforward strategy tested in TradingView can provide an edge by offering clear rules and repeatable setups. Many traders struggle with overcomplicating their approach, adding unnecessary indicators, or relying on gut feeling. However, a simple and tested system removes doubt and brings consistency to your trading.
By using TradingView’s built-in strategy tester, traders can evaluate how a strategy performs over historical data before applying it in live markets. This process helps develop confidence—knowing that your approach has statistical backing rather than being based on emotions or guesswork.
One such strategy is the Previous Day’s High and Low Breakout, which leverages key price levels to identify high-probability trade setups. When combined with a structured risk management plan, even a basic strategy like this can become a powerful tool for traders looking for consistency.
In this guide, we’ll explore how to implement this strategy in TradingView and provide you with a free source code so you can test and refine it yourself. ?
See my video:
Buy, Sell Rules and Stop Loss & Target for the Previous Day High and Low Strategy
Buy (Long) Entry Conditions:
- The price closes above the previous day’s high.
- The previous candle’s close was below the previous day’s high.
- Once the conditions are met, enter a long position.
Sell (Short) Entry Conditions:
- The price closes below the previous day’s low.
- The previous candle’s close was above the previous day’s low.
- Once the conditions are met, enter a short position.
Stop Loss & Take Profit Rules
For Long Positions (Buy):
- Stop Loss (SL): Placed at:
- Take Profit (TP): Placed at:
For Short Positions (Sell):
- Stop Loss (SL): Placed at:
- Take Profit (TP): Placed at:
This strategy dynamically adjusts stop loss and takes profit levels based on the previous day’s range and configurable multipliers.
DOWNLOAD STRATEGY – COPY CODE in PineScript
//@version=5 strategy("Previous Day High and Low Strategy with SL/TP Toggle and Dynamic SL", shorttitle="PDHL SL/TP Toggle Dynamic SL", overlay=true, initial_capital=10000, default_qty_type=strategy.percent_of_equity, default_qty_value=10) // Input options for strategy optimization and toggles for visualizations profitTargetMultiplier = input.float(title="Profit Target Multiplier", defval=2.0, minval=0.1, maxval=100.0, step=0.1) stopLossMultiplier = input.float(title="Stop Loss Multiplier", defval=1.0, minval=0.1, maxval=100.0, step=0.1) showSLTP = input.bool(title="Show SL/TP Lines", defval=true) // Fetching the previous trading session's high and low prevDayHigh = request.security(syminfo.tickerid, "D", high[1], lookahead=barmerge.lookahead_on) prevDayLow = request.security(syminfo.tickerid, "D", low[1], lookahead=barmerge.lookahead_on) // Plotting the previous day's high and low for visual reference plot(prevDayHigh, "Previous Day High", color=color.green, linewidth=2, style=plot.style_stepline) plot(prevDayLow, "Previous Day Low", color=color.red, linewidth=2, style=plot.style_stepline) // Entry conditions based on price crossing over/under the previous day's high/low longCondition = close > prevDayHigh and close[1] < prevDayHigh shortCondition = close < prevDayLow and close[1] > prevDayLow // Dynamic SL and TP calculation based on multiplier float longSL = na float longTP = na float shortSL = na float shortTP = na // Adjusting the SL based on the stopLossMultiplier if (longCondition) longSL := prevDayLow - (stopLossMultiplier - 1) * (prevDayHigh - prevDayLow) longTP := prevDayHigh + profitTargetMultiplier * (prevDayHigh - prevDayLow) if (shortCondition) shortSL := prevDayHigh + (stopLossMultiplier - 1) * (prevDayHigh - prevDayLow) shortTP := prevDayLow - profitTargetMultiplier * (prevDayHigh - prevDayLow) // Execute trade entries with dynamic SL and TP if (longCondition) strategy.entry("Long", strategy.long) strategy.exit("Exit Long", "Long", stop=longSL, limit=longTP) if (shortCondition) strategy.entry("Short", strategy.short) strategy.exit("Exit Short", "Short", stop=shortSL, limit=shortTP) // Conditional plotting for SL/TP outside local scope plotshape(showSLTP and longCondition ? longSL : na, title="Long SL", location=location.absolute, color=color.red, style=shape.cross, size=size.tiny) plotshape(showSLTP and longCondition ? longTP : na, title="Long TP", location=location.absolute, color=color.green, style=shape.cross, size=size.tiny) plotshape(showSLTP and shortCondition ? shortSL : na, title="Short SL", location=location.absolute, color=color.red, style=shape.cross, size=size.tiny) plotshape(showSLTP and shortCondition ? shortTP : na, title="Short TP", location=location.absolute, color=color.green, style=shape.cross, size=size.tiny)
This TradingView Pine Script strategy trades based on the previous day’s high and low breakouts, with dynamic stop-loss and take-profit levels. Let’s break down the code section by section:
1. Strategy Settings and Inputs:
//@version=5
strategy("Previous Day High and Low Strategy with SL/TP Toggle and Dynamic SL", shorttitle="PDHL SL/TP Toggle Dynamic SL", overlay=true, initial_capital=10000, default_qty_type=strategy.percent_of_equity, default_qty_value=10)
profitTargetMultiplier = input.float(title="Profit Target Multiplier", defval=2.0, minval=0.1, maxval=100.0, step=0.1)
stopLossMultiplier = input.float(title="Stop Loss Multiplier", defval=1.0, minval=0.1, maxval=100.0, step=0.1)
showSLTP = input.bool(title="Show SL/TP Lines", defval=true)
//@version=5
: Specifies the Pine Script version.strategy(...)
: Defines the strategy with its name, short title, overlay setting (displays on the chart), initial capital, and default quantity settings (10% of equity per trade).input.float(...)
: Creates input options for the user to adjust the profit target multiplier (default 2.0), stop-loss multiplier (default 1.0), and a boolean toggle to show/hide the stop-loss and take-profit lines.
2. Fetching Previous Day’s High and Low:
prevDayHigh = request.security(syminfo.tickerid, "D", high[1], lookahead=barmerge.lookahead_on)
prevDayLow = request.security(syminfo.tickerid, "D", low[1], lookahead=barmerge.lookahead_on)
request.security(...)
: This function fetches data from a different timeframe. Here, it’s retrieving the daily (D) high and low.syminfo.tickerid
: The symbol of the current chart.high[1]
andlow[1]
: The high and low of the previous day.lookahead=barmerge.lookahead_on
: This is crucial. It prevents the strategy from “peeking into the future” and repainting. It ensures the strategy only uses data that would have been available then.
3. Plotting Previous Day’s High and Low:
plot(prevDayHigh, "Previous Day High", color=color.green, linewidth=2, style=plot.style_stepline)
plot(prevDayLow, "Previous Day Low", color=color.red, linewidth=2, style=plot.style_stepline)
plot(...)
: Plots the previous day’s high (green) and low (red) on the chart as steplines.
4. Entry Conditions:
longCondition = close > prevDayHigh and close[1] < prevDayHigh
shortCondition = close < prevDayLow and close[1] > prevDayLow
longCondition
: Checks if the current close is more excellent than the previous day’s high and the previous close was less than the previous day’s high (a breakout).shortCondition
: Checks the opposite for a short entry (breakout below the previous day’s low).
5. Dynamic Stop-Loss and Take-Profit Calculation:
float longSL = na
float longTP = na
float shortSL = na
float shortTP = na
if (longCondition)
longSL := prevDayLow - (stopLossMultiplier - 1) * (prevDayHigh - prevDayLow)
longTP := prevDayHigh + profitTargetMultiplier * (prevDayHigh - prevDayLow)
if (shortCondition)
shortSL := prevDayHigh + (stopLossMultiplier - 1) * (prevDayHigh - prevDayLow)
shortTP := prevDayLow - profitTargetMultiplier * (prevDayHigh - prevDayLow)
float longSL = na
, etc.: Declares variables to store the stop-loss and take-profit levels.na
It means “not a number” and is used to initialize them.- The
if
blocks calculate the SL and TP based on thestopLossMultiplier
andprofitTargetMultiplier
inputs. The SL is calculated relative to the previous day’s range, and the TP is a multiple of that range above or below the entry point. Notice how the SL is adjusted; astopLossMultiplier
of 1 means the SL is at the opposite end of the daily range, while a multiplier of 2 would double the range.
6. Trade Execution:
if (longCondition)
strategy.entry("Long", strategy.long)
strategy.exit("Exit Long", "Long", stop=longSL, limit=longTP)
if (shortCondition)
strategy.entry("Short", strategy.short)
strategy.exit("Exit Short", "Short", stop=shortSL, limit=shortTP)
strategy.entry(...)
: Enters a long or short position when the corresponding condition is met.strategy.exit(...)
: Sets the stop-loss and take-profit orders for the open position. The names “Exit Long” and “Exit Short” must match the entry names.
7. Plotting SL/TP Lines (Conditional):
plotshape(showSLTP and longCondition ? longSL : na, title="Long SL", location=location.absolute, color=color.red, style=shape.cross, size=size.tiny)
// ... (similar plotshape calls for longTP, shortSL, and shortTP)
plotshape(...)
: Plots shapes on the chart.- The conditional
showSLTP and longCondition ? longSL : na
means the shape is only plotted if theshowSLTP
input is valid and met. Otherwise, it plotsna
(nothing). This makes plotting SL/TP optional.
Key Improvements and Explanations:
- Dynamic SL/TP: The stop-loss and take-profit are calculated dynamically based on the previous day’s range and the multiplier inputs. This is a more sophisticated approach than fixed SL/TP levels.
- Lookahead Bias Prevention: The
lookahead=barmerge.lookahead_on
argument inrequest.security
is essential for preventing repainting. This ensures the strategy’s backtesting results are realistic. - SL/TP Toggle: The
showSLTP
input allows the user to turn the plotting of the SL/TP lines on or off, which can help keep the chart clean. - More apparent Variable Names: More descriptive variable names (e.g.,
longSL
,longTP
) improve readability. - Comments: The code is well-commented, making it easier to understand.
This strategy aims to capitalize on short-term breakouts of the previous day’s range with dynamically adjusted risk management. Remember to thoroughly backtest and optimize the strategy’s inputs before using it with real capital. Past performance is not indicative of future results.