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 );
class NumericParameterWidget(GenericParameterWidget): """Widget class for Numeric parameter.""" def __init__(self, parameter, parent=None): """Constructor .. versionadded:: 2.2 :param parameter: A NumericParameter object. :type parameter: NumericParameter """ super(NumericParameterWidget, self).__init__(parameter, parent) self._input = QWidget() self._unit_widget = QLabel() self.set_unit() # Size policy self._spin_box_size_policy = QSizePolicy( QSizePolicy.Fixed, QSizePolicy.Fixed) label_policy = QSizePolicy( QSizePolicy.Minimum, QSizePolicy.Fixed) self._unit_widget.setSizePolicy(label_policy) # Add unit description to description description = self.help_label.text() if self._parameter.allowed_units: description += '<br><br>Available units:' description += '<ul>' for allowed_unit in self._parameter.allowed_units: description += '<li>' description += '<b>' + allowed_unit.name + '</b>: ' description += allowed_unit.description or '' description += '</li>' description += '</ul>' self.help_label.setText(description) def get_parameter(self): """Obtain numeric parameter object from the current widget state. :returns: A NumericParameter from the current state of widget """ self._parameter.value = self._input.value() if len(self._parameter.allowed_units) > 1: current_index = self._unit_widget.currentIndex() unit = self._unit_widget.itemData(current_index, Qt.UserRole) if hasattr(unit, 'toPyObject'): unit = unit.toPyObject() self._parameter.unit = unit return self._parameter def set_unit(self): """Set up label or combo box for unit.""" if len(self._parameter.allowed_units) == 1: self._unit_widget = QLabel(self._parameter.unit.name) self._unit_widget.setToolTip(self._parameter.unit.help_text) elif len(self._parameter.allowed_units) > 1: self._unit_widget = QComboBox() index = -1 current_index = -1 for allowed_unit in self._parameter.allowed_units: name = allowed_unit.name tooltip = allowed_unit.help_text index += 1 if allowed_unit.guid == self._parameter.unit.guid: current_index = index self._unit_widget.addItem(name) self._unit_widget.setItemData(index, tooltip, Qt.ToolTipRole) self._unit_widget.setItemData(index, allowed_unit, Qt.UserRole) self._unit_widget.setCurrentIndex(current_index) self._unit_widget.setToolTip('Select your preferred unit') self._unit_widget.currentIndex() def set_value(self, value): """Set the value of the input :param value: The new value :type value: int, float """ self._input.setValue(value)
class ResolutionSettingWidget(QWidget): def __init__(self, app, parent = None): super(ResolutionSettingWidget,self).__init__(parent) self.setStyleSheet("font-size : 16px;") self.app = app CDLL("libjson-c.so", mode=RTLD_GLOBAL) self.jytcapi = cdll.LoadLibrary('../lib/libjytcapi.so') self.jytcapi.jyinittcapi() self.resolutionLabel = QLabel(self.tr("Resolution setting")) self.resolutionCombox = QComboBox() self.resolutionCombox.setFixedSize(300, 30) self.saveBtn = QPushButton(self.tr("Save")) self.saveBtn.setStyleSheet("background: rgb(7,87,198); color: white; width: 90px; height: 30px;font-size : 16px;") gridLayout = QGridLayout() gridLayout.setSpacing(15) gridLayout.setMargin(10) gridLayout.addWidget(self.resolutionLabel, 0, 0, 1, 1) gridLayout.addWidget(self.resolutionCombox, 0, 1, 1, 1) topLayout = QHBoxLayout() topLayout.addStretch() topLayout.addSpacing(50) topLayout.addLayout(gridLayout) topLayout.addStretch(1) bottomHLayout = QHBoxLayout() bottomHLayout.addStretch() bottomHLayout.addWidget(self.saveBtn) bottomHLayout.addStretch() vLayout = QVBoxLayout() vLayout.addStretch() vLayout.addSpacing(50) vLayout.addLayout(topLayout) vLayout.addStretch(2) vLayout.addSpacing(10) vLayout.addLayout(bottomHLayout) self.setLayout(vLayout) self.updateResolutionCombox() self.timer = QTimer() self.timer.setSingleShot(True) self.connect(self.timer,SIGNAL("timeout()"),self.resetScreenResolution); self.connect(self.saveBtn, SIGNAL("clicked()"),self.slotSave) def updateWindow(self): self.resolutionLabel.setText(self.tr(self.tr("Resolution setting"))) self.saveBtn.setText(self.tr("Save")) def getCmdExecValue(self, cmd): statusOutput = commands.getstatusoutput(cmd) monitorList = statusOutput[1].split("\n") return monitorList def getCmdExecValueT(self, cmd): """得到命令执行的结果""" statusOutput = commands.getstatusoutput(cmd) monitorList = statusOutput[1].split("\n") return monitorList def showCurrentScreenResolution(self, curResolutionValue): """显示当前屏幕的分辨率""" count = self.resolutionCombox.count() for i in range(count): if self.resolutionCombox.itemText(i) == curResolutionValue: self.resolutionCombox.setCurrentIndex(i) return self.resolutionCombox.setCurrentIndex(-1) def getCurrentScreenResolution(self, screenName): currentSolution = "10" reSolution = "auto" solutionMap = {"0":"800x600","1":"1024x768","2":"1280x720","3":"1440x900","4":"1600x1020","5":"1920x1080","6":"1280x1024","7":"1366x768","8":"1600x900","10":"auto"} cmd = "../lib/ccr_jytcapi current_display" value = self.getCmdExecValueT(cmd) for i in range(len(value)): LogRecord.instance().logger.info("#".join(value)) if len(value[i].split(":"))==2 and value[i].split(":")[0]=="res" and value[i].split(":")[1] !="auto": currentSolution = value[i].split(":")[1] break if solutionMap.has_key(currentSolution): reSolution = solutionMap[currentSolution] return reSolution def updateResolutionCombox(self): """更新分辨率下拉框的内容""" #得到屏幕支持的分辨率 self.resolutionCombox.clear() resolutionmMap = self.getScreenResolution() if resolutionmMap: screenName = resolutionmMap.keys()[0] for resolution in resolutionmMap[screenName]: if resolution == "800x600": pass else: self.resolutionCombox.addItem(resolution) self.resolutionCombox.setItemData(0, screenName, Qt.UserRole + 1); #获取当前屏幕的分辨率 self.curResolutionValue = self.getCurrentScreenResolution(screenName) #显示当前屏幕的分辨率 self.showCurrentScreenResolution(self.curResolutionValue) def getScreenResolution(self): """得到屏幕支持的分辨率""" #获得显示器名称,连接状态及行号 Monitors = self.getCmdExecValueT("../lib/ccr_jytcapi display"); #根据组合列表把显示器名称和支持的分辨率放入到一个字典中 resolutionMap = {} resolutionList = [] count = len(Monitors) for i in range(count): if len(Monitors[i].split(":"))<2: continue valueName = Monitors[i].split(":")[0] valueValue = Monitors[i].split(":")[1] if valueName == "value": resolutionList.append(valueValue) resolutionMap["monitorName"] = resolutionList return resolutionMap def slotSave(self): language = StoreInfoParser.instance().getLanguage() m_pTranslator = QTranslator() exePath = "./" if language == "chinese": QmName = "zh_CN.qm" else: QmName = "en_US.qm" if(m_pTranslator.load(QmName, exePath)): QCoreApplication.instance().installTranslator(m_pTranslator) """改变当前的分辨率""" screenName = self.resolutionCombox.itemData(0, Qt.UserRole + 1).toString() if not screenName.isEmpty() and not screenName.isNull(): self.curResolutionValue = self.getCurrentScreenResolution(str(screenName)) if self.curResolutionValue: reScreen = self.resolutionCombox.currentText() if reScreen == "800x600": pass else: pass #弹出提示框,默认为取消 rb = MessageBox(self.tr("making sure set the resolution to current"), self).exec_() if rb == QDialog.Accepted: self.jytcapi.jysetdispconf(str(reScreen)) elif rb == QDialog.Rejected: pass def resetScreenResolution(self): """还原分辨率""" #关闭提示窗口 children = self.children() count = len(children) for i in range(count): if isinstance(children[i], MessageBox): children[i].close() #还原之前的分辨率 if self.jytcapi.jysetdispconf(self.curResolutionValue) != 0: # QMessageBox.information(None,u"错误",u'还原分辨率失败') InfoHintDialog(self.tr("reserve failed")).exec_() return #刷新分辨率下拉框 self.updateResolutionCombox() if QString(self.curResolutionValue).contains("x"): width = self.curResolutionValue.split("x")[0] height = self.curResolutionValue.split("x")[1] self.emit(SIGNAL("resizePosition"), width, height) #刷新屏幕 self.app.slotRefreshVMList() def writeConfigFile(self, curResolution): """记录修改后的配置文件""" StoreInfoParser.instance().setResolutionValue(curResolution)
class Chat(QFrame): # ======================================================================= def __init__(self, parent=None, _PARENT=None): # ------------------------------------------------------------------- QFrame.__init__(self, parent); # ------------------------------------------------------------------- self.PARENT = _PARENT; self.CONF = _PARENT.CONF; self.setGeometry(3, 5, 975, 548); self.setStyleSheet( "QFrame{ font: 12px 'monospace'; color: #000; background-color: transparent; background-image: url('./data/imgs/TAB_Chat.png'); }" ); # ------------------------------------------------------------------- self.CHAT_URL = "https://btc-e.com/"; self.CHAT_DATA = []; self.CHAT_LANG = self.CONF["USER"]["CHAT_LANG"]; self.CHAT_HEADERS = { "User-Agent" : "Mozilla/5.0 (Win-32; rv:24.0) Gecko/20140723 Firefox/24.0 Iceweasel/24.7.0", "Accept" : "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Accept-Language" : "en-US,en;q=0.5", "Referer" : "https://btc-e.com/", "Connection" : "keep-alive", "Cache-Control" : "max-age=0", "Cookie" : "" } self.CHAT_TIMER = QTimer(); #self.CHAT_BG_COLOR = "#555"; self.CHAT_BG_COLOR = "#0F0"; self.CHAT_ALLOW_UPD = False; # ------------------------------------------------------------------- self.CHAT_WIDGET = QTextEdit( self ); self.CHAT_WIDGET.setGeometry( 13, 116, 690, 388 ); self.CHAT_WIDGET.setStyleSheet( "QTextEdit{ background-color: transparent; color: #fff; background-image: url(''); }" ); self.CHAT_WIDGET.setReadOnly( True ); self.LANG_COMBO = QComboBox( self); self.LANG_COMBO.setGeometry( 86, 20, 108, 44 ); self.connect( self.LANG_COMBO, SIGNAL('currentIndexChanged(int)'), self.CHANGE_CHAT_LANG ); self.LANG_COMBO.setEditable(False); self.NEW_MSG = QLineEdit("", self); self.NEW_MSG.setGeometry( 20, 510, 500, 30 ); self.NEW_MSG.setStyleSheet(" QLineEdit{ border-style: none; background-color: #333; color: #fff; background-image: url(''); }"); self.NEW_MSG.setPlaceholderText(" Enter message:"); self.SEND = QPushButton(" Send", self); self.SEND.setGeometry( 593, 510, 90, 30 ); #self.SEND.setStyleSheet( "QPushButton{ background-color: transparent; border-style: none; }" ); #self.connect( self.SEND, SIGNAL('clicked()'), lambda: self.SEND_VALUES_TO_TRADE_TERMINAL("SEND_VALUES") ); # ------------------------------------------------------------------- self.ALLOW_UPDATE_CHECKBOX = QCheckBox("", self); self.ALLOW_UPDATE_CHECKBOX.setGeometry( 335, 83, 17, 17 ); self.ALLOW_UPDATE_CHECKBOX.setCheckState(Qt.Unchecked); self.connect(self.ALLOW_UPDATE_CHECKBOX, SIGNAL('stateChanged(int)'), self.CHANGE_VALUES ); self.UPDATE_NOW_BTN = QPushButton("Update Now!", self); self.UPDATE_NOW_BTN.setGeometry( 360, 74, 94, 24 ); self.connect( self.UPDATE_NOW_BTN, SIGNAL('clicked()'), self.UPDATE_NOW ); # ------------------------------------------------------------------- self.INIT(); # ------------------------------------------------------------------- # ======================================================================= def INIT(self): # ------------------------------------------------------------------- try: self.INIT_CHAT_COMBO(); self.UPDATE(); except Exception as _exception: print("-----------------------------------------------------"); print("[INIT]"+str(_exception)); # ------------------------------------------------------------------- # ======================================================================= def UPDATE_NOW(self): # ------------------------------------------------------------------- self.CHAT_ALLOW_UPD = True; self.UPDATE(); self.CHAT_ALLOW_UPD = False; # ------------------------------------------------------------------- # ======================================================================= def UPDATE(self): # ------------------------------------------------------------------- #print("UPDATE:") # ------------------------------------------------------------------- try: if self.CHAT_ALLOW_UPD: self.GET_DATA(); self.CHAT_WIDGET.clear(); for msg in self.CHAT_DATA: # --------------------------------------------------------------- """ print(msg["time"]); print(msg["nick"]); print(msg["msg"]); """ # --------------------------------------------------------------- item = '<p style="background-color: #555;">'; item += "[<span style='color: #000;'>"+msg["time"].split(" ")[1]+"</span>] : "; if msg["nick"] == "admin": item += "[<span style='color: #f00; font-weight: bold;'>"+msg["nick"]+"</span>]<br/><br/>"; else: item += "[<span style='color: #000; font-weight: bold;'>"+msg["nick"]+"</span>]<br/><br/>"; item += msg["msg"]+"<br/>"; item += "</p>"; self.CHAT_WIDGET.append(item); # --------------------------------------------------------------- self.CHAT_TIMER.singleShot( self.CONF["SYS"]["UPD_DELAY"], self.UPDATE ); except Exception as e: print("CHAT[0:0]"+str(e)) self.CHAT_TIMER.singleShot( self.CONF["SYS"]["UPD_DELAY"], self.UPDATE ); # ------------------------------------------------------------------- # ======================================================================= def CHANGE_VALUES(self): # ------------------------------------------------------------------- if self.ALLOW_UPDATE_CHECKBOX.isChecked(): self.CHAT_ALLOW_UPD = True; else: self.CHAT_ALLOW_UPD = False; # ------------------------------------------------------------------- # ======================================================================= def GET_DATA(self): # ------------------------------------------------------------------- try: self.CHAT_HEADERS["Cookie"] = "chatRefresh=1; locale="+self.CHAT_LANG+";" req = urllib2.Request(self.CHAT_URL, headers=self.CHAT_HEADERS); resp = urllib2.urlopen(req).read(); CHAT = BeautifulSoup( resp ).body.find('div', attrs={'id':'nChat'}); self.CHAT_DATA = []; for data in CHAT: self.CHAT_DATA.append( { "msg_id": data["id"], "nick":data.a.string, "time": data.a["title"], "msg": data.span.string } ); except Exception as e: print("CHAT[0:1]"+str(e)) # ------------------------------------------------------------------- # ======================================================================= def CHANGE_CHAT_LANG(self): # ------------------------------------------------------------------- self.CHAT_LANG = str(self.LANG_COMBO.currentText()).lower().strip(); #print(self.CHAT_LANG); # ------------------------------------------------------------------- # ======================================================================= def INIT_CHAT_COMBO(self): # ------------------------------------------------------------------- for LANG in self.CONF["USER"]["CHAT_LANGS"]: self.LANG_COMBO.addItem(LANG.upper()); for i in xrange(0, self.LANG_COMBO.__len__()): self.LANG_COMBO.setItemData( i, QColor("#333"),Qt.BackgroundRole ); self.LANG_COMBO.setItemData( i, QColor("#fff"),Qt.ForegroundRole );
def setup_left_panel(self): """Setup the UI for left panel. Generate all exposure, combobox, and edit button. """ hazard = self.parent.step_kw_subcategory.selected_subcategory() left_panel_heading = QLabel(tr('Classifications')) left_panel_heading.setFont(big_font) self.left_layout.addWidget(left_panel_heading) inner_left_layout = QGridLayout() row = 0 for exposure in exposure_all: special_case = False # Filter out unsupported exposure for the hazard if exposure in hazard['disabled_exposures']: # Remove from the storage if the exposure is disabled if self.layer_mode == layer_mode_continuous: if exposure['key'] in self.thresholds: self.thresholds.pop(exposure['key']) else: if exposure['key'] in self.value_maps: self.value_maps.pop(exposure['key']) continue # Trick for EQ raster for population #3853 if exposure == exposure_population and hazard == hazard_earthquake: if is_raster_layer(self.parent.layer): if self.layer_mode == layer_mode_continuous: self.use_default_thresholds = True special_case = True # Set classification for EQ Raster for Population self.thresholds[exposure_population['key']] = { earthquake_mmi_scale['key']: { 'classes': default_classification_thresholds( earthquake_mmi_scale), 'active': True } } # Add label # Hazard on Exposure Classifications label = tr( '{hazard_name} on {exposure_name} Classifications').format( hazard_name=hazard['name'], exposure_name=exposure['name'] ) exposure_label = QLabel(label) # Add combo box exposure_combo_box = QComboBox() hazard_classifications = hazard.get('classifications') exposure_combo_box.addItem(tr('No classifications')) exposure_combo_box.setItemData( 0, None, Qt.UserRole) current_index = 0 i = 0 # Iterate through all available hazard classifications for hazard_classification in hazard_classifications: # Skip if the classification is not for the exposure if 'exposures' in hazard_classification: if exposure not in hazard_classification['exposures']: continue exposure_combo_box.addItem(hazard_classification['name']) exposure_combo_box.setItemData( i + 1, hazard_classification, Qt.UserRole) if self.layer_mode == layer_mode_continuous: current_hazard_classifications = self.thresholds.get( exposure['key']) else: current_hazard_classifications = self.value_maps.get( exposure['key']) if current_hazard_classifications: current_hazard_classification = \ current_hazard_classifications.get( hazard_classification['key']) if current_hazard_classification: is_active = current_hazard_classification.get('active') if is_active: current_index = i + 1 i += 1 # Set current classification exposure_combo_box.setCurrentIndex(current_index) # Add edit button exposure_edit_button = QPushButton(tr('Edit')) # For special case. Raster EQ on Population. if special_case: mmi_index = exposure_combo_box.findText( earthquake_mmi_scale['name']) exposure_combo_box.setCurrentIndex(mmi_index) exposure_combo_box.setEnabled(False) exposure_edit_button.setEnabled(False) tool_tip_message = tr( 'InaSAFE use default classification for Raster Earthquake ' 'hazard on population.') exposure_label.setToolTip(tool_tip_message) exposure_combo_box.setToolTip(tool_tip_message) exposure_edit_button.setToolTip(tool_tip_message) else: if current_index == 0: # Disable if there is no classification chosen. exposure_edit_button.setEnabled(False) exposure_edit_button.clicked.connect( partial(self.edit_button_clicked, edit_button=exposure_edit_button, exposure_combo_box=exposure_combo_box, exposure=exposure)) exposure_combo_box.currentIndexChanged.connect( partial( self.classifications_combo_box_changed, exposure=exposure, exposure_combo_box=exposure_combo_box, edit_button=exposure_edit_button)) # Arrange in layout inner_left_layout.addWidget(exposure_label, row, 0) inner_left_layout.addWidget(exposure_combo_box, row, 1) inner_left_layout.addWidget(exposure_edit_button, row, 2) # Adding to step's attribute self.exposures.append(exposure) self.exposure_combo_boxes.append(exposure_combo_box) self.exposure_edit_buttons.append(exposure_edit_button) self.exposure_labels.append(label) if special_case: self.special_case_index = len(self.exposures) - 1 row += 1 self.left_layout.addLayout(inner_left_layout) # To push the inner_left_layout up self.left_layout.addStretch(1)
class SelectParameterWidget(GenericParameterWidget): """Widget class for List parameter.""" def __init__(self, parameter, parent=None): """Constructor :param parameter: A ListParameter object. :type parameter: ListParameter """ super(SelectParameterWidget, self).__init__(parameter, parent) self.input = QComboBox() index = -1 current_index = -1 for opt in self._parameter.options_list: index += 1 if opt == self._parameter.value: current_index = index self.input.addItem(opt) self.input.setItemData(index, opt, Qt.UserRole) self.input.setCurrentIndex(current_index) self.inner_input_layout.addWidget(self.input) def raise_invalid_type_exception(self): message = 'Expecting element type of %s' % ( self._parameter.element_type.__name__) err = ValueError(message) return err def get_parameter(self): """Obtain list parameter object from the current widget state. :returns: A ListParameter from the current state of widget """ current_index = self.input.currentIndex() selected_value = self.input.itemData(current_index, Qt.UserRole) if hasattr(selected_value, 'toPyObject'): selected_value = selected_value.toPyObject() try: self._parameter.value = selected_value except ValueError: err = self.raise_invalid_type_exception() raise err return self._parameter def set_choice(self, choice): """Set choice value by item's string. :param choice: The choice. :type choice: str :returns: True if success, else False. :rtype: bool """ # Find index of choice choice_index = self._parameter.options_list.index(choice) if choice_index < 0: return False else: self.input.setCurrentIndex(choice_index) return True
class NumericParameterWidget(GenericParameterWidget): """Widget class for Numeric parameter.""" def __init__(self, parameter, parent=None): """Constructor .. versionadded:: 2.2 :param parameter: A NumericParameter object. :type parameter: NumericParameter """ super(NumericParameterWidget, self).__init__(parameter, parent) self._input = QWidget() self._unit_widget = QLabel() self.set_unit() # Size policy self._spin_box_size_policy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) label_policy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) self._unit_widget.setSizePolicy(label_policy) # Add unit description to description description = self._description_label.text() description += '<br><br>Available units:' description += '<ul>' for allowed_unit in self._parameter.allowed_units: description += '<li>' description += '<b>' + allowed_unit.name + '</b>: ' description += allowed_unit.description description += '</li>' description += '</ul>' self._description_label.setText(description) def get_parameter(self): """Obtain boolean parameter object from the current widget state. :returns: A BooleanParameter from the current state of widget """ self._parameter.value = self._input.value() if len(self._parameter.allowed_units) > 1: current_index = self._unit_widget.currentIndex() unit = self._unit_widget.itemData(current_index, Qt.UserRole) if hasattr(unit, 'toPyObject'): unit = unit.toPyObject() self._parameter.unit = unit return self._parameter def set_unit(self): """Set up label or combo box for unit.""" if len(self._parameter.allowed_units) == 1: self._unit_widget = QLabel(self._parameter.unit.name) self._unit_widget.setToolTip(self._parameter.unit.help_text) elif len(self._parameter.allowed_units) > 1: self._unit_widget = QComboBox() index = -1 current_index = -1 for allowed_unit in self._parameter.allowed_units: name = allowed_unit.name tooltip = allowed_unit.help_text index += 1 if allowed_unit.guid == self._parameter.unit.guid: current_index = index self._unit_widget.addItem(name) self._unit_widget.setItemData(index, tooltip, Qt.ToolTipRole) self._unit_widget.setItemData(index, allowed_unit, Qt.UserRole) self._unit_widget.setCurrentIndex(current_index) self._unit_widget.setToolTip('Select your preferred unit') self._unit_widget.currentIndex() def set_value(self, value): """Set the value of the input :param value: The new value :type value: int, float """ self._input.setValue(value)
class EditPuWidget(PuWidget): """A widget for editing.""" set_text_statusbar = pyqtSignal(str, int, bool) def _setup_self(self): """Sets up self.""" self.categoryValue = 0 self.categoryValues = (0, 1, 2, None) self.categoryName = self.dW.puCategoryColumnName self.shortCategoryName = self.categoryName[:10] self.setCategoryValue = 0 self.setObjectName(u'editFrame') self.gridLayout = QGridLayout(self) self.gridLayout.setObjectName(u'gridLayout') self.gridLayout.setColumnStretch(1, 1) self._build_widgets() def _build_widgets(self): """Builds own widgets.""" self.set_text_statusbar.connect(self.dW.statusBar.set_text) self.lastPerimeterLayer = None self.editToolBar = QToolBar(self) self.editToolBar.setObjectName(u'editToolBar') self._set_icon_size() self.iface.initializationCompleted.connect(self._set_icon_size) self.gridLayout.addWidget(self.editToolBar, 0, 0, 1, 3) for action in self.iface.advancedDigitizeToolBar().actions(): if action.objectName() == 'mActionUndo': self.undoAction = action if action.objectName() == 'mActionRedo': self.redoAction = action self.editToolBar.addAction(self.undoAction) self.editToolBar.addAction(self.redoAction) self.editToolBar.addSeparator() self.toggleEditingAction = self.iface.actionToggleEditing() self.toggleEditingAction.setObjectName(u'toggleEditingAction') self.editToolBar.addAction(self.toggleEditingAction) self.saveActiveLayerEditsAction = \ self.iface.actionSaveActiveLayerEdits() self.saveActiveLayerEditsAction.setObjectName( u'saveActiveLayerEditsAction') self.editToolBar.addAction(self.saveActiveLayerEditsAction) self.cancelEditsAction = self.iface.actionCancelEdits() self.cancelEditsAction.setObjectName(u'cancelEditsAction') self.editToolBar.addAction(self.cancelEditsAction) self.addFeatureAction = self.iface.actionAddFeature() self.addFeatureAction.setObjectName(u'addFeatureAction') self.editToolBar.addAction(self.addFeatureAction) self.nodeToolAction = self.iface.actionNodeTool() self.nodeToolAction.setObjectName(u'nodeToolAction') self.editToolBar.addAction(self.nodeToolAction) self.deleteSelectedAction = self.iface.actionDeleteSelected() self.deleteSelectedAction.setObjectName(u'deleteSelectedAction') self.editToolBar.addAction(self.deleteSelectedAction) self.addPartAction = self.iface.actionAddPart() self.addPartAction.setObjectName(u'addPartAction') self.editToolBar.addAction(self.addPartAction) self.splitFeaturesAction = self.iface.actionSplitFeatures() self.splitFeaturesAction.setObjectName(u'splitFeaturesAction') self.editToolBar.addAction(self.splitFeaturesAction) self.perimeterLabel = QLabel(self) self.perimeterLabel.setObjectName(u'perimeterLabel') self.perimeterLabel.setText(u'Obvod:') self.gridLayout.addWidget(self.perimeterLabel, 1, 0, 1, 1) self.perimeterMapLayerComboBox = QgsMapLayerComboBox(self) self.perimeterMapLayerComboBox.setObjectName( u'perimeterMapLayerComboBox') self.perimeterMapLayerComboBox.setFilters( QgsMapLayerProxyModel.PolygonLayer) self.perimeterMapLayerComboBox.activated.connect( self.sync_perimeter_map_layer_combo_box) QgsMapLayerRegistry.instance().layersAdded.connect( self._rollback_perimeter_layer) QgsMapLayerRegistry.instance().layersRemoved.connect( self._reset_perimeter_layer) self.set_perimeter_layer(self.lastPerimeterLayer) self.gridLayout.addWidget(self.perimeterMapLayerComboBox, 1, 1, 1, 1) self.createPerimeterPushButton = QPushButton(self) self.createPerimeterPushButton.setObjectName( u'createPerimeterPushButton') self.createPerimeterPushButton.setText(u'Vytvořit') self.createPerimeterPushButton.setToolTip( u'Vytvořit vrstvu obvodu (.shp) z aktivní vrstvy a načíst') self.createPerimeterPushButton.clicked.connect(self._create_perimeter) self.gridLayout.addWidget(self.createPerimeterPushButton, 1, 2, 1, 1) self.gridLayout.setRowStretch(2, 1) self.categoryLabel = QLabel(self) self.categoryLabel.setObjectName(u'categoryLabel') self.categoryLabel.setText(u'Kategorie parcel:') self.gridLayout.addWidget(self.categoryLabel, 3, 0, 1, 1) self.categoryComboBox = QComboBox(self) self.categoryComboBox.setObjectName(u'categoryComboBox') self.categoryComboBox.addItem(u'mimo obvod (0)') self.categoryComboBox.addItem(u'v obvodu - neřešené (1)') self.categoryComboBox.addItem(u'v obvodu - řešené (2)') self.categoryComboBox.addItem(u'bez kategorie') self.categoryComboBox.currentIndexChanged.connect( self._set_categoryValue) self.gridLayout.addWidget(self.categoryComboBox, 3, 1, 1, 1) self.selectCategoryPushButton = QPushButton(self) self.selectCategoryPushButton.setObjectName( u'selectCategoryPushButton') self.selectCategoryPushButton.setText(u'Zobrazit') self.selectCategoryPushButton.setToolTip( u'Zobrazit (vybrat) parcely v kategorii') self.selectCategoryPushButton.clicked.connect(self._select_category) self.gridLayout.addWidget(self.selectCategoryPushButton, 3, 2, 1, 1) self.gridLayout.setRowStretch(4, 1) self.setCategoryLabel = QLabel(self) self.setCategoryLabel.setObjectName(u'setCategoryLabel') self.setCategoryLabel.setText(u'Zařadit:') self.gridLayout.addWidget(self.setCategoryLabel, 5, 0, 1, 1) self.setCategoryComboBox = QComboBox(self) self.setCategoryComboBox.setObjectName(u'setCategoryComboBox') self.setCategoryComboBox.addItem(u'vybrané parcely') self.setCategoryComboBox.setItemData( 0, u'Zařadit vybrané parcely do kategorie', Qt.ToolTipRole) self.setCategoryComboBox.addItem(u'obvodem') self.setCategoryComboBox.setItemData( 1, u'Zařadit všechny parcely do kategorií na základě obvodu', Qt.ToolTipRole) self.setCategoryComboBox.currentIndexChanged.connect( self._set_setCategoryValue) self.gridLayout.addWidget(self.setCategoryComboBox, 5, 1, 1, 1) self.setCategoryPushButton = QPushButton(self) self.setCategoryPushButton.setObjectName(u'setCategoryPushButton') self.setCategoryPushButton.setText(u'Zařadit') self.setCategoryPushButton.clicked.connect( self._start_setting_pu_category) self.gridLayout.addWidget(self.setCategoryPushButton, 5, 2, 1, 1) def _set_icon_size(self): """Sets editToolBar icon size according to the current QGIS settings.""" self.editToolBar.setIconSize(self.iface.mainWindow().iconSize()) def _set_categoryValue(self): """Sets categoryValue according to the current index. categoryValue - description: 0 - mimo obvod 1 - v obvodu - neřešené 2 - v obvodu - řešené """ currentIndex = self.categoryComboBox.currentIndex() if currentIndex == 3: self.categoryValue = None else: self.categoryValue = currentIndex def _set_setCategoryValue(self): """Sets setCategoryValue according to the current index. setCategoryValue - description: 0 - vybrané parcely 1 - obvodem """ self.setCategoryValue = self.setCategoryComboBox.currentIndex() def set_perimeter_layer(self, perimeterLayer, lastPerimeterLayer=True): """Sets the perimeter layer in the perimeterMapLayerComboBox. Args: perimeterLayer (QgsVectorLayer): A reference to the perimeter layer. lastPerimeterLayer (bool): True to set self.lastPerimeterLayer, False otherwise. """ if lastPerimeterLayer: self.lastPerimeterLayer = perimeterLayer self.perimeterMapLayerComboBox.setLayer(perimeterLayer) def sync_perimeter_map_layer_combo_box(self): """Synchronizes perimeter map layer combo boxes. Synchronizes with the perimeterMapLayerComboBox in the perimeterWidget. """ perimeterLayer = self.perimeterMapLayerComboBox.currentLayer() if perimeterLayer != self.lastPerimeterLayer: self.lastPerimeterLayer = perimeterLayer self.dW.stackedWidget.checkAnalysisPuWidget\ .perimeterPuCaWidget.set_perimeter_layer(perimeterLayer) def _reset_perimeter_layer(self): """Resets the perimeter layer.""" layers = self.iface.legendInterface().layers() if self.lastPerimeterLayer not in layers: self.set_perimeter_layer(None) def _rollback_perimeter_layer(self): """Rolls the perimeter layer back.""" if self.lastPerimeterLayer == None: self.set_perimeter_layer(self.lastPerimeterLayer, False) else: self.lastPerimeterLayer = \ self.perimeterMapLayerComboBox.currentLayer() def _create_perimeter(self): """Calls methods for creating and loading perimeter layer.""" try: succes, layer = self.dW.check_layer(self) if not succes: return if layer.featureCount() == 0: self.set_text_statusbar.emit( u'Aktivní vrstva neobsahuje žádný prvek.', 10, True) return editing = self.dW.check_editing() title = u'Uložit vrstvu obvodu jako...' filters = u'.shp (*.shp)' perimeterLayerFilePath = self.dW.open_file_dialog( title, filters, False) if perimeterLayerFilePath: self.set_text_statusbar.emit(u'Vytvářím vrstvu obvodu...', 0, False) fileInfo = QFileInfo(perimeterLayerFilePath) if not fileInfo.suffix() == u'shp': perimeterLayerFilePath = \ fileInfo.absoluteFilePath() + u'.shp' fileInfo = QFileInfo(perimeterLayerFilePath) selectedFeaturesIds = layer.selectedFeaturesIds() perimeterLayerName = fileInfo.completeBaseName() loadedLayer = self.dW.check_loaded_layers( perimeterLayerFilePath) perimeterLayer = self._create_perimeter_layer( layer, perimeterLayerFilePath, self.categoryName, perimeterLayerName, loadedLayer) QgsApplication.processEvents() loadedLayer = self.dW.check_loaded_layers( perimeterLayerFilePath) if loadedLayer: self.iface.actionDraw().trigger() self.set_perimeter_layer(loadedLayer, False) self.sync_perimeter_map_layer_combo_box() else: QgsMapLayerRegistry.instance().addMapLayer(perimeterLayer) layer.selectByIds(selectedFeaturesIds) self.iface.setActiveLayer(layer) if editing: self.toggleEditingAction.trigger() self.set_text_statusbar.emit(u'Obvod byl úspešně vytvořen.', 15, False) except: self.dW.display_error_messages(self, u'Error creating perimeter.', u'Chyba při vytváření obvodu.') def _create_perimeter_layer(self, layer, perimeterLayerFilePath, categoryName, perimeterLayerName, loadedLayer): """Creates a perimeter layer from the given layer. Args: layer (QgsVectorLayer): A reference to the layer. perimeterLayerFilePath (str): A full path to the perimeter layer. categoryName (str): A name of the category field the layer is about to be dissolved by. perimeterLayerName (str): A name of the perimeter layer. loadedLayer (bool): A reference to the loaded layer. This is relevant only for Windows platform. Returns: QgsVectorLayer: A reference to the perimeter layer. """ fileInfo = QFileInfo(perimeterLayerFilePath) tempPerimeterLayerName = fileInfo.completeBaseName() + u'.temp' layer.removeSelection() tempPerimeterLayerPath = processing.runalg('qgis:dissolve', layer, False, categoryName, None)['OUTPUT'] tempPerimeterLayer = QgsVectorLayer(tempPerimeterLayerPath, tempPerimeterLayerName, 'ogr') if loadedLayer: perimeterLayerName = loadedLayer.name() QgsMapLayerRegistry.instance().removeMapLayer(loadedLayer) QgsApplication.processEvents() processing.runalg('qgis:multiparttosingleparts', tempPerimeterLayer, perimeterLayerFilePath) perimeterLayer = QgsVectorLayer(perimeterLayerFilePath, perimeterLayerName, 'ogr') QgsMapLayerRegistry.instance().addMapLayer(perimeterLayer) expression = QgsExpression("\"{}\" is null".format( self.shortCategoryName)) self.dW.delete_features_by_expression(perimeterLayer, expression) return perimeterLayer def set_perimeter_layer_table_config(self, perimeterLayer): """Sets perimeter layer table config. Args: layer (QgsVectorLayer): A reference to the perimeter layer. """ fields = perimeterLayer.pendingFields() tableConfig = perimeterLayer.attributeTableConfig() tableConfig.update(fields) columns = tableConfig.columns() for column in columns: if not column.name == self.shortCategoryName: column.hidden = True tableConfig.setColumns(columns) perimeterLayer.setAttributeTableConfig(tableConfig) def _start_setting_pu_category(self): """Starts setting PU category in a separate thread..""" succes, layer = self.dW.check_layer(self) if not succes: return self.executeThread = ExecuteThread(layer) self.executeThread.started.connect(self._run_setting_pu_category) self.executeThread.start() def _run_setting_pu_category(self, layer): """Calls methods for setting PU category. Args: layer (QgsVectorLayer): A reference to the layer. """ try: perimeterLayer = self.perimeterMapLayerComboBox.currentLayer() editing = self.dW.check_editing() if self.setCategoryValue == 0: self._set_category_for_selected(layer, perimeterLayer) if self.setCategoryValue == 1: self._set_category_by_perimeter(layer, perimeterLayer) if editing: self.toggleEditingAction.trigger() except: QgsApplication.processEvents() self.dW.display_error_messages( self, u'Error setting parcel category.', u'Chyba při zařazování do kategorie parcel.') def _set_category_for_selected(self, layer, perimeterLayer): """Sets a categoryValue to categoryName column for selected features. Also updates the perimeter layer. Args: layer (QgsVectorLayer): A reference to the layer. perimeterLayer (QgsVectorLayer): A reference to the perimeter layer. """ featureCount = layer.selectedFeatureCount() if featureCount == 0: self.set_text_statusbar.emit( u'V aktivní vrstvě nejsou vybrány žádné prvky.', 10, True) return currentCategory = self.categoryComboBox.currentText() warning = False if featureCount == 1: self.set_text_statusbar.emit( u'Zařazuji vybranou parcelu do kategorie "{}"...'.format( currentCategory), 0, warning) else: self.set_text_statusbar.emit( u'Zařazuji vybrané parcely do kategorie "{}"...'.format( currentCategory), 0, warning) selectedFeaturesIds = layer.selectedFeaturesIds() selectedFeatures = layer.selectedFeaturesIterator() self.dW.set_field_value_for_features(layer, selectedFeatures, self.categoryName, self.categoryValue) QgsApplication.processEvents() self.update_perimeter_layer(layer, perimeterLayer) layer.selectByIds(selectedFeaturesIds) if featureCount == 1: self.set_text_statusbar.emit( u'Vybraná parcela byla zařazena do kategorie "{}".'.format( currentCategory), 20, warning) else: self.set_text_statusbar.emit( u'Vybrané parcely byly zařazeny do kategorie "{}".'.format( currentCategory), 20, warning) def update_perimeter_layer(self, layer=None, perimeterLayer=None): """Updates the perimeter layer. Args: layer (QgsVectorLayer): A reference to the layer. perimeterLayer (QgsVectorLayer): A reference to the perimeter layer. """ if not layer: layer = self.iface.activeLayer() if not perimeterLayer: perimeterLayer = self.perimeterMapLayerComboBox.currentLayer() if not self.dW.check_perimeter_layer(perimeterLayer, layer): # SpatiaLite fix - start perimeterString = u'-obvod.shp' if not self.dW.fixedSqliteDriver: composedURI = QgsDataSourceURI(layer.source()) perimeterLayerFilePath = \ composedURI.database().split('.sdb')[0] + perimeterString else: perimeterLayerFilePath = \ layer.source().split('.db')[0] + perimeterString # SpatiaLite fix - end fileInfo = QFileInfo(perimeterLayerFilePath) perimeterLayerName = fileInfo.baseName() loadedLayer = self.dW.check_loaded_layers(perimeterLayerFilePath) perimeterLayer = self._create_perimeter_layer( layer, perimeterLayerFilePath, self.categoryName, perimeterLayerName, loadedLayer) QgsApplication.processEvents() loadedLayer = self.dW.check_loaded_layers(perimeterLayerFilePath) if loadedLayer: self.iface.actionDraw().trigger() self.set_perimeter_layer(loadedLayer, False) self.sync_perimeter_map_layer_combo_box() else: QgsMapLayerRegistry.instance().addMapLayer(perimeterLayer) else: perimeterLayerFilePath = perimeterLayer.source() perimeterLayerName = perimeterLayer.name() perimeterLayer = self._create_perimeter_layer( layer, perimeterLayerFilePath, self.categoryName, perimeterLayerName, perimeterLayer) self.set_perimeter_layer(perimeterLayer, False) self.sync_perimeter_map_layer_combo_box() QgsApplication.processEvents() self.iface.actionDraw().trigger() self.iface.setActiveLayer(layer) def _set_category_by_perimeter(self, layer, perimeterLayer): """Sets a categoryValue to categoryName column for all features according to current layer in perimeterMapLayerComboBox. Args: layer (QgsVectorLayer): A reference to the layer. perimeterLayer (QgsVectorLayer): A reference to the perimeter layer. """ if not self.dW.check_perimeter_layer(perimeterLayer, layer, self): return if perimeterLayer.featureCount() == 0: self.set_text_statusbar.emit( u'Vrstva obvodu neobsahuje žádný prvek.', 10, True) return warning = False self.set_text_statusbar.emit( u'Zařazuji parcely do kategorií na základě obvodu...', 0, warning) selectedFeaturesIds = layer.selectedFeaturesIds() perimeterSelectedFeaturesIds = perimeterLayer.selectedFeaturesIds() layer.removeSelection() perimeterLayer.removeSelection() for categoryValue in self.categoryValues: if categoryValue == None: perimeterLayer.selectAll() else: self.dW.select_features_by_field_value(perimeterLayer, self.shortCategoryName, categoryValue) if perimeterLayer.selectedFeatureCount() != 0: selectedFeaturesLayerFilePath = processing.runalg( 'qgis:saveselectedfeatures', perimeterLayer, None)['OUTPUT_LAYER'] selectedFeaturesLayer = QgsVectorLayer( selectedFeaturesLayerFilePath, 'selectedFeaturesLayer', 'ogr') processing.runalg('qgis:selectbylocation', layer, selectedFeaturesLayer, u'within', 0, 0) if categoryValue == None: layer.invertSelection() categoryValue = QPyNullVariant features = layer.selectedFeaturesIterator() self.dW.set_field_value_for_features(layer, features, self.categoryName, categoryValue) layer.selectByIds(selectedFeaturesIds) perimeterLayer.selectByIds(perimeterSelectedFeaturesIds) self.set_text_statusbar.emit( u'Zařazení parcel na základě obvodu úspěšně dokončeno.', 30, warning) def _select_category(self): """Selects features in the current category.""" try: succes, layer = self.dW.check_layer(self) if not succes: return if self.categoryValue == None: expression = QgsExpression("\"{}\" is null".format( self.categoryName)) self.dW.select_features_by_expression(layer, expression) else: self.dW.select_features_by_field_value(layer, self.categoryName, self.categoryValue) currentCategory = self.categoryComboBox.currentText() featureCount = layer.selectedFeatureCount() duration = 10 warning = False if featureCount == 0: self.set_text_statusbar.emit( u'V kategorii "{}" není žádná parcela.'.format( currentCategory), duration, warning) elif featureCount == 1: self.set_text_statusbar.emit( u'V kategorii "{}" je {} parcela.'.format( currentCategory, featureCount), duration, warning) elif 1 < featureCount < 5: self.set_text_statusbar.emit( u'V kategorii "{}" jsou {} parcely.'.format( currentCategory, featureCount), duration, warning) elif 5 <= featureCount: self.set_text_statusbar.emit( u'V kategorii "{}" je {} parcel.'.format( currentCategory, featureCount), duration, warning) except: self.dW.display_error_messages( self, u'Error selecting parcels in category.', u'Chyba při vybírání parcel v kategorii.') def check_perimeter_map_layer_combo_box(self): """Checks if there is a layer in perimeterMapLayerComboBox. Returns: bool: True when there is a layer in perimeterMapLayerComboBox, False otherwise. """ if self.perimeterMapLayerComboBox.currentLayer(): return True else: return False
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)
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))
class CheckAnalysisPuWidget(PuWidget): """A widget with checks and analyzes.""" set_text_statusbar = pyqtSignal(str, int, bool) def _setup_self(self): """Sets up self.""" self.setObjectName(u'checkAnalysisPuWidget') self.gridLayout = QGridLayout(self) self.gridLayout.setObjectName(u'gridLayout') self.gridLayout.setColumnStretch(1, 1) self._build_widgets() def _build_widgets(self): """Builds own widgets.""" self.set_text_statusbar.connect(self.dW.statusBar.set_text) self.checkAnalysisLabel = QLabel(self) self.checkAnalysisLabel.setObjectName(u'checkAnalysisLabel') self.checkAnalysisLabel.setText(u'Kontrola/analýza:') self.gridLayout.addWidget(self.checkAnalysisLabel, 0, 0, 1, 1) self.checkAnalysisComboBox = QComboBox(self) self.checkAnalysisComboBox.setObjectName(u'checkAnalysisComboBox') self.gridLayout.addWidget(self.checkAnalysisComboBox, 0, 1, 1, 1) perimeterString = u'kontrola - obvodem' self.checkAnalysisComboBox.addItem(perimeterString) self.checkAnalysisComboBox.setItemData(0, perimeterString, Qt.ToolTipRole) notInSpiString = u'kontrola - není v SPI' self.checkAnalysisComboBox.addItem(notInSpiString) self.checkAnalysisComboBox.setItemData( 1, notInSpiString + u' (nová parcela)', Qt.ToolTipRole) notInMapString = u'kontrola - není v mapě' self.checkAnalysisComboBox.addItem(notInMapString) self.checkAnalysisComboBox.setItemData(2, notInMapString, Qt.ToolTipRole) areaString = u'kontrola - výměra nad mezní odchylkou' self.checkAnalysisComboBox.addItem(areaString) self.checkAnalysisComboBox.setItemData(3, areaString, Qt.ToolTipRole) unownedString = u'kontrola - bez vlastníka' self.checkAnalysisComboBox.addItem(unownedString) self.checkAnalysisComboBox.setItemData( 4, unownedString + u' (pouze zjednodušená evidence)', Qt.ToolTipRole) distanceString = u'analýza - měření vzdálenosti' self.checkAnalysisComboBox.addItem(distanceString) self.checkAnalysisComboBox.setItemData( 5, distanceString + u' (referenční bod - těžiště parcel)', Qt.ToolTipRole) bpejString = u'analýza - oceňování podle BPEJ' self.checkAnalysisComboBox.addItem(bpejString) self.checkAnalysisComboBox.setItemData(6, bpejString, Qt.ToolTipRole) self.gridLayout.setRowStretch(1, 1) self.checkAnalysisLabelStackedWidget = QStackedWidget(self) self.checkAnalysisLabelStackedWidget.setObjectName( u'checkAnalysisLabelStackedWidget') self.gridLayout.addWidget(self.checkAnalysisLabelStackedWidget, 2, 0, 1, 1) self.checkAnalysisStackedWidget = QStackedWidget(self) self.checkAnalysisStackedWidget.setObjectName( u'checkAnalysisStackedWidget') self.gridLayout.addWidget(self.checkAnalysisStackedWidget, 2, 1, 1, 1) self.perimeterLabelPuCaWidget = \ perimeter_pucawidget.PerimeterLabelPuCaWidget( self, self.dWName, self.iface, self.dW, self.pluginDir, u'perimeterLabelPuCaWidget') self.checkAnalysisLabelStackedWidget.addWidget( self.perimeterLabelPuCaWidget) self.perimeterPuCaWidget = perimeter_pucawidget.PerimeterPuCaWidget( self, self.dWName, self.iface, self.dW, self.pluginDir, u'perimeterPuCaWidget') self.checkAnalysisStackedWidget.addWidget(self.perimeterPuCaWidget) self.notInSpiLabelPuCaWidget = \ notinspi_pucawidget.NotInSpiLabelPuCaWidget( self, self.dWName, self.iface, self.dW, self.pluginDir, u'notInSpiLabelPuCaWidget') self.checkAnalysisLabelStackedWidget.addWidget( self.notInSpiLabelPuCaWidget) self.notInSpiPuCaWidget = notinspi_pucawidget.NotInSpiPuCaWidget( self, self.dWName, self.iface, self.dW, self.pluginDir, u'notInSpiPuCaWidget') self.checkAnalysisStackedWidget.addWidget(self.notInSpiPuCaWidget) self.notInMapLabelPuCaWidget = \ notinmap_pucawidget.NotInMapLabelPuCaWidget( self, self.dWName, self.iface, self.dW, self.pluginDir, u'notInMapLabelPuCaWidget') self.checkAnalysisLabelStackedWidget.addWidget( self.notInMapLabelPuCaWidget) self.notInMapPuCaWidget = notinmap_pucawidget.NotInMapPuCaWidget( self, self.dWName, self.iface, self.dW, self.pluginDir, u'notInMapPuCaWidget') self.checkAnalysisStackedWidget.addWidget(self.notInMapPuCaWidget) self.areaLabelPuCaWidget = area_pucawidget.AreaLabelPuCaWidget( self, self.dWName, self.iface, self.dW, self.pluginDir, u'areaLabelPuCaWidget') self.checkAnalysisLabelStackedWidget.addWidget( self.areaLabelPuCaWidget) self.areaPuCaWidget = area_pucawidget.AreaPuCaWidget( self, self.dWName, self.iface, self.dW, self.pluginDir, u'areaPuCaWidget') self.checkAnalysisStackedWidget.addWidget(self.areaPuCaWidget) self.unownedLabelPuCaWidget = unowned_pucawidget.UnownedLabelPuCaWidget( self, self.dWName, self.iface, self.dW, self.pluginDir, u'unownedLabelPuCaWidget') self.checkAnalysisLabelStackedWidget.addWidget( self.unownedLabelPuCaWidget) self.unownedPuCaWidget = unowned_pucawidget.UnownedPuCaWidget( self, self.dWName, self.iface, self.dW, self.pluginDir, u'unownedPuCaWidget') self.checkAnalysisStackedWidget.addWidget(self.unownedPuCaWidget) self.distanceLabelPuCaWidget = \ distance_pucawidget.DistanceLabelPuCaWidget( self, self.dWName, self.iface, self.dW, self.pluginDir, u'distanceLabelPuCaWidget') self.checkAnalysisLabelStackedWidget.addWidget( self.distanceLabelPuCaWidget) self.distancePuCaWidget = distance_pucawidget.DistancePuCaWidget( self, self.dWName, self.iface, self.dW, self.pluginDir, u'distancePuCaWidget') self.checkAnalysisStackedWidget.addWidget(self.distancePuCaWidget) self.bpejLabelPuCaWidget = bpej_pucawidget.BpejLabelPuCaWidget( self, self.dWName, self.iface, self.dW, self.pluginDir, u'bpejLabelPuCaWidget') self.checkAnalysisLabelStackedWidget.addWidget( self.bpejLabelPuCaWidget) self.bpejPuCaWidget = bpej_pucawidget.BpejPuCaWidget( self, self.dWName, self.iface, self.dW, self.pluginDir, u'bpejPuCaWidget') self.checkAnalysisStackedWidget.addWidget(self.bpejPuCaWidget) self.checkAnalysisComboBox.currentIndexChanged.connect( self.checkAnalysisLabelStackedWidget.setCurrentIndex) self.checkAnalysisComboBox.currentIndexChanged.connect( self.checkAnalysisStackedWidget.setCurrentIndex) self.checkAnalysisComboBox.currentIndexChanged.connect( self._set_text_checkAnalysisPushButton) self.gridLayout.setRowStretch(3, 1) self.checkAnalysisPushButton = QPushButton(self) self.checkAnalysisPushButton.setObjectName(u'checkAnalysisPushButton') self.checkAnalysisPushButton.clicked.connect(self._run_check) self.checkAnalysisPushButton.setText( u'Provést kontrolu a vybrat problémové parcely') self.gridLayout.addWidget(self.checkAnalysisPushButton, 4, 0, 1, 2) def _run_check(self): """Starts the current check or analysis. First it calls a function that checks if there is an active layer and if the active layer contains all required columns. If that function returns True, check or analysis is executed in a separate thread. """ succes, layer = self.dW.check_layer(self) if succes: self.executeThread = ExecuteThread(layer) self.executeThread.started.connect( self.checkAnalysisStackedWidget.currentWidget().execute) self.executeThread.start() def _set_text_checkAnalysisPushButton(self, currentIndex): """Sets checkAnalysisPushButton's text. Sets checkAnalysisPushButton's text according to checkAnalysisComboBox's current index. Args: currentIndex (int): Current index of the checkAnalysisComboBox. """ if currentIndex <= 4: self.checkAnalysisPushButton.setText( u'Provést kontrolu a vybrat problémové parcely') else: self.checkAnalysisPushButton.setText(u'Provést analýzu')