PeakeCoin uni_bot Fetch Market - fetch_market.pysteemCreated with Sketch.

in #marliansyesterday

🧠 Understanding get_orderbook_top in PeakeCoin Trading Scripts

If you've ever worked with Hive Engine's market API, you know it can be a bit of a dance to pull accurate buy and sell data. That's where the function get_orderbook_top comes in — a compact, effective tool for fetching the current highest bid and lowest ask for any token listed on Hive Engine.

But if you peek at the code (pun intended), you might notice that the function sets "SWAP.LTC" as the default token parameter. Let’s talk about why.


🎯 Why SWAP.LTC?

The line:

def get_orderbook_top(token="SWAP.LTC"):

simply defines a default argument. That means if no token is specified when the function is called, it'll automatically use SWAP.LTC.

This is not a hardcoded limit — just a convenience.

📌 What does this mean?

  • It makes testing easier. You can run the function without passing a token and still get real, valid market data.
  • It gives developers a reference token to test and debug on a live market that likely has active trades.
  • You can swap it for PEK, SWAP.BTC, LEO, or any token Hive Engine supports — just pass it as an argument.
get_orderbook_top("SWAP.HIVE")  # Returns top bid and ask for SWAP.HIVE

🧰 Use Case in Your Codebase

Imagine you're running a trading bot or a price-checker tool. You don’t always want to hardcode every token. With a default like SWAP.LTC, the function is ready to return data without needing extra inputs.

This makes the function beginner-friendly while still being fully customizable for advanced users.


💡 Pro Tip

When writing utility functions like this, a smart default token ensures you don’t run into API errors during early testing. But always override it with the token you're actually trading in production environments.


📦 Full Code

Below is the complete code from fetch_market.py, including the get_orderbook_top function and helper functions for fetching open orders.

import requests

def get_orderbook_top(token="SWAP.LTC"):
    # Pull top buy orders (usually works correctly with sorting)
    buy_payload = {
        "jsonrpc": "2.0",
        "method": "find",
        "params": {
            "contract": "market",
            "table": "buyBook",
            "query": {"symbol": token},
            "limit": 1000,
            "indexes": [{"index": "priceDec", "descending": True}]
        },
        "id": 1
    }

    # Pull up to 1000 sell orders to ensure we capture the true lowest ask
    sell_payload = {
        "jsonrpc": "2.0",
        "method": "find",
        "params": {
            "contract": "market",
            "table": "sellBook",
            "query": {"symbol": token},
            "limit": 1000,
            "indexes": [{"index": "price", "descending": False}]
        },
        "id": 2
    }

    # Request both buy and sell books
    buy_response = requests.post("https://api.hive-engine.com/rpc/contracts", json=buy_payload)
    sell_response = requests.post("https://api.hive-engine.com/rpc/contracts", json=sell_payload)

    if buy_response.status_code == 200 and sell_response.status_code == 200:
        buy_result = buy_response.json().get("result", [])
        sell_result = sell_response.json().get("result", [])

        # Use the highest priced buy order (top bid)
        highest_bid = float(buy_result[0]["price"]) if buy_result else 0

        # Use the true lowest sell price found in the result
        valid_asks = [float(order["price"]) for order in sell_result if float(order["price"]) > 0]
        lowest_ask = min(valid_asks) if valid_asks else 0

        return {"highestBid": highest_bid, "lowestAsk": lowest_ask}

    return None

def get_account_open_orders(account, limit=1000):
    """
    Fetch all open orders for the given account (across all tokens), paginated if needed.
    Returns a list of all open orders.
    """
    url = "https://api.hive-engine.com/rpc/contracts"
    all_orders = []
    offset = 0
    page_size = limit
    while True:
        payload = {
            "jsonrpc": "2.0",
            "method": "find",
            "params": {
                "contract": "market",
                "table": "openOrders",
                "query": {"account": account},
                "limit": page_size,
                "offset": offset
            },
            "id": 1
        }
        resp = requests.post(url, json=payload, timeout=10)
        if resp.status_code != 200:
            print(f"[ERROR] Failed to fetch open orders for {account} (status {resp.status_code})")
            break
        data = resp.json()
        orders = data.get('result')
        if not isinstance(orders, list):
            orders = []
        all_orders.extend(orders)
        if len(orders) < page_size:
            break
        offset += page_size
    return all_orders

def get_account_open_orders_all_tokens(account, limit=1000):
    """
    Fetch all open orders for the given account (across all tokens), paginated if needed.
    Returns a list of all open orders (all tokens).
    """
    url = "https://api.hive-engine.com/rpc/contracts"
    all_orders = []
    offset = 0
    page_size = limit
    while True:
        payload = {
            "jsonrpc": "2.0",
            "method": "find",
            "params": {
                "contract": "market",
                "table": "openOrders",
                "query": {"account": account},
                "limit": page_size,
                "offset": offset
            },
            "id": 1
        }
        resp = requests.post(url, json=payload, timeout=10)
        if resp.status_code != 200:
            print(f"[ERROR] Failed to fetch open orders for {account} (status {resp.status_code})")
            break
        data = resp.json()
        orders = data.get('result')
        if not isinstance(orders, list):
            orders = []
        all_orders.extend(orders)
        if len(orders) < page_size:
            break
        offset += page_size
    return all_orders
Sort:  

Upvoted! Thank you for supporting witness @jswit.