For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See:

Not all available trades taken

  • Hi there,

    I'm a newbie to algo trading and am running into some problems. I've been trying to backtest a trend-following strategy where I enter if the EMA50 > EMA200 and when the CCI20 crosses the -100. Sell when EMA50 and EMA200 cross lower.

    The problem is that backtrader is only taking some trades and not others for some reason. Can someone please help explain why this is the case and how I can solve this?

    Thanks, Howard

    Here is my code for the strategy:

    class maCross(bt.Strategy):
    For an official backtrader blog on this topic please take a look at:
    oneplot = Force all datas to plot on the same master.
    params = (
    ('ema50', 50),
    ('ema200', 200),
    ('cci20', 20),
    ('oneplot', True)
    def __init__(self):
        Create an dictionary of indicators so that we can dynamically add the
        indicators to the strategy using a loop. This mean the strategy will
        work with any number of data feeds.
        self.inds = dict()
        for i, d in enumerate(self.datas):
            self.inds[d] = dict()
            self.inds[d]['ema50'] = bt.indicators.ExponentialMovingAverage(
                d.close, period=self.params.ema50)
            self.inds[d]['ema200'] = bt.indicators.ExponentialMovingAverage(
                d.close, period=self.params.ema200)
            self.inds[d]['cci20'] = bt.indicators.CommodityChannelIndex(
            self.inds[d]['crossUp'] = bt.indicators.CrossOver(self.inds[d]['cci20'], -100)  # crossup = 1
            self.inds[d]['EMAcross'] = bt.indicators.CrossOver(self.inds[d]['ema50'], self.inds[d]['ema200']) #crossdown = -1
            if i > 0:  # Check we are not on the first loop of data feed:
                if self.p.oneplot == True:
                    d.plotinfo.plotmaster = self.datas[0]
    def prenext(self):
    def next(self):
        for i, d in enumerate(self.datas):
            dt, dn =, d._name
            pos = self.getposition(d).size
            if not pos:  # no market / no orders
                if self.inds[d]['ema50'] >= self.inds[d]['ema200']:
                    if self.inds[d]['crossUp'][0] == 1:
              , size=1000)
                if self.inds[d]['EMAcross'][0] == -1:
    def notify_trade(self, trade):
        dt =
        if trade.isclosed:
            print('{} {} Closed: PnL Gross {}, Net {}'.format(
                round(trade.pnl, 2),
                round(trade.pnlcomm, 2)))

  • Maybe sometime you don't have enough money to buy 1000 shares? Just a first guess.

  • @ab_trader That was actually it haha. Thanks for that. I'm literally just starting out and it's really tough.

    But cheers for the assistance, very much appreciated.

Log in to reply