Closing & Opening a new trade on the same bar with different conditions
Author: pholding2001
Creation Date: 3/3/2021 12:19 PM
profile picture

pholding2001

#1
Hi guys,

I hope you're well. I've been struggling with this problem for a while now and I think I understand why it doesn't work. I just cannot seem to come up with a workaround.

I'm still playing around with the simple reversal system, which, on it's own works fine. I start to encounter problems as soon as I add conditions to it. The condition I'm trying to add is a 200SMA filter. Only when price is below, is the system allowed to go short. I've coded it as follows (the full code will follow after):

CODE:
Please log in to see this code.


I think the problem is with the "For" loop and the scope. My understanding is that the "for" loop will go from bar to bar until the condition stops and then it will go to the code below ( in this case, look to see if a trade is open and close when conditions are met and then go to the next code which is to open a new trade). When the "for" loop closes a trade, it then goes to the next bar and I think that is where the problem lies. It closes a trade on the MA cross and I want it to also open a trade on the MA cross but it has moved to the next bar and the cross is no longer there and it doesn't open a trade. I've tried to get around this by adding an "||" condition which opens a trade on the next bar but of course the entry is not correct. I can't find a better way. I was wondering if you could help?

Many thanks

Here's the full code:

CODE:
Please log in to see this code.
profile picture

Cone

#2
Does this do it for you?

CODE:
Please log in to see this code.
profile picture

pholding2001

#3
Hi Cone,

Sorry for the late reply. That looks great! You make it look so obvious and easy... which it is if you know how, I suppose. I feel like I learnt a lot here. Thank you very much and have a good weekend.

Paul
profile picture

Cone

#4
Awesome. Glad it worked out.

Just remember that all the logic in that 'for' loop is trying to decide what to do on the following bar (bar + 1) - or in this case at the end of the current bar (bar + 0). Just talk through it.

I'll add my caveat that a strategy like this is somewhat unrealistic since you're using the result of the close to determine to buy or sell on the same bar's close, and, you can't get an Alert for a trade action. As long as you know that, you can certainly test anything the way you like!
This website uses cookies to improve your experience. We'll assume you're ok with that, but you can opt-out if you wish (Read more).