An indicator that knows if I have a position or not
-
I am building an indicator that does one thing if I'm not in the trade, and does another if I'm in.
Is it possible for a subclass of
Indicators
to access theposition
attribute of theStrategy
?Of course, this indicator cannot be pre-computed, but is emits data as the backtest progresses.
The following code surely raises
AttributeError: 'Lines_LineSeries_LineIterator_DataAccessor_Indicat' object has no attribute 'position'
class CustomIndicator(bt.Indicator): lines = ('custom_indicator',) params = (('period', 14), ) def next(self): if self.position: self.lines.custom_indicator[0] = True and is_something_else_true() self.do_something() else: self.lines.custom_indicator[0] = False self.do_nothing()
-
The strategy can turn on/off a parameter of the indicator according to whether in trade or not. Have a look at the dynamic indicator example
https://www.backtrader.com/blog/posts/2018-02-06-dynamic-indicator/dynamic-indicator.html -
@momentum Thanks! I would add that
Cerebro
will have to be instantiated withCerebro(runonce=False)
. Otherwise, if I use the default, i.e.runonce=True
, all indicators would be precalculated all the way to the end, and they would not be able to observe if a trade is open or not.Reference for the
runonce
argument:
https://www.backtrader.com/docu/cerebro.html?highlight=vectorize#backtrader.Cerebro -
I even like better the
_nextforce = True
pointed out to me by @backtrader some time ago.class CustomIndicator(bt.Indicator): _nextforce = True ...