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.06k stars 990 forks source link

ValueError: Short orders require: TP (1890.425) < LIMIT (1886.10523) < SL (1890.455) #1061

Open anugrah797 opened 10 months ago

anugrah797 commented 10 months ago

Expected Behavior I expect the backtesting strategy MyCandlesStrat to execute buy and sell orders with the calculated stop-loss (SL), take-profit (TP), and limit values without encountering a ValueError.

Actual Behavior When executing the backtesting strategy with the provided code, I encounter the following ValueError: Short orders require: TP (1890.425) < LIMIT (1886.10523) < SL (1890.455)

Steps to Reproduce 1.Import the required libraries and data. 2.initialize the backtesting strategy MyCandlesStrat as shown in the provided code. 3.Run the backtesting strategy by calling the next() method.

from backtesting import Strategy

class MyCandlesStrat(Strategy): def init(self): super().init() self.signal1 = self.I(SIGNAL) # You need to define SIGNAL or replace it with a concrete value

Initialize any additional variables or data you need here

def next(self):
    super().next()
    signal1 = self.signal1[-1]  # Change data.signal to self.signal1
    if signal1 == 1:
        sl1 = round(self.data.High[-1] - 4e-5, 5 ) # Calculate Stop Loss based on candle high and 4 pips
        tp1 = round(self.data.Close[-1] + 4e-5,5 ) # Calculate Take Profit based on candle close and 4 pips
        self.buy(sl=sl1, tp=tp1)
    elif signal1 == 2:
        sl2 = round(self.data.Low[-1] - 4e-5, 5)
        tp2 = round(self.data.Close[-1] + 4e-5, 5)
        limit2 = (tp2 + sl2) / 2  # Set the limit between tp2 and sl2
        self.sell(sl=sl2, tp=tp2, limit=limit2)  # Use sl2, tp2, and limit2 in the order
businessman1929 commented 2 months ago

I am having the same issue.

MarcinKamil84 commented 3 weeks ago

For 'sell' orders SL and TP should be reversed, as far as I'm aware. This should make your TP lower than LIMIT - as expected.

But even so I'm still getting this error unless i set SL and TP far enough from the last closing price: * 1.01:

https://github.com/Goblincomet/forex-trading-backtest/commit/77a0e424f4a1c9a8383c64f368d8357ebc81f6ca

If that's the case, I find 1% is much too harsh restriction in case of day trading for example. But I realize module is not made with daytrading in mind.