MetaTrader 5 Python User Group - как использовать Python в Метатрейдере - страница 65

 
Запустите пример из справки для https://www.mql5.com/ru/docs/integration/python_metatrader5/mt5ordersend_py
Документация по MQL5: Интеграция / MetaTrader для Python / order_send
Документация по MQL5: Интеграция / MetaTrader для Python / order_send
  • www.mql5.com
[in]  Структура типа MqlTradeRequest, которая описывает требуемое торговое действие. Обязательный неименованный параметр. Пример заполнения запроса и состав перечислений смотрите ниже. Идентификатор эксперта. Позволяет организовать аналитическую обработку торговых ордеров. Каждый эксперт может выставлять свой собственный уникальный...
 
AxxelTrader:

Обновил до версии 2432.
Но ошибка всё равно остаётся..
Уже перепробовал на разных брокерах даже..

r = mt5.Buy(...)
if r is None:
    print(mt5.last_error())
else:
    if r.retcode ...
 

copy_rates_from не предоставляет достаточно данных на таймфрейме M1.


Это правильный курс действий?

from datetime import datetime 
import matplotlib.pyplot as plt
import pandas as pd
from pandas.plotting import register_matplotlib_converters
import pytz

register_matplotlib_converters()
import MetaTrader5 as mt5


 if not mt5.initialize():
    print("initialize() failed")
    mt5.shutdown()


print(mt5.terminal_info())
print(mt5. version ())

timezone = pytz.timezone("Etc/UTC")
utc_from = datetime ( 2020 , 1 , 10 , tzinfo=timezone)


eurusd_rates_m1 = mt5.copy_rates_from("EURUSD", mt5.TIMEFRAME_M1, utc_from, 1000 )
print('M1 eurusd_rates(', len(eurusd_rates_m1), ')')
eurusd_rates_m5 = mt5.copy_rates_from("EURUSD", mt5.TIMEFRAME_M5, utc_from, 1000 )
print('M5 eurusd_rates(', len(eurusd_rates_m5), ')')
eurusd_rates_m10 = mt5.copy_rates_from("EURUSD", mt5.TIMEFRAME_M10, utc_from, 1000 )
print('M10 eurusd_rates(', len(eurusd_rates_m10), ')')
eurusd_rates_m15 = mt5.copy_rates_from("EURUSD", mt5.TIMEFRAME_M15, utc_from, 1000 )
print('M15 eurusd_rates(', len(eurusd_rates_m15), ')')
eurusd_rates_m30 = mt5.copy_rates_from("EURUSD", mt5.TIMEFRAME_M30, utc_from, 1000 )
print('M30 eurusd_rates(', len(eurusd_rates_m30), ')')


mt5.shutdown()
M1 eurusd_rates( 1 )      ???
M5 eurusd_rates( 1000 )
M10 eurusd_rates( 1000 )
M15 eurusd_rates( 1000 )
M30 eurusd_rates( 1000 )
 
Я знаю, что эта тема быстро станет очень длинной. Metaquotes необходимо добавить новый подфорум (Python) для каждого языка.
 
Christian:

copy_rates_range не предоставляет достаточно данных на таймфрейме M1.


Это правильный курс действий?

Pay attention at Note on copy rates range

Note

See the CopyRates() function for more information.

MetaTrader 5 terminal provides bars only within a history available to a user on charts. The number of bars available to users is set in the "Max. bars in chart" parameter.

When creating the 'datetime' object, Python uses the local time zone, while MetaTrader 5 stores tick and bar open time in UTC time zone (without the shift). Therefore, 'datetime' should be created in UTC time for executing functions that use time. Data received from the MetaTrader 5 terminal has UTC time.


Documentation on MQL5: Integration / MetaTrader for Python / copy_rates_range
Documentation on MQL5: Integration / MetaTrader for Python / copy_rates_range
  • www.mql5.com
# create 'datetime' objects in UTC time zone to avoid the implementation of a local time zone offset # get bars from USDJPY M5 within the interval of 2020.01.10 00:00 - 2020.01.11 13:00 in UTC time zone                  time     open     high      low    close  tick_volume  spread  real_volume...
 
Rashid Umarov:

Pay attention at Note on copy rates range

There is a bug in copy rates. I posted this several times but nobody has acknowledged it. 

import MetaTrader5 as mt5

mt5.initialize()
maxbars = mt5.terminal_info().maxbars
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
mt5.shutdown()

##
# Failed on count=7844 with strerror=IPC recv failed
##
 
Обидно, но по моему разумению есть проблема с инициализацией структур в MT.
 
Мне, кстати, внучку с Питоном познакомить предстоит, а я его не знаю... Пока. 
 

I have a script that ran for a few hours. but then I start getting these errors, Invalid_Stops, and then it does not open anymore trades. 

1.BUY order send (): by EURUSD 0.01 lots at 1.0949 

2. order_send failed, retcode = 10016 
   retcode = 10016 
   deal = 0 
   order = 0 
   volume = 0.0 
   price = 0.0 
   bid = 0.0 
   ask = 0.0 
   comment = Invalid stops 
   request_id = 0 
   retcode_external = 0 

   request = TradeRequest (action = 1, magic = 234000, order = 0, symbol = 'EURUSD', volume = 0.01, price = 1.0949, stoplimit = 0.0, sl = 1.0939, tp = 1.0979, 
   deviation = 0, type = 0, type_filling = 0, type_time = 0, expiration = 0, commen 

t = 'EURUSD Buy.', Position = 0, position_by = 0) 

Can anybody please help direct where to start looking for this issue?

Thank you

 
fbrand:

I have a script that ran for a few hours. but then I start getting these errors, Invalid_Stops, and then it does not open anymore trades. 

Can anybody please help direct where to start looking for this issue?

Thank you

А какие были текущие цены (Bid и Ask)? Какой был уровень заморозки (SYMBOL_TRADE_FREEZE_LEVEL)?

Причина обращения: