Ejemplo n.º 1
0
class Broker:

    def __init__(self, api_key, api_secret):
        self.client = Client(api_key, api_secret)

    def buy(self, coin, quantity):
        test_buy = self.client.create_test_order(symbol=coin, side=self.client.SIDE_BUY,\
            type=self.client.ORDER_TYPE_MARKET, quantity=quantity)

    def sell(self, coin, quantity):
        test_sell = self.client.create_test_order(symbol=coin, side=self.client.SIDE_SELL,\
            type=self.client.ORDER_TYPE_MARKET, quantity=quantity)
Ejemplo n.º 2
0
class BinanceUSDCConnector:

    def __init__(self):
        self.config = configparser.ConfigParser()
        self.config.read('setting.ini')
        self.api_key = self.config.get('binance_api', 'api_key')
        self.api_secret = self.config.get('binance_api', 'api_secret')
        self.client = Client(self.api_key, self.api_secret)

    def test_connect(self):
        """Test connectivity to the Rest API."""
        return self.client.ping()

    def get_exchange_info(self):
        """Return rate limits and list of symbols"""
        return self.client.get_exchange_info()

    def get_order_book(self, **kwargs):
        """Get the Order Book for the market"""
        return self.client.get_order_book(data=kwargs)

    def get_ticker(self, **kwargs):
        """24 hour price change statistics."""
        return self.client.get_ticker(data=kwargs)

    def get_24h_price_change(self, **kwargs):
        """24 hour price change statistics."""
        return self.client.get_ticker(data=kwargs)

    def get_latest_price(self, **kwargs):
        """Latest price for a symbol or symbols."""
        return self.client.get_symbol_ticker(data=kwargs)

    def test_new_order(self, **kwargs):
        """Test new order creation and signature/recvWindow long."""
        return self.client.create_test_order(data=kwargs)

    def create_order(self, order_type, **kwargs):
        """Send in a new order"""

        if order_type == 'limit':
            pass
        elif order_type == 'limit_buy':
            pass
        elif order_type == 'limit_sell':
            pass
        elif order_type == 'market':
            pass
        elif order_type == 'market_buy':
            pass
        elif order_type == 'market_sell':
            pass

    def check_order:

    def cancel_order:

    def get_open_order:

    def'''
Ejemplo n.º 3
0
class order_api(object):

	def __init__(self):
		self.client = Client("KCl8UvtnFcrlEgpqiwJlA0dr2SM3DuhKHHxiRtHA8oe7yl0JZYqas8oN2XNK0Lfz", "2wj46v8IAKpXoeigAmzfPg1VEjYi3oItNTeeNcEkDrK1HIev4nZHJr1Cd8tiJ5L0", {"verify": True, "timeout": 20})

	def get_all_orders(self,symbol='VENETH',limit=10):
		return self.get_all_orders(symbol,limit)

	# def create_order(self, symbol='VENETH', side='BUY', type=ORDER_TYPE_LIMIT, timeInForce=TIME_IN_FORCE_GTC, quantity=100, price='0.00001'):
		# self.client.create_order(symbol,side,type,timeInForce,quantity,price)

	# def create_sell_limit_order(self):
		# self.order = client.order_limit_buy(symbol,quantity,price)

	# def create_market_order(self):
		# pass

	def create_test_order(self,symbol,quantity,price):
		return self.client.create_test_order(symbol=symbol,quantity=quantity,price=price,side='BUY',type='LIMIT',timeInForce='GTC')

	def get_all_orders(self,symbol='VENETH'):
		return self.client.get_all_orders(symbol=symbol)

	def get_open_orders(self,symbol='VENETH'):
		return self.client.get_open_orders(symbol=symbol)

	def cancel_order(self,symbol='VENETH',orderId=0):
		return self.client.cancel_order(symbol=symbol,orderId=orderId)

	def order_status(self,symbol='VENETH',orderId=0):
		return self.client.get_order(symbol=symbol,orderId=orderId)
Ejemplo n.º 4
0
class BinanceAPIClient(BaseClient):
    """
    Wrapper for Binance API Python client
    """

    def __init__(self, *kwargs, **args):
        super().__init__(*kwargs, **args)
        api_key = os.getenv('binance_key')
        api_secret = os.getenv('binance_secret')
        self.client = Client(api_key, api_secret)

    def open_order(self, direction, price, quantity):
        return self.client.create_test_order(
            symbol=self.symbol,
            side=direction,
            type=ORDER_TYPE_LIMIT,
            timeInForce=TIME_IN_FORCE_GTC,
            quantity=quantity,
            price=price)

    def close_order(self):
        pass

    def get_orderbook(self):
        return self.client.get_order_book(symbol=self.symbol, limit=5)

    def get_balance(self):
        balance_response = self.client.get_asset_balance('EUR')
        return float(balance_response.get('free', 0))
Ejemplo n.º 5
0
class exchange:
    """
    建構式

    Args:
        apiKey (str): API金鑰
        apiSecret (str): API密鑰

    Returns:
        void
    """
    def __init__(self, apiKey: str, apiSecret: str):
        self.client = Client(apiKey, apiSecret)

    """
    取得當前價格

    Args:
        symbol (str): 要取得價格的標的,例BTCUSDT

    Returns:
        float: 當前的價格
    """

    def getSymbolPrice(self, symbol: str) -> float:
        prices = self.client.get_all_tickers()
        num = len(prices)
        price = 0
        for i in range(num):
            if symbol == prices[i]['symbol']:
                price = prices[i]['price']
        return price

    """
    進行交易

    Args:
        symbol (str): 要取得價格的標的,例BTCUSDT
        side (str): 要買進用buy,要賣出用sell
        quantity (float): 要買進的數量

    Returns:
        str: API response
    """

    def doExchange(self, symbol: str, side: str, quantity: float):
        sides = {'buy': Client.SIDE_BUY, 'sell': Client.SIDE_SELL}
        order = self.client.create_test_order(symbol=symbol,
                                              side=sides[side],
                                              type=Client.ORDER_TYPE_MARKET,
                                              quantity=quantity)
        return order
Ejemplo n.º 6
0
def binance_create_test_order(chat_id, **params):
    full_api = getbinanceapi(chat_id)['binance_api']
    api_key = full_api.split(':')[0].strip()
    api_secret = full_api.split(':')[1].strip()
    client = Client(api_key, api_secret)

    try:
        binance_timesync(client)

        js_info = client.create_test_order(**params)
        print(js_info)
    except Exception as e:
        print(e)
    return None
Ejemplo n.º 7
0
    def connectClient(self):

        client = Client(self.api_key, self.api_secret)

        # get market depth

        depth = client.get_order_book(symbol='BNBBTC')

        # place a test market buy order, to place an actual order use the create_order function
        order = client.create_test_order(
            symbol='BNBBTC',
            side=Client.SIDE_BUY,
            type=Client.ORDER_TYPE_MARKET,
            quantity=100)

        # get all symbol prices
        prices = client.get_all_tickers()

        # withdraw 100 ETH
        # check docs for assumptions around withdrawals
        from binance.exceptions import BinanceAPIException, BinanceWithdrawException
        try:
            result = client.withdraw(
                asset='ETH',
                address='<eth_address>',
                amount=100)
        except BinanceAPIException as e:
            print(e)
        except BinanceWithdrawException as e:
            print(e)
        else:
            print("Success")

        # fetch list of withdrawals
        withdraws = client.get_withdraw_history()

        # fetch list of ETH withdrawals
        eth_withdraws = client.get_withdraw_history(asset='ETH')

        # get a deposit address for BTC
        address = client.get_deposit_address(asset='BTC')
Ejemplo n.º 8
0
class binance_data():

    def __init__(self, api_key, api_secret):
        self.api_key = api_key
        self.api_secret = api_secret
        self.client = Client(api_key,api_secret)

    def get_order_book(self, symbol):

        order_book = self.client.get_order_book(symbol = symbol)

        bids = pd.DataFrame.from_dict(order_book["bids"]).iloc[:, 0:2]
        bids.columns = ['bid_price', 'bid_qty']

  
        asks = pd.DataFrame.from_dict(order_book["asks"]).iloc[:, 0:2]
        asks.columns = ['ask_price', 'ask_qty']
        
        data = pd.concat([asks, bids])

        return data


    def get_historical_klines(self, symbol, interval, start_str, end_str):
        return self.client.get_historical_klines(symbol, interval, start_str, end_str)

    def get_transactions(self, symbol):
        if isinstance(symbol,str):
            return self.client.get_recent_trades(symbol=symbol)
        else:
            raise Exception("Symbol should be an instance of string.")
    
    def test_order(self, symbol, quantity):
        test_order = self.client.create_test_order(
            symbol=symbol,
            side=Client.SIDE_BUY,
            type=Client.ORDER_TYPE_MARKET,
            quantity=quantity)
        return test_order
Ejemplo n.º 9
0
class BnOrder():
    def __init__(self) -> None:
        self.chat_id = BN_CHAT_ID_GROUP
        # self.chat_id = BN_CHAT_ID
        self.client = Client(BN_API_KEY, BN_API_SECRET)
        # self.client = Client(BN_TEST_API_KEY, BN_TEST_API_SECRET)
        # self.client.API_URL = 'https://testnet.binance.vision/api'
        self.client.PUBLIC_API_VERSION = "v3"
        self.bm = bn_UserSocket(self.client)
        self.tso = None

    def process_message(self, msg):
        try:
            self.send_chat_message("Account Update:\n" + json.dumps(msg))
        except Exception as e:
            logging.error("Process Account Update Error:" + str(e))
            self.send_chat_message("Process Account Update Error: " + str(e))

    def create_test_order(self, chat_id, symbol, buy_price, amount):
        try:
            if self.is_authorized(chat_id):
                symbol = symbol.strip().upper() + "BTC"
                logging.error("SYMBOL: " + symbol)

                order = self.client.create_test_order(
                    symbol=symbol,
                    side=SIDE_BUY,
                    type=ORDER_TYPE_LIMIT,
                    timeInForce=TIME_IN_FORCE_GTC,
                    quantity=amount,
                    price=buy_price)
                text = "TEST ORDER CREATED: " + json.dumps(order)
                self.send_chat_message(text)
        except Exception as e:
            logging.error("Test Order Failed error:" + str(e))
            self.send_chat_message("CREATE TEST ORDER FAILED: " + str(e))

    def create_market_buy(self, chat_id, symbol, amount, to_currency="BTC"):
        try:
            if self.is_authorized(chat_id):
                symbol = symbol.strip().upper() + to_currency.strip().upper()
                amount = round(amount, 8)
                order = self.client.order_market_buy(symbol=symbol,
                                                     quantity=amount)
                text = "REAL BUY CREATED: " + json.dumps(order)
                self.send_chat_message(text)
        except Exception as e:
            logging.error("Test Order Failed error:" + str(e))
            self.send_chat_message("CREATE ORDER FAILED: " + str(e))
            raise e

    def get_exchange_symbol(self, sell_coin, buy_coin):
        try:
            symbol = buy_coin.strip().upper() + sell_coin.strip().upper()
            info = self.client.get_symbol_info(symbol)
            if info is not None:
                result = self.client.get_symbol_ticker(symbol=symbol)
                s, t = self.get_step_size(info)
                return symbol, "BUY", result["price"], info, s, t
        except Exception as e:
            logging.error("Symbol fail:" + str(e))

        try:
            symbol = sell_coin.strip().upper() + buy_coin.strip().upper()
            info = self.client.get_symbol_info(symbol)
            if info is not None:
                result = self.client.get_symbol_ticker(symbol=symbol)
                s, t = self.get_step_size(info)
                return symbol, "SELL", result["price"], info, s, t
        except Exception as e:
            logging.error("Symbol fail:" + str(e))
            raise e

    def get_step_size(self, info):
        step_size = 0.0
        tick_size = 0.0
        logging.error("INFO:" + json.dumps(info))
        for f in info['filters']:
            if f['filterType'] == 'LOT_SIZE':
                step_size = float(f['stepSize'])
            if f['filterType'] == 'PRICE_FILTER':
                tick_size = float(f['tickSize'])
        return step_size, tick_size

    def create_market_conversion(self, chat_id, sell_coin, total_spend,
                                 buy_coin):
        try:
            if self.is_authorized(chat_id):
                symbol, sale_type, price, _, step_size, _ = self.get_exchange_symbol(
                    sell_coin, buy_coin)
                precision = int(round(-math.log(step_size, 10), 0))

                logging.error("AMOUNT:" + str(total_spend))
                logging.error("step_size:" + str(step_size))
                logging.error("precision:" + str(precision))

                logging.error("SALE TYPE:" + str(sale_type))
                if sale_type == "SELL":
                    amt_str = "{:0.0{}f}".format(total_spend, precision)
                    logging.error("QUANTITY:" + str(amt_str))
                    order = self.client.order_market_sell(symbol=symbol,
                                                          quantity=amt_str)
                    text = "SELL " + str(
                        amt_str) + " of " + symbol + "\nOrderId:" + str(
                            order["orderId"]) + " STATUS:" + str(
                                order["status"]) + "\nFILLS:\n" + json.dumps(
                                    order["fills"])

                else:
                    amount = total_spend / float(price)
                    amt_str = "{:0.0{}f}".format(amount, precision)
                    logging.error("QUANTITY:" + str(amt_str))
                    order = self.client.order_market_buy(symbol=symbol,
                                                         quantity=amt_str)
                    text = "BUY " + str(
                        amt_str) + " of " + symbol + "\nOrderId:" + str(
                            order["orderId"]) + " STATUS:" + str(
                                order["status"]) + "\nFILLS:\n" + json.dumps(
                                    order["fills"])
                self.send_chat_message(text)
                return amt_str, sale_type, symbol, buy_coin, sell_coin
        except Exception as e:
            logging.error("Order Failed error:" + str(e))
            self.send_chat_message("CREATE ORDER FAILED: " + str(e))
            raise e

    def create_trailing_stop_limit(self, market, buy_coin, sell_coin, type,
                                   stop_percentage, interval):
        try:
            if self.tso is not None and self.tso.running is True:
                self.send_chat_message(
                    "OPEN Trailing Stop Limit, Cancel First. ")
            else:
                self.tso = TrailingStopLimit(chat_id=self.chat_id,
                                             client=self.client,
                                             market=market,
                                             buy_coin=buy_coin,
                                             sell_coin=sell_coin,
                                             type=type,
                                             stop_percentage=stop_percentage,
                                             interval=interval)
                run(self.tso)
        except Exception as e:
            logging.error("Order Failed error:" + str(e))
            self.send_chat_message("CREATE ORDER FAILED: " + str(e))
            raise e

    def create_oco_conversion(self, chat_id, sell_coin, amount, buy_coin):
        try:
            if self.is_authorized(chat_id):
                symbol, sale_type, price, info, step_size, price_tick_size = self.get_exchange_symbol(
                    sell_coin, buy_coin)
                precision = int(round(-math.log(step_size, 10), 0))
                amt_str = "{:0.0{}f}".format(float(amount), precision)
                price_precision = int(round(-math.log(price_tick_size, 10), 0))
                logging.error("QUANTITY:" + str(amt_str))
                if sale_type == "SELL":
                    # BUY Orders: Limit Price < Last Price < Stop Price
                    sell_price = "{:0.0{}f}".format(
                        float(price) * 0.97, price_precision)
                    stop_price = "{:0.0{}f}".format(
                        float(price) * 1.01, price_precision)
                    stop_limit_price = "{:0.0{}f}".format(
                        float(price) * 1.01, price_precision)
                    order_oco = self.client.create_oco_order(
                        symbol=symbol,
                        side='BUY',
                        quantity=amt_str,
                        price=sell_price,
                        stopPrice=stop_price,
                        stopLimitPrice=stop_limit_price,
                        stopLimitTimeInForce='GTC')
                else:
                    # TODO check filters
                    # quantity >= minQty
                    # quantity <= maxQty
                    # (quantity-minQty) % stepSize == 0
                    # SELL Orders: Limit Price > Last Price > Stop Price
                    sell_price = "{:0.0{}f}".format(
                        float(price) * 1.03, price_precision)
                    stop_price = "{:0.0{}f}".format(
                        float(price) * 0.99, price_precision)
                    stop_limit_price = "{:0.0{}f}".format(
                        float(price) * 0.989, price_precision)
                    logging.error("CURRENT PRICE: " + str(price) +
                                  "   SELL PRICE: " + str(sell_price) +
                                  "  STOP PRICE:" + str(stop_price) +
                                  "  STOP LIMIT PRICE:" +
                                  str(stop_limit_price))
                    order_oco = self.client.create_oco_order(
                        symbol=symbol,
                        side='SELL',
                        quantity=amt_str,
                        price=sell_price,
                        stopPrice=stop_price,
                        stopLimitPrice=stop_limit_price,
                        stopLimitTimeInForce='GTC')

                oco_text = order_oco[
                    "listOrderStatus"] + " " + self.format_orders(
                        order_oco["orderReports"])
                self.send_chat_message(oco_text)
        except Exception as e:
            logging.error("OCO Failed error:" + str(e))
            self.send_chat_message("CREATE OCO FAILED: " + str(e))
            raise e

    def format_orders(self, orders):
        oco_text = "OPEN ORDERS:\n"
        for o in orders:
            if o["type"] == "STOP_LOSS_LIMIT":
                oco_text = oco_text + "\nSTOP LOSS:\n" + o["side"] + " " + o[
                    "symbol"] + "- Stop Limit: " + o[
                        "stopPrice"] + " Price: " + o["price"] + " Qty:" + o[
                            "origQty"] + "\n"
            elif o["type"] == "LIMIT_MAKER":
                oco_text = oco_text + "\nPROFIT:\n" + o["side"] + " " + o[
                    "symbol"] + "- Price: " + o["price"] + " Qty:" + o[
                        "origQty"] + "\n"
            else:
                oco_text = oco_text + "\n" + json.dumps(o) + "\n"
        oco_text = oco_text + "\nCheck Order Status with: /checkorders\n"
        oco_text = oco_text + "\nCancel All Orders with: /cancelorders\n"
        return oco_text

    def create_order(self, chat_id, selling_coin, buying_coin, price, amount):
        try:
            if self.is_authorized(chat_id):
                symbol, sale_type, price, info, step_size = self.get_exchange_symbol(
                    selling_coin, buying_coin)
                precision = int(round(-math.log(step_size, 10), 0))
                if sale_type == "SELL":
                    amt_str = "{:0.0{}f}".format(float(amount), precision)
                    order = self.client.order_limit_sell(symbol=symbol,
                                                         quantity=amt_str,
                                                         price=round(
                                                             float(price), 5))
                else:
                    amt_str = "{:0.0{}f}".format(float(amount), precision)
                    order = self.client.order_limit_buy(symbol=symbol,
                                                        quantity=amt_str,
                                                        price=round(
                                                            float(price), 5))
                text = "LIMIT ORDER CREATED:\n" + json.dumps(order)
                self.send_chat_message(text)

                # self.last_order_id = order['orderId']
                # saved_orders = r.get(LIVE_ORDER_KEY.format(self.chat_id))
                # if saved_orders is None:
                #     r.set(LIVE_ORDER_KEY.format(self.chat_id), json.dumps({"orders": [order]}))
                # else:
                #     ar = json.loads(saved_orders.decode("utf-8"))
                #     ar["orders"].append(order)
                #     r.set(LIVE_ORDER_KEY.format(self.chat_id), json.dumps(ar))
                self.check_orders(chat_id=chat_id)

        except Exception as e:
            logging.error("Test Order Failed error:" + str(e))
            self.send_chat_message("CREATE ORDER FAILED: " + str(e))

    def check_orders(self, chat_id):
        try:
            if self.is_authorized(chat_id):
                orders = self.client.get_open_orders()
                self.send_chat_message(self.format_orders(orders))

                # saved_orders = r.get(LIVE_ORDER_KEY.format(self.chat_id))
                # if saved_orders is not None:
                #     ar = json.loads(saved_orders.decode("utf-8"))
                #     self.send_chat_message("SAVED ORDERS: " + json.dumps(ar))

        except Exception as e:
            logging.error("Check Order Failed error:" + str(e))
            self.send_chat_message("CHECK ORDERS FAILED: " + str(e))

    def cancel_open_orders(self, chat_id):
        try:
            if self.is_authorized(chat_id):
                if self.tso is not None:
                    self.tso.running = False
                    FORCE_STOP = True
                orders = self.client.get_open_orders()
                for order in orders:
                    result = self.client.cancel_order(symbol=order['symbol'],
                                                      orderId=order["orderId"])
                    text = "CANCEL RESULT:\n" + json.dumps(result)
                    self.send_chat_message(text)

        except Exception as e:
            logging.error("Cancel Order Failed error:" + str(e))
            orders = self.client.get_open_orders()
            if len(orders) > 0:
                self.send_chat_message("FAILED TO CANCEL ORDER: " + str(e))

    def get_usd_price(self, symbol):
        usd_price = 0
        try:
            usd_price = self.client.get_symbol_ticker(symbol=symbol.upper() +
                                                      "USDT")
            return usd_price["price"]
        except Exception as e:
            logging.error("USD Price Failed error:" + symbol + " -- " + str(e))
        return usd_price

    def get_btc_price(self, symbol):
        btc_price = 0
        try:
            btc_price = self.client.get_symbol_ticker(symbol=symbol.upper() +
                                                      "BTC")
            return btc_price["price"]
        except Exception as e:
            logging.error("BTC Price Failed error:" + symbol + " -- " + str(e))
        return btc_price

    def round_sense(self, price):
        price = float(price)
        if price is None or price == 0:
            return 0
        if price > 1000:
            return int(price)
        if price > 100:
            return round(price, 1)
        if price > 10:
            return round(price, 2)
        if price > 0.01:
            return round(price, 4)
        if price > 0.001:
            return round(price, 5)
        return round(price, 8)

    def get_user_balance(self, symbol):
        try:
            balance = self.client.get_asset_balance(asset=symbol)
            logging.error("CHeck" + json.dumps(balance))
            return float(balance["free"])
        except Exception as e:
            logging.error("Account settings error:" + str(e))
            self.send_chat_message("FAILED TO GET BALANCE: " + str(e))
            return 0

    def get_wallet(self, chat_id):
        try:
            if self.is_authorized(chat_id):
                info = self.client.get_account()
                balances = info["balances"]
                # "balances": [{"asset": "BNB", "free": "1014.21000000", "locked": "0.00000000"}, {"asset": "BTC", "free": "0.92797152", "locked": "0.00000000"}, {"asset": "BUSD", "free": "10000.00000000", "locked": "0.00000000"}, {"asset": "ETH", "free": "100.00000000", "locked": "0.00000000"}, {"asset": "LTC", "free": "500.00000000", "locked": "0.00000000"}, {"asset": "TRX", "free": "500000.00000000", "locked": "0.00000000"}, {"asset": "USDT", "free": "10000.00000000", "locked": "0.00000000"}, {"asset": "XRP", "free": "50000.00000000", "locked": "0.00000000"}]
                out = "<pre>FREE       LOCKED      BTC      USD\n"
                val = 0
                btc_val = 0
                for b in balances:
                    quantity = float(b["free"]) + float(b["locked"])
                    if quantity > 0:
                        if b["asset"].upper() != "BETH":
                            usd_price = float(self.get_usd_price(b["asset"]))
                            btc_price = float(self.get_btc_price(b["asset"]))
                            if b["asset"].upper() in ["BUSD", "USDT"]:
                                usd_value = float(b["free"]) + float(
                                    b["locked"])
                                if btc_price > 0:
                                    btc_value = usd_value / btc_price
                                else:
                                    btc_value = 0
                            else:
                                usd_value = usd_price * quantity
                                if b["asset"].upper() == "BTC":
                                    btc_price = 1
                                    btc_value = float(b["free"]) + float(
                                        b["locked"])
                                else:
                                    btc_value = btc_price * quantity
                            val = val + usd_value
                            btc_val = btc_val + btc_value
                            out = out + "\n" + b["asset"] + " @ $" + str(
                                round(usd_price,
                                      2)) + " BTC" + str(btc_price) + "\n"
                            out = out + str(self.round_sense(b["free"])).ljust(
                                10, ' ') + " " + str(
                                    self.round_sense(b["locked"])).ljust(
                                        8, ' ') + " " + str(
                                            self.round_sense(btc_value)
                                        ).ljust(8, ' ') + " " + str(
                                            self.round_sense(usd_value)) + "\n"
                out = out + "</pre>\n$" + str(round(val, 2)) + "\n₿" + str(
                    round(btc_val, 6))
                self.send_chat_message(out)

        except Exception as e:
            logging.error("Account settings error:" + str(e))
            self.send_chat_message("FAILED TO GET WALLET: " + str(e))

    def send_chat_message(self, text):
        try:
            bot_key = TELEGRAM_BOT
            send_message_url = f'https://api.telegram.org/bot{bot_key}/sendMessage?chat_id={self.chat_id}&text={text}&parse_mode=HTML'
            resp = requests.post(send_message_url)
        except Exception as e:
            logging.error("Failed to send chat message:" + str(e))

    def is_authorized(self, chat_id):
        if self.chat_id is None or int(self.chat_id) != int(chat_id):
            raise Exception("Unauthorized Chat, use only correct chat.")
        starter = self.bm.start_user_socket(self.process_message)
        logging.error("Stream resp:" + str(starter))
        return True

    def get_symbol_trades(self, chat_id, symbol):
        try:
            if self.is_authorized(chat_id):
                trades = self.client.get_my_trades(symbol=symbol.upper() +
                                                   'BTC')
                if len(trades) > 0:
                    sorted_trades = sorted(trades,
                                           key=lambda k: k['time'],
                                           reverse=True)
                    out = "<pre>DATE TIME    SYMBOL   SIDE    PRICE     QUANTITY\n"
                    for t in sorted_trades:
                        if t["isBuyer"] == True:
                            action = "BUY"
                        else:
                            action = "SELL"
                        time_str = datetime.datetime.fromtimestamp(
                            int(t["time"]) / 1000).strftime('%d-%m %H:%M')
                        out = out + time_str + "  " + t[
                            "symbol"] + "  " + action + "  " + t[
                                "price"] + "   " + t["qty"] + "\n"
                    out = "TRADES vs BTC:\n" + out + "</pre>"
                    self.send_chat_message(out)

                trades = self.client.get_my_trades(symbol=symbol.upper() +
                                                   'USDT')
                if len(trades) > 0:
                    sorted_trades = sorted(trades,
                                           key=lambda k: k['time'],
                                           reverse=True)
                    out = "<pre>DATE TIME    SYMBOL   SIDE    PRICE     QUANTITY\n"
                    for t in sorted_trades:
                        if t["isBuyer"] == True:
                            action = "BUY"
                        else:
                            action = "SELL"
                        time_str = datetime.datetime.fromtimestamp(
                            int(t["time"]) / 1000).strftime('%d-%m %H:%M')
                        out = out + time_str + "  " + t[
                            "symbol"] + "  " + action + "  " + t[
                                "price"] + "   " + t["qty"] + "\n"
                    out = "TRADES vs USDT:\n" + out + "</pre>"
                    self.send_chat_message(out)
        except Exception as e:
            logging.error("Failed to get trades for symbol chat message:" +
                          str(e))
            self.send_chat_message("Failed to get trades for " + symbol +
                                   " -- " + str(e))
Ejemplo n.º 10
0
 def create_test_order(self, pair, side, type, quantity):
     return _Client.create_test_order(self,
                                      symbol=pair[0] + pair[1],
                                      side=side,
                                      type=type,
                                      quantity=quantity)
Ejemplo n.º 11
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("buy order created.\nSymbol:{0:5}\nQuantity:{1:5}".format(symbol,quantity))
        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))
Ejemplo n.º 12
0
class FXConnector(Logger):
    ORDER_STATUS_NEW = 'NEW'
    ORDER_STATUS_PARTIALLY_FILLED = 'PARTIALLY_FILLED'
    ORDER_STATUS_FILLED = 'FILLED'
    ORDER_STATUS_CANCELED = 'CANCELED'
    ORDER_STATUS_PENDING_CANCEL = 'PENDING_CANCEL'
    ORDER_STATUS_REJECTED = 'REJECTED'
    ORDER_STATUS_EXPIRED = 'EXPIRED'

    SIDE_BUY = 'BUY'
    SIDE_SELL = 'SELL'

    ORDER_TYPE_LIMIT = 'LIMIT'
    ORDER_TYPE_MARKET = 'MARKET'
    ORDER_TYPE_STOP_LOSS = 'STOP_LOSS'
    ORDER_TYPE_STOP_LOSS_LIMIT = 'STOP_LOSS_LIMIT'
    ORDER_TYPE_TAKE_PROFIT = 'TAKE_PROFIT'
    ORDER_TYPE_TAKE_PROFIT_LIMIT = 'TAKE_PROFIT_LIMIT'
    ORDER_TYPE_LIMIT_MAKER = 'LIMIT_MAKER'

    TIME_IN_FORCE_GTC = 'GTC'  # Good till cancelled
    TIME_IN_FORCE_IOC = 'IOC'  # Immediate or cancel
    TIME_IN_FORCE_FOK = 'FOK'  # Fill or kill

    ORDER_RESP_TYPE_ACK = 'ACK'
    ORDER_RESP_TYPE_RESULT = 'RESULT'
    ORDER_RESP_TYPE_FULL = 'FULL'

    def __init__(self, key=None, secret=None):
        super().__init__()
        self.__key = key
        self.__secret = secret
        self.client = Client(key, secret)
        self.bs: BinanceWebsocket = None

        # self.connection = None
        self.ticker_connection = None
        self.user_data_connection = None

    def listen_symbols(self, symbols, on_ticker_received, user_data_handler):
        self.bs = BinanceWebsocket(self.client)
        self.bs.start_ticker(symbols, on_ticker_received)
        self.bs.start_user_info(user_data_handler)

        self.logInfo('Ticker and User WS initialized')

    def start_listening(self):
        self.bs.start()
        self.logInfo('WS listening started')

    def stop_listening(self):
        self.bs.stop_sockets()
        self.logInfo('Socket stopped')

    @retry(**DEFAULT_RETRY_SETTINGS)
    def cancel_order(self, sym, id):
        return self.client.cancel_order(symbol=sym, orderId=id)

    @retry(**DEFAULT_RETRY_SETTINGS)
    def cancel_open_orders(self, sym):
        orders = self.get_open_orders(sym)
        if orders:
            for order_id in orders:
                self.client.cancel_order(symbol=sym, orderId=order_id)

    def get_server_time(self):
        return self.client.get_server_time()

    @retry(**DEFAULT_RETRY_SETTINGS)
    def get_open_orders(self, sym):
        return [o['orderId'] for o in self.client.get_open_orders(symbol=sym)]

    @retry(**DEFAULT_RETRY_SETTINGS)
    def get_all_orders(self, sym, limit=500):
        return {
            o['orderId']: {
                'status': o['status'],
                'price': o['price'],
                'stop_price': o['stopPrice'],
                'vol': o['origQty'],
                'vol_exec': o['executedQty']
            }
            for o in self.client.get_all_orders(symbol=sym, limit=limit)
        }

    @retry(**DEFAULT_RETRY_SETTINGS)
    def get_all_tickers(self):
        return self.client.get_all_tickers()

    @retry(**DEFAULT_RETRY_SETTINGS)
    def get_orderbook_tickers(self):
        return self.client.get_orderbook_tickers()

    @retry(**DEFAULT_RETRY_SETTINGS)
    def get_order_status(self, sym, id):
        return self.client.get_order(symbol=sym, orderId=id)

    # @retry(stop_max_attempt_number=MAX_ATTEMPTS, wait_fixed=DELAY)
    def create_makret_order(self, sym, side, volume):
        return self.client.create_order(
            symbol=sym,
            side=side,
            type=FXConnector.ORDER_TYPE_MARKET,
            quantity=FXConnector.format_number(volume))

    # @retry(stop_max_attempt_number=MAX_ATTEMPTS, wait_fixed=DELAY)
    def create_limit_order(self, sym, side, price, volume):
        return self.client.create_order(
            symbol=sym,
            side=side,
            type=FXConnector.ORDER_TYPE_LIMIT,
            timeInForce=FXConnector.TIME_IN_FORCE_GTC,
            quantity=FXConnector.format_number(volume),
            price=FXConnector.format_number(price))

    # @retry(stop_max_attempt_number=MAX_ATTEMPTS, wait_fixed=DELAY)
    def create_stop_order(self, sym, side, stop_price, price, volume):
        return self.client.create_order(
            symbol=sym,
            side=side,
            type=FXConnector.ORDER_TYPE_STOP_LOSS_LIMIT,
            timeInForce=FXConnector.TIME_IN_FORCE_GTC,
            quantity=FXConnector.format_number(volume),
            stopPrice=FXConnector.format_number(stop_price),
            price=FXConnector.format_number(price))

    # @retry(stop_max_attempt_number=MAX_ATTEMPTS, wait_fixed=DELAY)
    def create_test_stop_order(self, sym, side, price, volume):
        return self.client.create_test_order(
            symbol=sym,
            side=side,
            type=FXConnector.ORDER_TYPE_STOP_LOSS_LIMIT,
            timeInForce=FXConnector.TIME_IN_FORCE_GTC,
            quantity=FXConnector.format_number(volume),
            stopPrice=FXConnector.format_number(price),
            price=FXConnector.format_number(price))

    @retry(**DEFAULT_RETRY_SETTINGS)
    def get_balance(self, asset):
        bal = self.client.get_asset_balance(asset=asset)
        return float(bal['free']), float(bal['locked'])

    @retry(**DEFAULT_RETRY_SETTINGS)
    def get_all_balances(self, assets: dict):
        res = self.client.get_account()

        if 'balances' in res:
            for bal in res['balances']:
                if bal['asset'] in assets:
                    assets[bal['asset']] = {
                        'f': float(bal['free']),
                        'l': float(bal['locked'])
                    }

    @retry(**DEFAULT_RETRY_SETTINGS)
    def get_all_balances_dict(self):
        res = self.client.get_account()

        if 'balances' in res:
            return {
                bal['asset']: {
                    'f': float(bal['free']),
                    'l': float(bal['locked'])
                }
                for bal in res['balances']
            }

        return {}

    @retry(**DEFAULT_RETRY_SETTINGS)
    def get_exchange_info(self):
        return self.client.get_exchange_info()
        # info = self.client.get_exchange_info()
        #
        # symbol_info = None
        # for s in info['symbols']:
        #     if s['symbol'] == sym:
        #         symbol_info = s
        #         break
        #
        # props = {}
        # for f in symbol_info['filters']:
        #     props.update(f)
        #
        # props.pop('filterType', None)
        #
        # return FXConnector.ExchangeInfo(**props)

    @classmethod
    def format_number(cls, num):
        return '{:.08f}'.format(num)
Ejemplo n.º 13
0
class Interface:
    def __init__(self):
        self.binanceClient = BinanceClient(BinanceSettings.api_key,
                                           BinanceSettings.api_secret)
        self.gdax_public_client = GdaxPublicClient()
        self.gdax_authenticated_client = GdaxAuthenticatedClient(
            key=GdaxSettings.api_key,
            b64secret=GdaxSettings.api_secret,
            passphrase=GdaxSettings.api_passphrase)
        self.sandbox_gdax_authenticated_client = GdaxAuthenticatedClient(
            key=GdaxSettings.sandbox_key,
            b64secret=GdaxSettings.sandbox_secret,
            passphrase=GdaxSettings.sandbox_passphrase,
            api_url='https://api-public.sandbox.gdax.com')
        self.kraken_public_client = KrakenAPI()

        self.MARKET_BINANCE = 'binance'
        self.MARKET_GDAX = 'gdax'
        self.MARKET_KRAKEN = 'kraken'

    def get_prices(self, exchange):
        if exchange == self.MARKET_BINANCE:
            market_books = self.binanceClient.get_products_and_prices()
        elif exchange == self.MARKET_GDAX:
            market_books = self.gdax_public_client.get_products_with_prices()
        elif exchange == self.MARKET_KRAKEN:
            market_books = self.kraken_public_client.get_market_tickers()
        else:
            print("No exchange found with name: " + exchange)
            # TODO throw exception
        return market_books

    def create_test_order(self,
                          exchange,
                          symbol,
                          side,
                          limit_market,
                          quantity,
                          price=0.0):
        if exchange == self.MARKET_BINANCE:
            response = self.binanceClient.create_test_order(symbol=symbol,
                                                            side=side,
                                                            type=limit_market,
                                                            quantity=quantity,
                                                            price=price,
                                                            timeInForce="GTC")
            print("order is filled")
            # The binance test order does not actually get passed to the matching engine, so we're unable to test this.

        if exchange == self.MARKET_GDAX:
            symbol_reformatted = symbol[:3] + "-" + symbol[
                3:]  # TODO is this correct?
            response = self.sandbox_gdax_authenticated_client.create_order(
                symbol=symbol_reformatted,
                side=side,
                limit_market=limit_market,
                quantity=quantity,
                price=price)
            order_id = response["id"]
            order_filled = False
            while not order_filled:
                order = self.sandbox_gdax_authenticated_client.get_order(
                    order_id)
                if order["status"] == "done":
                    print("order is filled!")
                    order_filled = True
                else:
                    print("order not yet filled")
                    time.sleep(5)

    def create_order(self,
                     exchange,
                     symbol,
                     side,
                     limit_market,
                     quantity,
                     price=0.0):
        if exchange == self.MARKET_BINANCE:
            order = self.binanceClient.create_order(symbol,
                                                    side,
                                                    quantity,
                                                    price,
                                                    type=limit_market)
        elif exchange == self.MARKET_GDAX:
            order = self.gdax_authenticated_client.create_order(
                symbol, side, limit_market, quantity, price)
        else:
            print("No exchange found with name: " + exchange)
            # TODO throw exception
        print(order)

    def order_filled(self, exchange, order_id):
        if exchange == self.MARKET_BINANCE:
            return self.binanceClient.get_order(order_id)['status'] == 'done'
        elif exchange == self.MARKET_GDAX:
            return self.gdax_authenticated_client.get_order(
                order_id)['status'] == 'done'
        else:
            return ''
Ejemplo n.º 14
0
         Tradingpair=Symbol, Timeinterval=Timeframe))
 print("Price = " + str(ClosePriceVector[-1]))
 print("RSI = " + str(RSI))
 print("StochRSIK = " + str(StochRSIK))
 print("StochRSID = " + str(StochRSID))
 print("Money Flow = " + str(MoneyFlow))
 print("Time = " + str(TimeVector[-1]))
 print("")
 if BuyVariable == 1 and LiveTrades == 1:
     for i in key:
         if i == Symbol[:len(i)]:
             print("Buy Order Placed")
             try:
                 order = client.create_test_order(
                     symbol=Symbol,
                     side=Client.SIDE_BUY,
                     type=client.ORDER_TYPE_MARKET,
                     quantity=ExtraUsefulCode.quantity(
                         Symbol[:len(i)], Symbol, client))
                 print("Quantity being bought: " +
                       ExtraUsefulCode.quantity(
                           Symbol[:len(i)], Symbol, client))
             except:
                 order = client.create_test_order(
                     symbol=Symbol,
                     side=Client.SIDE_BUY,
                     type=client.ORDER_TYPE_MARKET,
                     quantity=1000 * float(
                         client.get_symbol_info(symbol=Symbol)
                         ['filters'][2]['stepSize']))
                 print("Quantity being bought: " + 1000 * float(
                     client.get_symbol_info(
Ejemplo n.º 15
0
class Binance(object):
    def __init__(self):
        print("-- Connecting to binance ...")
        self.client = Client(os.environ['BINANCE_API_KEY'],
                             os.environ['BINANCE_API_SECRET'])

    def get_balance(self, coin):
        print("-- Getting balance for " + coin)
        assetJSON = self.client.get_asset_balance(coin)
        return float(assetJSON['free'])

    def get_price(self, coin, coinfrom):
        priceJSON = self.client.get_symbol_ticker(symbol=coin + coinfrom)
        return float(priceJSON['price'])

    def buy_market(self, coin, coinfrom, ignored, quantity, testmode):
        print("-- Buying market " + str(quantity) + " " + coin + " from " +
              coinfrom)
        self.symbol = coin + coinfrom
        if testmode:
            print("[TEST] " + str(quantity) + " " + coin + " buy at : " +
                  str(ignored) + " " + coinfrom +
                  " (price is ignored on Binance)")
        else:
            orderBuy = self.client.create_order(
                symbol=coin + coinfrom,
                side=self.client.SIDE_BUY,
                type=self.client.ORDER_TYPE_MARKET,
                # timeInForce=clientBinance.TIME_IN_FORCE_GTC,
                quantity=quantity,
                # price=repr(originalPrice)
            )

            completed = False
            while not completed:
                time.sleep(0.2)
                self.orderID = orderBuy['clientOrderId']
                orderBuySt = self.client.get_order(symbol=coin + coinfrom,
                                                   orderId=self.orderID)
                print("+ Order buy status : " + orderBuySt['status'] +
                      " at : " + orderBuySt['price'])

                if not orderBuySt == self.client.ORDER_STATUS_NEW:
                    completed = True

    def sell_market(self, coin, coinTo, ignored, quantity, testmode):
        print("-- Selling market " + str(quantity) + " " + coin + " to " +
              coinTo)
        if testmode:
            print("[TEST] " + str(quantity) + " " + coin + " sell at : " +
                  str(ignored) + " " + coinTo +
                  " (price is ignored on Binance)")
        else:
            orderSell = self.client.create_test_order(
                symbol=coin + coinTo,
                side=self.client.SIDE_SELL,
                type=self.client.ORDER_TYPE_MARKET,
                # timeInForce=clientBinance.TIME_IN_FORCE_GTC,
                quantity=quantity,
                # price=repr(newPrice)
            )

            completed = False
            while not completed:
                time.sleep(0.2)
                orderSellId = orderSell['clientOrderId']
                orderSellSt = self.client.get_order(symbol=coin + coinTo,
                                                    orderId=orderSellId)
                print("+ Order sell status : " + orderSellSt['status'] +
                      " at : " + orderSellSt['price'])

                if not orderSellSt == self.client.ORDER_STATUS_NEW:
                    completed = True

    def cancel_order(self):
        print("-- Canceling order")
        self.client.cancel_order(symbol=self.symbol, orderId=self.orderID)
        self.symbol = None
        self.orderID = None
Ejemplo n.º 16
0
# df_orderbook.to_csv('orderbook.csv')

# transform traders to dataframe
df_traders = pd.DataFrame(traders)
df_traders.columns = [
    'Aggregated TradeId', 'Price', 'Quantity', 'First TradeId', 'Last TradeId',
    'Timestamp', 'Was the buyer the maker?',
    'Was the trade the best price match?'
]
print(df_traders.head())
# df_traders.to_csv('traders.csv')

df_candle = pd.DataFrame(candle)
df_candle.columns = [
    'Open time', 'Open', 'High', 'Low', 'Close', 'Volume', 'Closetime',
    'Quote Asset Volume', 'Number of Traders', 'Taker Buy Base Asset Volume',
    'Taker Buy Quote Asset Volume', 'a'
]
df_candle.drop(['a'], axis=1)
print(df_candle.head())
# df_candle.to_csv('candle.csv')

test_order = client.create_test_order(symbol='BNBBTC',
                                      side='BUY',
                                      type='LIMIT',
                                      timeInForce='GTC',
                                      quantity=1,
                                      price='0.007856',
                                      timestamp='1591839251')
print(test_order)
Ejemplo n.º 17
0
        mov_dx = tp.derivative_ratio(open_price, 10)
        
        current_price = float(client.get_symbol_ticker(symbol=token+asset)['price'])
        open_price.append(current_price)
        
        # BUY
        if(((current_price > res_trend[-1] and (current_price > res_01[-1])) 
#                or (mov_dx_01[-1] < 1 - (40/10000))            
                ) and         
                (int(funds) > 10)): 
            buybool = True       
            
            #client.order_market_buy(symbol=token+asset, quantity=int(10*funds/current_price)/10) 
            
            order = client.create_test_order(symbol=token+asset,
                                             side=Client.SIDE_BUY,
                                             type=Client.ORDER_TYPE_MARKET,
                                             quantity=int(10*funds/current_price)/10) 
            
            tokens = tokens + (1-0.001)*(int(10*funds/current_price)/10)
            
            buy_val_list.append(tokens)
            
            buy_price_list.append(current_price)
            
            # print("Epoch: " + 
            #       str(count) +
            #       ", Buy Made @ price: " + 
            #       str(current_price) +
            #       ", Quantity Bought: " + 
            #       str(int(10*funds/current_price)/10) +
            #       ", Gain: " +
Ejemplo n.º 18
0
# init
api_key = os.environ.get('binance_api')
api_secret = os.environ.get('binance_secret')

client = Client(
    'MIPFco456I2i3nSBeV6NnZUSYP3Bb8r4zejs9cHYf5dOAyxHDMo4bYbURkQGlaMn',
    'fdYtZD0hNqfQbMqKrcM5e5viqb8TYTV8AotCdGoRPxuvQcFtU5URoxeKah58z3sW',
)
## main

# create order

# make a test order first. This will raise an exception if the order is incorrect.
buy_order_limit = client.create_test_order(symbol='ETHUSDT',
                                           side='BUY',
                                           type='LIMIT',
                                           timeInForce='GTC',
                                           quantity=100,
                                           price='3.444')

buy_order = client.create_test_order(symbol='ETHUSDT',
                                     side='BUY',
                                     type='MARKET',
                                     quantity=100)

# create a real order if the test orders did not raise an exception
try:
    buy_limit = client.create_order(symbol='ETHUSDT',
                                    side='BUY',
                                    type='LIMIT',
                                    timeInForce='GTC',
                                    quantity=100,
Ejemplo n.º 19
0
class BinBot(object):
    def __init__(self):
        self.client = Client(binance_config.api_key, binance_config.api_secret)
        self.fee = 0.0005  #if user has BNB tokens
        self.orderbook = self.get_orderbook_total()
        self.bit_rate = self.extract_btc_eth_rate(self.orderbook)
        self.update_orderbook()
        self.symbol_keys = self.get_keys(self.orderbook)
        self.current_btc, self.current_eth = self.update_account()

    def get_orderbook_total(self):
        """ Returns orderbook from binance package. """
        return self.client.get_orderbook_tickers()

    def update_orderbook(self):
        """ Updates orderbook by analyzing exchange rates in BTC and removing
            coins in no_trade in binance_config. 
        """
        try:
            self.orderbook = self.get_orderbook_total()
            self.bit_rate = self.extract_btc_eth_rate(self.orderbook)
            self.orderbook = self.modify_orderbook(self.orderbook)
        except binexc.BinanceAPIException as e:
            print(e.status_code)
            print(e.message)
            time.sleep(10)
            self.update_orderbook()

    def update_account(self):
        """ Returns the amount of BTC or ETH in the account. """
        flag = False
        #If local time compared to Binance NTP server time is offset by +1000ms then API will throw error
        while (flag == False):
            try:
                acc = self.client.get_account(
                    recvWindow=binance_config.recv_window)
                flag = True
            except binexc.BinanceAPIException as e:
                print(str(e.status_code) + " : " + e.message)
                time.sleep(1)
        btc_eth = []
        for k in acc['balances']:
            if (k['asset'] == 'BTC' or k['asset'] == 'ETH'):
                btc_eth.append(k['free'])
            if (len(btc_eth) == 2):
                break
        if (btc_eth[0] >= btc_eth[1]):
            return btc_eth[0], btc_eth[1]
        else:
            return btc_eth[1], btc_eth[0]

    def alt_asset_amount(self, symbol, symbol_length=3):
        """ Returns the total amount of an altcoin on the account.
        
            Keyword Arguments:
            symbol -- the symbol of the altcoin e.g. 'NEO'
            symbol_length -- 'NEO' will have symbol_length of 3
                             'LINK' will have symbol_length of 4
                              Work around for the API
                              (default 3)
        """

        acc = self.client.get_account(recvWindow=binance_config.recv_window)
        for k in acc['balances']:
            if (k['asset'] == symbol[0, symbol_length]):
                return k['free']
        return "Symbol Not Found"

    def get_keys(self, orderbook):
        """ Returns symbols of all coins on Binance """
        _keys = []
        for k in orderbook:
            _keys.append(list(k.keys())[0])
        return _keys

    def extract_btc_eth_rate(self, orderbook):
        """ Returns ETHBTC exchange rate """
        for i in range(0, len(orderbook)):
            if (orderbook[i]['symbol'][0:6] == 'ETHBTC'):
                odbk = orderbook[i]
                odbk['btc_one'] = 1 / float(odbk['askPrice'])
                return orderbook[i]

    def modify_orderbook(self, orderbook):
        """ Helper function to modify orderbook to remove trading pairs that
            are not involved eg BTCUSDT """
        ob_sorted = sorted(orderbook, key=lambda k: k['symbol'])
        ob_sorted = self.del_non_pair_coins(ob_sorted)
        ob_dict = self.transform_data_list(ob_sorted)
        return ob_dict

    def del_non_pair_coins(self, orders):
        """ Deletes coins that are no longer listed on Binance as well as coins 
            listed on the binance_config.no_trade list
        """
        i = 0
        orders_to_return = []
        while (i < len(orders) - 1):
            if (orders[i]['symbol'][0:3] == orders[i + 1]['symbol'][0:3]):
                if (orders[i]['symbol'] == 'ETC'
                        or orders[i]['symbol'][-4:] == 'USDT'
                        or orders[i]['symbol'][0:4] in binance_config.no_trade
                        or orders[i]['symbol'][0:3] in binance_config.no_trade
                        or orders[i]['symbol'][-3:] == 'BNB'):
                    i += 1
                elif (orders[i + 1]['symbol'][-4:] == 'USDT'):
                    i += 1
                else:
                    orders_to_return.append(orders[i])
                    orders_to_return.append(orders[i + 1])
                    i += 2
            else:
                i += 1
        return orders_to_return

    def transform_data_list(self, orders):
        """ Transforms data from dictionary into list(BTC=0, ETH=1) """
        transform = []
        for i in range(0, len(orders), 2):
            transform.append(
                {orders[i]['symbol'][0:3]: [orders[i], orders[i + 1]]})
        return transform

    def orderbook_btc_eth(self, orderbook):
        """ Looks for viable trading pairs in the BTC --> ETH direction """
        btc_to_eth = {}
        btc_pos = 0
        eth_pos = 1
        for k in orderbook:
            try:
                btc_to_eth[list(k.keys())[0]] = 1 / float(k[list(
                    k.keys())[0]][btc_pos]['askPrice']) * float(k[list(
                        k.keys())[0]][eth_pos]['bidPrice'])
            except ZeroDivisionError as e:
                print(e)
        return sorted(btc_to_eth.items(),
                      key=operator.itemgetter(1),
                      reverse=True)

    def orderbook_eth_btc(self, orderbook):
        """ Looks for viable trading pairs in the ETH --> BTC direction """
        eth_to_btc = {}
        btc_pos = 0
        eth_pos = 1
        for k in orderbook:
            try:
                eth_to_btc[list(k.keys())[0]] = 1 / float(k[list(
                    k.keys())[0]][eth_pos]['askPrice']) * float(k[list(
                        k.keys())[0]][btc_pos]['bidPrice'])
            except ZeroDivisionError as e:
                print(e)
        return sorted(eth_to_btc.items(),
                      key=operator.itemgetter(1),
                      reverse=True)

    #Without client validation - no google authenticator
    #symbol - string,   quantity = int, price = string -- must be 0.0002
    def order_buy_alt(self, _symbol, _quantity, _price, order_rank, attempt=1):
        """ Buys an altcoin using Binance package
            
            Keyword Arguments:
            _symbol -- String: Symbol name of trading pair eg NEOBTC 
            _quantity -- Integer: Quantity to buy
            _price -- String: Price to buy at
            order_rank -- Integer: The order of buy/sell exection
            attempt -- Integer: Total of attempts to buy at the price
        """
        try:
            self.client.create_order(symbol=_symbol,
                                     side=enum.SIDE_BUY,
                                     type=enum.ORDER_TYPE_LIMIT,
                                     timeInForce=enum.TIME_IN_FORCE_GTC,
                                     quantity=_quantity,
                                     price=_price,
                                     disable_validation=True)
            return True
        except binexc.BinanceAPIException as e:
            print(e.status_code, e.message, " | order_buy_alt")
            return False

    def order_sell_alt(self,
                       _symbol,
                       _quantity,
                       _price,
                       order_rank,
                       attempt=1):
        """ Sells an altcoin using Binance package
            
            Keyword Arguments:
            _symbol -- String: Symbol name of trading pair eg NEOBTC 
            _quantity -- Integer: Quantity to buy
            _price -- String: Price to buy at
            order_rank -- Integer: The order of buy/sell exection
            attempt -- Integer: Total of attempts to buy at the price
        """
        try:
            self.client.create_order(symbol=_symbol,
                                     side=enum.SIDE_SELL,
                                     type=enum.ORDER_TYPE_LIMIT,
                                     timeInForce=enum.TIME_IN_FORCE_GTC,
                                     quantity=_quantity,
                                     price=_price,
                                     disable_validation=True)
        except binexc.BinanceAPIException as e:
            #print(e.message, e.status_code, " | order_sell_alt")
            if (order_rank is 4 or order_rank is 2):
                if (attempt <= 25):
                    attempt += 1
                    self.order_sell_alt(_symbol, _quantity, _price, order_rank,
                                        attempt)
                    time.sleep(0.02)
            else:
                print("Went to market price | order_sell_alt", e.message,
                      e.status_code)
                self.order_sell_market(_symbol, _quantity)

    def order_sell_market(self, _symbol, _quantity):
        """Sells coins into either ETH or BTC at MARKET VALUE.
            Use for upgrades for flexibility of binbot
                Say the order you originally placed was bought before your order arrived
                on the binance servers. This will immediately sell your coins and depending
                on the fluctuation of the market could still result in a (most likely milder)
                profit. 
        """
        try:
            self.crypto_storage.client.create_order(
                symbol=_symbol,
                side=enum.SIDE_SELL,
                type=enum.ORDER_TYPE_MARKET,
                quantity=_quantity)
        except binexc.BinanceAPIException as e:
            print(e.status_code)
            print(e.message)
            self.order_sell_market(_symbol, _quantity)

    def test_order_buy_alt(self, _symbol, _quantity, _price):
        """ FOR TESTING BINBOT BEFORE YOU LOSE MONEY
            Important to test if your orders will execute in time.
            Buys an altcoin using Binance package
            
            Keyword Arguments:
            _symbol -- String: Symbol name of trading pair eg NEOBTC 
            _quantity -- Integer: Quantity to buy
            _price -- String: Price to buy at
            order_rank -- Integer: The order of buy/sell exection
            attempt -- Integer: Total of attempts to buy at the price
        """
        try:
            self.client.create_test_order(symbol=_symbol,
                                          side=enum.SIDE_BUY,
                                          type=enum.ORDER_TYPE_LIMIT,
                                          timeInForce=enum.TIME_IN_FORCE_GTC,
                                          quantity=_quantity,
                                          price=_price,
                                          disable_validation=True)
        except binexc.BinanceAPIException as e:
            print(e.status_code)
            print(e.message)

    def test_order_sell_alt(self, _symbol, _quantity, _price):
        """ FOR TESTING BINBOT BEFORE YOU LOSE MONEY
            Important to test if your orders will execute in time.
            Sells an altcoin using Binance package
            
            Keyword Arguments:
            _symbol -- String: Symbol name of trading pair eg NEOBTC 
            _quantity -- Integer: Quantity to buy
            _price -- String: Price to buy at
            order_rank -- Integer: The order of buy/sell exection
            attempt -- Integer: Total of attempts to buy at the price
        """
        try:
            self.client.create_test_order(symbol=_symbol,
                                          side=enum.SIDE_SELL,
                                          type=enum.ORDER_TYPE_LIMIT,
                                          timeInForce=enum.TIME_IN_FORCE_GTC,
                                          quantity=_quantity,
                                          price=_price,
                                          disable_validation=True)
        except binexc.BinanceAPIException as e:
            print(e.status_code)
            print(e.message)

    def hunt(self, trials=10000, sleep_time=0.1):
        """ This is the main function of BinBot.
            This function will search for arbitrage opportunities and execute orders
            if it finds an inefficient pair.
            
            Keyword Arguments:
            trials -- Integer: how many loops the bot will run (default 10,000)
            sleep_time -- Float: The Binance API (since I last checked) will only allow
                                you to access it 18 times per second. So need a sleep time
                                to avoid this problem. Remember the longer the sleep time
                                the less likely your arbitrage oppurtunity will still be
                                available. (default 0.1)
        """
        num_runs = 0
        pre_arbitrage_assets = self.load_arbitrage_assets()
        time.sleep(sleep_time)
        while (num_runs < trials):
            try:
                self.update_orderbook()
            except ConnectionError as e:
                print(e + "will suspend bot for 10 seconds")
                time.sleep(10)
                continue
            #Search for inefficiency
            orderbook_btc = self.orderbook_btc_eth(self.orderbook)
            orderbook_eth = self.orderbook_eth_btc(self.orderbook)
            if (orderbook_btc[0][1] -
                (self.fee * orderbook_btc[0][1]) > self.bit_rate['btc_one']
                    and orderbook_eth[0][1] - (self.fee * orderbook_eth[0][1])
                    > float(self.bit_rate['askPrice'])):
                #print('found' + orderbook_btc[0][0] + orderbook_eth[0][0] + str(num_runs))
                num_runs += 1
                purchase = []
                for k in self.orderbook:
                    if (list(k.keys())[0] == orderbook_btc[0][0]):
                        purchase.insert(0, k)
                    if (list(k.keys())[0] == orderbook_eth[0][0]):
                        purchase.insert(1, k)
                btc_limit = binance_config.btc_trade_limit
                while (btc_limit > 0.001):
                    if (self.determine_feasibility(
                            orderbook_btc[0][0], orderbook_eth[0][0], purchase,
                            btc_limit) is True):
                        self.execute_trade(orderbook_btc[0][0],
                                           orderbook_eth[0][0], purchase,
                                           btc_limit)
                        break
                    else:
                        btc_limit = btc_limit - 0.001
            num_runs += 1
            if (num_runs % 100 == 0):
                print(str(num_runs))
        post_arbitrage_assets = self.load_arbitrage_assets()

        #Print results
        time_delta = datetime.datetime.now().replace(
            microsecond=0) - pre_arbitrage_assets['datetime']
        print('Initial: BTC:', pre_arbitrage_assets['BTC'], 'ETH:',
              pre_arbitrage_assets['ETH'], 'BNB:', pre_arbitrage_assets['BNB'])
        print('After__: BTC:', post_arbitrage_assets['BTC'], 'ETH:',
              post_arbitrage_assets['ETH'], 'BNB:',
              post_arbitrage_assets['BNB'])
        print(
            'Diff___: BTC:',
            float(post_arbitrage_assets['BTC']) -
            float(pre_arbitrage_assets['BTC']), 'ETH:',
            float(post_arbitrage_assets['ETH']) -
            float(pre_arbitrage_assets['ETH']), 'BNB:',
            float(post_arbitrage_assets['BNB']) -
            float(pre_arbitrage_assets['BNB']), 'TIME:',
            divmod(time_delta.total_seconds(), 60))

    def determine_feasibility(self, btc_sym, eth_sym, purchase,
                              btc_trade_limit):
        """ Determines if an arbitrage opportunity is profitable. """
        if (btc_trade_limit / float(purchase[0][btc_sym][0]['askPrice']) <=
                float(purchase[0][btc_sym][0]['askQty']) and
                btc_trade_limit / float(purchase[0][btc_sym][0]['askPrice']) <=
                float(purchase[0][btc_sym][1]['bidQty'])):
            eth_capital = (btc_trade_limit /
                           float(purchase[0][btc_sym][0]['askPrice'])) * float(
                               purchase[0][btc_sym][1]['bidPrice'])
            if (eth_capital / float(purchase[1][eth_sym][1]['askPrice']) <=
                    float(purchase[1][eth_sym][1]['askQty']) and
                    eth_capital / float(purchase[1][eth_sym][1]['askPrice']) <=
                    float(purchase[1][eth_sym][0]['bidQty'])):
                #and eth_capital / float(purchase[1][eth_sym][1]['askPrice']) >= 1):
                return True
            else:
                return False
        else:
            return False

    def execute_trade(self, btc_sym, eth_sym, purchase, btc_trade_limit):
        """ Executes trade in  BTC-->ALT_1-->ETH-->ALT_2-->BTC order.
                Side note: Making threads will improve likelihood of success. 
                            This implementation is inefficient. 
        """
        amount_btc = math.floor(btc_trade_limit /
                                float(purchase[0][btc_sym][0]['askPrice']))
        eth_capital = (btc_trade_limit /
                       float(purchase[0][btc_sym][0]['askPrice'])) * float(
                           purchase[0][btc_sym][1]['bidPrice'])
        amount_eth = math.floor(eth_capital /
                                float(purchase[1][eth_sym][1]['askPrice']))
        if (amount_btc * float(purchase[0][btc_sym][0]['askPrice']) > 0.001
                and amount_eth * float(purchase[1][eth_sym][0]['bidPrice']) >
                0.001):
            if self.order_buy_alt(
                    purchase[0][btc_sym][0]['symbol'], amount_btc,
                    purchase[0][btc_sym][0]['askPrice'], 1) is True:
                print("1: " + purchase[0][btc_sym][0]['symbol'] + " " +
                      str(amount_btc) + " " +
                      purchase[0][btc_sym][0]['askPrice'])

                self.order_sell_alt(purchase[0][btc_sym][1]['symbol'],
                                    amount_btc,
                                    purchase[0][btc_sym][1]['bidPrice'], 2)
                print("2: " + purchase[0][btc_sym][1]['symbol'] + " " +
                      str(amount_btc) + " " +
                      purchase[0][btc_sym][1]['bidPrice'])

                if self.order_buy_alt(
                        purchase[1][eth_sym][1]['symbol'], amount_eth,
                        purchase[1][eth_sym][1]['askPrice'], 3) is True:
                    print("3: " + purchase[1][eth_sym][1]['symbol'] + " " +
                          str(amount_eth) + " " +
                          purchase[1][eth_sym][1]['askPrice'])

                    self.order_sell_alt(purchase[1][eth_sym][0]['symbol'],
                                        amount_eth,
                                        purchase[1][eth_sym][0]['bidPrice'], 4)
                    print("4: " + purchase[1][eth_sym][0]['symbol'] + " " +
                          str(amount_eth) + " " +
                          purchase[1][eth_sym][0]['bidPrice'])

        self.remove_any_open_orders([
            purchase[0][btc_sym][0]['symbol'],
            purchase[0][btc_sym][1]['symbol'],
            purchase[1][eth_sym][1]['symbol'],
            purchase[1][eth_sym][0]['symbol']
        ])

    def remove_any_open_orders(self, poss_orders=[]):
        """ For upgrading flexibility of BinBot. Removes any open orders. """
        for order in poss_orders:
            open_orders = self.get_open_orders_symbol(_symbol=order)
            if len(open_orders) is not 0:
                self.order_sell_market(_symbol=open_orders[0]['symbol'],
                                       _quantity=open_orders[0]['origQty'])

    def check_server_time_difference(self):
        """ Checks the amount of time it takes for your packets to reach Binance 
            servers and return to your computer.
            VERY IMPORTANT: If your packets take too long, your trades will not execute
        """
        for i in range(0, 10):
            local_time_one = int(time.time() * 1000)
            server_time = self.client.get_server_time()
            diff_one = server_time['serverTime'] - local_time_one
            local_time_two = int(time.time() * 1000)
            diff_two = local_time_two - server_time['serverTime']
            print("local1: %s server: %s local2: %s diff1: %s diff2: %s" %
                  (local_time_one, server_time['serverTime'], local_time_two,
                   diff_one, diff_two))
            time.sleep(2)

    def get_specific_symbol(self, coin_sym='ETH', trade_currency='BTC'):
        """Returns a specific trading pair to see what price it is at in the orderbook.
            If no parameters are given, it will return the price of ETHBTC.
        
            Keyword Arguments:
            coin_sym -- This is the first symbol in the trading pair (default 'ETH')
            trade_currency -- This is the second symbol in the trading pair (default 'BTC')
        """
        if trade_currency != 'BTC' and trade_currency != 'ETH' and trade_currency != 'BNB':
            print('Trade currency can only be BTC or ETH')
            return {}
        trade_pair = coin_sym + trade_currency
        for k in self.orderbook:
            if list(k.keys())[0] == coin_sym[0:3]:
                for pair in k[list(k.keys())[0]]:
                    if pair['symbol'] == trade_pair:
                        return pair
        print('Pair not in orderbook.')
        return {}

    def get_orderbook_symbol(self, _symbol='ETHBTC', _limit=10):
        """ Returns the orderbook (buy/sell prices) of a given symbol.
            Limit will hold the orderbook to only 10 prices of the buy/sell pair
            
            Returns:
            Dictionary of prices
        """
        return self.client.get_order_book(symbol=_symbol, limit=_limit)

    def get_open_order_symbol(self, _symbol='ETHBTC'):
        """Get all open orders of a symbol """
        try:
            return self.client.get_open_orders(symbol=_symbol)
        except binexc.BinanceAPIException as e:
            print(e.message)
            self.get_open_orders_symbol(_symbol)

    def get_past_orders(self, _symbol='ETHBTC'):
        """ Get the user's past orders. 
        """
        return self.client.get_all_orders(symbol=_symbol)

    def load_arbitrage_assets(self):
        """ Loads the amount of coins in the user's account """
        flag = False
        btc_eth_bnb = {}
        while (flag is False):
            try:
                acc = self.client.get_account(
                    recvWindow=binance_config.recv_window)
                flag = True
            except binexc.BinanceAPIException as e:
                print(str(e.status_code) + " : " + e.message)
                time.sleep(1)
        #acc['balances']
        for cryptoasset in acc['balances']:
            if cryptoasset['asset'] == 'BTC':
                btc_eth_bnb['BTC'] = cryptoasset['free']
            if cryptoasset['asset'] == 'ETH':
                btc_eth_bnb['ETH'] = cryptoasset['free']
            if cryptoasset['asset'] == 'BNB':
                btc_eth_bnb['BNB'] = cryptoasset['free']
            if len(btc_eth_bnb) is 3:
                break
        btc_eth_bnb['datetime'] = datetime.datetime.now().replace(
            microsecond=0)
        return btc_eth_bnb
Ejemplo n.º 20
0
class BinanceExchange(Exchange):
    def __init__(self, api_key: str, api_secret: str):
        self.client = Client(api_key, api_secret)
        self.symbols: dict = {}  # Dictionary mapping symbol names to BinanceSymbol instances
        self.update_symbols()

    def update_symbols(self):
        info = self.client.get_exchange_info()

        for symbol_dict in info['symbols']:
            # Create BinanceSymbol and store it in self.symbols, with the symbol name as the key
            symbol = BinanceSymbol.from_dict(symbol_dict)
            self.symbols[symbol.symbol_name] = symbol

        pprint(self.symbols)

    @staticmethod
    def process_api_error(exception: exceptions.BinanceAPIException) -> APIError:
        """
        Returns a more specific API exception class for the given BinanceAPIException, if available.
        :param exception: A BinanceAPIException instance.
        :return: Instance of an appropriate subclass of APIError, if available, else an instance of APIError.
        """
        if 'MIN_NOTIONAL' in exception.message:
            return OrderValueTooLow(message=exception.message)
        else:
            return APIError(message=exception.message)

    def get_symbol_info(self, symbol: str) -> BinanceSymbol:
        """
        Checks that the provided symbol is listed on the exchange.
        :param symbol: Symbol to check.
        :return: BinanceSymbol for the requested symbol name.
        :raises UnknownSymbol: When symbol is not listed.
        """
        symbol_info = self.symbols.get(symbol, None)
        if not symbol_info:
            raise UnknownSymbol(f"Unknown symbol \"{symbol:s}\"")
        return symbol_info

    def check_price(self, symbol: str, price: Decimal) -> Decimal:
        """
        Checks that the provided price is valid for the provided symbol.
        :param symbol: Symbol to check.
        :param price: Price to check.
        :return: Price, rounded to the correct step size.
        :raises OrderPriceInvalid: When price is not valid.
        """
        symbol_info = self.get_symbol_info(symbol)

        # Check min/max bounds
        if price < symbol_info.min_price:
            raise OrderPriceInvalid(
                f"Price {price} for symbol {symbol} is less than allowed minimum of {symbol_info.min_price}")
        elif price > symbol_info.max_price:
            raise OrderPriceInvalid(
                f"Price {price} for symbol {symbol} is greater than allowed maximum of {symbol_info.max_price}")

        # Constrain to step size and check rounding
        rounded = price.quantize(symbol_info.price_step)
        rounding_error = abs(rounded - price) / price
        if rounding_error >= settings.TRADING_MAXIMUM_ROUNDING_ERROR:
            raise ExcessiveRoundingError(
                f"Rounding {price} to price step {symbol_info.price_step} for symbol {symbol} would cause"
                "rounding error of {rounding_error:.1%}, which is larger than the allowed rounding error of "
                "{settings.TRADING_MAXIMUM_ROUNDING_ERROR:.1%}")
        else:
            return rounded

    def check_quantity(self, symbol: str, quantity: Decimal) -> Decimal:
        """
        Checks that the provided quantity is valid for the provided symbol.
        :param symbol: Symbol to check.
        :param quantity: Quantity to check.
        :return: Quantity, rounded to the correct step size.
        :raises LotSizeInvalid: When quantity is not valid.
        """
        symbol_info = self.get_symbol_info(symbol)

        # Check min/max bounds
        if quantity < symbol_info.min_quantity:
            raise LotSizeInvalid(
                f"Quantity {quantity} of symbol {symbol} is less than allowed minimum of {symbol_info.min_quantity}")
        elif quantity > symbol_info.max_quantity:
            raise LotSizeInvalid(
                f"Quantity {quantity} of symbol {symbol} is greater than allowed maximum of {symbol_info.max_quantity}")

        # Constrain to step size and check rounding
        rounded = quantity.quantize(symbol_info.quantity_step)
        rounding_error = abs(rounded - quantity) / quantity
        if rounding_error >= settings.TRADING_MAXIMUM_ROUNDING_ERROR:
            raise ExcessiveRoundingError(
                f"Rounding {quantity} to quantity step {symbol_info.quantity_step} for symbol {symbol} would cause"
                "rounding error of {rounding_error:.1%}, which is larger than the allowed rounding error of "
                "{settings.TRADING_MAXIMUM_ROUNDING_ERROR:.1%}")
        else:
            return rounded

    def get_last_price(self, symbol: str) -> Decimal:
        try:
            ticker = self.client.get_ticker(symbol=symbol)
            return Decimal(ticker['lastPrice'])
        except exceptions.BinanceAPIException as e:
            raise self.process_api_error(e) from e

    def get_bid_price(self, symbol: str) -> Decimal:
        try:
            ticker = self.client.get_ticker(symbol=symbol)
            return Decimal(ticker['bidPrice'])
        except exceptions.BinanceAPIException as e:
            raise self.process_api_error(e) from e

    def get_ask_price(self, symbol: str) -> Decimal:
        try:
            ticker = self.client.get_ticker(symbol=symbol)
            return Decimal(ticker['askPrice'])
        except exceptions.BinanceAPIException as e:
            raise self.process_api_error(e) from e

    def get_order_status(self, symbol: str, order_id: str, last_state: OrderState) -> ExchangeOrderStatus:
        try:
            response = self.client.get_order(symbol=symbol, orderId=order_id)

            status = ExchangeOrderStatus()
            status.price = Decimal(response['price'])
            status.quantity = Decimal(response['origQty'])
            status.quantity_filled = Decimal(response['executedQty'])

            response_status = response['status']
            if response_status == 'NEW':
                status.status = OrderState.PLACED
            elif response_status == 'PARTIALLY_FILLED':
                status.status = OrderState.FILLING
            elif response_status == 'FILLED':
                status.status = OrderState.COMPLETED
            elif response_status == 'CANCELED' or response_status == 'EXPIRED':
                if last_state == OrderState.FILLING:
                    status.status = OrderState.CANCELLED_PARTIAL
                else:
                    status.status = OrderState.CANCELLED
            elif response_status == 'PENDING_CANCEL':
                status.status = last_state
            elif response_status == 'REJECTED':
                status.status = OrderState.CANCELLED
            else:
                raise APIError(f"Unknown response status {response_status:s}")

            return status
        except exceptions.BinanceAPIException as e:
            raise self.process_api_error(e) from e

    def place_buy_limit_order(self, symbol: str, quantity: Decimal, price: Decimal, test: bool = False) -> str:
        # Check and round parameters
        price = self.check_price(symbol, price)
        quantity = self.check_quantity(symbol, quantity)

        try:
            if test:
                self.client.create_test_order(symbol=symbol, quantity=quantity, price=str(price),
                                              side=enums.SIDE_BUY, type=enums.ORDER_TYPE_LIMIT,
                                              timeInForce=enums.TIME_IN_FORCE_GTC)
                return ""
            else:
                return self.client.order_limit_buy(symbol=symbol, quantity=quantity, price=str(price))['orderId']
        except exceptions.BinanceAPIException as e:
            raise self.process_api_error(e) from e

    def place_buy_market_order(self, symbol: str, quantity: Decimal, test: bool = False) -> str:
        # Check and round parameters
        quantity = self.check_quantity(symbol, quantity)

        try:
            if test:
                self.client.create_test_order(symbol=symbol, quantity=quantity,
                                              side=enums.SIDE_BUY, type=enums.ORDER_TYPE_MARKET,
                                              timeInForce=enums.TIME_IN_FORCE_GTC)
                return ""
            else:
                return self.client.order_market_buy(symbol=symbol, quantity=quantity)['orderId']
        except exceptions.BinanceAPIException as e:
            raise self.process_api_error(e) from e

    def place_sell_limit_order(self, symbol: str, quantity: Decimal, price: Decimal, test: bool = False) -> str:
        # Check and round parameters
        price = self.check_price(symbol, price)
        quantity = self.check_quantity(symbol, quantity)

        try:
            if test:
                self.client.create_test_order(symbol=symbol, quantity=quantity, price=str(price),
                                              side=enums.SIDE_SELL, type=enums.ORDER_TYPE_LIMIT,
                                              timeInForce=enums.TIME_IN_FORCE_GTC)
                return ""
            else:
                return self.client.order_limit_sell(symbol=symbol, quantity=quantity, price=str(price))['orderId']
        except exceptions.BinanceAPIException as e:
            raise self.process_api_error(e) from e

    def place_sell_market_order(self, symbol: str, quantity: Decimal, test: bool = False) -> str:
        # Check and round parameters
        quantity = self.check_quantity(symbol, quantity)

        try:
            if test:
                self.client.create_test_order(symbol=symbol, quantity=quantity,
                                              side=enums.SIDE_SELL, type=enums.ORDER_TYPE_MARKET,
                                              timeInForce=enums.TIME_IN_FORCE_GTC)
                return ""
            else:
                return self.client.order_market_sell(symbol=symbol, quantity=quantity)['orderId']
        except exceptions.BinanceAPIException as e:
            raise self.process_api_error(e) from e

    def cancel_order(self, symbol: str, order_id: str) -> None:
        try:
            self.client.cancel_order(symbol=symbol, orderId=order_id)
        except exceptions.BinanceAPIException as e:
            raise self.process_api_error(e) from e

    def get_balance(self, asset: str) -> Decimal:
        try:
            response = self.client.get_asset_balance(asset)
            return Decimal(response['free'])
        except exceptions.BinanceAPIException as e:
            raise self.process_api_error(e) from e
Ejemplo n.º 21
0
for origin_jump in range(1, 5):
    for second_jump in range(1, 5):
        drop = 2
        result[str(trading_algo(
            origin_jump, second_jump, drop,
            .5))] = "%d %d %d %d" % (origin_jump, second_jump, drop, .5)

for key in sorted(result.iterkeys()):
    print key + " " + result[key]

#pprint(account.get_positions)
#pprint(account.get_balance())

#place a test market buy order, to place an actual order use the create_order function
order = client.create_test_order(symbol='ICXETH',
                                 side=Client.SIDE_SELL,
                                 type=Client.ORDER_TYPE_MARKET,
                                 quantity=2)

#
# # get market depth
# depth = client.get_order_book(symbol='BNBBTC')
#
# # place a test market buy order, to place an actual order use the create_order function
# order = client.create_test_order(
#     symbol='BNBBTC',
#     side=Client.SIDE_BUY,
#     type=Client.ORDER_TYPE_MARKET,
#     quantity=100)
#
# # get all symbol prices
# prices = client.get_all_tickers()
Ejemplo n.º 22
0
def main():

    arg = docopt(__doc__, version=version)
    api_key = getenv('BINANCE_FUTURES_API')
    sec_key = getenv('BINANCE_FUTURES_SEC')
    if not api_key and not sec_key:
        print('please set these environment variables:\n'\
              '    BINANCE_FUTURES_API\n'\
              '    BINANCE_FUTURES_SEC', file=stderr)
        return 1
    if not api_key:
        print('environment variable not found: BINANCE_FUTURES_API',
              file=stderr)
        return 1
    if not sec_key:
        print('environment variable not found: BINANCE_FUTURES_SEC',
              file=stderr)
        return 1
    client = Client(api_key, sec_key)
    sides = {
        'buy': Client.SIDE_BUY,
        'long': Client.SIDE_BUY,
        'sell': Client.SIDE_SELL,
        'short': Client.SIDE_SELL,
    }
    types = {
        'limit': Client.ORDER_TYPE_LIMIT,
        'market': Client.ORDER_TYPE_MARKET
    }
    tifs = {
        'gtc': Client.TIME_IN_FORCE_GTC,
        'ioc': Client.TIME_IN_FORCE_IOC,
        'fok': Client.TIME_IN_FORCE_FOK
    }

    if arg['--verbose']:
        print(arg, file=stderr)
    else:
        sys.tracebacklimit = 0

    if arg['--help']:
        print(__doc__, file=stderr)
        return 0

    elif arg['status']:
        return client.get_system_status()['status']

    elif arg['balance']:
        if arg['futures']:
            print(dumps(client.futures_account_balance()))
        elif arg['spot']:
            print(dumps(client.get_account()['balances']))
        elif arg['coin']:
            print(dumps(client.futures_coin_account_balance()))
        return 0

    elif arg['show']:
        if arg['spot']:
            if arg['orders']:
                # if arg['--all']:
                #     print(dumps(client.get_all_orders()))
                # else:
                print(dumps(client.get_open_orders()))

    elif arg['order']:
        symbol = arg['<symbol>'].upper()
        if arg['futures'] and not symbol.endswith('USDT'):
            symbol += 'USDT'
        if arg['cancel']:
            if arg['futures']:
                print(
                    client.futures_cancel_order(symbol=symbol,
                                                orderid=arg['<orderid>'],
                                                timestamp=timemilli()))
            elif arg['spot']:
                print('not implemented', file=stderr)
        else:  # create order
            tif = tifs[arg['--tif']]
            if arg['<side>'].strip().lower() in sides:
                side = sides[arg['<side>'].strip().lower()]
            else:  # side is wrong
                print('error: side should be either "buy|long" or "sell|short"'\
                      ' not', arg['side'], file=stderr)
            quantity = float(arg['<quantity>'])
            if arg['--limit']:
                if arg['--limit']:
                    price = float(arg['--limit'])
                    type_ = types['limit']
                    if arg['--test']:
                        print(
                            client.create_test_order(symbol=symbol,
                                                     side=side,
                                                     quantity=quantity,
                                                     price=price,
                                                     timeInForce=tif,
                                                     type=type_))
                    else:  # actually send the order
                        if arg['futures']:
                            print(
                                client.futures_create_order(
                                    symbol=symbol,
                                    side=side,
                                    quantity=quantity,
                                    price=price,
                                    timeInForce=tif,
                                    reduceOnly=arg['--reduce-only'],
                                    timestamp=timemilli(),
                                    type=type_))
                        elif arg['spot']:
                            print(
                                client.create_order(symbol=symbol,
                                                    side=side,
                                                    quantity=quantity,
                                                    price=price,
                                                    timeInForce=tif,
                                                    type=type_))
                else:  # limit given but price not
                    print('please provide --limit \033[33m<price>\033[0m.')
            elif arg['--market']:
                type_ = types['market']
                if arg['--test']:
                    print(
                        client.create_test_order(symbol=symbol,
                                                 side=side,
                                                 quantity=quantity,
                                                 type=type_))
                else:  # actually send the order
                    if arg['futures']:
                        print(
                            client.futures_create_order(
                                symbol=symbol,
                                side=side,
                                quantity=quantity,
                                timestamp=timemilli(),
                                reduceOnly=arg['--reduce-only'],
                                type=type_))
                    elif arg['spot']:
                        print(
                            client.create_order(symbol=symbol,
                                                side=side,
                                                quantity=quantity,
                                                price=price,
                                                type=type_))
            else:  # limit or market not given
                print('please provide either '\
                      '\033[33m --limit <price>\033[0m '\
                      'or \033[33m--market\033[0m', file=stderr)

    else:  # no arguments given
        print(__doc__, file=stderr)
        return 1
Ejemplo n.º 23
0
class Manualbot:
    def __init__(self, args):
        self.buy_mode = True
        self.args = args
        self.target_profits = [50, 30, 20]
        self.targets_reached = [False, False, False]
        self.stoploss_reached = False
        config = ConfigParser()
        config.read("config.ini")
        self.config = config

    def run(self):
        self.client = Client(api_key=self.config['BINANCE']['KEY'],
                             api_secret=self.config['BINANCE']['SECRET'])
        if self.args.mode == "trading":
            logger.info(
                "START TRADE | symbol: {}, btc amount: {}, targets: {}, stoploss price: {}, trailing: {}, trailing price: {}"
                .format(self.args.symbol, self.args.btc_amount,
                        self.args.targets, self.args.immediate_stoploss,
                        self.args.use_trailing, self.args.trailing_stoploss))
            bm = BinanceSocketManager(self.client)
            self.conn_key = bm.start_symbol_ticker_socket(
                self.args.symbol, self.process_message)
            bm.start()
        elif self.args.mode == "analysis":
            alltickers = self.client.get_ticker()
            interval = "1h"
            exchange = ccxt.binance({
                'apiKey': self.config['BINANCE']['KEY'],
                'secret': self.config['BINANCE']['SECRET']
            })
            for ticker in alltickers:
                if float(ticker['priceChangePercent']) > 2 and (
                        "BTC" in ticker['symbol']):
                    data_base = exchange.fetch_ohlcv(
                        ticker['symbol'].split("BTC")[0] + "/BTC",
                        interval,
                        limit=100)
                    df = pd.DataFrame(data_base,
                                      columns=[
                                          'date', 'open', 'high', 'low',
                                          'close', 'volume'
                                      ])
                    df["date"] = pd.to_datetime(
                        df["date"], unit='ms').dt.strftime('%Y-%m-%d %H:%M')
                    self.save_analysis(df, ticker['symbol'], interval,
                                       ticker['priceChangePercent'])
        elif self.args.mode == "hamster":
            mongo_client = MongoClient('mongodb://localhost:27017/')
            db = mongo_client.projectlife
            self.previous_response = "initial"
            timeout = 30
            exchanges = dict()
            exchanges['binance'] = ccxt.binance({
                'apiKey':
                self.config['BINANCE']['KEY'],
                'secret':
                self.config['BINANCE']['SECRET']
            })
            exchanges['kucoin'] = ccxt.kucoin({
                'apiKey':
                self.config['KUCOIN']['KEY'],
                'secret':
                self.config['KUCOIN']['SECRET']
            })
            exchanges['bittrex'] = ccxt.bittrex({
                'apiKey':
                self.config['BITTREX']['KEY'],
                'secret':
                self.config['BITTREX']['SECRET']
            })
            exchanges['poloniex'] = ccxt.poloniex()

            def doWork():
                responses = []
                try:
                    url = 'https://www.mininghamster.com/api/v2/' + self.config[
                        'HAMSTER']['API']
                    responses = requests.get(url).json()
                    if len(responses) > 0:
                        for response in responses:
                            symbol = response['market'].split(
                                "BTC-")[1] + "/BTC"
                            bid, ask = self.get_prices(
                                exchanges[response['exchange']], symbol)
                            if response['signalmode'] == "buy":
                                result_buy = db.hamster.find_one({
                                    "signalID":
                                    response['signalID'],
                                    "signalmode":
                                    "buy"
                                })
                                if result_buy == None:
                                    response['buy_price'] = ask
                                    db.hamster.insert_one(response)
                                    self.send_telegram(str(response))
                            elif response['signalmode'] == "sell":
                                result_sell = db.hamster.find_one({
                                    "signalID":
                                    response['signalID'],
                                    "signalmode":
                                    "sell"
                                })
                                if result_sell == None:
                                    result_buy = db.hamster.find_one({
                                        "signalID":
                                        response['signalID'],
                                        "signalmode":
                                        "buy"
                                    })
                                    if result_buy != None:
                                        response['sell_price'] = bid
                                        response['profit'] = self.pct_change(
                                            result_buy['buy_price'], bid)
                                        db.hamster.insert_one(response)
                                        self.send_telegram(str(response))

                except BaseException as e:
                    print(e)
                pass

            lx = task.LoopingCall(doWork)
            lx.start(timeout)
            reactor.run()
        elif self.args.mode == "datacollect":
            client = MongoClient('mongodb://localhost:27017/')
            db = client.projectlife
            self.db_collection = db[self.args.symbol]
            bm = BinanceSocketManager(self.client)
            self.conn_key = bm.start_symbol_ticker_socket(
                self.args.symbol, self.process_datacollect_message)
            bm.start()

    def get_prices(self, exchange, symbol):
        orderbook = exchange.fetch_order_book(symbol)
        bid = orderbook['bids'][0][0] if len(orderbook['bids']) > 0 else None
        ask = orderbook['asks'][0][0] if len(orderbook['asks']) > 0 else None
        return bid, ask

    def pct_change(self, first, second):
        diff = second - first
        change = 0
        try:
            if diff > 0:
                change = (diff / first) * 100
            elif diff < 0:
                diff = first - second
                change = -((diff / first) * 100)
        except ZeroDivisionError:
            return float('inf')
        return change

    def create_order(self, symbol, side, type, quantity, price, actual_type):
        try:
            order = self.client.create_test_order(symbol=symbol,
                                                  side=side,
                                                  type=type,
                                                  timeInForce='GTC',
                                                  quantity=quantity,
                                                  price=price)
            print(order)
            if order == {}:
                #if order["status"] == "NEW":
                log = "{} ORDER FILLED | symbol: {}, type: {}, quantity: {}, price: {}, actual_type: {}".format(
                    side, symbol, type, str(quantity), price, actual_type)
                logger.info(log)
                self.send_telegram(log)
                return True
            else:
                log = "{} ORDER NOT FILLED | symbol: {}, type: {}, quantity: {}, price: {}, actual_type: {}".format(
                    side, symbol, type, str(quantity), price, actual_type)
                logger.info(log)
                self.send_telegram(log)
                return False
        except BaseException as e:
            log = 'Error occured when creating order: ' + str(e)
            logger.error(log)
            self.send_telegram(log)
            return False

    def send_telegram(self, msg):
        bot = telegram.Bot(token=self.config['TELEGRAM']['KEY'])
        bot.sendMessage(chat_id=self.config['TELEGRAM']['CHATID'], text=msg)

    def save_analysis(self, df, symbol, interval, percentchange):
        last_date = df.iloc[-1].date
        df["date"] = df.index.values
        plt.cla()
        fig, ax = plt.subplots(figsize=(16, 16))
        candlestick_ohlc(ax,
                         df.values,
                         width=0.6,
                         colorup='green',
                         colordown='red')
        df['sma5'] = talib.SMA(df['close'], 5)
        df['sma8'] = talib.SMA(df['close'], 8)
        df['sma13'] = talib.SMA(df['close'], 13)
        plt.plot(df.index, df.sma5, color="orange")
        plt.plot(df.index, df.sma8, color="blue")
        plt.plot(df.index, df.sma13, color="red")
        fig.suptitle(symbol + "-" + interval)
        fn = "/Users/apple/Desktop/dev/projectlife/data/images/analysis/" + symbol + "-" + percentchange + "%-" + interval + "-" + last_date + ".png"
        plt.savefig(fn, dpi=100)

    def stop_trading(self):
        bm = BinanceSocketManager(self.client)
        bm.stop_socket(self.conn_key)
        bm.close()
        reactor.stop()

    def process_message(self, msg):
        if msg['e'] == 'error':
            print("error on websocket. Restarting")
            bm.stop_socket(self.conn_key)
            bm.start()
        else:
            if self.buy_mode == True:
                ask_price = msg['a']
                self.buy_quantity = int(self.args.btc_amount /
                                        float(ask_price))
                self.latest_quantity = self.buy_quantity
                response = self.create_order(self.args.symbol, "BUY", 'LIMIT',
                                             self.buy_quantity, ask_price,
                                             "IMMEDIATE BUY")
                if response == True:
                    self.buy_mode = False
            else:
                bid_price = float(msg['b'])
                trl_stoploss_price = bid_price - self.args.trailing_stoploss
                imm_stoploss_price = self.args.immediate_stoploss

                if imm_stoploss_price >= bid_price:
                    imm_stoploss_price = "{:.8f}".format(bid_price)
                    response = self.create_order(self.args.symbol, "SELL",
                                                 'LIMIT', self.latest_quantity,
                                                 imm_stoploss_price,
                                                 "IMMEDIATE STOPLOSS")
                    if response == True:
                        self.stop_trading()

                if (trl_stoploss_price >= bid_price
                        and self.args.use_trailing == True
                        and self.targets_reached[0] == True):
                    trl_stoploss_price = "{:.8f}".format(bid_price)
                    response = self.create_order(self.args.symbol, "SELL",
                                                 'LIMIT', self.latest_quantity,
                                                 trl_stoploss_price,
                                                 "TRAILING STOPLOSS")
                    if response == True:
                        self.stop_trading()

                for index, target_price in enumerate(self.args.targets):
                    target_quantity = int(
                        (self.buy_quantity * self.target_profits[index]) / 100)
                    if bid_price >= target_price and self.targets_reached[
                            index] == False:
                        target_price = "{:.8f}".format(target_price)
                        response = self.create_order(
                            self.args.symbol, "SELL", 'LIMIT', target_quantity,
                            target_price,
                            "TAKE PROFIT TARGET " + str(index + 1))
                        if response == True:
                            self.targets_reached[index] = True
                            self.latest_quantity = self.latest_quantity - target_quantity
                            break

                if False not in self.targets_reached:
                    self.stop_trading()
Ejemplo n.º 24
0
class Binance_Connector:
    def __init__(self, mode='test', symbol='BTCUSDT'):
        self.mode = mode
        self.symbol = symbol
        self.binance_client = Client
        self.precision = 8  # TODO get from binance_client.get_symbol_info('BTCUSDT')
        self.step_size = 0.00000100  # TODO get from binance_client.get_symbol_info('BTCUSDT') LOT_SIZE
        assert mode in [
            'PROD', 'test', 'sim'
        ], 'mode should be PROD, test or sim'  # TODO pasar a un exception general
        self.base_asset = 'BTC'  #TODO get from get_symbol_info
        self.quoted_asset = 'USDT'  #TODO get from get_symbol_info

    def init_client(self):
        with open('secrets/binance.secrets', 'r') as f:
            secrets = json.loads(f.read())
        status = False
        while not status:
            try:
                self.binance_client = Client(api_key=secrets['api_key'],
                                             api_secret=secrets['api_secret'])
                status = True
            except requests.exceptions.Timeout:
                logging.info('init_client: Connection TimeOut')
                time.sleep(60)
        return self

    def buy(self, percentage_trade=0.5):
        if self.mode in ['PROD', 'test']:
            logging.info('env buy: Buying')
            self.init_client()
            account = self.binance_client.get_account()
            balance = float(account['balances'][np.argmax([
                x['asset'] == self.quoted_asset for x in account['balances']
            ])]['free'])
            logging.info('env buy: {} balance: {}'.format(
                self.quoted_asset, balance))
            depth = self.binance_client.get_order_book(symbol=self.symbol)
            current_price = np.mean([float(x[0]) for x in depth['bids']])
            logging.info('env buy: {} mean bids price: {}'.format(
                self.symbol, current_price))
            quantity = balance / current_price
            logging.info('env buy: {} quantity: {}'.format(
                self.symbol, quantity))
            quantity_trade = np.floor(
                (quantity * percentage_trade) *
                10**6) / 10**6  #TODO ver esta division hardcodeada
            logging.info('env buy: {} quantity to trade: {}'.format(
                self.symbol, quantity_trade))
            if self.mode == 'PROD':
                order = self.binance_client.create_order(
                    symbol=self.symbol,
                    side=Client.SIDE_BUY,
                    type=Client.ORDER_TYPE_MARKET,
                    quantity=quantity_trade)
            else:
                order = self.binance_client.create_test_order(
                    symbol=self.symbol,
                    side=Client.SIDE_BUY,
                    type=Client.ORDER_TYPE_MARKET,
                    quantity=quantity_trade)
            logging.info(order)
            return True
        else:
            return False

    def sell(self):
        if self.mode in ['PROD', 'test']:
            logging.info('env: Selling')
            self.init_client()
            account = self.binance_client.get_account()
            quantity = float(account['balances'][np.argmax([
                x['asset'] == self.base_asset for x in account['balances']
            ])]['free'])
            quantity = np.floor(
                quantity * 10**6) / 10**6  #TODO ver esta division hardcodeada
            logging.info('env sell: {} quantity: {}'.format(
                self.symbol, quantity))
            if self.mode == 'PROD':
                order = self.binance_client.create_order(
                    symbol=self.symbol,
                    side=Client.SIDE_SELL,
                    type=Client.ORDER_TYPE_MARKET,
                    quantity=quantity)
            else:
                order = self.binance_client.create_test_order(
                    symbol=self.symbol,
                    side=Client.SIDE_SELL,
                    type=Client.ORDER_TYPE_MARKET,
                    quantity=quantity)
            logging.info(order)
            return True
        else:
            return False

    def get_current_price(self):
        self.init_client()
        depth = self.binance_client.get_order_book(symbol=self.symbol)
        return np.mean([float(x[0]) for x in depth['bids']])
Ejemplo n.º 25
0
class Binance:
    def __init__(self, api_key, api_secret):
        self.client = Client(api_key, api_secret)

    def get_candle(self, symbol, interval, start, end='now'):
        # interval: eg:'1d','1h','30m' (str)
        # start: start time (str)
        # end: end time (str)
        #      default to now

        client = Client("", "")
        try:
            klines = client.get_historical_klines(symbol, interval, start, end)
        except BinanceAPIException as e:
            print(e.message)
            return
        self.klines = klines
        return klines

    def format_candle(self):
        df = pd.DataFrame(self.klines)
        df.columns = [
            'Open time', 'Open', 'High', 'Low', 'Close', 'BaseAsset Volume',
            'Close time', 'QuoteAsset Volume', 'Number of trades',
            'Taker buy baseAsset volume', 'Taker buy quoteAsset volume',
            'Ignore'
        ]
        df['Open time'] = pd.to_datetime(df['Open time'], unit='ms')
        df['Close time'] = pd.to_datetime(df['Close time'], unit='ms')
        closetime = df.pop('Close time')
        df.insert(1, closetime.name, closetime)
        df.pop('Ignore')
        df.to_csv('section1/task2/CandleData.csv', index=0)
        return

    def get_transactions(self, symbol, number=500):
        # number: # of trades wish to check (int)
        #         default:500 max:500
        # most recent trades show first

        client = Client("", "")
        try:
            trades = client.get_recent_trades(symbol=symbol, limit=number)
        except BinanceAPIException as e:
            print(e.message)
            return
        self.trades = trades
        return trades

    def format_trade(self):
        df = pd.DataFrame(self.trades)
        df.pop('id')
        time = df.pop('time')
        df.insert(0, time.name, time)
        df = df.sort_values(by='time', ascending=False)
        df['time'] = pd.to_datetime(df['time'], unit='ms')
        df.to_csv('section1/task2/TradesData.csv', index=0)
        return

    def get_marketdepth(self, symbol, number=100):
        # number: # wish to check (int)
        #         default:100 max:1000

        client = Client("", "")
        try:
            depth = client.get_order_book(symbol=symbol, limit=number)
        except BinanceAPIException as e:
            print(e.message)
            return
        self.depth = depth
        return depth

    def formant_depth(self):
        data = self.depth
        bids, asks = pd.DataFrame(data['bids']), pd.DataFrame(data['asks'])
        bids.columns, asks.columns = ['Bids Price',
                                      'Bids Qty'], ['Ask Price', 'Ask Qty']
        df = pd.concat([bids, asks], axis=1)
        df.to_csv('section1/task2/MarketDepth.csv', index=0)
        return

    def test_order(self, symbol, action, type, **kwargs):
        # action: SELL or BUY (str)
        # type: LIMIT, MARKET, STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, TAKE_PROFIT_LIMIT, LIMIT_MAKER (str)
        # timeInForce: GTC, IOC, FOK (str)
        # quantity: (int)
        # price: (str)
        # quoteOrderQty: (int)
        # newClientOrderId (str) – A unique id for the order. Automatically generated if not sent.
        # icebergQty (decimal) – Used with iceberg orders
        # newOrderRespType (str) – Set the response JSON. ACK, RESULT, or FULL; default: RESULT.
        # recvWindow (int) – The number of milliseconds the request is valid for
        # stopPrice: (int)

        # LIMIT	need: timeInForce, quantity, price
        # MARKET need: quantity or quoteOrderQty
        # STOP_LOSS	need: quantity, stopPrice
        # STOP_LOSS_LIMIT need: timeInForce, quantity, price, stopPrice
        # TAKE_PROFIT need: quantity, stopPrice
        # TAKE_PROFIT_LIMIT need: timeInForce, quantity, price, stopPrice
        # LIMIT_MAKER need: quantity, price

        try:
            self.client.create_test_order(symbol=symbol,
                                          side=action,
                                          type=type,
                                          **kwargs)
        except BinanceAPIException as e:
            print(e.message)
            return
Ejemplo n.º 26
0
def main():
    itchat.auto_login()
    api_key = '*****'
    api_secret = '*****'
    client = Client(api_key, api_secret)
    loop_count = 0
    triangle_count = 0
    exinfo = get_exinfo(client)
    #   print(f"[info]exinfo:{exinfo}")
    while (True):
        start_time = time()
        prices = get_prices(client)
        #       print(f"[info]prices:{prices}")
        prices_time = time()
        download_time = prices_time - start_time
        if (download_time > 0.5):
            print(f"[info]downloaded in {download_time:.4f}s, Sleep 2s...")
            sleep(2)
            continue
        else:
            print(f"[info]downloaded in: {prices_time-start_time:.4f}s")
        triangles = list(find_triangles(prices))
        computing_time = time()
        print(f"[info]computed in: {computing_time-prices_time:.4f}s")
        if triangles:
            sorted(triangles, key=itemgetter('profit'), reverse=True)
            triangle = triangles[0]
            triangle['coins'].reverse()
            coins = triangle['coins']
            describe_triangle(prices, coins, triangle)
            status = NORMAL
            for i_coin in range(len(coins) - 1):
                base_coin = coins[i_coin]
                quote_coin = coins[i_coin + 1]
                symb = base_coin + quote_coin
                symb_info = exinfo[symb]
                side = symb_info['side']
                tick = symb_info['tick']
                colm = symb_info['colm']
                pair = symb_info['pair']
                asset = 0.0
                price = prices[base_coin][quote_coin]
                try:
                    while (asset < 0.01):
                        asset = float(
                            client.get_asset_balance(asset=base_coin)['free'])
                        if asset < 0.01:
                            sleep(0.1)
                        else:
                            break
                    if side == 'BUY':
                        asset = asset * price
                        sprice = f"{ceiling(1.0/price, tick):.8f}"
                    else:
                        sprice = f"{price:.8f}"
                    quan = ceiling(asset, colm)
                    print(
                        f"[info]sym:{symb},bas:{base_coin},{side},tic:{tick},col:{colm},ass:{asset:.4f},qua:{quan},pri:{sprice}"
                    )
                    order = client.create_test_order(symbol=pair,
                                                     side=side,
                                                     type='LIMIT',
                                                     quantity=quan,
                                                     price=sprice)
#                   order = client.order_limit(symbol=pair, side=side, quantity=quan, price=sprice)
#                   order = client.order_market(symbol=pair, side=side, quantity=quan)
                except Exception as ex:
                    print(f"[info]exception:{ex}")
                    print(
                        f"[info]break at tri_count:{triangle_count}! as symbol:{symb}"
                    )
                    status = EXCEPTION
                    break
            if status == EXCEPTION:
                print(
                    f"[info]tri_count #{triangle_count} failed in {time()-computing_time:.4f}s@{datetime.datetime.today()}"
                )
                break
            else:
                print(
                    f"[info]tri_count #{triangle_count} succeeded in {time()-computing_time:.4f}s@{datetime.datetime.today()}"
                )
            triangle_count = triangle_count + 1
        else:
            sleep(0.2)
        loop_count += 1
    print(f"[info]tri_count/loop_count:{triangle_count}/{loop_count}")
    itchat.send('[info]exception:tri_count/loop_count:' + str(triangle_count) +
                '/' + str(loop_count),
                toUserName='******')
Ejemplo n.º 27
0
# https://github.com/sammchardy/python-binance/blob/master/docs/websockets.rst

import time
api_key = 'a89RHztsZkykoOTazLHjM9HkZHML6j8UND0fUMaa1Thk731r9FgKjcttVlhWhuRh'
api_secret = 'OYxgsFpxeefBzFUmU4UDRLcFc790CCscFgWEU8pFSOFbHkvP4JSHUWBKMtQfPyC8'

from binance.client import Client
client = Client(api_key, api_secret)

# get market depth
depth = client.get_order_book(symbol='BNBBTC')

# place a test market buy order, to place an actual order use the create_order function
order = client.create_test_order(symbol='BNBBTC',
                                 side=Client.SIDE_BUY,
                                 type=Client.ORDER_TYPE_MARKET,
                                 quantity=100,
                                 recvWindow=100000)

# get all symbol prices
prices = client.get_all_tickers()

symbol = 'BTCUSDT'


def get_asset_balance(asset):
    res_dict = client.get_asset_balance(asset=asset)
    if not res_dict:
        return 0.0

    free_num = float(res_dict.get('free', 0.0))
Ejemplo n.º 28
0
path = os.getcwd()

klines = client.get_historical_klines("ETHBTC", Client.KLINE_INTERVAL_30MINUTE,
                                      "1 Dec, 2017", "1 Jan, 2018")
k = pd.DataFrame([k[:6] for k in klines],
                 columns=['Time', 'Open', 'High', 'Low', 'Close', 'Volume'])
k['Time'] = [dateparser.parse(str(d)) for d in k.Time]
k.sort_values(by='Time', ascending=False, inplace=True, ignore_index=True)
k.to_csv(os.path.join(path, 'candle data.csv'), index=False)

mktdepth = client.get_order_book(symbol="BNBBTC")
depth = pd.DataFrame([[b[0], b[1]] for b in mktdepth['bids']],
                     columns=['bids', 'bids_size'])
depth[['asks',
       'asks_size']] = pd.DataFrame([[a[0], a[1]] for a in mktdepth['asks']])
depth.to_csv(os.path.join(path, 'orderbook.csv'), index=False)

trade = client.get_recent_trades(symbol='BNBBTC')
trades = pd.DataFrame(trade)
trades = trades[['id', 'price', 'qty', 'time']]
trades['time'] = [dateparser.parse(str(d)) for d in trades.time]
trades.sort_values(by='time', ascending=False, inplace=True, ignore_index=True)
trades.to_csv(os.path.join(path, 'trade data.csv'), index=False)

client = Client(api_key=api_key, api_secret=api_secret)
order = client.create_test_order(symbol='ETHBTC',
                                 side=Client.SIDE_BUY,
                                 type=Client.ORDER_TYPE_MARKET,
                                 quantity=100)
order
Ejemplo n.º 29
0
API_KEY = "i1s87G06vlhZTdKy7z3V0IRRKujhvps4umFTELYqre3awoeD4ZKpzWsCm8O3HklK"
API_SECRET = "mpZGQfH0SraheOvbJZMANJCWapD5xDo0HfbapGGmjm3YCXxsvrFj4a5zVxNOqdoP"
NUM_THREADS = 100


def truncate(f, n):
    # Truncates/pads a float f to n decimal places without rounding
    s = '{}'.format(f)
    if 'e' in s or 'E' in s:
        return '{0:.{1}f}'.format(f, n)
    i, p, d = s.partition('.')
    return '.'.join([i, (d + '0' * n)[:n]])


client = Client(API_KEY, API_SECRET, {"timeout": 60})

price = 0.001655552113213123
price = "%.4g" % price
newPrice = '{:.8f}'.format(float(price))
print(newPrice)

print("BUYING BTGBTC AT {0}", newPrice)

secondOrder = client.create_test_order(symbol="BTGBTC",
                                       side=Client.SIDE_BUY,
                                       type=ORDER_TYPE_LIMIT,
                                       timeInForce=TIME_IN_FORCE_GTC,
                                       quantity=1000,
                                       price=newPrice)
Ejemplo n.º 30
0
class trade_realtime():
    def __init__(self, api_key, api_secret, total_list=None):
        self.coin_list = total_list
        self.api_key = api_key
        self.api_secret = api_secret
        self.client = Client(api_key, api_secret)

    def get_time(self):
        server_time = self.client.get_server_time()
        #  {
        #         "serverTime": 1499827319559
        # }
        return int(server_time['serverTime'])

    def get_exchange_status(self):
        return self.client.get_system_status()

    def get_coin_price(self, coin_list):
        # kwargs = {'data': coin}
        output_data = []
        for coin in coin_list:
            price_d = ast.literal_eval(
                json.dumps(self.client.get_symbol_ticker(symbol=coin)))
            print(price_d)
            price = float(price_d['price'])
            output_data.append(price)

        return output_data

    def get_trade(self, start, end):
        output_data = []
        for coin in self.coin_list:
            output_data.append(
                self.client.get_aggregate_trades(symbol=coin,
                                                 startTime=start,
                                                 endTime=end))

        return output_data

    def get_kline(self, start, end):

        output_data = []
        for coin in self.coin_list:
            output_data.append(
                self.client.get_klines(symbol=coin,
                                       interval=Client.KLINE_INTERVAL_5MINUTE,
                                       limit=500,
                                       startTime=start,
                                       endTime=end))
        return output_data

    def get_historical_klines(self, symbol, interval, start, end):

        # init our list
        output_data = []

        # setup the max limit
        limit = 500
        timeframe = interval_to_milliseconds(interval)
        start_ts = start
        idx = 0
        # it can be difficult to know when a symbol was listed on Binance so allow start time to be before list date
        symbol_existed = False
        while True:
            # fetch the klines from start_ts up to max 500 entries or the end_ts if set
            temp_data = self.client.get_klines(symbol=symbol,
                                               interval=interval,
                                               limit=limit,
                                               startTime=start_ts,
                                               endTime=end)

            # handle the case where our start date is before the symbol pair listed on Binance
            if not symbol_existed and len(temp_data):
                symbol_existed = True

            if symbol_existed:
                # append this loops data to our output data
                output_data += temp_data

                # update our start timestamp using the last value in the array and add the interval timeframe
                start_ts = temp_data[len(temp_data) - 1][0] + timeframe
            else:
                # it wasn't listed yet, increment our start date
                start_ts += timeframe

            idx += 1
            # check if we received less than the required limit and exit the loop
            if len(temp_data) < limit:
                # exit the while loop
                break

            # sleep after every 3rd call to be kind to the API
            if idx % 3 == 0:
                time.sleep(1)

        return output_data

    def get_orderbook_ticker(self):
        pass

    def order_limit_buy(self, **params):

        return self.client.order_limit_buy(**params)

    def order_limit_sell(self, **params):

        return self.client.order_limit_sell(**params)

    def order_market_sell(self, **params):
        return self.client.order_market_sell(**params)

    def order_market_buy(self, **params):
        return self.client.order_market_buy(**params)

    def get_open_orders(self, **params):
        return self.client.get_open_orders(**params)

    def create_test_order(self, **params):

        self.client.create_test_order()

    def get_order(self, **params):
        self.client.get_order(self, **params)

    def get_all_orders(self, **params):
        self.client.get_all_orders(self, **params)

    def cancel_order(self, **params):
        self.client.cancel_order(self, **params)

    def get_account(self, **params):
        return (self.client.get_account(recvWindow=self.get_time()))

    def get_asset_balance(self, asset, **params):
        bal = self.client.get_asset_balance(asset=asset,
                                            recvWindow=self.get_time())
        return ast.literal_eval(json.dumps(bal))['free']

    def start_trade():
        pass

    def get_kline_lag_time(self, coin, lookback_in_ms):

        # lookback = 2*60*1000 #5mins
        # rt.pred_coin_list=[coin]

        end_ts = self.get_time()
        #  calendar.timegm(time.gmtime()) -lookback

        start_ts = end_ts - lookback_in_ms
        #  print("start=",start_ts)
        # print("end=",end_ts)

        f = self.get_historical_klines(symbol=coin,
                                       interval=Client.KLINE_INTERVAL_30MINUTE,
                                       end=end_ts,
                                       start=start_ts)
        f = ast.literal_eval(json.dumps(f))
        return f

    def getState(self, coin_list):

        features = np.empty((LOOK_BACK, 0), float)
        coin_f_index = [2, 3, 4, 5, 7]
        for coin in coin_list:
            coin_f = np.array(self.get_kline_lag_time(coin, LOOK_BACK_IN_MS),
                              dtype=np.float).reshape(-1, 12)
            coin_f = coin_f[coin_f.shape[0] - LOOK_BACK:, coin_f_index]
            if (coin_f.shape[0] < 10):
                print("something is wrong with binance api,return shape=",
                      coin_f.shape)
                return
            #print("coin_f shape ",coin_f.shape)
            #print("features shape ",features.shape)

            # COIN_FEATURE = np.concatenate((COIN_FEATURE, tmp), axis=0)
            features = np.hstack((features, coin_f))
        # features = self.create_input(features,LOOK_BACK)
        # DF_FEATURES
        #reshape for tensorflow backend
        features = features.reshape(1, DF_FEATURES, 1, LOOK_BACK)

        print("create_predictive_input, features shape ", features.shape)

        # print("kline shape after modify",features.shape)
        # features = self.create_input(features ,LOOK_BACK)
        return features