Exemplo n.º 1
0
def order_and_cancel():
    cybex_config(node_rpc_endpoint=NODE_WS_ENDPOINT, chain_id=CHAIN_ID)

    net = BitShares(node=NODE_WS_ENDPOINT, **{'prefix': 'CYB'})

    unlock(net)

    try:
        net.wallet.addPrivateKey('your active private key')
    except Exception as e:
        pass

    net.wallet.unlock('your wallet unlock password')

    account = Account('account name', bitshares_instance=net)

    market = Market(base=Asset('CYB'),
                    quote=Asset('JADE.ETH'),
                    bitshares_instance=net)

    # buy 0.001 JADE.ETH at price JADE.ETH:CYB 1000, expire in 60 seconds
    # market.sell will do the sell operation
    market.buy(1000, 0.001, 60, False, 'account name', 'Head')

    # query open orders
    for order in account.openorders:
        base_amount = order['base'].amount
        base_symbol = order['base'].symbol
        quote_amount = order['quote'].amount
        quote_symbol = order['quote'].symbol
        order_number = order['id']
        print('{}:{}--{}/{}'.format(quote_symbol, base_symbol, quote_amount,
                                    base_amount))
        # cancel order
        market.cancel(order_number, 'account name')
Exemplo n.º 2
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}")
Exemplo n.º 3
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())
Exemplo n.º 4
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}")
Exemplo n.º 5
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
Exemplo n.º 6
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))