cm CloseProfit

Orders Execution
Checks for the total of open ordersIt Closes Orders by itself It automatically opens orders when conditions are reached
Miscellaneous
It issuies visual alerts to the screen
0 Views
0 Downloads
0 Favorites
cm CloseProfit
ÿþ//+------------------------------------------------------------------+

#property copyright "Copyright © 2022, http://cmillion.ru"

#property link      "cmillion@narod.ru"

#property strict

#property description "!>25B=8: 70:@K205B 2A5 >@45@0 ?@8 4>AB865=88 7040==>3> @07<5@0 ?@>D8B0 8;8 C1KB:0 2 20;NB5 45?>78B0."

#property description " the EA closes all orders when the specified amount of profit or loss in the Deposit currency is reached."

//-------------------------------------------------------------------

input double ProfitClose     = 10;   

//70:@K20BL 2A5 >@45@0 ?@8 ?>;CG5=88 ?@>D8B0

input double LossClose       = 1000; 

//70:@K20BL 2A5 >@45@0 ?@8 ?>;CG5=88 C1KB:0

input bool   AllSymbol       = false;

//CG8BK20BL 2A5 8=AB@C<5=BK 8;8 B>;L:> B5:CI89

input bool   AllMagik        = true;

//CG8BK20BL 2A5 <038:8 8;8 B>;L:> C:070=K5 =865

input string Magik     = "0,1,2,3,4,5";

input bool   DeleteOrders    = true;

//C40;OBL >B;>65==K5 >@45@0

int Slippage = 100;

//--------------------------------------------------------------------

#ifdef __MQL5__

double Bid,Ask;

MqlTick tick;

MqlTradeRequest request;

MqlTradeResult result;

MqlTradeCheckResult check;

ENUM_ORDER_TYPE_FILLING FillingMode=ORDER_FILLING_RETURN;

int FREEZE_LEVEL=0;

#endif   

//--------------------------------------------------------------------

int magik[20],n;

string AC,txt="";

bool LANGUAGE;

bool CheckMagik(int MN)

{

   if (AllMagik) return(true);

   for(int i=0; i<n; i++)

   {

      if (magik[i]==MN) return(true);

   }

   return(false);

}

//--------------------------------------------------------------------

int OnInit()

{

#ifdef __MQL5__

   int FILLING_MODE=(int)SymbolInfoInteger(_Symbol, SYMBOL_FILLING_MODE);

   if ((SYMBOL_FILLING_IOC & FILLING_MODE)==SYMBOL_FILLING_IOC) FillingMode=ORDER_FILLING_IOC;// A5 8;8 G0AB8G=>

   if ((SYMBOL_FILLING_FOK & FILLING_MODE)==SYMBOL_FILLING_FOK) FillingMode=ORDER_FILLING_FOK;//<>65B 1KBL 8A?>;=5= 8A:;NG8B5;L=> 2 C:070==>< >1J5<5

#endif   

   AC=" "+AccountInfoString(ACCOUNT_CURRENCY);;

   LANGUAGE=TerminalInfoString(TERMINAL_LANGUAGE)=="Russian";

   string h;

   int i,index,bar=0;

   n=0;

   ArrayInitialize(magik,-100);

   for(i=0; i<=StringLen(Magik); i++)

   {

      index=StringFind(Magik,",",i);  

      h=StringSubstr(Magik,i,index);

      bar=(int)StringToInteger(h);

      magik[n]=bar; n++; i=index;

      if (index==-1 || n==20) break;

   }

   LabelCreate(0,"Balance"    ,0,5, 30,CORNER_RIGHT_UPPER,"Balance "    +DoubleToString(AccountInfoDouble(ACCOUNT_BALANCE),2)+AC);

   LabelCreate(0,"Equity"     ,0,5, 45,CORNER_RIGHT_UPPER,"Equity "     +DoubleToString(AccountInfoDouble(ACCOUNT_EQUITY),2)+AC);

   LabelCreate(0,"Profit" ,0,5, 60,CORNER_RIGHT_UPPER,"Profit ");

   LabelCreate(0,"Copyright" ,0,5, 20,CORNER_RIGHT_LOWER,"CloseProfit © 2022, http://cmillion.ru\n","Arial",8,clrGray);

   



   if (AllSymbol) txt = LANGUAGE?"> 2A5< 8=AB@C<5=B0< AG5B0":"For all account instruments"; else txt = (LANGUAGE?"> ":"In ")+Symbol();

   if (AllMagik) txt = txt+(LANGUAGE?"\n> 2A5< <038:0<":"\nFor all magicians");

   else

   {

      txt = txt+(LANGUAGE?"\n> <038:0<":"\nFor magicians");

      for(i=0; i<n; i++)

      {

         txt = txt+" "+IntegerToString(magik[i]);

      }

   }

   Comment(txt);

   return(INIT_SUCCEEDED);

}

//-------------------------------------------------------------------

void OnDeinit(const int reason)

{

   ObjectDelete(0,"Balance");

   ObjectDelete(0,"Equity");

   ObjectDelete(0,"Profit");

   ObjectDelete(0,"Copyright");

}

//-------------------------------------------------------------------

void OnTick()

{

   double profit,Profit=0,LB=0,LS=0,OL;

   int i,Mag,b=0,s=0,OT;

#ifdef __MQL5__

   for(i=PositionsTotal()-1; i>=0; i--)

   {

      OT=0;

      string Symb=PositionGetSymbol(i);

      Mag=(int)PositionGetInteger(POSITION_MAGIC);

      if ((Symb == Symbol() || AllSymbol) && CheckMagik(Mag))

      {

         profit  = PositionGetDouble(POSITION_PROFIT)+PositionGetDouble(POSITION_SWAP)+GetPositionCommission()*2;

         if (profit!=0)

         {

            if (PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY ) OT= 1;

            if (PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_SELL) OT=-1;

            OL  = PositionGetDouble(POSITION_VOLUME);

#endif   

#ifdef __MQL4__

   for (i=OrdersTotal()-1; i>=0; i--)

   {                                               

      if (OrderSelect(i,SELECT_BY_POS,MODE_TRADES))

      {

         if ((OrderSymbol() == Symbol() || AllSymbol) && CheckMagik(OrderMagicNumber()))

         {

            if (OrderType()==OP_BUY) OT=1;

            if (OrderLots()==OP_SELL) OT =-1;

            profit = OrderProfit()+OrderSwap()+OrderCommission();

            OL = OrderLots();

#endif   

            if (OT==1)

            {

               b++;LB+= OL;

               Profit+=profit;

            }

            if (OT==-1)

            {

               s++;LS+= OL;

               Profit+=profit;

            }

         }

      }

   }

   

   //--- 

   

   Comment(txt,"\nSum Lot ",DoubleToString((LB+LS),2),"\nProfitClose ",DoubleToString(ProfitClose,2),AC,"\nLossClose ",DoubleToString(-LossClose,2),AC,"\nBuy "+IntegerToString(b)+"  Lot Buy = "+DoubleToString(LB,2)+"\nSell "+IntegerToString(s)+"  Lot Sell = "+DoubleToString(LS,2));



   if (Profit>=ProfitClose) 

   {

      Alert(LANGUAGE?">AB83=CB C@>25=L ?@>D8B0 = ":"You have reached the level of profit = "+DoubleToString(Profit,2));

      CloseAll();

   }

   if (Profit<=-LossClose)

   {

      Alert(LANGUAGE?">AB83=CB C@>25=L <0:A8<0;L=>3> C1KB:0 ":"You have reached the level of maximum loss "+DoubleToString(Profit,2));

      CloseAll();

   }

   ObjectSetString(0,"Balance",OBJPROP_TEXT,"Balance "+DoubleToString(AccountInfoDouble(ACCOUNT_BALANCE),2));

   ObjectSetString(0,"Equity",OBJPROP_TEXT,"Equity "+DoubleToString(AccountInfoDouble(ACCOUNT_EQUITY),2));



   string txt2;

   if (LB>0 || LS>0) 

   {

      if (AllSymbol) txt2 = "Profit All Symbol "+DoubleToString(Profit,2);

      else           txt2 = "Profit "+Symbol()+" "+DoubleToString(Profit,2);

   }

   ObjectSetString(0,"Profit",OBJPROP_TEXT,txt2);

   ObjectSetInteger(0,"Profit",OBJPROP_COLOR,Color(Profit));

}

//------------------------------------------------------------------

color Color(double P)

{

   if (P>0) return(Green);

   if (P<0) return(Red);

   return(Green);

}

//------------------------------------------------------------------

#ifdef __MQL4__

bool CloseAll()

{

   bool error=true;

   int j,err,nn=0,OT;

   string Symb;

   while(true)

   {

      for (j = OrdersTotal()-1; j >= 0; j--)

      {

         if (OrderSelect(j, SELECT_BY_POS))

         {

            Symb = OrderSymbol();

            if ((Symb == Symbol() || AllSymbol) && CheckMagik(OrderMagicNumber()))

            {

               OT = OrderType();

               if (DeleteOrders && OT>1) 

               {

                  error=OrderDelete(OrderTicket());

               }

               if (OT==OP_BUY) 

               {

                  error=OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(MarketInfo(Symb,MODE_BID),(int)MarketInfo(Symb,MODE_DIGITS)),Slippage,Blue);

                  if (error) Alert(Symb,"  Close order N ",OrderTicket(),"  Profit ",OrderProfit(),

                                     "     ",TimeToStr(TimeCurrent(),TIME_SECONDS));

               }

               if (OT==OP_SELL) 

               {

                  error=OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(MarketInfo(Symb,MODE_ASK),(int)MarketInfo(Symb,MODE_DIGITS)),Slippage,Red);

                  if (error) Alert(Symb,"  Close order N ",OrderTicket(),"  Profit ",OrderProfit(),

                                     "     ",TimeToStr(TimeCurrent(),TIME_SECONDS));

               }

               if (!error) 

               {

                  err = GetLastError();

                  if (err<2) continue;

                  if (err==129) 

                  {

                     Sleep(5000);

                     RefreshRates();

                     continue;

                  }

                  if (err==146) 

                  {

                     if (IsTradeContextBusy()) Sleep(2000);

                     continue;

                  }

                  Comment("Error ",err," close order N ",OrderTicket(),

                          "     ",TimeToStr(TimeCurrent(),TIME_MINUTES));

               }

            }

         }

      }

      int k=0;

      for (j = 0; j < OrdersTotal(); j++)

      {

         if (OrderSelect(j, SELECT_BY_POS))

         {

            if ((OrderSymbol() == Symbol() || AllSymbol) && CheckMagik(OrderMagicNumber()))

            {

               OT = OrderType();

               if (OT==OP_BUY || OT==OP_SELL) k++;

            }

         }  

      }

      if (k==0) break;

      nn++;

      if (nn>10) {return(false);}

      Sleep(1000);

      RefreshRates();

   }

   return(true);

}

//--------------------------------------------------------------------

#endif   

#ifdef __MQL5__

bool CloseAll()

{

   bool error=true;

   ulong Ticket;

   int Mag,i,err,nn=0;

   long OT;

   string Symb;

   while(true)

   {

      for (i = PositionsTotal()-1; i >= 0; i--)

      {

         Symb=PositionGetSymbol(i);

         Mag=(int)PositionGetInteger(POSITION_MAGIC);

         if ((Symb == Symbol() || AllSymbol) && CheckMagik(Mag))

         {

            ZeroMemory(request);

            ZeroMemory(result);

            OT = PositionGetInteger(POSITION_TYPE);

            request.deviation = Slippage;

            request.volume=PositionGetDouble(POSITION_VOLUME);

            request.position  = PositionGetInteger(POSITION_TICKET);

            request.action=TRADE_ACTION_DEAL;

            request.comment="";

            request.type_filling = FillingMode;

            request.symbol = Symb;

            request.magic    =Mag; 

            if (OT==POSITION_TYPE_BUY) 

            {

               request.price=SymbolInfoDouble(Symb,SYMBOL_BID);

               request.type=ORDER_TYPE_SELL;

            }

            if (OT==POSITION_TYPE_SELL) 

            {

               request.price=SymbolInfoDouble(Symb,SYMBOL_ASK);

               request.type=ORDER_TYPE_BUY;

            }

            if(!OrderSend(request,result))

            {

               err = GetLastError();

               if (err<2) continue;

            }

         }

      }

      int nnn=0;

      for (i = 0; i < PositionsTotal(); i++)

      {

         Symb=PositionGetSymbol(i);

         Mag=(int)PositionGetInteger(POSITION_MAGIC);

         if ((Symb == Symbol() || AllSymbol) && CheckMagik(Mag))

         {

            nnn++;

         }  

      }

      if (nnn==0) break;

      nn++;

      if (nn>10) 

      {

         break;

      }

      Sleep(1000);

   }



   //---



   if (DeleteOrders)

   {

      for(i=0; i<OrdersTotal(); i++)

      {

         Mag=(int)OrderGetInteger(ORDER_MAGIC);

         Symb=OrderGetString(ORDER_SYMBOL);

         if ((Symb == Symbol() || AllSymbol) && CheckMagik(Mag))

         {

            if((Ticket=OrderGetTicket(i))>0)

            {

               ZeroMemory(request);

               ZeroMemory(result);

               request.action  = TRADE_ACTION_REMOVE;

               request.order   = Ticket;

               if(!OrderSend(request,result)) Print("error OrderDelete  ",GetLastError());

               else return(true);

            }

         }

      }

   }



   return(true);

}

//--------------------------------------------------------------------

#endif   

bool LabelCreate(const long              chart_ID=0,               // ID 3@0D8:0 

                 const string            name="Label",             // 8<O <5B:8 

                 const int               sub_window=0,             // =><5@ ?>4>:=0 

                 const int               x=0,                      // :>>@48=0B0 ?> >A8 X 

                 const int               y=0,                      // :>>@48=0B0 ?> >A8 Y 

                 const ENUM_BASE_CORNER  corner=CORNER_LEFT_UPPER, // C3>; 3@0D8:0 4;O ?@82O7:8 

                 const string            text="Label",             // B5:AB 

                 const string            font="Arial",             // H@8DB 

                 const int               font_size=10,             // @07<5@ H@8DB0 

                 const color             colr=clrGray,               // F25B 

                 const double            angle=0.0,                // =0:;>= B5:AB0 

                 const ENUM_ANCHOR_POINT anchor=ANCHOR_RIGHT_UPPER, // A?>A>1 ?@82O7:8 

                 const bool              back=false,               // =0 704=5< ?;0=5 

                 const bool              selection=false,          // 2K45;8BL 4;O ?5@5<5I5=89 

                 const bool              hidden=true,              // A:@KB 2 A?8A:5 >1J5:B>2 

                 const long              z_order=0)                // ?@8>@8B5B =0 =060B85 <KHLN 

{ 

   if (ObjectFind(chart_ID,name)==-1) 

   {

      if(!ObjectCreate(chart_ID,name,OBJ_LABEL,sub_window,0,0)) 

      { 

         Print(__FUNCTION__,": =5 C40;>AL A>740BL B5:AB>2CN <5B:C! >4 >H81:8 = ",GetLastError()); 

         return(false); 

      } 

   }

   ObjectSetInteger(chart_ID,name,OBJPROP_XDISTANCE,x); 

   ObjectSetInteger(chart_ID,name,OBJPROP_YDISTANCE,y); 

   ObjectSetInteger(chart_ID,name,OBJPROP_CORNER,corner); 

   ObjectSetString(chart_ID,name,OBJPROP_TEXT,text); 

   ObjectSetString(chart_ID,name,OBJPROP_FONT,font); 

   ObjectSetInteger(chart_ID,name,OBJPROP_FONTSIZE,font_size); 

   ObjectSetDouble(chart_ID,name,OBJPROP_ANGLE,angle); 

   ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor); 

   ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,colr); 

   ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back); 

   ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection); 

   ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection); 

   ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden); 

   ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order); 

   return(true); 

}

//--------------------------------------------------------------------

#ifdef __MQL5__

//--------------------------------------------------------------------

double GetPositionCommission(void)

  {

   double Commission=::PositionGetDouble(POSITION_COMMISSION);

// 0 A;CG09, 5A;8 POSITION_COMMISSION =5 @01>B05B

   if(Commission==0)

     {

      ulong Ticket=GetPositionDealIn();



      if(Ticket>0)

        {

         const double LotsIn=::HistoryDealGetDouble(Ticket,DEAL_VOLUME);

         if(LotsIn>0)

            Commission=::HistoryDealGetDouble(Ticket,DEAL_COMMISSION)*::PositionGetDouble(POSITION_VOLUME)/LotsIn;

        }

     }

   return(Commission);

  }

//--------------------------------------------------------------------

ulong GetPositionDealIn(const ulong HistoryTicket=0)

  {

   ulong Ticket=0;



   if((HistoryTicket==0) ? ::HistorySelectByPosition(::PositionGetInteger(POSITION_TICKET)) : ::HistorySelectByPosition(HistoryTicket))

     {

      const int Total=::HistoryDealsTotal();



      for(int i=0; i<Total; i++)

        {

         const ulong TicketDeal=::HistoryDealGetTicket(i);



         if(TicketDeal>0)

            if((ENUM_DEAL_ENTRY)::HistoryDealGetInteger(TicketDeal,DEAL_ENTRY)==DEAL_ENTRY_IN)

              {

               Ticket=TicketDeal;

               break;

              }

        }

     }

   return(Ticket);

  }

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

   #endif

Comments

Markdown supported. Formatting help

Markdown Formatting Guide

Element Markdown Syntax
Heading # H1
## H2
### H3
Bold **bold text**
Italic *italicized text*
Link [title](https://www.example.com)
Image ![alt text](image.jpg)
Code `code`
Code Block ```
code block
```
Quote > blockquote
Unordered List - Item 1
- Item 2
Ordered List 1. First item
2. Second item
Horizontal Rule ---