[ARCHIVE]Any rookie question, so as not to clutter up the forum. Professionals, don't pass it by. Can't go anywhere without you - 5. - page 45

 

Could you please tell me if I put"mn" in the code correctly or not?

//+----------------------------------------------------------------------------------------+
//| ММ Функция работает по принципу наращивания лота при увеличении                        |
//| депозита, и уменьшении лота при серии убыточных сделок лот возвращается                |
//| на начальный лот в данном случае 0.1 если происходит профит то следующий               |
//| лот расчитывается по прогресии.                                                        |
//| К примеру при депозите 500 старт лота будет равен 0.1 далее депозит                    |
//| увеличивается до 5000 лот будет равен 1 если будет две убыточные сделки                |
//| лот уменьшится от предыдущего деленое на DecreaseFactor = 3, если по далее             |
//| две сделки будут убыточные,уменьшится от предыдущего деленое на DecreaseFactor = 3,    |
//| далее если сделка будет прибыльной то следующий лот откроется из расчета               |
//| баланса депозита "баланс/500*0.1"=лот внешние переменные                               |
//+----------------------------------------------------------------------------------------+

double LotsOptimized() {
       double minlot = MarketInfo(Symbol(), MODE_MINLOT);
       double maxlot = MarketInfo(Symbol(), MODE_MAXLOT);       
       double lot = Lots;
       int orders = OrdersHistoryTotal();
       int losses = 0;
       lot = NormalizeDouble((AccountFreeMargin()- AccountCredit()) * MaximumRisk / balans, 2);
       if (DecreaseFactor > 0.0) {
for (int i = orders - 1; i >= 0; i--) {
       if (OrderSelect(i, SELECT_BY_POS, MODE_HISTORY) == FALSE) {
       Print("Error in history!");
       break;
       }
if (OrderSymbol() != Symbol() || OrderType() > OP_SELL || OrderMagicNumber()!=mn) continue;
if (OrderProfit() > 0.0) break; 
if (OrderProfit() < 0.0) losses++;
}
if (losses > 1) lot = NormalizeDouble(lot - lot * losses / DecreaseFactor, 2);
}
if(lot < minlot) lot = minlot;
if(lot > maxlot) lot = maxlot; 
return (lot);} 
 
Please suggest a Time "Condition" for the EA to switch on at a certain time, which I can set
 
I found a script that closes all orders, I want to insert it into an EA, I need this condition =(
 
Tiken123:
Please suggest a Time "Condition" for the EA to switch on at a certain time, which I can set
Here.
 
Thank you!!!
 
BeerGod:

Please tell me if I added"mn" to the code correctly or not, so that Magic number can be tracked in MM?

If Magic is declared as global variable or constant:

int mn = ****;

and so structurally without errors (small syntax edit):

double LotsOptimized()
{
    double minlot = MarketInfo (Symbol(), MODE_MINLOT),
           maxlot = MarketInfo(Symbol(), MODE_MAXLOT),       
           lot = Lots, ld_Profit = 0.0;
    int    orders = OrdersHistoryTotal(), losses = 0;
//----
    lot = NormalizeDouble ((AccountFreeMargin() - AccountCredit()) * MaximumRisk / balans, 2);
    if (DecreaseFactor > 0.0)
    {
        for (int i = orders - 1; i >= 0; i--)
        {
             if (!OrderSelect (i, SELECT_BY_POS, MODE_HISTORY)) {Print ("Error in history!"); break;}
             if (OrderSymbol() != Symbol()) continue;
             if (OrderType() > OP_SELL) continue;
             if (OrderMagicNumber() != mn) continue;
             ld_Profit = OrderProfit();
             if (ld_Profit > 0.0) break; 
             if (ld_Profit < 0.0) losses++;
        }
        if (losses > 1) lot = NormalizeDouble (lot - lot * losses / DecreaseFactor, 2);
    }
    if (lot < minlot) lot = minlot;
    if (lot > maxlot) lot = maxlot; 
//----
    return (lot);
}

You should normalize the lot by multiplicity MODE_LOTSTEP, otherwise you will sooner or later stumble upon error 131 (ERR_INVALID_TRADE_VOLUME).

Well, and variables not declared in the function on your conscience... :)

 
How do I do this: I need to set a new order at the right level after closing a particular order. I tried to write it this way, it doesn't open... How to write it correctly?
//-- Открытие ордеров  после закрытия
if  (OrderSelect(Ticket_B,SELECT_BY_TICKET,MODE_TRADES)==false)
     {Ticket_B=0;}
if  (OrderSelect(Ticket_B_1,SELECT_BY_TICKET,MODE_TRADES)==false)
     {Ticket_B_1=0;}
if  (OrderSelect(Ticket_B_2,SELECT_BY_TICKET,MODE_TRADES)==false)
     {Ticket_B_2=0;}

...

       if (Ticket_B==0)    // в этом месте пробовал и (Ticket_B<1), тоже никак
        {                                     
         SL=Bid - New_Stop(StopLoss)*Point;     
         TP=Ask + New_Stop(TakeProfit)*Point;   
         Alert("Попытка открыть Buy. Ожидание ответа..");
         Ticket_B=OrderSend(Symbol(),OP_BUY,Lts,Ask,1,SL,TP,"121212",121212,0,CLR_NONE);
         if (Ticket_B > 0)                       
           {
            Alert ("Открыт ордер Buy ",Ticket_B);
            OrderSelect(Ticket_B,SELECT_BY_TICKET,MODE_TRADES);
            one_price=OrderOpenPrice();
         if (Fun_Error(GetLastError())==1)     
            continue;                           
         return;                              
           }
        }
        
 
        
//-- Открытие ордеров -- BuyStop
       if (Up>=1 && Ticket_B_1<1)
        {
         SL_1=SL;
         TP_1=one_price + StepUp*Point + New_Stop(TakeProfit)*Point;
         Ticket_B_1=OrderSend(Symbol(), OP_BUYSTOP, Lts, one_price + StepUp*Point, 1, SL_1, TP_1,"121212",121212,0,CLR_NONE);
           {
            Alert("Торговый приказ B2 отправлен на сервер. Ожидание ответа..");
            if (Ticket_B_1>0)
              {
               Alert ("Установлен ордер BuyStop ",Ticket_B_1);
               }  
            }
         }
 

Hello,

I need some professional help (someone who knows this stuff...).

I can't get the idea to work... I found it all and put it into the robot but it still doesn't work that way =(

I want to close all profits.

I want to close all profitable positions when the total profitability is larger than the total loss. I try to close all profitable positions (Profit> Losses)

 

Help with code. The condition (Total Profit>Total Loss) to close all profitable trades does not work

I need it to count losing trades from the moment of "maximum balance" to close all profitable trades as they reach a profit more than the entire loss, and start counting losing trades again with the new depo

Has anybody seen an Expert Advisor that keeps track of a deposit balance, for example, trade started with a balance of 50... losses started, the Expert Advisor should remember how much the balance has fallen, so that in next time the profit of open positions exceeds this loss, it should close all profitable trades, and start counting losses again.

   if (GetProfitOpenPosInCurrency()>NumberOfLossPosToday()) 
   int slippage=1;
   int ask, bid, open;
   double point;
   for (int i=OrdersTotal()-1; i>=0; i--)
   {
      if (!OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) break;
      if (OrderType()==OP_BUY)
      {
         point=MarketInfo(OrderSymbol(),MODE_POINT);
         if (point==0) break;
         bid=MathRound(MarketInfo(OrderSymbol(),MODE_BID)/point);
         open=MathRound(OrderOpenPrice()/point);
         if (bid-open<Profit) continue;
         OrderClose(OrderTicket(),OrderLots(),bid*point,slippage);
      }
      if (OrderType()==OP_SELL)
      {
         point=MarketInfo(OrderSymbol(),MODE_POINT);
         if (point==0) break;
         ask=MathRound(MarketInfo(OrderSymbol(),MODE_ASK)/point);
         open=MathRound(OrderOpenPrice()/point);
         if (open-ask<Profit) continue;
         OrderClose (OrderTicket(),OrderLots(),ask*point,slippage);
      }
   }
}
//--------------------------------------------------------------------
double GetProfitOpenPosInCurrency(string sy="", int op=-1, int mn=-1) {
  double p=0;
  int    i, k=OrdersTotal();

  if (sy=="0") sy=Symbol();
  for (i=0; i<k; i++) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
      if ((OrderSymbol()==sy || sy=="") && (op<0 || OrderType()==op)) {
        if (OrderType()==OP_BUY || OrderType()==OP_SELL) {
          if (mn<0 || OrderMagicNumber()==mn) {
            p+=OrderProfit()+OrderCommission()+OrderSwap();
          }
        }
      }
    }
  }
  return(p);
}
//--------------------------------------------------------------------
int NumberOfLossPosToday(string sy="", int op=-1, int mn=-1) {
  datetime t;
  int      i, k=OrdersHistoryTotal(), kp=0;

  if (sy=="0") sy=Symbol();
  for (i=0; i<k; i++) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_HISTORY)) {
      if (OrderSymbol()==sy || sy=="") {
        if (OrderType()==OP_BUY || OrderType()==OP_SELL) {
          if (op<0 || OrderType()==op) {
            if (mn<0 || OrderMagicNumber()==mn) {
              t=OrderCloseTime();
              if (Year()==TimeYear(t) && DayOfYear()==TimeDayOfYear(t)) {
                if (OrderProfit()<0) kp++;
              }
            }
          }
        }
      }
    }
  }
  return(kp);
}
 

How do I know if the last 1-2-3 orders were losing?

How do I know what was the last order?

For example I need to know if a pending buy limit triggered and if it did, at what price and then place a new one.

How do I know if the order has triggered on a trailing stop and then place a new order after the trailing stop has been triggered?