Noro's Trend Ribbon Strategy
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © noro

//@version=4
strategy(title = "Noro's Trend Ribbon Strategy", shorttitle = "Trend Ribbon str", overlay = true, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, pyramiding = 0, commission_value = 0.1)

//Settings
needlong = input(true, defval = true, title = "Long")
needshort = input(true, defval = true, title = "Short")
type = input(defval = "SMA", options = ["SMA", "EMA", "VWMA", "RMA"], title = "MA Type")
len = input(20, minval = 5,  title = "MA Length (min. 5)")
src1 = input(ohlc4, title = "MA Source")
src2 = input(ohlc4, title = "Signal Source")
showrib = input(true, title = "Show ribbon")
showbg = input(true, title = "Show color")
fromyear = input(1900, defval = 1900, minval = 1900, maxval = 2100, title = "From Year")
toyear = input(2100, defval = 2100, minval = 1900, maxval = 2100, title = "To Year")
frommonth = input(01, defval = 01, minval = 01, maxval = 12, title = "From Month")
tomonth = input(12, defval = 12, minval = 01, maxval = 12, title = "To Month")
fromday = input(01, defval = 01, minval = 01, maxval = 31, title = "From day")
today = input(31, defval = 31, minval = 01, maxval = 31, title = "To day")

//MA
ma = type == "SMA" ? sma(src1, len) : type == "EMA" ? ema(src1, len) : type == "VWMA" ? vwma(src1, len) : rma(src1, len)
colorma = showrib ? color.black : na
pm = plot(ma, color = colorma, title = "MA")

//Price Channel
h = highest(ma, len)
l = lowest(ma, len)
colorpc = showrib ? color.blue : na
ph = plot(h, color = colorpc, title = "Upper line")
pl = plot(l, color = colorpc, title = "Lower Line")

//Trend
trend = 0
trend := src2 > h[1] ? 1 : src2 < l[1] ? -1 : trend[1]

//BG
colorbg1 = showbg ? color.red : na
colorbg2 = showbg ? color.blue : na
fill(ph, pm, color = colorbg1, transp = 50)
fill(pl, pm, color = colorbg2, transp = 50)

//Trading
truetime = time > timestamp(fromyear, frommonth, fromday, 00, 00) and time < timestamp(toyear, tomonth, today, 23, 59)
if trend == 1 and needlong
    strategy.entry("Long", strategy.long, when = truetime)
if trend == -1 and needshort
    strategy.entry("Short", strategy.short, when = truetime)
if trend == 1 and needlong == false
    strategy.close_all()
if trend == -1 and needshort == false
    strategy.close_all()
if time > timestamp(toyear, tomonth, today, 23, 59)
    strategy.close_all()