Ejemplo n.º 1
0
def orders(update, context):
    client = Client(api_key=SKey, api_secret=PKey)
    data = client.futures_get_open_orders()
    if len(data) == 0:
        update.message.reply_text("Buddy, No Open Orders!")
    else:
        price = data[0]['price']
        side = data[0]['side']
        symbol = data[0]['symbol']
        qty = data[0]['origQty']
        a = qty + symbol
        data2 = client.futures_mark_price(symbol=symbol)
        currentprice = data2.get("markPrice")
        x = float(currentprice)
        xx = round(x, 3)
        ordertxt = "Open Orders:\nCurrent Price:{}USDT\n{} EXIT AT {} WITH {}"
        ordermsg = ordertxt.format(xx, a, price, side)
        update.message.reply_text(ordermsg)
Ejemplo n.º 2
0
class BinanceAPI:
    def __init__(self, api_key, api_secret):
        API_KEY = api_key
        API_SECRET = api_secret

        self.client = Client(API_KEY, API_SECRET)

    def get_ticker(self, pair):
        try:
            value = self.client.get_ticker(symbol=pair)
            return value
        except Exception as e:
            print("Exception : " + str(e))

    def get_current_price(self, pair):
        try:
            ticker = self.client.get_symbol_ticker(symbol=pair)
            value = ticker["price"]
            return float(value)
        except Exception as e:
            print("Exception : " + str(e))

    def get_klines(self, pair, number):
        try:
            klines = pd.DataFrame(
                self.client.get_klines(symbol=pair,
                                       interval=Client.KLINE_INTERVAL_30MINUTE,
                                       limit=number),
                columns=[
                    "OpenTime", "Open", "High", "Low", "Close", "Volume",
                    "CloseTime", "QuoteVolume", "TradeCount", "TakerVolume",
                    "TakerQuoteVolume", "Ignore"
                ])
            value = klines[[
                "OpenTime", "Close", "High", "Low", "Volume", "QuoteVolume",
                "TakerVolume", "TakerQuoteVolume", "TradeCount"
            ]].copy()
            value.loc[:, "OpenTime"] = pd.to_datetime(value["OpenTime"].apply(
                lambda x: datetime.fromtimestamp(int(x / 1000))))
            value = value.set_index("OpenTime")
            return value
        except Exception as e:
            print("Exception : " + str(e))

    def get_historical_klines(self, pair, start, end):
        try:
            klines = pd.DataFrame(self.client.get_historical_klines(
                start_str=start,
                end_str=end,
                symbol=pair,
                interval=Client.KLINE_INTERVAL_30MINUTE,
                limit=500),
                                  columns=[
                                      "OpenTime", "Open", "High", "Low",
                                      "Close", "Volume", "CloseTime",
                                      "QuoteVolume", "TradeCount",
                                      "TakerVolume", "TakerQuoteVolume",
                                      "Ignore"
                                  ])
            value = klines[[
                "OpenTime", "Close", "High", "Low", "Volume", "QuoteVolume",
                "TakerVolume", "TakerQuoteVolume", "TradeCount"
            ]].copy()
            value.loc[:, "OpenTime"] = pd.to_datetime(value["OpenTime"].apply(
                lambda x: datetime.fromtimestamp(int(x / 1000))))
            value = value.set_index("OpenTime")
            return value
        except Exception as e:
            print("Exception : " + str(e))

    def get_balance(self, symbol):
        try:
            value = self.client.get_asset_balance(asset=symbol)
            return value
        except Exception as e:
            print('Exception : {}'.format(e))

    def get_free_balance(self, symbol):
        try:
            value = self.client.get_asset_balance(asset=symbol)
            return float(value["free"])
        except Exception as e:
            print('Exception : {}'.format(e))

    def get_futures_balance(self, symbol):
        try:
            value = self.client.futures_account_balance()
            balance = [
                balance["balance"] for balance in value
                if balance["asset"] == symbol
            ]
            return float(str(*balance))
        except Exception as e:
            print('Exception : {}'.format(e))

    def create_limit_order(self, symbol, price, quantity, side_str):
        try:
            if side_str == "BUY":
                side = self.client.SIDE_BUY
            elif side_str == "SELL":
                side = self.client.SIDE_SELL
            order = self.client.order_limit(
                symbol=symbol,
                side=side,
                timeInForce=self.client.TIME_IN_FORCE_IOC,
                price=price,
                quantity=quantity)
            print(order)
            print(
                "buy order created.\nSymbol:{0:5}\nPrice:{1:5}\nQuantity:{2:5}",
                symbol, price, quantity)
        except Exception as e:
            print("Exception : " + str(e))

    def create_market_order(self, symbol, quantity, side_str):
        try:
            if side_str == "BUY":
                side = self.client.SIDE_BUY
            elif side_str == "SELL":
                side = self.client.SIDE_SELL
            order = self.client.order_market(symbol=symbol,
                                             side=side,
                                             quantity=quantity)
            print(order)
            print(
                "buy order created.\nSymbol:{0:5}\nPrice:{1:5}\nQuantity:{2:5}",
                symbol, price, quantity)
        except Exception as e:
            print("Exception : " + str(e))

    def create_test_order(self, symbol, quantity, side_str):
        try:
            if side_str == "BUY":
                side = self.client.SIDE_BUY
            elif side_str == "SELL":
                side = self.client.SIDE_SELL
            order = self.client.create_test_order(
                symbol=symbol,
                side=side,
                type=self.client.ORDER_TYPE_MARKET,
                quantity=quantity)
            print(order)
            print("buy order created.\nSymbol:{0:5}\nQuantity:{1:5}".format(
                symbol, quantity))
        except Exception as e:
            print("Exception : " + str(e))

    def create_futures_order(self, symbol, quantity, side_str):
        try:
            if side_str == "BUY":
                side = self.client.SIDE_BUY
            elif side_str == "SELL":
                side = self.client.SIDE_SELL
            order = self.client.futures_create_order(
                symbol=symbol,
                side=side,
                type=self.client.ORDER_TYPE_MARKET,
                quantity=quantity)
            #print(order)
            print("order created.\nSymbol:{0:5}\nQuantity:{1:5}".format(
                symbol, quantity))
        except Exception as e:
            print("Exception : " + str(e))

    def create_futures_stoploss_order(self, symbol, quantity, side_str, price):
        if side_str == "BUY":
            side = self.client.SIDE_BUY
        elif side_str == "SELL":
            side = self.client.SIDE_SELL
        order = self.client.futures_create_order(symbol=symbol,
                                                 stopPrice=price,
                                                 side=side,
                                                 type="STOP_MARKET",
                                                 quantity=quantity)
        #print(order)
        #print("order created.\nSymbol:{0:5}\nQuantity:{1:5}".format(symbol,quantity))

    def cancel_futures_orders(self, symbol):
        for i in range(0, 50):
            try:
                self.client.futures_cancel_all_open_orders(symbol=symbol)
            except Exception as e:
                print("Exception : " + str(e))
                continue
            break

    def get_open_futures_orders(self, symbol):
        try:
            result = self.client.futures_get_open_orders(symbol=symbol)
            return result
        except Exception as e:
            print("Exception : " + str(e))

    def get_base_asset(self, symbol):
        try:
            return self.client.get_symbol_info(symbol)["baseAsset"]
        except Exception as e:
            print("Exception : " + str(e))

    def get_quote_asset(self, symbol):
        try:
            return self.client.get_symbol_info(symbol)["quoteAsset"]
        except Exception as e:
            print("Exception : " + str(e))

    def get_all_tickers(self):
        try:
            return self.client.get_all_tickers()
        except Exception as e:
            print("Exception : " + str(e))

    def get_all_orders(self):
        try:
            return self.client.get_all_orders()
        except Exception as e:
            print("Exception : " + str(e))

    def get_trades_data(self, symbol, start, end):
        try:
            data = []
            value = self.client.get_aggregate_trades(symbol=symbol,
                                                     startTime=start,
                                                     endTime=end)
            value_max = [-float('inf'), -float('inf')]
            value_min = [float('inf'), float('inf')]
            #price = self.client.get_historical_klines(start_str = start, end_str = start + 60000, symbol=symbol, interval=Client.KLINE_INTERVAL_1MINUTE, limit=1)[0][1]
            for i in value:
                if len(data) == const.IMG_LENGTH:
                    break
                data.append(
                    [float(i["p"]),
                     float(i["q"]), 0.3 if i["m"] else 0.6])
            if len(data) < const.IMG_LENGTH:
                data += [[0.0, 0.0, 0.0]] * (const.IMG_LENGTH - len(data))
            data = data[:const.IMG_LENGTH]
            data = pd.DataFrame(data)
            data = (data - data.min()) / (data.max() - data.min())
            data = (data - data.mean()) / data.std()
            data = (data - data.min()) / (data.max() - data.min())
            return data.values.tolist()
        except Exception as e:
            print("Exception : " + str(e))
            data = []
            data += [[0.0, 0.0, 0.0]] * (const.IMG_LENGTH)
            return data