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

 

Hello! Would one of the esteemed gurus like to check the start of my first EA? Is it possible to move on? Maybe i missed something? I would be very grateful for any specifics. I've seen somewhere on the forum how to make only one position open, but I didn't copy it and now I can't find it. Help, please.

Thank you!

// Trial version of Expert Advisor

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

//------Вводные данные:-----------------------------------------------------------

input double Lots = 0.1; //Lot

input int MovingPeriod =5; // МА calculation period

input int MovingShift =0; // MA shift

input int InpBandsPeriod=10; // Bollinger Bands period

input int InpBandsShift=0; // Bollinger Bands shift

input double InpBandsDeviations=2.0; // Bollinger Bands deviation

input int K_Period=30; // %K period of the Stochastic

input int D_Period=10; // %D Stochastic period

input int Slowdawn =8; // Stochastic Slowdown

input color clMainStoch =Yellow; // colour of the main Stochastic line

input color clSignalStoch =Red; // colour of the Stochastic signal line

// -----Declare Global Variables:------------------------------------------

double MA_0, MA_1, MA_2; // MA value on 0, 1 and 2 bars

double MB_0, MB_1, MB_2; // Value of Average Bollinger on 0, 1 and 2 bars

double ExtUpperBuffer[]; // value of upper Bollinger line

double ExtLowerBuffer[]; // Value of lower Bollinger line

double Delta_0, Delta_1; // difference between values of upper and lower Bollinger ...

// ...Bollinger lines on 0 and 1 bars

double Yellow_0, Yellow_1, Yellow_2; // MAIN value on 0, 1 and 2 bars

double Red_0, Red_1, Red_2; // value SIGNAL on 0, 1 and 2 bars

//-------Поехали!----------------------------------------------------------------

int start() //Special function start

{

//function call of the MA indicator

MA_0=iMA(NULL,0,MovingPeriod,MovingShift,MODE_SMA,PRICE_CLOSE,0);

MA_1=iMA(NULL,0,MovingPeriod,MovingShift,MODE_SMA,PRICE_CLOSE,1);

MA_2=iMA(NULL,0,MovingPeriod,MovingShift,MODE_SMA,PRICE_CLOSE,2);

//feedback to Bollinger Bands function

MB_0=iBands(NULL,0,InpBandsPeriod,InpBandsShift,InpBandsDeviations,PRICE_CLOSE,0);

MB_1=iBands(NULL,0,InpBandsPeriod,InpBandsShift,InpBandsDeviations,PRICE_CLOSE,1);

MB_2=iBands(NULL,0,InpBandsPeriod,InpBandsShift,InpBandsDeviations,PRICE_CLOSE,2);

Delta_0=iBands(ExtUpperBuffer[0]-ExtLowerBuffer[0]);

Delta_1=iBands(ExtUpperBuffer[1]-ExtLowerBuffer[1]);

//Stochastic function call

Yellow_0=iStochastic(NULL,0,K_Period,D_Period,Slowdawn,MODE_SMA,0,MODE_MAIN,0);

Yellow_1=iStochastic(NULL,0,K_Period,D_Period,Slowdawn,MODE_SMA,0,MODE_MAIN,1);

Yellow_2=iStochastic(NULL,0,K_Period,D_Period,Slowdawn,MODE_SMA,0,MODE_MAIN,2);

Red_0=iStochastic(NULL,0,K_Period,D_Period,Slowdawn,MODE_SMA,0,MODE_SIGNAL,0);

Red_1=iStochastic(NULL,0,K_Period,D_Period,Slowdawn,MODE_SMA,0,MODE_SIGNAL,1);

Red_2=iStochastic(NULL,0,K_Period,D_Period,Slowdawn,MODE_SMA,0,MODE_SIGNAL,2);

//-------Ситуации по Стохастику:-----------------------------------------------------

//The market is overbought

double MOB()=(Yellow_0>=80 && Red_0>=80); //Local variable

//The market is oversold.

double MOS()=(Yellow_0<=20 && Red_0<=20); //Local variable

//The market is normal.

double MN()=(20<Yellow_0<80 && 20<Red_0<80); //Local variable

//critical situation

double MC1()=(20<Yellow_0<80 && Red_0<=20); //Local variable

double MC2()=(20<Yellow_0<80 && Red_0>=80); //Local variable

double MC3()=(20<Red_0<80 && Yellow_0<=20); //Local variable

double MC4()=(20<Red_0<80 && Yellow_0>=80); //Local variable

//-------Example(my)order to open position-----------------------------------------------------


if (Delta_0 > Delta_1 && MOB()==true) //The market is overbought but delta is expanding

{ if (MB_2 > MB_1 && MB_1 < MB_0) //Lower Bollinger Break

OrderSend(Symbol(),OP_BUY,Lots,Ask,0,Bid-1500*Point,Bid+1500*Point);//open Buy order

Alert("GetLastError()); //Message of an error

Alert("Open position BAY with lots("Lots"),price("Ask")."); //Buy message

 

Additionally, BAY (as well as Sell) positions can be opened under different conditions, and depending on the conditions under which the position was opened (e.g. BAY), there will be different closing conditions. (e.g. BAY), there will be different closing conditions.

How do I translate this in MKL?

 
rapid_minus:

Additionally, BAY (as well as Sell) positions can be opened under different conditions, and depending on the conditions under which the position was opened (e.g. BAY), there will be different closing conditions. (e.g. BAY), there will be different closing conditions.

How do I translate this in MKL?

We select the order in the loop. If it is a Buy, and other data (symbol, magik, etc.) meet the criterion of that it should be closed at "custom closing conditions", then we will close it if "custom closing conditions" exist.
 
artmedia70:
We select the order in the loop. If it is a Buy and all other data (symbol, magician, whatever) meets the criterion of having to close it at "proper closing conditions", then we close it if there are "proper closing conditions".

It's a bit vague to me, but after a bit of digging I think I'll understand. Thank you very much for not turning away or lecturing from the peaks of knowledge, like some comrades from the Soviet country.

I figured out how to close it this way:

//-------Example(mine) of an order to open a position with a binding close (by ticket)-----------------------------------------------------

//Local variable that opens a BAY order (instead of line 63)

int Ticket_1() = (OrderSend(Symbol(),OP_BUY,Lots,Ask,0,Bid-1500*Point,Bid+1500*Point))

//-------Then the closure for this particular order could be as follows:-----------------------------------------------------

if (Ticket_1()==true) //if order #1 was opened, then...

{ if (Yellow_0>Red_0 && (Yellow_0-Red_0)<(Yellow_1-Red_1)) //Yellow is higher than red, contraction(condition)

{ if (MA_2 < MA_1 && MA_1 > MA_0);} //Red above the middle one(condition)

else (Yellow_0>Red_0 && (Yellow_0-Red_0)>(Yellow_1-Red_1)) //Yellow above red, expansion(condition)

{ if (MB_2 < MB_1 && MB_1 > MB_0);} //Upper Bollinger break (condition)

bool Ans=OrderClose(Ticket,Lot,Bid,0); //...close order (lockvariable)

Alert("Attempting to close the order with Bid("Lots"),price("Ask"). Waiting for reply...");

if (Ans==true) // It worked :)

{

Alert ("Close BAY order by lot("Lots"),Closing price("Bid");

break; // Exit from the position closing loop

}


}

Please give an analysis, well on the previous post too. Sorry for being stubborn, but you see - you're the only one who replies... Thank you!

 
//-------Пример(мой) приказа на открытие позиции с привязкой закрытия (по тикету)----------------------------------------------------- 
                                                      
                                                      //Локальная переменная, открывающая ордер БАЙ(вместо строки 63)
   int Ticket_1() = (OrderSend(Symbol(),OP_BUY,Lots,Ask,0,Bid-1500*Point,Bid+1500*Point));
   
        //-------Тогда закрытие именно для этого приказа может быть таким:-----------------------------------------------------
    
    if (Ticket_1()==true)                              //Если был открыт ордер №1, то...
     { if (Yellow_0>Red_0 && (Yellow_0-Red_0)<(Yellow_1-Red_1)) //Желтая выше красной, сужение(условие)
        { if (MA_2 < MA_1 && MA_1 > MA_0);}                      //Верхний перелом Средней (условие)
       else (Yellow_0>Red_0 && (Yellow_0-Red_0)>(Yellow_1-Red_1)) //Желтая выше красной, расширение(альтерн.условие)
         { if (MB_2 < MB_1 && MB_1 > MB_0);}                      //Верхний перелом Боллинджера (условие)
       
       bool Ans=OrderClose(Ticket,Lot,Bid,0);          //...закрытие ордера (лок.переменная)                                               
   Alert("Попытка закрыть ордер БАЙ лотом("Lots"),цена("Ask"). Ожидание ответа..");
   if (Ans==true)                                     // Получилось :)
        {
         Alert ("Закрыт ордер БАЙ лотом("Lots"),цена закрытия("Bid");
         break;                                       // Выход из цикла закрытия позиции
        }

     }
It's so much easier to read. Sorry.
 
rapid_minus:

It's a bit vague to me, but after some digging I think I'll understand. Thank you very much for not turning away or lecturing from the peaks of knowledge, as some comrades from the Soviet Union did.

I thought of closing it this way:

...

Please give an analysis, and on the previous post too. Sorry for insistence, but you see, you're the only one who answers... Thank you!

Well, it's a bit hazy, isn't it?

1. you have to determine the fact of occurrence of the condition to close the order

2. In the cycle, you review all the open positions and, when you find the required Buy order, you close it.

This is an example of a cycle:

void ClosePositions(string symbol, int type, int magic) {
   for(int i=OrdersTotal()-1; i>=0; i--) {      // цикл по открытым ордерам
      if(OrderSelect(i,SELECT_BY_POS)) {        // выбираем ордер по индексу
         if(OrderMagicNumber()!=magic) continue;// если магик не искомый - ищем дальше
         if(OrderSymbol()!=symbol)     continue;// если символ не тот - ищем дальше
         if(OrderType()!=type)         continue;// если тип ордера не тот - ищем дальше
         // здесь, если ордер выбран, то он соответствует нужным критериям,
         // вызов функции закрытия выбранного ордера по тикету
         }
      }   
   }

I.e., to close the Buy order at the current symbol (on the chart where the Expert Advisor is running) and with a magic number of 100500 (for example), you should call the function like this

ClosePositions(Symbol(),OP_BUY,100500);

You don't have to write the number 100500, usually the magic number is already set in the EA to a variable, for example int Magic = 100500; Then you need to write Magic instead of 100500

I did not write anything in the loop where the selected position should be closed, as it should call the function to close the order according to the ticket. This is usually a call of a full function with return codes of the trade server handled. You can write there a simple command to close the selected order OrderClose() to check;

 
rapid_minus:
It's much easier to read that way. Sorry.

It's also possible to edit an old post, so as not to create duplicates ;)

 
evillive:
It's still possible to edit an old post to avoid duplicates ;)
Tried to, but the SRC doesn't put it in anymore.
 
artmedia70:

It's a bit foggy.

1) Determine the fact that the condition to close the Buy order has occurred

2. In the loop, you review all the open positions and, when you find the required Buy order, you close it.

This is an example of a cycle:

I.e., to close the Buy order on the current symbol (on the chart where the Expert Advisor is running) and with a magic number of 100500 (for example), you should call the function like this

You don't have to write the number 100500, usually the magic number is already set in the EA to a variable, for example int Magic = 100500; Then you need to write Magic instead of 100500

I did not write anything in the loop where the selected position should be closed, as it should call the function to close the order according to the ticket. This is usually a call of a full function with return codes of the trade server handled. You can write there a simple command to close the selected order OrderClose() to check;


Thank you. But as far as I understood the magik is assigned automatically when opening an order. That is why I cannot determine on which conditions the order is opened and therefore I do not know the conditions to close it.
 
rapid_minus:
Thank you. But as I understand it, the magik is assigned automatically when the order is opened. That is why I cannot determine the conditions under which the order was opened, and therefore I do not know the conditions under which it should be closed.
There can be as many magicians as you like and each condition has its own magician.