Get startedGet started for free

Using add.rule() to implement an exit rule

Welcome to the chapter on rules! While rules in quantstrat can become very complex, this chapter will fill in many of the details for you to help you develop an understanding of the actual mechanics of rules. Rules are the final mechanic in the trinity of quantstrat mechanics -- indicators, signals, and rules. Rules are a way for you to specify exactly how you will shape your transaction once you decide you wish to execute on a signal.

Throughout this chapter, you will continue working the strategy developed in earlier chapters (strategy.st). Given that there are three rules to the strategy (two exit rules and one entry rule), there will be a handful of exercises to build up some intuition of the mechanics of rules.

This exercise will introduce you to the add.rule() function, which allows you to add customized rules to your strategy. Your strategy from earlier chapters (strategy.st) is preloaded in your workspace.

This exercise is part of the course

Financial Trading in R

View Course

Exercise instructions

  • Take a look at the add.rule() call in your workspace. For now, don't worry about the numerous arguments.
  • Generate an exit rule using add.rule() by setting the type argument to exit.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Fill in the rule's type as exit
add.rule(strategy.st, name = "ruleSignal", 
         arguments = list(sigcol = "filterexit", sigval = TRUE, orderqty = "all", 
                        ordertype = "market", orderside = "long", 
                        replace = FALSE, prefer = "Open"), 
         type = "___")
 
Edit and Run Code