Hello. I programmed a very simple MA crossover strategy, however the short signals are only closing the long positions, not opening new short positions. I used self.sell() for that, and changing it for self.close() will yield the same result. This is the code:
from datetime import datetime
import backtrader as bt
class MACross(bt.Strategy):
params = dict(
pfast=10,
pslow=30
)
def log(self, text, date=None):
date = date or self.datas[0].datetime.datetime(0)
print(f'{date.isoformat()}: {text}')
def __init__(self):
self.bar_executed = len(self)
self.order = None
self.comm = None
ema_short = bt.ind.EMA(period=self.p.pfast)
ema_long = bt.ind.EMA(period=self.p.pslow)
self.crossover = bt.ind.CrossOver(ema_short, ema_long)
def notify_order(self, order):
order.executed.comm = round(order.executed.comm, 2)
order.executed.price = round(order.executed.price, 2)
if order.status in [order.Submitted, order.Accepted]:
return
elif order.status in [order.Completed]:
if order.isbuy():
self.log(f'Entry long, price: {order.executed.price}; commission: {order.executed.comm}')
elif order.issell():
self.log(f'Entry short, price: {order.executed.price}; commission {order.executed.comm}')
elif order.status in [order.Margin]:
self.log('Order Margin')
self.order = None
def notify_trade(self, trade):
trade.pnlcomm = round(trade.pnlcomm, 2)
if not trade.isclosed:
return
else:
self.log(f'Net profit: {trade.pnlcomm}')
def next(self):
if self.crossover > 0:
self.buy()
if self.crossover < 0:
self.sell()
if __name__ == "__main__":
def print_sqn(analyzer):
sqn = round(analyzer.sqn, 2)
print(f'SQN: {sqn}')
start_cash = 10000
commission_percentage = 0.075
cerebro = bt.Cerebro()
data = bt.feeds.GenericCSVData(
dataname='BTCUSDT_1h.csv',
fromdate=datetime(2020, 1, 1),
# todate=datetime(2020, 5, 8),
timeframe=bt.TimeFrame.Minutes,
compression=60,
dtformat='%Y-%m-%d %H:%M:%S',
openinterest=None
)
cerebro.adddata(data)
cerebro.broker.setcash(start_cash)
cerebro.addsizer(bt.sizers.PercentSizer, percents=99)
cerebro.broker.setcommission(commission=(commission_percentage / 100), margin=False)
cerebro.addstrategy(MACross)
cerebro.addanalyzer(bt.analyzers.SQN)
strategies = cerebro.run()
current_strategy = strategies[0]
port_value = round(cerebro.broker.getvalue(), 2)
pnl = round(port_value - start_cash, 2)
print(f'Final value: ${port_value}')
print(f'P/L: ${pnl}')
print_sqn(current_strategy.analyzers.sqn.get_analysis())
# cerebro.plot(style='candle')
What should I do to get short positions?