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

buying at limit logic issue #700

Open Valerielucro opened 2 years ago

Valerielucro commented 2 years ago

the strategy is long only. the logic is as such: when price is over 50ema put a limit at the 50ema with tp and sl being 4 percent higher and lower than ema.

and looking at the results it works for the most part but then suddenly there are a few trades that randomly happen under 50ema(as a market order). is this a logic problem?

if not more confusing, sometimes the order is filled at the low of a candle? either a limit or market order, how can it be filled on candle lows?

I'd appreciate your help.

import numpy as np
import pandas as pd
from backtesting import Backtest , Strategy
import pandas_ta as ta
import backtesting
backtesting.set_bokeh_output(notebook=False)
import talib 

class limitonema(Strategy):
    ema = 50
    def init(self):
        self.ema = self.I(talib.EMA, self.data.Close, timeperiod=self.ema)
    def next(self):
        price = self.data.Close[-1]
        ema = self.ema[-1]
        if not self.position and price > ema:
            self.buy(limit=ema, sl=ema*0.96, tp=ema*1.04)

bt = Backtest(df, limitonema, cash=100)
stats=bt.run()
stats
bt.plot()

ss1

in the first picture as you see, after a trade was closed at loss two more longs were opened after eachother.

ss2

in the second picture limit was opened at candle low.

I'd appreciate your help.

kernc commented 2 years ago

in the first picture as you see, after a trade was closed at loss two more longs were opened after eachother.

        if not self.position and price > ema:
            self.buy(limit=ema, sl=ema*0.96, tp=ema*1.04)

Try to add and not self.orders to the condition, or for order in self.orders: order.cancel() above it. Otherwise multiple orders are placed until one of them turns into an open trade. I assume this is the underlying cause of the issues you observe.