2 trade with same AFL code, 1 stop out but another continue 1 year

Hi all,

Two trade with same AFL code, One stop out but another continue for more than 1 year. Why??
I can't find where is the problem. please help. Thanks

SetOption("InitialEquity", 1000000); // set initial equity = 1 million
SetOption("CommissionMode", 3);
SetOption("CommissionAmount", 0.01);
SetOption("AllowSameBarExit", False);
SetOption("MaxOpenPositions", 2000);// maximum number of open positions
SetOption("AccountMargin", 20);
SetOption("UsePrevBarEquityForPosSizing", False);
SetOption("AllowPositionShrinking", True);
SetOption("MinShares", 1);
SetOption("ActivateStopsImmediately", True);

SetTradeDelays( 0, 0, 1, 0 );

SetChartOptions(0, chartShowArrows | chartShowDates);
Plot(Close, "Close", colorDefault, GetPriceStyle() | styleNoTitle);


// Volume and StockAmount Arrangment //
AveVol = MA(Volume,30)>=2000000; //Ave Vol 5 mil
StockAmount = 5;
PriceAb		= Close > StockAmount;
PriceBl		= Close < 400;
VolUp		= volume > 1.2 * ema( volume, 30 );
VP = AveVol AND PriceAb AND PriceBl AND VolUp;

//@@@@@@@@@@@    REFER TO MARKET INDEX @@@@@@@@@@@@//
IndexClosePrice = Foreign ("SPY","Close",True); 
IndexMA20  = MA( IndexClosePrice , 20);
IndexMA30  = MA( IndexClosePrice , 30);
IndexMA50  = MA( IndexClosePrice , 50 );
IndexMA200  = MA( IndexClosePrice , 200 );
YIndexMA20 = Ref( INDEXMA20 , -20 );
IndexMAUp = IndexMA20 > (YIndexMA20 * 1.02 );
IndexAb = IndexClosePrice > IndexMA20;
IndexUp = IndexAb AND IndexMA20 > IndexMA50 AND IndexMA50 > IndexMA200 AND IndexMAUp;
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@//


//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@//
///////////    (TPR) TRIGGER PRICE RANGE AND BUYPRICE   //////////////
TICKSZ = 0.01;
YesterdayHigh  = Ref(High, -1);
YesterdayLow   = Ref(Low , -1);
YesterdayClose = Ref(Close , -1);
YesterdayMid   = ( YesterdayHigh + YesterdayLow) / 2;
PecentHighAmount = YesterdayClose * 0.07;
PecentLowAmount  = YesterdayClose * 0.01;


//////////     BUYPRICE - BRAKOUT OF YESTERDAY HIGH    //////////
PriceBreakHigh = HIGH > YesterdayHigh;
BuyPrice = Max( YesterdayHigh, Open < YesterdayHigh * 1.01);

/////////     BUYPRICE WITHIN YERTERDAY BAR RANGE    ///////////////
TriggerPriceRange = Open < YesterdayHigh * 1.015 AND Open > YesterdayLow;  // OPEN PRICE WITHIN YESTER BAR //
BuyPrice = ValueWhen(TriggerPriceRange , Open);


_SECTION_BEGIN(" Standard Chart ");

SetChartOptions(0, chartShowArrows | chartShowDates);
Plot(Close, "Close", colorDefault, GetPriceStyle() | styleNoTitle);

//$*$*$*$*$*$*$*$*$*$*    Trading Logic    $*$*$*$*$*$*$*$*$*$*$*$ //
//$*$*$*$*$*$*$*$*$*$*    Trading Logic    $*$*$*$*$*$*$*$*$*$*$*$ //
//$*$*$*$*$*$*$*$*$*$*    Trading Logic    $*$*$*$*$*$*$*$*$*$*$*$ //

MAPeriod			= Optimize(" Period", 12, 8, 24, 2);
MAPlus				= MA(Close, MAPeriod);
MA20				= MA(Close, 20);
MA30				= MA(Close, 30);
YMA20				= Ref(MAPlus,-1);
MA200				= MA(Close, 200);

MACross				= Cross(MAPlus, MA200);
Bullish				= MAPlus > MA30 AND MA30 > MA200;
Bearish				= MAPlus < MA200;

BuySignal 	= MACross AND VP;
SellSignal	= Cross(MA20 , close);

////////   For Scanning       /////////
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@//

//Buy = BuySignal;

//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@//

////////   For Backtest       /////////
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@//

Buy = Ref(BuySignal, -1);

//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@//


Sell = SellSignal;
Short = Cover = 0;

//Filter = BuySignal ;
//AND Close > 50 
//AND Volume > 2000000
//AND volume > 1.2 * ema( volume, 30 ) ;



//$*$*$*$*$*$*$*$*$*$*    Trading Logic  End  $*$*$*$*$*$*$*$*$*$*$*$ //
//$*$*$*$*$*$*$*$*$*$*    Trading Logic  End  $*$*$*$*$*$*$*$*$*$*$*$ //
//$*$*$*$*$*$*$*$*$*$*    Trading Logic  End  $*$*$*$*$*$*$*$*$*$*$*$ //



Short = Cover = 0;

//REMOVE EXCESSIVE SIGNAL
Buy = EXREM(Buy, Sell);
Sell = ExRem(Sell, Buy);

/* Plot Buy and Sell Signal Arrows */
PlotShapes(IIf(BuySignal, shapeSquare, shapeNone),colorGreen, 0, L, Offset=-40);
PlotShapes(IIf(BuySignal, shapeSquare, shapeNone),colorLime, 0,L, Offset=-50);                      
PlotShapes(IIf(BuySignal, shapeUpArrow, shapeNone),colorWhite, 0,L, Offset=-45); 
PlotShapes(IIf(Sell, shapeSquare, shapeNone),colorRed, 0, H, Offset=40);
PlotShapes(IIf(Sell, shapeSquare, shapeNone),colorOrange, 0,H, Offset=50);                      
PlotShapes(IIf(Sell, shapeDownArrow, shapeNone),colorWhite, 0,H, Offset=-45);

//PlotShapes(Sell * shapestar, colorBrightGreen, 0, High, 12);
//PlotShapes(Cover * shapeCircle, colorBrightGreen, 0, Low, -12);


_SECTION_BEGIN("Swing Trade Module");


//REMOVE EXCESSIVE SIGNAL
Buy = EXREM(Buy, Sell);
Sell = ExRem(Sell, Buy);
//REMOVE EXCESSIVE SIGNAL
BuySignal = EXREM(BuySignal, SellSignal);
SellSignal = ExRem(SellSignal, BuySignal);


NEWDAY = Day() != Ref(Day(), -1);
LIMITTRADES = Param("LIMIT TRADE", 5, 1, 1000, 100);
STARTTRADETIME = ValueWhen(newday,TimeNum());// ParamTime("START TRADE TIME", "09:30");
LASTTRADETIME = ParamTime("LAST TRADE TIME", "11:00");
COLORUP = ParamColor("up color", colorGreen);
COLORDOWN = ParamColor("down color", colorRed);
//RISKCONTROL =ParamToggle("ENABLE TARGET AND STOPLOSS", "ENABLE|DISABLE", 1);
MODE = ParamList("STOP AND TARGET MODE", "POINTS|PERCENTS", 0);
DISPLAYLINE = ParamToggle("SHOW TARGET AND STOP LINE", "SHOW|HIDE", 1);

BuyPrice = ValueWhen(Buy, Open);


// Buy Stop Arrangment //

MinBSPPercent   = Valuewhen(Buy, YesterdayMid * 0.02);
MaxBSPPercent   = ValueWhen(Buy, YesterdayMid * 0.08);  
BuyStopBuffer     = 0.05;
Risk          = 3;
//BuyStopLevel    = ATR ( 7 ) * Risk;
BuyStopLevel  = valuewhen(Buy,LLV( Low, Risk ) - BuyStopBuffer);// use lowest low of previous "x" bars
BuyStopAmount = ValueWhen( Buy, BuyStopLevel);
MinBuyStopPoint  = BuyPrice - BuyStopAmount;			   
BuyStopPoint     = IIf(MinBuyStopPoint < MinBSPPercent, MinBSPPercent, IIf(MinBuyStopPoint > MaxBSPPercent, MaxBSPPercent,
				MinBuyStopPoint));

BuyStop       = BuyPrice - BuyStopPoint;


// Buy Target Arrangment  //
BuyStopAmount = ValueWhen( Buy, BuyStopLevel);
Reward          =  35;
BuyTargetPoint  = BuyStopPoint * Reward;
BuyTarget     = BuyPrice + BuyTargetPoint;


// Position Arrangemnt //
RiskAmount       = 200;
BuyPositionSize  = RiskAmount / BuyStopPoint; 
SetPositionSize(round( BuyPositionSize ), spsShares ); 


// Buy Trailing Stop Arrangment  //
MA20    = MA(Close , 20);
TrailMA = Cross( Low , MA20 );


Buy = Buy AND (TimeNum() >= STARTTRADETIME AND TimeNum() <= LASTTRADETIME);
Sell = Sell;

//REMOVE EXCESSIVE SIGNAL
BuySignal = EXREM(BuySignal, SellSignal);
SellSignal = ExRem(SellSignal, BuySignal);


BUYCONTINUE = Flip(Buy, Sell);

Buy = Buy AND (TimeNum() >= STARTTRADETIME AND TimeNum() <= LASTTRADETIME);
iSell = Sell ;

Buy = ExRem(Buy, iSell);
iSell = ExRem(iSell, Buy);
ISell = Sell;

BuyPrice = ValueWhen(Buy, Open);

Sell = ISELL OR Cross(High, BUYTARGET) OR Cross( BUYSTOP, Low);// OR Cross( NW , Low );


//REMOVE EXCESSIVE SIGNAL
Buy = EXREM(Buy, Sell);
Sell = ExRem(Sell, Buy);

Sell = IIf(Cross(High, BUYTARGET), Sell, IIF(Cross(BUYSTOP, Low), Sell, IIf(Cross( MA20 , Low ), Sell, Ref( Sell, -1))));

SellPrice = ValueWhen(Sell, IIF(Cross(High, BUYTARGET), BUYTARGET, 
			IIF(Cross(BUYSTOP, Low), BUYSTOP, IIf(Cross( MA20 , Low ), MA20, Open))));

Short = ExRem(Short, Cover);
Cover = ExRem(Cover, Short);
ICOVER = Cover ;

Short = ExRem(Short, ICOVER);
ICOVER = ExRem(ICOVER, Short);

//REMOVE EXCESSIVE SIGNAL
Sell = Sell;

Buy = ExRem(Buy, Sell);
Sell = ExRem(Sell, Buy);

// STEP 6 : PLOT STOP AND TARGET

BUYCONTINUE = Flip(Buy, Sell);


Plot(IIF(BUYCONTINUE OR Sell, BUYSTOP, Null), "BUYSTOP", colorRed, styleDots | styleThick);
//Plot(IIF(BUYCONTINUE OR Sell, BUYTARGET, Null), "BUYTARGET", colorGreen, styleDashed | styleThick);

_SECTION_END();

maPlus	= MA(Close, MAPeriod);
ma20 = MA(Close,20);
ma50 = MA(Close,50);
ma200 = MA(Close,200);
_SECTION_END();

_SECTION_BEGIN("PLOT STOP AND TARGET");



Plot(maPlus,"MAPlus",colorBrightGreen);

Plot(ma20,"20MA",colorCustom11);
Plot(MA50,"50MA",colorRed);
Plot(ma200,"200MA",colorwhite);

AddColumn(BuyStopPoint,"BuyStopPoint",1.2);

Filter  = Buysignal;
color = IIf(BuySignal,colorGreen,colorRed);

mastatus = WriteIf(Buysignal,"Bullish","Bearish");


AddColumn(MA(C,200),"MA200",1.2,colorWhite,color);
AddTextColumn(mastatus,"Status",1,colorWhite,color);

Attach AFL code and picture UAL SELLSIGNAL AND STOPLOSS
UAL SECOND TRADE
UAL  PNL

Your code is kind of crazy, you declare the same things over and over, and sometimes differently.

Remove line 215 through 231 and it will work, but the code is still a mess. I suggest go through line by line and figure out what you need and what you do not need.

@Blackgarlic please make sure that you understand that if you re-define Buy/Sell/Cover/Short rules in your formula several times, only the very LAST assignment to Buy/Sell/Short/Cover counts with regards to backtest.

Yes, this is the real thing you need to understand. I could have been more clear :slight_smile:

Thanks you Pinecode and Tomasz for the guidance. So sorry for the late reply as I'm a part time trader.
Will try to reduce the code base on my little knowledge . Thanks again

This topic was automatically closed 100 days after the last reply. New replies are no longer allowed.