def cfg(_, start_response): start_response('200 OK', [('Content-type', 'text/html')]) read_config() symbols = get_option_val("trade", "symbol") build_html = "" for symbol in json.loads(symbols): build_html += "<div>" build_html += "<div>[{}]</div>".format(symbol) options = config.options(symbol) for option in options: val = get_option_val(symbol, option) build_html += "<div id='{}_{}'>{} = <a style='cursor:pointer;' onclick='modify(\"{}\",\"{}\")'>{}" \ "</a></div>".format(symbol, option, option, symbol, option, val) build_html += "</div>" build_html += "<br/>" build_html += "<div>" build_html += "<div>[{}-stat]</div>".format(symbol) try: options = config.options("{}-stat".format(symbol)) for option in options: val = get_option_val("{}-stat".format(symbol), option) build_html += "<div id='{}_{}'>{} = <a style='cursor:pointer;' onclick='modify(\"{}\",\"{}\")'>{}" \ "</a></div>".format(symbol + "-stat", option, option, symbol + "-stat", option, val) except Exception as e: logger.warning(str(e)) build_html += "</div><hr/>" with open('app/config.html', 'r', encoding="utf-8") as fp: yield fp.read().replace("#tbd", build_html).encode('utf-8')
def get_klines(self, symbol, period, size): result = {} granularity = granularityDict[period] end_s = int("%0.0f" % datetime.datetime.utcnow().timestamp()) start_s = end_s - granularity * size start = datetime.datetime.fromtimestamp(start_s).strftime( "%Y-%m-%dT%H:%M:%S.000Z") end = datetime.datetime.fromtimestamp(end_s).strftime( "%Y-%m-%dT%H:%M:%S.000Z") try: result = self.spotAPI.get_kline(symbol, start, end, granularity) except Exception as e: logger.error("***klines:%s" % e) is_list = isinstance(result, list) if is_list and len(result) == size: self.kline_data = list(map(self.get_line_data, result)) if len(self.kline_data) == 0: logger.error("***klines retry...") self.get_klines(symbol, period, size) elif is_list and len( result) == size - 1 and self.kline_data[0][5] != end: first = json.loads(json.dumps(result[0])) first[0] = end first[1] = first[4] first[2] = first[4] first[3] = first[4] first[5] = "0" result.insert(0, first) self.kline_data = list(map(self.get_line_data, result)) elif is_list and len(result) != size and len(result) != size - 1: logger.warning("***klines not refresh,{}".format(result))
def get_account_info(self): logger.info( '-----------------------------------spot account info--------------------------------------------' ) try: accounts = [self.BALANCE_E.upper(), self.BALANCE_T.upper()] for symbol in accounts: t_account = self.spotAPI.get_coin_account_info(symbol) if t_account.get('currency') == symbol: logger.info("%s:balance %s available %s frozen %s" % (symbol, t_account["balance"], t_account["available"], t_account["frozen"])) else: logger.warning("getAccountInfo Fail,Try again!") self.get_account_info() except Exception as err: logger.error(err) self.get_account_info()
def check_order_status(self, my_order_info, wait_count=0): order_id = my_order_info.orderId order_result = {} try: logger.info("check order status {}".format(wait_count)) order_result = self.spotAPI.get_order_info(my_order_info.orderId, my_order_info.symbol) except Exception as e: logger.error("***orderinfo:%s" % e) if order_result is not None and order_result.get( 'order_id') == my_order_info.orderId: order = order_result order_id = order["order_id"] status = order["status"] filled_size = float(order["filled_size"]) if filled_size > 0: my_order_info.set_deal_amount(filled_size) my_order_info.set_avg_price( float(order["filled_notional"]) / filled_size) if status == self.CANCELLED_STATUS: logger.info("order {} canceled".format(order_id)) elif status == 'open': if wait_count == self.TRADE_WAIT_COUNT: logger.info("timeout no deal") else: logger.info("no deal") elif status == 'part_filled': if wait_count == self.TRADE_WAIT_COUNT: logger.info("timeout part deal {}".format( my_order_info.dealAmount)) else: logger.info("part deal {}".format( my_order_info.dealAmount)) elif status == self.FILLED_STATUS: logger.info("order {} filled".format(order_id)) elif status == 'canceling': logger.info("order {} canceling".format(order_id)) elif status == 'ordering': logger.info("order {} ordering".format(order_id)) return status else: logger.warning( "order {} checkOrderStatus failed,try again.".format(order_id)) return self.check_order_status(my_order_info, wait_count)
def get_klines(self, symbol, period, size): result = {} try: result = self.MarketApi.get_history_candlesticks( symbol, period, size) except Exception as e: logger.error("***klines:%s" % e) time.sleep(0.2) if result["code"] == "0": data = result["data"] is_list = isinstance(data, list) if is_list and len(data) == size: self.kline_data = list(map(self.get_line_data, data)) if len(self.kline_data) == 0: logger.error("***klines retry...") self.get_klines(symbol, period, size) elif is_list and len(data) != size and len(data) != size - 1: logger.warning("***klines not refresh,{}".format(data)) else: logger.error("***klines:%s" % result["msg"])
def check_order_status(self, my_order_info, wait_count=0): order_id = my_order_info.orderId order_result = {} try: logger.info("check order status {}".format(wait_count)) order_result = self.TradeApi.get_orders(my_order_info.symbol, my_order_info.orderId) except Exception as e: logger.error("***orderinfo:%s" % e) if order_result is not None and order_result.get( 'code') == "0" and order_result.get('data'): order = order_result['data'][0] order_id = order["ordId"] status = order["state"] filled_size = float(order["accFillSz"]) if filled_size > 0: my_order_info.set_deal_amount(filled_size) my_order_info.set_avg_price(float(order["avgPx"])) if status == self.CANCELLED_STATUS: logger.info("order {} canceled".format(order_id)) elif status == 'live': if wait_count == self.TRADE_WAIT_COUNT: logger.info("timeout no deal") else: logger.info("no deal") elif status == 'partially_filled': if wait_count == self.TRADE_WAIT_COUNT: logger.info("timeout part deal {}".format( my_order_info.dealAmount)) else: logger.info("part deal {}".format( my_order_info.dealAmount)) elif status == self.FILLED_STATUS: logger.info("order {} filled".format(order_id)) return status else: logger.warning( "order {} checkOrderStatus failed,try again.".format(order_id)) return self.check_order_status(my_order_info, wait_count)
def get_coin_price(self, symbol): self.ws_connect() self.socketData = None gevent.spawn(self.socket_recv, self).join(15) if not self.socketData: self.ping = True self.pong = False t = 0 while not self.pong and t < 3: try: self.ws.send("ping") logger.info("[{}]ping.........".format(symbol)) gevent.spawn(self.socket_recv, self).join(3) except Exception as e: logger.info("[{}]ping exception,{}".format(symbol, e)) if self.socketData: self.pong = True logger.info("[{}]pong!!!!!!!!!".format(symbol)) t += 1 if self.ping: self.ping = False if not self.pong: logger.warning("[{}]no pong in 5s,reconnect!".format(symbol)) self.ws.close() self.get_coin_price(symbol) return res = None try: res = json.loads(self.socketData) except Exception as e: logger.error("{} : {}".format(self.socketData, e)) if res and res.get("data") is not None: data = res.get("data")[0] price_info = self.priceInfo[symbol] price_info["asks"] = list( map(lambda x: list(map(lambda d: float(d), x)), data["asks"])) price_info["bids"] = list( map(lambda x: list(map(lambda d: float(d), x)), data["bids"]))
def auth_fail(_, start_response): with open('app/info.html', 'r', encoding="utf-8") as fp: logger.warning("授权码验证失败,点击重试") start_response('200 OK', [('Content-type', 'text/html')]) yield fp.read().format(code="406 Forbidden", msg="授权码验证失败,点击重试!").encode('utf-8')
accounts_init = {} try: for _, _, files in os.walk("keys"): files.sort(key=lambda x: int(x.split("-")[0])) for file_name in files: decrypt_f(f"keys/{file_name}") _config = configparser.ConfigParser() _config.read("keys/" + file_name) apikey = _config.get("info", "apikey") secretkey = _config.get("info", "secretkey") passphrase = _config.get("info", "passphrase") trxpass = _config.get("info", "trxpass") accounts_init[file_name] = (apikey, secretkey, passphrase, trxpass) encrypt_f(f"keys/{file_name}") except FileNotFoundError: logger.warning("keys not found") def read_config(): config.clear() config.read(CONFIG_FILE) def write_config(): with open(CONFIG_FILE, "w") as fp: config.write(fp) def get_config_text(): with open(CONFIG_FILE, "r") as fp: return fp.read()