deeplens-trade
v0.1.2
Published
TypeScript SDK for trading on Aftermath Finance (Sui) — perpetuals, swaps, DCA, vaults, signals, and paper trading
Maintainers
Readme
deeplens-trade
TypeScript SDK for trading on Aftermath Finance (Sui blockchain). Perpetuals, token swaps, DCA orders, vaults, trading signals, and paper trading -- all in one package.
Install
npm install deeplens-tradeQuick Start
import { DeepLensSDK } from "deeplens-trade";
const sdk = new DeepLensSDK({ network: "mainnet" });
await sdk.init();
// Fetch all market prices
const prices = await sdk.prices();
// Scan markets + compute trading signals
const { stats, signals } = await sdk.scan();With a Signer (for trading)
import { DeepLensSDK, WalletManager } from "deeplens-trade";
const sdk = new DeepLensSDK({ network: "mainnet" });
await sdk.init();
// Create or import a wallet
const wallet = sdk.importWallet("your-secret-key", {
rpcUrl: "https://fullnode.mainnet.sui.io:443",
network: "mainnet",
});
// Open a 3x long on BTC with $50 collateral
const digest = await sdk.trading.long({
market: "BTC",
collateral: 50,
leverage: 3,
});
// Swap 1 SUI to USDC
const swapDigest = await sdk.swap.execute({
from: "SUI",
to: "USDC",
amount: 1,
});Architecture
DeepLensSDK
|-- markets MarketService (read-only, no signer needed)
|-- signals SignalEngine (read-only, no signer needed)
|-- paper PaperTrader (in-memory, no signer needed)
|-- state StateManager (file I/O, no signer needed)
|-- vaults VaultService (read: no signer, write: signer)
|-- trading TradingService (requires signer)
|-- swap SwapService (requires signer)
|-- dca DcaService (requires signer)Modules that don't require a signer are always available. Modules that need a signer throw if accessed before calling sdk.setSigner() or passing a signer in the constructor.
Signer Interface
Any object implementing this interface can be used as a signer:
interface Signer {
readonly address: string;
signAndExecute(tx: unknown): Promise<string>;
}The SDK ships WalletManager (Ed25519 keypair signer), but you can bring your own -- for example, a dapp-kit wallet adapter in a browser.
Modules
MarketService
Real-time perpetuals market data.
const markets = new MarketService();
// All markets with 24h stats
const stats = await markets.getStats();
// => MarketStats[] { symbol, price, change24h, volume24h, fundingRate, ... }
// Latest prices
const prices = await markets.getPrices();
// => MarketPrice[] { symbol, markPrice, indexPrice, midPrice }
// Single-market orderbook
const book = await markets.getOrderbook("BTC");
// => OrderbookData { bids, asks, spread, spreadPct }
// Raw market objects + stats (for advanced usage)
const snapshots = await markets.getSnapshots();
// Historical candles
const candles = await markets.getCandles({
marketId: MARKET_IDS.BTC,
fromTimestamp: Date.now() - 86400000,
toTimestamp: Date.now(),
intervalMs: 3600000,
});TradingService
Perpetuals trading -- open/close positions, manage collateral.
const trading = sdk.trading; // requires signer
// Create a perps account (first time only)
await trading.createAccount();
// Account summary (collateral, equity, positions, PnL)
const account = await trading.getAccount();
// Open long
await trading.long({
market: "ETH",
collateral: 100,
leverage: 5,
stopLoss: 1800,
takeProfit: 2500,
});
// Open short
await trading.short({
market: "SUI",
collateral: 25,
leverage: 3,
});
// Close a position
await trading.close({ market: "ETH" });
// Deposit / withdraw collateral
await trading.deposit(200);
await trading.withdraw(50);
// Order history
const orders = await trading.getOrderHistory(20);
// Collateral history
const collateralHistory = await trading.getCollateralHistory(20);SwapService
Token swaps via the Aftermath router.
const swap = sdk.swap; // requires signer
// Get a quote
const quote = await swap.quote({
from: "SUI",
to: "USDC",
amount: 10,
});
console.log(quote.amountOut, quote.priceImpact);
// Execute swap
const digest = await swap.execute({
from: "SUI",
to: "USDC",
amount: 10,
slippage: 0.01,
});
// Supported coins
const coins = await swap.getSupportedCoins();DcaService
Dollar-cost averaging orders.
const dca = sdk.dca; // requires signer
// Create a DCA order: buy USDC with SUI, $5/trade, daily, 30 trades
await dca.create({
from: "SUI",
to: "USDC",
amountPerTrade: 5,
frequency: "daily", // "hourly" | "daily" | "weekly" | "monthly"
totalTrades: 30,
});
// List active orders
const active = await dca.getActive();
// List past (completed/cancelled) orders
const past = await dca.getPast();
// Cancel orders
await dca.cancel(["order-id-1"]);VaultService
Aftermath perpetuals vaults (LP positions).
const vaults = sdk.vaults;
// List all vaults
const allVaults = await vaults.getAll();
// => VaultInfo[] { vaultId, lpPrice, isPaused, totalDeposited }
// Deposit into a vault
await vaults.deposit({ vaultId: "0x...", amount: 100 });
// Withdraw from a vault
await vaults.withdraw({ vaultId: "0x...", lpAmount: 50 });
// Get LP token prices
const lpPrices = await vaults.getLpPrices(["0x..."]);
// Get your LP coin holdings
const myLp = await vaults.getOwnedLpCoins();SignalEngine
Trading signal computation from market data. Uses three weighted components:
| Component | Weight | Description | | -------------- | ------ | ---------------------------------------- | | Momentum | 40% | Price change over rolling window | | MA Crossover | 35% | Short MA vs long MA divergence | | Funding Fade | 25% | Counter-trade extreme funding rates |
const engine = new SignalEngine(12); // 12-tick history
// Feed market data and get signals
const signals = engine.compute(stats);
// => TradingSignal[] {
// symbol, price, direction, strength,
// components: { momentum, maCrossover, fundingFade }
// }
// direction: "long" (score > 0.15), "short" (score < -0.15), "neutral"
// strength: 0..1
// Access raw price history
const history = engine.getHistory();
// Reset
engine.reset();PaperTrader
Simulated trading with virtual funds. No blockchain interaction.
const paper = new PaperTrader(1000); // $1,000 starting equity
// Open a paper position
const position = paper.open({
marketId: MARKET_IDS.BTC,
symbol: "BTC",
side: "long",
collateral: 100,
leverage: 3,
entryPrice: 65000,
stopLoss: 62000,
takeProfit: 72000,
});
// Check SL/TP against live prices
const closed = paper.checkStopLossTakeProfit({
[MARKET_IDS.BTC]: 63000,
});
// Close manually
const trade = paper.close(position.id, 67000, "manual-close");
// Portfolio snapshot
const portfolio = paper.getPortfolio({
[MARKET_IDS.BTC]: 67000,
});
// => { equity, available, positions, trades, stats: { totalPnl, winRate, ... } }
// Reset to initial state
paper.reset();StateManager
Persists agent state to disk as JSON. Used by the autonomous trading agent to share state with the web dashboard.
const state = new StateManager(); // default: ~/.deeplens/agent-state.json
// or: new StateManager("/custom/path.json")
state.write({
status: "running",
mode: "paper",
// ... full AgentState
});
const current = state.read(); // AgentState | null
state.isStale(600_000); // true if last update > 10min ago
state.clear(); // delete file
state.getPath(); // "~/.deeplens/agent-state.json"WalletManager
Ed25519 keypair wallet that implements the Signer interface.
import { WalletManager } from "deeplens-trade";
// Create a new random wallet
const wallet = WalletManager.create({
rpcUrl: "https://fullnode.mainnet.sui.io:443",
network: "mainnet",
});
// Import from secret key
const imported = WalletManager.fromSecretKey("suiprivkey1...", {
rpcUrl: "https://fullnode.mainnet.sui.io:443",
network: "mainnet",
});
console.log(wallet.address); // "0x..."
// Token balances
const balances = await wallet.getBalances();
const suiBalance = await wallet.getSuiBalance();
const usdcBalance = await wallet.getBalance("USDC");Constants
import {
TOKENS, // Record<string, TokenInfo> — SUI, USDC, USDC.e, USDT, ETH
TOKEN_LIST, // TokenInfo[]
MARKET_IDS, // { BTC, ETH, SUI, XAUT, XAG } => marketId
MARKET_SYMBOLS, // reverse: marketId => symbol
ALL_MARKET_IDS, // string[]
PERP_MARKETS, // PerpMarketMeta[] — full metadata per market
PERP_MARKET_META, // Record<symbol, { name, category, hours }>
DCA_FREQUENCIES, // { hourly, daily, weekly, monthly } => ms
COLLATERAL_COIN_TYPE, // native USDC coin type
} from "deeplens-trade";Resolver Helpers
import { resolveToken, resolveMarketId, resolveMarketSymbol } from "deeplens-trade";
resolveToken("sui"); // TokenInfo for SUI (case-insensitive)
resolveToken("USDC.e"); // TokenInfo for bridged USDC
resolveMarketId("BTC"); // "0x9596..."
resolveMarketSymbol("0x9596..."); // "BTC"Configuration
Environment variables (all optional):
| Variable | Default | Description |
| -------------------------------- | ----------- | --------------------------------- |
| AFTERMATH_NETWORK | MAINNET | MAINNET or TESTNET |
| DEFAULT_SLIPPAGE | 0.01 | Default slippage tolerance (1%) |
Web apps can use NEXT_PUBLIC_ prefixed versions of these variables.
Types
All types are exported from the package root:
import type {
// Core
Signer,
DeepLensConfig,
// Tokens
TokenInfo,
TokenBalance,
// Markets
PerpMarketMeta,
MarketPrice,
MarketStats,
OrderbookLevel,
OrderbookData,
// Account
PerpsAccountSummary,
Position,
// Trading
TradeParams,
CloseParams,
TradeResult,
OrderHistoryItem,
CollateralHistoryItem,
// Swap
SwapQuote,
SwapParams,
SwapResult,
// DCA
DcaOrderParams,
DcaOrder,
// Vaults
VaultInfo,
// Signals
SignalDirection,
TradingSignal,
// Paper Trading
PaperPosition,
PaperTrade,
PaperPortfolio,
// Agent
AgentState,
AgentPosition,
AgentTradeEntry,
} from "deeplens-trade";Available Markets
| Symbol | Name | Pair | Category | Hours | Max Leverage | | ------ | -------- | -------- | --------- | ----- | ------------ | | BTC | Bitcoin | BTC/USD | Crypto | 24/7 | 5x | | ETH | Ethereum | ETH/USD | Crypto | 24/7 | 5x | | SUI | Sui | SUI/USD | Crypto | 24/7 | 5x | | XAUT | Gold | XAUT/USD | Commodity | 24/7 | 5x | | XAG | Silver | XAG/USD | Commodity | 24/5 | 5x |
Supported Tokens
| Symbol | Name | Decimals | Notes | | ------ | ------------------ | -------- | ---------------------- | | SUI | Sui | 9 | Native gas token | | USDC | USD Coin (native) | 6 | Perps collateral | | USDC.e | USD Coin (bridged) | 6 | Wormhole bridged | | USDT | Tether | 6 | Wormhole bridged | | ETH | Ethereum | 8 | Wormhole bridged |
Important: Perpetuals collateral uses native USDC (not USDC.e). The SDK handles this distinction automatically.
Advanced Usage
Direct Aftermath Service Access
For operations not covered by the high-level modules:
import { getAftermathService } from "deeplens-trade";
const service = getAftermathService();
await service.init();
// Raw SDK access
const { markets } = await service.getAllMarkets(COLLATERAL_COIN_TYPE);Legacy Client Exports
Backward-compatible function exports from the original aftermath-client:
import {
getAftermathSdk,
getRouterClient,
getPerpetualsClient,
getDcaClient,
getAllMarkets,
getOrderbook,
getOwnedAccountCaps,
getPrimaryPerpsAccount,
} from "deeplens-trade";Custom Signer
Implement the Signer interface to use any wallet:
import type { Signer } from "deeplens-trade";
class DappKitSigner implements Signer {
get address() {
return this.currentAccount.address;
}
async signAndExecute(tx: unknown): Promise<string> {
const result = await signTransactionBlock({ transactionBlock: tx });
return result.digest;
}
}
sdk.setSigner(new DappKitSigner());License
MIT
