I'm trying to implement a strategy that updates limit orders on every bar. The strategy will always open a new position when closing an old position, so I always need an exit order as well as an entry order on the books.
If I use replace=T
, my exit order erases my entry order, which means it would take two bars to change positions instead of one. If I use replace=F
, then it keeps adding orders, leaving old orders unchanged. Neither is the behavior I'm looking for.
Is there a way to modify open orders by label? For example, change price for both my limit order labeled ShortExit
as well as my limit order labeled LongEntry
?
require(quantstrat)
stock.str='IBM' # what are we trying it on
currency('USD')
stock(stock.str,currency='USD',multiplier=1)
startDate='2006-12-31'
initEq=1000000
strat.st<-portfolio.st <-account.st <- 'bbands'
rm.strat(portfolio.st)
rm.strat(account.st)
strategy(strat.st, store=TRUE)
initPortf(portfolio.st, symbols=stock.str)
initAcct(account.st,portfolios='bbands')
initOrders(portfolio=portfolio.st)
addPosLimit(portfolio.st, stock.str, startDate, 100, 1 ) #set max pos
kchannel <- function(HLC,n){
center <- SMA(Cl(HLC),n)
atr <- ATR(HLC,n)$atr
up <- center + 2*atr
dn <- center - 2*atr
mom <- momentum(center)
out <- merge(center,atr,up,dn,mom)
colnames(out) <- c("center","atr","up","dn","mom")
return(out)
}
add.indicator(strategy = strat.st,
name = "kchannel",
arguments = list(HLC = quote(HLC(mktdata)),
n=n
),
label='kc')
add.signal(strategy = strat.st,
name="sigThreshold",
arguments = list(column="mom.kc",
thresh=0,
relationship="gt"),
label="long")
add.signal(strategy = strat.st,
name="sigThreshold",
arguments = list(column="mom.kc",
thresh=0,
relationship="lt"),
label="short")
add.rule(strategy = strat.st,name='ruleSignal',
arguments = list(sigcol="long",
sigval=TRUE,
orderqty=200,
orderside="long",
replace=T,
ordertype='limit',
prefer="dn",
osFUN=osMaxPos),
type='enter',
label="LongEntry")
add.rule(strategy = strat.st,name='ruleSignal',
arguments = list(sigcol="short",
sigval=TRUE,
orderqty=-200,
orderside="short",
replace=T,
ordertype='limit',
prefer="up",
osFUN=osMaxPos),
type='enter',
label="ShortEntry")
add.rule(strategy = strat.st,name='ruleSignal',
arguments = list(sigcol="short",
sigval=TRUE,
orderqty="all",
orderside="long",
replace=T,
ordertype='limit',
prefer="dn",
osFUN=osMaxPos),
type='exit',
label="LongExit")
add.rule(strategy = strat.st,name='ruleSignal',
arguments = list(sigcol="long",
sigval=TRUE,
orderqty="all",
orderside="short",
replace=T,
ordertype='limit',
prefer="up",
osFUN=osMaxPos),
type='exit',
label="ShortExit")
getSymbols(stock.str,from=startDate,index.class=c('POSIXt','POSIXct'), src='yahoo')
start_t<-Sys.time()
out<-try(applyStrategy(strategy='bbands' , portfolios='bbands') )
updatePortf(Portfolio='bbands')
chart.Posn(Portfolio='bbands',Symbol=stock.str)