Quantcast

Moving Limit orders

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
2 messages Options
Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Moving Limit orders

John Klingensmith
Hi,
 I am using the following packages quantstrat, IKTrading, DSTrading, along
with some other misc packages (see code).  I am having trouble
understanding entering moving limits (kind of like trailing stops) to close
the position.

When I enter a long (short) trade, I want a limit to close the position to
equal the moving average of the high (low).  I want the limit price to
equal the current value of the moving average I am targeting - for long
trade: SMA.highMA,  and for short trades: SMA.lowMA

I do plan to enter exit orders and stops, but I have not gotten that far
yet.


Here is my code:

require(quantstrat)
require(IKTrading)
require(DSTrading)
library(xlsx)
library(dygraphs)
library(htmltools)
library(knitr)

options(warn=1)

rm(list=ls(.blotter), envir = .blotter)

initDate = "2000-01-01"
from = "2012-01-01"
to = "2017-02-22"

currency('USD')
Sys.setenv(TZ="UTC")

#get symbols and set symbol currency and multiplyer

symbols <- "SPY"
suppressMessages(getSymbols(symbols, from = from, to = to))

stock(symbols, currency = "USD", multiplyer=1)

#trade sizing and initial equity settings
tradeSize <- 100000
initEq <- tradeSize*length(symbols)


strategy.st <- portfolio.st <- account.st <- "RSI_MR"
rm.strat(portfolio.st)
rm.strat(strategy.st)

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

MaxPos <- 1
lvls <- 1

addPosLimit(portfolio=portfolio.st, timestamp=initDate, symbol=symbols,
            maxpos=MaxPos, longlevels=lvls, minpos=-MaxPos,
shortlevels=lvls)

#parameters
nRSI = 3
lowerThreshold = 15
upperThreshold = 85
lowerMinThreshold = 5
upperMaxThreshold = 95
nSMAofRSI = 5
nMaHi = 5
nMaLo = 5

nATR = 14
xATR = 3

##rsi.sma <- SMA(RSI(Cl(SPY),3),5, label = "rsima")

#indicators
add.indicator(strategy.st,name = "RSI",
              arguments = list(price = quote(Cl(mktdata)),n = nRSI),
              label = "rsi")

add.indicator(strategy.st,name = "SMA",
              arguments = list(x = quote(RSI(Cl(SPY),nRSI)), n = nSMAofRSI),
              label = "rsiMA")

add.indicator(strategy.st,name = "SMA",
              arguments = list(x = quote(Hi(mktdata)),n = nMaHi),
              label = "highMA")

add.indicator(strategy.st,name = "SMA",
              arguments = list(x = quote(Lo(mktdata)),n = nMaLo),
              label = "lowMA")

add.indicator(strategy.st, name = "ATR",
              arguments=list(HLC = quote(HLC(mktdata)), n=nATR),
              label = "atr" )
'/
test <- applyIndicators(strategy.st, mktdata = OHLC(SPY))
head(test,10)
'

#Signals

#Enter Long Signal 1
add.signal(strategy.st, name = "sigThreshold",
           arguments = list(column = "rsiMA", threshold = lowerThreshold,
                            relationship = "lt", cross=FALSE),
           label = "rsiMAlowerThreshold")

#Enter Long Signal 2
add.signal(strategy.st, name = "sigThreshold",
           arguments = list(column = "rsiMA", threshold = lowerMinThreshold,
                            relationship = "gt", cross=FALSE),
           label = "rsiMAlowerMINThreshold")

#Enter Long Signal 1&2
add.signal(strategy.st, name="sigAND",
           arguments=list(columns=c("rsiMAlowerThreshold",
                                    "rsiMAlowerMINThreshold"), cross=TRUE),
           label="longEntry")

#Enter Short Signal 1
add.signal(strategy.st, name = "sigThreshold",
           arguments = list(column = "rsiMA", threshold = upperThreshold,
                            relationship = "gt", cross=FALSE),
           label = "rsiMAupperThreshold")

#Enter Short Signal 2
add.signal(strategy.st, name = "sigThreshold",
           arguments = list(column = "rsiMA", threshold = upperMaxThreshold,
                            relationship = "lt", cross=FALSE),
           label = "rsiMAmaxThreshold")

#Enter Short Signal 1&2
add.signal(strategy.st, name="sigAND",
           arguments=list(columns=c("rsiMAupperThreshold",
"rsiMAmaxThreshold"),
                          cross=TRUE),
           label="shortEntry")

#Exit Long Signal
add.signal(strategy.st, name = "sigComparison",
           arguments = list(columns = c("High", "highMA"), relationship =
"gt"),
           label = "normalExitLongFilter")

#Exit Short Signal
add.signal(strategy.st, name = "sigComparison",
           arguments = list(columns = c("Low", "lowMA"), relationship =
"lt"),
           label = "normalExitShortFilter")


#Rules
#LONG RULES
add.rule(strategy.st, name="ruleSignal",
         arguments = list(sigcol = "longEntry",
                          sigval = TRUE,
                          orderqty = 1,
                          ordertype = "market",
                          orderside = "long",
                          replace = FALSE,
                          prefer = "Open",
                          osFUN = "osMaxPos",
                          orderset="ocolong"),
         type = "enter", path.dep = TRUE,
         label = "enterLong1")

add.rule(strategy.st, name="ruleSignal",
         arguments=list(sigcol="longEntry",
                        sigval=TRUE,
                        ordertype="limit",
                        orderside="long",
                        replace=FALSE,
                        orderqty='all',
                        prefer = 'SMA.highMA',
                        #threshold = quote('SMA.highMA'),
                        #order.price=quote(mktdata$SMA.lowMA[timestamp]),
                        orderset="ocolong"),
         type="chain",
         parent="enterLong1",
         label="takeProfitLong",
         path.dep=TRUE)



#SHORT RULES
add.rule(strategy.st, name="ruleSignal",
         arguments = list(sigcol = "shortEntry",
                          sigval = TRUE,
                          orderqty = -1,
                          ordertype = "market",
                          orderside = "short",
                          replace = FALSE,
                          prefer = "Open",
                          osFUN = "osMaxPos",
                          orderset="ocoshort"),
         type = "enter", path.dep = TRUE,
         label = "enterShort1")

add.rule(strategy.st, name="ruleSignal",
         arguments=list(sigcol="shortEntry",
                        sigval=TRUE,
                        ordertype="limit",
                        orderside="short",
                        replace=FALSE,
                        orderqty='all',
                        prefer = 'SMA.lowMA',
                        #threshold = quote('SMA.lowMA'),
                        #order.price=quote(mktdata$SMA.lowMA[timestamp]),
                        orderset="ocoshort"),
         type="chain",
         parent="enterShort1",
         label="takeProfitShort",
         path.dep=TRUE)


#apply strategy
t1 <- Sys.time()
out <- applyStrategy(strategy=strategy.st,portfolios=portfolio.st)
t2 <- Sys.time()
print(t2-t1)

#set up analytics
updatePortf(portfolio.st)
dateRange <- time(getPortfolio(portfolio.st)$summary)[-1]
updateAcct(portfolio.st,dateRange)
updateEndEq(account.st)


Any help is appreciated!
Best,
 John

        [[alternative HTML version deleted]]

_______________________________________________
[hidden email] mailing list
https://stat.ethz.ch/mailman/listinfo/r-sig-finance
-- Subscriber-posting only. If you want to post, subscribe first.
-- Also note that this is not the r-help list where general R questions should go.
Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: Moving Limit orders

Victor Montanez
Anyone has a complete system so I can test and play with? Thanks.

-----Original Message-----
From: R-SIG-Finance [mailto:[hidden email]] On Behalf
Of John Klingensmith
Sent: Thursday, April 06, 2017 4:47 PM
To: r-sig-finance <[hidden email]>
Subject: [R-SIG-Finance] Moving Limit orders

Hi,
 I am using the following packages quantstrat, IKTrading, DSTrading, along
with some other misc packages (see code).  I am having trouble understanding
entering moving limits (kind of like trailing stops) to close the position.

When I enter a long (short) trade, I want a limit to close the position to
equal the moving average of the high (low).  I want the limit price to equal
the current value of the moving average I am targeting - for long
trade: SMA.highMA,  and for short trades: SMA.lowMA

I do plan to enter exit orders and stops, but I have not gotten that far
yet.


Here is my code:

require(quantstrat)
require(IKTrading)
require(DSTrading)
library(xlsx)
library(dygraphs)
library(htmltools)
library(knitr)

options(warn=1)

rm(list=ls(.blotter), envir = .blotter)

initDate = "2000-01-01"
from = "2012-01-01"
to = "2017-02-22"

currency('USD')
Sys.setenv(TZ="UTC")

#get symbols and set symbol currency and multiplyer

symbols <- "SPY"
suppressMessages(getSymbols(symbols, from = from, to = to))

stock(symbols, currency = "USD", multiplyer=1)

#trade sizing and initial equity settings tradeSize <- 100000 initEq <-
tradeSize*length(symbols)


strategy.st <- portfolio.st <- account.st <- "RSI_MR"
rm.strat(portfolio.st)
rm.strat(strategy.st)

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

MaxPos <- 1
lvls <- 1

addPosLimit(portfolio=portfolio.st, timestamp=initDate, symbol=symbols,
            maxpos=MaxPos, longlevels=lvls, minpos=-MaxPos,
shortlevels=lvls)

#parameters
nRSI = 3
lowerThreshold = 15
upperThreshold = 85
lowerMinThreshold = 5
upperMaxThreshold = 95
nSMAofRSI = 5
nMaHi = 5
nMaLo = 5

nATR = 14
xATR = 3

##rsi.sma <- SMA(RSI(Cl(SPY),3),5, label = "rsima")

#indicators
add.indicator(strategy.st,name = "RSI",
              arguments = list(price = quote(Cl(mktdata)),n = nRSI),
              label = "rsi")

add.indicator(strategy.st,name = "SMA",
              arguments = list(x = quote(RSI(Cl(SPY),nRSI)), n = nSMAofRSI),
              label = "rsiMA")

add.indicator(strategy.st,name = "SMA",
              arguments = list(x = quote(Hi(mktdata)),n = nMaHi),
              label = "highMA")

add.indicator(strategy.st,name = "SMA",
              arguments = list(x = quote(Lo(mktdata)),n = nMaLo),
              label = "lowMA")

add.indicator(strategy.st, name = "ATR",
              arguments=list(HLC = quote(HLC(mktdata)), n=nATR),
              label = "atr" )
'/
test <- applyIndicators(strategy.st, mktdata = OHLC(SPY))
head(test,10)
'

#Signals

#Enter Long Signal 1
add.signal(strategy.st, name = "sigThreshold",
           arguments = list(column = "rsiMA", threshold = lowerThreshold,
                            relationship = "lt", cross=FALSE),
           label = "rsiMAlowerThreshold")

#Enter Long Signal 2
add.signal(strategy.st, name = "sigThreshold",
           arguments = list(column = "rsiMA", threshold = lowerMinThreshold,
                            relationship = "gt", cross=FALSE),
           label = "rsiMAlowerMINThreshold")

#Enter Long Signal 1&2
add.signal(strategy.st, name="sigAND",
           arguments=list(columns=c("rsiMAlowerThreshold",
                                    "rsiMAlowerMINThreshold"), cross=TRUE),
           label="longEntry")

#Enter Short Signal 1
add.signal(strategy.st, name = "sigThreshold",
           arguments = list(column = "rsiMA", threshold = upperThreshold,
                            relationship = "gt", cross=FALSE),
           label = "rsiMAupperThreshold")

#Enter Short Signal 2
add.signal(strategy.st, name = "sigThreshold",
           arguments = list(column = "rsiMA", threshold = upperMaxThreshold,
                            relationship = "lt", cross=FALSE),
           label = "rsiMAmaxThreshold")

#Enter Short Signal 1&2
add.signal(strategy.st, name="sigAND",
           arguments=list(columns=c("rsiMAupperThreshold",
"rsiMAmaxThreshold"),
                          cross=TRUE),
           label="shortEntry")

#Exit Long Signal
add.signal(strategy.st, name = "sigComparison",
           arguments = list(columns = c("High", "highMA"), relationship =
"gt"),
           label = "normalExitLongFilter")

#Exit Short Signal
add.signal(strategy.st, name = "sigComparison",
           arguments = list(columns = c("Low", "lowMA"), relationship =
"lt"),
           label = "normalExitShortFilter")


#Rules
#LONG RULES
add.rule(strategy.st, name="ruleSignal",
         arguments = list(sigcol = "longEntry",
                          sigval = TRUE,
                          orderqty = 1,
                          ordertype = "market",
                          orderside = "long",
                          replace = FALSE,
                          prefer = "Open",
                          osFUN = "osMaxPos",
                          orderset="ocolong"),
         type = "enter", path.dep = TRUE,
         label = "enterLong1")

add.rule(strategy.st, name="ruleSignal",
         arguments=list(sigcol="longEntry",
                        sigval=TRUE,
                        ordertype="limit",
                        orderside="long",
                        replace=FALSE,
                        orderqty='all',
                        prefer = 'SMA.highMA',
                        #threshold = quote('SMA.highMA'),
                        #order.price=quote(mktdata$SMA.lowMA[timestamp]),
                        orderset="ocolong"),
         type="chain",
         parent="enterLong1",
         label="takeProfitLong",
         path.dep=TRUE)



#SHORT RULES
add.rule(strategy.st, name="ruleSignal",
         arguments = list(sigcol = "shortEntry",
                          sigval = TRUE,
                          orderqty = -1,
                          ordertype = "market",
                          orderside = "short",
                          replace = FALSE,
                          prefer = "Open",
                          osFUN = "osMaxPos",
                          orderset="ocoshort"),
         type = "enter", path.dep = TRUE,
         label = "enterShort1")

add.rule(strategy.st, name="ruleSignal",
         arguments=list(sigcol="shortEntry",
                        sigval=TRUE,
                        ordertype="limit",
                        orderside="short",
                        replace=FALSE,
                        orderqty='all',
                        prefer = 'SMA.lowMA',
                        #threshold = quote('SMA.lowMA'),
                        #order.price=quote(mktdata$SMA.lowMA[timestamp]),
                        orderset="ocoshort"),
         type="chain",
         parent="enterShort1",
         label="takeProfitShort",
         path.dep=TRUE)


#apply strategy
t1 <- Sys.time()
out <- applyStrategy(strategy=strategy.st,portfolios=portfolio.st)
t2 <- Sys.time()
print(t2-t1)

#set up analytics
updatePortf(portfolio.st)
dateRange <- time(getPortfolio(portfolio.st)$summary)[-1]
updateAcct(portfolio.st,dateRange)
updateEndEq(account.st)


Any help is appreciated!
Best,
 John

        [[alternative HTML version deleted]]

_______________________________________________
[hidden email] mailing list
https://stat.ethz.ch/mailman/listinfo/r-sig-finance
-- Subscriber-posting only. If you want to post, subscribe first.
-- Also note that this is not the r-help list where general R questions
should go.

_______________________________________________
[hidden email] mailing list
https://stat.ethz.ch/mailman/listinfo/r-sig-finance
-- Subscriber-posting only. If you want to post, subscribe first.
-- Also note that this is not the r-help list where general R questions should go.
Loading...