Questions from Beginners MQL5 MT5 MetaTrader 5 - page 773

 

Thank you.
Just registered, don't know how the forum functions yet.

 
0Aleksandr0:

I don't understand WinAPI, what's wrong here?

let me see your efforts in the form of a script

 
0Aleksandr0:

I have it as a function in my EA, here is the beginning of the code

this is the function itself

The rest of the EA works fine, the variables that are in the function are not used anywhere else in the code.
Terminal crashes on lineSetClipboardData( CF_UNICODETEXT, hMem );// Passing memory with string to the buffer

 
Artyom Trishkin:

I get it, I stand corrected.)

 
o_o:

let me see your efforts as a script


I have it as a function in my EA, here is the beginning of the code

#define  CF_UNICODETEXT 13
#define  GHND 0x0042

#import "User32.dll"
   int OpenClipboard( uint );
   int EmptyClipboard();
   int CloseClipboard();
   uint SetClipboardData( uint uFormat, uint hMem );
#import "Kernel32.dll"
   uint GlobalAlloc( uint uFlags, uint dwBytes );
   uint GlobalLock( uint hMem );
   int GlobalUnlock( uint hMem );
#import "msvcrt.dll"
   uint memcpy( uint &dest, string src, uint count );
#import

string text = "AAA";

this is the function itself

 void OutClipboard()
{
   uint hwnd = (uint)ChartGetInteger( 0, CHART_WINDOW_HANDLE );
   
   int strSize = StringLen( text ) * 2 + 2;  // Получаем размер строки в байтах
   
   if( OpenClipboard( hwnd ) )    // Открываем буфер
   {
      EmptyClipboard();           // Очищаем буфер
      
      uint hMem = GlobalAlloc( GHND, strSize ); // Выделяем память
      uint pMem = GlobalLock( hMem );    // Получаем адрес выделенной памяти
      memcpy( pMem, text, strSize );     // Копируем строку в память
      GlobalUnlock( hMem );
   
      SetClipboardData( CF_UNICODETEXT, hMem );  // Передаём память со строкой в буфер
      
      CloseClipboard();  // Закрываем буфер
   }
}

The rest of the EA works fine, the variables that are in the function are not used anywhere else in the code.
Terminal crashes on lineSetClipboardData( CF_UNICODETEXT, hMem );// Passing memory with string to the buffer

 
//+------------------------------------------------------------------+
//|                                                    Clipboard.mq4 |
//|                                               ПавелИванович(api) |
//|                                              p231970@hotmail.com |
//|  Перенос на MQL5 и доработка unicode - Сергеев Алексей (sergeev) |
//|                                              profy.mql@gmail.com |
//+------------------------------------------------------------------+
#property version "1.00"
#property description "Getting contents of the clipboard"

#import "user32.dll"
bool  OpenClipboard(int hwnd);
int   GetClipboardData(int uFormat);
bool  CloseClipboard();
int   GetAncestor(long hWnd,int gaFlags);
int   GetAncestor(int  hWnd,int gaFlags);
#import "kernel32.dll"
int   GlobalLock(int hMem);
bool  GlobalUnlock(int hMem);
string lstrcatW(int dst,string src);
#import
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
int OnStart()
  {
   int    hMain;
   string clip="";
//---
   if(_IsX64)
      hMain=GetAncestor(ChartGetInteger(ChartID(),CHART_WINDOW_HANDLE),2);
   else
      hMain=GetAncestor((int)ChartGetInteger(ChartID(),CHART_WINDOW_HANDLE),2);
//---
   if(OpenClipboard(hMain))
     {
      int hglb=GetClipboardData(1/*CF_TEXT*/);
      if(hglb!=0)
        {
         int lptstr=GlobalLock(hglb);

         if(lptstr!=0) { clip=lstrcatW(lptstr,""); GlobalUnlock(hglb); }
        }
      CloseClipboard();
     }

// translate ANSI to UNICODE
   ushort chW; uchar chA; string rez;
   for(int i=0; i<StringLen(clip); i++)
     {
      chW=StringGetCharacter(clip, i);
      chA=uchar(chW&255); rez=rez+CharToString(chA);
      chA=uchar(chW>>8&255); rez=rez+CharToString(chA);
     }

   MessageBox("Clipboard: \n"+rez,"Clipboard");
   return(0);
  }
//+------------------------------------------------------------------+

I found this script, which supposedly reads the buffer and outputs the value in the terminal window - it doesn't work either.

Although it doesn't kill terminal, it doesn't output anything in the window either.
It's a mystery with buffer, I'll limit outputting data to Alert for now, I can copy data from it with ctrl+c, though I wanted to avoid "manual" actions.

 

That example was for MT4, so it didn't take into account digit capacity.

Here is one for all platforms:

#ifdef __MQL5__
#define _WIN64  // Только для 64-разрядного терминала!
#endif

#include <WinDef.mqh>

#define  CF_UNICODETEXT 13
#define  GHND 0x0042

#import "User32.dll"
   BOOL OpenClipboard( HWND );
   BOOL EmptyClipboard();
   BOOL CloseClipboard();
   HANDLE SetClipboardData( uint uFormat, HANDLE hMem );
#import "Kernel32.dll"
   HANDLE GlobalAlloc( uint uFlags, size_t dwBytes );
   LPVOID GlobalLock( HANDLE hMem );
   BOOL GlobalUnlock( HANDLE hMem );
#import "msvcrt.dll"
   PVOID memcpy( PVOID dest, string src, size_t count );
#import

string str = "АБВГД";

//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
{
   HWND hwnd = (HWND)ChartGetInteger( 0, CHART_WINDOW_HANDLE );
   
   size_t strSize = StringLen( str ) * 2 + 2;  // Получаем размер строки в байтах
   
   if( OpenClipboard( hwnd ) )    // Открываем буфер
   {
      EmptyClipboard();           // Очищаем буфер
      
      HANDLE hMem = GlobalAlloc( GHND, strSize ); // Выделяем память
      PVOID pMem = GlobalLock( hMem );    // Получаем адрес выделенной памяти
      memcpy( pMem, str, strSize );     // Копируем строку в память
      GlobalUnlock( hMem );
   
      SetClipboardData( CF_UNICODETEXT, hMem );  // Передаём память со строкой в буфер
      
      CloseClipboard();  // Закрываем буфер
   }
}
//+------------------------------------------------------------------+
Files:
WinDef.mqh  1 kb
 
Koldun Zloy:

That example was for MT4, so it didn't take into account digit capacity.

Here is one for all platforms:


I got suspicious about capacity, especially when I looked at the second script reading the buffer.
That's the only way to fix it, I would have figured out at least a month later)).
Thank you very much, you saved me a lot of time).

Immediately integrate it into EA)

 

Please help me to rewrite code on MT5 - I am not good at orders :(

//+------------------------------------------------------------------+
//| Расчёт статистик                                                 |
//+------------------------------------------------------------------+
bool CTradeStatistics::Calculate(const bool _to_log=false,const double _init_balance=0.0)
  {
//---
   if(_init_balance>0.)
      m_init_deposit=_init_balance;
   else
     {
      m_init_deposit=TesterStatistics(STAT_INITIAL_DEPOSIT);
      double curr_balance=m_init_deposit;
      if(!m_balance_arr.Add(curr_balance))
        {
         if(_to_log)
            Print("Ошибка добавления значения депозита.");
         return false;
        }
      //---
      int  orders_num=OrdersHistoryTotal();
      if(orders_num<1)
        {
         if(_to_log)
            Print("Нет ордеров в истории.");
         return false;
        }

      //--- собрать данные
      for(int ord_idx=0;ord_idx<orders_num;ord_idx++)
         if(OrderSelect(ord_idx,SELECT_BY_POS,MODE_HISTORY))
           {
            ENUM_ORDER_TYPE curr_ord_type=(ENUM_ORDER_TYPE)OrderType();
            if((curr_ord_type==ORDER_TYPE_BUY) || (curr_ord_type==ORDER_TYPE_SELL))
               if(OrderCloseTime()>0)
                 {
                  //int ord_ticket=OrderTicket();// del
                  //--- добавить профит ордера
                  double curr_ord_profit=OrderProfit()-OrderCommission()+OrderSwap();
                  if(!m_orders_arr.Add(curr_ord_profit))
                    {
                     if(_to_log)
                        Print("Ошибка добавления значения профита.");
                     return false;
                    }
                  //--- добавить текущее значение баланса
                  curr_balance+=curr_ord_profit;
                  if(!m_balance_arr.Add(curr_balance))
                    {
                     if(_to_log)
                        Print("Ошибка добавления значения депозита.");
                     return false;
                    }
                 }
           }
     }

When compiling the code errors:

'SELECT_BY_POS' - undeclared identifier KamikadzeStatistics.mqh 257 33

'MODE_HISTORY' - undeclared identifier KamikadzeStatistics.mqh 257 47

'OrderSelect' - wrong parameters count KamikadzeStatistics.mqh 257 13

'OrderType' - function not defined KamikadzeStatistics.mqh 259 60

'OrderCloseTime' - function not defined KamikadzeStatistics.mqh 261 19

'OrderProfit' - function not defined KamikadzeStatistics.mqh 265 42


 
Aleksey Vyazmikin:

Please help me to rewrite code on MT5 - I am not good at orders :(

When compiling the code errors:

'SELECT_BY_POS' - undeclared identifier KamikadzeStatistics.mqh 257 33

'MODE_HISTORY' - undeclared identifier KamikadzeStatistics.mqh 257 47

'OrderSelect' - wrong parameters count KamikadzeStatistics.mqh 257 13

'OrderType' - function not defined KamikadzeStatistics.mqh 259 60

'OrderCloseTime' - function not defined KamikadzeStatistics.mqh 261 19

'OrderProfit' - function not defined KamikadzeStatistics.mqh 265 42



What is this? I am not a good judge of MQL4. If you tell me what I need, I will be able to write everything in MQL5.
Is it something to do with history profit/loss calculation?