# Задать время работы советника

Раздел: Язык программирования MQL4
Автор темы: Mansory
Создана: 2010-03-26 02:39
Ответов: 76 | Просмотров: 29414
Страница 2 из 4
Источник: https://forexsystemru.com/threads/27577/page-2

---

## ддеенниисс — 2016-09-22 20:31

У меня всё работает и на демо и в тестере,скорее всего старый сов нужно удалить вообще с компа иначе если названия одинаковые то он не меняется по факту.И название не менять какое я написал пусть такое и будет есть проверка по имени,но вообще сов проблемный в нём понатыкано всяких проверок по интернету,названию брокера,глобальной переменной и ошибок серьёзных в жёстком режиме полно.
Этот у меня работает отлично первую сделку открывает в зависимости прошлых свечей ка в нём и записано.

## politehnik — 2016-09-22 20:48

> Цитата (ддеенниисс):
> У меня всё работает и на демо и в тестере,скорее всего старый сов нужно удалить вообще с компа иначе если названия одинаковые то он не меняется по факту.И название не менять какое я написал пусть такое и будет есть проверка по имени,но вообще сов проблемный в нём понатыкано всяких проверок по интернету,названию брокера,глобальной переменной и ошибок серьёзных в жёстком режиме полно.
> Этот у меня работает отлично первую сделку открывает в зависимости прошлых свечей ка в нём и записано.

Спасибо, буду пробовать.

## warwick — 2016-11-18 12:23

Поставьте пожалуйста  время начала работы в этот сов :embrace:

## warwick — 2016-11-18 17:04

> Цитата (warwick):
> Поставьте пожалуйста  время начала работы в этот сов :embrace:

В общем я сам нагуглил код, вставил, все работает. Но есть проблема. Время работы совы внутри дня. Мне надо сделать так, чтобы начал работу в определенное время и больше не останавливался.

## FeNikS60 — 2016-11-18 22:07

**время старта**

Один из вариантов:
Выставление времени при запуске:
extern string StartTime ="yyyy.mm.dd hh:mi"; 
При достижении времени разрешение работать дальше.
if(TimeToString(TimeCurrent(),TIME_DATE|TIME_MINUTES)<StartTime) return();

## warwick — 2016-11-19 17:29

> Цитата (FeNikS60):
> Один из вариантов:
> Выставление времени при запуске:
> extern string StartTime ="yyyy.mm.dd hh:mi";
> При достижении времени разрешение работать дальше.
> if(TimeToString(TimeCurrent(),TIME_DATE|TIME_MINUTES)<StartTime) return();

Можно указать где должен стоять этот кусок кода, а то я не соображаю в программировании 

input Trade  TypeOrders  = Only_SELL;
input double Lot         = 0.00;  // Lot
input double Risk        = 1.01;  // Risk percent if Lot=0;
input int    MinStep     = 400;   // Step order
input int    MinStepPlus = 0;     // Add minimal step
input double MinProfit   = 10.00; // Minimal Profit Close
input int    Magic       = 227;
input int    Slippage    = 30;

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()

  {
   return(INIT_SUCCEEDED);
  }
  
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
  
   int b=0,s=0;
   double
   BuyProfit  = 0,
   SellProfit = 0,
   BuyMin     = 0,
   SellMax    = 0,
   BuyMinLot  = 0,
   SellMaxLot = 0,
   BuyLot     = 0,
   SellLot    = 0,
   BuyMax     = 0,
   SellMin    = 0,
   SellTicProfit = 0,
   BuyTicProfit  = 0;
   int
   BuyMaxTic  = 0,
   SellMinTic = 0; 
   for(int i=OrdersTotal()-1; i>=0; i--)
      if(OrderSelect(i,SELECT_BY_POS))
         if(OrderSymbol()==Symbol())
            if(OrderMagicNumber()==Magic)
              {
               if(OrderType()==OP_BUY)
                 {
                  b++;
                  if(OrderOpenPrice()<BuyMin || BuyMin==0)
                    {
                     BuyMin=OrderOpenPrice();
                     BuyMinLot=OrderLots();
                    }
                  if(OrderOpenPrice()>BuyMax || BuyMin==0)
                    {
                     BuyMax=OrderOpenPrice();
                     BuyMaxTic=OrderTicket();
                     BuyTicProfit=OrderProfit();
                    }
                  if(OrderProfit()>0)BuyProfit+=OrderProfit()+OrderCommission()+OrderSwap();
                 }
               if(OrderType()==OP_SELL)
                 {
                  s++;
                  if(OrderOpenPrice()>SellMax || SellMax==0)
                    {
                     SellMax=OrderOpenPrice();
                     SellMaxLot=OrderLots();
                    }
                  if(OrderOpenPrice()<SellMin || SellMin==0)
                    {
                     SellMin=OrderOpenPrice();
                     SellMinTic=OrderTicket();
                     SellTicProfit=OrderProfit();
                    }
                  if(OrderProfit()>0)SellProfit+=OrderProfit()+OrderCommission()+OrderSwap();
                 }
              
              
              
// Summ profit final
   double ProfitBuy=BuyTicProfit+BuyProfit;
   double ProfitSel=SellTicProfit+SellProfit;

   double  lot=NormalizeDouble(AccountBalance()*Risk/100/MarketInfo(Symbol(),MODE_MARGINREQUIRED),2);

   if(b==0)
      BuyLot=(Lot>0)?Lot:lot;
   else
      BuyLot=BuyMinLot+Lot;
   if(s==0)
      SellLot=(Lot>0)?Lot:lot;
   else
      SellLot=SellMaxLot+Lot;

   double BuyDist  = NormalizeDouble(MinStep*Point()+MinStepPlus*Point()*b,Digits());
   double SellDist = NormalizeDouble(MinStep*Point()+MinStepPlus*Point()*s,Digits());

   if(TypeOrders==Only_BUY || TypeOrders==Only_All)
      if((b==0) || (b>0 && (BuyMin-Ask)>=BuyDist))
         if(OrderSend(Symbol(),OP_BUY,NormalizeDouble(BuyLot,2),NormalizeDouble(Ask,Digits()),Slippage,0,0,"My order",Magic,0,clrGreen)<0)
            Print(" Error open Buy N ",GetLastError());

   if(TypeOrders==Only_SELL || TypeOrders==Only_All)
      if((s==0) || (s>0 && (Bid-SellMax)>=SellDist))
         if(OrderSend(Symbol(),OP_SELL,NormalizeDouble(SellLot,2),NormalizeDouble(Bid,Digits()),Slippage,0,0,"My order",Magic,0,clrGreen)<0)
            Print(" Error open Sell N ",GetLastError());

   if(ProfitBuy>=MinProfit && b>=2)
      CloseAll(OP_BUY,BuyMaxTic);

   if(ProfitSel>=MinProfit && s>=2)
      CloseAll(OP_SELL,SellMinTic);
  }
  }

## FeNikS60 — 2016-11-19 19:46

**Установка запуска по времени**

Пожалуйста первую строчку можно немного изменить:
input string StartTime ="yyyy.mm.dd hh:mi";
и вставить в любом месте среди вводимых input-- параметров.
вторую строчку расположить сразу за void OnTick()
{
получится:

void OnTick()
{
if(TimeToString(TimeCurrent(),TIME_DATE|TIME_MINUT ES)<StartTime) return();//нельзя
int b=0,s=0;
double
int b=0,s=0;
double.......

## warwick — 2016-11-19 20:38

> Цитата (FeNikS60):
> Пожалуйста первую строчку можно немного изменить:
> input string StartTime ="yyyy.mm.dd hh:mi";
> и вставить в любом месте среди вводимых input-- параметров.
> вторую строчку расположить сразу за void OnTick()
> {
> получится:
>
> void OnTick()
> {
> if(TimeToString(TimeCurrent(),TIME_DATE|TIME_MINUT ES)<StartTime) return();//нельзя
> int b=0,s=0;
> double
> int b=0,s=0;
> double.......

Вылезает 2 ошибки ')' - unexpected end of program    ')' - unexpected end of program

## FeNikS60 — 2016-11-19 20:53

**ошибка**

Прошу извинить, в строчке при копировании из справочника появились  неправильные буквы. должно быть:
if(TimeToString(TimeCurrent(),TIME_DATE|TIME_MINUTES)<StartTime) return();//нельзя
Обращаю внимание на правильность набора в строчке времени:
точки, двоеточие, пробелы должны быть как в первой строке

## FeNikS60 — 2016-11-19 20:55

почему то на сайте опять произошел разрыв. MINUTES пишется слитно

## warwick — 2016-11-19 21:20

Всё так же указывает на ошибки с кавычками вот тут

#property link      "http://www.forexfactory.com/" 
#property version   "1.00"
#property description "Programmer Voldemar227"
#property strict
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
enum Trade
  {
   Only_BUY,   // Only BUY
   Only_SELL,  // Only SELL
   Only_All    // BUY and SELL
  };
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
enum ma
  {
   BUY_MA  = 0,
   SELL_MA = 1,
   OFF     = 2
  };
input Trade  TypeOrders  = Only_SELL;
input double Lot         = 0.00;  // Lot
input double Risk        = 1.01;  // Risk percent if Lot=0;
input int    MinStep     = 400;   // Step order
input int    MinStepPlus = 0;     // Add minimal step
input double MinProfit   = 10.00; // Minimal Profit Close
input int    Magic       = 227;
input int    Slippage    = 30;
input string StartTime ="2016.10.06 10:00";

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()

  {
   return(INIT_SUCCEEDED);
  }
  
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {  Ошибка '{' - unbalanced parentheses   
if(TimeToString(TimeCurrent(),TIME_DATE|TIME_MINUTES)<StartTime) return();//нельзя
   int b=0,s=0;
   double
   BuyProfit  = 0,
   SellProfit = 0,
   BuyMin     = 0,
   SellMax    = 0,
   BuyMinLot  = 0,
   SellMaxLot = 0,
   BuyLot     = 0,
   SellLot    = 0,
   BuyMax     = 0,
   SellMin    = 0,
   SellTicProfit = 0,
   BuyTicProfit  = 0;
   int
   BuyMaxTic  = 0,
   SellMinTic = 0; 
   for(int i=OrdersTotal()-1; i>=0; i--)
      if(OrderSelect(i,SELECT_BY_POS))
         if(OrderSymbol()==Symbol())
            if(OrderMagicNumber()==Magic)
              {
               if(OrderType()==OP_BUY)
                 {
                  b++;
                  if(OrderOpenPrice()<BuyMin || BuyMin==0)
                    {
                     BuyMin=OrderOpenPrice();
                     BuyMinLot=OrderLots();
                    }
                  if(OrderOpenPrice()>BuyMax || BuyMin==0)
                    {
                     BuyMax=OrderOpenPrice();
                     BuyMaxTic=OrderTicket();
                     BuyTicProfit=OrderProfit();
                    }
                  if(OrderProfit()>0)BuyProfit+=OrderProfit()+OrderCommission()+OrderSwap();
                 }
               if(OrderType()==OP_SELL)
                 {
                  s++;
                  if(OrderOpenPrice()>SellMax || SellMax==0)
                    {
                     SellMax=OrderOpenPrice();
                     SellMaxLot=OrderLots();
                    }
                  if(OrderOpenPrice()<SellMin || SellMin==0)
                    {
                     SellMin=OrderOpenPrice();
                     SellMinTic=OrderTicket();
                     SellTicProfit=OrderProfit();
                    }
                  if(OrderProfit()>0)SellProfit+=OrderProfit()+OrderCommission()+OrderSwap();
                 }
              
              
              
// Summ profit final
   double ProfitBuy=BuyTicProfit+BuyProfit;
   double ProfitSel=SellTicProfit+SellProfit;

   double  lot=NormalizeDouble(AccountBalance()*Risk/100/MarketInfo(Symbol(),MODE_MARGINREQUIRED),2);

   if(b==0)
      BuyLot=(Lot>0)?Lot:lot;
   else
      BuyLot=BuyMinLot+Lot;
   if(s==0)
      SellLot=(Lot>0)?Lot:lot;
   else
      SellLot=SellMaxLot+Lot;

   double BuyDist  = NormalizeDouble(MinStep*Point()+MinStepPlus*Point()*b,Digits());
   double SellDist = NormalizeDouble(MinStep*Point()+MinStepPlus*Point()*s,Digits());

   if(TypeOrders==Only_BUY || TypeOrders==Only_All)
      if((b==0) || (b>0 && (BuyMin-Ask)>=BuyDist))
         if(OrderSend(Symbol(),OP_BUY,NormalizeDouble(BuyLot,2),NormalizeDouble(Ask,Digits()),Slippage,0,0,"My order",Magic,0,clrGreen)<0)
            Print(" Error open Buy N ",GetLastError());

   if(TypeOrders==Only_SELL || TypeOrders==Only_All)
      if((s==0) || (s>0 && (Bid-SellMax)>=SellDist))
         if(OrderSend(Symbol(),OP_SELL,NormalizeDouble(SellLot,2),NormalizeDouble(Bid,Digits()),Slippage,0,0,"My order",Magic,0,clrGreen)<0)
            Print(" Error open Sell N ",GetLastError());

   if(ProfitBuy>=MinProfit && b>=2)
      CloseAll(OP_BUY,BuyMaxTic);

   if(ProfitSel>=MinProfit && s>=2)
      CloseAll(OP_SELL,SellMinTic);
  }
   
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {

  }
//+------------------------------------------------------------------+
void CloseAll(int aType,int ticket)
  {
   for(int i=OrdersTotal()-1; i>=0; i--)
      if(OrderSelect(i,SELECT_BY_POS))
         if(OrderSymbol()==Symbol())
            if(OrderMagicNumber()==Magic)
              {
               if(OrderType()==aType && OrderType()==OP_BUY)
                  if(OrderProfit()>0 || OrderTicket()==ticket)
                     if(!OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(Bid,Digits()),Slippage,clrRed))
                        Print(" OrderClose OP_BUY Error N",GetLastError());

               if(OrderType()==aType && OrderType()==OP_SELL)
                  if(OrderProfit()>0 || OrderTicket()==ticket)
                     if(!OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(Ask,Digits()),Slippage,clrRed))
                        Print(" OrderClose OP_SELL Error N",GetLastError());

              }
  }   Ошибка ')' - unbalanced parentheses   

  
//+------------------------------------------------------------------+

## FeNikS60 — 2016-11-19 23:46

Проверил:
Ошибка появилась из-за отсутствия в функции void OnTick() последней закрывающей кавычки
 CloseAll(OP_SELL,SellMinTic);
  }
} -добавить.
Еще функция void не требует информации при выходе, поэтому команда
return() без скобок: return;

## warwick — 2016-11-20 01:38

> Цитата (FeNikS60):
> Проверил:
> Ошибка появилась из-за отсутствия в функции void OnTick() последней закрывающей кавычки
>  CloseAll(OP_SELL,SellMinTic);
>   }
> } -добавить.
> Еще функция void не требует информации при выходе, поэтому команда
> return() без скобок: return;

Да, спасибо, помогло. Ошибок нету. Но теперь новая проблема возникла, советник вообще не открывает сделок. :(

## eevviill2 — 2016-11-20 02:14

> Цитата (Mansory):
> Подскажите, пожалуйста, что нужно добать в код советника что-бы можно было в настройках выставлять время работы. Спасибо

 extern string emp3 = "//////////////Work time settings////////////////////";
extern bool Use_work_time = false;
extern string start_time_1 = "08:00";
extern string stop_time_1 = "16:00";
extern string start_time_2 = "";
extern string stop_time_2 = "";
extern string start_time_3 = "";
extern string stop_time_3 = "";
............................................................................................
 void OnTick()
 {
...
//time filter
 if(Use_work_time && !work_time_f()) return;

 //open order
...
 }
...........................................................................................
 bool work_time_f() 
{
string time_current=TimeToString(TimeCurrent(),TIME_MINUTES);

  if(
      (start_time_1+stop_time_1=="" || ((start_time_1<stop_time_1 && (time_current<start_time_1 || time_current>=stop_time_1)) || (start_time_1>stop_time_1 && (time_current<start_time_1 && time_current>=stop_time_1)))) 
   && (start_time_2+stop_time_2=="" || ((start_time_2<stop_time_2 && (time_current<start_time_2 || time_current>=stop_time_2)) || (start_time_2>stop_time_2 && (time_current<start_time_2 && time_current>=stop_time_2))))  
   && (start_time_3+stop_time_3=="" || ((start_time_3<stop_time_3 && (time_current<start_time_3 || time_current>=stop_time_3)) || (start_time_3>stop_time_3 && (time_current<start_time_3 && time_current>=stop_time_3))))  
    )  return(false);

 
   return (true);
}

## eevviill2 — 2016-11-20 02:27

> Цитата (warwick):
> В общем я сам нагуглил код, вставил, все работает. Но есть проблема. Время работы совы внутри дня. Мне надо сделать так, чтобы начал работу в определенное время и больше не останавливался.

extern datetime start_time_forever = D'2017.01.01 00:00';
.........................................................................
void onTick()
{
...
if(TimeCurrent()<start_time_forever) return;

//order open
...
}

## warwick — 2016-11-20 11:20

> Цитата (eevviill2):
> extern datetime start_time_forever = D'2017.01.01 00:00';.........................................................................void onTick(){...if(TimeCurrent()<start_time_forever) return;//order open...}

Тоже самое, ошибок нет, но перестал вообще открывать.

## Omukchaan — 2016-11-20 11:54

Счас выложу код.

## Omukchaan — 2016-11-20 12:07

//+------------------------------------------------------------------+
//|                                                    code work.mq4 |
//|                                                            Saasa |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Saasa"
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict

extern int start_trade=0;//час начала работы
extern int end_trade=24;//час окончания работы (плюс к начальному)

int tc, st, et;
bool work=false;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
  //***********************
  if(tc>=et)
   { 
    int dow=0;
    if(start_trade+end_trade > 24) {dow=DayOfWeek();}
    int dt=iTime(NULL,PERIOD_D1,0);
    st=dt+start_trade*3600;
    et=dt+(start_trade+end_trade)*3600;
    if(dow==5) et+=172800;
   }
   
  if(tc>=st && tc<=et) work=true; 
  else work=false;
  //***********************
  
    if(work && ........ ) buy();

    if(work &&.........) sell();  
 
//+------------------------------------------------------------------+

## Omukchaan — 2016-11-20 12:08

этот код можно добавить в советник.

## warwick — 2016-11-20 13:13

> Цитата (Omukchaan):
> этот код можно добавить в советник.

Можно здесь указать в каком месте вставить код? Я вставил, но время в советнике не работает, сразу начинает открывать

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
   int b=0,s=0;
   double
   BuyProfit  = 0,
   SellProfit = 0,
   BuyMin     = 0,
   SellMax    = 0,
   BuyMinLot  = 0,
   SellMaxLot = 0,
   BuyLot     = 0,
   SellLot    = 0,
   BuyMax     = 0,
   SellMin    = 0,
   SellTicProfit = 0,
   BuyTicProfit  = 0;
   int
   BuyMaxTic  = 0,
   SellMinTic = 0;

   for(int i=OrdersTotal()-1; i>=0; i--)
      if(OrderSelect(i,SELECT_BY_POS))
         if(OrderSymbol()==Symbol())
            if(OrderMagicNumber()==Magic)
              {
               if(OrderType()==OP_BUY)
                 {
                  b++;
                  if(OrderOpenPrice()<BuyMin || BuyMin==0)
                    {
                     BuyMin=OrderOpenPrice();
                     BuyMinLot=OrderLots();
                    }
                  if(OrderOpenPrice()>BuyMax || BuyMin==0)
                    {
                     BuyMax=OrderOpenPrice();
                     BuyMaxTic=OrderTicket();
                     BuyTicProfit=OrderProfit();
                    }
                  if(OrderProfit()>0)BuyProfit+=OrderProfit()+OrderCommission()+OrderSwap();
                 }
               if(OrderType()==OP_SELL)
                 {
                  s++;
                  if(OrderOpenPrice()>SellMax || SellMax==0)
                    {
                     SellMax=OrderOpenPrice();
                     SellMaxLot=OrderLots();
                    }
                  if(OrderOpenPrice()<SellMin || SellMin==0)
                    {
                     SellMin=OrderOpenPrice();
                     SellMinTic=OrderTicket();
                     SellTicProfit=OrderProfit();
                    }
                  if(OrderProfit()>0)SellProfit+=OrderProfit()+OrderCommission()+OrderSwap();
                 }
              }
// Summ profit final
   double ProfitBuy=BuyTicProfit+BuyProfit;
   double ProfitSel=SellTicProfit+SellProfit;

   double  lot=NormalizeDouble(AccountBalance()*Risk/100/MarketInfo(Symbol(),MODE_MARGINREQUIRED),2);

   if(b==0)
      BuyLot=(Lot>0)?Lot:lot;
   else
      BuyLot=BuyMinLot+Lot;
   if(s==0)
      SellLot=(Lot>0)?Lot:lot;
   else
      SellLot=SellMaxLot+Lot;

   double BuyDist  = NormalizeDouble(MinStep*Point()+MinStepPlus*Point()*b,Digits());
   double SellDist = NormalizeDouble(MinStep*Point()+MinStepPlus*Point()*s,Digits());

   if(TypeOrders==Only_BUY || TypeOrders==Only_All)
      if((b==0) || (b>0 && (BuyMin-Ask)>=BuyDist))
         if(OrderSend(Symbol(),OP_BUY,NormalizeDouble(BuyLot,2),NormalizeDouble(Ask,Digits()),Slippage,0,0,"My order",Magic,0,clrGreen)<0)
            Print(" Error open Buy N ",GetLastError());

   if(TypeOrders==Only_SELL || TypeOrders==Only_All)
      if((s==0) || (s>0 && (Bid-SellMax)>=SellDist))
         if(OrderSend(Symbol(),OP_SELL,NormalizeDouble(SellLot,2),NormalizeDouble(Bid,Digits()),Slippage,0,0,"My order",Magic,0,clrGreen)<0)
            Print(" Error open Sell N ",GetLastError());

   if(ProfitBuy>=MinProfit && b>=2)
      CloseAll(OP_BUY,BuyMaxTic);

   if(ProfitSel>=MinProfit && s>=2)
      CloseAll(OP_SELL,SellMinTic);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+

---

Следующая страница: https://forexsystemru.com/threads/27577/page-3
