• Home
  • Forums
  • Trades
  • News
  • Calendar
  • Market
  • Brokers
  • Login
  • Join
  • User/Email: Password:
  • 4:26pm
Menu
  • Forums
  • Trades
  • News
  • Calendar
  • Market
  • Brokers
  • Login
  • Join
  • 4:26pm
Sister Sites
  • Metals Mine
  • Energy EXCH
  • Crypto Craft

Options

Bookmark Thread

First Page First Unread Last Page Last Post

Printable Version

Similar Threads

Close all script 8 replies

Script EA manager - Maximum spread function, can you help me 0 replies

script for EA to close all orders by spec. time 3 replies

ibfx live script to close all positions 6 replies

Help for Script to close all open positions 4 replies

  • Platform Tech
  • /
  • Reply to Thread
  • Subscribe
  • 16
Attachments: Maximum overkill Close-All script
Exit Attachments

Maximum overkill Close-All script

  • Last Post
  •  
  • 1 2Page 3 4
  • 1 2Page 3 4
  •  
  • Post #41
  • Quote
  • Sep 17, 2018 9:23am Sep 17, 2018 9:23am
  •  Nicholishen
  • Joined Jul 2005 | Status: zzzzzzzzzzzzzzzzzzzzzzzzz zzzzzzzzzz | 1,289 Posts
Quoting VEEFX
Disliked
{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...
Ignored
Honestly, this makes no sense to me... I don't understand what you are asking.
  • Post #42
  • Quote
  • Sep 17, 2018 11:42am Sep 17, 2018 11:42am
  •  VEEFX
  • Joined Jun 2006 | Status: Adios! | 3,377 Posts
Quoting Nicholishen
Disliked
{quote} Honestly, this makes no sense to me... I don't understand what you are asking.
Ignored
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.
Staying in my lane...
  • Post #43
  • Quote
  • Sep 17, 2018 8:10pm Sep 17, 2018 8:10pm
  •  carddard
  • Joined Jan 2017 | Status: Member | 263 Posts
Quoting Nicholishen
Disliked
{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.
Ignored
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?
  • Post #44
  • Quote
  • Sep 18, 2018 10:44am Sep 18, 2018 10:44am
  •  Nicholishen
  • Joined Jul 2005 | Status: zzzzzzzzzzzzzzzzzzzzzzzzz zzzzzzzzzz | 1,289 Posts
Quoting carddard
Disliked
{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?
Ignored
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.
  • Post #45
  • Quote
  • Sep 18, 2018 10:50am Sep 18, 2018 10:50am
  •  carddard
  • Joined Jan 2017 | Status: Member | 263 Posts
Quoting Nicholishen
Disliked
{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...
Ignored
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!
  • Post #46
  • Quote
  • Edited at 3:11pm Sep 18, 2018 2:53pm | Edited at 3:11pm
  •  Nicholishen
  • Joined Jul 2005 | Status: zzzzzzzzzzzzzzzzzzzzzzzzz zzzzzzzzzz | 1,289 Posts
Quoting carddard
Disliked
{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!
Ignored
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
  • Post #47
  • Quote
  • Sep 19, 2018 12:54am Sep 19, 2018 12:54am
  •  mavilakandy
  • | Joined Aug 2016 | Status: Member | 442 Posts
Quoting Nicholishen
Disliked
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...
Ignored
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,
  • Post #48
  • Quote
  • Sep 19, 2018 1:52am Sep 19, 2018 1:52am
  •  Nicholishen
  • Joined Jul 2005 | Status: zzzzzzzzzzzzzzzzzzzzzzzzz zzzzzzzzzz | 1,289 Posts
Quoting mavilakandy
Disliked
{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...
Ignored
No it costs the same. It's just a more efficient way to close your trades.
  • Post #49
  • Quote
  • Sep 19, 2018 2:07am Sep 19, 2018 2:07am
  •  mavilakandy
  • | Joined Aug 2016 | Status: Member | 442 Posts
Quoting Nicholishen
Disliked
{quote} No it costs the same. It's just a more efficient way to close your trades.
Ignored
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,
Attached Image (click to enlarge)
Click to Enlarge

Name: Screenshot1.png
Size: 193 KB
  • Post #50
  • Quote
  • Sep 19, 2018 3:39am Sep 19, 2018 3:39am
  •  Nicholishen
  • Joined Jul 2005 | Status: zzzzzzzzzzzzzzzzzzzzzzzzz zzzzzzzzzz | 1,289 Posts
Quoting mavilakandy
Disliked
{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}
Ignored
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.
  • Post #51
  • Quote
  • Sep 19, 2018 5:24am Sep 19, 2018 5:24am
  •  mavilakandy
  • | Joined Aug 2016 | Status: Member | 442 Posts
Quoting Nicholishen
Disliked
{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.
Ignored
Nicholishen, thanks for the clarification.
Regards,
  • Post #52
  • Quote
  • Sep 19, 2018 10:58am Sep 19, 2018 10:58am
  •  VEEFX
  • Joined Jun 2006 | Status: Adios! | 3,377 Posts
Quoting Nicholishen
Disliked
{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.
Ignored
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
Staying in my lane...
  • Post #53
  • Quote
  • Sep 19, 2018 11:31am Sep 19, 2018 11:31am
  •  Nicholishen
  • Joined Jul 2005 | Status: zzzzzzzzzzzzzzzzzzzzzzzzz zzzzzzzzzz | 1,289 Posts
Quoting VEEFX
Disliked
{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......
Ignored
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.
  • Post #54
  • Quote
  • Sep 19, 2018 11:46am Sep 19, 2018 11:46am
  •  VEEFX
  • Joined Jun 2006 | Status: Adios! | 3,377 Posts
Quoting Nicholishen
Disliked
{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.
Ignored
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
Staying in my lane...
1
  • Post #55
  • Quote
  • Sep 19, 2018 12:02pm Sep 19, 2018 12:02pm
  •  Nicholishen
  • Joined Jul 2005 | Status: zzzzzzzzzzzzzzzzzzzzzzzzz zzzzzzzzzz | 1,289 Posts
Quoting VEEFX
Disliked
{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)...
Ignored
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.
  • Post #56
  • Quote
  • Sep 19, 2018 12:43pm Sep 19, 2018 12:43pm
  •  VEEFX
  • Joined Jun 2006 | Status: Adios! | 3,377 Posts
Quoting Nicholishen
Disliked
{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.
Ignored
You should look into how freezing profits is used as a technique to simply follow the long term trend (millipede style)
Staying in my lane...
  • Post #57
  • Quote
  • Sep 19, 2018 1:38pm Sep 19, 2018 1:38pm
  •  Nicholishen
  • Joined Jul 2005 | Status: zzzzzzzzzzzzzzzzzzzzzzzzz zzzzzzzzzz | 1,289 Posts
Quoting VEEFX
Disliked
{quote} You should look into how freezing profits is used as a technique to simply follow the long term trend (millipede style)
Ignored
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
  • Post #58
  • Quote
  • Sep 21, 2018 4:45am Sep 21, 2018 4:45am
  •  VEEFX
  • Joined Jun 2006 | Status: Adios! | 3,377 Posts
Quoting Nicholishen
Disliked
{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
Ignored
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() //
Attached Image (click to enlarge)
Click to Enlarge

Name: Image1.png
Size: 43 KB
Staying in my lane...
  • Post #59
  • Quote
  • Edited at 1:17pm Sep 21, 2018 12:08pm | Edited at 1:17pm
  •  Nicholishen
  • Joined Jul 2005 | Status: zzzzzzzzzzzzzzzzzzzzzzzzz zzzzzzzzzz | 1,289 Posts
Quoting VEEFX
Disliked
{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...
Ignored
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;
}
1
  • Post #60
  • Quote
  • Sep 21, 2018 12:35pm Sep 21, 2018 12:35pm
  •  VEEFX
  • Joined Jun 2006 | Status: Adios! | 3,377 Posts
Quoting Nicholishen
Disliked
{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...
Ignored
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.
Staying in my lane...
  • Platform Tech
  • /
  • Maximum overkill Close-All script
  • Reply to Thread
    • 1 2Page 3 4
    • 1 2Page 3 4
0 traders viewing now
  • More
Top of Page
  • Facebook
  • Twitter
About FF
  • Mission
  • Products
  • User Guide
  • Media Kit
  • Blog
  • Contact
FF Products
  • Forums
  • Trades
  • Calendar
  • News
  • Market
  • Brokers
  • Trade Explorer
FF Website
  • Homepage
  • Search
  • Members
  • Report a Bug
Follow FF
  • Facebook
  • Twitter

FF Sister Sites:

  • Metals Mine
  • Energy EXCH
  • Crypto Craft

Forex Factory® is a brand of Fair Economy, Inc.

Terms of Service / ©2021