### Get Open Trades in Python Source: https://github.com/darwinex/dwx-zeromq-connector/blob/master/README.md Retrieves a list of all currently open trades from MetaTrader using the DWX ZeroMQ Connector. The response is a JSON object detailing each trade's properties. ```python _zmq._DWX_MTX_OPEN_TRADES_() {'_action': 'OPEN_TRADES', '_trades': { 85052022: {'_magic': 123456, '_': 'EURUSD', '_': 0.05, '_': 0, '_': 1.14353, '_': 1.15}, 85052026: {'_magic': 123456, '_': 'EURUSD', '_': 0.05, '_': 0, '_': 1.14354, '_': 1.1}, 85052025: {'_magic': 123456, '_': 'EURUSD', '_': 0.05, '_': 0, '_': 1.14354, '_': 1.1}, 85052024: {'_magic': 123456, '_': 'EURUSD', '_': 0.05, '_': 0, '_': 1.14354, '_': 1.1}, 85052023: {'_magic': 123456, '_': 'EURUSD', '_': 0.05, '_': 0, '_': 1.14356, '_': 1} } } ``` -------------------------------- ### Close All Trades by Magic Number with DWX ZeroMQ Connector Source: https://github.com/darwinex/dwx-zeromq-connector/blob/master/README.md This example demonstrates how to close all open trades associated with a specific Magic Number in MetaTrader 4. Before executing this, it's useful to check the currently open trades to confirm which trades will be affected. ```python # 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_() ``` -------------------------------- ### Get Account Information using Python Source: https://context7.com/darwinex/dwx-zeromq-connector/llms.txt This snippet shows how to retrieve current account information, including balance, equity, profit, free margin, and leverage. It uses the DWX_ZeroMQ_Connector to send a request and requires a short delay for the response. The account information is then stored in the `account_info_DB` attribute and can be iterated through to extract specific details. ```python from api.DWX_ZeroMQ_Connector_v2_0_1_RC8 import DWX_ZeroMQ_Connector from time import sleep _zmq = DWX_ZeroMQ_Connector() # Request account information _zmq._DWX_MTX_GET_ACCOUNT_INFO_() # Wait for response sleep(0.5) # Access account information database account_info = _zmq.account_info_DB # Data structure: # { # 1234567: [{ # Account number as key # 'currenttime': '2020.01.15 14:30:25', # 'account_name': 'Trading Account', # 'account_balance': 10000.00, # 'account_equity': 10025.50, # 'account_profit': 25.50, # 'account_free_margin': 9800.00, # 'account_leverage': 100 # }] # } # Extract account details if account_info: for account_num, info_list in account_info.items(): for info in info_list: print(f"Balance: {info['account_balance']}") print(f"Equity: {info['account_equity']}") print(f"Free Margin: {info['account_free_margin']}") ``` -------------------------------- ### Subscribe to Real-Time Market Data in Python Source: https://context7.com/darwinex/dwx-zeromq-connector/llms.txt Subscribes to real-time BID/ASK price feeds for specified currency pairs and instruments. It also sends a request to MT4 to start publishing price data and allows access to market data via a database. Supports subscribing, unsubscribing, and unsubscribing from all symbols. ```python from api.DWX_ZeroMQ_Connector_v2_0_1_RC8 import DWX_ZeroMQ_Connector from time import sleep _zmq = DWX_ZeroMQ_Connector(_verbose=True) # Subscribe to EURUSD market data _zmq._DWX_MTX_SUBSCRIBE_MARKETDATA_('EURUSD') # Tell MT4 to start publishing price data _zmq._DWX_MTX_SEND_TRACKPRICES_REQUEST_(['EURUSD']) # Wait for data to accumulate sleep(5) # Access the market data database market_data = _zmq._Market_Data_DB # Output example: # [KERNEL] Subscribed to EURUSD BID/ASK updates. See self._Market_Data_DB. # {'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) # }} # Subscribe to multiple symbols _zmq._DWX_MTX_SUBSCRIBE_MARKETDATA_('GBPUSD') _zmq._DWX_MTX_SEND_TRACKPRICES_REQUEST_(['EURUSD', 'GBPUSD']) # Unsubscribe from specific symbol _zmq._DWX_MTX_UNSUBSCRIBE_MARKETDATA_('EURUSD') # Unsubscribe from all symbols _zmq._DWX_MTX_UNSUBSCRIBE_ALL_MARKETDATA_REQUESTS_() ``` -------------------------------- ### Partially Close a Trade by Ticket with DWX ZeroMQ Connector Source: https://github.com/darwinex/dwx-zeromq-connector/blob/master/README.md This example demonstrates how to partially close a trade in MetaTrader 4 by specifying the trade's ticket ID and the number of lots to close. After a partial close, the ticket ID may change, so it's recommended to retrieve all open trades again to get the updated ticket. ```python _zmq._DWX_MTX_CLOSE_PARTIAL_BY_TICKET_(85051741, 0.01) # Partially closing a trade renews the ticket ID, retrieve it again. _zmq._DWX_MTX_GET_ALL_OPEN_TRADES_() ``` -------------------------------- ### Subscribe to Real-Time Market Data Source: https://context7.com/darwinex/dwx-zeromq-connector/llms.txt Subscribes to real-time BID/ASK price feeds for specified currency pairs and instruments. It also includes methods to start publishing prices, access market data, and unsubscribe. ```APIDOC ## Subscribe to Real-Time Market Data ### Description Subscribe to BID/ASK price feeds for currency pairs and instruments. Includes functionality to start price tracking, access stored data, and manage subscriptions. ### Methods - **_DWX_MTX_SUBSCRIBE_MARKETDATA_(symbol)** - **_DWX_MTX_SEND_TRACKPRICES_REQUEST_(symbols_list)** - **_DWX_MTX_UNSUBSCRIBE_MARKETDATA_(symbol)** - **_DWX_MTX_UNSUBSCRIBE_ALL_MARKETDATA_REQUESTS_()** ### Parameters #### `_DWX_MTX_SUBSCRIBE_MARKETDATA_(symbol)` - **symbol** (string) - The trading symbol (e.g., 'EURUSD') to subscribe to. #### `_DWX_MTX_SEND_TRACKPRICES_REQUEST_(symbols_list)` - **symbols_list** (list of strings) - A list of trading symbols for which to request price updates. #### `_DWX_MTX_UNSUBSCRIBE_MARKETDATA_(symbol)` - **symbol** (string) - The trading symbol to unsubscribe from. #### `_DWX_MTX_UNSUBSCRIBE_ALL_MARKETDATA_REQUESTS_()` - No parameters. ### Accessing Market Data - **_Market_Data_DB** (dictionary) - A dictionary containing the latest market data. The structure is `{symbol: {timestamp: (bid, ask), ...}}`. ### Request Example (Subscribe and Track) ```python from api.DWX_ZeroMQ_Connector_v2_0_1_RC8 import DWX_ZeroMQ_Connector from time import sleep _zmq = DWX_ZeroMQ_Connector(_verbose=True) # Subscribe to EURUSD market data _zmq._DWX_MTX_SUBSCRIBE_MARKETDATA_('EURUSD') # Tell MT4 to start publishing price data _zmq._DWX_MTX_SEND_TRACKPRICES_REQUEST_(['EURUSD']) # Wait for data to accumulate sleep(5) # Access the market data database market_data = _zmq._Market_Data_DB print(market_data) ``` ### Response Example (Market Data) ```json { "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] } } ``` ### Request Example (Multiple Symbols and Unsubscribe) ```python # Subscribe to multiple symbols _zmq._DWX_MTX_SUBSCRIBE_MARKETDATA_('GBPUSD') _zmq._DWX_MTX_SEND_TRACKPRICES_REQUEST_(['EURUSD', 'GBPUSD']) # Unsubscribe from specific symbol _zmq._DWX_MTX_UNSUBSCRIBE_MARKETDATA_('EURUSD') # Unsubscribe from all symbols _zmq._DWX_MTX_UNSUBSCRIBE_ALL_MARKETDATA_REQUESTS_() ``` ``` -------------------------------- ### Get All Open Trades using DWX ZeroMQ Connector Source: https://context7.com/darwinex/dwx-zeromq-connector/llms.txt Retrieves information about all currently open positions from MetaTrader. It includes a delay to wait for the response and then iterates through the trades to print details like ticket, symbol, and P&L. ```python from api.DWX_ZeroMQ_Connector_v2_0_1_RC8 import DWX_ZeroMQ_Connector from time import sleep _zmq = DWX_ZeroMQ_Connector() # Request open trades _zmq._DWX_MTX_GET_ALL_OPEN_TRADES_() # Wait for response sleep(0.5) # MetaTrader response: # { # '_action': 'OPEN_TRADES', # '_trades': { # 85051741: { # '_magic': 123456, # '_symbol': 'EURUSD', # '_lots': 0.05, # '_type': 0, # '_open_price': 1.14414, # '_pnl': -0.45 # }, # 85051856: { # '_magic': 123456, # '_symbol': 'GBPUSD', # '_lots': 0.1, # '_type': 1, # '_open_price': 1.30125, # '_pnl': 2.35 # } # } # } # Access trade data response = _zmq._get_response_() if response and '_trades' in response: for ticket, trade_info in response['_trades'].items(): print(f"Ticket: {ticket}, Symbol: {trade_info['_symbol']}, P&L: {trade_info['_pnl']}") ``` -------------------------------- ### Initialize DWX ZeroMQ Connector Source: https://github.com/darwinex/dwx-zeromq-connector/blob/master/README.md This code initializes the DWX ZeroMQ Connector by creating an instance of the `DWX_ZeroMQ_Connector` class. This instance is then used to interact with MetaTrader 4. ```python _zmq = DWX_ZeroMQ_Connector() ``` -------------------------------- ### Open and Close All Trades in Python Source: https://github.com/darwinex/dwx-zeromq-connector/blob/master/README.md Illustrates the process of opening multiple trades and then closing all of them using the DWX ZeroMQ Connector. It shows the sequence of opening trades and the subsequent response when all trades are closed. ```python # 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', '_': 123456, '_': 1.1537, '_': 0.01, '_': 'CLOSE_MARKET'}, 85090926: {'_symbol': 'EURUSD', '_': 123456, '_': 1.1537, '_': 0.01, '_': 'CLOSE_MARKET'}, 85090922: {'_symbol': 'EURUSD', '_': 123456, '_': 1.1537, '_': 0.01, '_': 'CLOSE_MARKET'}, 85090921: {'_symbol': 'EURUSD', '_': 123456, '_': 1.15369, '_': 0.01, '_': 'CLOSE_MARKET'}, 85090920: {'_symbol': 'EURUSD', '_': 123456, '_': 1.15369, '_': 0.01, '_': 'CLOSE_MARKET'}}, '_response_value': 'SUCCESS'} ``` -------------------------------- ### Subscribe to Market Data with DWX ZeroMQ Connector Source: https://github.com/darwinex/dwx-zeromq-connector/blob/master/README.md This snippet demonstrates how to subscribe to real-time bid/ask prices for a specific symbol (e.g., EURUSD) using the DWX ZeroMQ Connector. It includes subscribing to the data feed and then requesting MetaTrader to publish that data. The received data is stored in `self._Market_Data_DB`. Unsubscribing is also shown. ```python _zmq._DWX_MTX_SUBSCRIBE_MARKETDATA_('EURUSD') _zmq._DWX_MTX_SEND_TRACKPRICES_REQUEST_(['EURUSD']) # BID/ASK prices are now being streamed into _zmq._Market_Data_DB. # _zmq._Market_Data_DB _zmq._DWX_MTX_UNSUBSCRIBE_MARKETDATA('EURUSD') ``` -------------------------------- ### Construct and Send a Trade Order with DWX ZeroMQ Connector Source: https://github.com/darwinex/dwx-zeromq-connector/blob/master/README.md This snippet shows how to construct a default trade order dictionary using the DWX ZeroMQ Connector and then modify its parameters such as lots, stop loss, take profit, and comment. Finally, it sends the constructed trade order to MetaTrader 4 for execution. ```python _my_trade = _zmq._generate_default_order_dict() _my_trade['_lots'] = 0.05 _my_trade['_SL'] = 250 _my_trade['_TP'] = 750 _my_trade['_comment'] = 'nerds_rox0r' _zmq._DWX_MTX_NEW_TRADE_(_order=_my_trade) ``` -------------------------------- ### Initialize and Use DWX ZeroMQ Connector Source: https://context7.com/darwinex/dwx-zeromq-connector/llms.txt Demonstrates how to initialize the DWX ZeroMQ Connector with custom data handlers, subscribe to market data, send a price request, open a new trade, and finally shut down the connector. This covers the basic workflow for interacting with MT4 through the connector. ```python from api.DWX_ZeroMQ_Connector_v2_0_1_RC8 import DWX_ZeroMQ_Connector from time import sleep # Define custom handlers (assuming MyPullDataHandler and MySubDataHandler are defined elsewhere) # pull_handler = MyPullDataHandler() # sub_handler = MySubDataHandler() # Initialize connector with custom handlers _zmq = DWX_ZeroMQ_Connector( _pulldata_handlers=[pull_handler], _subdata_handlers=[sub_handler], _verbose=False ) # Subscribe to market data _zmq._DWX_MTX_SUBSCRIBE_MARKETDATA_('EURUSD') _zmq._DWX_MTX_SEND_TRACKPRICES_REQUEST_(['EURUSD']) # Open a trade to trigger pull handler order = _zmq._generate_default_order_dict() _zmq._DWX_MTX_NEW_TRADE_(_order=order) # Let handlers process data sleep(10) # Cleanup _zmq._DWX_ZMQ_SHUTDOWN_() ``` -------------------------------- ### Build Multi-Threaded Trading Strategy with DWX ZeroMQ Connector Source: https://context7.com/darwinex/dwx-zeromq-connector/llms.txt This Python code demonstrates how to create a multi-threaded trading strategy. It initializes the DWX ZeroMQ Connector, subscribes to market data, and launches individual trading threads for each symbol. The strategy includes basic logic to open trades if none exist and handles stopping the strategy gracefully. Dependencies include the DWX_ZeroMQ_Connector and custom execution modules. ```python from api.DWX_ZeroMQ_Connector_v2_0_1_RC8 import DWX_ZeroMQ_Connector from examples.template.modules.DWX_ZMQ_Execution import DWX_ZMQ_Execution from examples.template.modules.DWX_ZMQ_Reporting import DWX_ZMQ_Reporting from threading import Thread, Lock from time import sleep import random class MyTradingStrategy: def __init__(self, symbols=[('EURUSD', 0.01), ('GBPUSD', 0.01)]): self._symbols = symbols self._active = True self._lock = Lock() # Initialize connector with custom handlers self._zmq = DWX_ZeroMQ_Connector( _ClientID='my-strategy', _pulldata_handlers=[], _subdata_handlers=[], _verbose=False ) # Initialize execution and reporting modules self._execution = DWX_ZMQ_Execution(self._zmq) def run(self): """Start the trading strategy""" # Subscribe to market data for all symbols for symbol, _ in self._symbols: self._zmq._DWX_MTX_SUBSCRIBE_MARKETDATA_(symbol) symbol_list = [s[0] for s in self._symbols] self._zmq._DWX_MTX_SEND_TRACKPRICES_REQUEST_(symbol_list) # Launch trading thread for each symbol traders = [] for symbol_info in self._symbols: t = Thread(target=self._trade_symbol, args=(symbol_info,)) t.daemon = True t.start() traders.append(t) # Keep strategy running try: while self._active: sleep(1) except KeyboardInterrupt: self.stop() def _trade_symbol(self, symbol_info): """Trading logic for individual symbol""" symbol, lot_size = symbol_info while self._active: try: self._lock.acquire() # Get current open trades self._zmq._DWX_MTX_GET_ALL_OPEN_TRADES_() sleep(0.1) response = self._zmq._get_response_() # Simple logic: open trade if none exist if response and '_trades' in response: open_trades = [t for t in response['_trades'].values() if t['_symbol'] == symbol] if len(open_trades) == 0: # Create order order = self._zmq._generate_default_order_dict() order['_symbol'] = symbol order['_lots'] = lot_size order['_type'] = random.randint(0, 1) # Random BUY/SELL order['_SL'] = 250 order['_TP'] = 500 # Execute trade self._execution._execute_( order, _verbose=True, _delay=0.1, _wbreak=10 ) finally: self._lock.release() sleep(5) # Wait between checks def stop(self): """Stop strategy and close all positions""" self._active = False self._zmq._DWX_MTX_CLOSE_ALL_TRADES_() self._zmq._DWX_MTX_UNSUBSCRIBE_ALL_MARKETDATA_REQUESTS_() self._zmq._DWX_ZMQ_SHUTDOWN_() # Run the strategy if __name__ == "__main__": strategy = MyTradingStrategy(symbols=[('EURUSD', 0.01)]) strategy.run() ``` -------------------------------- ### Place Buy and Sell Orders using DWX ZeroMQ Connector Source: https://context7.com/darwinex/dwx-zeromq-connector/llms.txt Demonstrates how to customize order parameters like lots, stop loss, take profit, and comment before sending a new trade to MetaTrader. It also shows how to place both buy and sell orders. ```python # Customize order parameters _my_trade['_lots'] = 0.05 _my_trade['_SL'] = 250 _my_trade['_TP'] = 750 _my_trade['_comment'] = 'my_strategy_v1' _my_trade['_type'] = 0 # OP_BUY # Send trade to MetaTrader _zmq._DWX_MTX_NEW_TRADE_(_order=_my_trade) # MetaTrader response: # { # '_action': 'EXECUTION', # '_magic': 123456, # '_ticket': 85051741, # '_open_price': 1.14414, # '_sl': 250, # '_tp': 750 # } # Open SELL order _sell_trade = _zmq._generate_default_order_dict() _sell_trade['_type'] = 1 # OP_SELL _sell_trade['_symbol'] = 'GBPUSD' _sell_trade['_lots'] = 0.1 _zmq._DWX_MTX_NEW_TRADE_(_order=_sell_trade) ``` -------------------------------- ### Initialize ZeroMQ Connector in Python Source: https://context7.com/darwinex/dwx-zeromq-connector/llms.txt Initializes the DWX ZeroMQ Connector for communication between Python and MetaTrader 4. Allows configuration of client ID, host, protocol, ports, verbosity, and timeouts. Default settings are used if no custom configuration is provided. ```python from api.DWX_ZeroMQ_Connector_v2_0_1_RC8 import DWX_ZeroMQ_Connector # Initialize with default settings _zmq = DWX_ZeroMQ_Connector() # Initialize with custom configuration _zmq = DWX_ZeroMQ_Connector( _ClientID='my-trading-bot', _host='localhost', _protocol='tcp', _PUSH_PORT=32768, _PULL_PORT=32769, _SUB_PORT=32770, _verbose=True, _poll_timeout=1000, _sleep_delay=0.001 ) # 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 ``` -------------------------------- ### Open New Trade Order in Python Source: https://context7.com/darwinex/dwx-zeromq-connector/llms.txt Generates a default order template dictionary for executing market orders in MetaTrader 4. This template includes parameters such as order type, symbol, price, stop loss, take profit, comment, lot size, and magic number. It serves as a base for defining trade parameters. ```python from api.DWX_ZeroMQ_Connector_v2_0_1_RC8 import DWX_ZeroMQ_Connector _zmq = DWX_ZeroMQ_Connector() # Generate default order template _my_trade = _zmq._generate_default_order_dict() # Default template structure: # { # '_action': 'OPEN', # '_type': 0, # 0=BUY, 1=SELL, 2=BUY_LIMIT, 3=SELL_LIMIT, 4=BUY_STOP, 5=SELL_STOP # '_symbol': 'EURUSD', # '_price': 0.0, # 0.0 for market orders # '_SL': 500, # Stop Loss in POINTS # '_TP': 500, # Take Profit in POINTS # '_comment': 'DWX_Python_to_MT', # '_lots': 0.01, # '_magic': 123456, # '_ticket': 0 # } ``` -------------------------------- ### Initialize ZeroMQ Connector Source: https://context7.com/darwinex/dwx-zeromq-connector/llms.txt Initializes the ZeroMQ Connector to establish a connection between Python and MetaTrader 4. It supports default settings or custom configurations for client ID, host, protocol, port numbers, verbosity, and timeouts. ```APIDOC ## Initialize ZeroMQ Connector ### Description Create and configure the connection between Python and MetaTrader 4. ### Method `DWX_ZeroMQ_Connector()` ### Parameters #### Initialization Parameters - **_ClientID** (string) - Optional - A unique identifier for the trading client. - **_host** (string) - Optional - The hostname or IP address of the MetaTrader 4 server. Defaults to 'localhost'. - **_protocol** (string) - Optional - The network protocol to use (e.g., 'tcp'). Defaults to 'tcp'. - **_PUSH_PORT** (integer) - Optional - The port for sending commands to MetaTrader 4. Defaults to 32768. - **_PULL_PORT** (integer) - Optional - The port for receiving responses from MetaTrader 4. Defaults to 32769. - **_SUB_PORT** (integer) - Optional - The port for subscribing to market data. Defaults to 32770. - **_verbose** (boolean) - Optional - If True, enables verbose logging output. Defaults to False. - **_poll_timeout** (integer) - Optional - The timeout in milliseconds for polling ZeroMQ sockets. Defaults to 1000. - **_sleep_delay** (float) - Optional - A small delay in seconds to prevent busy-waiting. Defaults to 0.001. ### Request Example (Default) ```python from api.DWX_ZeroMQ_Connector_v2_0_1_RC8 import DWX_ZeroMQ_Connector _zmq = DWX_ZeroMQ_Connector() ``` ### Request Example (Custom) ```python from api.DWX_ZeroMQ_Connector_v2_0_1_RC8 import DWX_ZeroMQ_Connector _zmq = DWX_ZeroMQ_Connector( _ClientID='my-trading-bot', _host='localhost', _protocol='tcp', _PUSH_PORT=32768, _PULL_PORT=32769, _SUB_PORT=32770, _verbose=True, _poll_timeout=1000, _sleep_delay=0.001 ) ``` ### Output Example ``` [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 ``` ``` -------------------------------- ### Retrieve All Open Trades from MetaTrader using DWX ZeroMQ Connector Source: https://github.com/darwinex/dwx-zeromq-connector/blob/master/README.md This code retrieves a list of all currently open trades from MetaTrader 4 using the DWX ZeroMQ Connector. The response is a dictionary where keys are trade ticket IDs and values contain trade details like magic number, symbol, lots, type, open price, and profit/loss. ```python _zmq._DWX_MTX_GET_ALL_OPEN_TRADES_() ``` -------------------------------- ### Implement Custom Data Handlers for DWX ZeroMQ Connector Source: https://context7.com/darwinex/dwx-zeromq-connector/llms.txt These Python classes show how to implement custom handlers for processing data received on the PULL and SUB ports of the DWX ZeroMQ Connector. `MyPullDataHandler` processes trade execution and closure events, while `MySubDataHandler` processes incoming market data. These handlers allow for real-time responses to trading events and market updates. They require the `DWX_ZeroMQ_Connector` library. ```python from api.DWX_ZeroMQ_Connector_v2_0_1_RC8 import DWX_ZeroMQ_Connector from time import sleep class MyPullDataHandler: """Handler for processing PULL port data (trade responses)""" def onPullData(self, data): """Called when data received on PULL port""" if '_action' in data: if data['_action'] == 'EXECUTION': print(f"Trade executed: Ticket {data['_ticket']} at {data['_open_price']}") elif data['_action'] == 'CLOSE': print(f"Trade closed: Ticket {data['_ticket']} at {data['_close_price']}") elif data['_action'] == 'OPEN_TRADES': print(f"Open trades count: {len(data['_trades'])}") class MySubDataHandler: """Handler for processing SUB port data (market data)""" def onSubData(self, data): """Called when market data received on SUB port""" topic, msg = data.split(":|:") print(f"Market update - {topic}: {msg}") ``` -------------------------------- ### General Command Sending Function Source: https://github.com/darwinex/dwx-zeromq-connector/blob/master/README.md A versatile function for sending various trading commands through the ZeroMQ interface. DWX_MTX_SEND_COMMAND_ can be used for a wide range of actions, including order placement and modification, by specifying the action type, symbol, price, and other relevant trade parameters. ```python DWX_MTX_SEND_COMMAND_(self, _action, _type, _symbol, _price, _SL, _TP, _comment, _lots, _magic, _ticket) ``` -------------------------------- ### Trade Data Retrieval Functions Source: https://github.com/darwinex/dwx-zeromq-connector/blob/master/README.md Functions for retrieving information about current trading activities. DWX_MTX_GET_ALL_OPEN_TRADES_ retrieves all currently open trades, providing insight into the trading book. The generate_default_order_dict and generate_default_data_dict functions assist in creating default data structures for orders and general data. ```python DWX_MTX_GET_ALL_OPEN_TRADES_(self) generate_default_order_dict(self) generate_default_data_dict(self) ``` -------------------------------- ### Open a New Trade Source: https://context7.com/darwinex/dwx-zeromq-connector/llms.txt Provides functionality to open new trades by generating a default order dictionary template and allowing customization of trade parameters. ```APIDOC ## Open a New Trade ### Description Execute market orders with customizable parameters. This method allows for generating a default order template and modifying its fields before sending the trade execution request. ### Method `_generate_default_order_dict()` ### Parameters This method does not take direct parameters but returns a dictionary template that needs to be populated. ### Default Order Template Structure ```json { "_action": "OPEN", # Action type: "OPEN", "CLOSE", "MODIFY" "_type": 0, # Order type: 0=BUY, 1=SELL, 2=BUY_LIMIT, 3=SELL_LIMIT, 4=BUY_STOP, 5=SELL_STOP "_symbol": "EURUSD", # Trading symbol "_price": 0.0, # Order price (0.0 for market orders) "_SL": 500, # Stop Loss in POINTS "_TP": 500, # Take Profit in POINTS "_comment": "DWX_Python_to_MT", # Order comment "_lots": 0.01, # Trade volume in lots "_magic": 123456, # Magic number for the order "_ticket": 0 # Ticket number (usually 0 for new orders) } ``` ### Request Example ```python from api.DWX_ZeroMQ_Connector_v2_0_1_RC8 import DWX_ZeroMQ_Connector _zmq = DWX_ZeroMQ_Connector() # Generate default order template _my_trade = _zmq._generate_default_order_dict() # Customize the trade _my_trade['_symbol'] = 'GBPUSD' _my_trade['_lots'] = 0.1 _my_trade['_SL'] = 300 _my_trade['_TP'] = 600 # To send the order, you would typically use another method like _DWX_MTX_SEND_TRADE_REQUEST_() # _zmq._DWX_MTX_SEND_TRADE_REQUEST_(_my_trade) ``` ``` -------------------------------- ### Market Data Request Functions Source: https://github.com/darwinex/dwx-zeromq-connector/blob/master/README.md Enables requesting historical and real-time market data for specific financial instruments. DWX_MTX_SEND_MARKETDATA_REQUEST_ allows fetching data within a specified date range and timeframe. DWX_MTX_SUBSCRIBE_MARKETDATA_ initiates a subscription to receive live market data for a symbol. ```python DWX_MTX_SEND_MARKETDATA_REQUEST_(self, _symbol, _timeframe, _start, _end) DWX_MTX_SUBSCRIBE_MARKETDATA_(self, _symbol, _string_delimiter=';') ``` -------------------------------- ### Market Data Subscription Management Functions Source: https://github.com/darwinex/dwx-zeromq-connector/blob/master/README.md Functions to manage market data subscriptions. DWX_MTX_UNSUBSCRIBE_MARKETDATA_ allows unsubscribing from a specific symbol's market data feed, while DWX_MTX_UNSUBSCRIBE_ALL_MARKETDATA_REQUESTS_ cancels all active market data subscriptions. ```python DWX_MTX_UNSUBSCRIBE_MARKETDATA_(self, _symbol) DWX_MTX_UNSUBSCRIBE_ALL_MARKETDATA_REQUESTS_(self) ``` -------------------------------- ### Trade Management Functions Source: https://github.com/darwinex/dwx-zeromq-connector/blob/master/README.md Provides functions to create, modify, and close trading positions. These functions interact with the trading terminal via the ZeroMQ interface. They require specific order or ticket details and may involve parameters like stop loss, take profit, and lot sizes. ```python DWX_MTX_NEW_TRADE_(self, _order=None) DWX_MTX_MODIFY_TRADE_BY_TICKET_(self, _ticket, _SL, _TP) DWX_MTX_CLOSE_TRADE_BY_TICKET_(self, _ticket) DWX_MTX_CLOSE_PARTIAL_BY_TICKET_(self, _ticket, _lots) DWX_MTX_CLOSE_TRADES_BY_MAGIC_(self, _magic) DWX_MTX_CLOSE_ALL_TRADES_(self) ``` -------------------------------- ### Proper Shutdown and Cleanup of DWX ZeroMQ Connector Source: https://context7.com/darwinex/dwx-zeromq-connector/llms.txt Provides multiple methods for safely shutting down the DWX ZeroMQ Connector and cleaning up resources. This includes direct instance shutdown, a global cleanup function, and pausing/resuming operations by changing the connector's status. Proper cleanup prevents resource leaks and ensures a stable trading environment. ```python from api.DWX_ZeroMQ_Connector_v2_0_1_RC8 import DWX_ZeroMQ_Connector, _DWX_ZMQ_CLEANUP_ # Method 1: Shutdown specific instance _zmq = DWX_ZeroMQ_Connector() # ... trading operations ... # Properly shutdown _zmq._DWX_ZMQ_SHUTDOWN_() # Expected Output: # ++ [KERNEL] Sockets unregistered from ZMQ Poller()! # ++ [KERNEL] ZeroMQ Context Terminated.. shut down safely complete! :) # Method 2: Cleanup before reinitializing _DWX_ZMQ_CLEANUP_() # This checks for any existing connector instances and shuts them down # before creating a new one _zmq = DWX_ZeroMQ_Connector() # Method 3: Set status to pause operations _zmq._setStatus(_new_status=False) # Pause # ... do something ... _zmq._setStatus(_new_status=True) # Resume ``` -------------------------------- ### Close Trades by Magic Number in Python Source: https://github.com/darwinex/dwx-zeromq-connector/blob/master/README.md Demonstrates how to close all open trades associated with a specific magic number using the DWX ZeroMQ Connector. This function sends a command to MetaTrader to close trades and processes the JSON response. ```python _zmq._DWX_MTX_CLOSE_TRADES_BY_MAGIC_(123456) {'_action': 'CLOSE_ALL_MAGIC', '_magic': 123456, '_responses': { 85052026: {'_symbol': 'EURUSD', '_': 1.14375, '_': 0.05, '_': 'CLOSE_MARKET'}, 85052025: {'_symbol': 'EURUSD', '_': 1.14375, '_': 0.05, '_': 'CLOSE_MARKET'}, 85052024: {'_symbol': 'EURUSD', '_': 1.14375, '_': 0.05, '_': 'CLOSE_MARKET'}, 85052023: {'_symbol': 'EURUSD', '_': 1.14375, '_': 0.05, '_': 'CLOSE_MARKET'}, 85052022: {'_symbol': 'EURUSD', '_': 1.14375, '_': 0.05, '_': 'CLOSE_MARKET'}}, '_response_value': 'SUCCESS'} ``` -------------------------------- ### Close a Trade by Ticket with DWX ZeroMQ Connector Source: https://github.com/darwinex/dwx-zeromq-connector/blob/master/README.md This code snippet shows how to close an entire trade in MetaTrader 4 by providing its unique ticket ID to the `_DWX_MTX_CLOSE_TRADE_BY_TICKET_` function of the DWX ZeroMQ Connector. The response indicates the success of the market closure. ```python _zmq._DWX_MTX_CLOSE_TRADE_BY_TICKET_(85051856) ``` -------------------------------- ### Request Historical Data using Python Source: https://context7.com/darwinex/dwx-zeromq-connector/llms.txt This snippet shows how to request historical Open, High, Low, Close (OHLC) candlestick data for a specified symbol and timeframe. It utilizes the DWX_ZeroMQ_Connector and requires a sleep interval to allow for data retrieval. The historical data is then accessible via the `_History_DB` attribute and is structured as a dictionary where keys are symbols and values are lists of candlestick data. ```python from api.DWX_ZeroMQ_Connector_v2_0_1_RC8 import DWX_ZeroMQ_Connector from pandas import Timestamp from time import sleep _zmq = DWX_ZeroMQ_Connector() # Request historical data _zmq._DWX_MTX_SEND_HIST_REQUEST_( _symbol='EURUSD', _timeframe=1440, # 1440 = Daily, 60 = H1, 15 = M15, 1 = M1 _start='2020.01.01 00:00:00', _end='2020.12.31 23:59:00' ) # Wait for data sleep(2) # Access historical data hist_data = _zmq._History_DB # Data structure: # { # 'EURUSD': [ # { # 'time': 1577836800, # 'open': 1.12145, # 'high': 1.12234, # 'low': 1.12089, # 'close': 1.12201, # 'tick_volume': 45632, # 'spread': 12, # 'real_volume': 0 # }, # ... # ] # } # Request multiple timeframes _zmq._DWX_MTX_SEND_HIST_REQUEST_(_symbol='GBPUSD', _timeframe=60) _zmq._DWX_MTX_SEND_HIST_REQUEST_(_symbol='USDJPY', _timeframe=15) ``` -------------------------------- ### Close All Open Trades using Python Source: https://context7.com/darwinex/dwx-zeromq-connector/llms.txt This snippet demonstrates how to close all open trades using the DWX_ZeroMQ_Connector. It requires an active ZeroMQ connection and sends a command to the MetaTrader terminal to close all positions. The response indicates the success or failure of the operation and details for each closed trade. ```python from api.DWX_ZeroMQ_Connector_v2_0_1_RC8 import DWX_ZeroMQ_Connector _zmq = DWX_ZeroMQ_Connector() # Close ALL open trades _zmq._DWX_MTX_CLOSE_ALL_TRADES_() # MetaTrader response: # { # '_action': 'CLOSE_ALL', # '_responses': { # 85090927: { # '_symbol': 'EURUSD', # '_magic': 123456, # '_close_price': 1.1537, # '_close_lots': 0.01, # '_response': 'CLOSE_MARKET' # }, # 85090926: { # '_symbol': 'GBPUSD', # '_magic': 789012, # '_close_price': 1.30125, # '_close_lots': 0.1, # '_response': 'CLOSE_MARKET' # } # }, # '_response_value': 'SUCCESS' # } ``` -------------------------------- ### Subscribe to OHLC Rate Data in Python Source: https://context7.com/darwinex/dwx-zeromq-connector/llms.txt Subscribes to candlestick/bar data (OHLC) for specified instruments and timeframes. It configures the subscription and sends a request to MT4 to track these rates. The OHLC data is then accessible via the market data database. ```python from api.DWX_ZeroMQ_Connector_v2_0_1_RC8 import DWX_ZeroMQ_Connector from time import sleep _zmq = DWX_ZeroMQ_Connector(_verbose=True) # Subscribe to EURUSD M1 and GDAXI M5 rates instruments = [ ('EURUSD_M1', 'EURUSD', 1), # 1-minute bars ('GDAXI_M5', 'GDAXI', 5) # 5-minute bars ] for instrument in instruments: _zmq._DWX_MTX_SUBSCRIBE_MARKETDATA_(instrument[0]) _zmq._DWX_MTX_SEND_TRACKRATES_REQUEST_(instruments) sleep(10) # Access OHLC data rates_data = _zmq._Market_Data_DB # Output format: # {'EURUSD_M1': { # '2019-01-08 13:46:52.283107': (1578484012, 1.14394, 1.14395, 1.14392, 1.14394, 15, 2, 0) # }} # Format: (timestamp, open, high, low, close, tick_volume, spread, real_volume) ``` -------------------------------- ### Subscribe to OHLC Rate Data Source: https://context7.com/darwinex/dwx-zeromq-connector/llms.txt Subscribes to candlestick/bar data (OHLC) for specified instruments and timeframes. It allows for multiple subscriptions and provides access to the OHLC data. ```APIDOC ## Subscribe to OHLC Rate Data ### Description Subscribe to candlestick/bar data with specified timeframes. This method allows for subscribing to multiple instruments and timeframes simultaneously. ### Method `_DWX_MTX_SEND_TRACKRATES_REQUEST_(instruments_list)` ### Parameters #### `instruments_list` (list of tuples) Each tuple represents an instrument subscription and should contain: - **Subscription Name** (string): A unique name for the subscription (e.g., 'EURUSD_M1'). - **Symbol** (string): The trading symbol (e.g., 'EURUSD'). - **Timeframe** (integer): The timeframe in minutes (e.g., 1 for M1, 5 for M5, 15 for M15, 30 for M30, 60 for H1, 240 for H4, 1440 for D1, 10080 for W1, 43200 for MN1). ### Accessing OHLC Data - **_Market_Data_DB** (dictionary) - The same dictionary used for market data, but populated with OHLC data when `_DWX_MTX_SEND_TRACKRATES_REQUEST_` is used. The structure is `{subscription_name: {timestamp: (timestamp, open, high, low, close, tick_volume, spread, real_volume), ...}}`. ### Request Example ```python from api.DWX_ZeroMQ_Connector_v2_0_1_RC8 import DWX_ZeroMQ_Connector from time import sleep _zmq = DWX_ZeroMQ_Connector(_verbose=True) # Subscribe to EURUSD M1 and GDAXI M5 rates instruments = [ ('EURUSD_M1', 'EURUSD', 1), # 1-minute bars ('GDAXI_M5', 'GDAXI', 5) # 5-minute bars ] for instrument in instruments: _zmq._DWX_MTX_SUBSCRIBE_MARKETDATA_(instrument[0]) # Subscribe first _zmq._DWX_MTX_SEND_TRACKRATES_REQUEST_(instruments) sleep(10) # Access OHLC data rates_data = _zmq._Market_Data_DB print(rates_data) ``` ### Response Example (OHLC Data) ```json { "EURUSD_M1": { "2019-01-08 13:46:52.283107": [1578484012, 1.14394, 1.14395, 1.14392, 1.14394, 15, 2, 0] } } ``` ### Data Format for OHLC Each entry in the OHLC data is a tuple: `(timestamp, open, high, low, close, tick_volume, spread, real_volume)` ``` -------------------------------- ### Modify Trade Stop Loss and Take Profit using DWX ZeroMQ Connector Source: https://context7.com/darwinex/dwx-zeromq-connector/llms.txt Updates the Stop Loss (SL) and Take Profit (TP) levels for an existing trade identified by its ticket number. The function can accept SL and TP in points and optionally a price level for pending orders. ```python from api.DWX_ZeroMQ_Connector_v2_0_1_RC8 import DWX_ZeroMQ_Connector _zmq = DWX_ZeroMQ_Connector() # Modify trade by ticket number ticket_number = 85051741 new_sl = 300 # New Stop Loss in POINTS new_tp = 600 # New Take Profit in POINTS _zmq._DWX_MTX_MODIFY_TRADE_BY_TICKET_(ticket_number, new_sl, new_tp) # For pending orders, specify price level _zmq._DWX_MTX_MODIFY_TRADE_BY_TICKET_( _ticket=85051741, _SL=300, _TP=600, _price=1.14500 # Price for pending order ) # MetaTrader response: # { # '_action': 'MODIFY', # '_ticket': 85051741, # '_sl': 300, # '_tp': 600, # '_response_value': 'SUCCESS' # } ```