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

How could I make force selling when using pre-defined signals?

  • Hi, I'm using pre-defined buy/sell signals for trading as below snippet, but sometimes I need to dynamically handle some situations to force selling. How can I make it? I'm thinking of adding some conditions on the function 'next' in my strategy which imports bt.strategy, but I'm worried about overriding the 'next' function will make my pre-defined signals ignored.

    Here's the snippet how I implemented the signals.

    import backtrader.feeds as btfeeds
    import backtrader as bt
    class MyDataLoader(btfeeds.PandasData):
        lines = ('signal','label',)
        params = (
            ('signal', -1),
            ('label', -1),
        datafields = btfeeds.PandasData.datafields + (['signal','label'])
    class MyStrategy(bt.Strategy):
        def __init__(self):
            self.dataclose = self.datas[0].close
            self.label = self.datas[0].label
            self.signal = self.datas[0].signal
    df['signal'] = pd.Series(predefined_signals, index=df.index)
    # Create a cerebro entity
    cerebro = bt.Cerebro()
    data = MyDataLoader(dataname=df)

  • You may want to share more code if you still want to get an advice. It is not clear how you process your signals in the strategy.

  • @ab_trader Sorry, I forgot to share my strategy code. What I've done is passing my signal into btfeeds.PandasData.datafields and then, initialize 'self.signal' of MyStrategy from the datafields.

  • @MarkWhatson answering your initial question - you need to add conditions for your force selling to __init__ or next() and then issue corresponding orders in the next(). This is all I can say based on what was shown here.

Log in to reply