1 | // "Mystery Strategy" / "Holy Grail for ETH" |
2 | // |
3 | // Preconfigured for ETH 30m on Bitget |
4 | // Works on: ETH since 2022-12, AVAX since 2023-3 |
5 | // |
6 | // (c) Stefan Reich |
7 | //@version=5 |
8 | |
9 | strategy(shorttitle="Stefan Reich's Mystery Strategy v230", title="Stefan Reich's Mystery Strategy", |
10 | overlay=true, |
11 | commission_type=strategy.commission.percent, commission_value=0.07, |
12 | initial_capital = 100, default_qty_type=strategy.cash, default_qty_value=1000, |
13 | calc_on_every_tick = true, |
14 | max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500) |
15 | |
16 | // commission_value is an approximately correct estimate for fees+spread on ETH on typical exchanges (Bitget, Bybit) |
17 | // This strategy opens few positions though, so fees+spread are not a big deal anyway. |
18 | |
19 | shrouded = input.bool(false) |
20 | startingDate = input.time(timestamp("8 Dec 2022")) |
21 | doLongs=input.bool(true, "Do longs") |
22 | doShorts=input.bool(false, "Do shorts") |
23 | |
24 | minMoveLong = input.float(1.6, step=0.1) |
25 | minMoveShort = input.float(1.6, step=0.1) |
26 | |
27 | arrowOffset = input.float(10) |
28 | initialOffset = input.float(10) |
29 | equityOffset = input.float(10) |
30 | topOffset = input.float(1, step=0.25) |
31 | filesSlanted = input.bool(true) |
32 | |
33 | ieBoxColor = input.color(color.black) |
34 | ieTextColor = input.color(color.blue) |
35 | |
36 | positionSize = input.float(1000, "Position size in $", tooltip="After leverage") |
37 | |
38 | // UTILITY FUNCTIONS |
39 | |
40 | drift() => |
41 | sumDrift = 0.0 |
42 | for tradeNo = 0 to strategy.opentrades - 1 |
43 | sumDrift += strategy.opentrades.size(tradeNo) |
44 | result = sumDrift |
45 | |
46 | // macro logFloat(value, title) { plotchar(value, title, "", location.top) } |
47 | |
48 | // MACD inputs |
49 | fast_length = input(title="Fast Length", defval=25) |
50 | slow_length = input(title="Slow Length", defval=100) |
51 | macd_src = input(title="Source", defval=close) |
52 | signal_length = input.int(title="Signal Smoothing", minval = 1, defval = 9) |
53 | sma_source = input.string(title="Oscillator MA Type", defval="EMA", options=["SMA", "EMA"]) |
54 | sma_signal = input.string(title="Signal Line MA Type", defval="EMA", options=["SMA", "EMA"]) |
55 | |
56 | intraCandleOperation = input.bool(false, tooltip="Open or close trades within a candle") |
57 | |
58 | switchOnLongsAbove = input.float(-100, step=0.1, tooltip="Allow longs only if MACD is above this level") |
59 | switchOnShortsBelow = input.float(100, step=0.1, tooltip="Allow shorts only if MACD is below this level") |
60 | |
61 | equityXOffset = input.int(10, tooltip="Move equity box to the right using this value") |
62 | |
63 | exitThresholdLong = input.float(999, step=0.1, tooltip="MACD histogram value to exit a long at. To use -MinMoveShort, enter 999") |
64 | exitThresholdShort = input.float(999, step=0.1, tooltip="MACD histogram value to exit a short at. To use MinMoveLong, enter 999") |
65 | |
66 | hotSwitchOkay = input.bool(true, tooltip="Can we kill a long by opening a short and vice versa?") |
67 | |
68 | equityShort = input.bool(true, tooltip="Show only the new equity, no text") |
69 | |
70 | useEndDate = input.bool(false, tooltip="Activate the end date below") |
71 | endDate = input.time(timestamp("31 Dec 2023"), tooltip="When to end the backtest or execution (if checkbox above is set)") |
72 | |
73 | useRelativeMACD = input.bool(false, tooltip="Use relative MACD (normalized to asset price)") |
74 | |
75 | // Add more inputs down here to not mess up configurations of older versions |
76 | |
77 | // MACD calculation |
78 | |
79 | fast_ma = sma_source == "SMA" ? ta.sma(macd_src, fast_length) : ta.ema(macd_src, fast_length) |
80 | slow_ma = sma_source == "SMA" ? ta.sma(macd_src, slow_length) : ta.ema(macd_src, slow_length) |
81 | macd = fast_ma - slow_ma |
82 | signal = sma_signal == "SMA" ? ta.sma(macd, signal_length) : ta.ema(macd, signal_length) |
83 | hist = macd - signal |
84 | |
85 | // Plot MACD |
86 | plot(fast_ma, title="MACD Fast MA", color=color.yellow) |
87 | plot(slow_ma, title="MACD Slow MA", color=color.blue) |
88 | plotchar(macd, "MACD", "", location.top) |
89 | |
90 | // Relative MACD values (in preparation for Mark II strategy) |
91 | factor = 1000 / slow_ma |
92 | relMACD = macd * factor |
93 | relSignal = signal * factor |
94 | relHist = (macd - signal) * factor |
95 | |
96 | plotchar(relMACD, "Relative MACD", "", location.top) // logFloat |
97 | plotchar(hist, "MACD Histogram", "", location.top) // logFloat |
98 | plotchar(relHist, "Relative MACD Histogram", "", location.top) // logFloat |
99 | |
100 | actualExitLong = exitThresholdLong == 999 ? -minMoveShort : exitThresholdLong |
101 | actualExitShort = exitThresholdShort == 999 ? minMoveLong : exitThresholdShort |
102 | |
103 | macdToUse = useRelativeMACD ? relMACD : macd |
104 | histToUse = useRelativeMACD ? relHist : hist |
105 | |
106 | if time >= startingDate and (not useEndDate or time <= endDate) and (intraCandleOperation or barstate.isconfirmed) |
107 | qty = positionSize/close |
108 | |
109 | if drift() < 0.0 and histToUse >= actualExitShort |
110 | strategy.close_all(shrouded ? "Exit" : "MACD Green") |
111 | else if drift() > 0.0 and histToUse <= actualExitLong |
112 | strategy.close_all(shrouded ? "Exit" : "MACD Red") |
113 | |
114 | if hotSwitchOkay or drift() == 0.0 |
115 | if doLongs and histToUse >= minMoveLong and macdToUse >= switchOnLongsAbove |
116 | strategy.entry("Long", strategy.long, qty=qty) |
117 | else if doShorts and histToUse <= -minMoveShort and macdToUse <= switchOnShortsBelow |
118 | strategy.entry("Short", strategy.short, qty=qty) |
119 | |
120 | // PAINT TRADES & INITIAL EQUITY |
121 | |
122 | plusMinusFix(s) => |
123 | currency = " $" |
124 | str.startswith(s, "-") ? "-" + currency + str.substring(s, 1) : "+" + currency + s |
125 | |
126 | formatProfit(profit) => |
127 | plusMinusFix(str.tostring(profit, "#,##0.00")) |
128 | |
129 | var int tradesPainted = 0 |
130 | var label initialEquityLabel = na |
131 | |
132 | if na(initialEquityLabel) and time >= startingDate |
133 | ieText = "⬆\nWe invest\n$" + str.tostring(strategy.initial_capital, "#,##0") + "\nand start\nthe strategy!" |
134 | ieTime = startingDate-2*24*60*60*1000 // 2 days back |
135 | //ieY = close*(1-arrowOffset/100) // for style_label_center |
136 | //style=label.style_label_center |
137 | ieY = close*(1-initialOffset/100) // for style_label_up |
138 | //boxColor = color.black |
139 | //textColor = color.white |
140 | style = label.style_label_up |
141 | //style = label.style_triangleup |
142 | initialEquityLabel := label.new(ieTime, ieY, ieText, xloc=xloc.bar_time, color=ieBoxColor, textcolor=ieTextColor, tooltip="Initial equity", size=size.huge, style=style) |
143 | |
144 | type PaintedTrade |
145 | array<line> lines |
146 | array<label> labels |
147 | |
148 | drawTrade(bar1, bar2, price1, price2, profit, open) => |
149 | t = PaintedTrade.new() |
150 | t.lines := array.new<line>() |
151 | t.labels := array.new<label>() |
152 | totalProfit = strategy.equity // -strategy.initial_capital |
153 | //line.new(bar1, price1, bar2, price2, xloc=xloc.bar_index, width = 10, color=color.black, style=line.style_arrow_right) |
154 | float y1 = price1*(1-arrowOffset/100) |
155 | float y2 = price2*(1-arrowOffset/100) |
156 | float top1 = price1*(1-topOffset/100) |
157 | float top2 = (open ? math.min(price2, low) : price2)*(1-topOffset/100) |
158 | color_solid = profit > 0 ? color.lime : color.red |
159 | color = color.new(color_solid, 50) |
160 | |
161 | if not filesSlanted |
162 | y1 := math.min(y1, y2) |
163 | y2 := y1 |
164 | |
165 | array.push(t.lines, line.new(bar1, top1, bar1, y1, color=color, width=3)) |
166 | array.push(t.lines, line.new(bar2, top2, bar2, y2, color=color, width=3)) |
167 | array.push(t.lines, line.new(bar1, y1, bar2, y2, xloc=xloc.bar_index, width = 10, color=color)) //, style=line.style_arrow_right) |
168 | |
169 | ypos = 0.6 |
170 | string profitText = formatProfit(profit) |
171 | yPrice = (price1+price2)/2 |
172 | yBottom = (y1+y2)/2 |
173 | yText = yPrice*(1-ypos)+yBottom*ypos |
174 | priceTooltip = "This trade " + (str.startswith(profitText, "+") ? "made" : "lost") + " " + profitText |
175 | if open |
176 | profitText := "OPEN TRADE. " + str.replace(profitText, " $", "$") |
177 | array.push(t.labels, label.new((bar1+bar2)/2, yText, profitText, textcolor=color.new(color_solid, 25), color=color.black, style=label.style_text_outline, size=size.huge, tooltip=priceTooltip)) |
178 | |
179 | // TODO: Show current equity even if there is no open trade |
180 | if not na(totalProfit) |
181 | //totalProfitText = "Total: " + formatProfit(totalProfit) |
182 | //totalProfitText = plusMinusFix(str.tostring(math.round(totalProfit))) |
183 | amount = "$" + str.tostring(totalProfit, "#,##0") |
184 | //totalProfitText = "⇒ " + amount |
185 | string format = na |
186 | if open |
187 | format := "Current\nequity:\n\n*" |
188 | else if equityShort |
189 | format := "*" |
190 | else if profit <= 0 |
191 | format := "*\nleft" |
192 | else if tradesPainted > 1 |
193 | format := "Now we\nhave\n*" |
194 | else |
195 | format := "Now we\nhave\n*." |
196 | totalProfitText = str.replace(format, "*", amount) |
197 | totalColor = totalProfit > 0 ? color.lime : color.orange |
198 | //yTotal = yBottom+(yBottom-yText)*4 |
199 | float yTotal = y2 |
200 | //xTotal = (bar1+bar2)/2 |
201 | int xTotal = bar2+(open ? equityXOffset : 4) |
202 | days = math.round((time-startingDate)/1000.0/60/60/24+1) |
203 | tooltip = "New total equity (started with $" + str.tostring(strategy.initial_capital, "#,##0") + " - " + str.tostring(days) + " " + (days == 1 ? "day" : "days") + " ago)" |
204 | string style = label.style_label_left |
205 | string size = size.large |
206 | if open |
207 | style := label.style_label_center |
208 | xTotal := xTotal+15 |
209 | yTotal := price2*(1-equityOffset/100) |
210 | size := size.huge |
211 | array.push(t.labels, label.new(xTotal, yTotal, totalProfitText, textcolor=color.new(totalColor, 25), style=style, color=color.black, size=size, tooltip=tooltip)) |
212 | |
213 | t |
214 | |
215 | method delete(PaintedTrade this) => |
216 | for line in this.lines |
217 | line.delete(line) |
218 | for lbl in this.labels |
219 | label.delete(lbl) |
220 | |
221 | while tradesPainted < strategy.closedtrades |
222 | bar1 = strategy.closedtrades.entry_bar_index(tradesPainted) |
223 | bar2 = strategy.closedtrades.exit_bar_index(tradesPainted) |
224 | price1 = strategy.closedtrades.entry_price(tradesPainted) |
225 | price2 = strategy.closedtrades.exit_price(tradesPainted) |
226 | //direction = strategy.closedtrades.size(tradesPainted) |
227 | profit = strategy.closedtrades.profit(tradesPainted) |
228 | drawTrade(bar1, bar2, price1, price2, profit, false) |
229 | tradesPainted := tradesPainted+1 |
230 | |
231 | var PaintedTrade openTrade = na |
232 | var label macdLabel = na |
233 | |
234 | if not barstate.ishistory |
235 | if not na(openTrade) |
236 | openTrade.delete() |
237 | |
238 | if strategy.opentrades != 0 |
239 | bar1 = strategy.opentrades.entry_bar_index(0) |
240 | bar2 = bar_index |
241 | price1 = strategy.opentrades.entry_price(0) |
242 | price2 = close |
243 | profit = strategy.opentrades.profit(0) |
244 | openTrade := drawTrade(bar1, bar2, price1, price2, profit, true) |
245 | |
246 | // Show/update floating MACD value |
247 | |
248 | if not na(macdLabel) |
249 | label.delete(macdLabel) |
250 | macdValue = str.tostring(histToUse, "0.0#") |
251 | lowerBound = -minMoveShort |
252 | upperBound = minMoveLong |
253 | macdPercent = (histToUse-lowerBound)/(upperBound-lowerBound)*100 |
254 | percentText = str.tostring(macdPercent, "0") + "%" |
255 | tooltip = "MACD value: " + macdValue + " (" + percentText + " between close and open)" |
256 | macdColor = macdPercent >= 0 and macdPercent <= 100 ? color.blue : color.yellow |
257 | macdLabel := label.new(bar_index, close, percentText, tooltip=tooltip, yloc=yloc.abovebar, textcolor=macdColor, color=color.black, style=label.style_text_outline, size=size.large) |
258 | |
259 | // Show unrealized P&L in data window |
260 | |
261 | unrealizedPnL = strategy.opentrades == 0 ? na : strategy.opentrades.profit(0) |
262 | plotchar(unrealizedPnL, "Unrealized P&L", "", location.top) // logString |
Travelled to 1 computer(s): mqqgnosmbjvj
No comments. add comment
Snippet ID: | #1036597 |
Snippet name: | Mystery Strategy [Pine Script] |
Eternal ID of this version: | #1036597/2 |
Text MD5: | 987925489f1be74cd7d5a725bef3a4e5 |
Author: | stefan |
Category: | pine script |
Type: | Document |
Public (visible to everyone): | Yes |
Archived (hidden from active list): | No |
Created/modified: | 2023-04-23 16:22:16 |
Source code size: | 11500 bytes / 262 lines |
Pitched / IR pitched: | No / No |
Views / Downloads: | 190 / 46 |
Version history: | 1 change(s) |
Referenced in: | [show references] |