[WARNING CLOSED!] Any newbie question, so as not to clutter up the forum. Professionals, don't go by. Can't go anywhere without you. - page 1126

 
drknn:


The code is wrong. First, if the start() function is of int type, it should return an integer value. You have a return returned only by condition. And if the condition is not fulfilled, what should the start() function return to the terminal?

Further, you are too complicated to check - better to do as follows: we create a counter of orders, open and closed today. If the number of orders closed today is greater than zero, then you do not trade. Otherwise, we are allowed to trade.

changed int to void... did not help

To be honest, I don't really understand how to make a counter of orders and still be able to enable/disable the one-time daily trade option....

....think-think-think I'll try it like this

if(CalculateCurrentOrders(Symbol())==0 && Orders==0)

{

CheckForOpen();

if(WaitForNewDay) {Orders++;}

return;

}

Reset counter:

if(WaitForNewDay)CheckForNewDay();

void CheckForNewDay()

{

tm=iTime(Symbol(),PERIOD_D1,0);

if (bt!=tm) {bt=tm; Orders=0;}

}

Anyway, got back to what I was running away from ))))

 
dzhini:

changed int to void... did not help

Honestly, I don't understand how to make an order counter and still be able to enable/disable the one-off day trading option....

-------------

Anyway, back to what I was running away from ))))

//+------------------------------------------------------------------+
//|                                                            0.mq4 |
//|                                          Copyright © 2010, Drknn |
//|                                                    drknn@mail.ru |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2010, Drknn"
#property link      "drknn@mail.ru"

// ---------- Пользовательские переменные ----------------------------
extern int      MAGIC=0;//У ордеров открытых вручную MAGIC=0

// ------------ Вспомогательные переменные --------------------------
string    ExpertName="0";// имя советника
string    SMB;
bool      DobroTorga;

//+------------------------------------------------------------------+
//|                  Блок инициализации                              |
//+------------------------------------------------------------------+
int init(){

  SMB=Symbol();
  return(0);
}
//+------------------------------------------------------------------+
//|                  Блок деинициализации                            |
//+------------------------------------------------------------------+
int deinit(){
        if (!IsTesting()){
    Comment("");
    Print("Советник деинициализирован (выключен совсем)");
  }
  return(0);
}
//+------------------------------------------------------------------+
//|                  Старт работы советника                          |
//+------------------------------------------------------------------+
int start(){
  if(!IsTradeAllowed()){
    Comment("Торговля запрещена в настройках терминала, либо торговый поток занят");
    Print("Торговля запрещена в настройках терминала, либо торговый поток занят");
    return(0);
  }
  DobroTorga=true;
  if(SchBuy(MAGIC)+SchSell(MAGIC)+HistSchBuy(MAGIC)+HistSchSell(MAGIC)>0){
    DobroTorga=false;
  }
  if(DobroTorga==true){
    // ---- добро торговать есть - ставим ордера ---------
  }
  return(0);
}
//+------------------------------------------------------------------+
//|                  Пользовательские подпрограммы                   |
//+------------------------------------------------------------------+


// =================================================================================================
// ************************* Счётчики ордеров ******************************************************
// =================================================================================================

//=========== SchBuy()  ===============================
//  Функция возвращает количество Buy-ордеров
//   SchBuy      - счётчик Buy ордеров
//-----------------------------------------------------------
int SchBuy(int MAGIC){
  int SchBuy=0;
  for (int i=OrdersTotal()-1;i>=0;i--) {
    if (!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)){
       Print("ОШибка № ",GetLastError()," при выборе ордера № ",i);
    }
    else {
      if(OrderSymbol()!= SMB || OrderMagicNumber()!= MAGIC){ continue;}
      if(OrderType()==OP_BUY){ 
        SchBuy++;
      }  
    }
  }
  return(SchBuy);
}                  
//==================================================================================================


//=========== SchSell()  ===============================
//  Функция возвращает количество Sell-ордеров
//  SchSell  - счётчик Sell ордеров
//-----------------------------------------------------------
int SchSell(int MAGIC){
  int SchSell=0;
  for (int i=OrdersTotal()-1;i>=0;i--){
    if (!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)){
       Print("ОШибка № ",GetLastError()," при выборе ордера № ",i);
    }
    else {
      if(OrderSymbol()!=SMB || OrderMagicNumber()!=MAGIC){ continue;} 
      if(OrderType()==OP_SELL){
        SchSell++;
      }
    }
  }
 return(SchSell);     
}                  
//==================================================================================================

//=========== HistSchBuy()  ===============================
//  Функция возвращает количество Buy-ордеров сегодняшнего дня в истории
//   SchBuy      - счётчик Buy ордеров
//-----------------------------------------------------------
int HistSchBuy(int MAGIC){
  int SchBuy=0;
  for (int i=OrdersHistoryTotal()-1;i>=0;i--) {
    if (!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)){
       Print("ОШибка № ",GetLastError()," при выборе ордера № ",i);
    }
    else {
      if(OrderSymbol()!= SMB || OrderMagicNumber()!= MAGIC){ continue;}
      if(OrderType()==OP_BUY){ 
        if(OrderOpenTime()>=iTime(SMB,PERIOD_D1,0)){
          SchBuy++;
        }
      }  
    }
  }
  return(SchBuy);
}                  
//==================================================================================================


//=========== HistSchSell()  ===============================
//  Функция возвращает количество Sell-ордеров сегодняшнего дня в истории
//  SchSell  - счётчик Sell ордеров
//-----------------------------------------------------------
int HistSchSell(int MAGIC){
  int SchSell=0;
  for (int i=OrdersHistoryTotal()-1;i>=0;i--){
    if (!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)){
       Print("ОШибка № ",GetLastError()," при выборе ордера № ",i);
    }
    else {
      if(OrderSymbol()!=SMB || OrderMagicNumber()!=MAGIC){ continue;} 
      if(OrderType()==OP_SELL){
        if(OrderOpenTime()>=iTime(SMB,PERIOD_D1,0)){
          SchSell++;
        }
      }
    }
  }
 return(SchSell);     
}                  
//==================================================================================================
 
Please help me with the code. I manually draw and move a horizontal line and when the price touches it, it should trigger a signal.
 
Alexandr24:
Please help me with the code. I manually draw and move a horizontal line and when the price touches it, it triggers a signal.

The price touches the line - there is a signal. I understand it. What is wrong with the code?
 
drknn:


You're in charge today))) thank you. I'll look into it
 
Sorry, I didn't set the task correctly)) I need a code that would do this.
 
Alexandr24:
Sorry, I have set the task incorrectly)). What you need is a code that would do this.


The first thing you need to understand is that a line is an object. The programming code distinguishes objects by their names. You need to write the name of the line in the code, and then when you drop the line onto a chart, you need to go into its properties and change the name to the one you wrote in the code. Only then will the code understand that you need to process the readings taken from this object.

Next in the code you need to query the price where the line stands. The request is made via double ObjectGet(string name, int prop_id) function. Instead of name you need to specify the name of your line, and instead of prop_id specify OBJPROP_PRICE1. This way you can programmatically get the price at which this line is set. Then in the code, you need to check if the price touches this line. For example: If the price on the previous tick is below the level where the line is set and it is more or equal to this level on the current tick, then this touch has occurred.

Alexander, if you can't manage to do something with the code, they can help you. If you need the code to be implemented for you, please go to https://www.mql5.com/ru/job.

 
int start()
  {
   int   i, counted_bars=IndicatorCounted();
//----

 double n=ObjectGet("n",OBJPROP_PRICE1); 
 if (Close[0]==n&&Close[0]!= 0)
 Alert(Symbol(),"  n  ",n);

//----
Comment(n);
   return(0);
  }
I did this, but the signal does not work when Close[0]==n. How to fix it? The conditions are fulfilled, but for some reason it does not work.
 
Alexandr24:
I have done it but the signal does not work when Close[0]==n. How to fix it?


Well, judging by the code, you have made an indicator. So, to check if this part of the code works, you will have to sit and wait for the next tick to touch the line. It is better to create a script to test this part of the code, as it will give you instant results.

The first thing you need to make sure of is that the code actually sees your line. How do you do that? You need to ask for its price and display it as an alert. Doing it.

//+------------------------------------------------------------------+
//| script program start function                                    |
//+------------------------------------------------------------------+
int start(){
  string LineName="1";
  double MyLine=-100;
  MyLine=ObjectGet(LineName,OBJPROP_PRICE1);
  if(MyLine>0){
    Alert ("Горизонтальная линия ",LineName," установлена на уровень = ",MyLine);
  }
  else{
    Alert("Запрос значения линии ",LineName," вренул ошибку № ",GetLastError());
  }
  return(0);
}
//+------------------------------------------------------------------+

Now that the script has been recompiled, we open any chart and draw a horizontal line on it. Then we enter its properties and, since we gave "1" name to the line in the code, we set this name in the line properties as well:

Click OK. We drop the script on the chart and make sure that the alert has returned the correct price. We move the line in the chart to another place and again throw the script back to the chart and make sure that if we change the position of the line manually, the code still sees and recognizes it.

Then we continue in the same vein.

 

The indicator is tested through the tester with the visualisation switched on. I corrected the code a bit, because for alert to be triggered the values should be normalized. But if you move the line on the current bar, say an hour, then the alert will be triggered only 1 time with subsequent movement of the line on the current bar alert for some reason it does not work. I have to wait for another bar.

int start()
  {
   int   i, counted_bars=IndicatorCounted();
//----
double b=NormalizeDouble((Close[0]),Digits);
 double n=NormalizeDouble(ObjectGet("n",OBJPROP_PRICE1),Digits); 
 if (b==n&&b!= 0)
 Alert(Symbol(),"  n  ",n);

//----
Comment(n);
   return(0);
  }