backtesting.py icon indicating copy to clipboard operation
backtesting.py copied to clipboard

Plot SL / TP levels

Open jamhot1 opened this issue 6 years ago • 3 comments

Is there a way to plot Stop loss and Take profit points? or indeed add any such additional plot points for specified data in scatter or line format. Useful for ensuring strategy is operating as per

jamhot1 avatar Mar 29 '20 14:03 jamhot1

You can think of the SL/TP levels as regular overlay indicators.

If you can precompute them in init(), that's probably the preferred option. But if you can't, an alternative is to define an empty indicator (plotted as scatter plot since line plots don't work well with NaN values), and fill it only gradually in next():

class MyStrategy(Strategy):

    def init(self):
        # Initialize an empty SL/TP-level indicator (filled with NaNs) 
        self.sl_level = self.I(lambda: np.repeat(np.nan, len(self.data)), 
                               name='SL level', scatter=True)

    def next(self):
        # Determine actual SL/TP level
        sl_level = ...
        # Enter position with a contingent SL/TP order attached
        self.buy(sl=sl_level)
        # And mark the computed SL/TP level on the SL indicator plot
        self.sl_level[-1] = sl_level        

Above code is untested, but something to the like should work.

kernc avatar Mar 29 '20 23:03 kernc

Brilliant! Thanks Kernc. I was going along those sort of lines but couldn't quite implement the indicator correctly. I guessed it would have to be some sort of logging or custom indicator. Could I ask. Are there any forum pages dedicated to this framework? A place for everyone to exchange tips/questions etc? I really like this lib over the others and would love to see it used more widely.

jamhot1 avatar Mar 30 '20 08:03 jamhot1

BTW, if anyone else is interested. The NP array needs to be made none immutable by adding the code:

self.sl_level.flags.writeable = True 

Many thanks to the dev for pointing me on the right track!

jamhot1 avatar Mar 30 '20 19:03 jamhot1