Making a Python trading system for MT. - page 17

 

Finally mastered the graph layout in Python. Oh, it's hard to swim in hydrochloric acid learning the matplotlib package.

This is the result on the graph:

I like it).

And here is the code:

import MyPack.Filters as flt
import TSClasses as tsc
import matplotlib.pyplot as plt
#import numpy as np
#from scipy.stats import randint

#rv=randint.rvs(0,10,size=10)

# чтение данных из БД
DB='csvdb1.db'
Ticker='SPFB.SBRF-9.18'
c=flt.cCandle()

SD=tsc.StockData(DB,
                 Ticker)
rdb=SD.rdb  
F8=SD.F8
F16=SD.F16
F32=SD.F32
F150=SD.F150
rd=SD.rdb
Dev=SD.Dev
Stoch=SD.Stoch

# определение диапазона значений по оси х
Ib=1500
Ie=Ib+150

# подготовка данных для графиков
I=[i for i in range(Ib,Ie)]
Hist=[rdb.history[i][c.c] for i in I]
f8=[F8[i] for i in I]
f16=[F16[i] for i in I]
f32=[F32[i] for i in I]
f150=[F150[i] for i in I]
Devp=[F150[i]+Dev[i] for i in I]
Devm=[F150[i]-Dev[i] for i in I]
Kpb=[Stoch[0][i] for i in I]
Dpb=[Stoch[1][i] for i in I]

# построение графиков
#fig, axs = plt.subplots(2, 1,figsize=(10.0,5))

fig = plt.figure(figsize=(10,6.5))
axs1 = plt.subplot2grid((3, 1), (0, 0),rowspan=2,fig=fig)
axs2 = plt.subplot2grid((3, 1), (2,0), rowspan=1,fig=fig)

axs1.plot(I,Hist, label='Hist')
axs1.plot(I,f8,label='F8')
axs1.plot(I,f16,label='F16')
axs1.plot(I,f32,label='F32')
axs1.plot(I,f150,label='F150')
axs1.plot(I,Devp)
axs1.plot(I,Devm)
axs1.legend()
axs1.set_xticks(range(Ib,Ie+10,10))
axs1.grid(True, which='both')

axs2.plot(I,Kpb, label='F')
axs2.plot(I,Dpb, label='S')
axs2.set_xticks(range(Ib,Ie+10,10))
axs2.legend()
axs2.grid(True)

plt.show()

The code is given as a whole, but I don't give any data, it's impossible - you have to do it yourself. You only need to use #plotlib. The rest is just for understanding - what, where and from where.

I don't write comments as usual, but it will be easier for you to understand the ready copy.

 
Yuriy Asaulenko:

In addition to my previous post, looked at the distribution relative to the regression line at 3000 counts. At shorter intervals it is very jagged.

Actually it is very unstable, and its shape changes a lot from plot to plot, but the min and max deviations remain at about the same levels. Well, and there's no trace of the long tails. I am not making any conclusions, see for yourself.

I can only say that distribution tails are a result of our actions, not due to the market.

In general, the meaning of these studies on the finiteness of the variance is clear.

 
Novaja:

By and large, the point of this exploration into the finiteness of the variance of deviations is clear.

No, you don't.) It's not a result or exploration at all.) There's nothing to explore here. It's a by-product. I wrote about all this in the TIP thread back at the very beginning of the conversation about tails and looking for the unknown. But since you can show it in between, pourquoi not pas. Don't take it so seriously, look at things more simply). Advice, from an old and experienced provocateur.))

 

You may have read the article about wavelets

Generally, great stuff, sees in the signal what you can't see with your eyes (and probably other ways). It's all great and very tempting. Yes, but all this in an already formed signal. Everything is great and very tempting.

I tried it with market quotes. Huh? - It's a great indicator. But no, again the edge effects, at the very edge of the picture, where the quotes break off, nothing can be said about anything.

It's a pity, but the subject of wavelets is closed. Probably, closed for now, until better times).

 
Yuriy Asaulenko:

Finally mastered the graph layout in Python. Oh, it's hard to swim in hydrochloric acid learning the matplotlib package.

This is the result on the graph:

I like it).

And here is the code:

The code is given as a whole, but I don't give any data, it's impossible - you have to do it yourself. You only need to use #plotlib. The rest, just for understanding - what, where and from where.

I don't write comments as usual, but it will be easier for you to understand the ready sample.

put the code in the file


D:\PYTHON\YURAZ>yz_112.py

Traceback (most recent call last):

File "D:\PYTHON\YURAZ\yz_112.py", line 1, in <module>

import MyPack.Filters as flt

ModuleNotFoundError: No module named 'MyPack'

D:\PYTHON\YURAZ>pip install MyPack

Requirement already satisfied: MyPack in c:\users\yuraz\appdata\local\programs\python\python38\lib\site-packages (0.1)

D:\PYTHON\YURAZ>


Is something missing ?

 

Could you please tell me where you can find the parameter that the tool is active for trading.


https://www.mql5.com/en/docs/integration/python_metatrader5/mt5symbolinfo_py

Documentation on MQL5: Integration / MetaTrader for Python / symbol_info
Documentation on MQL5: Integration / MetaTrader for Python / symbol_info
  • www.mql5.com
SymbolInfo(custom=False, chart_mode=0, select=True, visible=True, session_deals=0, session_buy_orders=0, session_sell_orders=0, ...
 
Андрей Кузнецов:

Could you please tell me where you can find the parameter that the tool is active for trading.


https://www.mql5.com/en/docs/integration/python_metatrader5/mt5symbolinfo_py


#### Качаем справочник ценных бумаг

#
подключение библиотеки from openapi_client import openapi # читаем наш токен handle = open(r"D:\PYTHON\MYKEYTOKEN\token.sec", "r") dataToken = handle.read() handle.close() token = dataToken client = openapi.api_client(token) # Получение списка облигаций bonds = client.market.market_bonds_get() # Получение списка ETF etfs = client.market.market_etfs_get() # Получение списка акций stocks     = client.market.market_stocks_get() # Получение валютных пар currencies = client.market.market_currencies_get() mFigi = bonds.payload.instruments + etfs.payload.instruments + stocks.payload.instruments +  currencies.payload.instruments   # В mFigi попадут все инструменты

The structure is described on the official website.

or like this

[{'currency': 'RUB',
  'figi': 'BBG00844BD08',
  'isin': 'RU000A0JU898',
  'lot': 1,
  'min_price_increment': 0.1,
  'name': 'МКБ выпуск 9',
  'ticker': 'RU000A0JU898'}, {'currency': 'RUB',
  'figi': 'BBG00R05JT04',
  'isin': 'RU000A1013Y3',
  'lot': 1,
  'min_price_increment': 0.1,
  'name': 'Черкизово выпуск\xa02',
  'ticker': 'RU000A1013Y3'}, {'currency': 'RUB',
  'figi': 'BBG00PNLY692',
  'isin': 'RU000A100DC4',
  'lot': 1,
  'min_price_increment': 0.1,
  'name': 'МСБ-Лизинг 002P выпуск 2',
  'ticker': 'RU000A100DC4'}]

This is how it is decided for MICEX and SPX

 

Python-based Python workbench, with graphical interface tkinter

uses Python 3.7 64x + Microsoft Visual Studio Enterprise 2019 (2) 16.8.2

from tkinter import *                              # импорт объектов для графики

import datetime
from datetime import datetime, timedelta
from pytz import timezone

dt_Begin = datetime(2020,6,30, 0, 0, 0, tzinfo=timezone('Europe/Moscow'))  # timezone нужно указывать. Иначе - ошибка
today = datetime.now(tz=timezone('Europe/Moscow'))
start = today.replace(hour=0, minute=0, second=0, microsecond=0)
dt_End = start + timedelta(1)
 
def makeWidgets():
    # создание графической формы
    global ent_Date                               # перечень глобальных переменных, которые будут использоваться и за пределами функции
    ent_Date = {}                                 # словарь, для занесения в него объектов Entry ячеек таблицы ввода записей

    window = Tk()                                  # создание главного окна
    window.title('YuraZ Отчет Tinkoff')            # заголовок окна
    window.geometry('2100 x800+0+0')                # размеры окна

    form1 = Frame(window)                          # создание внутри окна window контейнера form1
    form1.pack()

    form2 = Frame(window)                          # создание внутри окна window контейнера form2
    form2.pack()


    Label(window, text=' ', width=1).pack(side=LEFT)                        # вспомогательная пустая метка
    labKey1 = Label(window, text='Дата Начала    :').pack(side=LEFT)        # надпись перед полем ввода Даты
    ent_dt_Begin = Entry(window, width=23)                                  # поле ввода Даты
    ent_dt_Begin.pack(side=LEFT)
    ent_dt_Begin.insert(0, dt_Begin)
    ent_Date['ent_dt_Begin'] = ent_dt_Begin             # занесение объекта поле ввода   в словарь entRec

    Label(window, text=' ', width=1).pack(side=LEFT)                         
    labKey2 = Label(window, text='Дата Окончания :').pack(side=LEFT)         
    ent_dt_End = Entry(window, width=23)                                     
    ent_dt_End.pack(side=LEFT)
    ent_dt_End.insert(0, dt_End)
    ent_Date['ent_dt_End'] = ent_dt_End             # занесение объекта поле ввода   в словарь entRec

    Label(window, text=' ', width=20).pack(side=LEFT)                      # вспомогательная пустая метка
    Button(window, text="Отчет", command=ОтчетПоПортфелю).pack(side=LEFT)  # Кнопка Отчет
    Label(window, text=' ', width=20).pack(side=LEFT)                      
    Button(window, text="Выход", command=fin).pack(side=LEFT)              # кнопка Выход (из программы)
    return window                                                          # функция makeWidgets возвращает окно window
 
def fin():            
    window.destroy()

def ОтчетПоПортфелю():
    sd1 = ent_Date['ent_dt_Begin'].get()  # из ячейки entKeyRec берется ключ записи для удаления
    sd2 = ent_Date['ent_dt_End'].get()  # из ячейки entKeyRec берется ключ записи для удаления
    d1 = datetime.strptime(sd1, "%Y-%m-%d %H:%M:%S%z")
    d2 = datetime.strptime(sd2, "%Y-%m-%d %H:%M:%S%z")

if __name__ == '__main__':
    window = makeWidgets()       # создание формы
    window.mainloop()            # передача управления форме




Reason: