我正在尝试在 MQL5 中设置一个 PUB 套接字,并在 Python 中设置一个 SUB 套接字来接收消息。
我在 MQL5 中有这个:
#include <Zmq/Zmq.mqh>
Context context("helloworld");
Socket socket(context,ZMQ_PUB);
string BROKER;
int OnInit()
{
if (socket.bind("tcp://*:5556"))
{
Print("Error");
}
else
Print("Bound");
BROKER = AccountInfoString(ACCOUNT_COMPANY);
return(INIT_SUCCEEDED);
}
void OnTick()
{
MqlTick last_tick;
string str;
if(SymbolInfoTick(Symbol(),last_tick))
{
StringConcatenate(str, BROKER, ",", Symbol(), ",", last_tick.time_msc, ",", last_tick.ask, ",", last_tick.bid, ",", last_tick.last, ",", last_tick.volume);
}
else
str = "FAIL";
Print(str);
ZmqMsg reply(str);
socket.send(reply);
}
Python 中是这样的:
import zmq
import random
import sys
import time
context = zmq.Context()
socket = context.socket(zmq.SUB)
ports = [5556]
for port in ports:
print(port)
socket.connect("tcp://localhost:{}".format(port))
socket.setsockopt_string(zmq.SUBSCRIBE, '')
print('connected')
f = open('metatrader-1.csv', 'a')
while True:
msg = socket.recv()
print(msg)
f.write(str(msg) + '\n')
这个问题是,这似乎在Python端没有收到任何东西,recv调用只是永远阻塞。 OnTick 方法在 MT 中触发,因为可以看到打印内容。
我怎样才能让它发挥作用?
请注意,如果我切换到 REP/REQ 对,它就会起作用。
MQL5:
#include <Zmq/Zmq.mqh>
Context context("helloworld");
Socket socket(context,ZMQ_REQ);
string BROKER;
int OnInit()
{
if (socket.connect("tcp://localhost:5555"))
{
Print("Error");
}
else
Print("Bound");
BROKER = AccountInfoString(ACCOUNT_COMPANY);
return(INIT_SUCCEEDED);
}
void OnTick()
{
MqlTick last_tick;
string str;
if(SymbolInfoTick(Symbol(),last_tick))
{
StringConcatenate(str, BROKER, ",", Symbol(), ",", last_tick.time_msc, ",", last_tick.ask, ",", last_tick.bid, ",", last_tick.last, ",", last_tick.volume);
}
else
str = "FAIL";
Print(str);
ZmqMsg reply(str);
socket.send(reply);
socket.recv(reply);
}
Python:
import zmq
import random
import sys
import time
context = zmq.Context()
socket = context.socket(zmq.REP)
ports = [5555]
for port in ports:
print(port)
socket.bind("tcp://*:{}".format(port))
#socket.setsockopt_string(zmq.SUBSCRIBE, '')
print('connected')
f = open('metatrader-1.csv', 'a')
while True:
msg = socket.recv()
socket.send_string('ack')
print(msg)
f.write(str(msg) + '\n')
但这有一些缺点,所以如果可以的话我宁愿不使用它。