-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathposition_sizing_example
More file actions
56 lines (45 loc) · 2.05 KB
/
position_sizing_example
File metadata and controls
56 lines (45 loc) · 2.05 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
//@version=5
strategy('Test with pos. sizing', overlay=true, initial_capital = 1000, currency = currency.NONE, default_qty_type=strategy.cash, commission_value=0.1, commission_type=strategy.commission.percent)
// *** Parameters ***
bb_length = 30
bb_mult = 1
atr_mult = 2
rrr = 1./3
exposure = 2.
// *** Bollinger Bands ***
bb_stddev = ta.stdev(close, bb_length)
bb_average = ta.sma(close, bb_length)
bb_upper = bb_average + bb_mult * bb_stddev
bb_lower = bb_average - bb_mult * bb_stddev
// *** ATR ***
atr = ta.atr(14)
// *** Signals ***
entry_long = ta.crossover(close, bb_upper)
exit_long = ta.crossunder(close, bb_upper)
entry_short = ta.crossunder(close, bb_lower)
exit_short = ta.crossover(close, bb_lower)
// *** Risk management ***
entry_price = close
stop_loss_price = entry_price - atr_mult * atr
take_profit_price = entry_price + atr_mult * atr / rrr
stop_loss_in_ticks = (entry_price - stop_loss_price) / syminfo.mintick
take_profit_in_ticks = (take_profit_price - entry_price) / syminfo.mintick
// *** Positions ***
if entry_long and strategy.position_size == 0
distance_to_sl = math.abs(entry_price - stop_loss_price)
entry_qty = exposure / 100 * strategy.equity / distance_to_sl
strategy.entry("Long", strategy.long, qty = entry_qty)
strategy.exit("Long", loss = stop_loss_in_ticks, profit = take_profit_in_ticks, comment_loss = "SL Long", comment_profit = "TP Long")
if entry_short and strategy.position_size == 0
distance_to_sl = math.abs(entry_price - stop_loss_price)
entry_qty = exposure / 100 * strategy.equity / distance_to_sl
strategy.entry("Short", strategy.short, qty = entry_qty)
strategy.exit("Short", loss = stop_loss_in_ticks, profit = take_profit_in_ticks, comment_loss = "SL Short", comment_profit = "TP Short")
if exit_long
strategy.close("Long", "Exit Long")
if exit_short
strategy.close("Short", "Exit Short")
// *** Plots ***
plot(bb_upper, color=color.new(#ffb13b, 0), linewidth=1)
plot(bb_average, color=color.new(#b43bff, 0), linewidth=1)
plot(bb_lower, color=color.new(#ffb13b, 0), linewidth=1)