示例#1
0
 def __createListWidget(self):
     iconList=QListWidget()
     iconList.setAlternatingRowColors(True)
     iconList.setContextMenuPolicy(Qt.CustomContextMenu)
     #iconList.setStyleSheet("QListWidget { background: red; } QListWidget::item { background: yellow; } QListWidget::item:selected { background: blue; }")
     iconList.setStyleSheet("QListWidget::item:selected:active { background: #28D9FF; color:#FFFFFF; } ")#that text color seems not to work!
     return iconList
示例#2
0
class PanelPage(QWizardPage):
    def __init__(self):
        super(PanelPage, self).__init__()
        self.setTitle('生成信息')
        self.setSubTitle('显示工程配置的简要信息和即将生成的文件')

    def initializePage(self):
        super(PanelPage, self).initializePage()

        rootLayout = QVBoxLayout()
        rootLayout.setContentsMargins(20, 20, 10, 20)

        row0 = QHBoxLayout()
        lable0 = QLabel('依赖库:')
        lable0.setAlignment(Qt.AlignTop | Qt.AlignHCenter)
        self.lw_files = QListWidget()
        items0 = QStringList()
        for moudel in app.g_configurations.libs:
            items0.append(moudel['name'])
        self.lw_files.addItems(items0)
        row0.addWidget(lable0)
        row0.addSpacing(25)
        row0.addWidget(self.lw_files)

        row1 = QHBoxLayout()
        lable1 = QLabel('工程文件:')
        lable1.setAlignment(Qt.AlignTop | Qt.AlignHCenter)
        self.lw_files = QListWidget()
        self.lw_files.setStyleSheet("Height:66px;")
        items1 = QStringList()
        for file in app.g_configurations.config['files']:
            items1.append(file['target'])
        self.lw_files.addItems(items1)
        row1.addWidget(lable1)
        row1.addSpacing(10)
        row1.addWidget(self.lw_files)

        rootLayout.addLayout(row0)
        rootLayout.addSpacing(10)
        rootLayout.addLayout(row1)
        self.setLayout(rootLayout)
        self.setStyleSheet(stylesheet)

    def validatePage(self):
        return True
class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.media = Phonon.MediaObject(self)
        ### video widget ####
        self.video = Phonon.VideoWidget(self)
        self.video.setMinimumSize(320,200)
        self.videoCuts = []
        self.myfilename = ""
        self.extension = ""
        self.t1 = ""
        self.t2 = ""
        self.t3 = ""
        self.t4 = ""
        self.t5 = ""
        self.t6 = ""

        ### open button ###
        self.button = QtGui.QPushButton('Choose Video', self)
        self.button.setFixedWidth(90)
        self.button.clicked.connect(self.handleButton)
        self.button.setStyleSheet(stylesheet(self))

		### context menu ####
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.popup2)

        ### play / pause button ###
        self.playbutton = QtGui.QPushButton('Play', self)
        self.playbutton.setFixedWidth(70)
        self.playbutton.clicked.connect(self.handlePlayButton)
        self.playbutton.setStyleSheet(stylesheet(self))
        self.connect(QtGui.QShortcut(QtGui.QKeySequence(QtCore.Qt.Key_Space), self), QtCore.SIGNAL('activated()'), self.handlePlayButton)
        self.connect(QtGui.QShortcut(QtGui.QKeySequence("Ctrl+o"), self), QtCore.SIGNAL('activated()'), self.handleButton)
        self.connect(QtGui.QShortcut(QtGui.QKeySequence("Ctrl+s"), self), QtCore.SIGNAL('activated()'), self.handleSaveVideo)
        self.connect(QtGui.QShortcut(QtGui.QKeySequence("Ctrl+q"), self), QtCore.SIGNAL('activated()'), self.handleQuit)
        ### save button ###
        self.savebutton = QtGui.QPushButton('Save Video', self)
        self.savebutton.setFixedWidth(90)
        self.savebutton.clicked.connect(self.handleSaveVideo)
        self.savebutton.setStyleSheet(stylesheet(self))

        ### seek slider ###
        self.slider = Phonon.SeekSlider(self.media)
        self.slider.setStyleSheet(stylesheet(self))
        isize = QSize(16,16)
        self.slider.setIconSize(isize)
        self.slider.setFocus()
       # self.slider.connect(self.handleLabel)

        ### connection position to label ###
        self.media.isSeekable()
        self.media.tick.connect(self.handleLabel)
        self.media.seekableChanged.connect(self.handleLabel)
        #self.slider.wheel.connect(self.handleLabel)

        ### table view ###
        self.iconList = QListWidget()
        self.iconList.setAlternatingRowColors(True)
        self.iconList.setFixedWidth(200)
        self.iconList.setContextMenuPolicy(Qt.CustomContextMenu)
        self.iconList.setStyleSheet("QListWidget::item:selected:active { background: #7D8ED9; color:#FFFFFF; } ")
        self.iconList.setViewMode(0)
        self.iconList.setSelectionBehavior(1)
        self.iconList.setIconSize(QSize(80, 80/1.78))
        self._hookListActions()
        self.iconList.customContextMenuRequested.connect(self._openListMenu)

                ### set start button ###
        self.startbutton = QtGui.QPushButton('set Start', self)
        self.startbutton.setFixedWidth(70)
        self.startbutton.clicked.connect(self.handleStartButton)
        self.startbutton.setStyleSheet(stylesheet(self))
        self.connect(QtGui.QShortcut(QtGui.QKeySequence("s"), self), QtCore.SIGNAL('activated()'), self.handleStartButton)

                ### set end button ###
        self.endbutton = QtGui.QPushButton('set End', self)
        self.endbutton.setFixedWidth(70)
        self.endbutton.clicked.connect(self.handleEndButton)
        self.endbutton.setStyleSheet(stylesheet(self))
        self.connect(QtGui.QShortcut(QtGui.QKeySequence("e"), self), QtCore.SIGNAL('activated()'), self.handleEndButton)
                ### label ###
        self.mlabel = QtGui.QLabel('Frame', self)
        self.mlabel.setStyleSheet('QLabel \
				{background-color: transparent; color: white;}\nQLabel{color: darkcyan; font-size: 12px; background-color: transparent; border-radius: 5px; padding: 6px; text-align: center;}\n QLabel:hover{color: red;}')
        #self.mlabel.setFixedWidth(80)

        ### layout ###
        layout = QtGui.QGridLayout(self)
        layout.addWidget(self.iconList, 0, 0, 1, 1)
        layout.addWidget(self.video, 0, 1, 1, 6)
        layout.addWidget(self.slider, 1, 1, 1, 6)
        layout.addWidget(self.button, 2, 0, 1, 1)
        layout.addWidget(self.savebutton, 2, 1, 1, 1)
        layout.addWidget(self.playbutton, 2, 3, 1, 1)
        layout.addWidget(self.startbutton, 2, 5, 1, 1)
        layout.addWidget(self.endbutton, 2, 6, 1, 1)
        layout.addWidget(self.mlabel, 2, 4, 1, 1)

    def popup2(self, pos):	
        contextmenu = QMenu()
        contextmenu.addAction("Play / Pause (SPACE)", self.handlePlayButton)
        contextmenu.addSeparator()
        contextmenu.addAction("Load Video (Ctrl-O)", self.handleButton)
        contextmenu.addAction("Save Video (Ctrl-S)", self.handleSaveVideo)
        contextmenu.addSeparator()
        contextmenu.addAction("Info", self.handleInfo)
        contextmenu.addSeparator()
        contextmenu.addAction("Exit (q)", self.handleQuit)
        contextmenu.exec_(QCursor.pos())

    def handleInfo(self):
            msg = QMessageBox()
            #msg.setFixedSize(500, 300)
            #msg.setGeometry(100,100, 400, 200)
            msg.setIcon(QMessageBox.Information)
            msg.setText("Axel Schneider")
            msg.setInformativeText(unicode(u"©2016"))
            msg.setWindowTitle("Cut Video")
            msg.setDetailedText("Python Qt4")
            msg.setStandardButtons(QMessageBox.Ok)
	
            retval = msg.exec_()
            print "value of pressed message box button:", retval

    def handleQuit(self):
        app.quit()

    def handleButton(self):
        if self.media.state() == Phonon.PlayingState:
            self.media.stop()
        else:
            path = QtGui.QFileDialog.getOpenFileName(self, ("Video laden"),
                                                	'/Axel_1/Filme',
                                                	"Videos (*.ts *.mp4)")
            if path:
                self.myfilename = unicode(path) #.encode("utf-8")
                window.setWindowTitle(self.myfilename.split("/")[-1])
                self.extension = path.split(".")[1]
                print(self.extension)
                self.media.setCurrentSource(Phonon.MediaSource(path))
                self.video.setScaleMode(1)
                self.video.setAspectRatio(1)
                self.audio = Phonon.AudioOutput(Phonon.VideoCategory, self)
                Phonon.createPath(self.media, self.audio)
                Phonon.createPath(self.media, self.video)
                self.media.play()
                self.playbutton.setText('Pause')

    def handleSaveVideo(self):
        result = QFileDialog.getSaveFileName(self, ("Video speichern"),
             						'/tmp/film.' + str(self.extension),
             						"Videos (*.ts *.mp4)")
        if result:
            target = unicode(result)
            self.t1 = float(self.videoCuts[0])
            self.t2 = float(self.videoCuts[1])
            ffmpeg_extract_subclip(self.myfilename, self.t1, self.t2, targetname=target)
            window.setWindowTitle("Film gespeichert")
            self.purgeMarker()

    def handlePlayButton(self):
        if self.media.state() == Phonon.PlayingState:
            self.media.pause()
            self.playbutton.setText('Play')
				
        else:
            #print(self.iconList.count())
            self.media.play()
            self.playbutton.setText('Pause')

    def handleStartButton(self):
        if self.iconList.count() < 2:
            rm = str(self.media.currentTime() / 100.00 / 10.00)
            item = QListWidgetItem()
            img = QImage(self.video.snapshot())
            pix = QtGui.QPixmap.fromImage(img)
            item.setIcon(QIcon(pix))
            item.setText("Start: " + rm)
            self.iconList.addItem(item)
            self.videoCuts.append(rm)
        else:
            return

    def handleEndButton(self):
        if self.iconList.count() < 2:
            rm = str(self.media.currentTime() / 100.00 / 10.00)
            item = QListWidgetItem()
            #item.setSizeHint(QSize(150, 40))
            img = QImage(self.video.snapshot())
            pix = QtGui.QPixmap.fromImage(img)
            item.setIcon(QIcon(pix))
            item.setText("End: " + rm)
            self.iconList.addItem(item)
            self.videoCuts.append(rm)
            self.t3 = float(str(self.media.remainingTime()))
            print(self.t3)
            self.media.stop()
            self.playbutton.setText('Play')
        else:
            return

    def handleLabel(self):
            ms = self.media.currentTime()
            seconds=str((ms/1000)%60)
            minutes=str((ms/(1000*60))%60)
            hours=str((ms/(1000*60*60))%24)
            if int(seconds) < 10:
                seconds = "0" + seconds
            if int(minutes) < 10:
                minutes = "0" + minutes
            if int(hours) < 10:
                hours = "0" + hours
                s = hours + ":" + minutes + ":" + seconds
                self.mlabel.setText(s)

    def _hookListActions(self):
        #TOO bad-the list model -should be here...
        rmAction = QtGui.QAction(QtGui.QIcon('icons/close-x.png'), 'entfernen', self)
        rmAction.triggered.connect(self._removeMarker)
        rmAllAction = QtGui.QAction(QtGui.QIcon('icons/clear-all.png'), 'alle entfernen', self)
        rmAllAction.triggered.connect(self.purgeMarker)
        self.gotoAction = QtGui.QAction(QtGui.QIcon('icons/go-next.png'), 'zu dieser Position springen', self)
        self.gotoAction.triggered.connect(self._gotoFromMarker)

        #menus
        self._listMenu = QMenu()
        self._listMenu.addAction(self.gotoAction)
        self._listMenu.addSeparator()
        self._listMenu.addAction(rmAction)
        self._listMenu.addAction(rmAllAction)

    #---List widget context menu
    def _removeMarker(self,whatis):
        selectionList = self.iconList.selectedIndexes()
        if len(selectionList)==0:
            return
        item = selectionList[0]
        self.iconList.takeItem(item.row())
        #self.videoCuts.remove[1])

    def clearMarkerList(self):
        self.iconList.clear()

    #remove contents, remove file
    def purgeMarker(self):
        self.iconList.clear()
        self.videoCuts = []

    def _gotoFromMarker(self,whatis):
        selectionList = self.iconList.selectedIndexes()
        if len(selectionList)==0:
            return
        item = selectionList[0]
        pos = item.data().toString().replace("Start: ", "").replace("End: ", "")
        #frame = pos.ToInt()
        #self.video.currentTime = 1589
        self.setWindowTitle(pos)

    def _openListMenu(self,position):
        selectionList = self.iconList.selectedIndexes()
        if len(selectionList)==0:
            return
        self._listMenu.exec_(self.iconList.viewport().mapToGlobal(position))
示例#4
0
class OrdersWidget(QFrame):

    # =======================================================================
    def __init__(self, parent=None, _PARENT=None):

        # -------------------------------------------------------------------
        QFrame.__init__(self, parent)
        # -------------------------------------------------------------------
        self.setGeometry(3, 5, 968, 555)
        self.setStyleSheet(
            "QFrame{ color: #fff;  background-image: url('./data/imgs/TAB_Orders.png'); }"
        )

        # -------------------------------------------------------------------
        self.PARENT = _PARENT
        self.CONF = _PARENT.CONF
        self.ORDER_ID_TO_CANCEL = False
        self.ORDER_TYPE_TO_CANCEL = False
        # buy/sell to be able delete records from bookkeeping separatly

        self.ORDERS_FROM_DB = {}

        # -------------------------------------------------------------------
        WIDGETS_W = 469
        WIDGETS_H = 325
        WIDGETS_ML = 13
        WIDGETS_MT = 144

        list_style = "QListWidget{ font: 10px 'monospace'; color: #fff;  background-color: #000; border-style: none; background-image: url('./data/imgs/TAB_Orders_line.png'); }"

        # BUY
        self.ORDERS_LIST_BUY = QListWidget(self)
        self.ORDERS_LIST_BUY.setGeometry(WIDGETS_ML, WIDGETS_MT, WIDGETS_W,
                                         WIDGETS_H)
        self.ORDERS_LIST_BUY.setStyleSheet(list_style)
        self.ORDERS_LIST_BUY.setViewMode(QListView.ListMode)

        self.connect(self.ORDERS_LIST_BUY, SIGNAL('itemSelectionChanged()'),
                     lambda: self.SELECT_ORDER_ID("buy"))
        self.ORDERS_LIST_BUY.itemClicked.connect(
            lambda: self.SELECT_ORDER_ID("buy"))

        # SELL
        self.ORDERS_LIST_SELL = QListWidget(self)
        self.ORDERS_LIST_SELL.setGeometry(WIDGETS_W + (WIDGETS_ML * 2) - 1,
                                          WIDGETS_MT, WIDGETS_W - 1, WIDGETS_H)
        self.ORDERS_LIST_SELL.setStyleSheet(list_style)

        self.connect(self.ORDERS_LIST_SELL, SIGNAL('itemSelectionChanged()'),
                     lambda: self.SELECT_ORDER_ID("sell"))
        self.ORDERS_LIST_SELL.itemClicked.connect(
            lambda: self.SELECT_ORDER_ID("sell"))
        # -------------------------------------------------------------------
        self.CANCEL_ORDER_BTN = QPushButton("Apply", self)
        self.CANCEL_ORDER_BTN.setGeometry(555, 506, 80, 30)

        self._i_ = "|"
        # List delimiter

        # -------------------------------------------------------------------
        self.INIT()
        # -------------------------------------------------------------------

    # =======================================================================
    def INIT(self):

        # -------------------------------------------------------------------
        self.GET_ORDERS_FROM_DB()
        # -------------------------------------------------------------------

    # =======================================================================
    def SELECT_ORDER_ID(self, _type):

        # -------------------------------------------------------------------
        try:

            self.ORDER_TYPE_TO_CANCEL = _type

            if _type == "sell":
                self.ORDER_ID_TO_CANCEL = str(
                    self.ORDERS_LIST_SELL.currentItem().text()).split(
                        "|")[0].strip()[1:]

            elif _type == "buy":
                self.ORDER_ID_TO_CANCEL = str(
                    self.ORDERS_LIST_BUY.currentItem().text()).split(
                        "|")[0].strip()[1:]

        except Exception as _exception:
            print(_exception)
        # -------------------------------------------------------------------

    # =======================================================================
    def CREATE_LISTS(self):

        # -------------------------------------------------------------------
        try:

            self.ORDERS_LIST_SELL.clear()
            self.ORDERS_LIST_BUY.clear()

            for ID in self.ORDERS_FROM_DB:

                item = ""

                item += "#{:11} DEL".format(str(ID))
                # order_id
                item += "{:7} DEL".format(self.ORDERS_FROM_DB[ID]["pair"])
                # type
                item += "{:13} DEL".format(
                    str("{:10,.6f}".format(
                        self.ORDERS_FROM_DB[ID]["amount"])).strip())
                # Amount
                item += "{:13} DEL".format(
                    str("{:10,.6f}".format(
                        self.ORDERS_FROM_DB[ID]["at_price"])).strip())
                # at_price

                newItemToolTip = "Order ID: #" + str(
                    ID) + " Created: " + time.ctime(
                        self.ORDERS_FROM_DB[ID]["unix_time"])

                if self.ORDERS_FROM_DB[ID]["type"] == "buy":

                    ttl = self.ORDERS_FROM_DB[ID]["amount"] - (
                        self.ORDERS_FROM_DB[ID]["amount"] / 100 *
                        self.PARENT.FEE)

                    item += "{:13}".format(
                        str("{:10,.6f}".format(ttl)).strip())
                    # ttl_usd
                    newItem = QListWidgetItem(
                        QIcon("./data/imgs/icon_filled_status_0.png"),
                        item.replace("DEL", self._i_), self.ORDERS_LIST_BUY, 0)
                    newItem.setToolTip(newItemToolTip)

                elif self.ORDERS_FROM_DB[ID]["type"] == "sell":

                    ttl = self.ORDERS_FROM_DB[ID][
                        "at_price"] * self.ORDERS_FROM_DB[ID]["amount"]
                    ttl -= (ttl / 100 * self.PARENT.FEE)

                    item += "{:13}".format(
                        str("{:10,.6f}".format(ttl)).strip())
                    # ttl_usd
                    newItem = QListWidgetItem(
                        QIcon("./data/imgs/icon_filled_status_0.png"),
                        item.replace("DEL", self._i_), self.ORDERS_LIST_SELL,
                        0)
                    newItem.setToolTip(newItemToolTip)

        except Exception as _exception:
            print("FRAME_ORDER.CREATE_LISTS: " + str(_exception))

        # -------------------------------------------------------------------

    # =======================================================================
    def DELETE_ORDER(self, _order_id, _pair, _type):

        # ------------------------------------------------------------------
        _SQL = "DELETE FROM " + _pair + " WHERE order_id=" + str(_order_id)
        self.PARENT.DB.EXEC("ORDERS_DB", _SQL)

        # ------------------------------------------------------------------

    # =======================================================================
    def UPDATE_ACTIVE_ORDERS(self):

        # ------------------------------------------------------------------
        pass
        # ------------------------------------------------------------------

    # =======================================================================
    def GET_ORDERS_FROM_DB(self):

        # ------------------------------------------------------------------
        #del self.ORDERS_FROM_DB;
        #self.ORDERS_FROM_DB = {};
        # ------------------------------------------------------------------
        for PAIR in self.CONF["API"]["ALL_PAIRS"]:

            THIS_FIELDS = "order_id, unix_time, filled, at_price, amount, pair, type"

            DATA = self.PARENT.DB.FETCH("ORDERS_DB",
                                        "SELECT " + THIS_FIELDS + " FROM " +
                                        PAIR + " WHERE filled=0",
                                        ALL=True)

            _len = len(DATA)

            for order_id, unix_time, filled, at_price, amount, pair, _type in DATA:
                self.ORDERS_FROM_DB[order_id] = {
                    "order_id": order_id,
                    "unix_time": unix_time,
                    "filled": filled,
                    "at_price": at_price,
                    "amount": amount,
                    "pair": pair,
                    "type": _type
                }
            """
            if _len > 0:
                #print(order_id, "->", self.ORDERS_FROM_DB[ order_id ])
                print(self.ORDERS_FROM_DB)
            exit();
            """
        # ------------------------------------------------------------------

    # =======================================================================


###################################################################################################
示例#5
0
class LeapFlow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)

        self.controller = Controller()
        self.listener = LeapListener(self)
        self.controller.add_listener(self.listener)

        self.mode = "gallery"
        self.scroll = False
        self.direction = ""
        self.direction_x = 0
        self.scroll_velocity = 0
        self.current_index = 0

        # List containing images for the gallery
        self.list_view = QListWidget()
        self.list_view.setFlow(0)
        self.list_view.setHorizontalScrollMode(1)
        self.list_view.setMouseTracking(True)
        self.list_view.itemClicked.connect(self.show_image)

        # Setting the style of the ListView, background, item selected, etc
        self.list_view.setStyleSheet(
            """
				QListWidget::item:hover {background: transparent;}
				QListWidget::item:disabled:hover {background: transparent;}
				QListWidget::item:hover:!active {background: transparent;}
				QListWidget::item:selected:active {background: transparent;}
	            QListWidget::item:selected:!active {background: transparent;}
	            QListWidget::item:selected:disabled {background: transparent;}
	            QListWidget::item:selected:!disabled {background: transparent;}
	            QListWidget {background: #2C3539}
			"""
        )

        # Image viewer
        self.scene = QGraphicsScene()
        self.viewer = QGraphicsView(self.scene)

        self.stackedWidget = QStackedWidget()
        self.stackedWidget.addWidget(self.list_view)
        self.stackedWidget.addWidget(self.viewer)

        self.setCentralWidget(self.stackedWidget)
        self.resize(500, 400)
        self.showMaximized()

        scan = ScanLibrary("/home/chris/Example")
        threads.append(scan)
        self.connect(scan, SIGNAL(scan.signal), self.add_images_to_list)
        scan.start()

        self.connect(self, SIGNAL("scrollChanged(bool)"), self.scroll_view)

    def setScroll(self, scroll):
        """Emit signal to scroll the view"""
        if self.scroll != scroll:
            self.scroll = scroll
            self.emit(SIGNAL("scrollChanged(bool)"), scroll)

    def scroll_view(self):
        """Scroll the view based on scroll velocity and direction"""

        x = self.direction_x * self.scroll_velocity / 100
        bar_x = self.list_view.horizontalScrollBar().value()
        self.list_view.horizontalScrollBar().setValue(bar_x + x)

    def add_images_to_list(self):
        """To add a widget to the listview you must add a QListWidgetItem
		and replace with your widget"""

        for image in library:
            item = QListWidgetItem()
            pixmap = QPixmap.fromImage(QImage(library[image]))
            label = QLabel()
            label.setPixmap(pixmap.scaled(600, 400))
            item.setSizeHint(label.sizeHint())
            item.setData(0, library[image])
            self.list_view.addItem(item)
            self.list_view.setItemWidget(item, label)

    def show_image(self, item):
        """"Display the selected image"""

        self.current_index = self.list_view.indexFromItem(item).row()
        self.scene.addPixmap((QPixmap.fromImage(QImage(item.text()))).scaled(self.viewer.size()))

        self.stackedWidget.setCurrentIndex(1)
        self.mode = "viewer"

    def previous_image(self):
        """Load previous image"""

        if self.current_index - 1 >= 0:
            self.current_index -= 1
            self.load_image()

    def next_image(self):
        """Load next image"""

        if self.current_index + 1 <= len(library.keys()) - 1:
            self.current_index += 1
            self.load_image()

    def load_image(self):
        """Load the image in self.current_index"""

        self.scene.addPixmap(QPixmap.fromImage(QImage(library[library.keys()[self.current_index]])))
示例#6
0
class LeapFlow (QMainWindow):

	def __init__ (self):
		QMainWindow.__init__ (self)

		self.controller = Controller ()
		self.listener = LeapListener (self)
		self.controller.add_listener (self.listener)

		self.mode = "gallery"
		self.scroll = False
		self.direction = ""
		self.direction_x = 0
		self.scroll_velocity = 0
		self.current_index = 0

		# List containing images for the gallery
		self.list_view = QListWidget ()
		self.list_view.setFlow (0)
		self.list_view.setHorizontalScrollMode (1)
		self.list_view.setMouseTracking (True)
		self.list_view.itemClicked.connect (self.show_image)

		# Setting the style of the ListView, background, item selected, etc
		self.list_view.setStyleSheet ("""
				QListWidget::item:hover {background: transparent;}
				QListWidget::item:disabled:hover {background: transparent;}
				QListWidget::item:hover:!active {background: transparent;}
				QListWidget::item:selected:active {background: transparent;}
	            QListWidget::item:selected:!active {background: transparent;}
	            QListWidget::item:selected:disabled {background: transparent;}
	            QListWidget::item:selected:!disabled {background: transparent;}
	            QListWidget {background: #2C3539}
			""")

		# Image viewer
		self.scene = QGraphicsScene ()
		self.viewer = QGraphicsView (self.scene)

		self.stackedWidget = QStackedWidget ()
		self.stackedWidget.addWidget (self.list_view)
		self.stackedWidget.addWidget (self.viewer)

		self.setCentralWidget (self.stackedWidget)
		self.resize (500, 400)
		self.showMaximized ()

		scan = ScanLibrary ("/home/chris/Example")
		threads.append (scan)
		self.connect (scan, SIGNAL (scan.signal), self.add_images_to_list)
		scan.start ()

		self.connect (self, SIGNAL ("scrollChanged(bool)"), self.scroll_view)

	def setScroll (self, scroll):
		"""Emit signal to scroll the view"""
		if (self.scroll != scroll):
			self.scroll = scroll
			self.emit (SIGNAL("scrollChanged(bool)"), scroll)

	def scroll_view (self):
		"""Scroll the view based on scroll velocity and direction"""

		x = self.direction_x * self.scroll_velocity / 100
		bar_x = self.list_view.horizontalScrollBar ().value ()
		self.list_view.horizontalScrollBar ().setValue (bar_x + x)

	def add_images_to_list (self):
		"""To add a widget to the listview you must add a QListWidgetItem
		and replace with your widget"""

		for image in library:
			item = QListWidgetItem ()
			pixmap = QPixmap.fromImage (QImage (library[image]))
			label = QLabel ()
			label.setPixmap (pixmap.scaled (600, 400))
			item.setSizeHint (label.sizeHint ())
			item.setData (0, library[image])
			self.list_view.addItem (item)
			self.list_view.setItemWidget (item, label)

	def show_image (self, item):
		""""Display the selected image"""

		self.current_index = self.list_view.indexFromItem (item).row ()
		self.scene.addPixmap ((QPixmap.fromImage (QImage (item.text()))).scaled (self.viewer.size()))

		self.stackedWidget.setCurrentIndex (1)
		self.mode = "viewer"

	def previous_image (self):
		"""Load previous image"""

		if self.current_index - 1 >= 0:
			self.current_index -= 1
			self.load_image ()

	def next_image (self):
		"""Load next image"""

		if self.current_index + 1 <= len(library.keys ()) - 1:
			self.current_index += 1
			self.load_image ()

	def load_image (self):
		"""Load the image in self.current_index"""

		self.scene.addPixmap (QPixmap.fromImage (QImage (library[library.keys()[self.current_index]])))
示例#7
0
class BookKeeping(QFrame):

    # =======================================================================
    def __init__(self, parent=None, _PARENT=None):

        # -------------------------------------------------------------------
        QFrame.__init__(self, parent);
        # -------------------------------------------------------------------
        self.PARENT                         = _PARENT;
        self.CONF                           = _PARENT.CONF;

        #self.SHA256                         = hashlib.sha256;
        #UID_SHA256 = self.SHA256( str(time.time()) ).hexdigest();
        self.SELECTED_BKKPG_UID             = None;

        # -------------------------------------------------------------------
        self.setGeometry( 3, 5, 975, 555 );
        self.setStyleSheet( "QFrame{ font: 12px 'monospace'; color: #000; background-color: transparent; background-image: url('./data/imgs/TAB_BookKeeping.png'); }" );

        self.PAIR_COMBO                     = QComboBox( self);
        self.PAIR_COMBO.setGeometry( 86, 20, 108, 44 ); 
        self.connect( self.PAIR_COMBO, SIGNAL('currentIndexChanged(int)'), self.CREATE_LISTS );
        #self.PAIR_COMBO.setStyleSheet( "QComboBox{ font: 16px 'monospace'; background-color: #333; color: #FFF; border-style: solid; border-width: 1px; border-color: #000; border-radius: none; }" );
        self.PAIR_COMBO.setEditable(False);

        """
        #self.PAIR_COMBO.setItemIcon( 0, QIcon("./data/imgs/500.png") );
        print(self.PAIR_COMBO.__len__());
        #set at tooltip
        combo.setItemData(0,"a tooltip",Qt.ToolTipRole)
        # set the Font Color
        combo.setItemData(0,QColor("#FF333D"), Qt.BackgroundColorRole)
        #set the font
        combo.setItemData(0, QtGui.QFont('Verdana', bold=True), Qt.FontRole)
        """

        # -------------------------------------------------------------------
        list_style                          = "QListWidget{ font: 10px 'monospace'; color: #fff;  background-color: #000; border-style: none; background-image: url('./data/imgs/TAB_BookKeeping_line.png'); }"; # ./data/imgs/BookKeeping_line.png
        lable_style                         = "QLabel{ font: 10px 'monospace'; color: #fff;  background-color: transparent; border-style: none; background-image: url(''); }"; 

        # -------------------------------------------------------------------
        self.DATA_TO_SEND                   = None;
        self._i_                            = "|"; # List delimiter
        self.CALCULATE_ONLY_COMPLETED       = True;
        self.DATA_TO_SEND_SELECTED          = False;
        
        # -------------------------------------------------------------------
        self.BOOKKEEPING_WIDGET             = QListWidget( self );
        self.BOOKKEEPING_WIDGET.setGeometry( 13, 144, 949, 259 );
        self.BOOKKEEPING_WIDGET.setStyleSheet( list_style );

        self.connect( self.BOOKKEEPING_WIDGET, SIGNAL('itemSelectionChanged()'), lambda: self.SEND_VALUES_TO_TRADE_TERMINAL("SOLD_WIDGET") );
        self.BOOKKEEPING_WIDGET.itemClicked.connect( lambda: self.SEND_VALUES_TO_TRADE_TERMINAL("SELECT_VALUES") );


        self.BOUGHT_TTL_LABLE               = QLabel("0.0", self);
        self.BOUGHT_TTL_LABLE.setGeometry( 304, 406, 85, 17 );
        #self.BOUGHT_TTL_LABLE.setEditable( False );
        self.BOUGHT_TTL_LABLE.setStyleSheet( lable_style );
        self.BOUGHT_TTL                     = 0;

        self.BOUGHT_TTL_PLUS_FEE_LABLE      = QLabel("0.0", self);
        self.BOUGHT_TTL_PLUS_FEE_LABLE.setGeometry( 396, 406, 85, 17 );
        #self.BOUGHT_TTL_PLUS_FEE_LABLE.setEditable( False );
        self.BOUGHT_TTL_PLUS_FEE_LABLE.setStyleSheet( lable_style );
        self.BOUGHT_TTL_PLUS_FEE            = 0;


        self.SOLD_TTL_LABLE                 = QLabel("0.0", self);
        self.SOLD_TTL_LABLE.setGeometry( 694, 406, 85, 17 );
        #self.SOLD_TTL_LABLE.setEditable( False );
        self.SOLD_TTL_LABLE.setStyleSheet( lable_style );
        self.SOLD_TTL                       = 0;

        self.SOLD_TTL_PLUS_FEE_LABLE        = QLabel("0.0", self);
        self.SOLD_TTL_PLUS_FEE_LABLE.setGeometry( 784, 406, 85, 17 );
        #self.SOLD_TTL_PLUS_FEE_LABLE.setEditable( False );
        self.SOLD_TTL_PLUS_FEE_LABLE.setStyleSheet( lable_style );
        self.SOLD_TTL_PLUS_FEE              = 0;

        self.PROFIT_TTL_LABLE               = QLabel("0.0", self);
        self.PROFIT_TTL_LABLE.setGeometry( 874, 406, 88, 17 );
        #self.PROFIT_TTL_LABLE.setEditable( False );
        self.PROFIT_TTL_LABLE.setStyleSheet( lable_style );
        self.PROFIT_TTL                     = 0;

        # -------------------------------------------------------------------
        self.SEND_ID_LABLE                  = QLabel("n/a", self);
        self.SEND_ID_LABLE.setGeometry( 18, 467, 43, 17 );
        self.SEND_ID_LABLE.setStyleSheet( lable_style );

        self.SEND_AMOUNT_LABLE              = QLabel("n/a", self);
        self.SEND_AMOUNT_LABLE.setGeometry( 66, 467, 85, 17 );
        self.SEND_AMOUNT_LABLE.setStyleSheet( lable_style );

        self.SEND_AT_PRICE_LABLE            = QLabel("n/a", self);
        self.SEND_AT_PRICE_LABLE.setGeometry( 156, 467, 43, 17 );
        self.SEND_AT_PRICE_LABLE.setStyleSheet( lable_style );

        self.SEND_VALUES_BTN                = QPushButton("", self); 
        self.SEND_VALUES_BTN.setGeometry( 60, 502, 131, 33 );
        self.SEND_VALUES_BTN.setStyleSheet( "QPushButton{ background-color: transparent; border-style: none; }" ); 
        self.connect( self.SEND_VALUES_BTN, SIGNAL('clicked()'), lambda: self.SEND_VALUES_TO_TRADE_TERMINAL("SEND_VALUES") );

        # -------------------------------------------------------------------
        self.ONLY_COMPLETED_CHECKBOX        = QCheckBox("", self);
        self.ONLY_COMPLETED_CHECKBOX.setGeometry( 665, 444, 17, 17 );
        self.ONLY_COMPLETED_CHECKBOX.setCheckState(Qt.Checked);
        #self.ONLY_COMPLETED_CHECKBOX.setEnabled(False);
        self.connect(self.ONLY_COMPLETED_CHECKBOX, SIGNAL('stateChanged(int)'), lambda: self.CHANGE_VALUES("only_completed") );

        # -------------------------------------------------------------------
        self.INIT();
        # -------------------------------------------------------------------

    # =======================================================================
    def INIT(self):

        # -------------------------------------------------------------------
        try:

            self.CREATE_PAIRS_SELECTOR();
            self.CREATE_LISTS();

        except Exception as _exception:

            print("-----------------------------------------------------");
            print("[INIT]"+str(_exception));
        # -------------------------------------------------------------------

    # =======================================================================
    def BKKPG_UID_ACTION(self, _ACTION, BKKPG_UID, _D):

        # -------------------------------------------------------------------
        #print("_ACTION: ", _ACTION, "BKKPG_UID: ", BKKPG_UID)
        # -------------------------------------------------------------------
        try:

            CURR_PAIR =  str(self.PAIR_COMBO.currentText()).lower().strip();

            order_id    = _D[0];
            unix_time   = _D[1];
            filled      = _D[2];
            amount      = _D[3];
            at_price    = _D[4];

            if _ACTION == "buy":

                # For CRYPTO
                ttl = amount;
                fee = ( ttl/100*self.PARENT.FEE );
            
            elif _ACTION == "sell":

                # For USD
                ttl = amount*at_price;
                fee = ( ttl/100*self.PARENT.FEE );

            grand_ttl = ttl-fee;

            # -------------------------------------------------------------------
            if BKKPG_UID == "": # Is New Record

                TPL = "buy_order_id, buy_unix_time, buy_filled, buy_amount, buy_at_price, buy_fee, buy_ttl, buy_grand_ttl, sell_order_id, sell_unix_time, sell_filled, sell_amount, sell_at_price, sell_fee, sell_ttl, sell_grand_ttl ";
                
                _SQL = "INSERT INTO "+CURR_PAIR+"( BKKPG_UID, completed, started, "+TPL+", profit_ttl ) ";

                if _ACTION == "buy":
                    _SQL += "VALUES( NULL,0,1,{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15}, 0 )".format( _D[0],_D[1],_D[2],_D[3],_D[4],fee, ttl, grand_ttl, 0, 0, 0, 0, 0, 0, 0, 0 );

                else:
                    _SQL += "VALUES( NULL,0,1,{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15}, 0 )".format( 0, 0, 0, 0, 0, 0, 0, 0, _D[0], _D[1],_D[2],_D[3],_D[4],fee, ttl, grand_ttl );


                self.PARENT.DB.EXEC("BOOK_DB", _SQL);

            else: # Existing Record

                # ------------------------------------------------
                if filled == 1:

                    completed = 1;

                    _SQL = "SELECT ACT_grand_ttl from "+CURR_PAIR+" WHERE BKKPG_UID="+BKKPG_UID;
                    
                    if _ACTION == "buy":

                        DATA = self.PARENT.DB.FETCH("BOOK_DB", _SQL.replace("ACT","sell"), ALL=False);
                        profit_ttl = DATA - grand_ttl;

                    else:

                        DATA = self.PARENT.DB.FETCH("BOOK_DB", _SQL.replace("ACT","buy"), ALL=False);
                        profit_ttl = grand_ttl - DATA;
                else:
                    profit_ttl = 0;
                    completed = 0;

                # ------------------------------------------------
                A = _ACTION;
                
                _SQL = "UPDATE "+CURR_PAIR+" SET completed={0}, "+A+"_order_id={1}, "+A+"_unix_time={2}, "+A+"_filled={3}, ";
                _SQL += A+"_amount={4}, "+A+"_at_price={5}, "+A+"_fee={6}, "+A+"_ttl={7}, "+A+"_grand_ttl={8}";
                _SQL += " WHERE BKKPG_UID="+BKKPG_UID;

                _SQL = _SQL.format( completed, order_id, unix_time, filled, amount, at_price, fee, ttl, grand_ttl );

                self.PARENT.DB.EXEC("BOOK_DB", _SQL);

        except Exception as _exception:

            print(" BOOKKEEPING[0:0]");
            print(_exception);
        # -------------------------------------------------------------------
        """
        BKKPG_UID, completed, started, 
        
        buy_order_id, buy_unix_time, buy_filled, buy_amount, buy_at_price, buy_fee, buy_ttl, buy_grand_ttl, 
        sell_order_id, sell_unix_time, sell_filled, sell_amount, sell_at_price, sell_fee, sell_ttl, sell_grand_ttl, 
        
        profit_ttl
        """
        # -------------------------------------------------------------------

    # =======================================================================
    def DELETE_ORDER(self, _order_id, _pair, _type):

        # -------------------------------------------------------------------

        _SQL = "SELECT buy_order_id, sell_order_id FROM "+_pair;
        _SQL += " WHERE buy_order_id="+str(_order_id)+" OR sell_order_id="+str(_order_id);

        DATA = self.PARENT.DB.FETCH("BOOK_DB", _SQL, ALL=False);

        if DATA is None:
            pass;

        if _type == "buy" and DATA[1] == 0:

            _SQL = "DELETE FROM "+_pair+" WHERE buy_order_id="+str(_order_id)+" OR sell_order_id="+str(_order_id);
            self.PARENT.DB.EXEC("BOOK_DB", _SQL);
            self.CREATE_LISTS();

        elif _type == "sell" and DATA[0] == 0:

            _SQL = "DELETE FROM "+_pair+" WHERE buy_order_id="+str(_order_id)+" OR sell_order_id="+str(_order_id);
            self.PARENT.DB.EXEC("BOOK_DB", _SQL);
            self.CREATE_LISTS();

        else:

            A = _type;

            _SQL = "UPDATE "+self.PARENT.CURR_PAIR+" SET ";
            _SQL += " completed=0, "+A+"_order_id=0, "+A+"_unix_time=0, "+A+"_filled=0, ";
            _SQL += A+"_amount=0, "+A+"_at_price=0, "+A+"_fee=0, "+A+"_ttl=0, "+A+"_grand_ttl=0 ";
            _SQL += "WHERE "+A+"_order_id="+str(_order_id);

            self.PARENT.DB.EXEC("BOOK_DB", _SQL);

        # -------------------------------------------------------------------

    # =======================================================================
    def CREATE_LISTS(self):

        # -------------------------------------------------------------------
        try:
            CURR_PAIR =  str(self.PAIR_COMBO.currentText()).lower();

            # -------------------------------------------------------------------
            self.BOOK = { "bought" : [], "sold" : [] };

            self.BOUGHT_TTL = 0;
            self.BOUGHT_TTL_PLUS_FEE = 0;

            self.SOLD_TTL = 0;
            self.SOLD_TTL_PLUS_FEE = 0;

            # -------------------------------------------------------------------
            #self.PARENT.DB.EXEC( "BOOK_DB", "DELETE FROM "+CURR_PAIR+" WHERE BKKPG_UID>7" );

            DATA = self.PARENT.DB.FETCH("BOOK_DB", "SELECT * FROM "+CURR_PAIR+" ORDER BY BKKPG_UID DESC", ALL=True);
            self.BOOKKEEPING_WIDGET.clear();

            for data in DATA:

                # ---------------------------------------------------------------
                """ " "" 
                print( data )
                for d in data:
                    print( d )
                exit();
                "" " """ 
                # ---------------------------------------------------------------
                # In-Memory DATA
                BKKPG_UID       = data[0]
                completed       = data[1]
                started         = data[2]

                buy_order_id    = data[3]
                buy_unix_time   = data[4]
                buy_filled      = data[5]
                buy_amount      = data[6]
                buy_at_price    = data[7]
                #buy_fee         = data[8]
                buy_ttl         = data[9]
                buy_grand_ttl   = data[10]

                sell_order_id   = data[11]
                sell_unix_time  = data[12]
                sell_filled     = data[13]
                sell_amount     = data[14]

                sell_at_price   = data[15]
                #sell_fee        = data[16]
                sell_ttl        = data[17]
                sell_grand_ttl  = data[18]

                profit_ttl      = data[19]

                # ---------------------------------------------------------------

                # ---------------------------------------------------------------
                """
                self.BOOK[ data[3] ].append( {
                                            
                                        BKKPG_UID,
                                        completed,
                                        started,

                                        buy_order_id,
                                        buy_unix_time,
                                        buy_filled,
                                        buy_amount,
                                        buy_at_price,
                                        buy_fee,
                                        buy_ttl,
                                        buy_grand_ttl,

                                        sell_order_id,
                                        sell_unix_time,
                                        sell_filled,
                                        sell_amount,
                                        sell_at_price,
                                        sell_fee,
                                        sell_ttl,
                                        sell_grand_ttl,

                                        profit_ttl

                                            } );

                """
                # ---------------------------------------------------------------
                if self.CALCULATE_ONLY_COMPLETED:

                    if buy_filled == 1 and sell_filled == 1:

                        self.BOUGHT_TTL += buy_ttl;
                        self.BOUGHT_TTL_PLUS_FEE += buy_grand_ttl*buy_at_price;

                        self.SOLD_TTL += sell_ttl;
                        self.SOLD_TTL_PLUS_FEE += sell_grand_ttl;

                else:

                    self.BOUGHT_TTL += buy_ttl;
                    self.BOUGHT_TTL_PLUS_FEE += buy_grand_ttl*buy_at_price;

                    self.SOLD_TTL += sell_ttl;
                    self.SOLD_TTL_PLUS_FEE += sell_grand_ttl;


                self.PROFIT_TTL_LABLE.setText( "{:10,.6f}".format(self.SOLD_TTL_PLUS_FEE - self.BOUGHT_TTL_PLUS_FEE) );


                # ---------------------------------------------------------------
                # Formating data to Display in BookKeeping Wodget

                item = "";

                item += "DEL{:7} ".format(str( BKKPG_UID )); # id

                # BUY / BOUGHT
                item += "#{:11} DEL".format( str(buy_order_id) ); # order_id
                item += "{:4} DEL".format( str(buy_filled) ); # filed
                item += "{:13} DEL".format( str("{:10,.6f}".format( float(buy_amount) )).strip() ); # Amount
                item += "{:13} DEL".format( str("{:10,.6f}".format( buy_at_price )).strip() ); # at_price
                #item += "{:13} DEL".format( str("{:10,.6f}".format( data[7] )).strip() ); # fee
                #item += "{:13} DEL".format( str("{:10,.6f}".format( buy_ttl )).strip() ); # ttl
                item += "{:14} ".format( str("{:10,.6f}".format( buy_grand_ttl )).strip() ); # grand_ttl

                # SELL / SOLD
                item += "#{:11} DEL".format( str(sell_order_id) ); # order_id
                item += "{:4} DEL".format( str(sell_filled) ); # filed
                item += "{:13} DEL".format( str("{:10,.6f}".format( sell_amount )).strip() ); # Amount
                item += "{:13} DEL".format( str("{:10,.6f}".format( sell_at_price )).strip() ); # at_price
                #item += "{:13} DEL".format( str("{:10,.6f}".format( data[7] )).strip() ); # fee
                #item += "{:13} DEL".format( str("{:10,.6f}".format( sell_ttl )).strip() ); # ttl
                item += "{:14} ".format( str("{:10,.6f}".format( sell_grand_ttl )).strip() ); # grand_ttl
                
                # PROFIT
                item += "{:13}".format( str("{:10,.6f}".format( profit_ttl )).strip() ); # grand_ttl

                newItem = QListWidgetItem( QIcon("./data/imgs/icon_filled_status_0.png"), item.replace("DEL", self._i_), self.BOOKKEEPING_WIDGET, 0);
                #newItemToolTip = "Order ID: #"+str()+" Created: "+time.ctime(int(data[2]));
                #newItem.setToolTip(newItemToolTip);

                # ---------------------------------------------------------------

            # / for
            # -------------------------------------------------------------------
            try: 
                self.BOUGHT_TTL_LABLE.setText( str("{:10,.6f}".format( self.BOUGHT_TTL ).strip()) );
                self.BOUGHT_TTL_PLUS_FEE_LABLE.setText( str("{:10,.6f}".format( self.BOUGHT_TTL_PLUS_FEE ).strip()) );

                self.SOLD_TTL_LABLE.setText( str("{:10,.6f}".format( self.SOLD_TTL ).strip()) );
                self.SOLD_TTL_PLUS_FEE_LABLE.setText( str("{:10,.6f}".format( self.SOLD_TTL_PLUS_FEE ).strip()) );

            except Exception as e:
                print("BOOKKEEPING[3:0]"+str(e))


        except Exception as _exception:

            print(" BOOKKEEPING[1:0]");
            print(_exception);
        # -------------------------------------------------------------------

    # =======================================================================
    def RESET_BKKPG_UID(self):

        # -------------------------------------------------------------------
        #CURR_PAIR =  str(self.PAIR_COMBO.currentText()).lower();
        self.PARENT.GUI.BKKPG_UID_VALUE.setText("");
        self.PARENT.GUI.CONTROL_TRADINGS_BTNS("buy", "show");
        self.PARENT.GUI.CONTROL_TRADINGS_BTNS("sell", "show");
        # -------------------------------------------------------------------

    # =======================================================================
    def CHANGE_VALUES(self, _this):

        # -------------------------------------------------------------------
        if _this == "only_completed":
            if self.ONLY_COMPLETED_CHECKBOX.isChecked():
                self.CALCULATE_ONLY_COMPLETED = True;
            else:
                self.CALCULATE_ONLY_COMPLETED = False;

        # -------------------------------------------------------------------
        self.CREATE_LISTS();
        # -------------------------------------------------------------------

    # =======================================================================
    def CREATE_PAIRS_SELECTOR(self, ALL=False):

        # -------------------------------------------------------------------
        if not ALL:
            for PAIR in self.CONF["API"]["PAIRS"]:
                self.PAIR_COMBO.addItem(PAIR.upper());

        else:
            for PAIR in self.CONF["API"]["ALL_PAIRS"]:
                self.PAIR_COMBO.addItem(PAIR.upper());

        for i in xrange(0, self.PAIR_COMBO.__len__()):

            self.PAIR_COMBO.setItemData( i, QColor("#333"),Qt.BackgroundRole );
            self.PAIR_COMBO.setItemData( i, QColor("#fff"),Qt.ForegroundRole );
            #self.PAIR_COMBO.setItemData( i, QFont('monospace', 16, -1, False), Qt.FontRole);
        # -------------------------------------------------------------------

    # =======================================================================
    def SEND_VALUES_TO_TRADE_TERMINAL(self, _action):

        # -------------------------------------------------------------------
        if _action == "SELECT_VALUES":

            self.DATA_TO_SEND_SELECTED = True;
            #self.DATA_TO_SEND = [ str(item).stip() for iten in str(self.BOOKKEEPING_WIDGET.currentItem().text()).strip().split("|")];
            self.DATA_TO_SEND = str(self.BOOKKEEPING_WIDGET.currentItem().text()).strip().split("|")[1].split("#")[0].strip();

        elif _action == "SEND_VALUES":

            if self.DATA_TO_SEND_SELECTED:

                _SQL = "SELECT buy_order_id, sell_order_id FROM "+self.PARENT.CURR_PAIR;
                _SQL += " WHERE BKKPG_UID="+self.DATA_TO_SEND;

                DATA = self.PARENT.DB.FETCH("BOOK_DB", _SQL, ALL=False);

                if DATA[0] != 0 and DATA[1] != 0:

                    self.PARENT.GUI.SHOW_QMESSAGE("info", "This UID is Full!<br> You can't add data to it enymore.<br>Bud You can delete sell and/or buy part<br/> and add new part.");
                    return;

                self.PARENT.GUI.BKKPG_UID_VALUE.setText( self.DATA_TO_SEND );

                self.PARENT.GUI.CONTROL_TRADINGS_BTNS("buy", "show");
                self.PARENT.GUI.CONTROL_TRADINGS_BTNS("sell", "show");

                self.DATA_TO_SEND_SELECTED = False;
                self.DATA_TO_SEND = None;

                # Clear Lables 
                self.SEND_ID_LABLE.setText( "n/a" );
                self.SEND_AMOUNT_LABLE.setText( "n/a" );
                self.SEND_AT_PRICE_LABLE.setText( "n/a" );


                if DATA[0] == 0:
                    self.PARENT.GUI.CONTROL_TRADINGS_BTNS("sell", "hide");

                else:
                    self.PARENT.GUI.CONTROL_TRADINGS_BTNS("buy", "hide");


                # Switch to Trader-Tab
                self.PARENT.GUI.MAIN_TABS.setCurrentIndex(0);

            else:

                self.PARENT.GUI.SHOW_QMESSAGE("info", " Select first item which one you would like<br/> send to the Trade-Terminal !");
                return; 
                
        # -------------------------------------------------------------------
        if self.DATA_TO_SEND is not None:
    
            self.SEND_ID_LABLE.setText( self.DATA_TO_SEND );
示例#8
0
文件: inicio.py 项目: ekimdev/edis
    def __init__(self, parent=None):
        super(Inicio, self).__init__(parent, Qt.Dialog)
        self.setWindowTitle("Welcome to EDIS !")
        self.esettings = configuracion.ESettings()
        contenedor = QVBoxLayout(self)
        self.setMinimumWidth(570)
        hbox = QHBoxLayout()
        hbox.setContentsMargins(0, 0, 0, 0)
        lbl_titulo = QLabel(self.tr("Bienvenido a EDIS..."))
        lbl_titulo.setFont(QFont("Consolas", 20))
        hbox.addWidget(lbl_titulo)
        hbox.addStretch(1)

        icono = QLabel()
        icono.setScaledContents(True)
        icono.setPixmap(QPixmap(paths.ICONOS['explore']))
        hbox.addWidget(icono)

        frame = QFrame()
        frame.setStyleSheet("background: gray")
        frame.setFrameShape(frame.HLine)
        frame.setFrameShadow(frame.Plain)

        contenedor.addLayout(hbox)
        contenedor.addWidget(frame)

        lbl_texto = QLabel(self.tr(ui.__descripcion__))
        lbl_texto.setWordWrap(True)
        lbl_texto.setFont(QFont("Consolas", 10))
        contenedor.addWidget(lbl_texto)

        contenedor.addWidget(QLabel("<b>Archivos en la última sesión:</b>"))

        lista_archivos = QListWidget()
        lista_archivos.setStyleSheet("background: #383733; color: #dedede")
        #FIXME: debería agregar los proyectos recientes y no los archivos
        recientes = configuracion.RECIENTES
        if recientes is not None:
            for reciente in recientes:
                lista_archivos.addItem(reciente)
        contenedor.addWidget(lista_archivos)

        frame = QFrame()
        frame.setStyleSheet("background: gray")
        frame.setFrameShape(frame.HLine)
        frame.setFrameShadow(frame.Plain)

        contenedor.addWidget(frame)

        box_botones = QHBoxLayout()

        btn_abrir = QPushButton(self.tr("Abrir"))
        btn_abrir.setIcon(QIcon(paths.ICONOS['open-small']))
        btn_nuevo = QPushButton(self.tr("Nuevo"))
        btn_nuevo.setIcon(QIcon(paths.ICONOS['new-small']))
        btn_edis = QPushButton(self.tr("Edis web"))
        btn_edis.setIcon(QIcon(paths.ICONOS['web']))
        self.check = QCheckBox(self.tr("Mostrar en la próxima sesión"))
        self.check.setChecked(self.esettings.get('general/inicio'))
        self.check.setStyleSheet("color: #dedede")
        box_botones.addWidget(btn_edis)
        box_botones.addWidget(self.check)
        box_botones.addStretch(1)
        box_botones.addWidget(btn_abrir)
        box_botones.addWidget(btn_nuevo)

        contenedor.addLayout(box_botones)

        EDIS.cargar_componente("inicio", self)
        # Conexiones
        btn_edis.clicked.connect(self._open_web)
        btn_abrir.clicked.connect(self._abrir)
        btn_nuevo.clicked.connect(self._nuevo)

        escape = QShortcut(QKeySequence(Qt.Key_Escape), self)
        escape.activated.connect(self.close)
示例#9
0
文件: muWizard.py 项目: Xifax/muscale
class SeriesPreview(QDialog):

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

        self.data = None
        self.workingSet = None

        self.list = QListWidget()
        self.cancel = QPushButton('Close')
        self.apply = QPushButton('Update')

        self.layout = QGridLayout()
        self.layout.addWidget(self.list, 0, 0, 1, 2)
        self.layout.addWidget(self.apply, 1, 0)
        self.layout.addWidget(self.cancel, 1, 1)
        self.setLayout(self.layout)

        self.initComponents()
        self.initActions()

    def initComponents(self):
        self.setWindowFlags(Qt.Tool)
        self.setWindowTitle("Time series")

        self.setStyleSheet('''QPushButton {
                                color: #333;
                                border: 1px solid #555;
                                border-radius: 11px;
                                padding: 2px;
                                background: qradialgradient(cx: 0.3, cy: -0.4,
                                fx: 0.3, fy: -0.4,
                                radius: 1.35, stop: 0 #fff, stop: 1 #888);
                                min-width: 80px;
                            }
                            QPushButton:hover {
                                color: #fff;
                                background: qradialgradient(cx: 0.3, cy: -0.4,
                                fx: 0.3, fy: -0.4,
                                radius: 1.35, stop: 0 #fff, stop: 1 #bbb);}
                            QPushButton:pressed {
                                background: qradialgradient(cx: 0.4, cy: -0.1,
                                fx: 0.4, fy: -0.1,
                                radius: 1.35, stop: 0 #fff, stop: 1 #ddd);}
                            QPushButton:checked {
                                background: qradialgradient(cx: 0.4, cy: -0.1,
                                fx: 0.4, fy: -0.1,
                                radius: 1.35, stop: 0 #fff, stop: 1 #ddd);}
                            QListView::focus {
                                border: 2px solid black;
                                border-radius: 6px;
                            }
                            QScrollBar:vertical {
                              width: 20px;
                              border: 1px solid grey;
                              border-radius: 6px;
                              background-color: transparent;
                              margin: 28px 0 28px 0;
                            }
                            QScrollBar::add-line:vertical {
                              background: transparent;
                              height: 32px;
                              subcontrol-position: bottom;
                              subcontrol-origin: margin;
                            }
                            QScrollBar::sub-line:vertical {
                              background: transparent;
                              height: 32px;
                              subcontrol-position: top;
                              subcontrol-origin: margin;
                            }
                            QScrollBar::up-arrow:vertical {
                              width: 20px;
                              height: 32px;
                              background: transparent;
                              image: url(../res/icons/arrow_up.png);
                            }
                            QScrollBar::up-arrow:hover {
                              bottom: 2px;
                            }
                            QScrollBar::down-arrow:vertical {
                              width: 20px;
                              height: 32px;
                              background: transparent;
                              image: url(../res/icons/arrow_down.png);
                            }
                            QScrollBar::down-arrow:hover {
                              top: 2px;
                            }
                            QScrollBar::handle:vertical {
                                border-radius: 6px;
                                background: url(../res/icons/handle.png) 0% center no-repeat;
                                background-color: white;
                                min-height: 32px;
                            }
                            QScrollBar::handle:hover {
                                background: url(../res/icons/handle_hover.png) 0% center no-repeat;
                                background-color: white;
                                border: 1px solid gray;
                            }''')

        self.list.setAlternatingRowColors(True)
        self.list.setStyleSheet('''QListView::item:selected:active {
                 background: qlineargradient(x1: 1, y1: 0, x2: 0, y2: 3, stop: 0 #cbdaf1, stop: 1 #bfcde4);
            }
            QListView::item {
                border: 1px solid #d9d9d9;
                border-top-color: transparent;
                border-bottom-color: transparent;
            }
            QListView::item:hover {
                 background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #e7effd, stop: 1 #cbdaf1);
                 border: 1px solid #bfcde4;
            }''')

        self.list.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.list.setContextMenuPolicy(Qt.ActionsContextMenu)

    def initActions(self):
        self.apply.clicked.connect(self.applyChanges)
        self.cancel.clicked.connect(self.close)

        self.list.itemDoubleClicked.connect(self.removeFromList)
        self.list.addAction(QAction('&Remove selected', self, triggered=self.removeItems))

    #--- actions ---#
    def updateData(self, data):
        self.data = data
        self.workingSet = data[0][:]
        self.updateList()

    def updateList(self):
        self.list.clear()
        for item in self.workingSet:
            item = QListWidgetItem(str(item))
            item.setTextAlignment(Qt.AlignCenter)
            self.list.addItem(item)

    def applyChanges(self):
        self.data = (self.workingSet, self.data[1])

    def removeFromList(self, item):
        self.workingSet.remove(float(item.text()))
        self.list.takeItem(self.list.indexFromItem(item).row())

    def removeItems(self):
        for item in self.list.selectedItems():
            self.workingSet.remove(float(item.text()))
            self.list.takeItem(self.list.indexFromItem(item).row())
示例#10
0
class OrdersWidget(QFrame):

    # =======================================================================
    def __init__(self, parent=None, _PARENT=None):

        # -------------------------------------------------------------------
        QFrame.__init__(self, parent);
        # -------------------------------------------------------------------
        self.setGeometry( 3, 5, 968, 555 );
        self.setStyleSheet("QFrame{ color: #fff;  background-image: url('./data/imgs/TAB_Orders.png'); }" );

        # -------------------------------------------------------------------
        self.PARENT                         = _PARENT;
        self.CONF                           = _PARENT.CONF;
        self.ORDER_ID_TO_CANCEL             = False;
        self.ORDER_TYPE_TO_CANCEL           = False; # buy/sell to be able delete records from bookkeeping separatly

        self.ORDERS_FROM_DB                 = {};

        # -------------------------------------------------------------------
        WIDGETS_W = 469;
        WIDGETS_H = 325;
        WIDGETS_ML = 13;
        WIDGETS_MT = 144;

        list_style                          = "QListWidget{ font: 10px 'monospace'; color: #fff;  background-color: #000; border-style: none; background-image: url('./data/imgs/TAB_Orders_line.png'); }";

        # BUY
        self.ORDERS_LIST_BUY = QListWidget(self);
        self.ORDERS_LIST_BUY.setGeometry( WIDGETS_ML, WIDGETS_MT, WIDGETS_W, WIDGETS_H );
        self.ORDERS_LIST_BUY.setStyleSheet( list_style );
        self.ORDERS_LIST_BUY.setViewMode( QListView.ListMode );

        self.connect( self.ORDERS_LIST_BUY, SIGNAL('itemSelectionChanged()'), lambda: self.SELECT_ORDER_ID("buy") );
        self.ORDERS_LIST_BUY.itemClicked.connect( lambda: self.SELECT_ORDER_ID("buy") )

        # SELL
        self.ORDERS_LIST_SELL = QListWidget(self);
        self.ORDERS_LIST_SELL.setGeometry( WIDGETS_W+(WIDGETS_ML*2 )-1, WIDGETS_MT, WIDGETS_W-1, WIDGETS_H );
        self.ORDERS_LIST_SELL.setStyleSheet( list_style );

        self.connect( self.ORDERS_LIST_SELL, SIGNAL('itemSelectionChanged()'), lambda: self.SELECT_ORDER_ID("sell") );
        self.ORDERS_LIST_SELL.itemClicked.connect( lambda: self.SELECT_ORDER_ID("sell") )
        # -------------------------------------------------------------------
        self.CANCEL_ORDER_BTN = QPushButton("Apply", self);
        self.CANCEL_ORDER_BTN.setGeometry( 555, 506, 80, 30 );

        self._i_                            = "|"; # List delimiter

        # -------------------------------------------------------------------
        self.INIT();
        # -------------------------------------------------------------------

    # =======================================================================
    def INIT(self):

        # -------------------------------------------------------------------
        self.GET_ORDERS_FROM_DB();
        # -------------------------------------------------------------------

    # =======================================================================
    def SELECT_ORDER_ID(self, _type):

        # -------------------------------------------------------------------
        try:

            self.ORDER_TYPE_TO_CANCEL = _type;

            if _type == "sell":
                self.ORDER_ID_TO_CANCEL = str(self.ORDERS_LIST_SELL.currentItem().text()).split("|")[0].strip()[1:];

            elif _type == "buy":
                self.ORDER_ID_TO_CANCEL = str(self.ORDERS_LIST_BUY.currentItem().text()).split("|")[0].strip()[1:];


        except Exception as _exception:
            print(_exception);
        # -------------------------------------------------------------------

    # =======================================================================
    def CREATE_LISTS(self):

        # -------------------------------------------------------------------
        try:

            self.ORDERS_LIST_SELL.clear();
            self.ORDERS_LIST_BUY.clear();

            for ID in self.ORDERS_FROM_DB:

                item = "";

                item += "#{:11} DEL".format( str(ID) ); # order_id
                item += "{:7} DEL".format( self.ORDERS_FROM_DB[ID]["pair"] ); # type
                item += "{:13} DEL".format( str("{:10,.6f}".format( self.ORDERS_FROM_DB[ID]["amount"] )).strip() ); # Amount
                item += "{:13} DEL".format( str("{:10,.6f}".format( self.ORDERS_FROM_DB[ID]["at_price"] )).strip() ); # at_price

                newItemToolTip = "Order ID: #"+str(ID)+" Created: "+time.ctime( self.ORDERS_FROM_DB[ID]["unix_time"] );
                
                if self.ORDERS_FROM_DB[ID]["type"] == "buy":

                    ttl = self.ORDERS_FROM_DB[ID]["amount"] - (self.ORDERS_FROM_DB[ID]["amount"]/100*self.PARENT.FEE);

                    item += "{:13}".format( str("{:10,.6f}".format( ttl )).strip() ); # ttl_usd
                    newItem = QListWidgetItem( QIcon("./data/imgs/icon_filled_status_0.png"), item.replace("DEL", self._i_), self.ORDERS_LIST_BUY, 0);
                    newItem.setToolTip(newItemToolTip);

                elif self.ORDERS_FROM_DB[ID]["type"] == "sell":

                    ttl = self.ORDERS_FROM_DB[ID]["at_price"]*self.ORDERS_FROM_DB[ID]["amount"];
                    ttl -= (ttl/100*self.PARENT.FEE);
                    
                    item += "{:13}".format( str("{:10,.6f}".format( ttl )).strip() ); # ttl_usd
                    newItem = QListWidgetItem( QIcon("./data/imgs/icon_filled_status_0.png"), item.replace("DEL", self._i_), self.ORDERS_LIST_SELL, 0);
                    newItem.setToolTip(newItemToolTip);

        except Exception as _exception:
            print("FRAME_ORDER.CREATE_LISTS: "+str(_exception));

        # -------------------------------------------------------------------

    # =======================================================================
    def DELETE_ORDER(self, _order_id, _pair, _type):

        # ------------------------------------------------------------------
        _SQL = "DELETE FROM "+_pair+" WHERE order_id="+str(_order_id);
        self.PARENT.DB.EXEC("ORDERS_DB", _SQL );

        # ------------------------------------------------------------------

    # =======================================================================
    def UPDATE_ACTIVE_ORDERS(self):

        # ------------------------------------------------------------------
        pass;
        # ------------------------------------------------------------------
 
    # =======================================================================
    def GET_ORDERS_FROM_DB(self):

        # ------------------------------------------------------------------
        #del self.ORDERS_FROM_DB;
        #self.ORDERS_FROM_DB = {};
        # ------------------------------------------------------------------
        for PAIR in self.CONF["API"]["ALL_PAIRS"]:

            THIS_FIELDS = "order_id, unix_time, filled, at_price, amount, pair, type";

            DATA = self.PARENT.DB.FETCH("ORDERS_DB", "SELECT "+THIS_FIELDS+" FROM "+PAIR+" WHERE filled=0", ALL=True);

            _len = len(DATA);

            for order_id, unix_time, filled, at_price, amount, pair, _type in DATA:
                self.ORDERS_FROM_DB[ order_id ] = { "order_id":order_id, "unix_time":unix_time, "filled":filled, "at_price":at_price, "amount":amount, "pair":pair, "type":_type };

            """
            if _len > 0:
                #print(order_id, "->", self.ORDERS_FROM_DB[ order_id ])
                print(self.ORDERS_FROM_DB)
            exit();
            """ 
        # ------------------------------------------------------------------

    # =======================================================================

###################################################################################################
示例#11
0
class BookKeeping(QFrame):

    # =======================================================================
    def __init__(self, parent=None, _PARENT=None):

        # -------------------------------------------------------------------
        QFrame.__init__(self, parent)
        # -------------------------------------------------------------------
        self.PARENT = _PARENT
        self.CONF = _PARENT.CONF

        #self.SHA256                         = hashlib.sha256;
        #UID_SHA256 = self.SHA256( str(time.time()) ).hexdigest();
        self.SELECTED_BKKPG_UID = None

        # -------------------------------------------------------------------
        self.setGeometry(3, 5, 975, 555)
        self.setStyleSheet(
            "QFrame{ font: 12px 'monospace'; color: #000; background-color: transparent; background-image: url('./data/imgs/TAB_BookKeeping.png'); }"
        )

        self.PAIR_COMBO = QComboBox(self)
        self.PAIR_COMBO.setGeometry(86, 20, 108, 44)
        self.connect(self.PAIR_COMBO, SIGNAL('currentIndexChanged(int)'),
                     self.CREATE_LISTS)
        #self.PAIR_COMBO.setStyleSheet( "QComboBox{ font: 16px 'monospace'; background-color: #333; color: #FFF; border-style: solid; border-width: 1px; border-color: #000; border-radius: none; }" );
        self.PAIR_COMBO.setEditable(False)
        """
        #self.PAIR_COMBO.setItemIcon( 0, QIcon("./data/imgs/500.png") );
        print(self.PAIR_COMBO.__len__());
        #set at tooltip
        combo.setItemData(0,"a tooltip",Qt.ToolTipRole)
        # set the Font Color
        combo.setItemData(0,QColor("#FF333D"), Qt.BackgroundColorRole)
        #set the font
        combo.setItemData(0, QtGui.QFont('Verdana', bold=True), Qt.FontRole)
        """

        # -------------------------------------------------------------------
        list_style = "QListWidget{ font: 10px 'monospace'; color: #fff;  background-color: #000; border-style: none; background-image: url('./data/imgs/TAB_BookKeeping_line.png'); }"
        # ./data/imgs/BookKeeping_line.png
        lable_style = "QLabel{ font: 10px 'monospace'; color: #fff;  background-color: transparent; border-style: none; background-image: url(''); }"

        # -------------------------------------------------------------------
        self.DATA_TO_SEND = None
        self._i_ = "|"
        # List delimiter
        self.CALCULATE_ONLY_COMPLETED = True
        self.DATA_TO_SEND_SELECTED = False

        # -------------------------------------------------------------------
        self.BOOKKEEPING_WIDGET = QListWidget(self)
        self.BOOKKEEPING_WIDGET.setGeometry(13, 144, 949, 259)
        self.BOOKKEEPING_WIDGET.setStyleSheet(list_style)

        self.connect(self.BOOKKEEPING_WIDGET, SIGNAL('itemSelectionChanged()'),
                     lambda: self.SEND_VALUES_TO_TRADE_TERMINAL("SOLD_WIDGET"))
        self.BOOKKEEPING_WIDGET.itemClicked.connect(
            lambda: self.SEND_VALUES_TO_TRADE_TERMINAL("SELECT_VALUES"))

        self.BOUGHT_TTL_LABLE = QLabel("0.0", self)
        self.BOUGHT_TTL_LABLE.setGeometry(304, 406, 85, 17)
        #self.BOUGHT_TTL_LABLE.setEditable( False );
        self.BOUGHT_TTL_LABLE.setStyleSheet(lable_style)
        self.BOUGHT_TTL = 0

        self.BOUGHT_TTL_PLUS_FEE_LABLE = QLabel("0.0", self)
        self.BOUGHT_TTL_PLUS_FEE_LABLE.setGeometry(396, 406, 85, 17)
        #self.BOUGHT_TTL_PLUS_FEE_LABLE.setEditable( False );
        self.BOUGHT_TTL_PLUS_FEE_LABLE.setStyleSheet(lable_style)
        self.BOUGHT_TTL_PLUS_FEE = 0

        self.SOLD_TTL_LABLE = QLabel("0.0", self)
        self.SOLD_TTL_LABLE.setGeometry(694, 406, 85, 17)
        #self.SOLD_TTL_LABLE.setEditable( False );
        self.SOLD_TTL_LABLE.setStyleSheet(lable_style)
        self.SOLD_TTL = 0

        self.SOLD_TTL_PLUS_FEE_LABLE = QLabel("0.0", self)
        self.SOLD_TTL_PLUS_FEE_LABLE.setGeometry(784, 406, 85, 17)
        #self.SOLD_TTL_PLUS_FEE_LABLE.setEditable( False );
        self.SOLD_TTL_PLUS_FEE_LABLE.setStyleSheet(lable_style)
        self.SOLD_TTL_PLUS_FEE = 0

        self.PROFIT_TTL_LABLE = QLabel("0.0", self)
        self.PROFIT_TTL_LABLE.setGeometry(874, 406, 88, 17)
        #self.PROFIT_TTL_LABLE.setEditable( False );
        self.PROFIT_TTL_LABLE.setStyleSheet(lable_style)
        self.PROFIT_TTL = 0

        # -------------------------------------------------------------------
        self.SEND_ID_LABLE = QLabel("n/a", self)
        self.SEND_ID_LABLE.setGeometry(18, 467, 43, 17)
        self.SEND_ID_LABLE.setStyleSheet(lable_style)

        self.SEND_AMOUNT_LABLE = QLabel("n/a", self)
        self.SEND_AMOUNT_LABLE.setGeometry(66, 467, 85, 17)
        self.SEND_AMOUNT_LABLE.setStyleSheet(lable_style)

        self.SEND_AT_PRICE_LABLE = QLabel("n/a", self)
        self.SEND_AT_PRICE_LABLE.setGeometry(156, 467, 43, 17)
        self.SEND_AT_PRICE_LABLE.setStyleSheet(lable_style)

        self.SEND_VALUES_BTN = QPushButton("", self)
        self.SEND_VALUES_BTN.setGeometry(60, 502, 131, 33)
        self.SEND_VALUES_BTN.setStyleSheet(
            "QPushButton{ background-color: transparent; border-style: none; }"
        )
        self.connect(self.SEND_VALUES_BTN, SIGNAL('clicked()'),
                     lambda: self.SEND_VALUES_TO_TRADE_TERMINAL("SEND_VALUES"))

        # -------------------------------------------------------------------
        self.ONLY_COMPLETED_CHECKBOX = QCheckBox("", self)
        self.ONLY_COMPLETED_CHECKBOX.setGeometry(665, 444, 17, 17)
        self.ONLY_COMPLETED_CHECKBOX.setCheckState(Qt.Checked)
        #self.ONLY_COMPLETED_CHECKBOX.setEnabled(False);
        self.connect(self.ONLY_COMPLETED_CHECKBOX, SIGNAL('stateChanged(int)'),
                     lambda: self.CHANGE_VALUES("only_completed"))

        # -------------------------------------------------------------------
        self.INIT()
        # -------------------------------------------------------------------

    # =======================================================================
    def INIT(self):

        # -------------------------------------------------------------------
        try:

            self.CREATE_PAIRS_SELECTOR()
            self.CREATE_LISTS()

        except Exception as _exception:

            print("-----------------------------------------------------")
            print("[INIT]" + str(_exception))
        # -------------------------------------------------------------------

    # =======================================================================
    def BKKPG_UID_ACTION(self, _ACTION, BKKPG_UID, _D):

        # -------------------------------------------------------------------
        #print("_ACTION: ", _ACTION, "BKKPG_UID: ", BKKPG_UID)
        # -------------------------------------------------------------------
        try:

            CURR_PAIR = str(self.PAIR_COMBO.currentText()).lower().strip()

            order_id = _D[0]
            unix_time = _D[1]
            filled = _D[2]
            amount = _D[3]
            at_price = _D[4]

            if _ACTION == "buy":

                # For CRYPTO
                ttl = amount
                fee = (ttl / 100 * self.PARENT.FEE)

            elif _ACTION == "sell":

                # For USD
                ttl = amount * at_price
                fee = (ttl / 100 * self.PARENT.FEE)

            grand_ttl = ttl - fee

            # -------------------------------------------------------------------
            if BKKPG_UID == "":  # Is New Record

                TPL = "buy_order_id, buy_unix_time, buy_filled, buy_amount, buy_at_price, buy_fee, buy_ttl, buy_grand_ttl, sell_order_id, sell_unix_time, sell_filled, sell_amount, sell_at_price, sell_fee, sell_ttl, sell_grand_ttl "

                _SQL = "INSERT INTO " + CURR_PAIR + "( BKKPG_UID, completed, started, " + TPL + ", profit_ttl ) "

                if _ACTION == "buy":
                    _SQL += "VALUES( NULL,0,1,{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15}, 0 )".format(
                        _D[0], _D[1], _D[2], _D[3], _D[4], fee, ttl, grand_ttl,
                        0, 0, 0, 0, 0, 0, 0, 0)

                else:
                    _SQL += "VALUES( NULL,0,1,{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15}, 0 )".format(
                        0, 0, 0, 0, 0, 0, 0, 0, _D[0], _D[1], _D[2], _D[3],
                        _D[4], fee, ttl, grand_ttl)

                self.PARENT.DB.EXEC("BOOK_DB", _SQL)

            else:  # Existing Record

                # ------------------------------------------------
                if filled == 1:

                    completed = 1

                    _SQL = "SELECT ACT_grand_ttl from " + CURR_PAIR + " WHERE BKKPG_UID=" + BKKPG_UID

                    if _ACTION == "buy":

                        DATA = self.PARENT.DB.FETCH("BOOK_DB",
                                                    _SQL.replace(
                                                        "ACT", "sell"),
                                                    ALL=False)
                        profit_ttl = DATA - grand_ttl

                    else:

                        DATA = self.PARENT.DB.FETCH("BOOK_DB",
                                                    _SQL.replace("ACT", "buy"),
                                                    ALL=False)
                        profit_ttl = grand_ttl - DATA
                else:
                    profit_ttl = 0
                    completed = 0

                # ------------------------------------------------
                A = _ACTION

                _SQL = "UPDATE " + CURR_PAIR + " SET completed={0}, " + A + "_order_id={1}, " + A + "_unix_time={2}, " + A + "_filled={3}, "
                _SQL += A + "_amount={4}, " + A + "_at_price={5}, " + A + "_fee={6}, " + A + "_ttl={7}, " + A + "_grand_ttl={8}"
                _SQL += " WHERE BKKPG_UID=" + BKKPG_UID

                _SQL = _SQL.format(completed, order_id, unix_time, filled,
                                   amount, at_price, fee, ttl, grand_ttl)

                self.PARENT.DB.EXEC("BOOK_DB", _SQL)

        except Exception as _exception:

            print(" BOOKKEEPING[0:0]")
            print(_exception)
        # -------------------------------------------------------------------
        """
        BKKPG_UID, completed, started, 
        
        buy_order_id, buy_unix_time, buy_filled, buy_amount, buy_at_price, buy_fee, buy_ttl, buy_grand_ttl, 
        sell_order_id, sell_unix_time, sell_filled, sell_amount, sell_at_price, sell_fee, sell_ttl, sell_grand_ttl, 
        
        profit_ttl
        """
        # -------------------------------------------------------------------

    # =======================================================================
    def DELETE_ORDER(self, _order_id, _pair, _type):

        # -------------------------------------------------------------------

        _SQL = "SELECT buy_order_id, sell_order_id FROM " + _pair
        _SQL += " WHERE buy_order_id=" + str(
            _order_id) + " OR sell_order_id=" + str(_order_id)

        DATA = self.PARENT.DB.FETCH("BOOK_DB", _SQL, ALL=False)

        if DATA is None:
            pass

        if _type == "buy" and DATA[1] == 0:

            _SQL = "DELETE FROM " + _pair + " WHERE buy_order_id=" + str(
                _order_id) + " OR sell_order_id=" + str(_order_id)
            self.PARENT.DB.EXEC("BOOK_DB", _SQL)
            self.CREATE_LISTS()

        elif _type == "sell" and DATA[0] == 0:

            _SQL = "DELETE FROM " + _pair + " WHERE buy_order_id=" + str(
                _order_id) + " OR sell_order_id=" + str(_order_id)
            self.PARENT.DB.EXEC("BOOK_DB", _SQL)
            self.CREATE_LISTS()

        else:

            A = _type

            _SQL = "UPDATE " + self.PARENT.CURR_PAIR + " SET "
            _SQL += " completed=0, " + A + "_order_id=0, " + A + "_unix_time=0, " + A + "_filled=0, "
            _SQL += A + "_amount=0, " + A + "_at_price=0, " + A + "_fee=0, " + A + "_ttl=0, " + A + "_grand_ttl=0 "
            _SQL += "WHERE " + A + "_order_id=" + str(_order_id)

            self.PARENT.DB.EXEC("BOOK_DB", _SQL)

        # -------------------------------------------------------------------

    # =======================================================================
    def CREATE_LISTS(self):

        # -------------------------------------------------------------------
        try:
            CURR_PAIR = str(self.PAIR_COMBO.currentText()).lower()

            # -------------------------------------------------------------------
            self.BOOK = {
                "bought": [],
                "sold": []
            }

            self.BOUGHT_TTL = 0
            self.BOUGHT_TTL_PLUS_FEE = 0

            self.SOLD_TTL = 0
            self.SOLD_TTL_PLUS_FEE = 0

            # -------------------------------------------------------------------
            #self.PARENT.DB.EXEC( "BOOK_DB", "DELETE FROM "+CURR_PAIR+" WHERE BKKPG_UID>7" );

            DATA = self.PARENT.DB.FETCH("BOOK_DB",
                                        "SELECT * FROM " + CURR_PAIR +
                                        " ORDER BY BKKPG_UID DESC",
                                        ALL=True)
            self.BOOKKEEPING_WIDGET.clear()

            for data in DATA:

                # ---------------------------------------------------------------
                """ " "" 
                print( data )
                for d in data:
                    print( d )
                exit();
                "" " """
                # ---------------------------------------------------------------
                # In-Memory DATA
                BKKPG_UID = data[0]
                completed = data[1]
                started = data[2]

                buy_order_id = data[3]
                buy_unix_time = data[4]
                buy_filled = data[5]
                buy_amount = data[6]
                buy_at_price = data[7]
                #buy_fee         = data[8]
                buy_ttl = data[9]
                buy_grand_ttl = data[10]

                sell_order_id = data[11]
                sell_unix_time = data[12]
                sell_filled = data[13]
                sell_amount = data[14]

                sell_at_price = data[15]
                #sell_fee        = data[16]
                sell_ttl = data[17]
                sell_grand_ttl = data[18]

                profit_ttl = data[19]

                # ---------------------------------------------------------------

                # ---------------------------------------------------------------
                """
                self.BOOK[ data[3] ].append( {
                                            
                                        BKKPG_UID,
                                        completed,
                                        started,

                                        buy_order_id,
                                        buy_unix_time,
                                        buy_filled,
                                        buy_amount,
                                        buy_at_price,
                                        buy_fee,
                                        buy_ttl,
                                        buy_grand_ttl,

                                        sell_order_id,
                                        sell_unix_time,
                                        sell_filled,
                                        sell_amount,
                                        sell_at_price,
                                        sell_fee,
                                        sell_ttl,
                                        sell_grand_ttl,

                                        profit_ttl

                                            } );

                """
                # ---------------------------------------------------------------
                if self.CALCULATE_ONLY_COMPLETED:

                    if buy_filled == 1 and sell_filled == 1:

                        self.BOUGHT_TTL += buy_ttl
                        self.BOUGHT_TTL_PLUS_FEE += buy_grand_ttl * buy_at_price

                        self.SOLD_TTL += sell_ttl
                        self.SOLD_TTL_PLUS_FEE += sell_grand_ttl

                else:

                    self.BOUGHT_TTL += buy_ttl
                    self.BOUGHT_TTL_PLUS_FEE += buy_grand_ttl * buy_at_price

                    self.SOLD_TTL += sell_ttl
                    self.SOLD_TTL_PLUS_FEE += sell_grand_ttl

                self.PROFIT_TTL_LABLE.setText(
                    "{:10,.6f}".format(self.SOLD_TTL_PLUS_FEE -
                                       self.BOUGHT_TTL_PLUS_FEE))

                # ---------------------------------------------------------------
                # Formating data to Display in BookKeeping Wodget

                item = ""

                item += "DEL{:7} ".format(str(BKKPG_UID))
                # id

                # BUY / BOUGHT
                item += "#{:11} DEL".format(str(buy_order_id))
                # order_id
                item += "{:4} DEL".format(str(buy_filled))
                # filed
                item += "{:13} DEL".format(
                    str("{:10,.6f}".format(float(buy_amount))).strip())
                # Amount
                item += "{:13} DEL".format(
                    str("{:10,.6f}".format(buy_at_price)).strip())
                # at_price
                #item += "{:13} DEL".format( str("{:10,.6f}".format( data[7] )).strip() ); # fee
                #item += "{:13} DEL".format( str("{:10,.6f}".format( buy_ttl )).strip() ); # ttl
                item += "{:14} ".format(
                    str("{:10,.6f}".format(buy_grand_ttl)).strip())
                # grand_ttl

                # SELL / SOLD
                item += "#{:11} DEL".format(str(sell_order_id))
                # order_id
                item += "{:4} DEL".format(str(sell_filled))
                # filed
                item += "{:13} DEL".format(
                    str("{:10,.6f}".format(sell_amount)).strip())
                # Amount
                item += "{:13} DEL".format(
                    str("{:10,.6f}".format(sell_at_price)).strip())
                # at_price
                #item += "{:13} DEL".format( str("{:10,.6f}".format( data[7] )).strip() ); # fee
                #item += "{:13} DEL".format( str("{:10,.6f}".format( sell_ttl )).strip() ); # ttl
                item += "{:14} ".format(
                    str("{:10,.6f}".format(sell_grand_ttl)).strip())
                # grand_ttl

                # PROFIT
                item += "{:13}".format(
                    str("{:10,.6f}".format(profit_ttl)).strip())
                # grand_ttl

                newItem = QListWidgetItem(
                    QIcon("./data/imgs/icon_filled_status_0.png"),
                    item.replace("DEL", self._i_), self.BOOKKEEPING_WIDGET, 0)
                #newItemToolTip = "Order ID: #"+str()+" Created: "+time.ctime(int(data[2]));
                #newItem.setToolTip(newItemToolTip);

                # ---------------------------------------------------------------

            # / for
            # -------------------------------------------------------------------
            try:
                self.BOUGHT_TTL_LABLE.setText(
                    str("{:10,.6f}".format(self.BOUGHT_TTL).strip()))
                self.BOUGHT_TTL_PLUS_FEE_LABLE.setText(
                    str("{:10,.6f}".format(self.BOUGHT_TTL_PLUS_FEE).strip()))

                self.SOLD_TTL_LABLE.setText(
                    str("{:10,.6f}".format(self.SOLD_TTL).strip()))
                self.SOLD_TTL_PLUS_FEE_LABLE.setText(
                    str("{:10,.6f}".format(self.SOLD_TTL_PLUS_FEE).strip()))

            except Exception as e:
                print("BOOKKEEPING[3:0]" + str(e))

        except Exception as _exception:

            print(" BOOKKEEPING[1:0]")
            print(_exception)
        # -------------------------------------------------------------------

    # =======================================================================
    def RESET_BKKPG_UID(self):

        # -------------------------------------------------------------------
        #CURR_PAIR =  str(self.PAIR_COMBO.currentText()).lower();
        self.PARENT.GUI.BKKPG_UID_VALUE.setText("")
        self.PARENT.GUI.CONTROL_TRADINGS_BTNS("buy", "show")
        self.PARENT.GUI.CONTROL_TRADINGS_BTNS("sell", "show")
        # -------------------------------------------------------------------

    # =======================================================================
    def CHANGE_VALUES(self, _this):

        # -------------------------------------------------------------------
        if _this == "only_completed":
            if self.ONLY_COMPLETED_CHECKBOX.isChecked():
                self.CALCULATE_ONLY_COMPLETED = True
            else:
                self.CALCULATE_ONLY_COMPLETED = False

        # -------------------------------------------------------------------
        self.CREATE_LISTS()
        # -------------------------------------------------------------------

    # =======================================================================
    def CREATE_PAIRS_SELECTOR(self, ALL=False):

        # -------------------------------------------------------------------
        if not ALL:
            for PAIR in self.CONF["API"]["PAIRS"]:
                self.PAIR_COMBO.addItem(PAIR.upper())

        else:
            for PAIR in self.CONF["API"]["ALL_PAIRS"]:
                self.PAIR_COMBO.addItem(PAIR.upper())

        for i in xrange(0, self.PAIR_COMBO.__len__()):

            self.PAIR_COMBO.setItemData(i, QColor("#333"), Qt.BackgroundRole)
            self.PAIR_COMBO.setItemData(i, QColor("#fff"), Qt.ForegroundRole)
            #self.PAIR_COMBO.setItemData( i, QFont('monospace', 16, -1, False), Qt.FontRole);
        # -------------------------------------------------------------------

    # =======================================================================
    def SEND_VALUES_TO_TRADE_TERMINAL(self, _action):

        # -------------------------------------------------------------------
        if _action == "SELECT_VALUES":

            self.DATA_TO_SEND_SELECTED = True
            #self.DATA_TO_SEND = [ str(item).stip() for iten in str(self.BOOKKEEPING_WIDGET.currentItem().text()).strip().split("|")];
            self.DATA_TO_SEND = str(
                self.BOOKKEEPING_WIDGET.currentItem().text()).strip().split(
                    "|")[1].split("#")[0].strip()

        elif _action == "SEND_VALUES":

            if self.DATA_TO_SEND_SELECTED:

                _SQL = "SELECT buy_order_id, sell_order_id FROM " + self.PARENT.CURR_PAIR
                _SQL += " WHERE BKKPG_UID=" + self.DATA_TO_SEND

                DATA = self.PARENT.DB.FETCH("BOOK_DB", _SQL, ALL=False)

                if DATA[0] != 0 and DATA[1] != 0:

                    self.PARENT.GUI.SHOW_QMESSAGE(
                        "info",
                        "This UID is Full!<br> You can't add data to it enymore.<br>Bud You can delete sell and/or buy part<br/> and add new part."
                    )
                    return

                self.PARENT.GUI.BKKPG_UID_VALUE.setText(self.DATA_TO_SEND)

                self.PARENT.GUI.CONTROL_TRADINGS_BTNS("buy", "show")
                self.PARENT.GUI.CONTROL_TRADINGS_BTNS("sell", "show")

                self.DATA_TO_SEND_SELECTED = False
                self.DATA_TO_SEND = None

                # Clear Lables
                self.SEND_ID_LABLE.setText("n/a")
                self.SEND_AMOUNT_LABLE.setText("n/a")
                self.SEND_AT_PRICE_LABLE.setText("n/a")

                if DATA[0] == 0:
                    self.PARENT.GUI.CONTROL_TRADINGS_BTNS("sell", "hide")

                else:
                    self.PARENT.GUI.CONTROL_TRADINGS_BTNS("buy", "hide")

                # Switch to Trader-Tab
                self.PARENT.GUI.MAIN_TABS.setCurrentIndex(0)

            else:

                self.PARENT.GUI.SHOW_QMESSAGE(
                    "info",
                    " Select first item which one you would like<br/> send to the Trade-Terminal !"
                )
                return

        # -------------------------------------------------------------------
        if self.DATA_TO_SEND is not None:

            self.SEND_ID_LABLE.setText(self.DATA_TO_SEND)
示例#12
0
class History(QFrame):

    # =======================================================================
    def __init__(self, parent=None, _PARENT=None):

        # -------------------------------------------------------------------
        QFrame.__init__(self, parent)
        # -------------------------------------------------------------------
        self.PARENT = _PARENT
        self.CONF = _PARENT.CONF

        self.BOOK = {
            "bought": [],
            "sold": []
        }

        # -------------------------------------------------------------------
        self.setGeometry(3, 5, 975, 555)
        self.setStyleSheet(
            "QFrame{ font: 12px 'monospace'; color: #000; background-color: transparent; background-image: url('./data/imgs/TAB_History.png'); }"
        )

        self.PAIR_COMBO = QComboBox(self)
        self.PAIR_COMBO.setGeometry(86, 20, 108, 44)
        self.connect(self.PAIR_COMBO, SIGNAL('currentIndexChanged(int)'),
                     self.CREATE_LISTS)
        #self.PAIR_COMBO.setStyleSheet( "QComboBox{ font: 16px 'monospace'; background-color: #333; color: #FFF; border-style: solid; border-width: 1px; border-color: #000; border-radius: none; }" );
        self.PAIR_COMBO.setEditable(False)
        """
        #self.PAIR_COMBO.setItemIcon( 0, QIcon("./data/imgs/500.png") );
        print(self.PAIR_COMBO.__len__());
        #set at tooltip
        combo.setItemData(0,"a tooltip",Qt.ToolTipRole)
        # set the Font Color
        combo.setItemData(0,QColor("#FF333D"), Qt.BackgroundColorRole)
        #set the font
        combo.setItemData(0, QtGui.QFont('Verdana', bold=True), Qt.FontRole)
        """

        # -------------------------------------------------------------------
        list_style = "QListWidget{ font: 10px 'monospace'; color: #fff;  background-color: #000; border-style: none; background-image: url('./data/imgs/TAB_History_line.png'); }"
        # ./data/imgs/BookKeeping_line.png
        lable_style = "QLabel{ font: 10px 'monospace'; color: #fff;  background-color: transparent; border-style: none; background-image: url(''); }"
        # -------------------------------------------------------------------

        # Bought
        self.BOOKKEEPING_BOUGHT_WIDGET = QListWidget(self)
        self.BOOKKEEPING_BOUGHT_WIDGET.setGeometry(13, 144, 469, 400)
        self.BOOKKEEPING_BOUGHT_WIDGET.setStyleSheet(list_style)

        self.connect(
            self.BOOKKEEPING_BOUGHT_WIDGET, SIGNAL('itemSelectionChanged()'),
            lambda: self.SEND_VALUES_TO_TRADE_TERMINAL("BOUGHT_WIDGET"))
        self.BOOKKEEPING_BOUGHT_WIDGET.itemClicked.connect(
            lambda: self.SEND_VALUES_TO_TRADE_TERMINAL("BOUGHT_WIDGET"))

        self.BOUGHT_TTL_LABLE = QLabel("0.0", self)
        self.BOUGHT_TTL_LABLE.setGeometry(272, 406, 85, 17)
        #self.BOUGHT_TTL_LABLE.setEditable( False );
        self.BOUGHT_TTL_LABLE.setStyleSheet(lable_style)
        self.BOUGHT_TTL_LABLE.hide()
        self.BOUGHT_TTL = 0

        self.BOUGHT_TTL_PLUS_FEE_LABLE = QLabel("0.0", self)
        self.BOUGHT_TTL_PLUS_FEE_LABLE.setGeometry(362, 406, 118, 17)
        #self.BOUGHT_TTL_PLUS_FEE_LABLE.setEditable( False );
        self.BOUGHT_TTL_PLUS_FEE_LABLE.setStyleSheet(lable_style)
        self.BOUGHT_TTL_PLUS_FEE_LABLE.hide()
        self.BOUGHT_TTL_PLUS_FEE = 0

        # -------------------------------------------------------------------
        # Sold
        self.LAST_ACTIVE_WIDGET = None

        self.BOOKKEEPING_SOLD_WIDGET = QListWidget(self)
        self.BOOKKEEPING_SOLD_WIDGET.setGeometry(493, 144, 469, 400)
        self.BOOKKEEPING_SOLD_WIDGET.setStyleSheet(list_style)

        self.connect(self.BOOKKEEPING_SOLD_WIDGET,
                     SIGNAL('itemSelectionChanged()'),
                     lambda: self.SEND_VALUES_TO_TRADE_TERMINAL("SOLD_WIDGET"))
        self.BOOKKEEPING_SOLD_WIDGET.itemClicked.connect(
            lambda: self.SEND_VALUES_TO_TRADE_TERMINAL("SOLD_WIDGET"))

        self.SOLD_TTL_LABLE = QLabel("0.0", self)
        self.SOLD_TTL_LABLE.setGeometry(752, 406, 85, 17)
        #self.SOLD_TTL_LABLE.setEditable( False );
        self.SOLD_TTL_LABLE.setStyleSheet(lable_style)
        self.SOLD_TTL_LABLE.hide()
        self.SOLD_TTL = 0

        self.SOLD_TTL_PLUS_FEE_LABLE = QLabel("0.0", self)
        self.SOLD_TTL_PLUS_FEE_LABLE.setGeometry(842, 406, 118, 17)
        #self.SOLD_TTL_PLUS_FEE_LABLE.setEditable( False );
        self.SOLD_TTL_PLUS_FEE_LABLE.setStyleSheet(lable_style)
        self.SOLD_TTL_PLUS_FEE_LABLE.hide()
        self.SOLD_TTL_PLUS_FEE = 0

        # -------------------------------------------------------------------
        """
        self.DATA_TO_SEND                   = None;

        self.SEND_ID_LABLE                  = QLabel("n/a", self);
        self.SEND_ID_LABLE.setGeometry( 18, 467, 43, 17 );
        self.SEND_ID_LABLE.setStyleSheet( lable_style );

        self.SEND_AMOUNT_LABLE              = QLabel("n/a", self);
        self.SEND_AMOUNT_LABLE.setGeometry( 66, 467, 85, 17 );
        self.SEND_AMOUNT_LABLE.setStyleSheet( lable_style );

        self.SEND_AT_PRICE_LABLE            = QLabel("n/a", self);
        self.SEND_AT_PRICE_LABLE.setGeometry( 156, 467, 43, 17 );
        self.SEND_AT_PRICE_LABLE.setStyleSheet( lable_style );

        self.SEND_VALUES_BTN                = QPushButton("", self); 
        self.SEND_VALUES_BTN.setGeometry( 60, 502, 131, 33 );
        self.SEND_VALUES_BTN.setStyleSheet( "QPushButton{ background-color: transparent; border-style: none; }" ); 
        self.connect( self.SEND_VALUES_BTN, SIGNAL('clicked()'), lambda: self.SEND_VALUES_TO_TRADE_TERMINAL("SEND_VALUES") );
        """

        # -------------------------------------------------------------------
        self._i_ = "|"
        # List delimiter

        # -------------------------------------------------------------------
        self.ONLY_FILLED_CHECKBOX = QCheckBox("", self)
        self.ONLY_FILLED_CHECKBOX.setGeometry(647, 444, 17, 17)
        self.ONLY_FILLED_CHECKBOX.setCheckState(Qt.Checked)
        #self.ONLY_FILLED_CHECKBOX.setEnabled(False);
        self.connect(self.ONLY_FILLED_CHECKBOX, SIGNAL('stateChanged(int)'),
                     lambda: self.CHANGE_VALUES("only_filled"))
        self.ONLY_FILLED_CHECKBOX.hide()

        self.CALCULATE_ONLY_FILLED = True
        # -------------------------------------------------------------------
        self.INIT()
        # -------------------------------------------------------------------

    # =======================================================================
    def INIT(self):

        # -------------------------------------------------------------------
        try:

            self.CREATE_PAIRS_SELECTOR()
            self.CREATE_LISTS()

        except Exception as _exception:
            print("-----------------------------------------------------")
            print(_exception)
        # -------------------------------------------------------------------

    # =======================================================================
    def CREATE_LISTS(self):

        # -------------------------------------------------------------------
        CURR_PAIR = str(self.PAIR_COMBO.currentText()).lower()

        # -------------------------------------------------------------------
        self.BOOK = {
            "bought": [],
            "sold": []
        }

        self.BOUGHT_TTL = 0
        self.BOUGHT_TTL_PLUS_FEE = 0

        self.SOLD_TTL = 0
        self.SOLD_TTL_PLUS_FEE = 0

        # -------------------------------------------------------------------
        # Bought List
        # id, order_id, unix_time, action, filled, amount, at_price, fee, ttl, grand_ttl

        #self.PARENT.DB.EXEC( "HISTORY_DB", "DELETE FROM "+CURR_PAIR+" WHERE id>7" );

        DATA = self.PARENT.DB.FETCH("HISTORY_DB",
                                    "SELECT * FROM " + CURR_PAIR +
                                    " WHERE action='bought' ORDER BY id DESC",
                                    ALL=True)
        self.BOOKKEEPING_BOUGHT_WIDGET.clear()

        for data in DATA:

            # ---------------------------------------------------------------
            # In-Memory DATA

            self.BOOK[data[3]].append({
                "id": data[0],
                "order_id": data[1],
                "unix_time": data[2],
                "action": data[3],
                "filled": data[4],
                "amount": data[5],
                "at_price": data[6],
                "fee": data[7],
                "ttl": data[8],
                "grand_ttl": data[9]
            })

            if self.CALCULATE_ONLY_FILLED:
                if data[4] == 1:
                    self.BOUGHT_TTL += data[8]
                    self.BOUGHT_TTL_PLUS_FEE += data[9]

            else:
                self.BOUGHT_TTL += data[8]
                self.BOUGHT_TTL_PLUS_FEE += data[9]

            # ---------------------------------------------------------------
            # Formatinf data to Display in BookKeeping Wodget

            item = ""

            item += "DEL{:6} DEL".format(str(data[0]))
            # id
            #item += "{:11} DEL".format( data[1] ); # order_id
            #item += "{:11} DEL".format( data[2] ); # unix_time
            #item += "{:11} DEL".format( data[3] ); # action
            #item += "{:11} DEL".format( data[4] ); # filed
            item += "{:13} DEL".format(
                str("{:10,.6f}".format(data[5])).strip())
            # Amount
            item += "{:13} DEL".format(
                str("{:10,.6f}".format(data[6])).strip())
            # at_price
            #item += "{:13} DEL".format( str("{:10,.6f}".format( data[7] )).strip() ); # fee
            item += "{:13} DEL".format(
                str("{:10,.6f}".format(data[8])).strip())
            # ttl
            item += "{:13}".format(str("{:10,.6f}".format(data[9])).strip())
            # grand_ttl

            #self.BOOKKEEPING_BOUGHT_WIDGET.addItem( item.replace("DEL", self._i_) );
            newItem = QListWidgetItem(
                QIcon("./data/imgs/icon_filled_status_" + str(data[4]) +
                      ".png"), item.replace("DEL", self._i_),
                self.BOOKKEEPING_BOUGHT_WIDGET, 0)
            newItemToolTip = "Order ID: #" + str(
                data[1]) + " Created: " + time.ctime(int(data[2]))

            newItem.setToolTip(newItemToolTip)

            # ---------------------------------------------------------------
        # / for
        # -------------------------------------------------------------------
        self.BOUGHT_TTL_LABLE.setText(
            str("{:10,.6f}".format(self.BOUGHT_TTL).strip()))
        self.BOUGHT_TTL_PLUS_FEE_LABLE.setText(
            str("{:10,.6f}".format(self.BOUGHT_TTL_PLUS_FEE).strip()))

        # -------------------------------------------------------------------
        # Sold List
        # id, order_id, unix_time, action, filled, amount, at_price, fee, ttl, grand_ttl

        DATA = self.PARENT.DB.FETCH("HISTORY_DB",
                                    "SELECT * FROM " + CURR_PAIR +
                                    " WHERE action='sold' ORDER BY id DESC",
                                    ALL=True)
        self.BOOKKEEPING_SOLD_WIDGET.clear()

        for data in DATA:

            # ---------------------------------------------------------------
            # In-Memory DATA

            self.BOOK[data[3]].append({
                "id": data[0],
                "order_id": data[1],
                "unix_time": data[2],
                "action": data[3],
                "filled": data[4],
                "amount": data[5],
                "at_price": data[6],
                "fee": data[7],
                "ttl": data[8],
                "grand_ttl": data[9]
            })

            if self.CALCULATE_ONLY_FILLED:
                if data[4] == 1:
                    self.SOLD_TTL += data[8]
                    self.SOLD_TTL_PLUS_FEE += data[9]

            else:
                self.SOLD_TTL += data[8]
                self.SOLD_TTL_PLUS_FEE += data[9]

            # ---------------------------------------------------------------
            # Formatinf data to Display in BookKeeping Wodget

            item = ""

            item += "DEL{:6} DEL".format(str(data[0]))
            # id
            #item += "{:11} DEL".format( data[1] ); # order_id
            #item += "{:11} DEL".format( data[2] ); # unix_time
            #item += "{:11} DEL".format( data[3] ); # action
            #item += "{:11} DEL".format( data[4] ); # filed
            item += "{:13} DEL".format(
                str("{:10,.6f}".format(data[5])).strip())
            # Amount
            item += "{:13} DEL".format(
                str("{:10,.6f}".format(data[6])).strip())
            # at_price
            #item += "{:13} DEL".format( str("{:10,.6f}".format( data[7] )).strip() ); # fee
            item += "{:13} DEL".format(
                str("{:10,.6f}".format(data[8])).strip())
            # ttl
            item += "{:13}".format(str("{:10,.6f}".format(data[9])).strip())
            # grand_ttl

            #self.BOOKKEEPING_SOLD_WIDGET.addItem( item.replace("DEL", self._i_) );
            newItem = QListWidgetItem(
                QIcon("./data/imgs/icon_filled_status_" + str(data[4]) +
                      ".png"), item.replace("DEL", self._i_),
                self.BOOKKEEPING_SOLD_WIDGET, 0)

            newItemToolTip = "Order ID: #" + str(
                data[1]) + " Created: " + time.ctime(int(data[2]))

            newItem.setToolTip(newItemToolTip)
            # ---------------------------------------------------------------
        # / for
        # -------------------------------------------------------------------
        self.SOLD_TTL_LABLE.setText(
            str("{:10,.6f}".format(self.SOLD_TTL).strip()))
        self.SOLD_TTL_PLUS_FEE_LABLE.setText(
            str("{:10,.6f}".format(self.SOLD_TTL_PLUS_FEE).strip()))

        # -------------------------------------------------------------------

    # =======================================================================
    def CHANGE_VALUES(self, _this):

        # -------------------------------------------------------------------
        if _this == "only_filled":
            if self.ONLY_FILLED_CHECKBOX.isChecked():
                self.CALCULATE_ONLY_FILLED = True
            else:
                self.CALCULATE_ONLY_FILLED = False

        # -------------------------------------------------------------------
        self.CREATE_LISTS()
        # -------------------------------------------------------------------

    # =======================================================================
    def CREATE_PAIRS_SELECTOR(self, ALL=False):

        # -------------------------------------------------------------------
        if not ALL:
            for PAIR in self.CONF["API"]["PAIRS"]:
                self.PAIR_COMBO.addItem(PAIR.upper())

        else:
            for PAIR in self.CONF["API"]["ALL_PAIRS"]:
                self.PAIR_COMBO.addItem(PAIR.upper())

        for i in xrange(0, self.PAIR_COMBO.__len__()):

            self.PAIR_COMBO.setItemData(i, QColor("#333"), Qt.BackgroundRole)
            self.PAIR_COMBO.setItemData(i, QColor("#fff"), Qt.ForegroundRole)
            #self.PAIR_COMBO.setItemData( i, QFont('monospace', 16, -1, False), Qt.FontRole);
        # -------------------------------------------------------------------

    # =======================================================================
    def SEND_VALUES_TO_TRADE_TERMINAL(self, _action):

        # -------------------------------------------------------------------
        if _action == "BOUGHT_WIDGET":

            self.LAST_ACTIVE_WIDGET = "BOUGHT_WIDGET"
            self.DATA_TO_SEND = str(self.BOOKKEEPING_BOUGHT_WIDGET.currentItem(
            ).text()).strip().split("|")

            #self.SEND_ID_LABLE.setFocus();

        elif _action == "SOLD_WIDGET":

            self.LAST_ACTIVE_WIDGET = "SOLD_WIDGET"
            self.DATA_TO_SEND = str(self.BOOKKEEPING_SOLD_WIDGET.currentItem().
                                    text()).strip().split("|")

            #self.SEND_ID_LABLE.setFocus();

        elif _action == "SEND_VALUES":

            if self.LAST_ACTIVE_WIDGET is not None:

                self.PARENT.GUI.USER_SELL_AMOUNT.setText(
                    self.DATA_TO_SEND[2].strip())
                self.PARENT.GUI.USER_SELL_AT_PRICE.setText(
                    self.DATA_TO_SEND[3].strip())

                self.PARENT.GUI.USER_BUY_AMOUNT.setText(
                    self.DATA_TO_SEND[2].strip())
                self.PARENT.GUI.USER_BUY_AT_PRICE.setText(
                    self.DATA_TO_SEND[3].strip())

                self.LAST_ACTIVE_WIDGET = None
                self.DATA_TO_SEND = None

                # Show Tradeer Tab
                self.PARENT.GUI.MAIN_TABS.setCurrentIndex(0)

                # Clear Lables
                self.SEND_ID_LABLE.setText("n/a")
                self.SEND_AMOUNT_LABLE.setText("n/a")
                self.SEND_AT_PRICE_LABLE.setText("n/a")

            else:

                self.PARENT.GUI.SHOW_QMESSAGE(
                    "info",
                    " Select first item which one you would like<br/> send to the Trade-Terminal !"
                )
                return

        # -------------------------------------------------------------------
        if self.DATA_TO_SEND is not None:

            self.SEND_ID_LABLE.setText(self.DATA_TO_SEND[1])
            self.SEND_AMOUNT_LABLE.setText(self.DATA_TO_SEND[2])
            self.SEND_AT_PRICE_LABLE.setText(self.DATA_TO_SEND[3])

        # -------------------------------------------------------------------

    # =======================================================================
    def DELETE_ORDER(self, _order_id, _pair, _type):

        # ------------------------------------------------------------------
        self.PARENT.DB.EXEC(
            "HISTORY_DB",
            "DELETE FROM " + _pair + " WHERE order_id=" + str(_order_id))
示例#13
0
class Ui_MainWindow(object):
    # plot visualization variable
    present = None
    timer = None
    buffer = 16384
    linecolor = "green"
    # setting for pyaudio

    rate = 44100
    p = pyaudio.PyAudio()
    chunks = []
    inStream = None
    recThread = None
    addThread = None

    xlimit = 10000
    ylimit = 1000000

    savename = None
    displayTime = None
    data = None
    capFlag = 0
    mlFlag = 0

    fth = True
    sth = False
    tth = False

    dapper = [0.00, 0.00, 0.00]
    avgper = 0.00

    ndapper = [0.00, 0.00, 0.00]
    navgper = 0.00

    #    namePre=None
    #   ratePre=None
    #  spectrumPre=None
    # freqPre=None
    #nsamPre=None

    #

    def stream(self):
        while True:
            if self.inStream is not None:
                self.chunks.append(self.inStream.read(self.buffer))

    def record(self):
        self.inStream = self.p.open(format=pyaudio.paInt16,
                                    channels=1,
                                    rate=self.rate,
                                    input=True,
                                    frames_per_buffer=self.buffer)
        self.addThread = threading.Thread(target=self.stream)
        self.addThread.start()

    # a figure instance to plot on
    figure = None
    # this is the Canvas Widget that displays the `figure`
    canvas = None
    # this is the Navigation widget
    # it takes the Canvas widget and a parent
    toolbar = None

    def setupUi(self, MainWindow):
        screen_resolution = app.desktop().screenGeometry()
        width, height = screen_resolution.width(), screen_resolution.height()
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(width / 1.5, height / 1.5)
        #        MainWindow.setMinimumSize(QtCore.QSize(1024, 768))
        #        MainWindow.setMaximumSize(QtCore.QSize(width / 1.5, height / 1.5))

        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))

        # self.plotlayout = QtGui.QVBoxLayout(self.centralwidget)
        self.gridlayout = QtGui.QGridLayout(self.centralwidget)

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

        self.inGridlayout = QtGui.QGridLayout()
        self.inBoxlayout = QtGui.QHBoxLayout()

        self.list = QListWidget(self.centralwidget)

        # self.gridlayout.addLayout(self.list, 1)

        # inGridlayout has toolbar, button, ...etc
        # inBoxlayout has button6, button5, button4
        #        self.gridLayout.addWidget(self.toolbar)
        self.gridlayout.addWidget(self.toolbar, 0, 0)
        self.gridlayout.addWidget(self.canvas, 1, 0)
        self.gridlayout.addLayout(self.inGridlayout, 3, 0)
        self.gridlayout.addLayout(self.inBoxlayout, 2, 0)
        self.gridlayout.addLayout(self.inBoxlayout, 0, 3)
        self.gridlayout.addWidget(self.list, 0, 1, 4, 4)
        # self.inBoxlayout.addWidget(self.toolbar,0)
        self.gridlayout.setObjectName(_fromUtf8("griddisplay"))
        # self.centralwidget.setLayout(self.plotlayout)

        palettegl = QtGui.QPalette()
        palettegl.setBrush(QtGui.QPalette.Light, QtCore.Qt.black)
        """
                self.lineEdit = QtGui.QTextEdit(self.centralwidget)
                # self.lineEdit.setGeometry(QtCore.QRect(10, 475, 800, 105))
                self.gridlayout.addWidget(self.lineEdit, 0, 3, 4, 4)
                self.lineEdit.setObjectName(_fromUtf8("lineEdit"))
                self.lineEdit.setReadOnly(True)


"""

        self.qlabeldap = QtGui.QLabel(self.centralwidget)
        self.qlabeldap.setText("Estimated Payloaded DAP Percentage")
        self.inGridlayout.addWidget(self.qlabeldap, 1, 0, 1, 1)

        self.leftBoundary_1 = QtGui.QPushButton(self.centralwidget)
        self.leftBoundary_1.setGeometry(QtCore.QRect(340, 668, 91, 38))
        self.leftBoundary_1.setObjectName(_fromUtf8("leftBoundary_1"))
        self.leftBoundary_1.clicked.connect(self.lbnd1f)
        #        self.leftBoundary_1.setPalette(palettegl)
        #        self.leftBoundary_1.display("00:00")
        self.inGridlayout.addWidget(self.leftBoundary_1, 1, 1, 1, 1)

        self.rightBoundary_1 = QtGui.QPushButton(self.centralwidget)
        self.rightBoundary_1.setGeometry(QtCore.QRect(340, 668, 91, 38))
        self.rightBoundary_1.setObjectName(_fromUtf8("rightBoundary_1"))
        self.rightBoundary_1.clicked.connect(self.rbnd1f)
        #        self.rightBoundary_1.setPalette(palettegl)
        #        self.rightBoundary_1.display("00:00")
        self.inGridlayout.addWidget(self.rightBoundary_1, 1, 2, 1, 1)

        self.threshold_1 = QtGui.QPushButton(self.centralwidget)
        self.threshold_1.setGeometry(QtCore.QRect(340, 668, 91, 38))
        self.threshold_1.setObjectName(_fromUtf8("threshold_1"))
        self.threshold_1.clicked.connect(self.th1f)
        #        self.threshold_1.setPalette(palettegl)
        #        self.threshold_1.display("00:00")
        self.inGridlayout.addWidget(self.threshold_1, 1, 3, 1, 1)

        #        self.qLabelChunk1 = QtGui.QLabel(self.centralwidget)
        #        self.qLabelChunk1.setText("labelChunk1")
        #        self.inGridlayout.addWidget(self.qLabelChunk1,2,0,1,1)

        self.Dapp = QtGui.QLCDNumber(self.centralwidget)
        self.Dapp.setGeometry(QtCore.QRect(340, 668, 91, 38))
        self.Dapp.setObjectName(_fromUtf8("Dapp"))
        self.Dapp.setPalette(palettegl)
        self.Dapp.display("00.00")
        self.inGridlayout.addWidget(self.Dapp, 2, 0, 1, 1)

        self.lbnd1 = QtGui.QSpinBox(self.centralwidget)
        self.lbnd1.setRange(0, 20000)
        self.lbnd1.setValue(1000)
        self.lbnd1.setGeometry(QtCore.QRect(740, 668, 55, 38))
        self.lbnd1.setObjectName(_fromUtf8("lbnd1size"))
        self.inGridlayout.addWidget(self.lbnd1, 2, 1, 1, 1)

        self.rbnd1 = QtGui.QSpinBox(self.centralwidget)
        self.rbnd1.setRange(0, 20000)
        self.rbnd1.setValue(2500)
        self.rbnd1.setGeometry(QtCore.QRect(740, 668, 55, 38))
        self.rbnd1.setObjectName(_fromUtf8("rbnd1size"))
        self.inGridlayout.addWidget(self.rbnd1, 2, 2, 1, 1)

        self.th1 = QtGui.QSpinBox(self.centralwidget)
        self.th1.setRange(200000, 100000000)
        self.th1.setValue(200000)
        self.th1.setGeometry(QtCore.QRect(740, 668, 55, 38))
        self.th1.setObjectName(_fromUtf8("th1size"))
        self.inGridlayout.addWidget(self.th1, 2, 3, 1, 1)

        self.qLabelLCD2 = QtGui.QLabel(self.centralwidget)
        self.qLabelLCD2.setText("Estimated Non Payloaded DAP Percentage")
        self.inGridlayout.addWidget(self.qLabelLCD2, 3, 0, 1, 1)

        self.leftBoundary_2 = QtGui.QPushButton(self.centralwidget)
        self.leftBoundary_2.setGeometry(QtCore.QRect(340, 668, 91, 38))
        self.leftBoundary_2.setObjectName(_fromUtf8("leftBoundary_2"))
        self.leftBoundary_2.clicked.connect(self.lbnd2f)
        #        self.leftBoundary_2.setPalette(palettegl)
        #        self.leftBoundary_2.display("00:00")
        self.inGridlayout.addWidget(self.leftBoundary_2, 3, 1, 1, 1)

        self.rightBoundary_2 = QtGui.QPushButton(self.centralwidget)
        self.rightBoundary_2.setGeometry(QtCore.QRect(340, 668, 91, 38))
        self.rightBoundary_2.setObjectName(_fromUtf8("rightBoundary_2"))
        self.rightBoundary_2.clicked.connect(self.rbnd2f)
        #        self.rightBoundary_2.setPalette(palettegl)
        #        self.rightBoundary_2.display("00:00")
        self.inGridlayout.addWidget(self.rightBoundary_2, 3, 2, 1, 1)

        self.threshold_2 = QtGui.QPushButton(self.centralwidget)
        self.threshold_2.setGeometry(QtCore.QRect(340, 668, 91, 38))
        self.threshold_2.setObjectName(_fromUtf8("threshold_2"))
        self.threshold_2.clicked.connect(self.th2f)
        #        self.threshold_2.setPalette(palettegl)
        #        self.threshold_2.display("00:00")
        self.inGridlayout.addWidget(self.threshold_2, 3, 3, 1, 1)

        #        self.qLabelChunk2 = QtGui.QLabel(self.centralwidget)
        #        self.qLabelChunk2.setText("labelChunk2")
        #        self.inGridlayout.addWidget(self.qLabelChunk2,4,0,1,1)

        self.nDapp = QtGui.QLCDNumber(self.centralwidget)
        self.nDapp.setGeometry(QtCore.QRect(340, 668, 91, 38))
        self.nDapp.setObjectName(_fromUtf8("nDapp"))
        self.nDapp.setPalette(palettegl)
        self.nDapp.display("00.00")
        self.inGridlayout.addWidget(self.nDapp, 4, 0, 1, 1)

        self.lbnd2 = QtGui.QSpinBox(self.centralwidget)
        self.lbnd2.setRange(0, 20000)
        self.lbnd2.setValue(2500)
        self.lbnd2.setGeometry(QtCore.QRect(740, 668, 55, 38))
        self.lbnd2.setObjectName(_fromUtf8("lbnd2size"))
        self.inGridlayout.addWidget(self.lbnd2, 4, 1, 1, 1)
        self.lbnd2.setEnabled(False)

        self.rbnd2 = QtGui.QSpinBox(self.centralwidget)
        self.rbnd2.setRange(0, 20000)
        self.rbnd2.setValue(6000)
        self.rbnd2.setGeometry(QtCore.QRect(740, 668, 55, 38))
        self.rbnd2.setObjectName(_fromUtf8("rbnd2size"))
        self.inGridlayout.addWidget(self.rbnd2, 4, 2, 1, 1)
        self.rbnd2.setEnabled(False)

        self.th2 = QtGui.QSpinBox(self.centralwidget)
        self.th2.setRange(200000, 100000000)
        self.th2.setValue(200000)
        self.th2.setGeometry(QtCore.QRect(740, 668, 55, 38))
        self.th2.setObjectName(_fromUtf8("th2size"))
        self.inGridlayout.addWidget(self.th2, 4, 3, 1, 1)
        self.th2.setEnabled(False)

        self.qLabelLCD3 = QtGui.QLabel(self.centralwidget)
        self.qLabelLCD3.setText("Payloaded Drone/Non PD Detection Count")
        self.inGridlayout.addWidget(self.qLabelLCD3, 5, 0, 1, 1)

        self.leftBoundary_3 = QtGui.QPushButton(self.centralwidget)
        self.leftBoundary_3.setGeometry(QtCore.QRect(340, 668, 91, 38))
        self.leftBoundary_3.setObjectName(_fromUtf8("leftBoundary_3"))
        self.leftBoundary_3.clicked.connect(self.lbnd3f)
        #        self.leftBoundary_3.setPalette(palettegl)
        #        self.leftBoundary_3.display("00:00")
        self.inGridlayout.addWidget(self.leftBoundary_3, 5, 1, 1, 1)

        self.rightBoundary_3 = QtGui.QPushButton(self.centralwidget)
        self.rightBoundary_3.setGeometry(QtCore.QRect(340, 668, 91, 38))
        self.rightBoundary_3.setObjectName(_fromUtf8("rightBoundary_3"))
        self.rightBoundary_3.clicked.connect(self.rbnd3f)
        #        self.lcdNumber3_2.setPalette(palettegl)
        #        self.lcdNumber3_2.display("00:00")
        self.inGridlayout.addWidget(self.rightBoundary_3, 5, 2, 1, 1)

        self.threshold_3 = QtGui.QPushButton(self.centralwidget)
        self.threshold_3.setGeometry(QtCore.QRect(340, 668, 91, 38))
        self.threshold_3.setObjectName(_fromUtf8("threshold_3"))
        self.threshold_3.clicked.connect(self.th3f)
        #        self.threshold_3.setPalette(palettegl)
        #        self.threshold_3.display("00:00")
        self.inGridlayout.addWidget(self.threshold_3, 5, 3, 1, 1)

        #        self.qLabelChunk3 = QtGui.QLabel(self.centralwidget)
        #        self.qLabelChunk3.setText("labelChunk3")
        #        self.inGridlayout.addWidget(self.qLabelChunk3, 6, 0, 1, 1)

        self.CntLcd = QtGui.QLCDNumber(self.centralwidget)
        self.CntLcd.setGeometry(QtCore.QRect(340, 668, 91, 38))
        self.CntLcd.setObjectName(_fromUtf8("CntLcd"))
        self.CntLcd.setPalette(palettegl)
        self.CntLcd.display("00:00")
        self.inGridlayout.addWidget(self.CntLcd, 6, 0, 1, 1)

        self.lbnd3 = QtGui.QSpinBox(self.centralwidget)
        self.lbnd3.setRange(0, 20000)
        self.lbnd3.setValue(6000)
        self.lbnd3.setGeometry(QtCore.QRect(740, 668, 55, 38))
        self.lbnd3.setObjectName(_fromUtf8("lbnd3size"))
        self.inGridlayout.addWidget(self.lbnd3, 6, 1, 1, 1)
        self.lbnd3.setEnabled(False)

        self.rbnd3 = QtGui.QSpinBox(self.centralwidget)
        self.rbnd3.setRange(0, 20000)
        self.rbnd3.setValue(9000)
        self.rbnd3.setGeometry(QtCore.QRect(740, 668, 55, 38))
        self.rbnd3.setObjectName(_fromUtf8("rbnd3size"))
        self.inGridlayout.addWidget(self.rbnd3, 6, 2, 1, 1)
        self.rbnd3.setEnabled(False)

        self.th3 = QtGui.QSpinBox(self.centralwidget)
        self.th3.setRange(200000, 100000000)
        self.th3.setValue(200000)
        self.th3.setGeometry(QtCore.QRect(740, 668, 55, 38))
        self.th3.setObjectName(_fromUtf8("th3size"))
        self.inGridlayout.addWidget(self.th3, 6, 3, 1, 1)
        self.th3.setEnabled(False)

        self.lcdNumber = QtGui.QLCDNumber(self.centralwidget)
        self.lcdNumber.setGeometry(QtCore.QRect(340, 668, 91, 38))
        self.lcdNumber.setObjectName(_fromUtf8("lcdNumber"))
        self.lcdNumber.setPalette(palettegl)
        self.lcdNumber.display("00:00")
        self.inBoxlayout.addWidget(self.lcdNumber, 1)

        self.analyzeButton = QtGui.QPushButton(self.centralwidget)
        self.analyzeButton.setGeometry(QtCore.QRect(440, 668, 91, 38))
        self.analyzeButton.setObjectName(_fromUtf8("analyzeButton"))
        self.analyzeButton.clicked.connect(self.start)
        self.inBoxlayout.addWidget(self.analyzeButton, 2)
        self.analyzeButton.connect(
            QtGui.QShortcut(QtGui.QKeySequence(QtCore.Qt.Key_F1),
                            self.centralwidget), QtCore.SIGNAL('activated()'),
            self.start)
        #     self.inGridlayout.addWidget(self.analyzeButton)

        self.stopButton = QtGui.QPushButton(self.centralwidget)
        self.stopButton.setGeometry(QtCore.QRect(540, 668, 91, 38))
        self.stopButton.setObjectName(_fromUtf8("stopButton"))
        self.stopButton.clicked.connect(self.stop)
        self.inBoxlayout.addWidget(self.stopButton, 3)
        self.stopButton.connect(
            QtGui.QShortcut(QtGui.QKeySequence(QtCore.Qt.Key_F2),
                            self.centralwidget), QtCore.SIGNAL('activated()'),
            self.stop)
        #      self.inGridlayout.addWidget(self.stopButton)

        self.recordButton = QtGui.QPushButton(self.centralwidget)
        self.recordButton.setGeometry(QtCore.QRect(640, 668, 91, 38))
        self.recordButton.setObjectName(_fromUtf8("recordButton"))
        self.recordButton.clicked.connect(self.save)
        self.inBoxlayout.addWidget(self.recordButton, 4)
        self.recordButton.connect(
            QtGui.QShortcut(QtGui.QKeySequence(QtCore.Qt.Key_F3),
                            self.centralwidget), QtCore.SIGNAL('activated()'),
            self.save)

        self.chunksize = QtGui.QSpinBox(self.centralwidget)
        self.chunksize.setRange(10, 17)
        self.chunksize.setValue(14)
        self.chunksize.setGeometry(QtCore.QRect(740, 668, 55, 38))
        self.chunksize.setObjectName(_fromUtf8("chunksize"))
        self.inBoxlayout.addWidget(self.chunksize, 5)
        self.chunksize.valueChanged.connect(self.intchanged)

        #       self.inGridlayout.addWidget(self.recordButton)
        self.horizontalSlider = QtGui.QSlider(self.centralwidget)
        self.horizontalSlider.setRange(200, 20000)
        self.horizontalSlider.setValue(10000)
        self.horizontalSlider.valueChanged.connect(self.hsvhandler)
        self.horizontalSlider.setGeometry(QtCore.QRect(800, 668, 71, 38))
        self.inBoxlayout.addWidget(self.horizontalSlider, 6)
        self.horizontalSlider.setOrientation(QtCore.Qt.Horizontal)
        self.horizontalSlider.setObjectName(_fromUtf8("horizontalSlider"))
        #    self.inGridlayout.addWidget(self.horizontalSlider)

        self.verticallSlider = QtGui.QSlider(self.centralwidget)
        self.verticallSlider.setRange(1000000, 100000000)
        self.verticallSlider.setValue(1000000)
        self.verticallSlider.valueChanged.connect(self.vsvhandler)
        self.verticallSlider.setGeometry(QtCore.QRect(880, 668, 71, 38))
        self.verticallSlider.setOrientation(QtCore.Qt.Vertical)
        self.inBoxlayout.addWidget(self.verticallSlider, 7)
        self.verticallSlider.setObjectName(_fromUtf8("verticalSlider"))
        #  self.inGridlayout.addWidget(self.verticallSlider, 7, 0, 7, 2)
        #   self.inGridlayout.addWidget(self.verticallSlider)

        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtGui.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 1024, 26))
        self.menubar.setObjectName(_fromUtf8("menubar"))

        self.menuFFT_Mode = QtGui.QMenu(self.menubar)
        self.menuFFT_Mode.setObjectName(_fromUtf8("menuDegree"))

        self.menuCross = QtGui.QMenu(self.menubar)
        self.menuCross.setObjectName(_fromUtf8("menuCross"))

        self.menuCapture = QtGui.QMenu(self.menubar)
        self.menuCapture.setObjectName(_fromUtf8("menuCapture"))

        self.menuThreshold = QtGui.QMenu(self.menubar)
        self.menuThreshold.setObjectName(_fromUtf8("menuThreshold"))

        self.menuConnection = QtGui.QMenu(self.menubar)
        self.menuConnection.setObjectName(_fromUtf8("menuConnection"))

        self.menuConsole = QtGui.QMenu(self.menubar)
        self.menuConsole.setObjectName(_fromUtf8("menuConsole"))

        self.menuHelp = QtGui.QMenu(self.menubar)
        self.menuHelp.setObjectName(_fromUtf8("menuHelp"))

        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtGui.QStatusBar(MainWindow)
        self.statusbar.setObjectName(_fromUtf8("statusbar"))

        MainWindow.setStatusBar(self.statusbar)
        ag = QtGui.QActionGroup(MainWindow, exclusive=True)
        self.actionDrone = ag.addAction(
            QtGui.QAction(MainWindow, checkable=True))
        self.actionDrone.setChecked(True)
        self.actionDrone.triggered.connect(self.green)
        self.actionDrone.setObjectName(_fromUtf8("zero"))

        self.actionOthers = ag.addAction(
            QtGui.QAction(MainWindow, checkable=True))
        self.actionOthers.triggered.connect(self.red)
        self.actionOthers.setObjectName(_fromUtf8("sixty"))

        self.menuFFT_Mode.addAction(self.actionDrone)
        self.menuFFT_Mode.addAction(self.actionOthers)
        self.menubar.addAction(self.menuFFT_Mode.menuAction())

        ag2 = QtGui.QActionGroup(MainWindow, exclusive=True)
        self.scr = ag2.addAction(QtGui.QAction(MainWindow, checkable=True))
        self.scr.setChecked(True)
        self.scr.triggered.connect(self.scrmode)
        self.scr.setObjectName(_fromUtf8("scrOnly"))

        self.rec = ag2.addAction(QtGui.QAction(MainWindow, checkable=True))
        self.rec.triggered.connect(self.recmode)
        self.rec.setObjectName(_fromUtf8("recOnly"))

        self.scrnrec = ag2.addAction(QtGui.QAction(MainWindow, checkable=True))
        self.scrnrec.triggered.connect(self.scrnrecmode)
        self.scrnrec.setObjectName(_fromUtf8("scrNrec"))

        self.menuCapture.addAction(self.scr)
        self.menuCapture.addAction(self.rec)
        self.menuCapture.addAction(self.scrnrec)

        self.menubar.addAction(self.menuCapture.menuAction())

        ag3 = QtGui.QActionGroup(MainWindow, exclusive=True)
        self.autopilot = ag3.addAction(
            QtGui.QAction(MainWindow, checkable=True))
        self.autopilot.triggered.connect(self.automode)
        self.autopilot.setObjectName(_fromUtf8("autopilot"))

        self.supervise = ag3.addAction(
            QtGui.QAction(MainWindow, checkable=True))
        self.supervise.triggered.connect(self.manualmode)
        self.supervise.setObjectName(_fromUtf8("supervise"))

        self.thonly = ag3.addAction(QtGui.QAction(MainWindow, checkable=True))
        self.thonly.triggered.connect(self.thmode)
        self.thonly.setObjectName(_fromUtf8("thonly"))
        self.thonly.setChecked(True)

        self.menuCross.addAction(self.autopilot)
        self.menuCross.addAction(self.supervise)
        self.menuCross.addAction(self.thonly)

        self.menubar.addAction(self.menuCross.menuAction())

        ag4 = QtGui.QActionGroup(MainWindow, exclusive=False)

        self.fir = ag4.addAction(QtGui.QAction(MainWindow, checkable=True))
        self.fir.setChecked(True)
        self.fir.setObjectName(_fromUtf8("First"))
        self.fir.triggered.connect(self.chkfir)

        self.sec = ag4.addAction(QtGui.QAction(MainWindow, checkable=True))
        self.sec.setObjectName(_fromUtf8("Second"))
        self.sec.triggered.connect(self.chksec)

        self.thi = ag4.addAction(QtGui.QAction(MainWindow, checkable=True))
        self.thi.setObjectName(_fromUtf8("Third"))
        self.thi.triggered.connect(self.chkthi)

        self.menuThreshold.addAction(self.fir)
        self.menuThreshold.addAction(self.sec)
        self.menuThreshold.addAction(self.thi)

        self.menubar.addAction(self.menuThreshold.menuAction())

        ag5 = QtGui.QActionGroup(MainWindow, exclusive=True)

        self.con = ag5.addAction(QtGui.QAction(MainWindow, checkable=True))
        self.con.setChecked(True)
        self.con.setObjectName(_fromUtf8("Connect"))

        self.discon = ag5.addAction(QtGui.QAction(MainWindow, checkable=True))
        self.discon.setObjectName(_fromUtf8("Disconnect"))

        self.menuConnection.addAction(self.con)
        self.menuConnection.addAction(self.discon)
        self.menubar.addAction(self.menuConnection.menuAction())

        ag6 = QtGui.QActionGroup(MainWindow)

        self.write = ag6.addAction(QtGui.QAction(MainWindow))
        self.write.setChecked(True)
        self.write.setObjectName(_fromUtf8("Write"))

        self.clear = ag6.addAction(QtGui.QAction(MainWindow))
        self.clear.setObjectName(_fromUtf8("Clear"))

        self.menuConsole.addAction(self.write)
        self.menuConsole.addAction(self.clear)

        self.menubar.addAction(self.menuConsole.menuAction())

        ag7 = QtGui.QActionGroup(MainWindow)

        self.dev = ag7.addAction(QtGui.QAction(MainWindow))
        self.dev.setChecked(True)
        # self.dev.triggered.connect(self.help)
        self.dev.setObjectName(_fromUtf8("Developers"))

        self.about = ag7.addAction(QtGui.QAction(MainWindow))
        self.about.setObjectName(_fromUtf8("About"))

        self.menuHelp.addAction(self.dev)
        self.menuHelp.addAction(self.about)

        self.menubar.addAction(self.menuHelp.menuAction())

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(
            _translate(
                "MainWindow",
                "Realtime Fast Fourier Transform Analyzer For Caputuring Payloaded Drone Frequency-Made by Kiefer Kim",
                None))
        self.recordButton.setText(_translate("MainWindow", "Record(F3)", None))
        self.stopButton.setText(_translate("MainWindow", "Stop(F2)", None))
        self.analyzeButton.setText(
            _translate("MainWindow", "Analyze(F1)", None))

        # leftBoundary_1 etc
        self.leftBoundary_1.setText(
            _translate("MainWindow", "1st Minimum Frequency", None))
        self.rightBoundary_1.setText(
            _translate("MainWindow", "1st Maximum Frequency", None))
        self.threshold_1.setText(
            _translate("MainWindow", "1st Threshold", None))
        self.leftBoundary_2.setText(
            _translate("MainWindow", "2nd Minimum Frequency", None))
        self.rightBoundary_2.setText(
            _translate("MainWindow", "2nd Maximum Frequency", None))
        self.threshold_2.setText(
            _translate("MainWindow", "2nd Threshold", None))
        self.leftBoundary_3.setText(
            _translate("MainWindow", "3rd Minimum Frequency", None))
        self.rightBoundary_3.setText(
            _translate("MainWindow", "3rd Maximum Frequency", None))
        self.threshold_3.setText(
            _translate("MainWindow", "3rd Threshold", None))

        self.menuFFT_Mode.setTitle(
            _translate("MainWindow", "Object Type", None))
        self.actionDrone.setText(
            _translate("MainWindow", "Payloaded Drone", None))
        self.actionOthers.setText(_translate("MainWindow", "Others", None))

        self.menuCross.setTitle(
            _translate("MainWindow", "Machine Learning", None))
        self.autopilot.setText(_translate("MainWindow", "Self Learn", None))
        self.supervise.setText(_translate("MainWindow", "Validation", None))
        self.thonly.setText(_translate("MainWindow", "Deactivate", None))

        self.menuCapture.setTitle(_translate("MainWindow", "Record", None))
        self.scr.setText(_translate("MainWindow", "Plot.png Only", None))
        self.rec.setText(_translate("MainWindow", "Record.wav Only", None))
        self.scrnrec.setText(
            _translate("MainWindow", "Plot.png+Record.wav", None))

        self.menuThreshold.setTitle(_translate("MainWindow", "Threshold",
                                               None))
        self.fir.setText(_translate("MainWindow", "First", None))
        self.sec.setText(_translate("MainWindow", "Second", None))
        self.thi.setText(_translate("MainWindow", "Third", None))

        self.menuConnection.setTitle(
            _translate("MainWindow", "Connection", None))
        self.con.setText(_translate("MainWindow", "Connect", None))
        self.discon.setText(_translate("MainWindow", "Disconnect", None))
        #
        self.menuConsole.setTitle(_translate("MainWindow", "Console", None))
        self.write.setText(_translate("MainWindow", "Write", None))
        self.clear.setText(_translate("MainWindow", "Clear", None))

        self.menuHelp.setTitle(_translate("MainWindow", "Help", None))
        self.dev.setText(_translate("MainWindow", "Developers", None))
        self.about.setText(_translate("MainWindow", "About", None))

    def tick(self):
        now = datetime.datetime.now()
        minutes, seconds = divmod((now - self.present).total_seconds(), 60)
        self.displayTime = QtCore.QTime(0, minutes, round(seconds))
        self.lcdNumber.display(self.displayTime.toString('mm:ss'))

        if len(self.chunks) > 0:
            X = self.chunks.pop(0)
            self.data = scipy.array(struct.unpack("%dB" % (self.buffer * 2),
                                                  X))

            # print "RECORDED",len(self.data)/float(self.rate),"SEC"
            # ffty = scipy.fftpack.fft(self.data)
            # fftx = scipy.fftpack.rfftfreq(self.buffer * 2, 1.0 / self.rate)

            spectrum = scipy.fftpack.fft(self.data)
            freq = scipy.fftpack.fftfreq(len(self.data), d=0.5 / self.rate)
            #if self.mlFlag is 0:
            ax2 = self.figure.add_subplot(111)
            ax2.plot(freq, abs(spectrum), color=self.linecolor)
            if self.fir.isChecked():
                l1 = self.lbnd1.value() * self.buffer / self.rate
                r1 = self.rbnd1.value() * self.buffer / self.rate
                max1 = np.amax(abs(spectrum[l1:r1]))
                for index, xy in enumerate(zip(freq, abs(spectrum))):
                    if xy[1] == max1:
                        plt.annotate('(%s, %s)' % (int(xy[0]), int(xy[1])),
                                     xy=xy)
                        if max1 >= self.th1.value() and xy[0] > 0:
                            temp = self.capFlag
                            self.capFlag = -1
                            self.save()
                            if self.actionDrone.isChecked():
                                self.lineEdit.append(u'드론모드 th1 검출:')
                                if self.thonly.isChecked():
                                    self.dapper[0] = max1 / self.th1.value(
                                    ) * 100
                                    if self.dapper[0] > 100.00:
                                        self.dapper[0] = 100.00
                            else:
                                self.lineEdit.append(u'기타모드 th1 검출:')
                            self.lineEdit.append(self.savename + ":" +
                                                 str(xy) + ">=" +
                                                 str(self.th1.value()))
                            self.capFlag = temp

            if self.sec.isChecked():
                l2 = self.lbnd2.value() * self.buffer / self.rate
                r2 = self.rbnd2.value() * self.buffer / self.rate
                max2 = np.amax(abs(spectrum[l2:r2]))
                for index, xy in enumerate(zip(freq, abs(spectrum))):
                    if xy[1] == max2:
                        plt.annotate('(%s, %s)' % (int(xy[0]), int(xy[1])),
                                     xy=xy)
                        if max2 >= self.th2.value() and xy[0] > 0:
                            temp = self.capFlag
                            self.capFlag = -1
                            self.save()
                            if self.actionDrone.isChecked():
                                self.lineEdit.append(u'드론모드 th2 검출:')
                                if self.thonly.isChecked():
                                    self.dapper[1] = max2 / self.th2.value(
                                    ) * 100
                                    if self.dapper[1] > 100.00:
                                        self.dapper[1] = 100.00
                            else:
                                self.lineEdit.append(u'기타모드 th2 검출:')
                            self.lineEdit.append(self.savename + ":" +
                                                 str(xy) + ">=" +
                                                 str(self.th2.value()))
                            self.capFlag = temp

            if self.thi.isChecked():
                l3 = self.lbnd3.value() * self.buffer / self.rate
                r3 = self.rbnd3.value() * self.buffer / self.rate
                max3 = np.amax(abs(spectrum[l3:r3]))
                for index, xy in enumerate(zip(freq, abs(spectrum))):
                    if xy[1] == max3:
                        plt.annotate('(%s, %s)' % (int(xy[0]), int(xy[1])),
                                     xy=xy)
                        if max3 >= self.th3.value() and xy[0] > 0:
                            temp = self.capFlag
                            self.capFlag = -1
                            self.save()
                            if self.actionDrone.isChecked():
                                self.lineEdit.append(u'드론모드 th3 검출:')
                                if self.thonly.isChecked():
                                    self.dapper[2] = max3 / self.th3.value(
                                    ) * 100
                                    if self.dapper[2] > 100.00:
                                        self.dapper[2] = 100.00
                            else:
                                self.lineEdit.append(u'기타모드 th3 검출:')
                            self.lineEdit.append(self.savename + ":" +
                                                 str(xy) + ">=" +
                                                 str(self.th3.value()))
                            self.capFlag = temp
            self.calcdap()

            #print np.alen(abs(spectrum))
            #print np.alen(freq)
            #for xy in zip(freq, abs(spectrum)):
            #   if maxamplitude == xy[1]:
            #      plt.annotate('(%s, %s)' % xy, xy=xy, textcoords='data')
            ax2.set_xlim(0, self.xlimit)
            ax2.set_ylim(0, self.ylimit)
            ax2.set_xlabel("frequency [Hz]")
            #ax2.set_title("Recorded Chunk Sec: " + str(len(self.data) / float(self.rate)))
            # ax2.yaxis.set_major_formatter(mtick.FormatStrFormatter('%.1e'))
            ax2.grid(True)
            ax2.hold(False)
            plt.title("Recorded Chunk Sec: " +
                      str(len(self.data) / float(self.rate)))
            self.canvas.draw()

            #elif self.mlFlag is 1 and self.namePre:
        '''
        data = [random.random() for i in range(10)]
        # create an axis
        ax = self.figure.add_subplot(111)
        # discards the old graph
        ax.hold(True)
        # plot data
        ax.plot(data, '*-')
        # refresh canvas
        self.canvas.draw()
        '''

    # 리스트에 CustomWidget의 객체들을 삽입
    def create(self):
        for i in range(0, 3):
            wid = Ui_MainWindow.CustomWidget(
                "abcdefghijklmnopqrstu")  # 매개변수가 log 값이 되어야함

            wid2 = QtGui.QListWidgetItem()
            wid2.setSizeHint(QtCore.QSize(100, 60))
            self.list.addItem(wid2)
            self.list.setItemWidget(wid2, wid)
            self.list.setStyleSheet(
                "QListWidget::item { border-bottom: 1px solid black; }")

    # 리스트에 있는 CustomWidget의 객체들을 삭제
    def remove(self):
        self.list.takeItem(self.list.currentRow())

    def tongtong(self):
        print "When I look into your eyes"

    def start(self):
        if self.timer is None:
            self.recThread = threading.Thread(target=self.record)
            self.recThread.start()
            self.present = datetime.datetime.now()
            self.timer = QtCore.QTimer()
            self.timer.timeout.connect(self.tick)
            self.timer.start(10)
            self.chunksize.setDisabled(True)
            self.statusbar.showMessage("Analyzing Started")

    def stop(self):
        if self.timer is not None:
            self.statusbar.showMessage("Analyzing Stopped")
            self.timer.stop()
            self.timer = None
            self.addThread = None
            self.recThread = None
            self.inStream = None
            self.chunks = []
            self.chunksize.setEnabled(True)

    def save(self):
        if self.figure:
            now = datetime.datetime.now()
            self.savename = now.isoformat().replace("T", "-").replace(
                ":", "-") + "+" + self.displayTime.toString('mm-ss')
            if self.capFlag is 0:
                if self.displayTime:
                    self.figure.savefig("%s.png" % self.savename,
                                        bbox_inches='tight')
                    self.statusbar.showMessage(
                        self.savename + ".png Saved on Current Directory")
            elif self.capFlag is 1:
                if self.data is not None:
                    scipy.io.wavfile.write("%s.wav" % self.savename, self.rate,
                                           self.data)
                    self.statusbar.showMessage(
                        self.savename + ".wav Saved on Current Directory")
            elif self.capFlag is 2:
                if self.data is not None and self.displayTime:
                    self.figure.savefig("%s.png" % self.savename,
                                        bbox_inches='tight')
                    scipy.io.wavfile.write("%s.wav" % self.savename, self.rate,
                                           self.data)
                    self.statusbar.showMessage(
                        self.savename + ".png and " + self.savename +
                        ".wav Saved on Current Directory")

    def intchanged(self):
        self.buffer = 2**self.chunksize.value()
        self.statusbar.showMessage(
            "Current Buffer Size Changed: " + str(self.buffer * 2) +
            " Change will be affected on further analysis ")

    def green(self):
        self.linecolor = "green"
        self.statusbar.showMessage(
            "Fast Fourier Transform Mode Changed to Payloaded Drone")

    def red(self):
        self.linecolor = "red"
        self.statusbar.showMessage(
            "Fast Fourier Transform Mode Changed to Others")

    def hsvhandler(self, value):
        self.xlimit = self.horizontalSlider.value()
        self.statusbar.showMessage("X-limit Changed to: " + str(self.xlimit))

    def vsvhandler(self, value):
        self.ylimit = self.verticallSlider.value()
        self.statusbar.showMessage("Y-limit Changed to: " + str(self.ylimit))

    def scrmode(self):
        self.capFlag = 0
        self.statusbar.showMessage("Recording Mode Changed to Plot Only")

    def recmode(self):
        self.capFlag = 1
        self.statusbar.showMessage("Recording Mode Changed to Wave Only")

    def scrnrecmode(self):
        self.capFlag = 2
        self.statusbar.showMessage("Recording Mode Changed to Plot+Wave")

    def automode(self):
        self.mlFlag = 0
        self.statusbar.showMessage(
            "Machine Learning Mode Changed to Autopilot")

    def manualmode(self):
        self.mlFlag = 1
        self.statusbar.showMessage("Machine Learning Mode Changed to Manual")
        #name = QtGui.QFileDialog.getOpenself.savenames(None, u'녹음 파일 선택 - wav확장자를 가진 파일 하나를 열어주세요',QtGui.QDesktopServices.storageLocation(QtGui.QDesktopServices.MusicLocation),"Record (*.wav)");
        #name = QtGui.QFileDialog.getOpenself.savenames(None, u'녹음 파일 선택 - wav확장자를 가진 파일 하나를 열어주세요',"./","Record (*.wav)");

    '''
        if not name:
            return
        else:
            self.namePre=name[0]
            self.ratePre, X = scipy.io.wavfile.read(self.namePre)
            fnarray=self.namePre.split("\\")
            self.namePre=fnarray[len(fnarray)-1]
            self.spectrumPre = scipy.fftpack.fft(X)
            self.freqPre=scipy.fftpack.fftfreq(len(X), d=1.0 / self.ratePre)
            self.nsamPre=X.shape[0]
    '''

    def thmode(self):
        '''
        for file in os.listdir("./X"):
            if file.endswith(".wav"):
                fnarray = file.split("/")
                tt=fnarray[len(fnarray) - 1]
                self.ratePre, X = scipy.io.wavfile.read("./X/"+file)
                self.spectrumPre = scipy.fftpack.fft(X)
                self.freqPre = scipy.fftpack.fftfreq(len(X), d=1.0 / self.ratePre)
                ax2 = self.figure.add_subplot(111)
                ax2.plot(self.freqPre, abs(self.spectrumPre), color=self.linecolor)
                ax2.set_xlim(1000, self.xlimit)
                ax2.set_ylim(0, 10000000)
                ax2.set_xlabel("frequency [Hz]")
                # ax2.set_title("Recorded Chunk Sec: " + str(len(self.data) / float(self.rate)))
                # ax2.yaxis.set_major_formatter(mtick.FormatStrFormatter('%.1e'))
                ax2.set_title(tt)
                ax2.grid(True)
                #self.canvas.draw()
                print tt
                plt.savefig("%s.png" % tt, bbox_inches='tight')

            '''

        self.mlFlag = 2
        self.statusbar.showMessage(
            "Machine Learning Mode Deactivated. Using Preset Threshold")

    def chkfir(self):
        if self.fir.isChecked() == False:
            self.lbnd1.setEnabled(False)
            self.rbnd1.setEnabled(False)
            self.th1.setEnabled(False)
        else:
            self.lbnd1.setEnabled(True)
            self.rbnd1.setEnabled(True)
            self.th1.setEnabled(True)

    def chksec(self):
        if self.sec.isChecked() == False:
            self.lbnd2.setEnabled(False)
            self.rbnd2.setEnabled(False)
            self.th2.setEnabled(False)
        else:
            self.lbnd2.setEnabled(True)
            self.rbnd2.setEnabled(True)
            self.th2.setEnabled(True)

    def chkthi(self):
        if self.thi.isChecked() == False:
            self.lbnd3.setEnabled(False)
            self.rbnd3.setEnabled(False)
            self.th3.setEnabled(False)
        else:
            self.lbnd3.setEnabled(True)
            self.rbnd3.setEnabled(True)
            self.th3.setEnabled(True)

    def lbnd1f(self):
        self.leftBoundary_1.setEnabled(False)
        self.leftBoundary_2.setEnabled(True)
        self.leftBoundary_3.setEnabled(True)
        self.rightBoundary_1.setEnabled(True)
        self.rightBoundary_2.setEnabled(True)
        self.rightBoundary_3.setEnabled(True)
        self.threshold_1.setEnabled(True)
        self.threshold_2.setEnabled(True)
        self.threshold_3.setEnabled(True)
        self.lbnd1.setFocus(True)

    def lbnd2f(self):
        self.leftBoundary_1.setEnabled(True)
        self.leftBoundary_2.setEnabled(False)
        self.leftBoundary_3.setEnabled(True)
        self.rightBoundary_1.setEnabled(True)
        self.rightBoundary_2.setEnabled(True)
        self.rightBoundary_3.setEnabled(True)
        self.threshold_1.setEnabled(True)
        self.threshold_2.setEnabled(True)
        self.threshold_3.setEnabled(True)
        self.lbnd2.setFocus(True)

    def lbnd3f(self):
        self.leftBoundary_1.setEnabled(True)
        self.leftBoundary_2.setEnabled(True)
        self.leftBoundary_3.setEnabled(False)
        self.rightBoundary_1.setEnabled(True)
        self.rightBoundary_2.setEnabled(True)
        self.rightBoundary_3.setEnabled(True)
        self.threshold_1.setEnabled(True)
        self.threshold_2.setEnabled(True)
        self.threshold_3.setEnabled(True)
        self.lbnd3.setFocus(True)

    def rbnd1f(self):
        self.leftBoundary_1.setEnabled(True)
        self.leftBoundary_2.setEnabled(True)
        self.leftBoundary_3.setEnabled(True)
        self.rightBoundary_1.setEnabled(False)
        self.rightBoundary_2.setEnabled(True)
        self.rightBoundary_3.setEnabled(True)
        self.threshold_1.setEnabled(True)
        self.threshold_2.setEnabled(True)
        self.threshold_3.setEnabled(True)
        self.rbnd1.setFocus(True)

    def rbnd2f(self):
        self.leftBoundary_1.setEnabled(True)
        self.leftBoundary_2.setEnabled(True)
        self.leftBoundary_3.setEnabled(True)
        self.rightBoundary_1.setEnabled(True)
        self.rightBoundary_2.setEnabled(False)
        self.rightBoundary_3.setEnabled(True)
        self.threshold_1.setEnabled(True)
        self.threshold_2.setEnabled(True)
        self.threshold_3.setEnabled(True)
        self.rbnd2.setFocus(True)

    def rbnd3f(self):
        self.leftBoundary_1.setEnabled(True)
        self.leftBoundary_2.setEnabled(True)
        self.leftBoundary_3.setEnabled(True)
        self.rightBoundary_1.setEnabled(True)
        self.rightBoundary_2.setEnabled(True)
        self.rightBoundary_3.setEnabled(False)
        self.threshold_1.setEnabled(True)
        self.threshold_2.setEnabled(True)
        self.threshold_3.setEnabled(True)
        self.rbnd3.setFocus(True)

    def th1f(self):
        self.leftBoundary_1.setEnabled(True)
        self.leftBoundary_2.setEnabled(True)
        self.leftBoundary_3.setEnabled(True)
        self.rightBoundary_1.setEnabled(True)
        self.rightBoundary_2.setEnabled(True)
        self.rightBoundary_3.setEnabled(True)
        self.threshold_1.setEnabled(False)
        self.threshold_2.setEnabled(True)
        self.threshold_3.setEnabled(True)
        self.th1.setFocus(True)

    def th2f(self):
        self.leftBoundary_1.setEnabled(True)
        self.leftBoundary_2.setEnabled(True)
        self.leftBoundary_3.setEnabled(True)
        self.rightBoundary_1.setEnabled(True)
        self.rightBoundary_2.setEnabled(True)
        self.rightBoundary_3.setEnabled(True)
        self.threshold_1.setEnabled(True)
        self.threshold_2.setEnabled(False)
        self.threshold_3.setEnabled(True)
        self.th2.setFocus(True)

    def th3f(self):
        self.leftBoundary_1.setEnabled(True)
        self.leftBoundary_2.setEnabled(True)
        self.leftBoundary_3.setEnabled(True)
        self.rightBoundary_1.setEnabled(True)
        self.rightBoundary_2.setEnabled(True)
        self.rightBoundary_3.setEnabled(True)
        self.threshold_1.setEnabled(True)
        self.threshold_2.setEnabled(True)
        self.threshold_3.setEnabled(False)
        self.th3.setFocus(True)

    def calcdap(self):
        nzerocnt = 0
        avgdap = 0.00
        for per in self.dapper:
            if per > 0:
                nzerocnt += 1
                avgdap += per
        if nzerocnt > 0:
            self.avgper = avgdap / float(nzerocnt)
            self.Dapp.display(self.avgper)
        else:
            self.Dapp.display(0.00)

    def calcndap(self):
        nzerocnt = 0
        avgndap = 0.00
        for per in self.ndapper:
            if per > 0:
                nzerocnt += 1
                avgndap += per
        if nzerocnt > 0:
            self.navgper = avgndap / float(nzerocnt)
            self.nDapp.display(self.navgper)
        else:
            self.nDapp.display(0.00)

    def plotClick(self, value):
        if not str(value).__contains__("(None,None)"):
            arr = str(value).split("=")[2].lstrip("(").replace(") button",
                                                               "").split(",")
            xflt = float(arr[0])
            x = int(xflt)
            yflt = float(arr[1])
            y = int(yflt)
            if self.leftBoundary_1.isEnabled() is False:
                if x < self.rbnd1.value():
                    self.lbnd1.setValue(x)
                    self.leftBoundary_1.setEnabled(True)
            elif self.leftBoundary_2.isEnabled() is False:
                if x < self.rbnd2.value():
                    self.lbnd2.setValue(x)
                    self.leftBoundary_2.setEnabled(True)
            elif self.leftBoundary_3.isEnabled() is False:
                if x < self.rbnd3.value():
                    self.lbnd3.setValue(x)
                    self.leftBoundary_3.setEnabled(True)
            elif self.rightBoundary_1.isEnabled() is False:
                if x > self.lbnd1.value():
                    self.rbnd1.setValue(x)
                    self.rightBoundary_1.setEnabled(True)
            elif self.rightBoundary_2.isEnabled() is False:
                if x > self.lbnd2.value():
                    self.rbnd2.setValue(x)
                    self.rightBoundary_2.setEnabled(True)
            elif self.rightBoundary_3.isEnabled() is False:
                if x > self.lbnd3.value():
                    self.rbnd3.setValue(x)
                    self.rightBoundary_3.setEnabled(True)
            elif self.threshold_1.isEnabled() is False:
                self.th1.setValue(y)
                self.threshold_1.setEnabled(True)
            elif self.threshold_2.isEnabled() is False:
                self.th2.setValue(y)
                self.threshold_2.setEnabled(True)
            elif self.threshold_3.isEnabled() is False:
                self.th3.setValue(y)
                self.threshold_3.setEnabled(True)

                #if event.xdata is not None:
        #   print('button=%d, x=%d, y=%d, xdata=%f, ydata=%f' % (event.button, event.x, event.y, event.xdata, event.ydata))

    def listItemRightClicked(self, QPos):
        self.listMenu = QtGui.QMenu()
        menu_item = self.listMenu.addAction("Remove Item")
        #        self.connect(menu_item, QtCore.SIGNAL("triggered()"), self.menuItemClicked)
        parentPosition = self.list.mapToGlobal(QtCore.QPoint(0, 0))
        self.listMenu.move(parentPosition + QPos)
        self.listMenu.show()

    def menuItemClicked(self):
        currentItemName = str(
            self.listWidget_extractedmeters.currentItem().text())
        print(currentItemName)

    class CustomWidget(QtGui.QWidget):
        downloadRequest = QtCore.pyqtSignal(str)

        def __init__(self, log):
            QtGui.QWidget.__init__(self)
            self.label = QtGui.QLabel(self)
            self.label.setText(log)
            self.button1 = QtGui.QPushButton('1', self)
            self.button1.setFixedSize(20, 20)
            #self.button1.clicked.connect(Ui_MainWindow.tongtong)
            self.button2 = QtGui.QPushButton('2', self)
            self.button2.setFixedSize(20, 20)
            self.button2.clicked.connect(self.handleButton)
            self.button3 = QtGui.QPushButton('3', self)
            self.button3.setFixedSize(20, 20)
            self.button3.clicked.connect(self.handleButton)
            self.button4 = QtGui.QPushButton('4', self)
            self.button4.setFixedSize(20, 20)
            self.button4.clicked.connect(self.handleButton)
            self.button5 = QtGui.QPushButton('5', self)
            self.button5.setFixedSize(20, 20)
            self.button5.clicked.connect(self.handleButton)

            self.layout = QtGui.QVBoxLayout(self)
            self.layout2 = QtGui.QHBoxLayout(self)
            self.layout.addWidget(self.label)
            self.layout.addLayout(self.layout2, 1)

            self.layout2.addWidget(self.button1)
            self.layout2.addWidget(self.button2)
            self.layout2.addWidget(self.button3)
            self.layout2.addWidget(self.button4)
            self.layout2.addWidget(self.button5)

        def handleButton(self):
            url = self.edit.text().strip()
            if url and not self._thread.isRunning():
                self.viewer.clear()
                self._thread.start()
                # safely communicate with worker via signal
                self.downloadRequest.emit(url)