In the scheme of these games of things, I'm trying to arrive at I'm attempting to make @PeakeCoin a cross-chain type of token. The trading bot's purpose is to acquire enough BNB to move itself to the Binance Chain also.... I don't have the knowledge of the contract stuff on Binance at the moment, but that's the goal.
First things first... @nectarflower I took your logo and applied Maryland's flag onto it for the purpose of all my @PeakeCoin works and to not discount the amount of help that community has allowed me to do.
As soon as I noticed I was burning through Resource Credits, so did @txracer, so the next step is to add a delay into the bot... but that is for next time, be aware that this will go through those credits like Taco Bell does the average digestive system.
I've spent the past few weeks trying to code this damn trading bot and thanks to @ecoinstant and @thecrazygm this trading bot is up and running. If you are familiar with GitHub, you can slide into https://github.com/PaulMoon410/peakecoin_bnb_bot/tree/main and download the few files required to make the bot run.
The place_order file had given me the largest headache, even though I had both Posting Keys and Active Keys applied. I had to specifically indicate where the Active Key but I was hard-headed, lol. No matter how many times @txracer reiterated that I needed the Active Key only...and to remove my keys from the GitHub file...smh... I did so and cleaned it all up.
So @enginewitty it's up and running now. I got the help I needed. So be sure to spread the love to @thecrazygm slid in and pointed out where I went wrong.
place_order.py
import time
import requests
import json as jsonlib
from nectar.hive import Hive
from beem import Hive
from nectar.account import Account
from nectar.transactionbuilder import TransactionBuilder
from nectarbase.operations import Custom_json
from nectar.instance import set_shared_blockchain_instance
# 🔐 Hive account + keys
HIVE_ACCOUNT = "peakecoin.bnb"
HIVE_POSTING_KEY = ""
HIVE_ACTIVE_KEY = ""
HIVE_NODES = ["https://api.hive.blog", "https://anyx.io"]
# ✅ Connect to Hive
hive = Hive(node=HIVE_NODES, keys=[HIVE_POSTING_KEY,
HIVE_ACTIVE_KEY])
set_shared_blockchain_instance(hive)
account = Account(HIVE_ACCOUNT, blockchain_instance=hive)
def get_balance(account_name, token):
payload = {
"jsonrpc": "2.0",
"method": "find",
"params": {
"contract": "tokens",
"table": "balances",
"query": {"account": account_name, "symbol": token},
},
"id": 1,
}
r = requests.post("https://api.hive-engine.com/rpc/contracts", json=payload)
if r.status_code == 200:
result = r.json()
if result["result"]:
return float(result["result"][0]["balance"])
return 0.0
def place_order(account_name, token, price, quantity, order_type="buy"):
token_used = token if order_type == "sell" else "SWAP.HIVE"
available = get_balance(account_name, token_used)
if available < quantity:
print(f"⚠️ Not enough balance! Adjusting order. Available: {available}")
quantity = max(available * 0.95, 0.00001)
if quantity <= 0:
print(f"🚫 Skipping order — quantity too small: {quantity}")
return False
payload = {
"contractName": "market",
"contractAction": order_type,
"contractPayload": {
"symbol": token,
"quantity": str(round(quantity, 8)),
"price": str(round(price, 6)),
},
}
print(f"📝 Final Order Payload: {payload}")
try:
tx = TransactionBuilder(blockchain_instance=hive)
op = Custom_json(
required_auths=[account_name],
required_posting_auths=[],
id="ssc-mainnet-hive",
json=jsonlib.dumps(payload),
)
tx.appendOps([op])
tx.appendSigner(account_name, "active")
print("🔐 Loaded public keys in wallet:", hive.wallet.getPublicKeys())
print("🔑 Required signing key (active):", account["active"]["key_auths"][0][0])
tx.sign()
print("🔏 Transaction signed successfully!")
tx.broadcast()
print(f"✅ Order placed: {order_type.upper()} {quantity} {token} at {price}")
return True
except Exception as e:
print(f"❌ Error broadcasting order: {e}")
import traceback
traceback.print_exc()
return False
fetch_market.py
import requests
def get_orderbook_top(token="SWAP.BNB"):
payload = {
"jsonrpc": "2.0",
"method": "find",
"params": {
"contract": "market",
"table": "buyBook",
"query": {"symbol": token},
"limit": 1,
"indexes": [{"index": "priceDec", "descending": True}]
},
"id": 1
}
buy_response = requests.post("https://api.hive-engine.com/rpc/contracts", json=payload)
payload["table"] = "sellBook"
payload["indexes"] = [{"index": "price", "descending": False}]
sell_response = requests.post("https://api.hive-engine.com/rpc/contracts", json=payload)
print("📥 Buy:", buy_response.text)
print("📤 Sell:", sell_response.text)
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", [])
highest_bid = float(buy_result[0]["price"]) if buy_result else 0
lowest_ask = float(sell_result[0]["price"]) if sell_result else 0
return {"highestBid": highest_bid, "lowestAsk": lowest_ask}
return None
peakecoin_bnb_bot.py
import time
from fetch_market import get_orderbook_top
from place_order import place_order, HIVE_ACCOUNT
TOKEN = "SWAP.BNB"
SPREAD = 0.01 # 3% above/below for placing orders
TRADE_QTY = 0.001
SLEEP_TIME = 60 # seconds
def trading_bot():
while True:
book = get_orderbook_top(TOKEN)
if not book:
print("❌ Failed to fetch orderbook.")
time.sleep(SLEEP_TIME)
continue
buy_price = book["highestBid"] * (1 - SPREAD)
sell_price = book["lowestAsk"] * (1 + SPREAD)
print(f"🟢 Market Price: {(book['highestBid'] + book['lowestAsk']) / 2} | Buy: {buy_price} | Sell: {sell_price}")
print(f"⚡ Placing BUY order: {TRADE_QTY} {TOKEN} at {buy_price}")
place_order(HIVE_ACCOUNT, TOKEN, buy_price, TRADE_QTY, "buy")
print(f"⚡ Placing SELL order: {TRADE_QTY} {TOKEN} at {sell_price}")
place_order(HIVE_ACCOUNT, TOKEN, sell_price, TRADE_QTY, "sell")
time.sleep(SLEEP_TIME)
if __name__ == "__main__":
trading_bot()