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
//@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
The configurable EMA and ATR use the chart timeframe. They are calculated each bar; insufficient ATR history blocks an entry.
- 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
Positive candle range guards prevent a flat OHLC bar from qualifying as a doji or hammer. ATR and reward multipliers must be positive.
- 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
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.
| Metric | Value |
|---|---|
| Direction | Long only |
| Initial capital | 10,000 account-currency units |
| Order allocation | 10% of equity |
| EMA / ATR periods | 200 / 14 bars |
| Stop offset / target ratio | 2 ATR / 1.5 signal-price ratio |
| Commission / slippage | 0.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
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.
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.
Test costs and gaps
Increase commission and slippage assumptions and inspect gap fills. A stop price is not a guarantee of maximum loss.
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
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.
Related Strategy Tutorials
RSI Overbought Oversold Strategy Tutorial
Compare RSI threshold entries, recovery crosses and EMA trend filters. Test a Pine Script v6 strategy with explicit stops, costs and time exits on TradingView.
Breakout and Retest Strategy Tutorial
Study a Pine Script v6 breakout-and-retest strategy with confirmed pivots, volume filters and simulated ATR-based exits; test its assumptions in TradingView.
Mean Reversion Strategy Tutorial
Learn how to build, backtest, and optimize a Mean Reversion Strategy on TradingView using Bollinger Bands and RSI with Pine Script v5.
Bollinger Bands Breakout Strategy Tutorial
Master the Bollinger Bands Squeeze and Breakout strategy on TradingView. Learn the Pine Script v5 code and professional analysis with Pineify.