uni_pek.py Trading Bot - Cancellation Addition

0 comments

paulmoon4103 hours ago7 min read

If you've kept eyes on me I've been working on these bots for months. Now I've fixed what I found probematic...


I'm currently working on fixing place_order.py if you're running this. The cancellations aren't returning the correct output. I'll have it figured in no time.


from profit_strategies import get_profit_percent
import time
from fetch_market import get_orderbook_top
from place_order import place_order, get_open_orders, get_balance, buy_peakecoin_gas, cancel_oldest_order

# Hive account details
HIVE_ACCOUNT = "peakecoin"
HIVE_ACTIVE_KEY = "Your Active Key Here"  # Replace with your Hive active key
HIVE_NODES = ["https://api.hive.blog", "https://anyx.io"]
TOKEN = "SWAP.PEK"
DELAY = 1500
LOW_RC_CONSECUTIVE_COUNT = 0  # Track consecutive low RC occurrences
DYNAMIC_DELAY = DELAY  # Start with base delay

def get_resource_credits(account_name):
    try:
        import requests
        url = "https://api.hive.blog"
        payload = {
            "jsonrpc": "2.0",
            "method": "rc_api.find_rc_accounts",
            "params": {"accounts": [account_name]},
            "id": 1
        }
        resp = requests.post(url, json=payload, timeout=10)
        if resp.status_code == 200:
            data = resp.json()
            rc = data.get('result', {}).get('rc_accounts', [{}])[0]
            if rc and 'rc_manabar' in rc and 'max_rc' in rc:
                current = int(rc['rc_manabar']['current_mana'])
                max_rc = int(rc['max_rc'])
                percent = round(current / max_rc * 100, 2) if max_rc > 0 else 0.0
                return percent
    except Exception:
        pass
    return None

def get_total_orders_from_orderbook(account_name):
    """Fetch total order count from buyBook and sellBook (more reliable than openOrders)"""
    import requests
    try:
        combined = []
        nodes = ["https://api.hive-engine.com/rpc/contracts", "https://herpc.dtools.dev", "https://engine.rishipanthee.com/rpc"]
        for node in nodes:
            try:
                for table in ("buyBook", "sellBook"):
                    payload = {
                        "jsonrpc": "2.0",
                        "method": "find",
                        "params": {
                            "contract": "market",
                            "table": table,
                            "query": {"account": account_name},
                            "limit": 1000
                        },
                        "id": 1
                    }
                    r = requests.post(node, json=payload, timeout=10)
                    if r.status_code == 200:
                        res = r.json().get("result", [])
                        if isinstance(res, list):
                            combined.extend(res)
                if combined:
                    return len(combined)
            except Exception:
                continue
        return 0
    except Exception:
        return 0

def smart_trade(account_name, token):
    global LOW_RC_CONSECUTIVE_COUNT, DYNAMIC_DELAY
    
    print("\n==============================")
    print(f"[PEK BOT] Starting Smart Trade for {token}")
    
    # CHECK TOTAL OPEN ORDERS using orderbook (more reliable than openOrders table)
    open_count = get_total_orders_from_orderbook(account_name)
    print(f"[PEK BOT] Current total open orders (from orderbook): {open_count}")
    
    # If severely maxed out (200+), cancel multiple oldest orders
    if open_count >= 200:
        print(f"[PEK BOT] 🚨 CRITICAL: Account maxed out with {open_count} orders! Cancelling 3 oldest orders...")
        for i in range(3):
            try:
                cancel_oldest_order(account_name, None, active_key=HIVE_ACTIVE_KEY, nodes=HIVE_NODES)
                print(f"[PEK BOT] Cancelled oldest order {i+1}/3")
                time.sleep(2)
            except Exception as e:
                print(f"[PEK BOT] Failed to cancel order {i+1}: {e}")
        print(f"[PEK BOT] Skipping trade cycle to allow orders to clear.")
        print("==============================\n")
        return
    
    # If approaching limit, cancel one oldest order (any token)
    if open_count >= 195:
        print(f"[PEK BOT] ⚠️  SELF-REGULATION: Open orders ({open_count}) >= 195. Cancelling oldest order...")
        try:
            cancel_oldest_order(account_name, None, active_key=HIVE_ACTIVE_KEY, nodes=HIVE_NODES)
            print(f"[PEK BOT] Oldest order cancelled. Skipping trade cycle to maintain equilibrium.")
        except Exception as e:
            print(f"[PEK BOT] Failed to cancel oldest order: {e}")
        print("==============================\n")
        return
    
    # Cancel oldest order for THIS token ONLY if approaching limit
    if open_count >= 190:
        print(f"[PEK BOT] Open orders at {open_count}. Cancelling oldest {token} order...")
        cancel_result = cancel_oldest_order(account_name, token, active_key=HIVE_ACTIVE_KEY, nodes=HIVE_NODES)
        time.sleep(2)  # Give time for the cancellation to propagate
    else:
        print(f"[PEK BOT] Open orders at {open_count}. Skipping cancel (below 190 threshold).")
    
    rc_percent = get_resource_credits(account_name)
    if rc_percent is not None:
        print(f"[PEK BOT] Resource Credits: {rc_percent}%")
        if rc_percent < 10.0:
            LOW_RC_CONSECUTIVE_COUNT += 1
            DYNAMIC_DELAY = DELAY + (LOW_RC_CONSECUTIVE_COUNT * 300)
            print(f"[PEK BOT] WARNING: Resource Credits too low ({rc_percent}%). Skipping trade cycle.")
            print(f"[PEK BOT] Low RC count: {LOW_RC_CONSECUTIVE_COUNT}. Next delay: {DYNAMIC_DELAY}s ({DYNAMIC_DELAY/60:.1f} min)")
            print("==============================\n")
            return
        else:
            if LOW_RC_CONSECUTIVE_COUNT > 0:
                print(f"[PEK BOT] RC recovered! Resetting delay from {DYNAMIC_DELAY}s to {DELAY}s")
                LOW_RC_CONSECUTIVE_COUNT = 0
                DYNAMIC_DELAY = DELAY
    else:
        print(f"[PEK BOT] Resource Credits: Unable to fetch.")

    market = get_orderbook_top(token)
    if not market:
        print(f"[PEK BOT] Market fetch failed for {token}. Skipping this cycle.")
        print("==============================\n")
        # Buy smallest increment of SWAP.MATIC at market ask
        time.sleep(2)
        try:
            matic_market = get_orderbook_top("SWAP.MATIC")
            if matic_market and matic_market.get("lowestAsk"):
                matic_price = float(matic_market.get("lowestAsk"))
                place_order(account_name, "SWAP.MATIC", matic_price, 0.00000001, order_type="buy", active_key=HIVE_ACTIVE_KEY, nodes=HIVE_NODES)
                print(f"[PEK BOT] SWAP.MATIC buy attempted at {matic_price}.")
            else:
                print(f"[PEK BOT] SWAP.MATIC market unavailable, skipping buy.")
        except Exception as e:
            print(f"[PEK BOT] SWAP.MATIC buy exception: {e}")
        time.sleep(2)
        return
    print(f"[PEK BOT] Market fetch success for {token}.")
    bid = float(market.get("highestBid", 0))
    ask = float(market.get("lowestAsk", 0))
    buy_price = round(bid * 0.95, 8) if bid > 0 else 0  # Buy at 5% below highest bid
    sell_price = round(ask * 1.10, 8) if ask > 0 else 0  # Sell at 10% above current market ask
    hive_balance = get_balance(account_name, "SWAP.HIVE")
    pek_balance = get_balance(account_name, token)
    buy_qty = round(hive_balance * 0.20 / buy_price, 8) if buy_price > 0 else 0
    sell_qty = round(pek_balance * 0.20, 8)
    
    print(f"[PEK BOT] Preparing BUY: {buy_qty} {token} at {buy_price}")
    print(f"[PEK BOT] Preparing SELL: {sell_qty} {token} at {sell_price}")
    open_orders = get_open_orders(account_name, token)
    duplicate_buy = any(o.get('type') == 'buy' and float(o.get('price', 0)) == buy_price for o in open_orders)
    if buy_qty <= 0:
        print(f"[PEK BOT] Skipping BUY: buy_qty is zero or negative. Check HIVE balance and buy price.")
    elif duplicate_buy:
        print(f"[PEK BOT] Skipping BUY: Duplicate buy order at {buy_price} detected.")
    else:
        try:
            place_order(account_name, token, buy_price, buy_qty, order_type="buy", active_key=HIVE_ACTIVE_KEY, nodes=HIVE_NODES)
            print(f"[PEK BOT] BUY order submitted: {buy_qty} {token} at {buy_price}")
            time.sleep(5)
            open_orders = get_open_orders(account_name, token)
            if open_orders:
                print(f"[PEK BOT] Open orders after BUY: {len(open_orders)} found.")
            else:
                print(f"[PEK BOT] No open orders found after BUY (may be node delay).")
            time.sleep(1)
        except Exception as e:
            print(f"[PEK BOT] BUY order exception: {e}")
    
    # Place SELL order at market-based price
    if sell_price > 0 and sell_qty > 0:
        open_orders = get_open_orders(account_name, token)
        duplicate_sell = any(o.get('type') == 'sell' and float(o.get('price', 0)) == sell_price for o in open_orders)
        if duplicate_sell:
            print(f"[PEK BOT] Skipping SELL: Duplicate sell order at {sell_price} detected.")
        else:
            try:
                place_order(account_name, token, sell_price, sell_qty, order_type="sell", active_key=HIVE_ACTIVE_KEY, nodes=HIVE_NODES)
                print(f"[PEK BOT] SELL order submitted: {sell_qty} {token} at {sell_price}")
                print(f"[PEK BOT] Profit percent: {get_profit_percent(buy_price, sell_price)}%")
                time.sleep(5)
                open_orders = get_open_orders(account_name, token)
                if open_orders:
                    print(f"[PEK BOT] Open orders after SELL: {len(open_orders)} found.")
                else:
                    print(f"[PEK BOT] No open orders found after SELL (may be node delay).")
                time.sleep(1)
            except Exception as e:
                print(f"[PEK BOT] SELL order exception: {e}")
    else:
        print(f"[PEK BOT] SELL order skipped: sell_qty is zero.")
    
    # Buy smallest increment of token at market price
    time.sleep(2)
    try:
        if ask > 0:
            place_order(account_name, token, ask, 0.00000001, order_type="buy", active_key=HIVE_ACTIVE_KEY, nodes=HIVE_NODES)
            print(f"[PEK BOT] {token} tiny buy attempted at {ask}.")
        else:
            print(f"[PEK BOT] {token} market ask unavailable, skipping tiny buy.")
    except Exception as e:
        print(f"[PEK BOT] {token} tiny buy exception: {e}")
    
    # Buy smallest increment of SWAP.MATIC at market ask
    try:
        matic_market = get_orderbook_top("SWAP.MATIC")
        if matic_market and matic_market.get("lowestAsk"):
            matic_price = float(matic_market.get("lowestAsk"))
            place_order(account_name, "SWAP.MATIC", matic_price, 0.00000001, order_type="buy", active_key=HIVE_ACTIVE_KEY, nodes=HIVE_NODES)
            print(f"[PEK BOT] SWAP.MATIC buy attempted at {matic_price}.")
        else:
            print(f"[PEK BOT] SWAP.MATIC market unavailable, skipping buy.")
    except Exception as e:
        print(f"[PEK BOT] SWAP.MATIC buy exception: {e}")
    
    print(f"[PEK BOT] Trade cycle for {token} complete.")
    print("==============================\n")
    time.sleep(DYNAMIC_DELAY)

if __name__ == "__main__":
    while True:
        try:
            print(f"[BOT] Starting new trade cycle for {TOKEN}.")
            smart_trade(HIVE_ACCOUNT, TOKEN)
            print(f"[BOT] Waiting 10 seconds before next cycle...")
            time.sleep(10)
        except Exception as e:
            print(f"[BOT] Unexpected error in main loop: {e}")
            import traceback
            traceback.print_exc()
        remaining = max(0, DELAY - 10)
        if remaining > 0:
            print(f"[BOT] Waiting {remaining} seconds to complete delay interval...")
            time.sleep(remaining)


🪙 PeakeCoin Ecosystem

💱 PeakeCoin USDT Bridge (Hive ↔ Polygon/MATIC)
Bridge SWAP.USDT from Hive Engine to USDT on Polygon (MATIC).
Whitelist access, documentation, and bridge status updates:
👉


⚙️ HiveP.I.M.P. — PeakeCoin Intelligent Market Protector
Operated by @hivepimp, P.I.M.P. stabilizes PEK markets and supports liquidity on Hive Engine.
Community liquidity participation strengthens long-term market health.
📈 Open-source code, bots, and documentation:
👉 https://github.com/paulmoon410


🎰 PeakeSino — The PeakeCoin Casino (Beta)
Blockchain-powered games using PEK as the native in-game currency.
Built on Hive with a focus on provable fairness and community-driven growth.
🃏 Play the beta games here:
👉


🙏 Acknowledgements

Thanks to and please follow:
@enginewitty @ecoinstant @neoxian @txracer @thecrazygm @holdonia @aggroed

For their continued support, guidance, and help expanding the PeakeCoin ecosystem.


Hashtags 9
A general topic community built around PoB technology and the POB token

Comments

Sort byBest