Any rookie question, so as not to clutter up the forum. Professionals, don't pass by. Nowhere without you - 6. - page 537

 

There is a script:

#property show_confirm;
int slip=5;

void start()
{
  for(int i=OrdersTotal()-1;i<=0;i--)
  {
   int p=0; double price=0;
      if(OrderSelect(i,SELECT_BY_POS))
     {
       switch(OrderType())
        {
         case 0: price = MarketInfo(OrderSymbol(),MODE_BID); break;
         case 1: price = MarketInfo(OrderSymbol(),MODE_ASK); break;
         default: break;
        }
         while(p<5)                              
           {                                    
            bool tik= OrderClose(OrderTicket(),OrderLots(),price,slip,Red);
            if(tik==true) 
               break;                   
            else                              
              {
               p++;                              
               Print(__FUNCTION__,"_Error_",GetLastError()); 
               Sleep(1000);                       
              }
           }
     }
 }
}

Which does not even attempt to close a single market order currently open. Why?

It doesn't write any errors in the log:

2014.03.10 04:39:11.093 Script closeallmarket AUDUSD,M30: removed<br / translate="no"> 2014.03.10 04:39:11.093 closeallmarket AUDUSD,M30: uninit reason 0
2014.03.10 04:39:11.093 closeallmarket AUDUSD,M30: initialized
2014.03.10 04:39:10.109 Script closeallmarket AUDUSD,M30: loaded successfully
 

Replace

 for(int i=OrdersTotal()-1;i<=0;i--)

to

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

Hello Mr. professionals.Don't refuse a newcomer to programming, look at the code, to see if it is written correctly. Who is not too lazy to deal with it. I cannot test it in the Strategy Tester because it is multicurrency. File with the code and indicators attached to the archive.



 

Afternoon.

I can't make a code analogue from php to mql4:

$massiv = array(
            "1" => 0.2145,
            "2" => 1.5447,
            "3" => 0.3544,
            "4" => 3.6541,
            "5" => 6.5441,
            "6" => 4.3217,
            "7" => 5.8354,
            "8" => 7.6877            
            );
                        
            asort($massiv);
            $i=0;
            foreach ($massiv as $key => $val){$i++;$massiv[$key]=$i;}
            
            $a="";
            ksort($massiv);
            foreach ($massiv as $key => $val){$a=$a.$val.".";}  

That is, from an array.

            "1" => 0.2145,
            "2" => 1.5447,
            "3" => 0.3544,
            "4" => 3.6541,
            "5" => 6.5441,
            "6" => 4.3217,
            "7" => 5.8354,
            "8" => 7.6877 

Need to get an array

            "1" => 1,
            "2" => 3,
            "3" => 2,
            "4" => 4,
            "5" => 7,
            "6" => 5,
            "7" => 6,
            "8" => 8 

Need help.

 
Roger:

Replace

to


Ohhhh... Man, that's another time, thanks ))))
 

I'm trying to write a simple EA that closes all positions on my account when it reaches specified profit or loss values in the deposit currency (I open by several symbols), but it closes positions as soon as they appear (((

I don't understand what's wrong:

input double tp_c = 80.0;
input double sl_c = 120.0;

input int slip=5;

 double profit_c = 0.0;

void OnTick()
  {
   currencyprofit();
   if(profit_c > tp_c || profit_c < sl_c) closeall();
  }

double currencyprofit()
  {
   for(int i=OrdersTotal()-1;i>=0;i--)
     {
      if(OrderSelect(i,SELECT_BY_POS))
         profit_c = profit_c + OrderProfit();
     }
   return(profit_c);
  }

void closeall()
  {
     for(int i=OrdersTotal()-1;i>=0;i--)
     {
      int p=0; double price=0;
         if(OrderSelect(i,SELECT_BY_POS))
        {
          switch(OrderType())
           {
            case 0: price = MarketInfo(OrderSymbol(),MODE_BID); break;
            case 1: price = MarketInfo(OrderSymbol(),MODE_ASK); break;
            default: break;
           }
            bool tik= OrderClose(OrderTicket(),OrderLots(),price,slip,Red);
            if(tik==false) 
              {
               Print(__FUNCTION__,"_Error_",GetLastError()); 
               Sleep(3000);
               break;
              }
        }
     }
  }
 
denis77515:

Hello Mr. professionals.Don't refuse a newcomer to programming, look at the code, to see if it is written correctly. Who is not too lazy to deal with it. I cannot test it in the Strategy Tester because it is multicurrency. I attached a file with the code and indicators to the archive.



I am very interested in how a beginner is so determined to trade with such an Expert Advisor and to write a trading system that it is worth it. I don't feel sorry for the deposit?


The code shows a lot of errors without going into the trading algorithm, no attempt to optimize it.

Please find the difference between your functions CountBuy_JPY() CountSell_JPY() CountBuy_GBP() In the output of any of them you get the same result, in Buy all open Buy positions, in others all Sal ones. Try to write all these functions in one and get two linked arrays with symbols and number of orders in it.

You are as far away from the Tester as the moon. You should write scripts for each function and look what you get, then run the debugger and look at all variables. This is the only way you will be gradually moving forward

 
evillive:

I'm trying to write a simple EA that closes all positions on my account when it reaches specified profit or loss values in the deposit currency (I open by several symbols), but it closes positions as soon as they appear (((

I don't understand what's wrong:


Analyse the condition ... And the advice is the same, use the printout scripts, and comment out the trade operations for now and debug
if(profit_c > tp_c || profit_c < sl_c) closeall();   profit_c > 80 ИЛИ  profit_c < 120   
 
evillive:

I'm trying to write a simple EA that closes all positions on my account when it reaches specified profit or loss values in the deposit currency (I open by several symbols), but it closes positions as soon as they appear (((

I don't understand what's wrong:



input double tp_c = 80.0;
input double sl_c = - 120.0; //// minus 120

input int slip=5;

 double profit_c ;

void OnTick()
  {
   currencyprofit();
   if(profit_c > tp_c || profit_c < sl_c) closeall();
  }

double currencyprofit()
  {
   profit_c = 0.0;
   for(int i=OrdersTotal()-1;i>=0;i--)
     {
      if(OrderSelect(i,SELECT_BY_POS))
         profit_c = profit_c + OrderProfit();
     }
   return(profit_c);
  }

void closeall()
  {
     for(int i=OrdersTotal()-1;i>=0;i--)
     {
      int p=0; double price=0;
         if(OrderSelect(i,SELECT_BY_POS))
        {
          switch(OrderType())
           {
            case 0: price = MarketInfo(OrderSymbol(),MODE_BID); break;
            case 1: price = MarketInfo(OrderSymbol(),MODE_ASK); break;
            default: break;
           }
            bool tik= OrderClose(OrderTicket(),OrderLots(),price,slip,Red);
            if(tik==false) 
              {
               Print(__FUNCTION__,"_Error_",GetLastError()); 
               Sleep(3000);
               break;
              }
        }
     }
  }
 
denis77515:

Hello Mr. professionals.Don't refuse a newcomer to programming, look at the code, to see if it is written correctly. Who is not too lazy to deal with it. I cannot test it in the Strategy Tester because it is multicurrency. File with the code and indicators attached to the archive.


I have worked out for you a single function to create linked arrays of symbols and number of orders (open positions) to buy and sell, test the script by opening a few positions on a demo
string Smbl[];
int CntBuy[],CntSell[];
void OnStart()
 {
    if(CountBuySell(Smbl, CntSell, CntBuy))
       for(int i=0; i<ArraySize(Smbl); i++) PrintFormat(" Symbol %s CntBuy %d CntSell %d", Smbl[i], CntBuy[i], CntSell[i]);
 }
//-------------------
bool CountBuySell(string &symb[], int &cnt_sell[], int &cnt_buy[])
{
   int ot,n,N=0,f=0,cb=0,cs=0;
   string symbol;
   for(int i=OrdersTotal()-1; i>=0; i--)
   {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
      {
         
         ot=OrderType()+1; if(ot>2)  continue;                       // пропускаем лимит ордера
         symbol=""; symbol=OrderSymbol(); if (symbol=="") continue;  // убедились что символ выбран
         f=0; cb=0; cs=0;                                            // обнулили счетчики и флаг символа
         for (n=0; n<N; n++) if (symbol==symb[n]) f=1;               // если в массиве символ OrderSymbol() уже есть, то не будем увеличивать размерность массивов, просто допишем в нижнем цикле еще 1 позицию
         if (f==0)                                                   // такого символа symbol=OrderSymbol() еще не было, увеличим размерность массивов под новый символ и запишем этот символ
         {
            N++; 
            ArrayResize(symb,N); ArrayResize(cnt_buy,N); ArrayResize(cnt_sell,N);
            symb[N-1]=symbol; cnt_buy[N-1]=0.0; cnt_sell[N-1]=0;
         }
         
         if(ot==1) cb++;  // OP_BUY   для выбранного символа
         else      cs++;  // OP_SELL
         
        // перебираем массив и сравним его с выбранным символом. В найденный индекс запишем для данного символа кол-во откр позиций
        // такоим образом для каждого индекса всех 3 массивов будет соответствовать  конкретный символ и количество позиций покупки и продажи для него
         for (n=0; n<N; n++) if (symbol==symb[n]) { cnt_buy[n]+=cb; cnt_sell[n]+=cs;  }
         
      }
   }
   if(N>0) return(1);   // есть открытые позиции
   return(0);           // позиций нет
}
Reason: