Reputation: 11
My buying conditions for taking long position are
Place order between 09:15 to 13:30
opening price of recent candle greater than EMA(20)
I will go for long postion when price crosses the high of last 7 candles
After placing a buy order with strategy.entry, I have three targets (+20, +40, +60) and one stop loss price (-20). I would like to exit order with following conditions
- Sell whole quantity at Stop Loss (-20) or Sell 25% at Target 1 (+20) and Trail SL to buy price (0)
- Sell remaining 75% at buy price (trailed SL) (0) or Sell another 25% at Target 2 (+40) and Trail SL to Target 1 (+20)
- Sell final 50% at Target 1 (trailed SL) (+20) or Target 3 (+60)
In view of the above please review the code and tell me the what is going on wrong here?
//@version=4
strategy("BreakOutStrategy", overlay=true)
length = input(title="Length", type=input.integer, minval=1, maxval=1000, defval=7)
upBound = highest(high, length)
downBound = lowest(low, length)
timeFilter = (year == 2019) and (time > 0915 and time < 1330)
c1 = (open>ema(hl2,20))
buy_entry = (c1==true) and (timeFilter==true)
strategy.entry("buy", strategy.long, 4, stop=upBound + syminfo.mintick, when=buy_entry and strategy.position_size <= 0, comment="BUY")
strategy.exit("bracket1", "buy", stop=20, when=strategy.position_size==4)
strategy.exit("bracket2", "buy", 1, profit=20, when=strategy.position_size==4)
strategy.exit("bracket3", "buy", stop=0, when=strategy.position_size==3)
strategy.exit("bracket4", "buy", 1, profit=40, when=strategy.position_size==3)
strategy.exit("bracket5", "buy", 2, profit=60, stop=-20, when=strategy.position_size==2)
Upvotes: 0
Views: 891
Reputation: 2821
Let my make some clarification by your code.
First of all, time
returns amount of milliseconds elapsed from Unix epoch, so from 1 January 1970 and your code time > 0915
says, that you expect time be greater than 915 ms from 1970. Thereby it won't work as you want. If you want time from 9:15, then you should do it as you did with year:
timeFilter = (year == 2019) and (hour > 9 or (hour == 9 and minute > 15)) and (hour < 13 or (hour == 13 and minute < 30))
Next, for trailing stop and part exit, I've made a little example:
//@version=4
strategy("BreakOutStrategy", overlay=true)
if close < ema(close, 20)
strategy.entry("buy", strategy.long, qty = 4)
strategy.exit("exitId", "buy", trail_offset=200, trail_price=strategy.position_avg_price, profit=2000, qty_percent=25)
strategy.exit("exitId2", "buy", trail_offset=400, trail_price=strategy.position_avg_price, profit=4000, qty_percent=25)
strategy.exit("exitId3", "buy", trail_offset=800, trail_price=strategy.position_avg_price, profit=6000, qty_percent=50)
That's not exactly what you want, but I think that's enough to start with.
Upvotes: 1