I am wanting to backtest a trade exit within quantstrat/blotter where I reference the price (inside a loop) that the latest blotter entry transaction was made at. I am wanting to add a rule that if the latest trade has fallen by eg 5% since inception then exit the trade as a kind of stop loss.
if( !is.na(X) )#if the indicator X has begun (it is NA at start of time series)
{
if(Posn == 0) {#No position test to go long
if(X < 20){
#enter long position
addTxn(a.strategy,Symbol='T',TxnDate=CurrentDate,
TxnPrice=ClosePrice,TxnQty=UnitSize,TxnFees=0)}
}else {#Have a position so check exit
This is where I want to reference TxnPrice:
if ( (X > 35) || (ClosePrice < (0.95 * TxnPrice)){
#exit position
addTxn(a.strategy,Symbol='T',TxnDate=CurrentDate,
TxnPrice = ClosePrice,TxnQty = -Posn,TxnFees=0)}
}
}
Where ClosePrice is
ClosePrice <- as.numeric(Cl(T[i,]))
The problem is that TxnPrice does not exist as an object within the global environment. I'm sure I am missing something very simple to reference it. Any help much appreciated.
Seems like the easiest thing to do is to make a variable in your global environment to track the last transaction price:
# initialize value so ClosePrice < (0.95 * lastTxnPrice) == FALSE
# until the first lastTxnPrice <- ClosePrice is run
lastTxnPrice <- -Inf
#if the indicator X has begun (it is NA at start of time series)
if(!is.na(X)) {
if(Posn == 0) {
#No position test to go long
if(X < 20) {
#enter long position
addTxn(a.strategy,Symbol='T',TxnDate=CurrentDate,
TxnPrice=ClosePrice,TxnQty=UnitSize,TxnFees=0)
lastTxnPrice <- ClosePrice
}
} else {
#Have a position so check exit
if((X > 35) || ClosePrice < (0.95 * lastTxnPrice)) {
#exit position
addTxn(a.strategy,Symbol='T',TxnDate=CurrentDate,
TxnPrice = ClosePrice,TxnQty = -Posn,TxnFees=0)
}
}
}