PeakeCoin Bot - Offset Transactions

This is what you need to do to avoid problems with bot transactions that are trying to go through on each block. Don't be a douche, copy the code

Using @nectarflower API and the hard work of @thecrazygm to allow it all to happen.

This is just the bot code, not the fetch_market or place_order which this uses.


# peake_bot.py
import time
import datetime
import json
import os
from fetch_market import get_orderbook_top
from place_order import place_order, get_open_orders, cancel_order, get_balance  # ✅ Uses external module with PEK gas logic

# 🔐 Hive account
HIVE_ACCOUNT = "paulmoon410"
TOKEN = "PEK"
TICK = 0.000001
DELAY = 60  # seconds between cycles

last_gas_time = 20
GAS_INTERVAL = 3720  # seconds (1 hour and 2 minutes)

def maybe_buy_gas(account_name):
    global last_gas_time
    now = time.time()
    print(f"[DEBUG] now: {now}, last_gas_time: {last_gas_time}, elapsed: {now - last_gas_time}, interval: {GAS_INTERVAL}")
    if now - last_gas_time > GAS_INTERVAL:
        print("Placing SWAP.MATIC buy order (hourly, up to 0.01 at market value, will use all available balance if less)...")
        from fetch_market import get_orderbook_top
        from place_order import place_order, get_balance
        matic_market = get_orderbook_top("SWAP.MATIC")
        print(f"[DEBUG] SWAP.MATIC market data: {matic_market}")
        if not matic_market or not matic_market.get("lowestAsk"):
            print("❌ Could not fetch SWAP.MATIC market price. Skipping buy.")
            return
        matic_price = float(matic_market["lowestAsk"])
        max_qty = 0.01
        # Check available SWAP.HIVE balance
        swap_hive_balance = get_balance(account_name, "SWAP.HIVE")
        print(f"[DEBUG] SWAP.HIVE balance: {swap_hive_balance}")
        # Calculate max affordable qty
        affordable_qty = swap_hive_balance / matic_price if matic_price > 0 else 0
        buy_qty = min(max_qty, affordable_qty)
        min_qty = 0.001
        if buy_qty < min_qty:
            print(f"[INFO] Not enough SWAP.HIVE to buy even the minimum ({min_qty}) SWAP.MATIC. Skipping buy.")
            return
        print(f"[DEBUG] Attempting to place order: account={account_name}, price={matic_price}, qty={buy_qty}")
        try:
            result = place_order(account_name, "SWAP.MATIC", matic_price, buy_qty, order_type="buy")
            print(f"SWAP.MATIC buy: ✅ Placed order for {buy_qty} at {matic_price}")
            print(f"[DEBUG] place_order result: {result}")
        except Exception as e:
            print(f"SWAP.MATIC buy: ❌ Failed to place order ({e})")
        last_gas_time = now
    else:
        print(f"Skipping SWAP.MATIC buy order (not time yet, {int(GAS_INTERVAL - (now - last_gas_time))}s left).")

def smart_trade(account_name, token, forbidden_user=None):
    print(f"\n==============================")
    print(f"🤖 Starting Smart Trade for {token}")
    print(f"==============================")
    try:
        open_orders = get_open_orders(account_name, token)
        num_open_orders = len(open_orders) if open_orders else 0
        all_open_orders = get_open_orders(account_name)
        total_open_orders = len(all_open_orders) if all_open_orders else 0
        print(f"📊 Open {token} orders: {num_open_orders} | Total open: {total_open_orders}")
        ORDER_LIMIT = 198
        if num_open_orders >= ORDER_LIMIT or total_open_orders >= ORDER_LIMIT:
            print(f"⚠️ Too many open orders. Cancelling oldest...")
            if open_orders:
                oldest = min(open_orders, key=lambda o: o.get('timestamp', o.get('_id', 0)))
                order_id = oldest.get('_id')
                try:
                    success, txid, error = cancel_order(account_name, order_id)
                    print(f"🗑️ Cancel oldest: {'✅ Success' if success else '❌ Fail'}")
                except Exception as e:
                    print(f"🗑️ Cancel oldest: ❌ Fail ({e})")
            else:
                print("🗑️ Cancel oldest: ❌ Fail (no open orders)")
            maybe_buy_gas(account_name)
            print(f"⏭️ Trade for {token} skipped due to order limit.")
            print(f"==============================\n")
            return
        print("✅ Order limit check passed.")
        buy_orders = [o for o in open_orders if o.get('type') == 'buy']
        sell_orders = [o for o in open_orders if o.get('type') == 'sell']
        print(f"🔄 Orders split: {len(buy_orders)} buy | {len(sell_orders)} sell")
        market = get_orderbook_top(token)
        if not market:
            print("❌ Market fetch failed!")
            print(f"==============================\n")
            return
        print("✅ Market fetch success.")
        bid = market["highestBid"]
        ask = market["lowestAsk"]
        buy_price = round(bid + 0.00000001, 8)
        sell_price = round(max(ask - 0.00000001, buy_price + 0.00000001), 8)
        # --- 20% of HIVE for buys, 20% of LTC for sells ---
        hive_balance = get_balance(account_name, "SWAP.HIVE")
        ltc_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(ltc_balance * 0.20, 8)
     

I was thinking off adding a Forbidden User Function if there was a user abusing the platform

   # --- Check forbidden user in orderbook ---
        # if forbidden_user:
        #     # Check top of book for forbidden user
        #     if any(o.get('account') == forbidden_user for o in market.get('buyOrders', [])):
        #         print(f"[BLOCKED] Top buy order is from forbidden user {forbidden_user}. Skipping buy.")
        #         return
        #     if any(o.get('account') == forbidden_user for o in market.get('sellOrders', [])):
        #         print(f"[BLOCKED] Top sell order is from forbidden user {forbidden_user}. Skipping sell.")
        #         return
        own_min_sell = min([float(o['price']) for o in sell_orders], default=None)
        if own_min_sell is not None and buy_price >= own_min_sell:
            print("📥 Buy: ❌ Skipped (would cross own sell)")
        elif any(abs(float(o['price']) - buy_price) < 1e-8 for o in buy_orders):
            print("📥 Buy: ❌ Skipped (already have buy)")
        else:
            try:
                print(f"📥 Placing BUY order for {buy_qty} {token} at {buy_price}...")
                place_order(account_name, token, buy_price, buy_qty, order_type="buy")
                print("📥 Buy: ✅ Success")
                time.sleep(10)  # Ensure 10s between buy and sell
            except Exception as e:
                print(f"📥 Buy: ❌ Fail ({e})")
        own_max_buy = max([float(o['price']) for o in buy_orders], default=None)
        if own_max_buy is not None and sell_price <= own_max_buy:
            print("📤 Sell: ❌ Skipped (would cross own buy)")
        elif any(abs(float(o['price']) - sell_price) < 1e-8 for o in sell_orders):
            print("📤 Sell: ❌ Skipped (already have sell)")
        else:
            try:
                print(f"📤 Placing SELL order for {sell_qty} {token} at {sell_price}...")
                place_order(account_name, token, sell_price, sell_qty, order_type="sell")
                print("📤 Sell: ✅ Success")
                time.sleep(10)  # Ensure 10s after sell as well
            except Exception as e:
                print(f"📤 Sell: ❌ Fail ({e})")
        print(f"🏁 Trade for {token} complete.")
        print(f"==============================\n")
    except Exception as e:
        print(f"❌ Trade: Fail ({e})\n==============================\n")

Now here's the piece you don't want to miss... this is offsetting the transactions.

if __name__ == "__main__":
    cycle = 0
    while True:
        try:
            # Buy
            if cycle % 3 == 0:
                smart_trade(HIVE_ACCOUNT, TOKEN)
            # Sell
            elif cycle % 3 == 1:
                smart_trade(HIVE_ACCOUNT, TOKEN)
            # Gas/Matic
            elif cycle % 3 == 2:
                maybe_buy_gas(HIVE_ACCOUNT)
            cycle = (cycle + 1) % 3
            time.sleep(10)  # 10s offset between each action
        except Exception as e:
            print(f"⚠️ Unexpected error: {e}")
        # Wait the remainder of the DELAY, minus the 10s already waited
        remaining = max(0, DELAY - 10)
        if remaining > 0:
            time.sleep(remaining)




0
0
0.000
3 comments
avatar
(Edited)

Great quick work!!

!PAKX
!PIMP
!PIZZA

0
0
0.000
avatar

View or trade PAKX tokens.

You have already used the number of vote calls you had for the day. You can call again later in 1h 0m or buy more PAKX tokens to call for more votes.

0
0
0.000