Вопросы от начинающих MQL5 MT5 MetaTrader 5 - страница 1385

 
qadexys #:

Подскажите пожалуйста:
Нужно получить прибыль по незавершенной сделке - с учетом прошедших клирингов.

Это возможно сделать классами CDealInfo или CPositionInfo? 

Конструкция:

позволила получить только текущую, без учета прибыли полученной ранее.

Пример для неттинга (выделение позиции по названию символа)

Forum on trading, automated trading systems and testing trading strategies

How to turn profit into profit points?

Vladimir Karputov, 2022.01.11 05:59

Like that:

//+------------------------------------------------------------------+
//|               Points profit of a position by trading history.mq5 |
//|                              Copyright © 2022, Vladimir Karputov |
//|                      https://www.mql5.com/en/users/barabashkakvn |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2022, Vladimir Karputov"
#property link      "https://www.mql5.com/en/users/barabashkakvn"
#property version   "1.003"
#property script_show_inputs
#include <Trade\PositionInfo.mqh>
CPositionInfo  m_position;
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
   if(m_position.Select(Symbol())) // select the position for further work
     {
      double profit=m_position.Profit();
      //--- request trade history
      if(!HistorySelectByPosition(m_position.Identifier()))
        {
         Print("Error HistorySelectByPosition");
         return;
        }
      //---
      uint history_deals_total=HistoryDealsTotal();
      double price_in=0.0;
      long time_in=TimeCurrent()+3600*24*3;
      //--- for all deals
      for(uint i=0; i<history_deals_total; i++)
        {
         ulong ticket=HistoryDealGetTicket(i);
         if(ticket)
           {
            profit+=HistoryDealGetDouble(ticket,DEAL_COMMISSION)+HistoryDealGetDouble(ticket,DEAL_SWAP)+HistoryDealGetDouble(ticket,DEAL_PROFIT);
            if(HistoryDealGetInteger(ticket,DEAL_ENTRY)==DEAL_ENTRY_IN)
              {
               long deal_time=HistoryDealGetInteger(ticket,DEAL_TIME);
               double deal_price=HistoryDealGetDouble(ticket,DEAL_PRICE);
               if(deal_time<time_in)
                 {
                  time_in=deal_time;
                  price_in=deal_price;
                 }
              }
           }
        }
      if(price_in>0.0)
        {
         double price_diff=MathAbs(m_position.PriceCurrent()-price_in);
         int points_profit=(int)(price_diff/Point());
         PrintFormat("position Ticket %d, position ID %d, profit %.2f, points profit %d: ",
                     m_position.Ticket(),m_position.Identifier(),profit,points_profit);
        }
     }
  }
//+------------------------------------------------------------------+


Result:

2022.01.11 06:57:32.678 Points profit of a position by trading history (XAUUSD,M15)     position Ticket 1235269798, position ID 1235269434, profit -0.63, points profit 71: 

 
Добрый вечер!
Такой вопрос, можно ли написать телеграм бота который будет транслировать информацию о закрытых ордера и тд. Как на картинке
Файлы:
 
Семён Метлицкий #:
Добрый вечер!
Такой вопрос, можно ли написать телеграм бота который будет транслировать информацию о закрытых ордера и тд. Как на картинке

Можно, сюда пишите

 
Семён Метлицкий #:
Добрый вечер!
Такой вопрос, можно ли написать телеграм бота который будет транслировать информацию о закрытых ордера и тд. Как на картинке

"Таким образом вы будете видеть насколько робот закупил ордеров из вашего депозита"...

Это жесть. Полный депозит приказов продажных.

Неужели люди ведутся на такое?

Остановите Землю.

Шучу.

 
Я Atamurat Abdukayimov я  прошлый год когда установил  приложение мт5 мне звонила с номера +998339667671 на мой старый номер +998975221951который сейчас ликвидирована можно ли будет с ней общаться.
 

Добрый день.

Переделываю стандартный MACD:

//+------------------------------------------------------------------+
//|                                                         MACD.mq5 |
//|                   Copyright 2009-2020, MetaQuotes Software Corp. |
//|                                              http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright   "2009-2020, MetaQuotes Software Corp."
#property link        "http://www.mql5.com"
#property description "Moving Average Convergence/Divergence"
#include <MovingAverages.mqh>
//--- indicator settings
#property indicator_separate_window
#property indicator_buffers 4
#property indicator_plots   2
#property indicator_type1   DRAW_HISTOGRAM
#property indicator_type2   DRAW_LINE
#property indicator_color1  Silver
#property indicator_color2  Red
#property indicator_width1  2
#property indicator_width2  1
#property indicator_label1  "MACD"
#property indicator_label2  "Signal"
//--- input parameters
input int                InpFastEMA=12;               // Fast EMA period
input int                InpSlowEMA=26;               // Slow EMA period
input int                InpSignalSMA=9;              // Signal SMA period
input ENUM_APPLIED_PRICE InpAppliedPrice=PRICE_CLOSE; // Applied price
//--- indicator buffers
double ExtMacdBuffer[];
double ExtSignalBuffer[];
double ExtFastMaBuffer[];
double ExtSlowMaBuffer[];

int    ExtFastMaHandle;
int    ExtSlowMaHandle;
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
void OnInit()
  {
//--- indicator buffers mapping
   SetIndexBuffer(0,ExtMacdBuffer,INDICATOR_DATA);
   SetIndexBuffer(1,ExtSignalBuffer,INDICATOR_DATA);
   SetIndexBuffer(2,ExtFastMaBuffer,INDICATOR_CALCULATIONS);
   SetIndexBuffer(3,ExtSlowMaBuffer,INDICATOR_CALCULATIONS);
//--- sets first bar from what index will be drawn
   PlotIndexSetInteger(1,PLOT_DRAW_BEGIN,InpSignalSMA-1);
//--- name for indicator subwindow label
   string short_name=StringFormat("MACD(%d,%d,%d)",InpFastEMA,InpSlowEMA,InpSignalSMA);
   IndicatorSetString(INDICATOR_SHORTNAME,short_name);
//--- get MA handles
   ExtFastMaHandle=iMA(NULL,0,InpFastEMA,0,MODE_EMA,InpAppliedPrice);
   ExtSlowMaHandle=iMA(NULL,0,InpSlowEMA,0,MODE_EMA,InpAppliedPrice);
  }
//+------------------------------------------------------------------+
//| Moving Averages Convergence/Divergence                           |
//+------------------------------------------------------------------+
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[])
  {
   if(rates_total<InpSignalSMA)
      return(0);
//--- not all data may be calculated
   int calculated=BarsCalculated(ExtFastMaHandle);
   if(calculated<rates_total)
     {
      Print("Not all data of ExtFastMaHandle is calculated (",calculated," bars). Error ",GetLastError());
      return(0);
     }
   calculated=BarsCalculated(ExtSlowMaHandle);
   if(calculated<rates_total)
     {
      Print("Not all data of ExtSlowMaHandle is calculated (",calculated," bars). Error ",GetLastError());
      return(0);
     }
//--- we can copy not all data
   int to_copy;
   if(prev_calculated>rates_total || prev_calculated<0)
      to_copy=rates_total;
   else
     {
      to_copy=rates_total-prev_calculated;
      if(prev_calculated>0)
         to_copy++;
     }
//--- get Fast EMA buffer
   if(IsStopped()) // checking for stop flag
      return(0);
   if(CopyBuffer(ExtFastMaHandle,0,0,to_copy,ExtFastMaBuffer)<=0)
     {
      Print("Getting fast EMA is failed! Error ",GetLastError());
      return(0);
     }
//--- get SlowSMA buffer
   if(IsStopped()) // checking for stop flag
      return(0);
   if(CopyBuffer(ExtSlowMaHandle,0,0,to_copy,ExtSlowMaBuffer)<=0)
     {
      Print("Getting slow SMA is failed! Error ",GetLastError());
      return(0);
     }
//---
   int start;
   if(prev_calculated==0)
      start=0;
   else
      start=prev_calculated-1;
//--- calculate MACD
   for(int i=start; i<rates_total && !IsStopped(); i++)
      ExtMacdBuffer[i]=ExtFastMaBuffer[i]-ExtSlowMaBuffer[i];
//--- calculate Signal
   SimpleMAOnBuffer(rates_total,prev_calculated,0,InpSignalSMA,ExtMacdBuffer,ExtSignalBuffer);
//--- OnCalculate done. Return new prev_calculated.
   return(rates_total);
  }
//+------------------------------------------------------------------+

Добавляю переменную символа:

Symbol1

Меняю 

   ExtFastMaHandle=iMA(NULL,0,InpFastEMA,0,MODE_EMA,InpAppliedPrice);
   ExtSlowMaHandle=iMA(NULL,0,InpSlowEMA,0,MODE_EMA,InpAppliedPrice);

На:

   ExtFastMaHandle=iMA(Symbol1,0,InpFastEMA,0,MODE_EMA,InpAppliedPrice);
   ExtSlowMaHandle=iMA(Symbol1,0,InpSlowEMA,0,MODE_EMA,InpAppliedPrice);

В итоге в логе ошибка: Not all data of ExtFastMaHandle is calculated (20057 bars). Error 4806

И индикатор не отрисовывает. Пробовал убрать из кода проверку и ретурн(0):

   if(calculated<rates_total)
     {
      Print("Not all data of ExtFastMaHandle is calculated (",calculated," bars). Error ",GetLastError());
      return(0);
     }

и 

   if(calculated<rates_total)
     {
      Print("Not all data of ExtSlowMaHandle is calculated (",calculated," bars). Error ",GetLastError());
      return(0);
     }

Получаю в логах:

Getting fast EMA is failed! Error 4807

Это из за разного количества баров на графике где прикреплен индикатор и графика откуда берет данные ima?

Как оптимально изменить код чтобы MACD расчитывал по выбранному инструменту а не по инструменту к графику которого он прикреплен?

 
Sergey #:

Добрый день.

Переделываю стандартный MACD:

Добавляю переменную символа:

Меняю 

На:

В итоге в логе ошибка: Not all data of ExtFastMaHandle is calculated (20057 bars). Error 4806

И индикатор не отрисовывает. Пробовал убрать из кода проверку и ретурн(0):

и 

Получаю в логах:

Getting fast EMA is failed! Error 4807

Это из за разного количества баров на графике где прикреплен индикатор и графика откуда берет данные ima?

Как оптимально изменить код чтобы MACD расчитывал по выбранному инструменту а не по инструменту к графику которого он прикреплен?

Используйте справочный пример:  iMACD

 
Vladimir Karputov #:

Используйте справочный пример:  iMACD

Спасибо!

 

Всем привет!

Открыл счет в FXCM в МТ5 нет символов валютных пар и естественно нет графиков, по ссылке  https://www.metatrader5.com/ru/news/1372 указано что MT5 заточен под котировки FXCM

Кто подскажет где копать или подскажите какой брокер использует котировки от FXCM?


и сделать как здесь



Заранее благодарю за ответ...

 

Как получить код из WinAPI функции 'GetLastError'? Я хочу удалить несуществующий файл при помощи WinAPI функции DeleteFileW.

Согласно справке DeleteFileW если 

... приложение пытается удалить несуществующий файл, функция DeleteFile завершается с ошибкой ERROR_FILE_NOT_FOUND. Если файл доступен только для чтения, функция завершается с ошибкой ERROR_ACCESS_DENIED

Описание кода 'ERROR_FILE_NOT_FOUND'

ERROR_FILE_NOT_FOUND

2 (0x2)

The system cannot find the file specified.


То есть я должен получить '2' при попытке удалить несуществующий файл - но я получаю '0'.


Мой код скрипта:

//+------------------------------------------------------------------+
//|                                                   DeleteFile.mq5 |
//|                              Copyright © 2022, Vladimir Karputov |
//|                      https://www.mql5.com/en/users/barabashkakvn |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2022, Vladimir Karputov"
#property link      "https://www.mql5.com/en/users/barabashkakvn"
#property version   "1.00"
#property script_show_inputs
#include <WinAPI\errhandlingapi.mqh>
#include <WinAPI\fileapi.mqh>
//--- input parameters
input string   InpFileName="C:\\123.txt";
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
//---
   ResetLastError();
   int result=DeleteFileW(InpFileName);
   uint res=GetLastError();
   if(result==0)
      PrintFormat("DeleteFile failed (%d)",res);
   else
      PrintFormat("DeleteFile OK (%d)",res);
  }
//+------------------------------------------------------------------+

Результат выполнения:

DeleteFile failed (0)
Файлы: