Esempio n. 1
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 );
Esempio n. 2
0
class GUI(object):

    def __init__(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        
        # Set size of window
        MainWindow.resize(800, 589)
        MainWindow.setFocusPolicy(QtCore.Qt.NoFocus)
        MainWindow.setWindowTitle("Text to Kill")
        
        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")

        self.gridLayout = QGridLayout(self.centralwidget)
        self.gridLayout.setMargin(0)
        self.gridLayout.setObjectName("gridLayout")
        self.stackedWidget = QStackedWidget(self.centralwidget)
        self.stackedWidget.setEnabled(True)
        self.stackedWidget.setObjectName("stackedWidget")
        
        font = QFont()
        font.setFamily("Times New Roman")
        
        # Main menu page
        self.menuPage = QWidget()
        self.menuPage.setObjectName("menuPage")
        self.titleLabel = QLabel(self.menuPage)
        self.titleLabel.setGeometry(QtCore.QRect(250, 60, 300, 50))
        font.setPointSize(45)
        self.titleLabel.setFont(font)
        self.titleLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.titleLabel.setObjectName("titleLabel")
        self.titleLabel.setText("Text to Kill")
        self.subtitleLabel = QLabel(self.menuPage)
        self.subtitleLabel.setGeometry(QtCore.QRect(100, 140, 600, 40))
        font.setPointSize(25)
        self.subtitleLabel.setFont(font)
        self.subtitleLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.subtitleLabel.setObjectName("subtitleLabel")
        self.subtitleLabel.setText("The Murder Mystery Automation System")
        self.createButton = QPushButton(self.menuPage)
        self.createButton.setGeometry(QtCore.QRect(310, 260, 180, 60))
        self.createButton.setObjectName("createButton")
        self.createButton.setText("Create Game")
        self.runButton = QPushButton(self.menuPage)
        self.runButton.setGeometry(QtCore.QRect(310, 350, 180, 60))
        self.runButton.setObjectName("runButton")
        self.runButton.setText("Run Game")
        self.stackedWidget.addWidget(self.menuPage)
        
        # Create page
        self.createPage = QWidget()
        self.createPage.setObjectName("createPage")
        self.createTabWidget = QTabWidget(self.createPage)
        self.createTabWidget.setGeometry(QtCore.QRect(0, 0, 800, 600))

        self.createTabWidget.setFocusPolicy(QtCore.Qt.NoFocus)
        self.createTabWidget.setObjectName("createTabWidget")
        
        # Create game tab
        self.createTab = QWidget()
        self.createTab.setObjectName("createTab")
        self.createDoneButton = QPushButton(self.createTab)
        self.createDoneButton.setGeometry(QtCore.QRect(580, 470, 180, 60))
        self.createDoneButton.setObjectName("createDoneButton")
        self.createDoneButton.setText("Done")
        self.gameNameEdit = QLineEdit(self.createTab)
        self.gameNameEdit.setGeometry(QtCore.QRect(140, 20, 160, 30))
        self.gameNameEdit.setObjectName("gameNameEdit")
        self.gameNameLabel = QLabel(self.createTab)
        self.gameNameLabel.setGeometry(QtCore.QRect(20, 25, 110, 20))

        font.setPointSize(15)
        self.gameNameLabel.setFont(font)
        self.gameNameLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.gameNameLabel.setObjectName("gameNameLabel")
        self.gameNameLabel.setText("Game name")
        self.line = QFrame(self.createTab)
        self.line.setGeometry(QtCore.QRect(20, 150, 311, 20))
        self.line.setFrameShape(QFrame.HLine)
        self.line.setFrameShadow(QFrame.Sunken)
        self.line.setObjectName("line")
        self.addCharLabel = QLabel(self.createTab)
        self.addCharLabel.setGeometry(QtCore.QRect(20, 180, 160, 20))
        
        font.setPointSize(20)
        self.addCharLabel.setFont(font)
        self.addCharLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.addCharLabel.setObjectName("addCharLabel")
        self.addCharLabel.setText("Add Character")
        self.charNameLabel = QLabel(self.createTab)
        self.charNameLabel.setGeometry(QtCore.QRect(20, 230, 66, 20))

        font.setPointSize(15)
        self.charNameLabel.setFont(font)
        self.charNameLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.charNameLabel.setObjectName("charNameLabel")
        self.charNameLabel.setText("Name")
        self.charNameEdit = QLineEdit(self.createTab)
        self.charNameEdit.setGeometry(QtCore.QRect(140, 220, 160, 30))
        self.charNameEdit.setObjectName("charNameEdit")
        self.charAbilScroll = QListWidget(self.createTab)
        self.charAbilScroll.setGeometry(QtCore.QRect(140, 260, 161, 51))
        self.charAbilScroll.setObjectName("charAbilScroll")
        self.characterTable = QTableWidget(self.createTab)
        self.characterTable.setGeometry(QtCore.QRect(405, 20, 381, 401))
        self.characterTable.setFocusPolicy(QtCore.Qt.NoFocus)
        self.characterTable.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
        self.characterTable.setRowCount(1)
        self.characterTable.setColumnCount(2)
        self.characterTable.setObjectName("characterTable")
        self.characterTable.horizontalHeader().setVisible(False)
        self.characterTable.horizontalHeader().setCascadingSectionResizes(False)
        self.characterTable.horizontalHeader().setMinimumSectionSize(50)
        self.characterTable.horizontalHeader().setStretchLastSection(True)
        self.characterTable.verticalHeader().setVisible(False)
        self.characterTable.verticalHeader().setDefaultSectionSize(30)
        self.scrollArea = QListWidget(self.createTab)
        self.scrollArea.setGeometry(QtCore.QRect(140, 60, 161, 71))
        self.scrollArea.setObjectName("scrollArea")
        self.scrollArea.setSelectionMode(3)
        self.createSaveButton = QPushButton(self.createTab)
        self.createSaveButton.setGeometry(QtCore.QRect(380, 470, 180, 60))
        self.createSaveButton.setObjectName("createSaveButton")
        self.createSaveButton.setText("Save")
        self.charAbilitiesLabel = QLabel(self.createTab)
        self.charAbilitiesLabel.setGeometry(QtCore.QRect(30, 280, 71, 20))

        font.setPointSize(15)
        self.charAbilitiesLabel.setFont(font)
        self.charAbilitiesLabel.setObjectName("charAbilitiesLabel")
        self.charAbilitiesLabel.setText("Abilities")
        self.abilitiesDropdown = QComboBox(self.createTab)
        self.abilitiesDropdown.setGeometry(QtCore.QRect(140, 330, 151, 25))
        self.abilitiesDropdown.setObjectName("abilitiesDropdown")
        
        self.addCharButton = QPushButton(self.createTab)
        self.addCharButton.setGeometry(QtCore.QRect(30, 370, 98, 27))
        self.addCharButton.setObjectName("addCharButton")
        self.addCharButton.setText("Add")
        self.gameAbilitiesLabel = QLabel(self.createTab)
        self.gameAbilitiesLabel.setGeometry(QtCore.QRect(30, 80, 71, 20))
        
        self.setGameAbilButton = QPushButton(self.createTab)
        self.setGameAbilButton.setGeometry(QtCore.QRect(30, 110, 71, 27))
        self.setGameAbilButton.setObjectName("setGameAbilButton")
        self.setGameAbilButton.setText("Set")
        
        self.saveCharButton = QPushButton(self.createTab)
        self.saveCharButton.setGeometry(QtCore.QRect(70, 430, 180, 60))
        self.saveCharButton.setObjectName("saveCharButton")
        self.saveCharButton.setText("Save Character")

        font.setPointSize(15)
        self.gameAbilitiesLabel.setFont(font)
        self.gameAbilitiesLabel.setObjectName("gameAbilitiesLabel")
        self.gameAbilitiesLabel.setText("Abilities")
        self.createTabWidget.addTab(self.createTab, "")
        
        # Setup tab widget
        self.setupTab = QWidget()
        self.setupTab.setObjectName("setupTab")
        self.setupDoneButton = QPushButton(self.setupTab)
        self.setupDoneButton.setGeometry(QtCore.QRect(580, 470, 180, 60))
        self.setupDoneButton.setObjectName("setupDoneButton")
        self.setupDoneButton.setText("Done")
        self.setupTable = QTableWidget(self.setupTab)
        self.setupTable.setGeometry(QtCore.QRect(20, 20, 750, 400))
        self.setupTable.setFocusPolicy(QtCore.Qt.TabFocus)
        self.setupTable.setRowCount(1)
        self.setupTable.setColumnCount(3)
        self.setupTable.setObjectName("setupTable")
        self.setupTable.horizontalHeader().setVisible(False)
        self.setupTable.horizontalHeader().setCascadingSectionResizes(False)
        self.setupTable.horizontalHeader().setDefaultSectionSize(187)
        self.setupTable.horizontalHeader().setHighlightSections(False)
        self.setupTable.horizontalHeader().setStretchLastSection(True)
        self.setupTable.verticalHeader().setVisible(False)
        self.setupTable.verticalHeader().setHighlightSections(False)
        self.setupSaveButton = QPushButton(self.setupTab)
        self.setupSaveButton.setGeometry(QtCore.QRect(380, 470, 180, 60))
        self.setupSaveButton.setObjectName("setupSaveButton")
        self.setupSaveButton.setText("Save")
        self.createTabWidget.addTab(self.setupTab, "")
        self.createTabWidget.setTabText(self.createTabWidget.indexOf(self.createTab), "Create New Game")
        self.createTabWidget.setTabText(self.createTabWidget.indexOf(self.setupTab), "Set Up Game")
        self.stackedWidget.addWidget(self.createPage)
        
        # Game page
        self.gamePage = QWidget()
        self.gamePage.setObjectName("gamePage")
        self.gameTabWidget = QTabWidget(self.gamePage)
        self.gameTabWidget.setGeometry(QtCore.QRect(0, 0, 800, 600))
        self.gameTabWidget.setFocusPolicy(QtCore.Qt.NoFocus)
        self.gameTabWidget.setObjectName("gameTabWidget")
        self.statusTab = QWidget()
        self.statusTab.setObjectName("statusTab")
        self.startGameButton = QPushButton(self.statusTab)
        self.startGameButton.setGeometry(QtCore.QRect(60, 180, 180, 60))
        self.startGameButton.setObjectName("startGameButton")
        self.startGameButton.setText("Start Game")
        self.endGameButton = QPushButton(self.statusTab)
        self.endGameButton.setGeometry(QtCore.QRect(60, 260, 180, 60))
        self.endGameButton.setObjectName("endGameButton")
        self.endGameButton.setText("End Game")
        self.loadGameLabel = QLabel(self.statusTab)
        self.loadGameLabel.setGeometry(QtCore.QRect(20, 65, 101, 21))

        font.setPointSize(15)
        self.loadGameLabel.setFont(font)
        self.loadGameLabel.setObjectName("loadGameLabel")
        self.loadGameLabel.setText("Load Game")
        self.gameTabWidget.addTab(self.statusTab, "")
        self.logTab = QWidget()
        self.logTab.setObjectName("logTab")
        self.logList = QListWidget(self.logTab)
        self.logList.setGeometry(QtCore.QRect(30, 30, 730, 500))
        self.logList.setObjectName("logList")
        self.gameTabWidget.addTab(self.logTab, "")
        self.inputTab = QWidget()
        self.inputTab.setObjectName("inputTab")
        self.gameTabWidget.addTab(self.inputTab, "")
        self.gameTabWidget.setTabText(self.gameTabWidget.indexOf(self.statusTab), "Game Status")
        self.gameTabWidget.setTabText(self.gameTabWidget.indexOf(self.logTab), "Game Log")
        self.gameTabWidget.setTabText(self.gameTabWidget.indexOf(self.inputTab), "Input")
        self.stackedWidget.addWidget(self.gamePage)
        self.gridLayout.addWidget(self.stackedWidget, 0, 0, 1, 1)
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        self.stackedWidget.setCurrentIndex(0)
        self.createTabWidget.setCurrentIndex(0)
        self.gameTabWidget.setCurrentIndex(0)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        pass
Esempio n. 3
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();
            """ 
        # ------------------------------------------------------------------

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

###################################################################################################
Esempio n. 4
0
class main_window(QMainWindow):

    def __init__(self):
        super(main_window, self).__init__()

        self.setWindowTitle('Minecraft Backup Manager')
        self.setGeometry(0, 0, 700, 520)
        self.setMinimumSize(700, 520)
        self.setMaximumSize(700, 520)
        center_widget(self)

        #Header
        self.header_label = QLabel(self)
        self.header_label.resize(700, 170)
        self.header_label.setPixmap(QPixmap(IMAGES['header']))

        #menu_about
        self.menu_about = QMenu(self)
        self.menu_about.addAction('About Minecraft Backup Manager',
                            lambda: self.open_about_minebackup())
        self.menu_about.addAction('About Qt', lambda: msg_about_qt(self))

        #btn_config
        self.btn_config = QPushButton(QIcon(IMAGES['config_icon']), '', self)
        self.btn_config.setGeometry(QRect(7, 7, 32, 32))
        self.btn_config.setToolTip('Configuration')

        #btn_about
        self.btn_about = QPushButton('About', self)
        self.btn_about.setGeometry(QRect(45, 7, 80, 32))
        self.btn_about.setMenu(self.menu_about)

        # list_backup
        self.list_backup = QListWidget(self)
        self.list_backup.setGeometry(QRect(20, 190, 450, 310))

        # btn_new_backup
        self.btn_new_backup = QPushButton('New backup', self)
        self.btn_new_backup.setGeometry(QRect(485, 190, 200, 30))

        # btn_restore_backup
        self.btn_restore_backup = QPushButton('Restore backup', self)
        self.btn_restore_backup.setGeometry(QRect(485, 260, 200, 30))
        self.btn_restore_backup.setEnabled(False)

        # btn_remove_backup
        self.btn_remove_backup = QPushButton('Remove Backup', self)
        self.btn_remove_backup.setGeometry(QRect(485, 300, 200, 30))
        self.btn_remove_backup.setEnabled(False)

        # CONNECT SIGNALS
        self.connect(self.btn_config, SIGNAL('clicked()'), self.open_config)
        self.connect(self.btn_new_backup, SIGNAL('clicked()'),
                     self.open_new_backup)
        self.connect(self.btn_remove_backup, SIGNAL('clicked()'),
                     self.remove_backup)
        self.connect(self.btn_restore_backup, SIGNAL('clicked()'),
                     self.restore_backup)
        self.connect(self.list_backup,
                     SIGNAL('itemClicked(QListWidgetItem *)'),
                     self.enabled_buttons)

        self.load_backup_list()

    def load_backup_list(self):
        self.list_backup.clear()
        self.backup_list = load_backup_list()

        if self.backup_list is not False:
            for backup in self.backup_list.values():
                if path.exists(backup['path']):
                    self.list_item = QListWidgetItem(backup['name'])
                    self.list_item.setToolTip('<b>Directory:</b> %s' %
                                    backup['path'])

                    self.list_backup.addItem(self.list_item)
                else:
                    msg_backup_folder_not_exists(self, backup['name'])
                    remove_backup_name(backup['name'])

    def remove_backup(self):
        self.remove_question = msg_remove_backup(self)

        if self.remove_question is not False:
            self.backup_name = self.list_backup.currentItem().text()

            remove_backup(unicode(self.backup_name))
            self.load_backup_list()

    def restore_backup(self):
        self.restore_question = msg_restore_backup(self)

        if self.restore_question is not False:
            self.backup_name = self.list_backup.currentItem().text()

            restore_backup(unicode(self.backup_name))
            msg_restore_finishied(self, self.backup_name)

    def enabled_buttons(self):
        self.btn_remove_backup.setEnabled(True)
        self.btn_restore_backup.setEnabled(True)

    def open_config(self):
        self.configuration_window = config_window.config_window(self)
        self.configuration_window.show()

    def open_about_minebackup(self):
        self.about_minebackup = about_minebackup.about_minebackup(self)
        self.about_minebackup.show()

    def open_new_backup(self):
        self.new_backup_window = new_backup_window.new_backup_window(self)
        self.new_backup_window.show()

        # CONNECT SIGNALS
        self.connect(self.new_backup_window, SIGNAL('close()'),
                     self.load_backup_list)
Esempio n. 5
0
class urlgroup(QGroupBox):
    def __init__(self, parent=None):
        super(urlgroup, self).__init__(parent)
        self.setGeometry(10,30,500,80)
        self.setObjectName('urlgroup')
        self.urlbar = QLineEdit()
        self.urlbar.setObjectName('urlbar')
        self.urlbar.setText('Collez votre URL içi')
        self.urlbar.setStyleSheet('font-weight:lighter;color:gray;')
        self.urlbar.show()
        self.parsebutton = QPushButton('Go !!')
        self.parsebutton.setObjectName('parsebutton')
        self.parsebutton.show()
        layout = QBoxLayout(QBoxLayout.LeftToRight, self)
        layout.addWidget(self.urlbar)
        layout.addWidget(self.parsebutton)
        self.show()
        self.group2 = QGroupBox(parent)
        self.group2.setObjectName('core')
        self.group2.setGeometry(10,120,500,280)
        self.group2.show()
        self.group3 = QGroupBox(self.group2)
        self.group3.setObjectName('albuminfos')
        self.group3.setGeometry(10,15,200,245)
        self.group3.show()
        self.itemlist = QListWidget(self.group2)
        self.itemlist.setGeometry(250,15,230,245)
        self.itemlist.show()
        self.dlgroup = QGroupBox(parent)
        self.dlgroup.setObjectName('dlgroup')
        self.dlgroup.setGeometry(10,420,500,100)
        self.dlgroup.show()
        self.dlgroup.dlbutton = QPushButton('Download', self.dlgroup)
        self.dlgroup.dlbutton.setObjectName('dlbutton')
        self.dlgroup.dlbutton.move(10,20)
        self.dlgroup.dlbutton.show()
        self.dlgroup.progressbar = QProgressBar(self.dlgroup)
        self.dlgroup.progressbar.setObjectName('progressbar')
        self.dlgroup.progressbar.setGeometry(100,21,380,21)
        self.dlgroup.progressbar.show()
        self.dlgroup.dlinfos = QLabel(self.dlgroup)
        self.dlgroup.dlinfos.setGeometry(100,70,200,21)
        self.dlgroup.dlinfos.show()
        self.dlgroup.dledfile = QLabel(self.dlgroup)
        self.dlgroup.dledfile.setGeometry(300,70,200,21)
        self.dlgroup.dledfile.show()
        self.dlgroup.dlto = QLineEdit('C:\\', self.dlgroup)
        self.dlgroup.dlto.setGeometry(100,50,350,21)
        self.dlgroup.dlto.show()
        self.dlgroup.dlto.changebt = QToolButton(self.dlgroup)
        self.dlgroup.dlto.changebt.setObjectName('dltobt')
        self.dlgroup.dlto.changebt.setGeometry(10,50,75,21)
        self.dlgroup.dlto.changebt.setText('To')
        self.dlgroup.dlto.changebt.show()
        self.dlgroup.dlto.openf = QPushButton('Open', self.dlgroup)
        self.dlgroup.dlto.openf.setGeometry(455,50,35,21)
        self.dlgroup.dlto.openf.setObjectName('openfolder')
        self.dlgroup.dlto.openf.show()  
        self.album = QLabel(self.group3)
        self.artist = QLabel(self.group3)
        self.year = QLabel(self.group3)
        self.tracks = QLabel(self.group3)
        self.coverart = QLabel(self.group3)
        self.urlbar.setFocus(True)
        self.connect(self.parsebutton, SIGNAL('clicked()'), self.parseclicked )
        self.connect(self.dlgroup.dlbutton, SIGNAL('clicked()'), self.launchdl)
        self.connect(self.dlgroup.dlto.changebt, SIGNAL('clicked()'), self.changedir)
        self.connect(self.dlgroup.dlto.openf, SIGNAL('clicked()'), self.openfolder)
        
    def parseclicked(self):
        self.itemlist.clear()
        url = str(self.urlbar.text())
        self.infos = getsonglist(url)
        if (self.infos == 'connexion impossible') or (self.infos == 'unsupported'):
            self.error = QMessageBox()
            if self.infos == 'connexion impossible':
                self.error.setText('Connexion Impossible !')
            elif self.infos == 'unsupported':
                self.error.setText('Site Unsupported !!')
            self.error.setWindowTitle('Erreur!')
            self.error.setIcon(QMessageBox.Warning)
            self.icon = QIcon('images/mainwindowicon.png')
            self.error.setWindowIcon(self.icon)
            self.error.exec_()
        else:
            self.artist.setText('Artiste : ' + self.infos['artist'])
            self.artist.move(40,175)
            self.artist.show()
            self.album.setText('Album : ' + self.infos['albumname'])
            self.album.move(40,190)
            self.album.show()
            try:
                self.year.setText('Annee : ' + self.infos['year'])
                
            except KeyError:
                self.year.setText('Annee : ' + 'N/A')
            self.year.move(40,205)
            self.year.show()
            self.tracks.setText('Tracks : ' + str(self.infos['tracks']))
            self.tracks.move(40,220)
            self.tracks.show()
            coverartpix = QPixmap(self.infos['coverart'])
            coverartpix = coverartpix.scaled(178,135,)
            self.coverart.setPixmap(coverartpix) 
            self.coverart.move(10,10)
            self.coverart.show()
            self.list2 = []
            for item in self.infos['titles']:
                item = tracklistitems(item)
                self.list2.append(item)
            for item in self.list2:
                self.itemlist.addItem(item)
                
            
            
            

    def launchdl(self):
        if self.dlgroup.dlbutton.text() == 'Download':
            try:
                self.itemlist.item(self.currentitem).setText(self.text)
            except:
                pass
            self.dlgroup.dlbutton.setText('Stop')
            rmtree('tmpimg', True)
            i= 0
            dllist = []
            for item in self.list2:
                if item.eligible() =='Checked':
                    dllist.append(i)
                i= i+1
            self.stritemlist = []
            for i in range(0,self.infos['tracks']):
                #print i
                #print self.itemlist.item(i).text()
                #TODO: hamida album breaks, recheck regexes
                self.stritemlist.append(str(self.itemlist.item(i).text()))
            dlto =  self.dlgroup.dlto.text()
            self.thread = dlThread(dllist, self.infos, dlto, self.stritemlist) 
            self.connect(self.thread, SIGNAL('progress(PyQt_PyObject)'), self.updateProgress)
            self.connect(self.thread, SIGNAL('dledfile(PyQt_PyObject)'), self.updateDlednow)
            self.thread.start()
        else:
            self.dlgroup.dlbutton.setText('Download')
            self.thread.terminate()
      
    def updateProgress(self, progress):
        self.dlgroup.progressbar.setValue(progress['bar'])
        self.dlgroup.dlinfos.setText(progress['info'])
        self.text = self.stritemlist[progress['item']]
        self.currentitem = progress['item']
        self.percent = str(progress['bar']) + ' % - '
        self.percent = QString(self.percent)
        self.dlingicon = QIcon('images/dling.png')
        self.doneicon = QIcon('images/done.png')
        self.itemlist.item(progress['item']).setIcon(self.dlingicon)
        self.itemlist.item(progress['item']).setText(self.percent + self.text)
        if progress['bar'] >= 98:
            self.itemlist.item(progress['item']).setIcon(self.doneicon)
            self.itemlist.item(progress['item']).setText(self.text)
            self.itemlist.item(progress['item']).setCheckState(Qt.Unchecked)
            self.itemlist.item(progress['item']).setFlags(Qt.ItemIsEnabled | Qt.ItemIsEditable | Qt.ItemIsSelectable)
            
    def updateDlednow(self, dledfile):
        self.dlgroup.dledfile.setText(dledfile)

    
    def changedir(self):
        self.dir = QFileDialog.getExistingDirectory()
        self.dlgroup.dlto.setText(self.dir + '/')
    def openfolder(self):
        startfile(self.dlgroup.dlto.text())
        
    def stopdl(self):
        pass
Esempio n. 6
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)
Esempio n. 7
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))