[ARQUIVO!] Qualquer pergunta de novato, para não desorganizar o fórum. Profissionais, não passem por aqui. Em nenhum lugar sem você - 4. - página 449

 
ilunga:

Não, isso significa apenas que os dados correspondiam a um pedaço de história.

Você poderia ter entrado manualmente, por exemplo. Ou escrito a partir de um arquivo de texto. Ou você poderia tê-lo obtido de uma calculadora.


Porque mesmo inserindo alguns dados condicionais "1,25 1,16 1,73 1,35" podemos ter a história de alguma moeda há muitos anos. Mas isso não significa que criamos uma série de séries cronológicas

Afinou um pouco o roteiro original:

1. Copiei para a matriz personalizada apenas 5 últimos preços de abertura.

2. Calculou a matriz personalizada obtida por todos os 5 preços de abertura copiados.

/+------------------------------------------------------------------------------------------+
//|                                                                ArrayGetAsSeries_плюс.mq4 |
//+------------------------------------------------------------------------------------------+
//|                         script program start function                                    |
//+------------------------------------------------------------------------------------------+
//------------------------------------ НАЧАЛО START -------------------------------------- 1 -
int start()                                           //функция start
  {                                                   //начало start
   double Timestart=GetTickCount();                   //переменная, с помощью которой вычисляется время (в милисекундах) начала выполнения эксперта 
   double array1[];                                   //объявляем массив-приемник (массив, куда будут скопированы данные)
   int element=ArrayCopy(array1,Open,0,0,5);          //копируем данные по максимальным ценам в пользовательский массив (начиная с 1-о бара, а не с нулевого)
   int size=ArraySize(array1);                        //устанавливаем количество элементов массива array1
//----------------------------------------------------------------------------------------- 2 -
   Comment("\nФункция ArrayCopy(array1[],Open,0,0,WHOLE_ARRAY) вернула: ",element,
           "\nФункция ArraySize(array1) вернула: ",size,
           "\nЗначение цены открытия бара №0 равно ",array1[0],"; Время цены открытия бара №0: ",TimeToStr(iTime(NULL,0,0),TIME_DATE|TIME_MINUTES),
           "\nЗначение цены открытия бара №1 равно ",array1[1],"; Время цены открытия бара №1: ",TimeToStr(iTime(NULL,0,1),TIME_DATE|TIME_MINUTES),
           "\nЗначение цены открытия бара №2 равно ",array1[2],"; Время цены открытия бара №2: ",TimeToStr(iTime(NULL,0,2),TIME_DATE|TIME_MINUTES),
           "\nЗначение цены открытия бара №3 равно ",array1[3],"; Время цены открытия бара №3: ",TimeToStr(iTime(NULL,0,3),TIME_DATE|TIME_MINUTES),
           "\nЗначение цены открытия бара №4 равно ",array1[4],"; Время цены открытия бара №4: ",TimeToStr(iTime(NULL,0,4),TIME_DATE|TIME_MINUTES),
           "\nФункция ArrayGetAsSeries(array1) вернула: ",ArrayGetAsSeries(array1),
           "\nСкрипт выполнялся всего ",GetTickCount()-Timestart," миллисекунд, из них: ",MathFloor((GetTickCount()-Timestart)/1000),
           " секунд ",((GetTickCount()-Timestart)/1000-MathFloor((GetTickCount()-Timestart)/1000))*1000," миллисекунд");//печать 
           //сообщения на экран
//----------------------------------------------------------------------------------------- 3 -
   return(0);                                                             //выход из start
  }                                                                       //конец start
//-------------------------------------- КОНЕЦ START -------------------------------------- 4 -

Aqui está o que eu tenho:


Como você pode ver na figura, os preços abertos são indexados em ordem inversa (como evidenciado pelo NÚMERO de preços de barras abertas (vai em ordem crescente) e o TEMPO de preços de barras abertas (vai em ordem decrescente)), ou seja, o array é organizado como uma série de arrays timeseries.

Mas a função ArrayGetAsSeries retorna no entanto 0 (falso), o que significa: a matriz do usuário NÃO é organizada como uma array-timeseries.

Muito gentilmente, peça clareza

Pergunta: como explicar isto?

P.S. Obrigado por responder às minhas perguntas

 
7777877:

Afinou um pouco o roteiro original:

1. Copiei apenas os últimos 5 preços de abertura em uma matriz personalizada.

2. Rasperfeiçoou a matriz personalizada resultante por todos os 5 preços de abertura copiados.

Aqui está o que eu tenho:

Como você pode ver na figura, os preços abertos são indexados em ordem inversa (como evidenciado pelo NÚMERO de preços de barras abertas (vai em ordem crescente) e o TEMPO de preços de barras abertas (vai em ordem decrescente)), ou seja, o array é organizado como uma série de arrays timeseries.

Mas a função ArrayGetAsSeries retorna no entanto 0 (falso), o que significa: a matriz do usuário NÃO é organizada como uma array-timeseries.

Por favor, esclareça

Pergunta: como explicar isso?

P.S. Obrigado por responder às minhas perguntas.

Você já tentou usar o

boolArraySetAsSeries(conjunto vazio[], conjunto de bool)
Define a direção de indexação de uma matriz. Umconjunto TRUE define a direção de indexação em ordem inversa, ou seja, o último elemento tem um índice zero. Um valor de FALSE define a direção normal da indexação. A função retorna o estado anterior.
Parâmetros:
matriz[]-Articulação numérica a definir.
conjunto-A direção na qual a matriz é indexada.
 
Vinin:

Você já tentou as funções

boolArraySetAsSeries(conjunto vazio[], conjunto de bool)
Define a direção de indexação da matriz. Umvalor doconjunto TRUE define a direção de indexação em ordem inversa, ou seja, o último elemento tem um índice zero. Um valor de FALSE define a direção normal da indexação. A função retorna o estado anterior.
Parâmetros:
matriz[]-Articulação numérica a definir.
conjunto-A direção na qual a matriz é indexada.

Meu objetivo nesta fase é entender como funciona uma determinada função e, neste caso particular, como funciona o ArrayGetAsSeries. Entendo que posso usar a função ArraySetAsSeries com parâmetro set=true, que define à força a indexação, como em array-timeseries. Mas quero entender, por que no meu caso a função ArrayGetAsSeries retornou 0, apesar da matriz se parecer com timeseries (i.e. indexada como timeseries)
 
Sepulca:


i_maTF == Período() ??????

i_maPeriodo leva um valor razoável????

Talvez haja algo errado com o i_maShiftByPrice???

É difícil ser mais preciso.

As informações que ela emite não são corretas. Aqui está o código completo:

#property copyright "hoz"
#property link      ""
#include <stderror.mqh>
#include <stdlib.mqh>

extern string  h1 = "основные параметры машки";
extern int     i_maTF = 0;
extern int     i_maPeriod = 50;
extern int     i_maShiftByPrice = 0;
extern int     i_maMethod = 0;
extern int     i_maPrice = 0;
extern int     i_shiftBarsBack1 = 1;                        // Первое значение shift
extern int     i_shiftBarsBack2 = 49;                       // Второе значение shift
extern string  h2 = "===============================";

string         h3 = "Значения цены и времени в точках А и В гипотенузы";
double         price1,                                      // Цена в точке А
               price2,                                      // Цена в точке В
               time1,                                       // Время в точке А
               time2,                                       // Время в точке В
string         h4 = "Переменые массивов цены и времени в точках А и В гипотенузы";
double         varsPrice1[100],                             // Буфер для цены в точке А
               varsPrice2[100],                             // Буфер для цены в точке В
               varsTime1[100],                              // Буфер для времени в точке А
               varsTime2[100],                              // Буфер для времени в точке В

#property indicator_separate_window
#property indicator_buffers 5
#property indicator_color1 Red
//+------------------------------------------------------------------+
//|               Функция инициализации индикатора                   |
//+------------------------------------------------------------------+
int init()
  {
   IndicatorDigits(MarketInfo(Symbol(),MODE_DIGITS));
   SetIndexBuffer(0,varsAngle);                          // Связываем массив значений угла с буфером
   SetIndexStyle(0,DRAW_HISTOGRAM); 
   
// -------------- блок инициализации закончен ----------------------
   return(0);
  }
//+------------------------------------------------------------------+
//|              Функция деинициализации индикатора                  |
//+------------------------------------------------------------------+
int deinit()
  {

// -------------- блок деинициализации закончен ----------------------
   return(0);
  }
//+------------------------------------------------------------------+
//|                  Функция итерации эксперта                       |
//+------------------------------------------------------------------+
int start()
  {
   int i, countedBars = IndicatorCounted();
   int limit = Bars - countedBars;
   if (limit > 100) limit = 100;
        
   for(i = limit - 1;i > 0;i--)
    {
      price1 = iMA(Symbol(),i_maTF,i_maPeriod,i_maShiftByPrice,i_maMethod,i_maPrice,i_shiftBarsBack1+i);       // Цена в точке А
      price2 = iMA(Symbol(),i_maTF,i_maPeriod,i_maShiftByPrice,i_maMethod,i_maPrice,i_shiftBarsBack2+i);       // Цена в точке В
      time1 = iTime(Symbol(),Period(),i_shiftBarsBack1 + i - 1);                                               // Время в точке А
      time2 = iTime(Symbol(),Period(),i_shiftBarsBack2 + i - 1);                                               // Время в точке В
    
      Print("i = ", i," i_maTF = ", i_maTF, " i_maPeriod = ", i_maPeriod," i_maShiftByPrice ", i_maShiftByPrice, " i_maMethod = ", i_maMethod," i_maPrice = ", i_maPrice, " i_shiftBarsBack1 = ", i_shiftBarsBack1);
      string error = GetMyLastError2();
      
  //    Print("vars", DoubleToStr(price1,5));
    //  Print("vars", DoubleToStr(varsPrice1[i],5));
      
      varsPrice1[i] = price1;                                                                        // Массив цен в точке А
      varsPrice2[i] = price2;                                                                        // Массив цен в точке В
      varsTime1[i] = time1;                                                                          // Массив времени в точке А
      varsTime2[i] = time2;                                                                          // Массив времени в точке В
    
   
  //    Print("vars", DoubleToStr(varsPrice1[i],5));

            
      double d = (MathAbs(varsTime1[i] - varsTime2[i]))*1.0;
      double h = (MathAbs(varsPrice1[i] - varsPrice2[i]));
      
  //    Print("d = ", d, " h = ", h);
      
      double angle = h/d;
      varsAngle[i] = angle;
    }
   return(0);
  }
  
string GetMyLastError2()
  {
    int err = GetLastError();
    string serr = ErrorDescription(err);
    return(serr);
  }

/* //+------------------------------------------------------------------+
//|                  Функция рассчёта тангенса угла                  |
//+------------------------------------------------------------------+
double TanA(double d, double h)
 {
   double angle = h/d;
   
  return(0);
 }
// -------------- блок деинициализации закончен ---------------------- */

O registro do Expert Advisor mostra isso:







14:50:36 2010.08.11 12:30  AngleByTg GBPUSD,M15: i = 25 i_maTF = 50 i_maPeriod = 0 i_maShiftByPrice 0 i_maMethod = 0 i_maPrice = 2 i_shiftBarsBack1 = 7
14:50:36 2010.08.11 12:30  AngleByTg GBPUSD,M15: i = 24 i_maTF = 50 i_maPeriod = 0 i_maShiftByPrice 0 i_maMethod = 0 i_maPrice = 2 i_shiftBarsBack1 = 7
14:50:36 2010.08.11 12:30  AngleByTg GBPUSD,M15: i = 23 i_maTF = 50 i_maPeriod = 0 i_maShiftByPrice 0 i_maMethod = 0 i_maPrice = 2 i_shiftBarsBack1 = 7
14:50:36 2010.08.11 12:30  AngleByTg GBPUSD,M15: i = 22 i_maTF = 50 i_maPeriod = 0 i_maShiftByPrice 0 i_maMethod = 0 i_maPrice = 2 i_shiftBarsBack1 = 7
14:50:36 2010.08.11 12:30  AngleByTg GBPUSD,M15: i = 21 i_maTF = 50 i_maPeriod = 0 i_maShiftByPrice 0 i_maMethod = 0 i_maPrice = 2 i_shiftBarsBack1 = 7
14:50:36 2010.08.11 12:30  AngleByTg GBPUSD,M15: i = 20 i_maTF = 50 i_maPeriod = 0 i_maShiftByPrice 0 i_maMethod = 0 i_maPrice = 2 i_shiftBarsBack1 = 7
14:50:36 2010.08.11 12:30  AngleByTg GBPUSD,M15: i = 19 i_maTF = 50 i_maPeriod = 0 i_maShiftByPrice 0 i_maMethod = 0 i_maPrice = 2 i_shiftBarsBack1 = 7
14:50:36 2010.08.11 12:30  AngleByTg GBPUSD,M15: i = 18 i_maTF = 50 i_maPeriod = 0 i_maShiftByPrice 0 i_maMethod = 0 i_maPrice = 2 i_shiftBarsBack1 = 7
14:50:36 2010.08.11 12:30  AngleByTg GBPUSD,M15: i = 17 i_maTF = 50 i_maPeriod = 0 i_maShiftByPrice 0 i_maMethod = 0 i_maPrice = 2 i_shiftBarsBack1 = 7
14:50:36 2010.08.11 12:30  AngleByTg GBPUSD,M15: i = 16 i_maTF = 50 i_maPeriod = 0 i_maShiftByPrice 0 i_maMethod = 0 i_maPrice = 2 i_shiftBarsBack1 = 7
14:50:36 2010.08.11 12:30  AngleByTg GBPUSD,M15: i = 15 i_maTF = 50 i_maPeriod = 0 i_maShiftByPrice 0 i_maMethod = 0 i_maPrice = 2 i_shiftBarsBack1 = 7
14:50:36 2010.08.11 12:30  AngleByTg GBPUSD,M15: i = 14 i_maTF = 50 i_maPeriod = 0 i_maShiftByPrice 0 i_maMethod = 0 i_maPrice = 2 i_shiftBarsBack1 = 7
14:50:36 2010.08.11 12:30  AngleByTg GBPUSD,M15: i = 13 i_maTF = 50 i_maPeriod = 0 i_maShiftByPrice 0 i_maMethod = 0 i_maPrice = 2 i_shiftBarsBack1 = 7
14:50:36 2010.08.11 12:30  AngleByTg GBPUSD,M15: i = 12 i_maTF = 50 i_maPeriod = 0 i_maShiftByPrice 0 i_maMethod = 0 i_maPrice = 2 i_shiftBarsBack1 = 7
14:50:36 2010.08.11 12:30  AngleByTg GBPUSD,M15: i = 11 i_maTF = 50 i_maPeriod = 0 i_maShiftByPrice 0 i_maMethod = 0 i_maPrice = 2 i_shiftBarsBack1 = 7
14:50:36 2010.08.11 12:30  AngleByTg GBPUSD,M15: i = 10 i_maTF = 50 i_maPeriod = 0 i_maShiftByPrice 0 i_maMethod = 0 i_maPrice = 2 i_shiftBarsBack1 = 7
14:50:36 2010.08.11 12:30  AngleByTg GBPUSD,M15: i = 9 i_maTF = 50 i_maPeriod = 0 i_maShiftByPrice 0 i_maMethod = 0 i_maPrice = 2 i_shiftBarsBack1 = 7
14:50:36 2010.08.11 12:30  AngleByTg GBPUSD,M15: i = 8 i_maTF = 50 i_maPeriod = 0 i_maShiftByPrice 0 i_maMethod = 0 i_maPrice = 2 i_shiftBarsBack1 = 7
14:50:36 2010.08.11 12:30  AngleByTg GBPUSD,M15: i = 7 i_maTF = 50 i_maPeriod = 0 i_maShiftByPrice 0 i_maMethod = 0 i_maPrice = 2 i_shiftBarsBack1 = 7
14:50:36 2010.08.11 12:30  AngleByTg GBPUSD,M15: i = 6 i_maTF = 50 i_maPeriod = 0 i_maShiftByPrice 0 i_maMethod = 0 i_maPrice = 2 i_shiftBarsBack1 = 7
14:50:36 2010.08.11 12:30  AngleByTg GBPUSD,M15: i = 5 i_maTF = 50 i_maPeriod = 0 i_maShiftByPrice 0 i_maMethod = 0 i_maPrice = 2 i_shiftBarsBack1 = 7
14:50:36 2010.08.11 12:30  AngleByTg GBPUSD,M15: i = 4 i_maTF = 50 i_maPeriod = 0 i_maShiftByPrice 0 i_maMethod = 0 i_maPrice = 2 i_shiftBarsBack1 = 7
14:50:36 2010.08.11 12:30  AngleByTg GBPUSD,M15: i = 3 i_maTF = 50 i_maPeriod = 0 i_maShiftByPrice 0 i_maMethod = 0 i_maPrice = 2 i_shiftBarsBack1 = 7
14:50:36 2010.08.11 12:30  AngleByTg GBPUSD,M15: i = 2 i_maTF = 50 i_maPeriod = 0 i_maShiftByPrice 0 i_maMethod = 0 i_maPrice = 2 i_shiftBarsBack1 = 7
14:50:36 2010.08.11 12:30  AngleByTg GBPUSD,M15: i = 1 i_maTF = 50 i_maPeriod = 0 i_maShiftByPrice 0 i_maMethod = 0 i_maPrice = 2 i_shiftBarsBack1 = 7

Como você pode ver, as variáveis i_maTF, i_maPeriod e i_maPrice não são o que inicializei. O que está errado?

 
hoz:

Produz a informação errada. Aqui está o código completo:

O registro de especialista mostra isso:

Como você pode ver, as variáveis i_maTF, i_maPeriod e i_maPrice não são as mesmas que eu inicializei. O que está errado?

Como será que você conseguiu obter algo no registro se o código que você enviou não foi compilado?

E, se você compilá-lo, não haverá nenhuma esquisitice.

Arquivos anexados:
hoz_1.mq4  4 kb
 
TarasBY:

Pergunto-me como você conseguiu colocar alguma coisa no registro se o código que você apresentou não foi compilado?

Ah, se você compilá-lo, não terá nenhuma esquisitice.

Eu sempre compenso normalmente.

Limpei o código de impressoras e variáveis extras, para não confundir ninguém. Mas eu não os removi abaixo, por isso não compilou. Aqui está o código completo que compila:

//+------------------------------------------------------------------+
//|                                                    AngleByTg.mq4 |
//|                                                              hoz |
//|                                                                  |
//+------------------------------------------------------------------+
#property copyright "hoz"
#property link      ""
#include <stderror.mqh>
#include <stdlib.mqh>

extern string  h1 = "основные параметры машки";
extern int     i_maTF = 0;
extern int     i_maPeriod = 50;
extern int     i_maShiftByPrice = 0;
extern int     i_maMethod = 0;
extern int     i_maPrice = 0;
extern int     i_shiftBarsBack1 = 1;                        // Первое значение shift
extern int     i_shiftBarsBack2 = 49;                       // Второе значение shift
extern string  h2 = "===============================";

string         h3 = "Значения цены и времени в точках А и В гипотенузы";
double         price1,                                      // Цена в точке А
               price2,                                      // Цена в точке В
               time1,                                       // Время в точке А
               time2,                                       // Время в точке В
               angle;                                       // Значение возвращаемой тангенсом
string         h4 = "Переменые массивов цены и времени в точках А и В гипотенузы";
double         varsPrice1[100],                             // Буфер для цены в точке А
               varsPrice2[100],                             // Буфер для цены в точке В
               varsTime1[100],                              // Буфер для времени в точке А
               varsTime2[100],                              // Буфер для времени в точке В
               varsAngle[100];                              // Буфер для хранения значение угла

#property indicator_separate_window
#property indicator_buffers 5
#property indicator_color1 Red
//#property indicator_minimum -90
//#property indicator_maximum 90
//+------------------------------------------------------------------+
//|               Функция инициализации индикатора                   |
//+------------------------------------------------------------------+
int init()
  {
   IndicatorDigits(MarketInfo(Symbol(),MODE_DIGITS));
   SetIndexBuffer(0,varsAngle);                          // Связываем массив значений угла с буфером
   SetIndexStyle(0,DRAW_HISTOGRAM); 
   
// -------------- блок инициализации закончен ----------------------
   return(0);
  }
//+------------------------------------------------------------------+
//|              Функция деинициализации индикатора                  |
//+------------------------------------------------------------------+
int deinit()
  {

// -------------- блок деинициализации закончен ----------------------
   return(0);
  }
//+------------------------------------------------------------------+
//|                  Функция итерации эксперта                       |
//+------------------------------------------------------------------+
int start()
  {
 //   if (!isNewBar())
 //   return(0);
    
   int i, countedBars = IndicatorCounted();
   int limit = Bars - countedBars;
   if (limit > 100) limit = 100;
        
   for(i = limit - 1;i > 0;i--)
    {
      price1 = iMA(Symbol(),i_maTF,i_maPeriod,i_maShiftByPrice,i_maMethod,i_maPrice,i_shiftBarsBack1+i);       // Цена в точке А
      price2 = iMA(Symbol(),i_maTF,i_maPeriod,i_maShiftByPrice,i_maMethod,i_maPrice,i_shiftBarsBack2+i);       // Цена в точке В
      time1 = iTime(Symbol(),Period(),i_shiftBarsBack1 + i - 1);                                               // Время в точке А
      time2 = iTime(Symbol(),Period(),i_shiftBarsBack2 + i - 1);                                               // Время в точке В
    
      Print("i = ", i," i_maTF = ", i_maTF, " i_maPeriod = ", i_maPeriod," i_maShiftByPrice ", i_maShiftByPrice, " i_maMethod = ", i_maMethod," i_maPrice = ", i_maPrice, " i_shiftBarsBack1 = ", i_shiftBarsBack1);
      string error = GetMyLastError2();
      
      
//      Print("i = ", i," time1 = ", time1, " price1 = ", price1);
  //    Print("vars", DoubleToStr(price1,5));
    //  Print("vars", DoubleToStr(varsPrice1[i],5));
      
      varsPrice1[i] = price1;                                                                        // Массив цен в точке А
      varsPrice2[i] = price2;                                                                        // Массив цен в точке В
      varsTime1[i] = time1;                                                                          // Массив времени в точке А
      varsTime2[i] = time2;                                                                          // Массив времени в точке В
    
   
  //    Print("vars", DoubleToStr(varsPrice1[i],5));
    
      //Print("i = ", i," time1 = ", time1, " price1 = ", price1);
    //  Print("i = ", i," time2 = ", time2, " price2 = ", price2);
  //    Print("i = ", i," varsTime1[i] = ", varsTime1[i], " varsPrice1[i] = ", varsPrice1[i]);
     // Print("i = ", i," varsTime2[i] = ", varsTime2[i], " varsPrice2[i] = ", varsPrice2[i]);
            
      double d = (MathAbs(varsTime1[i] - varsTime2[i]))*1.0;
      double h = (MathAbs(varsPrice1[i] - varsPrice2[i]));
      
  //    Print("d = ", d, " h = ", h);
      
      double angle = h/d;
      varsAngle[i] = angle;
      
 //     Print("i = ", i," varsAngle[i] = ", varsAngle[i]);
    }
   return(0);
  }
  
string GetMyLastError2()
  {
    int err = GetLastError();
    string serr = ErrorDescription(err);
    return(serr);
  }

/* //+------------------------------------------------------------------+
//|                  Функция рассчёта тангенса угла                  |
//+------------------------------------------------------------------+
double TanA(double d, double h)
 {
   double angle = h/d;
   
  return(0);
 }
// -------------- блок деинициализации закончен ---------------------- */
Arquivos anexados:
anglebytg.mq4  6 kb
 

Por favor, ajude! Como fazer uma EA fechar um pedido antigo ao abrir um novo? No Testador de Estratégia funciona bem, mas, por alguma razão, quando abro um novo, o antigo sai???????? Eu sou um zero total na programação(((

//---- input parameters
//ooooooooooooooooooooooooooooooooooooooooooooooooo
extern bool In_BUY=true;
extern int SL_buy=62; //---входные параметры по лонгам
extern int Risk_buy=0;
//ooooooooooooooooooooooooooooooooooooooooooooooooo
extern bool In_SELL=true;
extern int SL_sell=62; //---входные параметры по шортам
extern int Risk_sell=0;
//ooooooooooooooooooooooooooooooooooooooooooooooooo

//---- other parameters
static int prevtime=0;
int ticket=0;
int x=1;
//----------------------------------------------
int Magic_BUY =123;
int Magic_SELL =321;


//+------------------------------------------------------------------+
//| expert initialization function |
//+------------------------------------------------------------------+
int init()
{
//----
if(Digits == 5) x=10;
//----
return(0);
}
//+------------------------------------------------------------------+
//| expert deinitialization function |
//+------------------------------------------------------------------+
int deinit()
{
//----

//----
return(0);
}
//+------------------------------------------------------------------+
//| expert start function |
//+------------------------------------------------------------------+
int start()
{
//oooooooooooooooooooooooooooooooooooooooooooooooooooo
if (Time[0] == prevtime) return(0);
prevtime = Time[0];
if (!IsTradeAllowed()) {
prevtime=Time[1]; MathSrand(TimeCurrent());Sleep(30000 + MathRand()); //--- формировка бара---
}
//ooooooooooooooooooooooooooooooooooooooooooooooooooooOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO


Trade( Magic_BUY, In_BUY,Ask,0,2, SL_buy, Risk_buy); //---торговля по лонгам


Trade(Magic_SELL,In_SELL,Bid,2,0, SL_sell,Risk_sell); //---торговля по шортам


//ooooooooooooooooooooooooooooooooooooooooooooooooooooOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO
return(0);//-----------выход из стартовой функции------------
}
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
void Trade(int mn,bool flag,double price,int period_1,int period_2,int sl,int Risk) {

int total=OrdersTotal();

for (int i = 0; i < total; i++) { OrderSelect(i, SELECT_BY_POS, MODE_TRADES);//---проход по ордерам--


if (OrderSymbol() == Symbol() && OrderMagicNumber() == mn) {

if(Open[period_2]>Open[period_1]) { //----условие закрытия ордера---------

OrderClose(OrderTicket(),OrderLots(),price,5*x); RefreshRates();

}

return(0);
}
}

//ooooooooooooooooooooooooooooooooooooooooooooooooooo
ticket = -1;



if ( flag &&

Open[period_1]>Open[period_2] && //----вход в рынок по условию---


OrdersTotal()<2 && //-----ограничения чемпионата------

AccountEquity()>200 &&

IsTradeAllowed()) {

if (mn<200) {

ticket= OrderSend(Symbol(), OP_BUY,lot(Risk_buy),Ask,5,Bid-x*sl*Point,0,DoubleToStr(mn,0),mn,0,Blue);


}


else {

ticket= OrderSend(Symbol(),OP_SELL,lot(Risk_sell),Bid,5,Ask+x*sl*Point,0,DoubleToStr(mn,0),mn,0, Red);

}


RefreshRates();

if ( ticket < 0) { Sleep(30000); prevtime = Time[1]; }

} //-- Exit ---

return(0); }


//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
double lot(int R) { if (R<0)R=0; if (R>80)R=80; //------корректность ввода -------
double minlot = MarketInfo(Symbol(), MODE_MINLOT);
int o = MathAbs(MathLog(minlot) *0.4343) + 0.5;
double lot = minlot;
//ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
lot = NormalizeDouble(AccountFreeMargin() * 0.00001*R, o);//---
if (AccountFreeMargin() < lot * MarketInfo(Symbol(), MODE_MARGINREQUIRED)) {
lot = NormalizeDouble(AccountFreeMargin() / MarketInfo(Symbol(), MODE_MARGINREQUIRED), o);
}
//ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
if(lot < minlot) lot = minlot;
double maxlot =MarketInfo(Symbol(), MODE_MAXLOT);
if(lot > maxlot) lot = maxlot;
return(lot); }
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx_end_film_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Ou talvez escrever outra EA que funcionaria com base no princípio de 1 abriu, 2 abriu-1 fechou, 3 abriu-2 fechou, etc. Ajude realmente, realmente preciso!!!
 
al7bar:

Por favor, ajude! Como fazer um EA fechar um pedido antigo ao abrir um novo? No Testador de Estratégia funciona bem, mas, por alguma razão, quando abro um novo, o antigo sai???????? Eu não tenho a menor idéia sobre programação((!

//---- input parameters
//ooooooooooooooooooooooooooooooooooooooooooooooooo
extern bool In_BUY=true;
extern int SL_buy=62; //---входные параметры по лонгам
extern int Risk_buy=0;

Substitua

if(Open[period_2]>Open[period_1]) { //----условие закрытия ордера---------

 OrderClose(OrderTicket(),OrderLots(),price,5*x); RefreshRates(); 

 }

para

if(Open[period_2]>Open[period_1]) { //----условие закрытия ордера---------

 OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),5*x); RefreshRates(); 

 }
 
7777877:
Meu objetivo nesta fase é entender como funciona esta ou aquela função e, neste caso particular, como funciona o ArrayGetAsSeries. Entendo que você pode usar a função ArraySetAsSeries com parâmetro set=true, que define à força a indexação, como em array-timeseries. Mas quero entender, por que no meu caso a função ArrayGetAsSeries retornou 0, apesar da matriz se parecer com timeseries (ou seja, indexada como timeseries)

Exatamente porque só EXPLAIZA como uma série cronológica.

Esta é apenas sua opinião pessoal. E se você colocar aí os números 1, 2, 1.2, 2.1, você recebe uma série de tempos para a carne de porco de 1927 (os números são condicionais). Mas isso não torna a matriz uma série de tempos - você precisa especificá-la explicitamente com a função

 
TarasBY:

Pergunto-me como você conseguiu colocar alguma coisa no registro se o código que você apresentou não foi compilado?

Ah, se você compilá-lo, não terá nenhuma esquisitice.

Eu lhe dei a versão original acima, que, é claro, compila. Eu tenho uma pergunta. Por que você substituiu as linhas?

      price1 = iMA(Symbol(),i_maTF,i_maPeriod,i_maShiftByPrice,i_maMethod,i_maPrice,i_shiftBarsBack1+i);       // Цена в точке А
      price2 = iMA(Symbol(),i_maTF,i_maPeriod,i_maShiftByPrice,i_maMethod,i_maPrice,i_shiftBarsBack2+i);       // Цена в точке В

i_maTF aPeríodo(). Eu estou errado?

A documentação diz que ao calcular a média móvel:

double iMA( string symbol, int timeframe, int period, int ma_shift, int ma_method, int applied_price, int shift)

tempo, ou seja, minha variáveli_maTF( Período. Pode ser um dos períodos do gráfico. 0 significa o período do gráfico atual.) Eu tinha 0 especificado.i_maPeríodo não é mencionado.Por favor, esclareça!

Razão: