Skip to content
Skillv1.0.0

SunPerp Perpetual Futures Trading

Trade USDT-margined perpetual futures on SunPerp (TRON) — place orders, manage positions, query market data, and manage account via REST API.

by BofAI(0) 0 installs
Free
Sign in to install

Free account. Installing gives you the manifest plus copy-paste snippets.

See reviews

About

Imported from BofAI/skills (sunperp-skill/SKILL.md). Install upstream with npx skills add BofAI/skills --skill sunperp-skill. Copyright stays with the author.

SunPerp Perpetual Futures Trading

Overview

This skill enables AI agents to trade USDT-margined perpetual futures on SunPerp, the perpetual futures DEX on the TRON blockchain. It provides scripts for:

  • Market data: Prices, order books, candlesticks, funding rates
  • Account management: Balances, fee rates, trading bills
  • Order management: Place, cancel, and query orders (market, limit, post-only)
  • Position management: View positions, set leverage, set position mode, close positions

All scripts communicate with the SunPerp REST API at https://api.sunx.io.

Prerequisites

Wallet required: Run agent-wallet list first.
If no wallets exist, invoke bankofai-guide (Section C — Wallet Guard) before proceeding.

1. Environment Setup

Install Node.js dependencies from the skill directory:

cd sunperp-skill
npm install

2. API Key Configuration

The user must create API keys at https://www.sunperp.com/futures/api-manage/ and set them as environment variables:

export SUNPERP_ACCESS_KEY="your_access_key"
export SUNPERP_SECRET_KEY="your_secret_key"

[!CAUTION] Never hardcode API keys in commands or files. Always read them from environment variables. If the environment variables are not set, prompt the user to set them before proceeding.

3. Verify Setup

Run a public endpoint to verify connectivity (no API key needed):

node scripts/market.js ticker contract_code=BTC-USDT

Then verify authenticated access:

node scripts/account.js balance

Usage Instructions

Contract Code Format

SunPerp contracts follow these naming patterns:

Type Format Example
Perpetual swap {SYMBOL}-USDT BTC-USDT
Current week {SYMBOL}-USDT-CW BTC-USDT-CW
Next week {SYMBOL}-USDT-NW BTC-USDT-NW
Current quarter {SYMBOL}-USDT-CQ BTC-USDT-CQ
Next quarter {SYMBOL}-USDT-NQ BTC-USDT-NQ

Popular perpetual contracts: BTC-USDT, ETH-USDT, TRX-USDT, SOL-USDT, SUN-USDT, DOGE-USDT, XRP-USDT.

Position Modes

SunPerp supports two position modes:

  • single_side (One-way): Use position_side=both for all orders. The side field determines direction.
  • dual_side (Hedge): Must specify position_side=long or position_side=short. Allows simultaneous long and short positions.

Check the current mode before trading:

node scripts/position.js get_mode

Margin Mode

The API uses cross margin (margin_mode=cross) as the standard mode. All order and position scripts default to cross margin.


Script Reference

All scripts are located in the scripts/ directory and invoked as:

node scripts/<script>.js <command> [key=value ...]

Market Data (scripts/market.js)

No authentication required for market data.

Get 24h Ticker

node scripts/market.js ticker contract_code=BTC-USDT

Returns: open, close, high, low, volume, best bid/ask.

Get Order Book

node scripts/market.js depth contract_code=BTC-USDT type=step0

type values: step0 (unmerged, 150 levels) through step5; step6 (unmerged, 20 levels) through step13.

Get Candlestick Data

node scripts/market.js kline contract_code=BTC-USDT period=60min size=50

period values: 1min, 5min, 15min, 30min, 60min, 60min, 4hour, 1day, 1mon.

Get Best Bid/Offer

node scripts/market.js bbo contract_code=BTC-USDT

Get Last Trade

node scripts/market.js trade contract_code=BTC-USDT

Get Recent Trades

node scripts/market.js trades contract_code=BTC-USDT size=20

Get Funding Rate

node scripts/market.js funding contract_code=BTC-USDT

Get Index Price

node scripts/market.js index contract_code=BTC-USDT

List Available Contracts

node scripts/market.js contracts

Get Price Limits

node scripts/market.js price_limit contract_code=BTC-USDT

Account (scripts/account.js)

Requires authentication (API keys).

Check Account Balance

node scripts/account.js balance

Returns: equity, available margin, unrealized PnL, maintenance margin rate.

Get Fee Rates

node scripts/account.js fee contract_code=BTC-USDT

Get Trading Bills

node scripts/account.js bills mar_acct=USDT

Optional: contract=BTC-USDT, start_time=<ms>, end_time=<ms>.


Order Management (scripts/order.js)

Requires authentication with Trade permission.

Place a Market Order

Open a long position (buy):

node scripts/order.js place contract_code=BTC-USDT side=buy type=market volume=1

Open a short position (sell):

node scripts/order.js place contract_code=BTC-USDT side=sell type=market volume=1

Place a Limit Order

node scripts/order.js place contract_code=BTC-USDT side=buy type=limit volume=1 price=95000

Place an Order with TP/SL

node scripts/order.js place contract_code=BTC-USDT side=buy type=market volume=1 tp_trigger_price=100000 sl_trigger_price=90000

Place a Post-Only Order

node scripts/order.js place contract_code=BTC-USDT side=buy type=post_only volume=1 price=94000

Place an Order in Hedge Mode

When position_mode=dual_side, you must specify position_side:

# Open long
node scripts/order.js place contract_code=BTC-USDT side=buy type=market volume=1 position_side=long

# Close long
node scripts/order.js place contract_code=BTC-USDT side=sell type=market volume=1 position_side=long

# Open short
node scripts/order.js place contract_code=BTC-USDT side=sell type=market volume=1 position_side=short

# Close short
node scripts/order.js place contract_code=BTC-USDT side=buy type=market volume=1 position_side=short

Cancel an Order

node scripts/order.js cancel contract_code=BTC-USDT order_id=123456789

Or by client order ID:

node scripts/order.js cancel contract_code=BTC-USDT client_order_id=my_order_1

Cancel All Orders

node scripts/order.js cancel_all

Optionally filter: contract_code=BTC-USDT, side=buy, position_side=long.

Close Position for a Symbol

node scripts/order.js close contract_code=BTC-USDT position_side=both

In hedge mode use position_side=long or position_side=short.

Close All Positions

node scripts/order.js close_all

List Open Orders

node scripts/order.js open_orders contract_code=BTC-USDT

Get Order Info

node scripts/order.js info contract_code=BTC-USDT order_id=123456789

Get Order History

node scripts/order.js history contract_code=BTC-USDT

Optional: state=filled, start_time=<ms>, end_time=<ms>, limit=50.

Get Execution Details

node scripts/order.js details contract_code=BTC-USDT order_id=123456789

Position Management (scripts/position.js)

Requires authentication.

List Open Positions

node scripts/position.js list

Or for a specific contract:

node scripts/position.js list contract_code=BTC-USDT

Returns: entry price, volume, liquidation price, unrealized PnL, margin rate, leverage, ADL risk.

Get Current Leverage

node scripts/position.js get_leverage contract_code=BTC-USDT

Set Leverage

node scripts/position.js set_leverage contract_code=BTC-USDT lever_rate=20

[!WARNING] Increasing leverage increases liquidation risk. Always confirm the desired leverage with the user before setting it.

Get Position Mode

node scripts/position.js get_mode

Set Position Mode

node scripts/position.js set_mode position_mode=single_side

[!NOTE] Position mode can only be changed when there are no open positions or orders.

Get Risk Limits

node scripts/position.js risk_limit contract_code=BTC-USDT

Get Position Limits

node scripts/position.js position_limit contract_code=BTC-USDT

Wallet (scripts/wallet.js)

Requires authentication with Withdraw permission. Also requires TRON_PRIVATE_KEY env var for signing withdrawal confirmations.

export TRON_PRIVATE_KEY="your_hex_private_key"

Withdraw USDT (Full Flow)

Performs the complete two-step withdraw: apply → sign → confirm.

node scripts/wallet.js withdraw address=TXxxxxxxxxxxxxxxxxxxxxxxxxxxxx amount=10

Optional: currency=usdt (default), chain=trc20usdt (default), fee=0 (default).

Withdraw Apply Only (Step 1)

Returns nonce and content for manual signing:

node scripts/wallet.js apply address=TXxxxxxxxxxxxxxxxxxxxxxxxxxxxx amount=10

Withdraw Confirm Only (Step 2)

Confirm a previously applied withdrawal with a pre-computed signature:

node scripts/wallet.js confirm nonce=<nonce_from_apply> signature=<hex_signature>

Query Deposit/Withdraw Records

node scripts/wallet.js records type=deposit
node scripts/wallet.js records type=withdraw

Optional: currency=usdt, size=50, direct=next, from=<id>.

[!CAUTION] Withdrawals move funds off-platform and are irreversible. Always confirm the destination address and amount with the user before executing.


Examples

Example 1: Check Price and Open a Long Position

User: "Buy 5 contracts of BTC-USDT at market price"

Agent steps:
1. Check the current price:
   node scripts/market.js ticker contract_code=BTC-USDT

2. Check account balance:
   node scripts/account.js balance

3. Confirm with user: "BTC-USDT is currently at $96,500. You have $10,000 available margin.
   Placing a market buy for 5 contracts. Proceed?"

4. After user confirms, place the order:
   node scripts/order.js place contract_code=BTC-USDT side=buy type=market volume=5

5. Verify the position was opened:
   node scripts/position.js list contract_code=BTC-USDT

6. Report: "Opened long position: 5 BTC-USDT contracts at $96,502 avg entry.
   Liquidation price: $48,251. Current unrealized PnL: $0."

Example 2: Set Leverage and Place a Limit Order

User: "Set leverage to 20x on ETH-USDT and place a limit buy at $3,200 for 10 contracts"

Agent steps:
1. Set leverage:
   node scripts/position.js set_leverage contract_code=ETH-USDT lever_rate=20

2. Check current price for context:
   node scripts/market.js ticker contract_code=ETH-USDT

3. Confirm with user: "Leverage set to 20x. ETH-USDT is at $3,350.
   Placing limit buy for 10 contracts at $3,200. Proceed?"

4. After user confirms, place the order:
   node scripts/order.js place contract_code=ETH-USDT side=buy type=limit volume=10 price=3200

5. Verify the order was placed:
   node scripts/order.js open_orders contract_code=ETH-USDT

6. Report: "Limit buy order placed: 10 ETH-USDT at $3,200. Order ID: 987654321. Status: open."

Example 3: Close a Position and Check PnL

User: "Close my BTC-USDT position"

Agent steps:
1. Check existing position:
   node scripts/position.js list contract_code=BTC-USDT

2. Report position details and confirm:
   "You have a long position of 5 BTC-USDT contracts. Entry: $96,502, Current: $97,100.
   Unrealized PnL: +$2.99. Close at market? Proceed?"

3. After user confirms, close:
   node scripts/order.js close contract_code=BTC-USDT position_side=both

4. Verify:
   node scripts/position.js list contract_code=BTC-USDT

5. Report: "Position closed. Realized PnL: +$2.95 after fees."

Example 4: Monitor Funding Rate

User: "What's the funding rate for TRX-USDT?"

Agent steps:
1. Get funding rate:
   node scripts/market.js funding contract_code=TRX-USDT

2. Report: "TRX-USDT funding rate: 0.01% (next funding in 2h 15m).
   Positive rate means longs pay shorts."

Error Handling

Common Error Scenarios

Error Cause Resolution
Missing env vars SUNPERP_ACCESS_KEY / SUNPERP_SECRET_KEY not set Ask user to set API keys
HTTP 401 Invalid or expired API keys Ask user to check/regenerate keys
HTTP 403 Insufficient permissions API key needs Trade permission for orders
Timestamp error System clock skew > 5 minutes Check system time synchronization
Insufficient margin Not enough available margin for the order Show balance, suggest reducing volume or leverage
Position mode conflict Trying to set mode while positions are open Close positions first, then switch mode
Order rejected Price outside limits or volume too small Check price_limit and contract info for min/max

Error Handling Pattern

When a script returns an error:

  1. Parse the error message from the JSON response (code, message, or error-msg fields)
  2. Explain the error to the user in plain language
  3. Suggest a specific corrective action
  4. Do NOT retry automatically for trade operations — always confirm with the user

Agent Safety Locks

Two mandatory safety mechanisms are enforced at the script level to prevent catastrophic losses. Both are configured in resources/sunperp_config.json under the safety key.

1. Max Leverage Cap

Parameter Default Description
safety.max_leverage 20 Maximum leverage the agent is allowed to use

The cap is enforced in two places:

  • position.js set_leverage — rejects any lever_rate above the cap before calling the API.
  • order.js place — if lever_rate is passed inline, it is validated before the order is submitted.

If the agent attempts to exceed the cap, the script exits with a clear error:

ERROR: Leverage 50x exceeds the agent safety cap of 20x.
Adjust max_leverage in sunperp_config.json to raise this limit.

To change the cap, edit safety.max_leverage in the config file. This is an operator-level setting — the agent cannot change it at runtime.

2. Mandatory Stop-Loss

Parameter Default Description
safety.stop_loss.required true Whether every position-opening order must have a stop-loss
safety.stop_loss.default_percent 5 Auto-calculated SL distance when sl_trigger_price is omitted
safety.stop_loss.max_percent 25 Maximum allowed SL distance — rejects wider stop-losses

When required is true, every position-opening order (i.e., not reduce_only) must include a stop-loss:

  • If sl_trigger_price is provided: validated to be within max_percent of the reference price.
  • If omitted on a limit order: auto-calculated at default_percent below entry (long) or above entry (short).
  • If omitted on a market order: the script fetches the current market price and auto-calculates. If the price fetch fails, the order is rejected with an instruction to provide sl_trigger_price explicitly.

Example — auto stop-loss on a limit long:

# Limit buy at $95,000 — SL auto-set to $90,250 (5% below)
node scripts/order.js place contract_code=BTC-USDT side=buy type=limit volume=1 price=95000

Example — explicit stop-loss:

node scripts/order.js place contract_code=BTC-USDT side=buy type=market volume=1 sl_trigger_price=90000

Example — rejected (SL too wide):

# 30% distance exceeds max_percent of 25%
node scripts/order.js place contract_code=BTC-USDT side=buy type=limit volume=1 price=95000 sl_trigger_price=66500

[!NOTE] The reduce_only flag (close-position orders) is exempt from the stop-loss requirement since those orders are already reducing risk.


Security Considerations

[!CAUTION] Private Keys & API Secrets: Never log, display, or store API secret keys. Read them exclusively from environment variables.

[!WARNING] Trade Confirmation: Always confirm the following with the user BEFORE executing any trade:

  • Contract code and direction (long/short)
  • Order type (market/limit) and volume
  • Price (for limit orders)
  • Current leverage setting
  • Estimated margin requirement

Security Checklist

  • API keys loaded from environment variables only
  • No secrets in command output or logs
  • Trade confirmations shown before execution
  • Leverage changes confirmed before applying
  • Leverage never exceeds safety.max_leverage cap
  • Every position-opening order has a stop-loss attached
  • Position mode changes confirmed before applying
  • Close-all operations require explicit user confirmation
  • Cancel-all operations require explicit user confirmation

User Communication Templates

Pre-trade confirmation:

📋 Order Summary:
  Contract: {contract_code}
  Side: {side} ({long/short})
  Type: {type}
  Volume: {volume} contracts
  Price: {price or "market"}
  Leverage: {lever_rate}x (cap: {max_leverage}x)
  Stop-loss: ${sl_trigger_price}
  Est. margin: ~${margin}

Proceed? (yes/no)

Post-trade report:

✅ Order executed:
  Order ID: {order_id}
  Avg. fill price: ${trade_avg_price}
  Fee: ${fee}

Position summary:

📊 Position: {contract_code} {direction}
  Volume: {volume} contracts
  Entry: ${open_avg_price}
  Mark: ${mark_price}
  Liq. price: ${liquidation_price}
  Unrealized PnL: ${profit_unreal} ({profit_rate}%)
  Leverage: {lever_rate}x

Version 1.0.0 — Created by M2M Agent Registry for Bank of AI

Use it

Copy one of these into your project. Installing also returns the manifest and these snippets.

yaml
targets:
  - https://api.opensmartroute.ai/api/v1/registry/bofai-skills-sunperp-skill/manifest   # or paste the manifest below

Manifest

An Open Capability Manifest: the router reads it to know what this does, what it costs and when to pick it.

bofai-skills-sunperp-skill.ocm.jsonjson
{
  "ocm": "1",
  "id": "bofai-skills-sunperp-skill",
  "kind": "skill",
  "name": "SunPerp Perpetual Futures Trading",
  "description": "Trade USDT-margined perpetual futures on SunPerp (TRON) — place orders, manage positions, query market data, and manage account via REST API.",
  "publisher": "BofAI",
  "version": "1.0.0",
  "capabilities": {
    "domains": [
      "coding",
      "data_analysis"
    ],
    "tags": [
      "skill-md",
      "defi",
      "perpetual",
      "futures",
      "tron",
      "sunperp",
      "trading",
      "github"
    ],
    "languages": [
      "en"
    ]
  },
  "quality_prior": 0.6,
  "examples": [
    "Trade USDT-margined perpetual futures on SunPerp (TRON) — place orders, manage positions, query market data, and manage account via REST API."
  ],
  "primary": false,
  "metadata": {
    "source": {
      "provider": "github",
      "repository": "https://github.com/BofAI/skills",
      "path": "sunperp-skill/SKILL.md",
      "ref": "44b76abdf321bf9ed2556d30880e6be22c13bdf0",
      "url": "https://github.com/BofAI/skills/blob/44b76abdf321bf9ed2556d30880e6be22c13bdf0/sunperp-skill/SKILL.md",
      "key": "BofAI/skills/sunperp-skill/SKILL.md"
    }
  },
  "instructions": "# SunPerp Perpetual Futures Trading\n\n## Overview\n\nThis skill enables AI agents to trade USDT-margined perpetual futures on [SunPerp](https://www.sunperp.com), the perpetual futures DEX on the TRON blockchain. It provides scripts for:\n\n- **Market data**: Prices, order books, candlesticks, funding rates\n- **Account management**: Balances, fee rates, trading bills\n- **Order management**: Place, cancel, and query orders (market, limit, post-only)\n- **Position management**: View positions, set leverage, set position mode, close positions\n\nAll scripts communicate with the SunPerp REST API at `https:",
  "cost": {
    "context_tokens": 4360
  }
}

Fetch it by URL: GET /api/v1/registry/bofai-skills-sunperp-skill/manifest?version=1.0.0

Reviews

Star ratings from people who tried it. One review per account; edit yours any time.

No reviews yet. Install it, try it, and be the first to rate it.