Pine Script v5 · Strategy
Stochastic Moving Average
A Pine Script v5 strategy built on Stoch (close, high), SMA (K, 2) and Crossover (K, D). It has 4 order rules, 2 entries among them, and trades long and short with the default settings. Exits use a stop loss and a profit target. Each trade commits 100 in cash and pays no commission. 30 settings; defaults include Risk : Reward 1.1, Risk Prct Equi 1 and Risk USD 200.
Generated from the script's code by a template: every clause is a fact read from the source. Not written by a person or a model, and not taken from the author's description.
- Does Stochastic Moving Average repaint?
- No
- No repainting patterns were found in the source. The live replay was not measured: the script acts only when barstate.isconfirmed is true, which Zeal Terminal's engine never reports during a live replay (it does not run a bar's closing update in live mode), so the replay cannot test this script.
- How did Stochastic Moving Average do on BTCUSDT 1D with default settings?
- +2.80%
- From 26 Jan 2024 to 21 Oct 2026, over 7 closed trades, against +102.5% for buy and hold. A backtest, not investment advice.
- What alerts does Stochastic Moving Average have?
- 4
- openLongAlertMessage; openShortAlertMessage; closeLongAlertMessage; closeShortAlertMessage.
- Does Stochastic Moving Average run in Pine Script v6?
- Yes
- Same 7 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine. Both versions were run on Zeal Terminal's engine, and the results are identical. The v6 script can be downloaded below.
- Does Stochastic Moving Average use a stop loss?
- Yes
- strategy.exit sets a stop on line 123, 124.
BTCUSDT · 1D · default settings
- Plot
- Plot
- Plot
- Plot
- Shape
- Shape
- Winning trade
- Losing trade
- Equity
- Buy and hold
Needs BINANCE:BTCUSDT 30 data, not available: a lower timeframe than the chart; the engine does not evaluate intrabar data Values that depend on it are empty on this chart.
- Net profit
- +2.80%
- $280.00
- Buy and hold
- +102.5%
- same period
- Closed trades
- 7
- 4 won · 3 lost
- Profitable
- 57.1%
- of closed trades
- Profit factor
- 1.47
- gross profit ÷ gross loss
- Max drawdown
- 4.44%
- −$464.36
One run with the author's default settings, $10,000 starting capital, commission as the script sets it. A long position was still open at the last bar. A single backtest says little about future results and is not a recommendation. Backtests are simulations on historical data and are not investment advice.
Review
What a careful reader of this script would point out, found by checking the source and the backtest.
-
Check
No commission
The backtest assumes free trading. Results on any real exchange will be lower.
-
Note
2 settings have no label
In the settings dialog riskPrctEqui (line 14), riskUSD (line 16) show an empty name. The labels on this page come from the variable names.
-
Note
No slippage
Fills are assumed at the exact open price. Add slippage in the properties for a more realistic test.
-
Note
Uses an argument v6 removed
when = on line 123, 124. The upgraded version below moves each call inside an if block.
Settings
Every input the script declares, with its default and what it feeds. Bounds are the ones the script enforces.
| Setting | Default | Type and range | Feeds |
|---|---|---|---|
| Trade Setup | |||
| Long Trades | true | bool | validLong |
| Short Trades | true | bool | validShort |
| Risk : Reward | 1.1 | float · min 0 · max 100 · step 0.1 | longTP shortTP |
| Risk = % Equity Set stop loss size as a percentage of 'Initial Capital' -> Strategy Parameter -> Properties tab (Low liquidity markets will affect will prevent to get an exact amount du to gaps) | false | bool | entry Long entry Short |
| Risk Prct Equi (no label in the script) | 1 | float · min 0 · max 100 · step 0.1 | entry Long entry Short |
| Risk = $ Amount Set stop loss size as a fixed Base currency amount (Low liquidity markets will affect will prevent to get an exact amount du to gaps) | true | bool | entry Long entry Short |
| Risk USD (no label in the script) | 200 | float · min 0 · max 1000000 · step 100 | entry Long entry Short |
| Stop Loss | |||
| ATR Multiplier | 3 | float · min 0 · max 100 · step 0.1 | SLdist |
| ATR Lookback | 14 | int · min 0 · max 1000 · step 1 | SLdist |
| Stochastic | |||
| K% | 14 | int · min 0 · max 1000 · step 1 | K |
| D% | 2 | int · min 0 · max 1000 · step 1 | D |
| OB | 80 | int · min 0 · max 100 · step 1 | line 62 fill |
| OS | 20 | int · min 0 · max 100 · step 1 | line 56 fill |
| Stoch. OB/OS lookbackThis option allow to look 'x' bars back for a value of the Stochastic K line to be overbought or oversold when detecting an entry signal (if 0, looks only at current bar. if 1, looks at current and previous and so on) | 0 | int · min 0 · max 100 · step 1 | line 55 line 61 |
| All must be OB/OSIf turned on, all bars within the Stochastic K line lookback period must be overbought or oversold to return a true signal | false | bool | line 59 line 65 |
#00ffff | color | fill | |
| Will trun to designated color when stochastic gets to opposite extrem zone of current trend / Number = transparency | #333333 | color | fill |
50 | int · min 0 · max 100 · step 10 | fill | |
| Exp. Moving Average | |||
| Fast EMA | 4 | int · min 0 · max 1000 · step 1 | ema1 |
| Slow EMA | 40 | int · min 0 · max 1000 · step 1 | ema2 |
#0066ff | color | l1 plot | |
#0000ff | color | l2 plot | |
| Reference Market | |||
| Reference Market Filter | false | bool | validLong validShort bgcolor |
| Market | BINANCE:BTCUSDT | symbol | emaHTF closeHTF |
| Timeframe | 30 | timeframe | emaHTF closeHTF |
| EMA Length | 50 | int | ema |
| 3Commas Alert Messages | |||
| Open Long Alert MessagePaste ''Message for deal start signal'' from long bot | | string | alert |
| Open Short Alert MessagePaste ''Message for deal start signal'' from short bot | | string | alert |
| Close Long Alert MessagePaste ''Message to close order at Market Price'' from long bot | | string | alert |
| Close Short Alert MessagePaste ''Message to close order at Market Price'' from short bot | | string | alert |
What it calculates
- Stochclose, high, low, K% (14)
K · line 49 - SMAK, D% (2)
D · line 50 - CrossoverK, D
stochBullCross · line 51 - CrossoverD, K
stochBearCross · line 52 - EMAclose, Fast EMA (4)
ema1 · line 68 - EMAclose, Slow EMA (40)
ema2 · line 69 - EMAclose, EMA Length (50)
ema · line 76 - ATRATR Lookback (14)
SLdist · line 90
Signal flow
How price data and settings reach the orders. Each box is a name in the script, or several computed the same way; each arrow is a value one of them reads. Hover a box for its members.
Order rules
| Order | Fires when | By default | Line |
|---|---|---|---|
| Open Long long | validLong | On | 118 |
| Open Short short | validShort | On | 121 |
| Exit Long Exit stop and limit | strategy.position_size > 0 | On | 123 |
| Exit Short Exit stop and limit | strategy.position_size < 0 | On | 124 |
Each order is guarded by the setting shown. “Off” orders never fire unless that setting is switched on.
Alerts
| Alert | Call | Message | Line |
|---|---|---|---|
| (no title) | alert | openLongAlertMessage | 129 |
| (no title) | alert | openShortAlertMessage | 131 |
| (no title) | alert | closeLongAlertMessage | 133 |
| (no title) | alert | closeShortAlertMessage | 135 |
Does it repaint?
No
No repainting patterns in the source.
- ClearHigher-timeframe data2 request.security call(s), none with lookahead on.
- ClearFuture-bar referencesNo negative history offsets such as close[-1].
- ClearIntrabar recalculationNo varip, calc_on_every_tick or realtime-only state. Orders are decided once per closed bar.
- ClearOrder timingOrders fill at the next bar's open, after the signal bar has closed.
The checks read the source; the replay runs it. Together they catch the common causes, not every possible one.
Other markets
Not run on other markets: the script requests BINANCE:BTCUSDT 30, and that data is not available here (a lower timeframe than the chart; the engine does not evaluate intrabar data). Its results would rest on empty values.
The trades
By market direction
| At entry, last 90 bars | Trades | Won | P&L |
|---|---|---|---|
| Rising market | 2 | 100% | $440.00 |
| Sideways market | 3 | 33% | −$180.00 |
| Falling market | 2 | 50% | $20.00 |
Rising and falling mean the market moved more than 15% over the 90 bars before entry.
How bad could the drawdown be?
5.7%
The 95th percentile of the worst drawdown when the same 7 trades are reshuffled 5,000 times. The bar spans the 5th to 95th percentile, 1.9% to 5.7%; the tick is what actually happened, 3.8%. Order luck alone moves it this much.
All 7 trades
| Side | Entry | Exit | Bars | P&L |
|---|---|---|---|---|
| long | 29 Dec 2024 95,300.00 | 20 Jan 2025 108,641.00 | 22 | $220.00 |
| short | 26 Mar 2025 87,392.90 | 7 Apr 2025 75,465.60 | 12 | $220.00 |
| short | 19 Apr 2025 84,474.70 | 25 Apr 2025 94,789.70 | 6 | −$200.00 |
| short | 5 Dec 2025 92,078.10 | 31 Jan 2026 79,363.10 | 57 | $220.00 |
| long | 18 May 2026 77,457.70 | 1 Jun 2026 71,056.30 | 14 | −$200.00 |
| short | 8 Jul 2026 63,364.00 | 19 Aug 2026 69,966.90 | 42 | −$200.00 |
| long | 12 Sep 2026 77,225.70 | 21 Sep 2026 84,943.50 | 9 | $220.00 |
Similar scripts
Indicators and strategies built from the same calculations, run on BTCUSDT 1D with their own defaults so they can be compared directly.
| Script | Shares | Type | Net | Trades | Max drawdown |
|---|---|---|---|---|---|
| Stochastic Moving Average this page | — | v5 strategy | +2.8% | 7 | 4.4% |
| ATR with EOM and VORTEX by SoftKill21 | atr ema sma | v4 strategy | +66.2% | 22 | 29.9% |
| cATRpillar Strategy by Obi-wanClintobe | atr sma ema | v4 strategy | +1.02827e+24% | 27 | 88,097.2% |
| Optimized Zhaocaijinbao strategy by fzj20020403 | sma ema atr | v5 strategy | +15.6% | 12 | 9.8% |
| EMA & Supertrend by bhavikmota | ema sma atr | v4 strategy | +2,123.6% | 13 | 980.9% |
| Koala System EURUSD 15min by SoftKill21 | sma ema atr | v4 strategy | No trades on this market | ||
Upgrade and export
Written in Pine Script v5. The clean-v5 step types the settings and moves when = into if blocks, which v6 requires; it is run before and after like any upgrade.
- 2 strategy calls use the when = argument (line 123, 124). It is deprecated in v5 and removed in v6, where each call moves inside an if block.
- No v6-only features. v6 is not needed to run this script.
Same 7 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine.
- Line 123: when = strategy.position_size > 0 → if block
- Line 124: when = strategy.position_size < 0 → if block
⋯ qty = RiskEquity ? ((riskPrctEqui/100)*strategy.equity)/shortSLDist : RiskUSD ? riskUSD/shortSLDist : na)-strategy.exit(id="Long Exit" , from_entry="Long" , limit=TPsaved, stop=SLsaved, when=strategy.position_size > 0)+if strategy.position_size > 0+ strategy.exit(id="Long Exit" , from_entry="Long" , limit=TPsaved, stop=SLsaved)-strategy.exit(id="Short Exit", from_entry="Short", limit=TPsaved, stop=SLsaved, when=strategy.position_size < 0)+if strategy.position_size < 0+ strategy.exit(id="Short Exit", from_entry="Short", limit=TPsaved, stop=SLsaved)//==============================================================================⋯Does it run in Pine Script v6?
Yes
Same 7 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine. Both versions were run on Zeal Terminal's engine, and the results are identical. It differs from the v5 version by 1 edit.
⋯// Since this Strategy may have its stop loss hit within the opening candle, consider turning on 'Recalculate : After Order is filled' in the strategy settings, in the "Properties" tabs-//@version=5+//@version=6strategy("Stochastic Moving Average", shorttitle="Stoch. EMA", overlay=true, default_qty_type= strategy.cash, initial_capital=10000, default_qty_value=100)⋯Where it runs
| Engine | Compiles | Runs | Matches TradingView |
|---|---|---|---|
| Zeal Terminal · OpenPineScript v2 | Yes 43 ms | With a workaround 1,000 bars in 97 ms | Not measured |
| PineTS | Not tested | Not tested | Not measured |
The engine's host API cannot yet declare a chart's symbol and timeframe, so this page sets them on the engine directly for each market.
“Matches TradingView” needs this script's own output exported from TradingView and compared bar by bar, which has not been done for this script. The engine is built on OpenPineScript, whose conformance results are in its conformance report.
Source
Copied verbatim from the author's published script, with its licence header intact. The author may have updated the original since this snapshot.
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/// © LucasVivien// Since this Strategy may have its stop loss hit within the opening candle, consider turning on 'Recalculate : After Order is filled' in the strategy settings, in the "Properties" tabs//@version=5strategy("Stochastic Moving Average", shorttitle="Stoch. EMA", overlay=true, default_qty_type= strategy.cash, initial_capital=10000, default_qty_value=100)//==============================================================================//============================== USER INPUT ================================//==============================================================================var g_tradeSetup = " Trade Setup"activateLongs = input.bool (title="Long Trades" , defval=true , inline="A1", group=g_tradeSetup, tooltip="")activateShorts = input.bool (title="Short Trades" , defval=true , inline="A1", group=g_tradeSetup, tooltip="")rr = input.float(title="Risk : Reward" , defval=1.1 , minval=0, maxval=100 , step=0.1, inline="" , group=g_tradeSetup, tooltip="")RiskEquity = input.bool (title="Risk = % Equity ", defval=false , inline="A2", group=g_tradeSetup, tooltip="Set stop loss size as a percentage of 'Initial Capital' -> Strategy Parameter -> Properties tab (Low liquidity markets will affect will prevent to get an exact amount du to gaps)")riskPrctEqui = input.float(title="" , defval=1 , minval=0, maxval=100 , step=0.1, inline="A2", group=g_tradeSetup, tooltip="")RiskUSD = input.bool (title="Risk = $ Amount " , defval=true , inline="A3", group=g_tradeSetup, tooltip="Set stop loss size as a fixed Base currency amount (Low liquidity markets will affect will prevent to get an exact amount du to gaps)")riskUSD = input.float(title="" , defval=200 , minval=0, maxval=1000000, step=100, inline="A3", group=g_tradeSetup, tooltip="")var g_stopLoss = " Stop Loss"atrMult = input.float(title="ATR Multiplier", defval=3 , minval=0, maxval=100 , step=0.1, tooltip="", inline="", group=g_stopLoss)atrLen = input.int (title="ATR Lookback" , defval=14, minval=0, maxval=1000, step=1 , tooltip="", inline="", group=g_stopLoss)var g_stochastic = " Stochastic"Klen = input.int (title="K%" , defval=14, minval=0, maxval=1000, step=1, inline="S2", group=g_stochastic, tooltip="")Dlen = input.int (title=" D%" , defval=2 , minval=0, maxval=1000, step=1, inline="S2", group=g_stochastic, tooltip="")OBstochLvl = input.int (title="OB" , defval=80, minval=0, maxval=100 , step=1, inline="S1", group=g_stochastic, tooltip="")OSstochLvl = input.int (title=" OS" , defval=20, minval=0, maxval=100 , step=1, inline="S1", group=g_stochastic, tooltip="")OBOSlookback = input.int (title="Stoch. OB/OS lookback", defval=0 , minval=0, maxval=100 , step=1, inline="" , group=g_stochastic, tooltip="This option allow to look 'x' bars back for a value of the Stochastic K line to be overbought or oversold when detecting an entry signal (if 0, looks only at current bar. if 1, looks at current and previous and so on)")OBOSlookbackAll = input.bool (title="All must be OB/OS" , defval=false , inline="" , group=g_stochastic, tooltip="If turned on, all bars within the Stochastic K line lookback period must be overbought or oversold to return a true signal")entryColor = input.color(title=" " , defval=#00ffff , inline="S3", group=g_stochastic, tooltip="")baseColor = input.color(title=" " , defval=#333333 , inline="S3", group=g_stochastic, tooltip="Will trun to designated color when stochastic gets to opposite extrem zone of current trend / Number = transparency")transp = input.int (title=" " , defval=50, minval=0, maxval=100, step=10, inline="S3", group=g_stochastic, tooltip="")var g_ema = " Exp. Moving Average"ema1len = input.int (title="Fast EMA ", defval=4 , minval=0, maxval=1000, step=1, inline="E1", group=g_ema, tooltip="")ema2len = input.int (title="Slow EMA ", defval=40, minval=0, maxval=1000, step=1, inline="E2", group=g_ema, tooltip="")ema1col = input.color(title=" " , defval=#0066ff , inline="E1", group=g_ema, tooltip="")ema2col = input.color(title=" " , defval=#0000ff , inline="E2", group=g_ema, tooltip="")var g_referenceMarket =" Reference Market"refMfilter = input.bool (title="Reference Market Filter", defval=false , inline="", group=g_referenceMarket)market = input.symbol (title="Market" , defval="BINANCE:BTCUSDT", inline="", group=g_referenceMarket)res = input.timeframe(title="Timeframe" , defval="30" , inline="", group=g_referenceMarket)len = input.int (title="EMA Length" , defval=50 , inline="", group=g_referenceMarket)var g_alertMessages =" 3Commas Alert Messages"openLongAlertMessage = input.string(title="Open Long Alert Message" , defval="", group=g_alertMessages, tooltip="Paste ''Message for deal start signal'' from long bot")openShortAlertMessage = input.string(title="Open Short Alert Message" , defval="", group=g_alertMessages, tooltip="Paste ''Message for deal start signal'' from short bot")closeLongAlertMessage = input.string(title="Close Long Alert Message" , defval="", group=g_alertMessages, tooltip="Paste ''Message to close order at Market Price'' from long bot")closeShortAlertMessage = input.string(title="Close Short Alert Message", defval="", group=g_alertMessages, tooltip="Paste ''Message to close order at Market Price'' from short bot")//==============================================================================//========================== FILTERS & SIGNALS =============================//==============================================================================//------------------------------ Stochastic --------------------------------K = ta.stoch(close, high, low, Klen)D = ta.sma(K, Dlen)stochBullCross = ta.crossover(K, D)stochBearCross = ta.crossover(D, K)OSstoch = falseOBstoch = falsefor i = 0 to OBOSlookback if K[i] < OSstochLvl OSstoch := true else if OBOSlookbackAll OSstoch := falsefor i = 0 to OBOSlookback if K[i] > OBstochLvl OBstoch := true else if OBOSlookbackAll OBstoch := false//---------------------------- Moving Averages -----------------------------ema1 = ta.ema(close, ema1len)ema2 = ta.ema(close, ema2len)emaBull = ema1 > ema2emaBear = ema1 < ema2//---------------------------- Price source --------------------------------bullRetraceZone = (close < ema1 and close >= ema2) bearRetraceZone = (close > ema1 and close <= ema2)//--------------------------- Reference market -----------------------------ema = ta.ema(close, len)emaHTF = request.security(market, res, ema [barstate.isconfirmed ? 0 : 1])closeHTF = request.security(market, res, close[barstate.isconfirmed ? 0 : 1])bullRefMarket = (closeHTF > emaHTF or closeHTF[1] > emaHTF[1])bearRefMarket = (closeHTF < emaHTF or closeHTF[1] < emaHTF[1])//-------------------------- SIGNAL VALIDATION -----------------------------validLong = stochBullCross and OSstoch and emaBull and bullRetraceZone and activateLongs and (refMfilter ? bullRefMarket : true) and strategy.position_size == 0validShort = stochBearCross and OBstoch and emaBear and bearRetraceZone and activateShorts and (refMfilter ? bearRefMarket : true) and strategy.position_size == 0//==============================================================================//=========================== STOPS & TARGETS ==============================//============================================================================== // SL & TP calculationSLdist = ta.atr(atrLen) * atrMultlongSL = close - SLdistlongSLDist = close - longSLlongTP = close + (longSLDist * rr)shortSL = close + SLdistshortSLDist = shortSL - closeshortTP = close - (shortSLDist * rr)var SLsaved = 0.0var TPsaved = 0.0if validLong or validShort SLsaved := validLong ? longSL : validShort ? shortSL : na TPsaved := validLong ? longTP : validShort ? shortTP : na // SL & TP hitsvar longSLTPhit = falsevar shortSLTPhit = falseif strategy.position_size[1] > 0 and strategy.position_size == 0 and (high >= TPsaved or low <= SLsaved) longSLTPhit := trueelse longSLTPhit := falseif strategy.position_size[1] < 0 and strategy.position_size == 0 and (low <= TPsaved or high >= SLsaved) shortSLTPhit := trueelse shortSLTPhit := false//==============================================================================//========================== STRATEGY COMMANDS =============================//============================================================================== if validLong strategy.entry("Long", strategy.long, qty = RiskEquity ? ((riskPrctEqui/100)*strategy.equity)/longSLDist : RiskUSD ? riskUSD/longSLDist : na)if validShort strategy.entry("Short", strategy.short, qty = RiskEquity ? ((riskPrctEqui/100)*strategy.equity)/shortSLDist : RiskUSD ? riskUSD/shortSLDist : na)strategy.exit(id="Long Exit" , from_entry="Long" , limit=TPsaved, stop=SLsaved, when=strategy.position_size > 0)strategy.exit(id="Short Exit", from_entry="Short", limit=TPsaved, stop=SLsaved, when=strategy.position_size < 0)//==============================================================================//================================ ALERTS ==================================//==============================================================================if validLong alert(openLongAlertMessage , alert.freq_once_per_bar_close)if validShort alert(openShortAlertMessage , alert.freq_once_per_bar_close)if longSLTPhit alert(closeLongAlertMessage , alert.freq_once_per_bar)if shortSLTPhit alert(closeShortAlertMessage, alert.freq_once_per_bar)//==============================================================================//============================= CHART PLOTS ================================//============================================================================== //---------------------------- Stops & Targets -----------------------------plot(strategy.position_size != 0 or (strategy.position_size[1] != 0 and strategy.position_size == 0) ? SLsaved : na, color=color.red , style=plot.style_linebr)plot(strategy.position_size != 0 or (strategy.position_size[1] != 0 and strategy.position_size == 0) ? TPsaved : na, color=color.green, style=plot.style_linebr) //--------------------------------- EMAs -----------------------------------l1 = plot(ema1, color=ema1col, linewidth=2)l2 = plot(ema2, color=ema2col, linewidth=2)//-------------------------- Stochastic gradient ---------------------------fill(l1, l2, color.new(color.from_gradient(K, OSstochLvl, OBstochLvl, emaBull ? entryColor : emaBear ? baseColor : na, emaBull ? baseColor : emaBear ? entryColor : na), transp)) //---------------------------- Trading Signals -----------------------------plotshape(validLong, color=color.green, location=location.belowbar, style=shape.xcross, size=size.small)plotshape(validShort, color=color.red , location=location.abovebar, style=shape.xcross, size=size.small)//---------------------------- Reference Market ----------------------------bgcolor(bullRefMarket and refMfilter ? color.new(color.green,90) : na)bgcolor(bearRefMarket and refMfilter ? color.new(color.red ,90) : na)