How to set a stoploss in vectorbt based on the number of ticks or price per contract

688 views Asked by At

There's an options to add tp_stop or sl_stop on vbt.Portfolio.from_signals which is percent based.

sl_stop : array_like of float Stop loss. Will broadcast.

A percentage below/above the acquisition price for long/short position. Note that 0.01 = 1%.

I would like to exit based on a move of n price ticks or n dollars per contract. For example if price moves 50 ticks in against me then exit.

1

There are 1 answers

0
chrbal On

I can at least point you in the right direction, though I can't answer fully.

You need to check out vectorbt's "adjust_tp_func_nb" and "adjust_sl_func_nb".

When asked about how to create a take profit rule that is more elaborate than just a static percentage, vectorbt's author has said "To add a further condition ... you need to use adjust_tp_func_nb."

Similarly, you can create custom stop loss logic with "adjust_sl_func_nb".

See vectorbt's docs

And the author's answer I mentioned

Edit: I found an example that is close to your scenario, at the first link, here. Look for "We can implement our own stop loss or take profit, or adjust the existing one at each time step. Let's implement stepped stop-loss:"

You will see an example like:

>>> @njit
... def adjust_sl_func_nb(c):
...     current_profit = (c.val_price_now - c.init_price) / c.init_price
...     if current_profit >= 0.40:
...         return 0.25, True
...     elif current_profit >= 0.25:
...         return 0.15, True
...     elif current_profit >= 0.20:
...         return 0.07, True
...     return c.curr_stop, c.curr_trail

>>> close = pd.Series([10, 11, 12, 11, 10])
>>> pf = vbt.Portfolio.from_signals(close, adjust_sl_func_nb=adjust_sl_func_nb)
>>> pf.asset_flow()
0    10.0
1     0.0
2     0.0
3   -10.0  # 7% from 12 hit
4    11.0
dtype: float64