For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/
self.close() does NOT clear position
-
I'm writing a strategy that it longs Bitcoin if price goes beyond the Bollinger upper band and shorts Bitcoin if price goes below the Bollinger lower band:
class MeanReversionStrategy(bt.Strategy): """Mean Reversion Strategy.""" alias = ('MeanReversion',) params = ( ('price_bb_period', 20), ('price_bb_ndev', 2), ) def __init__(self): self.price_bb = bt.indicators.BBands(self.data.close, period=self.params.price_bb_period, devfactor=self.params.price_bb_ndev) def next(self): if self.data.close > self.price_bb.top: if self.position.size >= 0: if self.position.size > 0: self.close() # close long position assert self.position.size == 0 # FAIL!!! self.sell(price=self.price_bb.top, exectype=bt.Order.Limit) self.buy(exectype=bt.Order.StopTrail, trailpercent=0.1) elif self.data.close < self.price_bb.bot: if self.position.size <= 0: if self.position.size < 0: self.close() # close short position assert self.position.size == 0 # FAIL!!! self.buy(price=self.price_bb.top, exectype=bt.Order.Limit) self.sell(exectype=bt.Order.StopTrail, trailpercent=0.1)
After calling
self.close()
the value ofself.position.size
is not zero, why? -
bt
simulates real life and in real life in order to open or close position, the order is issued by trader, submitted to broker, accepted by broker, and than executed by broker. Last three steps happen before the followingnext()
call, but not during current `next() call.I would recommend to go thru the Docs - Quickstart Guide and read docs more to understand how
bt
operates. -
@ab_trader Thanks, I fixed my code, it works now:
class MeanReversionStrategy(bt.Strategy): """Mean Reversion Strategy.""" alias = ('MeanReversion',) params = ( ('price_bb_period', 20), ('price_bb_ndev', 2), ) def __init__(self): self.price_bb = bt.indicators.BBands(self.data.close, period=self.params.price_bb_period, devfactor=self.params.price_bb_ndev) def next(self): if self.data.close > self.price_bb.top: if self.position.size > 0: self.close() # close long position elif self.position.size == 0: self.sell(price=self.price_bb.top, exectype=bt.Order.Limit) self.buy(exectype=bt.Order.StopTrail, trailpercent=0.1) elif self.data.close < self.price_bb.bot: if self.position.size < 0: self.close() # close short position elif self.position.size == 0: self.buy(price=self.price_bb.top, exectype=bt.Order.Limit) self.sell(exectype=bt.Order.StopTrail, trailpercent=0.1)