Strategy · Pine Script v5 · On the chart

Buy the Dip in an Uptrend

by Jaden300· code credited to your_username

This strategy overlays directly on the price chart to identify pullback buying opportunities during established bullish moves.

View on GitHub

GitHub stars4on the repository
Pine versionv5runs as is
Lines of code116
Settings7inputs
LicenceNone statedfile: MPL-2.0
Last update5 months ago31 May 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new strategy, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart. The trades and results appear in the Strategy Tester tab; adjust the settings with the gear icon.

Source Code

116 lines of Pine Script v5 from strategy/strategy_pullback/pine_pullback_largecap.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

pine_pullback_largecap.pine
// This source code is subject to the terms of the Mozilla Public License 2.0
// © your_username
//
// "Buy the Dip in an Uptrend" — Pullback Strategy
//
// HOW IT WORKS:
//   1. Looks back long_period bars and checks that price went UP by at least trend_threshold
//   2. Then checks that price has pulled DOWN by at least dip_threshold over the last short_period bars
//   3. If both are true → places a buy-stop slightly above the current close
//   4. Once filled, sets a Take Profit and Stop Loss from entry price
//
// SETTINGS: plug in the best values from your Python optimizer output (run_tsla.py)

//@version=5
strategy(
     title             = "Buy the Dip in an Uptrend",
     overlay           = true,
     initial_capital   = 500,
     currency          = currency.USD,
     commission_type   = strategy.commission.percent,
     commission_value  = 1.5,
     default_qty_type  = strategy.percent_of_equity,
     default_qty_value = 100,
     calc_on_every_tick = false
 )

// ── Inputs ────────────────────────────────────────────────────────────────────

// ── OPTIMIZED VALUES (NVDA, GOOG, AAPL, MSFT, AMZN, AVGO — Apr 2025 → Apr 2026) ──
// Cross-asset score: 0.72  |  Mean Sharpe: 0.97  |  Avg return: +21%
// Per-ticker $500 results: NVDA +14%, GOOG +21%, AAPL +19%, MSFT +3%, AMZN +17%, AVGO +52%
// You can tweak these in the Settings panel on TradingView

grp1 = "Signal Parameters"
long_period     = input.int  (15,    "Long Period (bars — the 'first month')",   minval=5,     group=grp1)
short_period    = input.int  (8,     "Short Period (bars — the 'dip window')",   minval=3,     group=grp1)
trend_threshold = input.float(0.02,  "Min Uptrend % (e.g. 0.02 = 2%)",          step=0.01,    group=grp1)
dip_threshold   = input.float(0.02,  "Min Dip % (e.g. 0.02 = 2%)",              step=0.01,    group=grp1)

grp2 = "Entry / Exit"
stop_buffer     = input.float(0.02,  "Buy-Stop Buffer above close (e.g. 0.02 = 2%)", step=0.005, group=grp2)
tp_pct          = input.float(0.25,  "Take Profit % from entry (e.g. 0.25 = 25%)",   step=0.01,  group=grp2)
sl_pct          = input.float(0.12,  "Stop Loss % from entry   (e.g. 0.12 = 12%)",   step=0.01,  group=grp2)

// ── Signal conditions ─────────────────────────────────────────────────────────

price_long_ago  = close[long_period]
price_short_ago = close[short_period]

// Month 1: did price go UP from long_period bars ago → short_period bars ago?
trend_ok = (price_short_ago / price_long_ago - 1.0) >= trend_threshold

// Month 2: has price pulled DOWN from short_period bars ago → now?
dip_ok = (close / price_short_ago - 1.0) <= -dip_threshold

signal = trend_ok and dip_ok

// ── Entry ─────────────────────────────────────────────────────────────────────

buy_stop_price = close * (1.0 + stop_buffer)

if signal and strategy.position_size == 0
    strategy.entry("Long", strategy.long, stop=buy_stop_price,
                   comment="BUY DIP")

// Cancel the pending order if conditions are no longer met
if not signal and strategy.position_size == 0
    strategy.cancel("Long")

// ── Exit ──────────────────────────────────────────────────────────────────────

if strategy.position_size > 0
    tp_price = strategy.position_avg_price * (1.0 + tp_pct)
    sl_price = strategy.position_avg_price * (1.0 - sl_pct)
    strategy.exit("Exit", from_entry="Long", limit=tp_price, stop=sl_price)

// ── Visuals ───────────────────────────────────────────────────────────────────

in_trade = strategy.position_size > 0

// TP / SL lines while in a trade
tp_line = in_trade ? strategy.position_avg_price * (1.0 + tp_pct) : na
sl_line = in_trade ? strategy.position_avg_price * (1.0 - sl_pct) : na
entry_line = in_trade ? strategy.position_avg_price : na

plot(tp_line,    "Take Profit", color=color.new(color.green, 0),  style=plot.style_linebr, linewidth=1)
plot(sl_line,    "Stop Loss",   color=color.new(color.red,   0),  style=plot.style_linebr, linewidth=1)
plot(entry_line, "Entry",       color=color.new(color.white, 30), style=plot.style_linebr, linewidth=1)

// Arrow below bar when signal fires and we're flat
plotshape(
     signal and not in_trade,
     title     = "Dip Signal",
     style     = shape.triangleup,
     location  = location.belowbar,
     color     = color.new(color.blue, 20),
     size      = size.small,
     text      = "DIP"
 )

// Green background while in a trade
bgcolor(in_trade ? color.new(color.green, 90) : na, title="In Trade")

// ── Info table ────────────────────────────────────────────────────────────────

var table info = table.new(position.top_right, 2, 4, border_width=1)

if barstate.islast
    table.cell(info, 0, 0, "TP",          text_color=color.white, bgcolor=color.gray)
    table.cell(info, 1, 0, str.tostring(tp_pct * 100, "#.0") + "%", text_color=color.green)
    table.cell(info, 0, 1, "SL",          text_color=color.white, bgcolor=color.gray)
    table.cell(info, 1, 1, str.tostring(sl_pct * 100, "#.0") + "%", text_color=color.red)
    table.cell(info, 0, 2, "Commission",  text_color=color.white, bgcolor=color.gray)
    table.cell(info, 1, 2, "1.5% / leg",  text_color=color.yellow)
    table.cell(info, 0, 3, "Capital",     text_color=color.white, bgcolor=color.gray)
    table.cell(info, 1, 3, "$500",        text_color=color.white)

Overview

Buy the Dip in an Uptrend checks whether price gained by a specified percentage over an earlier window and subsequently pulled back by a minimum threshold over a recent window. Upon meeting these conditions, it places a buy-stop order slightly above the close. Once executed, positions exit via fixed percentage take-profit and stop-loss targets from entry price. Configurable inputs adjust lookback durations, percentage thresholds, order buffer, and exit targets.

Details

Published by

Jaden300 on GitHub

Code credit

your_username, as written in the script's header

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Trend, Mean reversion

Markets

Stocks

Timeframes

H4 and above

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Topics

algorithmic-tradingbacktestingstock-markettradingview-ideas

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Long Period (bars — the 'first month')int15long_period
Short Period (bars — the 'dip window')int8short_period
Min Uptrend % (e.g. 0.02 = 2%)float0.02trend_threshold
Min Dip % (e.g. 0.02 = 2%)float0.02dip_threshold
Buy-Stop Buffer above close (e.g. 0.02 = 2%)float0.02stop_buffer
Take Profit % from entry (e.g. 0.25 = 25%)float0.25tp_pct
Stop Loss % from entry (e.g. 0.12 = 12%)float0.12sl_pct
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

330 stars

This strategy calculates Bollinger Bands and Aroon oscillator values to identify mean-reversion opportunities. It enters a long position using full equity when the closing price crosses below the lower Bollinger Band while Aroon Up remains above a user-specifi

Strategy v5 Mean reversionVolatility & bands
Updated 2 months ago · None stated GitHub repository of Bollinger bands + Aroon [Alorse]
285 stars

Mean Reversion Strategy is an overlay strategy that identifies pullbacks using a long-term EMA, RSI, and candlestick patterns. It generates long signals when a bullish engulfing candle forms below the EMA while RSI is oversold, and short signals when a bearish

Strategy v4 Mean reversionCandlestick patterns
Updated 3 years ago · None stated GitHub repository of Mean Reversion Strategy

8 Day Run

by hasnocool
106 stars

Inspired by Linda Raschke's strategy for T-note futures, this script identifies extended trends where price remains on one side of a 5-period SMA for more than eight consecutive bars. It enters long on the first pullback below the SMA following an eight-bar bu

Strategy v4 TrendMoving averages
Updated 2 years ago · GPL-3.0 GitHub repository of 8 Day Run

Bollinger Bands Strategy

by cklose2000
105 stars

This strategy generates buy and sell signals based on Bollinger Band crossovers combined with a simple moving average trend filter. It enters a long position when price crosses above the lower band while trading above the SMA filter line, and enters a short po

Strategy v5 Volatility & bandsMoving averages
Updated 1 year ago · None stated GitHub repository of Bollinger Bands Strategy
53 stars

This strategy identifies long entry opportunities based on short-term price pullbacks below a major trend filter. It enters long when three consecutive lower closes occur below the 200-period simple moving average, followed by the current bar closing back abov

Strategy v6 TrendMoving averages
Updated 2 months ago · MPL-2.0 GitHub repository of Ivan Scherman Pattern - TP/SL

More strategys

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers