Exit on the basis BARHELD after entry
-
Hello All,
I am new to BT community and obvious I am stuck with some code logic, I am trying to enter based on 2 period RSI and want exit based on bars held after entry , like I want exit on 2 day of entering the trade basis closing price of second day.
PFA the snippet of code which I am using now
TIA
-
@mukeshcm Try using an iteration counter.
def __init__(self): self.count = 0 # your stuff def next(self): # your trade logic # after you go eg if self.position self.count += 1 if self.count > n: sell
ps.(This would be lot easier to reply to if you enter your code into your question instead of an image. See at the top of the page: For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/
-
Dear @run-out , I checked this but it is not serving purpose if you see the attached code I am incrementing when code goes into buy and reinitializing once sell is done for current buy, code is printing 1 and 0 alternate and if I do not do reinitialization it is printing 1 to 169. My logic of code wants to test that once buy is executed I need to exit second day after the execution means if Buy is executed on Monday it should exit on wednesday.PFA the code
class firstStrategy(bt.Strategy): def __init__(self): self.rsi = bt.indicators.RSI_Safe(self.data.close, period=2) self.count=0 def next(self): if not self.position: if self.rsi <9: self.count +=1 print(self.count) self.buy(size=100) else: if self.rsi>30: self.count=0 print(self.count) self.sell(size=100)
-
@mukeshcm not sure to understand, but if you want an exit based on bar count, why do you test (after the else statement) the rsi and not the bar count ?
-
@emr and of course, you would need to increment the count when position is held in each next loop.
-
@emr , yes you are right that I need to increment the counter and that I am doing in my attached code , purpose of code snippet was to mention that even incrementing the counter it was not working as I explained in my post. But a post of @ab_trader helped me out to achieve my desired logic based on self.bar_executed. Now I am stuck with other issues...will post it after all my attempts are done.