@lnfi-network/lnex-sdk
v0.1.0
Published
LN Exchange SDK for spot and perpetual trading
Readme
LnexSdk
A JavaScript SDK for interacting with Lnex Exchange API, supporting both spot and perpetual trading.
Installation
npm install @lnfi-network/lnex-sdkQuick Start
Browser Environment
Use Case: Web applications where users trade through their browser wallets
Features:
- Wallet integration is optional - automatically connects to installed crypto wallets
- Supports popular wallet extensions (OKX, TokenPocket, Alby, etc.)
- Uses browser-compatible HTTP client
import { LnexSdk } from '@lnfi-network/lnex-sdk';
// Basic initialization (all parameters optional)
const lnex = new LnexSdk();
// Get available trading pairs and market information
const spotPublicInfo = await lnex.spot.getPublicInfo();
const perpPublicInfo = await lnex.perp.getPublicInfo();
Node.js Environment
Use Case: Server applications, trading bots, or backend services
Features:
- Private key authentication is required for security
- Uses LnfiNostr for Nostr protocol implementation
- Supports automated trading and server-side applications
import { LnexSdk, LnfiNostr } from '@lnfi-network/lnex-sdk';
// Create signer (required)
const signer = new LnfiNostr({
privateKey: 'nsec1...' // or hex string
});
// Basic initialization
const lnex = new LnexSdk({ signer });
// Get available trading pairs and market information
const spotPublicInfo = await lnex.spot.getPublicInfo();
const perpPublicInfo = await lnex.perp.getPublicInfo();
API Reference
LnexSdk Class
Constructor Options
env(string, optional): Environment setting (default: 'production')- 'development': Development environment
- 'production': Production environment
signer(object, optional): Nostr signer instance- Browser: Automatically reads from wallet extensions if not provided
- Node.js: Must provide LnfiNostr instance
- When no signer is provided, the SDK will automatically select in this priority:
- 'window.lnfi.nostr'
- 'window.okxwallet.nostr'
- 'window.tokenpocket.nostr'
- 'window.alby.nostr'
- 'window.nostr'
spotBaseURL(string, optional): Custom spot trading API base URL- Default: 'https://test-spots-api.ln.exchange'
perpBaseURL(string, optional): Custom perpetual trading API base URL- Default: 'https://test-futures-api.ln.exchange'
relay(string|string[], optional): Custom Nostr relay URL(s)- Accepts single relay URL string or array of relay URLs
- Default: Uses lnfi-sdk's built-in relay configuration based on environment
- Production: Uses production relay endpoints from lnfi-sdk
- Development: Uses development relay endpoints from lnfi-sdk
Configuration Examples
Custom Configuration:
// Browser environment with custom settings
const lnex = new LnexSdk({
env: 'development',
spotBaseURL: 'https://custom-spot-api.example.com',
perpBaseURL: 'https://custom-perp-api.example.com',
relay: 'wss://custom-relay.example.com'
});
// Node.js environment with custom settings
import { LnexSdk, LnfiNostr } from '@lnfi-network/lnex-sdk';
const signer = new LnfiNostr({ privateKey: 'nsec1...' });
const lnex = new LnexSdk({
signer,
env: 'development',
spotBaseURL: 'https://custom-spot-api.example.com',
perpBaseURL: 'https://custom-perp-api.example.com',
relay: 'wss://custom-relay.example.com'
});Signer Configuration & LnfiNostr Class
The SDK supports multiple signing methods through the signer parameter. You can use browser Nostr extensions directly or create custom signers using the LnfiNostr class.
Browser Environment (Auto-detection)
// SDK automatically detects available Nostr providers in this order:
// 1. window.lnfi.nostr → 2. window.okxwallet.nostr → 3. window.tokenpocket.nostr
// 4. window.alby.nostr → 5. window.nostr
const lnex = new LnexSdk();
// Or specify a particular provider
const lnex = new LnexSdk({ signer: window.nostr });LnfiNostr Class for Custom Signing
The LnfiNostr class provides flexible signing options for different wallet types:
1. Using Private Key
import { LnexSdk, LnfiNostr } from '@lnfi-network/lnex-sdk';
const signer = new LnfiNostr({
privateKey: 'nsec1...' // or hex format private key
});
const lnex = new LnexSdk({ signer });2. Using EVM Wallet (MetaMask, etc.)
// Using default window.ethereum
const signer = new LnfiNostr({ evm: true });
// Using custom provider (viem/wagmi walletClient)
const signer = new LnfiNostr({ evm: walletClient });
// Using ethers provider
const provider = new ethers.BrowserProvider(window.ethereum).provider;
const signer = new LnfiNostr({ evm: provider });
const lnex = new LnexSdk({ signer });3. Using BTC Wallet (Unisat, etc.)
// Using default window.unisat
const signer = new LnfiNostr({ btc: true });
// Using custom BTC provider
const signer = new LnfiNostr({ btc: customBtcProvider });
const lnex = new LnexSdk({ signer });Note: If no signer is provided and no browser Nostr extensions are available, the SDK will throw an error: "Nostr provider not available"
For more detailed LnfiNostr usage, refer to the lnfi-sdk documentation.
Core Methods
- spot: Getter property that returns SpotApi instance for spot trading
- perp: Getter property that returns PerpApi instance for perpetual trading
getPublicKey()
Retrieve the public key for the current account.
Returns: Promise<Object> - Object containing public key in raw hex and npub format
const publicKey = await lnex.getPublicKey();
console.log(publicKey);SpotApi Methods
User Management
createUser(referrals?)
Registers a user for trading.
Parameters:
referrals(string, optional): Referral ID for user registration (default: "")
Returns: Promise<Object> - Response from the API containing user registration result
Example:
const result = await lnex.spot.createUser("referral123");enableTrade(symbolName)
Enables trading for a specific symbol.
Parameters:
symbolName(string, required): The name of the symbol to enable trading for
Returns: Promise<Object> - Response data of the enable trade request
Example:
const result = await lnex.spot.enableTrade("BTC-USDT");getUserInfo()
Fetches user information.
Returns: Promise<Object> - User information data
Example:
const userInfo = await lnex.spot.getUserInfo();Asset Management
approve(tokenName, amount)
Approves a token for trading.
Parameters:
tokenName(string, required): Token name to approveamount(number, required): Amount to approve (must be positive)
Returns: Promise<Object> - Response from the approval operation
Example:
const result = await lnex.spot.approve("USDT", 1000);deposit(tokenNameOrAssetId, amount)
Deposits an asset.
Parameters:
tokenNameOrAssetId(string, required): Token name (e.g., "USDT") or Asset IDamount(number, required): Amount to deposit (must be positive)
Returns: Promise<Object> - Response from the deposit operation
Example:
// Using token name
const result = await lnex.spot.deposit("USDT", 100);
// Using asset ID
const result2 = await lnex.spot.deposit("asset_id_here", 100);withdraw(assetsId, amount)
Withdraws an asset.
Parameters:
assetsId(string, required): Asset IDamount(number, required): Amount to withdraw
Returns: Promise<Object> - Response from the API
Example:
const result = await lnex.spot.withdraw("asset_id_here", 50);Market Data
getAllMarkets()
Fetches all available markets.
Returns: Promise<Object> - Market data
Example:
const markets = await lnex.spot.getAllMarkets();Order Management
createOrderApi(params)
Creates a new order.
Parameters:
params(Object, required): Order parametersside(string, required): Order side ("buy" or "sell")volume(number, required): Order volume (must be positive)symbolName(string, required): Symbol nameprice(number, optional): Order price (default: 0 for market order)type(number, optional): Order type (default: 2)timeInForce(number, optional): Time in force (default: 2)leverageLevel(number, optional): Leverage level (default: 1)
Returns: Promise<Object> - Response from the API
Example:
const order = await lnex.spot.createOrderApi({
side: "buy",
volume: 0.1,
symbolName: "BTC-USDT",
price: 50000
});cancelOrder(params)
Cancels an order.
Parameters:
params(Object, required): Order parameterssymbolName(string, required): Symbol nameorderId(number, required): Order ID
Returns: Promise<Object> - Response from the API
Example:
const result = await lnex.spot.cancelOrder({
symbolName: "BTC-USDT",
orderId: 12345
});cancelAllOrder(params)
Cancels all orders for a specific symbol.
Parameters:
params(Object, required): Order parameterssymbolName(string, required): Symbol name
Returns: Promise<Object> - Response from the API
Example:
const result = await lnex.spot.cancelAllOrder({
symbolName: "BTC-USDT"
});currentOrderList(params)
Retrieves current order list for a specific symbol.
Parameters:
params(Object, required): Query parameterssymbolName(string, required): Symbol namepage(number, optional): Page number (default: 1)limit(number, optional): Items per page (default: 10)type(string, optional): Order type filter (default: "")
Returns: Promise<Object> - Response from the API
Example:
const orders = await lnex.spot.currentOrderList({
symbolName: "BTC-USDT",
page: 1,
limit: 20
});triggerOrderList(params)
Retrieves trigger order list for a specific symbol.
Parameters:
params(Object, required): Query parameterssymbolName(string, required): Symbol namepage(number, optional): Page number (default: 1)limit(number, optional): Items per page (default: 10)type(string, optional): Order type filter (default: "")
Returns: Promise<Object> - Response from the API
Example:
const triggerOrders = await lnex.spot.triggerOrderList({
symbolName: "BTC-USDT"
});historyOrderList(params)
Retrieves historical order list for a specific symbol.
Parameters:
params(Object, required): Query parameterssymbolName(string, required): Symbol namepage(number, optional): Page number (default: 1)limit(number, optional): Items per page (default: 10)wallet(string, optional): Wallet address (default: current user's address)type(string, optional): Order type filter (default: "")beginTime(string, optional): Start time filter (default: "")endTime(string, optional): End time filter (default: "")
Returns: Promise<Object> - Response from the API
Example:
const historyOrders = await lnex.spot.historyOrderList({
symbolName: "BTC-USDT",
page: 1,
limit: 50,
beginTime: "2024-01-01",
endTime: "2024-01-31"
});historyTriggerOrderList(params)
Retrieves historical trigger order list for a specific symbol.
Parameters:
params(Object, required): Query parameterssymbolName(string, required): Symbol namepage(number, optional): Page number (default: 1)limit(number, optional): Items per page (default: 10)wallet(string, optional): Wallet address (default: current user's address)type(string, optional): Order type filter (default: "")beginTime(string, optional): Start time filter (default: "")endTime(string, optional): End time filter (default: "")
Returns: Promise<Object> - Response from the API
Example:
const historyTriggerOrders = await lnex.spot.historyTriggerOrderList({
symbolName: "BTC-USDT"
});hisTradeList(params)
Retrieves historical trade list for a specific symbol.
Parameters:
params(Object, required): Query parameterssymbolName(string, required): Symbol namepage(number, optional): Page number (default: 1)limit(number, optional): Items per page (default: 10)wallet(string, optional): Wallet address (default: current user's address)type(string, optional): Trade type filter (default: "")beginTime(string, optional): Start time filter (default: "")endTime(string, optional): End time filter (default: "")
Returns: Promise<Object> - Response from the API
Example:
const trades = await lnex.spot.hisTradeList({
symbolName: "BTC-USDT",
limit: 100
});PerpApi Methods
User Management
createUser(referrals?)
Registers a user for perpetual trading.
Parameters:
referrals(string, optional): Referral ID for user registration (default: "")
Returns: Promise<Object> - Response from the API containing user registration result
Example:
const result = await lnex.perp.createUser("referral123");enableTrade(contractName)
Enables trading for a specific contract.
Parameters:
contractName(string, required): The name of the contract to enable trading for
Returns: Promise<Object> - Response data of the enable trade request
Example:
const result = await lnex.perp.enableTrade("E-BTC-USDT");getUserInfo()
Fetches user information.
Returns: Promise<Object> - User information data
Example:
const userInfo = await lnex.perp.getUserInfo();Asset Management
approve(tokenName, amount)
Approves a token for perpetual trading.
Parameters:
tokenName(string, required): Token nameamount(number, required): Amount to approve
Returns: Promise<Object> - Response from the API
Example:
const result = await lnex.perp.approve("USDT", 1000);deposit(tokenNameOrAssetId, amount)
Deposits an asset for perpetual trading.
Parameters:
tokenNameOrAssetId(string, required): Token name (e.g., "USDT") or Asset IDamount(number, required): Amount to deposit (must be positive)
Returns: Promise<Object> - Response from the deposit operation
Example:
const result = await lnex.perp.deposit("USDT", 100);withdraw(assetsId, amount)
Withdraws an asset from perpetual trading.
Parameters:
assetsId(string, required): Asset IDamount(number, required): Amount to withdraw
Returns: Promise<Object> - Response from the API
Example:
const result = await lnex.perp.withdraw("asset_id_here", 50);Market Data
getAllMarkets()
Fetches all available perpetual markets.
Returns: Promise<Object> - Market data
Example:
const markets = await lnex.perp.getAllMarkets();Position Management
getAllPosition(data?)
Fetches all positions.
Parameters:
data(Object, optional): Query parameterspositionStatus(string, optional): Position status filter (default: "1")
Returns: Promise<Object> - Position data
Example:
const positions = await lnex.perp.getAllPosition({
positionStatus: "1"
});getHistoryPosition(data)
Fetches historical positions.
Parameters:
data(Object, required): Query parameterscontractId(string, required): Contract IDpage(number, optional): Page number (default: 1)limit(number, optional): Items per page (default: 10)
Returns: Promise<Object> - Historical position data
Example:
const historyPositions = await lnex.perp.getHistoryPosition({
contractId: "contract123",
page: 1,
limit: 20
});editLevel(data)
Edits leverage level for a contract.
Parameters:
data(Object, required): ParameterscontractName(string, required): Contract namenowLevel(number, required): New leverage level
Returns: Promise<Object> - Response from the API
Example:
const result = await lnex.perp.editLevel({
contractName: "E-BTC-USDT",
nowLevel: 10
});Order Management
createOrderApi(params)
Creates a new perpetual order.
Parameters:
params(Object, required): Order parametersside(string, required): Order side ("buy" or "sell")volume(number, required): Order volume (must be positive)contractName(string, required): Contract nameopenOrClose(string, required): "open" or "close"price(number, optional): Order price (default: 0 for market order)type(number, optional): Order type (default: 2)leverageLevel(number, optional): Leverage level (default: 8)
Returns: Promise<Object> - Response from the API
Example:
const order = await lnex.perp.createOrderApi({
side: "buy",
volume: 0.1,
contractName: "E-BTC-USDT",
openOrClose: "open",
leverageLevel: 10
});cancelOrder(params)
Cancels a perpetual order.
Parameters:
params(Object, required): Order parameterscontractName(string, required): Contract nameorderId(number, required): Order ID
Returns: Promise<Object> - Response from the API
Example:
const result = await lnex.perp.cancelOrder({
contractName: "E-BTC-USDT",
orderId: 12345
});cancelAllOrder(params)
Cancels all orders for a specific contract.
Parameters:
params(Object, required): Order parameterscontractName(string, required): Contract name
Returns: Promise<Object> - Response from the API
Example:
const result = await lnex.perp.cancelAllOrder({
contractName: "E-BTC-USDT"
});currentOrderList(params)
Retrieves current order list for a specific contract.
Parameters:
params(Object, required): Query parameterscontractName(string, required): Contract namepage(number, optional): Page number (default: 1)limit(number, optional): Items per page (default: 10)type(string, optional): Order type filter (default: "")
Returns: Promise<Object> - Response from the API
Example:
const orders = await lnex.perp.currentOrderList({
contractName: "E-BTC-USDT"
});triggerOrderList(params)
Retrieves trigger order list for a specific contract.
Parameters:
params(Object, required): Query parameterscontractName(string, required): Contract namepage(number, optional): Page number (default: 1)limit(number, optional): Items per page (default: 10)type(string, optional): Order type filter (default: "")
Returns: Promise<Object> - Response from the API
Example:
const triggerOrders = await lnex.perp.triggerOrderList({
contractName: "E-BTC-USDT"
});historyOrderList(params)
Retrieves historical order list for a specific contract.
Parameters:
params(Object, required): Query parameterscontractName(string, required): Contract namepage(number, optional): Page number (default: 1)limit(number, optional): Items per page (default: 10)wallet(string, optional): Wallet address (default: current user's address)type(string, optional): Order type filter (default: "")beginTime(string, optional): Start time filter (default: "")endTime(string, optional): End time filter (default: "")
Returns: Promise<Object> - Response from the API
Example:
const historyOrders = await lnex.perp.historyOrderList({
contractName: "E-BTC-USDT",
page: 1,
limit: 50
});historyTriggerOrderList(params)
Retrieves historical trigger order list for a specific contract.
Parameters:
params(Object, required): Query parameterscontractName(string, required): Contract namepage(number, optional): Page number (default: 1)limit(number, optional): Items per page (default: 10)wallet(string, optional): Wallet address (default: current user's address)type(string, optional): Order type filter (default: "")beginTime(string, optional): Start time filter (default: "")endTime(string, optional): End time filter (default: "")
Returns: Promise<Object> - Response from the API
Example:
const historyTriggerOrders = await lnex.perp.historyTriggerOrderList({
contractName: "E-BTC-USDT"
});hisTradeList(params)
Retrieves historical trade list for a specific contract.
Parameters:
params(Object, required): Query parameterscontractName(string, required): Contract namepage(number, optional): Page number (default: 1)limit(number, optional): Items per page (default: 10)wallet(string, optional): Wallet address (default: current user's address)type(string, optional): Trade type filter (default: "")beginTime(string, optional): Start time filter (default: "")endTime(string, optional): End time filter (default: "")
Returns: Promise<Object> - Response from the API
Example:
const trades = await lnex.perp.hisTradeList({
contractName: "E-BTC-USDT",
limit: 100
});Error Handling
All API methods return promises and may throw errors. Always use try-catch blocks:
try {
const result = await lnex.spot.createOrderApi({
symbolName: "BTC-USDT",
side: "buy",
volume: 0.01,
type: 1,
price: 30000,
});
console.log('Order created:', result);
} catch (error) {
console.error('Order failed:', error.message);
}License
MIT
