CloseAllPostionByMargin

Download script
Author: Copyright � 2005, Matias Romeo.
CloseAllPostionByMargin

This script is designed as an automated risk management tool for the MetaTrader platform. Its primary purpose is to monitor your trading account's real-time performance and automatically exit all open positions once a specific profit milestone—calculated based on your utilized margin—is reached.

How the Logic Works

1. Performance Monitoring The script continuously tracks two key pieces of data: your Account Profit (the money you are currently making or losing) and your Margin Used (the amount of capital currently "locked" to maintain your open trades).

2. The Target Calculation Unlike a standard "Take Profit" that uses a fixed dollar amount, this tool uses a dynamic target. It looks at the margin you are currently using and multiplies it by a specific percentage (defined by the Margin Multiplier). This ensures that your profit goals scale automatically with the size of your positions.

3. Automated Execution The script constantly compares your current live profit against this calculated target. As soon as your profit exceeds the target amount, the logic triggers an immediate cleanup of your account:

  • Active Trades: It identifies every open "Buy" and "Sell" position and closes them instantly at the current market price.
  • Pending Orders: It also scans for any "limit" or "stop" orders (trades waiting to be triggered) and removes them from the system to ensure no new positions are opened.

4. Visual Feedback While the script is running, it provides a real-time text overlay on your trading chart. This allows you to see:

  • Your current Margin Usage.
  • The specific Profit Target the script is aiming for.
  • The remaining amount of profit needed before the script will automatically close your trades.

Summary for the User

Think of this as an "Auto-Exit" safety net. Instead of you having to manually watch the charts and click "Close" when you reach a certain goal, this script does the math for you. It ensures that once your trading activity generates a profit proportional to the risk you've taken (the margin), it secures those gains by closing everything out automatically.

Orders Execution
Checks for the total of open ordersIt Closes Orders by itself
14 Views
0 Downloads
0 Favorites
CloseAllPostionByMargin
//+------------------------------------------------------------------+
//|                                    close-all-ordersByMargin.mq4  |
//|                                  Copyright © 2005, Matias Romeo. |
//|                                       Custom Metatrader Systems. |
//| History:                                                         |
//| Modify to close order by Margin Used                             |                            |
//+------------------------------------------------------------------+

#property copyright "Copyright © 2005, Matias Romeo."
#property link      "mailto:matiasDOTromeoATgmail.com"

extern double MarginMultiplier = 0.7; // For the purpose of Multiplying MarginUsed to determine profit target

int start()
{
   if(OrdersTotal() > 0 )
   Comment("MarginUsed",(AccountMargin())," Multiplier",MarginMultiplier," Fraction",AccountProfit()/AccountMargin()," |||ProfitTarget: $",(AccountMargin())*MarginMultiplier," Less AccountProfit: ",AccountProfit()," = RemainingTarget: $",((AccountMargin())*MarginMultiplier)-AccountProfit());
   if(OrdersTotal() > 0 && AccountProfit()>(AccountMargin())*MarginMultiplier) 

  int total = OrdersTotal();
  for(int i=total-1;i>=0;i--)
  {
    OrderSelect(i, SELECT_BY_POS);
    int type   = OrderType();

    bool result = false;

//   if(OrdersTotal() > 0 && AccountProfit()>(AccountMargin())*MarginMultiplier) 
    
    switch(type)
    {
      //Close opened long positions
      case OP_BUY       : result = OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_BID), 5, Red );
                          break;
      
      //Close opened short positions
      case OP_SELL      : result = OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_ASK), 5, Red );
                          break;

      //Close pending orders
      case OP_BUYLIMIT  :
      case OP_BUYSTOP   :
      case OP_SELLLIMIT :
      case OP_SELLSTOP  : result = OrderDelete( OrderTicket() );
    }
    
    if(result == false)
    {
//      Alert("Order " , OrderTicket() , " failed to close. Error:" , GetLastError() );
//      Sleep(3000);
    }  
  }
  
  return(0);
}




Comments