Exemple #1
0
def get_order_book_cmc(base, quote, limit=False):
    baseID = bitshares_ws_client.request('database', 'lookup_asset_symbols',
                                         [[base], 0])[0]
    quoteID = bitshares_ws_client.request('database', 'lookup_asset_symbols',
                                          [[quote], 0])[0]

    limit = _ensure_safe_limit(limit)
    order_book = bitshares_ws_client.request(
        'database', 'get_order_book', [baseID['id'], quoteID['id'], limit])

    result = {
        'asks': [],
        'bids': [],
        'LastUpdateTimestamp':
        str(datetime.datetime.now().replace(microsecond=0).isoformat())
    }

    for order in order_book['bids']:
        result['bids'].append([
            round(float(order['quote']) / float(order['base']), 8),
            order['base']
        ])

    for order in order_book['asks']:
        result['asks'].append([
            round(float(order['quote']) / float(order['base']), 8),
            order['base']
        ])

    return result
Exemple #2
0
def get_all_activenodes():
    look_for_nodes = bitshares_ws_client.request('database',
                                                 'lookup_activenode_accounts',
                                                 [0, 1000])
    all_activenode_count = len(look_for_nodes)
    global_properties = bitshares_ws_client.get_global_properties()
    activenode_count = len(global_properties["current_activenodes"])
    activenodes = bitshares_ws_client.request(
        'database', 'get_objects',
        [[look_for_nodes[w][1] for w in range(0, all_activenode_count)]])

    now = str(datetime.datetime.now(pytz.timezone('Etc/GMT+0')).time())
    x = time.strptime(now.split('.')[0], '%H:%M:%S')
    seconds = datetime.timedelta(hours=x.tm_hour,
                                 minutes=x.tm_min,
                                 seconds=x.tm_sec).total_seconds()

    result = []
    for activenode in activenodes:
        if activenode:
            activenode["activenode_account_name"] = get_account_name(
                activenode["activenode_account"])
            activenode["activities_approx_count"] = round(
                ((seconds) / 2) / activenode_count)  #localtime +2 hours
            activenode["activities_aprrox_missed_activities"] = round(
                (activenode["activities_approx_count"] -
                 activenode["activities_sent"]) /
                activenode["activities_approx_count"] * 100)
            result.append([activenode])

    return activenodes
Exemple #3
0
def get_workers():
    workers_count = bitshares_ws_client.request('database', 'get_worker_count',
                                                [])
    workers = bitshares_ws_client.request(
        'database', 'get_objects',
        [['1.14.{}'.format(i) for i in range(0, workers_count)]])

    # get the votes of worker 1.14.0 - refund 400k
    #refund400k = bitshares_ws_client.get_object("1.14.0")
    #thereshold =  int(refund400k["total_votes_for"])

    result = []
    for worker in workers:
        if worker:
            worker["worker_account_name"] = get_account_name(
                worker["worker_account"])
            current_votes = int(worker["total_votes_for"])
            perc = (
                current_votes * 100
            ) / 28945815532168  #TODO: change to "thereshold" / changed for test run
            worker["perc"] = perc
            result.append([worker])

    result = result[::-1]  # Reverse list.
    return result
def get_market_chart_data(base, quote):
    base_asset = bitshares_ws_client.request('database',
                                             'lookup_asset_symbols',
                                             [[base], 0])[0]
    base_id = base_asset["id"]
    base_precision = 10**base_asset["precision"]

    quote_asset = bitshares_ws_client.request('database',
                                              'lookup_asset_symbols',
                                              [[quote], 0])[0]
    quote_id = quote_asset["id"]
    quote_precision = 10**quote_asset["precision"]

    now = datetime.date.today()
    ago = now - datetime.timedelta(days=100)
    market_history = bitshares_ws_client.request(
        'history', 'get_market_history', [
            base_id, quote_id, 86400,
            ago.strftime("%Y-%m-%dT%H:%M:%S"),
            now.strftime("%Y-%m-%dT%H:%M:%S")
        ])

    data = []
    for market_operation in market_history:

        open_quote = float(market_operation["open_quote"])
        high_quote = float(market_operation["high_quote"])
        low_quote = float(market_operation["low_quote"])
        close_quote = float(market_operation["close_quote"])

        open_base = float(market_operation["open_base"])
        high_base = float(market_operation["high_base"])
        low_base = float(market_operation["low_base"])
        close_base = float(market_operation["close_base"])

        open = 1 / (float(open_base / base_precision) /
                    float(open_quote / quote_precision))
        high = 1 / (float(high_base / base_precision) /
                    float(high_quote / quote_precision))
        low = 1 / (float(low_base / base_precision) /
                   float(low_quote / quote_precision))
        close = 1 / (float(close_base / base_precision) /
                     float(close_quote / quote_precision))

        ohlc = [open, close, low, high]

        data.append(ohlc)

    append = [0, 0, 0, 0]
    if len(data) < 99:
        complete = 99 - len(data)
        for c in range(0, complete):
            data.insert(0, append)

    return data
Exemple #5
0
def get_trade_history2(base, quote, limit):
    baseID = bitshares_ws_client.request('database', 'lookup_asset_symbols',
                                         [[base], 0])[0]
    quoteID = bitshares_ws_client.request('database', 'lookup_asset_symbols',
                                          [[quote], 0])[0]

    now = str(datetime.datetime.now().isoformat())
    results = bitshares_ws_client.request(
        'database', 'get_trade_history',
        [quote, base, now, "2019-01-01T00:00:00", limit])

    for result in results:
        operations = es_wrapper.get_account_history(
            account_id=result["side2_account_id"], operation_type=4, size=1000)

        amountNeedle = str(int(str(result["value"]).replace('.', '')))
        quoteNeedle = str(int(str(result["amount"]).replace('.', '')))

        is_maker = True

        for operation in operations:
            if 'operation_history' in operation:
                operationHistory = operation['operation_history']
                if 'op' in operationHistory:
                    items = json.loads(operationHistory['op'])
                    for item in items:
                        if type(
                                item
                        ) is not int and 'receives' in item and 'pays' in item:
                            if str(
                                    item['receives']
                                ['amount']).find(amountNeedle) == 0 and str(
                                    item['pays']['amount']
                                ).find(quoteNeedle) == 0 and item['receives'][
                                    'asset_id'] == quoteID['id'] and item[
                                        'pays']['asset_id'] == baseID['id']:
                                is_maker = item['is_maker']

        if 'is_maker' in result:
            result.pop("is_maker")

        result["side1"] = get_account(
            result.pop("side1_account_id"))[0]["name"]
        result["side2"] = get_account(
            result.pop("side2_account_id"))[0]["name"]
        result["time"] = result.pop("date")
        result["marketPair"] = base + '_' + quote
        result["tradeID"] = result.pop("sequence")
        result["baseVolume"] = result.pop("value")
        result["quoteVolume"] = result.pop("amount")
        result["isBuyerMaker"] = is_maker == False
    #result["markets"] = get_markets(quote)

    return results
def get_witnesses():
    witnesses_count = bitshares_ws_client.request('database', 'get_witness_count', [])
    witnesses = bitshares_ws_client.request('database', 'get_objects', [ ['1.6.{}'.format(w) for w in range(0, witnesses_count)] ])
    result = []
    for witness in witnesses:
        if witness:
            witness["witness_account_name"] = get_account_name(witness["witness_account"])
            result.append(witness)

    result = sorted(result, key=lambda k: int(k['total_votes']))
    result = result[::-1] # Reverse list.
    return result
Exemple #7
0
def get_trade_history(base, quote, bucket):
    baseID = bitshares_ws_client.request('database', 'lookup_asset_symbols',
                                         [[base], 0])[0]
    quoteID = bitshares_ws_client.request('database', 'lookup_asset_symbols',
                                          [[quote], 0])[0]
    now = str(datetime.datetime.now().isoformat())

    result = bitshares_ws_client.request(
        'history', 'get_market_history',
        [baseID["id"], quoteID["id"], bucket, "2019-01-01T00:00:00", now])

    return list(reversed(result))
def get_committee_members():
    committee_count = bitshares_ws_client.request('database', 'get_committee_count', [])
    committee_members = bitshares_ws_client.request('database', 'get_objects', [ ['1.5.{}'.format(i) for i in range(0, committee_count)] ])

    result = []
    for committee_member in committee_members:
        if committee_member:
            committee_member["committee_member_account_name"] = get_account_name(committee_member["committee_member_account"])
            result.append([committee_member])

    result = sorted(result, key=lambda k: int(k[0]['total_votes']))
    result = result[::-1] # this reverses array

    return result
def get_account_history(account_id):
    account_id = get_account_id(account_id)

    account_history = bitshares_ws_client.request('history', 'get_account_history', [account_id, "1.11.1", 20, "1.11.9999999999"])

    if(len(account_history) > 0):
        for transaction in account_history:
            creation_block = bitshares_ws_client.request('database', 'get_block_header', [str(transaction["block_num"]), 0])
            transaction["timestamp"] = creation_block["timestamp"]
            transaction["witness"] = creation_block["witness"]
    try:
        return account_history
    except:
        return {}
def get_market_ticker(base, quote):
    ticker = bitshares_ws_client.request('database', 'get_ticker',
                                         [base, quote])

    asset_base = bitshares_ws_client.request('database',
                                             'lookup_asset_symbols',
                                             [[base], 0])[0]
    asset_quote = bitshares_ws_client.request('database',
                                              'lookup_asset_symbols',
                                              [[quote], 0])[0]
    ticker["id"] = asset_base["id"].replace(
        "1.3.", "") + "_" + asset_quote["id"].replace("1.3.", "")

    return ticker
Exemple #11
0
def _get_accounts_by_chunks_via_ws(account_ids, chunk_size=1000):
    all_accounts = []
    for i in xrange(0, len(account_ids), chunk_size):
        accounts = bitshares_ws_client.request('database', 'get_accounts',
                                               [account_ids[i:i + chunk_size]])
        all_accounts.extend(accounts)
    return all_accounts
def _ensure_asset_id(asset_id):
    if not _is_object(asset_id):
        asset = bitshares_ws_client.request('database', 'lookup_asset_symbols',
                                            [[asset_id], 0])[0]
        return asset['id']
    else:
        return asset_id
def get_workers_votes():
    proxies = get_top_proxies()
    proxies = proxies[:10]
    proxies = bitshares_ws_client.request('database', 'get_objects',
                                          [[p['id'] for p in proxies]])

    workers = get_workers()
    workers = workers[:30]

    workers_votes = []
    for worker in workers:
        vote_id = worker[0]["vote_for"]
        id_worker = worker[0]["id"]
        worker_account_name = worker[0]["worker_account_name"]
        worker_name = worker[0]["name"]
        proxy_votes = _get_formatted_proxy_votes(proxies, vote_id)

        workers_votes.append({
            'worker_account_name': worker_account_name,
            'worker_id': id_worker,
            'worker_name': worker_name,
            'top_proxy_votes': proxy_votes
        })

    return workers_votes
Exemple #14
0
def _get_account_id(account_name):
    if not _is_object(account_name):
        account = bitshares_ws_client.request('database',
                                              'lookup_account_names',
                                              [[account_name], 0])
        return account[0]['id']
    else:
        return account_name
def get_asset(asset_id):
    asset = None
    if not _is_object(asset_id):
        asset = bitshares_ws_client.request('database', 'lookup_asset_symbols', [[asset_id], 0])[0]
    else:
        asset = bitshares_ws_client.request('database', 'get_assets', [[asset_id], 0])[0]
    
    dynamic_asset_data = bitshares_ws_client.get_object(asset["dynamic_asset_data_id"])
    asset["current_supply"] = dynamic_asset_data["current_supply"]
    asset["confidential_supply"] = dynamic_asset_data["confidential_supply"]
    asset["accumulated_fees"] = dynamic_asset_data["accumulated_fees"]
    asset["fee_pool"] = dynamic_asset_data["fee_pool"]

    issuer = bitshares_ws_client.get_object(asset["issuer"])
    asset["issuer_name"] = issuer["name"]

    return asset
def get_history(symbol, to, resolution):
    from_ = connexion.request.args.get('from')

    buckets = BUCKET_CONFIG.get(resolution, '86400')
    base, quote = symbol.split('_')

    results = {}

    base_asset = bitshares_ws_client.request('database', 'lookup_asset_symbols', [ [ base ], 0])[0]
    base_id = base_asset["id"]
    base_precision = 10**base_asset["precision"]

    quote_asset = bitshares_ws_client.request('database', 'lookup_asset_symbols', [ [ quote ], 0])[0]
    quote_id = quote_asset["id"]
    quote_precision = 10**quote_asset["precision"]


    base_1, base_2, base_3 = base_id.split('.')
    quote_1, quote_2, quote_3 = quote_id.split('.')
    invert = bool(int(base_3) > int(quote_3))

    left = datetime.fromtimestamp(int(from_)).strftime('%Y-%m-%dT%H:%M:%S')
    right = datetime.fromtimestamp(int(to)).strftime('%Y-%m-%dT%H:%M:%S')

    results = {
        't': [],
        'c': [],
        'o': [],
        'h': [],
        'l': [],
        'v': []
    }

    len_result = _load_next_market_history(base_id, base_precision, quote_id, quote_precision, invert, buckets, left, right, results)

    counter = 0
    while len_result == 200:
        counter = counter + 200

        left = datetime.fromtimestamp(int(result['t'][-1]+1)).strftime('%Y-%m-%dT%H:%M:%S')
        len_result = _load_next_market_history(base_id, base_precision, quote_id, quote_precision, invert, buckets, left, right, results)

    results["s"] = "ok"

    return results
def get_grouped_limit_orders(quote, base, group=10, limit=False):
    limit = _ensure_safe_limit(limit)    

    base = _ensure_asset_id(base)
    quote = _ensure_asset_id(quote)

    grouped_limit_orders = bitshares_ws_client.request('orders', 'get_grouped_limit_orders', [base, quote, group, None, limit])

    return grouped_limit_orders
def get_all_asset_holders(asset_id):
    asset_id = _ensure_asset_id(asset_id)

    all = []

    asset_holders = bitshares_ws_client.request('asset', 'get_asset_holders', [asset_id, 0, 100])

    all.extend(asset_holders)

    len_result = len(asset_holders)
    start = 100
    while  len_result == 100:
        start = start + 100
        asset_holders = bitshares_ws_client.request('asset', 'get_asset_holders', [asset_id, start, 100])
        len_result = len(asset_holders)
        all.extend(asset_holders)

    return all
Exemple #19
0
def _load_next_market_history(base_id, base_precision, quote_id,
                              quote_precision, invert, buckets, from_, to_,
                              results):
    history = bitshares_ws_client.request(
        'history', 'get_market_history',
        [base_id, quote_id, buckets, from_, to_])

    for quote in history:

        open_quote = float(quote["open_quote"])
        high_quote = float(quote["high_quote"])
        low_quote = float(quote["low_quote"])
        close_quote = float(quote["close_quote"])
        close_quote = float(quote["close_quote"])
        quote_volume = int(quote["quote_volume"])

        open_base = float(quote["open_base"])
        high_base = float(quote["high_base"])
        low_base = float(quote["low_base"])
        close_base = float(quote["close_base"])
        base_volume = int(quote["base_volume"])

        if invert:
            open = 1 / (float(open_base / quote_precision) /
                        float(open_quote / base_precision))
            high = 1 / (float(high_base / quote_precision) /
                        float(high_quote / base_precision))
            low = 1 / (float(low_base / quote_precision) /
                       float(low_quote / base_precision))
            close = 1 / (float(close_base / quote_precision) /
                         float(close_quote / base_precision))
            volume = base_volume
        else:
            open = (float(open_base / base_precision) /
                    float(open_quote / quote_precision))
            high = (float(high_base / base_precision) /
                    float(high_quote / quote_precision))
            low = (float(low_base / base_precision) /
                   float(low_quote / quote_precision))
            close = (float(close_base / base_precision) /
                     float(close_quote / quote_precision))
            volume = quote_volume

        results['c'].append(close)
        results['o'].append(open)
        results['h'].append(high)
        results['l'].append(low)
        results['v'].append(volume)

        date = datetime.strptime(quote["key"]["open"], "%Y-%m-%dT%H:%M:%S")
        ts = calendar.timegm(date.utctimetuple())
        results['t'].append(ts)

    return len(history)
Exemple #20
0
def get_market_ticker(base, quote):
    ticker = bitshares_ws_client.request('database', 'get_ticker',
                                         [base, quote])

    asset_base = bitshares_ws_client.request('database',
                                             'lookup_asset_symbols',
                                             [[base], 0])[0]
    asset_quote = bitshares_ws_client.request('database',
                                              'lookup_asset_symbols',
                                              [[quote], 0])[0]
    ticker["tradeID"] = asset_base["id"].replace(
        "1.3.", "") + "_" + asset_quote["id"].replace("1.3.", "")

    ticker["lastUpdateTimestamp"] = ticker.pop("time")
    ticker["tradingPairs"] = ticker["quote"] + "_" + ticker["base"]
    ticker["LastPrice"] = ticker.pop("latest")
    ticker["lowestAsk"] = ticker.pop("lowest_ask")
    ticker["highestBid"] = ticker.pop("highest_bid")
    ticker["baseVolume24h"] = ticker.pop("base_volume")
    ticker["quoteVolume24h"] = ticker.pop("quote_volume")
    ticker["tradesEnabled"] = True

    return ticker
def get_witnesses_votes():
    proxies = get_top_proxies()
    proxies = proxies[:10]
    proxies = bitshares_ws_client.request('database', 'get_objects', [[ p[0] for p in proxies ]])

    witnesses = get_witnesses()
    witnesses = witnesses[:25] # FIXME: Witness number is variable.

    witnesses_votes = []
    for witness in witnesses:
        vote_id =  witness[0]["vote_id"]
        id_witness = witness[0]["id"]
        witness_account_name = witness[0]["witness_account_name"]
        proxy_votes = _get_formatted_proxy_votes(proxies, vote_id)        

        witnesses_votes.append([witness_account_name, id_witness] + proxy_votes)

    return witnesses_votes
def get_committee_votes():
    proxies = get_top_proxies()
    proxies = proxies[:10]
    proxies = bitshares_ws_client.request('database', 'get_objects', [[ p[0] for p in proxies ]])

    committee_members = get_committee_members()
    committee_members = committee_members[:11]

    committee_votes = []
    for committee_member in committee_members:
        vote_id =  committee_member[0]["vote_id"]
        id_committee = committee_member[0]["id"]
        committee_account_name = committee_member[0]["committee_member_account_name"]
        proxy_votes = _get_formatted_proxy_votes(proxies, vote_id)        

        committee_votes.append([committee_account_name, id_committee] + proxy_votes)

    return committee_votes
def get_symbols(symbol):
    base, quote = symbol.split('_')

    asset = bitshares_ws_client.request('database', 'lookup_asset_symbols', [ [ base ], 0])[0]
    base_precision = 10**asset["precision"]

    return {
        "name": symbol,
        "ticker": symbol,
        "description": base + "/" + quote,
        "type": "",
        "session": "24x7",
        "exchange": "",
        "listed_exchange": "",
        "timezone": "Europe/London",
        "minmov": 1,
        "pricescale": base_precision,
        "minmove2": 0,
        "fractional": False,
        "has_intraday": True,
        "supported_resolutions": ["1", "5", "15", "30", "60", "240", "1D"],
        "intraday_multipliers": "",
        "has_seconds": False,
        "seconds_multipliers": "",
        "has_daily": True,
        "has_weekly_and_monthly": False,
        "has_empty_bars": True,
        "force_session_rebuild": "",
        "has_no_volume": False,
        "volume_precision": "",
        "data_status": "",
        "expired": "",
        "expiration_date": "",
        "sector": "",
        "industry": "",
        "currency_code": ""
    }
def get_time():
    dynamic_global_properties = bitshares_ws_client.request('database', 'get_dynamic_global_properties', [])
    date = datetime.strptime(dynamic_global_properties["time"], "%Y-%m-%dT%H:%M:%S")
    return str(calendar.timegm(date.utctimetuple()))
def get_full_account(account_id):
    account = bitshares_ws_client.request('database', 'get_full_accounts', [[account_id], 0])[0][1]
    return account
def get_fill_order_history(base, quote):
    fill_order_history = bitshares_ws_client.request('history', 'get_fill_order_history', [base, quote, 100])
    return fill_order_history
def get_last_block_time():
    dynamic_global_properties = bitshares_ws_client.request('database', 'get_dynamic_global_properties', [])
    return dynamic_global_properties["time"]
def get_last_block_number():
    dynamic_global_properties = bitshares_ws_client.request('database', 'get_dynamic_global_properties', [])
    return dynamic_global_properties["head_block_number"]
def lookup_accounts(start):
    accounts = bitshares_ws_client.request('database', 'lookup_accounts', [start, 1000])
    return accounts
def get_margin_positions(account_id):
    margin_positions = bitshares_ws_client.request('database', 'get_margin_positions', [account_id])
    return margin_positions