1

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.

RichS
  • 659
  • 12
  • 19

1 Answers1

1

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)
    }
  }
}
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
  • Thanks very much! Elegant in its simplicity. I couldn't work out where to capture lastTxnprice, but now it all makes sense. Thanks again! – RichS Aug 23 '14 at 00:31
  • @RichS Hi! Where do you put the code above? I have a pending question at http://stackoverflow.com/questions/26716128/pennypershare-quantstrat-not-working/26780586?noredirect=1#comment42141347_26780586, where I try to understand how to set transaction fees as a percentage of the asset price. I guess that the above solution could solve my problem but dont really understand how... – user1665355 Nov 07 '14 at 07:40