forked from JPBuilds/PineScript-Indicators
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJPBuilds Trend Strategy
53 lines (36 loc) · 2.38 KB
/
JPBuilds Trend Strategy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © JPBuilds
//@version=4
strategy("JPBuilds Trend Strategy", overlay=true, pyramiding=25)
// Timeframe
fromMonth = input(1, title = "From Month", minval = 1, maxval = 12)
fromDay = input(1, title = "From Day", minval = 1, maxval = 31)
fromYear = input(2000, title = "From Year", minval = 2000)
fromTimestamp = timestamp(fromYear, fromMonth, fromDay, 0, 0)
toMonth = input(1, title = "To Month", minval = 1, maxval = 12)
toDay = input(1, title = "To Day", minval = 1, maxval = 31)
toYear = input(9999, title = "To Year", minval = 2001)
toTimestamp = timestamp(toYear, toMonth, toDay, 0, 0)
isWithinTimeframe = iff(time >= fromTimestamp and time <= toTimestamp, true, false)
// Trend Direction MA
trendMALength = input(200, minval=5, maxval=1000, title="Trend Direction MA Length")
trendMA = sma(close, trendMALength)
sellMAFlag = iff(close[0] < trendMA[0], true, false)
buyMAFlag = iff(close[0] > trendMA[0], true, false)
// MACD Cross
[macdLine, signalLine, histLine] = macd(close, 12, 26, 9)
isMACDShrinking = iff(histLine[0] < histLine[1] and histLine[1] < histLine[2] and histLine[2] < histLine[3], true, false)
isMACDRising = iff(histLine[0] > histLine[1] and histLine[1] > histLine[2] and histLine[2] > histLine[3], true, false)
sellMACDFlag = iff(isMACDShrinking == true and histLine[0] < 0.1 and histLine[1] >= 0.1 and macdLine[0] > 0 and signalLine[0] > 0, true, false)
buyMACDFlag = iff(isMACDRising == true and histLine[0] > -0.1 and histLine[1] < -0.1 and macdLine[0] < 0 and signalLine[0] < 0, true, false)
// Buy/Sell Flags
sellFlag = sellMAFlag and sellMACDFlag
buyFlag = buyMAFlag and buyMACDFlag
// Position Management
useStoploss = input(false, title="Use Stoploss?")
stoplossPercent = input(15, minval=0.1, maxval=100, title="Stoploss %") / 100
if useStoploss
strategy.exit("stoploss", "TrendBuy", stop=strategy.position_avg_price*(1-stoplossPercent), when = isWithinTimeframe and strategy.position_size > 0)
strategy.exit("stoploss", "TrendSell", stop=strategy.position_avg_price*(1+stoplossPercent), when = isWithinTimeframe and strategy.position_size < 0)
strategy.entry("TrendBuy", strategy.long, comment="Trend Buy", when = isWithinTimeframe and buyFlag)
strategy.entry("TrendSell", strategy.short, comment="Trend Sell", when = isWithinTimeframe and sellFlag)