Esempio n. 1
0
class MyWidget(QWidget):

    def __init__(self, parent=None):
        super(QWidget, self).__init__(parent)
        self.btn1 = QRadioButton()
        self.btn2 = QRadioButton()
        self.create_UI()

    def create_UI(self):
        self.setWindowTitle("QRadioButton dome")
        # 初始化btn1
        self.btn1 = QRadioButton("button1")
        # 设置默认选中状态
        self.btn1.setCheckable(True)
        # 设置按钮选中状态发生变化时,发送信号
        self.btn1.toggled.connect(lambda: self.btnstate(self.btn1))

        # 初始化btn2
        self.btn2 = QRadioButton("button2")
        # 设置按钮选中状态发生变化时,发送信号
        self.btn2.toggled.connect(lambda: self.btnstate(self.btn2))

        # 布局
        layout = QHBoxLayout()
        layout.addWidget(self.btn1)
        layout.addWidget(self.btn2)
        self.setLayout(layout)

    def btnstate(self, btn):
        if btn.text() == "button1":
            if btn.isCheckable() == True:
                print(btn.text() + "is selected")
            else:
                print(btn.text() + "is deselected")

        if btn.text() == "button2":
            if btn.isCheckable() == True:
                print(btn.text() + "is selected")
            else:
                print(btn.text() + "is deselected")
class Demo(QWidget):
    def __init__(self):
        super(Demo, self).__init__()
        self.off_button = QRadioButton('off', self)  # 1
        self.on_button = QRadioButton('on', self)  # 2

        self.pic_label = QLabel(self)  # 3
        self.button_h_layout = QHBoxLayout()
        self.pic_h_layout = QHBoxLayout()
        self.all_v_layout = QVBoxLayout()

        self.layout_init()
        self.radiobutton_init()
        self.label_init()

    def layout_init(self):
        self.pic_h_layout.addStretch(1)  # 4
        self.pic_h_layout.addWidget(self.pic_label)
        self.pic_h_layout.addStretch(1)
        self.button_h_layout.addWidget(self.off_button)
        self.button_h_layout.addWidget(self.on_button)
        self.all_v_layout.addLayout(self.pic_h_layout)
        self.all_v_layout.addLayout(self.button_h_layout)

        self.setLayout(self.all_v_layout)

    def radiobutton_init(self):
        self.off_button.setCheckable(True)
        self.off_button.toggled.connect(self.on_off_bulb_func)

    def label_init(self):
        self.pic_label.setPixmap(QPixmap("off.png"))

    def on_off_bulb_func(self):
        if self.off_button.isChecked():
            self.pic_label.setPixmap(QPixmap('off.png'))
        else:
            self.pic_label.setPixmap(QPixmap('on.png'))
Esempio n. 3
0
class MainWindow(QMainWindow):

    def __init__(self, autoTradingSystem):

        super(MainWindow, self).__init__()
        self.ATM = autoTradingSystem
        self.initUI()

    def initUI(self):

        self.setStyle()
        self.setWindowTitle('Auto Trading System')
        self.initToolBar()
        self.initMenuBar()
        self.initMainBoard()
        self.techAnPage()
        #self.pairTrPage()

        # make window in center point
        self.setFixedSize(1000, 700)
        qr = self.frameGeometry()
        qr.moveCenter(QDesktopWidget().availableGeometry().center())
        self.move(qr.topLeft())

        self.show()

    def initMainBoard(self):

        self.mainBoard = QWidget()
        self.setCentralWidget(self.mainBoard)
        self.pagesStatus = [0]*5
        self.pages = [QWidget(self.mainBoard) for i in self.pagesStatus]
        self.toolButtons

        self.mainBoard.setStyleSheet(self.mainBoardQSS)
        for page in self.pages: page.setStyleSheet(self.pagesQSS)

    def initToolBar(self):

        self.toolBar = QToolBar("Tools")
        self.toolBar.setMovable(False)
        self.addToolBar(Qt.LeftToolBarArea, self.toolBar)
        self.toolBar.setIconSize(QSize(20, 20))

        self.techAnButton = QToolButton()
        self.techAnButton.setText("Technical analysis")
        self.techAnButton.setFixedSize(130, 25)
        self.pairTrButton = QToolButton()
        self.pairTrButton.setText("Pair Trading")
        self.pairTrButton.setFixedSize(130, 25)
        self.atoTrdButton = QToolButton()
        self.atoTrdButton.setText("Monitor")
        self.atoTrdButton.setFixedSize(130, 25)
        self.trdPnlButton = QToolButton()
        self.trdPnlButton.setText("PnL Report")
        self.trdPnlButton.setFixedSize(130, 25)
        self.trdHisButton = QToolButton()
        self.trdHisButton.setText("Trade History")
        self.trdHisButton.setFixedSize(130, 25)

        self.techAnButton.clicked.connect(self.techAnPage)
        self.pairTrButton.clicked.connect(self.pairTrPage)
        self.atoTrdButton.clicked.connect(self.atoTrdPage)
        self.trdPnlButton.clicked.connect(self.trdPnlPage)
        self.trdHisButton.clicked.connect(self.trdHisPage)

        self.toolBar.addWidget(self.techAnButton)
        self.toolBar.addWidget(self.pairTrButton)
        self.toolBar.addWidget(self.atoTrdButton)
        self.toolBar.addWidget(self.trdPnlButton)
        self.toolBar.addWidget(self.trdHisButton)
        self.toolButtons = [self.techAnButton, self.pairTrButton, self.atoTrdButton, self.trdPnlButton, self.trdHisButton]

    def initMenuBar(self):

        exitAction = QAction('&Exit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.triggered.connect(qApp.quit)

        techAnAction = QAction('&Technical Analysis', self)
        techAnAction.setShortcut('Ctrl+T')
        techAnAction.triggered.connect(self.techAnPage)
        pairTrAction = QAction('&Pair Trading', self)
        pairTrAction.setShortcut('Ctrl+P')
        pairTrAction.triggered.connect(self.pairTrPage)
        atoTrdAction = QAction('&Monitor', self)
        atoTrdAction.setShortcut('Ctrl+M')
        atoTrdAction.triggered.connect(self.atoTrdPage)
        trdPnlAction = QAction('&Profit And Loss Report', self)
        trdPnlAction.setShortcut('Ctrl+R')
        trdPnlAction.triggered.connect(self.trdPnlPage)
        trdHisAction = QAction('&Trade History', self)
        trdHisAction.setShortcut('Ctrl+H')
        trdHisAction.triggered.connect(self.trdHisPage)

        menubar = self.menuBar()
        menubar.setNativeMenuBar(False)
        fannsMenu = menubar.addMenu('&App')
        fannsMenu.addAction(exitAction)
        naviMenu = menubar.addMenu('&Navigate')
        naviMenu.addAction(techAnAction)
        naviMenu.addAction(pairTrAction)
        naviMenu.addAction(atoTrdAction)
        naviMenu.addAction(trdPnlAction)
        naviMenu.addAction(trdHisAction)

    # The technical analysis page
    def techAnPage(self):

        # hide all pages to show self page
        for pi in range(0,len(self.pages)):
            self.toolButtons[pi].setStyleSheet(self.toolButtonHideQSS)
            self.pages[pi].hide()

        print "in technical analysis page"
        ci = 0
        page = self.pages[ci]
        self.toolButtons[ci].setStyleSheet(self.toolButtonFocusQSS)

        if self.pagesStatus[ci] == 0:

            self.pageTechAnConfigWidget = QWidget(page)
            self.pageTechAnConfigWidget.setFixedSize(860, 700)

            pageMainVerticalBox = QVBoxLayout()
            pageMainVerticalBox.setContentsMargins(0, 5, 0, 0)

            self.pageTechAnTitleLabel = QLabel("Technical Analysis", page)
            self.pageTechAnTitleLabel.setFixedSize(860, 25)
            self.pageTechAnTitleLabel.setStyleSheet(self.pageTitleQSS)
            pageMainVerticalBox.addWidget(self.pageTechAnTitleLabel)

            # capital config components
            self.pageTechAnCapitalLabel = QLabel("Capital Config", page)
            self.pageTechAnCapitalLabel.setFixedSize(860, 25)
            self.pageTechAnCapitalLabel.setStyleSheet(self.pageSubTitleQSS)
            pageMainVerticalBox.addWidget(self.pageTechAnCapitalLabel)
            capitalHbox = QHBoxLayout()
            capitalHbox.setContentsMargins(30, 10, 0, 10)
            self.pageTechAnCapitalInputLabel = QLabel("Capital: ", page)
            self.pageTechAnCapitalInputLabel.setFont(self.contentFont)
            self.pageTechAnCapitalInputLabel.setFixedSize(100, 25)
            self.pageTechAnCapitalInputLabel.setStyleSheet(self.itemNameQSS)
            capitalHbox.addWidget(self.pageTechAnCapitalInputLabel)
            self.pageTechAnCapitalEdit = QLineEdit("$ 100,000,000")
            self.pageTechAnCapitalEdit.setStyleSheet(self.lineEditQSS)
            self.pageTechAnCapitalEdit.setFixedSize(300, 25)
            self.pageTechAnCapitalEdit.setEnabled(False)
            capitalHbox.addWidget(self.pageTechAnCapitalEdit)
            capitalHbox.addStretch(1)
            pageMainVerticalBox.addLayout(capitalHbox)

            # security code select components
            self.pageTechAnSecurityLabel = QLabel("Security Select", page)
            self.pageTechAnSecurityLabel.setFixedSize(860, 25)
            self.pageTechAnSecurityLabel.setStyleSheet(self.pageSubTitleQSS)
            pageMainVerticalBox.addWidget(self.pageTechAnSecurityLabel)
            securityHbox = QHBoxLayout()
            securityHbox.setContentsMargins(30, 10, 0, 10)
            self.pageTechAnSecurityCode= QLabel("Security Code: ", page)
            self.pageTechAnSecurityCode.setFont(self.contentFont)
            self.pageTechAnSecurityCode.setFixedSize(100, 25)
            self.pageTechAnSecurityCode.setStyleSheet(self.itemNameQSS)
            securityHbox.addWidget(self.pageTechAnSecurityCode)
            self.pageTechAnSecurityCombo = QComboBox(page)
            self.pageTechAnSecurityCombo.setFixedSize(300, 25)
            self.pageTechAnSecurityCombo.setStyleSheet(self.comboQSS)
            self.pageTechAnSecurityCombo.addItem("hsi_futures_jan")
            for item in self.ATM.data.getAssetList("./dataManager/data/hsi_futures"): self.pageTechAnSecurityCombo.addItem(item)
            securityHbox.addWidget(self.pageTechAnSecurityCombo)
            securityHbox.addStretch(1)
            pageMainVerticalBox.addLayout(securityHbox)

            # investment strategies select components
            self.pageTechAnStrategiesLabel = QLabel("Investment Strategies Select", page)
            self.pageTechAnStrategiesLabel.setFixedSize(860, 25)
            self.pageTechAnStrategiesLabel.setStyleSheet(self.pageSubTitleQSS)
            pageMainVerticalBox.addWidget(self.pageTechAnStrategiesLabel)
            self.pageTechAnStrategiesWidget = QWidget(page)
            self.pageTechAnStrategiesWidget.setFixedSize(700, 80)
            strategiesGrid = QGridLayout()
            strategiesGrid.setContentsMargins(30, 10, 0, 10)
            self.pageTechAnStrategyCheckBoxACOscillator = QCheckBox("  ACOscillator")
            self.pageTechAnStrategyCheckBoxCCICorrection= QCheckBox("  CCI Correction")
            self.pageTechAnStrategyCheckBoxDMRSIADX     = QCheckBox("  DM RSI ADX")
            self.pageTechAnStrategyCheckBoxMACD         = QCheckBox("  MACD")
            self.pageTechAnStrategyCheckBoxBreakoutsSwing=QCheckBox("  Breakouts Swing")
            self.pageTechAnStrategyCheckBoxOscillator313= QCheckBox("  Oscillator3 13")
            self.pageTechAnStrategyCheckBoxACOscillator.setChecked(False)
            self.pageTechAnStrategyCheckBoxCCICorrection.setChecked(False)
            self.pageTechAnStrategyCheckBoxDMRSIADX.setChecked(False)
            self.pageTechAnStrategyCheckBoxMACD.setChecked(True)
            self.pageTechAnStrategyCheckBoxBreakoutsSwing.setChecked(False)
            self.pageTechAnStrategyCheckBoxOscillator313.setChecked(False)
            strategiesGrid.addWidget(self.pageTechAnStrategyCheckBoxACOscillator, *(1, 1))
            strategiesGrid.addWidget(self.pageTechAnStrategyCheckBoxCCICorrection, *(1, 2))
            strategiesGrid.addWidget(self.pageTechAnStrategyCheckBoxDMRSIADX, *(1, 3))
            strategiesGrid.addWidget(self.pageTechAnStrategyCheckBoxMACD, *(2,1))
            strategiesGrid.addWidget(self.pageTechAnStrategyCheckBoxBreakoutsSwing, *(2,2))
            strategiesGrid.addWidget(self.pageTechAnStrategyCheckBoxOscillator313, *(2,3))
            self.pageTechAnStrategiesWidget.setLayout(strategiesGrid)
            pageMainVerticalBox.addWidget(self.pageTechAnStrategiesWidget)

            # trading time config components
            self.pageTechAnTimeSpanLabel = QLabel("Trading Time Config", page)
            self.pageTechAnTimeSpanLabel.setFixedSize(860, 25)
            self.pageTechAnTimeSpanLabel.setStyleSheet(self.pageSubTitleQSS)
            pageMainVerticalBox.addWidget(self.pageTechAnTimeSpanLabel)
            timeVbox = QVBoxLayout()
            timeVbox.setContentsMargins(30, 10, 0, 10)
            startTimeHbox = QHBoxLayout()
            self.pageTechAnStartTimeName = QLabel("Start Time: ", page)
            self.pageTechAnStartTimeName.setFont(self.contentFont)
            self.pageTechAnStartTimeName.setFixedSize(100, 25)
            self.pageTechAnStartTimeName.setStyleSheet(self.itemNameQSS)
            startTimeHbox.addWidget(self.pageTechAnStartTimeName)
            self.pageTechAnStartTimeEdit = QLineEdit("2016-02-10 16:00:00")
            self.pageTechAnStartTimeEdit.setEnabled(False)
            self.pageTechAnStartTimeEdit.setStyleSheet(self.lineEditQSS)
            self.pageTechAnStartTimeEdit.setFixedSize(300, 25)
            startTimeHbox.addWidget(self.pageTechAnStartTimeEdit)
            startTimeHbox.addStretch(1)
            timeVbox.addLayout(startTimeHbox)
            endTimeHbox = QHBoxLayout()
            self.pageTechAnEndTimeName = QLabel("End Time: ", page)
            self.pageTechAnEndTimeName.setFont(self.contentFont)
            self.pageTechAnEndTimeName.setFixedSize(100, 25)
            self.pageTechAnEndTimeName.setStyleSheet(self.itemNameQSS)
            endTimeHbox.addWidget(self.pageTechAnEndTimeName)
            self.pageTechAnEndTimeEdit = QLineEdit("2016-02-26 16:00:00")
            self.pageTechAnEndTimeEdit.setEnabled(False)
            self.pageTechAnEndTimeEdit.setStyleSheet(self.lineEditQSS)
            self.pageTechAnEndTimeEdit.setFixedSize(300, 25)
            endTimeHbox.addWidget(self.pageTechAnEndTimeEdit)
            endTimeHbox.addStretch(1)
            timeVbox.addLayout(endTimeHbox)
            pageMainVerticalBox.addLayout(timeVbox)

            # trading strategies select components
            self.pageTechAnTStrSpanLabel = QLabel("Trading Strategies Select", page)
            self.pageTechAnTStrSpanLabel.setFixedSize(860, 25)
            self.pageTechAnTStrSpanLabel.setStyleSheet(self.pageSubTitleQSS)
            pageMainVerticalBox.addWidget(self.pageTechAnTStrSpanLabel)
            self.pageTechAnTradeStrateWidget = QWidget(page)
            self.pageTechAnTradeStrateWidget.setFixedSize(700, 40)
            tradeStratGrid = QGridLayout()
            tradeStratGrid.setContentsMargins(30, 5, 0, 5)
            self.pageTechAnTStrRadioButtonVWAP = QRadioButton("  VWAP")
            self.pageTechAnTStrRadioButtonVWAP.setCheckable(False)
            self.pageTechAnTStrRadioButtonTWAP = QRadioButton("  TWAP")
            self.pageTechAnTStrRadioButtonTWAP.setChecked(True)
            self.pageTechAnTStrRadioButtonNONE = QRadioButton("  NONE")
            tradeStratGrid.addWidget(self.pageTechAnTStrRadioButtonVWAP, *(1, 1))
            tradeStratGrid.addWidget(self.pageTechAnTStrRadioButtonTWAP, *(1, 2))
            tradeStratGrid.addWidget(self.pageTechAnTStrRadioButtonNONE, *(1, 3))
            tradeStratGrid.addWidget(QLabel(), *(1, 4))
            tradeStratGrid.addWidget(QLabel(), *(1, 5))
            self.pageTechAnTradeStrateWidget.setLayout(tradeStratGrid)
            pageMainVerticalBox.addWidget(self.pageTechAnTradeStrateWidget)

            # position management method select components
            self.pageTechAnPManSpanLabel = QLabel("Position Management Method Select", page)
            self.pageTechAnPManSpanLabel.setFixedSize(860, 25)
            self.pageTechAnPManSpanLabel.setStyleSheet(self.pageSubTitleQSS)
            pageMainVerticalBox.addWidget(self.pageTechAnPManSpanLabel)
            self.pageTechAnPManageMthdWidget = QWidget(page)
            self.pageTechAnPManageMthdWidget.setFixedSize(700, 40)
            pManageMtdGrid = QGridLayout()
            pManageMtdGrid.setContentsMargins(30, 10, 0, 10)
            self.pageTechAnPMtdRadioButtonFixedFraction = QRadioButton("  Fixed Fraction")
            self.pageTechAnPMtdRadioButtonFixedFraction.setChecked(True)
            self.pageTechAnPMtdRadioButtonMaximDrawDown = QRadioButton("  Max Draw Down")
            pManageMtdGrid.addWidget(self.pageTechAnPMtdRadioButtonFixedFraction, *(1, 1))
            pManageMtdGrid.addWidget(self.pageTechAnPMtdRadioButtonMaximDrawDown, *(1, 2))
            pManageMtdGrid.addWidget(QLabel(), *(1, 3))
            pManageMtdGrid.addWidget(QLabel(), *(1, 4))
            pManageMtdGrid.addWidget(QLabel(), *(1, 5))
            self.pageTechAnPManageMthdWidget.setLayout(pManageMtdGrid)
            pageMainVerticalBox.addWidget(self.pageTechAnPManageMthdWidget)

            space = QWidget()
            space.setFixedSize(0, 0)
            pageMainVerticalBox.addWidget(space)

            self.pageTechAnLaunchButton = QPushButton("Launch")
            self.pageTechAnLaunchButton.setFont(self.contentFont)
            self.pageTechAnLaunchButton.setFixedSize(860, 40)
            self.pageTechAnLaunchButton.setStyleSheet(self.launchWdgtReadyQSS)
            self.pageTechAnLaunchButton.clicked.connect(self.pageTechAnLaunch)
            pageMainVerticalBox.addWidget(self.pageTechAnLaunchButton)

            page.setLayout(pageMainVerticalBox)

            self.pagesStatus[ci] = 1

        page.show()

    def pageTechAnLaunch(self):

        capital      = int("".join(re.split("\$| |,", self.pageTechAnCapitalEdit.text())))
        securityCode = self.pageTechAnSecurityCombo.currentText()

        investmentStrategies = []
        if self.pageTechAnStrategyCheckBoxACOscillator.isChecked()  : investmentStrategies.append("ACOscillator")
        if self.pageTechAnStrategyCheckBoxCCICorrection.isChecked() : investmentStrategies.append("CCI_Correction")
        if self.pageTechAnStrategyCheckBoxDMRSIADX.isChecked()      : investmentStrategies.append("DM_RSI_ADX")
        if self.pageTechAnStrategyCheckBoxMACD.isChecked()          : investmentStrategies.append("MACD")
        if self.pageTechAnStrategyCheckBoxBreakoutsSwing.isChecked(): investmentStrategies.append("breakouts_swing")
        if self.pageTechAnStrategyCheckBoxOscillator313.isChecked() : investmentStrategies.append("oscillator3_13")

        startTime = self.pageTechAnStartTimeEdit.text()
        endTime   = self.pageTechAnEndTimeEdit.text()

        tradeStrategy = None
        if self.pageTechAnTStrRadioButtonVWAP.isChecked()   : tradeStrategy = "VWAP"
        if self.pageTechAnTStrRadioButtonTWAP.isChecked()   : tradeStrategy = "TWAP"
        # if self.pageTechAnTStrRadioButtonPOV.isChecked()    : tradeStrategy = "POV"
        # if self.pageTechAnTStrRadioButtonSimple.isChecked() : tradeStrategy = "Simple"
        if self.pageTechAnTStrRadioButtonNONE.isChecked()   : tradeStrategy = "Default"

        positionManagement = None
        if self.pageTechAnPMtdRadioButtonFixedFraction.isChecked()  : positionManagement = "FixedFraction"
        if self.pageTechAnPMtdRadioButtonMaximDrawDown.isChecked()  : positionManagement = "MaximumDrawDown"

        thread.start_new_thread(self.ATM.launchTechnicalAnalysis, (capital, securityCode, investmentStrategies, startTime, endTime, tradeStrategy, positionManagement))

    def pageTechAnLaunchProcess(self):
        self.pageTechAnLaunchButton.setStyleSheet(self.launchWdgtProcesQSS)
        self.pageTechAnLaunchButton.setText("Processing")

    def pageTechAnLaunchFinish(self):
        self.pageTechAnLaunchButton.setStyleSheet(self.launchWdgtReadyQSS)
        self.pageTechAnLaunchButton.setText("Re-Launch")

    # The pair trading page
    def pairTrPage(self):

        # hide all pages to show self page
        for pi in range(0, len(self.pages)):
            self.toolButtons[pi].setStyleSheet(self.toolButtonHideQSS)
            self.pages[pi].hide()

        print "in pair trading page"
        ci = 1
        page = self.pages[ci]
        self.toolButtons[ci].setStyleSheet(self.toolButtonFocusQSS)

        if self.pagesStatus[ci] == 0:
            self.pagePairTrConfigWidget = QWidget(page)
            self.pagePairTrConfigWidget.setFixedSize(860, 700)

            pageMainVerticalBox = QVBoxLayout()
            pageMainVerticalBox.setContentsMargins(0, 5, 0, 0)

            self.pagePairTrTitleLabel = QLabel("Pair Trading")
            self.pagePairTrTitleLabel.setFixedSize(860, 25)
            self.pagePairTrTitleLabel.setStyleSheet(self.pageTitleQSS)
            pageMainVerticalBox.addWidget(self.pagePairTrTitleLabel)

            self.pagePairTrCapitalLabel = QLabel("Capital Config", page)
            self.pagePairTrCapitalLabel.setFixedSize(860, 25)
            self.pagePairTrCapitalLabel.setStyleSheet(self.pageSubTitleQSS)
            pageMainVerticalBox.addWidget(self.pagePairTrCapitalLabel)
            capitalHbox = QHBoxLayout()
            capitalHbox.setContentsMargins(30, 10, 0, 10)
            self.pagePairTrCapitalInputLabel = QLabel("Capital: ", page)
            self.pagePairTrCapitalInputLabel.setFont(self.contentFont)
            self.pagePairTrCapitalInputLabel.setFixedSize(100, 25)
            self.pagePairTrCapitalInputLabel.setStyleSheet(self.itemNameQSS)
            capitalHbox.addWidget(self.pagePairTrCapitalInputLabel)
            self.pagePairTrCapitalEdit = QLineEdit("$ 100,000,000")
            self.pagePairTrCapitalEdit.setStyleSheet(self.lineEditQSS)
            self.pagePairTrCapitalEdit.setFixedSize(300, 25)
            self.pagePairTrCapitalEdit.setEnabled(False)
            capitalHbox.addWidget(self.pagePairTrCapitalEdit)
            capitalHbox.addStretch(1)
            pageMainVerticalBox.addLayout(capitalHbox)

            self.pagePairTrSecurityLabel = QLabel("Security Select", page)
            self.pagePairTrSecurityLabel.setFixedSize(860, 25)
            self.pagePairTrSecurityLabel.setStyleSheet(self.pageSubTitleQSS)
            pageMainVerticalBox.addWidget(self.pagePairTrSecurityLabel)
            securityHbox = QHBoxLayout()
            securityHbox.setContentsMargins(30, 10, 0, 10)
            self.pagePairTrSecurityCode = QLabel("Security Basket: ", page)
            self.pagePairTrSecurityCode.setFont(self.contentFont)
            self.pagePairTrSecurityCode.setFixedSize(100, 25)
            self.pagePairTrSecurityCode.setStyleSheet(self.itemNameQSS)
            securityHbox.addWidget(self.pagePairTrSecurityCode)
            self.pagePairTrSecurities = QTextEdit(page)
            self.pagePairTrSecurities.setEnabled(False)
            self.pagePairTrSecurities.setFixedSize(600, 148)
            securities = ""
            for item in self.ATM.data.getAssetList("./dataManager/data/hsi_stocks"): securities += item + '   '
            self.pagePairTrSecurities.setText(securities)
            securityHbox.addWidget(self.pagePairTrSecurities)
            securityHbox.addStretch(1)
            pageMainVerticalBox.addLayout(securityHbox)

            self.pagePairTrTimeSpanLabel = QLabel("Trading Time Config", page)
            self.pagePairTrTimeSpanLabel.setFixedSize(860, 25)
            self.pagePairTrTimeSpanLabel.setStyleSheet(self.pageSubTitleQSS)
            pageMainVerticalBox.addWidget(self.pagePairTrTimeSpanLabel)
            timeVbox = QVBoxLayout()
            timeVbox.setContentsMargins(30, 10, 0, 10)
            startTimeHbox = QHBoxLayout()
            self.pagePairTrStartTimeName = QLabel("Start Time: ", page)
            self.pagePairTrStartTimeName.setFont(self.contentFont)
            self.pagePairTrStartTimeName.setFixedSize(100, 25)
            self.pagePairTrStartTimeName.setStyleSheet(self.itemNameQSS)
            startTimeHbox.addWidget(self.pagePairTrStartTimeName)
            self.pagePairTrStartTimeEdit = QLineEdit("2016-02-10 16:00:00")
            self.pagePairTrStartTimeEdit.setEnabled(False)
            self.pagePairTrStartTimeEdit.setStyleSheet(self.lineEditQSS)
            self.pagePairTrStartTimeEdit.setFixedSize(300, 25)
            startTimeHbox.addWidget(self.pagePairTrStartTimeEdit)
            startTimeHbox.addStretch(1)
            timeVbox.addLayout(startTimeHbox)
            endTimeHbox = QHBoxLayout()
            self.pagePairTrEndTimeName = QLabel("End Time: ", page)
            self.pagePairTrEndTimeName.setFont(self.contentFont)
            self.pagePairTrEndTimeName.setFixedSize(100, 25)
            self.pagePairTrEndTimeName.setStyleSheet(self.itemNameQSS)
            endTimeHbox.addWidget(self.pagePairTrEndTimeName)
            self.pagePairTrEndTimeEdit = QLineEdit("2016-02-26 16:00:00")
            self.pagePairTrEndTimeEdit.setEnabled(False)
            self.pagePairTrEndTimeEdit.setStyleSheet(self.lineEditQSS)
            self.pagePairTrEndTimeEdit.setFixedSize(300, 25)
            endTimeHbox.addWidget(self.pagePairTrEndTimeEdit)
            endTimeHbox.addStretch(1)
            timeVbox.addLayout(endTimeHbox)
            pageMainVerticalBox.addLayout(timeVbox)

            self.pagePairTrTStrSpanLabel = QLabel("Trading Strategies Select", page)
            self.pagePairTrTStrSpanLabel.setFixedSize(860, 25)
            self.pagePairTrTStrSpanLabel.setStyleSheet(self.pageSubTitleQSS)
            pageMainVerticalBox.addWidget(self.pagePairTrTStrSpanLabel)
            self.pagePairTrTradeStrateWidget = QWidget(page)
            self.pagePairTrTradeStrateWidget.setFixedSize(700, 40)
            tradeStratGrid = QGridLayout()
            tradeStratGrid.setContentsMargins(30, 5, 0, 5)
            self.pagePairTrTStrRadioButtonVWAP = QRadioButton("  VWAP")
            self.pagePairTrTStrRadioButtonVWAP.setCheckable(False)
            self.pagePairTrTStrRadioButtonTWAP = QRadioButton("  TWAP")
            self.pagePairTrTStrRadioButtonTWAP.setChecked(True)
            self.pagePairTrTStrRadioButtonNONE = QRadioButton("  NONE")
            tradeStratGrid.addWidget(self.pagePairTrTStrRadioButtonVWAP, *(1, 1))
            tradeStratGrid.addWidget(self.pagePairTrTStrRadioButtonTWAP, *(1, 2))
            tradeStratGrid.addWidget(self.pagePairTrTStrRadioButtonNONE, *(1, 3))
            tradeStratGrid.addWidget(QLabel(), *(1, 4))
            tradeStratGrid.addWidget(QLabel(), *(1, 5))
            self.pagePairTrTradeStrateWidget.setLayout(tradeStratGrid)
            pageMainVerticalBox.addWidget(self.pagePairTrTradeStrateWidget)

            self.pagePairTrPManSpanLabel = QLabel("Position Management Method Select", page)
            self.pagePairTrPManSpanLabel.setFixedSize(860, 25)
            self.pagePairTrPManSpanLabel.setStyleSheet(self.pageSubTitleQSS)
            pageMainVerticalBox.addWidget(self.pagePairTrPManSpanLabel)
            self.pagePairTrPManageMthdWidget = QWidget(page)
            self.pagePairTrPManageMthdWidget.setFixedSize(700, 40)
            pManageMtdGrid = QGridLayout()
            pManageMtdGrid.setContentsMargins(30, 10, 0, 10)
            self.pagePairTrPMtdRadioButtonFixedFraction = QRadioButton("  Fixed Fraction")
            self.pagePairTrPMtdRadioButtonFixedFraction.setChecked(True)
            self.pagePairTrPMtdRadioButtonMaximDrawDown = QRadioButton("  Max Draw Down")
            pManageMtdGrid.addWidget(self.pagePairTrPMtdRadioButtonFixedFraction, *(1, 1))
            pManageMtdGrid.addWidget(self.pagePairTrPMtdRadioButtonMaximDrawDown, *(1, 2))
            pManageMtdGrid.addWidget(QLabel(), *(1, 3))
            pManageMtdGrid.addWidget(QLabel(), *(1, 4))
            pManageMtdGrid.addWidget(QLabel(), *(1, 5))
            self.pagePairTrPManageMthdWidget.setLayout(pManageMtdGrid)
            pageMainVerticalBox.addWidget(self.pagePairTrPManageMthdWidget)

            space = QWidget()
            space.setFixedSize(0, 0)
            pageMainVerticalBox.addWidget(space)

            self.pagePairTrLaunchButton = QPushButton("Launch")
            self.pagePairTrLaunchButton.setFont(self.contentFont)
            self.pagePairTrLaunchButton.setFixedSize(860, 40)
            self.pagePairTrLaunchButton.setStyleSheet(self.launchWdgtReadyQSS)
            self.pagePairTrLaunchButton.clicked.connect(self.pagePairTrdLaunch)
            pageMainVerticalBox.addWidget(self.pagePairTrLaunchButton)

            page.setLayout(pageMainVerticalBox)

            self.pagesStatus[ci] = 1

        page.show()

    def pagePairTrdLaunch(self):

        capital = int("".join(re.split("\$| |,", self.pagePairTrCapitalEdit.text())))

        investmentStrategies = ["pairstrading", ]

        startTime = self.pagePairTrStartTimeEdit.text()
        endTime = self.pagePairTrEndTimeEdit.text()

        tradeStrategy = None
        if self.pagePairTrTStrRadioButtonVWAP.isChecked(): tradeStrategy = "VWAP"
        if self.pagePairTrTStrRadioButtonTWAP.isChecked(): tradeStrategy = "TWAP"
        if self.pagePairTrTStrRadioButtonNONE.isChecked(): tradeStrategy = "Default"

        positionManagement = None
        if self.pagePairTrPMtdRadioButtonFixedFraction.isChecked(): positionManagement = "FixedFraction"
        if self.pagePairTrPMtdRadioButtonMaximDrawDown.isChecked(): positionManagement = "MaximumDrawDown"

        thread.start_new_thread(self.ATM.launchPairTradingAnalysis, (capital, investmentStrategies, startTime, endTime, tradeStrategy, positionManagement))

    def pagePairTrdLaunchProcess(self):
        self.pagePairTrLaunchButton.setStyleSheet(self.launchWdgtProcesQSS)
        self.pagePairTrLaunchButton.setText("Processing")

    def pagePairTrdLaunchFinish(self):
        self.pagePairTrLaunchButton.setStyleSheet(self.launchWdgtReadyQSS)
        self.pagePairTrLaunchButton.setText("Re-Launch")

    def atoTrdPage(self):

        for pi in range(0,len(self.pages)):
            self.toolButtons[pi].setStyleSheet(self.toolButtonHideQSS)
            self.pages[pi].hide()

        print "in monitor page"
        ci = 2
        page = self.pages[ci]
        self.toolButtons[ci].setStyleSheet(self.toolButtonFocusQSS)

        if self.pagesStatus[ci] == 0:

            if not page.layout() == None:
                while page.layout().count() > 0:
                    page.layout().takeAt(0).widget().setParent(None)

            if page.layout() == None:
                self.pageAutoTrdPageMainVerticalBox = QVBoxLayout()
                self.pageAutoTrdPageMainVerticalBox.setContentsMargins(0, 5, 0, 0)
                page.setLayout(self.pageAutoTrdPageMainVerticalBox)

            self.pageAutoTrdTitleLabel = QLabel("Monitor", page)
            self.pageAutoTrdTitleLabel.setFixedSize(860, 25)
            self.pageAutoTrdTitleLabel.setStyleSheet(self.pageTitleQSS)
            self.pageAutoTrdPageMainVerticalBox.addWidget(self.pageAutoTrdTitleLabel)

            pnlReport = self.ATM.report
            if not len(self.ATM.strategies.strategiesPool.keys()) == 0:
                self.pageAtoTrdPageScroll = QScrollArea(page)
                self.pageAtoTrdPageScroll.setWidgetResizable(True)
                self.pageAtoTrdPageScroll.setBackgroundRole(QPalette.NoRole)
                self.pageAtoTrdPageScroll.setStyleSheet("background: transparent")
                self.pageAtoTrdPageScroll.setFixedSize(860, 635)
                self.pageAtoTrdScrollContentsWidget = QWidget(page)
                scrollContentVBox = QVBoxLayout()
                scrollContentVBox.setAlignment(Qt.AlignTop)
                scrollContentVBox.setContentsMargins(0, 0, 0, 0)

                self.pageAtoTrdSignalPlotLabel = QLabel("Signals Plots", page)
                self.pageAtoTrdSignalPlotLabel.setFixedSize(860, 25)
                self.pageAtoTrdSignalPlotLabel.setStyleSheet(self.pageSubTitleQSS)
                scrollContentVBox.addWidget(self.pageAtoTrdSignalPlotLabel)

                path = "./strategies/image/"
                for file in os.listdir(path):
                    if file.endswith(".png") and file.split('.')[0] in self.ATM.strategies.strategiesPool.keys():
                        pageAtoTrdSignalPlotStrategyLabel = QLabel(file.split('.')[0], page)
                        pageAtoTrdSignalPlotStrategyLabel.setFixedSize(860, 25)
                        pageAtoTrdSignalPlotStrategyLabel.setStyleSheet(self.pageSubSubTitleQSS)
                        scrollContentVBox.addWidget(pageAtoTrdSignalPlotStrategyLabel)

                        widget = QWidget()
                        widget.setFixedHeight(300)
                        hbox = QHBoxLayout()
                        hbox.setContentsMargins(0, 0, 0, 0)
                        hbox.setAlignment(Qt.AlignCenter)
                        lbl = QLabel()
                        pixmap = QPixmap(path + file)
                        scaled_pixmap = pixmap.scaled(860, 330, Qt.KeepAspectRatio)
                        lbl.setPixmap(scaled_pixmap)
                        hbox.addWidget(lbl)
                        widget.setLayout(hbox)
                        scrollContentVBox.addWidget(widget)

                self.pageAtoTrdAllSignalsLabel = QLabel("All Signals", page)
                self.pageAtoTrdAllSignalsLabel.setFixedSize(860, 25)
                self.pageAtoTrdAllSignalsLabel.setStyleSheet(self.pageSubTitleQSS)
                scrollContentVBox.addWidget(self.pageAtoTrdAllSignalsLabel)

                self.pageAtoTrdAllSignalsTitle = QWidget(page)
                self.pageAtoTrdAllSignalsTitle.setFixedSize(860, 25)
                self.pageAtoTrdAllSignalsTitle.setStyleSheet(self.pageSubSubTitleQSS)
                titlesHBox = QHBoxLayout()
                titlesHBox.setContentsMargins(10, 0, 20, 0)
                titlesHBox.addWidget(QLabel("Code"))
                titlesHBox.addWidget(QLabel("Time"))
                titlesHBox.addWidget(QLabel("Action"))
                titlesHBox.addWidget(QLabel("Qnt"))
                titlesHBox.addWidget(QLabel("Price"))
                titlesHBox.addWidget(QLabel("Volumn"))
                titlesHBox.addWidget(QLabel("Strategy"))
                self.pageAtoTrdAllSignalsTitle.setLayout(titlesHBox)
                scrollContentVBox.addWidget(self.pageAtoTrdAllSignalsTitle)

                signals = self.ATM.strategies.signals
                if not len(signals) == 0:
                    for i in xrange(len(signals)):
                        widget = QWidget(page)
                        widget.setFixedHeight(15)
                        widget.setStyleSheet("color:#ffffff")
                        signalHBox = QHBoxLayout()
                        signalHBox.setContentsMargins(20, 0, 10, 0)
                        signalHBox.addWidget(QLabel(signals.ix[i]["Code"]))
                        signalHBox.addWidget(QLabel(str(signals.ix[i]["Time"])))
                        signalHBox.addWidget(QLabel(signals.ix[i]["Action"]))
                        signalHBox.addWidget(QLabel(str(signals.ix[i]["Qnt"])))
                        signalHBox.addWidget(QLabel(str(signals.ix[i]["Price"])))
                        signalHBox.addWidget(QLabel(str(signals.ix[i]["Volume"])))
                        signalHBox.addWidget(QLabel(signals.ix[i]["Strategy"]))
                        widget.setLayout(signalHBox)
                        scrollContentVBox.addWidget(widget)

                else:
                    widget = QLabel("No Data.")
                    widget.setFixedSize(860, 550)
                    widget.setStyleSheet(self.noDataLabelQSS)
                    widget.setAlignment(Qt.AlignCenter)
                    scrollContentVBox.addWidget(widget)

                self.pageAtoTrdScrollContentsWidget.setLayout(scrollContentVBox)
                self.pageAtoTrdPageScroll.setWidget(self.pageAtoTrdScrollContentsWidget)
                self.pageAutoTrdPageMainVerticalBox.addWidget(self.pageAtoTrdPageScroll)

            else:
                widget = QLabel("No Data.")
                widget.setFixedSize(860, 550)
                widget.setStyleSheet(self.noDataLabelQSS)
                widget.setAlignment(Qt.AlignCenter)
                self.pageAutoTrdPageMainVerticalBox.addWidget(widget)

            self.pagesStatus[ci] = 1

        page.show()

    def trdPnlPage(self):

        for pi in range(0,len(self.pages)):
            self.toolButtons[pi].setStyleSheet(self.toolButtonHideQSS)
            self.pages[pi].hide()

        print "in profit and loss report page"
        ci = 3
        page = self.pages[ci]
        self.toolButtons[ci].setStyleSheet(self.toolButtonFocusQSS)

        if self.pagesStatus[ci] == 0:

            if not page.layout() == None:
                while page.layout().count() > 0:
                    page.layout().takeAt(0).widget().setParent(None)

            if page.layout() == None:
                self.pageTrdPnlPageMainVerticalBox = QVBoxLayout()
                self.pageTrdPnlPageMainVerticalBox.setContentsMargins(0, 5, 0, 0)
                page.setLayout(self.pageTrdPnlPageMainVerticalBox)

            self.pageTrdHisTitleLabel = QLabel("Profit And Loss Report", page)
            self.pageTrdHisTitleLabel.setFixedSize(860, 25)
            self.pageTrdHisTitleLabel.setStyleSheet(self.pageTitleQSS)
            self.pageTrdPnlPageMainVerticalBox.addWidget(self.pageTrdHisTitleLabel)

            pnlReport = self.ATM.report
            if not len(pnlReport) == 0:

                self.pageTrdHisBookTitles = QWidget(page)
                self.pageTrdHisBookTitles.setFixedSize(860, 25)
                self.pageTrdHisBookTitles.setStyleSheet(self.pageSubTitleQSS)
                titlesHBox = QHBoxLayout()
                titlesHBox.setContentsMargins(10, 0, 20, 0)
                strategy = QLabel("Strategy")
                titlesHBox.addWidget(QLabel("Strategy"))
                titlesHBox.addWidget(QLabel("Realized PnL"))
                titlesHBox.addWidget(QLabel("Return"))
                areturn = QLabel("Annual Return")
                areturn.setFixedWidth(130)
                titlesHBox.addWidget(areturn)
                titlesHBox.addWidget(QLabel("Volatility"))
                titlesHBox.addWidget(QLabel("Sharpe Ratio"))
                mdd = QLabel("Maximum Draw Down")
                mdd.setFixedWidth(155)
                titlesHBox.addWidget(mdd)
                self.pageTrdHisBookTitles.setLayout(titlesHBox)
                self.pageTrdPnlPageMainVerticalBox.addWidget(self.pageTrdHisBookTitles)


                self.pageTrdHisPageScroll = QScrollArea(page)
                self.pageTrdHisPageScroll.setWidgetResizable(True)
                self.pageTrdHisPageScroll.setBackgroundRole(QPalette.NoRole)
                self.pageTrdHisPageScroll.setStyleSheet("background: transparent")
                self.pageTrdHisPageScroll.setFixedSize(860, 600)
                self.pageTrdHisScrollContentsWidget = QWidget(page)
                scrollContentVBox = QVBoxLayout()
                scrollContentVBox.setAlignment(Qt.AlignTop)
                scrollContentVBox.setContentsMargins(0, 0, 0, 0)
                for i in xrange(0, len(pnlReport)):
                    widget = QWidget()
                    widget.setFixedHeight(15)
                    if pnlReport.ix[i]["realized PnL"] > 0: widget.setStyleSheet("color:#fa2020")
                    if pnlReport.ix[i]["realized PnL"] < 0: widget.setStyleSheet("color:#27AE60")
                    hbox   = QHBoxLayout()
                    hbox.setContentsMargins(20, 0, 10, 0)
                    strategy = QLabel(pnlReport.ix[i]["Strategy"])
                    strategy.setFixedWidth(100)
                    hbox.addWidget(strategy)
                    hbox.addWidget(QLabel(str("{0:.2f}".format(pnlReport.ix[i]["realized PnL"]))))
                    hbox.addWidget(QLabel(str("{0:.4f}".format(pnlReport.ix[i]["Return"]))))
                    areturn = QLabel(str("{0:.4f}".format(pnlReport.ix[i]["Annualized Return"])))
                    # hbox.addWidget(QLabel(str("{0:.2f}".format(tradeHistory.ix[i]["QntPer"] * 100))))
                    areturn.setFixedWidth(130)
                    hbox.addWidget(areturn)
                    hbox.addWidget(QLabel(str("{0:.4f}".format(pnlReport.ix[i]["Volatility"]))))
                    hbox.addWidget(QLabel(str("{0:.4f}".format(pnlReport.ix[i]["Sharpe Ratio"]))))
                    mdd = QLabel(str("{0:.6f}".format(pnlReport.ix[i]["MDD"])))
                    mdd.setFixedWidth(155)
                    hbox.addWidget(mdd)
                    widget.setLayout(hbox)
                    scrollContentVBox.addWidget(widget)
                self.pageTrdHisScrollContentsWidget.setLayout(scrollContentVBox)
                self.pageTrdHisPageScroll.setWidget(self.pageTrdHisScrollContentsWidget)
                self.pageTrdPnlPageMainVerticalBox.addWidget(self.pageTrdHisPageScroll)

            else:
                widget = QLabel("No Data.")
                widget.setFixedSize(860, 550)
                widget.setStyleSheet(self.noDataLabelQSS)
                widget.setAlignment(Qt.AlignCenter)
                self.pageTrdPnlPageMainVerticalBox.addWidget(widget)

            self.pagesStatus[ci] = 1

        page.show()

    def trdHisPage(self):

        for pi in range(0,len(self.pages)):
            self.toolButtons[pi].setStyleSheet(self.toolButtonHideQSS)
            self.pages[pi].hide()

        print "in trade history page"
        ci = 4
        page = self.pages[ci]
        self.toolButtons[ci].setStyleSheet(self.toolButtonFocusQSS)

        if self.pagesStatus[ci] == 0:

            if not page.layout() == None:
                while page.layout().count() > 0:
                    page.layout().takeAt(0).widget().setParent(None)

            if page.layout() == None:
                self.pageTrdHisPageMainVerticalBox = QVBoxLayout()
                self.pageTrdHisPageMainVerticalBox.setContentsMargins(0, 5, 0, 0)
                page.setLayout(self.pageTrdHisPageMainVerticalBox)

            self.pageTrdHisTitleLabel = QLabel("Trade History", page)
            self.pageTrdHisTitleLabel.setFixedSize(860, 25)
            self.pageTrdHisTitleLabel.setStyleSheet(self.pageTitleQSS)
            self.pageTrdHisPageMainVerticalBox.addWidget(self.pageTrdHisTitleLabel)

            tradeHistory = self.ATM.account.queryTradeHistory()

            if not len(tradeHistory) == 0:
                self.pageTrdHisBookTitles = QWidget(page)
                self.pageTrdHisBookTitles.setFixedSize(860, 25)
                self.pageTrdHisBookTitles.setStyleSheet(self.pageSubTitleQSS)
                titlesHBox = QHBoxLayout()
                titlesHBox.setContentsMargins(10, 0, 20, 0)
                code = QLabel("Code")
                code.setFixedWidth(100)
                titlesHBox.addWidget(code)
                time = QLabel("Time")
                time.setFixedWidth(145)
                titlesHBox.addWidget(time)
                titlesHBox.addWidget(QLabel("Action"))
                qnt = QLabel("Qnt")
                qnt.setFixedWidth(50)
                titlesHBox.addWidget(qnt)
                titlesHBox.addWidget(QLabel("Occupy"))
                titlesHBox.addWidget(QLabel("Price"))
                titlesHBox.addWidget(QLabel("PnL"))
                titlesHBox.addWidget(QLabel("Equity"))
                strategy = QLabel("Strategy")
                strategy.setFixedWidth(100)
                titlesHBox.addWidget(strategy)
                self.pageTrdHisBookTitles.setLayout(titlesHBox)
                self.pageTrdHisPageMainVerticalBox.addWidget(self.pageTrdHisBookTitles)

                self.pageTrdHisPageScroll = QScrollArea(page)
                self.pageTrdHisPageScroll.setWidgetResizable(True)
                self.pageTrdHisPageScroll.setBackgroundRole(QPalette.NoRole)
                self.pageTrdHisPageScroll.setStyleSheet("background: transparent")
                self.pageTrdHisPageScroll.setFixedSize(860, 600)
                self.pageTrdHisScrollContentsWidget = QWidget(page)
                scrollContentVBox = QVBoxLayout()
                scrollContentVBox.setContentsMargins(0, 0, 0, 0)
                scrollContentVBox.setAlignment(Qt.AlignTop)
                for i in xrange(0, len(tradeHistory)):
                    widget = QWidget()
                    widget.setFixedHeight(15)
                    if tradeHistory.ix[i]["Action"] == "Short" : widget.setStyleSheet("color:#27AE60")
                    if tradeHistory.ix[i]["Action"] == "SellToCover"  : widget.setStyleSheet("color:#27AE60")
                    if tradeHistory.ix[i]["Action"] == "Long" : widget.setStyleSheet("color:#fa2020")
                    if tradeHistory.ix[i]["Action"] == "BuyToCover" : widget.setStyleSheet("color:#fa2020")
                    hbox   = QHBoxLayout()
                    hbox.setContentsMargins(20, 0, 10, 0)
                    code = QLabel(str(tradeHistory.ix[i]["Code"])); code.setFixedWidth(100); hbox.addWidget(code);
                    time = QLabel(str(tradeHistory.ix[i]["Time"])); time.setFixedWidth(145); hbox.addWidget(time);
                    hbox.addWidget(QLabel(tradeHistory.ix[i]["Action"]))
                    qnt = QLabel(str(tradeHistory.ix[i]["Qnt"])); qnt.setFixedWidth(50); hbox.addWidget(qnt);
                    hbox.addWidget(QLabel(str("{0:.2f}".format(tradeHistory.ix[i]["QntPer"] * 100))+"%"))
                    hbox.addWidget(QLabel(str(round(tradeHistory.ix[i]["Price"]))))
                    pnl = QLabel()
                    if not tradeHistory.ix[i]["PnL"] == "": pnl = QLabel(str(round(float(tradeHistory.ix[i]["PnL"]))));
                    hbox.addWidget(pnl)
                    hbox.addWidget(QLabel(str(round(tradeHistory.ix[i]["Equity"]))))
                    strategy = QLabel(tradeHistory.ix[i]["Strategy"]); strategy.setFixedWidth(100); hbox.addWidget(strategy);
                    widget.setLayout(hbox)
                    scrollContentVBox.addWidget(widget)
                self.pageTrdHisScrollContentsWidget.setLayout(scrollContentVBox)
                self.pageTrdHisPageScroll.setWidget(self.pageTrdHisScrollContentsWidget)
                self.pageTrdHisPageMainVerticalBox.addWidget(self.pageTrdHisPageScroll)

            else:
                widget = QLabel("No Data.")
                widget.setFixedSize(860, 550)
                widget.setStyleSheet(self.noDataLabelQSS)
                widget.setAlignment(Qt.AlignCenter)
                self.pageTrdHisPageMainVerticalBox.addWidget(widget)

            self.pagesStatus[ci] = 1

        page.show()

    def setStyle(self):

        self.setStyleSheet(
            "QToolBar {" +
                "background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #203138, stop: 1.0 #000000);" +
                "border-right: 1px solid #065279;" +
                "padding: 5px}" +
            "QToolBar > QToolButton {" +
                "color: #ffffff;" +
                "font-family:'ArialRegular';" +
                "font-size: 14px}" +
            "QToolBar > QToolButton:hover {" +
                "background: qlineargradient(x1: 0, y1: 1, x2: 0, y2: 0, stop: 0 #ffcb06, stop: 1.0 #ff9c28);" +
                "border-radius:3px}" +
            "QLabel {" +
                "font-family:'ArialRegular';" +
                "padding: 10px;}" +
            "QPushButton {" +
                "height: 20px}" +
            "QComboBox {" +
                "border-radius: 1px; " +
                "border-top-right-radius:11px;" +
                "border-bottom-right-radius:11px;" +
                "font-family:'ArialRegular'}" +
            "QComboBox::drop-down {" +
                "width:15px;" +
                "background-color: #ff9c28;" +
                "border-top-right-radius:10px;" +
                "border-bottom-right-radius:10px;}" +
            "QCheckBox {" +
                "color: #ffffff;" +
                "font-family:'ArialRegular'}" +
            "QCheckBox::indicator {" +
                "background-color:#ffffff;" +
                "border-radius: 1px}" +
            "QCheckBox::indicator:checked {" +
                "background-color:#ff9c28}" +
            "QLineEdit {" +
                "background:#ff9c28;" +
                "border-radius:1px}" +
            "QLineEdit:focus {" +
                "border-radius:1px;}" +
            "QRadioButton {color: #ffffff}" +
            "QScrollArea {border:0px; background:transparent}" +
            "QTextEdit {padding-left: 5px; border: 0px; font-family: 'ArialRegular'; font-weight:20; font-size:14px; background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #ec2f4b, stop: 1.0 #85030f);}"
        )

        self.mainBoardQSS       = "padding:0px; background:qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #203138, stop: 1.0 #000000);"
        self.pagesQSS           = "background:none; padding: 0px"
        self.pageTitleQSS       = "padding-left:5px; background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #ec2f4b, stop: 1.0 #85030f); color: #ffffff; font-family: 'ArialRegular'; font-weight:20; font-size: 16px"
        self.pageSubTitleQSS    = "padding-left:5px; background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #495d76, stop: 1.0 #1f4e7c); color: #dddddd; font-family: 'ArialRegular'; font-weight:20; font-size: 14px"
        self.pageSubSubTitleQSS = "padding-left:5px; background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #646464, stop: 1.0 #838683); color: #dddddd; font-family: 'ArialRegular'; font-weight:20; font-size: 14px"
        self.toolButtonHideQSS  = "background:none; font-size: 14px; font-family:'ArialRegular'"
        self.toolButtonFocusQSS = "background:qlineargradient(x1: 0, y1: 1, x2: 0, y2: 0, stop: 0 #ffcb06, stop: 1.0 #ff9c28);border-radius:3px; color:#000000"
        self.itemNameQSS        = "color: #ffffff; font-family: 'ArialRegular'"
        self.comboQSS           = "padding-left:5px;background:qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #eeeeee, stop: 1.0 #dddddd);"
        self.lineEditQSS        = "background:qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #eeeeee, stop: 1.0 #dddddd);border: 0px; padding-left:5px; font-family:'ArialRegular'; font-weight:20; font-size: 14px"
        self.launchWdgtReadyQSS = "background:qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #004900, stop: 1.0 #033502);border: 0px; color:#ffffff"
        self.launchWdgtProcesQSS= "background:qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #006602, stop: 1.0 #007b03);border: 0px; color:#ffffff"
        self.tableTitleQSS      = "padding-left:5px; background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #495d76, stop: 1.0 #1f4e7c); color: #dddddd; font-family: 'ArialRegular'; font-weight:20; font-size: 14px"
        self.noDataLabelQSS     = "color: #ffffff; font-family: ArialRegular; font-weight: 20; font-size: 14px"
        self.pageTitleFont  = QFont('ArialRegular')
        self.titleFont      = QFont('ArialRegular')
        self.contentFont    = QFont('ArialRegular')

        self.pageTitleColor = "#ffffff"
        self.titleColor     = "#ffffff"
        self.contentColor   = "#ffffff"
Esempio n. 4
0
    def __init__(self, parent, name=None):
        super().__init__()
        self.parent = parent
        self.name = name

        self.cron_job = None

        self.layout = QHBoxLayout()

        self.setMovable(True)
        self.is_running = False
        self.is_enabled_checkbox = QCheckBox(self.name)

        self.num_tanks = 30
        self.num_quantity = ["1", "2", "3", "4"]
        self.program_settings = {
            "Program_name": self.name,
            "Enabled": self.is_enabled_checkbox.isChecked(),
            "Type": "Feeding and washing",
            "Day": None,
            "Time": None,
            "Tanks": [None] * self.num_tanks
        }
        program_default = copy(self.program_settings)

        # Layout left
        self.left_layout = QVBoxLayout()
        self.left_layout.setAlignment(Qt.AlignTop)

        self.button_startstop = QPushButton("Run", self)
        self.button_startstop.setFixedSize(QtCore.QSize(100, 35))
        self.button_startstop.setCheckable(True)
        self.button_startstop.clicked.connect(lambda: self.start_program())
        self.button_reset = QPushButton("Reset", self)
        self.button_reset.setFixedSize(QtCore.QSize(100, 35))
        self.button_reset.clicked.connect(lambda: self.reset(program_default))
        self.button_reset.clicked.connect(lambda: self.repaint())
        self.button_duplicate = QPushButton("Duplicate", self)
        self.button_duplicate.setFixedSize(QtCore.QSize(100, 35))
        self.button_duplicate.clicked.connect(lambda: self.duplicate())
        self.button_delete = QPushButton("Delete", self)
        self.button_delete.setFixedSize(QtCore.QSize(100, 35))
        self.button_delete.clicked.connect(lambda: self.delete_tab())

        self.first_button_row_layout = QHBoxLayout()
        self.first_button_row_layout.setAlignment(Qt.AlignLeft)
        self.first_button_row_layout.addWidget(self.button_startstop)
        self.first_button_row_layout.addWidget(self.button_reset)

        self.second_button_row_layout = QHBoxLayout()
        self.second_button_row_layout.setAlignment(Qt.AlignLeft)
        self.second_button_row_layout.addWidget(self.button_duplicate)
        self.second_button_row_layout.addWidget(self.button_delete)

        self.left_layout.addLayout(self.first_button_row_layout)
        self.left_layout.addLayout(self.second_button_row_layout)

        # Create a button group for feed & washing
        self.bgroup1_1 = QButtonGroup(self)
        # self.bgroup1_1.setExclusive(False)
        self.button_feeding = QRadioButton("Feeding and washing", self)
        self.button_feeding.setCheckable(True)
        self.button_feeding.setChecked(True)
        self.button_washing = QRadioButton("Only washing", self)
        # self.button_washing.setEnabled(False)
        self.button_washing.setCheckable(True)

        self.bgroup1_1.addButton(self.button_feeding, 1)
        self.bgroup1_1.addButton(self.button_washing, 2)
        self.bgroup1_1.buttonClicked.connect(
            lambda: self.record_log("Type", self.bgroup1_1))

        # Create a group box for feeding & washing
        gpbox1_1 = QGroupBox("Program Type")
        grid = QVBoxLayout()
        grid.addWidget(self.button_feeding)
        grid.addWidget(self.button_washing)
        grid.setAlignment(Qt.AlignLeft)
        gpbox1_1.setLayout(grid)
        self.left_layout.addWidget(gpbox1_1)

        # Create a button group for day of week
        self.button_dow = [
            'Monday',
            'Tuesday',
            'Wednesday',
            'Thursday',
            'Friday',
            'Saturday',
            'Sunday',
            'Everyday',
        ]
        self.bgroup1_2 = QButtonGroup(self)
        self.bgroup1_2.setExclusive(False)
        for id, name in enumerate(self.button_dow):
            button = QCheckBox(name, self)
            button.stateChanged.connect(lambda: self.update_active_days())
            if name == 'Everyday':
                button.clicked.connect(lambda: self.check_everyday())
            self.bgroup1_2.addButton(button, id)

        # adds each button to the layout
        gpbox1_2 = QGroupBox("Select day of week")
        gpbox1_2.setAlignment(Qt.AlignLeft)
        grid = QGridLayout()
        grid.setSpacing(5)
        for i, button in enumerate(self.bgroup1_2.buttons()):
            grid.addWidget(button, i % 4, i // 4)
        gpbox1_2.setLayout(grid)
        self.left_layout.addWidget(gpbox1_2)

        # Add time pulldown
        gpbox1_2_1 = QGroupBox("Select time")
        self.pd_time = QComboBox(self)
        for h in range(24):
            for m in range(2):
                self.pd_time.addItem(
                    f'{h // 12 * 12 + h % 12} : {m * 30 :02d} {"AM" if h < 12 else "PM"}'
                )
        self.pd_time.currentIndexChanged.connect(lambda: self.update_time())
        self.update_time()
        gpbox1_2_1_layout = QVBoxLayout()
        gpbox1_2_1_layout.addWidget(self.pd_time)
        gpbox1_2_1.setLayout(gpbox1_2_1_layout)
        self.left_layout.addWidget(gpbox1_2_1)

        # Group box right
        # Box for food quantity =================================================
        gpbox2 = QGroupBox("Food Quantity")
        gpbox2.setStyleSheet('QGroupBox:title {'
                             'subcontrol-origin: margin;'
                             'subcontrol-position: top center;'
                             'padding-left: 10px;'
                             'padding-right: 10px; }')
        gpbox2_layout = QVBoxLayout()
        gpbox2.setLayout(gpbox2_layout)

        gpbox2_1 = QGroupBox()
        grid = QGridLayout()
        grid.setSpacing(15)
        scroll = QScrollArea()
        scroll.setWidget(gpbox2_1)
        # scroll.setFixedWidth(470)
        scroll.setWidgetResizable(True)

        self.bgroup2_1 = QButtonGroup(self)  # buttn gp of tank selecetion
        self.bgroup2_1.setExclusive(False)
        self.bgroup2_2 = [
        ]  # QButtonGroup(self)  # buttn gp of food amount selecetion

        # Select/Unselect all tanks
        self.select_unselect_all_checkbox = QCheckBox(f'All Tanks', self)
        self.select_unselect_all_checkbox.toggled.connect(
            self.select_unselect_all_tanks)
        self.select_unselect_all_checkbox.setChecked(True)
        self.bgroup2_1.addButton(self.select_unselect_all_checkbox, 1)
        grid.addWidget(self.select_unselect_all_checkbox, 0, 0)
        bg = QButtonGroup(self)
        for j, name in enumerate(self.num_quantity):
            b = QRadioButton(name, self)
            b.setFixedSize(QtCore.QSize(40, 20))
            b.setCheckable(True)
            bg.addButton(b, j + 1)
            grid.addWidget(b, 0, j + 1)
        bg.buttonClicked.connect(lambda: self.select_unselect_food_amount())
        self.bgroup2_2.append(bg)

        # Populate tank rows
        for i in range(1, self.num_tanks + 1):
            cb = QCheckBox(f'Tank {i}', self)
            cb.setChecked(True)
            self.bgroup2_1.addButton(cb, i + 1)
            grid.addWidget(cb, i, 0)
            bg = QButtonGroup(self)
            for j, name in enumerate(self.num_quantity):
                b = QRadioButton(name, self)
                b.setFixedSize(QtCore.QSize(40, 20))
                b.setCheckable(True)
                bg.addButton(b, j + 1)
                grid.addWidget(b, i, j + 1)
            bg.buttonClicked.connect(lambda: self.record_log())
            self.bgroup2_2.append(bg)
        self.bgroup2_1.buttonClicked.connect(lambda: self.record_log())
        grid.setAlignment(Qt.AlignCenter)
        gpbox2_1.setLayout(grid)
        gpbox2_layout.addWidget(scroll)

        # Add to layout
        self.layout.addLayout(self.left_layout)
        self.layout.addWidget(gpbox2)
        self.setLayout(self.layout)

        self.update_json()
Esempio n. 5
0
class ProgramTab(QTabBar):
    early_stop_signal = pyqtSignal()

    def __init__(self, parent, name=None):
        super().__init__()
        self.parent = parent
        self.name = name

        self.cron_job = None

        self.layout = QHBoxLayout()

        self.setMovable(True)
        self.is_running = False
        self.is_enabled_checkbox = QCheckBox(self.name)

        self.num_tanks = 30
        self.num_quantity = ["1", "2", "3", "4"]
        self.program_settings = {
            "Program_name": self.name,
            "Enabled": self.is_enabled_checkbox.isChecked(),
            "Type": "Feeding and washing",
            "Day": None,
            "Time": None,
            "Tanks": [None] * self.num_tanks
        }
        program_default = copy(self.program_settings)

        # Layout left
        self.left_layout = QVBoxLayout()
        self.left_layout.setAlignment(Qt.AlignTop)

        self.button_startstop = QPushButton("Run", self)
        self.button_startstop.setFixedSize(QtCore.QSize(100, 35))
        self.button_startstop.setCheckable(True)
        self.button_startstop.clicked.connect(lambda: self.start_program())
        self.button_reset = QPushButton("Reset", self)
        self.button_reset.setFixedSize(QtCore.QSize(100, 35))
        self.button_reset.clicked.connect(lambda: self.reset(program_default))
        self.button_reset.clicked.connect(lambda: self.repaint())
        self.button_duplicate = QPushButton("Duplicate", self)
        self.button_duplicate.setFixedSize(QtCore.QSize(100, 35))
        self.button_duplicate.clicked.connect(lambda: self.duplicate())
        self.button_delete = QPushButton("Delete", self)
        self.button_delete.setFixedSize(QtCore.QSize(100, 35))
        self.button_delete.clicked.connect(lambda: self.delete_tab())

        self.first_button_row_layout = QHBoxLayout()
        self.first_button_row_layout.setAlignment(Qt.AlignLeft)
        self.first_button_row_layout.addWidget(self.button_startstop)
        self.first_button_row_layout.addWidget(self.button_reset)

        self.second_button_row_layout = QHBoxLayout()
        self.second_button_row_layout.setAlignment(Qt.AlignLeft)
        self.second_button_row_layout.addWidget(self.button_duplicate)
        self.second_button_row_layout.addWidget(self.button_delete)

        self.left_layout.addLayout(self.first_button_row_layout)
        self.left_layout.addLayout(self.second_button_row_layout)

        # Create a button group for feed & washing
        self.bgroup1_1 = QButtonGroup(self)
        # self.bgroup1_1.setExclusive(False)
        self.button_feeding = QRadioButton("Feeding and washing", self)
        self.button_feeding.setCheckable(True)
        self.button_feeding.setChecked(True)
        self.button_washing = QRadioButton("Only washing", self)
        # self.button_washing.setEnabled(False)
        self.button_washing.setCheckable(True)

        self.bgroup1_1.addButton(self.button_feeding, 1)
        self.bgroup1_1.addButton(self.button_washing, 2)
        self.bgroup1_1.buttonClicked.connect(
            lambda: self.record_log("Type", self.bgroup1_1))

        # Create a group box for feeding & washing
        gpbox1_1 = QGroupBox("Program Type")
        grid = QVBoxLayout()
        grid.addWidget(self.button_feeding)
        grid.addWidget(self.button_washing)
        grid.setAlignment(Qt.AlignLeft)
        gpbox1_1.setLayout(grid)
        self.left_layout.addWidget(gpbox1_1)

        # Create a button group for day of week
        self.button_dow = [
            'Monday',
            'Tuesday',
            'Wednesday',
            'Thursday',
            'Friday',
            'Saturday',
            'Sunday',
            'Everyday',
        ]
        self.bgroup1_2 = QButtonGroup(self)
        self.bgroup1_2.setExclusive(False)
        for id, name in enumerate(self.button_dow):
            button = QCheckBox(name, self)
            button.stateChanged.connect(lambda: self.update_active_days())
            if name == 'Everyday':
                button.clicked.connect(lambda: self.check_everyday())
            self.bgroup1_2.addButton(button, id)

        # adds each button to the layout
        gpbox1_2 = QGroupBox("Select day of week")
        gpbox1_2.setAlignment(Qt.AlignLeft)
        grid = QGridLayout()
        grid.setSpacing(5)
        for i, button in enumerate(self.bgroup1_2.buttons()):
            grid.addWidget(button, i % 4, i // 4)
        gpbox1_2.setLayout(grid)
        self.left_layout.addWidget(gpbox1_2)

        # Add time pulldown
        gpbox1_2_1 = QGroupBox("Select time")
        self.pd_time = QComboBox(self)
        for h in range(24):
            for m in range(2):
                self.pd_time.addItem(
                    f'{h // 12 * 12 + h % 12} : {m * 30 :02d} {"AM" if h < 12 else "PM"}'
                )
        self.pd_time.currentIndexChanged.connect(lambda: self.update_time())
        self.update_time()
        gpbox1_2_1_layout = QVBoxLayout()
        gpbox1_2_1_layout.addWidget(self.pd_time)
        gpbox1_2_1.setLayout(gpbox1_2_1_layout)
        self.left_layout.addWidget(gpbox1_2_1)

        # Group box right
        # Box for food quantity =================================================
        gpbox2 = QGroupBox("Food Quantity")
        gpbox2.setStyleSheet('QGroupBox:title {'
                             'subcontrol-origin: margin;'
                             'subcontrol-position: top center;'
                             'padding-left: 10px;'
                             'padding-right: 10px; }')
        gpbox2_layout = QVBoxLayout()
        gpbox2.setLayout(gpbox2_layout)

        gpbox2_1 = QGroupBox()
        grid = QGridLayout()
        grid.setSpacing(15)
        scroll = QScrollArea()
        scroll.setWidget(gpbox2_1)
        # scroll.setFixedWidth(470)
        scroll.setWidgetResizable(True)

        self.bgroup2_1 = QButtonGroup(self)  # buttn gp of tank selecetion
        self.bgroup2_1.setExclusive(False)
        self.bgroup2_2 = [
        ]  # QButtonGroup(self)  # buttn gp of food amount selecetion

        # Select/Unselect all tanks
        self.select_unselect_all_checkbox = QCheckBox(f'All Tanks', self)
        self.select_unselect_all_checkbox.toggled.connect(
            self.select_unselect_all_tanks)
        self.select_unselect_all_checkbox.setChecked(True)
        self.bgroup2_1.addButton(self.select_unselect_all_checkbox, 1)
        grid.addWidget(self.select_unselect_all_checkbox, 0, 0)
        bg = QButtonGroup(self)
        for j, name in enumerate(self.num_quantity):
            b = QRadioButton(name, self)
            b.setFixedSize(QtCore.QSize(40, 20))
            b.setCheckable(True)
            bg.addButton(b, j + 1)
            grid.addWidget(b, 0, j + 1)
        bg.buttonClicked.connect(lambda: self.select_unselect_food_amount())
        self.bgroup2_2.append(bg)

        # Populate tank rows
        for i in range(1, self.num_tanks + 1):
            cb = QCheckBox(f'Tank {i}', self)
            cb.setChecked(True)
            self.bgroup2_1.addButton(cb, i + 1)
            grid.addWidget(cb, i, 0)
            bg = QButtonGroup(self)
            for j, name in enumerate(self.num_quantity):
                b = QRadioButton(name, self)
                b.setFixedSize(QtCore.QSize(40, 20))
                b.setCheckable(True)
                bg.addButton(b, j + 1)
                grid.addWidget(b, i, j + 1)
            bg.buttonClicked.connect(lambda: self.record_log())
            self.bgroup2_2.append(bg)
        self.bgroup2_1.buttonClicked.connect(lambda: self.record_log())
        grid.setAlignment(Qt.AlignCenter)
        gpbox2_1.setLayout(grid)
        gpbox2_layout.addWidget(scroll)

        # Add to layout
        self.layout.addLayout(self.left_layout)
        self.layout.addWidget(gpbox2)
        self.setLayout(self.layout)

        self.update_json()

    @property
    def json_path(self):
        return f'/home/pi/Dev/prod/zaf_data/{self.name}.json'

    def toggle_program_enabled(self):
        self.is_enabled_checkbox.setChecked(
            not self.is_enabled_checkbox.isChecked())
        self.program_settings["Enabled"] = self.is_enabled_checkbox.isChecked()
        self.update_json()

    def check_everyday(self):
        if self.bgroup1_2.buttons()[-1].isChecked():
            for i, bt in enumerate(self.bgroup1_2.buttons()):
                if i != 8:
                    bt.setChecked(True)
        else:
            for i, bt in enumerate(self.bgroup1_2.buttons()):
                if i != 8:
                    bt.setChecked(False)
        self.repaint()
        self.update_active_days()

    def update_time(self):
        time = self.pd_time.currentText()
        self.program_settings["Time"] = time
        self.update_json()

    def update_active_days(self):
        checked_dow = [i.isChecked() for i in self.bgroup1_2.buttons()]
        dow = [
            self.button_dow[i][:3] for i, ii in enumerate(checked_dow)
            if ii and self.button_dow[i] != "Everyday"
        ]

        self.parent.tabs[0].update_program_list()
        self.program_settings["Day"] = dow
        self.update_json()

    def select_unselect_food_amount(self):
        for idx, (tk, bt) in enumerate(
                zip(self.bgroup2_1.buttons(), self.bgroup2_2)):
            if tk.isChecked():
                for index, i in enumerate(self.bgroup2_2[0].buttons()):
                    if i.isChecked():
                        bt.buttons()[index].setChecked(True)

        self.record_log()

    def select_unselect_all_tanks(self):
        if self.select_unselect_all_checkbox.isChecked():
            for tank in self.bgroup2_1.buttons():
                tank.setChecked(True)
        else:
            for tank in self.bgroup2_1.buttons():
                tank.setChecked(False)

    def record_log(self, key=None, obj=None):
        if isinstance(obj, QButtonGroup):
            # For logging feeding or washing
            for i in obj.buttons():
                if i.isChecked():
                    self.program_settings[key] = i.text()
        elif key == "Enabled":
            self.program_settings[key] = obj
        else:
            # For logging food quantity
            for idx, (tk, bt) in enumerate(
                    zip(self.bgroup2_1.buttons(), self.bgroup2_2)):
                if idx != 0:
                    if tk.isChecked():
                        for i in bt.buttons():
                            if i.isChecked():
                                self.program_settings["Tanks"][
                                    int(tk.text().split()[1]) - 1] = i.text()
                    else:
                        self.program_settings["Tanks"][
                            int(tk.text().split()[1]) - 1] = None

        self.update_json()

    def reset(self, preset):
        self.program_settings = copy(preset)
        for key, val in preset.items():
            if key == "Enabled":
                if isinstance(val, str):
                    val = eval(val)
                self.is_enabled_checkbox.setChecked(bool(val))
                # self.button_onoff.setChecked(val)
            elif key == "Type":
                if val == "Feeding and washing":
                    self.button_feeding.setChecked(True)
                    self.button_washing.setChecked(False)
                elif val == "Only washing":
                    self.button_feeding.setChecked(False)
                    self.button_washing.setChecked(True)
                self.record_log("Type", self.bgroup1_1)
            elif key == "Day":
                # Reset all checkboxes
                for bt in self.bgroup1_2.buttons():
                    bt.setChecked(False)
                # Turn on checkboxes
                if val:
                    if isinstance(val, str):
                        val = eval(val)
                    for v in val:
                        for bt in self.bgroup1_2.buttons():
                            if v in bt.text():
                                bt.setChecked(True)
                                break
            elif key == "Time":
                if val:
                    self.pd_time.setCurrentIndex(self.pd_time.findText(val))
                else:
                    self.pd_time.setCurrentIndex(0)
            elif "Tanks" in key:
                for idx, tank in enumerate(val):
                    tankid = idx + 1
                    if tank:
                        self.bgroup2_1.buttons()[tankid].setChecked(True)
                        bg = self.bgroup2_2[tankid]
                        for bt in bg.buttons():
                            if tank == bt.text():
                                bt.setChecked(True)
                                break
                    else:
                        self.bgroup2_1.buttons()[tankid].setChecked(True)
                        bg = self.bgroup2_2[tankid]
                        bg.setExclusive(False)
                        for bt in bg.buttons():
                            bt.setChecked(False)
                        bg.setExclusive(True)

    def duplicate(self):
        self.parent.addprogramtab()
        duplicated_program_settings = self.program_settings.copy()
        duplicated_program_settings["Program_name"] = self.parent.tabs[-1].name
        self.parent.tabs[-1].reset(duplicated_program_settings)

    def delete_tab(self):
        # Delete the associated crontab job
        self.parent.cron.remove(self.parent.cron.find_comment(self.name))
        self.parent.cron.write()

        # Scan for the current tab
        for id, tab in enumerate(self.parent.tabs):
            if tab.name == self.name:
                del self.parent.tabs[id]
                self.parent.removeTab(id)

                if os.path.isfile(self.json_path):
                    os.remove(self.json_path)
                else:  ## Show an error ##
                    print("Error: %s file not found" % self.json_path)

    def update_json(self):
        # Serializing json
        json_object = json.dumps(self.program_settings, indent=4)

        # Writing to sample.json
        with open(self.json_path, "w") as outfile:
            outfile.write(json_object)

        self.parent.update_crontab_job()

    def progress_fn(self, log_str):
        self.parent.log_tab.infoTextBox.insertPlainText(log_str)

    def thread_complete(self):
        self.is_running = False
        self.button_startstop.setText("Start")
        self.button_startstop.setEnabled(True)
        self.parent.log_tab.program_name_label.setText(f"{self.name} is done")
        self.parent.status_bar.showMessage(f"{self.name} is done.")

    def start_program(self):
        if self.is_running:
            self.early_stop_signal.emit()
            self.is_running = False
        else:
            self.update_json()

            self.worker = Worker(
                run)  # Any other args, kwargs are passed to the run function

            self.worker.kwargs['food_amounts'] = self.program_settings["Tanks"]
            self.worker.kwargs['program_type'] = self.program_settings["Type"]

            # worker.signals.result.connect(self.result_callback)
            self.early_stop_signal.connect(self.worker.set_early_stop)
            self.worker.signals.finished.connect(self.thread_complete)
            self.worker.signals.progress.connect(self.progress_fn)

            self.parent.log_tab.clear_activity()

            # Execute
            self.parent.threadpool.start(self.worker)

            self.is_running = True
            self.parent.log_tab.program_name_label.setText(
                f"{self.name} is running now")
            self.parent.status_bar.showMessage(
                f"{self.name} is running now...")
            self.button_startstop.setText("Stop")
Esempio n. 6
0
class IcerikWidget(QWidget):
    def __init__(self, parent=None, name=""):
        super(IcerikWidget, self).__init__(parent)

        self.parent = parent
        self.name = "icerik/" + name + ".json"
        self.init_ui()

    def init_ui(self):

        with open(self.name, "r") as file:
            self.json_veri = file.read()
        self.json_veriq = json.loads(self.json_veri)
        self.aktifSoru = 0
        self.area = QScrollArea()
        self.area.setAlignment(Qt.AlignCenter)
        self.area.setWidgetResizable(True)
        self.area.setMaximumHeight(300)
        self.area.setMinimumHeight(150)

        self.metin = QLabel(
            self.json_veriq["sorular"][self.aktifSoru]["metin"])
        self.metin.setWordWrap(True)

        self.metin.setAlignment(Qt.AlignVCenter)
        self.metin.setObjectName("metin_icerik")
        self.metin.setTextInteractionFlags(Qt.TextSelectableByMouse)

        self.metin.setFont(QFont("Handlee", 16))
        self.area.setWidget(self.metin)

        self.soru = QLabel(self.json_veriq["sorular"][self.aktifSoru]["soru"])
        self.soru.setObjectName("soru")
        self.soru.setAlignment(Qt.AlignCenter)
        self.soru.setTextInteractionFlags(Qt.TextSelectableByMouse)

        self.form = QFormLayout()
        self.sik_0 = QRadioButton(
            self.json_veriq["sorular"][self.aktifSoru]["siklar"][0])
        self.sik_0.setObjectName("0")
        self.sik_1 = QRadioButton(
            self.json_veriq["sorular"][self.aktifSoru]["siklar"][1])
        self.sik_1.setObjectName("1")
        self.sik_2 = QRadioButton(
            self.json_veriq["sorular"][self.aktifSoru]["siklar"][2])
        self.sik_2.setObjectName("2")
        self.sik_3 = QRadioButton(
            self.json_veriq["sorular"][self.aktifSoru]["siklar"][3])
        self.sik_3.setObjectName("3")

        self.form.addRow(self.sik_0)
        self.form.addRow(self.sik_1)
        self.form.addRow(self.sik_2)
        self.form.addRow(self.sik_3)

        self.next = QPushButton("İleri")
        self.next.setIcon(QIcon("icon/next.png"))
        self.back = QPushButton("Geri")
        self.back.setIcon(QIcon("icon/back.png"))

        self.progres = QProgressBar()
        self.progres.setMaximum(len(self.json_veriq["sorular"]) - 1)
        self.progres.setMinimum(0)
        self.progres.setValue(self.aktifSoru)

        self.hb = QHBoxLayout()
        self.hb.addWidget(self.back)
        self.hb.addStretch()
        self.hb.addWidget(self.next)

        self.sonuc = QLabel("başarısız oldu")
        self.sonuc.setObjectName("sonuc")

        self.sonuc.setPixmap(QPixmap("icon/locked.png"))
        self.sonuc.setAlignment(Qt.AlignCenter)

        self.v_box1 = QVBoxLayout()

        self.v_box1.addWidget(self.area)
        self.v_box1.addStretch()
        self.v_box1.addWidget(self.soru)
        self.v_box1.addStretch()
        self.v_box1.addLayout(self.form)
        self.v_box1.addWidget(self.sonuc)

        self.l_vBox = QVBoxLayout()
        self.l_vBox.addLayout(self.v_box1)
        self.l_vBox.addStretch()
        self.l_vBox.addLayout(self.hb)
        self.l_vBox.addWidget(self.progres)

        self.setLayout(self.l_vBox)

        self.next.clicked.connect(self.ileri)
        self.back.clicked.connect(self.geri)
        self.sik_0.clicked.connect(self.secildi)
        self.sik_1.clicked.connect(self.secildi)
        self.sik_2.clicked.connect(self.secildi)
        self.sik_3.clicked.connect(self.secildi)

    def ileri(self):

        if self.aktifSoru < len(self.json_veriq["sorular"]) - 1:

            self.aktifSoru += 1

            self.metin.setText(
                self.json_veriq["sorular"][self.aktifSoru]["metin"])
            self.soru.setText(
                self.json_veriq["sorular"][self.aktifSoru]["soru"])
            self.sik_0.setText(
                self.json_veriq["sorular"][self.aktifSoru]["siklar"][0])
            self.sik_1.setText(
                self.json_veriq["sorular"][self.aktifSoru]["siklar"][1])
            self.sik_2.setText(
                self.json_veriq["sorular"][self.aktifSoru]["siklar"][2])
            self.sik_3.setText(
                self.json_veriq["sorular"][self.aktifSoru]["siklar"][3])
            self.sifirla()
            self.progres.setValue(self.aktifSoru)

    def geri(self):

        if not self.aktifSoru == 0:

            self.aktifSoru -= 1

            self.metin.setText(
                self.json_veriq["sorular"][self.aktifSoru]["metin"])
            self.soru.setText(
                self.json_veriq["sorular"][self.aktifSoru]["soru"])
            self.sik_0.setText(
                self.json_veriq["sorular"][self.aktifSoru]["siklar"][0])

            self.sik_1.setText(
                self.json_veriq["sorular"][self.aktifSoru]["siklar"][1])
            self.sik_2.setText(
                self.json_veriq["sorular"][self.aktifSoru]["siklar"][2])
            self.sik_3.setText(
                self.json_veriq["sorular"][self.aktifSoru]["siklar"][3])

            self.sifirla()
            self.progres.setValue(self.aktifSoru)

    def secildi(self):
        self.secilen = self.sender().objectName()

        self.dogru_sik = self.json_veriq["sorular"][
            self.aktifSoru]["dogruindex"]
        if self.secilen == self.dogru_sik:
            self.sonuc.setPixmap(QPixmap("icon/success.png"))
            self.sender().setStyleSheet(
                "background-color:rgba(27, 58, 27, 0.658)")
            self.metin.setStyleSheet(
                "background-color:rgba(27, 58, 27, 0.658)")
        else:
            self.sonuc.setPixmap(QPixmap("icon/error.png"))
            self.sender().setStyleSheet(
                "background-color: rgba(58, 27, 27, 0.658)")
            self.metin.setStyleSheet(
                "background-color: rgba(58, 27, 27, 0.658)")

    def sifirla(self):
        self.sik_0.setCheckable(False)
        self.sik_0.setCheckable(True)
        self.sik_0.setStyleSheet(
            "outline: none; color: #212222; margin-bottom: 2px;border: 2px solid rgba(0, 0, 0, 0.2); color: rgb(255, 255, 255);"
        )
        self.sik_1.setCheckable(False)
        self.sik_1.setCheckable(True)
        self.sik_1.setStyleSheet(
            "outline: none; color: #212222; margin-bottom: 2px;border: 2px solid rgba(0, 0, 0, 0.2); color: rgb(255, 255, 255);"
        )
        self.sik_2.setCheckable(False)
        self.sik_2.setCheckable(True)
        self.sik_2.setStyleSheet(
            "outline: none; color: #212222; margin-bottom: 2px;border: 2px solid rgba(0, 0, 0, 0.2); color: rgb(255, 255, 255);"
        )
        self.sik_3.setCheckable(False)
        self.sik_3.setCheckable(True)
        self.sik_3.setStyleSheet(
            "outline: none; color: #212222; margin-bottom: 2px;border: 2px solid rgba(0, 0, 0, 0.2); color: rgb(255, 255, 255);"
        )
        self.sonuc.setPixmap(QPixmap("icon/locked.png"))
        self.metin.setStyleSheet("background-color: rgb(29, 29, 29);")
Esempio n. 7
0
class ConnectionWindow:
    """
    Fenetre de connexion en local. Impossible pour le moment de se connecter à un réseau
    et de s'enregistrer dedans 
    """
    current_user = None

    def __init__(self):
        ## Variables autres -----------------------
        global version

        self.colorText = ""
        if sys.platform == "win32":
            self.colorText = "color: #334d9b"

        if choicedBackgroundColor() == 1:
            self.colorText = "color: white;"

        self.version = version
        self.files_enregistrement = None
        self.connected_one = None

        self.ftp = Online()
        # self.ftp.downloadftp("comptes.spi")

        self.ftp.downloadftp("admin.spi")

        try:
            with open("./bin/comptes.spi", "rb") as file:
                depickle = pickle.Unpickler(file)
                self.files_enregistrement = depickle.load()
                Donnees.comptes = self.files_enregistrement

        except:
            with open("./bin/comptes.spi", "wb") as file:
                pickler = pickle.Pickler(file)
                pickler.dump({"uadmin": "padmin"})
                Donnees.comptes, self.files_enregistrement = {
                    "uadmin": "padmin"
                }

        ## APPLICATION ----------------------------

        self.app = QApplication(sys.argv)
        self.win = QWidget()
        x, y = 650, 320
        self.posx, self.posy = center(x, y)
        self.win.setGeometry(self.posx, self.posy, x, y)
        self.win.setWindowTitle("Page de Connexion")
        self.win.setWindowFlag(Qt.FramelessWindowHint)
        self.win.setWindowIcon(QIcon("./bin/icon1.png"))

        self.win.show()

        self.label0 = QLabel(self.win)
        self.label0.move(0, 0)
        self.label0.resize(x, y)
        self.label0.setStyleSheet(getBackgroundColor())
        self.label0.show()

        self.label1 = QLabel(self.win)
        self.label1.setText("Choix")
        self.label1.move(20, 10)
        self.label1.setFont(QFont('Mangal', 80))
        self.label1.setStyleSheet(self.colorText)
        self.label1.adjustSize()
        self.label1.show()

        self.label2 = QLabel(self.win)
        self.label2.setText("Mauvais identifiants, réessayez.")
        self.label2.move(260, 150)
        self.label2.setFont(QFont('Mangal', 11))
        self.label2.adjustSize()
        # self.label2.show()

        self.label3 = QLabel(self.win)
        self.label3.setText("Vérification de version en cours...")
        self.label3.move(20, 190)
        self.label3.setFont(QFont('Mangal', 11))
        self.label3.setStyleSheet(self.colorText)
        self.label3.adjustSize()
        self.label3.show()
        self.threadLabel3 = Thread(None, self.version_search)
        self.threadLabel3.start()

        self.champ1 = QLineEdit(self.win)
        self.champ1.move(20, 140)
        self.champ1.resize(220, 30)
        self.champ1.setFont(QFont('Mangal', 15))
        # self.champ1.show()

        self.champ2 = QLineEdit(self.win)
        self.champ2.setEchoMode(QLineEdit.Password)
        self.champ2.move(20, 180)
        self.champ2.setFont(QFont('Mangal', 15))
        self.champ2.resize(220, 30)
        # self.champ2.show()

        self.bouton1 = QPushButton(self.win)
        self.bouton1.setText(" Se connecter ")
        self.bouton1.move(20, 220)
        self.bouton1.setFont(QFont('Mangal', 20))
        self.bouton1.clicked.connect(self.connection)

        self.openAction = QAction("&ouvrir", self.win)
        self.openAction.setShortcut("Return")
        self.openAction.triggered.connect(self.connection)
        self.win.addAction(self.openAction)
        # self.bouton1.show()

        self.bouton2 = QPushButton(self.win)
        self.bouton2.setText(" S'enregistrer ")
        self.bouton2.move(220, 220)
        self.bouton2.setFont(QFont('Mangal', 20))
        self.bouton2.clicked.connect(self.register_window)
        # self.bouton2.show()

        self.bouton3 = QPushButton(self.win)
        self.bouton3.setText("Fermer")
        self.bouton3.move(20, 270)
        self.bouton3.setFont(QFont('Mangal', 11))
        self.bouton3.clicked.connect(self.quitterNet)
        self.bouton3.show()

        self.bouton4 = QPushButton(self.win)
        self.bouton4.setText("Télécharger ?")
        self.bouton4.move(400, 220)
        self.bouton4.setFont(QFont('Mangal', 20))
        self.bouton4.setStyleSheet(self.colorText)
        self.bouton4.clicked.connect(self.updateDownload)

        self.radio1 = QRadioButton(self.win)
        self.radio1.setText("En Ligne")
        self.radio1.move(120, 275)
        self.radio1.setStyleSheet(self.colorText)
        self.radio1.adjustSize()
        self.radio1.toggled.connect(self.onlineOrNot)
        self.radio1.show()

        self.radio2 = QRadioButton(self.win)
        self.radio2.setText("Hors Ligne")
        self.radio2.move(200, 275)
        self.radio2.setStyleSheet(self.colorText)
        self.radio2.adjustSize()
        self.radio2.toggled.connect(self.onlineOrNot)
        self.radio2.show()

        # --------------- Page d'enregistrement --------------

        self.win2 = QWidget()
        x2, y2 = 270, 400
        self.posx2, self.posy2 = center(x2, y2)
        self.win2.setGeometry(self.posx2, self.posy2, x2, y2)
        self.win2.setWindowTitle("S'enregistrer")
        self.win2.setWindowIcon(QIcon("./bin/icon1.png"))

        self.labelWin21 = QLabel(self.win2)
        self.labelWin21.setText("S'enregistrer")
        self.labelWin21.move(20, 10)
        self.labelWin21.setFont(QFont('Mangal', 30))
        self.labelWin21.adjustSize()
        self.labelWin21.show()

        self.labelWin22 = QLabel(self.win2)
        self.labelWin22.setText("Nouveau nom d'utilisateur")
        self.labelWin22.move(20, 70)
        self.labelWin22.setFont(QFont('Mangal', 12))
        self.labelWin22.adjustSize()
        self.labelWin22.show()

        self.champWin21 = QLineEdit(self.win2)
        self.champWin21.setText("username")
        self.champWin21.move(20, 90)
        self.champWin21.resize(220, 30)
        self.champWin21.show()

        self.labelWin23 = QLabel(self.win2)
        self.labelWin23.setText("Mot de passe")
        self.labelWin23.move(20, 130)
        self.labelWin23.setFont(QFont('Mangal', 12))
        self.labelWin23.adjustSize()
        self.labelWin23.show()

        self.champWin22 = QLineEdit(self.win2)
        self.champWin22.setEchoMode(QLineEdit.Password)
        self.champWin22.move(20, 150)
        self.champWin22.resize(220, 30)
        self.champWin22.show()

        self.labelWin24 = QLabel(self.win2)
        self.labelWin24.setText("Retapez le mot de passe")
        self.labelWin24.move(20, 190)
        self.labelWin24.setFont(QFont('Mangal', 12))
        self.labelWin24.adjustSize()
        self.labelWin24.show()

        self.champWin23 = QLineEdit(self.win2)
        self.champWin23.setEchoMode(QLineEdit.Password)
        self.champWin23.move(20, 210)
        self.champWin23.resize(220, 30)
        self.champWin23.show()

        self.labelWin25 = QLabel(self.win2)
        self.labelWin25.setText("Retapez le mot de passe")
        self.labelWin25.move(20, 250)
        self.labelWin25.setFont(QFont('Mangal', 12))
        self.labelWin25.adjustSize()

        self.boutonWin21 = QPushButton(self.win2)
        self.boutonWin21.setText("S'enregistrer")
        self.boutonWin21.move(20, 300)
        self.boutonWin21.setFont(QFont('Mangal', 13))
        self.boutonWin21.clicked.connect(self.register)
        self.boutonWin21.show()

        self.app.exec_()

    def onlineOrNot(self) -> None:
        if Donnees.online_final == False:
            self.radio1.setCheckable(False)
            self.radio1.setStyleSheet("color : red;")

        if self.radio1.isChecked():

            self.bouton2.show()
            self.bouton1.show()
            self.label1.setText("Connexion")
            self.label1.adjustSize()
            self.bouton1.setText(" Se connecter ")
            self.bouton1.adjustSize()
            self.bouton2.setVisible(True)
            self.champ1.setVisible(True)
            self.champ2.setVisible(True)
            self.label3.setVisible(True)
            self.label3.move(250, 170)
            self.label3.show()
            Donnees.online = True
            self.ftp.downloadftp("comptes.spi")

        elif self.radio2.isChecked():

            self.label1.setText("Offline")
            self.label1.adjustSize()
            self.bouton1.setText(" Se connecter Hors Ligne ")
            self.bouton1.show()
            self.bouton1.adjustSize()
            self.bouton2.setVisible(False)
            self.champ1.setVisible(False)
            self.champ2.setVisible(False)
            self.label3.setVisible(False)

            Donnees.online = False

    def connection(self) -> None:
        """
        Module connexion
        """
        admin = False
        admin_list = None
        if self.radio1.isChecked():
            try:
                with open("./bin/admin.spi", "rb") as adm:
                    pic = pickle.Unpickler(adm)
                    admin_list = pic.load()
                    Donnees.admin = admin_list
            except:
                with open("./bin/admin.spi", "wb") as adm:
                    pic = pickle.Pickler(adm)
                    pic.dump(["uadmin", "Shayajs"])
                    Donnees.admin = ["uadmin", "Shayajs"]

            tha = Thread(None, self._timer_labe2)
            try:
                if self.files_enregistrement[
                        self.champ1.text()] and self.files_enregistrement[
                            self.champ1.text()] == self.champ2.text():

                    self.label2.setText("Connecté !")
                    self.label2.setStyleSheet("color : green;")
                    self.label2.adjustSize()
                    self.label2.show()
                    self.connected_one = (self.champ1.text(), True)

                    if self.champ1.text() in admin_list:
                        admin = True

                    Donnees.current_user = {
                        "user": self.champ1.text(),
                        "admin": admin
                    }

                    self.quitter()
                    self.win.setVisible(False)

                else:

                    self.label2.setStyleSheet("color : red;")
                    self.label2.show()
                    tha.start()

            except:
                self.label2.show()
                self.label2.setStyleSheet("color : red;")
                tha.start()
        elif self.radio2.isChecked():
            self.quitter()
            self.win.setVisible(False)
            Donnees.current_user = {"user": "******", "admin": False}

    def version_search(self) -> None:
        """
        Vérifie si le logiciel est à jour
        """
        a = 0
        b = 0

        try:
            verif = verif_ver()

            splited1 = verif.split(".")
            splited2 = self.version.split(".")

            for i in range(0, 3):
                if int(splited1[i]) == int(splited2[i]):
                    pass
                elif int(splited1[i]) > int(splited2[i]):
                    a = 1
                    break
                elif int(splited1[i]) < int(splited2[i]):
                    b = 1
                    break

            if b == a:
                self.label3.setText("Vous êtes à jour")
                self.label3.adjustSize()
                self.label3.setStyleSheet("color: green;")

            elif b < a:
                self.label3.setText(f"La version {verif} est disponible !")
                self.label3.adjustSize()
                self.label3.setStyleSheet("color: steelblue;")
                self.bouton4.show()

            elif b > a:
                # self.label3.move(250, 170)
                self.label3.setText(
                    f"Votre version ({self.version}) est une version beta !\n(Version en ligne : {verif})"
                )
                self.label3.setStyleSheet("color: goldenrod;")
                self.label3.adjustSize()

            else:
                self.label3.setText(
                    "Impossible de vérifier les mises à jours.")
        except:
            self.label3.setText("Impossible de vérifier les mises à jours.")
            self.label3.adjustSize()

    def _timer_labe2(self) -> None:
        """
        Permettre un affichage limité de l'étiquette de connexion
        """
        sleep(2.5)
        self.label2.setVisible(False)
        self.win2.setVisible(False)

    def quitter(self) -> None:
        """
        Quitter l'application
        """
        self.win.setVisible(False)
        # self.app.quit()
        qApp.quit()

    def quitterNet(self):
        """
        Quitter l'application
        """
        Donnees.current_user = {"user": None, "admin": False}
        self.win.setVisible(False)
        # self.app.quit()
        qApp.quit()
        del self

    def register_window(self) -> None:
        """
        Ouvrir la page d'enregistrement
        """
        try:
            self.win2.show()
            self.champWin21.setText("")
            self.champWin22.setText("")
            self.champWin23.setText("")
            self.labelWin25.setVisible(False)
        except:
            self.label2.setText("Une erreur est survenue")
            threadExceptLabel2 = Thread(None, self._timer_labe2)
            threadExceptLabel2.start()
            exceptionRaised()

    def register(self):
        """
        Page d'enregistrement
        """
        a = 0
        try:
            self.files_enregistrement[self.champWin21.text()]
            a = 1
        except:
            a = 2

        if a == 1:
            self.labelWin25.setText("Ce compte est déjà enregistré !")
            self.labelWin25.setStyleSheet("color: red;")
            self.labelWin25.adjustSize()
            self.labelWin25.show()

        elif a == 2:
            if self.champWin22.text() == self.champWin23.text() and (
                    self.champWin22.text() != ""
                    and self.champWin23.text() != ""):

                self.files_enregistrement[
                    self.champWin21.text()] = self.champWin22.text()

                self.labelWin25.setText("Enregistrement en cours ...")

                with open("./bin/comptes.spi", "wb") as file:
                    pickler = pickle.Pickler(file)
                    pickler.dump(self.files_enregistrement)

                sleep(1)

                Donnees.comptes = self.files_enregistrement
                self.ftp.uploadftp("comptes.spi")

                self.labelWin25.setText("Enregistré")
                self.labelWin25.setStyleSheet("color: green;")
                self.labelWin25.adjustSize()
                self.labelWin25.show()

            elif self.champWin22.text() != self.champWin23.text():
                self.labelWin25.setText(
                    "Vous n'avez pas renseigné deux\nfois le même mot de passe !"
                )
                self.labelWin25.setStyleSheet("color: red;")
                self.labelWin25.adjustSize()
                self.labelWin25.show()

            elif self.champWin22.text() == "" and self.champWin23.text() == "":
                self.labelWin25.setText("Renseignez un mot de passe")
                self.labelWin25.setStyleSheet("color: red;")
                self.labelWin25.adjustSize()
                self.labelWin25.show()

            else:
                self.labelWin25.setText("Une erreur s'est déroulée")
                self.labelWin25.setStyleSheet("color: steelblue;")
                self.labelWin25.adjustSize()
                self.labelWin25.show()

    def updateThread(self):

        self.champ1.setVisible(False)
        self.champ2.setVisible(False)
        self.bouton4.setVisible(False)
        self.label3.setText("Téléchargement en cours...")
        self.label3.setFont(QFont('Mangal', 30))
        self.label3.move(30, 140)
        self.label3.adjustSize()
        self.bouton1.setVisible(False)
        self.bouton2.setVisible(False)
        self.radio1.setVisible(False)
        self.radio2.setVisible(False)
        self.bouton3.setText("Annuler")

    def updateStateTwo(self):
        self.label3.setText("Installation en cours")

    def updateDownload(self):

        sender = Recver()
        tha = Thread(None, self.updateThread)
        tha.start()
        thb = Thread(None, sender.recvtd2, None, (self.label3, ))

        try:
            thb.start()
        except:
            self.label3.setStyleSheet("color: red;")
            self.label3.setText("Le serveur est down")

    def __del__(self):
        print("Sortie sans connexion")
Esempio n. 8
0
class GUI(QMainWindow):
    def __init__(self):
        super().__init__()
        self.thread()
        self.initGui()

    def initGui(self):
        self.resize(800, 500)
        self.setMinimumSize(800, 500)
        self.setMaximumSize(800, 500)
        self.layout = QHBoxLayout(self, spacing=0)
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.setWindowIcon(QIcon('./static/logo.ico'))
        self.move_center()
        self.font()
        self.lable()
        self.log()
        self.tab()
        self.radiobutton()
        # self.win.show()
        self.statusBar().showMessage("Go for your son")
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.button()

    def thread(self):
        #start thread
        self.thread_start = start.START()

    def move_center(self):
        screen = QDesktopWidget().screenGeometry()
        form = self.geometry()
        x_move_step = (screen.width() - form.width()) / 2
        y_move_step = (screen.height() - form.height()) / 2
        self.move(int(x_move_step), int(y_move_step))

    def font(self):
        self.font_bigbutton = QFont()
        self.font_bigbutton.setBold(True)
        self.font_bigbutton.setPointSize(20)
        self.font_bigbutton.setWeight(25)
        # radio button fot
        self.font_rbt = QFont()
        self.font_rbt.setBold(True)
        self.font_rbt.setPointSize(15)
        self.font_rbt.setWeight(15)

    def button(self):
        self.btn_start = QPushButton("初始化", self.tab_one)
        self.btn_start.resize(150, 50)
        self.btn_start.setFont(self.font_bigbutton)
        self.btn_start.setIcon(QIcon("./static/start.png"))
        self.btn_start.setIconSize(QSize(25, 25))
        self.btn_start.clicked.connect(self.start_server)
        self.btn_start.move(350, 350)

    def tab(self):
        self.tab_panel = QTabWidget(self)
        self.tab_one = QWidget(self)
        self.tab_two = QWidget(self)
        self.tab_panel.addTab(self.tab_one, "开始")
        self.tab_panel.addTab(self.tab_two, "设置")
        self.tab_panel.resize(520, 440)
        self.tab_panel.move(10, 30)

    def log(self):
        self.log_panel = QTextBrowser(self)
        self.log_panel.resize(250, 415)
        self.log_panel.move(540, 55)

    def lable(self):
        # logo picture
        self.label_icon = QLabel(self)
        self.label_icon.setPixmap(QPixmap("./static/logo.png"))
        self.label_icon.resize(30, 30)
        self.label_icon.move(0, 0)
        # title label
        self.label_title = QLabel(self)
        self.label_title.setText("TFDS-OneKey")
        self.label_title.move(30, 0)
        # close label button
        self.label_close = MyLabel(self)
        self.label_close.setPixmap(QPixmap("./static/close.png"))
        self.label_close.resize(30, 30)
        self.label_close.move(770, 0)
        self.label_close.click_fun(self.close)
        # clear log label
        self.label_clearlog = MyLabel(self)
        self.label_clearlog.setPixmap(QPixmap("./static/clear.png"))
        self.label_clearlog.resize(30, 30)
        self.label_clearlog.move(540, 20)
        self.label_clearlog.click_fun(self.log_clear)
        # minisize label button
        self.label_mini = MyLabel(self)
        self.label_mini.setPixmap(QPixmap("./static/mini.png"))
        self.label_mini.resize(30, 30)
        self.label_mini.move(740, 0)
        self.label_mini.click_fun(self.showMinimized)
        # steamcmd save dir
        #self.label_steamcmd = QLabel(self.tab_one)
        # self.label_steamcmd.setText("Steamcmd:")
        # self.label_steamcmd.move(300,100)

    def radiobutton(self):
        # use pre setting
        self.rbt_preset = QRadioButton("预设", self.tab_one)
        self.rbt_preset.setFont(self.font_rbt)
        self.rbt_preset.setChecked(True)
        self.rbt_preset.move(250, 370)
        # uses setting
        self.rbt_customset = QRadioButton("自定义", self.tab_one)
        self.rbt_customset.setFont(self.font_rbt)
        self.rbt_customset.setCheckable(False)
        self.rbt_customset.move(130, 370)

    def closeEvent(self, event):
        result = QMessageBox.question(self, "注意:", "您真的要关闭TFDS吗?",
                                      QMessageBox.Yes | QMessageBox.No,
                                      QMessageBox.No)
        if result == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.m_flag = True
            self.m_Position = event.globalPos() - self.pos()  # 获取鼠标相对窗口的位置
            event.accept()
            self.setCursor(QCursor(Qt.OpenHandCursor))  # 更改鼠标图标

    def mouseMoveEvent(self, QMouseEvent):
        if Qt.LeftButton and self.m_flag:
            self.move(QMouseEvent.globalPos() - self.m_Position)  # 更改窗口位置
            QMouseEvent.accept()

    def mouseReleaseEvent(self, QMouseEvent):
        self.m_flag = False
        self.setCursor(QCursor(Qt.ArrowCursor))

    def log_add(self, data):
        self.log_panel.append(data)

    def log_clear(self):
        self.log_panel.clear()

    def start_server(self):
        self.thread_start.start()
        self.thread_start.trg.connect(self.log_add)
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        self.setWindowTitle('Feedback Interactive Analysis')

        self.enzyme = E_PIP5K
        self.f_type = FEEDBACK_POSITIVE
        self.f_carry = 1
        self.f_multi = 1
        self.f_hill = 1
        self.f_sub = I_PIP2
        self.carry_factor = 1
        self.lipids_to_analyze = [I_PIP2]
        self.mutant_enzyme = E_NONE
        self.enz_box = None
        self.show_standard = True

        # a figure instance to plot on
        self.figure = plt.figure()
        # this is the Canvas Widget that displays the `figure`
        self.canvas = FigureCanvas(self.figure)
        # it takes the Canvas widget and a parent
        self.toolbar = NavigationToolbar(self.canvas, self)

        grid = QGridLayout()
        widget = QWidget(self)  # central widget

        s_box = QHBoxLayout()

        substrate_group = QButtonGroup(widget)  # Substrate group
        s_box.addStretch()
        s_box.setContentsMargins(1, 15, 1, 1)
        s_box.addWidget(QLabel("Feedback From"))
        self.substrates = []
        for l in LIPID_NAMES:
            b = QRadioButton(l, self)
            b.setObjectName(l)
            b.setCheckable(True)
            if l == L_PIP2:
                b.setChecked(True)
            b.clicked.connect(partial(self.substrate_clicked, l))
            self.substrates.append(b)
            substrate_group.addButton(b)
            s_box.addWidget(b)

        display_box = QVBoxLayout()
        display_box.setContentsMargins(30, 1, 1, 1)
        display_box.addStretch()
        self.display_lipids = []
        for l in LIPID_NAMES:
            b = QCheckBox(l)
            b.setObjectName(l)
            b.setCheckable(True)
            if l == L_PIP2:
                b.setChecked(True)
            b.clicked.connect(partial(self.on_display_lipid_changed, l))
            self.display_lipids.append(b)
            display_box.addWidget(b)
        display_box.addStretch()

        feedback_group = QButtonGroup(widget)  # Number group
        f_box = QVBoxLayout()
        f_box.setContentsMargins(30, 1, 1, 1)
        f_box.addStretch()
        f_box.addWidget(QLabel("Feedback Type"))
        self.b_pos_feed = QRadioButton("Positive", self)
        self.b_pos_feed.setObjectName("p")
        self.b_pos_feed.setCheckable(True)
        self.b_pos_feed.setChecked(True)
        self.b_pos_feed.clicked.connect(partial(self.feedback_changed, "p"))
        feedback_group.addButton(self.b_pos_feed)
        f_box.addWidget(self.b_pos_feed)

        self.b_neg_feed = QRadioButton("Negative", self)
        self.b_neg_feed.setObjectName("n")
        self.b_neg_feed.setCheckable(True)
        self.b_neg_feed.clicked.connect(partial(self.feedback_changed, "n"))
        feedback_group.addButton(self.b_neg_feed)
        f_box.addWidget(self.b_neg_feed)
        f_box.addStretch()

        a_box = QVBoxLayout()
        a_box.setContentsMargins(30, 30, 30, 15)
        a_slider = QSlider(Qt.Horizontal, self)
        a_slider.setMinimum(1)
        a_slider.setMaximum(100)
        a_slider.setTickInterval(1)
        self.a_label = QLabel("Multiplication Factor : 1")
        a_slider.valueChanged[int].connect(self.multi_changed)
        a_slider.setValue(1)
        a_box.addWidget(self.a_label)
        a_box.addWidget(a_slider)

        c_box = QVBoxLayout()
        c_box.setContentsMargins(30, 0, 30, 15)
        c_slider = QSlider(Qt.Horizontal, self)
        c_slider.setMinimum(1)
        c_slider.setMaximum(10)
        c_slider.setTickInterval(1)
        self.c_label = QLabel("Carrying Capacity : 1")
        c_slider.valueChanged[int].connect(self.carry_changed)
        c_slider.setValue(1)

        c_sub_box = QHBoxLayout()
        c_sub_box.addWidget(self.c_label)

        carry_factor = QComboBox(self)
        for c in CARRY_FACTORS:
            carry_factor.addItem(c)
        carry_factor.activated[str].connect(self.on_carry_factor)
        c_sub_box.addWidget(carry_factor)
        c_sub_box.addStretch()

        c_box.addLayout(c_sub_box, 1)
        c_box.addWidget(c_slider)

        h_box = QVBoxLayout()
        h_box.setContentsMargins(30, 0, 30, 15)
        h_slider = QSlider(Qt.Horizontal, self)
        h_slider.setMinimum(0)
        h_slider.setMaximum(5)
        h_slider.setTickInterval(1)
        self.h_label = QLabel("Hill Coefficient")
        h_slider.valueChanged[int].connect(self.hill_changed)
        h_slider.setValue(1)
        h_box.addWidget(self.h_label)
        h_box.addWidget(h_slider)

        e_box = QVBoxLayout()
        e_box.setContentsMargins(30, 1, 1, 1)
        e_box.addStretch()
        e_box.addWidget(QLabel("Feedback to"))
        enz_box = QComboBox(self)
        for e in ENZYME_NAMES:
            enz_box.addItem(e)
        enz_box.activated[str].connect(self.on_enzyme_selection)
        e_box.addWidget(enz_box)
        e_box.addStretch()

        hill_box = QHBoxLayout()
        hill_box.addLayout(h_box)
        hill_box.addWidget(self.toggle_plot)

        grid.addWidget(self.toolbar, 1, 0)
        grid.addWidget(self.canvas, 2, 0)
        grid.addLayout(display_box, 1, 1, 2, 2)
        grid.addLayout(s_box, 4, 0)
        grid.addLayout(f_box, 5, 1, 2, 2)
        grid.addLayout(self.mutant_list, 4, 1)
        grid.addLayout(a_box, 5, 0)
        grid.addLayout(c_box, 6, 0)
        grid.addLayout(hill_box, 7, 0)
        grid.addLayout(e_box, 7, 1)
        self.setLayout(grid)
class Window(QDialog):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        self.setWindowTitle('Feedback Interactive Analysis')

        self.enzyme = E_PIP5K
        self.f_type = FEEDBACK_POSITIVE
        self.f_carry = 1
        self.f_multi = 1
        self.f_hill = 1
        self.f_sub = I_PIP2
        self.carry_factor = 1
        self.lipids_to_analyze = [I_PIP2]
        self.mutant_enzyme = E_NONE
        self.enz_box = None
        self.show_standard = True

        # a figure instance to plot on
        self.figure = plt.figure()
        # this is the Canvas Widget that displays the `figure`
        self.canvas = FigureCanvas(self.figure)
        # it takes the Canvas widget and a parent
        self.toolbar = NavigationToolbar(self.canvas, self)

        grid = QGridLayout()
        widget = QWidget(self)  # central widget

        s_box = QHBoxLayout()

        substrate_group = QButtonGroup(widget)  # Substrate group
        s_box.addStretch()
        s_box.setContentsMargins(1, 15, 1, 1)
        s_box.addWidget(QLabel("Feedback From"))
        self.substrates = []
        for l in LIPID_NAMES:
            b = QRadioButton(l, self)
            b.setObjectName(l)
            b.setCheckable(True)
            if l == L_PIP2:
                b.setChecked(True)
            b.clicked.connect(partial(self.substrate_clicked, l))
            self.substrates.append(b)
            substrate_group.addButton(b)
            s_box.addWidget(b)

        display_box = QVBoxLayout()
        display_box.setContentsMargins(30, 1, 1, 1)
        display_box.addStretch()
        self.display_lipids = []
        for l in LIPID_NAMES:
            b = QCheckBox(l)
            b.setObjectName(l)
            b.setCheckable(True)
            if l == L_PIP2:
                b.setChecked(True)
            b.clicked.connect(partial(self.on_display_lipid_changed, l))
            self.display_lipids.append(b)
            display_box.addWidget(b)
        display_box.addStretch()

        feedback_group = QButtonGroup(widget)  # Number group
        f_box = QVBoxLayout()
        f_box.setContentsMargins(30, 1, 1, 1)
        f_box.addStretch()
        f_box.addWidget(QLabel("Feedback Type"))
        self.b_pos_feed = QRadioButton("Positive", self)
        self.b_pos_feed.setObjectName("p")
        self.b_pos_feed.setCheckable(True)
        self.b_pos_feed.setChecked(True)
        self.b_pos_feed.clicked.connect(partial(self.feedback_changed, "p"))
        feedback_group.addButton(self.b_pos_feed)
        f_box.addWidget(self.b_pos_feed)

        self.b_neg_feed = QRadioButton("Negative", self)
        self.b_neg_feed.setObjectName("n")
        self.b_neg_feed.setCheckable(True)
        self.b_neg_feed.clicked.connect(partial(self.feedback_changed, "n"))
        feedback_group.addButton(self.b_neg_feed)
        f_box.addWidget(self.b_neg_feed)
        f_box.addStretch()

        a_box = QVBoxLayout()
        a_box.setContentsMargins(30, 30, 30, 15)
        a_slider = QSlider(Qt.Horizontal, self)
        a_slider.setMinimum(1)
        a_slider.setMaximum(100)
        a_slider.setTickInterval(1)
        self.a_label = QLabel("Multiplication Factor : 1")
        a_slider.valueChanged[int].connect(self.multi_changed)
        a_slider.setValue(1)
        a_box.addWidget(self.a_label)
        a_box.addWidget(a_slider)

        c_box = QVBoxLayout()
        c_box.setContentsMargins(30, 0, 30, 15)
        c_slider = QSlider(Qt.Horizontal, self)
        c_slider.setMinimum(1)
        c_slider.setMaximum(10)
        c_slider.setTickInterval(1)
        self.c_label = QLabel("Carrying Capacity : 1")
        c_slider.valueChanged[int].connect(self.carry_changed)
        c_slider.setValue(1)

        c_sub_box = QHBoxLayout()
        c_sub_box.addWidget(self.c_label)

        carry_factor = QComboBox(self)
        for c in CARRY_FACTORS:
            carry_factor.addItem(c)
        carry_factor.activated[str].connect(self.on_carry_factor)
        c_sub_box.addWidget(carry_factor)
        c_sub_box.addStretch()

        c_box.addLayout(c_sub_box, 1)
        c_box.addWidget(c_slider)

        h_box = QVBoxLayout()
        h_box.setContentsMargins(30, 0, 30, 15)
        h_slider = QSlider(Qt.Horizontal, self)
        h_slider.setMinimum(0)
        h_slider.setMaximum(5)
        h_slider.setTickInterval(1)
        self.h_label = QLabel("Hill Coefficient")
        h_slider.valueChanged[int].connect(self.hill_changed)
        h_slider.setValue(1)
        h_box.addWidget(self.h_label)
        h_box.addWidget(h_slider)

        e_box = QVBoxLayout()
        e_box.setContentsMargins(30, 1, 1, 1)
        e_box.addStretch()
        e_box.addWidget(QLabel("Feedback to"))
        enz_box = QComboBox(self)
        for e in ENZYME_NAMES:
            enz_box.addItem(e)
        enz_box.activated[str].connect(self.on_enzyme_selection)
        e_box.addWidget(enz_box)
        e_box.addStretch()

        hill_box = QHBoxLayout()
        hill_box.addLayout(h_box)
        hill_box.addWidget(self.toggle_plot)

        grid.addWidget(self.toolbar, 1, 0)
        grid.addWidget(self.canvas, 2, 0)
        grid.addLayout(display_box, 1, 1, 2, 2)
        grid.addLayout(s_box, 4, 0)
        grid.addLayout(f_box, 5, 1, 2, 2)
        grid.addLayout(self.mutant_list, 4, 1)
        grid.addLayout(a_box, 5, 0)
        grid.addLayout(c_box, 6, 0)
        grid.addLayout(hill_box, 7, 0)
        grid.addLayout(e_box, 7, 1)
        self.setLayout(grid)

    @property
    def mutant_list(self):
        e_box = QHBoxLayout()
        e_box.setContentsMargins(30, 1, 1, 1)
        e_box.addStretch()
        e_box.addWidget(QLabel("Mutant Enzyme : "))
        self.enz_box = QComboBox(self)
        self.enz_box.addItem(E_NONE)
        for e in ENZYME_NAMES:
            self.enz_box.addItem(e)
            self.enz_box.activated[str].connect(self.on_mutant_selection)
        e_box.addWidget(self.enz_box)
        e_box.addStretch()
        return e_box

    @property
    def toggle_plot(self):
        btn = QPushButton("Toggle Scale")
        btn.clicked[bool].connect(self.on_toggle_plot)
        return btn

    def on_toggle_plot(self):
        if self.show_standard:
            self.show_standard = False
        else:
            self.show_standard = True
        self.plot()

    def on_mutant_selection(self, value):
        self.mutant_enzyme = value
        self.plot()

    def plot(self):

        # instead of ax.hold(False)
        self.figure.clear()

        enz = extract_enzyme_set("para.txt", PARAMETER_NO)
        enz2 = extract_enzyme_set("para.txt",
                                  PARAMETER_NO)  # Required because ODEAnalysis
        # changes enzyme values
        base = ODEAnalysis(SYSTEM, 1, enz)
        feed = ODEAnalysis(SYSTEM, 1, enz2, self.feed_para)

        provide_condition(base)
        provide_condition(feed)

        ax = self.figure.add_subplot(111)

        for lipid in self.lipids_to_analyze:
            base_con = base.concentration_array[:, lipid]
            feed_con = feed.concentration_array[:, lipid]

            if not self.show_standard:
                base_con = base_con * 100 / base_con[0]
                feed_con = feed_con * 100 / feed_con[0]

            ax.plot(base.time_array, base_con,
                    label=LIPID_NAMES[lipid], color=COLORS_PRIMARY[lipid],
                    linestyle="--")
            ax.plot(feed.time_array, feed_con,
                    label=LIPID_NAMES[lipid] + "(with Feedback)",
                    color=COLORS_PRIMARY[lipid])

        if self.mutant_enzyme != E_NONE:
            enz3 = extract_enzyme_set("para.txt", PARAMETER_NO)
            mut = ODEAnalysis(SYSTEM, 1, enz3, self.feed_para)
            mut.enz[self.mutant_enzyme].v *= MUTANT_DEPLETION
            provide_condition(mut)

            for lipid in self.lipids_to_analyze:
                mut_con = mut.concentration_array[:, lipid]
                if not self.show_standard:
                    mut_con = mut_con * 100 / mut_con[0]
                ax.plot(mut.time_array, mut_con,
                        label=LIPID_NAMES[lipid] + "(Mutant)",
                        color=COLORS_PRIMARY[lipid], linestyle="-.")

        if self.show_standard:
            ax.set_ylabel("Scaled Concentration")
        else:
            ax.set_ylabel("Concentration Percentage\n(w.r.t. Steady State)")
        ax.set_xlabel("Time (arbitrary)")
        ax.legend(loc=0)
        plt.axvline(0, linestyle="--", color="k")

        # refresh canvas
        self.canvas.draw()

    @property
    def feed_para(self):
        return {
            self.enzyme: {
                F_TYPE_OF_FEEDBACK: self.f_type,
                F_HILL_COEFFICIENT: self.f_hill,
                F_MULTIPLICATION_FACTOR: self.f_multi,
                F_CARRYING_CAPACITY: self.f_carry * self.carry_factor,
                F_FEED_SUBSTRATE_INDEX: self.f_sub
            }
        }

    def on_carry_factor(self, text):
        if text == CARRY_FACTORS[0]:
            self.carry_factor = 1
        elif text == CARRY_FACTORS[1]:
            self.carry_factor = 10
        elif text == CARRY_FACTORS[2]:
            self.carry_factor = 0.1
        elif text == CARRY_FACTORS[3]:
            self.carry_factor = 0.01

        self.plot()

    def on_enzyme_selection(self, text):
        self.enzyme = text
        self.plot()

    def on_display_lipid_changed(self, text):
        self.lipids_to_analyze.clear()
        for b in self.display_lipids:
            if b.isChecked():
                self.lipids_to_analyze.append(LIPID_NAMES.index(b.objectName()))

        self.plot()

    def substrate_clicked(self, e):
        for b in self.substrates:
            bt = b  # type: QRadioButton
            if bt.objectName() != e:
                if bt.isChecked():
                    bt.toggle()
        self.f_sub = LIPID_NAMES.index(e)
        self.plot()

    def multi_changed(self, value):
        multi_value = value
        multi_label = "Multiplication Factor : %.2f" % multi_value
        self.a_label.setText(multi_label)
        self.f_multi = value
        self.plot()

    def carry_changed(self, value):
        carry_value = value
        carry_label = "Carrying capacity : %.2f" % carry_value
        self.c_label.setText(carry_label)
        self.f_carry = value
        self.plot()

    def hill_changed(self, value):
        hill_value = value
        hill_label = "Hill Coefficient : %.2f" % hill_value
        self.h_label.setText(hill_label)
        self.f_hill = value
        self.plot()

    def feedback_changed(self, name):
        if name == "p":
            self.f_type = FEEDBACK_POSITIVE
            self.b_neg_feed.setChecked(False)
        else:
            self.f_type = FEEDBACK_NEGATIVE
            self.b_neg_feed.setChecked(False)

        self.plot()