 
 require(quantstrat)

 try(rm("order_book.macd",pos=.strategy),silent=TRUE)

 try(rm("account.macd","portfolio.macd",pos=.blotter),silent=TRUE)

 try(rm("account.st","portfolio.st","stock.str","stratMACD","initDate","initEq",'start_t','end_t'),silent=TRUE)

 stock.str='AAPL' # what are we trying it on

 #MA parameters for MACD
 fastMA = 12 

 slowMA = 26 

 signalMA = 9

 maType="EMA"

 currency('USD')

 stock(stock.str,currency='USD',multiplier=1)

 #or use fake data
 #stock.str='sample_matrix' # what are we trying it on
 #data(sample_matrix)                 # data included in package xts
 #sample_matrix<-as.xts(sample_matrix)
 
 
 initDate='2009-12-31'

 initEq=1000000

 portfolio.st='macd'

 account.st='macd'

 initPortf(portfolio.st,symbols=stock.str, initDate=initDate)

 initAcct(account.st,portfolios=portfolio.st, initDate=initDate)

 initOrders(portfolio=portfolio.st,initDate=initDate)

 stratMACD <- strategy(portfolio.st)

 stratMACD <- add.indicator(strategy = stratMACD, name = "MACD", arguments = list(x=quote(Cl(mktdata))) )

 stratMACD <- add.signal(strategy = stratMACD,name="sigThreshold",arguments = list(column="signal",relationship="gt",threshold=0,cross=TRUE),label="signal.gt.zero")

 stratMACD <- add.signal(strategy = stratMACD,name="sigThreshold",arguments = list(column="signal",relationship="lt",threshold=0,cross=TRUE),label="signal.lt.zero")

 stratMACD <- add.rule(strategy = stratMACD,name='ruleSignal', arguments = list(sigcol="signal.gt.zero",sigval=TRUE, orderqty=100, ordertype='market', orderside='long', threshold=NULL),type='enter')

 stratMACD <- add.rule(strategy = stratMACD,name='ruleSignal', arguments = list(sigcol="signal.gt.zero",sigval=TRUE, orderqty=-100, ordertype='stoplimit', orderside='long', threshold=1,tmult=TRUE),type='risk')

 # alternately, use a trailing order
 # stratMACD <- add.rule(strategy = stratMACD,name='ruleSignal', arguments = list(sigcol="signal.gt.zero",sigval=TRUE, orderqty=-100, ordertype='stoptrailing', orderside='long', threshold=.9,tmult=TRUE),type='risk')
 
 
 stratMACD <- add.rule(strategy = stratMACD,name='ruleSignal', arguments = list(sigcol="signal.lt.zero",sigval=TRUE, orderqty='all', ordertype='market', orderside='long', threshold=NULL),type='exit')

 getSymbols(stock.str,from=initDate)

 start_t<-Sys.time()

 out<-try(applyStrategy(strategy=stratMACD , portfolios=portfolio.st,parameters=list(nFast=fastMA, nSlow=slowMA, nSig=signalMA,maType=maType)))

 end_t<-Sys.time()

 print(end_t-start_t)


 start_t<-Sys.time()

 updatePortf(Portfolio=portfolio.st,Dates=paste('::',as.Date(Sys.time()),sep=''))

 end_t<-Sys.time()

 print("trade blotter portfolio update:")

 print(end_t-start_t)

 chart.Posn(Portfolio=portfolio.st,Symbol=stock.str)

 plot(add_MACD(fast=fastMA, slow=slowMA, signal=signalMA,maType="EMA"))

 #look at the order book
 getOrderBook('macd')
