Новая версия платформы MetaTrader 5 build 2360: Расширение интеграции с SQLite - страница 26

 
Stanislav Korotky:

You used static. This is one time initialization!

Переменная - static, для неё выполнена однократная инициализация.

Oh, sorry, sometimes I can't see the forest for the trees.

О, простите, иногда я не вижу леса за деревьями.

 

Форум по трейдингу, автоматическим торговым системам и тестированию торговых стратегий

Тестируем 'CopyTicks'

traveller00, 2020.04.15 08:29

MT5 последняя релизная сборка 2361. В аттаче кастомный символ. Создать символ из json, импортировать тики, запустить тест советника на чарте этого символа.

Советник

void OnTick()
{
  MqlTick Tick={0};
  if(SymbolInfoTick(_Symbol,Tick))
  {
    MqlTick OldTicks[];
    Print(CopyTicks(_Symbol,OldTicks,COPY_TICKS_ALL));
    Print(GetLastError());
    Print(CopyTicks(_Symbol,OldTicks,COPY_TICKS_ALL,(ulong)D'2020.04.06 00:00:00' * 1000));
    Print(GetLastError());
  }
  ExpertRemove();
}

Параметры теста

[Tester]
Expert=test.ex5
Symbol=AUDNZD.RannForex
Period=M1
Optimization=0
Model=4
FromDate=2020.04.08
ToDate=2020.04.09
ForwardMode=0
Deposit=10000000
Currency=USD
ProfitInPips=1
Leverage=100
ExecutionMode=0
OptimizationCriterion=6
Visual=0

1. Счёт неттинг.

    1.1. При указанных датах вывод похож на правду: 2000   0   2000   0.

    1.2. При смене дат на 07.04.2020-08.04.2020 вывод становится странным: -1   4004   1   0.

            Во-первых, почему появляется ошибка в первом случае? Во-вторых, почему второй случай берёт только 1 тик? Дата запроса тиков не менялась.

2. Счёт хедж.

    2.1. При указанных датах вывод становится странным: 2000   0   1   0.

            Почему второй случай берёт только 1 тик? Дата запроса тиков не менялась.

    2.2. При смене дат на 07.04.2020-08.04.2020 вывод остановится странным, но таким же: 2000   0   1   0.


Отсюда вопросы: почему CopyTicks с фиксированными параметрами зависит не только от дат тестирования, но и от типа счёта? Или я что-то не понимаю и делаю не так?

Это сильно затрудняет работу, просьба по возможности поправить. Удалось воспроизвести? Что-то ещё нужно от меня для повторения? Спасибо.


Просьба поправить странные баги. Или пояснить, что я делаю не так. Спасибо.

 

Вот такая строка в коде намертво вешает Метаедитор при попытке компиляции, либо закрытии окна, либо переключении на другую вкладку:

string s = typename(class{ template<typename T> void f(T); });
 

2380:

Terminal        MetaTrader 5 x64 build 2380 started for MetaQuotes Software Corp.
Terminal        Windows 10 build 19041, Intel Core i3-3120M  @ 2.50GHz, 1 / 7 Gb memory, 66 / 415 Gb disk, IE 11, UAC, GMT+2
Terminal        C:\Users\barab\AppData\Roaming\MetaQuotes\Terminal\D0E8209F77C8CF37AD8BF550E51FF075
Network	'19332146': authorized on MetaQuotes-Demo through Access Point EU 2 (ping: 66.90 ms, build 2385)


Такой вопрос: есть индикатор 'DigitsTest', он в OnInit() и в OnCalculate() распечатывает Digits(). Если индикатор запустить в тестере или онлайн (на графике) - Digits() работает верно.

А теперь эксперимент: советник 'DigitsTest EA' запускается на символе 'AUDJPY' (на сегодня по символу 'AUDJPY'  цена 67.448 - то есть Digits() выдаёт '3'). Советник создаёт два хендла индикатора 'DigitsTest' - первый на символе 'EURJPY' (на сегодня по символу 'EURJPY'  цена 116.326 - то есть Digits() выдаёт '3'), а второй на символе 'EURUSD' (на сегодня по символу 'EURUSD'  цена 1.08333 - то есть Digits() выдаёт '5'). И теперь индикаторы (созданные в советнике) распечатывают Digits() равное '3'.

Вопрос: почему оба индикатора выдают Digits() равное '3', а не '3' и '5'?


Код индикатора:

//+------------------------------------------------------------------+
//|                                                   DigitsTest.mq5 |
//|                                           Copyright 2020, Markus |
//|                                                                  |
//+------------------------------------------------------------------+
#property copyright "Copyright 2020, Markus"
#property link      ""
#property version   "1.00"
#property indicator_chart_window
#property indicator_plots 0
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- indicator buffers mapping
   long dig=SymbolInfoInteger(Symbol(),SYMBOL_DIGITS);
   Print("Indicator DigitsTest: ",Symbol(),", _Digits: ",_Digits,", Digits(): ",Digits(),", ::Digits(): ",::Digits(),", SYMBOL_DIGITS: ",dig);
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
  {
//---
   long dig=SymbolInfoInteger(Symbol(),SYMBOL_DIGITS);
   Print("Indicator DigitsTest: ",Symbol(),", _Digits: ",_Digits,", Digits(): ",Digits(),", ::Digits(): ",::Digits(),", SYMBOL_DIGITS: ",dig,", close ",close[rates_total-1]);
//--- return value of prev_calculated for next call
   return(rates_total);
  }
//+------------------------------------------------------------------+


Код советника:

//+------------------------------------------------------------------+
//|                                                DigitsTest EA.mq5 |
//|                                           Copyright 2020, Markus |
//|                                                                  |
//+------------------------------------------------------------------+
#property copyright "Copyright 2020, Markus"
#property link      ""
#property version   "1.00"

int   ghDigitsTestEURJPY = NULL;
int   ghDigitsTestEURUSD = NULL;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   Print(Symbol() + ": Digits(): " + (string)(Digits()));
   ghDigitsTestEURJPY=iCustom("EURJPY",PERIOD_H6,"Test\\DigitsTest");
   if(ghDigitsTestEURJPY==INVALID_HANDLE)
     {
      Print("ghDigitsTest == INVALID_HANDLE");
      return(INIT_PARAMETERS_INCORRECT);
     }
   ghDigitsTestEURUSD=iCustom("EURUSD",PERIOD_H6,"Test\\DigitsTest");
   if(ghDigitsTestEURUSD==INVALID_HANDLE)
     {
      Print("ghDigitsTest == INVALID_HANDLE");
      return(INIT_PARAMETERS_INCORRECT);
     }
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---

  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   static long counter=0;
   if(counter>=6)
     {
      IndicatorRelease(ghDigitsTestEURJPY);
      IndicatorRelease(ghDigitsTestEURUSD);
      ExpertRemove();
     }
   counter++;
  }
//+------------------------------------------------------------------+


Результат запуска в тестере стратегий (отладка на истории)

MetaTester 5 started on 127.0.0.1:3000
initialization finished
login (build 2380)
template file tester.tpl added. 2708 bytes loaded
4372 bytes of account info loaded
1482 bytes of tester parameters loaded
188 bytes of input parameters loaded
1022 bytes of symbols list loaded (73 symbols)
expert file added: Experts\Tests\DigitsTest EA.ex5. 16145 bytes loaded
program file added: Indicators\DigitsTest.ex5. 13417 bytes loaded
2517 Mb available, 31 blocks set for ticks generating
initial deposit 10000.00 USD, leverage 1:100
successfully initialized
30 Kb of total initialization data received
Intel Core i3-3120M  @ 2.50GHz, 8077 MB
AUDJPY: symbol to be synchronized
AUDJPY: symbol synchronized, 3720 bytes of symbol info received
AUDJPY: history synchronization started
AUDJPY: load 27 bytes of history data to synchronize in 0:00:00.003
AUDJPY: history synchronized from 2015.01.02 to 2020.04.08
AUDJPY,M15: history cache allocated for 31468 bars and contains 25913 bars from 2019.01.02 06:00 to 2020.01.17 23:45
AUDJPY,M15: history begins from 2019.01.02 06:00
AUDJPY,M15 (MetaQuotes-Demo): every tick generating
testing with execution delay 1000 milliseconds
AUDJPY,M15: testing of Experts\Tests\DigitsTest EA.ex5 from 2020.01.19 00:00 to 2020.04.08 00:00 started
2020.01.19 00:00:00   AUDJPY: Digits(): 3
EURJPY: symbol to be synchronized
EURJPY: symbol synchronized, 3720 bytes of symbol info received
EURJPY: history synchronization started
EURJPY: load 27 bytes of history data to synchronize in 0:00:00.001
EURJPY: history synchronized from 2015.01.02 to 2020.04.08
2020.01.19 00:00:00   Indicator DigitsTest: EURJPY, _Digits: 3, Digits(): 3, ::Digits(): 3, SYMBOL_DIGITS: 3
EURJPY,H6: history cache allocated for 1313 bars and contains 1081 bars from 2019.01.02 06:00 to 2020.01.17 18:00
EURJPY,H6: history begins from 2019.01.02 06:00
EURUSD: symbol to be synchronized
EURUSD: symbol synchronized, 3720 bytes of symbol info received
EURUSD: history synchronization started
EURUSD: load 27 bytes of history data to synchronize in 0:00:00.002
EURUSD: history synchronized from 2015.01.02 to 2020.04.08
2020.01.19 00:00:00   Indicator DigitsTest: EURUSD, _Digits: 3, Digits(): 3, ::Digits(): 3, SYMBOL_DIGITS: 3
EURUSD,H6: history cache allocated for 1313 bars and contains 1081 bars from 2019.01.02 06:00 to 2020.01.17 18:00
EURUSD,H6: history begins from 2019.01.02 06:00
2020.01.19 00:00:00   Indicator DigitsTest: EURJPY, _Digits: 3, Digits(): 3, ::Digits(): 3, SYMBOL_DIGITS: 3, close 122.163
2020.01.19 00:00:00   Indicator DigitsTest: EURUSD, _Digits: 3, Digits(): 3, ::Digits(): 3, SYMBOL_DIGITS: 3, close 1.10893
2020.01.20 00:05:00   Indicator DigitsTest: EURJPY, _Digits: 3, Digits(): 3, ::Digits(): 3, SYMBOL_DIGITS: 3, close 122.145
2020.01.20 00:05:00   Indicator DigitsTest: EURUSD, _Digits: 3, Digits(): 3, ::Digits(): 3, SYMBOL_DIGITS: 3, close 1.1092
2020.01.20 00:05:03   Indicator DigitsTest: EURJPY, _Digits: 3, Digits(): 3, ::Digits(): 3, SYMBOL_DIGITS: 3, close 122.15
2020.01.20 00:05:06   Indicator DigitsTest: EURJPY, _Digits: 3, Digits(): 3, ::Digits(): 3, SYMBOL_DIGITS: 3, close 122.155
2020.01.20 00:05:06   Indicator DigitsTest: EURUSD, _Digits: 3, Digits(): 3, ::Digits(): 3, SYMBOL_DIGITS: 3, close 1.10917
2020.01.20 00:05:09   Indicator DigitsTest: EURJPY, _Digits: 3, Digits(): 3, ::Digits(): 3, SYMBOL_DIGITS: 3, close 122.154
2020.01.20 00:05:12   Indicator DigitsTest: EURJPY, _Digits: 3, Digits(): 3, ::Digits(): 3, SYMBOL_DIGITS: 3, close 122.152
2020.01.20 00:05:13   Indicator DigitsTest: EURUSD, _Digits: 3, Digits(): 3, ::Digits(): 3, SYMBOL_DIGITS: 3, close 1.10918
2020.01.20 00:05:15   Indicator DigitsTest: EURJPY, _Digits: 3, Digits(): 3, ::Digits(): 3, SYMBOL_DIGITS: 3, close 122.155
2020.01.20 00:05:18   Indicator DigitsTest: EURJPY, _Digits: 3, Digits(): 3, ::Digits(): 3, SYMBOL_DIGITS: 3, close 122.159
2020.01.20 00:05:20   Indicator DigitsTest: EURUSD, _Digits: 3, Digits(): 3, ::Digits(): 3, SYMBOL_DIGITS: 3, close 1.10915
2020.01.20 00:05:22   Indicator DigitsTest: EURJPY, _Digits: 3, Digits(): 3, ::Digits(): 3, SYMBOL_DIGITS: 3, close 122.151
2020.01.20 00:05:25   Indicator DigitsTest: EURJPY, _Digits: 3, Digits(): 3, ::Digits(): 3, SYMBOL_DIGITS: 3, close 122.143
2020.01.20 00:05:26   Indicator DigitsTest: EURUSD, _Digits: 3, Digits(): 3, ::Digits(): 3, SYMBOL_DIGITS: 3, close 1.10916
2020.01.20 00:05:28   Indicator DigitsTest: EURJPY, _Digits: 3, Digits(): 3, ::Digits(): 3, SYMBOL_DIGITS: 3, close 122.142
2020.01.20 00:05:31   Indicator DigitsTest: EURJPY, _Digits: 3, Digits(): 3, ::Digits(): 3, SYMBOL_DIGITS: 3, close 122.144
2020.01.20 00:05:33   Indicator DigitsTest: EURUSD, _Digits: 3, Digits(): 3, ::Digits(): 3, SYMBOL_DIGITS: 3, close 1.10913
2020.01.20 00:05:34   Indicator DigitsTest: EURJPY, _Digits: 3, Digits(): 3, ::Digits(): 3, SYMBOL_DIGITS: 3, close 122.128
2020.01.20 00:05:37   Indicator DigitsTest: EURJPY, _Digits: 3, Digits(): 3, ::Digits(): 3, SYMBOL_DIGITS: 3, close 122.129
2020.01.20 00:05:40   Indicator DigitsTest: EURUSD, _Digits: 3, Digits(): 3, ::Digits(): 3, SYMBOL_DIGITS: 3, close 1.10915
2020.01.20 00:05:41   Indicator DigitsTest: EURJPY, _Digits: 3, Digits(): 3, ::Digits(): 3, SYMBOL_DIGITS: 3, close 122.113
2020.01.20 00:05:44   Indicator DigitsTest: EURJPY, _Digits: 3, Digits(): 3, ::Digits(): 3, SYMBOL_DIGITS: 3, close 122.122
2020.01.20 00:05:47   Indicator DigitsTest: EURJPY, _Digits: 3, Digits(): 3, ::Digits(): 3, SYMBOL_DIGITS: 3, close 122.119
2020.01.20 00:05:50   Indicator DigitsTest: EURJPY, _Digits: 3, Digits(): 3, ::Digits(): 3, SYMBOL_DIGITS: 3, close 122.122
2020.01.20 00:05:59   ExpertRemove() function called
removed itself within OnTick
final balance 10000.00 USD
removed itself on 1% of testing interval
AUDJPY,M15: 7 ticks, 1 bars generated. Environment synchronized in 0:00:00.143. Test passed in 0:00:02.690 (including ticks preprocessing 0:00:01.844).
AUDJPY,M15: total time from login to stop testing 0:00:02.833 (including 0:00:00.146 for history data synchronization)
31 total ticks for all symbols
AUDJPY: generate 6054824 ticks in 0:00:00.594, passed to tester 28128 ticks
EURJPY: generate 7807510 ticks in 0:00:00.781, passed to tester 28070 ticks
EURUSD: generate 5004172 ticks in 0:00:00.469, passed to tester 18389 ticks
620 Mb memory used including 2 Mb of history data, 384 Mb of tick data
log file "C:\Users\barab\AppData\Roaming\MetaQuotes\Tester\D0E8209F77C8CF37AD8BF550E51FF075\Agent-127.0.0.1-3000\logs\20200421.log" written
test Experts\Tests\DigitsTest EA.ex5 on AUDJPY,M15 thread finished
prepare for shutdown

На распечатке видно, что индикатор созданный на символе и 'EURJPY' и 'EURUSD' распечатывают Digits равное '3'. 

Тестирование стратегий - Алгоритмический трейдинг, торговые роботы - Справка по MetaTrader 5
Тестирование стратегий - Алгоритмический трейдинг, торговые роботы - Справка по MetaTrader 5
  • www.metatrader5.com
Тестер стратегий позволяет тестировать и оптимизировать торговые стратегии (советники) перед началом использования их в реальной торговле. При тестировании советника происходит его однократная прогонка с начальными параметрами на исторических данных. При оптимизации торговая стратегия прогоняется несколько раз с различным набором параметров...
Файлы:
 

2380

SymbolInfoTick не получает тиковые объёмы и реальные объёмы

Terminal        MetaTrader 5 x64 build 2380 started for MetaQuotes Software Corp.
Terminal        Windows 10 build 19041, Intel Core i3-3120M  @ 2.50GHz, 1 / 7 Gb memory, 66 / 415 Gb disk, IE 11, UAC, GMT+2
Terminal        C:\Users\barab\AppData\Roaming\MetaQuotes\Terminal\D0E8209F77C8CF37AD8BF550E51FF075
Network	'19332146': authorized on MetaQuotes-Demo through Access Point EU 2 (ping: 66.90 ms, build 2385)

Код:

//+------------------------------------------------------------------+
//|                                                      ProjectName |
//|                                      Copyright 2018, CompanyName |
//|                                       http://www.companyname.net |
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OnTick()
  {
   MqlTick m_tick;
   if(SymbolInfoTick(Symbol(),m_tick))
     {
      Print(m_tick.time,",",
            " Bid ",DoubleToString(m_tick.bid,Digits()),
            " Ask ",DoubleToString(m_tick.ask,Digits()),
            " Volume ",IntegerToString(m_tick.volume),
            " Volume real ",DoubleToString(m_tick.volume_real,0));
     }
   else
      Print("SymbolInfoTick() failed, error = ",GetLastError());
  }
//+------------------------------------------------------------------+

Результат запуска

2020.04.22 08:54:03, Bid 0.63225 Ask 0.63234 Volume 0 Volume real 0
Документация по MQL5: Константы, перечисления и структуры / Константы индикаторов / Ценовые константы
Документация по MQL5: Константы, перечисления и структуры / Константы индикаторов / Ценовые константы
  • www.mql5.com
Технические индикаторы требуют для своих расчетов указания значений цен и/или значений объемов, на которых они будут считаться. Существуют 7 предопределенных идентификаторов перечисления ENUM_APPLIED_PRICE, для указания нужной ценовой базы расчетов. Если технический индикатор для своих расчетов использует ценовые данные, тип которых задается...
Файлы:
1.mq5  3 kb
 
Vladimir Karputov:

2380

SymbolInfoTick не получает тиковые объёмы и реальные объёмы

Код:

Результат запуска

А почему вы считаете, что там должны быть объёмы???

В документации однозначно сказано

Возвращает текущие цены  для указанного символа в переменной типа MqlTick.

а про объёмы ничего нет.

 
Vladimir Karputov:

2380

SymbolInfoTick не получает тиковые объёмы и реальные объёмы

Код:

Результат запуска

Дополнил вызовами SYMBOL_VOLUME и SYMBOL_VOLUME_REAL - всё равно объёмов нет.

//+------------------------------------------------------------------+
//|                                                      ProjectName |
//|                                      Copyright 2018, CompanyName |
//|                                       http://www.companyname.net |
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OnTick()
  {
   long volume=SymbolInfoInteger(Symbol(),SYMBOL_VOLUME);
   double volume_real=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_REAL);

   MqlTick m_tick;
   if(!SymbolInfoTick(Symbol(),m_tick))
      return;
   Print(TimeToString(m_tick.time,TIME_DATE|TIME_MINUTES),",",
         " Bid ",DoubleToString(m_tick.bid,Digits()),
         " Ask ",DoubleToString(m_tick.ask,Digits()),
         " Volume ",IntegerToString(m_tick.volume),
         " Volume real ",DoubleToString(m_tick.volume_real,0),
         " SYMBOL_VOLUME ",IntegerToString(volume),
         " SYMBOL_VOLUME_REAL ",DoubleToString(volume_real,0));
  }
//+------------------------------------------------------------------+


Результат

1 (AUDUSD,H1)   2020.04.22 09:01, Bid 0.63184 Ask 0.63195 Volume 0 Volume real 0 SYMBOL_VOLUME 0 SYMBOL_VOLUME_REAL 0
Файлы:
1.mq5  3 kb
 
Vladimir Karputov:

Дополнил вызовами SYMBOL_VOLUME и SYMBOL_VOLUME_REAL - всё равно объёмов нет.

Результат

Биржевой инструмент

2020.04.22 09:53:08.290 TestScript (CLEM20,M1)  2020.04.22 06:53, Bid 10.72 Ask 10.74 Volume 2 Volume real 2 SYMBOL_VOLUME 2 SYMBOL_VOLUME_REAL 2
Какой вы объём ожидаете на форекс? AUDUSD
 

Объёмы тиков удалось получить только при помощи CopyTickVolume. Почему остальные способы перестали работать?

//+------------------------------------------------------------------+
//|                                                      ProjectName |
//|                                      Copyright 2018, CompanyName |
//|                                       http://www.companyname.net |
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OnTick()
  {
   long volume=SymbolInfoInteger(Symbol(),SYMBOL_VOLUME);
   double volume_real=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_REAL);
   long volume_array[],real_volume_array[];


   MqlTick m_tick;
   if(!SymbolInfoTick(Symbol(),m_tick) || CopyTickVolume(Symbol(),Period(),0,1,volume_array)!=1 ||
      CopyRealVolume(Symbol(),Period(),0,1,real_volume_array)!=1)
      return;
   Print(TimeToString(m_tick.time,TIME_DATE|TIME_MINUTES),",",
         " Bid ",DoubleToString(m_tick.bid,Digits()),
         " Ask ",DoubleToString(m_tick.ask,Digits()),
         " Volume ",IntegerToString(m_tick.volume),
         " Volume real ",DoubleToString(m_tick.volume_real,0),
         " SYMBOL_VOLUME ",IntegerToString(volume),
         " SYMBOL_VOLUME_REAL ",DoubleToString(volume_real,0),
         " CopyTickVolume ",IntegerToString(volume_array[0]));
  }
//+------------------------------------------------------------------+


Результат

2020.04.22 10:05:47.492 1 (AUDUSD,H1)   2020.04.22 10:05, Bid 0.63283 Ask 0.63291 Volume 0 Volume real 0 SYMBOL_VOLUME 0 SYMBOL_VOLUME_REAL 0 CopyTickVolume 407
Файлы:
1.mq5  3 kb
 

Если на хедже открыть две противоположные позиции по лоту, а затем схлопнуть через CloseBy, то во вкладке История (режим) будут показаны эти две позиции по лоту.

Такое отображение схлопнувшихся позиций показывает, будто было полностью проторговано 2 лота. Но на самом деле - один.


В MT4 с этим сделано хорошо - одна из позиций показывается с нулевым объемом.

Строка для поиска: Uluchshenie 021.
Причина обращения: