kernc / backtesting.py

:mag_right: :chart_with_upwards_trend: :snake: :moneybag: Backtest trading strategies in Python.
https://kernc.github.io/backtesting.py/
GNU Affero General Public License v3.0
5.5k stars 1.07k forks source link

How to take partials using close() or sell() methods #1180

Open danielwang730 opened 5 days ago

danielwang730 commented 5 days ago

Hi,

Apologies in advance if I'm not following convention for submitting this issue, but I had a question about taking partials: specifically, is it possible to do so at an exact price specified?

For example (using made-up numbers), if I buy 20 shares of MSFT at 9:40 AM at $100/share, I want to partial (take profit) 50% if it hits exactly $102.31. Let's say at 9:41 AM the OHLC values are {O: $101, H: $104, L: $100.5, C: $102.8}, which means the $102.31 figure is met. How would I now sell 10 shares of MSFT at $102.31 exactly?

I noticed that when using SL or TP in Strategy.buy(), it would get the exact price, but I only want to take a partial, and not the whole thing. For comparison, when using TradingView's platform, their Strategy.exit() function gives options for partial amount, when to partial, etc., and it hits precisely at the specified price. Is there a way to do it here as well?

Thanks, Daniel

ferromariano commented 3 days ago

ES

La funcionalidad de configurar tu TP parcial por defecto, No existe.

Pero me parece que podes simularlo haciendo un seguimiento de la orden

Ejemplo:

EN

The functionality to configure your partial TP by default does not exist.

But I think you can simulate it by tracking the order

Example:

class MSFT102(Strategy):

    def init(self):
      ....

    def buyLimitPartialTP(self, price: float, tp_price: float, tp_partial_price: float, size: float, tp_partial_size_perce: float):
        tp_partial_size = size*tp_partial_size_perce
        tp_size         = size-tp_partial_size

        self.buy(limit=price, tp=tp_price,         size=tp_size)
        self.buy(limit=price, tp=tp_partial_price, size=tp_partial_size)

    def next(self):
        self.buyLimitPartialTP(price=100, tp_price=105, tp_partial_price=102.5, size=20, tp_partial_size_perce=0.5)