No new Buy after Sell signal

Hi,

From time to time people send us their formulas asking what happens in their own code. Or they do not know why given trade is taken or not. These questions are usually caused by the fact that people lack the insight what is happening inside and what values values their variables hold.

I checked serveral resources on the internet and did a lot of effort to debug my code.
I displayed the used variable in the chart and also the columns for the explore function are included.
Everything is made visible as possible, so that you can check the problem fast.

Problem:
I have 5 Buy conditions and when they all are true the Array KOOP is true.
Buy = KOOP;

This works fine only once !

The Buy and Sell signal is visible in the chart. But after the Sell signal there is no new Buy signal generated when KOOP (BUY) is True. You can check this in the exploration.

I Know, it's my error, but i cannot find it. It is alway me who makes the mistake and Amibroker is realy great. :slight_smile:

MY CODE:

_SECTION_BEGIN("Price");
SetChartOptions(0,chartShowArrows|chartShowDates);
Plot( C, "Close", ParamColor("Color", colorDefault ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() ); 
_SECTION_END();

SetTradeDelays(0,0,0,0);// geen vertragingen
SetOption("EveryBarNullCheck",True); // controleer of bar geen null waarde heeft
SetChartOptions(0, chartShowDates);// geef datum weer ook in eventuele chartpanes
SetChartOptions( 0, chartShowArrows );// plaats koop en verkoop pijlen op chart
SetChartOptions(2, chartWrapTitle );// plaats de titel binnen het chart
SetOption("InitialEquity",20000);// start kapitaal 20000
SetOption("MaxOpenPositions",20); // Maximaal aantal open posities (20)
SetPositionSize(5.00,spsPercentOfEquity);// Maximaal 5,00% van totaal Equity
SetOption("accountmargin",100); // Maximaal leverage 100% EV en 0% VV
SetOption("CommissionMode",2); 
SetOption("CommissionAmount",5); // commission per trade 5 euro
SetOption("Minshares",1);// minimum 1 aandeel maximum aandelen in 1 koop aangeven ?. Voorkomen aankoop penny stocks
SetOption("AllowPositionShrinking", True);
RoundLotSize=1; // afronden op hele aandelen
TimeFrameSet( inWeekly ); // switch to timeframe

// Declartion variable
EMAfast = EMA(C,9);
EMAslow = EMA(C,26);

Buy=0;
Sell=0;

PriceBuySignal=0;
PriceShortSignal=0;
ATR13 = ATR(13);

SLOPEADX =LinRegSlope(ADX(13),7);
SLOPEfast = LinRegSlope(EMAfast,3);


// Buy Sell condition
Koop1 = Flip(Cross(EMAfast,EMAslow),Cross(EMAslow,EMAfast)); 
Koop2 = SLOPEfast > 0.150;
Koop3 = SLOPEADX > 0.1; 
Koop4 = PDI(13)-MDI(13)>10;
Koop5 = Close > Open;
KOOP  = Koop1 AND Koop2 AND Koop3 AND Koop4 AND Koop5;        
Buy   = KOOP;   
Buy   = ExRem(Buy, Sell);

Aankoop    	= ValueWhen(Buy,BuyPrice);
Intrade    	= Flip(Buy,Sell);

TP2line    	= IIf(InTrade, aankoop * 1.02, Null );
TP4line    	= IIf(InTrade, aankoop * 1.04, Null );
TP6line    	= IIf(InTrade, aankoop * 1.06, Null );
TP8line    	= IIf(InTrade, aankoop * 1.08, Null );
TP10line   	= IIf(InTrade, aankoop * 1.10, Null );
TP12line   	= IIf(InTrade, aankoop * 1.12, Null );
TP14line   	= IIf(InTrade, aankoop * 1.14, Null );
TP16line   	= IIf(InTrade, aankoop * 1.16, Null );
TP18line   	= IIf(InTrade, aankoop * 1.18, Null );

Lowline		= IIf(InTrade, Low, Null );
Loss       	= IIf(InTrade, Aankoop * 0.97,0);
PR         	= ((TP2line / Aankoop)-1)*100;
LO         	= ((loss   / Aankoop)-1)*100; 

Verkoop1 	= Cross(TP18line,Lowline);
Verkoop2 	= Cross(TP16line,Lowline);
Verkoop3 	= Cross(TP14line,Lowline);
Verkoop4 	= Cross(TP12line,Lowline);
Verkoop5 	= Cross(TP10line,Lowline);
Verkoop6 	= Cross(TP8line,Lowline);
Verkoop7 	= Cross(TP6line,Lowline);
Verkoop8 	= Cross(TP4line,Lowline);
Verkoop9 	= Cross(TP2line,Lowline);
Verkoop10	= Cross(Loss,Lowline);
Verkoop11 	= Cross(EMAslow,Low);
VERKOOP  	= Verkoop1 OR Verkoop2 OR Verkoop3 OR Verkoop4 OR Verkoop5 OR 
			  Verkoop6 OR Verkoop7 OR Verkoop8 OR Verkoop9 OR Verkoop10 OR Verkoop11;
Sell = VERKOOP;
Sell  = ExRem(Sell, Buy);

RE      = (ValueWhen(Sell,SellPrice) / Aankoop) * 100 - 100;

// Price to Buy or Sell
BuyPrice   = Close;
SellPrice  = Close;
ShortPrice = Close;
CoverPrice = Close;

Aankoop = ValueWhen(Buy,BuyPrice);
ExitPrice = ValueWhen(Sell,SellPrice);

Profit2  = Aankoop * 1.02;
Profit4  = Aankoop * 1.04;
Profit6  = Aankoop * 1.06;
Profit8  = Aankoop * 1.08;
Profit10 = Aankoop * 1.10;
Profit12 = Aankoop * 1.12;
Profit14 = Aankoop * 1.14;
Profit16 = Aankoop * 1.16;
Profit18 = Aankoop * 1.18;

PR2      = ((Profit2 / Aankoop)-1)*100;
PR4      = ((Profit4 / Aankoop)-1)*100;
PR6      = ((Profit6 / Aankoop)-1)*100;
PR8      = ((Profit8 / Aankoop)-1)*100;
PR10      = ((Profit10 / Aankoop)-1)*100;
PR12      = ((Profit12 / Aankoop)-1)*100;
PR14      = ((Profit14 / Aankoop)-1)*100;
PR16      = ((Profit16 / Aankoop)-1)*100;
PR18      = ((Profit18 / Aankoop)-1)*100;

LO       = ((loss   / Aankoop)-1)*100; 
RE       = (ExitPrice / Aankoop) * 100 - 100;

Plot(EMAfast,"EMAfast",colorAqua, styleThick);
Plot(EMAslow,"EMASlow",colorRed, styleThick); 

//Plot buy and sell signal arrows LONG
Buy = ExRem(Buy,Sell);
Sell =ExRem(Sell,Buy);
EntryPrice = ValueWhen(Buy,BuyPrice);
ExitPrice = ValueWhen(Sell,SellPrice);
ExRem(EntryPrice,ExitPrice);
Plot(EntryPrice,"Entry",colorGold,styleNoDraw);
Plot(ExitPrice,"Exit",colorGold,styleNoDraw);
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorGreen, 0, L, Offset=-40);
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorLime, 0, L, Offset=-50);
PlotShapes(IIf(Buy, shapeUpArrow, shapeNone),colorWhite, 0, L, Offset=-45);
PlotShapes(IIf(Buy, shapeStar,shapeNone),colorGold,0,C, Offset=0);
PlotShapes(IIf(Sell, shapeSquare, shapeNone),colorRed, 0, L, Offset=40);
PlotShapes(IIf(Sell, shapeSquare, shapeNone),colorOrange, 0, L, Offset=50);
PlotShapes(IIf(Sell, shapeDownArrow, shapeNone),colorWhite, 0, L, Offset=-40);
PlotShapes(IIf(Sell, shapeStar,shapeNone),colorwhite, 0, C, Offset=0);
dist  = 2.0 * ATR(10);
dist1 = 1.8 * ATR(10);
for( i = 0; i <BarCount; i++)
{
if (Buy[i])  PlotText("Buy  \n" +round(C[i]*100)/100, i, L[i]-dist[i], colorGreen, colorGold, yoffset=-50);
if (Sell[i]) PlotText("Sell \n"+ round(C[i]*100)/100, i, H[i]-dist1[i], colorRed, colorGold, yoffset=0);
}
Intrade = Flip(Buy,Sell);
PlotShapes(IIf(Intrade,shapeSquare,shapeNone),colorGreen,0,EntryPrice, offset=-110);
_SECTION_END();

// PLOT Take profit lines 
Plot(Lowline,"Lowline", colorOrange);

PlotShapes(IIf(Buy,shapeDigit2,shapeNone),colorYellow,0,Profit2, offset=0);
PlotShapes(IIf(Intrade,22,shapeNone),colorYellow,0,Profit2, offset=0);

PlotShapes(IIf(Buy,shapeDigit4,shapeNone),colorYellow,0,Profit4, offset=0);
PlotShapes(IIf(Intrade,22,shapeNone),colorYellow,0,Profit4, offset=0);

PlotShapes(IIf(Buy,shapeDigit6,shapeNone),colorYellow,0,Profit6, offset=0);
PlotShapes(IIf(Intrade,22,shapeNone),colorYellow,0,Profit6, offset=0);

PlotShapes(IIf(Buy,shapeDigit8,shapeNone),colorYellow,0,Profit8, offset=0);
PlotShapes(IIf(Intrade,22,shapeNone),colorYellow,0,Profit8, offset=0);

PlotShapes(IIf(Buy,shapeDigit0,shapeNone),colorYellow,0,Profit10, offset=0);
PlotShapes(IIf(Intrade,22,shapeNone),colorYellow,0,Profit10, offset=0);

PlotShapes(IIf(Buy,shapeDigit2,shapeNone),colorYellow,0,Profit12, offset=0);
PlotShapes(IIf(Intrade,22,shapeNone),colorYellow,0,Profit12, offset=0);

PlotShapes(IIf(Buy,shapeDigit4,shapeNone),colorYellow,0,Profit14, offset=0);
PlotShapes(IIf(Intrade,22,shapeNone),colorYellow,0,Profit14, offset=0);

PlotShapes(IIf(Buy,shapeDigit6,shapeNone),colorYellow,0,Profit16, offset=0);
PlotShapes(IIf(Intrade,22,shapeNone),colorYellow,0,Profit16, offset=0);

PlotShapes(IIf(Buy,shapeDigit8,shapeNone),colorYellow,0,Profit18, offset=0);
PlotShapes(IIf(Intrade,22,shapeNone),colorYellow,0,Profit18, offset=0);

PlotShapes(IIf(Intrade,22,shapeNone),colorRed,0,Loss, offset=0);

// Waarden Variabelen
Title =StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) )+

 "\n\nVariabelen Controle\n\n"+
"Entry:              "+NumToStr(Entryprice,1.2)+"\n"+
"Take Profit:%    "+NumToStr(Pr2,1.2)+"         "+NumToStr(Pr4,1.2)+"         "+NumToStr(Pr6,1.2)+"         "+NumToStr(Pr8,1.2)+"        "+NumToStr(Pr10,1.2)+"       "+NumToStr(Pr12,1.2)+"       "+NumToStr(Pr14,1.2)+"       "+NumToStr(Pr16,1.2)+"       "+NumToStr(Pr18,1.2)+"\n"+
"Take Profit:       "+NumToStr(Profit2,1.2)+"       "+NumToStr(Profit4,1.2)+"       "+NumToStr(Profit6,1.2)+"       "+NumToStr(Profit8,1.2)+"       "+NumToStr(Profit10,1.2)+"       "+NumToStr(Profit12,1.2)+"       "+NumToStr(Profit14,1.2)+"       "+NumToStr(Profit16,1.2)+"       "+NumToStr(Profit18,1.2)+"\n"+
"Take Loss          "+NumToStr(loss,1.2)+"    "+NumToStr(Lo,1.1)+"%"+"\n"+
"EXit:                 "+NumToStr(Exitprice,1.2)+"       "+NumToStr(RE,1.1)+"%"+"\n\n"+

"High:                 "+NumToStr(H,1.2)+"\n"+
"Open:                "+NumToStr(O,1.2)+"\n"+
"Close:                "+NumToStr(C,1.2)+"\n"+
"Low:                  "+NumToStr(L,1.2)+"\n\n"+

"Koop1: Flip(Cross(EMAfast,EMAslow),Cross(EMAslow,EMAfast))  "+NumToStr(Koop1,1.)+"\n"+
"Koop2: SLOPEfast > 0.150           = "+NumToStr(SLOPEfast,1.3)+"                                "+NumToStr(Koop2,1.)+"\n"+
"Koop3: SLOPEADX > 0.1             = "+NumToStr(SLOPEADX,1.3)+"                                 "+NumToStr(Koop3,1.)+"\n"+
"Koop4: PDI(13)-MDI(13)>10     = "+NumToStr(PDI(13)-MDI(13))+"                               "+NumToStr(Koop4,1.)+"\n"+
"Koop5: Close > Open                                                               "+NumToStr(Koop5,1.)+"\n"+
"BUY :                                                                                      "+NumToStr(Buy,1.0)+"\n\n"+

"Verkoop1-9 : Cross(TP?ine,LowLine)         "+NumToStr(Verkoop1+Verkoop2+Verkoop3+verkoop4+Verkoop5+verkoop6+verkoop7+verkoop8+verkoop9,1.0)+"\n"+
"Verkoop10 : Cross(Loss,Lowline)              "+NumToStr(Verkoop10,1.0)+"\n"+
"Verkoop11 : Cross(EMAslow,Low)             "+NumToStr(Verkoop11,1.0)+"\n"+
"SELL :                                                    "+NumToStr(VERKOOP,1.0)+"\n";

TimeFrameRestore(); // restore time frame to original

Filter=1;

AddColumn(Buy,"Buy",1.0,0,iif(Buy==1,colorOrange,colorWhite));
AddColumn(KOOP,"KOOP",1.0,0,iif(KOOP==1,colorOrange,colorWhite));
AddColumn(Koop1,"K1 cross EMA fs",1.0,0,iif(Koop1==1,colorGreen,colorWhite));
AddColumn(Koop2,"K2 Slopefast>0.150",1.0,0,iif(Koop2==1,colorGreen,colorWhite));
AddColumn(Koop3,"K3 SlodeADX>0.1",1.0,0,iif(Koop3==1,colorGreen,colorWhite));
AddColumn(Koop4,"K4 PDI-MDI>10",1.0,0,iif(Koop4==1,colorGreen,colorWhite));
AddColumn(Koop5,"K5 Close >Open",1.0,0,iif(Koop5==1,colorGreen,colorWhite));
AddColumn(Sell,"Sell",1.0,0,iif(Sell==1,colorOrange,colorWhite));
AddColumn(VERKOOP,"VERKOOP",1.0,0,iif(VERKOOP==1,colorOrange,colorWhite));
AddColumn(Verkoop1,"VK1 18%",1.0,0,iif(Verkoop1==1,colorGreen,colorWhite));
AddColumn(Verkoop2,"VK2 16%",1.0,0,iif(Verkoop2==1,colorGreen,colorWhite));
AddColumn(Verkoop3,"VK3 14%",1.0,0,iif(Verkoop3==1,colorGreen,colorWhite));
AddColumn(Verkoop4,"VK4 12%",1.0,0,iif(Verkoop4==1,colorGreen,colorWhite));
AddColumn(Verkoop5,"VK5 10%",1.0,0,iif(Verkoop5==1,colorGreen,colorWhite));
AddColumn(Verkoop6,"VK6 8%",1.0,0,iif(Verkoop6==1,colorGreen,colorWhite));
AddColumn(Verkoop7,"VK7 6%",1.0,0,iif(Verkoop7==1,colorGreen,colorWhite));
AddColumn(Verkoop8,"VK8 8%",1.0,0,iif(Verkoop8==1,colorGreen,colorWhite));
AddColumn(Verkoop9,"VK9 2%",1.0,0,iif(Verkoop9==1,colorGreen,colorWhite));
AddColumn(Verkoop10,"VK10 Cross Loss",1.0,0,iif(Verkoop10==1,colorGreen,colorWhite));
AddColumn(Verkoop11,"VK11 Cross EMASlow",1.0,0,iif(Verkoop11==1,colorGreen,colorWhite));




Please explain me what i did wrong?

Thanks Roel

@rola, I briefly looked at your code and it seems to me that you are using ExRem in a wrong way:

Try to modify your code here:

Koop5 = Close > Open;
KOOP  = Koop1 AND Koop2 AND Koop3 AND Koop4 AND Koop5;        
Buy   = KOOP;   
/// Comment out or remove this line since SELL array is not yet defined - you will add it later in the code
// Buy   = ExRem(Buy, Sell);

Change the code also here:

VERKOOP  	= Verkoop1 OR Verkoop2 OR Verkoop3 OR Verkoop4 OR Verkoop5 OR 
			  Verkoop6 OR Verkoop7 OR Verkoop8 OR Verkoop9 OR Verkoop10 OR Verkoop11;
Sell = VERKOOP;
/// Add this line now since you have defined both the BUY and SELL arrays
Buy   = ExRem(Buy, Sell);
Sell  = ExRem(Sell, Buy);

Later in the formula you call ExRem again and this too seems redundant.

1 Like

Hi Beppe,

Thanks for your nice reply.
The problem is solved :slight_smile:.

For my own understanding, i have one question left.

Before the Buy and Sell rules i defined Buy=0; and Sell=0;
So when i call the function Exrem(Buy,Sell) after the Buy rules the SELL array was defined otherwise there schould be an error occurred.

What i am misunderstanding is the fact how the originalcode operates once and then stops.
The Exrem function removes the buy and sell signals which occur after the first Buy or first Sell signal. I got the SELL signal. Why schouldn't i receive an new Buy signal ?

Can you explain that to me ?

Kind regards,

Roel

1 Like

Moving ExRem does not solve the problem of your code. The solution is to remove everything after SetOption lines and before Plot and to start from scratch again because most of it is incorrect.

First you are misusing TimeFrame functions. Please read below main sample links explaining how to properly using them
https://www.amibroker.com/guide/h_timeframe.html
https://www.amibroker.com/guide/afl/timeframeset.html
Hint: You seem to want to exit intra-weekly bar (on shorter intervals) at target levels. Buy and Sell rules (Koop1 to 5 and Koop, EMA cross of regular Sell) are only ones to be required to be inside TimeFrameSet. Buy, Sell exit code including target exits follow after Time Frame expansion (which is missing in your code, BTW).

Secondly you try to exit at target levels (profit/loss target or regular Sell (EMA cross)). In general to exit at target levels you either have to use ApplyStop function or you have to iterate (creating looping code).
Some material:
https://www.amibroker.com/guide/afl/applystop.html
http://www.amibroker.com/kb/index.php?s=applystop
https://www.amibroker.com/kb/2007/03/24/how-to-plot-a-trailing-stop-in-the-price-chart
http://www.amibroker.com/guide/h_backtest.html

Since you seem to want to scale-out at several target levels (since multiple levels are set from buy entry price in your code. So without scale-out the lowest profit target one (out of nine ones) would always be the exit one) you would have to iterate. Material:
Example 4: partial exit (scaling out) on profit target stops
https://www.amibroker.com/guide/h_pyramid.html

1 Like

Hi Fxshrat,

Thanks for the usefull guidelines.
Esspecialy the comment of misusing Timeframes. Top

Hi Amibroker Users,

I studied hard on the suggested topics and build the code again.
New effort comes with a variant on the first error.

After a regular sell signal the InTrade formule flips form 1 to zero like i want it to behave.

Sell = ExRem(Sell,Buy); // Only Fisrt Sell signal genrates Sell

ResetTrade = IIf(Sell>0, 1, 0); // Traillingstop generates sell==4, Regular Sell==1
InTrade = Flip( Buy, ResetTrade );`Code button (use to enter/paste AFL formula)`

In Example 1 you can see that Buy1 and Buy2 and Buy3 and Buy4 is active and the Buy signal is generated.Example1

In example 2 you see the Regular Sell. InTrade switches from 1 to 0.
Example2

In Example 3 there is new buy signal. But this trade will be ended bij a trailling stop instead of a regular sell signal. Example3

In Example 4 the Trailling stop is hit and and the sell Signal==4. Despite of the sell signal the InTrade function stays active "1" and schould be expected to switch to 0.
Example4

After a while in Example 5 the regular sell condition is met, but i generates not a sell signal, but it does reset the InTrade function. After this was happening there could be an new Buy signal.
Example5

I also present the signals generated in the exploration columns.
Explore1
Explore2

My questions about this case ?

1 What causes that after hitting the trailling stop the InTrade state does not reset like the regular sell signal ?

2 Why does the applystop function used by the //Build in custom Profit ActivationFloor not generate a sell signal.

3 Will you help me correct this code ?

The total code


SetTradeDelays(0,0,0,0);// geen vertragingen
SetOption("EveryBarNullCheck",True); // controleer of bar geen null waarde heeft
SetChartOptions(0, chartShowDates);// geef datum weer ook in eventuele chartpanes
SetChartOptions( 0, chartShowArrows );// plaats koop en verkoop pijlen op chart
SetChartOptions(2, chartWrapTitle );// plaats de titel binnen het chart
SetOption("InitialEquity",20000);// start kapitaal 20000
SetOption("MaxOpenPositions",30); // Maximaal aantal open posities (30)
SetOption("accountmargin",100); // leverage 100% EV en 0% VV
SetOption("CommissionMode",2); // Commission Amount bij aankoop en ook bij verkoop
Commissionmode = 2;
SetOption("CommissionAmount",5); // Commission per trade 5 euro
CommissionAmount = 5;
SetOption("Minshares",1);// Minimum 1 aandeel maximum aandelen in 1 koop aangeven 
SetOption("AllowPositionShrinking", True);
SetOption("AllowSameBarExit" , True );// If this option is not set true positions that are exited at the same bar remains open
SetOption("PriceBoundChecking", False);// This option must be set false in order to exit at specified stop price and not bar close
SetOption("UsePrevBarEquityForPosSizing",1); // gebruik vorige bar Equity voor positionsizing
SetOption("ActivateStopsImmediately",True); 

// Price in Chart
_SECTION_BEGIN("Price");
_N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) ));
Plot( C, "Close", ParamColor("Color", colorDefault ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() ); 
_SECTION_END();


// Risk Management
ATR20		= ATR(20);
StopSize	= 2.7 * ATR20;              // 2.7 maal gemiddelde waarde High-Low Laatste 20 dagen
StopLoss_L	= (Stopsize / Close)* 100 ; // Stoploss procentueel bij Long
StopLoss_S	= (Stopsize / Close) * 100; // Stoploss procentueel bij Short
RiskPct		= 1;                        // Risico percentage van totale Equity. 200000 * 1% = maximum 200 euro verlies per trade.
EquityVal	= Foreign("~~~EQUITY", "C");// waarde Equity
EquityRisk	= (RiskPct/100)*EquityVal;  // RiskPct * Equity = maximumverlies huidige equity
Lotsize     = round(EquityRisk / Stopsize);  // Amount stocks to Buy
PositionVal	= Lotsize * Close;               // Value stocks to Buy 
CostPct		= Nz(((Commissionmode * CommissionAmount) / PositionVal) * 100); // Cost Percent versus Lotsize. (CostPct < 2 = Ok)


// Set Variable Calculated in Weekly Timeframe
TimeFrameSet( inWeekly );
WMA62W 	= WMA( Close, 62 );
WMA4W	= WMA( Close,  4 );
CW		= Close;
TimeFrameRestore();


// BUY RULES. Trade with the StockTrend and trade with the StockMarketTrend
Buy1 = TimeFrameExpand (WMA62W, inWeekly)   > Ref(TimeFrameExpand(WMA62W,inWeekly),-1); // 62 Weeks weighted moving avarage is increasing
Buy2 = TimeFrameExpand (CW, inWeekly)       > TimeFrameExpand(WMA4W,inWeekly); // WeeklyClose is greater then 4 week weighted moving avarage
Buy3 = Ref(TimeFrameExpand(CW,inweekly),-1) > TimeFrameExpand(WMA4W,inWeekly); // Lastweek Close is greater then 4 week weighted moving avarage
Buy4 = TimeFrameExpand (CW, inWeekly)       > ref(TimeFrameExpand(CW,inWeekly),-1); // This week Close is greater than Lastweek Close
Buy = Buy1 AND Buy2 AND Buy3 AND Buy4;  

// SELL RULES. Sell when trend reverse
Sell1 = TimeFrameExpand (WMA62W, inWeekly)   < Ref(TimeFrameExpand(WMA62W,inWeekly),-1); // 62 weeks weighted moving avarage is decreasing  
Sell2 = TimeFrameExpand (CW, inWeekly)       < TimeFrameExpand(WMA4W,inWeekly);; // weeklyClose is smaller then 4 week weighted moving avarage              
Sell3 = Ref(TimeFrameExpand(CW,inweekly),-1) < TimeFrameExpand(WMA4W,inWeekly);; // Lastweek Close is smaller then 4 week weighted moving avarage           
Sell4 = TimeFrameExpand (CW, inWeekly)       < ref(TimeFrameExpand(CW,inWeekly),-1); // This week Close is smaller than Lastweek Close          
Sell  = Sell1 AND Sell2 AND Sell3 AND Sell4; 

Buy  = ExRem(Buy,Sell); // Only First Buy signal generates Buy
Sell = ExRem(Sell,Buy); // Only Fisrt Sell signal genrates Sell

ResetTrade = IIf(Sell>0, 1, 0); // Traillingstop generates sell==4, Regular Sell==1
InTrade = Flip( Buy, ResetTrade );

//Build in custom Profit ActivationFloor
EntryPrice = ValueWhen(Buy,BuyPrice);
Floor06 = IIf(C>EntryPrice * 1.12,6,0); // 12% profit fix Profitfloor 6%
Floor12 = IIf(C>EntryPrice * 1.18,6,0); // 18% profit fix Profitfloor 12%
Floor18 = IIf(C>EntryPrice * 1.24,6,0); // 24% profit fix Profitfloor 18%
Floor23 = IIf(C>EntryPrice * 1.29,5,0); // 29% profit fix Profitfloor 23%
Floor28 = IIf(C>EntryPrice * 1.34,5,0); // 34% profit fix Profitfloor 29%
Floor32 = IIf(C>EntryPrice * 1.38,4,0); // 38% profit fix Profitfloor 32%
Floor35 = IIf(C>EntryPrice * 1.41,3,0); // 41% profit fix Profitfloor 35%
Floor38 = IIf(C>EntryPrice * 1.43,3,0); // 43% profit fix Profitfloor 38%
Floor41 = IIf(C>Entryprice * 1.45,3,0); // 45% profit fix Profitfloor 41%
Active0 = (Floor06 + Floor12 + Floor18 + Floor23 + Floor28 + Floor32 + Floor35 + Floor38 + Floor41);
Active1 = HighestSince(Buy,Active0);// determine which floor is active
ActiveFloor = HighestSince(Buy,IIf(Active1 > 0, (Entryprice * (1+(Active1/100))), 0));// Amount Floor level
Activation = Close < ActiveFloor;// Check in chart stop condition on ActiveFloor amount
//ApplyStop( type, mode, amount, exitatstop, volatile = False, ReEntryDelay = 0, ValidFrom = 0, ValidTo = -1, ActivationFloor = 0 )
ApplyStop( stopTypeLoss, stopModePoint, ActiveFloor, ExitAtStop = 0);// STOP IS NOT WORKING ??? Exit=0 Check only Close price
PlotShapes(IIf(InTrade,22,shapeNone),colorAqua,0,ActiveFloor, offset=0);

//Plot Weighted Moving Averages
Plot(TimeFrameExpand(WMA62W,inWeekly),"WMA62",colorRed,styleThick);
Plot(TimeFrameExpand(WMA4W,inWeekly),"WMA4",colorLightBlue,styleThick);

// Trailingstoploss 2.7 * ATR(20)
ApplyStop(stopTypeTrailing, stopModePercent, StopLoss_L, ExitAtStop=1, Volatile=True, ReEntryDelay=1, ValidFrom=0, ValidTo=-1);
Equity( 1, 0 ); // evaluate stops, all quotes
StopValue = HighestSince( Buy, High ) * ( 1 - 0.01 * StopLoss_L );
Stopline  = IIf( InTrade, StopValue, Null );
Plot( Stopline, "trailing stop line", colorRed, styleDots );

//Plot buy and sell signal arrows LONG 
_SECTION_BEGIN("LONG Arrows");
EntryPrice = ValueWhen(Buy,BuyPrice);
ExitPrice  = ValueWhen(Buy,0);
ExitPrice  = ValueWhen(Sell,SellPrice);
ArrowColor = IIf(Sell==1,ColorWhite,IIf(Sell==4,colorYellow,0));// white is normal sell rule, Yellow is hit Stoploss 
Plot(EntryPrice,"Entry",colorGold,styleNoDraw);
Plot(ExitPrice,"Exit",colorGold,styleNoDraw);
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorGreen, 0, L, Offset=-40);
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorLime, 0, L, Offset=-50);
PlotShapes(IIf(Buy, shapeUpArrow, shapeNone),colorWhite, 0, L, Offset=-45);
PlotShapes(IIf(Buy, shapeStar,shapeNone),colorGold,0,L, Offset=0);
PlotShapes(IIf(Sell, shapeSquare, shapeNone),colorRed, 0, L, Offset=40);
PlotShapes(IIf(Sell, shapeSquare, shapeNone),colorOrange, 0, L, Offset=50);
PlotShapes(IIf(Sell, shapeDownArrow, shapeNone),ArrowColor,0, L, Offset=-40);
PlotShapes(IIf(Sell, shapeStar,shapeNone),colorwhite, 0, L, Offset=0);
dist  = 2.0 * ATR(10);
dist1 = 1.8 * ATR(10);
for( i = 0; i <BarCount; i++)
{
if (Buy[i])  PlotText("Buy  \n" +round(Entryprice[i]*100)/100, i, L[i]-dist[i], colorGreen, colorGold, yoffset=-50);
if (Sell[i]) PlotText("Sell \n"+ round(Exitprice[i]*100)/100, i, H[i]-dist1[i], colorRed, colorGold, yoffset=-50);
}
PlotShapes(IIf(InTrade,shapeSquare,shapeNone),colorGreen,0,EntryPrice, offset=-110);
_SECTION_END();

// Values Variable 
Title =StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) )+"\n"+
"InTrade:             "+NumToStr(InTrade,1.0)+"\n"+
"Entry:               "+NumToStr(Entryprice,1.2)+"\n"+
"EXit:                 "+NumToStr(Exitprice,1.2)+"\n"+
"Resultaat %     "+NumToStr(((ExitPrice / Entryprice)-1)*100,1.2)+" %\n\n"+

"WMA62:            "+NumToStr(WMA(C,62),1.2)+"\n"+
"WMA62-1:         "+NumToStr(Ref(WMA(C,62),-1),1.2)+"\n"+
"WMA4:              "+NumToStr(WMA(C,4),1.2)+"\n"+
"Close:               "+NumToStr(C,1.2)+"\n"+
"Close-1             "+NumToStr(Ref(C,-1),1.2)+"\n\n"+

"Buy1 = WMA(C,62) > Ref(WMA(C,62),-1) : "+NumToStr(Buy1,1.0)+"\n"+
"Buy2 = Close > WMA(C,4):                        "+NumToStr(Buy2,1.0)+"\n"+
"Buy3 = Ref(C,-1) > WMA(C,4):                  "+NumToStr(Buy3,1.0)+"\n"+
"Buy4 = Close > ref(Close,-1):                    "+NumToStr(Buy4,1.0)+"\n"+
"BUY :                                                        "+EncodeColor(colorLime)+NumToStr(Buy,1.0)+EncodeColor(colorWhite)+"\n\n"+

"Sell1 = WMA(C,62) < Ref(WMA(C,62),-1)   "+NumToStr(Sell1,1.0)+"\n"+
"Sell2 = Close < WMA(C,4)                         "+NumToStr(Sell2,1.0)+"\n"+
"Sell3 = Ref(C,-1) < WMA(C,4)                   "+NumToStr(Sell3,1.0)+"\n"+
"Sell4 = Close < ref(Close,-1)                     "+NumToStr(Sell4,1.0)+"\n"+
"SELL :                                                      "+EncodeColor(colorRed)+NumToStr(Sell,1.0)+EncodeColor(colorWhite)+"\n\n"+

"ATR(20):                 "+NumToStr(ATR20,1.2)+"\n"+
"Stopsize:                 "+NumToStr(Stopsize,1.2)+"\n"+
"Factor ATR(20):       "+NumToStr(Stopsize/ATR20,1.2)+"\n"+
"StopLoss %            "+NumToStr(Stoploss_L*-1,1.1)+" %\n"+
"StopLoss Value        "+NumToStr(Stopvalue,1.2)+"\n"+
"StopLoss Hit            "+EncodeColor(colorRed)+NumToStr(Cross(HighestSince( Buy, High ) * ( 1 - 0.01 * StopLoss_L ),L),1.0)+EncodeColor(colorWhite)+"      \n\n"+

"Profit since Buy:            "+NumToStr(((C/Entryprice)-1)*100,1.2)+" % \n"+
"Max. Profit since Buy:    "+NumToStr((((HighestSince(Buy,C)/Entryprice)-1))*100,1.2)+" %\n"+
"Resultaat %                    "+NumToStr(((ExitPrice / Entryprice)-1)*100,1.2)+" %\n\n"+
"Active1:                    "+NumToStr(Active1,1.0)+"\n"+
"Active Floor           "+NumToStr(ActiveFloor,1.2)+"\n"+
"Activation                    "+NumToStr(Activation,1.0);


// Column exploration code for verification

// 0 - No signal
// 1 - regular exit 
// 2 - max. loss  
// 3 - profit target  
// 4 - trailing stop 
// 5 - n-bar stop 
// 6 - ruin stop  
// 7 - Buy 
// 8 - Buy and Regular Exit same bar

Filter=1;
TextList = "No signal\n Sell Regular exit\n Sell Max. Loss\n Sell Profit Target\n Sell Trailling Stop\n Sell n-bar Stop\n Sell Ruin Stop\n Buy\n Buy and Sell"; 
TextSelector = 1*Sell +7*Buy;
AddMultiTextColumn( TextSelector, TextList, "Which signal", 1, IIf( Buy, colorGreen, IIf( Sell, colorRed, colorBlue)),55,140);
AddColumn (Buy1 + Buy2 + Buy3 + Buy4,"BUY1234",1.2,1,IIf(Buy1+Buy2+Buy3+Buy4 == 4,8,55),100);
AddColumn (Buy,"Buy",1.0,1,IIf(Buy == 1,8,55),45);
AddColumn (EntryPrice,"EntryPrice",1.2,1,55,100);
AddColumn (ResetTrade,"ResetTrade",1.0,1,55,50);
AddColumn (InTrade,"InTrade",1.0,1,IIf(InTrade == 1,42,55),100);
AddColumn (Sell1 + Sell2+ Sell3 + sell4,"Sell1234",1.2,1,IIf(Sell1+Sell2+sell3+sell4 == 4,32,55),100);
AddColumn (Sell,"Sell",1.0,1,IIF(Sell == 1,32,IIf(Sell==4,25,55)),45);
AddColumn (ExitPrice,"ExitPrice",1.2,1,55,100);
AddColumn (Close,"Close",1.2,1,55,100);
AddColumn (Low,"Low",1.2,1,55,100);
AddColumn (StopValue,"StopValue",1.2,1,IIf(Low < Stopvalue,25,55),100);
AddColumn (Active0,"Active0",1.2);
AddColumn (Active1,"Active1",1.2);
AddColumn (ActiveFloor,"ActiveFloor",1.2);
AddColumn (Activation,"Activation",1.2,1,IIf(Activation == 1,25,55));
AddColumn (ATR20,"ATR20",1.2);
AddColumn (Close,"Close",1.2);
AddColumn (StopSize,"RiskSize",1.2);
AddColumn (Stoploss_S,"StopLoss_S",1.2);
AddColumn (RiskPct,"RiskPct",1.1);
AddColumn (EquityVal,"EquityVal",1.2);
AddColumn (EquityRisk,"EquityRisk",1.2);
AddColumn (Lotsize,"Lotsize",1.2);
AddColumn (PositionVal,"PositionVal",1.2);
AddColumn (CostPct,"CostPct",1.2);
AddColumn(((C - Ref(C,-1))/Ref(C,-1))*100 ,"% Increase ");
AddColumn(C,"Price");
AddColumn(V,"Volume");

1 Like