TA-Lib / ta-lib-python

Python wrapper for TA-Lib (http://ta-lib.org/).
http://ta-lib.github.io/ta-lib-python
Other
9.56k stars 1.75k forks source link

Help with exit strategy part of code #612

Open azimgiant opened 1 year ago

azimgiant commented 1 year ago

I have a simple code I am testing. Buy when cci crosses above 0 and short when cci crosses below 0. I got that part correctly in the code however I am having trouble with the exit. I want to close out of the position when the closing price goes below sma when in a long position and close out of my short position when closing price goes above sma. When I do bt.plot() the grpah is showing trades where I am still in the position even though the exit conditions have been met. Does anyone know where I am going wrong?

class CCI(Strategy):

sma_window = 11
cci_window = 50
zero = 0
position_open = False

def init(self):
    self.cci = self.I(talib.CCI, self.data.High, self.data.Low, self.data.Close, self.cci_window)
    self.sma = self.I(talib.SMA, self.data.Close, self.sma_window)

def next(self):
    if crossover(self.cci, self.zero):
        if not self.position_open:
            self.buy()
            self.position_open = True

    if self.data.Close < self.sma and self.position_open:
        self.position.close()
        self.position_open = False

    if crossover(self.zero, self.cci):
        if not self.position_open:
            self.sell()
            self.position_open = True

    if self.data.Close > self.sma and self.position_open:
        self.position.close()
        self.position_open = False

image In this picture I entered a long position however I should have exited when the closing price went below sma where I highlighted it blue in the picture