back-testingamibroker

Move profit target and stop loss after initial profit target is hit in amibroker


I have the following amibroker afl backtesting code with stop-loss set at 10 points and profit target set at 20 points.

long_entry_condition = close > EMA(close, 50);
Buy = long_entry_condition;
BuyPrice = Close;

risk = 10;

ApplyStop(Type=stopTypeLoss, mode=stopModePoint, Amount=risk, 
            ExitAtStop=1, volatile=False, ReEntryDelay=0, ValidFrom=0, ValidTo=-1 );
ApplyStop(Type=stopTypeProfit, mode=stopModePoint, Amount=2*risk, 
            ExitAtStop=1, volatile=False, ReEntryDelay=0, ValidFrom=0, ValidTo=-1 );
        

Suppose I want to take profit for half the position at 10 points. Then for the remaining half position, I want to set the stop loss level to breakeven and the profit target at 30 points. How do I modify the existing code to achieve this?


Solution

  • Buy = long_entry_condition;
    BuyPrice = Open;
    Sell = 0;
    
    profit = Close - BuyPrice;
    cover_cond = 0;
    
    if (BarsSince(Buy) == 0){
        status = "initial";
    }
    else if (status == "initial" AND profit >= 10){
        status = "firstProfit";
        Sell = 1; // sell half
    }
    else if (status == "firstProfit"){
        if (profit < 0){ // stop loss at breakeven
            status = "stoppedOut";
            Sell = 1;
        }
        else if (profit >= 30){
            status = "secondProfit";
            Sell = 1;
        }
    }
    
    ApplyStop( type = stopTypeLoss, mode = stopModePoint, amount = 10);
    ApplyStop( type = stopTypeProfit, mode = stopModePoint, amount = 20);
    

    This example makes a couple of simplifying assumptions. It assumes that you always sell exactly half, and that signal processing happens at bar close. In real trading, there'd be slippage, and we could reach these profit targets partway through the bar. Real trading also involves managing ongoing orders to sell or cover the position, while here we're doing it bar by bar. But it captures the basic idea of what you're trying to do. Consider this a starting point and adjust as necessary.