hi guys,
first of all - I cannot even imagine that software like backtrader is free - so much work and development like - big thank to creator!
anyway, I'm beginner in python and playing with backtrader and I have working code, but it doesn't work :) cannot find why -> I want to SELL when close price is lower than was buy price + 5 percent.
my code is very simple and temp is used to store buy price:
class TestStrategy(bt.Strategy):
params = ( ('pfast', 20), ('pslow', 50), ('order_percentage', 0.95), ('temp', 0.00))
def __init__(self):
sma1, sma2 = bt.ind.SMA(period=self.p.pfast), bt.ind.SMA(period=self.p.pslow)
self.crossover = bt.indicators.CrossOver(sma1,sma2)
def next(self):
#print(self.data.close[0]) #last close price
if self.position.size == 0:
if self.crossover > 0:
amount_to_invest = (self.params.order_percentage * self.broker.cash)
self.size = math.floor(amount_to_invest / self.data.close)
print(f"Buy {self.size} for {self.data.close[0]} USD")
self.params.temp = self.data.close[0]
self.buy(size=self.size)
if self.position.size > 0:
#HERE IS UNKNOWN BUG - it doesn't sell with 5% profit
if self.params.temp < self.data.close[0] * 1.05:
self.close()
print(f"SELL {self.size} for {self.data.close[0]} USD")
on apple data it looks like this:
Buy 129 for 73.45 USD
SELL 129 for 72.2675 USD
Buy 80 for 119.03 USD
SELL 80 for 118.69 USD
so it sell for not +5% but even cheaper -> what is wrong? can you help me?
and also, is there any better way to store buy price as I'm doing? (I believe my approach is not very clean code..)
thank you in advance