Discussão do artigo "Integração da MetaTrader 5 e Python: recebendo e enviando dados"

 

Novo artigo Integração da MetaTrader 5 e Python: recebendo e enviando dados foi publicado:

O vasto processamento de dados requer ferramentas extensas e muitas vezes está além do ambiente seguro de um único aplicativo. Linguagens de programação especializadas são usadas para processar e analisar dados, estatísticas e aprendizado de máquina. Uma das principais linguagens de programação para processamento de dados é o Python. O artigo fornece uma descrição de como conectar a MetaTrader 5 e o Python usando sockets, além de como receber cotações por meio da API do terminal.

Nós vamos escrever um programa simples que irá criar um servidor socket e receber as informações necessárias do cliente (o programa em MQL5), manipulá-lo e enviar o resultado de volta. Esse parece ser o método de interação mais eficiente. Suponha que nós precisamos usar uma biblioteca de aprendizado de máquina, como por exemplo scikit learn, que calculará a regressão linear usando preços e retornar as coordenadas, com base nos quais uma linha pode ser desenhada no terminal MetaTrader 5. Este é um exemplo simples. No entanto, essa interação também pode ser usada para treinar uma rede neural, para enviar à ela dados do terminal (cotações), aprender e retornar o resultado para o terminal.

Agora nós podemos continuar a criação de uma classe responsável pela manipulação do socket:
class socketserver:
    def __init__(self, address = '', port = 9090):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.address = address
        self.port = port
        self.sock.bind((self.address, self.port))
        self.cummdata = ''
        
    def recvmsg(self):
        self.sock.listen(1)
        self.conn, self.addr = self.sock.accept()
        print('connected to', self.addr)
        self.cummdata = ''

        while True:
            data = self.conn.recv(10000)
            self.cummdata+=data.decode("utf-8")
            if not data:
                break    
            self.conn.send(bytes(calcregr(self.cummdata), "utf-8"))
            return self.cummdata
            
    def __del__(self):
        self.sock.close()

Autor: Maxim Dmitrievsky

 
I tried this but I receive the errorcode 4014  (function not allowed), running it as an expert program. Is the option not activated?   
 
Ótimo artigo! Eu preciso enviar uma string para o servidor, aí fiquei meio perdido. É possível?
 
Problema ao rodar, erro 4014 ao criar o socket no mql5, diz que não posso usar socket com expert. Alguma ideia?
 
Também estou com o erro 4014 ao criar o socket no mql5
 
Alguém conseguiu resolver a situação do erro 4014 ?
 

Hi all

Note

Connection address should be added to the list of allowed ones on the client terminal side (Tools \ Options \ Expert Advisors).

If connection fails, error 5272 (ERR_NETSOCKET_CANNOT_CONNECT) is written to  _LastError.

The function can be called only from Expert Advisors and scripts, as they run in their own execution threads. If calling from an indicator,  GetLastError() returns the error 4014 – "Function is not allowed for call".



https://www.mql5.com/en/docs/network/socketconnect

Documentation on MQL5: Network Functions / SocketConnect
Documentation on MQL5: Network Functions / SocketConnect
  • www.mql5.com
//|                                                SocketExample.mq5 | //|                        Copyright 2018, MetaQuotes Software Corp. | //|                                             https://www.mql5.com | "Add Address to the list of allowed ones in the terminal settings to let the example work...
 
Maxim Dmitrievsky:

Hi all

Note

Connection address should be added to the list of allowed ones on the client terminal side (Tools \ Options \ Expert Advisors).

If connection fails, error 5272 (ERR_NETSOCKET_CANNOT_CONNECT) is written to  _LastError.

The function can be called only from Expert Advisors and scripts, as they run in their own execution threads. If calling from an indicator,  GetLastError() returns the error 4014 – "Function is not allowed for call".



https://www.mql5.com/en/docs/network/socketconnect


Hi Maxim Dmitrievsky,

I allowed the localhost and it's working correctly. Thank you very much! But when I ran in backtest using the Strategy Tester, the error 4014 persisted. The socket doesn't work with backtest?

Best regards
 
auuuuu1628:

Hi Maxim Dmitrievsky,

I allowed the localhost and it's working correctly. Thank you very much! But when I ran in backtest using the Strategy Tester, the error 4014 persisted. The socket doesn't work with backtest?

Best regards

Yes, all right. Metaquotes disabled this feature in backtester, but they say maybe allow this in near future.

 

Bom dia, estou tendo erro de dll

Traceback (most recent call last):

  File "teste_conexao.py", line 2, in <module>
    from MetaTrader5 import *
  File "C:\Users\anton\AppData\Local\Programs\Python\Python37\lib\site-packages\MetaTrader5\__init__.py", line 35, in <module>
    from .C import *

ImportError: DLL load failed: Não foi possível encontrar o módulo especificado.


alguém sabe o que estou fazendo errado ?

 
Antonio Batista:

Bom dia, estou tendo erro de dll

Traceback (most recent call last):

  File "teste_conexao.py", line 2, in <module>
    from MetaTrader5 import *
  File "C:\Users\anton\AppData\Local\Programs\Python\Python37\lib\site-packages\MetaTrader5\__init__.py", line 35, in <module>
    from .C import *

ImportError: DLL load failed: Não foi possível encontrar o módulo especificado.


alguém sabe o que estou fazendo errado ?

Olá Antonio,

esse erro normalmente acontece quando tenta instalar a biblioteca em um python que não é o Python para windows. Tente instalar o https://www.python.org/downloads/  e veja se corrige o erro.


Abraço

Download Python
Download Python
  • www.python.org
The official home of the Python Programming Language
Razão: