def make_matrix(_symbol): _api_ = _GENERAL_API_LIST["CANDLESTICK"] svrtime = get_general_api(_GENERAL_API_LIST["GETSVRTIME"]) if (svrtime.get("code") == 1): svrtime = svrtime.get("content") svrtime = svrtime.get("serverTime") else: logger.debug( "[{}][create_new_order] - Error code: {} | {} | {}".format( self.symbol, server.get("code"), server.get("content"), server.get("exception"))) return svrtime timestamp = svrtime + 3 starttime = timestamp - 60 * 5 * 60 params = "symbol={}&interval=1m".format(_symbol) rs = get_general_api(_api_, params) if (rs.get("code") == 1): # logger.debug("[{}][coinanalyze] - Content: {}".format(_symbol, rs)) candles = rs.get("content")[::-1] check = 0 candle_coins = [] while (check < 30): candle_coins.append(float(candles[check][4]) * 10000) check += 1 return candle_coins[::-1]
def query_order(self, _orderid, _origClientOrderId): _RETURN_DATA = None # make header headers = {"X-MBX-APIKEY": self._API_KEY_} # Test get server time svrtime = self.get_general_api(_GENERAL_API_LIST["GETSVRTIME"]) if (svrtime.get("code") == 1): svrtime = svrtime.get("content") svrtime = svrtime.get("serverTime") else: logger.debug( "[{}][create_new_order] - Error code: {} | {} | {}".format( self.symbol, server.get("code"), server.get("content"), server.get("exception"))) return svrtime timestamp = svrtime + 3 bodies = "symbol={}&orderId={}&origClientOrderId={}×tamp={}&recvWindow=50000".format( self.symbol, _orderid, _origClientOrderId, timestamp) signature = self.generate_hmac_signature(bodies.encode("utf-8")) bodies = "{}&signature={}".format(bodies, signature) rs = self.account_api(_ACCOUNT_API_["ORDER"], _method="GET", _req_body=bodies, _req_header=headers) _RETURN_DATA = rs return _RETURN_DATA
def get_balance(self): _RETURN_DATA = None # make header headers = {"X-MBX-APIKEY": self._API_KEY_} # Test get server time svrtime = self.get_general_api(_GENERAL_API_LIST["GETSVRTIME"]) if (svrtime.get("code") == 1): svrtime = svrtime.get("content") timestamp = svrtime.get("serverTime") + 3 bodies = "timestamp={}&recvWindow=50000".format(timestamp) signature = self.generate_hmac_signature(bodies.encode("utf-8")) bodies = "{}&signature={}".format(bodies, signature) rs = self.account_api(_ACCOUNT_API_["BALANCE"], _method="GET", _req_body=bodies, _req_header=headers) if (rs.get("code") == 1): rs = rs.get("content") rs = rs.get("balances") for _rs in rs: if (_rs.get("asset") == _MARKET_): _RETURN_DATA = _rs.get("free") else: logger.debug("[check_balance] - Error code: {} | {}".format( rs.get("code"), rs.get("content"))) return _RETURN_DATA
def get_top_symbols(): _RETURN_DATA = dict() _RETURN_DATA["code"] = 0 _api_ = _GENERAL_API_LIST["TIKER_STATISTICS"] tiker_statistics = dict() rs = get_general_api(_api_) bnbmarket = list() market = list() if (rs.get("code") == 1): rs = rs.get("content") for _rs in rs: if (_rs.get("symbol").find(_MARKET_) >= 1): _UP_ = "UP{}".format(_MARKET_) _DOWN_ = "DOWN{}".format(_MARKET_) if (_UP_ not in _rs.get("symbol") and _DOWN_ not in _rs.get("symbol")): bnbmarket.append(_rs) bnbmarket = sorted(bnbmarket, key=lambda k: float(k.get("quoteVolume")), reverse=True) for m in bnbmarket: if (float(m.get("priceChangePercent")) > 5.0): logger.debug("[get_top_symbols] - [{}]-{}".format( m.get("symbol"), m.get("quoteVolume"))) market.append(m) with open(_TOP_CHANGE_COIN_DB_, "w+") as f: f.write(str(market)) else: logger.debug("[check_tiker_statistics] - Error code {} | {}".format( rs.get("code"), rs.get("content"))) return market
def create_new_order(self, _limit_price=None, _stop_price=None, _quantity=0, _type="STOP_LOSS_LIMIT", _side="SELL"): _RETURN_DATA = dict() _RETURN_DATA["code"] = 0 if (_limit_price != None and _stop_price != None): # Handler headers = {"X-MBX-APIKEY": self._API_KEY_} # Test get server time svrtime = self.get_general_api(_GENERAL_API_LIST["GETSVRTIME"]) if (svrtime.get("code") == 1): svrtime = svrtime.get("content") svrtime = svrtime.get("serverTime") else: logger.debug( "[{}][create_new_order] - Error code: {} | {} | {}".format( self.symbol, server.get("code"), server.get("content"), server.get("exception"))) return svrtime logger.debug("[+] Server time: {}".format(svrtime)) balances = self.get_balance() timestamp = svrtime + 3 bodies = "symbol={}&side={}&type={}&timeInForce={}&quantity={}&price={}×tamp={}&recvWindow=50000".format( self.symbol, _side, _type, "GTC", _quantity, _limit_price, timestamp) if (float(_stop_price) != 0.0): bodies = "{}&stopPrice={}".format(bodies, _stop_price) signature = self.generate_hmac_signature(bodies.encode("utf-8")) bodies = "{}&signature={}".format(bodies, signature) logger.debug("[{}][create_new_order] - Body: {}".format( self.symbol, bodies)) # def account_api(_api, _method="GET", _req_body=None, _req_header=None): rs = self.account_api(_ACCOUNT_API_["ORDER"], _method="POST", _req_body=bodies, _req_header=headers) # logger.debug("[create_new_order] - DEBUG - {}".format(rs)) if (rs.get("code") == 1): ct = rs.get("content") ct["price"] = _stop_price ct["origQty"] = _quantity rs["content"] = ct return rs else: logger.debug( "[{}][create_new_order] - Error code: {} | {} | {}".format( self.symbol, rs.get("code"), rs.get("content"), rs.get("exception"))) return rs else: _RETURN_DATA["code"] = -1 _RETURN_DATA["content"] = "Assession failed" return _RETURN_DATA
def check_tiker_statistics(_list_tikers): _api_ = _GENERAL_API_LIST["TIKER_STATISTICS"] tiker_statistics = dict() for tiker in _list_tikers: rs = get_general_api(_api_, _params="symbol={}".format(tiker)) if (rs.get("code") == 1): rs = rs.get("content") tiker_statistics[rs.get("symbol")] = rs.get("priceChangePercent") else: logger.debug( "[check_tiker_statistics] - Error code {} | {}".format( rs.get("code"), rs.get("content"))) return tiker_statistics
def send_notification(context): # URL = bot[TOKEN]/sendMessage?chat_id=[CHAT_ID]&text=[MY_MESSAGE_TEXT] _BASE_URL_ = "https://api.telegram.org" _endpoint_url_ = "{}/{}/sendMessage?chat_id={}&text={}".format( _BASE_URL_, _TELEGRAM_BOT_TOKEN_, _CHATID_, context) logger.debug( "[send_notification] - _endpoint_url_: {}".format(_endpoint_url_)) triedtime = 3 while (triedtime): try: req = requests.get(_endpoint_url_) triedtime = 0 except Exception as ex: triedtime -= 1 logger.debug("[send_notification] - Error: {}".format(ex)) pass return 0
def read_config(): # read apikey, secretkey, timetodelay global _TIME_TO_DELAY_, _API_KEY_, _SECRET_KEY_, _CHATID_, _TELEGRAM_BOT_TOKEN_ try: configurations = dict() with open(_CONFIG_FILE_PATH_, "r") as f: for line in f: temp = line.strip().split("=") configurations[temp[0]] = temp[1] # logger.debug((temp[1])) # logger.debug(configurations) _TIME_TO_DELAY_ = int(configurations.get("_TIME_TO_DELAY_")) _API_KEY_ = configurations.get("_API_KEY_") _SECRET_KEY_ = configurations.get("_SECRET_KEY_").encode() _TELEGRAM_BOT_TOKEN_ = configurations.get("_TELEGRAM_BOT_TOKEN_") _CHATID_ = configurations.get("_CHATID_") except Exception as ex: logger.debug("[read_config][read_config] - Error: {}".format(ex))
def read_config(self): try: configurations = dict() with open(self._CONFIG_FILE_PATH_, "r+") as f: for line in f: temp = line.strip().split("=") configurations[temp[0]] = temp[1] # logger.debug((temp[1])) # logger.debug(configurations) self._TIME_TO_DELAY_ = int(configurations.get("_TIME_TO_DELAY_")) self._API_KEY_ = configurations.get("_API_KEY_") self._SECRET_KEY_ = configurations.get("_SECRET_KEY_").encode() self._TELEGRAM_BOT_TOKEN_ = configurations.get( "_TELEGRAM_BOT_TOKEN_") self._CHATID_ = configurations.get("_CHATID_") except Exception as ex: logger.debug("[{}][read_config] - Error: {}".format( self.symbol, ex))
def cancel_order(self, _orderid, _origClientOrderId): _RETURN_DATA = dict() _RETURN_DATA["code"] = 0 # b'{"symbol":"IQBNB","orderId":12856460,"orderListId":-1,"clientOrderId":"IWiBFgXE3WOWVPskKazLcS","transactTime":1615721252141}' headers = {"X-MBX-APIKEY": self._API_KEY_} # Test get server time svrtime = self.get_general_api(_GENERAL_API_LIST["GETSVRTIME"]) if (svrtime.get("code") == 1): svrtime = svrtime.get("content") svrtime = svrtime.get("serverTime") else: logger.debug( "[{}][create_new_order] - Error code: {} | {} | {}".format( self.symbol, server.get("code"), server.get("content"), server.get("exception"))) return svrtime logger.debug("[+] Server time: {}".format(svrtime)) timestamp = svrtime bodies = "symbol={}&orderId={}&origClientOrderId={}×tamp={}&recvWindow=50000".format( self.symbol, _orderid, _origClientOrderId, timestamp) signature = self.generate_hmac_signature(bodies.encode("utf-8")) bodies = "{}&signature={}".format(bodies, signature) logger.debug("[{}][cancel_order] - Body: {}".format( self.symbol, bodies)) # def account_api(_api, _method="GET", _req_body=None, _req_header=None): rs = self.account_api(_ACCOUNT_API_["ORDER"], _method="DELETE", _req_body=bodies, _req_header=headers) logger.debug("[{}][cancel_order] - Body: {}".format(self.symbol, rs)) if (rs.get("code") == 1): return rs else: logger.debug( "[{}][cancel_order] - Error code: {} | {} | {}".format( self.symbol, rs.get("code"), rs.get("content"), rs.get("exception"))) return rs return rs
def is_btc_goup(_symbol="BTCUSDT"): _api_ = _GENERAL_API_LIST["CANDLESTICK"] svrtime = get_general_api(_GENERAL_API_LIST["GETSVRTIME"]) if (svrtime.get("code") == 1): svrtime = svrtime.get("content") svrtime = svrtime.get("serverTime") else: logger.debug( "[{}][create_new_order] - Error code: {} | {} | {}".format( self.symbol, server.get("code"), server.get("content"), server.get("exception"))) return svrtime timestamp = svrtime + 3 starttime = timestamp - 60 * 5 * 60 params = "symbol={}&interval=1h".format(_symbol) rs = get_general_api(_api_, params) if (rs.get("code") == 1): # logger.debug("[{}][coinanalyze] - Content: {}".format(_symbol, rs)) candles = rs.get("content")[::-1] return candles[0] > candles[1]
def get_general_api(self, _api, _params=None): _RETURN_DATA = dict() _RETURN_DATA["code"] = 0 api_index = 0 while (api_index < len(_BASE_API_)): logger.debug("[{}] - Trying {}".format(self.symbol, api_index)) try: if (_params == None): _endpoint_url_ = "{}/{}".format(_BASE_API_[api_index], _api) else: _endpoint_url_ = "{}/{}?{}".format(_BASE_API_[api_index], _api, _params) logger.debug("[{}][+] EP URL: {}".format( self.symbol, _endpoint_url_)) req = requests.get(_endpoint_url_) if (req.status_code == 200): _RETURN_DATA["content"] = json.loads( req.content.decode("utf-8")) _RETURN_DATA["code"] = 1 break else: logger.debug("[{}][+] Connection info: {} - {}".format( self.symbol, req.status_code, req.content)) _RETURN_DATA["content"] = json.loads( req.content.decode("utf-8")) _RETURN_DATA["code"] = -1 break except Exception as ex: logger.debug("[{}][-] Error: {}".format(self.symbol, ex)) _RETURN_DATA["content"] = "Connection error!" _RETURN_DATA["code"] = -2 _RETURN_DATA["exception"] = ex api_index += 1 time.sleep(0.5) return _RETURN_DATA
def bamday(_symbol, _saferange, _budget): # topprice topprice = 0 iswait = True global _NUMBER_OF_ZERO_DIGIT, _TIME_TO_DELAY_, _LOT_SIZE_ # 1. Check price if (_saferange < 0): _saferange *= -1 current_price = query_symbol_price(_symbol) topprice = current_price # Stop < Limit _stopprice = round((current_price + _saferange * _RANGEPRICE_), _NUMBER_OF_ZERO_DIGIT) _limitprice = _stopprice logger.debug("_NUMBER_OF_ZERO_DIGIT {}".format(_NUMBER_OF_ZERO_DIGIT)) logger.debug( "[Follow lowest price] Current price: {:.8f}".format(current_price)) logger.debug( "[Follow lowest price] Top/Old price: {:.8f}".format(topprice)) logger.debug("[Follow lowest price] SafeRange: {:.8f}".format(_saferange)) logger.debug("[+] _LOT_SIZE_: {}".format((_LOT_SIZE_))) result = create_new_order(_symbol=_symbol, _limit_price="{:.8f}".format(_limitprice), _stop_price="{:.8f}".format(_stopprice), _quantity=round(_budget / current_price, _LOT_SIZE_), _side="BUY") # logger.debug("[*] Result: {}".format(result)) result = result.decode("utf-8") result = json.loads(result) orderId = result["orderId"] clientOrderId = result["clientOrderId"] logger.debug( "[Follow lowest price] - orderId: {}\nclientOrderID: {}".format( orderId, clientOrderId)) while (iswait): if (orderId == None or clientOrderId == None): iswait = False break result = query_order(_symbol=_symbol, _orderid=orderId, _origClientOrderId=clientOrderId) temp_result = result.decode("utf-8") temp_result = json.loads(temp_result) # logger.debug("[bamday] - {}".format(result)) status = temp_result.get("status") origQty = float(temp_result["origQty"]) price = float(temp_result["price"]) # logger.debug("[bamday] - Order status: {}\nPrice: {}\nQuantity: {}".format(status, price, origQty)) if (status == "FILLED"): logger.debug("[bamday] - FILLED") iswait = False break logger.debug("[bamday] - Delay: {}s".format(_TIME_TO_DELAY_)) time.sleep(_TIME_TO_DELAY_) current_price = query_symbol_price(_symbol) if (current_price < topprice or status == "CANCELED"): # Stop < Limit _stopprice = round((current_price + _saferange * _RANGEPRICE_), _NUMBER_OF_ZERO_DIGIT) _limitprice = _stopprice logger.debug("[Follow lowest price] Current price: {:.8f}".format( _stopprice)) logger.debug( "[bamday] - Cancel order id: {}\nCreate new order with price: {} and quantity: {}" .format(orderId, current_price + _saferange, round((_budget / current_price), _LOT_SIZE_))) cancel_order(_symbol=_symbol, _orderid=orderId, _origClientOrderId=clientOrderId) topprice = current_price result = create_new_order( _symbol=_symbol, _limit_price="{:.8f}".format(_limitprice), _stop_price="{:.8f}".format(_stopprice), _quantity=round((_budget / current_price), _LOT_SIZE_), _side="BUY") result = result.decode("utf-8") result = json.loads(result) orderId = result.get("orderId") clientOrderId = result.get("clientOrderId") else: logger.debug("Cho vao gia!") return result
def automated(_symbol, _fund, _changed=None): #calculator current_price = query_symbol_price(_symbol) str_current_price = "{:.8f}".format(current_price) logger.debug(str_current_price.split(".")) global _NUMBER_OF_ZERO_DIGIT, _TIME_TO_DELAY_, _PROFIT_ _NUMBER_OF_ZERO_DIGIT = len(str_current_price.split(".")[1]) logger.debug("_NUMBER_OF_ZERO_DIGIT: {}/{:.8f}".format( _NUMBER_OF_ZERO_DIGIT, current_price)) logger.debug("_TIME_TO_DELAY_: {}".format(_TIME_TO_DELAY_)) isnextstep = False while (isnextstep is False): time.sleep(5) next_price = query_symbol_price(_symbol) time.sleep(5) third_price = query_symbol_price(_symbol) # logger.debug("[automated] - last_price: {:.8f}".format(current_price)) # logger.debug("[automated] - current_price: {:.8f}".format(next_price)) if (_changed != None): change_price = _changed else: change_price = current_price - next_price change_one_price = next_price - third_price logger.debug("[automated] - change_price: {:.8f}".format(change_price)) current_price = query_symbol_price(_symbol) if (change_price != 0): if (change_price <= 0.00000003): change_price == 0.00000004 if (change_price > 0 or change_one_price > 0): # Giam result = bamday(_symbol=_symbol, _saferange=change_price, _budget=_fund) bought_price = float(result.get("price")) orderId = result.get("orderId") clientOrderId = result.get("clientOrderId") logger.debug( "[automated] - orderId: {}\nclientOrderID: {}".format( orderId, clientOrderId)) status = result.get("status") origQty = float(result.get("origQty")) isnextstep = True else: # Tang logger.debug("[+] - Buying coin {}".format(_symbol)) change_price = change_price * (-1) if (change_price <= 0.00000003): change_price == 0.00000004 # Stop limit < Limit # Mới mua vào nên giá mua chỉ cần cao hơn 1 chút so với hiện tại _stopprice = round(current_price + change_price * 0.5, _NUMBER_OF_ZERO_DIGIT) _limitprice = _stopprice result = create_new_order( _symbol=_symbol, _type="STOP_LOSS_LIMIT", _limit_price="{:.8f}".format( round(_limitprice, _NUMBER_OF_ZERO_DIGIT)), _stop_price="{:.8f}".format(_stopprice), _quantity=round(_fund / next_price, _LOT_SIZE_), _side="BUY") logger.debug("[*] Result: {}".format(result)) result = result.decode("utf-8") result = json.loads(result) orderId = result.get("orderId") clientOrderId = result.get("clientOrderId") logger.debug( "[automated] - orderId: {}\nclientOrderID: {}".format( orderId, clientOrderId)) isbuy = False while (isbuy == False and orderId != None): time.sleep(_TIME_TO_DELAY_) try: result = query_order(_symbol=_symbol, _orderid=orderId, _origClientOrderId=clientOrderId) result = result.decode("utf-8") logger.debug("[automated] - Result: {}".format(result)) result = json.loads(result) status = result.get("status") origQty = float(result.get("origQty")) price = float(result.get("price")) symbol = result.get("symbol") logger.debug(status) bought_price = price current_price = query_symbol_price(_symbol) if (status == "FILLED"): isbuy = True except Exception as ex: logger.debug("[automated] - {}".format(ex)) isnextstep = True else: logger.debug( "[automated] - Average change to low! Find other coins!") send_notification( "[automated] - Average change to low! Find other coins!") # time.sleep(_TIME_TO_DELAY_) logger.info("[automated] - Bought {} {} successful with {:.8f}".format( origQty, _symbol, bought_price)) send_notification( "[automated] - Bought {} {} successful with {:.8f}".format( origQty, _symbol, bought_price)) # Follow top price iswait = True while (iswait): time.sleep(_TIME_TO_DELAY_ / 2) current_price = query_symbol_price(_symbol) logger.info( "[automated] - Current price: {:.8f} (Waiting for > {:.8f})". format(current_price, (bought_price + change_price * 1.1))) if (current_price > bought_price + change_price * 1.1): logger.debug("[automated] - Buy {}\nSell: >{}".format( current_price, (bought_price + change_price * 1.1))) iswait = False _dutheodinh = dutheodinh(_symbol=_symbol, _saferange=change_price, _quantity=origQty) filled_price = float(_dutheodinh.get("price")) filled_quantity = float(_dutheodinh.get("origQty")) logger.info("[automated] - Sold {} {} successfull with {:.8f}".format( filled_quantity, _symbol, filled_price)) logger.info(":)") global _PROFIT_ _PROFIT_ = (filled_price - bought_price) * filled_quantity with open("profit.data", "a+") as f: _now = datetime.now() data = "{} - [{}] - {:.8f}\n".format(_now.strftime("%d%m%y %H:%M:%S"), _symbol, _PROFIT_) f.write(str(data)) logger.info("[automated] - _PROFIT_: {:.8f} {}".format(_PROFIT_, _symbol)) send_notification("[automated] - _PROFIT_: {:.8f} {}".format( _PROFIT_, _symbol)) return 0
def dutheodinh(targeted_coin, _account, _saferange): topprice = 0 # 1. Check price if (_saferange < 0): _saferange *= -1 current_price = round(float(targeted_coin.get_current_price()), targeted_coin.lotsize) topprice = current_price print("Current price: {}".format(current_price)) # Stop > limit _stopprice = str( round((float(current_price) - _saferange * _RANGEPRICE_), targeted_coin.lotsize)) _limitprice = _stopprice logger.debug("[+] Limit price: {}".format((_limitprice))) logger.debug("[+] _LOT_SIZE_: {}".format((targeted_coin.lotsize))) logger.debug("[+] STEP: {}".format((targeted_coin.stepsize))) _quantity = str( round(targeted_coin.budget / float(_limitprice), targeted_coin.stepsize)) result = _account.buy(_limitprice, _quantity) _RETURN_DATA = result logger.debug(result) if (result.get("code") == 1): result = result.get("content") logger.info("[{}][dutheodinh] - Buy successful! {}".format( _limitprice, result.get("content"))) else: logger.info("[{}][dutheodinh] - Error occurs!".format(_limitprice)) orderId = result.get("orderId") clientOrderId = result.get("clientOrderId") logger.debug("[dutheodinh] - orderId: {}\nclientOrderID: {}".format( orderId, clientOrderId)) while (1): time.sleep(_TIME_TO_DELAY_) current_price = round(float(targeted_coin.get_current_price()), targeted_coin.lotsize) # Stop > limit _stopprice = str( round((current_price - _saferange * _RANGEPRICE_), targeted_coin.lotsize)) _limitprice = _stopprice if (current_price > topprice): topprice = current_price cancel_order(_symbol=_symbol, _orderid=orderId, _origClientOrderId=clientOrderId) result = create_new_order( _symbol=_symbol, _limit_price="{:.8f}".format(_limitprice), _stop_price="{:.8f}".format(_stopprice), _quantity=_quantity) # result = result.decode("utf-8") result = json.loads(result) orderId = result.get("orderId") clientOrderId = result.get("clientOrderId") else: logger.debug("Cho cat lo!") if (orderId == None): break result = query_order(_symbol=_symbol, _orderid=orderId, _origClientOrderId=clientOrderId) result = result.decode("utf-8") result = json.loads(result) _RETURN_DATA = result status = result.get("status") if (status == "FILLED"): break return _RETURN_DATA
def account_api(self, _api, _method="GET", _req_body=None, _req_header=None): _RETURN_DATA = dict() # _RETURN_DATA = {"code": 0, "content": "", "exception": ""} _RETURN_DATA["code"] = 0 # Do not do anything api_index = 0 while (api_index < len(_BASE_API_)): logger.debug("[{}]Trying {}".format(self.symbol, api_index)) try: _endpoint_url_ = "{}/{}".format(_BASE_API_[api_index], _api) if (_method == "GET"): if (_req_body != None): _endpoint_url_ = "{}?{}".format( _endpoint_url_, _req_body) logger.debug("[{}][+] EP URL: [GET] / {}".format( self.symbol, _endpoint_url_)) req = requests.get(_endpoint_url_, headers=_req_header) elif (_method == "POST"): #Post request, make header/body logger.debug("[{}][+] EP URL: [POST] / {}".format( self.symbol, _endpoint_url_)) if (_req_body == None): logger.debug( "[{}][account_api] - _req_body needed!".format( self.symbol)) else: logger.debug( "[{}][account_api] - _req_body: {}\n_req_header: {}\n" .format(self.symbol, _req_body, _req_header)) req = requests.post(_endpoint_url_, data=_req_body, headers=_req_header) elif (_method == "DELETE"): logger.debug( "[{}][account_api] - _req_body: {}\n_req_header: {}\n". format(self.symbol, _req_body, _req_header)) req = requests.delete(_endpoint_url_, data=_req_body, headers=_req_header) if (req.status_code == 200): # logger.debug("[200][account_api][{}] - {}".format(_api, req.content)) _RETURN_DATA["content"] = json.loads( req.content.decode("utf-8")) _RETURN_DATA["code"] = 1 #Success break else: logger.debug("[{}][+] Connection info: {}/{}".format( self.symbol, req.status_code, req.content)) _RETURN_DATA["content"] = json.loads( req.content.decode("utf-8")) _RETURN_DATA["code"] break except Exception as ex: logger.debug("[{}][-] Error: {}".format(self.symbol, ex)) _RETURN_DATA["content"] = "Connection error!" _RETURN_DATA["exception"] = ex _RETURN_DATA["code"] = -2 #Exception time.sleep(0.1) api_index += 1 return _RETURN_DATA
def followbottom(self, targeted_coin, _saferange): _RETURN_DATA = dict() _RETURN_DATA["code"] = -1 isloop = True while isloop: isloop = False topprice = 0 # 1. Check price if (_saferange < 0): _saferange *= -1 current_price = round(float(targeted_coin.get_current_price()), targeted_coin.lotsize) topprice = current_price # Stop > limit _stopprice = str( round((float(current_price) + _saferange * 0.2), targeted_coin.lotsize)) if (targeted_coin.lotsize == 8): _stopprice = "{:.8f}".format( round((float(current_price) + round(_saferange * 0.2, 8)), targeted_coin.lotsize)) _limitprice = _stopprice _quantity = str( round(targeted_coin.budget / float(_limitprice), targeted_coin.stepsize)) logger.info("[{}][followbottom][+]Current price: {}".format( self.symbol, current_price)) logger.info("[{}][followbottom][+]_saferange: {:.8f}".format( self.symbol, _saferange)) logger.info("[{}][followbottom][+]Limit price: {}".format( self.symbol, _limitprice)) logger.info("[{}][followbottom][+]_LOT_SIZE_: {}".format( self.symbol, targeted_coin.lotsize)) logger.info("[{}][followbottom][+]STEP: {}".format( self.symbol, targeted_coin.stepsize)) result = self.buy(_limitprice, _quantity) # Error handler if (result.get("code") != 1): error = result.get("content") logger.info("[{}][followbottom] - Code: {} | msg: {}".format( self.symbol, error.get("code"), error.get("msg"))) if (error.get("code") == -2010 and error.get("msg") == "Stop price would trigger immediately." ): # Stop price would trigger immediately. isloop = True _saferange += _saferange * 0.5 time.sleep(1) elif (error.get("msg") == "Account has insufficient balance for requested action." ): _RETURN_DATA = result _RETURN_DATA["code"] = -1 _RETURN_DATA["content"] = error return _RETURN_DATA elif (error.get("code") == -1100): _RETURN_DATA = result _RETURN_DATA["code"] = -1 _RETURN_DATA["content"] = error return _RETURN_DATA else: _RETURN_DATA = result _RETURN_DATA["code"] = -1 _RETURN_DATA["content"] = error return _RETURN_DATA else: tranaction = result.get("content") logger.debug("[{}][followbottom] - Content: {}".format( self.symbol, tranaction)) # if(tranaction.get("status") != "FILLED"): isloop = True # End error handler _RETURN_DATA = result.get("content") logger.debug(result) if (result.get("code") == 1): logger.info("[{}][followbottom] - Order accepted! {}".format( _limitprice, result.get("content"))) result = result.get("content") else: logger.info( "[{}][followbottom] - Buy unsuccessful!".format(_limitprice)) _RETURN_DATA["profit"] = 0 return _RETURN_DATA orderId = result.get("orderId") clientOrderId = result.get("clientOrderId") logger.debug("[followbottom] - orderId: {} | clientOrderID: {}".format( orderId, clientOrderId)) while (1): time.sleep(_TIME_TO_DELAY_) current_price = round(float(targeted_coin.get_current_price()), targeted_coin.lotsize) # Stop > limit _stopprice = str( round((current_price + _saferange * _RANGEPRICE_), targeted_coin.lotsize)) _limitprice = _stopprice if (current_price < topprice): topprice = current_price self.cancel_order(_orderid=orderId, _origClientOrderId=clientOrderId) isloop = True while (isloop): if (targeted_coin.lotsize == 8): _limitprice = "{:.8f}".format( round( float(_limitprice) + round(float(_saferange) * 0.1, 8), targeted_coin.lotsize)) else: _limitprice = str( round( float(_limitprice) + float(_saferange) * 0.1, targeted_coin.lotsize)) isloop = False result = self.buy(_limitprice, _quantity) # result = result.decode("utf-8") # Error handler if (result.get("code") != 1): error = result.get("content") logger.info( "[{}][followbottom] - Code: {} | msg: {}".format( self.symbol, error.get("code"), error.get("msg"))) if (error.get("code") == -2010 and error.get("msg") == "Stop price would trigger immediately." ): # Stop price would trigger immediately. isloop = True _saferange += _saferange * 0.5 time.sleep(1) elif (error.get( "msg" ) == "Account has insufficient balance for requested action." ): _RETURN_DATA["code"] = -1 _RETURN_DATA["content"] = error elif (error.get("code") == -1100): _RETURN_DATA["code"] = -1 _RETURN_DATA["content"] = error else: _RETURN_DATA = result _RETURN_DATA["code"] = -1 _RETURN_DATA["content"] = error return _RETURN_DATA else: tranaction = result.get("content") logger.debug("[{}][followbottom] - Content: {}".format( self.symbol, tranaction)) # if(tranaction.get("status") != "FILLED"): isloop = True # End error handler orderId = tranaction.get("orderId") clientOrderId = tranaction.get("clientOrderId") else: logger.debug("Waiting for filled!") result = self.query_order(_orderid=orderId, _origClientOrderId=clientOrderId) # Error handler if (result.get("code") != 1): error = result.get("content") logger.info("[{}][followbottom] - Code: {} | msg: {}".format( self.symbol, error.get("code"), error.get("msg"))) # _RETURN_DATA["profit"] = 0 # return _RETURN_DATA # End error handler _RETURN_DATA = result.get("content") logger.debug("[{}][followbottom] - Content: {}".format( self.symbol, _RETURN_DATA)) status = _RETURN_DATA.get("status") if (status == "FILLED"): _RETURN_DATA["code"] = 1 _RETURN_DATA["content"] = result.get("content") # profit = float(_limitprice) - buy_price # _RETURN_DATA["profit"] = round(profit, 8)*float(_quantity) break return _RETURN_DATA
def followtop(self, targeted_coin, _saferange, orderinfo=None): _RETURN_DATA = dict() _RETURN_DATA["code"] = -1 if (orderinfo == None): logger.debug("[{}][followtop][+] There is not orderinfo!".format( self.symbol)) else: logger.debug("[{}][followtop][+] orderinfo: {}".format( self.symbol, orderinfo)) orderId = orderinfo.get("orderId") clientOrderId = orderinfo.get("clientOrderId") _limitprice = orderinfo.get("price") buy_price = float(_limitprice) _quantity = orderinfo.get("origQty") logger.debug("[followtop] - orderId: {} | clientOrderID: {}".format( orderId, clientOrderId)) # Waiting for filled buy order isWait = True while (isWait): isWait = False time.sleep(1.337) result = self.query_order(_orderid=orderId, _origClientOrderId=clientOrderId) # Error handler if (result.get("code") != 1): error = result.get("content") logger.info("[{}][followtop] - Code: {} | msg: {}".format( self.symbol, error.get("code"), error.get("msg"))) isWait = True # End error handler _RETURN_DATA = result.get("content") tranaction = result.get("content") logger.debug("[{}][followtop] - Line 300: {}".format( self.symbol, tranaction)) status = _RETURN_DATA.get("status") if (tranaction.get("status") == "FILLED"): filled_quantity = tranaction.get("origQty") logger.info( "[{}][followtop] - Line 304 buy successfull! {} | {}". format(self.symbol, _limitprice, filled_quantity)) profit = float(_limitprice) - buy_price isWait = False _RETURN_DATA["profit"] = round(profit, 8) * float(filled_quantity) _RETURN_DATA["code"] = 1 _RETURN_DATA["content"] = tranaction return _RETURN_DATA # End waiting # Wait for always take profit nottakeprofit = True while (nottakeprofit): current_price = round(float(targeted_coin.get_current_price()), targeted_coin.lotsize) targeted_price = str( round( float(buy_price) + _saferange * _RANGEPRICE_, targeted_coin.lotsize)) # ID: 112233 logger.info( "[{}][followtop] - 112233 - wait for always taking profit currnet price {} | {}" .format(self.symbol, current_price, targeted_price)) if (current_price >= float(targeted_price)): nottakeprofit = False time.sleep(1.337) # End wait to take profit # Sell when filled buy order isloop = True while (isloop): isloop = False current_price = round(float(targeted_coin.get_current_price()), targeted_coin.lotsize) topprice = float(current_price) targeted_price = str( round( float(current_price) - _saferange * _RANGEPRICE_, targeted_coin.lotsize)) if (targeted_coin.lotsize == 8): targeted_price = "{:.8f}".format( round( float(current_price) - _saferange * _RANGEPRICE_, targeted_coin.lotsize)) result = self.sell(targeted_price, _quantity) # Error handler if (result.get("code") != 1): error = result.get("content") logger.info("[{}][followbottom] - Code: {} | msg: {}".format( self.symbol, error.get("code"), error.get("msg"))) if (error.get("code") == -2010 and error.get("msg") == "Stop price would trigger immediately." ): # Stop price would trigger immediately. isloop = True _saferange += _saferange * 0.2 time.sleep(1) elif (error.get("msg") == "Account has insufficient balance for requested action." ): _RETURN_DATA = result _RETURN_DATA["code"] = -1 _RETURN_DATA["content"] = error return _RETURN_DATA elif (error.get("code") == -1100): _RETURN_DATA = result _RETURN_DATA["code"] = -1 _RETURN_DATA["content"] = error return _RETURN_DATA else: _RETURN_DATA = result _RETURN_DATA["code"] = -1 _RETURN_DATA["content"] = error return _RETURN_DATA else: tranaction = result.get("content") logger.debug("[{}][followtop] - First sell: {}".format( self.symbol, tranaction)) if (tranaction.get("status") == "FILLED"): filled_quantity = tranaction.get("origQty") logger.info( "[{}][followtop] - Line 338 Sell successfull! {} | {}" .format(self.symbol, _limitprice, filled_quantity)) if (float(filled_quantity) == float(_quantity)): profit = float(_limitprice) - buy_price _RETURN_DATA["code"] = 1 _RETURN_DATA["content"] = tranaction _RETURN_DATA["profit"] = round( profit, 8) * float(filled_quantity) isloop = False return _RETURN_DATA else: _quantity = str( round((float(_quantity) - float(filled_quantity)), targeted_coin.stepsize)) orderId = tranaction.get("orderId") clientOrderId = tranaction.get("clientOrderId") # End # if price is increasing --> follow price. isloop = True while (isloop): time.sleep(_TIME_TO_DELAY_) current_price = round(float(targeted_coin.get_current_price()), targeted_coin.lotsize) if (current_price > topprice): topprice = current_price # Stop > limit if (targeted_coin.lotsize == 8): _stopprice = "{:.8f}".format( round((current_price - round(_saferange * _RANGEPRICE_, 8)), targeted_coin.lotsize)) else: _stopprice = str( round((current_price - _saferange * _RANGEPRICE_), targeted_coin.lotsize)) _limitprice = _stopprice self.cancel_order(_orderid=orderId, _origClientOrderId=clientOrderId) result = self.sell(_limitprice, _quantity) # result = result.decode("utf-8") # Error handler if (result.get("code") != 1): error = result.get("content") logger.info( "[{}][followbottom] - Code: {} | msg: {}".format( self.symbol, error.get("code"), error.get("msg"))) if (error.get("code") == -2010 and error.get("msg") == "Stop price would trigger immediately." ): # Stop price would trigger immediately. _saferange += _saferange * 0.5 time.sleep(1) elif (error.get( "msg" ) == "Account has insufficient balance for requested action." ): _RETURN_DATA = result _RETURN_DATA["code"] = -1 _RETURN_DATA["content"] = error return _RETURN_DATA elif (error.get("code") == -1100): _RETURN_DATA = result _RETURN_DATA["code"] = -1 _RETURN_DATA["content"] = error return _RETURN_DATA else: _RETURN_DATA = result _RETURN_DATA["code"] = -1 _RETURN_DATA["content"] = error return _RETURN_DATA else: tranaction = result.get("content") logger.debug( "[{}][followtop] - Create new order: {}".format( self.symbol, tranaction)) if (tranaction.get("status") == "FILLED"): filled_quantity = tranaction.get("origQty") logger.info( "[{}][followtop] - Line 399 Sell successfull! {} | {}" .format(self.symbol, _limitprice, filled_quantity)) isloop = False profit = float(_limitprice) - buy_price _RETURN_DATA["code"] = 1 _RETURN_DATA["content"] = tranaction _RETURN_DATA["profit"] = round( profit, 8) * float(filled_quantity) return _RETURN_DATA orderId = tranaction.get("orderId") clientOrderId = tranaction.get("clientOrderId") if (orderId == None): break # Double check order status isloopp = True while (isloopp): isloopp = False result = self.query_order(_orderid=orderId, _origClientOrderId=clientOrderId) # Error handler if (result.get("code") != 1): error = result.get("content") logger.info( "[{}][followtop] - Code: {} | msg: {}".format( self.symbol, error.get("code"), error.get("msg"))) isloopp = True # End error handler _RETURN_DATA = result.get("content") tranaction = result.get("content") logger.debug("[{}][followtop] - Query order: {}".format( self.symbol, tranaction)) status = _RETURN_DATA.get("status") if (tranaction.get("status") == "FILLED"): filled_quantity = tranaction.get("origQty") logger.info( "[{}][followtop] - Line 431 Sell successfull! {} | {}" .format(self.symbol, _limitprice, filled_quantity)) profit = float(_limitprice) - buy_price isloopp = False _RETURN_DATA["profit"] = round( profit, 8) * float(filled_quantity) _RETURN_DATA["code"] = 1 _RETURN_DATA["content"] = tranaction return _RETURN_DATA # End else: # Check order status again result = self.query_order(_orderid=orderId, _origClientOrderId=clientOrderId) # Error handler if (result.get("code") != 1): error = result.get("content") logger.info("[{}][followtop] - Code: {} | msg: {}".format( self.symbol, error.get("code"), error.get("msg"))) isloopp = True else: tranaction = result.get("content") # End error handler _RETURN_DATA = result.get("content") tranaction = result.get("content") logger.debug("[{}][followtop] - Content: {}".format( self.symbol, _RETURN_DATA)) status = _RETURN_DATA.get("status") if (tranaction.get("status") == "FILLED"): filled_quantity = tranaction.get("origQty") logger.info( "[{}][followtop] - Sell successfull! {} | {}".format( self.symbol, _limitprice, filled_quantity)) profit = float(_limitprice) - buy_price _RETURN_DATA["profit"] = round(profit, 8) * float(filled_quantity) _RETURN_DATA["code"] = 1 _RETURN_DATA["content"] = tranaction return _RETURN_DATA # end order status logger.debug("[{}][followtop] - Waiting for price...".format( self.symbol)) # End following price return _RETURN_DATA
def iscontinuetrade(_symbol): _api_ = _GENERAL_API_LIST["CANDLESTICK"] svrtime = get_general_api(_GENERAL_API_LIST["GETSVRTIME"]) if (svrtime.get("code") == 1): svrtime = svrtime.get("content") svrtime = svrtime.get("serverTime") else: logger.debug( "[{}][create_new_order] - Error code: {} | {} | {}".format( self.symbol, server.get("code"), server.get("content"), server.get("exception"))) return svrtime timestamp = svrtime + 3 starttime = timestamp - 60 * 5 * 60 params = "symbol={}&interval=5m".format(_symbol) rs = get_general_api(_api_, params) if (rs.get("code") == 1): logger.debug("[{}][coinanalyze] - Content: {}".format(_symbol, rs)) candles = rs.get("content")[::-1] candle_coins = dict() check = 0 while (check < 3): temp = dict() candle = candles[check] logger.debug("Open: {}".format(candle[1])) temp["open"] = candle[1] logger.debug("High: {}".format(candle[2])) temp["high"] = candle[2] logger.debug("Low: {}".format(candle[3])) temp["low"] = candle[3] logger.debug("Num of trades: {}".format(candle[8])) temp["numoftrades"] = candle[8] logger.debug("================") candle_coins[check] = temp check += 1 if (candle_coins[0].get("numoftrades") > 10): if (float(candle_coins[0].get("high")) > float( candle_coins[0].get("open"))): if (float(candle_coins[0].get("open")) > float( candle_coins[1].get("open")) and float(candle_coins[1].get("open")) > float( candle_coins[2].get("open"))): return True else: return False else: return False return False
def coinanalyze(_symbol): reborn = False _api_ = _GENERAL_API_LIST["CANDLESTICK"] svrtime = get_general_api(_GENERAL_API_LIST["GETSVRTIME"]) if (svrtime.get("code") == 1): svrtime = svrtime.get("content") svrtime = svrtime.get("serverTime") else: logger.debug( "[{}][create_new_order] - Error code: {} | {} | {}".format( self.symbol, server.get("code"), server.get("content"), server.get("exception"))) return svrtime timestamp = svrtime + 3 starttime = timestamp - 60 * 5 * 60 params = "symbol={}&interval=3m".format(_symbol) rs = get_general_api(_api_, params) if (rs.get("code") == 1): # logger.debug("[{}][coinanalyze] - Content: {}".format(_symbol, rs)) candles = rs.get("content")[::-1] candle_coins = dict() check = 0 while (check < 100): temp = dict() candle = candles[check] # logger.debug("Candle: {}".format(candle)) temp["open"] = candle[1] # logger.debug("High: {}".format(candle[2])) temp["high"] = candle[2] # logger.debug("Low: {}".format(candle[3])) temp["low"] = candle[3] temp["closed"] = candle[4] # logger.debug("Num of trades: {}".format(candle[8])) temp["numoftrades"] = candle[8] # logger.debug("================") candle_coins[check] = temp check += 1 count = 0 for i in candle_coins.keys(): if (i >= 100): break if (float(candle_coins[1].get("closed")) > float( candle_coins[0].get("open"))): count += 1 if (count >= 55): reborn = True else: return False else: return False params = "symbol={}&interval=5m".format(_symbol) rs = get_general_api(_api_, params) if (rs.get("code") == 1): # logger.debug("[{}][coinanalyze] - Content: {}".format(_symbol, rs)) candles = rs.get("content")[::-1] logger.debug("Dict: {}".format(candle_coins)) if (candle_coins[0].get("numoftrades") > 100): if (float(candle_coins[1].get("closed")) < float( candle_coins[0].get("open"))): if (float(candle_coins[2].get("closed")) < float( candle_coins[1].get("open"))): if (float(candle_coins[3].get("closed")) > float( candle_coins[2].get("open")) and reborn): logger.debug("Passed: {}".format(_symbol)) return True else: return False else: return False return False