AftermathFinance Trading Bot in Python

This guide shows how to build a AftermathFinance trading bot in Python with LumiBot, for both AI agent trading and algorithmic trading. LumiBot connects to AftermathFinance through CCXT, the open source library that talks to more than 100 crypto exchanges. You will create a AftermathFinance account and API wallet, connect it, and run two examples: a simple algorithmic trading bot and an agentic trading bot where an AI agent makes the calls.

AftermathFinance at a glance

CCXT exchange id

aftermath

Markets

Perpetual swaps

Testnet (sandbox)

Yes

Credentials

private key, wallet address

Live data streams

order book, trades, your positions

CCXT request spacing

about 50 ms between requests

Official site

https://aftermath.finance

What is AftermathFinance?

Aftermath Perpetuals is a fully onchain perpetual futures exchange on the Sui blockchain, run by Aftermath Finance. Every order, cancel, trade and liquidation runs onchain, and positions use USDC as collateral.

Sign up for AftermathFinance

  1. There is no account form. Open aftermath.finance, click Login / Connect, and connect a Sui wallet (Aftermath suggests Sui Wallet, Nightly or Phantom), or log in with zkLogin.

  2. Hold a little SUI for gas and native USDC on Sui for collateral.

  3. Create a Perpetuals account and deposit USDC into it. One wallet can own several Perpetuals accounts (sub-accounts).

Open a AftermathFinance account

Set up a AftermathFinance API wallet

  1. Aftermath has no API key and secret. Transactions are signed with a Sui wallet’s private key. Aftermath says to always use an agent wallet for automation, never your main (admin) wallet.

  2. Create a new Sui wallet just for the bot and save its address and private key.

  3. With your main wallet connected, open the Agent Wallets page (https://aftermath.finance/automation) and authorize the bot wallet as an agent on your Perpetuals account.

  4. Give the bot wallet a small amount of SUI for gas, or set up a GasPool from your main wallet to pay its gas.

  5. Give LumiBot the bot wallet’s address as walletAddress and its private key as privateKey.

Which permissions to turn on: There are no permission boxes to set. Aftermath says an agent wallet can do everything except withdraw collateral, grant or revoke other agent wallets, and revoke builder code approvals. So the agent wallet can trade but cannot withdraw. The admin wallet can revoke it at any time.

Warning

A AftermathFinance private key is as powerful as the money it controls. Use a separate wallet or API wallet that holds only what you want the bot to trade, keep the key out of your code and out of Git, and move your funds if the key ever leaks.

Connect AftermathFinance to LumiBot

The simplest way: put these lines in a .env file next to your strategy. LumiBot loads the file, sees TRADING_BROKER=aftermath and connects to AftermathFinance for you, so your strategy needs no broker code.

TRADING_BROKER=aftermath
AFTERMATH_PRIVATE_KEY=your_privateKey
AFTERMATH_WALLET_ADDRESS=your_walletAddress
AFTERMATH_SANDBOX=true   # testnet; remove this line for your live account

LumiBot reads exactly the fields CCXT needs for AftermathFinance (privateKey, walletAddress). If one is missing, LumiBot stops at start-up and names the variable you still need.

You can also build the broker in code. This is handy when one script talks to more than one exchange, or when you need extra CCXT options. The keys in the config are CCXT’s own credential names for AftermathFinance:

import os

AFTERMATH_CONFIG = {
    "exchange_id": "aftermath",
    "privateKey": os.environ.get("AFTERMATH_PRIVATE_KEY"),
    "walletAddress": os.environ.get("AFTERMATH_WALLET_ADDRESS"),
    "sandbox": True,  # testnet first; set False for your live account
}

from lumibot.brokers import Ccxt

broker = Ccxt(AFTERMATH_CONFIG)
# then: MyStrategy(broker=broker, ...)

Either way, LumiBot turns on CCXT’s built-in rate limiting for you.

Practice on the AftermathFinance testnet

CCXT points the sandbox at Aftermath’s testnet API on https://testnet.aftermath.finance. Set AFTERMATH_SANDBOX=true (or "sandbox": True in a code config) to use it. Aftermath’s docs do not include a testnet guide, so check the testnet site for how to get test funds.

CCXT sends sandbox requests to: https://testnet.aftermath.finance/api/ccxt. Testnet and live accounts use different keys.

Algorithmic trading example: a simple AftermathFinance bot

CCXT lists no spot market for AftermathFinance, so this example trades a perpetual contract. It opens one small long BTC position worth about 50 USDC and then holds it. It is a starting point to check that your keys, balances and orders work. If the exchange’s minimum order is larger, raise the amount. If your account uses hedge mode, add position_side="long" to create_order.

from lumibot.entities import Asset
from lumibot.strategies import Strategy


class AftermathOpenOneLong(Strategy):
    """Open one small long BTC perpetual position, then hold it."""

    def initialize(self):
        self.sleeptime = "1H"
        self.set_market("24/7")  # crypto trades all day, every day

    def on_trading_iteration(self):
        # The full CCXT symbol keeps the settlement currency clear.
        contract = self.broker.get_asset("BTC/USD:USDC")
        if self.get_position(contract) is not None:
            return  # already holding the position
        price = self.get_last_price(contract)
        if price:
            # Each contract covers contract.multiplier BTC; size the order to about 50 USDC.
            quantity = round(50 / (price * contract.multiplier), 6)
            order = self.create_order(contract, quantity, "buy")
            self.submit_order(order)


if __name__ == "__main__":
    # LumiBot reads TRADING_BROKER and the keys from your .env file.
    strategy = AftermathOpenOneLong(quote_asset=Asset("USDC", asset_type=Asset.AssetType.CRYPTO))
    strategy.run_live()

Agentic trading example: an AI agent that trades on AftermathFinance

Agentic trading means an AI agent reads the market and decides what to do. In this example one LumiBot agent looks at prices and your AftermathFinance account, then places the orders itself. There is no Python logic in between: you set the rules in plain English in the prompt, such as what it may trade and how big each order can be. This follows the same pattern as LumiBot’s AI trading team examples.

from lumibot.entities import Asset
from lumibot.strategies import Strategy


class AftermathAITrader(Strategy):
    """One AI agent researches the market and places the trades itself."""

    def initialize(self):
        self.sleeptime = "4H"
        self.set_market("24/7")
        self.agents.create(
            name="trader",
            model="openai/gpt-6-luna",
            reasoning_effort="high",
            allow_trading=True,
            system_prompt=(
                "You manage a small crypto account on AftermathFinance. "
                "You may trade the BTC/USD:USDC perpetual contract (asset_type 'crypto_future'), long or short, or stay flat. "
                "Before every order, call account_portfolio, account_positions and "
                "market_last_price for that exact symbol in the same run. "
                "Keep each order under 10% of the account value. "
                "Explain each decision in one short paragraph."
            ),
        )

    def on_trading_iteration(self):
        self.agents["trader"].run(
            task_prompt="Review recent BTC/USD:USDC prices and your current position, then decide whether to buy, sell or hold.",
            context={"exchange": "AftermathFinance", "quote": "USDC", "date": self.get_datetime().isoformat()},
        )


if __name__ == "__main__":
    # LumiBot reads TRADING_BROKER and the keys from your .env file.
    strategy = AftermathAITrader(quote_asset=Asset("USDC", asset_type=Asset.AssetType.CRYPTO))
    strategy.run_live()

The agent needs a model key such as OPENAI_API_KEY in your environment. See the AI agents quickstart for models, tools and memory.

What you can trade on AftermathFinance through CCXT

Market

Listed by CCXT

Spot

No

Margin

No

Perpetual swaps

Yes

Dated futures

No

Options

No

CCXT lists these order features for AftermathFinance: market orders, limit orders, canceling orders.

For perpetual contracts, use the full CCXT symbol so the settlement currency is clear, for example BTC/USD:USDC. See the CCXT guide for contract quantities, position modes and leverage.

AftermathFinance tips

  • CCXT symbols for Aftermath look like BTC/USD:USDC (priced in USD, settled in USDC). There are no spot markets in CCXT for Aftermath.

  • Trading needs a Perpetuals account. CCXT’s position and open order calls ask for an accountNumber, which fetch_accounts returns for the wallet.

  • An account can have up to 10 active agent wallets at once. Use one agent wallet per bot so you can revoke one without stopping the others.

  • Collateral must be allocated from the account to a market before it can back a position. Liquidation on one sub-account does not affect your other sub-accounts.

Frequently asked questions

Can I build a AftermathFinance trading bot in Python?

Yes. Install LumiBot (pip install lumibot), set your AftermathFinance keys and use the aftermath CCXT exchange id as shown above.

Does AftermathFinance have a testnet?

Yes. Set AFTERMATH_SANDBOX=true and use keys from the AftermathFinance testnet.

Which keys does a AftermathFinance bot need?

There are no permission boxes to set. Aftermath says an agent wallet can do everything except withdraw collateral, grant or revoke other agent wallets, and revoke builder code approvals. So the agent wallet can trade but cannot withdraw. The admin wallet can revoke it at any time.

Can an AI agent trade on AftermathFinance by itself?

Yes. The agentic example above gives one agent permission to trade. You control what it may trade and how much through its prompt.

Can I trade AftermathFinance perpetual futures with LumiBot?

CCXT lists perpetual swaps for this exchange. Use the full contract symbol, such as BTC/USD:USDC.

Is LumiBot free?

Yes. LumiBot is open source on GitHub at https://github.com/Lumiwealth/lumibot. You pay only your exchange’s trading fees and, for AI agents, your model provider.

Run it in the cloud with BotSpot

Do not want to keep a computer running for your AftermathFinance bot? BotSpot is the hosted home for LumiBot strategies and AI trading agents: build with AI, backtest, connect a broker, and watch every trade with logs and alerts.

Try BotSpot

Sources