Trading with Python - page 3

 
Mikhael1983 #:

Using the functions described in the library, implement the functions for initiating a connection to the terminal and for terminating a connection to the terminal. We plan to do this in an endless loop every 5 minutes.

...

Program running:

This is all successfully implemented by mql5 means

 
Vitaly Muzichenko #:

This is all successfully implemented with mql5

Naturally. However, there is a large layer of people who are unfamiliar with mql5, and see no point in learning an obsolete tool that only applies to an extremely narrow area of work with a particular terminal of a particular company.
 

Questions would be appreciated, I can explain how and what.

Let's write a function that will save quotes to files. In principle, there is no need to save quotes to files at all. It's enough to keep them in memory. I have it historically came from the fact that the terminal is in a Windows virtual machine and a Python program saves quotes, and all the logic is in the host system, Debian GNU/Linux, and there is its own Python program spinning, which reads these files and writes in other files trade instructions, which the Python program in virtual Windows reads, and executes.

However, writing the quotes into the files is just useful in itself. It's visual. Allows you to see what happened, feel, read by other means (the same Matcad), etc. So, let's do it this way.

def pips_definer(instrument): 
    '''
    Функция возвращает величину пипса для инструмента, например для EURUSD - 0.0001, для USDJPY - 0.01 
    '''
    if instrument in ['EURUSD_i', 'GBPUSD_i', 'EURGBP_i', 'USDCHF_i', 'USDCAD_i']: 
        return 0.0001 
    elif instrument in ['USDJPY_i']: 
        return 0.01 
    else: 
        return None 


def save_prices_to_file(instrument, n=100):
    '''
    Функция принимает инструмент, количество отсчётов цены n в таймфрейме М5, 
    и сохраняет в файл (только сформировавшиеся полностью бары, время соответствует времени закрытия (!) бара)
    '''
    w = pips_definer(instrument) 
    tochn = int(abs(log10(w))+1)  
    path_file = os.path.join(work_catalog, instrument+'.txt') 
    
    bars = mt5.copy_rates_from_pos(instrument, mt5.TIMEFRAME_M5, 0, n+1) # в случае ошибки mt5.copy_rates_from_pos возвращает None 
    
    try: 
        f = open(path_file, 'w') 
        for i in range(0, n+1): 
            bar = bars[i] 
            dt_stamp = date_time.fromtimestamp(bar[0], dt.timezone.utc) + dt.timedelta(hours=1, minutes=5) 
            open_ = str(round(bar[1], tochn)) 
            high_ = str(round(bar[2], tochn))
            low_ = str(round(bar[3], tochn))
            close_ = str(round(bar[4], tochn))
            if i != n: 
                f.write(dt_stamp.M5_view + ' ' + open_ + ' ' + high_ + ' ' + low_ + ' ' + close_ + '\n')
        f.close()    
        print(date_time.now().nice_view, ' - котировки {} успешно записаны в файл'.format(instrument))
    except: 
        print(date_time.now().nice_view, ' - котировки {} записать в файл не удалось'.format(instrument)) 

And let's add to main function a call to save quotes:

def main(N): 
    
    '''
    Главная функция, обеспечивающая в бесконечном цикле связь с терминалом, 
    сохранение котировок, и запуск функции, осуществляющей торговлю
    '''    
    
    dt_start = date_time.now() 
    dt_write = dt_stamp_from_M5_view(dt_start.M5_view) + dt.timedelta(minutes=5, seconds=10) 
    print('\n' + dt_start.nice_view, ' - начал работу, бездействую до ' + dt_write.nice_view + '\n') 
    timedelta_sleep = dt_write - date_time.now() 
    time.sleep(timedelta_sleep.seconds) 
    
    while True:
        
        # установка соединения с MetaTrader5 
        if terminal_init(os.path.join('C:\\', 'Program Files', 'Alpari MT5', 'terminal64.exe'), work_account): 
            
            # запись цен в файлы: для всех инструментов, N отсчётов  
            if (dt.datetime.now() - dt_write) < dt.timedelta(seconds=10): 
                print('\n' + date_time.now().nice_view + '  - начинаю запись котировок в файлы')
                for instrument in instruments: 
                    save_prices_to_file(instrument, N) 
            
            # пауза 10 секунд: временная заглушка, имитирующая анализ цен, принятие и выполнение решений 
            print('\nосуществляю торговлю: анализирую котировки, открываю и/или закрываю сделки')
            time.sleep(10)
            
            # завершение соединения с MetaTrader5 
            terminal_done() 
        
            # определение параметров ожидания до следующего выполнения тела цикла 
            dt_start = date_time.now()  
            dt_write = dt_stamp_from_M5_view(dt_start.M5_view) + dt.timedelta(minutes=5, seconds=10) 
            timedelta_sleep = dt_write - dt_start 
            print(date_time.now().nice_view + '  - засыпаю до {}\n\n\n\n\n'.format(dt_write.nice_view))  
            time.sleep(timedelta_sleep.seconds) 
        


Result of the work:


The /fx/ folder contains six files:


They have the following structure (using EURUSD_i.txt as an example): date-time countdown as M5_view, open, high, low, close, with the time countdown corresponding to the moment of bar closing.

202112071335 1.1269 1.12697 1.12659 1.1266
202112071340 1.12669 1.12636 1.12659
202112071345 1.12661 1.12664 1.12627 1.12627
202112071350 1.12628 1.12633 1.12595 1.12595
202112071355 1.12598 1.126 1.12564 1.12586

...

202112110040 1.13173 1.13181 1.13164 1.13167
202112110045 1.13167 1.1317 1.13157 1.13163
202112110050 1.13163 1.13167 1.13155 1.13157


Note that my server time is 1 hour less than the current time on my computer, and it is convenient for me to think in that time (Moscow time).

That's why I added a 1 hour and 5 minutes timedelta in the code of the function to save the quotes:

dt.timedelta(hours=1, minutes=5)

in it 1 hour is the difference in time between server time and mine, and 5 minutes arises from the fact that I am comfortable thinking with bar closing time, and the terminal gives opening time.

Every 5 minutes the price files are overwritten, rewritten, not a line added to the end, but the whole file is overwritten. For modern SSDs, and only 1000 lines, and only once every 5 minutes, there is nothing to talk about.
 
Sergey Deev #:

i.e. give an example of saving any indicator data to a csv file or SQLite and then reading it into python? Wouldn't that be funny?

It is ridiculous. It has nothing to do with python. With such data, the script can be written in any programming language

 
Malik Arykov #:

That's exactly what's so funny. Because it has nothing to do with python. The same thing can be done in any programming language

Of course you can. But the entry threshold in Python is much lower than in C++ which one. People completely unfamiliar with programming can easily start doing what they need using Python after 3 months. If something uncomplicated is needed.

 
Malik Arykov #:

That's exactly what's so funny. Because it has nothing to do with python. The same can be done in any programming language

Is it funny to use python against any other language? no argument... if any other language has integration with MT and allows you to get quotes - go for it...

 

I don't understand what TC wants, according to the messages there are only contradictions - there are people who don't want to know about MQL, but these people will visit a thematic resource, these people also need to install MT5, so they can finally dive into Python ...... it's kind of hard


If you really want to create something in Python for the benefit of the community, you may write it in Python, and postpone the integration or exchange task to a later date ,

importing quotes into Python for educational purposes is not a problem either.

I have found it myself, I was sorting it out a couple of months ago:

import finplot as fplt
import yfinance
df = yfinance.download('AAPL')
fplt.candlestick_ochl(df[['Open', 'Close', 'High', 'Low']])
fplt.show()



I don't understand the purpose of the topic at all.

 
Sergey Deev #:

Ridiculous to use python against any other language? no argument... if any other language has integration with MT and allows you to get quotes - go for it...

My point is that python integration with MT5 is not complete. You can't get indicator values directly

 

Igor Makanu importing quotes in Python for training purposes isn't a problem either.

found this in mine, sorted it out a couple of months ago:

...


in general, the goals of this topic are not clear at all

The integration problem has been solved by metatrader5 library, it doesn't need to be solved or abandoned.

The quotes import is necessary not for educational purposes, but for real trading, so it is not from the mythical *finanse, but directly from the terminal, in which the trading is done.

Aim of this thread is simple as five pennies: allow everyone to start algorithmic trading in Python, just by copying pieces of code like initialization of connection to terminal, request for quotes, request to server to open or close a deal, etc., etc. Focus on logic only, and in an extremely user-friendly language at that.

 
Malik Arykov #:

My point is that the integration of python with MT5 is not complete. You can't get the indicator values directly

Why do you need indicator values if you have prices from which these indicators are calculated? I'll give you a couple of simple functions later, like SMA calculations, just as an example. But you can write whatever you want, no one is stopping you.