Quanstrat strategy - error
Asked Answered
C

2

9

My quanstrat strategy returns an error which I didnt find being discussed yet.

Strategy is very simple: calculate rolling sum over given period of time. If the rolling sum is over some threshold, enter long and submit siultanesouly two oco orders, take-profit and stop loss in the distance of +/- 5%.

The code is:

require("quantstrat")
from <- "2014-09-25"
to <- "2014-10-01"

rm(strategy.st)
try(rm("account.st","portfolio.st"),silent=TRUE)  

.blotter <- new.env()
.strategy <- new.env()

initDate <- as.character(as.Date(from) - 1)
currency("USD")
Sys.setenv(TZ = "UTC")   
symbols <- "data"
stock(symbols, currency = "USD", multiplier = 1)  # Initialisation of the instrument
tradeSize <- 1                                    # Initialisation of trade size
initEq <- 1000                                    # Initialisation of initial equity

strategy.st <- "btc"                              # Initialisation of the strategy
portfolio.st <- "btc"                             # Initialisation of the strategy, must be after strategy
account.st <- "btc"                               # Initialisation of the strategy, must be after strategy and portolio


initPortf(portfolio.st, symbols=symbols, initDate=initDate, currency='USD')
initAcct(account.st, portfolios=portfolio.st, initDate=initDate, currency='USD',initEq=initEq)
initOrders(portfolio.st, initDate=initDate)
strategy(strategy.st, store=TRUE)  

### Parametres
lookBackVol <- 5
thresholdVol <- 20
stopLoss <- -0.05
profitTarget <- 0.05

### Indicators
add.indicator(strategy.st, name = "runSum", arguments = list(x = quote(data$ask.vol), n = lookBackVol), label = "volRunSum")

### Signals
add.signal(strategy.st, name = "sigThreshold", arguments = list(column = "volRunSum", threshold = thresholdVol, relationship = "gte", cross = TRUE), label = "longSig")

### Rules
add.rule(strategy = strategy.st, name = "ruleSignal",
         arguments = list(sigcol = "longSig", sigval = 1,
                          orderqty = tradeSize,
                          ordertype = "market",
                          orderside = "long",
                          replace = FALSE,
                          orderset = "ocolong"
                          ),
         type = "enter",
         label = "enterLong"
        )


add.rule(strategy.st, name = "ruleSignal",
         arguments = list(sigcol = "longSig", sigval = 1,
                          orderqty = "all",
                          ordertype = "stoplimit",
                          orderside = "long",
                          replace = FALSE,
                          tmult = TRUE,
                          threshold = stopLoss,
                          orderset = "ocolong"
           ),
         type = "chain",
         parent = "enterLong",
         label = "stopLossLong",
  )


add.rule(portfolio.st, name = "ruleSignal",
         arguments = list(sigcol = "longSig", sigval = 1,
                          orderqty = "all",
                          ordertype = "limit",
                          orderside = "long",
                          replace = FALSE,
                          tmult = TRUE,
                          threshold = profitTarget,
                          orderset = "ocolong"
           ),
         type = "chain",
         parent = "enterLong",
         label = "profitTargetLong",
  )

 ### Results
results <- applyStrategy(strategy.st, portfolio.st)
View(getOrderBook(portfolio.st)$btc$data)

Data structure is as follows:

> dput(head(data))
structure(c(0, 0.0423759, 0.0299792, 0, 0, 0, 0.0722401, 0.0430572, 
0.1648549, 2.9369966, 0, 0, 0.0722401, 0.0854331, 0.1948341, 
2.9369966, 0, 0, 0, 1, 1, 0, 0, 0, 1, 2, 4, 9, 0, 0, 1, 3, 5, 
9, 0, 0, NA, 408.11, 408.106, 408.106, 408.106, 408.106, 408.11, 
408.111, 408.112, 407.5, 407.5, 407.5, 408.11, 408.111, 408.112, 
407.5, 407.5, 407.5), class = c("xts", "zoo"), .indexCLASS = c("POSIXct", 
"POSIXt"), .indexTZ = structure("UTC", .Names = "TZ"), tclass = c("POSIXct", 
"POSIXt"), tzone = structure("UTC", .Names = "TZ"), index = structure(c(1411596001, 
1411596002, 1411596003, 1411596004, 1411596005, 1411596006), tzone = structure("UTC", .Names = "TZ"), tclass = c("POSIXct", 
"POSIXt")), .Dim = c(6L, 9L), .Dimnames = list(NULL, c("bid.vol", 
"ask.vol", "vol", "bid.freq", "ask.freq", "freq", "bid.price", 
"ask.price", "price")))

It is an xts object showing bid/ask volume/frekvency of trades in one second and the mentioned error says:

[1] "2014-09-24 22:00:17 data 1 @ 407"
Error in dindexOrderProc(openOrderSubset[i, ], mktPrices, curIndex) : 
  no price discernable for limit in applyRules

There doesnt seem to be a problem with order-chain as orderbook contains all three orders with correct prices:

                    Order.Qty Order.Price Order.Type  Order.Side Order.Threshold Order.Status Order.StatusTime      Prefer Order.Set Txn.Fees
2014-09-24 22:00:16 "1"       "407"       "market"    "long"     NA              "closed"     "2014-09-24 22:00:17" "ask"  "ocolong" "0"     
2014-09-24 22:00:17 "all"     "386.65"    "stoplimit" "long"     "-20.35"        "open"       NA                    ""     "ocolong" "0"     
2014-09-24 22:00:17 "all"     "427.35"    "limit"     "long"     "20.35"         "open"       NA                    ""     "ocolong" "0"  

Any ideas?

I somewhere found specifying the limit order price like:

order.price=quote(data$ask.price[timestamp])

but it didn't work out.

Coats answered 23/11, 2014 at 23:29 Comment(4)
Hi Steef, haven't got to the bottom of it yet but hoping this will help. The error message generated is triggered by if (is.na(mktPrice) || is.null(mktPrice)) stop("no price discernable for ", orderType, " in applyRules") The error presents on applyStrategy right?Emblazonry
Hi Olie, I traced the error too and yes, you are right. The error comes from applyStrategy, indicators and signals are correct. I think that the error comes from the order.price statement in limit order rule as my data is not (and cannot be) in OHLC format, so th elimit order does not know where to take the price from. I tried something like order.price=quote(data$ask.price[timestamp]) but it didn't work.Coats
rearrange your data so the prices come first. if you don't specify the price column, e.g. via the prefer argument, then quantstrat will call getPrice, and try to guess. It should be able to detect bid/ask data, but will expect the prices to come before supplementary data in BBO data sets.Buroker
Can you pleae be more specific or provide the solution? I firstly tried to rearrange the columns so as that price, bid.price and ask.price go first, but this did not help and ended with the same error. I then tried to include prefer = "ask.price" to stoploss and takeprofit orers, but it threw the same error too. The onnly difference was that orderbook showed "ask" for enter order and "ask.price" for both exit orders in the column Prefer. Including prefer = "ask.price" to enter order did not help either.Coats
C
1

Removing some columns from mktdata and moving the price column to the very left solved the issue.

Coats answered 26/1, 2015 at 23:10 Comment(0)
R
1

I had the same issue, i found out that i had some N/A's in my "Ask" column.

removing the N/A's fixed the issue na.locf()

Retain answered 10/8, 2015 at 7:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.