TheSnowGuru / PyTrader-python-mt4-mt5-trading-api-connector-drag-n-drop

Open Source Trading Strategies & End-to-End solution connecting Metatrader4 & Metatrader5 💹 with Python with a simple drag and drop EA. Fully tested bug free & efficient solution for live & paper trading⭐ Full Documentation ready. Lightweight, efficient and stable implementation 🔥
https://discord.gg/wRMUNP8ERa
653 stars 11 forks source link

Suggest to use pandas capabilities #11

Closed rkahun closed 3 years ago

rkahun commented 3 years ago

First of all, thanks for your effort. I'd like to suggest using of pandas data reading capabilities rather than using loops. What do you think of something like this? Cheers

--

import io

TZ_SERVER = 'Europe/Tallinn' # EET
TZ_LOCAL  = 'Europe/Budapest'
TZ_UTC    = 'UTC'

# get all open positions
ok, resp = MT.send_command("F061#0#")
if ok==True and resp[0:5]=="F061#" and resp[-1]=="!":
    df = pd.read_table(io.StringIO(resp[resp.index('#',5)+1:-1]), sep='$', lineterminator='#',
                       header=None,
                       names=np.array(MT.columnsOpenPositions[1:])[:,0],
                       dtype=MT.columnsOpenPositions[1:]
    ).fillna('')
    df.open_time = pd.to_datetime(df.open_time, unit='s').dt.tz_localize(TZ_SERVER).dt.tz_convert(TZ_UTC)
else:
    pass
Branly76 commented 3 years ago

@rhahun,

Hi i will have a look at it. Python is a new language for me. So it is a discovery all the time. Python is very different from all the languages I did in the last 40 years.

BR

Branly76 commented 3 years ago

Appreciated.

BR

rkahun commented 3 years ago

In this case I give a bit more universal, although not optimized example. BTW I like your code. ;) Cheers

updated:

import sys

commands = {
    'get_open_orders':      ('F060#', 'columnsOpenOrders', 'open_time'),
    'get_open_positions':   ('F061#', 'columnsOpenPositions', 'open_time'),
    'get_deleted_orders':   ('F065#', 'columnsDeletedOrders', 'delete_time'),
    'get_closed_positions': ('F063#', 'columnsClosedPositions', 'close_time'),
}   

def get_table(command, cols, field, tz=TZ_UTC, **kwargs):
    ok, resp = MT.send_command(command)
    if ok==True and resp[0:5]==command[0:5] and resp[-1]=="!":

        t0 = datetime(1970,1,1)
        t1 = datetime.now()
        if 'date_from' in kwargs.keys():
            t0 = kwargs['date_from']
        if 'date_to' in kwargs.keys():
            t1 = kwargs['date_to']

        df = pd.read_table(io.StringIO(resp[resp.index('#',5)+1:-1]), sep='$', lineterminator='#',
                           header=None,
                           names=np.array(getattr(MT,cols)[1:])[:,0],
                           dtype=getattr(MT, cols)[1:]
        ).fillna('')
        df.index.name = getattr(MT,cols)[0][0]
        for f in df.columns[df.columns.str.contains('_time')]:
            df[f] = pd.to_datetime(df[f], unit='s').dt.tz_localize(TZ_SERVER).dt.tz_convert(tz)
        filter = ((df[field] >= t0.astimezone()) & (df[field] <= t1.astimezone()))
        df = df.loc[filter]
    else:
        df = None

    return df

def get_open_orders(**kwargs):
    command, cols, field = commands[sys._getframe().f_code.co_name]
    df = get_table(command, cols, field, **kwargs)
    return df

def get_deleted_orders(**kwargs):
    command, cols, field = commands[sys._getframe().f_code.co_name]
    df = get_table(command, cols, field, **kwargs)
    return df

def get_open_positions(**kwargs):
    command, cols, field = commands[sys._getframe().f_code.co_name]
    df = get_table(command, cols, field, **kwargs)
    return df

def get_closed_positions(**kwargs):
    command, cols, field = commands[sys._getframe().f_code.co_name]
    df = get_table(command, cols, field, **kwargs)
    return df

display(
    get_open_orders(tz=TZ_LOCAL,
                    date_from=(datetime.now()+timedelta(seconds=-86400)).astimezone(),
                    date_to  =(datetime.now()+timedelta(seconds=-8000)).astimezone()),
    get_deleted_orders(tz=TZ_LOCAL, date_from=(datetime.now()+timedelta(days=-2)).astimezone()),
    get_open_positions(tz=TZ_SERVER),
    get_closed_positions(),
    get_open_orders(),
)
rkahun commented 3 years ago

I see, you've revised it. Cheers