How It Works Chart Features House Rules Moderators For the WEB Widgets Stock Charting Library Feature Request FAQ Help & Wiki Twitter

# Trend Strategy

195 0
Trend Strategy
```//@version=2
strategy("Trend Strategy", shorttitle="TSTrend Strategy", overlay=true)

// Trend Strategy
// If the inverse logic is true, the strategy
// goes short. For the worst case there is a
// max intraday equity loss of 50% filter.

// Input
source = input(close)
fastLength = input(12, minval=1, title="MACD fast moving average")
slowLength=input(26,minval=1, title="MACD slow moving average")
signalLength=input(9,minval=1, title="MACD signal line moving average")
veryslowLength=input(200,minval=1, title="Very slow moving average")
switch1=input(true, title="Enable Bar Color?")
switch2=input(true, title="Enable Moving Averages?")
switch3=input(true, title="Enable Background Color?")

// Calculation
fastMA = sma(source, fastLength)
slowMA = sma(source, slowLength)
veryslowMA = sma(source, veryslowLength)
macd = fastMA - slowMA
signal = sma(macd, signalLength)
hist = macd - signal

// Colors
MAtrendcolor = change(veryslowMA) > 0 ? green : red
trendcolor = fastMA > slowMA and change(veryslowMA) > 0 and close > slowMA ? green : fastMA < slowMA and change(veryslowMA) < 0 and close < slowMA ? red : blue
bartrendcolor = close > fastMA and close > slowMA and close > veryslowMA and change(slowMA) > 0 ? green : close < fastMA and close < slowMA and close < veryslowMA and change(slowMA) < 0 ? red : blue
backgroundcolor = slowMA > veryslowMA and crossover(hist, 0) and macd > 0 and fastMA > slowMA and close[slowLength] > veryslowMA ? green : slowMA < veryslowMA and crossunder(hist, 0) and macd < 0 and fastMA < slowMA and close[slowLength] < veryslowMA ? red : na
bgcolor(switch3?backgroundcolor:na,transp=80)
barcolor(switch1?bartrendcolor:na)

// Output
F=plot(switch2?fastMA:na,color=trendcolor)
S=plot(switch2?slowMA:na,color=trendcolor,linewidth=2)
V=plot(switch2?veryslowMA:na,color=MAtrendcolor,linewidth=4)
fill(F,V,color=gray)

// Strategy
sellprice = high
cancelLong = slowMA < veryslowMA
cancelShort = slowMA > veryslowMA

if (cancelLong)
strategy.cancel("MACDLE")

if crossover(hist, 0) and macd > 0 and fastMA > slowMA and close[slowLength] > veryslowMA

if (cancelShort)
strategy.cancel("MACDSE")

if crossunder(hist, 0) and macd < 0 and fastMA < slowMA and close[slowLength] < veryslowMA
strategy.entry("MACDSE", strategy.short, stop=sellprice, comment="Bearish")

maxIdLossPcnt = input(50, "Max Intraday Loss(%)", type=float)

//plot(strategy.equity, title="equity", color=red, linewidth=2, style=areabr)```
United States
United Kingdom
India
España
France
Italia
Polska
Brasil
Россия
Türkiye
Indonesia

한국
Home Stock Screener Forex Signal Finder Economic Calendar How It Works Chart Features House Rules Moderators For the WEB Widgets Stock Charting Library Priority Support Feature Request Blog & News FAQ Help & Wiki Twitter