Skip to content

position.close() and stop loss features #1018

Answered by peacerider
huytradingz asked this question in Q&A
Discussion options

You must be logged in to vote

Hi,

Thank you for your explanation. I understood.

Your trailing stop is not working.
Once the order (buy or sell) is done, the stop loss of backtesting.py "sl" is not changed until the position is closed.

If you want to change the stop loss level to always be 5% of price.
You need to change the "sl" parametor of "trades".
https://kernc.github.io/backtesting.py/doc/backtesting/backtesting.html#backtesting.backtesting.Strategy.trades

Example

# set a pl/tp (trailing stop)
if len(self.trades) > 0 and self.trades[0].is_long:
    self.trades[0].sl = price - price*self.stop_loss/100
    self.trades[0].tp = price + price*self.stop_loss/100

elif len(self.trades) > 0 and self.trades[0].is_short:
 …

Replies: 1 comment 7 replies

Comment options

You must be logged in to vote
7 replies
@huytradingz
Comment options

@peacerider
Comment options

@huytradingz
Comment options

@peacerider
Comment options

Answer selected by huytradingz
@huytradingz
Comment options

@huytradingz
Comment options

@peacerider
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants