-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_strategy.py
More file actions
166 lines (155 loc) · 9.94 KB
/
test_strategy.py
File metadata and controls
166 lines (155 loc) · 9.94 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
"""Auto-generated by PocketPine transpiler."""
import numpy as np
from pocketpine import indicators as ta
from pocketpine.strategy import Strategy
from pocketpine.signal_parser import Signal, Action
class PineStrategy(Strategy):
def setup(self):
self.p = {
'patternStrength': 3,
'bodyRatio': 0.65,
'shadowRatio': 2.2,
'patternLookback': 3,
'minPatternSize': 0.5,
'enableHammer': True,
'enableDoji': True,
'enableEngulfing': True,
'enableStar': True,
'enableHarami': True,
'enablePiercing': True,
'enableShootingStar': True,
'enableInvertedHammer': True,
'useVolumeConfirmation': True,
'volumeMultiplier': 1.15,
'useTrendConfirmation': True,
'trendPeriod': 20,
'useRSIConfirmation': True,
'rsiPeriod': 14,
'rsiOverbought': 70,
'rsiOversold': 30,
'useMAConfirmation': False,
'maFastPeriod': 9,
'maSlowPeriod': 21,
'stopLossType': "ATR",
'stopLossPercent': 1.5,
'atrPeriod': 14,
'atrMultiplier': 1.6,
'takeProfitRatio': 3.2,
'showTPSL': True,
'showLabels': True,
'maxSignalsDisplay': 10,
}
self._lastSignalType = None
def _calculateStopLoss(self, isLong, entryPrice, **kw):
p = self.p
close = kw.get('close', self.bars.close)
open_ = kw.get('open_', self.bars.open)
high = kw.get('high', self.bars.high)
low = kw.get('low', self.bars.low)
volume = kw.get('volume', self.bars.volume)
if p['stopLossType'] == "Percentage":
if isLong:
return entryPrice * (1 - p['stopLossPercent'] / 100)
else:
return entryPrice * (1 + p['stopLossPercent'] / 100)
elif p['stopLossType'] == "ATR":
if isLong:
return entryPrice - atrValue * p['atrMultiplier']
else:
return entryPrice + atrValue * p['atrMultiplier']
else:
if isLong:
return np.minimum(low, ta.shift(low, 1)) - atrValue * 0.5
else:
return np.maximum(high, ta.shift(high, 1)) + atrValue * 0.5
def _calculateTakeProfit(self, isLong, entryPrice, stopLoss, **kw):
p = self.p
close = kw.get('close', self.bars.close)
open_ = kw.get('open_', self.bars.open)
high = kw.get('high', self.bars.high)
low = kw.get('low', self.bars.low)
volume = kw.get('volume', self.bars.volume)
stopDistance = np.abs(entryPrice - stopLoss)
if isLong:
return entryPrice + stopDistance * p['takeProfitRatio']
else:
return entryPrice - stopDistance * p['takeProfitRatio']
def compute(self):
p = self.p
close = self.bars.close
open_ = self.bars.open
high = self.bars.high
low = self.bars.low
volume = self.bars.volume
if len(close) < 3:
return
atrValue = ta.atr(high, low, close, p['atrPeriod'])
ema = ta.ema(close, p['trendPeriod'])
uptrend = close > ema
downtrend = close < ema
maFast = ta.ema(close, p['maFastPeriod'])
maSlow = ta.ema(close, p['maSlowPeriod'])
bullishTrendMA = ((maFast > maSlow) & (close > maFast))
bearishTrendMA = ((maFast < maSlow) & (close < maFast))
rsi = ta.rsi(close, p['rsiPeriod'])
rsiOverboughtCondition = rsi > p['rsiOverbought']
rsiOversoldCondition = rsi < p['rsiOversold']
avgVolume = ta.sma(volume, 20)
highVolume = volume > avgVolume * p['volumeMultiplier']
bodySize = np.abs(close - open_)
totalRange = high - low
upperShadow = high - np.maximum(close, open_)
lowerShadow = np.minimum(close, open_) - low
bodyRatioActual = np.where(totalRange > 0, bodySize / totalRange, 0)
upperShadowRatio = np.where(bodySize > 0, upperShadow / bodySize, 0)
lowerShadowRatio = np.where(bodySize > 0, lowerShadow / bodySize, 0)
bullishCandle = close > open_
bearishCandle = close < open_
bullishDoji = (p['enableDoji'] & (((bodyRatioActual < 0.1) & (totalRange > atrValue * 0.5))) & downtrend)
bullishHammer = (p['enableHammer'] & (((lowerShadow >= bodySize * p['shadowRatio']) & (upperShadow <= bodySize * 0.5) & (bodyRatioActual >= p['bodyRatio'] * 0.5) & (bodyRatioActual <= 0.8))) & downtrend)
bullishInvertedHammer = (p['enableInvertedHammer'] & (((upperShadow >= bodySize * p['shadowRatio']) & (lowerShadow <= bodySize * 0.5) & (bodyRatioActual >= p['bodyRatio'] * 0.5))) & downtrend)
bullishEngulfing = (p['enableEngulfing'] & ((ta.shift(bearishCandle, 1) & bullishCandle & (open_ <= ta.shift(close, 1)) & (close > ta.shift(open_, 1)) & (bodySize > ta.shift(bodySize, 1) * 1.2))))
bullishMorningStar = (p['enableStar'] & ((ta.shift(bearishCandle, 2) & (ta.shift(bodySize, 2) > atrValue) & (ta.shift(bodyRatioActual, 1) < 0.3) & bullishCandle & (close > (ta.shift(open_, 2) + ta.shift(close, 2)) / 2))))
bullishHarami = (p['enableHarami'] & ((ta.shift(bearishCandle, 1) & bullishCandle & (open_ > ta.shift(close, 1)) & (close < ta.shift(open_, 1)) & (bodySize < ta.shift(bodySize, 1) * 0.7))))
bullishPiercing = (p['enablePiercing'] & ((ta.shift(bearishCandle, 1) & bullishCandle & (open_ < ta.shift(low, 1)) & (close > (ta.shift(open_, 1) + ta.shift(close, 1)) / 2) & (close < ta.shift(open_, 1)))))
bearishDoji = (p['enableDoji'] & (((bodyRatioActual < 0.1) & (totalRange > atrValue * 0.5))) & uptrend)
bearishShootingStar = (p['enableShootingStar'] & (((upperShadow >= bodySize * p['shadowRatio']) & (lowerShadow <= bodySize * 0.5) & (bodyRatioActual >= p['bodyRatio'] * 0.5) & (bodyRatioActual <= 0.8))) & uptrend)
bearishHangingMan = (p['enableHammer'] & (((lowerShadow >= bodySize * p['shadowRatio']) & (upperShadow <= bodySize * 0.5) & (bodyRatioActual >= p['bodyRatio'] * 0.5) & (bodyRatioActual <= 0.8))) & uptrend)
bearishEngulfing = (p['enableEngulfing'] & ((ta.shift(bullishCandle, 1) & bearishCandle & (open_ >= ta.shift(close, 1)) & (close < ta.shift(open_, 1)) & (bodySize > ta.shift(bodySize, 1) * 1.2))))
bearishEveningStar = (p['enableStar'] & ((ta.shift(bullishCandle, 2) & (ta.shift(bodySize, 2) > atrValue) & (ta.shift(bodyRatioActual, 1) < 0.3) & bearishCandle & (close < (ta.shift(open_, 2) + ta.shift(close, 2)) / 2))))
bearishHarami = (p['enableHarami'] & ((ta.shift(bullishCandle, 1) & bearishCandle & (open_ < ta.shift(close, 1)) & (close > ta.shift(open_, 1)) & (bodySize < ta.shift(bodySize, 1) * 0.7))))
bearishDarkCloud = (p['enablePiercing'] & ((ta.shift(bullishCandle, 1) & bearishCandle & (open_ > ta.shift(high, 1)) & (close < (ta.shift(open_, 1) + ta.shift(close, 1)) / 2) & (close > ta.shift(open_, 1)))))
bullishPatternDetected = (bullishDoji) | (bullishHammer) | (bullishInvertedHammer) | (bullishEngulfing) | (bullishMorningStar) | (bullishHarami) | (bullishPiercing)
bearishPatternDetected = (bearishDoji) | (bearishShootingStar) | (bearishHangingMan) | (bearishEngulfing) | (bearishEveningStar) | (bearishHarami) | (bearishDarkCloud)
volumeConfirmed = np.where(p['useVolumeConfirmation'], highVolume, True)
trendConfirmedBullish = np.where(p['useTrendConfirmation'], ((close > ema * 0.99)) | (~uptrend), True)
trendConfirmedBearish = np.where(p['useTrendConfirmation'], ((close < ema * 1.01)) | (~downtrend), True)
maConfirmedBullish = np.where(p['useMAConfirmation'], bullishTrendMA, True)
maConfirmedBearish = np.where(p['useMAConfirmation'], bearishTrendMA, True)
rsiConfirmedBullish = np.where(p['useRSIConfirmation'], ((rsi < 55) & ~rsiOverboughtCondition), True)
rsiConfirmedBearish = np.where(p['useRSIConfirmation'], ((rsi > 45) & ~rsiOversoldCondition), True)
buySignalRaw = (ta.shift(bullishPatternDetected, 1) & ta.shift(volumeConfirmed, 1) & ta.shift(trendConfirmedBullish, 1) & ta.shift(rsiConfirmedBullish, 1) & ta.shift(maConfirmedBullish, 1))
sellSignalRaw = (ta.shift(bearishPatternDetected, 1) & ta.shift(volumeConfirmed, 1) & ta.shift(trendConfirmedBearish, 1) & ta.shift(rsiConfirmedBearish, 1) & ta.shift(maConfirmedBearish, 1))
buySignal = ((buySignalRaw & (self._lastSignalType != "BUY"))) | ((self._lastSignalType is None))
sellSignal = ((sellSignalRaw & (self._lastSignalType != "SELL"))) | ((self._lastSignalType is None))
# Store signals
self._sellSignalRaw = sellSignalRaw if isinstance(sellSignalRaw, np.ndarray) else np.full(1, bool(sellSignalRaw))
self._buySignal = buySignal if isinstance(buySignal, np.ndarray) else np.full(1, bool(buySignal))
self._sellSignal = sellSignal if isinstance(sellSignal, np.ndarray) else np.full(1, bool(sellSignal))
self._bearishPatternDetected = bearishPatternDetected if isinstance(bearishPatternDetected, np.ndarray) else np.full(1, bool(bearishPatternDetected))
self._buySignalRaw = buySignalRaw if isinstance(buySignalRaw, np.ndarray) else np.full(1, bool(buySignalRaw))
self._bullishPatternDetected = bullishPatternDetected if isinstance(bullishPatternDetected, np.ndarray) else np.full(1, bool(bullishPatternDetected))
def get_signal(self):
if len(self.bars) < 3:
return None
try:
if bool(self._buySignal[-1]) and self._lastSignalType != 'BUY':
self._lastSignalType = 'BUY'
return Signal(Action.BUY, self.asset, self.amount, self.duration)
except (IndexError, TypeError): pass
try:
if bool(self._sellSignal[-1]) and self._lastSignalType != 'SELL':
self._lastSignalType = 'SELL'
return Signal(Action.SELL, self.asset, self.amount, self.duration)
except (IndexError, TypeError): pass
return None