MetaTrader 5 Python用户组 - 如何在Metatrader中使用Python - 页 66

 
Vladimir Karputov:

当时的价格(买入价和卖出价)是多少?冻结水平是多少(SYMBOL_TRADE_FREEZE_LEVEL)?

对FREEZE水平不确定?

我的买入价使用的是卖出价,而我的卖出价使用的是空头。

我现在已经尝试对我的sl和tp进行硬编码。

只是奇怪的是,它将买入和卖出完美的几个小时,然后停止。

price_ask = mt5.symbol_info_tick(symbol).ask # Buying    

####################

##cONDITION FOR buy

if close_past < close_current and position_type(symbol) != 0 or position_type(symbol) == None:
        mt5.Close(symbol)
        buy(symbol, lot, price_ask, point, digits)
        print('{} LONG Postition bought!'.format(symbol))

####################

##### Function to BUY
def buy(symbol, lot, price, point, digits):
    request_buy = {
        "action": mt5.TRADE_ACTION_DEAL,
        "symbol": symbol,
        "volume": lot,
        "type": mt5.ORDER_TYPE_BUY,
        "price": round(price, digits),
        "sl": round((price - 100 * point),digits),
        "tp": round((price + 300 * point),digits),
        "magic": 234000,
        "comment": "{} Buy.".format(symbol),
        "type_time": mt5.ORDER_TIME_GTC,
        }
    # send a trading request
    result_buy = mt5.order_send(request_buy)
    # check the execution result
    print("1.BUY order send(): by {} {} lots at {}".format(symbol,lot,price));
    if result_buy.retcode != mt5.TRADE_RETCODE_DONE:
        print("2. order_send failed, retcode={}".format(result_buy.retcode))
        # request the result as a dictionary and display it element by element
        result_dict=result_buy._asdict()
        for field in result_dict.keys():
            print("   {}={}".format(field,result_dict[field]))
            # if this is a trading request structure, display it element by element as well
            if field=="request":
                traderequest_dict=result_dict[field]._asdict()
                for tradereq_filed in traderequest_dict:
                    print("       traderequest: {}={}".format(tradereq_filed,traderequest_dict[tradereq_filed]))
    else:
        return result_buy
#########
 
nicholi shen:

仍然写道。

如果r.retcode != TRADE_RETCODE_REQUOTE 和 r.retcode != TRADE_RETCODE_PRICE_OFF:
AttributeError: 'NoneType' 对象没有属性 'retcode'



我在我的函数中使用了一个例子,并写道。

如果 result_buy.retcode != mt5.TRADE_RETCODE_DONE:
AttributeError: 'NoneType' object has no attribute 'retcode' 。

 
IvanDorofeev:

它仍然写道。

帮助中的例子是有效的。

应用我函数中的例子,它说。

如果result_buy.retcode != mt5.TRADE_RETCODE_DONE:
AttributeError: 'NoneType' object has no attribute 'retcode'

所以你得到result_buy==None,没有检查值,并试图从None获得retcode?

 

新的MT5终端测试版和MetaTrader5 5.0.31只能维持大约7700次对copy_rates_from_pos() 的调用,然后它就会完全锁住线程。为了证明这个错误,我使用asyncio实现了一个超时。超时在控件上起作用,然而,它对copy_rates_from_pos不起作用,因为线程由于这个错误而完全冻结了。

import asyncio
import time

import MetaTrader5 as mt5


async def proof_timeout_works_on_blocking_call():
    loop = asyncio.get_running_loop()
    future = loop.run_in_executor(None, time.sleep, 5.0)
    try:
        await asyncio.wait_for(future, timeout=0.5)
    except asyncio.TimeoutError:
        print("Timeout works as expected for blocking calls!")


async def async_copy_rates(*args, timeout):
    loop = asyncio.get_running_loop()
    future = loop.run_in_executor(None, mt5.copy_rates_from_pos, *args)
    try:
        return await asyncio.wait_for(future, timeout=timeout)
    except asyncio.TimeoutError:
        print(f"async_copy_rates timed out")
        print('mql errors =', *mt5.last_error())
        raise


async def async_last_error():
    loop = asyncio.get_running_loop()
    err = await loop.run_in_executor(None, mt5.last_error)
    return err


async def main():
    await proof_timeout_works_on_blocking_call()
    maxbars = mt5.terminal_info().maxbars
    for i in range(1, maxbars):
        r = await async_copy_rates('EURUSD', mt5.TIMEFRAME_M1, 0, i, timeout=0.5)
        if r is not None:
            print(f'{i} -> {len(r)}')


if __name__ == '__main__':
    mt5.initialize()
    print(mt5.__version__)
    asyncio.run(main())
    mt5.shutdown()
 

即使关闭并重新初始化连接也没有帮助。

import time

import MetaTrader5 as mt5


def main():
    maxbars = mt5.terminal_info().maxbars
    for i, count in enumerate(range(1000, maxbars), 1):
        for retry in range(5):
            r = mt5.copy_rates_from_pos('EURUSD', mt5.TIMEFRAME_M1, 0, count)
            errno, strerr = mt5.last_error()
            if errno != mt5.RES_S_OK:
                print(strerr)
                print('Reinitialing connection')
                mt5.shutdown()
                time.sleep(1)
                print('Reinitialing connection =', mt5.initialize())
            else:
                print(f"{i} -> {len(r)}")
                break
        else:
            print('maxium retry exceed')
            mt5.shutdown()
            quit()


if __name__ == '__main__':
    mt5.initialize()
    print(mt5.__version__)
    main()
    mt5.shutdown()
 
nicholi shen:

在复制率方面有一个错误。我发了好几次这个帖子,但没有人承认它。

for count in range(maxbars):
    rates = mt5.copy_rates_from_pos('EURUSD', mt5.TIMEFRAME_M1, 0, count)
    errno, strerror = mt5.last_error()
    if errno != mt5.RES_S_OK:
        print(f"Failed on count={count} with strerror={strerror}")
        break

问题:这个周期是为了什么?

 
Vladimir Perervenko:

问题:为什么是这个周期?

我在请求将maxbars作为 "count "参数时遇到了失败,所以我写了一个简单的例程,在每次迭代时增加请求的条数,作为一个单元测试来测试该函数。这应该可以顺利完成,但考虑到你只能调用有限的次数,这使得它不可靠。

 
nicholi shen:

我在请求将maxbars作为 "count "参数时遇到了失败,所以我写了一个简单的例程,在每次迭代时增加请求的条数,作为测试函数 的单元测试。 这应该可以顺利完成,但考虑到你只能调用有限的次数,所以它不可靠。

这个问题在5.0.33中得到了修复,它在发布时没有自动释放numpy数组。
 
IvanDorofeev:

仍然写道。

如果r.retcode != TRADE_RETCODE_REQUOTE 和 r.retcode != TRADE_RETCODE_PRICE_OFF:
AttributeError: 'NoneType' 对象没有属性 'retcode'



在我的函数中应用一个例子,它说

如果 result_buy.retcode != mt5.TRADE_RETCODE_DONE:
AttributeError: 'NoneType' object has no attribute 'retcode' 。

更新到5.0.33,买入/关闭脚本在那里得到了修复,它们仍然会返回错误为无,但现在你可以调用mt5.last_error(),没有例外,看到错误代码
 

ckeiderling:

...

我使用mt5.copy_ticks_range()和mt5.copy_rates_range()得到了同样的问题。我必须重置内核,以便清除内存。

...
这一点在5.0.33中得到了修复