示例#1
0
def fill_out_dates(transactions):
    fill_dates = []
    prices = PriceInfo.get_instance().prices
    # Filling in dates up to the last transaction
    for tx_index, tx in enumerate(transactions[0:-1]):
        for i in timestamps_between_transactions(
                transactions[tx_index]["timeStamp"],
                transactions[tx_index + 1]["timeStamp"]):
            values = {}
            token_prices = {}
            if transactions[tx_index].get("values", None):
                for key, value in transactions[tx_index]["values"].items():
                    values[key] = 0
                    token_prices[key] = get_price(
                        i, key,
                        PriceInfo.get_instance().prices)
            fill_dates.append({
                "timeStamp": i,
                "values": values,
                "prices": token_prices,
                "isError": 0,
            })

    # Filling in dates from the last transaction until now
    now_timestamp = datetime.datetime(
        *datetime.datetime.utcnow().timetuple()[:3]).timestamp()
    for i in timestamps_between_transactions(transactions[-1]["timeStamp"],
                                             now_timestamp):
        values = {}
        token_prices = {}
        if transactions[tx_index].get("values", None):
            for key, value in transactions[-1]["values"].items():
                values[key] = 0
                token_prices[key] = get_price(i, key, prices)
        fill_dates.append({
            "timeStamp": i,
            "values": values,
            "prices": token_prices,
            "isError": 0
        })
    # FIXME: This is using local time, but tx timestamps are in UTC. This should changed to UTC
    # and timezone conversion should be done later or on the frontend
    now = int(datetime.datetime.now().timestamp())
    values = {}
    token_prices = {}
    if transactions[tx_index].get("values", None):
        for key, value in transactions[-1]["values"].items():
            values[key] = 0
            token_prices[key] = get_price(now, key, prices)
    fill_dates.append({
        "timeStamp": now,
        "values": values,
        "prices": token_prices,
        "isError": 0
    })
    for i in fill_dates:
        transactions.append(i)
    transactions.sort(key=sortTransactions)

    return transactions
示例#2
0
def balance_calc(balances, transaction):
    contract_info = Contracts.get_instance()
    price_info = PriceInfo.get_instance()
    for i, key in enumerate(transaction["values"]):
        if not key in price_info.all_tokens:
            price_info.all_tokens.append(key)
        value = transaction["values"][key]
        balances[key] = (balances.get(key) or 0) + value
    transaction["balances"] = dict(balances)
    for token in transaction["balances"]:
        transaction["prices"][token] = get_price(
            transaction["timeStamp"], token,
            PriceInfo.get_instance().prices)
    tempBalArrays = [[
        key, balances[key], transaction["prices"], transaction["timeStamp"],
        contract_info.get_contract(symbol=key).address
    ] for i, key in enumerate(balances)]
    usd = reduce(balancesUSD, tempBalArrays, {})
    transaction["balancesUSD"] = dict(usd)
    return balances
示例#3
0
def test_get_price():
    # Given: a subscription type junior picked.
    # When: we pass it to get_price function.
    # Then: it should be equal to 2391.
    assert get_price(SubscriptionForm.JUNIOR) == 2391
示例#4
0
def get_batched_positions(batched_data, index):
    price_info = PriceInfo.get_instance()
    positions = {}
    index_map = {}
    start_timestamps = []
    token_balance = {}
    query = """
        {
        """
    for i, timestamp in enumerate(batched_data):
        symbol_data = batched_data[timestamp]
        index_map[timestamp] = index_map.get(timestamp) or {}
        for j, symbol in enumerate(symbol_data):
            args = symbol_data[symbol]
            index_map[timestamp][symbol] = index_map[timestamp].get(symbol) or {}
            if not args[0] in start_timestamps:
                query_id = f"position{index}"
                index_map[timestamp][symbol]["start"] = index
                query += (get_batched_query(args[0], args[2], query_id))
                token_balance[query_id] = (args[3])
                index += 1
            else:
                index_map[timestamp][symbol]["start"] = start_timestamps.index(args[0])
            query_id = f"position{index}"
            index_map[timestamp][symbol]["end"] = index
            query += (get_batched_query(args[1], args[2],query_id))
            token_balance[query_id] = (args[3])
            index += 1
    query += ("""
        }""")
    statusCode = 200
    headers = {}
    uri = "https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v2"
    results = run_query(uri, query, statusCode, headers)
    if not results.get("data"):
        print(results)
        return None
    for ind, query_id in enumerate(results["data"]):
        position = results["data"][query_id]
        if not position:
            positions[query_id] = None
        else:
            token0 = (
                "ETH"
                if position["token0"]["symbol"] == "WETH"
                else position["token0"]["symbol"]
            )
            token1 = (
                "ETH"
                if position["token1"]["symbol"] == "WETH"
                else position["token1"]["symbol"]
            )
            positions[query_id] = {
                "pair": f"{token0}/{token1}",
                "timestamp": int(position["date"]),
                "liquidityTokenBalance": float(token_balance[query_id]),
                "reserve0": float(position["reserve0"]),
                "reserve1": float(position["reserve1"]),
                "reserveUSD": float(position["reserveUSD"]),
                "liquidityTokenTotalSupply": float(
                    position["totalSupply"]
                ),
                "token0PriceUSD": get_price(int(position["date"]), token0, price_info.prices),
                "token1PriceUSD": get_price(int(position["date"]), token1, price_info.prices),
            }
    return [positions, index_map, index]
示例#5
0
def get_positions(timestamp1, timestamp2, pair_address, token_balance):
    price_info = PriceInfo.get_instance()
    uri = "https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v2"
    day_id1 = int(timestamp1 / 86400)
    pair_day_id1 = f"{pair_address.lower()}-{day_id1}"
    day_id2 = int(timestamp2 / 86400)
    pair_day_id2 = f"{pair_address.lower()}-{day_id2}"
    query = """
        {{
            position1: pairDayData(id: "{pair_day_id1}") {{
                date
                pairAddress
                token0 {{
                    symbol
                }}
                token1 {{
                    symbol
                }}
                reserve0
                reserve1
                totalSupply
                reserveUSD
            }}
            position2: pairDayData(id: "{pair_day_id2}") {{
                date
                pairAddress
                token0 {{
                    symbol
                }}
                token1 {{
                    symbol
                }}
                reserve0
                reserve1
                totalSupply
                reserveUSD
            }}
        }}
        """
    query = query.format(pair_day_id1=pair_day_id1, pair_day_id2=pair_day_id2)
    statusCode = 200
    headers = {}
    attempt = 0
    results = run_query(uri, query, statusCode, headers, "liquidity_pools_query")
    if (
        not results.get("data")
        or not results["data"].get("position1")
        or not results["data"].get("position2")
    ):
        return None
    token0 = (
        "ETH"
        if results["data"]["position1"]["token0"]["symbol"] == "WETH"
        else results["data"]["position1"]["token0"]["symbol"]
    )
    token1 = (
        "ETH"
        if results["data"]["position1"]["token1"]["symbol"] == "WETH"
        else results["data"]["position1"]["token1"]["symbol"]
    )
    return [
        {
            "pair": None,
            "timestamp": int(timestamp1),
            "liquidityTokenBalance": float(token_balance),
            "reserve0": float(results["data"]["position1"]["reserve0"]),
            "reserve1": float(results["data"]["position1"]["reserve1"]),
            "reserveUSD": float(results["data"]["position1"]["reserveUSD"]),
            "liquidityTokenTotalSupply": float(
                results["data"]["position1"]["totalSupply"]
            ),
            "token0PriceUSD": get_price(timestamp1, token0, price_info.prices),
            "token1PriceUSD": get_price(timestamp1, token1, price_info.prices),
        },
        {
            "pair": None,
            "timestamp": int(timestamp2),
            "liquidityTokenBalance": float(token_balance),
            "reserve0": float(results["data"]["position2"]["reserve0"]),
            "reserve1": float(results["data"]["position2"]["reserve1"]),
            "reserveUSD": float(results["data"]["position2"]["reserveUSD"]),
            "liquidityTokenTotalSupply": float(
                results["data"]["position2"]["totalSupply"]
            ),
            "token0PriceUSD": get_price(timestamp2, token0, price_info.prices),
            "token1PriceUSD": get_price(timestamp2, token1, price_info.prices),
        },
    ]