Giter Site home page Giter Site logo

darwinex / dwx-zeromq-connector Goto Github PK

View Code? Open in Web Editor NEW
338.0 41.0 224.0 5.74 MB

Wrapper library for algorithmic trading in Python 3, providing DMA/STP access to Darwinex liquidity via a ZeroMQ-enabled MetaTrader Bridge EA.

Home Page: https://blog.darwinex.com/zeromq-interface-python-r-metatrader4/

License: BSD 3-Clause "New" or "Revised" License

Python 100.00%
zeromq python distributed-messaging metatrader algorithmic-trading darwinex darwinex-api

dwx-zeromq-connector's Introduction

Important Update (15 Feb 2022):

DWX ZeroMQ Connector will be soon be archived (available to use, but not actively maintained).

We encourage both new and existing users to please visit its successor DWX Connect, that alongside removing the ZeroMQ dependency, also brings with it native support for both MetaTrader 4 and 5 without any 3rd-party dependencies 🙌

Many thanks!

DWX ZeroMQ Connector { Python 3 to MetaTrader 4 }

Latest version: 2.0.1 (here)

Need help? Join the Darwinex Collective Slack for code updates, Q&A and more.

About Darwinex

Darwinex is a UK FCA-Regulated broker & technology provider, enabling traders to:

  1. Trade the markets on the best terms and competitive execution conditions
  2. Develop their trading skills and build verifiable, investable track records
  3. Provide regulatory cover to attract capital and charge a 20% performance fee on investor profits

Please take a moment to read our Risk Disclosure here

Click here to visit our Trader Hall of Fame * ranked by Performance Fees earned (over 2M EUR paid to date)

Click here to Open a Darwinex Trading Account

Table of Contents

Introduction

In this project, we present a technique employing ZeroMQ (an Open Source, Asynchronous Messaging Library and Concurrency Framework) for building a basic – but easily extensible – high performance bridge between external (non-MQL) programming languages and MetaTrader 4.

IMPORTANT NOTES - PLEASE READ:

  1. Please note that we cannot provide support for Python or MQL as programming languages themselves. Therefore, if you are new to Python and MQL, incorporating the project into your specific algorithmic trading environment will require some additional work on your part (i.e. enough Python experience to integrate the Bridge into your environment -> it is assumed that users of the Bridge are self-sufficient in Python).

  2. Any code provided and/or referenced in this repository is NOT meant to be used "as-is". Users must treat all code as educational content that requires modification / incorporation into existing works, as per their individual requirements.

  3. We have drafted as detailed a set of steps as possible in our project README, but cannot cover all the dependencies as they are independent projects on their own that programmers need to account for / follow / keep up to speed with when considering using the DWX ZeroMQ Connector.

  4. This project and all accompanying source code should be run standalone (i.g. via a Python or IPython console, or batch process).

  5. Please DO NOT run this code in Jupyter or IPython Notebooks.

  6. The project's dependencies require MS VC++ Libraries. Without these installed, you are likely to run into "Resource Timeout" errors. The DLLs in the dependency projects (mql-zmq, libzmq, libsodium) require that you have the latest Visual C++ runtime (2015) libraries already installed.

  7. This project has not been tested on emulated environments (e.g. WINE, VMWare, etc).

  8. This project is intended for use solely in Windows 10 environments, at the present time.

Reasons for writing this post:

  • Lack of comprehensive, publicly available literature about this topic on the web.
  • Traders have traditionally relied on Winsock/WinAPI based solutions that often require revision with both Microsoft™ and MetaQuotes™ updates.
  • Alternatives to ZeroMQ include named pipes, and approaches where filesystem-dependent functionality forms the bridge between MetaTrader and external languages.

We lay the foundation for a distributed trading system that will:

  • Consist of one or more trading strategies developed outside MetaTrader 4 (non-MQL),
  • Use MetaTrader 4 for acquiring market data, trade execution and management,
  • Support multiple non-MQL strategies interfacing with MetaTrader 4 simultaneously,
  • Consider each trading strategy as an independent “Client”,
  • Consider MetaTrader 4 as the “Server”, and medium to market,
  • Permit both Server and Clients to communicate with each other on-demand.

Infographic: ZeroMQ-Enabled Distributed Trading Infrastructure (with MetaTrader 4) DWX ZMQ Infographic 1

Why ZeroMQ?

  • Enables programmers to connect any code to any other code, in a number of ways.
  • Eliminates a MetaTrader user’s dependency on just MetaTrader-supported technology (features, indicators, language constructs, libraries, etc.)
  • Traders can develop indicators and strategies in C/C#/C++, Python, R and Java (to name a few), and deploy to market via MetaTrader 4.
  • Leverage machine learning toolkits in Python and R for complex data analysis and strategy development, while interfacing with MetaTrader 4 for trade execution and management.
  • ZeroMQ can be used as a high-performance transport layer in sophisticated, distributed trading systems otherwise difficult to implement in MQL.
  • Different strategy components can be built in different languages if required, and seamlessly talk to each other over TCP, in-process, inter-process or multicast protocols.
  • Multiple communication patterns and disconnected operation.

Installation

This project requires the following:

You may install Python-specific dependencies either via pip install -r ./v2.0.1/python/api/requirements.txt or via installing the latest Anaconda distribution (Python 3 variants).

For your convenience, files from the last three items above have been included in this repository with appropriate copyrights referenced within.

This project incorporates functionality authored by Ding Li (GitHub: https://github.com/dingmaotu), who has kindly licensed his work under the Apache 2.0 license.

We acknowledge copyright as per the terms of the license, the following repositories serving as mandatory dependencies for this project:

  1. https://github.com/dingmaotu/mql-zmq

  2. https://github.com/dingmaotu/mql4-lib

Thank you Ding for your amazing open source contribution to this space!

Sincerely,
The Darwinex Labs Team
www.darwinex.com

Steps:

  1. Download and unzip mql-zmq-master.zip (by GitHub author @dingmaotu)
  2. Copy the contents of mql-zmq-master/Include/Mql and mql-zmq-master/Include/Zmq into your MetaTrader installation's MQL4/Include directory as-is. Your MQL4/Include directory should now have two additional folders "Mql" and "Zmq".
  3. Copy libsodium.dll and libzmq.dll from mql-zmq-master/Library/MT4 to your MetaTrader installation's MQL4/Libraries directory.
  4. Download DWX_ZeroMQ_Server_vX.Y.Z_RCx.mq4 and place it inside your MetaTrader installation's MQL4/Experts directory.
  5. Finally, download v2.0.1 / python / api / DWX_ZeroMQ_Connector_v2_0_1_RC8.py.

Configuration

  1. After completing the steps above, terminate and restart MetaTrader 4.

  2. Open any new chart, e.g. EUR/USD M, then drag and drop DWX_ZeroMQ_Server_v2.0.1_RC8.

  3. Switch to the EA's Inputs tab and customize values as necessary:

    EA Inputs

  4. Note: The variable Publish_MarketData was removed in recent versions. There is no need to modify this variable or to manually change the Publish_Symbols array. Symbols will automatically be added when the _DWX_MTX_SEND_TRACKPRICES_REQUEST_() function is called in python (see code example below).

    MetaTrader Publishing Tick Data 1

    MetaTrader Publishing Tick Data 2

Example Usage

Subscribe/Unsubscribe to/from EUR/USD bid/ask prices in real-time:

# subscribe to data:
_zmq._DWX_MTX_SUBSCRIBE_MARKETDATA_('EURUSD')
# tell MT4 to publish data:
_zmq._DWX_MTX_SEND_TRACKPRICES_REQUEST_(['EURUSD'])

Output:
[KERNEL] Subscribed to EURUSD BID/ASK updates. See self._Market_Data_DB.

# BID/ASK prices are now being streamed into _zmq._Market_Data_DB.
_zmq._Market_Data_DB

Output: 
{'EURUSD': {
  '2019-01-08 13:46:49.157431': (1.14389, 1.14392),
  '2019-01-08 13:46:50.673151': (1.14389, 1.14393),
  '2019-01-08 13:46:51.010993': (1.14392, 1.14395),
  '2019-01-08 13:46:51.100941': (1.14394, 1.14398),
  '2019-01-08 13:46:51.205881': (1.14395, 1.14398),
  '2019-01-08 13:46:52.283107': (1.14394, 1.14397),
  '2019-01-08 13:46:52.377055': (1.14395, 1.14398),
  '2019-01-08 13:46:52.777823': (1.14394, 1.14398),
  '2019-01-08 13:46:52.870773': (1.14395, 1.14398),
  '2019-01-08 13:46:52.985708': (1.14395, 1.14397),
  '2019-01-08 13:46:53.080652': (1.14393, 1.14397),
  '2019-01-08 13:46:53.196584': (1.14394, 1.14398),
  '2019-01-08 13:46:53.294541': (1.14393, 1.14397)}}

_zmq._DWX_MTX_UNSUBSCRIBE_MARKETDATA('EURUSD')

Output:
**
[KERNEL] Unsubscribing from EURUSD
**

Initialize Connector:

_zmq = DWX_ZeroMQ_Connector()

Construct Trade to send via ZeroMQ to MetaTrader:

_my_trade = _zmq._generate_default_order_dict()

Output: 
{'_action': 'OPEN',
 '_type': 0,
 '_symbol': 'EURUSD',
 '_price': 0.0,
 '_SL': 500,
 '_TP': 500,
 '_comment': 'DWX_Python_to_MT',
 '_lots': 0.01,
 '_magic': 123456,
 '_ticket': 0}

_my_trade['_lots'] = 0.05

_my_trade['_SL'] = 250

_my_trade['_TP'] = 750

_my_trade['_comment'] = 'nerds_rox0r'

Send trade to MetaTrader:

_zmq._DWX_MTX_NEW_TRADE_(_order=_my_trade)

# MetaTrader response (JSON):
{'_action': 'EXECUTION', 
'_magic': 123456, 
'_ticket': 85051741, 
'_open_price': 1.14414, 
'_sl': 250, 
'_tp': 750}

Get all open trades from MetaTrader:

_zmq._DWX_MTX_GET_ALL_OPEN_TRADES_()

# MetaTrader response (JSON):

{'_action': 'OPEN_TRADES', 
'_trades': {
    85051741: {'_magic': 123456, 
                '_symbol': 'EURUSD', 
                '_lots': 0.05, 
                '_type': 0, 
                '_open_price': 1.14414, 
                '_pnl': -0.45}
    }
}

Partially close 0.01 lots:

_zmq._DWX_MTX_CLOSE_PARTIAL_BY_TICKET_(85051741, 0.01)

# MetaTrader response (JSON):
{'_action': 'CLOSE', 
'_ticket': 85051741, 
'_response': 'CLOSE_PARTIAL', 
'_close_price': 1.14401, 
'_close_lots': 0.01}

# Partially closing a trade renews the ticket ID, retrieve it again.

_zmq._DWX_MTX_GET_ALL_OPEN_TRADES_()

# MetaTrader response (JSON):
{'_action': 'OPEN_TRADES', 
'_trades': {
    85051856: {'_magic': 123456, 
                '_symbol': 'EURUSD', 
                '_lots': 0.04, 
                '_type': 0, 
                '_open_price': 1.14414, 
                '_pnl': -0.36}
    }
}

Close a trade by ticket:

_zmq._DWX_MTX_CLOSE_TRADE_BY_TICKET_(85051856)

# MetaTrader response (JSON):
{'_action': 'CLOSE', 
'_ticket': 85051856, 
'_close_price': 1.14378, 
'_close_lots': 0.04, 
'_response': 'CLOSE_MARKET', 
'_response_value': 'SUCCESS'}

Close all trades by Magic Number:

# Before running the following example, 5 trades were executed using the same values as in "_my_trade" above, the magic number being 123456.

# Check currently open trades.

_zmq._DWX_MTX_GET_ALL_OPEN_TRADES_()

# MetaTrader response (JSON):
{'_action': 'OPEN_TRADES', 
    '_trades': {
        85052022: {'_magic': 123456, '_symbol': 'EURUSD', '_lots': 0.05, '_type': 0, '_open_price': 1.14353, '_pnl': 1.15}, 
        85052026: {'_magic': 123456, '_symbol': 'EURUSD', '_lots': 0.05, '_type': 0, '_open_price': 1.14354, '_pnl': 1.1}, 
        85052025: {'_magic': 123456, '_symbol': 'EURUSD', '_lots': 0.05, '_type': 0, '_open_price': 1.14354, '_pnl': 1.1}, 
        85052024: {'_magic': 123456, '_symbol': 'EURUSD', '_lots': 0.05, '_type': 0, '_open_price': 1.14354, '_pnl': 1.1}, 
        85052023: {'_magic': 123456, '_symbol': 'EURUSD', '_lots': 0.05, '_type': 0, '_open_price': 1.14356, '_pnl': 1}
    }
}

# Close all trades with magic number 123456
_zmq._DWX_MTX_CLOSE_TRADES_BY_MAGIC_(123456)

# MetaTrader response (JSON):
{'_action': 'CLOSE_ALL_MAGIC', '_magic': 123456, 
'_responses': {
    85052026: {'_symbol': 'EURUSD', '_close_price': 1.14375, '_close_lots': 0.05, '_response': 'CLOSE_MARKET'}, 
    85052025: {'_symbol': 'EURUSD', '_close_price': 1.14375, '_close_lots': 0.05, '_response': 'CLOSE_MARKET'}, 
    85052024: {'_symbol': 'EURUSD', '_close_price': 1.14375, '_close_lots': 0.05, '_response': 'CLOSE_MARKET'}, 
    85052023: {'_symbol': 'EURUSD', '_close_price': 1.14375, '_close_lots': 0.05, '_response': 'CLOSE_MARKET'}, 
    85052022: {'_symbol': 'EURUSD', '_close_price': 1.14375, '_close_lots': 0.05, '_response': 'CLOSE_MARKET'}}, 
'_response_value': 'SUCCESS'}

Close ALL open trades:


# Open 5 trades

_zmq._DWX_MTX_NEW_TRADE_()
{'_action': 'EXECUTION', '_magic': 123456, '_ticket': 85090920, '_open_price': 1.15379, '_sl': 500, '_tp': 500}

_zmq._DWX_MTX_NEW_TRADE_()
{'_action': 'EXECUTION', '_magic': 123456, '_ticket': 85090921, '_open_price': 1.15379, '_sl': 500, '_tp': 500}

_zmq._DWX_MTX_NEW_TRADE_()
{'_action': 'EXECUTION', '_magic': 123456, '_ticket': 85090922, '_open_price': 1.15375, '_sl': 500, '_tp': 500}

_zmq._DWX_MTX_NEW_TRADE_()
{'_action': 'EXECUTION', '_magic': 123456, '_ticket': 85090926, '_open_price': 1.15378, '_sl': 500, '_tp': 500}

_zmq._DWX_MTX_NEW_TRADE_()
{'_action': 'EXECUTION', '_magic': 123456, '_ticket': 85090927, '_open_price': 1.15378, '_sl': 500, '_tp': 500}

# Close all open trades
_zmq._DWX_MTX_CLOSE_ALL_TRADES_()

# MetaTrader response (JSON):
{'_action': 'CLOSE_ALL',
 '_responses': {85090927: {'_symbol': 'EURUSD',
   '_magic': 123456,
   '_close_price': 1.1537,
   '_close_lots': 0.01,
   '_response': 'CLOSE_MARKET'},
  85090926: {'_symbol': 'EURUSD',
   '_magic': 123456,
   '_close_price': 1.1537,
   '_close_lots': 0.01,
   '_response': 'CLOSE_MARKET'},
  85090922: {'_symbol': 'EURUSD',
   '_magic': 123456,
   '_close_price': 1.1537,
   '_close_lots': 0.01,
   '_response': 'CLOSE_MARKET'},
  85090921: {'_symbol': 'EURUSD',
   '_magic': 123456,
   '_close_price': 1.15369,
   '_close_lots': 0.01,
   '_response': 'CLOSE_MARKET'},
  85090920: {'_symbol': 'EURUSD',
   '_magic': 123456,
   '_close_price': 1.15369,
   '_close_lots': 0.01,
   '_response': 'CLOSE_MARKET'}},
 '_response_value': 'SUCCESS'}

Video Tutorials

Step-by-Step Installation & Configuration Tutorials

  1. Introduction

  2. Dependencies

  3. MetaTrader 4 Setup

  4. Programming Environment Setup

  5. ZeroMQ Client Configuration

  6. ZeroMQ Server Configuration

  7. Example Usage

The nuts & bolts of the DWX ZeroMQ Connector project

  1. How to Interface Python/R Trading Strategies with MetaTrader 4

  2. Algorithmic Trading via ZeroMQ: Trade Execution, Reporting & Management (Python to MetaTrader)

  3. Algorithmic Trading via ZeroMQ: Subscribing to Market Data (Python to MetaTrader)

  4. Build Algorithmic Trading Strategies with Python & ZeroMQ: Part 1

  5. Build Algorithmic Trading Strategies with Python & ZeroMQ: Part 2

  6. Troubleshooting Python, ZeroMQ & MetaTrader Configuration for Algorithmic Trading

Available functions:

  1. DWX_MTX_NEW_TRADE_(self, _order=None)
  2. DWX_MTX_MODIFY_TRADE_BY_TICKET_(self, _ticket, _SL, _TP)
  3. DWX_MTX_CLOSE_TRADE_BY_TICKET_(self, _ticket)
  4. DWX_MTX_CLOSE_PARTIAL_BY_TICKET_(self, _ticket, _lots)
  5. DWX_MTX_CLOSE_TRADES_BY_MAGIC_(self, _magic)
  6. DWX_MTX_CLOSE_ALL_TRADES_(self)
  7. DWX_MTX_GET_ALL_OPEN_TRADES_(self)
  8. generate_default_order_dict(self)
  9. generate_default_data_dict(self)
  10. DWX_MTX_SEND_MARKETDATA_REQUEST_(self, _symbol, _timeframe, _start, _end)
  11. DWX_MTX_SEND_COMMAND_(self, _action, _type, _symbol, _price, _SL, _TP, _comment, _lots, _magic, _ticket)
  12. DWX_MTX_SUBSCRIBE_MARKETDATA_(self, _symbol, _string_delimiter=';')
  13. DWX_MTX_UNSUBSCRIBE_MARKETDATA_(self, _symbol)
  14. DWX_MTX_UNSUBSCRIBE_ALL_MARKETDATA_REQUESTS_(self)

License

BSD 3-Clause License

Copyright (c) 2019, Darwinex. All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  • Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

  • Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

  • Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

dwx-zeromq-connector's People

Contributors

darwinex avatar elvinex avatar integracore2 avatar paduel avatar raulmrello avatar teddywaweru avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

dwx-zeromq-connector's Issues

[SOLVED]libzmq.dll dependencies

I’m having issues starting the ZMQ server, according to the logs it won’t initilazed because MT4 is not able to import the libzmq.dll file

2cc8729600a72b90c2c0bb1beaaaa706d42fc02e

Info:
-I’m using windows 8 64 bit
-AutoTrading and DLL import are both activated
-The dependencies are all imported to the libraries folder

zmp communication problem between python and MT4

Hi,
I want to test the subscribe data function. I can successfully get EA work, but when I execute my subscriber in python script, it doesn't show anything, when I pass the parameter zmq.NOBLOCK to the socket.recv(), it gives me the error: zmq.error.again: Resource temporarily unavailable.
I write the simplest code of subscriber in a single python script to check the rightness. I also test the zmq pub sub mode seperately only in python. It works.

import sys
import zmq
port = "5576"
context = zmq.Context()
socket = context.socket(zmq.SUB)
socket.connect ("tcp://localhost:5576")
socket.setsockopt_string(zmq.SUBSCRIBE,"EURUSD")
string = socket.recv(zmq.NOBLOCK)
print(string)

Does anyone know why?
Thanks!

Autentication

there is any solution like token something like that to make my mt4 server safety coz any one with endpoint url can open trade to my account i couldnt find on library how to ser new public key any one could give a exemplo

DWX_SetInstrumentList overwrite old calls

Hello,
I noticed that DWX_SetInstrumentList(string& compArray[], string& zmq_ret) { }
overwrites the content of PublishInstruments.
This is my solution:
`bool check_if_in_instrument_list(ENUM_TIMEFRAMES timeframe, string symbol){

  for( int i = 0; i < ArraySize(Publish_Instruments); i ++){
        if ( StringCompare(Publish_Instruments[i].symbol(), symbol) == 0 && Publish_Instruments[i].timeframe() == timeframe)
           return True;
  }
  return False;

}

//+------------------------------------------------------------------+
// Set list of instruments to get OHLC rates
void DWX_SetInstrumentList(string& compArray[], string& zmq_ret) {

zmq_ret = zmq_ret + "'_action': 'TRACK_RATES'";

// Format: TRACK_RATES|SYMBOL_1|TIMEFRAME_1|SYMBOL_2|TIMEFRAME_2|...|SYMBOL_N|TIMEFRAME_N
string result = "Tracking RATES from";      
int _num_instruments = (ArraySize(compArray) - 1)/2;
if(_num_instruments > 0){
    
           
    for(int s=0; s<_num_instruments; s++){ 
        ENUM_TIMEFRAMES timeframe = (ENUM_TIMEFRAMES)StrToInteger(compArray[(2*s)+2]);
        string symbol = compArray[(2*s)+1]; 
        bool res = check_if_in_instrument_list(timeframe, symbol);
        if( res )
        {
           Print("Timeframe and Symbol are already there");
           continue;
        }
        int oldSize =  ArraySize(Publish_Instruments);
        ArrayResize(Publish_Instruments, ArraySize(Publish_Instruments) + 1);
        Print("Added timeFrame and Symbol");            
        Publish_Instruments[s + oldSize].setup(compArray[(2*s)+1], (ENUM_TIMEFRAMES)StrToInteger(compArray[(2*s)+2]));
        result += " " + Publish_Instruments[s + oldSize].name();
     }
    zmq_ret = zmq_ret + ", '_data': {'instrument_count':" + IntegerToString(ArraySize(Publish_Instruments)) + "}";
    Publish_MarketRates = true;
}
else {
    Publish_MarketRates = false;    
    ArrayResize(Publish_Instruments, 1);           
    zmq_ret = zmq_ret + ", '_data': {'instrument_count': 0}";
    result += " NONE";

}
Print(result);
}`

'TRADING_IS_NOT_ALLOWED__ABORTED_COMMAND'

Trying to use both the DWX_MTX_CLOSE_ALL_TRADES() and DWX_MTX_NEW_TRADE(), at first they were working now they send the following message:

{'_response': 'TRADING_IS_NOT_ALLOWED__ABORTED_COMMAND'}

Coin flip trader

HI!

The issue is that coin flip trader is not closing trades and is stoped to open new ones as well. It opens them randomly than stops working and I get:

_NoneException Type TypeError. Args:
("'bool' object is not iterable",)
{'_action': 'OPEN_TRADES', '_trades': {3779123: {'_magic': 123456, '_symbol': 'AUDNZD', '_lots': 0.01, '_type': 1, '_open_price': 1.04874, '_open_time': '2019.07.10 15:23:04', '_SL': 1.04974, '_TP': 1.04774, '_pnl': -0.13, '_comment': 'AUDNZD_Trader'}, 3779122: {'_magic': 123456, '_symbol': 'EURUSD', '_lots': 0.01, '_type': 1, '_open_price': 1.12134, '_open_time': '2019.07.10 15:23:02', '_SL': 1.12234, '_TP': 1.12034, '_pnl': -0.04, '_comment': 'EURUSD_Trader'}}}Exception in thread EURUSD_Trader:
Traceback (most recent call last):
File "xxx\AppData\Local\Programs\Python\Python36-32\lib\threading.py", line 916, in _bootstrap_inner
self.run()
File "xxx\AppData\Local\Programs\Python\Python36-32\lib\threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "xxx/coin_flip_traders_v1.0.py", line 178, in trader
10)
File "xxx\DWX_ZMQ_Reporting.py", line 55, in get_open_trades
index=_response['trades'].keys())
File "xxx\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas\core\frame.py", line 404, in init
raise ValueError('DataFrame constructor not properly called!')
ValueError: DataFrame constructor not properly called!

for example if I run _zmq.DWX_MTX_CLOSE_ALL_TRADES() it will close all trades instant.

Any idea please what would solve the issue?

Tested in Jupyter notebook, ipython and PyCharm

Running on MT5

Hi
Is there anyway to be able to run the advisor on MT5 or do I have to convert the code fully to MQL5?

Run other EA together with the dwx connector EA

Hi,

Thanks a lot for the great work and I got it worked correctly.

However, the connector only works if I ONLY run ONE EA (DWX_ZeroMQ) on MT4. The DWX EA will not work if I have other EA running.

Is it possible to run DWX with other EAs on the same MT4? It would be great if we can.

Thanks,
Frank

MT4 not publishing data

Hi, i have followed your setup instructions for installing the MT4 EA, however when i start it i am not seeing any publish data in the expert tab at the bottom, does this mean it is not publishing the data correctly?

Screenshot 2019-04-17 at 21 49 49

Market Data Subscription: command does not reach MT4 Server, Order does

I'm on Windows 10, connecting via
_zmq = DWX_ZeroMQ_Connector(_verbose=True)
_zmq.DWX_MTX_SUBSCRIBE_MARKETDATA(_symbol='EURUSD')

then waiting via a timer in a thread for print(_zmq._Market_Data_DB) to update, but I get no data.

In the class and method
DWX_ZeroMQ_Connector
def DWX_MTX_SUBSCRIBE_MARKETDATA(self, _symbol, _string_delimiter=';'):

this code never gets called when I subscribe to market data:
self._MarketData_Thread = Thread(target=self._DWX_ZMQ_Poll_Data, args=(_string_delimiter))
self._MarketData_Thread.start()

Also the MT4 server only receives messages (in void InterpretZmqMessage(...)) when I order (which it executes fine), but not when I subscribe to market data, or request all open trades.

I installed a couple different versions and libraries I thought were related, but weren't. So maybe it's .dlls?

[ADMIN TODO] Rewrite for PEP8 Compliance

There are a few PEP8 violations in 'DWX_ZeroMQ_Connector_v2_0_1_RC8.py' file.

Such as:

image

There are two reasons it needs to be fixed (in my opinion):

  1. If I fixed it only on my end, each file update on the repository will overwrite my fix in case I would want to use the latest version.

  2. Almost all methods are named with a '_' as a prefix and Pycharm hides those methods as they are marked as private which is pretty uncomfortable.

Can I open a pull request and change this?

Broker Error 129: Invalid Price on FXCM

hello,
This error has been mentioned before but it seems there has been no cure for it but I keep getting the error when I attempt to execute a New Trade using the Default Order Dict.
simply:

import DWX_ZeroMQ_Connector_v2_0_1_RC8 as dwx

_zmq = dwx.DWX_ZeroMQ_Connector()
_zmq._generate_default_order_dict()
_zmq.DWX_MTX_NEW_TRADE()

Cannot call 'libzmq.dll::zmq_ctx_new', DLL is not allowed

image
Cannot call 'libzmq.dll::zmq_ctx_new', DLL is not allowed
DWX_ZeroMQ_Server_v2.0.1_RC8 EURUSD,M1: unresolved import function call
DWX_ZeroMQ_Server_v2.0.1_RC8 EURUSD,M1: global initialization failed

I have followed the step by step instruction and still getting this
even when i call _zmq.DWX_MTX_GET_ALL_OPEN_TRADES() i get nothing ,it runs but it doesn't return anything
image

Array out of range in DWX_ZeroMQ_Server_v2.0.1_RC8.mq4

I have been modified DWX_ZeroMQ_Server_v2.0.1_RC8.mq4 to be able to perform my strategy. My workflow as per below.

  1. The EA keep track on market. when something interesting occor it will execute python script.
  2. Python script connect to the same ports as setup in EA. then request the opened orders detail.
  3. Python script perform some task. then request the opened orders detail again to modify orders.
  4. After the order was modified the python script is terminated.
  5. The EA keep tracking the market again.

The problem is the EA may get request from somewhere ( default ports was used ). I don't know how. So these break the code as per attatched picture below.

err_msg
code

I am sure that this request didn't come from python script because EA status inform that it didn't execute the python script.

My question is :

  1. How this occur? and how to handle?
  2. When the EA get error as attatched picture, is it keep working or terminated?

Migration to MQL5

Hi everyone!
I would like to migrate the connector to MQL5 (dwx-zeromq-connector/v2.0.1/mql4/DWX_ZeroMQ_Server_v2.0.1_RC8.mq4) .. I'm willing to pay for.
Unfortunately, here in Brazil all the exchanges only work with MT5...

Thanks!

uninit reason 4 error

Hi,
Sometimes I receive this uninit reason 4 and don't know why:

2019.09.11 01:25:15.010 DWX_ZeroMQ_Server_v2.0.1_RC8 USDCHF,H1: [PUSH] Unbinding MT4 Server from Socket on Port 32769..
2019.09.11 01:25:15.008 DWX_ZeroMQ_Server_v2.0.1_RC8 USDCHF,H1: uninit reason 4

Any extra logs that I can get to try found out what is causing it? at the time that error appears I wan't doing nothing, the DWX_ZeroMQ_Server_v2.0.1_RC8.mq4 was just running

thanks

[RESOLVED] subscribe data has no response

Hello,
Thanks a lot for writing this amazing library.
I have tried to follow the tutorial, and I can successfully place and close orders through python spyder meaning python and MT4 are successfully connected. Yet when I tried to subscribe to market data there's no response. I've made sure it's not the verbose issue. I can also see clearly in the MT4 experts window the prices are publishing constantly.

_zmq.DWX_MTX_SUBSCRIBE_MARKETDATA(_symbol = 'EURUSD')
[KERNEL] Subscribed to EURUSD BID/ASK updates. See self._Market_Data_DB.

_zmq._Market_Data_DB.keys()
Out[44]: dict_keys([])

_zmq._Market_Data_DB
Out[45]: {}

image

Thanks for helping

Remote connecting to ec2 instance from local pc

Hi, i have a windows ec2 instance on AWS that is running an MT4 platform with the Darwinex Zeromq EA 24/7. I am trying to connect to it from my local computer. I have followed your instructions listed in your readme and if i try to run the python client from my computer (notably changing the _host variable in the DWX_ZeroMQ_Connector_v2_0_1_RC8.py file of the client to the ec2 IPv4 elastic public ip) it gives me the following error.

[INIT] Ready to send commands to METATRADER (PUSH): 32768
[INIT] Listening for responses from METATRADER (PULL): 32769
[INIT] Listening for market data from METATRADER (SUB): 32770
[EURUSD_Trader] Alright, here we go.. Gerrrronimooooooooooo! ..... xD

+--------------+

  • LIVE UPDATES +
    +--------------+

Resource timeout.. please try again. Failed to send commands

[EURUSD_Trader] {'_action': 'OPEN', '_type': 1, '_symbol': 'EURUSD', '_price': 0.0, '_SL': 100, '_TP': 100, '_comment': 'EURUSD_Trader', '_lots': 0.01, '_magic': 123456, '_ticket': 0} -> MetaTrader
None

However, if i run the same client on the ec2 instance itself, changing the same variable _host to 127.0.0.1, then it works fine and creates trades etc...
I am guessing that there is an issue with the connection to the ec2 instance. I have checked all the security groups for the instance that allow connections on all ports and IP's inbound and outbound. I am wondering if i need to change any other variables in the client or on the MT4 EA to allow remote connections not from a local computer.

Thanks for the help

IDEA "TELEGRAM + MT4 + dwx-zeromq-connector"

Hi,

Sorry for my English, I used the google translator

While studying FX, I found several channels / groups on telegram that offer signal services.

The problem is that the "signals" arrive between 00: 00-07: 00 AM (Local Time) where I am almost always sleeping.

As I had previously developed BOT for telegram, the idea of joining Telegram with this project was born.

Happy to receive ideas and collaborations in this thread.

SO = Ubuntu 18.04
RAM = 8GB

First I am testing with 2 signal channels, one sends the signal as text and another sends the signal with an image (pair) and text, which motivated me more to learn from Artificial Vision + Python> 3.

  • Sign only text.
EUR/CAD

SELL 1.4591

TP 1.4571
TP 1.4541
TP 1.4491
SL 1.4619
  • Image + text signal.
|------------------------------|
|         IMG(PAIR)            |
|------------------------------|

SELL 0.6320

TP 0.6300
TP 0.6270
TP 0.6220
SL 0.6370

*** After going through several iterations I have reached this, which is not working correctly ***

Now the entertaining part, the code

# -*- coding: utf-8 -*-

from DWX_ZeroMQ_Connector_v2_0_1_RC8 import *
import time
from telethon import TelegramClient, sync
from telethon import TelegramClient, events
from telethon import utils,functions, types
import sys
import zmq
import threading
import cv2
import os
import pytesseract

#*********************************************
api_id = 
api_hash =
phone = 
client = TelegramClient('phone.session', api_id, api_hash)
#**********************************************


def img_txt(img):
	try:
		image = cv2.imread(img)
		image = cv2.resize(image,(500,500))
		#xy1 xy2		Y			X
		crop_img = image[300:450, 60:450]
		text = pytesseract.image_to_string(crop_img)
		large = len(text)
		txt = text.split()
		#print(txt,len(txt))
		if(len(txt)==3):
			if(txt[0]=='GOLD'):
				txt[0]='XAU'
			os.remove(img)
			return(txt[0]+txt[2])
		else:
			print("Problem to convert imgtxt: ",txt)
	except Exception as e:
		print("ERROR : ",e)

# Lectura de msg telegram
@client.on(events.NewMessage())
async def orden_(event):

	# Order
	par   =''
	orde  =''
	n_orde=0
	be    =''
	slf   =''
	tp1   =''
	tp2   =''
	tp3   =''
	lt    =''
	msg   = ''

	## MetaTrader response (JSON):{'_action': 'EXECUTION', '_magic': 123456, '_ticket': 85051741, '_open_price': 1.14414, '_sl': 250, '_tp': 750}
	ordentst = {'_action': 'OPEN','_type': 0,'_symbol': 'EURUSD','_price': 0.0,'_SL': 0,'_TP': 0,'_comment': "Python-Bot",'_lots': 0,'_magic': 0,'_ticket': 0}

	try:

		#Channel ESP
		if(event.message.to_id.channel_id == IDCHANELSIGNAL):

			a  = event.raw_text.split()
			if(len(a)==11):

				par = a[0].replace("/","")
				orde  = a[1]
				be  = a[2]
				sl  = a[10]
				tp1 = a[4]
				tp2 = a[6]
				tp3 = a[8]
				lt1 = 0.03
				lt2 = 0.03
				lt3 = 0.02

				if(orde=="SELL"):
					n_orden = 1
					ordentst['_type']=n_orden

				ordentst['_symbol']=str(par)
				ordentst['_SL']=str(sl)

				for x in range(0,2):

					if x == 0:
						ordentst['_lots']=str(lt1)
						ordentst['_TP']=str(tp1)

					elif x ==1:
						ordentst['_lots']=str(lt2)
						ordentst['_TP']=str(tp3)

					#abrimos orden
					print("open order: ", ordentst)
					_zmq._DWX_MTX_NEW_TRADE_(_order=ordentst)
					time.sleep(2)
					rps = _zmq._thread_data_output#Capturamos rps
					print("RSP:",rps)
					time.sleep(3)

					try:

						if(rps==None):
							msg = "Error Order : "+str(a)
							print("No se envia msg")

						else:
							msg = "Orden Ok Ubuntu : "+str(par)+" ,"+str(orde)+" ,"+str(rps['_ticket'])
							print("Enviando msg")

					except Exception as e:
						print("Error:",e)

			else:
				pass

		
	except Exception as e:
		msg = "Error Orden :\n{}\n{}".format(str(event.raw_text),str(e))

#*********************************************
# main
if __name__ == '__main__':
    print("Init code")

    try:

        # Declarar el programador para consultar alertas
        print("Init Telegram")
        client.start()

        print("Init connector Python-MQL4")
        _zmq = DWX_ZeroMQ_Connector()
        time.sleep(0.5)

        print("Comienza el codigo")
        ################################################
        client.run_until_disconnected()

    except KeyboardInterrupt:
        print("Adios")
        #client.disconnect()

    except Exception as e:
        print("Error ",e)
        client.disconnect()

Example:

MSG:  GBP/CHF

BUY 1.2708

TP 1.2728
TP 1.2758
TP 1.2808
SL 1.2672
Open Order:  {'_action': 'OPEN', '_type': 0, '_symbol': 'GBPCHF', '_price': 0.0, '_SL': '1.2672', '_TP': '1.2728', '_comment': 'Python-Bot', '_lots': '0.03', '_magic': 0, '_ticket': 0}
('unexpected EOF while parsing', ('<string>', 1, 124, "{'_action': 'EXECUTION', '_magic': 0, '_ticket': 150955783, '_open_time': '2019.11.14 17:17:42', '_open_price': 1.27102000}}"))

Resource timeout.. please try again.

I can open and close trades but i cannot get open trades using _DWX_MTX_GET_ALL_OPEN_TRADES_ function i get the following error

Resource timeout.. please try again.

How can i fix this?

cannot capture every instrument

It tried to record every instrument of a broker called FXCM just to see if there is any arbitrage opportunity. (looks like there isn't)
I was able to record only 54 instruments out of 94. For me it looks like zeroqm cannot see CFDs like 'USB30YUSD' or "DAX-SEP19."
I can see that MT4 is publishing 'USB30YUSD' and it is also included in the Publish_Symbols[94] list in the mq4 file.
Is it possible that zeromq can only see instruments with 6 characters?

_get_response_ works intermittently

A piece of my python code:

ordine = {'_action': 'OPEN',
         '_type': 1,
         '_symbol': 'EURUSD',
         '_price':0.0,
         '_SL': 100,                     # 10 pips
         '_TP': 100,                     # 10 pips
         '_comment': 'EURUSD_Trader',
         '_lots': 0.01,
         '_magic': 123456}

a = DWX_ZMQ_Execution(_zmq)
a._execute_(ordine, _verbose=False)
sleep(5)
print("---------------")
a._execute_(ordine, _verbose=False)
sleep(5)
print("---------------")
a._execute_(ordine, _verbose=False)
sleep(5)
print("---------------")
a._execute_(ordine, _verbose=False)

Output:

{'_action': 'EXECUTION', '_magic': 123456, '_ticket': 229172741, '_open_time': '2019.11.18 23:29:40', '_open_price': 1.10721, '_sl': 1.10821, '_tp': 1.10621}
---------------
break
---------------
{'_action': 'EXECUTION', '_magic': 123456, '_ticket': 229172743, '_open_time': '2019.11.18 23:29:51', '_open_price': 1.10722, '_sl': 1.10822, '_tp': 1.10622}
---------------
break

print("break") is added by me in while loop before the real break here https://github.com/darwinex/dwx-zeromq-connector/blob/master/v2.0.1/python/examples/template/modules/DWX_ZMQ_Execution.py

Mt4 executes all the orders, but get_response works intermittently, once yes and once not. What could be the problem?

[SOLVED] Connecting from Python to MT4 server using ZeroMQ (Solution: initialize with _verbose=True)

@darwinex OK I will reply here and on youtube. I used the version of dwx_zermq_connector that you sent me and it didn't help. There are no logs on the MetaTrader side, everything is working as demonstrated in the github page. But there is no connection from the python side:

Python 3.6.7 |Anaconda, Inc.| (default, Dec 10 2018, 20:35:02) [MSC v.1915 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.

from DWX_ZeroMQ_Connector_v2_0_1_RC8 import DWX_ZeroMQ_Connector()
File "", line 1
from DWX_ZeroMQ_Connector_v2_0_1_RC8 import DWX_ZeroMQ_Connector()
^
SyntaxError: invalid syntax
from DWX_ZeroMQ_Connector_v2_0_1_RC8 import DWX_ZeroMQ_Connector
_zmq = DWX_ZeroMQ_Connector()
[INIT] Ready to send commands to METATRADER (PUSH): 32768
[INIT] Listening for responses from METATRADER (PULL): 32769
_zmq._generate_default_order_dict()
{'_action': 'OPEN', '_type': 0, '_symbol': 'EURUSD', '_price': 0.0, '_SL': 500, '_TP': 500, '_comment': 'DWX_Python_to_MT', '_lots': 0.01, '_magic': 123456, '_ticket': 0}
_zmq.DWX_MTX_GET_ALL_OPEN_TRADES()
print(_zmq.DWX_MTX_GET_ALL_OPEN_TRADES())
None

_zmq.DWX_MTX_GET_ALL_OPEN_TRADES()

As you can see it fails to check open positions. And I have a trade open, besides its supposed to return the json you received when you had no open positions. I did on spyder too and the result is no different. Thanks for your help.

Save output to a Python variable instead of printing on screen

Hi,

I was trying to record all open trades called by trades = _zmq._DWX_MTX_GET_ALL_OPEN_TRADES_()

However, the variable "trades" is a NoneType. Is there any way that I can store the output from the connector to a Python variable so that I can write it to csv, instead of printing on screen?

Thanks,
Frank

How to enable data I/O with _DWX_MTX_SEND_MARKETDATA_REQUEST_ ?

Hi there, first of all, thanks for the great project, secondly I'm not sure if I am the only one having this issue or not but when I called _zmq._DWX_MTX_SEND_MARKETDATA_REQUEST_() , noting is return to the ipython console, but for some reason I cannot request the market data. . In mt4 however this is printed in the Experts tab 2019.09.23 22:54:53.640 DWX_ZeroMQ_Server_v2.0.1_RC8 EURUSD,M1: DATA;EURUSD;1;2019.01.04 17:00:00;2019.09.23 22:52:00 . I can open orders, close orders......etc . Subscribing only works if I change Publish_MarketData in the EA from false to true
Please help. Cheers

Python version: 3.7.2
zmq version: 18.1.0
dwx-zeromq-connector version: 2.0.1
windows: 10

MT4 not publishing data

Hi, i have followed your setup instructions for installing the MT4 EA, however when i start it i am not seeing any publish data in the expert tab at the bottom, does this mean it is not publishing the data correctly?

Screenshot 2019-04-17 at 21 49 49

[RESOLVED] Socket Monitoring

hey
when I change monitor variable == true
I got result below:
[KERNEL] NO HANDSHAKE ON PUSH SOCKET.. Cannot SEND data
please help me to fix this error.

[OO-SCOPE] Error 129: Invalid Price (MetaTrader 4)

Good day

I don't mean to be a nuisance, I'm just following along with the video tutorial and I just run into issues as usual, when I'm programming. Usually I do my best to resolve these by myself. But this seems like it could be resolved quicker if i just ask.

I'm getting the following error when i try to place a trade using _price: '0.0' as per the instruction in the tut.. Can you please tell me why its saying im using an invalid price.

_Zmq._generate_default_order_dict()
Out[15]:
{'_action': 'OPEN',
'_type': 0,
'_symbol': 'EURUSD',
'_price': 0.0,
'_SL': 500,
'_TP': 500,
'_comment': 'DWX_Python_to_MT',
'_lots': 0.01,
'_magic': 123456,
'_ticket': 0}

_Zmq.DWX_MTX_NEW_TRADE()
{'_action': 'EXECUTION', '_response': '129', 'response_value': 'invalid price'}

[Socket Monitoring] How to deal with EVENT_CONNECT_DELAYED

Initializing the connector results in a PUSH socket EVENT_CONNET_DELAYED error. My ea works with the smiley face at the top right corner, but the pythons script is not connecting to the platform.

INPUT:
import zmq
from DWX_ZeroMQ_Connector_v2_0_1_RC8 import *

_zmq = DWX_ZeroMQ_Connector()
_zmq._verbose

OUTPUT:
[INIT] Ready to send commands to METATRADER (PUSH): 32768
[INIT] Listening for responses from METATRADER (PULL): 32769
[INIT] Listening for market data from METATRADER (SUB): 32770

[KERNEL] Retrieving ZeroMQ Monitor Event Names:

32 : EVENT_ACCEPTED
64 : EVENT_ACCEPT_FAILED
65535 : EVENT_ALL
16 : EVENT_BIND_FAILED
128 : EVENT_CLOSED
256 : EVENT_CLOSE_FAILED
1 : EVENT_CONNECTED
2 : EVENT_CONNECT_DELAYED
4 : EVENT_CONNECT_RETRIED
512 : EVENT_DISCONNECTED
16384 : EVENT_HANDSHAKE_FAILED_AUTH
2048 : EVENT_HANDSHAKE_FAILED_NO_DETAIL
8192 : EVENT_HANDSHAKE_FAILED_PROTOCOL
4096 : EVENT_HANDSHAKE_SUCCEEDED
8 : EVENT_LISTENING
1024 : EVENT_MONITOR_STOPPED

[KERNEL] Socket Monitoring Config -> DONE!

[PUSH Socket] >> EVENT_CONNECT_DELAYED[Finished in 1.0s]

Resource timeout.. please try again

I was due an update on my connector as MT4 stopped working with the old bridge version, I went to Github and got the new v2.0.1 mql4(last mth update) and python(2mths old) snippets and updated on my computer, I am using Python 3.6 on Spyder and MT4 Build 1220 (Sept2019), I also update libsodium and mql and zmq libraries in include and library just in case

I managed to establish the connection, however, the rate of updating of the Dictionary _Market_Data_DB went down considerably, whereas the expert tab on MT4 carries on bursting PUB Socket updates (1 update per second per ccy), the rate of build up of the dictionary on the Python side is much slower (for e.g. GBPUSD and GBPJPY get on 2 updates per minute ,AUDUSD 1 update per minute in the London mng? Before was one update every 1-3 secs)

I see there are some new features on the Python side a pool_timeout and sleep_delay, I don’t want to mess with it and brake it even more, if I can get some advice on what settings I can use to speed up the Market Data updates would be a great help as I use the spot from MT4 from Market_Data_DB as an input for the model and 2 quotes per minute is clearly not enough

Thanks in Advance!

Marcello

[SOLVED] MQL4 OrderModify Error 4112

Hello I have an unknown error when I try to modify a trade or create a trade, I can still get the json answer from all my trades but I don't have the possibility to send it. Do you have any leads so I can debug this error? Thank you in advance

[INIT] Ready to send commands to METATRADER (PUSH): 32768
[INIT] Listening for responses from METATRADER (PULL): 32769
[INIT] Listening for market data from METATRADER (SUB): 32770
{'_action': 'OPEN_TRADES', '_trades': {464727: {'_magic': 0, '_symbol': 'EURUSD.', '_lots': 0.01, '_type': 0, '_open_price': 1.12393, '_open_time': '2019.06.06 11:18:41', '_SL': 0.0, '_TP': 0.0, '_pnl': 0.01, '_comment': ''}}}

{'_action': 'MODIFY', '_response': '4112', '_response_value': 'unknown error', '_sl_attempted': 1.12193, '_tp_attempted': 1.12893}

[RESOLVED] "Resource timeout.. please try again.” notification

Hi,

I have just installed required server and client.

trades = 10
for _ in range(trades):
    _zmq._DWX_MTX_NEW_TRADE_()

the strange thing is, only second half of my orders are executed. If i set "trades" variable to 20, MT4 will open only 10 orders. If I set 2, only one order will be opened. This may help you to find the problem and possible solution.

I have not changed any default parameters. I have updated EA properties and changed Maximum orders to 10 and maximum lot size to 10.

_verbose is set to True. I can send orders anyway, the problem is totally different here.

NOTE: I have reinstalled VC++ reps. and after rebooting my PC, i am only getting this error message. Can not send any commands.

I have two more questions

  1. Can I ask how can i reach return values of following line? “tt” is None type and doesn’t return anything. It just prints results to console.

tt = _zmq._DWX_MTX_GET_ALL_OPEN_TRADES_()

  1. How can i get last 400 OHLC data?

Path issue

Hi, i am having an issue with the path in the coin_flip_trader script. i have set it to _path = '../../..' which should take me to the project root, however i am still getting an error when executing exec(open("coin_flip_traders_v1.0.py").read())

The error i get is

File "/Users/Al/Desktop/Trading/examples/template/strategies/base/DWX_ZMQ_Strategy.py", line 20, in
os.chdir(_path)
NameError: name '_path' is not defined

If i add a path to the DWX_ZMQ_STRATEGY.py like _path = '../../../..' i get the error

File "/Users/Al/Desktop/Trading/examples/template/strategies/base/DWX_ZMQ_Strategy.py", line 24, in
from api.DWX_ZeroMQ_Connector_v2_0_1_RC8 import DWX_ZeroMQ_Connector
ModuleNotFoundError: No module named 'api'

Not sure what i am doing wrong, i know it must have something to do with the path.

Thanks for your help

[RESOLVED] TP bug, when _TP is not 0, the order is closed immediately

Hi,

I came across an issue making me very confused. When using the DWX_MTX_NEW_TRADE() to place an order: {'_action': 'OPEN', '_type': 1, '_symbol': 'USDJPY', '_price': 0.0, '_SL': 0.0, '_TP': 10, '_comment': 'good luck', '_lots': 1, '_magic': 123456, '_ticket': 0}, the _msg, TRADE;OPEN;1;USDJPY;0.0;0.0;10;good luck;1;123456;0, is sent to MT4 server. Yes, the server received the messege, and placed the order, however, immediately it closed the order.

2019.07.04 00:05:00.544 DWX_ZeroMQ_Server_v2.0.1_RC8 USDJPY,M1: open #179916973 sell 1.00 USDJPY at 107.785 ok
2019.07.04 00:05:00.746 DWX_ZeroMQ_Server_v2.0.1_RC8 USDJPY,M1: close #179916973 sell 1.00 USDJPY at 107.785 at price 107.798

Then I tried when the _TP is 0, the order can be placed and kept there.

Could you please give me some help?

Thanks.

Xiangyi

New Trade SL and TP price values

Hi,

I need to open new trades passing SL and TP that are price values instead of points. There is any way of doing this?

I tried to pass it in DWX_MTX_NEW_TRADE but the values are not accepted, it's supposed to be only points from what I understood.

Thanks

EA not showing in MT5

Im putting the file in the experts folder, but it does not show up, and when I go to compile it it shows 100 errors when I change it to MQL5
image

[SOLVED] Connectivity between MQL4 EA and Python script

Hello, I cannot seem to get the ZMQ EA to perform basic tasks reliably or at all.

_zmq.DWX_MTX_GET_ALL_OPEN_TRADES()
responds with
“Resource timeout… please try again.”

If I subscribe:
_zmq.DWX_MTX_SUBSCRIBE_MARKETDATA(_symbol=‘EURUSD’)

it will tell me the Kernel subscribed but _zmq._Market_Data_DB.keys()
will respond with dict_keys([]), meaning there is no data for EURUSD.

I’ll get “KeyError: 'EURUSD” when I _zmq._Market_Data_DB[‘EURUSD’] eventhough it saids it is subscribed.

I am wondering whether I have this EA installed correctly or it is bugged.
When I go into the dependencies, I see a ton of red flags. I followed the instructions on the site to a T, dropping the Zml and Mql folders into Include as-is, putting libsodium.dll and libzmq.dll into the Libaries folder, and also installed pyzmq via pip install pyzmq in command line. The EA is in the experts folder and I did a %run for the .py file before running the commands in the Ipython shell.

Is there more that I need to do that is not mentioned on the instructions page that maybe perhaps they are just a given assumption for someone who is more experienced?

I am at a loss now as to how to make this work. I need this ZMQ EA to come to a place where I can trust it to work so I can continue developing my algorithm. The idea of binding Python to MT4 is extremely promising.

Thank you so much for your help and for your time.

dev branch

Instead of warning users to avoid using the latest version and creating a separate folder, why don't create a dev branch?

DWX_ZeroMQ_Server_v2.0.1_RC8.mq4 won't reply with more than 12 orders

I'm placing orders in EURUSD and once I send a 13th order it appears the MQL4 expert server stops replying to the python connector's request to get open orders.

DWX_ZeroMQ_Connector_v2_0_1_RC8.py prints None after a 13th order has been sent.

Is anyone else able to replicate?

[RESOLVED] Ubuntu + Python+ Wine + MT4 + dwx-zeromq-connector

Hello,

I am writing to tell you that I am happily using your in Linux development :D

I am currently using this function to ask for open orders and perform a moviemto of SL if applicable, but I have found it difficult to have the dictionary that returns printed on the whole screen, which is not useful for debugging the code since the I am storing in a variable.

I enclose function that I use.

def alarma():
    try:
        while 1:
            _zmq._DWX_MTX_GET_ALL_OPEN_TRADES_()
            orden_open = _zmq._thread_data_output#Capturamos rps
       
            if(orden_open==None):
                pass
            else:
                 print("Ordenes Abiertas:",len(orden_open['_trades'].keys()))
                 time.sleep(6)


    except Exception as e:
        print("Error al obtener toda la data: ",e)

Could you tell me what should I do so that this is not done?

Congratulations again

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.