DWX Connect

repository·main·Indexed 42 days ago

https://github.com/darwinex/dwxconnect

A multi-language bridge that links custom trading strategies written in Python, Java, or C# to the Darwinex trading platform via MetaTrader 4 (MT4) or MetaTrader 5 (MT5). It enables developers to subscribe to tick and bar data, request historical data and trades, and execute or manage orders using a file-based communication mechanism.

Tokens
4.6K
Snippets
14
Records
22
Agent score
53%

What's inside DWX Connect

  1. Overview of DWX_Connect

    main

    DWX_Connect is a multi-language connector designed to link trading strategies to MetaTrader 4 (MT4) or MetaTrader 5 (MT5). It provides a simple, file-based communication mechanism that allows developers to interact with MT4/MT5 platforms using Python, Java, or C#.

    Key capabilities include:

    • Subscribing to tick data.
    • Subscribing to bar data.
    • Executing trades on MT4 or MT5.
  2. Use event handlers in DWX Connect

    main

    When using the DWX Connect client (e.g., by extending the example client), you can implement callback functions to react to real-time data and messages from MetaTrader:

    • on_tick(symbol, bid, ask): Triggered on every change in bid/ask prices.
    • on_bar_data(symbol, time_frame, time, open_price, high, low, close_price, tick_volume): Triggered when new bar data is registered.
    • on_historic_data(symbol, time_frame, data): Triggered after a historic data request is fulfilled.
    • on_historic_trades(): Triggered after a historic trades request is fulfilled. Access data via self.dwx.historic_trades.
    • on_message(message): Triggered on new messages from MetaTrader. message is a dict with type ('INFO' or 'ERROR'). Errors include error_type and description.
  3. Access stored market and account information

    main

    The DWX client maintains several dictionaries that provide direct access to the current state of the account and market. You can access these via the client instance (e.g., self.dwx):

    • open_orders: Dictionary of open orders, keyed by order ticket.
    • account_info: Account details (name, number, equity, balance, leverage, free margin).
    • market_data: Current bid/ask prices for all subscribed symbols and the tick value.
    • bar_data: Latest bar data for subscribed symbols.
    • historic_data: Latest historic data (updated only after a request).
    • historic_trades: Requested trade history (updated only after a request).
  4. Compile and Run the DWX_Connect Java Example

    main

    Once the environment is configured, use the following commands to compile and execute the Java client. Note that the compilation command relies on a sources.txt file and a libs/ directory containing necessary dependencies.

    Important: If you rename DWXExampleClient.java, you must also update the class name inside the file and the corresponding entry in sources.txt.

    # Compile the project
    javac -cp ".;libs/*" "@sources.txt"
    
    # Run the example client
    java -cp ".;libs/*" DWXExampleClient
  5. Install and set up DWX Connect

    main

    DWX Connect links trading strategies to Darwinex via MetaTrader 4 or 5. Follow these steps to set up the environment:

    1. Download the repository from GitHub.
    2. Install the MetaTrader Server EA:
      • Download dwx_server_mt4.mq4 (for MT4) or dwx_server_mt5.mq5 (for MT5).
      • Copy the file into your MT4/MT5 data folder under /MQL4/Experts or /MQL5/Experts.
      • Open the file in MetaEditor and press F7 to compile it.
      • Restart MetaTrader or refresh the Navigator window, then attach the EA to a chart.
    3. Configure the Python side:
      • Copy the python/ folder to your working directory.
      • Open dwx_client_example.py and update the MT4_files_dir variable to point to your MetaTrader /MQL4/Files or /MQL5/Files directory.
        • Windows example: C:/Users/<username>/AppData/Roaming/MetaQuotes/Terminal/.../MQL4/Files
        • macOS example: /Users/<username>/Library/Application Support/MetaTrader 4/Bottles/metatrader4/drive_c/Program Files/MetaTrader 4/MQL4/Files
        • Linux example: /home/<username>/.wine/drive_c/Program Files (x86)/Darwinex MT4/MQL4/Files
    4. Run the example:
      python dwx_client_example.py

    Warning: Use a Darwinex demo account for testing. Do not run test scripts on a live account.

    python dwx_client_example.py
  6. Set up DWX_Connect for Java

    main

    To use DWX_Connect with Java, you must first configure the MetaTrader (MT4/MT5) side by installing the Server EA, and then set up your Java environment.

    1. MetaTrader Configuration

    1. Download the DWX_Connect repository.
    2. Copy the server EA (DWX_Server_MT4.mq4 for MT4 or DWX_Server_MT5.mq5 for MT5) into your MT4/MT5 data folder under /MQL4/Experts or /MQL5/Experts.
    3. Open the EA in MetaEditor and press F7 to compile it.
    4. Restart MetaTrader or refresh the Navigator window.
    5. Attach the EA to a chart. You can adjust input parameters like MaximumOrders and MaximumLotSize in the EA settings.

    2. Java Environment Setup

    1. Ensure the Java Development Kit (JDK) is installed and added to your system PATH.
    2. Copy the contents of the java/ directory from the DWX_Connect repository into your local working directory.
    3. Use DWXExampleClient.java as a template for your own trading algorithm.
  7. Setup DWX_Connect for C#

    main

    To use DWX_Connect with C#, follow these steps to configure both the MetaTrader server and your local development environment:

    1. Configure MetaTrader (MT4/MT5)

    1. Download the DWX_Connect source code from GitHub.
    2. Locate the server EA file (DWX_Server_MT4.mq4 for MT4 or DWX_Server_MT5.mq5 for MT5).
    3. Copy the EA file into your MetaTrader data folder under /MQL4/Experts or /MQL5/Experts.
    4. Open the file in MetaEditor, compile it by pressing F7, and then refresh your Navigator window in MT4/MT5.
    5. Attach the EA to a chart. You can adjust input parameters such as MaximumOrders and MaximumLotSize within the EA settings.

    2. Configure C# Environment

    1. Copy the contents of the dotnet/DWX_Connect directory into your project's working directory.
    2. Use DWXExampleClient.cs as a template for your custom trading algorithm.
    3. Build and run the application using the .NET CLI.
    # Build the project
    dotnet build
    
    # Run the application
    dotnet run
  8. Configure the MetaTrader Server EA (MQL side)

    main

    The MetaTrader Server EA (MT4/MT5) can be customized via input parameters. The most critical ones for trading are MaximumOrders and MaximumLotSize.

    ParameterDescription
    MILLISECOND_TIMERInterval (ms) the EA checks for new prices and order changes.
    numLastMessagesNumber of messages stored in the message file (used for debug/feedback).
    openChartsForBarDataIf true, opens charts for subscribed symbol/timeframe combos to force faster data updates.
    openChartsForHistoricDataIf true, opens charts for requested historic data symbols.
    MaximumOrdersMaximum number of orders allowed. If exceeded, new orders from Python will return an error.
    MaximumLotSizeMaximum lot size allowed for a single order.
    SlippagePointsValue used in OrderSend(). Usually ignored by brokers but available for completeness.
    lotSizeDigitsDigits to which lot size is rounded (default is 2 for Forex).
  9. Configure the Python client side

    main

    The Python client has several configuration parameters to control communication and behavior:

    ParameterDescription
    sleep_delayTime interval (seconds) the Python side checks files. Default is 0.005 (5ms).
    max_retry_command_secondsPeriod in which the Python side retries sending a command if the file is busy.
    load_orders_from_fileIf true, loads orders from a file on initialization. If false, it triggers on_order_event() after a restart if orders are open.
    verboseIf true, prints more debug information.
  10. Initialize the Client for MT4/MT5 communication

    main

    The Client class is the primary entry point for communicating with MetaTrader 4 or 5. To instantiate it, you must provide an EventHandler to handle incoming data events, the directory path where MetaTrader is installed, and several configuration parameters for timing and reliability.

    Constructor Parameters:

    • EventHandler eventHandler: An implementation of the EventHandler interface to receive callbacks (e.g., onTick, onOrderEvent).
    • String MetaTraderDirPath: The local filesystem path to the MetaTrader installation directory.
    • int sleepDelay: Delay in milliseconds between file checks.
    • int maxRetryCommandSeconds: Maximum time in seconds to retry sending a command if the command files are currently being processed by MetaTrader.
    • boolean loadOrdersFromFile: If true, the client will attempt to load existing orders from DWX_Orders_Stored.txt to maintain state across restarts.
    • boolean verbose: If true, enables detailed logging to the console.
    // Example initialization
    EventHandler myHandler = new MyEventHandler();
    Client client = new Client(myHandler, "C:/Program Files/MetaTrader 5", 100, 5, true, true);
  11. Initialize the DWXConnect Client

    main

    To interact with MT4/MT5, instantiate the Client class. The constructor requires an EventHandler to receive updates, the path to your MetaTrader directory, and several configuration parameters for polling and retries.

    Constructor Parameters:

    • eventHandler: An instance of EventHandler to handle incoming data events.
    • MetaTraderDirPath: The directory where MetaTrader is installed (must exist).
    • sleepDelay: Time in milliseconds to wait between file checks.
    • maxRetryCommandSeconds: Maximum time to retry sending a command if the command files are busy.
    • loadOrdersFromFile: Boolean; if true, the client will attempt to reload existing orders from DWX_Orders_Stored.txt upon startup.
    • verbose: Boolean; if true, enables detailed logging of order changes.
    // Example initialization
    Client client = new Client(myEventHandler, "C:\Program Files\MetaTrader 5", 100, 5, true, true);
  12. Subscribe to market data

    main

    Use the following methods to subscribe to data streams:

    • subscribe_symbols(symbols): Subscribes to tick data.
      • Example: symbols = ['EURUSD', 'GBPUSD']
    • subscribe_symbols_bar_data(symbols): Subscribes to bar data for specific symbol/timeframe combinations.
      • Example: symbols = [['EURUSD', 'M15'], ['GBPUSD', 'H4']]
    • get_historic_data(symbol, time_frame, start, end): Requests historic bar data using start and end timestamps.
    # Example subscriptions
    dwx.subscribe_symbols(['EURUSD', 'GBPUSD'])
    dwx.subscribe_symbols_bar_data([['EURUSD', 'M15'], ['GBPUSD', 'H4']])