create account

PeakeCoin Bot - Offset Transactions by paulmoon410

View this thread on: hive.blogpeakd.comecency.com
· @paulmoon410 ·
$0.67
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 

<center>![](https://images.ecency.com/DQmWfgrKECP47pSK6LpAZwFMFcffm99LjUxsNHXGtFmstCf/image.png)</a></center>

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)


```
👍  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,
properties (23)
authorpaulmoon410
permlinkpeakecoin-bot-offset-transactions
categoryhive-186392
json_metadata"{"app":"ecency/4.1.1-vision","tags":["hive-186392","pimp","neoxian","waivio","proofofbrain","palnet","bee","archon","peakecoin","creativecoin","ecency"],"format":"markdown+html","image":["https://images.ecency.com/DQmWfgrKECP47pSK6LpAZwFMFcffm99LjUxsNHXGtFmstCf/image.png"],"thumbnails":["https://images.ecency.com/DQmWfgrKECP47pSK6LpAZwFMFcffm99LjUxsNHXGtFmstCf/image.png"],"description":"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","image_ratios":["1.0000"],"type":"video"}"
created2025-05-29 01:19:18
last_update2025-05-29 01:19:18
depth0
children3
last_payout2025-06-05 01:19:18
cashout_time1969-12-31 23:59:59
total_payout_value0.338 HBD
curator_payout_value0.331 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length8,498
author_reputation40,462,270,619,406
root_title"PeakeCoin Bot - Offset Transactions"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd0
post_id143,029,481
net_rshares2,025,457,366,962
author_curate_reward""
vote details (58)
@ecoinstant · (edited)
Great quick work!!

!PAKX
!PIMP
!PIZZA
properties (22)
authorecoinstant
permlinkre-paulmoon410-sx046n
categoryhive-186392
json_metadata{"tags":"hive-186392"}
created2025-05-29 02:28:00
last_update2025-05-29 02:28:39
depth1
children1
last_payout2025-06-05 02:28:00
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length38
author_reputation834,065,541,300,754
root_title"PeakeCoin Bot - Offset Transactions"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id143,030,357
net_rshares0
@pakx ·
<center><table><tr></tr><tr><td><center><img src='https://files.peakd.com/file/peakd-hive/pakx/PakX-logo-transparent.png'><p><sup><a href='https://hive-engine.com/?p=market&t=PAKX'>View or trade </a> <code>PAKX</code> tokens.</sup></p></center></td><td>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.</td></tr></table></center>
properties (22)
authorpakx
permlinkre-ecoinstant-1748485752
categoryhive-186392
json_metadata"{"tags": ["pakx", "hivepakistan"], "app": "HiveDiscoMod"}"
created2025-05-29 02:29:12
last_update2025-05-29 02:29:12
depth2
children0
last_payout2025-06-05 02:29:12
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length429
author_reputation32,486,708,418
root_title"PeakeCoin Bot - Offset Transactions"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id143,030,379
net_rshares0
@pizzabot ·
<center>PIZZA!


$PIZZA slices delivered:
@ecoinstant<sub>(2/20)</sub> tipped @paulmoon410 


<sub>Come get [MOON](https://moon.hive.pizza)ed!</sub></center>
properties (22)
authorpizzabot
permlinkre-peakecoin-bot-offset-transactions-20250529t022901z
categoryhive-186392
json_metadata"{"app": "pizzabot"}"
created2025-05-29 02:29:00
last_update2025-05-29 02:29:00
depth1
children0
last_payout2025-06-05 02:29:00
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length157
author_reputation7,459,833,231,431
root_title"PeakeCoin Bot - Offset Transactions"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id143,030,375
net_rshares0