Please, help me to amend this code (no buy/sell signals / how to plot applystop exit shapes?)

//////////////chart & back ground color////////////////////
SetChartBkGradientFill(colorBlack,colorBlack,colorBlack);
//Plot( C, "Close", ParamColor("Color", colorDefault ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() ); 
Plot( Close, "C", colorWhite, styleCandle); 
separator = Day() != Ref( Day(), -1 );
Plot( separator, "", colorPink, styleHistogram | styleOwnScale | styleNoLabel | styleNoRescale, 0, 1, 0, -2, 5 );
starttime = 091500;
endtime = 151500;
separator = Day() != Ref( Day(), -1 );
insession =  timenum() >= starttime && timenum() <= 151000;
endsession = timenum() >= endtime;
endsession = ( endsession - Ref( endsession, -1 ) ) == 1 ;//OR Ref( separator, 1 );
startsession = timenum() >= starttime;
startsession = ( startsession - Ref( startsession, -1 ) ) == 1;
timelmits =    insession  && !endsession; 
Plot( endsession, "", colorWhite, styleHistogram | styleOwnScale | styleNoLabel | styleNoRescale, 0, 1, 0, -2, 1 );
Plot( startsession, "", colorViolet, styleHistogram | styleOwnScale | styleNoLabel | styleNoRescale, 0, 1, 0, -2, 1 );
GraphXSpace=85;
//////////////////////
ema1 = EMA( C, 5 );
ema2 = EMA( C, 10 );
Plot(ema1,"",colorBlue,styleThick);
Plot(ema2,"",colorRed,styleThick);

Buy = Cross(ema1,ema2 );
Short = Cross( ema2, ema1 );

Equity(1); 

Sell = Cover = 0; // 0 or False means exit only by ApplyStop
ApplyStop( stopTypeLoss, stopModePercent, 5 ); // 5% max loss from short/buy price
ApplyStop( stopTypeProfit, stopModePercent, 5 ); // 5% profit target from short/buy price

HaClose =EMA((O+H+L+C)/4,3); 
HaOpen = AMA( Ref( HaClose, -1 ), 0.5 );
HaHigh = Max( H, Max( HaClose, HaOpen ) );
HaLow = Min( L, Min( HaClose, HaOpen ) );   
PlotShapes( IIf( Buy , shapeUpArrow,0) , colorGreen ,layer = 0, yposition = HaLow, offset = -8);
PlotShapes( IIf( SHORT , shapeDownArrow,0) , colorRed ,layer = 0, yposition = HaHigh, offset = -8);
//PlotShapes( IIf( SELL , shapeHollowDownArrow,0) , colorRed ,layer = 0, yposition = HaHigh, offset = -8);
//PlotShapes( IIf( COVER, shapeHollowUpArrow,0) , colorGreen ,layer = 0, yposition = HaLow, offset = -8);

The above code produces the chat as below:

image

My problem are as below:

  1. Why I am not getting the Buy and Short signals?
  2. How to plot the exit signals by the applystop codes?

please help me to correct my coding errors to get the desired output.

Buy transaction should be followed by Sell order &
Short transaction should be followed by Cover order

that's the axioms for the logical sequence of any transaction in stock market .. right ?

for this reason you may need to revise and modify line no 26 .. Simply replacing short by sell would made your code working fine

@santy, when you run in trouble with a formula, one way to debug it is to simplify it as much as possible (always adding an exploration to check the buy/sell rules logic).
Then, start to add other code/conditions again and continuously verify your most recent changes to know what you did precisely when at a certain point the formula no longer works as expected.
For instance, I simplified your formula to work with EOD data and as a "long" only strategy (no short/cover logic), moved the Equity(1) line (see comments) and it seems to work:

//////////////chart & back ground color////////////////////
SetChartBkGradientFill( colorBlack, colorBlack, colorBlack );
Plot( Close, "C", colorWhite, styleCandle );
//////////////////////
ema1 = EMA( C, 5 );
ema2 = EMA( C, 10 );
Plot( ema1, "", colorBlue, styleThick );
Plot( ema2, "", colorRed, styleThick );

Buy = Cross( ema1, ema2 );
Sell = 0; // 0 or False means exit only by ApplyStop

Short = 0; // Not used - Cross( ema2, ema1 );
Cover = 0; 

ApplyStop( stopTypeLoss, stopModePercent, 5 ); // 5% max loss from short/buy price
ApplyStop( stopTypeProfit, stopModePercent, 5 ); // 5% profit target from short/buy price
// note the position of the Equity(1) line  as per documentation:
// https://www.amibroker.com/guide/afl/equity.html
Equity( 1 );
// Depending on kind of the stop various values are written back to sell/cover array to enable you
// to distinguish if given signal was generated by regular rule or by stop.
// 1 - regular exit
// 2 - max. loss
// 3 - profit target
// 4 - trailing
// 5 - n-bar stop
// 6 - ruin stop 

PlotShapes( IIf( Buy , shapeUpArrow, 0 ) , colorWhite , 0, L, -12 );
PlotShapes( IIf( Sell , shapeDownArrow, 0 ) , colorYellow, 0, H, 12 );


Filter = 1;
AddColumn( Buy, "Buy", 1 );  
AddColumn( Sell, "Sell", 1 ); // check the result codes in this array

If this is what you expect from your formula, then start to add back your code, one small piece at a time, and check the intermediate results until you reach your goal.

Happy debugging!

6 Likes

Thanks a lot for your guidance.
what should be the code for SellPrice here for claculations?

BuyPrice = ValueWhen( Buy, O );
SellPrice =???;

@Santy why do you want to define a SellPrice when your code does not have a Sell rule?
The actual "sell" price is decided by the market when your stop loss or profit taking levels are reached.

Moreover, I will double check also the rule used for the BuyPrice: is it realistic? In a real trade can you buy at the open price on the bar where you get a signal?

Additionally, since you are using the Equity() function, I suggest you read with attention all the comments section where TJ provides some details about its proper utilization.

1 Like

image

I want to print the prices ad trade results on the chart as shown in the above picture. so I need the sellprice code.

it will also help to verify if the system works properly i.e are the exits as per the condition in the applystop code or not.

so, please help to find a way.

@santy Amibroker already defines default BuyPrice and SellPrice; these arrays are filled in with the default values according to the Automatic Analyser settings - see this documentation page.

As I wrote before, exploration IMHO is the best tool available to check your code logic dealing with arrays.
Personally, I would change the sample exploration as follows:

// Comment out any BuyPrice/SellPrice line to see the default values
// BuyPrice = ValueWhen( Buy, O );
// SellPrice =???;

myBuyPrice = ValueWhen( Buy, O ); // to check what happens using this function

Filter = 1;
AddColumn( Buy, "Buy", 1 );  
AddColumn( Sell, "Sell", 1 ); // check the result codes in this array
AddColumn( BuyPrice, "BuyPrice", 1.2 ); 
AddColumn( SellPrice, "SellPrice", 1.2 ); 
AddColumn( Open, "Open", 1.2 ); 
AddColumn( High, "High", 1.2 ); 
AddColumn( Low, "Low", 1.2 ); 
AddColumn( Close, "Close", 1.2 ); 
AddColumn( myBuyPrice, "myBuyPrice", 1.2);

(the last line is used to verify what values are in the array returned using the ValueWhen(Buy, 0) code as per your previous post).

If the default BuyPrice/Sell Price arrays value are not what you want to use in your backtest you can redefine them evaluating/doing calculations the other columns prices, but be aware of the possible impact on your strategy.

On the other hand, if you simply want to "plot" their values on the chart, you should just use the default arrays value without reassigning them.
Here is a snippet that will plot those values (adding on the sell side also the kind of exit):

// Plot BuyPrice / SellPrice arrays
bi = Barindex();
fvb = FirstVisiblevalue( bi );
lvb = LastVisiblevalue( bi );

for( i = fvb; i <= lvb; i++ )
{
    if( Buy[i] )
        PlotText( "Buy\n" + BuyPrice[i], i, BuyPrice[i], colorWhite, -1, 0 ); 

    if( Sell[i] )
    {
        sellTrigger = "";
		switch( Sell[i] )
        {
            case 1:
                sellTrigger = ""; break;
            case 2:
                sellTrigger = "Stop"; break;
            case 3:
                sellTrigger = "Profit"; break;
            case 4:
                sellTrigger = "Trail"; break;
            case 5:
                sellTrigger = "N-Bars"; break;
            case 6:
                sellTrigger = "Ruin"; break;
        }
        PlotText( sellTrigger + "\n" + SellPrice[i], i, SellPrice[i], colorYellow, -1, 0 );
    }
}

In any case, although displaying prices and arrows on the chart is a nice touch, what really matter is the Backtest report with its entries/exit prices. Makes sure that all your values are aligned.

3 Likes
//////////////chart & back ground color////////////////////
SetChartBkGradientFill( colorBlack, colorBlack, colorBlack );
Plot( Close, "C", colorWhite, styleCandle );
//////////////////////
ema1 = EMA( C, 5 );
ema2 = EMA( C, 10 );
Plot( ema1, "", colorBlue, styleThick );
Plot( ema2, "", colorRed, styleThick );

Buy = Cross( ema1, ema2 );
Sell = 0; // 0 or False means exit only by ApplyStop

Short = 0; // Not used - Cross( ema2, ema1 );
Cover = 0; 

ApplyStop( stopTypeLoss, stopModePercent, 5 ); // 5% max loss from short/buy price
ApplyStop( stopTypeProfit, stopModePercent, 5 ); // 5% profit target from short/buy price
// note the position of the Equity(1) line  as per documentation:
// https://www.amibroker.com/guide/afl/equity.html
Equity( 1 );
// Depending on kind of the stop various values are written back to sell/cover array to enable you
// to distinguish if given signal was generated by regular rule or by stop.
// 1 - regular exit
// 2 - max. loss
// 3 - profit target
// 4 - trailing
// 5 - n-bar stop
// 6 - ruin stop 

PlotShapes( IIf( Buy , shapeUpArrow, 0 ) , colorWhite , 0, L, -12 );
PlotShapes( IIf( Sell , shapeDownArrow, 0 ) , colorYellow, 0, H, 12 );
bi = Barindex();
fvb = FirstVisiblevalue( bi );
lvb = LastVisiblevalue( bi );

for( i = fvb; i <= lvb; i++ )
{
    if( Buy[i] )
        PlotText( "Buy\n" + BuyPrice[i], i, BuyPrice[i], colorWhite, -1, 0 ); 

    if( Sell[i] )
    {
        sellTrigger = "";
		switch( Sell[i] )
        {
            case 1:
                sellTrigger = ""; break;
            case 2:
                sellTrigger = "Stop"; break;
            case 3:
                sellTrigger = "Profit"; break;
            case 4:
                sellTrigger = "Trail"; break;
            case 5:
                sellTrigger = "N-Bars"; break;
            case 6:
                sellTrigger = "Ruin"; break;
        }
        PlotText( sellTrigger + "\n" + SellPrice[i], i, SellPrice[i], colorYellow, -1, 0 );
    }
}

Filter = 1;
AddColumn( Buy, "Buy", 1 );  
AddColumn( Sell, "Sell", 1 ); // check the result codes in this array


image

Ok, now i get the above chart for the code.

There is no arrows----no texts and prices on the chart.

could you please guide where I went wrong?

You are on 5 second chart but profit and loss targets are set to 5%.
So just lower the percentage value in the code (e.g. to 1% or lower). Then you should see (more) signals in your 5 sec chart.
123512

Also there isn't switch statement required here. Simply use StrExtract function - shorter, faster code.

//////////////chart & back ground color////////////////////
SetChartBkGradientFill( colorBlack, colorBlack, colorBlack );
Plot( Close, "C", colorWhite, styleCandle );
//////////////////////

ema1 = EMA( C, 5 );
ema2 = EMA( C, 10 );
Plot( ema1, "", colorBlue, styleThick );
Plot( ema2, "", colorRed, styleThick );

Buy = Cross( ema1, ema2 );

Sell = 0; // 0 or False means exit only by ApplyStop
Short = 0; // Not used - Cross( ema2, ema1 );
Cover = 0; 

ApplyStop( stopTypeLoss, stopModePercent, 1 ); // n% max loss from short/buy price
ApplyStop( stopTypeProfit, stopModePercent, 1 ); // n% profit target from short/buy price
// note the position of the Equity(1) line  as per documentation:
// https://www.amibroker.com/guide/afl/equity.html

Equity( 1 );
// Depending on kind of the stop various values are written back to sell/cover array to enable you
// to distinguish if given signal was generated by regular rule or by stop.
// 1 - regular exit
// 2 - max. loss
// 3 - profit target
// 4 - trailing
// 5 - n-bar stop
// 6 - ruin stop 

PlotShapes( IIf( Buy , shapeUpArrow, 0 ) , colorWhite , 0, L, -12 );
PlotShapes( IIf( Sell , shapeDownArrow, 0 ) , colorYellow, 0, H, 12 );

bi = Barindex();
fvb = FirstVisiblevalue( bi );
lvb = LastVisiblevalue( bi );

selltrigger = "Regular,Stop,Profit,Trail,N-bars,Ruin";

for( i = fvb; i <= lvb; i++ )
{
    if( Buy[i] )
        PlotText( "Buy\n" + BuyPrice[i], i, BuyPrice[i], colorWhite, -1, 0 ); 
    if( Sell[i] )
        PlotText( StrExtract(sellTrigger, Sell[i]-1) + "\n" + SellPrice[i], i, SellPrice[i], colorYellow, -1, 0 );
}

Filter = 1;
AddColumn( Buy, "Buy", 1 ); 
AddColumn( Sell, "Sell", 1 ); // check the result codes in this array
3 Likes

Thanks a lot for your help. now it works fine.

Just I wanted to include short and cover also ---and now the problem is short and cover signals and texts are not getting printed on chart as they are there for buy and sell.

Below is the code and screen print----please help/guide further.

//////////////chart & back ground color////////////////////
SetChartBkGradientFill( colorBlack, colorBlack, colorBlack );
Plot( Close, "C", colorWhite, styleCandle );
//////////////////////
ema1 = EMA( C, 5 );
ema2 = EMA( C, 10 );
Plot( ema1, "", colorBlue, styleThick );
Plot( ema2, "", colorRed, styleThick );

Buy = Cross( ema1, ema2 );
Sell = 0; // 0 or False means exit only by ApplyStop
ApplyStop( stopTypeLoss, stopModePoint, 15, ExitAtStop = 1, 
            Volatile = False, ReentryDelay = 1, ValidFrom = 0, -1 );
ApplyStop( stopTypeProfit, stopModePoint,10 , 
            ExitAtStop = 1, Volatile = False, ReentryDelay = 1, 
            ValidFrom = 1, -1 );
            
Short = Cross( ema2, ema1 );
Cover = 0; 

ApplyStop( stopTypeLoss, stopModePoint, 15, ExitAtStop = 1, 
            Volatile = False, ReentryDelay = 1, ValidFrom = 0, -1 );
ApplyStop( stopTypeProfit, stopModePoint,10 , 
            ExitAtStop = 1, Volatile = False, ReentryDelay = 1, 
            ValidFrom = 1, -1 );
Equity( 1 );

HaClose =EMA((O+H+L+C)/4,3); 
HaOpen = AMA( Ref( HaClose, -1 ), 0.5 );
HaHigh = Max( H, Max( HaClose, HaOpen ) );
HaLow = Min( L, Min( HaClose, HaOpen ) );   

PlotShapes( IIf( Buy , shapeUpArrow,0) , colorGreen ,layer = 0, yposition = HaLow, offset = -8);
PlotShapes( IIf( SHORT , shapeDownArrow,0) , colorRed ,layer = 0, yposition = HaHigh, offset = -8);
PlotShapes( IIf( SELL , shapeHollowDownArrow,0) , colorRed ,layer = 0, yposition = HaHigh, offset = -8);
PlotShapes( IIf( COVER, shapeHollowUpArrow,0) , colorGreen ,layer = 0, yposition = HaLow, offset = -8);

bi = Barindex();
fvb = FirstVisiblevalue( bi );
lvb = LastVisiblevalue( bi );

sellorcovertrigger = "Regular,Stop,Profit,Trail,N-bars,Ruin";

for( i = fvb; i <= lvb; i++ )
{
    if( Buy[i] )
        PlotText( "Buy\n" + BuyPrice[i], i, BuyPrice[i], colorGreen, -1, 0 ); 
    if( Sell[i] )
        PlotText( StrExtract(sellorcovertrigger, Sell[i]-1) + "\n" + SellPrice[i], i, SellPrice[i], colorRed, -1, 0 );
    if( Short[i] )
        PlotText( "Short\n" + ShortPrice[i], i, ShortPrice[i], colorRed, -1, 0 ); 
    if( Cover[i] )
        PlotText( StrExtract(sellorcovertrigger, Cover[i]-1) + "\n" + CoverPrice[i], i, CoverPrice[i], colorGreen, -1, 0 );
  
}

image

You do not need to call Applystop "one-thousand" times but just one time per each stop type.

//////////////chart & back ground color////////////////////
SetChartBkGradientFill( colorBlack, colorBlack, colorBlack );
Plot( Close, "C", colorWhite, styleCandle );
//////////////////////

ema1 = EMA( C, 5 );
ema2 = EMA( C, 10 );
Plot( ema1, "", colorBlue, styleThick );
Plot( ema2, "", colorRed, styleThick );

Buy = Cross( ema1, ema2 );
Short = Cross( ema2, ema1 );

Sell = 0; // 0 or False means exit only by ApplyStop
Cover = 0; 

ApplyStop( stopTypeLoss, stopModePoint, 15, ExitAtStop = 1, Volatile = False, ReentryDelay = 1, ValidFrom = 0, -1 );
ApplyStop( stopTypeProfit, stopModePoint,10,  ExitAtStop = 1, Volatile = False, ReentryDelay = 1, ValidFrom = 1, -1 );

Equity( 1 );

HaClose =EMA((O+H+L+C)/4,3); 
HaOpen = AMA( Ref( HaClose, -1 ), 0.5 );
HaHigh = Max( H, Max( HaClose, HaOpen ) );
HaLow = Min( L, Min( HaClose, HaOpen ) );  

PlotShapes( IIf( Buy, shapeUpArrow,0) , colorGreen ,layer = 0, yposition = HaLow, offset = -8);
PlotShapes( IIf( SHORT, shapeDownArrow,0) , colorRed ,layer = 0, yposition = HaHigh, offset = -8);
PlotShapes( IIf( SELL, shapeHollowDownArrow,0) , colorRed ,layer = 0, yposition = HaHigh, offset = -8);
PlotShapes( IIf( COVER, shapeHollowUpArrow,0) , colorGreen ,layer = 0, yposition = HaLow, offset = -8);


bi = Barindex();
fvb = FirstVisiblevalue( bi );
lvb = LastVisiblevalue( bi );

sellorcovertrigger = "Regular,Stop,Profit,Trail,N-bars,Ruin";

for( i = fvb; i <= lvb; i++ )
{
    if( Buy[i] )
        PlotText( "Buy\n" + BuyPrice[i], i, BuyPrice[i], colorGreen, -1, 0 ); 

    if( Sell[i] )
        PlotText( StrExtract(sellorcovertrigger, Sell[i]-1) + "\n" + SellPrice[i], i, SellPrice[i], colorRed, -1, 0 );

    if( Short[i] )
        PlotText( "Short\n" + ShortPrice[i], i, ShortPrice[i], colorRed, -1, 0 ); 

    if( Cover[i] )
        PlotText( StrExtract(sellorcovertrigger, Cover[i]-1) + "\n" + CoverPrice[i], i, CoverPrice[i], colorGreen, -1, 0 );
}

It works here

212

4 Likes

but my chart is like below for the same code:

image

any reason why I am not getting the short and cover on shart?

Check Analysis /BackTest Settings , may be you have selected only Buy , Select Both Buy & Short .

3 Likes

I did not change any settings---all are defaults only!!!

@santy,

@NowToLook has given you correct answer. Default positions setting in analysis is "Long" after initial AmiBroker installation. Equity() function being used in your ApplyStop code is old single security backtester so it is attached to analysis settings. So if in analysis settings "Positions" setting is still at "Long" only then Short trades are ignored. So go to analysis settings general tab and set to "Long and Short" there.
Just in addition... do restart AmiBroker after changing to Long&Short in Analysis settings.
2018-06-19_141051

PS: Stop using multiple exclamation marks or we will stop here. We don't have to do this.

4 Likes

Sorry. My apologies for the multiple exclamation marks.

Now its working fine.

Thanks all for the help.

ApplyStop( stopTypeProfit, stopModePoint,10, ExitAtStop = 1, Volatile = False, ReentryDelay = 1, ValidFrom = 1, -1 );

please guide how to amend the above line to get the desired output as below:
The exit point while in profit , should be revised to +5 points for every +10 points rise in the new high / low while in a buy / short trade respectively and the trade should be ridden till the exit happens due to the above logic.

Any help for the above please.

Any help for the above please.

Greatings of the Day!

I need some help for the applystop code for the trailing profit type. Can I ask now?