Zeal Terminal Open in Zeal Terminal

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
40,00060,00080,000100,000120,000AprJulOct2025AprJulOct2026AprJulOct$10,367$20,253Equity from $10,000
Binance BTCUSDT 1D candles, 26 Jan 2024 to 21 Oct 2026, 1,000 bars, default settings. Triangles mark entries; circles mark exits. Lines are what the script plots. 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. The live re-run is not offered here: the script requests BINANCE:BTCUSDT 30, which this page cannot load in your browser.

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.

SettingDefaultType and rangeFeeds
Trade Setup
Long TradestrueboolvalidLong
Short TradestrueboolvalidShort
Risk : Reward1.1float · min 0 · max 100 · step 0.1longTP 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)falseboolentry Long entry Short
Risk Prct Equi (no label in the script)1float · min 0 · max 100 · step 0.1entry 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)trueboolentry Long entry Short
Risk USD (no label in the script)200float · min 0 · max 1000000 · step 100entry Long entry Short
Stop Loss
ATR Multiplier3float · min 0 · max 100 · step 0.1SLdist
ATR Lookback14int · min 0 · max 1000 · step 1SLdist
Stochastic
K%14int · min 0 · max 1000 · step 1K
D%2int · min 0 · max 1000 · step 1D
OB80int · min 0 · max 100 · step 1line 62 fill
OS20int · min 0 · max 100 · step 1line 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)0int · min 0 · max 100 · step 1line 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 signalfalseboolline 59 line 65
#00ffffcolorfill
Will trun to designated color when stochastic gets to opposite extrem zone of current trend / Number = transparency#333333colorfill
50int · min 0 · max 100 · step 10fill
Exp. Moving Average
Fast EMA 4int · min 0 · max 1000 · step 1ema1
Slow EMA 40int · min 0 · max 1000 · step 1ema2
#0066ffcolorl1 plot
#0000ffcolorl2 plot
Reference Market
Reference Market FilterfalseboolvalidLong validShort bgcolor
MarketBINANCE:BTCUSDTsymbolemaHTF closeHTF
Timeframe30timeframeemaHTF closeHTF
EMA Length50intema
3Commas Alert Messages
Open Long Alert MessagePaste ''Message for deal start signal'' from long botstringalert
Open Short Alert MessagePaste ''Message for deal start signal'' from short botstringalert
Close Long Alert MessagePaste ''Message to close order at Market Price'' from long botstringalert
Close Short Alert MessagePaste ''Message to close order at Market Price'' from short botstringalert

What it calculates

  • Stochclose, high, low, K% (14)K · line 49
  • SMAK, D% (2)D · line 50
  • CrossoverK, DstochBullCross · line 51
  • CrossoverD, KstochBearCross · 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.

lowlowprice datahighhighprice dataclosecloseprice dataKlenK%setting · 14Dlen D%setting · 2ema1lenFast EMA setting · 4ema2lenSlow EMA setting · 40lenEMA Lengthsetting · 50high · low · closehigh · low · closeprice dataatrLenATR Lookbacksetting · 14atrMultATR Multipliersetting · 3marketMarketsetting · BINANCE:BTCUSDTresTimeframesetting · 30rrRisk : Rewardsetting · 1.1openLongAlertMessageOpen Long Alert Messagesetting · openShortAlertMessageOpen Short Alert Messagesetting · closeLongAlertMessageClose Long Alert Messagesetting · closeShortAlertMessageClose Short Alert Messa…setting · KStoch→ KDSMA→ DstochBullCrossCrossover→ stochBullCrossstochBearCrossCrossover→ stochBearCrossema1EMA→ ema1ema2EMA→ ema2emaEMA→ emaSLdistATR→ SLdistemaHTFemaHTFvaluecloseHTFcloseHTFvaluevalidLongvalidLongvaluevalidShortvalidShortvaluelongSL, shortSLlongSL · shortSL2 valueslongSLDistlongSLDistvaluelongTPlongTPvalueshortSLDistshortSLDistvalueshortTPshortTPvalueSLsavedSLsavedvalueTPsavedTPsavedvalueemaBull, emaBearemaBull · emaBear2 conditionsbullRetraceZone, bearRetraceZonebullRetraceZone · bearR…2 conditionsbullRefMarket, bearRefMarketbullRefMarket · bearRef…2 conditionsentry:LongOpen Longstrategy.entryentry:ShortOpen Shortstrategy.entryexit:Long Exitexit Long Exitstrategy.exitexit:Short Exitexit Short Exitstrategy.exitalert:129alertalertalert:131alertalertalert:133alertalertalert:135alertalertplot:141plotplotplot:142plotplotplot:144plotplotplot:145plotplotfill:147Fillfillplotshape:152plotshapeplotshapeplotshape:153plotshapeplotshapebgcolor:155bgcolorbgcolorbgcolor:156bgcolorbgcolor

Order rules

OrderFires whenBy defaultLine
Open Long longvalidLongOn118
Open Short shortvalidShortOn121
Exit Long Exit stop and limitstrategy.position_size > 0On123
Exit Short Exit stop and limitstrategy.position_size < 0On124

Each order is guarded by the setting shown. “Off” orders never fire unless that setting is switched on.

Alerts

AlertCallMessageLine
(no title)alertopenLongAlertMessage129
(no title)alertopenShortAlertMessage131
(no title)alertcloseLongAlertMessage133
(no title)alertcloseShortAlertMessage135

Does it repaint?

No

No repainting patterns in the source.

Not measuredAn engine gap, not the scriptThe 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. The answer comes from the checks on the source alone.
  • 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 barsTradesWonP&L
Rising market2100%$440.00
Sideways market333%−$180.00
Falling market250%$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.

0%7%
All 7 trades
SideEntryExitBarsP&L
long29 Dec 2024 95,300.0020 Jan 2025 108,641.0022$220.00
short26 Mar 2025 87,392.907 Apr 2025 75,465.6012$220.00
short19 Apr 2025 84,474.7025 Apr 2025 94,789.706−$200.00
short5 Dec 2025 92,078.1031 Jan 2026 79,363.1057$220.00
long18 May 2026 77,457.701 Jun 2026 71,056.3014−$200.00
short8 Jul 2026 63,364.0019 Aug 2026 69,966.9042−$200.00
long12 Sep 2026 77,225.7021 Sep 2026 84,943.509$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.

ScriptSharesTypeNetTradesMax drawdown
Stochastic Moving Average this page—v5 strategy+2.8%74.4%
ATR with EOM and VORTEX by SoftKill21atr ema smav4 strategy+66.2%2229.9%
cATRpillar Strategy by Obi-wanClintobeatr sma emav4 strategy+1.02827e+24%2788,097.2%
Optimized Zhaocaijinbao strategy by fzj20020403sma ema atrv5 strategy+15.6%129.8%
EMA & Supertrend by bhavikmotaema sma atrv4 strategy+2,123.6%13980.9%
Koala System EURUSD 15min by SoftKill21sma ema atrv4 strategyNo 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.

Clean v5

VerifiedDownload the v5 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.

Download the v6 script

⋯// 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

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2Yes 43 msWith a workaround 1,000 bars in 97 msNot measured
PineTSNot testedNot testedNot 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)