使用 MQL API 打开和关闭交易

问题描述

我的问题是如何使用下面的代码打开和关闭有条件的交易?例如如果满足某些条件,如 RSI 或移动平均线,我们调用函数 (open_Trade) 方法自动执行,以及如何使用 (close_Trade) 方法关闭同一交易以在 4 小时蜡烛后关闭.

代码如下:

import MetaTrader5 as mt5


ea_magic_number = 9986989 # if you want to give every bot a unique identifier

def get_info(symbol):
    '''https://www.mql5.com/en/docs/integration/python_MetaTrader5/mt5symbolinfo_py
    '''
    # get symbol properties
    info=mt5.symbol_info(symbol)
    return info

def open_Trade(action,symbol,lot,sl_points,tp_points,deviation):
    '''https://www.mql5.com/en/docs/integration/python_MetaTrader5/mt5ordersend_py
    '''
    # prepare the buy request structure
    symbol_info = get_info(symbol)

    if action == 'buy':
        Trade_type = mt5.ORDER_TYPE_BUY
        price = mt5.symbol_info_tick(symbol).ask
    elif action =='sell':
        Trade_type = mt5.ORDER_TYPE_SELL
        price = mt5.symbol_info_tick(symbol).bid
    point = mt5.symbol_info(symbol).point

    buy_request = {
        "action": mt5.TradE_ACTION_DEAL,"symbol": symbol,"volume": lot,"type": Trade_type,"price": price,"sl": price - sl_points * point,"tp": price + tp_points * point,"deviation": deviation,"magic": ea_magic_number,"comment": "sent by python","type_time": mt5.ORDER_TIME_GTC,# good till cancelled
        "type_filling": mt5.ORDER_FILLING_RETURN,}
    # send a Trading request
    result = mt5.order_send(buy_request)
    return result,buy_request

def close_Trade(action,buy_request,result,deviation):
    '''https://www.mql5.com/en/docs/integration/python_MetaTrader5/mt5ordersend_py
    '''
    # create a close request
    symbol = buy_request['symbol']
    if action == 'buy':
        Trade_type = mt5.ORDER_TYPE_BUY
        price = mt5.symbol_info_tick(symbol).ask
    elif action =='sell':
        Trade_type = mt5.ORDER_TYPE_SELL
        price = mt5.symbol_info_tick(symbol).bid
    position_id=result.order
    lot = buy_request['volume']

    close_request={
        "action": mt5.TradE_ACTION_DEAL,"position": position_id,"comment": "python script close",}
    # send a close request
    result=mt5.order_send(close_request)


# This is how I would execute the order
result,buy_request = open_Trade('buy','USDJPY',0.1,50,10)
close_Trade('sell',10)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)