Forex Factory (https://www.forexfactory.com/forum.php)
-   Platform Tech (https://www.forexfactory.com/forumdisplay.php?f=69)
-   -   Maximum overkill Close-All script (https://www.forexfactory.com/showthread.php?t=716973)

Nicholishen Sep 17, 2018 9:23am | Post# 41

{quote} Perhaps I am over-thinking this CloseBy thingy :-) Bare with me please as I want to see if this scenario will have any adverse impact to my overall strategy. first, I base by position size only on AccountFreeMargin() and not accountEquity(). If I have free margin, i take the next available signal. With this being the case from MM standpoint and assuming all my SL and TP for the same pair is at the same price level and away from the average entry price... Can I use two "consolidated hedge" Sell hedge orders one for SL and another one for...
Honestly, this makes no sense to me... I don't understand what you are asking.

VEEFX Sep 17, 2018 11:42am | Post# 42

{quote} Honestly, this makes no sense to me... I don't understand what you are asking.
No worries. I will whip up a new EA and try this out before I mess around with mine. I spray bullets to enter and use "cannon ball" to exit in baskets.

carddard Sep 17, 2018 8:10pm | Post# 43

{quote} I'm not sure where the confusion is then... Sum up all your positions and set one limit order of equal size in the opposite direction. All positions instantly closed. Done. Then all you have to do is reconcile them as closed either manually or programmatically. That is, afterall, how this script works.
Thanks for the great work N.
Just to clarify, in that scenario, before the ordercloseby could be triggered, the limit order first has to be an open order yea? Or are you saying that there is a way in MT4 to net your orders with unopened limit orders?

Nicholishen Sep 18, 2018 10:44am | Post# 44

{quote} Thanks for the great work N. Just to clarify, in that scenario, before the ordercloseby could be triggered, the limit order first has to be an open order yea? Or are you saying that there is a way in MT4 to net your orders with unopened limit orders?
It's important to stop think of orders as individual entities and start thinking of them as you would on a netted account. On a netted account, for example, you would place the following long orders to average into a position [1, 2, 1, 1] and your net position would be 5 lots long. Now lets say you placed an order for 1 lot short, well, then the platform would show you that you now only have 4 lots long. On a hedging account you can do the exact same thing, but the difference is that you will see offsetting orders and double commissions -- ONLY before you use closeby. After closeby there is virtually no difference between how you used orders on your hedged account and your netted account. In order to understand closeby you must absolutely understand netted accounts and net positions.

carddard Sep 18, 2018 10:50am | Post# 45

{quote} It's important to stop think of orders as individual entities and start thinking of them as you would on a netted account. On a netted account, for example, you would place the following long orders to average into a position [1, 2, 1, 1] and your net position would be 5 lots long. Now lets say you placed an order for 1 lot short, well, then the platform would show you that you now only have 4 lots long. On a hedging account you can do the exact same thing, but the difference is that you will see offsetting orders and double commissions...
Thanks for this N, I have been using close by for 2 years now, before you generously shared your thoughts to the broader FF community. I actually just wanted to clarify with you if you meant that the ordercloseby function within MT4 could also be triggered with for e.g., 5 open buys, and 1 sell limit. My understanding is that it isn't possible. The sell limit would first have to be triggered before ordercloseby can be used. Or did I misunderstand? Thanks!

Nicholishen Sep 18, 2018 2:53pm | Post# 46

{quote} Thanks for this N, I have been using close by for 2 years now, before you generously shared your thoughts to the broader FF community. I actually just wanted to clarify with you if you meant that the ordercloseby function within MT4 could also be triggered with for e.g., 5 open buys, and 1 sell limit. My understanding is that it isn't possible. The sell limit would first have to be triggered before ordercloseby can be used. Or did I misunderstand? Thanks!
You have to programmatically decide how to reconcile your orders. So you'd need to recursively use one order to close another. For example, 1(1Lot) buy + 1(5lot) Sell becomes a modified Short of 4 lots. Then you do the next order and so on until there are no offsetting positions.

So it would look something like this...

Inserted Code
[1, 1, 1] [3] one closed / one modified
[1, 1] [2]
[1] [1]
0

mavilakandy Sep 19, 2018 12:54am | Post# 47

The goal of this script is to minimize risk in all situations, especially when the shit hits the fan. This script provides the best and the fastest possible risk mitigation available thru MT4 by utilizing some unique logic not found in any other close-all scripts. Operation Summary: Net positions are calculated per symbol (sum of all open trades). Symbols are prioritized to manage net-positions from larger (more risk) to smaller. Hedge orders are sent in the order of priority to close all exposure at once regardless of the number of trades. Once...
Hello Nicholishen,
Thank you very much for your script 'HedgeAccountCloseAll'. It is really fantastic.
(Maybe, the right name for the script is 'CloseAllTradesWithoutCost')
It closes all open trades without any further cost of commission and spread.
I think we can apply this script also for closing of all open positions in profit (when we see the market is reversing) to avoid brokers commission and spread.
Please comment.

Isn't it a loss for the brokers ? Probably that is why, it is not working with one of the broker IG. Maybe they put some restrictions.

Again, thanks for your script.
Regards,

Nicholishen Sep 19, 2018 1:52am | Post# 48

{quote} Hello Nicholishen, Thank you very much for your script 'HedgeAccountCloseAll'. It is really fantastic. (Maybe, the right name for the script is 'CloseAllTradesWithoutCost') It closes all open trades without any further cost of commission and spread. I think we can apply this script also for closing of all open positions in profit (when we see the market is reversing) to avoid brokers commission and spread. Please comment. Isn't it a loss for the brokers ? Probably that is why, it is not working with one of the broker IG. Maybe they put some...
No it costs the same. It's just a more efficient way to close your trades.

mavilakandy Sep 19, 2018 2:07am | Post# 49

1 Attachment(s)
{quote} No it costs the same. It's just a more efficient way to close your trades.
Nicholishen, thanks for your reply.
Please see attached screenshot of Account History where you can see the open trades of EURUSD and USDJPY were closed without any cost.
The lot size of closing trades were shown '0.00'
Please comment.
Thanks,
Click to Enlarge

Name: Screenshot1.png
Size: 193 KB

Nicholishen Sep 19, 2018 3:39am | Post# 50

{quote} Nicholishen, thanks for your reply. Please see attached screenshot of Account History where you can see the open trades of EURUSD and USDJPY were closed without any cost. The lot size of closing trades were shown '0.00' Please comment. Thanks, {image}
Yes, I know.

You only pay spread/commission on one trade instead of two when you use closeby with offsetting orders, but it is the same cost as if you had closed one trade normally. There is no cost advantage in using a hedge to close a trade - only convenience.

mavilakandy Sep 19, 2018 5:24am | Post# 51

{quote} Yes, I know. You only pay spread/commission on one trade instead of two when you use closeby with offsetting orders, but it is the same cost as if you had closed one trade normally. There is no cost advantage in using a hedge to close a trade - only convenience.
Nicholishen, thanks for the clarification.
Regards,

VEEFX Sep 19, 2018 10:58am | Post# 52

{quote} Yes, I know. You only pay spread/commission on one trade instead of two when you use closeby with offsetting orders, but it is the same cost as if you had closed one trade normally. There is no cost advantage in using a hedge to close a trade - only convenience.
Thanks for clarifying this. I went into a major spin last night working on this technique. Unfortunately, replacing a close-all with close-by would require more work to keep track of hedged and unhedged positions if one decides to keep the hedged trades running. I see no benefit to keep the hedges running with frozen pnl. To keep things simple, when times comes to do a close-all, it is better to open a opposing hedge and trigger a closeby right after (manually works fine but via script it won't)

So to summarize my understanding this far...
1)there is no cost savings with closeby
2) there is no savings in slippage prevention either as slippage could happen with the hedged order also.
3) The benefit is there in regards to performance and convenience

Nicholishen Sep 19, 2018 11:31am | Post# 53

{quote} Thanks for clarifying this. I went into a major spin last night working on this technique. Unfortunately, replacing a close-all with close-by would require more work to keep track of hedged and unhedged positions if one decides to keep the hedged trades running. I see no benefit to keep the hedges running with frozen pnl. To keep things simple, when times comes to do a close-all, it is better to open a opposing hedge and trigger a closeby right after (manually works fine but via script it won't) So to summarize my understanding this far......
The only reason to ever "freeze" a position is to game the system and preserve the leverage of the original order. If you NEED this then you're obviously in trouble on the position and at that point you're not trading, you're gambling.

VEEFX Sep 19, 2018 11:46am | Post# 54

{quote} The only reason to ever "freeze" a position is to game the system and preserve the leverage of the original order. If you NEED this then you're obviously in trouble on the position and at that point you're not trading, you're gambling.
I would 100% ageee if one is freezing losses but I am freezing only my floating profits for even more exponential growth/explosion. I am leveraging up my floating profits to building even more positions when the conditions are ripe for further moves. If not, all I lose is my frozen price fits and get out at BE. It could be described as close and add instead of close and reverse.:-)

And I do this compartmentalizing on several filters on the same pair for all buys and all sells in a sub-recursive manner so, if my bigger floating profit (weekly) target is reached, I do a "master" closeall and call it a week...at least that is the idea behind this endeavor

Nicholishen Sep 19, 2018 12:02pm | Post# 55

{quote} I would 100% ageee if one is freezing losses but I am freezing only my floating profits for even more exponential growth/explosion. I am leveraging up my floating profits to building even more positions when the conditions are ripe for further moves. If not, all I lose is my frozen price fits and get out at BE. It could be described as close and add instead of close and reverse.:-) And I do this compartmentalizing on several filters on the same pair for all buys and all sells in a sub-recursive manner so, if my bigger floating profit (weekly)...
That makes no sense. Free margin is based on account equity. There is absolutely no reason to freeze profits unless you're just a glutton for fees.

VEEFX Sep 19, 2018 12:43pm | Post# 56

{quote} That makes no sense. Free margin is based on account equity. There is absolutely no reason to freeze profits unless you're just a glutton for fees.
You should look into how freezing profits is used as a technique to simply follow the long term trend (millipede style)

Nicholishen Sep 19, 2018 1:38pm | Post# 57

{quote} You should look into how freezing profits is used as a technique to simply follow the long term trend (millipede style)
Again I will strongly assert that hedging to freeze profits and taking profit are literally the same net effect, except with the freeze you take on extra risk of accruing double swaps. Unless for some really specific reason you're trying to play games with your account balance curve, there is no benefit to freezing profit

VEEFX Sep 21, 2018 4:45am | Post# 58

1 Attachment(s)
{quote} Again I will strongly assert that hedging to freeze profits and taking profit are literally the same net effect, except with the freeze you take on extra risk of accruing double swaps. Unless for some really specific reason you're trying to play games with your account balance curve, there is no benefit to freezing profit
You will probably hate me more now :-(

Still playing around with my test EA to figure this out. Your script is in new(er) mql version with constructs that I am not quite familiar with so please bare with me (keeping the benefits or flaws of hedging aside for a minute). I have stumbled upon a pretty decent microscopic "reversion to mean" > Flip > "Diversion from Mean > Flip > "Reversion to Mean"....an always-in strategy triggered by a razor sharp single manual entry. Works great in demo but may not be practical for live trading. So leaving all that aside, here's what I did:

 

  1. EA waits for my MIN_LOT (0.01 lotsize) Manual entry
  2. EA detects the manual order and goes into binge mode... adding 100s of orders using all the available free margin (There is a tick based filter which is similar to my other OHLC automation so it's not a blind additions)
  3. If Equity explodes, I keep adding every time freemargin becomes positive and exceeding the required margin for one min_lot...giving me more and more buying power with equity explosion
  4. If Equity depletes resulting in a quick approach towards STOPOUT level (typically at 50% margin), I trigger my MarginCallPrevention routine which triggers a partial close of one min_lot at a time... this slows the decend and slowly frees up margin. If equity keeps depleting with not retrace, I am left with whatever Equity is at 50% margin. If equity explodes, I make 200-300% per manual entry trigger... ending with a RR of 1:4+... all good for broker competions or a small account but a bit impractical for larger size accounts.
  5. When my target profit is reached:

    1. I calculate the total position size across all trades and open a hedge position of that size... this freezes the profit. Then immediately afterwards, I extracted the code from CloseByHedge() function in your script that is called from my EA. This triggers a closeby exiting all open positions.






Question: When I do a Manual CloseBY (multiple) from within the terminal, the exit of all open positions is instantaneous with all positions wiped clean in a micro second but when I call your function, it closes one at a time. Am I doing this right ? Can I mimic the intantaneous closeby manual option in my EA?

Here's the code.

Inserted Code
void CloseByHedge() {
int Total;
for(int s=0;s<OrdersTotal();s++) {
   string symbol = OpenOrderSymbol;
   for(int i=OrdersTotal()-1;i>0&&!IsStopped();i--) {
      if(OrderSelect(i,SELECT_BY_POS) && OrderSymbol()==symbol && OrderType()<2) {
         int type = OrderType();
         int ticket = OrderTicket();
         for(int j=i-1;OrderSelect(j,SELECT_BY_POS);j--) {
            if(OrderSymbol()==symbol && OrderType()<2 && OrderType()!=type) {
               if(!OrderCloseBy(OrderTicket(),ticket)) Print("OrderCLoseByError: ",GetErrorMessage(GetLastError()));
               i=OrdersTotal();
               break; }}}}}
} // End of CloseByHedge() //
Click to Enlarge

Name: Image1.png
Size: 43 KB

Nicholishen Sep 21, 2018 12:08pm | Post# 59

{quote} You will probably hate me more now :-( Still playing around with my test EA to figure this out. Your script is in new(er) mql version with constructs that I am not quite familiar with so please bare with me (keeping the benefits or flaws of hedging aside for a minute). I have stumbled upon a pretty decent microscopic "reversion to mean" > Flip > "Diversion from Mean > Flip > "Reversion to Mean"....an always-in strategy triggered by a razor sharp single manual entry. Works great in demo but may not be practical for live trading. So leaving...
No, you cannot do "multiple-closeby" programmatically, and iterative closeby is the closest you will get to mimicking it. That said it looks like you are trying to filter the closeby routine by symbol and magic. I'd use a recursive func like this.
Inserted Code
bool multiple_closeby(const string symbol=NULL, const int magic=NULL)
{
   for(int i=OrdersTotal()-1; i>0; --i){
      if(OrderSelect(i, SELECT_BY_POS)
         && OrderType() < 2 
         && (symbol == NULL || OrderSymbol() == symbol)
         && (magic == NULL  || OrderMagicNumber() == magic)
      ){
         int    first_ticket = OrderTicket();
         string first_symbol = OrderSymbol();
         int    first_type   = OrderType();
         for(int j=i-1; j>=0; --j){
            if(OrderSelect(j, SELECT_BY_POS)
               && OrderType() < 2
               && (magic == NULL || OrderMagicNumber() == magic)
               && OrderSymbol() == first_symbol  
               && OrderType()   != first_type
            ){
               if(OrderCloseBy(first_ticket, OrderTicket())){
                  return multiple_closeby(symbol, magic);
               }else{
                  return false;
               }
            }
         }
         break;
      }
   }
   return true;
}

VEEFX Sep 21, 2018 12:35pm | Post# 60

{quote} No, you cannot do "multiple-closeby" programmatically, and iterative closeby is the closest you will get to mimicking it. That said it looks like you are trying to filter the closeby routine by symbol and magic. I'd use a recursive func like this. bool multiple_closeby(const string symbol=NULL, const int magic=NULL) { for(int i=0; OrderSelect(i, SELECT_BY_POS); i++){ if(OrderType() < 2 && (symbol == NULL || OrderSymbol() == symbol) && (magic == NULL || OrderMagicNumber() == magic) ){ int first_ticket = OrderTicket(); string first_symbol...
Thanks man. This explains why I experienced a tiny bit of slippage when comparing my account balance and equity prior to hedge and after completion of this function. With manual multiple closeby, there is absolutely no slippage.
I learnt a lot from this endeavor so thanks for generously sharing the code. It really helps to tweak and play around on your own to truly understand the inner workings of leveraged margin accounts. I bet many simply trade looking at charts without truly understanding. I know I was like that for over 4-5 yrs clicking buttons like a monkey and going nowhere :-(

EDIT: Just FYI - I discovered a bug within MT4 mobile. After the completion of this script, the balance and equity between MT4 mobile and Terminal are not synced immediately. I had to exit the terminal, log back into my (demo) account for MT4 mobile to reflect the netting.


© Forex Factory