Ejemplo n.º 1
0
class Binance():
    def __init__(self,
                 api_key,
                 api_secret,
                 symbol: str,
                 base_instrument: str,
                 useTestNet: bool = False,
                 isLive: bool = False):

        self.isLive = isLive
        #self.previousBuy_price = 0.0
        self.client = Client(api_key, api_secret, testnet=useTestNet)

        # self.asset_balance = 0
        # self.base_instrument_balance = 10000.0

        self.pair = symbol + base_instrument
        print('Trading pair: ', self.pair)

        if self.isLive:
            account_info = self.client.get_account()
            print(list(account_info.items())[:9])

            if not useTestNet:
                trade_fees = self.client.get_trade_fee(
                    symbol=symbol.upper() +
                    base_instrument.upper())  ## this is a list of dict
                self.fees = trade_fees[0]['makerCommission']
                print('trading fees/commission = {} '.format(self.fees))

            self.asset_balance = self.client.get_asset_balance(
                asset=symbol.upper())["free"]
            self.base_instrument_balance = self.client.get_asset_balance(
                asset=base_instrument.upper())["free"]

            print('account balance, {} = '.format(symbol), self.asset_balance)
            print('account balance, {} = '.format(base_instrument),
                  self.base_instrument_balance)

    def get_historical_klines(self,
                              trading_pair: str,
                              interval,
                              from_date: str = None,
                              to_date: str = None) -> list:

        return self.client.get_historical_klines(trading_pair, interval,
                                                 from_date, to_date)

    def check_all_open_order(self, order_side):

        list_all_open_orders = self.client.get_open_orders(symbol=self.pair)
        n_order = 0
        for order in list_all_open_orders:
            if order['side'] == order_side and order['status'] == 'NEW':
                n_order += 1

        return n_order

    def execute_buy_order(order: 'Order', base_wallet: 'Wallet',
                          quote_wallet: 'Wallet', current_price: float,
                          options: 'ExchangeOptions',
                          clock: 'Clock') -> 'Trade':
        """Executes a buy order on the exchange.

        Parameters
        ----------
        order : `Order`
            The order that is being filled.
        base_wallet : `Wallet`
            The wallet of the base instrument.
        quote_wallet : `Wallet`
            The wallet of the quote instrument.
        current_price : float
            The current price of the exchange pair.
        options : `ExchangeOptions`
            The exchange options.
        clock : `Clock`
            The clock for the trading process..

        Returns
        -------
        `Trade`
            The executed trade that was made.
        """
        if order.type == TradeType.LIMIT and order.price < current_price:
            return None

        filled = order.remaining.contain(order.exchange_pair)

        if order.type == TradeType.MARKET:
            scale = order.price / max(current_price, order.price)
            filled = scale * filled

        commission = options.commission * filled
        quantity = filled - commission

        if commission.size < Decimal(10)**-quantity.instrument.precision:
            logging.warning(
                "Commission is less than instrument precision. Canceling order. "
                "Consider defining a custom instrument with a higher precision."
            )
            order.cancel("COMMISSION IS LESS THAN PRECISION.")
            return None

        transfer = Wallet.transfer(source=base_wallet,
                                   target=quote_wallet,
                                   quantity=quantity,
                                   commission=commission,
                                   exchange_pair=order.exchange_pair,
                                   reason="BUY")

        trade = Trade(order_id=order.id,
                      step=clock.step,
                      exchange_pair=order.exchange_pair,
                      side=TradeSide.BUY,
                      trade_type=order.type,
                      quantity=transfer.quantity,
                      price=transfer.price,
                      commission=transfer.commission)

        # n_order = self.check_all_open_order(SIDE_BUY)
        # if n_order>0: print(' ======>> There are more than {} existing buy orders, not placing further order'.format(n_order))

        if self.isLive:
            order = self.client.create_order(symbol=order.exchange_pair,
                                             side=SIDE_BUY,
                                             type=ORDER_TYPE_LIMIT,
                                             timeInForce=TIME_IN_FORCE_GTC,
                                             quantity=transfer.quantity,
                                             price=transfer.price)

            print('  =============== Placing buy order ============== \n',
                  order)
        else:
            order = self.client.create_test_order(
                symbol=order.exchange_pair,
                side=SIDE_BUY,
                type=ORDER_TYPE_LIMIT,
                timeInForce=TIME_IN_FORCE_GTC,
                quantity=transfer.quantity,
                price=transfer.price)

            print('  =============== Placing test buy order ============== \n',
                  order)

        return trade

    def execute_sell_order(order: 'Order', base_wallet: 'Wallet',
                           quote_wallet: 'Wallet', current_price: float,
                           options: 'ExchangeOptions',
                           clock: 'Clock') -> 'Trade':
        """Executes a sell order on the exchange.

        Parameters
        ----------
        order : `Order`
            The order that is being filled.
        base_wallet : `Wallet`
            The wallet of the base instrument.
        quote_wallet : `Wallet`
            The wallet of the quote instrument.
        current_price : float
            The current price of the exchange pair.
        options : `ExchangeOptions`
            The exchange options.
        clock : `Clock`
            The clock for the trading process..

        Returns
        -------
        `Trade`
            The executed trade that was made.
        """
        if order.type == TradeType.LIMIT and order.price > current_price:
            return None

        filled = order.remaining.contain(order.exchange_pair)

        commission = options.commission * filled
        quantity = filled - commission

        if commission.size < Decimal(10)**-quantity.instrument.precision:
            logging.warning(
                "Commission is less than instrument precision. Canceling order. "
                "Consider defining a custom instrument with a higher precision."
            )
            order.cancel("COMMISSION IS LESS THAN PRECISION.")
            return None

        # Transfer Funds from Quote Wallet to Base Wallet
        transfer = Wallet.transfer(source=quote_wallet,
                                   target=base_wallet,
                                   quantity=quantity,
                                   commission=commission,
                                   exchange_pair=order.exchange_pair,
                                   reason="SELL")

        trade = Trade(order_id=order.id,
                      step=clock.step,
                      exchange_pair=order.exchange_pair,
                      side=TradeSide.SELL,
                      trade_type=order.type,
                      quantity=transfer.quantity,
                      price=transfer.price,
                      commission=transfer.commission)

        # n_order = self.check_all_open_order(SIDE_SELL)
        # if n_order>0: print(' ======>> There are more than {} existing sell orders, not placing further order'.format(n_order))

        if self.isLive:
            order = self.client.create_order(symbol=order.exchange_pair,
                                             side=SIDE_SELL,
                                             type=ORDER_TYPE_LIMIT,
                                             timeInForce=TIME_IN_FORCE_GTC,
                                             quantity=transfer.quantity,
                                             price=transfer.price)
            print('  =============== Placing sell order ============== \n',
                  order)
        else:
            order = self.client.create_test_order(
                symbol=order.exchange_pair,
                side=SIDE_SELL,
                type=ORDER_TYPE_LIMIT,
                timeInForce=TIME_IN_FORCE_GTC,
                quantity=transfer.quantity,
                price=transfer.price)
            print(
                '  =============== Placing test sell order ============== \n',
                order)

        return trade

    def execute_order(order: 'Order', base_wallet: 'Wallet',
                      quote_wallet: 'Wallet', current_price: float,
                      options: 'Options', clock: 'Clock') -> 'Trade':
        """Executes an order on the exchange.

        Parameters
        ----------
        order : `Order`
            The order that is being filled.
        base_wallet : `Wallet`
            The wallet of the base instrument.
        quote_wallet : `Wallet`
            The wallet of the quote instrument.
        current_price : float
            The current price of the exchange pair.
        options : `ExchangeOptions`
            The exchange options.
        clock : `Clock`
            The clock for the trading process..

        Returns
        -------
        `Trade`
            The executed trade that was made.
        """
        kwargs = {
            "order": order,
            "base_wallet": base_wallet,
            "quote_wallet": quote_wallet,
            "current_price": current_price,
            "options": options,
            "clock": clock
        }

        if order.is_buy:
            trade = execute_buy_order(**kwargs)
        elif order.is_sell:
            trade = execute_sell_order(**kwargs)
        else:
            trade = None

        return trade
Ejemplo n.º 2
0
def list_coins_binance(key, secret, type):

    api = Client(key, secret)

    tableaux = api.get_ticker()
    balances = api.get_account()

    data = {}
    balance_coins = []
    contents = []
    #print(balances['balances'][0]['free'])
    #####
    # Check coins availables with balances > 0.0
    #####
    for i in range(0, len(balances)):
        if float(balances['balances'][i]['free']) > 0.001 \
            and balances['balances'][i]['asset'] != 'BNB' \
            and balances['balances'][i]['asset'] != 'BTC':
            balance_coins.append(balances['balances'][i]['asset'])
    print('\n-----------------------Binance-------------------- \n')
    print('... Bags Holder ... \n')
    print(balance_coins)
    ###
    # Construct list of coins to trade with volume criteria
    ###
    for i in range(0, len(tableaux)):
        if type in tableaux[i]['symbol'][-4:]:
            #print(tableaux[i]['symbol'][-4:] + '------' +tableaux[i]['quoteVolume'])
            data[tableaux[i]['symbol']] = float(tableaux[i]['quoteVolume'])
            sorted_data = sorted(data.items(),
                                 key=operator.itemgetter(1),
                                 reverse=True)

    if int(read_config('binance', 'last_position')) > len(sorted_data):
        total = len(sorted_data)
    else:
        total = int(read_config('binance', 'last_position'))

    for i in range(int(read_config('binance', 'first_position')) - 1, total):
        #print(sorted_data[i][0][:-3] + '-----' + str(sorted_data[i][1]))
        contents.append(sorted_data[i][0][:-len(type)])
    results = contents
    print('------------- Coins top ------------- \n')
    print(results)
    all_contents = ''

    for result in balance_coins:
        all_contents += result + '\n'

    with open('bags_binance.txt', 'w', encoding='utf8') as f:
        f.write(all_contents)
    f.close()

    all_contents = ''

    for result in results:
        all_contents += result + '\n'

    with open('Choices_binance.txt', 'w', encoding='utf8') as f:
        f.write(all_contents)
    f.close()

    create_file_config(type)
Ejemplo n.º 3
0
class Binance:

    def __init__(self):
        api_key = '0Lqjlvte26MGjAYXJa8UWggtQrqjyhWklxvWdJD72oSIfVcKr4AWeVq7OOm415uw'
        api_secret = 'ItyCJ0Re2bjNiHWfHHEb6d01OSZTFxitKoWVmkTwMPFmX3bVAl8F5GtQsoGM6vEx'
        self.client = Client(api_key, api_secret)

    def balances(self):
        balances = self.client.get_account()

        for balance in balances['balances']:
            if float(balance['locked']) > 0 or float(balance['free']) > 0:
                print('%s: %s' % (balance['asset'], balance['free']))

    def balance(self, asset='BTC'):
        balances = self.client.get_account()
        balances['balances'] = {item['asset']: item for item in balances['balances']}
        print(balances['balances'][asset]['free'])

    def orders(self, symbol, limit):
        orders = self.client.get_open_orders(symbol, limit)
        print(orders)

    def tickers(self):

        return self.client.get_all_tickers()

    def server_status(self):
        systemT=int(time.time()*1000)           #timestamp when requested was launch
        serverT= self.client.get_server_time()  #timestamp when server replied
        lag=int(serverT['serverTime']-systemT)

        print('System timestamp: %d' % systemT)
        print('Server timestamp: %d' % serverT['serverTime'])
        print('Lag: %d' % lag)

        if lag>1000:
            print('\nNot good. Excessive lag (lag > 1000ms)')
        elif lag<0:
            print('\nNot good. System time ahead server time (lag < 0ms)')
        else:
            print('\nGood (0ms > lag > 1000ms)')
        return

    def openorders(self):

        return self.client.get_open_orders()

    def profits(self, asset='BTC'):
        coins = self.client.get_products()

        for coin in coins['data']:
            if coin['quoteAsset'] == asset:
                orders = self.client.get_order_books(coin['symbol'], 5)
                if len(orders['bids'])>0 and len(orders['asks'])>0:
                    lastBid = float(orders['bids'][0][0]) #last buy price (bid)
                    lastAsk = float(orders['asks'][0][0]) #last sell price (ask)

                    if lastBid!=0:
                        profit = (lastAsk - lastBid) /  lastBid * 100
                    else:
                        profit = 0
                    print('%6.2f%% profit : %s (bid: %.8f / ask: %.8f)' % (profit, coin['symbol'], lastBid, lastAsk))
                else:
                    print('---.--%% profit : %s (No bid/ask info retrieved)' % (coin['symbol']))

    def market_value(self, symbol, kline_size, dateS, dateF="" ):
        dateS=datetime.strptime(dateS, "%d/%m/%Y %H:%M:%S")

        if dateF!="":
            dateF=datetime.strptime(dateF, "%d/%m/%Y %H:%M:%S")
        else:
            dateF=dateS + timedelta(seconds=59)

        print('Retrieving values...\n')
        klines = self.client.get_klines(symbol, kline_size, int(dateS.timestamp()*1000), int(dateF.timestamp()*1000))

        if len(klines)>0:
            for kline in klines:
                print('[%s] Open: %s High: %s Low: %s Close: %s' % (datetime.fromtimestamp(kline[0]/1000), kline[1], kline[2], kline[3], kline[4]))

        return