// Trend Follower
//
// https://it.tradingview.com/script/o0ZOSVHj-Trend-Follower/
//
MAtype = 1 //1=Ema
TrendP = 20 //20 periods to check trend
MAperiods = 20 //20 periods for MA
TrendRate = 1 //1% trend channel rate
UseLR = 1 //1=use Linear Regression, 0=do not use LR
LRperiods = 5 //5 periods for Linear Regression
RangeP = 1 //300 period for the range
MAtype = max(0,min(8,MAtype))
TrendP = max(1,min(999,TrendP))
MAperiods = max(1,min(999,MAperiods))
TrendRate = max(0.00001,min(99,TrendRate))
RangeP = max(1,min(999,RangeP))
//
RateMult = TrendRate / 100
PriceRange= highest[RangeP](high) - lowest[RangeP](low)
MyChannel = PriceRange * RateMult
MyMA = average[MAperiods,MAtype](close)
IF UseLR THEN
MyMA = LinearRegression[LRperiods](close)
ENDIF
hh = highest[TrendP](MyMA)
ll = lowest[TrendP](MyMA)
diff = abs(hh - ll)
x = 0
IF diff > MyChannel THEN
IF MyMA > (ll + MyChannel) THEN
x = 1
ELSE
IF MyMA < (hh - MyChannel) THEN
x = -1
ENDIF
ENDIF
ENDIF
Trend = x * diff / MyChannel
IF Trend> 0 THEN
r = 0
g = 255
b = 0
t = 255
IF Trend < Trend[1] THEN
g = 128
t = 180
ENDIF
ELSE
r = 255
g = 0
b = 0
t = 255
IF Trend > Trend[1] THEN
r = 139
g = 0
b = 0
t = 255
ENDIF
ENDIF
// "LONG" trend open
if not onmarket and trend > 0 then
BUY 1 CONTRACTS AT MARKET
endif
// "LONG" trend closed
if longonmarket and trend < 0 then
SELL AT MARKET
ENDIF
// "SHORT" trend open
if not onmarket and trend < 0 then
SELLSHORT 1 CONTRACTS AT MARKET
endif
// "SHORT" trend closed
if shortonmarket and trend > 0 then
EXITSHORT AT MARKET
ENDIF