Custom Labels/Indicator with events from a strategy
-
I developed a strategy, and i would like to visually view specific "events". The logic of determining the events can be found in the strategy. in other words: In the strategy i have all the if statements in order to determine the exact time that i want to see this event on the graph.
Is it possible to add labels on bars, from the strategy?
Alternatively, and this is not so pretty solution but it will work, i think about developing a custom indicator and change it from 0 to 1 for just 1 bar when this event occurs, but i'm not sure how to do it from the strategy itself (i don't want to duplicate the entire logic of the strategy to a new indicator)
How can i do that?
Do you have any code sample for that? -
Write an observer.
Code samples -
https://github.com/mementum/backtrader/tree/master/backtrader/observers -
Thanks, i see that observers can display events like buys/sells. But how do i signal into an observer from the strategy itself? how can i code something like this?
if (condition): myobserver.event1[0]=1 #change value in the observer somehow
is it possible to do so from the strategy?
I don't want to duplicate the entire if-logic to the observer just to display a value.I will also mention that i do see a specific case that it is possible: in the Observers example i see the OrderObserver that displays information about orders, but it is only because the strategy generates orders and the observer catches them using the next() function. but what about just any events, without generating orders? just generating the event from the strategy?
-
OK i found a solution
Observer can access the strategy using self._owner so we can do the following:in the Observer, we listen to anything inside an self._owner.events array (i just made up the name .events):
def next(self): while len(self._owner.events)>0: event,value = self._owner.events.pop(0) getattr(self.lines,event)[0]=value
and in the Strategy, we just send events:
def __init__(self): self.events=[] if (CONDITION): self.events.append(["event_x",1])
Note that event_x must be the name of a line defined in the observer.
-
if you define
self.events
in the strategy asbt
line instead of the list, than in the observer'snext()
its values can be accessed simplylast_event_value = self._owner.events[0]
-
Here is the link to observer I wrote to plot stop and take prices defined as
self.sl_price
andself.tp_price
in the strategy - https://community.backtrader.com/post/1856