Strategy · Pine Script v5 · On the chart

Ruckard Noro TrendRibbon Ladder

by ruckard

This strategy uses Noro TrendRibbon direction to set a long or short bias, then opens a trade when price leaves a high-low corridor built from recent candles.

View on GitHub

GitHub stars13on the repository
Pine versionv5runs as is
Lines of code681
Settings40inputs
LicenceNone statedfile: MPL-2.0
Last update1 year ago2 Mar 2025

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

681 lines of Pine Script v5 from scripts/ruckard_noro_trendribbon/ruckard_noro_trendribbon_b_ladder.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

ruckard_noro_trendribbon_b_ladder.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ruckard

//@version=5

// Current version: v20220202 ( B003 )
// Tradingview Public description - BEGIN
// 
// This strategy uses Noro Trendribbon side change to know if the positions need to be long and short.
// In addition to the former a corridor is defined using high and low prices from latest candles.
// When the price is below that corridor (and we are longing) a long position is open with a certain percentage of the usual corridor.
// When the price is above that corridor (and we are shorting) a short position is open with a certain percentage of the usual corridor.
// This specific strategy also includes Risk Management.
// 
// It was originally tested at 1000SHIBUSDT pair and 30m timeframe.
//
// Before using this documentation it's recommended that you:
// [LIST]
// [*] Use default TradingView strategy script or another script and setup its associated alert manually. Just make the alert pop-up in the screen.
// [*] Create a 'Copy-Trader provider' (or Signal Provider) in Zignaly and send signals to it either thanks to your browser or with some basic programming.
// [/LIST]

// [B]SETTINGS[/B]
// [B]__ SETTINGS - Capital[/B]
// [LIST]
// [*] (CAPITAL) Capital quote invested per order in USDT units {100.0}. This setting is only used when '(ZIG) Provider type' is set to 'Signal Provider'.
// [*] (CAPITAL) Capital percentage invested per order (%) {25.0}. This setting is only used when '(ZIG) Provider type' is set to 'Copy Trader Provider'.
// [/LIST]
// [B]__ SETTINGS - Misc[/B]
// [LIST]
// [*] (ZIG) Enable Alert message {True}: Whether to enable alert message or not.
// [*] (DEBUG) Enable debug on order comments {False}: Whether to show alerts on order comments or not.
// [*] Number of decimal digits for Prices {2}.
// [*] (DECIMAL) Maximum number of decimal for contracts {3}.
// [/LIST]
// [B]__ SETTINGS - Zignaly[/B]
// [LIST]
// [*] (ZIG) Integration type {TradingView only}: [b]Hybrid[/b]: Both TradingView and Zignaly handle take profit, trailing stops and stop losses. Useful if you are scared about TradingView not firing an alert. It might arise problems if TradingView and Zignaly get out of sync. [b]TradingView only[/b]: TradingView sends entry and exit orders to Zignaly so that Zignaly only buys or sells. Zignaly won't handle stop loss or other settings on its own.
// [*] (ZIG) Zignaly Alert Type {WebHook}: 'Email' or 'WebHook'.
// [*] (ZIG) Provider type {Profit Sharing Provider}: 'Profit Sharing Provider', 'Copy Trader Provider', or 'Signal Provider'. 'Copy Trader Provider' or 'Profit Sharing Provider' sends a percentage to manage. 'Signal Provider' sends a quote to manage.
// [*] (ZIG) Exchange {Zignaly}: 'Zignaly', 'Binance' or 'Kucoin'.
// [*] (ZIG) Exchange Type {Futures}: 'Spot' or 'Futures'.
// [*] (ZIG) Leverage {1}. Set it to '1' when '(ZIG) Exchange Type' is set to 'Spot'.
// [/LIST]
// [B]__ SETTINGS - Strategy[/B]
// [LIST]
// [*] (STRAT) Strategy Type: 'Long and Short', 'Long Only' or 'Short Only'.
// [*] (STRAT) Strategy Start Time {2021-01-01 00:00:00}: When to start the strategy if '(STRAT) Strategy Start Time forced?' setting is set to true.
// [*] (STRAT) Strategy Stop Time {2021-12-31 00:00:00}: When to stop the strategy if '(STRAT) Strategy Stop Time forced?' setting is set to true.
// [*] (STRAT) Strategy Start Time forced? {True}: Whether to start the strategy from a given point in time.
// [*] (STRAT) Strategy Stop Time forced? {False}: Whether to stop the strategy after a given point in time.
// [*] (STOPTAKE) Take Profit? {false}: Whether to enable Take Profit.
// [*] (STOPTAKE) Stop Loss? {True}: Whether to enable Stop Loss.
// [*] (TRAILING) Enable Trailing Take Profit (%) {True}: Whether to enable Trailing Take Profit.
// [*] (STOPTAKE) Take Profit % {3.0}: Take profit percentage. This setting is only used when '(STOPTAKE) Take Profit?' setting is set to true.
// [*] (STOPTAKE) Stop Loss % {2.0}: Stop loss percentage. This setting is only used when '(STOPTAKE) Stop Loss?' setting is set to true.
// [*] (TRAILING) Trailing Take Profit Trigger (%) {2.5}: Trailing Stop Trigger Percentage. This setting is only used when '(TRAILING) Enable Trailing Take Profit (%)' setting is set to true.
// [*] (TRAILING) Trailing Take Profit as a percentage of Trailing Take Profit Trigger (%) {25.0}: Trailing Stop Distance Percentage. This setting is only used when '(TRAILING) Enable Trailing Take Profit (%)' setting is set to true.
// [*] (RECENT) Number of minutes to wait to open a new order after the previous one has been opened {6}.
// [/LIST]
// [B]____ SETTINGS - Risk Management [/B]
// [list]
// [*] (RISKM) Risk Management Type: 'Safe', 'Somewhat safe compound' or 'None'. '[b]Safe[/b]': Calculations are always done with the initial capital (1000) in mind. The maximum losses per trade/day/week/month are taken into account. '[b]Somewhat safe compound[/b]': Calculations are done with initial capital (1000) or a higher capital if it increases. The maximum losses per trade/day/week/month are taken into account. '[b]None[/b]': In each order all the current capital is gambled and only the default stop loss per order is taken into account. That means that the maximum losses per trade/day/week/month are not taken into account. [b]Default[/b]: 'Somewhat safe compound'.
// [*] (RISKM) Maximum loss per trade % {1.0}.
// [*] (RISKM) Maximum loss per day % {6.0}.
// [*] (RISKM) Maximum loss per week % {8.0}.
// [*] (RISKM) Maximum loss per month % {10.0}.
// [/list]

// [B]DEFAULT SETTINGS[/B]

// By default this strategy has been setup with these beginner settings:
// [LIST]
// [*] '(ZIG) Integration type' : TradingView only
// [*] '(ZIG) Provider type'    : 'Copy Trader Provider'
// [*] '(ZIG) Exchange'         : 'Binance'
// [*] '(ZIG) Exchange Type'    : 'Spot'
// [*] '(STRAT) Strategy Type'  : 'Long Only'
// [*] '(ZIG) Leverage'         : '1' (Or no leverage)
// [/LIST]
// but you can change those settings if needed.


// [B]FIRST STEP[/B]
// [LIST]
// [*] For both future or spot markets you should make sure to change '(ZIG) Zignaly Alert Type' to match either WebHook or Email. If you have a non paid account in TradingView as in October 2020 you would have to use Email which it's free to use.
// [/LIST]

// [B]RECOMMENDED SETTINGS[/B]
// [B]__ RECOMMENDED SETTINGS - Spot markets[/B]
// [LIST]
// [*] '(ZIG) Exchange Type'   setting should be set to 'Spot'
// [*] '(STRAT) Strategy Type' setting should be set to 'Long Only'
// [*] '(ZIG) Leverage'        setting should be set to '1'
// [/LIST]
// [B]__ RECOMMENDED SETTINGS - Future markets[/B]
// [LIST]
// [*] '(ZIG) Exchange Type'   setting should be set to 'Futures'
// [*] '(STRAT) Strategy Type' setting should be set to 'Long and Short'
// [*] '(ZIG) Leverage'        setting might be changed if desired.
// [/LIST]
// [B]__ RECOMMENDED SETTINGS - Signal Providers[/B]
// [LIST]
// [*] '(ZIG) Provider type'   setting should be set to 'Signal Provider'
// [*] '(CAPITAL) Capital quote invested per order in USDT units' setting might be changed if desired.
// [/LIST]
// [B]__ RECOMMENDED SETTINGS - Copy Trader Providers[/B]
// [LIST]
// [*] '(ZIG) Provider type'   setting should be set to 'Copy Trader Provider'
// [*] '(CAPITAL) Capital percentage invested per order (%)' setting might be changed if desired.
// [*] Strategy Properties setting: 'Initial Capital' might be changed if desired.
// [/LIST]

// [B]INTEGRATION TYPE EXPLANATION[/B]
// [LIST]
// [*] 'Hybrid': Both TradingView and Zignaly handle take profit, trailing stops and stop losses. Useful if you are scared about TradingView not firing an alert. It might arise problems if TradingView and Zignaly get out of sync.
// [*] 'TradingView only': TradingView sends entry and exit orders to Zignaly so that Zignaly only buys or sells. Zignaly won't handle stop loss or other settings on its own.
// [/LIST]

// [B]HOW TO USE THIS STRATEGY[/B]
// [LIST]
// [*] Beginner: Copy and paste the strategy and change it to your needs. Turn off '(DEBUG) Enable debug on order comments' setting.
// [*] Medium: Reuse functions and inputs from this strategy into your own as if it was a library.
// [*] Advanced: Check Strategy Tester. List of trades. Copy and paste the different suggested 'alert_message' variable contents to your script and change them to your needs.
// [*] Expert: You needed a way to pass data from TradingView script to the alert. Now you know it's the 'alert_message' variable. You can find several examples in the source code using the variable. You also have seen 'ALERTS SETUP' explanation below. An additional quick look at 'Strategy Tester', 'List of Trades' and you are ready to go.
// [/LIST]


// [B] ALERTS SETUP[/B]
// This is the important piece of information that allows you to connect TradingView to Zignaly in a semi-automatic manner.
// [B] __ ALERTS SETUP - WebHook[/B]
// [LIST]
// [*] Webhook URL: https : // zignaly . com / api / signals.php?key=MYSECRETKEY
// [*] Message: { {{strategy.order.alert_message}} , "key" : "MYSECRETKEY" }
// [/LIST]
// [B] __ ALERTS SETUP - Email[/B]
// [LIST]
// [*] Setup a new Hotmail account
// [*] Add it as an 'SMS email' in TradingView Profile settings page.
// [*] Confirm your own the email address
// [*] Create a rule in your Hotmail account that 'Redirects' (not forwards) emails to 'signals @ zignaly . email' when (1): 'Subject' includes 'Alert', (2): 'Email body' contains string 'MYZIGNALYREDIRECTTRIGGER' and (3): 'From' contains 'noreply @ tradingview . com'.
// [*] In 'More Actions' check: Send Email-to-SMS
// [*] Message: ||{{strategy.order.alert_message}}||key=MYSECRETKEY||
// MYZIGNALYREDIRECTTRIGGER
// [/LIST]


// '(DEBUG) Enable debug on order comments' is turned on by default so that you can see in the Strategy Tester. List of Trades. The different orders alert_message that would have been sent to your alert. You might want to turn it off it some many letters in the screen is problem.

// [B]STRATEGY ADVICE[/B]
// [LIST]
// [*] If you turn on 'Take Profit' then turn off 'Trailing Take Profit'.
// [/LIST]
//
// [B]ZIGNALY SIDE ADVICE[/B]
// [LIST]
// [*] If you are a 'Signal Provider' make sure that 'Allow reusing the same signalId if there isn't any open position using it?' setting in the profile tab is set to true.
// [*] You can find your 'MYSECRETKEY' in your 'Copy Trader/Signal' provider Edit tab at 'Signal URL'.
// [/LIST]
//
// [B]ADDITIONAL ZIGNALY DOCUMENTATION[/B]
// This beginner's guide is quite basic and meant to be an introduction. Please read additional documentation to learn what you actually can do with Zignaly.
// [LIST]
// [*] docs . zignaly . com / signals / how-to -- How to send signals to Zignaly
// [*] help . zignaly . com / hc/en-us/categories/360002703720-Sending-Signals -- Sending zignals
// [/LIST]
//
// [B]FINAL REMARKS[/B]
// [LIST]
// [*] This strategy tries to match the Pine Script Coding Conventions as best as possible.
// [*] You can check my 'Ruckard TradingLatino' strategy for a more complex strategy that it's also integrated with Zignaly. Unfortunatley it does not use Pine Script Coding Conventions as much.
// [/LIST]

// Tradingview Public description - END

strategy('Ruckard Noro TrendRibbon Ladder B003', shorttitle='B003RNoroTRLadder', overlay=true, max_bars_back=5000, calc_on_order_fills=false, calc_on_every_tick=false, pyramiding=0, initial_capital=1000, slippage=1, commission_type=strategy.commission.percent, commission_value=0.04)

import ruckard/RiskManagementBeta/3 as rm
import ruckard/ZignalyBeta/7 as zig

// INPUTS - BEGIN

// Strategy - Inputs
i_enableZignalyAlert = input(true, '(ZIG) Enable Alert message {True}')

_ZIGHYBRIDINTEGRATION_ = 'Hybrid', _ZIGTVONLYINTEGRATION_ = 'TradingView only'
i_zignalyIntegrationTypePre = input.string(_ZIGHYBRIDINTEGRATION_, '(ZIG) Integration type', options=[_ZIGTVONLYINTEGRATION_, _ZIGHYBRIDINTEGRATION_])
i_zignalyIntegrationType = (i_zignalyIntegrationTypePre == _ZIGHYBRIDINTEGRATION_) ? 'hybrid' : 'nonhybrid'
_ZIGSIGNALPROVIDER_ = 'Signal Provider', _ZIGCOPYTRADERPROVIDER_ = 'Profit Sharing/Copy Trader Provider'
i_zignalyProviderTypePre = input.string(_ZIGCOPYTRADERPROVIDER_, '(ZIG) Provider type', options=[_ZIGSIGNALPROVIDER_, _ZIGCOPYTRADERPROVIDER_])
i_zignalyProviderType = (i_zignalyProviderTypePre == _ZIGCOPYTRADERPROVIDER_) ? 'copytrader' : 'signalprovider'
L_S = 'Long and Short', _L_ = 'Long Only', _S_ = 'Short Only', _REVERSE_ = 'Reverse'
i_strategyType = input.string(L_S, '(STRAT) Strategy Type', options=[L_S, _L_, _S_, _REVERSE_])
i_strategyStartTime = input.time(timestamp('01 Jan 2021'), '(STRAT) Strategy Start Time {2021-01-01 00:00:00}')
i_strategyStopTime = input.time(timestamp('31 Dec 2021'), '(STRAT) Strategy Stop Time {2021-12-31 00:00:00}')
i_strategyStartTimeOn = input.bool(true, '(STRAT) Strategy Start Time forced? {True}')
i_strategyStopTimeOn = input.bool(false, '(STRAT) Strategy Stop Time forced? {False}')
i_maType = input.string(defval = 'SMA', options = ['SMA', 'EMA', 'VWMA', 'RMA'], title = '(STRAT) MA Type [SMA]')
i_maLength = input.int(20, minval = 5,  title = '(STRAT) MA Length (min. 5) [20]')
i_maSource = input.source(ohlc4, title = '(STRAT) MA Source [ohlc4]')
i_signalSource = input.source(ohlc4, title = '(STRAT) Signal Source [ohcl4]')
i_minimumLongDistancePercentage = input.float(0.90, title='(STRAT) Minimum High Low Distance % {0.90}')
i_minimumDistanceProfitPercentage = input.float(55.0, title='(STRAT) Minimum Distance Profit % {55.0}')
i_StopLossDistancePercentage = input.float(110.0, title='(STRAT) Stop Loss Distance % {110.0}')
i_HalfCandleEMA = input.int(3, '(STRAT) High Low Range EMA {3}', minval=1, step=1, maxval=125)
i_showRibbon = input.bool(true, title = 'Show ribbon [true]')
i_showBackground = input.bool(true, title = 'Show color [true]')
// Order comments based debug
i_enableOrderCommentDebug = input.bool(false, title='(DEBUG) Enable debug on order comments {False}')
i_enableTakeProfit = input.bool(true, '(STOPTAKE) (Dynamic) Take Profit? {true}')
i_enableStopLoss = input.bool(true, '(STOPTAKE) (Dynamic) Stop Loss? {true}')
i_enableTrailingTakeProfit = input.bool(false, title='(TRAILING) Enable Trailing Take Profit (%) {False}')
i_takeProfitDisabled = input.float(1.1, title='(STOPTAKE) Take Profit % {3.0}')
i_takeProfitPerOneDisabled = i_takeProfitDisabled / 100
i_stopLossDisabled = input.float(7.0, title='(STOPTAKE) Stop Loss % {7.0}', minval=0.01) / 100
// Trailing Take Profit - Inputs
i_trailingTakeProfitPercentageTrigger = input.float(1.2, '(TRAILING) Trailing Take Profit Trigger (%) {2.5}', minval=0, step=0.01)
i_trailingTakeProfitPercentageTriggerPerOne = i_trailingTakeProfitPercentageTrigger * 0.01
i_trailingTakeProfitPercentageOffset = input.float(25.0, '(TRAILING) Trailing Take Profit as a percentage of Trailing Take Profit Trigger (%) {25.0}', minval=0, step=0.01)
i_trailingTakeProfitPercentageOffsetPerOne = i_trailingTakeProfitPercentageOffset * 0.01
// Zignaly - Email (zignalye)
_ZIGNALYE_ = 'Email', _ZIGNALYW_ = 'WebHook'
i_zignalyAlertTypePre = input.string(_ZIGNALYW_, '(ZIG) Zignaly Alert Type {WebHook}', options=[_ZIGNALYW_, _ZIGNALYE_])
i_zignalyAlertType = (i_zignalyAlertTypePre == _ZIGNALYW_) ? 'webhook' : 'email'
_ZIGEXZIGNALY_ = 'Zignaly', _ZIGEXBINANCE_ = 'Binance', _ZIGEXKUCOIN_ = 'Kucoin'
i_zignalyExchange = input.string(_ZIGEXZIGNALY_, '(ZIG) Exchange {Zignaly}', options=[_ZIGEXZIGNALY_, _ZIGEXBINANCE_, _ZIGEXKUCOIN_])
_ZIGEXTYPESPOT_ = 'spot', _ZIGEXFUTURES_ = 'futures'
i_zignalyExchangeType = input.string(_ZIGEXFUTURES_, '(ZIG) Exchange Type {Futures}', options=[_ZIGEXFUTURES_, _ZIGEXTYPESPOT_])
i_zignalyLeverage = input.int(1, '(ZIG) Leverage {1}', minval=1, step=1, maxval=125)
var i_zignalyLeverage_str = str.tostring(i_zignalyLeverage)  // It needs to run only once
i_priceDecimalDigits = input.int(2, 'Number of decimal digits for Prices {2}', minval=0, maxval=10, step=1)
// Decimal - Inputs
i_contractMaximumDecimalNumber = input.int(3, title='(DECIMAL) Maximum number of decimal for contracts {3}', minval=0)
i_tooRecentMinutesNumber = input.int(6, '(RECENT) Number of minutes to wait to open a new order after the previous one has been opened {0}', minval=0, maxval=100, step=1)
i_CapitalQuote = input.float(100.0, title='(CAPITAL) Capital quote invested per order in USDT units {100.0}')
i_CapitalPercentage = input.float(25.0, title='(CAPITAL) Capital percentage invested per order (%) {25.0}', minval=0, step=0.01) * 0.01
// Risk Management - Inputs
_SAFE_ = 'Safe', _SCOMPOUND_ = 'Somewhat safe compound', _NONE_ = 'None'
i_riskManagementTypePre = input.string(_NONE_, '(RISKM) Risk Management Type', options=[_SAFE_, _SCOMPOUND_, _NONE_])
i_riskManagementType = (i_riskManagementTypePre == _SAFE_) ? 'SAFE' : (i_riskManagementTypePre == _SCOMPOUND_) ? 'SCOMPOUND' : 'NONE'
i_riskManagementMaximumLossPerTrade = input.float(1.0, title='(RISKM) Maximum loss per trade % {1.0}') / 100
i_riskManagementMaximumLossPerDay = input.float(6.0, title='(RISKM) Maximum loss per day % {6.0}') / 100
i_riskManagementMaximumLossPerWeek = input.float(8.0, title='(RISKM) Maximum loss per week % {8.0}') / 100
i_riskManagementMaximumLossPerMonth = input.float(10.0, title='(RISKM) Maximum loss per month % {10.0}') / 100

// INPUTS - END



// Strategy - INIT - BEGIN

onStartTimeInterval = (not i_strategyStartTimeOn) or (time >= i_strategyStartTime)
offStopTimeInterval = (i_strategyStopTimeOn) and (time > i_strategyStopTime)

// order Stop Loss
float orderStopLossPerOne = na
float orderStopLoss = orderStopLossPerOne

// Dynamic Trailing Take Profit - Variables

var int buyOrderOpenBarIndex = na
var int sellOrderOpenBarIndex = na

// Handle to avoid two long and short orders being too next to each other
var bool _oldInsideABuyOrder = false
var bool oldInsideASellOrder = false
var bool insideABuyOrder = false
var bool insideASellOrder = false

_oldInsideABuyOrder := insideABuyOrder
oldInsideASellOrder := insideASellOrder

var int lastOrderOpenBarTime = na

// Handle recalculate after Stop Loss / Take Profit order
if (strategy.position_size == 0.0)
    insideABuyOrder := false
    insideASellOrder := false
else
    lastOrderOpenBarTime := time_close

// Zignaly
exchangeTickerID = syminfo.ticker

var string tmpOrderComment = na
var string tmpOrderAlertMessage = na

var int i_tooRecentMinutesNumber_ms = i_tooRecentMinutesNumber * 60 * 1000 // Convert minutes into milliseconds only once

// Strategy - INIT - END

// FUNCTIONS - BEGIN

// Decimals - Functions
f_getContractMultiplier(_contractMaximumDecimalNumber) =>
    _contractMultiplier = 1
    if (_contractMaximumDecimalNumber == 0)
        _contractMultiplier // Return 1
    else
        for _counter = 1 to _contractMaximumDecimalNumber
            _contractMultiplier:= _contractMultiplier * 10
        _contractMultiplier

// Order comment - Functions - BEGIN

f_getOrderComment(_typeOrder, _side, _alertMessage) =>
    // Dependencies: i_enableOrderCommentDebug (initialized in inputs).

    // TODO: Add descriptive comments
    // _typeOrder="entry" or _typeOrder="close"
    // _side: true means long ; false means short ; We can use strategy.long or strategy.short as true and false aliases
    // _alertMessage
    var string _orderComment = ""
    
    if (i_enableOrderCommentDebug)
        _orderComment := _alertMessage
    else
        // TODO: Use human explanations instead of default order comment value (na)
        _orderComment := na
        
    _orderComment

// Order comment - Functions - END

// Too recent orders functions

f_getTooRecentOrderNotOpenAdvice () =>
    // Dependencies: i_tooRecentMinutesNumber_ms
    // Dependencies: lastOrderOpenBarTime

    // Condition 1: The order was open
    // Condition 2: The order was long or short
    // Condition 3: Time since order was last open is smaller than minimum between orders
    // Returns boolean
    bool _isTooRecent =  ((time_close) <= (lastOrderOpenBarTime + i_tooRecentMinutesNumber_ms))

    bool _tooRecentOrderBuyNotOpenAdvice = na
    if (na(lastOrderOpenBarTime))
        _tooRecentOrderBuyNotOpenAdvice := false
    else
        _tooRecentOrderBuyNotOpenAdvice := _isTooRecent
    _tooRecentOrderBuyNotOpenAdvice

// FUNCTIONS - END


// Strategy Body - BEGIN


// Simple Logic to go LONG/LONG or go SHORT/SHORT - BEGIN

// Low band and High band calculation - BEGIN
HighCandle = high
HighOpenCloseCandle = math.max(close, open)
float HighHalfCandle = ( HighCandle + HighOpenCloseCandle ) / 2.0
HighHalfCandleEMA = ta.ema(HighHalfCandle, i_HalfCandleEMA)

LowCandle = low
LowOpenCloseCandle = math.min(close, open)
float LowHalfCandle = ( LowCandle + LowOpenCloseCandle ) / 2.0
LowHalfCandleEMA = ta.ema(LowHalfCandle, i_HalfCandleEMA)

LongDistancePercentage = ( HighHalfCandleEMA/LowHalfCandleEMA - 1 ) * 100

// Low band and High band calculation - END

ma = i_maType == "SMA" ? ta.sma(i_maSource, i_maLength) : i_maType == "EMA" ? ta.ema(i_maSource, i_maLength) : i_maType == "VWMA" ? ta.vwma(i_maSource, i_maLength) : ta.rma(i_maSource, i_maLength)
//Price Channel
highestMA = ta.highest(ma, i_maLength)
lowestMA = ta.lowest(ma, i_maLength)

//Trend
trend = 0
trend := i_signalSource > highestMA[1] ? 1 : i_signalSource < lowestMA[1] ? -1 : trend[1]

//Trading
longCondition = (trend == 1)
shortCondition = (trend == -1)
// Simple Logic to go LONG/LONG or go SHORT/SHORT - END

MAColor = i_showRibbon ? color.black : na
MAPlot = plot(ma, color = MAColor, title = "MA")
highestLowestColor = i_showRibbon ? color.blue : na
highestMAPlot = plot(highestMA, color = highestLowestColor, title = "Upper line")
lowestMAPlot = plot(lowestMA, color = highestLowestColor, title = "Lower Line")
highestMABackgroundColor = i_showBackground ? color.red : na
lowestMABackgroundColor = i_showBackground ? color.blue : na
fill(highestMAPlot, MAPlot, color = color.new(highestMABackgroundColor, 50))
fill(lowestMAPlot, MAPlot, color = color.new(lowestMABackgroundColor, 50))

// Position price calculation - BEGIN
float positionPrice = na
if (insideASellOrder or insideABuyOrder)
    positionPrice := strategy.position_avg_price
else
    positionPrice := close
    
// Position price calculation - END

tooRecentOrderNotOpenAdvice = f_getTooRecentOrderNotOpenAdvice ()

// Decide if we are going to LONG/Go LONG - BEGIN
PRE_LONG = false
ladderLong = false
if ( (LongDistancePercentage > i_minimumLongDistancePercentage) and (close < LowHalfCandleEMA) )
    ladderLong := true
ladderShort = false
if ( (LongDistancePercentage > i_minimumLongDistancePercentage) and (close > HighHalfCandleEMA) )
    ladderShort := true
i_takeProfit = ((i_minimumDistanceProfitPercentage / 100.0) * i_minimumLongDistancePercentage)
i_takeProfitPerOne = i_takeProfit / 100
i_stopLoss = ((i_StopLossDistancePercentage / 100.0) * i_minimumLongDistancePercentage) * 0.01

if (i_tooRecentMinutesNumber == 0)
    PRE_LONG := onStartTimeInterval and longCondition and ladderLong
else
    PRE_LONG := onStartTimeInterval and longCondition and (not tooRecentOrderNotOpenAdvice) and ladderLong

// LONG = PRE_LONG[1] and PRE_LONG // Wait for confirmation
LONG = PRE_LONG // Do not wait for confirmation

// Decide if we are going to LONG/Go LONG - END

// Decide if we are going to SHORT/Go SHORT - BEGIN
PRE_SHORT = false
if (i_tooRecentMinutesNumber == 0)
    PRE_SHORT := onStartTimeInterval and shortCondition and ladderShort
else
    PRE_SHORT := onStartTimeInterval and shortCondition and (not tooRecentOrderNotOpenAdvice) and ladderShort

// SHORT = PRE_SHORT[1] and PRE_SHORT // Wait for confirmation
SHORT = PRE_SHORT // Do not wait for confirmation

// Decide if we are going to SHORT/Go SHORT - END

// Decide if a LONG/LONG entry should be closed - BEGIN
LONG_CLOSE = true
LONG_CLOSE := offStopTimeInterval or (not (longCondition)) or shortCondition

// Let's make sure LONG does not trigger if LONG_CLOSE would tell us to close the LONG
if LONG_CLOSE
    LONG := false
// Decide if a LONG/LONG entry should be closed - END

// Decide if a SHORT/SHORT entry should be closed - BEGIN
SHORT_CLOSE = true
SHORT_CLOSE := offStopTimeInterval or (not (shortCondition)) or longCondition

// Let's make sure SHORT does not trigger if SHORT_CLOSE would tell us to close the SHORT
if SHORT_CLOSE
    SHORT := false
// Decide if a SHORT/SHORT entry should be closed - END

// orderStopLoss is just here just in case
// we implement i_longStopLoss and i_shortStopLoss
// in the future
if LONG
    orderStopLossPerOne := i_stopLoss
    orderStopLoss := orderStopLossPerOne * 100
else
    orderStopLossPerOne := i_stopLoss
    orderStopLoss := orderStopLossPerOne * 100


// How much to LONG/GO LONG/SHORT/GO SHORT - BEGIN

// Custom take profit and stop loss
LongTakeProfit = positionPrice * (1 + i_takeProfitPerOne)
ShortTakeProfit = positionPrice * (1 - i_takeProfitPerOne)

float LongStopLoss = na
float ShortStopLoss = na

LongStopLoss := positionPrice * (1 - orderStopLossPerOne)
ShortStopLoss := positionPrice * (1 + orderStopLossPerOne)

float entryQuantity = na
float currentCapital = strategy.initial_capital + strategy.netprofit

if (i_zignalyProviderType == 'copytrader')
    entryQuantity := i_CapitalPercentage * currentCapital
else // _ZIGSIGNALPROVIDER_
    entryQuantity := i_CapitalQuote

if (i_zignalyProviderType == 'copytrader') // Risk management is only implemented for CopyTrader Providers
    var currentDayCapital = 0.0
    var currentDay = 0
    var currentWeekCapital = 0.0
    var currentWeek = 0
    var currentMonthCapital = 0.0
    var currentMonth = 0

    currentDay := rm.getCurrentDay ()
    currentWeek := rm.getCurrentWeek ()
    currentMonth := rm.getCurrentMonth ()

    [__entryQuantity, __currentDay, __currentDayCapital, __currentWeek, __currentWeekCapital, __currentMonth, __currentMonthCapital] = rm.advisedEntryQuantity (currentCapital, currentDay, currentDayCapital, currentWeek, currentWeekCapital, currentMonth, currentMonthCapital, i_riskManagementMaximumLossPerDay, i_riskManagementMaximumLossPerWeek, i_riskManagementMaximumLossPerMonth, i_riskManagementMaximumLossPerTrade, orderStopLossPerOne, i_riskManagementType)

    entryQuantity := __entryQuantity
    currentDayCapital := __currentDayCapital
    currentWeekCapital := __currentWeekCapital
    currentMonthCapital := __currentMonthCapital

float entryQuantityContractsReducer = 0.99

contractMultiplier = f_getContractMultiplier(i_contractMaximumDecimalNumber)

// We assume the current price is current bar close

entryQuantityContracts = (math.floor(((entryQuantity / close) * entryQuantityContractsReducer) * contractMultiplier) / contractMultiplier)
entryQuantityContractsUSDT = entryQuantityContracts * (close)

// How much to LONG/GO LONG/SHORT/GO SHORT - END


// GO LONG only logic - BEGIN

var float tmpPositionBeforeOpeningOrder = na

if (i_strategyType == _L_)
    if LONG
        tmpPositionBeforeOpeningOrder := strategy.position_avg_price
        tmpOrderAlertMessage := zig.longEntry(positionSizeQuote=entryQuantityContractsUSDT, currentCapital=currentCapital, alertType=i_zignalyAlertType, stopLoss=i_enableStopLoss, takeProfit=i_enableTakeProfit, takeProfitPercentage1=i_takeProfit, trailingStopLoss=i_enableTrailingTakeProfit, trailingStopTriggerPercentage=i_trailingTakeProfitPercentageTrigger, trailingStopDistancePercentage=i_trailingTakeProfitPercentageOffset, integration=i_zignalyIntegrationType, priceDecimalDigits=i_priceDecimalDigits, exchange=i_zignalyExchange, exchangeAccountType=i_zignalyExchangeType, pair=exchangeTickerID, leverage=i_zignalyLeverage, providerType=i_zignalyProviderType, stopLossPercentage=orderStopLoss)
        tmpOrderComment := f_getOrderComment("entry", strategy.long, tmpOrderAlertMessage)
        strategy.entry("[L]", strategy.long, qty=entryQuantityContracts, alert_message=i_enableZignalyAlert ? tmpOrderAlertMessage : na, comment=tmpOrderComment)
        if (na(tmpPositionBeforeOpeningOrder)) // bar_index should only be saved when there is no order opened
            buyOrderOpenBarIndex := bar_index + 1
        insideABuyOrder := true
        0 // Workaround for making every if branch to return the same type of value
    else if LONG_CLOSE
        tmpOrderComment := f_getOrderComment("close", strategy.long, zig.longExit(exchange=i_zignalyExchange,exchangeAccountType=i_zignalyExchangeType,pair=exchangeTickerID,leverage=i_zignalyLeverage,alertType=i_zignalyAlertType))
        strategy.close("[L]", alert_message=i_enableZignalyAlert ? zig.longExit(exchange=i_zignalyExchange,exchangeAccountType=i_zignalyExchangeType,pair=exchangeTickerID,leverage=i_zignalyLeverage,alertType=i_zignalyAlertType) : na, comment=tmpOrderComment)
        insideABuyOrder := false
        0 // Workaround for making every if branch to return the same type of value
// GO LONG only logic - END

// GO SHORT only logic - BEGIN
if (i_strategyType == _S_)
    if SHORT
        tmpPositionBeforeOpeningOrder := strategy.position_avg_price
        tmpOrderAlertMessage := zig.shortEntry(positionSizeQuote=entryQuantityContractsUSDT, currentCapital=currentCapital, alertType=i_zignalyAlertType, stopLoss=i_enableStopLoss, takeProfit=i_enableTakeProfit, takeProfitPercentage1=i_takeProfit, trailingStopLoss=i_enableTrailingTakeProfit, trailingStopTriggerPercentage=i_trailingTakeProfitPercentageTrigger, trailingStopDistancePercentage=i_trailingTakeProfitPercentageOffset, integration=i_zignalyIntegrationType, priceDecimalDigits=i_priceDecimalDigits, exchange=i_zignalyExchange, exchangeAccountType=i_zignalyExchangeType, pair=exchangeTickerID, leverage=i_zignalyLeverage, providerType=i_zignalyProviderType, stopLossPercentage=orderStopLoss)
        tmpOrderComment := f_getOrderComment("entry", strategy.short, tmpOrderAlertMessage)
        strategy.entry("[S]", strategy.short, qty=entryQuantityContracts, alert_message=i_enableZignalyAlert ? tmpOrderAlertMessage : na, comment=tmpOrderComment)
        if (na(tmpPositionBeforeOpeningOrder)) // bar_index should only be saved when there is no order opened
            sellOrderOpenBarIndex := bar_index + 1
        insideASellOrder := true
        0 // Workaround for making every if branch to return the same type of value
    else if SHORT_CLOSE
        tmpOrderComment := f_getOrderComment("close", strategy.short, zig.shortExit(exchange=i_zignalyExchange,exchangeAccountType=i_zignalyExchangeType,pair=exchangeTickerID,leverage=i_zignalyLeverage,alertType=i_zignalyAlertType))
        strategy.close("[S]", alert_message=i_enableZignalyAlert ? zig.shortExit(exchange=i_zignalyExchange,exchangeAccountType=i_zignalyExchangeType,pair=exchangeTickerID,leverage=i_zignalyLeverage,alertType=i_zignalyAlertType) : na, comment=tmpOrderComment)
        insideASellOrder := false
        0 // Workaround for making every if branch to return the same type of value
// GO SHORT only logic - END

// GO LONG and SHORT logic - BEGIN
if (i_strategyType == L_S)
// Asumption: Above we have:
// if LONG_CLOSE
//    LONG := false
// if SHORT_CLOSE
//    SHORT := false

    // LONG and SHORT cannot be true at the same time
    // Anyways we will take it into account
    if (LONG == true) and (SHORT == true)
        LONG := true
        SHORT := false
        SHORT_CLOSE := true

    if LONG
        tmpPositionBeforeOpeningOrder := strategy.position_avg_price
        tmpOrderAlertMessage := zig.longEntry(positionSizeQuote=entryQuantityContractsUSDT, currentCapital=currentCapital, alertType=i_zignalyAlertType, stopLoss=i_enableStopLoss, takeProfit=i_enableTakeProfit, takeProfitPercentage1=i_takeProfit, trailingStopLoss=i_enableTrailingTakeProfit, trailingStopTriggerPercentage=i_trailingTakeProfitPercentageTrigger, trailingStopDistancePercentage=i_trailingTakeProfitPercentageOffset, integration=i_zignalyIntegrationType, priceDecimalDigits=i_priceDecimalDigits, exchange=i_zignalyExchange, exchangeAccountType=i_zignalyExchangeType, pair=exchangeTickerID, leverage=i_zignalyLeverage, providerType=i_zignalyProviderType, stopLossPercentage=orderStopLoss)
        tmpOrderComment := f_getOrderComment("entry", strategy.long, tmpOrderAlertMessage)
        strategy.entry("[L]", strategy.long, qty=entryQuantityContracts, alert_message=i_enableZignalyAlert ? tmpOrderAlertMessage : na, comment=tmpOrderComment)
        if (na(tmpPositionBeforeOpeningOrder)) // bar_index should only be saved when there is no order opened
            buyOrderOpenBarIndex := bar_index + 1
        insideABuyOrder := true
    if LONG_CLOSE
        tmpOrderComment := f_getOrderComment("close", strategy.long, zig.longExit(exchange=i_zignalyExchange,exchangeAccountType=i_zignalyExchangeType,pair=exchangeTickerID,leverage=i_zignalyLeverage,alertType=i_zignalyAlertType))
        strategy.close("[L]", alert_message=i_enableZignalyAlert ? zig.longExit(exchange=i_zignalyExchange,exchangeAccountType=i_zignalyExchangeType,pair=exchangeTickerID,leverage=i_zignalyLeverage,alertType=i_zignalyAlertType) : na, comment=tmpOrderComment)
        insideABuyOrder := false
    if SHORT
        tmpPositionBeforeOpeningOrder := strategy.position_avg_price
        tmpOrderAlertMessage := zig.shortEntry(positionSizeQuote=entryQuantityContractsUSDT, currentCapital=currentCapital, alertType=i_zignalyAlertType, stopLoss=i_enableStopLoss, takeProfit=i_enableTakeProfit, takeProfitPercentage1=i_takeProfit, trailingStopLoss=i_enableTrailingTakeProfit, trailingStopTriggerPercentage=i_trailingTakeProfitPercentageTrigger, trailingStopDistancePercentage=i_trailingTakeProfitPercentageOffset, integration=i_zignalyIntegrationType, priceDecimalDigits=i_priceDecimalDigits, exchange=i_zignalyExchange, exchangeAccountType=i_zignalyExchangeType, pair=exchangeTickerID, leverage=i_zignalyLeverage, providerType=i_zignalyProviderType, stopLossPercentage=orderStopLoss)
        tmpOrderComment := f_getOrderComment("entry", strategy.short, tmpOrderAlertMessage)
        strategy.entry("[S]", strategy.short, qty=entryQuantityContracts, alert_message=i_enableZignalyAlert ? tmpOrderAlertMessage : na, comment=tmpOrderComment)
        if (na(tmpPositionBeforeOpeningOrder)) // bar_index should only be saved when there is no order opened
            sellOrderOpenBarIndex := bar_index + 1
        insideASellOrder := true
    if SHORT_CLOSE
        tmpOrderComment := f_getOrderComment("close", strategy.short, zig.shortExit(exchange=i_zignalyExchange,exchangeAccountType=i_zignalyExchangeType,pair=exchangeTickerID,leverage=i_zignalyLeverage,alertType=i_zignalyAlertType))
        strategy.close("[S]", alert_message=i_enableZignalyAlert ? zig.shortExit(exchange=i_zignalyExchange,exchangeAccountType=i_zignalyExchangeType,pair=exchangeTickerID,leverage=i_zignalyLeverage,alertType=i_zignalyAlertType) : na, comment=tmpOrderComment)
        insideASellOrder := false
// GO LONG and SHORT logic - END

// Reverse logic - BEGIN
if (i_strategyType == _REVERSE_)
// Asumption: Above we have:
// if LONG_CLOSE
//    LONG := false
// if SHORT_CLOSE
//    SHORT := false

    // LONG and SHORT cannot be true at the same time
    // Anyways we will take it into account
    if (LONG == true) and (SHORT == true)
        LONG := true
        SHORT := false
    LONG_CLOSE := offStopTimeInterval
    SHORT_CLOSE := offStopTimeInterval

    if (LONG and (not LONG_CLOSE))
        tmpPositionBeforeOpeningOrder := strategy.position_avg_price
        tmpOrderAlertMessage := zig.reverseLongEntry(positionSizeQuote=entryQuantityContractsUSDT, currentCapital=currentCapital, alertType=i_zignalyAlertType, stopLoss=i_enableStopLoss, takeProfit=i_enableTakeProfit, takeProfitPercentage1=i_takeProfit, trailingStopLoss=i_enableTrailingTakeProfit, trailingStopTriggerPercentage=i_trailingTakeProfitPercentageTrigger, trailingStopDistancePercentage=i_trailingTakeProfitPercentageOffset, integration=i_zignalyIntegrationType, priceDecimalDigits=i_priceDecimalDigits, exchange=i_zignalyExchange, exchangeAccountType=i_zignalyExchangeType, pair=exchangeTickerID, leverage=i_zignalyLeverage, providerType=i_zignalyProviderType, stopLossPercentage=orderStopLoss)
        tmpOrderComment := f_getOrderComment("entry", strategy.long, tmpOrderAlertMessage)
        strategy.entry("[L]", strategy.long, qty=entryQuantityContracts, alert_message=i_enableZignalyAlert ? tmpOrderAlertMessage : na, comment=tmpOrderComment)
        if (na(tmpPositionBeforeOpeningOrder)) // bar_index should only be saved when there is no order opened
            buyOrderOpenBarIndex := bar_index + 1
        insideABuyOrder := true
    if LONG_CLOSE
        tmpOrderComment := f_getOrderComment("close", strategy.long, zig.longExit(exchange=i_zignalyExchange,exchangeAccountType=i_zignalyExchangeType,pair=exchangeTickerID,leverage=i_zignalyLeverage,alertType=i_zignalyAlertType))
        strategy.close("[L]", alert_message=i_enableZignalyAlert ? zig.longExit(exchange=i_zignalyExchange,exchangeAccountType=i_zignalyExchangeType,pair=exchangeTickerID,leverage=i_zignalyLeverage,alertType=i_zignalyAlertType) : na, comment=tmpOrderComment)
        insideABuyOrder := false
    if (SHORT and (not SHORT_CLOSE))
        tmpPositionBeforeOpeningOrder := strategy.position_avg_price
        tmpOrderAlertMessage := zig.reverseShortEntry(positionSizeQuote=entryQuantityContractsUSDT, currentCapital=currentCapital, alertType=i_zignalyAlertType, stopLoss=i_enableStopLoss, takeProfit=i_enableTakeProfit, takeProfitPercentage1=i_takeProfit, trailingStopLoss=i_enableTrailingTakeProfit, trailingStopTriggerPercentage=i_trailingTakeProfitPercentageTrigger, trailingStopDistancePercentage=i_trailingTakeProfitPercentageOffset, integration=i_zignalyIntegrationType, priceDecimalDigits=i_priceDecimalDigits, exchange=i_zignalyExchange, exchangeAccountType=i_zignalyExchangeType, pair=exchangeTickerID, leverage=i_zignalyLeverage, providerType=i_zignalyProviderType, stopLossPercentage=orderStopLoss)
        tmpOrderComment := f_getOrderComment("entry", strategy.short, tmpOrderAlertMessage)
        strategy.entry("[S]", strategy.short, qty=entryQuantityContracts, alert_message=i_enableZignalyAlert ? tmpOrderAlertMessage : na, comment=tmpOrderComment)
        if (na(tmpPositionBeforeOpeningOrder)) // bar_index should only be saved when there is no order opened
            sellOrderOpenBarIndex := bar_index + 1
        insideASellOrder := true
    if SHORT_CLOSE
        tmpOrderComment := f_getOrderComment("close", strategy.short, zig.shortExit(exchange=i_zignalyExchange,exchangeAccountType=i_zignalyExchangeType,pair=exchangeTickerID,leverage=i_zignalyLeverage,alertType=i_zignalyAlertType))
        strategy.close("[S]", alert_message=i_enableZignalyAlert ? zig.shortExit(exchange=i_zignalyExchange,exchangeAccountType=i_zignalyExchangeType,pair=exchangeTickerID,leverage=i_zignalyLeverage,alertType=i_zignalyAlertType) : na, comment=tmpOrderComment)
        insideASellOrder := false
// Reverse logic - END

// Handle STOP LOSS (and similar) order exits - BEGIN

// Quick Paste - BEGIN
float longTrailingTakeProfitPrice = na
float longTrailingTakeProfitPoints = na
float longTrailingTakeProfitOffset = na
float shortTrailingTakeProfitPrice = na
float shortTrailingTakeProfitPoints = na
float shortTrailingTakeProfitOffset = na

// Calculate trailing_take_profit_offset based on tick units
longTmpTtpBaseValue = positionPrice * (1 + i_trailingTakeProfitPercentageTriggerPerOne)
longTmpTtpTop_value = longTmpTtpBaseValue * (1 + i_trailingTakeProfitPercentageOffsetPerOne)
longTrailingTakeProfitOffsetFloat = longTmpTtpTop_value - longTmpTtpBaseValue
float longTrailingTakeProfitOffsetTick = math.floor (longTrailingTakeProfitOffsetFloat / syminfo.mintick)

shortTmpTtpBaseValue = positionPrice * (1 - i_trailingTakeProfitPercentageTriggerPerOne)
shortTmpTtpBottomValue = shortTmpTtpBaseValue * (1 - i_trailingTakeProfitPercentageOffsetPerOne)
shortTrailingTakeProfitOffsetFloat = shortTmpTtpBaseValue - shortTmpTtpBottomValue
float shortTrailingTakeProfitOffsetTick = math.floor (shortTrailingTakeProfitOffsetFloat / syminfo.mintick)

if i_enableTrailingTakeProfit
    longTrailingTakeProfitPrice := positionPrice * (1 + i_trailingTakeProfitPercentageTriggerPerOne)
    longTrailingTakeProfitOffset := longTrailingTakeProfitOffsetTick
    shortTrailingTakeProfitPrice := positionPrice * (1 - i_trailingTakeProfitPercentageTriggerPerOne)
    shortTrailingTakeProfitOffset := shortTrailingTakeProfitOffsetTick
else
    longTrailingTakeProfitPrice := na
    longTrailingTakeProfitOffset := na
    shortTrailingTakeProfitPrice := na
    shortTrailingTakeProfitOffset := na
// Quick Paste - END

// This might trigger additional close orders than needed in zignaly
// Better close an existing order twice than regreting zignaly not having closed it.

tmpOrderComment := f_getOrderComment("close", strategy.long, zig.longExit(exchange=i_zignalyExchange,exchangeAccountType=i_zignalyExchangeType,pair=exchangeTickerID,leverage=i_zignalyLeverage,alertType=i_zignalyAlertType))
strategy.exit("[SL/TP]", "[L]", stop= i_enableStopLoss ? LongStopLoss : na, limit= i_enableTakeProfit ? LongTakeProfit : na, trail_price= i_enableTrailingTakeProfit ? longTrailingTakeProfitPrice : na, trail_offset = i_enableTrailingTakeProfit ? longTrailingTakeProfitOffset : na, alert_message= i_enableZignalyAlert ? zig.longExit(exchange=i_zignalyExchange,exchangeAccountType=i_zignalyExchangeType,pair=exchangeTickerID,leverage=i_zignalyLeverage,alertType=i_zignalyAlertType) : na, comment=tmpOrderComment)
tmpOrderComment := f_getOrderComment("close", strategy.short, zig.shortExit(exchange=i_zignalyExchange,exchangeAccountType=i_zignalyExchangeType,pair=exchangeTickerID,leverage=i_zignalyLeverage,alertType=i_zignalyAlertType))
strategy.exit("[SL/TP]", "[S]", stop= i_enableStopLoss ? ShortStopLoss : na, limit= i_enableTakeProfit ? ShortTakeProfit : na, trail_price= i_enableTrailingTakeProfit ? shortTrailingTakeProfitPrice : na, trail_offset = i_enableTrailingTakeProfit ? shortTrailingTakeProfitOffset : na, alert_message= i_enableZignalyAlert ? zig.shortExit(exchange=i_zignalyExchange,exchangeAccountType=i_zignalyExchangeType,pair=exchangeTickerID,leverage=i_zignalyLeverage,alertType=i_zignalyAlertType) : na, comment=tmpOrderComment)

// Handle STOP LOSS (and similar) order exits - END

// Strategy Body - END

Overview

A long opens below the corridor in a long bias, and a short opens above it in a short bias, sized from a percentage of that corridor. Moving-average type, length, sources, and distance settings change the ribbon and entries. Optional dynamic take profit, stop loss, and trailing take profit close trades. It draws the ribbon and background on the price chart and can send external alert messages.

Details

Published by

ruckard on GitHub

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Trend, Moving averages, Mean reversion

Markets

Crypto

Timeframes

M15-H1

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Settings

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

SettingTypeDefaultVariable
(ZIG) Enable Alert message {True}booltruei_enableZignalyAlert
(ZIG) Integration typestring_ZIGHYBRIDINTEGRATION_i_zignalyIntegrationTypePre
(ZIG) Provider typestring_ZIGCOPYTRADERPROVIDER_i_zignalyProviderTypePre
(STRAT) Strategy TypestringL_Si_strategyType
(STRAT) Strategy Start Time {2021-01-01 00:00:00}timetimestamp('01 Jan 2021')i_strategyStartTime
(STRAT) Strategy Stop Time {2021-12-31 00:00:00}timetimestamp('31 Dec 2021')i_strategyStopTime
(STRAT) Strategy Start Time forced? {True}booltruei_strategyStartTimeOn
(STRAT) Strategy Stop Time forced? {False}boolfalsei_strategyStopTimeOn
(STRAT) MA Type [SMA]stringSMAi_maType
(STRAT) MA Length (min. 5) [20]int20i_maLength
(STRAT) MA Source [ohlc4]sourceohlc4i_maSource
(STRAT) Signal Source [ohcl4]sourceohlc4i_signalSource
Show all 40 settings
SettingTypeDefaultVariable
(STRAT) Minimum High Low Distance % {0.90}float0.90i_minimumLongDistancePercentage
(STRAT) Minimum Distance Profit % {55.0}float55.0i_minimumDistanceProfitPercentage
(STRAT) Stop Loss Distance % {110.0}float110.0i_StopLossDistancePercentage
(STRAT) High Low Range EMA {3}int3i_HalfCandleEMA
Show ribbon [true]booltruei_showRibbon
Show color [true]booltruei_showBackground
(DEBUG) Enable debug on order comments {False}boolfalsei_enableOrderCommentDebug
(STOPTAKE) (Dynamic) Take Profit? {true}booltruei_enableTakeProfit
(STOPTAKE) (Dynamic) Stop Loss? {true}booltruei_enableStopLoss
(TRAILING) Enable Trailing Take Profit (%) {False}boolfalsei_enableTrailingTakeProfit
(STOPTAKE) Take Profit % {3.0}float1.1i_takeProfitDisabled
(STOPTAKE) Stop Loss % {7.0}float7.0i_stopLossDisabled
(TRAILING) Trailing Take Profit Trigger (%) {2.5}float1.2i_trailingTakeProfitPercentageTrigger
(TRAILING) Trailing Take Profit as a percentage of Trailing Take Profit Trigger (%) {25.0}float25.0i_trailingTakeProfitPercentageOffset
(ZIG) Zignaly Alert Type {WebHook}string_ZIGNALYW_i_zignalyAlertTypePre
(ZIG) Exchange {Zignaly}string_ZIGEXZIGNALY_i_zignalyExchange
(ZIG) Exchange Type {Futures}string_ZIGEXFUTURES_i_zignalyExchangeType
(ZIG) Leverage {1}int1i_zignalyLeverage
Number of decimal digits for Prices {2}int2i_priceDecimalDigits
(DECIMAL) Maximum number of decimal for contracts {3}int3i_contractMaximumDecimalNumber
(RECENT) Number of minutes to wait to open a new order after the previous one has been opened {0}int6i_tooRecentMinutesNumber
(CAPITAL) Capital quote invested per order in USDT units {100.0}float100.0i_CapitalQuote
(CAPITAL) Capital percentage invested per order (%) {25.0}float25.0i_CapitalPercentage
(RISKM) Risk Management Typestring_NONE_i_riskManagementTypePre
(RISKM) Maximum loss per trade % {1.0}float1.0i_riskManagementMaximumLossPerTrade
(RISKM) Maximum loss per day % {6.0}float6.0i_riskManagementMaximumLossPerDay
(RISKM) Maximum loss per week % {8.0}float8.0i_riskManagementMaximumLossPerWeek
(RISKM) Maximum loss per month % {10.0}float10.0i_riskManagementMaximumLossPerMonth
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

This mean-reversion strategy plots Bollinger Bands and a long-term moving average directly on the price chart. It enters trades when price candles penetrate the outer Bollinger Bands beyond a user-defined body percentage, anticipating a price reversal. Entries

Strategy v5 Mean reversionVolatility & bands
Updated 2 months ago · None stated GitHub repository of Bollinger Bands Winner PRO [Alorse]

8 Day Run

by hasnocool
106 stars

Inspired by Linda Raschke's strategy for T-note futures, this script identifies extended trends where price remains on one side of a 5-period SMA for more than eight consecutive bars. It enters long on the first pullback below the SMA following an eight-bar bu

Strategy v4 TrendMoving averages
Updated 2 years ago · GPL-3.0 GitHub repository of 8 Day Run

Bollinger Bands Strategy

by cklose2000
105 stars

This strategy generates buy and sell signals based on Bollinger Band crossovers combined with a simple moving average trend filter. It enters a long position when price crosses above the lower band while trading above the SMA filter line, and enters a short po

Strategy v5 Volatility & bandsMoving averages
Updated 1 year ago · None stated GitHub repository of Bollinger Bands Strategy
53 stars

This strategy identifies long entry opportunities based on short-term price pullbacks below a major trend filter. It enters long when three consecutive lower closes occur below the 200-period simple moving average, followed by the current bar closing back abov

Strategy v6 TrendMoving averages
Updated 2 months ago · MPL-2.0 GitHub repository of Ivan Scherman Pattern - TP/SL

VWAP Bounce - Eterna

by EternaHybridExchange
9 stars

This strategy overlays volume-weighted average price deviation bands and an exponential moving average trend filter directly on the price chart. It enters long positions during an uptrend when price recovers above the lower band, and enters short positions in

Strategy v5 Mean reversionTrend
Updated 7 months ago · MIT GitHub repository of VWAP Bounce - Eterna
7 stars

This long-only strategy identifies pullback opportunities within a broader trend. It enters a long position when the closing price trades above a long-term exponential moving average while falling below a short-term exponential moving average. Once in a trade,

Strategy v5 TrendMoving averages
Updated 1 year ago · MPL-2.0 GitHub repository of Pullback Strategy for Stocks

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