Trading StrategyPine Script v6

Candlestick Pattern Strategy: From Candle Shape to Testable Rules

This long-only Pine Script example enters after a hammer-shaped candle, bullish body engulfing pattern or doji closes above an EMA. It turns specific geometry into a reproducible test; it does not establish that a pattern predicts a reversal. No measured performance results are supplied. Start with standard price candles, verify the order list, and choose costs appropriate to your market.

Separate candle geometry, trend conditions and execution

Three definitions, not a ranking of reliability

Body size is the absolute difference between open and close. Upper wick is high minus the larger of open and close; lower wick is the smaller of open and close minus low. The hammer rule requires a positive body, lower wick at least twice the body and upper wick no more than one tenth of the body. It does not require a preceding downtrend, so it is a geometric label rather than a complete reversal setup.

Bullish engulfing requires a bearish previous candle and bullish current candle whose body covers the previous body, allowing equal endpoints. It does not require the current high and low to engulf the previous full range. A doji has a body at most one tenth of its positive high-low range. The doji condition is directionless; the decision to test it as a long entry is this strategy's assumption.

The EMA is a gate

Each pattern must close above the EMA, set to 200 bars by default. This is a price-level test, not an EMA-slope or prior-downtrend test. Entries combine the three conditions with OR. The script runs on one chart symbol and timeframe and does not scan other markets.

Read signals separately from fills

A confirmed signal while flat submits one market entry and its stop/limit bracket. Under the supplied execution settings, the entry normally fills on the next available tick, typically the next bar open in a historical test. The stop is the signal-bar low minus two signal-bar ATR values by default; the target is 1.5 times the signal-close-to-stop distance above that close. Both prices are fixed when submitted, so the ratio to the actual fill can differ. These are not trailing exits, and gaps can produce a larger loss than the intended stop distance.

The 10% equity setting is order allocation, not an account-risk limit. The example uses 0.1% commission per execution and one tick of slippage as illustrative assumptions. Change them in Strategy Properties for the instrument and broker. See TradingView's official strategy execution and testing documentation for fill assumptions, costs and standard-chart limitations.

Pine Script v6 Implementation

Pine Script v6
//@version=6
strategy("Candlestick Pattern Strategy [Pineify]", overlay=true, initial_capital=10000, default_qty_type=strategy.percent_of_equity, default_qty_value=10, pyramiding=0, commission_type=strategy.commission.percent, commission_value=0.1, slippage=1)

// --- Inputs ---
emaLength = input.int(200, "EMA Trend Filter Length", minval=1)
atrLength = input.int(14, "ATR Length for Stop Loss", minval=1)
atrMultiplier = input.float(2.0, "ATR Multiplier for Stop Loss", minval=0.1, step=0.1)
riskRewardRatio = input.float(1.5, "Risk/Reward Ratio", minval=0.1, step=0.1)

// --- Indicators ---
ema200 = ta.ema(close, emaLength)
atr = ta.atr(atrLength)
plot(ema200, color=color.blue, title="200 EMA")

// --- Candlestick Pattern Logic ---
bodySize = math.abs(close - open)
upperWick = high - math.max(open, close)
lowerWick = math.min(open, close) - low
totalRange = high - low

// 1. Hammer Pattern
isHammer = totalRange > 0 and bodySize > 0 and lowerWick >= 2 * bodySize and upperWick <= 0.1 * bodySize and close > ema200

// 2. Bullish Engulfing Pattern
isBullishEngulfing = close[1] < open[1] and close > open and close >= open[1] and open <= close[1] and close > ema200

// 3. Doji Pattern
isDoji = totalRange > 0 and bodySize <= 0.1 * totalRange and close > ema200

// --- Entry Logic ---
longCondition = isHammer or isBullishEngulfing or isDoji

if (barstate.isconfirmed and longCondition and strategy.position_size == 0 and not na(atr) and atr > 0)
    stopLoss = low - (atr * atrMultiplier)
    takeProfit = close + (close - stopLoss) * riskRewardRatio
    strategy.entry("Long", strategy.long, comment="Pattern Detected")
    strategy.exit("Exit Long", "Long", stop=stopLoss, limit=takeProfit, comment="SL/TP Hit")

// --- Visual Cues ---
plotshape(isHammer, title="Hammer", location=location.belowbar, color=color.green, style=shape.labelup, text="Hammer")
plotshape(isBullishEngulfing, title="Engulfing", location=location.belowbar, color=color.blue, style=shape.labelup, text="Engulfing")
plotshape(isDoji, title="Doji", location=location.belowbar, color=color.gray, style=shape.labelup, text="Doji")

Match each rule to the script

  1. 1

    The configurable EMA and ATR use the chart timeframe. They are calculated each bar; insufficient ATR history blocks an entry.

  2. 2

    Pattern labels identify geometry above the EMA, including when a position is already open. A label is not proof that an order filled.

  3. 3

    Positive candle range guards prevent a flat OHLC bar from qualifying as a doji or hammer. ATR and reward multipliers must be positive.

  4. 4

    The confirmed-bar entry gate accepts any of the three patterns only while flat. There are no short entries, support-level tests or session filters.

  5. 5

    The exit bracket is submitted with the entry using signal-bar prices. It stays fixed; this implementation does not recalculate a trailing stop from later ATR values.

Backtest Assumptions and Metrics

No measured backtest results are supplied. The table describes the example settings. Run your own documented test before interpreting performance; these inputs are not an established optimal configuration.

MetricValue
DirectionLong only
Initial capital10,000 account-currency units
Order allocation10% of equity
EMA / ATR periods200 / 14 bars
Stop offset / target ratio2 ATR / 1.5 signal-price ratio
Commission / slippage0.1% per execution / 1 tick

Record the exchange symbol, timeframe, date range, account currency, costs and every input before comparing runs. Examine trade count, net results after costs, drawdown and sensitivity to nearby parameters. Reserve unseen data for evaluation; selecting a profitable in-sample setting is not evidence of future profitability. No pattern win-rate ranking has been established here.

Review changes with Pineify Coding Agent

Pineify Coding Agent can help draft and explain Pine Script changes. Ask for one explicit modification at a time, such as a pattern toggle or session condition, and request a syntax check. Review the generated source and test it in TradingView; compiling does not validate strategy logic or establish profitability.

The Visual Pine Editor offers a separate configuration workflow for supported components. This tutorial does not claim that pasting arbitrary Pine code imports it into the visual builder. Neither workflow executes this example as a live brokerage strategy.

Strategy Optimization Suggestions

1

Isolate the pattern contribution

Create separate test variants for hammer, engulfing and doji entries while holding other settings constant. Pattern toggles are not implemented in this example; they require a code change.

2

Vary the trend gate

Compare nearby EMA lengths on a fixed sample, then evaluate the selected rule on unseen data. Do not assume that a longer EMA raises the win rate.

3

Test costs and gaps

Increase commission and slippage assumptions and inspect gap fills. A stop price is not a guarantee of maximum loss.

4

Define any additional filter before testing

Session, trend-slope and multi-pattern confirmation filters require new rules and code. They can reduce the sample size as well as change results; improvement is a hypothesis.

Frequently Asked Questions

This page provides no measured ranking. Compare separate pattern variants on the same instrument, dates, costs and exit rules, then check an independent period.

No. It checks wick-to-body geometry above the EMA. It does not test a preceding decline or a support level, and the candle can have either body direction.

The target uses the signal close and the stop uses the signal low and ATR. A market entry usually fills later, so a gap, costs or slippage changes the realized risk/reward. The bracket is fixed, not trailing.

No. The script simulates trades on its current TradingView chart. Multi-symbol scanning, alerts and broker execution are separate features and are not implemented in this example.

Specify the intended rule, request a syntax check, inspect the source and compare the resulting order list in TradingView. A successful compile does not prove the rule is correct or profitable.

Make One Rule Change, Then Inspect the Test

Use the coding workflow to draft a specific variation, keep a copy of the baseline, and compare assumptions and simulated orders before interpreting performance.

Disclaimer: Trading involves significant risk. The strategies and code provided are for educational purposes only and do not constitute financial advice. Past performance is not indicative of future results.