Подскажите пожалуйста как написать закрытие всех ордеров при достижении определённого профита ? - страница 2

 
Tenimagalon:
А если нужно закрыть не все. допустим 4 ордера пара бай и пара селл. Допустим пара бай вышла в профит на заданную мной прибыли.И нужно закрыть Все бай и оставить. Селл ордера как выразить в коде плиз помогите голову уже сломал. 

вот тут есть эта функция \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ Добавил - как общая прибыль сработает, сменятся на всех открытых графиках шаблон(отмечено зелёным)

 

//+------------------------------------------------------------------+
//|                                                    Proba San.mq4 |
//|                        Copyright 2021, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2021, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict
#include <stdlib.mqh>
//---
#define MAGICMA  20131111
//--- Inputs
input string   t="------------- Balans Parameters -----"; //
input string   Template         = "ADX";         // Имя шаблона(without '.tpl')
input double   TargetProfit     = 999999.99;     // Баланс + Прибыль(прибавить к балансу)
input double   TargetLoss       = 0;             // Баланс - Убыток(отнять от баланса)
input string   t2="------------ Exchange TP SL --------"; //
input double   InpTProfit       = 10;            // Exchange TP
input double   InpStopLoss      = 1000000;       // Exchange SL
input string   t0="------------ Lots Parameters -------"; //
input double   InpLots1         = 0.02;          // : Lots 1
input int      InpLots_01       = 20;            // Exchange Lots
input double   InpLots2         = 0.04;          // : Lots 2
input int      InpLots_02       = 40;            // Exchange Lots
input double   InpLots3         = 0.08;          // : Lots 3
input int      InpLots_03       = 80;            // Exchange Lots
input double   InpLots4         = 0.16;          // : Lots 4
input string   _Orders_="------ Revers Order ------";     //
input bool     ObjRevers        = false;         // Revers
//---
uint   SLEEPTIME        = 1;
bool   CloseOpenOrders  = true;
double Price[2];
ENUM_TIMEFRAMES TimeFrame; // Change TimeFrame - Current = dont changed
//+------------------------------------------------------------------+
//| Calculate open positions                                         |
//+------------------------------------------------------------------+
int CalculateCurrentOrders(string symbol)
  {
   int buys=0,sells=0;
//---
   for(int i=0; i<OrdersTotal(); i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false)
         break;
      if(OrderSymbol()==Symbol() && OrderMagicNumber()==MAGICMA)
        {
         if(OrderType()==OP_BUY)
            buys++;
         if(OrderType()==OP_SELL)
            sells++;
        }
     }
//--- return orders volume
   if(buys>0)
      return(buys);
   else
      return(-sells);
  }
//+------------------------------------------------------------------+
//| Calculate optimal lot size                                       |
//+------------------------------------------------------------------+
double OptimizedBuy(void)
  {
   double PROFIT_BUY=0.00;
   double PROFIT_SELL=0.00;
   for(int i=OrdersTotal()-1; i>=0; i--) // returns the number of open positions
     {
      if(OrderSelect(i,SELECT_BY_POS) && OrderSymbol()==Symbol())
        {
         if(OrderSymbol()==Symbol() && OrderType()==OP_BUY)
           {
            PROFIT_BUY=PROFIT_BUY+NormalizeDouble(OrderProfit(),2);
           }
         if(OrderSymbol()==Symbol() && OrderType()==OP_SELL)
           {
            PROFIT_SELL=PROFIT_SELL+NormalizeDouble(OrderProfit(),2);
           }
        }
     }
   double Lots=InpLots1;
   double ab=PROFIT_BUY;
   if(ab<-1 && ab>=-InpLots_01)
      Lots=InpLots1;
   if(ab<-InpLots_01 && ab>=-InpLots_02)
      Lots=InpLots2;
   if(ab<-InpLots_02 && ab>=-InpLots_03)
      Lots=InpLots3;
   if(ab<-InpLots_03)
      Lots=InpLots4;
//--- return trading volume
   return(Lots);
  }
//+------------------------------------------------------------------+
//| Calculate optimal lot size                                       |
//+------------------------------------------------------------------+
double OptimizedSell(void)
  {
   double PROFIT_BUY=0.00;
   double PROFIT_SELL=0.00;
   for(int i=OrdersTotal()-1; i>=0; i--) // returns the number of open positions
     {
      if(OrderSelect(i,SELECT_BY_POS) && OrderSymbol()==Symbol())
        {
         if(OrderSymbol()==Symbol() && OrderType()==OP_BUY)
           {
            PROFIT_BUY=PROFIT_BUY+NormalizeDouble(OrderProfit(),2);
           }
         if(OrderSymbol()==Symbol() && OrderType()==OP_SELL)
           {
            PROFIT_SELL=PROFIT_SELL+NormalizeDouble(OrderProfit(),2);
           }
        }
     }
   double Lots=InpLots1;
   double ab=PROFIT_SELL;
   if(ab<-1 && ab>=-InpLots_01)
      Lots=InpLots1;
   if(ab<-InpLots_01 && ab>=-InpLots_02)
      Lots=InpLots2;
   if(ab<-InpLots_02 && ab>=-InpLots_03)
      Lots=InpLots3;
   if(ab<-InpLots_03)
      Lots=InpLots4;
//--- return trading volume
   return(Lots);
  }
//+------------------------------------------------------------------+
//| Check for open order conditions                                  |
//+------------------------------------------------------------------+
void CheckForOpen()
  {
   double MacdCurrent,SignalCurrent;
   int    res;
//--- go trading only for first tiks of new bar
   if(Volume[0]>1)
      return;
//--- get Moving Average
   MacdCurrent=iCustom(NULL,0,"Phoenix",MODE_MAIN,1);
   SignalCurrent=iCustom(NULL,0,"Phoenix",MODE_SIGNAL,1);
//--- sell conditions
   if((ObjRevers && MacdCurrent<SignalCurrent) || (!ObjRevers && MacdCurrent>SignalCurrent))
     {
      res=OrderSend(Symbol(),OP_SELL,OptimizedSell(),Bid,3,0,0,"",16384,0,Red);
      return;
     }
//--- buy conditions
   if((ObjRevers && MacdCurrent>SignalCurrent) || (!ObjRevers && MacdCurrent<SignalCurrent))
     {
      res=OrderSend(Symbol(),OP_BUY,OptimizedBuy(),Ask,3,0,0,"",16384,0,Green);
      return;
     }
  }
//+------------------------------------------------------------------+
//| OnTick function                                                  |
//+------------------------------------------------------------------+
void OnTick()
  {
//--- check for history and trading
   if(Bars<100 || IsTradeAllowed()==false)
      return;
//--- calculate open orders by current symbol
   if(CalculateCurrentOrders(Symbol())==0)
      CheckForOpen();
   ProfitOnTick();
   ProfitTarget();
//---
  }
//+------------------------------------------------------------------+
//| Check for long position closing                                  |
//+------------------------------------------------------------------+
bool ProfitOnTick(void)
  {
   bool res=false;
   double PROFIT_BUY=0.00;
   double PROFIT_SELL=0.00;
   for(int i=OrdersTotal()-1; i>=0; i--) // returns the number of open positions
     {
      if(OrderSelect(i,SELECT_BY_POS) && OrderSymbol()==Symbol())
        {
         if(OrderSymbol()==Symbol() && OrderType()==OP_BUY)
           {
            PROFIT_BUY=PROFIT_BUY+NormalizeDouble(OrderProfit(),2);
           }
         if(OrderSymbol()==Symbol() && OrderType()==OP_SELL)
           {
            PROFIT_SELL=PROFIT_SELL+NormalizeDouble(OrderProfit(),2);
           }
        }
     }
   int Close_ticketb=0;
   int totalb=OrdersTotal();
   int b = 0;
   for(b = totalb; b >=0; b--)
     {
      if(OrderSelect(b,SELECT_BY_POS) && OrderSymbol()==Symbol())
        {
         //OrderSelect(i,SELECT_BY_POS);
         if(OrderSymbol()==Symbol() && OrderType()==OP_BUY)
           {
            if(PROFIT_BUY<-InpStopLoss || PROFIT_BUY>=InpTProfit)
              {
               Close_ticketb = OrderClose(OrderTicket(),OrderLots(),MarketInfo(Symbol(),MODE_BID),5);
               PlaySound("ok.wav");
              }
           }
        }
      res=true;
     }
   int Close_tickets=0;
   int totals=OrdersTotal();
   int s = 0;
   for(s = totals; s >=0; s--)
     {
      if(OrderSelect(s,SELECT_BY_POS) && OrderSymbol()==Symbol())
        {
         if(OrderSymbol()==Symbol() && OrderType()==OP_SELL)
           {
            if(PROFIT_SELL<-InpStopLoss || PROFIT_SELL>=InpTProfit)
              {
               Close_tickets = OrderClose(OrderTicket(),OrderLots(),MarketInfo(Symbol(),MODE_ASK),5);
               PlaySound("ok.wav");
              }
           }
        }
      res=true;
     }
//--- result
   return(res);
  }
//+------------------------------------------------------------------+
//| Check  closing                                                   |
//+------------------------------------------------------------------+
bool ProfitTarget(void)
  {
   bool res=false;
   if(AccountInfoDouble(ACCOUNT_EQUITY)<=TargetLoss ||
      AccountInfoDouble(ACCOUNT_EQUITY)>=TargetProfit)
     {
      CloseAllOrders();
      Sleep(SLEEPTIME*1000);
      CloseAllOrders();
      ExpertRemove();
      DeleteChart();
      PlaySound("expert.wav");
      res=true;
     }
//--- result
   return(res);
  }
//+------------------------------------------------------------------+
//| script program start function                                    |
//+------------------------------------------------------------------+
void CloseAllOrders(void)
  {
   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()],0))
            Print(OrderError());
         if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
           {
            if(OrderDelete(OrderTicket()))
               Print(OrderError());
           }
        }
     }
  }
//+------------------------------------------------------------------+
//| Function..: OrderError                                           |
//+------------------------------------------------------------------+
string OrderError(void)
  {
   int iError=GetLastError();
   return(StringConcatenate("Order:",OrderTicket()," GetLastError()=",iError," ",ErrorDescription(iError)));
  }
//+------------------------------------------------------------------+
//| Function..: GetMarketInfo                                        |
//+------------------------------------------------------------------+
bool GetMarketInfo(void)
  {
   RefreshRates();
   Price[0]=MarketInfo(OrderSymbol(),MODE_ASK);
   Price[1]=MarketInfo(OrderSymbol(),MODE_BID);
   double dPoint=MarketInfo(OrderSymbol(),MODE_POINT);
   if(dPoint==0)
      return(false);
   return(Price[0]>0.0 && Price[1]>0.0);
  }
//+------------------------------------------------------------------+
//| start function                                                   |
//+------------------------------------------------------------------+
void DeleteChart(void)
  {
   long currChart,prevChart=ChartFirst();
   int i=0,limit=100;
   bool errTemplate;
   while(i<limit)
     {
      currChart=ChartNext(prevChart);
      if(TimeFrame!=PERIOD_CURRENT)
        {
         ChartSetSymbolPeriod(prevChart,ChartSymbol(prevChart),TimeFrame);
        }
      errTemplate=ChartApplyTemplate(prevChart,Template+".tpl");
      if(!errTemplate)
        {
         Print("Error ",ChartSymbol(prevChart),"-> ",GetLastError());
        }
      if(currChart<0)
         break;
      Print(i,ChartSymbol(currChart)," ID =",currChart);
      prevChart=currChart;
      i++;
     }
  }
//+------------------------------------------------------------------+

Где синим  1. задайте свою логику - Где жёлтым 2.меняйте Индикатор 

от Индикатора  "Phoenix" https://www.mql5.com/ru/code/28364 с начальным Балансом 10000 - задал 1050 заработать прибыли. и по 10 в каждую из сторон.

Phoenix

Phoenix
Phoenix
  • www.mql5.com
Стрелочный форекс индикатор Phoenix обладает целым набором параметром, которые позволяют подстроить его для торговли на любой валютной паре.
Причина обращения: