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

buying at limit logic issue

Open Valerielucro opened this issue 2 years ago • 1 comments

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.

Valerielucro avatar Jul 29 '22 09:07 Valerielucro

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.

kernc avatar Jul 30 '22 13:07 kernc