<reponame>super6liu/technical-analysis-julian<filename>src/analyzer/backtrader_wrapper/base_strategy.py<gh_stars>0
from backtrader import Strategy
from src.logger import WithLogger


class BaseStrategy(Strategy, WithLogger):
    def __init__(self, verbose: bool = False):
        WithLogger.__init__(self)
        self.verbose = verbose

        # Keep a reference to the "close" line in the data[0] dataseries
        self.dataclose = self.datas[0].close

        # To keep track of pending orders
        self.order = None
        self.qualifiers = self.qualifier(self.datas[0])

    def notify_order(self, order):
        if order.status in [order.Submitted, order.Accepted]:
            # Buy/Sell order submitted/accepted to/by broker - Nothing to do
            return

        # Check if an order has been completed
        # Attention: broker could reject order if not enough cash
        if order.status in [order.Completed]:
            if order.isbuy():
                self.log('BUY EXECUTED, %.2f' % order.executed.price)
            elif order.issell():
                self.log('SELL EXECUTED, %.2f' % order.executed.price)

            self.bar_executed = len(self)

        elif order.status in [order.Canceled, order.Margin, order.Rejected]:
            self.log('Order Canceled/Margin/Rejected')

        # Write down: no pending order
        self.order = None

    def next(self):
        # Simply log the closing price of the series from the reference
        # print('Close, %.2f' % self.dataclose[0])

        # Check if an order is pending ... if yes, we cannot send a 2nd one
        if self.order:
            return

        # Check if we are in the market
        if not self.position:

            # Not yet ... we MIGHT BUY if ...
            if self.shouldBuy(self.data, self.qualifiers):

                # BUY, BUY, BUY!!! (with default parameters)
                self.log('BUY CREATE, %.2f' % self.dataclose[0])

                # Keep track of the created order to avoid a 2nd order
                self.order = self.buy()

        else:
            # Already in the market ... we might sell
            if self.shouldSell(self.data, self.qualifiers):
                # SELL, SELL, SELL!!! (with all possible default parameters)
                self.log('SELL CREATE, %.2f' % self.dataclose[0])

                # Keep track of the created order to avoid a 2nd order
                self.order = self.sell()

    def stop(self):
        print("%s stop at %f" % (self.params._getkwargs(), self.broker.getvalue()))

    def log(self, txt, dt=None, force: bool = False):
        ''' Logging function fot this strategy'''
        if False :#force or self.verbose:
            dt = dt or self.datas[0].datetime.date(0)
            self.logger.debug('%s, %s' % (dt.isoformat(), txt))
