rquantstrat

Quantstrat dynamic order sizing in percents


I want to set order size not in absolute values in lots or dollars but in percents. E.g. I set ordersize <- 0.3 and then the necessary number of lots is calculated as 30% of current equity. Should I use osMaxPos / osMaxDollar or write a custom sizing function somehow?

add.rule(
  strategy.st, name = 'ruleSignal',
  label = 'EnterLONG', type = 'enter',
  arguments = list(
    sigcol = signal$long$enter$label, sigval = TRUE,
    replace = TRUE, orderset = 'ocolong', orderqty = 1,
    ordertype = 'market', orderside = 'long'
  )
)
add.rule(
  strategy.st, name = 'ruleSignal',
  label = 'ExitLONG', type = 'exit',
  arguments = list(
    sigcol = signal$long$exit$label, sigval = TRUE,
    replace = TRUE, orderset = 'ocolong', orderqty = 'all',
    ordertype = 'market', orderside = 'long'
  )
)

Solution

  • For those as excited as i am, here's a solution:

    I found a perfect beginning in creating custom order sizing function here, Tim Trice referenced to comments section in Ilya Kipnis' blog. Also i found out that a portfolio needs to be updated to get actual equity in a Joshua Ulrich's answer.

    leverage <- 10 # 1:10
    tradeSize <- 0.3 # 30%
    osFixedPercent <- function(timestamp, orderqty, portfolio, symbol, ruletype, ...) {
      if(!exists("tradeSize")) stop("You must set trade size")
    
      updatePortf(portfolio)
      portfolio <- getPortfolio(portfolio)
      equity <- initEq + sum(portfolio$summary$Period.Realized.PL)
    
      ClosePrice <- as.numeric(mktdata[timestamp,]$close)
      maxPos <- equity * tradeSize
      initialMargin <- ClosePrice / leverage
      orderqty <- sign(orderqty) * floor(maxPos / initialMargin)
    
      return(orderqty)
    }