Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Help with exit strategy part of code #612

Open
azimgiant opened this issue Aug 31, 2023 · 0 comments
Open

Help with exit strategy part of code #612

azimgiant opened this issue Aug 31, 2023 · 0 comments

Comments

@azimgiant
Copy link

azimgiant commented Aug 31, 2023

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant