Beispiel #1
0
def cancel(ctx, market, account):
    """
    Cancel Orders in Mkt, (Eg: cancel USD/BTS --account name)

    :param ctx: context
    :param market: market e.g. USD/BTS
    :param account: name of your bitshares acct
    :return: Success or Fail message
    """
    try:
        my_market = Market(market)
        ctx.bitshares.bundle = True
        my_market.cancel(
            [x["id"] for x in my_market.accountopenorders(account)],
            account=account)
        response = ctx.bitshares.txbuffer.broadcast()
        log.info(response)
        if response is not None:
            log.info(
                f'Cancelled all orders on Market: {market} for account: {account}'
            )
        else:
            log.info(f'No orders to cancel! {market} for account: {account}')

    except bitshares.exceptions.AssetDoesNotExistsException:
        log.info(f"Asset does not exist: {market}")
    except graphenecommon.exceptions.AccountDoesNotExistsException:
        log.info(f"Account does not exist: {account}")
Beispiel #2
0
def cancelall(ctx, market, account):
    """ Cancel all orders of an account in a market
    """
    market = Market(market)
    ctx.bitshares.bundle = True
    market.cancel([x["id"] for x in market.accountopenorders(account)],
                  account=account)
    print_tx(ctx.bitshares.txbuffer.broadcast())
Beispiel #3
0
def cancel(ctx, market, account):
    """
    Cancel all orders in a market
    :param ctx: context
    :param market: market e.g.
    :param account: name of your bitshares acct
    :return: Success or Fail
    """
    try:
        log.info(f"Market: {market}")
        log.info(f'Account to use: {account}')
        market = Market(market)
        ctx.bitshares.bundle = True
        market.cancel([x["id"] for x in market.accountopenorders(account)],
                      account=account)
        log.info(ctx.bitshares.txbuffer.broadcast())

    except (bitshares.exceptions.AssetDoesNotExistsException):
        log.error(f"Asset does not exist: {market}")
    except (graphenecommon.exceptions.AccountDoesNotExistsException):
        log.error(f"Account does not exist: {account}")
Beispiel #4
0
def dex(  # Public AND Private API Bitshares
        command, amount=ANTISAT, price=None,
        depth=1, expiration=ANTISAT):

    MARKET = Market(BitPAIR, bitshares_instance=BitShares(nodes(), num_retries=0))
    CHAIN = Blockchain(bitshares_instance=BitShares(nodes(), num_retries=0), mode='head')
    #MARKET.bitshares.wallet.unlock(PASS_PHRASE)
    ACCOUNT.refresh()

    if command == 'buy':

        # buy relentlessly until satisfied or currency exhausted
        print(('Bitshares API', command))
        if price is None:
            price = ANTISAT
        print(('buying', amount, 'at', price))
        attempt = 1
        currency = float(ACCOUNT.balance(BitCURRENCY))
        if amount > 0.998 * currency * price:
            amount = 0.998 * currency * price
        if amount > 0:
            while attempt:
                try:
                    details = (MARKET.buy(price, amount, expiration))
                    print (details)
                    attempt = 0
                except:
                    print(("buy attempt %s failed" % attempt))
                    attempt += 1
                    if attempt > 10:
                        print ('buy aborted')
                        return
                    pass
        else:
            print('no currency to buy')

    if command == 'sell':

        # sell relentlessly until satisfied or assets exhausted
        expiration = 86400 * 7
        print(('Bitshares API', command))
        if price is None:
            price = SATOSHI
        print(('selling', amount, 'at', price))
        attempt = 1
        assets = float(ACCOUNT.balance(BitASSET))
        if amount > 0.998 * assets:
            amount = 0.998 * assets
        if amount > 0:
            while attempt:
                try:
                    details = (MARKET.sell(price, amount, expiration))
                    print (details)
                    attempt = 0
                except:
                    print(("sell attempt %s failed" % attempt))
                    attempt += 1
                    if attempt > 10:
                        print ('sell aborted')
                        return
                    pass
        else:
            print('no assets to sell')

    if command == 'cancel':

        # cancel all orders in this MARKET relentlessly until satisfied
        print(('Bitshares API', command))  
        orders = MARKET.accountopenorders()
        print((len(orders), 'open orders to cancel'))
        if len(orders):
            attempt = 1   
            order_list = []      
            for order in orders:
                order_list.append(order['id'])
            while attempt:
                try:
                    details = MARKET.cancel(order_list)
                    print (details)
                    attempt = 0
                except:
                    print((attempt, 'cancel failed', order_list))
                    attempt += 1
                    if attempt > 10:
                        print ('cancel aborted')
                        return
                    pass    

    if command == 'orders':

        servers = nodes()
        orders_list =[]
        satisfied = 0
        while not satisfied: #while len set triplicate
            for n in servers:
                sorders = [str(i) for i in orders_list]
                if (len(sorders) >= 3) and len(set(sorders[-3:])) == 1:
                    orders = orders_list[-1]
                    satisfied = 1
                else:
                    MARKET = Market(BitPAIR, bitshares_instance=BitShares(n, num_retries=0))
                    MARKET.bitshares.wallet.unlock(PASS_PHRASE)
                    ACCOUNT.refresh()

                    # dictionary of open orders in traditional format:
                    # orderNumber, orderType, market, amount, price
                    print(('Bitshares API', command))
                    orders = []
                    for order in MARKET.accountopenorders():
                        orderNumber = order['id']
                        asset = order['base']['symbol']
                        currency = order['quote']['symbol']
                        amount = float(order['base'])
                        price = float(order['price'])
                        orderType = 'buy'
                        if asset == BitASSET:
                            orderType = 'sell'
                            price = 1 / price
                        orders.append({'orderNumber': orderNumber,
                                       'orderType': orderType,
                                       'market': BitPAIR, 'amount': amount,
                                       'price': price})
                    orders_list.append(orders)


        for o in orders:
            print (o)
        if len(orders) == 0:
            print ('no open orders')
        return orders

    if command == 'market_balances':

        # dictionary of currency and assets in this MARKET
        print(('Bitshares API', command))
        currency = float(ACCOUNT.balance(BitCURRENCY))
        assets = float(ACCOUNT.balance(BitASSET))
        balances = {'currency': currency, 'assets': assets}
        print (balances)
        return balances

    if command == 'complete_balances':

        # dictionary of ALL account balances
        print(('Bitshares API', command))
        raw = list(ACCOUNT.balances)
        balances = {}
        for i in range(len(raw)):
            balances[raw[i]['symbol']] = float(raw[i]['amount'])
        print (balances)
        return balances

    if command == 'book':

        try:
            opened = 0
            while not opened:
                with open('book.txt', 'r') as f:
                    book = f.read()
                    opened = 1
        except Exception as e:
            print (e)
            print ('book.txt failed, try again...')
            pass
        return literal(book)

    if command == 'last':

        try:
            opened = 0
            while not opened:
                with open('last.txt', 'r') as f:
                    last = f.read()
                    opened = 1
        except Exception as e:
            print (e)
            print ('last.txt failed, try again...')
            pass
        return literal(last)

    if command == 'account_value':

        # dictionary account value in BTS BTC and USD
        print(('Bitshares API', command))
        raw = list(ACCOUNT.balances)
        balances = {}
        for i in range(len(raw)):
            balances[raw[i]['symbol']] = float(raw[i]['amount'])
        btc_value = 0
        for asset, amount in list(balances.items()):
            market_pair = 'OPEN.BTC:' + asset
            market = Market(market_pair)
            price = float(market.ticker()['latest'])
            try:
                value = amount / price
            except:
                value = 0
            if value < 0.0001:
                value = 0
            else:
                if asset != 'USD':
                    price = 1 / (price + SATOSHI)
                print((('%.4f' % value), 'OPEN.BTC', ('%.2f' % amount),
                       asset, '@', ('%.8f' % price)))
                btc_value += value

        market_pair = 'OPEN.BTC:USD'
        market = Market(market_pair)
        price = float(market.ticker()['latest'])
        usd_value = btc_value * price
        market_pair = 'OPEN.BTC:BTS'
        market = Market(market_pair)
        price = float(market.ticker()['latest'])
        bts_value = btc_value * price
        print((('%.2f' % bts_value), 'BTS',
             ('%.4f' % btc_value), 'OPEN.BTC',
             ('%.2f' % usd_value), 'bitUSD'))
        return bts_value, btc_value, usd_value

    if command == 'blocktime':

        current_block = CHAIN.get_current_block_num()
        blocktime = CHAIN.block_time(current_block)
        blocktimestamp = CHAIN.block_timestamp(current_block) - 18000
        now = time.time()
        latency = now - blocktimestamp
        print(('block               :', current_block))
        # print(('blocktime           :', blocktime))
        # print(('stamp               :', blocktimestamp))
        # print(('ctime(stamp)        :', time.ctime(blocktimestamp)))
        # print(('now                 :', now))
        print(('dex_rate latency    :', ('%.2f' % latency)))
        return current_block, blocktimestamp, latency
Beispiel #5
0
def auto_trans():
    bitshares = BitShares()
    pwd = get_bitshare_pwd()
    private_key = get_bitshare_private_key()
    # create usd:cny market obj
    usd_cny_market = Market("USD:CNY")
    # create fox wallet obj
    fox_wallet = Wallet()
    if not fox_wallet.created():
        fox_wallet.newWallet(pwd)
    # add private key, TODO:keep private key and pwd in safe place
    usd_cny_market.bitshares.wallet.unlock(pwd)
    try:
        usd_cny_market.bitshares.wallet.addPrivateKey(private_key)
    except ValueError as ve:
        logger.info('wif is already set')

    logger.info('start auto trans usd:cny')
    lb = 6.40
    ub = 6.50
    fox = Account("zfpx-fdjl")
    while True:
        start_time = time.time()
        logger.info("my open orders:%s", fox.openorders)
        my_usd = fox.balance("USD")
        my_cny = fox.balance("CNY")

        if start_time % 60 < 10:
            logger.info("my balance:%s", fox.balances)
            logger.info("my USD:%s my CNY:%s", my_usd, my_cny)

        # get avg price
        avg_price = update_market(usd_cny_market)[0]
        if avg_price < 6 or avg_price > 7:
            logger.error("!!!!!!!!!!!!!!!!!!!!!!!!:avg price out of range:",
                         avg_price)
            continue

        # set upper bound and lower bound
        lb = avg_price * (1 - 0.005)
        ub = avg_price * (1 + 0.005)

        # get top orders
        top_orders = usd_cny_market.orderbook()
        # unlock fox wallet for usd:cny maket
        usd_cny_market.bitshares.wallet.unlock(pwd)
        # cancel all of the orders
        orders = usd_cny_market.accountopenorders(fox)
        for order in orders:
            logger.info("try cancel %s : %s", order["id"], order)
            usd_cny_market.cancel(order["id"], fox)
            time.sleep(1)

        # sell all
        for bid in top_orders["bids"]:
            price = bid["price"]
            quote = bid["quote"]
            print("price:%s ub:%s quote:%s", price, ub, quote)
            if price >= ub:
                print("price:%s >= ub:%s quote:%s", price, ub, quote)
                if my_usd > 0:
                    # sell_usd = min(my_usd, quote)
                    if my_usd["amount"] < quote["amount"]:
                        sell_usd = my_usd
                    else:
                        sell_usd = quote
                    left_usd = my_usd["amount"] - sell_usd["amount"]
                    print("sell_usd:%s left_usd:%s price:%s bid:%s", sell_usd,
                          left_usd, price, bid)
                    logger.info("sell_usd:%s left_usd:%s price:%s bid:%s",
                                sell_usd, left_usd, price, bid)
                    try:
                        usd_cny_market.sell(price, sell_usd, 86400, False, fox)
                    except Exception as e:
                        logger.error("on except:%s", e)
                        log_bt()
                    my_usd["amount"] = left_usd
            else:
                break
            #    print("price:", price, " < ub:", ub)

        # buy all
        for ask in top_orders["asks"]:
            price = ask["price"]
            base = ask["base"]
            print("price:%s lb:%s base:%s", price, lb, base)
            if price <= lb:
                print("price:%s <= lb:%s base:%s", price, lb, base)
                if my_cny > 0:
                    if base["amount"] < my_cny["amount"]:
                        buy_cny = base["amount"]
                    else:
                        buy_cny = my_cny["amount"]
                    buy_usd = buy_cny / price
                    left_cny = my_cny["amount"] - buy_cny
                    print("buy_usd:%s left_cny:%s price:%s ask:%s", buy_usd,
                          left_cny, price, ask)
                    logger.info("buy_usd:%s left_cny:%s price:%s ask:%s",
                                buy_usd, left_cny, price, ask)
                    try:
                        # usd_cny_market.buy(price, buy_usd, 5, False, fox)
                        usd_cny_market.buy(price, 1, 86400, False, fox)
                    except Exception as e:
                        logger.error("on except:%s", e)
                        log_bt()
                    my_cny["amount"] = left_cny
            else:
                break
            #    print("price:", price, " > lb:", lb)

        usd_cny_market.bitshares.wallet.lock()
        delta_t = time.time() - start_time
        time.sleep(max(1, 30 - delta_t))
Beispiel #6
0
cp = account.callpositions
# если есть любые займы
if len(cp) > 0:
    print(cp)
    # проверяем есть ли по юаню
    cp2 = cp.get(our_symbol)
    if cp2 is not None:
        print(cp2)
        # получаем коэффициент перекрытия
        current_ratio = cp2.get('ratio')
        print(current_ratio)

    # проверяем не повысился ли коэффициент перекрытия выше нормы
    if current_ratio > max_ratio:
        # если увеличился, то  
        open_orders = market.accountopenorders(account)
        print(len(open_orders))
        # удаляем ордер на откуп шар по МК
        dex.close_debt_position(our_symbol, our_account)

        #if len(open_orders) == 1:
        #    for h in account.history(1,1,10):
        #        print(h)
        #        o_num = h.get('result')
        #        first = o_num[0]
        #        print(first)
        #        order_num = o_num[1]
        #        print(order_num)
        #        if first == 1:
        #            #market.cancel(order_num, account)
        #            break  
Beispiel #7
0
def dex_cancel():

    # update wallet unlock to low latency node
    zprint('CANCEL')
    nds = race_read('nodes.txt')
    if isinstance(nds, list):
        nodes = nds
    account = Account(USERNAME,
                      bitshares_instance=BitShares(nodes, num_retries=0))
    market = Market(BitPAIR,
                    bitshares_instance=BitShares(nodes, num_retries=0),
                    mode='head')
    orders = market.accountopenorders()
    try:
        market.bitshares.wallet.unlock(PASS_PHRASE)
    except:
        pass
    # attempt cancel all 10X or until satisfied
    def cancel():
        confirm.destroy()
        zprint('CONFIRMED')
        attempt = 1
        order_list = []
        for order in orders:
            order_list.append(order['id'])
        while attempt:
            try:
                details = market.cancel(order_list)
                print(details)
                attempt = 0
            except:
                zprint((attempt, 'cancel failed', order_list))
                attempt += 1
                if attempt > 10:
                    zprint('cancel aborted')
                    return
                pass

    # interact with tkinter
    confirm = Tk()
    if len(orders):
        if market.bitshares.wallet.unlocked():
            if len(orders) > 1:
                title = str(len(orders)) + ' ORDERS TO CANCEL'
            else:
                title = str(len(orders)) + ' ORDER TO CANCEL'
            confirm.title(title)
            Button(confirm, text='CONFIRM CANCEL ALL',
                   command=cancel).grid(row=1, column=0, pady=8)
            Button(confirm, text='INVALIDATE',
                   command=confirm.destroy).grid(row=2, column=0, pady=8)
            confirm.geometry('500x100+800+175')
            confirm.lift()
            confirm.call('wm', 'attributes', '.', '-topmost', True)
        else:
            confirm.title('YOUR WALLET IS LOCKED')
            Button(confirm, text='OK', command=confirm.destroy).grid(row=2,
                                                                     column=0,
                                                                     pady=8)
    else:
        confirm.title('NO OUTSTANDING ORDERS')
        Button(confirm, text='OK', command=confirm.destroy).grid(row=2,
                                                                 column=0,
                                                                 pady=8)
    confirm.geometry('500x100+800+175')
    confirm.lift()
    confirm.call('wm', 'attributes', '.', '-topmost', True)
Beispiel #8
0
def book(nodes, a=None, b=None):  #updates orderbook details

    # create fresh websocket connections for this child instance
    account = Account(USERNAME,
                      bitshares_instance=BitShares(nodes, num_retries=0))
    market = Market(BitPAIR,
                    bitshares_instance=BitShares(nodes, num_retries=0),
                    mode='head')
    node = nodes[0]
    begin = time.time()
    while time.time() < (begin + TIMEOUT):
        time.sleep(random())
        try:
            # add unix time to trades dictionary
            trades = market.trades(limit=100)
            for t in range(len(trades)):
                ts = time.strptime(str(trades[t]['time']), '%Y-%m-%d %H:%M:%S')
                trades[t]['unix'] = int(time.mktime(ts))
                fprice = '%.16f' % float(trades[t]['price'])
                trades[t]['fprice'] = fprice[:10] + ',' + fprice[10:]
            # last price
            # last = market.ticker()['latest']
            last = float(trades[0]['price'])
            slast = '%.16f' % last
            # complete account balances
            call = decimal(time.time())
            raw = list(account.balances)
            elapsed = float(decimal(time.time()) - call)
            if elapsed > 1:
                continue
            elapsed = '%.17f' % elapsed
            cbalances = {}
            for i in range(len(raw)):
                cbalances[raw[i]['symbol']] = float(raw[i]['amount'])
            # orderbook
            raw = market.orderbook(limit=20)
            bids = raw['bids']
            asks = raw['asks']
            sbidp = [('%.16f' % bids[i]['price']) for i in range(len(bids))]
            saskp = [('%.16f' % asks[i]['price']) for i in range(len(asks))]
            sbidv = [('%.2f' % float(bids[i]['quote'])).rjust(12, ' ')
                     for i in range(len(bids))]
            saskv = [('%.2f' % float(asks[i]['quote'])).rjust(12, ' ')
                     for i in range(len(asks))]
            bidv = [float(bids[i]['quote']) for i in range(len(bids))]
            askv = [float(asks[i]['quote']) for i in range(len(asks))]
            cbidv = list(np.cumsum(bidv))
            caskv = list(np.cumsum(askv))
            cbidv = [('%.2f' % i).rjust(12, ' ') for i in cbidv]
            caskv = [('%.2f' % i).rjust(12, ' ') for i in caskv]
            # dictionary of currency and assets in this market
            currency = float(account.balance(BitCURRENCY))
            assets = float(account.balance(BitASSET))
            balances = {BitCURRENCY: currency, BitASSET: assets}
            # dictionary of open orders in traditional format:
            # orderNumber, orderType, market, amount, price
            orders = []
            for order in market.accountopenorders():
                orderNumber = order['id']
                asset = order['base']['symbol']
                currency = order['quote']['symbol']
                amount = float(order['base'])
                price = float(order['price'])
                orderType = 'buy'
                if asset == BitASSET:
                    orderType = 'sell'
                    price = 1 / price
                else:
                    amount = amount / price
                orders.append({
                    'orderNumber': orderNumber,
                    'orderType': orderType,
                    'market': BitPAIR,
                    'amount': amount,
                    'price': ('%.16f' % price)
                })
            trades = trades[:10]
            stale = int(time.time() - float(trades[0]['unix']))
            # display orderbooks
            print("\033c")
            print(time.ctime(), '            ', int(time.time()), '   ', a, b)
            print('                        PING', (elapsed), '   ', node)
            print('')
            print('                        LAST',
                  slast[:10] + ',' + slast[10:], '   ', BitPAIR)
            print('')
            print('            ', sbidv[0], '  ',
                  (sbidp[0])[:10] + ',' + (sbidp[0])[10:], '   ',
                  (saskp[0])[:10] + ',' + (saskp[0])[10:], (saskv[0]))
            print('                                           ', 'BIDS', '   ',
                  'ASKS')
            for i in range(1, len(sbidp)):
                print(cbidv[i], sbidv[i], '  ',
                      (sbidp[i])[:10] + ',' + (sbidp[i])[10:], '   ',
                      (saskp[i])[:10] + ',' + (saskp[i])[10:], saskv[i],
                      caskv[i])
            print('')
            for o in orders:
                print(o)
            if len(orders) == 0:
                print('                                  NO OPEN ORDERS')
            print('')
            print('%s BALANCE:' % BitPAIR)
            print(balances)
            print('')
            print('MARKET HISTORY:', stale, 'since last trade')
            for t in trades:
                # print(t.items())
                print(t['unix'],
                      str(t['time'])[11:19], t['fprice'],
                      ('%.4f' % float(t['quote']['amount'])).rjust(12, ' '))
            print('')
            print('ctrl+shift+\ will EXIT to terminal')
            print('')
            print('COMPLETE HOLDINGS:')
            print(cbalances)
        except:
            pass