Strategy · Pine Script v5 · On the chart

Previous Candle Theory

by wynnforthework· code credited to TraderNunz

This strategy enters trades based on consecutive candle directions relative to a chosen moving average filter.

View on GitHub

GitHub stars2on the repository
Pine versionv5runs as is
Lines of code62
Settings5inputs
LicenceNone statedfile: MPL-2.0
Last update1 year ago7 Oct 2025

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

62 lines of Pine Script v5 from 策略/Previous Candle Theory.txt, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

Previous Candle Theory.txt
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © TraderNunz

//@version=5
strategy("Previous Candle Theory", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=10)

// Define the tick size
tick_size = syminfo.mintick

// Input fields for user to set stop loss and take profit in ticks
ticks_stop_loss = input.int(20, title="Stop Loss (ticks)")
ticks_take_profit = input.int(40, title="Take Profit (ticks)")

// Input fields for EMA and SMA periods
ema_period = input.int(9, title="EMA Period")
sma_period = input.int(21, title="SMA Period")

// Input field to select the type of moving average
use_ema = input.bool(true, title="Use EMA (false = SMA)")

// Calculate the moving averages
ema_value = ta.ema(close, ema_period)
sma_value = ta.sma(close, sma_period)

// Choose which moving average to use based on the input
ma_value = use_ema ? ema_value : sma_value

// Calculate the stop loss and take profit prices based on ticks
stop_loss_price_long = close - (ticks_stop_loss * tick_size)
take_profit_price_long = close + (ticks_take_profit * tick_size)

stop_loss_price_short = close + (ticks_stop_loss * tick_size)
take_profit_price_short = close - (ticks_take_profit * tick_size)

// Define the condition for a positive or negative candle
is_positive_candle = close > open
is_negative_candle = close < open

// Entry conditions based on the previous candle's direction and selected moving average
long_condition = is_positive_candle[1] and is_positive_candle and close > ma_value
short_condition = is_negative_candle[1] and is_negative_candle and close < ma_value

// Execute trades based on the conditions
if (long_condition)
    strategy.entry("Long", strategy.long)

if (short_condition)
    strategy.entry("Short", strategy.short)

// Exit conditions based on tick-based stop loss and take profit
strategy.exit("Exit Long", from_entry="Long", stop=stop_loss_price_long, limit=take_profit_price_long)
strategy.exit("Exit Short", from_entry="Short", stop=stop_loss_price_short, limit=take_profit_price_short)

// Plot the selected moving average for visual reference
plot(ma_value, title="Selected MA", color=use_ema ? color.blue : color.orange, linewidth=2)

// Plot the candles for visual reference
plotshape(series=long_condition, title="Long Signal", location=location.belowbar, color=color.green, style=shape.labelup, text="BUY")
plotshape(series=short_condition, title="Short Signal", location=location.abovebar, color=color.red, style=shape.labeldown, text="SELL")

// Plot a background color for visual feedback on the chart's timeframe
bgcolor(long_condition ? color.new(color.green, 90) : short_condition ? color.new(color.red, 90) : na)

Overview

Previous Candle Theory triggers a long entry when both the current and previous candles close bullish above the moving average, and a short entry when both candles close bearish below it. Trades exit using static tick-based stop loss and take profit prices established at entry. Inputs allow selection between an Exponential Moving Average (EMA) or Simple Moving Average (SMA), period adjustments, and custom tick distances for exits. Signals and indicators are plotted directly on the price chart.

Details

Published by

wynnforthework on GitHub

Code credit

TraderNunz, as written in the script's header

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Trend, Moving averages, Candlestick patterns

Markets

Any symbol

Timeframes

Any timeframe

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.

Settings

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

SettingTypeDefaultVariable
Stop Loss (ticks)int20ticks_stop_loss
Take Profit (ticks)int40ticks_take_profit
EMA Periodint9ema_period
SMA Periodint21sma_period
Use EMA (false = SMA)booltrueuse_ema
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

Pin Bar Magic v1

by Alorse
330 stars

This strategy trades price action pin bar patterns aligned with moving average trend alignment on the main price chart. It defines uptrends or downtrends using a fan arrangement of three moving averages (6 EMA, 18 EMA, and 50 SMA). Entry conditions require a b

Strategy v4 Candlestick patternsTrend
Updated 2 months ago · None stated GitHub repository of Pin Bar Magic v1
257 stars

This overlay strategy marks short-term turning points on the price chart and enters SPY option-style trades from them. It plots simple moving averages of highs and lows, draws up and down reversal arrows, and colors bars when a short-term extreme coincides wit

Strategy v5 TrendMoving averages Repaints
Updated 6 weeks ago · None stated GitHub repository of SPY Options Trading - Alert

This strategy calculates and plots smoothed Heikin-Ashi candles directly onto the main price chart using exponential moving averages of open, high, low, and close prices. It enters a long position after three consecutive bullish smoothed candles with sequentia

Strategy v4 TrendMoving averages
Updated 2 years ago · GPL-3.0 GitHub repository of Abdoli's Heikin Ashi Smoothed Buy & Sell Strategy Rev.4

DI Engulfing A002

by ruckard
13 stars

This strategy executes trades based on candlestick engulfing patterns aligned with a 200-period exponential moving average trend filter. It enters long positions when a bullish engulfing candle follows three consecutive bearish candles while price trades above

Strategy v5 Candlestick patternsTrend
Updated 1 year ago · None stated GitHub repository of DI Engulfing A002
7 stars

This strategy combines Ichimoku Kinko Hyo components, a Stochastic oscillator, and specific candlestick patterns to generate trade signals. It identifies Kumo twists and range breakouts while evaluating candle body shapes using Fibonacci threshold filters. Tra

Strategy v4 TrendOscillators & momentum
Updated 2 years ago · MIT GitHub repository of Soulevement / Ressaut Strategy

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