refining trailing stop loss in simple trend following strategy
Im after some help with the trailing stop loss functionality in quanstrat.
I have written a simple script that uses EMAs as a trend filter, enters
positions based on breakouts from Donchian Channels and rides the position
with a trailing stop loss based on ATR.
The script runs ok but Ive run into the following problems trying to refine
this strategy in quantstrat.
1. When specifying the ATR lookback period, anything above n=1 generates an
error "Error in if (threshold > 0) threshold = -threshold :
missing value where TRUE/FALSE needed"
Can anyone explain whats going on here? I'd like to set the look back
window much further.
Also - is the ATR stop loss working as it should? This seems to hinge on
the threshold part of the 'ruleSignal' function. Could anyone explain how
this part works? I could not find any documentation.
2. Ideally, I want the ATR stop loss to only move in the direction of the
winning position. E.g. if we are long and the position moves in our favour
then the stop moves up with the Close - 2*ATR band. However, if the price
moves down I want the ATR to remain fixed at the last highest value,
rapidly closing out the winning position. This what I currently do manually
but would love to have a way of automating it. Im struggling to think of a
way to do this within the quantstrat framework.
Below I copy a reproducible version of the script.
Any guidance would be gratefully received.
start_date <- Sys.Date() -365
end_date <- Sys.Date()
init_equity <- 1e6
tradesize <- 100
adjustment <- TRUE
# stock data
symbols <- c("MSFT", "IBM") #symbols used in our backtest