Strategy · Pine Script v5 · On the chart

Simple Pullback Strategy

by Web3Degenerate

This strategy executes long trades during pullbacks within an established uptrend, plotting moving averages, entry prices, and stop levels on the price chart.

View on GitHub

GitHub stars2on the repository
Pine versionv5runs as is
Lines of code59
Settings6inputs
LicenceNone statedfile: MPL-2.0
Last update2 years ago13 Sep 2024

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

59 lines of Pine Script v5 from advanced-pine-script/9.Strategy-Scripts/10.Pullback-Strategy-Example.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

10.Pullback-Strategy-Example.pine
//Demonstrates how to convert an extremely simple strategy idea into Pine Script Code (with a 75% win rate)

// 00:00 - Strategy Overview
// 10:30 - User Input
// 13:42 - Strategy Conditions
// 20:50 - Entry & Exits
// 27:10 - Outro & Summary

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/

// @version=5
strategy("Simple Pullback Strategy", 
     overlay=true, 
     initial_capital=50000,
     default_qty_type=strategy.percent_of_equity, 
     default_qty_value=100, // 100% of balance invested on each trade
     commission_type=strategy.commission.cash_per_contract, 
     commission_value=0.005) // Interactive Brokers rate

// Get user input
i_ma1           = input.int(title="MA 1 Length", defval=200, step=10, group="Strategy Parameters", tooltip="Long-term MA")
i_ma2           = input.int(title="MA 2 Length", defval=10, step=10, group="Strategy Parameters", tooltip="Short-term MA")
i_stopPercent   = input.float(title="Stop Loss Percent", defval=0.10, step=0.1, group="Strategy Parameters", tooltip="Failsafe Stop Loss Percent Decline")
i_lowerClose    = input.bool(title="Exit On Lower Close", defval=false, group="Strategy Parameters", tooltip="Wait for a lower-close before exiting above MA2")
i_startTime     = input.time(title="Start Filter", defval=timestamp("01 Jan 1995 13:30 +0000"), group="Time Filter", tooltip="Start date & time to begin searching for setups")
i_endTime       = input.time(title="End Filter", defval=timestamp("1 Jan 2099 19:30 +0000"), group="Time Filter", tooltip="End date & time to stop searching for setups")

// Get indicator values
ma1 = ta.sma(close, i_ma1)
ma2 = ta.sma(close, i_ma2)

// Check filter(s)
f_dateFilter = time >= i_startTime and time <= i_endTime

// Check buy/sell conditions
var float buyPrice = 0
buyCondition    = close > ma1 and close < ma2 and strategy.position_size == 0 and f_dateFilter
sellCondition   = close > ma2 and strategy.position_size > 0 and (not i_lowerClose or close < low[1])
stopDistance    = strategy.position_size > 0 ? ((buyPrice - close) / close) : na
stopPrice       = strategy.position_size > 0 ? buyPrice - (buyPrice * i_stopPercent) : na
stopCondition   = strategy.position_size > 0 and stopDistance > i_stopPercent

// Enter positions
if buyCondition
    strategy.entry(id="Long", direction=strategy.long)

if buyCondition[1]
    buyPrice := open

// Exit positions
if sellCondition or stopCondition
    strategy.close(id="Long", comment="Exit" + (stopCondition ? "SL=true" : ""))
    buyPrice := na

// Draw pretty colors
plot(buyPrice, color=color.lime, style=plot.style_linebr)
plot(stopPrice, color=color.red, style=plot.style_linebr, offset=-1)
plot(ma1, color=color.blue)
plot(ma2, color=color.orange)

Overview

Simple Pullback Strategy buys when the close is above the long-term simple moving average and below the short-term moving average. Positions exit when price closes above the short-term average, with an optional lower-close filter, or when price drops beyond a set stop loss percentage from the entry price. The stop loss is evaluated at bar close rather than as an intrabar stop order.

Details

Published by

Web3Degenerate on GitHub

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Trend, Moving averages, Mean reversion

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

  • The strategy enters trades without a stop loss

Settings

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

SettingTypeDefaultVariable
MA 1 Lengthint200i_ma1
MA 2 Lengthint10i_ma2
Stop Loss Percentfloat0.10i_stopPercent
Exit On Lower Closeboolfalsei_lowerClose
Start Filtertimetimestamp("01 Jan 1995 13:30 +0000")i_startTime
End Filtertimetimestamp("1 Jan 2099 19:30 +0000")i_endTime
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

This mean-reversion strategy plots Bollinger Bands and a long-term moving average directly on the price chart. It enters trades when price candles penetrate the outer Bollinger Bands beyond a user-defined body percentage, anticipating a price reversal. Entries

Strategy v5 Mean reversionVolatility & bands
Updated 2 months ago · None stated GitHub repository of Bollinger Bands Winner PRO [Alorse]

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
13 stars

This strategy evaluates market trend direction using a Noro TrendRibbon and creates a price corridor based on recent moving-average extremes, plotting directly on the price chart. It executes long entries when price dips below the corridor during an upward tre

Strategy v5 TrendMoving averages
Updated 1 year ago · None stated GitHub repository of Ruckard Noro TrendRibbon G004

VWAP Bounce - Eterna

by EternaHybridExchange
9 stars

This strategy overlays volume-weighted average price deviation bands and an exponential moving average trend filter directly on the price chart. It enters long positions during an uptrend when price recovers above the lower band, and enters short positions in

Strategy v5 Mean reversionTrend
Updated 7 months ago · MIT GitHub repository of VWAP Bounce - Eterna

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