Skip to content

Commit

Permalink
修复同花顺“刷新”;去除对win32gui的引用
Browse files Browse the repository at this point in the history
一、修复同花顺“刷新”
改为模拟点击工具栏“刷新”按钮。
二、去除对win32gui的引用
1)将所有对SetForegroundWindow, ShowWindow, win32defines的引用全部集中到easytrader.utils.win_gui
2)win_gui.py中,删除对win32gui的引用,改为对pywinauto的引用。(若引用pywinauto有问题,则可以把注释掉的对win32gui的引用瞬间恢复起来)。
  • Loading branch information
qzhjiang committed Jun 6, 2020
1 parent ee7cf8b commit ae97c30
Show file tree
Hide file tree
Showing 5 changed files with 52 additions and 62 deletions.
56 changes: 22 additions & 34 deletions easytrader/clienttrader.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
from easytrader.log import logger
from easytrader.utils.misc import file2dict
from easytrader.utils.perf import perf_clock
from win32gui import SetForegroundWindow, ShowWindow

if not sys.platform.startswith("darwin"):
import pywinauto
Expand Down Expand Up @@ -87,14 +86,6 @@ def __init__(self):
self._main = None
self._toolbar = None

def _set_foreground(self, grid=None):
if grid is None:
grid = self._trader.main
if grid.has_style(pywinauto.win32defines.WS_MINIMIZE): # if minimized
ShowWindow(grid.wrapper_object(), 9) # restore window state
else:
SetForegroundWindow(grid.wrapper_object()) # bring to front

@property
def app(self):
return self._app
Expand Down Expand Up @@ -243,7 +234,6 @@ def market_trade(self, security, amount, ttype=None, limit_price=None, **kwargs)
:param ttype: 市价委托类型,默认客户端默认选择,
深市可选 ['对手方最优价格', '本方最优价格', '即时成交剩余撤销', '最优五档即时成交剩余 '全额成交或撤销']
沪市可选 ['最优五档成交剩余撤销', '最优五档成交剩余转限价']
:param limit_price:
:return: {'entrust_no': '委托单号'}
"""
Expand Down Expand Up @@ -290,7 +280,9 @@ def auto_ipo(self):

if len(stock_list) == 0:
return {"message": "今日无新股"}
invalid_list_idx = [i for i, v in enumerate(stock_list) if v[self.config.AUTO_IPO_NUMBER] <= 0]
invalid_list_idx = [
i for i, v in enumerate(stock_list) if v[self.config.AUTO_IPO_NUMBER] <= 0
]

if len(stock_list) == len(invalid_list_idx):
return {"message": "没有发现可以申购的新股"}
Expand All @@ -310,8 +302,8 @@ def auto_ipo(self):
def _click_grid_by_row(self, row):
x = self._config.COMMON_GRID_LEFT_MARGIN
y = (
self._config.COMMON_GRID_FIRST_ROW_HEIGHT
+ self._config.COMMON_GRID_ROW_HEIGHT * row
self._config.COMMON_GRID_FIRST_ROW_HEIGHT
+ self._config.COMMON_GRID_ROW_HEIGHT * row
)
self._app.top_window().child_window(
control_id=self._config.COMMON_GRID_CONTROL_ID,
Expand All @@ -323,12 +315,12 @@ def is_exist_pop_dialog(self):
self.wait(0.5) # wait dialog display
try:
return (
self._main.wrapper_object() != self._app.top_window().wrapper_object()
self._main.wrapper_object() != self._app.top_window().wrapper_object()
)
except (
findwindows.ElementNotFoundError,
timings.TimeoutError,
RuntimeError,
findwindows.ElementNotFoundError,
timings.TimeoutError,
RuntimeError,
) as ex:
logger.exception("check pop dialog timeout")
return False
Expand Down Expand Up @@ -388,8 +380,8 @@ def __get_top_window_pop_dialog(self):
def _get_pop_dialog_title(self):
return (
self._app.top_window()
.child_window(control_id=self._config.POP_DIALOD_TITLE_CONTROL_ID)
.window_text()
.child_window(control_id=self._config.POP_DIALOD_TITLE_CONTROL_ID)
.window_text()
)

def _set_trade_params(self, security, price, amount):
Expand Down Expand Up @@ -432,10 +424,6 @@ def _type_keys(self, control_id, text):
text
)

def _type_common_control_keys(self, control, text):
self._set_foreground(control)
control.type_keys(text, set_foreground=False)

def _type_edit_control_keys(self, control_id, text):
if not self._editor_need_type_keys:
self._main.child_window(
Expand Down Expand Up @@ -481,17 +469,17 @@ def _get_left_menus_handle(self):
def _cancel_entrust_by_double_click(self, row):
x = self._config.CANCEL_ENTRUST_GRID_LEFT_MARGIN
y = (
self._config.CANCEL_ENTRUST_GRID_FIRST_ROW_HEIGHT
+ self._config.CANCEL_ENTRUST_GRID_ROW_HEIGHT * row
self._config.CANCEL_ENTRUST_GRID_FIRST_ROW_HEIGHT
+ self._config.CANCEL_ENTRUST_GRID_ROW_HEIGHT * row
)
self._app.top_window().child_window(
control_id=self._config.COMMON_GRID_CONTROL_ID,
class_name="CVirtualGridCtrl",
).double_click(coords=(x, y))

def refresh(self):
# self._switch_left_menus(["买入[F1]"], sleep=0.05)
self._toolbar.button(3).click() # 我的交易客户端工具栏中“刷新”是排在第4个的,所以其索引值是3
# self._switch_left_menus_by_shortcut("{F5}", sleep=0.1)
self._toolbar.button(3).click() # 我的交易客户端工具栏中“刷新”是排在第4个的,所以其索引值是3

@perf_clock
def _handle_pop_dialogs(self, handler_class=pop_dialog_handler.PopDialogHandler):
Expand All @@ -516,13 +504,13 @@ def login(self, user, password, exe_path, comm_password=None, **kwargs):
pass

def prepare(
self,
config_path=None,
user=None,
password=None,
exe_path=None,
comm_password=None,
**kwargs
self,
config_path=None,
user=None,
password=None,
exe_path=None,
comm_password=None,
**kwargs
):
"""
登陆客户端
Expand Down
17 changes: 9 additions & 8 deletions easytrader/grid_strategies.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,10 @@
import pywinauto.keyboard
import pywinauto
import pywinauto.clipboard
from pywinauto import win32defines

from easytrader.log import logger
from easytrader.utils.captcha import captcha_recognize
from easytrader.utils.win_gui import SetForegroundWindow, ShowWindow
from easytrader.utils.win_gui import SetForegroundWindow, ShowWindow, win32defines

if TYPE_CHECKING:
# pylint: disable=unused-import
Expand All @@ -37,6 +36,9 @@ def set_trader(self, trader: "clienttrader.IClientTrader"):


class BaseStrategy(IGridStrategy):
def __init__(self):
self._trader = None

def set_trader(self, trader: "clienttrader.IClientTrader"):
self._trader = trader

Expand All @@ -58,7 +60,7 @@ def _set_foreground(self, grid=None):
try:
if grid is None:
grid = self._trader.main
if grid.has_style(pywinauto.win32defines.WS_MINIMIZE): # if minimized
if grid.has_style(win32defines.WS_MINIMIZE): # if minimized
ShowWindow(grid.wrapper_object(), 9) # restore window state
else:
SetForegroundWindow(grid.wrapper_object()) # bring to front
Expand Down Expand Up @@ -95,9 +97,7 @@ def _format_grid_data(self, data: str) -> List[Dict]:
def _get_clipboard_data(self) -> str:
if Copy._need_captcha_reg:
if (
self._trader.app.top_window()
.window(class_name="Static", title_re="验证码")
.exists(timeout=1)
self._trader.app.top_window().window(class_name="Static", title_re="验证码").exists(timeout=1)
):
file_path = "tmp.png"
count = 5
Expand All @@ -123,8 +123,8 @@ def _get_clipboard_data(self) -> str:
try:
logger.info(
self._trader.app.top_window()
.window(control_id=0x966, class_name="Static")
.window_text()
.window(control_id=0x966, class_name="Static")
.window_text()
)
except Exception as ex: # 窗体消失
logger.exception(ex)
Expand Down Expand Up @@ -171,6 +171,7 @@ def __init__(self, tmp_folder: Optional[str] = None):
"""
:param tmp_folder: 用于保持临时文件的文件夹
"""
super().__init__()
self.tmp_folder = tmp_folder

def get(self, control_id: int) -> List[Dict]:
Expand Down
18 changes: 8 additions & 10 deletions easytrader/pop_dialog_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,21 @@
import time
from typing import Optional

import pywinauto

from easytrader import exceptions
from easytrader.utils.perf import perf_clock
from easytrader.utils.win_gui import SetForegroundWindow, ShowWindow
from easytrader.utils.win_gui import SetForegroundWindow, ShowWindow, win32defines


class PopDialogHandler:
def __init__(self, app):
self._app = app

def _set_foreground(self, grid=None):
if grid is None:
grid = self._trader.main
if grid.has_style(pywinauto.win32defines.WS_MINIMIZE): # if minimized
ShowWindow(grid.wrapper_object(), 9) # restore window state
@staticmethod
def _set_foreground(window):
if window.has_style(win32defines.WS_MINIMIZE): # if minimized
ShowWindow(window.wrapper_object(), 9) # restore window state
else:
SetForegroundWindow(grid.wrapper_object()) # bring to front
SetForegroundWindow(window.wrapper_object()) # bring to front

@perf_clock
def handle(self, title):
Expand All @@ -40,7 +37,8 @@ def handle(self, title):
def _extract_content(self):
return self._app.top_window().Static.window_text()

def _extract_entrust_id(self, content):
@staticmethod
def _extract_entrust_id(content):
return re.search(r"[\da-zA-Z]+", content).group()

def _submit_by_click(self):
Expand Down
21 changes: 12 additions & 9 deletions easytrader/utils/win_gui.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
# coding:utf-8
import win32gui


def SetForegroundWindow(hwd):
win32gui.SetForegroundWindow(hwd._as_parameter_)


def ShowWindow(hwd, window_status):
win32gui.ShowWindow(hwd._as_parameter_, window_status)
from pywinauto import win32defines
from pywinauto.win32functions import SetForegroundWindow, ShowWindow

# import win32gui
#
#
# def SetForegroundWindow(hwd):
# win32gui.SetForegroundWindow(hwd._as_parameter_)
#
#
# def ShowWindow(hwd, window_status):
# win32gui.ShowWindow(hwd._as_parameter_, window_status)
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,4 @@ requests==2.19.1
six==1.11.0
urllib3==1.23; python_version != '3.1.*'
werkzeug==0.14.1
win32gui

0 comments on commit ae97c30

Please sign in to comment.