Strategy · Pine Script v4 · On the chart

SMAOffsetProtectOptV1

by viktors1982· code credited to VikSal1982

SMAOffsetProtectOptV1 is a long-only price-chart strategy that buys when close falls below an offset SMA or EMA and either the Elliott Wave Oscillator is above its high threshold with RSI below a limit, or the oscillator is below its low threshold.

View on GitHub

Repaints

GitHub stars36on the repository
Pine versionv4older, still runs
Lines of code96
Settings16inputs
LicenceNone statedfile: MPL-2.0
Last update2 years ago10 Apr 2024

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new strategy, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart. The trades and results appear in the Strategy Tester tab; adjust the settings with the gear icon.

Source Code

96 lines of Pine Script v4 from tradingview/pinescripts/strategies/SMAOffsetProtectOptV1.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

SMAOffsetProtectOptV1.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © VikSal1982
// freqtrade authors: https://discord.gg/MA9v74M  @Perkmeister 's hyperopted version of @LamborghiniAventador 's SMAOffsetProtect strat, heavily based on @tirail 's original SMAOffset
//@version=4

strategy("SMAOffsetProtectOptV1", overlay=true, currency=currency.EUR, default_qty_type=strategy.cash, default_qty_value=150, initial_capital = 33000, calc_on_every_tick=true,commission_type=strategy.commission.percent, commission_value =0.15)



startDate                      = input(title="Start Strat", type=input.time, defval=timestamp("01 Jan 2021 00:00 +0000"), group = "buy" )

base_nb_candles_buy            = input(title="Buy base nb candles", type=input.integer, defval= 16, step =1, minval = 5, maxval = 100, group = "buy") 
low_offset                     = input(title="low_offset", type=input.float,     defval=  0.978, step =0.01, minval = 0.9, maxval = 0.990, group = "buy")
buy_trigger                    = input(title="Buy trigger", type=input.string, defval="EMA", options=["SMA","EMA"], group = "buy")
ewo_low                        = input(title="ewo_low", type=input.float,     defval=  -19.993, step =0.01, minval = -20.0, maxval = -8.00, group = "buy")
ewo_high                       = input(title="ewo_high", type=input.float,     defval=   5.638, step =0.01, minval = 2.0, maxval = 12.00, group = "buy")
fast_ewo                       = input(title="fast_ewo", type=input.integer,     defval=   50, step =1, minval = 10, maxval = 500, group = "buy")
slow_ewo                       = input(title="slow_ewo", type=input.integer,     defval=   200, step =1, minval = 100, maxval = 2000, group = "buy")
rsi_buy                        = input(title="rsi_buy", type=input.integer,     defval=   61, step =1, minval = 30, maxval = 700, group = "buy")


base_nb_candles_sell           = input(title="Sell base nb candles", type=input.integer, defval= 49, step =1, minval = 5, maxval = 100, group = "sell") 
high_offset                    = input(title="High offset", type=input.float,     defval=  1.006, step =0.01, minval = 0.99, maxval = 1.1, group = "sell")
sell_trigger                   = input(title="Sell trigger", type=input.string, defval="EMA", options=["SMA","EMA"], group = "sell")

enableRoi                      = input(title="RIO", type=input.bool, defval=true, group = "roi" )
sell_roi                       = input(title="Sell  roi", type=input.float,     defval= 0.01, step =0.001, minval = 0.01, maxval = 0.2, group = "roi")

enableST                      = input(title="Stoploss", type=input.bool, defval=true, group = "stoploss" )
sell_st                       = input(title="Sell Stoploss", type=input.float,     defval= -0.05, step =0.001, minval = -0.5, maxval = -0.001, group = "stoploss")



ma_type(type, src, len) =>
    float result = 0
    if type=="SMA" // Simple
        result := sma(src, len)
    if type=="EMA" // Exponential
        result := ema(src, len)
    result
        
ma_buy  = ma_type(buy_trigger,  close, base_nb_candles_buy)
ma_sell = ma_type(sell_trigger, close, base_nb_candles_sell)
rsi_14  = rsi(close, 14)


ewo = ((ema(close, fast_ewo) - ema(close, slow_ewo))/close) * 100

long_1 = close < (ma_buy * low_offset) and ewo > ewo_high and rsi_14 < rsi_buy
long_2 = close < (ma_buy * low_offset) and ewo < ewo_low 

sell   = close > (ma_sell * high_offset)


rioProfit =enableRoi? (strategy.position_avg_price * (1 + sell_roi)) : na
plot(rioProfit, color=color.green, style=plot.style_linebr, linewidth=2, title='rioProfit')
//roi_sell = (rioProfit < close)  

sell_stoploss = sell_st? (strategy.position_avg_price * (1 + sell_st)) : na
plot(sell_stoploss, color=color.red, style=plot.style_linebr, linewidth=2, title='sell_stoploss')

m = plot((ma_buy), color=color.blue, linewidth = 1)
ms = plot((ma_sell), color=color.red, linewidth = 1)
ml = plot((ma_buy * low_offset), color=color.blue, linewidth = 2)
msl =plot((ma_sell * high_offset), color=color.red, linewidth = 2)

//plotewo = plot(ewo, color=color.green, linewidth = 3)

fill(m, ml,  color.green)
fill(ms, msl,  color.yellow)


//debug
plotchar(ma_buy, "ma_buy", "", location = location.top)
plotchar(ma_sell, "ma_sell", "", location = location.top)
plotchar(ewo, "ewo", "", location = location.top)
plotchar(rsi_14, "rsi_14", "", location = location.top)

//-----


afterStartDate = (time >= startDate)
longCondition = (long_1 == 1 or long_2 == 1) and afterStartDate  and strategy.position_size <= 0


if (longCondition)
    strategy.entry("Entry", strategy.long, when=(long_1) , comment = 'long_1')
    strategy.entry("Entry", strategy.long, when=(long_2) , comment = 'long_2')

if (strategy.position_size > 0)
    strategy.close(id="Entry", when=(sell) , comment = 'sell')
   // strategy.close(id="Entry", when=(roi_sell) , comment = 'roi_sell')
    // if enableRoi
    strategy.exit(id="Entry", limit=rioProfit, stop  =sell_stoploss, comment = 'rs_sell')
    // if enableST
    //     strategy.exit(id="Entry", stop  =sell_stoploss, comment = 'stoploss_sell')

Overview

SMAOffsetProtectOptV1 exits when close rises above an offset sell average. Optional percentage take-profit and stop-loss settings are on by default. Buy and sell lengths, offsets, moving-average type, and oscillator thresholds are adjustable. It recalculates on every tick, so signals can change on the live bar.

Details

Published by

viktors1982 on GitHub

Code credit

VikSal1982, as written in the script's header

Type

Strategy, Pine Script v4

Draws

On the price chart

Category

Moving averages, Oscillators & momentum

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

  • Signals can change on the live bar or after it closes (repainting)

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Start Strattimetimestamp("01 Jan 2021 00:00 +0000")startDate
Buy base nb candlesint16base_nb_candles_buy
low_offsetfloat0.978low_offset
Buy triggerstringEMAbuy_trigger
ewo_lowfloat-19.993ewo_low
ewo_highfloat5.638ewo_high
fast_ewoint50fast_ewo
slow_ewoint200slow_ewo
rsi_buyint61rsi_buy
Sell base nb candlesint49base_nb_candles_sell
High offsetfloat1.006high_offset
Sell triggerstringEMAsell_trigger
Show all 16 settings
SettingTypeDefaultVariable
RIObooltrueenableRoi
Sell roifloat0.01sell_roi
StoplossbooltrueenableST
Sell Stoplossfloat-0.05sell_st
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

330 stars

2 EMA/SMA + RSI Strategy [Alorse] combines three configurable moving averages with a short-period Relative Strength Index filter. It plots fast, slow, and trend moving averages on the price chart. Long entries trigger when the fast moving average is above the

Strategy v4 TrendOscillators & momentum
Updated 2 months ago · None stated GitHub repository of 2 EMA/SMA + RSI Strategy [Alorse]

Acrypto - Weighted Strategy

by AlbertoCuadra
318 stars

This strategy plots on the price chart and opens long or short positions when a weighted score from MACD, Stochastic RSI, RSI, Supertrend and a moving-average crossover exceeds a user-set trigger. Each component has its own weight and candle delay. Entries can

Strategy v5 TrendOscillators & momentum
Updated 3 years ago · Custom licence GitHub repository of Acrypto - Weighted Strategy

This strategy combines Arnaud Legoux Moving Average percentage price change calculations with an adaptive Gaussian Moving Average to generate trend-following signals. Long and short entries are triggered when the ALMA change calculation crosses above or below

Strategy v5 Moving averagesOscillators & momentum
Updated 6 weeks ago · None stated GitHub repository of ESM2024 - ALMA Smoothed Gaussian Moving Average

MACD Strategy

by TradersPost
218 stars

This overlay strategy is built around MACD inputs for a fast average, a slow average, and a signal line. Comments say the script keeps MACD values available and can draw a histogram and zero line in a separate pane, with an optional overlay on price. Settings

Strategy v6 Oscillators & momentumMoving averages
Updated 3 months ago · None stated GitHub repository of MACD Strategy

255 EMA Strategy

by hasnocool
106 stars

255 EMA Strategy combines an exponential moving average with Average True Range bands and standard MACD crossovers to generate entry signals. Drawn directly on the price chart, it plots the central 255 EMA along with upper and lower volatility envelopes. Trade

Strategy v4 Moving averagesOscillators & momentum
Updated 2 years ago · GPL-3.0 GitHub repository of 255 EMA Strategy
104 stars

This overlay strategy combines a machine-learning distance model with a MACD oscillator to open trades on the price chart. It compares recent history using cosine similarity or Euclidean and Lorentzian distance, then filters direction with selectable moving-av

Strategy v5 AI / machine learningOscillators & momentum
Updated 3 years ago · MIT GitHub repository of MLCEL and MACD Strategy

More strategys

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers