Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
6efc5e0
deleted: pyFinance.py file
May 30, 2021
fb70654
chenge from 01.06.2021
Jun 1, 2021
84cd47f
chenge from 01.06.2021 №2
Jun 1, 2021
c9fff3b
теперь опцион тыкается дважды и добавлен рассчет сумм колен
Jun 4, 2021
f0f485e
логи в отдельной папке и конфиг дополнен разделом context_menu
Jun 5, 2021
24ac6ae
изменен канал телеграмма, забыл исправить после тестирования
Jun 5, 2021
f270d0e
теперь context_menu относительные координаты
Jun 6, 2021
453038a
мелкие изменения и создание папки tools
Jun 6, 2021
f55ba6a
добавлена проверка кнопки опциона с помощью скриншота
Jun 6, 2021
d767521
исправлен путь к логу, добавленны функции получения значения из поля …
Jun 12, 2021
d98f2fe
добавленно исключение когда все проверки неудачные, создан файл с пол…
Jun 13, 2021
be2af88
изменения в формулировке лога и иcправление в функции получения резул…
Jun 15, 2021
113fb8a
внедрено ФП, только вместо двух повторяющихся мест теперь в функции t…
Jun 20, 2021
215e84d
поправил расчет времени запуска изнавания результата
Jun 20, 2021
0499a90
заменен канал телеграмма
Jun 21, 2021
8c0a442
изменения 21.06
Jun 21, 2021
161e71d
посмотри я там со временем изменения внес и с кликом по опциону, но к…
Jun 24, 2021
e4390e4
все сделал что там обговаривали, кроме финиш_тайм, все таки я потом п…
Jun 25, 2021
8bbdc0e
поменял канал
Jun 25, 2021
23dff84
сделан декоратор
Jun 26, 2021
99178f6
сделан декоратор, все работает
Jun 27, 2021
8a8d2b0
декоратор через @ сделан теперь
Jun 30, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added .screenshot2021-0606_19-25-04-863328.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
174 changes: 112 additions & 62 deletions broker_manager_gui.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import logging
import pyautogui
import pyperclip
import pytz
import time

import geometry_2d
Expand All @@ -13,26 +12,29 @@
logger = logging.getLogger('pyFinance')


def repeater(action):
def repeat_action(*args, **kvargs):
tries = 5
for k in range(tries):
if action(*args, **kvargs):
logger.debug('Check {} - True'.format(action.__name__))
return
logger.debug('Check {} - False'.format(action.__name__))
# при всех неудачных попытках кидаем исключение об ошибке
raise RuntimeError('{} setting error'.format(action.__name__))
return repeat_action


class BrokerManagerGui(BrokerManagerInterface):
TRY_COUNT = 3
TRY_COUNT = 5

def __init__(self, result_handler, config_file):
super().__init__(result_handler)

with open(config_file, 'r') as cf:
self.config = json.load(cf)

self.exp_hour_buttons = geometry_2d.get_matrix(
m_size=geometry_2d.Vector(x=6, y=4),
start=geometry_2d.Vector(**self.config['buttons']['expiration_time']['first_hour']),
delta=geometry_2d.Vector(**self.config['buttons']['expiration_time']['delta'])
)

self.exp_minute_buttons = geometry_2d.get_matrix(
m_size=geometry_2d.Vector(x=3, y=4),
start=geometry_2d.Vector(**self.config['buttons']['expiration_time']['first_minute']),
delta=geometry_2d.Vector(**self.config['buttons']['expiration_time']['delta'])
)
self.interval_deal_time = None

self.option_buttons = dict(zip(
BrokerManagerInterface.OPTION_LIST,
Expand All @@ -51,76 +53,124 @@ def __init__(self, result_handler, config_file):
]
))

# Устанавливаем начальный опцион
self.current_option = None
try:
self.click_option('EURUSD')
except:
pass

self.option_buttons['CADCHF'] = self.option_buttons['CADJPY']

def _get_deal_result(self):
self.is_deal = False

result = ''
windows_manager.activate_window('Прозрачный брокер бинарных опционов')

# открываем графу сделок "открытые"
pyautogui.doubleClick(
self.config['buttons']['opened']['x'],
self.config['buttons']['opened']['y'],
duration=0.1
)
time.sleep(5)

for k in range(BrokerManagerGui.TRY_COUNT):
pyperclip.copy("") # <- Это предотвращает замену последней копии текущей копией null.
pyautogui.doubleClick(self.config['fields']['result']['x'], self.config['fields']['result']['y'])
pyautogui.hotkey('ctrl', 'c')
time.sleep(1) # ctrl-c обычно работает очень быстро, но ваша программа может выполняться быстрее
result = pyperclip.paste()
result = self.get_field('result')
if result in ['LOSE', 'WIN']:
break
time.sleep(5)

# If result not in ['LOSE', 'WIN'] return as is
self.result_handler(result)

def set_field(self, field, value):
pyautogui.doubleClick(
self.config['fields'][field]['x'],
self.config['fields'][field]['y'],
duration=0.1
)
time.sleep(0.5)
pyautogui.write(str(value), interval=0.25)
time.sleep(0.5)

def get_field(self, field, use_mouse=False):
pyperclip.copy("") # <- Это предотвращает замену последней копии текущей копией null.

pyautogui.doubleClick(
self.config['fields'][field]['x'],
self.config['fields'][field]['y'],
duration=0.1
)
time.sleep(0.5)

if use_mouse:
pyautogui.rightClick(
self.config['fields'][field]['x'],
self.config['fields'][field]['y'],
duration=0.1
)
time.sleep(0.5)

pyautogui.click(
self.config['fields'][field]['x'] + self.config['context_menu']['copy']['x'],
self.config['fields'][field]['y'] + self.config['context_menu']['copy']['y'],
duration=0.1
)
else:
# ctrl-c обычно работает очень быстро, но ваша программа может выполняться быстрее
pyautogui.hotkey('ctrl', 'c')

time.sleep(0.5)
return pyperclip.paste()

@repeater
def try_set_field(self, field, value, use_mouse=False):
self.set_field(field, value)
return self.get_field(field, use_mouse) == str(value)

@repeater
def set_expiration_time(self, finish_datetime):
self.interval_deal_time = int((finish_datetime - datetime.datetime.now()).total_seconds() // 60)
self.set_field('expiration_time', self.interval_deal_time)
return self.get_field('expiration_time') == str(self.interval_deal_time)

def click_option(self, option):
@repeater
def click_option_button(point, screenshot):
pyautogui.click(point.x, point.y, duration=0.1)
time.sleep(3)
screenshot_new = pyautogui.screenshot(region=(point.x - 5, point.y - 5, point.x + 5, point.y + 5))
if screenshot == screenshot_new:
return False
self.current_option = option
return True

if self.current_option == option:
return

point = self.option_buttons[option]
screenshot = pyautogui.screenshot(region=(point.x - 5, point.y - 5, point.x + 5, point.y + 5))

click_option_button(point, screenshot)


def make_deal(self, option, prognosis, summ, deal_time):
if self.is_deal:
logger.info('Deal is active now, skip new deal.')
logger.info('Deal is active now, skip new deal.\n')
return

windows_manager.activate_window('Прозрачный брокер бинарных опционов')
pyautogui.click(self.option_buttons[option].x, self.option_buttons[option].y, duration=0.1)
time.sleep(2)

for k in range(self.TRY_COUNT):
pyautogui.doubleClick(
self.config['fields']['investment_money']['x'],
self.config['fields']['investment_money']['y'],
duration=0.1
)
time.sleep(1)
pyautogui.write(str(summ), interval=0.25)
time.sleep(1)
finish_datetime = datetime.datetime.now() + datetime.timedelta(minutes=deal_time)

self.click_option(option)
self.try_set_field('investment_money', summ, use_mouse=True)
self.set_expiration_time(finish_datetime)

pyautogui.click(
self.config['fields']['expiration_time']['x'],
self.config['fields']['expiration_time']['y'],
duration=0.1
)
time.sleep(2)
pyautogui.click(self.exp_hour_buttons[deal_time.hour].x, self.exp_hour_buttons[deal_time.hour].y, duration=0.1)
time.sleep(2)
pyautogui.click(
self.exp_minute_buttons[deal_time.minute // 5].x,
self.exp_minute_buttons[deal_time.minute // 5].y,
duration=0.1
)
time.sleep(2)
pyautogui.click(self.prognosis_table[prognosis].x, self.prognosis_table[prognosis].y, duration=0.1)
self.is_deal = True

# Set up timer on finish job
msk_tz = pytz.timezone('Europe/Moscow')
now_date = datetime.datetime.now(msk_tz)
finish_datetime = msk_tz.localize(
datetime.datetime(
now_date.year,
now_date.month,
now_date.day,
deal_time.hour,
deal_time.minute
)
)
if deal_time.hour in [0, 1]:
finish_datetime += datetime.timedelta(days=1)
finish_datetime = finish_datetime.astimezone()

logger.debug("finish_datetime={}".format(finish_datetime))

finish_datetime = datetime.datetime.now() + datetime.timedelta(minutes=self.interval_deal_time)
self.scheduler.add_job(self._get_deal_result, 'date', run_date=finish_datetime)
13 changes: 12 additions & 1 deletion broker_manager_gui_luzin_config.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@
"x": 1250,
"y": 340
}
},
"opened": {
"x": 1213,
"y": 415
}
},

Expand All @@ -48,7 +52,14 @@
},
"result": {
"x": 1330,
"y": 462
"y": 470
}
},

"context_menu": {
"copy": {
"x": 44,
"y": 85
}
}
}
29 changes: 20 additions & 9 deletions broker_manager_gui_nick_config.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@
"expiration_time": {
"first_hour": {
"x": 585,
"y": 219
"y": 231
},
"first_minute": {
"x": 831,
"y": 219
"y": 231
},
"delta": {
"x": 39,
Expand All @@ -18,7 +18,7 @@
"option": {
"first": {
"x": 164,
"y": 146
"y": 159
},
"delta": {
"x": 54,
Expand All @@ -28,27 +28,38 @@
"prognosis": {
"call": {
"x": 824,
"y": 351
"y": 363
},
"put": {
"x": 944,
"y": 351
"y": 363
}
},
"opened": {
"x": 866,
"y": 412
}
},

"fields": {
"investment_money": {
"x": 851,
"y": 156
"y": 168
},
"expiration_time": {
"x": 911,
"y": 156
"y": 168
},
"result": {
"x": 983,
"y": 457
"x": 987,
"y": 470
}
},

"context_menu": {
"copy": {
"x": 52,
"y": 91
}
}
}
2 changes: 1 addition & 1 deletion broker_manager_interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
class BrokerManagerInterface:
OPTION_LIST = (
'AUDCAD', 'AUDJPY', 'AUDUSD', 'EURAUD', 'EURCHF', 'EURJPY', 'GBPAUD', 'GBPJPY', 'NZDJPY', 'USDCAD', 'USDJPY',
'AUDCHF', 'AUDNZD', 'CADJPY', 'EURCAD', 'EURGBP', 'EURUSD', 'GBPCHF', 'GBPNZD', 'NZDUSD', 'USDCHF'
'AUDCHF', 'AUDNZD', 'CADJPY', 'EURCAD', 'EURGBP', 'EURUSD', 'GBPCHF', 'GBPNZD', 'NZDUSD', 'USDCHF', 'CADCHF'
)
PROGNOSIS_LIST = ('вверх', 'вниз')

Expand Down
Loading