Esempio 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')
Esempio n. 2
0
def test_get_own_last_trade_taker_sell(base_account, ro_worker, other_worker):
    """Test for https://github.com/Codaone/DEXBot/issues/708."""
    worker1 = ro_worker
    worker3 = base_account()
    market1 = Market(worker1.worker["market"])

    # Fill worker's order from different account
    # Note this order is significantly bigger by amount and lower by price than worker's order
    sell_orders1 = worker1.get_own_sell_orders()
    to_buy = sell_orders1[0]['base']['amount'] * 1.5
    buy_price = sell_orders1[0]['price'] * 1.2
    log.debug('Buying {} @ {} by worker3 from worker1'.format(
        to_buy, buy_price))
    tx = market1.buy(buy_price, to_buy, account=worker3)
    log.debug(tx)

    # Bot uses last own trade price and acts as a taker
    worker1.is_center_price_dynamic = True
    worker1.cp_from_last_trade = True
    worker1['bootstrapped'] = True
    time.sleep(1.1)
    worker1.check_orders()

    # Expect correct last trade
    result = worker1.get_own_last_trade()
    assert result['price'] == pytest.approx(
        buy_price, rel=(10**-worker1.market['base']['precision']))
def mySell(ccy_quot, ccy_base, amount_quot, amount_base, amount, account, bitshares):
    if account.name != "test2017":
        # Use account test2017 to simulate the market reactivity to offer and demand
        acc2 = accounts["test2017"]
        bts2 = BitShares(btsNode, acc2.name, acc2.pwd)
        market = Market(ccy_quot + ":" + ccy_base, bitshares_instance=bts2)
        bts2.wallet.unlock("supersecret")
        market.buy(Price(amount_quot, amount_base, bitshares_instance=bts2), Amount(str(amount) + " " + ccy_quot, bitshares_instance=bts2), account=Account(acc2.name, bitshares_instance=bts2))
        bts2.wallet.lock()

    market = Market(ccy_quot + ":" + ccy_base, bitshares_instance=bitshares)
    bitshares.wallet.unlock("supersecret")
    market.sell(Price(amount_quot, amount_base, bitshares_instance=bitshares), Amount(str(amount) + " " + ccy_quot, bitshares_instance=bitshares), account=account)
    bitshares.wallet.lock()

    sleep(2)
    return
Esempio n. 4
0
def buy(ordertype,
        base,
        price,
        amount,
        expiration=None,
        killfill=False,
        account=None,
        returnOrderId=False):
    from bitsharesbase.account import PasswordKey, PublicKey
    active_key = str(
        PasswordKey(account=MEMBER["account_name"],
                    password=MEMBER["password"],
                    role="active").get_private_key())
    bts_obj = BitShares(node=BITSHARES_NODE,
                        keys=active_key,
                        nobroadcast=NOBROADCAST)
    market = Market(base, bitshares_instance=bts_obj)
    order = market.buy(price, amount, expiration, killfill, account,
                       returnOrderId)
    print(" * Placed order: " + str(
        market.buy(price, amount, expiration, killfill, account,
                   returnOrderId)))
    bts_obj.clear()
    print()
Esempio n. 5
0
account = "alfredo-worker"
proposer = "oxarbitrage.a699"
vesting_id = "1.13.1608"

bitshares = BitShares(
    nobroadcast=False,
    bundle=True,
    proposer=proposer,
    proposal_expiration=60 * 60 * 24 * 2,
)
set_shared_bitshares_instance(bitshares)
market = Market("USD:BTS")
price = market.ticker()["quoteSettlement_price"]

bitshares.wallet.unlock(getpass())
vesting = Vesting(vesting_id)

print("Claiming Vesting Balance: %s" % vesting.claimable)
bitshares.vesting_balance_withdraw(vesting["id"],
                                   amount=vesting.claimable,
                                   account=account)

print("Buying as much bitUSD at price up to %s or %s" %
      (price * 0.90, (price * 0.90).copy().invert()))
market.buy(price * 0.9, Amount(3200, "USD"), killfill=True, account=account)

print("Worker alfredo payment - 15 days")
bitshares.transfer("oxarbitrage.a699", 3200, "USD", account=account)

pprint(bitshares.broadcast())
Esempio n. 6
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
Esempio n. 7
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))
Esempio n. 8
0
pw = input("please input the pw: ")
bts.wallet.unlock(pw)
dexmarket = Market('BTS/GDEX.USDT', blockchain_instance=bts)

while True:
    ##get huobi and bts tickers
    huobidepth = market_client.get_pricedepth("btsusdt", DepthStep.STEP0, 1)
    dexticker = dexmarket.orderbook(limit=1)

    dexbid = dexticker['bids'][0]
    dexask = dexticker['asks'][0]

    huobibid = huobidepth.bids[0]
    huobiask = huobidepth.asks[0]
    
    ##compare the ticker and place orders if there are trading chances:
    if dexbid.price > huobiask.price * 1.006 and min(dexbid['quote'].amount, huobiask.amount) > 100:
        huobibuyorder_id = trade_client.create_order(symbol='btsusdt', account_id=88888888, order_type='buy-limit',
                                         source="api", amount=100, price=huobiask.price)
        dexmarket.sell(price=dexbid.price, amount=100, account='test')
    else:
        print('no chance for trading, dex bid price is %.5f and huobi ask price is %.5f' % (dexbid.price, huobiask.price))

    if dexask.price*1.006 < huobibid.price and min(dexask['quote'].amount,huobiask.amount)>100:
        huobisellorder_id = trade_client.create_order(symbol='btsusdt', account_id=88888888, order_type='sell-limit',
                                                     source="api", amount=100, price=huobibid.price)
        dexmarket.buy(price=dexask.price, amount=100, account='test')
    else:
        print('no chance for trading, dex ask price is %.5f and huobi bid price is %.5f' % (dexask.price, huobibid.price))
    time.sleep(5)