darwinex / dwx-zeromq-connector

Wrapper library for algorithmic trading in Python 3, providing DMA/STP access to Darwinex liquidity via a ZeroMQ-enabled MetaTrader Bridge EA.
https://blog.darwinex.com/zeromq-interface-python-r-metatrader4/
BSD 3-Clause "New" or "Revised" License
341 stars 227 forks source link

how do we know the order is tped or sled #114

Closed ZixiSu closed 2 years ago

ZixiSu commented 3 years ago

Hi team,

After one order reached the tp point, in the comment it will show, for example, EURUSD_Trader[tp], how can I let my python code know this order is just tped as I need to restore the info into my external database.

elvinex commented 3 years ago

Hi, True, this information can be important. I haven't tested it live, but there should be a '_comment' field in the open order dictionary, which you could check for containing '[tp]' or '[sl]'.

ZixiSu commented 3 years ago

Thank you, but we need to check closed orders, since after tp, the comment will show [tp]

elvinex commented 3 years ago

Right, my mistake. Sorry, there is no option to get historic trades at the moment. You would have to write an own function to request the historic trades, similar to the historic data function.

ZixiSu commented 3 years ago

Thank you, trying now, if it is possible, may you provide some sample code

ZixiSu commented 3 years ago

I have a question regarding compArray[0], as it is closed trade, which is not TRADE or DATA: This one is added DWX_ZeroMQ_COnnector_v2_0_1_RC8.py

    from pandas import DataFrame, Timestamp
    import datetime
    def _SEND_CLOSED_TRADES_(self,
                             _symbol = 'EURUSD',
                             _comment='[tp]',
                             _timeframe = 1,
                             _end = Timestamp.now(),
                             _two_minute = datetime.timedelta(minutes=2),
                             ):
        _start = _end - _two_minute
        _msg = "{};{};{};{};{}".format('CLOSED_TRADE', _comment, _timeframe, _start, _end)
        self.remote_send(self._PUSH_SOCKET, _msg)

And based on DWX_ZMQ_Strategy.py:

# Append path for main project folder
import sys
sys.path.append('../../..')

# Import ZMQ-Strategy from relative path
from base.DWX_ZMQ_Strategy import DWX_ZMQ_Strategy

#############################################################################
# Other required imports
#############################################################################

import os
from pandas import Timedelta, to_datetime, Timestamp
from threading import Thread, Lock
from time import sleep
import random
import datetime

class get_closed_trades(DWX_ZMQ_Strategy):

    def __init__(self,
                 _name="Closed_Trade",
                 _delay=0.1,
                 _broker_gmt=2,
                 _verbose=False):
        # call DWX_ZMQ_Strategy constructor and passes itself as data processor for handling
        # received data on PULL and SUB ports
        super().__init__(_name,
                         [],  # Empty symbol list (not needed for this example)
                         _broker_gmt,
                         [self],  # Registers itself as handler of pull data via self.onPullData()
                         [self],  # Registers itself as handler of sub data via self.onSubData()
                         _verbose)

        # This strategy's variables
        self._delay = _delay
        self._verbose = _verbose
        self._finished = False

    ##########################################################################
    def isFinished(self):
        """ Check if execution finished"""
        return self._finished

    def onPullData(self, data):
        """
        Callback to process new data received through the PULL port
        """
        # print responses to request commands
        print('Historic from ExpertAdvisor={}'.format(data))

    def onSubData(self, data):
        """
        Callback to process new data received through the SUB port
        """
        # split msg to get topic and message
        _topic, _msg = data.split(" ")
        print('Data on Topic={} with Message={}'.format(_topic, _msg))

    ##########################################################################
    def run(self):
        """
        Request historic data
        """
        self._finished = False

        # request rates
        print('Requesting Closed trades from EURUSD')
        self._zmq._SEND_CLOSED_TRADES_(_symbol='EURUSD',
                                       _comment='[tp]',
                                       _timeframe=1,
                                       _end= Timestamp.now(),
                                       _two_minute = datetime.timedelta(minutes=2),
                                       )
        sleep(1)
        print(self._zmq._History_DB)

if __name__ == "__main__":
    print('Loading example...')
    example = get_closed_trades()
    print('unning example...')
    example.run()

no error, but not solve the problem, really need sample code help.

Loading 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
unning example...
Requesting Closed trades from EURUSD
{}

Process finished with exit code 0
elvinex commented 2 years ago

In the meantime we published a new package, which includes a function get_historic_trades(lookback_days): https://github.com/darwinex/dwxconnect Once the data arrives on the python side, it will trigger the on_historic_trades() function of the tick processor. To start best copy the example tick processor: https://github.com/darwinex/dwxconnect/blob/main/python/examples/dwx_client_example.py