def ticker_price(self): url = self.price params = [("symbol", self.symbol)] res = requests.get(url=url, params=params) handle_error(res) price = res.json()["price"] return price
def get_open_orders(self): timestamp = int(round(tm.time() * 1000)) url = self.open_orders params = [("timestamp", timestamp), ("recvWindow", self.recvWindow)] headers = {"X-MBX-APIKEY": self.key} # Prepare request for signing r = requests.Request(url=url, params=params, headers=headers) prepped = r.prepare() query_string = urlparse(prepped.url).query total_params = query_string # Generate and append signature signature = hmac.new(self.secret.encode("utf-8"), total_params.encode("utf-8"), hashlib.sha256).hexdigest() params.append(("signature", signature)) res = requests.get(url=url, params=params, headers=headers) handle_error(res) data = res.json() if len(data) > 0: resp = jsonResp({ "message": "Open orders found!", "data": data }, 200) else: resp = jsonResp_message("No open orders found!", 200) return resp
def get_ticker_price(self, symbol): url = self.ticker_price params = {"symbol": symbol} res = requests.get(url=url, params=params) handle_error(res) data = res.json() return data["price"]
def matching_engine(self, order_side, qty, limit_index=0): """ Match quantity with available 100% fill order price, so that order can immediately buy/sell @param: order_side - Buy order = get ask prices = True Sell order = get bids prices = False @param: qty - quantity wanted to be bought @param: order_side - BUY or SELL """ url = self.order_book_url limit = EnumDefinitions.order_book_limits[limit_index] params = [("symbol", self.symbol), ("limit", limit)] res = requests.get(url=url, params=params) handle_error(res) data = res.json() if order_side: df = pd.DataFrame(data["bids"], columns=["price", "qty"]) else: df = pd.DataFrame(data["asks"], columns=["price", "qty"]) df["qty"] = df["qty"].astype(float) # If quantity matches list match_qty = df[df.qty > float(qty)] condition = df["qty"] > float(qty) if not condition.any(): limit_index += limit_index if limit_index == 4: return None self.matching_engine(order_side, qty, limit_index) final_qty = match_qty["price"].iloc[0] return final_qty
def ticker_24(self): url = self.ticker24_url symbol = request.view_args["symbol"] params = {"symbol": symbol} res = requests.get(url=url, params=params) handle_error(res) data = res.json() resp = jsonResp({"data": data}, 200) return resp
def get_listenkey(self): url = self.user_datastream_listenkey # Get data for a single crypto e.g. BTT in BNB market params = [] headers = {"X-MBX-APIKEY": self.key} url = self.user_datastream_listenkey # Response after request res = requests.post(url=url, params=params, headers=headers) handle_error(res) data = res.json() return data
def poll_historical_orders(self): global poll_percentage url = self.all_orders_url symbols = self.get_exchange_info()["symbols"] symbols_count = len(symbols) # Empty collection first self.app.db.orders.remove() with self.app.app_context(): for i in range(symbols_count): timestamp = int(round(tm.time() * 1000)) params = [ ("symbol", symbols[i]["symbol"]), ("timestamp", timestamp), ("recvWindow", self.recvWindow), ] headers = {"X-MBX-APIKEY": self.key} # Prepare request for signing r = requests.Request(url=url, params=params, headers=headers) prepped = r.prepare() query_string = urlparse(prepped.url).query total_params = query_string # Generate and append signature signature = hmac.new( self.secret.encode("utf-8"), total_params.encode("utf-8"), hashlib.sha256, ).hexdigest() params.append(("signature", signature)) res = requests.get(url=url, params=params, headers=headers) handle_error(res) data = res.json() # Check that we have no empty orders if (len(data) > 0) and self.app: for o in data: # Save in the DB self.app.db.orders.save( o, {"$currentDate": { "createdAt": "true" }}) if i == (symbols_count - 1): poll_percentage = 0 else: poll_percentage = round_numbers( (i / symbols_count) * 100, 0) print(f"Polling historical orders: {poll_percentage}")
def last_price(self, order_side="bids"): url = self.order_book_url limit = EnumDefinitions.order_book_limits[0] params = [("symbol", self.symbol), ("limit", limit)] res = requests.get(url=url, params=params) handle_error(res) data = res.json() if order_side == "bids": df = pd.DataFrame(data["bids"], columns=["price", "qty"]) elif order_side == "asks": df = pd.DataFrame(data["asks"], columns=["price", "qty"]) else: print("Incorrect bid/ask keyword for matching_engine") exit(1) price = df["price"].astype(float)[0] return price
def post_stop_loss_limit(self): data = request.json symbol = data["pair"] qty = data["qty"] price = data["price"] stop_price = data["stop_price"] if "stop_price" in data else price # Limit order order_type = EnumDefinitions.order_types[3] timestamp = int(round(tm.time() * 1000)) url = self.order_url # Get data for a single crypto e.g. BTT in BNB market params = [ ("recvWindow", self.recvWindow), ("timestamp", timestamp), ("symbol", symbol), ("side", self.side), ("type", order_type), ("timeInForce", self.timeInForce), ("price", price), ("stopPrice", stop_price), ("quantity", qty), ("newOrderRespType", "FULL"), ] headers = {"X-MBX-APIKEY": self.key} # Prepare request for signing r = requests.Request(url=url, params=params, headers=headers) prepped = r.prepare() query_string = urlparse(prepped.url).query total_params = query_string # Generate and append signature signature = hmac.new(self.secret.encode("utf-8"), total_params.encode("utf-8"), hashlib.sha256).hexdigest() params.append(("signature", signature)) # Response after request res = requests.post(url=url, params=params, headers=headers) handle_error(res) data = res.json() return data
def delete_all_orders(self): """ Delete All orders by symbol - Optimal for open orders table """ symbol = request.args["symbol"] timestamp = int(round(tm.time() * 1000)) url = self.open_orders # query params -> args # path params -> view_args symbol = request.args["symbol"] params = [ ("symbol", symbol), ("timestamp", timestamp), ("recvWindow", self.recvWindow), ] headers = {"X-MBX-APIKEY": self.key} # Prepare request for signing r = requests.Request(url=url, params=params, headers=headers) prepped = r.prepare() query_string = urlparse(prepped.url).query total_params = query_string # Generate and append signature signature = hmac.new(self.secret.encode("utf-8"), total_params.encode("utf-8"), hashlib.sha256).hexdigest() params.append(("signature", signature)) # Response after request res = requests.delete(url=url, params=params, headers=headers) handle_error(res) data = res.json() if len(data) > 0: resp = jsonResp({"message": "Orders deleted", "data": data}, 200) else: resp = jsonResp_message("No open orders found!", 200) return resp
def get_diff(self): today = datetime.today() first = today.replace(day=1) lastMonth = first - timedelta(days=1) # One month from today first_lastMonth = today - timedelta(days=lastMonth.day) startTime = int(round(first_lastMonth.timestamp() * 1000)) pair = request.view_args["pair"] interval = request.view_args["interval"] params = { "symbol": pair, "interval": interval, "limit": lastMonth.day, "startTime": startTime, } url = self.candlestick_url res = requests.get(url=url, params=params) handle_error(res) data = res.json() df = pd.DataFrame(data) # New df with dates and close df_new = df[[0, 3]] df_new[3].astype(float) close_prices = df_new[3].astype( float).pct_change().iloc[1:].values.tolist() dates = df_new[0].iloc[1:].values.tolist() trace = { "x": dates, "y": close_prices, "type": "scatter", "mode": "lines+markers", } resp = jsonResp( { "message": "Successfully retrieved data", "data": trace }, 200) return resp
def request_data(self): timestamp = int(round(tm.time() * 1000)) # Get data for a single crypto e.g. BTT in BNB market params = {"recvWindow": self.recvWindow, "timestamp": timestamp} headers = {"X-MBX-APIKEY": self.key} url = self.account_url # Prepare request for signing r = requests.Request("GET", url=url, params=params, headers=headers) prepped = r.prepare() query_string = urlparse(prepped.url).query total_params = query_string # Generate and append signature signature = hmac.new(self.secret.encode("utf-8"), total_params.encode("utf-8"), hashlib.sha256).hexdigest() params["signature"] = signature # Response after request res = requests.get(url=url, params=params, headers=headers) handle_error(res) data = res.json() return data
def _get_24_ticker(self, market): url = f"{self.bb_24_ticker_url}/{market}" res = requests.get(url=url) handle_error(res) data = res.json()["data"] return data
def _get_candlestick(self, market): url = f"{self.bb_candlestick_url}/{market}/{self.interval}" res = requests.get(url=url) handle_error(res) return res.json()
def _get_raw_klines(self, pair): params = {"symbol": pair, "interval": self.interval, "limit": "200"} res = requests.get(url=self.candlestick_url, params=params) handle_error(res) return res.json()