I'm trying to backtest a trading strategy using blotter. After a long search I've found out that the error is only as long as no trade has taken place and no position is opened. Before any trade is opened Posn is listed in the Workspace of RStudio as numeric(0). After that it always is either 0 or a position. Where is my mistake or what could I add to the first if clause if(Posn!=0)? Because this if generates the error with the following message:
Error in if (Posn != 0) { : argument is of length zero
I then tried these two Inputs and got these results:
> Posn
numeric(0)
> Posn!=0
logical(0)
Here's my complete code:
for(i in 84:200){
CurrentDate <- time(MergedXTS)[i]
ClosePrice <- as.numeric(MergedXTS[i,'Close'])
if(!(is.na(as.numeric(MergedXTS[i,'Close']))) && !(is.na(as.numeric(MergedXTS[i-1,'Close'])))){
RiskClose <- as.numeric(MergedXTS[i,'RiskIndicatorMA'])
RiskClose.PreviousDay <- as.numeric(MergedXTS[i-1,'RiskIndicatorMA'])
Posn <- getPosQty(StrategyName, Symbol=CrossCurrency, Date=CurrentDate)
print(Posn)
if(Posn != 0){
if(Posn>0){
#Long active, sell long
if(RiskClose <= ParamUp && RiskClose.PreviousDay > ParamUp){
addTxn(Risk.Strategy, Symbol=CrossCurrency, TxnDate=CurrentDate,
TxnPrice=ClosePrice, TxnQty = -1000 , TxnFees=0)
}
} else {
#Short active sell short
if(RiskClose >= ParamDown && RiskClose.PreviousDay < ParamDown){
addTxn(StrategyName, Symbol=CrossCurrency, TxnDate=CurrentDate,
TxnPrice=ClosePrice, TxnQty = 1000 , TxnFees=0)
}
}
} else {
if(RiskClose >= ParamUp && RiskClose.PreviousDay < ParamUp){
#Buy
addTxn(StrategyName, Symbol=CrossCurrency, TxnDate=CurrentDate,
TxnPrice=ClosePrice, TxnQty = 1000 , TxnFees=0)
}
if(RiskClose <= ParamDown && RiskClose.PreviousDay > ParamDown){
#Short
addTxn(StrategyName, Symbol=CrossCurrency, TxnDate=CurrentDate,
TxnPrice=ClosePrice, TxnQty = -1000 , TxnFees=0)
}
}
# Calculate P&L and resulting equity with blotter
updatePortf(StrategyName, Dates=CurrentDate)
updateAcct(StrategyName, Dates=CurrentDate)
updateEndEq(StrategyName, Dates=CurrentDate)
print(i)
}
}
Simply test if length(Posn)==0
after you call getPosQty
:
Posn <- numeric(0)
if(!length(Posn)) Posn <- 0