Applystop problem

Hello. I need some help concerning the applystop.
I have read the documents but I don`t find it .
Buy at the open of the next day and close the same day. If the market falls on this day 20 Points from the open stop will trigger. In my code the stoploss is not working. Can someone help me out here.

// I would like to buy at the open on the next day if Buycondition 
// and sell at the close. Stoploss 20 Point  
//Problem the stoploss is NOT working I have set the Applystop at 1 
// I am using daily data EOD 

SetOption( "AllowSameBarExit", true);
SetOption("ActivateStopsImmediately", True ); 
SetOption("FuturesMode", True );   
PointValue = 5;
 
SetOption( "initialequity", 30000 );
SetOption("accountmargin",10); 
SetPositionSize( 1, spsShares );  
SetTradeDelays(1,1,1,1);
days = LLV( L, 20 );
//timestop
Days_Stop = 0;
ApplyStop(stopTypeNBar, stopModeBars, Days_Stop, 1, volatile = False, ReEntryDelay = 0, ValidFrom = 0, ValidTo = -1, ActivationFloor = 0 ) ;
// stoploss 20 Points
ApplyStop(stopTypeloss,stopModePoint,20,1,False,0); //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
 
Setup = Cross( H, Ref( days, -1 ) ); 

Buy_setup = Setup;

BuyPrice =  Open;   
SellPrice = Close;   
 
Buy = Buy_setup;
Sell = 0;

Hi Munichtrader,

I'm just learning AFL, so there might be more to the answer, but I tried a couple of things, and here is what I found:

You have these 3 lines (by the way, I commented out the 20-Point stop before trying the NbarStop):

SetOption("ActivateStopsImmediately", True );
Days_Stop = 0;
ApplyStop(stopTypeNBar, stopModeBars, Days_Stop, 1, volatile = False, ReEntryDelay = 0, ValidFrom = 0, ValidTo = -1, ActivationFloor = 0 ) ;

which basically instructs AmiBroker to use a TimeStop of 0 bars, so it complies and takes you out of the trade, and the holding period is just 1 bar.

If you change ActivateStopsImmediately to False, you will stay in the trade for 2 bars.

I think the behavior you get with ActivateStopsImmediately True is what you want, based on your explanations, and if so, then so far, so good...

Moving along, you have another 2 lines of code:

SetOption( "AllowSameBarExit", True );
ApplyStop(stopTypeLoss, stopModePoint, 20, 1, False, 0); // stoploss 20 Points

I don't know what 20 means for you, but to test this idea I used a FX database and changed that to 20 * TickSize. The backtest worked as expected (hitting a stop loss of 20 ticks) BUT ONLY after I disabled the TimeStop (= NbarStop).

So, based on what I tried, it looks like the TimeStop kicks in before the StopLoss, even though the documentation says the order should be with TimeStop (N-bar stop) as the last to kick in...

Maybe there is another parameter that overrides the behavior of NbarStop being the last?

You post a link to Applystop documentation which you have not carefully read till the very end.

You have set ExitAtStop to 1. So nbar stop has highest priority in your case.

2 Likes

Thanks for jumping in and correcting me, fxshrat. I did my best to help, but indeed I missed that part...

The merged information from the documentation then it reads like this, and it all makes sense:

If two or more different stops are triggered on the VERY SAME bar then they are evaluated in this fixed order:

N-bar stop, if ExitAtStop was set to 1 OR "Has priority" box is checked in AA Settings window
Fixed Ruin stop (losing 99.96% of the starting capital)
Max. loss stop
Profit target stop
Trailing stop
N-bar stop, if ExitAtStop was set to 0

Thanks for your help. Is there a solution possible for an open trade to buy at the open and close it end of the day with an for example stop of 20 Points with
SetTradeDelays(1,1,1,1)
For example
Trade entry: XYZ today
fill at the open of the next day
and close it end of the day
Stoploss: XYZ Points - exit if OPEN -20 else sell it to the close.
Thanks for any help.

Not behind pc but should be as simple as

SetTradeDelays(1, 0, 1, 1) (or set cover to 0 if needed)

Sell = 1;
Buyprice = open;
Sellprice = close;

@Munichtrader I don't use ApplyStop so this is just a suggestion for you to try. I believe it will perform what you need (if you are using Daily bars).

SetTradeDelays( 1, 0, 0, 0 );
SetOption( "AllowSameBarExit", True );
Buy 	= // enter your buy rules
Sell 	= Ref(Buy, -1); // Buy signal was on previous bar

BuyPrice 	= Open;
SellPrice 	= Close;
CoverPrice = Short = 0;

ApplyStop(stopTypeLoss, stopModePoint, 20, 1, False, 0);

1 Like

thanks portfoliobuilder, but this not working to setup the stop intraday with EOD data.
It is selling at the close and not taking the stop. It is not possible to use a stop here with EOD data?

SetPositionSize( 1, spsShares );
SetOption("FuturesMode", True );  
PointValue = 50;

SetTradeDelays( 1, 0, 0, 0 );
SetOption( "AllowSameBarExit", True );

  
Buy_setup= Cross( MACD(), SIGNAL() );

Buy 	= Buy_setup  ;
Sell 	= Ref(Buy, -1); // Buy signal was on previous bar

BuyPrice 	= Open;
SellPrice 	= Close;
CoverPrice = Short = 0;

ApplyStop(stopTypeLoss, stopModePoint, 20, 1, False, 0);

// Columns
Filter = 1;
 
AddColumn(buy, "Buy", 1.0, colorWhite,IIf(buy, colorGreen, colorDefault) );
AddColumn(ROC(Close,1) , "%TG", 1.2 );
AddColumn( Open, "Open", 1.2 );
AddColumn(Low,"Low",1.2);
AddColumn(High,"High",1.2);
AddColumn( Close, "Close", 1.2 );

Sorry but it's working for me on stock data ( I don't have futures data to test it on).
Ran a quick test,

Tuesday = DayOfWeek() == 2;

maxpos = 1; // maximum number of open positions
SetOption("InitialEquity", 100000 ); // set initial equity = 100K
SetOption( "MaxOpenPositions", maxpos );
SetPositionSize( 1, spsShares  ); // 1 share in each trade

SetTradeDelays( 1, 0, 0, 0 );
SetOption( "AllowSameBarExit", True );

Buy 	= Tuesday;
Sell 	= Ref(Buy, -1);

BuyPrice 	= Open;
SellPrice 	= Close;

CoverPrice = Short = 0;

ApplyStop(stopTypeLoss, stopModePoint, 20, 1, False, 0); // stoploss 20 Points

image

Sorry as I wrote I do not use ApplyStop so have no further advice. The above code works for me. Maybe someone more familiar with it can help.

Thanks. I found the mistake. Under Stops I changed the scenario.
Many thanks.:smile:

Nbar stop does work contrary to your incorrect claim of ApplyStop not working.
For nbar stop set priority to zero as been posted above.
Also it's not a good practice to mix SetTradeDelays (non-zero values) with Ref().
Either use Ref or SetTradeDelays.
Besides simply set Sell = 1; instead of using Sell = Ref(...).

Anyway here is ApplyStop code.

SetOption("InitialEquity", 100000 ); 
SetOption( "MaxOpenPositions", 1 );
SetPositionSize( 1, spsShares  ); 

SetTradeDelays( 0, 0, 0, 0 );// disable trade delays of analysis settings
SetOption( "ActivateStopsImmediately", True );

Buy_setup = Cross( MACD(), SIGNAL() );

Buy 	= Ref(Buy_setup,-1);
Sell 	= 0;

BuyPrice = Open;
SellPrice = Close;
Cover = Short = 0;

ApplyStop(stopTypeNBar, stopModeBars, bars = 0, priority = 0); 
ApplyStop(stopTypeLoss, stopModePoint, points = 20, exitatstop = 1); 

9

1 Like

It looks for me not right. If I use the script from portfoliobuilder it seems right, fxshrat I get to many wrong signals. Can you compare your scripts with the same symbol, than I would like to see the difference. Thanks for your suggestion.

I disagree. The code works correctly in my tests.
If stop loss target is not reached within same day as day of entry then nbar stop comes into play and exits at end of day of same day.

You possibly confuse loss target with profit target. But it is you who set StopTypeLoss in 1st post.
Or you applied the code in Exploration which is incorrect way of applying that code. FYI ApplyStop is backtester function.

Re-read ApplyStop documentation in manual.
In addition set "Scenario" to "Custom" in Analysis settings -> "Stops" tab and disable all UI stops.
We are using code stops but not UI stops.

Alternativaly to using ApplyStop function you may just use UI settings to get same results.
So instead of upper code use this one

SetOption("InitialEquity", 100000 ); 
SetOption( "MaxOpenPositions", 1 );
SetPositionSize( 1, spsShares  ); 
SetTradeDelays( 0, 0, 0, 0 );// disable trade delays of analysis settings
SetOption( "ActivateStopsImmediately", True );

Buy_setup = Cross( MACD(), SIGNAL() );

Buy 	= Ref(Buy_setup,-1);
Sell 	= 0;

BuyPrice = Open;
SellPrice = Close;

Cover = Short = 0;

And then applys these Stop settings of UI.

9

I don't sit in front of your PC! Saying "looks not right" is not helpful but waste of time and energy.
Simply upload symbol file (of database) and APX file. It is as simple as that. "looks not right" is rubbish in my book. Why wasting so much energy for creating a pointless post that no one can follow? To me such posts are of category "spam". I don't understand some people's way of thinking.

Thanks for your nice words. For two code solutions why is this waste of time to find the right code to solve the problem. If you are master then stay polite and not arrogant. My target is to learn and not like you said to create pointless post.
Unfortunally the scenarios are not explain to create different solution. The first code works for me fine with the scenario trade next bar to open and stops intraday. Your code is correct but the scenario must change again. Very confusing for beginners.

I am not your master and not your God.
Also I am not arrogant but telling it the way it is.
You expect detail but are not providing detail.
Re-read your previous post. What sense is reader supposed to make out of it? I will tell you... none.
Why if being beginner making post "looks not right" (which is useless to any reader) without being detailed about what is not right and what has been used and set? Once again such posts are considered spam in my book. It's not arrogance it is fact.


???

So all of the sudden it is correct. So we conclude... user error on your end.

In any other case

And provide detail (please).


And FYI, ApplyStop function is code level of Analysis settings - Stops tab. There isn't anything confusing about it. ApplyStop() code (type, mode) overrides UI's corresponding "Stop" analysis settings. If Applystop() is not used anywhere in your code and "Stops" of UI analysis settings being enabled then latter one(s) are applied in your analysis.

thanks for the detail explanation fxshrat but please don`t use insulting language. Stay positive.

I do use proper language as you confirmed yourself.

BTW, please don't make people wasting time on non-detailed posts containing non detailed claims. It is insulting to some readers and leads to wasting time on other end (asking/explaining back and forth) and unnecessary length of threads. Once again there are pinned threads on how to create a post by help seeker. The goal is efficiency. You have plenty of time to create a post so please take the time to do so. Thank you!

@Munichtrader,

You don't realise how lucky your are to have the likes of @fxshrat helping you (and for free keep in mind!). As @Milosz very appropriately once said:

@fxshrat kindly gave you the correct code to your problem with the details that you provided. He also clearly explained what the problem was (nBar priority). So if I was you, I would put that knowledge in your learning bank, say thank-you and continue your learning of AmiBroker.

No one is forcing @fxshrat or any other of the many generous people on this forum to give their free help!

As @fxshrat stated, there is a difference between being "arrogant" and pointing out the users misunderstanding/s of what they think their code or AmiBroker is really doing!

You posted your post (problem) because you wanted a solution to your problem - you got that from people providing their extensive AmiBroker knowledge and their free time! When it's pointed out to you that the actual problem is that your current understanding is incorrect, that is not criticism! It is you receiving the help that you asked for!

Also please understand that if you don't give the full details to your problem (or post full code when necessary/requested) for people trying to help that is very frustrating! It's wasting their time because they are then playing a guessing game! Do you see that?

@fxshrat is just simply being direct with you, isn't that the best way to learn?

3 Likes