def accept(self): if not self.name: QtWidgets.QMessageBox.warning( self, _translate("trade", "error"), _translate("trade", "The account name cannot be empty.")) return self.done(1)
def on_tree_itemClicked(self, item: QtWidgets.QTreeWidgetItem, column): data = item.data(0, QtCore.Qt.UserRole) if data is not None: # 一级节点,使能会话编辑与移除菜单 self.parent().action_dict['action_edit_file_session'].setEnabled( True) self.parent().action_dict['action_del_file_session'].setEnabled( True) self.parent().action_dict['action_file_connect'].setEnabled(True) return # 屏蔽会话编辑与移除菜单 self.parent().action_dict['action_edit_file_session'].setEnabled(False) self.parent().action_dict['action_del_file_session'].setEnabled(False) self.parent().action_dict['action_file_connect'].setEnabled(False) session = item.parent().data(0, QtCore.Qt.UserRole) if session.name == "admin": item_text = item.text(0) if item_text == _translate("HkuSessionViewWidget", "person info"): self.open_tab_tigger.emit(session, HkuPersonInfoWidget) elif item_text == _translate("HkuSessionViewWidget", "users manage"): self.open_tab_tigger.emit(session, HkuUserManagerWidget) else: pass else: item_text = item.text(0) if item_text == _translate("HkuSessionViewWidget", "person info"): self.open_tab_tigger.emit(session, HkuPersonInfoWidget) elif item_text == _translate("HkuSessionViewWidget", "Xueqiu account"): self.open_tab_tigger.emit(session, HkuXueqiuAccountWidget)
def on_reset_password_pushButton_clicked(self): selected = self.users_tableView.selectionModel() if selected: indexes = selected.selectedRows() for index in indexes: try: userid_index = self.rest_data_model.index( index.row(), 0, QtCore.QModelIndex()) userid = self.rest_data_model.data(userid_index, QtCore.Qt.DisplayRole) name_index = self.rest_data_model.index( index.row(), 1, QtCore.QModelIndex()) name = self.rest_data_model.data(name_index, QtCore.Qt.DisplayRole) r = UserService.reset_password(self.session, userid) QtWidgets.QMessageBox.about( self, _translate("UserManage", "info"), _translate( "UserManage", "The password of user ({}) had be reset to 123456" ).format(name)) except Exception as e: QtWidgets.QMessageBox.warning( self, _translate("UserManage", "error"), str(e)) return
def on_remove_pushButton_clicked(self): indexes = self.tableView.selectedIndexes() for index in indexes: row = self.rest_data_model.row(index) if row is None: continue try: td_id, name = row["td_id"], row["name"] r = QtWidgets.QMessageBox.information( self, _translate("trade", "Confirm"), _translate( "trade", "Are you sure to remove the trade account ({})?"). format(name), QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No) if r == QtWidgets.QMessageBox.No: return r = TradeService.remove_xq_account(self.session, td_id) except Exception as e: QtWidgets.QMessageBox.warning(self, _translate("trade", "error"), str(e)) return self.rest_data_model.removeRows(index.row(), 1, QtCore.QModelIndex())
def initMenuBar(self): self.menubar_dict = dict(menu_file=self.menuBar().addMenu( _translate('MainWindow', "&File(F)")), menu_view=self.menuBar().addMenu( _translate('MainWindow', "&View(V)")), menu_help=self.menuBar().addMenu( _translate('MainWindow', "&Help(H)")))
def on_remove_pushButton_clicked(self): selected = self.users_tableView.selectionModel() if selected: indexes = selected.selectedRows() for index in indexes: try: userid_index = self.rest_data_model.index( index.row(), 0, QtCore.QModelIndex()) userid = self.rest_data_model.data(userid_index, QtCore.Qt.DisplayRole) name_index = self.rest_data_model.index( index.row(), 1, QtCore.QModelIndex()) name = self.rest_data_model.data(name_index, QtCore.Qt.DisplayRole) r = QtWidgets.QMessageBox.information( self, _translate("UserManage", "Confirm"), _translate( "UserManage", "Are you sure to remove the user ({})?").format( name), QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No) if r == QtWidgets.QMessageBox.No: return r = UserService.remove_user(self.session, userid) except Exception as e: QtWidgets.QMessageBox.warning( self, _translate("UserManage", "error"), str(e)) return self.rest_data_model.removeRows(index.row(), 1, QtCore.QModelIndex())
def initMenu(self): file_session_menu = self.menubar_dict['menu_file'].addMenu( QtGui.QIcon(":/icon/server_16.png"), _translate('MainWindow', '&Session Manager')) style_menu = self.menubar_dict['menu_view'].addMenu( _translate('MainWindow', 'Skin style')) self.menu_dict = dict( menu_file_new_session=file_session_menu.addAction( self.action_dict['action_new_file_session']), menu_file_edit_session=file_session_menu.addAction( self.action_dict['action_edit_file_session']), menu_file_del_session=file_session_menu.addAction( self.action_dict['action_del_file_session']), menu_file_connect=self.menubar_dict['menu_file'].addAction( self.action_dict['action_file_connect']), menu_file_quit=self.menubar_dict['menu_file'].addAction( self.action_dict['action_file_quit']), menu_view_normal_style=style_menu.addAction( self.action_dict['action_view_normal_style']), menu_view_dark_style=style_menu.addAction( self.action_dict['action_view_dark_style']), menu_about=self.menubar_dict['menu_help'].addAction( self.action_dict['action_about']), menu_about_qt=self.menubar_dict['menu_help'].addAction( self.action_dict['action_about_qt']), )
def __init__(self): super().__init__() appid = 'HikyuuAdmin' QtWidgets.QApplication.setApplicationName(appid) QtWidgets.QApplication.setOrganizationName("org.hikyuu") # 国际化支持 loc = QtCore.QLocale() if loc.language() == QtCore.QLocale.Chinese: self.trans = QtCore.QTranslator() self.trans.load("{}/language/zh_CN.qm".format(os.path.dirname(__file__))) # 读取qm语言包 _app = QtWidgets.QApplication.instance() # 应用实例 _app.installTranslator(self.trans) # 将翻译者安装到实例中 # 设置程序图标资源 # 如未能正常显示图标,请检查 "import resource" 是否 icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(":/logo/logo_16.png")) icon.addPixmap(QtGui.QPixmap(":/logo/logo_32.png")) icon.addPixmap(QtGui.QPixmap(":/logo/logo_48.png")) icon.addPixmap(QtGui.QPixmap(":/logo/logo_64.png")) icon.addPixmap(QtGui.QPixmap(":/logo/logo_128.png")) icon.addPixmap(QtGui.QPixmap(":/logo/logo_256.png")) self.setWindowIcon(icon) if sys.platform == 'win32': # window下设置任务栏图片 import ctypes ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(appid) self.ui_config = UiConfig() self.setObjectName("HikyuuAdminMainWindow") self.setWindowTitle(_translate("MainWindow", "Hikyuu Strategy Server Manager")) # 绑定本地数据库,辅助使用,尽量直接使用 Model 中的方法 self.db = get_local_db() self.initAction() self.initMenuBar() self.initMenu() self.initToolBar() self.initActionConnect() self.initMainTabWidget() self.initDockWidgets() self.statusBar().showMessage(_translate('MainWindow', 'Running')) # 在窗口初始化完毕后,根据历史信息对窗口风格和大小进行重置 style = self.ui_config.get('main_window', 'style', fallback='normal_style') if style == 'dark_style': QtWidgets.qApp.setStyleSheet(qdarkstyle.load_stylesheet(qt_api='pyqt5')) if self.ui_config.getboolean('main_window', 'maximized', fallback=False): self.showMaximized() else: self.resize( self.ui_config.getint('main_window', 'width', fallback=800), self.ui_config.getint('main_window', 'height', fallback=500) ) QtCore.QMetaObject.connectSlotsByName(self)
def retranslateUi(self): self.tree.headerItem().setText( 0, _translate("HkuSessionViewWidget", "name")) self.tree.headerItem().setText( 1, _translate("HkuSessionViewWidget", "status")) __sortingEnabled = self.tree.isSortingEnabled() #self.tree.setSortingEnabled(False) #self.tree.topLevelItem(0).setText(0, _translate("HkuSessionViewWidget", "local")) #self.tree.topLevelItem(0).child(0).setText(0, _translate("HkuSessionViewWidget", "account")) #self.tree.topLevelItem(1).setText(0, _translate("HkuSessionViewWidget", "other")) self.tree.setSortingEnabled(__sortingEnabled)
def getServerStatus(session: SessionModel): try: r = session_get(session, "assist", "status") if r["result"]: return "running", _translate("service", "running") else: return "stop", _translate("service", "failed! {}").format(r["errmsg"]) except Exception as e: logging.info("{}: {}".format(e.__class__.__name__, e)) return "stop", _translate("service", "failed connect!")
def openUserManageTab(self, session): """用户管理""" title = "{}({})".format(self.tab_title_user_manage, session.name) if title not in self.tabs or self.tabs[title] is None: if not session.running: QtWidgets.QMessageBox.warning( self, _translate("MainWindow", "info"), _translate( "MainWindow", "The server is disconnected. Please connect first!")) else: tab = HkuUserManagerWidget(session, self.main_tab) self.main_tab.addTab(tab, title) self.tabs[title] = tab
def actionAbout(self): msg = _translate( 'MainWindow', "<p><b>Hikyuu Strategy Server Manager</b><p>" "<p>Hikyuu strategy server management is used to " "manage quant trading strategies based on hikyuu " "quant framework</p>" "<p><b>Hikyuu Quant Framework</b></p>" "It is a high performance open source quantitative " "trading research framework based on C++/Python, " "which is used for stratgy analysis and back testing." "Now it only used in Chinese stock market)</p>" '<p>see more: <a href="https://hikyuu.org">https://hikyuu.org<a></p>' ) QtWidgets.QMessageBox.about(self, _translate('MainWindow', 'About Hikyuu Strategy Server Manager'), msg)
def actionConnect(self): item = self.server_view_dock.tree.currentItem() if item is None: logging.error("Can't get currentItem.") return session = item.data(0, QtCore.Qt.UserRole) status, msg = AssisService.getServerStatus(session) if not session.running: self.server_view_dock.set_gray(item) QtWidgets.QMessageBox.warning( self, _translate("MainWindow", "info"), _translate("MainWindow", "connection failed")) else: self.server_view_dock.set_default(item) self.server_view_dock.tree.viewport().update()
def actionConnect(self): item = self.server_view_dock.tree.currentItem() session = item.data(0, QtCore.Qt.UserRole) status, msg = AssisService.getServerStatus(session) icons = { "running": QtGui.QIcon(":/icon/circular_green.png"), "stop": QtGui.QIcon(":/icon/circular_yellow.png") } item.setText(1, msg) item.setIcon(1, icons[status]) self.server_view_dock.tree.viewport().update() if not session.running: QtWidgets.QMessageBox.warning( self, _translate("MainWindow", "info"), _translate("MainWindow", "connection failed"))
def on_add_pushButton_clicked(self): dialog = HkuEditXueqiuAccountDialog(self.session, self) if dialog.exec() > 0: try: r = TradeService.add_xq_account(self.session, dialog.name, dialog.cookies, dialog.portfolio_code, dialog.portfolio_market) info = ( r["td_id"], dialog.name, dialog.portfolio_code, dialog.portfolio_market, dialog.cookies, ) self.rest_data_model.insertRows(0, 1, QtCore.QModelIndex()) for i in range(len(info)): index = self.rest_data_model.index(0, i, QtCore.QModelIndex()) self.rest_data_model.setData(index, info[i], QtCore.Qt.EditRole) except Exception as e: QtWidgets.QMessageBox.warning(self, _translate("trade", "error"), str(e))
def actionEditSession(self): item = self.server_view_dock.tree.currentItem() server_session = self.db.session.query(SessionModel).filter_by(name=item.text(0)).first() if item else None if server_session is None: QtWidgets.QMessageBox.about( self, _translate("MainWindow", "info"), _translate("MainWindow", "Please select a session to execute") ) return edit_session_dialog = HkuEditSessionDialog(self) edit_session_dialog.setWindowTitle(_translate("MainWindow", "Edit Session")) edit_session_dialog.setData(server_session) if edit_session_dialog.exec() >= 0: session_data = edit_session_dialog.getData() session_data.save() self.server_view_dock.modifySession(item, session_data) edit_session_dialog.destroy()
def actionDeleteSession(self): item = self.server_view_dock.tree.currentItem() data = item.data(0, QtCore.Qt.UserRole) if item is not None else None if data is None: QtWidgets.QMessageBox.about( self, _translate("MainWindow", "info"), _translate("MainWindow", "Please select a session to execute")) return ret = QtWidgets.QMessageBox.question( self, _translate("MainWindow", "Confirm removal"), _translate("MainWindow", "Confirm to remove the session (%s)?") % item.text(0), QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No) if ret == QtWidgets.QMessageBox.Yes: root_index = self.server_view_dock.tree.indexOfTopLevelItem(item) self.server_view_dock.tree.takeTopLevelItem(root_index) data.delete()
def create_new_radiobutton(parent, text): new_radiobutton = QtWidgets.QRadioButton(parent) new_radiobutton.setObjectName("{}".format(new_radiobutton)) new_radiobutton.setFocusPolicy(Qt.ClickFocus) new_radiobutton.setText(_translate("MainWindow", text, None)) return new_radiobutton
def create_new_checkbox(parent, text, checked=False): new_checkbox = QtWidgets.QCheckBox(parent) new_checkbox.setObjectName(_fromUtf8("{}".format(new_checkbox))) new_checkbox.setText(_translate("MainWindow", text, None)) new_checkbox.setChecked(checked) return new_checkbox
def create_new_button(parent, text, command): new_button = QtWidgets.QPushButton(parent) new_button.setObjectName("{}".format(new_button)) new_button.setText(_translate("MainWindow", text, None)) if command != None: new_button.clicked.connect(lambda: command()) return new_button
def add_action(parent, menu, text, command): new_action = QtWidgets.QAction(parent) new_action.setObjectName(_fromUtf8("{}".format(new_action))) menu.addAction(new_action) new_action.setText(_translate("MainWindow", text, None)) new_action.triggered.connect(lambda: command()) return new_action
def on_refresh_pushButton_clicked(self): try: data = RestDataTableModel(['userid', 'name', 'start_time'], [ _translate("UserManage", "userid"), _translate("UserManage", "name"), _translate("UserManage", "start_time") ], UserService.query_users(self.session)) self.rest_data_model = data self.users_tableView.setModel(self.rest_data_model) # self.users_tableView.horizontalHeader().setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents) # self.users_tableView.horizontalHeader().setSectionResizeMode(0, QtWidgets.QHeaderView.Interactive) except Exception as e: logging.error(e) self.add_user_pushButton.setEnabled(False) QtWidgets.QMessageBox.warning( self, _translate("MainWindow", "error"), "{}: {}".format(e.__class__.__name__, e))
def __init__(self, session: SessionModel, parent): super(HkuXueqiuAccountWidget, self).__init__(parent) self.session = session self.setupUi(self) self.head = [ 'td_id', 'name', 'portfolio_code', 'portfolio_market', 'cookies' ] self.head_tr = [ _translate("trade", "td_id"), _translate("trade", "name"), _translate("trade", "portfolio_code"), _translate("trade", "portfolio_market"), _translate("trade", "cookies"), ] self.edit_pushButton.setEnabled(False) self.remove_pushButton.setEnabled(False) self.on_refresh_pushButton_clicked()
def actionNewSession(self): server_session = SessionModel() session_dialog = HkuEditSessionDialog(self) session_dialog.setWindowTitle(_translate("MainWindow", "New Session")) session_dialog.setData(server_session) if session_dialog.exec() >= 0: session_data = session_dialog.getData() session_data.save() self.server_view_dock.addSession(session_data) session_dialog.destroy()
def initMainTabWidget(self): self.main_tab = QtWidgets.QTabWidget() self.setCentralWidget(self.main_tab) # 设置为可关闭,并连接信号 self.main_tab.setTabsClosable(True) self.main_tab.tabCloseRequested.connect(self.closeTab) self.tab_title_user_manage = _translate("MainWindow", "User Manage") self.tabs = {}
def accept(self): if not self.name: QtWidgets.QMessageBox.warning( self, "error", _translate("UserManage", "The user name cannot be empty.")) return r = UserService.add_user(self.session, self.name, self.password) print(r) self.done(1)
def create_new_label(parent, text, wordwrap=False, clickable=False): new_label = ClickLabel() if clickable == False: new_label = QtWidgets.QLabel(parent) elif clickable == True: new_label = ClickLabel() new_label.setObjectName("{}".format(new_label)) new_label.setText(_translate("MainWindow", text, None)) new_label.setWordWrap(wordwrap) return new_label
def openUserManageTab(self, session): """用户管理""" title = "{}({})".format(self.tab_title_user_manage, session.name) if title not in self.tabs or self.tabs[title] is None: if not session.running: QtWidgets.QMessageBox.warning( self, _translate("MainWindow", "info"), _translate("MainWindow", "The server is disconnected. Please connect first!") ) else: try: data = RestDataTableModel( ['userid', 'name', 'start_time'], [ _translate("UserManage", "userid"), _translate("UserManage", "name"), _translate("UserManage", "start_time") ], UserService.query_users(session) ) print(data) except Exception as e: logging.error(e) QtWidgets.QMessageBox.warning( self, _translate("MainWindow", "error"), "{}: {}".format(e.__class__.__name__, e) ) return tab = HkuUserManagerWidget(session, data, self.main_tab) self.main_tab.addTab(tab, title) self.tabs[title] = tab
def on_refresh_pushButton_clicked(self): try: data = RestDataTableModel( self.head, self.head_tr, TradeService.query_xq_accounts(self.session)) self.rest_data_model = data self.tableView.setModel(self.rest_data_model) except Exception as e: logging.error(e) #self.add_user_pushButton.setEnabled(False) QtWidgets.QMessageBox.warning( self, _translate("trade", "error"), "{}: {}".format(e.__class__.__name__, e))
def accept(self) -> None: if not self.new_password: QtWidgets.QMessageBox.warning( self, _translate("PersonInfo", "error"), _translate("PersonInfo", "Please input new password")) return if self.old_password != self.session.password: QtWidgets.QMessageBox.warning( self, _translate("PersonInfo", "error"), _translate("PersonInfo", "The old password does not match")) return if self.new_password == self.old_password: QtWidgets.QMessageBox.warning( self, _translate("PersonInfo", "error"), _translate("PersonInfo", "The old and new passwords are the same")) return if self.new_password != self.confirm_password: QtWidgets.QMessageBox.warning( self, _translate("PersonInfo", "error"), _translate("PersonInfo", "The two passwords are different")) return try: UserService.change_password(self.session, self.old_password, self.new_password, self.confirm_password) self.session.password = self.new_password self.session.save() except Exception as e: QtWidgets.QMessageBox.warning(self, _translate("PersonInfo", "error"), str(e)) return self.done(1)