Exp-CloseIfProfitAndLoss12062009

Download script
Author: Copyright � 2009, Expforex
Exp-CloseIfProfitAndLoss12062009

This script is an automated trade management tool designed to monitor your open trading positions and execute closing actions based on specific financial milestones. It functions as a safety net and a profit-taking mechanism by tracking the real-time performance of your portfolio.

The logic operates under two primary modes, which you can toggle through the settings:

1. Fixed Profit/Loss Management

In this mode, the script constantly calculates the cumulative profit or loss of all currently active trades. It monitors two specific thresholds defined by the user:

  • Profit Target: If the total profit across all trades reaches a specific monetary value that you have set, the script will automatically trigger an alert (playing a sound) and close every open position instantly to lock in those gains.
  • Loss Limit: Conversely, it monitors for a maximum allowable loss. If the combined losses of your trades drop below a certain negative threshold, the script will intervene by closing all positions to prevent further capital depletion.

2. Percentage-Based Management

This mode allows you to manage your risk based on the total size of your account rather than a fixed dollar amount. It calculates what percentage of your current balance is required to reach a target goal. For example, if you set a target of 20%, the script will automatically close all trades once your floating profit equals 20% of your total account balance.

Key Features and Behaviors

  • Real-Time Monitoring: The script continuously scans your open orders and updates the "Profit" status on your screen, allowing you to see how close you are to your targets at any moment.
  • Global Execution: When a trigger condition (Profit, Loss, or Percentage) is met, the script is designed to clear out all active trades—including Buy, Sell, and pending orders—ensuring that no positions remain open once the goal is hit.
  • Automated Error Handling: The logic includes built-in checks to ensure that trade executions are successful and provides status updates on the screen regarding any market movements or execution errors.
  • Audio Alerts: To ensure the user is aware of actions being taken, the script provides an audible notification whenever a closing event is triggered by your pre-defined limits.
Orders Execution
Checks for the total of open ordersIt Closes Orders by itself
Miscellaneous
It plays sound alerts
9 Views
0 Downloads
0 Favorites
Exp-CloseIfProfitAndLoss12062009
//+------------------------------------------------------------------+
//|                                     Exp-CloseIfProfitAndLoss.mq4 |
//|                                       Copyright © 2009, Expforex |
//|                                            http://expforex.at.ua |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2009, Expforex"
#property link      "http://expforex.at.ua"
#property show_inputs
#include <stdlib.mqh>
extern bool Çàêðûòèåïîïðèáûëè=true;
extern double ïðèáûëü=0;
extern bool Çàêðûòèåïîóáûòêó=true;
extern string a="Óáûòîê äîëæåí áûòü ñ çíàêîì ìèíóñ";
extern double óáûòîê=0;
double Prof=0;
extern int slippage=0;
extern bool PrClose=false;
extern int ProcentToclose=20;

//+------------------------------------------------------------------+
double Price[2];
int    giSlippage;
bool   CloseOpenOrders = true;

void init()
{

Stamp();
start();
}

int start()
{
  if (PrClose)Comment("Ïðîãðàììà çàêðîåò îðäåðà â ïðîöåíòíîì ñîîòíîøåíèè ");
  if (!PrClose)Comment("Ïðîãðàììà çàêðîåò îðäåðà ïî ïðîôèòó");

  double proftockose=0;
  if (!PrClose){
 for (int cnt = 1 ; cnt <= OrdersTotal(); cnt++) 
   { 
      OrderSelect(cnt-1,SELECT_BY_POS,MODE_TRADES); 
      double OrderProf=OrderProfit();
      Prof=Prof+OrderProf;
    }     
if  (Çàêðûòèåïîïðèáûëè==true&&Prof>=ïðèáûëü&&Prof!=0)    
{
PlaySound("stops.wav");
while (OrdersTotal()!=0)
{
startcLOSE();
Comment("Çàêðûâàåì îðäåðà ïî Ïðèáûëè: ", Prof, "\n Âîçìîæíàÿ îøèáêà:",GetLastError());
}
Prof=0;
}

if  (Çàêðûòèåïîóáûòêó==true&&Prof<óáûòîê&&Prof!=0)  
   {
PlaySound("stops.wav");
while (OrdersTotal()!=0)
{
startcLOSE();  
Comment("Çàêðûâàåì îðäåðà ïî Óáûòêó: ", Prof, "\n Âîçìîæíàÿ îøèáêà:",GetLastError());
}
}
    Prof=0;
    
    }
    
    
 //----------------------------------------------------------------------------------------
 
 
 
if (PrClose){
 for (int cnt2 = 1 ; cnt2 <= OrdersTotal(); cnt2++) 
   { 
      OrderSelect(cnt2-1,SELECT_BY_POS,MODE_TRADES); 
      double OrderProf2=OrderProfit();
      Prof=Prof+OrderProf2;
    }  
    
proftockose=(AccountBalance()/100)*ProcentToclose;      
if (Prof>=proftockose){
PlaySound("stops.wav");
while (OrdersTotal()!=0)
    {
startcLOSE();
Comment("Çàêðûâàåì îðäåðà ïî Ïðîöåíòó: ", Prof, "\n Âîçìîæíàÿ îøèáêà:",GetLastError());
    }


}
Comment("Òåêóùèé ïðîöåíò ïðîôèòà = "+Prof/(AccountBalance()/100));
Prof=0;
}   
   return(0);
  }
  








//+------------------------------------------------------------------+

void CloseOrder()
{
for(int i=1; i<=OrdersTotal(); i++)          // Öèêë ïåðåáîðà îðäåðîâ
     {
      if (OrderSelect(i-1,SELECT_BY_POS)==true) // Åñëè åñòü ñëåäóþùèé ïðîâåðÿåì åãî
        { 
        string sym=OrderSymbol();
        RefreshRates();                                      // Àíàëèç îðäåðî
 if(OrderType()==OP_SELL) OrderClose(OrderTicket(),OrderLots(),MarketInfo(sym,MODE_ASK),slippage);
 if(OrderType()==OP_BUY) OrderClose(OrderTicket(),OrderLots(),MarketInfo(sym,MODE_BID),slippage);
 if(OrderType()==OP_SELLSTOP) OrderDelete(OrderTicket()); 
 if(OrderType()==OP_BUYSTOP) OrderDelete(OrderTicket());
 }
 }
}

 
void startcLOSE() {
  int iOrders=OrdersTotal()-1, i;
  
  if(CloseOpenOrders) {
    for(i=iOrders; i>=0; i--) {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && (OrderType()<=OP_SELL) && GetMarketInfo() && !OrderClose(OrderTicket(),OrderLots(),Price[1-OrderType()],giSlippage)) Print(OrderError());
    }
  }
}
//+------------------------------------------------------------------+
//| Function..: OrderError                                           |
//+------------------------------------------------------------------+
string OrderError() {
  int iError=GetLastError();
  return(StringConcatenate("Order:",OrderTicket()," GetLastError()=",iError," ",ErrorDescription(iError)));
}
//+------------------------------------------------------------------+
//| Function..: GetMarketInfo                                        |
//+------------------------------------------------------------------+
bool GetMarketInfo() {
  RefreshRates();
  Price[0]=MarketInfo(OrderSymbol(),MODE_ASK);
  Price[1]=MarketInfo(OrderSymbol(),MODE_BID);
  double dPoint=MarketInfo(OrderSymbol(),MODE_POINT);
  if(dPoint==0) return(false);
  giSlippage=(Price[0]-Price[1])/dPoint;
  return(Price[0]>0.0 && Price[1]>0.0);
}
//+------------------------------------------------------------------+

void Stamp(){

   ObjectCreate("Original", OBJ_LABEL, 0, 0, 0);
   ObjectSetText("Original", " ---http://Expforex.at.ua---", 10, "Arial Bold", Red);
   ObjectSet("Original", OBJPROP_CORNER, 2);
   ObjectSet("Original", OBJPROP_XDISTANCE, 200);
   ObjectSet("Original", OBJPROP_YDISTANCE, 10);


}

Comments