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

 

Help people need to trade on each currency with its own orders to distinguish and differentiate + after the open order if the price rolls back even farther could open another order the same as the first.

//+------------------------------------------------------------------+
//|                                                  MACD Sample.mq4 |
//|                      Copyright © 2005, MetaQuotes Software Corp. |
//|                                       http://www.metaquotes.net/ |
//+------------------------------------------------------------------+
 
extern double TakeProfit = 50;
extern double Lots = 0.1;
extern double TrailingStop = 30;
extern double MACDOpenLevel=3;
extern double MACDCloseLevel=2;
extern double MATrendPeriod=26;

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int start()
  {
   double MacdCurrent, MacdPrevious, SignalCurrent;
   double SignalPrevious, MaCurrent, MaPrevious;
   int cnt=0, ticket, total;
// первичные проверки данных
// важно удостовериться что эксперт работает на нормальном графике и
// пользователь правильно выставил внешние переменные (Lots, StopLoss,
// TakeProfit, TrailingStop)
// в нашем случае проверяем только TakeProfit
   if(Bars<100)
     {
      Print("bars less than 100");
      return(0);  
     }
   if(TakeProfit<10)
     {
      Print("TakeProfit less than 10");
      return(0);  // проверяем TakeProfit
     }
// ради упрощения и ускорения кода, сохраним необходимые
// данные индикаторов во временных переменных
   MacdCurrent=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_MAIN,0);
   MacdPrevious=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_MAIN,1);
   SignalCurrent=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_SIGNAL,0);
   SignalPrevious=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_SIGNAL,1);
   MaCurrent=iMA(NULL,0,MATrendPeriod,0,MODE_EMA,PRICE_CLOSE,0);
   MaPrevious=iMA(NULL,0,MATrendPeriod,0,MODE_EMA,PRICE_CLOSE,1);
 
   total=OrdersTotal();
   if(total<1) 
     {
      // нет ни одного открытого ордера
      if(AccountFreeMargin()<(1000*Lots))
        {
         Print("We have no money. Free Margin = ", AccountFreeMargin());
         return(0);  
        }
      // проверяем на возможность встать в длинную позицию (BUY)
      if(MacdCurrent<0 && MacdCurrent>SignalCurrent && MacdPrevious<SignalPrevious &&
         MathAbs(MacdCurrent)>(MACDOpenLevel*Point) && MaCurrent>MaPrevious)
        {
         ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,0,Ask+TakeProfit*Point,
                          "macd sample",16384,0,Green);
         if(ticket>0)
           {
            if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES))
               Print("BUY order opened : ",OrderOpenPrice());
           }
         else Print("Error opening BUY order : ",GetLastError()); 
         return(0); 
        }
      // проверяем на возможность встать в короткую позицию (SELL)
      if(MacdCurrent>0 && MacdCurrent<SignalCurrent && MacdPrevious>SignalPrevious && 
         MacdCurrent>(MACDOpenLevel*Point) && MaCurrent<MaPrevious)
        {
         ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,3,0,Bid-TakeProfit*Point,
                          "macd sample",16384,0,Red);
         if(ticket>0)
           {
            if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES))
               Print("SELL order opened : ",OrderOpenPrice());
           }
         else Print("Error opening SELL order : ",GetLastError()); 
         return(0); 
        }
      return(0);
     }
   // переходим к важной части эксперта - контролю открытых позиций
   // 'важно правильно войти в рынок, но выйти - еще важнее...'
   for(cnt=0;cnt<total;cnt++)
     {
      OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
      if(OrderType()<=OP_SELL &&   // это открытая позиция? OP_BUY или OP_SELL 
         OrderSymbol()==Symbol())  // инструмент совпадает?
        {
         if(OrderType()==OP_BUY)   // открыта длинная позиция
           {
            // проверим, может уже пора закрываться?
            if(MacdCurrent>0 && MacdCurrent<SignalCurrent && MacdPrevious>SignalPrevious &&
               MacdCurrent>(MACDCloseLevel*Point))
                {
                 OrderClose(OrderTicket(),OrderLots(),Bid,3,Violet); // закрываем позицию
                 return(0); // выходим
                }
            // проверим - может можно/нужно уже трейлинг стоп ставить?
            if(TrailingStop>0)  
              {                 
               if(Bid-OrderOpenPrice()>Point*TrailingStop)
                 {
                  if(OrderStopLoss()<Bid-Point*TrailingStop)
                    {
                     OrderModify(OrderTicket(),OrderOpenPrice(),Bid-Point*TrailingStop,
                                 OrderTakeProfit(),0,Green);
                     return(0);
                    }
                 }
              }
           }
         else // иначе это короткая позиция
           {
            // проверим, может уже пора закрываться?
            if(MacdCurrent<0 && MacdCurrent>SignalCurrent &&
               MacdPrevious<SignalPrevious && MathAbs(MacdCurrent)>(MACDCloseLevel*Point))
              {
               OrderClose(OrderTicket(),OrderLots(),Ask,3,Violet); // закрываем позицию
               return(0); // выходим
              }
            // проверим - может можно/нужно уже трейлинг стоп ставить?
            if(TrailingStop>0)  
              {                 
               if((OrderOpenPrice()-Ask)>(Point*TrailingStop))
                 {
                  if((OrderStopLoss()>(Ask+Point*TrailingStop)) || (OrderStopLoss()==0))
                    {
                     OrderModify(OrderTicket(),OrderOpenPrice(),Ask+Point*TrailingStop,
                                 OrderTakeProfit(),0,Red);
                     return(0);
                    }
                 }
              }
           }
        }
     }
   return(0);
  }
// конец.
 

Hi all !

I have just noticed that NormalizeDouble works strangely.

That is, the Expert Advisor works well and has no errors, but the logs in the Strategy Tester are very strange.

I will explain.

I calculate the profit using this function. I do what I think NormalizeDouble(Profit,Digits) should do;

Then I Print(" profit=",DoubleToStrMorePrecision(Profit,8));

As a result, the log shows the following message: "profit=0.88881912". It seems to be 0.88881000, right?

Or maybe I am stupid and do something wrong ?

 
goodearth:

Hi all !

I have just noticed that NormalizeDouble works strangely.

That is, the Expert Advisor works well and has no errors, but the logs in the Strategy Tester are very strange.

I will explain.

I calculate the profit using this function. I do what I think NormalizeDouble(Profit,Digits) should do;

Then I Print(" profit=",DoubleToStrMorePrecision(Profit,8));

As a result, the log shows the following message: "profit=0.88881912". It seems to be 0.88881000, right?

Or maybe I am stupid and do something wrong ?

Do you have a Profit value in trade orders?
 
artmedia70:
Does your Profit value participate in trade orders?

Yes, of course. And no mistakes :-). That's why I was surprised.

I have Build 735.

Trading is on the demo.

Aaaaaaaaah I got it ! I forgot the assignment operation:-). "Profit=NormalizeDouble(Profit,Digits)".

But I still do not understand why the EA does not show errors ))

Maybe the server automatically rounds.....

I thought NormalizeDouble is a procedure, not a function :-).

 
Ozero:

Put ";" behind a parenthesis.

The programme works, BUT it occasionally fails with error 4108.


Ozero.

In fact, it needs to be deleted!

 
borilunad:

In fact, it should be deleted!

Boris, you'd better show him the code directly, because I was too sleepy to remember... ;)

ResetLastError();
if(!OrderClose(OrderTicket(),OrderLots(),_Bid,15)) Print("Чё-та не закрылася позиция. Фигня вот такая происходит: "+GetLastError());
 
artmedia70:

Boris, you'd better show him the code directly, because I was too sleepy to remember... ;)

Didn't mean to abuse your copyright! ;)

And seriously, something didn't stick! But I'll try it now!

ResetLastError();
if(!OrderClose(OrderTicket(),OrderLots(),_Bid,15)) Print("");

And now it's working! That's weird!

 
Hello

Please give me a solution.

There is an EA which compiles without errors with the 500th build of the editor.

But in new version it generates errors. I see these errors:

bool TP?=true;   // ошибка  '?' - semicolon expected    
And this one twice.

if(TP?)    // ')' - unexpected token    
           // ')' - ':' colon sign expected     
I looked through the manual for the new version and the old one, but I didn't find anything about the question mark.

Question: what do these operations mean and how to correct them to make the code compile normally?

Thanks in advance.


 

Hello! Could you please tell me why I sometimes have an ifle operator that doesn't work.
Here's an example:

double H3=ObjectGet ("H3 line", OBJPROP_PRICE1);
int start()
{
double price = Bid;
if (price==H3)
{
 Alert ("Урааааа  ", Symbol());
}
return(0);
}

Where:
H3 is the price value of the level
price is the current price

The result is that the price reaches this level (sometimes even stops at it), but Alert does not trigger.
Can you tell me what the error is?

 
Kapizdo4ka:

Hello! Could you please tell me why I sometimes have an ifle operator that doesn't work.
Here's an example:

Where:
H3 is the price value of the level
price is the current price

The result is that the price reaches this level (sometimes even stops at it), but Alert does not trigger.
Can you tell me what the error is?

The error is that the price rarely coincides exactly with the value of the level. Either price >= H3 or define an error range.