I'm having trouble with a simple bool type switch... can anyone see the problem with this code? Here is a piece of sample code -
variables: BoolExitLong(False);
....
//exit code
if marketposition[0] = 1 then begin
if close[0] < average(close,20)[0] then
BoolExitLong = True;
if BoolExitLong = True and close[0] > average(close,50)[0] then
sell ("boolexL") next bar at market;
BoolExitLong = False;
//some more code
end;
What I'm trying to achieve here is "if a certain low level is hit, then sell at next opportunity at a higher level". Everything else works, but this doesn't... when I do get it to work its just constantly stopping out long trades - so clearly not shutting off properly. But also not really working in the first place...
Thanks in advance.
Can you help answer these questions from other members on futures io?
Hard to say at this point. The algorithm at least appears to be functional [at least according to a quick comparison of output of the following test indicator with close price in a 240 minute chart of spot EUR.USD (i.e., it appears to be generating a sell signal when close lies between the 20 and 50 SMAs and 20MA > 50MA)]
Assuming there are no errors in the rest of the code logically the go-long algorithm may be entering trades after 20 MA rises above 50 but while the close is still between them, in which case the trade would be immediately stopped out. In the chart below there are a few places this might occur (points where one might go long between the 20MA and 50MA when 20 > 50), but this does not appear to be the rule.
Hi bnichols,
I really appreciate the help. That was terrific - however, I'm still stuck on why it won't work for me.
how can I be seeing output like this…
1121107.00 557.00Bool was TRUE and EXIT level reached
1121107.00 557.00Turning Bool OFF
1121107.00 618.00Bool was TRUE and EXIT level reached
1121107.00 618.00Turning Bool OFF
1121106.00 1957.00Initial Bool ON
1121106.00 1957.00Turning Bool OFF
1121107.00 824.00Initial Bool ON
1121107.00 824.00Turning Bool OFF
with the following code blocks:
if marketposition(0) = 1 then begin
if close[0] < KeltnerChannelLower(close,Kexitlen,KeltWidex)[0] then begin
Print(D," ",T,"Initial Bool ON");
BoolExitLong = 1;
end;
if BoolExitLong = 1 then begin
if close[0] > KeltnerChannelLower(close,Keltlen,keltwid)[0] then
Print(D," ",T,"Bool was TRUE and EXIT level reached");
sell ("bool was true exit") next bar at market;
Print(D," ",T,"Turning Bool OFF");
BoolExitLong = 0;
end;
...
end;
How is it running through that last block of code and acting on the last part but not the middle part? Doesn't it only execute the two actions (and two print statements) if the first two were true? How is it only executing one of the actions?
Referring to this part of the output:
1121106.00 1957.00Initial Bool ON
1121106.00 1957.00Turning Bool OFF
1121107.00 824.00Initial Bool ON
1121107.00 824.00Turning Bool OFF
Here is an image of whats happening as well - it appears to be closing the position on the "Bool was true exit level reached" exit - so selling at market right there, however it's not fulfilling the the second requirement of that block of code:
Close must be greater than KeltnerChannelLower
"if close[0] > KeltnerChannelLower(close,20,1.5)[0] then"
As you can see its closing below the Keltner Channel Lower, its only supposed to close when it retraces back up to the kelt band. The KeltnerChannelLower function normally works so that shouldn't be the issue...
While I don't see any issues with the output versus the code snippet in post #4 (i.e., it appears to be doing exactly what it's told to do), the comment in post #5 (" it's not fulfilling the the second requirement of that block of code: Close must be greater than KeltnerChannelLower") suggests that you might be missing a begin/end block.
Right now the code will exit the position as soon as price drops below the lower Keltner boundary because the lines
simply prints out some text if the test is true, rather than controlling the exit.
BTW, I wrote a signal to test the exit policy you describe and it appears to have a fairly robust expectancy, which means while it might be improved it may make money as is once optimized for your instrument, more money with more investment, so good luck with it
Edited to add: Which is a warning it will probably lose money trading micro lots with realistic slippage and commission
Hi Bnichols and Ehlaban, thank you very much for your help. Much appreciated!
I tried both of these suggestions:
However, I was still getting a million improper exits >> as compared to what I was trying to achieve. So I started to think that it might be something else that's causing the issue.
I decided to start over with this section of code so that it is very simple and all parts of the code can be seen. I am only looking at the long side of the code to make this even simpler.
So I'll try to explain again what I am trying to do:
The entry is not important here. The exit is what I am trying to get right. The idea is that once the price closes below a certain level then an exit signal is generated (the bool turning to TRUE, no trades taking place). This means that the price is lower than the KeltnerChannel (in this case - could be a bollinger band etc) - now we're looking for a retracement to get out of the long position. I have the retracement level required set as an 18 period moving average which should always be in between the keltners.
So the bool can only be turned on when we're in a long position and when we're below the lower keltner and it will always exit once we retrace up to the moving average. It should not continue holding beyond that level...
I also have the bool being turned off after any other type of exit so that the bool is only True just before an exit takes place.
I have it acting fairly well now (as I had intended) However, I still can't account why it will only exit half of the time when "it is supposed to" - according to my intent.
Here is my current simple code (all of it):
This issue remaining is shown below - As you can see the code has us in a long trade coming into the section shown - then price drops below the keltnerchannel lower bound around 18:45 which should have turned on the bool exit (CloseTrade = True) - it should have then been looking for price to close above the 18 period moving average. It moves above the average but nothing happens. Same thing further along at 7/11/2012 7:00-11:00 and then moves back above and through the moving average - but no exit once it gets to that level. And then for some reason the CloseTrade trade happens later on after another move below the lower keltner....
Any thoughts here? I'm really stuck...
Thanks again for all of the help.
I use that keltner function in other signals and plot the keltner indicator separately and they always seem to match up. I don't imagine that is the issue. I think I did even try taking it out and using a different requirement for that part. I think I tried RSI, if RSI was below a certain level then it was supposed to turn the TradeClose bool to True. Same issue though.
Alrighty then. When assumption checking fails time to put on our thinking caps.
Can you post 2 things:
1. a screenshot of the entire chart containing the offending trade compressed so that the image contains both the entry and the exit if possible (but not so compressed numbers on the axes are not discernible), but of main interest is the exit, the time axis at the bottom and price axis at the right; and,
The second chart is further back - you can see another 2 instances where it should have triggered the exit.
One around the beginning of the 30th and one on the 25th. The asset is AUDJPY and the timeframe was a 21 minute chart.
*The entry related to the exit we were looking at is on the 29th.
The first thing to notice is that the trade spanned not one but many session boundaries which (given my experience with Interactive Brokers and NT) probably means all bets are off for automated strategies running on platforms designed for retail traders.
I'm a day trader (at least don't leave strategies running overnight because of my experience with IB and NT ) and still learning MC so would have to discover if MC has issues similar to NT, assuming we can rule out IB as the common factor.
In any event clearly it seems the trade should have exited around 4 AM on the 30th of October, soon after the trade was entered (in swing trading terms).
I can understand your confusion but I'm curious why it exited at all since it makes no sense to me unless it was a live trade--in which case it's my experience 3rd party retail platforms tend to fall apart.
Can you confirm it exited automatically (confirm you did not kill it to make the exit) and that this is a backtesting result rather than an actual live trade?
While I assume it's a backtest, if a live trade for the record can you confirm 2 things:
1. whether you tinkered with the signal or the chart or even turned your computer off and back on between Oct 29 (entry) and Dec 8 (exit)?
2. whether your broker is IB?
Tough puzzle. I already know your answer is that it was a backtest
At this point should probably post the....
Disclaimer
All my tests have been on bar intervals likely to give an intraday exit rather than a 21 minute bar interval--the assumption I missed-- and this is probably the key. Should confess I may not be able to help you with this if the strat runs past session close and if so there are 2 choices: close at end of session or wait for someone better informed than I (your future self perhaps!) to parachute in.
If it's a backtest it may be a bug in MC, in which case have to ask are you running 8 or 8.5 (beta). NT at least can handle backtests (screws up in real time). Otherwise I've learned not to trust a retail broker/platform pair for strategies overnight exactly because of insoluble swing trade issues of this sort :-/
Edited to add: That's one reason I use IB's interface (TWS) for swing trades.
This was a backtest in MC using IQFeed data. If/when trading live I use MC with IB as my data and broker. I haven't had any issues with multi-day trades in a live environment with MC and IB though.
I just took a look back through the data and found a situation where the entry, the exit trigger (bool) was triggered and the price retraced to the moving average all within the same day and the trade did not exit as it should have (I will post that below).
Yeah it's really quite confusing to me why it exits when it does - it seems to ignore other situations that seem to be equivalent in all respects...
Thanks again for your help on this - maybe I should just try approaching this from a different angle?
For the record here is what I'm seeing (in this case a 21 minute AUD.JPY chart with the signal applied, data courtesy of IB). The entry is slightly different presumably because of the different feed, given the signal MAs (cyan and magenta) are intertwined around the point of entry, but the exit is as expected :-/
Well....identical entry and exit code but not quite the same code because of the permutations it has been through [note much of it is commented out with {} brackets] but the changes don't affect the outcome no matter what I try.
Edited to add: Perhaps the major difference is testing for flat before entry, but removing that condition does not change the outcome.
ehlaban -
I am using this as a function:
inputs: PriceValue( numericseries ), Len( numericsimple ), NumATRs( numericsimple ) ;
KeltnerChannelLower = Average( PriceValue, Len ) - NumATRs * AvgTrueRange( Len ) ;
21minute bars is the timeframe
bnichols -
When I try your code I get similar results, however, if I turn on bar magnifier @ 1 minute resolution, I get a lot of weird trading right around entries and exits. I've run into this a lot, some times my charts are just a mess of in/out trading...
Any idea what is going on there? Do you see that with bar mag?
If I turn on bar magnifier I get your (weird) results. That is, no multiple entry/exit (although I have seen that previously) but the exit is missed--no clue why at the moment.
haha - I suppose that is an accomplishment of sorts
The trading as seen in the close up image is the reason that I put so many CloseTrade = False snip-its throughout the code. I wanted to make sure that any time it made a trade or performed an action CloseTrade was set to False.
You can see in that close up image that we end the previous trade and the code should have turned CloseTrade bool to false, so we should not be exiting again with CloseTrade right away and yet we are. Even though we're no where near the lower KC and yet is still triggers a CloseTrade trade next bar.
You're getting multiple intrabar orders at exits likely because
1. bar magnifier is on
2. entry conditions exist at the time (i.e., fast MA > slow MA); and
3. Your profit exit*** is causing the trade to close very quickly--you might want to confirm you have the symbol settings (scale, movement and bigpointvalue) configured properly.
***
In general (i.e., even with bar magnifier off and no profit exit) new orders will be generated when the last trade closes if entry conditions exist.
bnichols -
I have bar magnifier on, but it doesn't seem to be an issue with other scripts I use. I have that profit target turned off for simplicity and all of the exits that follow the entries are "CloseTrade" exits. So it must still have something to do with the CloseTrade code...
If you think about the order of events in the code the CloseTrade exit is last and the last thing in that block is to turn the CloseTrade variable to False. So how could the next bar after re-entering (which also has a CloseTrade = False in it) still execute the CloseTrade Exit further down the code (which requires CloseTrade = True)?
ehlaban -
I don't see how using conditions would replace using the bool variable we have- is that what you are suggesting? I agree it would be simpler and clearer but I don't think the same end goal can be achieved.. ? unless I am missing something?
I now understand the logic about the CloseTrade better. It indeed is a switch.
A thing i noticed is that when exiting a trade next bar at market
it is possible that another buy is given in the same next bar due to the
IntrabarOrder etc etc. You could use sell this bar at close but this code works for me:
[IntrabarOrderGeneration = True]
inputs: Num1(40), Num2(60), Num3(18), profitamount(4000);
variables: CloseTrade(false);
If marketposition = 0 then
begin
CloseTrade = False;
if Average(close, Num1) Cross Above Average(close, Num2) then
buy ("long") next bar at market;
end;
if marketposition = 1 AND CloseTrade = False then
begin
if Close <= keltnerchannellower(Close, 25, 2.5) then CloseTrade = true;
end;
if marketposition = 1 AND CloseTrade = True then
begin
if Close > Average(Close, Num3) then sell ("CloseTrade") next bar at market;
end;
SetStopContract;
SetProfitTarget(profitamount);
The following user says Thank You to ehlaban for this post:
Hi Ehlaban - I think you've solved this puzzle! I haven't had a chance to take a close look yet, but initially all seems to be functioning as it "should" even with intrabarorder gen!
Great job.
Thanks for your help!