Reputation: 21
I am trying to make a system in python with 1 precise buy condition and 3 possible sell conditions. However, I can't make sell conditions work as I would like to.
I use simple moving averages with 8 and 50 periods AND 10% stop loss for buying. I don't face with any problem there. System buys when they crossover.
My sell conditions are basically occurs when moving average 50 crosses moving average 8. However, I would like to sell different position sizes if the signal occurs when the price is below the entry price or not.
I mean, assume that I bought at the price 50 (when mov8 and 50 crosses)
When mov 50 and mov8 crosses (which is sell signal), I would like to check if the price is below the entry price or not.
If the price is below than the entry price when the selling signal occurs, I would like to close my all position ( first possible sell condition). However, if the price is above than the entry price, I would like to sell only %30 of my position, and keep the trade until mov50 and mov8 crosses next time ( second possible sell condition). If mov50 and mov8 crosses again, then I would like to close my rest of position, which is 70%, ( third possible sell condition).
But as you can see on my trades that I backtested, my second and third conditions don't work well.
Firstly, I defined moving averages and stop loss here,:
class Z(Strategy):
day1 = 8
day2 = 50
sprice=0.1
def init(self):
self.signal1 = self.I(SIGNAL)
self.ma1 = self.I(talib.SMA, self.data.Close, self.day1)
self.ma2 = self.I(talib.SMA, self.data.Close, self.day2)
self.long_position1 = False
self.long_position2 = False
self.long_position3 = False
self.long_position4 = False
self.entry_price = 0
Here is my buy condition:
def next(self):
if not self.position:
if crossover(self.ma1, self.ma2):
sl1 = self.data.Close[-1] - self.data.Close[-1] *self.sprice
self.buy(sl=sl1)
self.entry_price = self.data.Close[-1]
Here is my first sell condition, which closes all position:
if self.position:
if crossover(self.ma2, self.ma1):
if (self.data.Close <= self.entry_price):
self.position.close()
And here is where I would like to sell 30% of my position size. I used here boolean variables so I aimed that if this happens, it can only go to my third sell condition. :
else:
self.sell(size=0.3)
self.long_position1 = False
self.long_position2 = True
self.long_position3 = True
self.long_position4 = False
if not self.long_position1 and self.long_position2 and self.long_position3 and not self.long_position4:
if crossover(self.ma2, self.ma1) :
self.position.close()
self.long_position1 = False
self.long_position2 = False
self.long_position3 = False
self.long_position4 = False
a=Backtest(K,Z,cash=10000,trade_on_close=True,margin=0.6,exclusive_orders=True)
Here is my trades, When it sells %30 of the position, It keeps sell somehow. But It should happens only once and then go through the third condition.
Upvotes: 0
Views: 238