Pine Script Scalping Strategy: Read the Rules and Test Execution
A Pine Script scalping strategy can simulate short-term entries and exits, but its value depends on the rules and execution assumptions. The example below combines moving-average crossovers, RSI, and Bollinger Bands. It has no protective stop order, and its entry conditions may be restrictive. Those facts matter more than labeling it a scalping system or assigning it an unsupported win rate.

What the Example Actually Trades
The table below follows the source listing, including its asymmetrical RSI exit thresholds. Parameter values are the existing defaults, not evidence of suitable settings for a particular market.
| Rule | Long position | Short position |
|---|---|---|
| Entry | 20-bar SMA crosses above 200-bar SMA while RSI is below 30 | 20-bar SMA crosses below 200-bar SMA while RSI is above 70 |
| RSI exit | RSI rises above 30 | RSI falls below 70 |
| Band exit | Close reaches or exceeds the upper band | Close reaches or falls below the lower band |
| Band calculation | 20-bar SMA plus two standard deviations | 20-bar SMA minus two standard deviations |
| Size declaration | 10% of equity as position value | 10% of equity as position value |
| Protective stop | None in the source | None in the source |
Both entry conditions must be true on the same bar. A crossover is an event, whereas a fast average remaining above a slow average is a state. The example requires the event. If no trades appear, check how often the crossover and RSI extreme coincide before assuming there is a platform error.
The long RSI exit does not require RSI to enter the whole 30–70 interval; any value above 30 satisfies it. Likewise, the short exit only requires a value below 70. These are signal-based market exits, not fixed profit targets. They can close losing positions.
Retained Pine Script Example
This listing is retained for inspection. The article does not supply a new compiler validation or a verified performance run for it. In particular, do not infer that risk controls discussed later are already implemented.
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Pineify
//======================================================================//
// ____ _ _ __ //
// | _ \(_)_ __ ___(_)/ _|_ _ //
// | |_) | | '_ \ / _ \ | |_| | | | //
// | __/| | | | | __/ | _| |_| | //
// |_| |_|_| |_|\___|_|_| \__, | //
// |___/ //
//======================================================================//
//@version=6
strategy("Pine Script Scalping Strategy", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=10)
// Input parameters
lengthMA = input.int(20, title="Fast MA Length", minval=1)
longMALength = input.int(200, title="Slow MA Length", minval=1)
rsiLength = input.int(14, title="RSI Length", minval=1)
bbLength = input.int(20, title="Bollinger Bands Length", minval=1)
rsiOversold = input.int(30, title="RSI Oversold Level", minval=1, maxval=50)
rsiOverbought = input.int(70, title="RSI Overbought Level", minval=50, maxval=100)
// Calculate indicators
shortMA = ta.sma(close, lengthMA)
longMA = ta.sma(close, longMALength)
rsi = ta.rsi(close, rsiLength)
basis = ta.sma(close, bbLength)
dev = 2 * ta.stdev(close, bbLength)
upper = basis + dev
lower = basis - dev
// Plot indicators
plot(shortMA, color=color.blue, title="Fast MA", linewidth=2)
plot(longMA, color=color.red, title="Slow MA", linewidth=2)
plot(basis, color=color.yellow, title="BB Middle")
p1 = plot(upper, color=color.green, title="BB Upper")
p2 = plot(lower, color=color.green, title="BB Lower")
fill(p1, p2, title="BB Background", color=color.rgb(33, 150, 243, 90))
// Entry conditions
longCondition = ta.crossover(shortMA, longMA) and rsi < rsiOversold
shortCondition = ta.crossunder(shortMA, longMA) and rsi > rsiOverbought
// Exit conditions
longExitCondition = rsi > rsiOversold or close >= upper
shortExitCondition = rsi < rsiOverbought or close <= lower
// Execute trades
if (longCondition)
strategy.entry("Long", strategy.long)
if (shortCondition)
strategy.entry("Short", strategy.short)
if (longExitCondition and strategy.position_size > 0)
strategy.close("Long")
if (shortExitCondition and strategy.position_size < 0)
strategy.close("Short")
// Plot entry signals
plotshape(longCondition, title="Long Signal", location=location.belowbar, color=color.green, style=shape.triangleup, size=size.small)
plotshape(shortCondition, title="Short Signal", location=location.abovebar, color=color.red, style=shape.triangledown, size=size.small)
Signal Timing Is Not Fill Timing
The code uses strategy.close() after detecting an exit condition. It does not place a limit order at a Bollinger Band. If a bar's high touches the upper band but its close finishes below it, the long band-exit condition is not satisfied. If the close finishes above it, the resulting market exit still depends on the emulator's execution settings.
Under ordinary default strategy calculation, a bar-close signal generally results in a fill on a later tick rather than at the signal's close. Opposite-direction strategy.entry() orders can also reverse an existing position. TradingView describes these mechanics in its strategy documentation. Review reversal transactions and conditional exits separately in the order list.
Switching to tick-by-tick recalculation changes live behavior without recreating complete historical tick data. A one-minute chart label does not establish that a strategy captures every price movement or executes automatically in a brokerage account.
Measure Costs in the Same Units as the Target
Small intended price moves make the cost assumptions important. For a hypothetical share trade with entry price 100 and exit price 100.10, the gross gain is 0.10 per share. If total entry-and-exit fees, spread, and slippage are 0.08 per share, the net gain is 0.02. These are illustrative inputs, not observed results or a broker quote.
Net profit = quantity × (exit price − entry price) − total trading costs
That equation applies to a long cash-equity example. Short positions, derivatives, currency conversion, borrowing fees, and funding payments require the corresponding accounting. Do not apply a per-share calculation unchanged to a futures contract.
For equal-unit outcomes, the break-even win fraction is:
Break-even win fraction = (average gross loss + average cost) / (average gross win + average gross loss)
The formula assumes nonnegative win/loss magnitudes and a comparable average cost per completed trade. It illustrates why a claimed 60% win rate alone cannot establish profitability. It does not predict this strategy's win rate.
Position Value and Risk Are Different
The listing requests an order worth 10% of equity. It does not calculate quantity from a stop distance. Because it has no protective stop, there is no stop-defined maximum loss to attach to that setting.
For a separate cash-equity design that actually places a stop, a planning calculation is:
Quantity = planned dollar risk / (entry-to-stop distance per share + estimated loss-side costs per share)
Round to the allowed trading increment and enforce available capital. A stop is an execution instruction, not a guarantee that a gap or liquidity shortage will fill at the requested price. The planned risk fraction must be chosen for the account and overall exposure; the article has no basis for prescribing a universal 1%–2% scalping allocation.
If the intended system requires a stop, a maximum holding period, or a session close exit, those are additional rules to implement and validate before treating this example as that system.
A Reproducible Scalping Test
- Record the market precisely. Save the exchange-qualified instrument, timeframe, session, time zone, and data provider. State whether the test includes extended hours.
- Verify the sample. Confirm available intraday history and the warm-up period for the 200-bar average. Record the effective start and end of the evaluated trades.
- Count entry opportunities. Inspect crossover bars and RSI values. Separate a lack of qualifying signals from rejected orders or insufficient capital.
- Audit individual fills. Include a long entry, a short entry, an RSI exit, a band exit, and a reversal if they occur. Explain any missing category rather than inventing examples.
- Apply execution costs. Save the actual commission model and a justified spread/slippage assumption. Run a worse-cost scenario to show how dependent the result is on fills.
- Reserve later data. Choose candidate rules on an earlier period, then evaluate the frozen rules on a later period. Keep results for failed variants too.
- Log live observations. Compare confirmed signal timestamps, alert timestamps, and any separately obtained paper fills. This checks operational behavior without treating simulated fills as real execution evidence.
When order sequencing within a candle matters, TradingView's Bar Magnifier documentation explains how lower-timeframe data can refine historical fills. Availability and historical coverage remain constraints; it does not model order-book queue position or guarantee live fills.
What Would Support a Performance Claim?
A useful result needs the exact source version, settings, data range, all trading costs, trade list, and equity curve. Report net profit, drawdown, trade count, average net trade, and exposure. If the strategy trades rarely, disclose that instead of claiming it has been validated for frequent scalping.
This article provides none of the records required to substantiate the previously stated NASDAQ-100 return or win rate. Those figures are not retained as evidence. The next useful result would be a reproducible test of the exact listing, including the missing protective-stop limitation.
Frequently Asked Questions
Does this scalping example include stop losses?
No. It closes positions on RSI or closing-price conditions and may reverse on an opposite entry. A protective stop and stop-based sizing would require additional implementation and validation.
Why might the script produce very few trades?
Each entry requires an SMA crossover and an RSI extreme on the same bar. Check their intersection, available warm-up data, and order settings before changing parameters.
Does touching a Bollinger Band guarantee a profitable exit?
No. The example evaluates closing price relative to the band, and it submits a market close rather than a band-price limit order. The trade can be losing when that condition occurs.
How long should a scalping backtest run?
Calendar length alone is insufficient. Report the actual trade count, market conditions, data coverage, and a later holdout. A fixed number of months cannot guarantee statistical reliability.
