Ranger Finance SDK for building perpetual futures trading applications on Solana. The first Solana Perps Aggregator - aggregates liquidity across multiple perp protocols (Drift, Flash, Adrena, Jupiter). Use when integrating perps trading, smart order routing, position management, or building AI trading agents.
npx skills add https://github.com/sendaifun/skills --skill ranger-finance
A comprehensive guide for building Solana applications with Ranger Finance - the first perpetual futures aggregator on Solana.
Ranger Finance is a Smart Order Router (SOR) that aggregates perpetual futures trading across multiple Solana protocols:
# Clone the SDK demo
git clone https://github.com/ranger-finance/sor-ts-demo.git
cd sor-ts-demo
npm install
Create a .env file:
RANGER_API_KEY=your_api_key_here
SOLANA_RPC_URL=https://api.mainnet-beta.solana.com
WALLET_PRIVATE_KEY=your_base58_private_key # Optional, for signing
import { SorApi, TradeSide } from 'ranger-sor-sdk';
import dotenv from 'dotenv';
dotenv.config();
// Initialize the SOR API client
const sorApi = new SorApi({
apiKey: process.env.RANGER_API_KEY!,
solanaRpcUrl: process.env.SOLANA_RPC_URL,
});
// Your wallet public key
const walletAddress = 'YOUR_WALLET_PUBLIC_KEY';
type TradeSide = 'Long' | 'Short';
type AdjustmentType =
| 'Quote' // Get a quote only
| 'Increase' // Open or increase position
| 'DecreaseFlash' // Decrease via Flash
| 'DecreaseJupiter' // Decrease via Jupiter
| 'DecreaseDrift' // Decrease via Drift
| 'DecreaseAdrena' // Decrease via Adrena
| 'CloseFlash' // Close via Flash
| 'CloseJupiter' // Close via Jupiter
| 'CloseDrift' // Close via Drift
| 'CloseAdrena' // Close via Adrena
| 'CloseAll'; // Close entire position
interface Position {
id: string;
symbol: string;
side: TradeSide;
quantity: number;
entry_price: number;
liquidation_price: number;
position_leverage: number;
real_collateral: number;
unrealized_pnl: number;
borrow_fee: number;
funding_fee: number;
open_fee: number;
close_fee: number;
created_at: string;
opened_at: string;
platform: string; // 'DRIFT', 'FLASH', 'ADRENA', 'JUPITER'
}
interface Quote {
base: number;
fee: number;
total: number;
fee_breakdown: {
base_fee: number;
spread_fee: number;
volatility_fee: number;
margin_fee: number;
close_fee: number;
other_fees: number;
};
}
interface VenueAllocation {
venue_name: string;
collateral: number;
size: number;
quote: Quote;
order_available_liquidity: number;
venue_available_liquidity: number;
}
interface OrderMetadataResponse {
venues: VenueAllocation[];
total_collateral: number;
total_size: number;
}
Before executing a trade, get a quote to see pricing across venues:
import { SorApi, OrderMetadataRequest, TradeSide } from 'ranger-sor-sdk';
const sorApi = new SorApi({ apiKey: process.env.RANGER_API_KEY! });
async function getQuote() {
const request: OrderMetadataRequest = {
fee_payer: walletAddress,
symbol: 'SOL',
side: 'Long' as TradeSide,
size: 1.0, // 1 SOL position size
collateral: 10.0, // 10 USDC collateral (10x leverage)
size_denomination: 'SOL',
collateral_denomination: 'USDC',
adjustment_type: 'Quote',
};
const quote = await sorApi.getOrderMetadata(request);
console.log('Available venues:');
quote.venues.forEach(venue => {
console.log(` ${venue.venue_name}: ${venue.quote.total} USDC`);
});
return quote;
}
async function openLongPosition() {
const request = {
fee_payer: walletAddress,
symbol: 'SOL',
side: 'Long' as TradeSide,
size: 1.0,
collateral: 10.0,
size_denomination: 'SOL',
collateral_denomination: 'USDC',
adjustment_type: 'Increase' as const,
};
// Get transaction instructions
const response = await sorApi.increasePosition(request);
console.log('Transaction message (base64):', response.message);
if (response.meta) {
console.log('Executed price:', response.meta.executed_price);
console.log('Venues used:', response.meta.venues_used);
}
return response;
}
// Open a short position
async function openShortPosition() {
const request = {
fee_payer: walletAddress,
symbol: 'ETH',
side: 'Short' as TradeSide,
size: 0.5,
collateral: 100.0,
size_denomination: 'ETH',
collateral_denomination: 'USDC',
adjustment_type: 'Increase' as const,
};
return await sorApi.increasePosition(request);
}
async function decreasePosition() {
const request = {
fee_payer: walletAddress,
symbol: 'SOL',
side: 'Long' as TradeSide,
size: 0.5, // Decrease by 0.5 SOL
collateral: 5.0, // Withdraw 5 USDC collateral
size_denomination: 'SOL',
collateral_denomination: 'USDC',
adjustment_type: 'DecreaseFlash' as const, // Route through Flash
};
return await sorApi.decreasePosition(request);
}
// Close entire position on a specific venue
async function closePosition() {
const request = {
fee_payer: walletAddress,
symbol: 'SOL',
side: 'Long' as TradeSide,
adjustment_type: 'CloseFlash' as const,
};
return await sorApi.closePosition(request);
}
// Close all positions across all venues
async function closeAllPositions() {
const request = {
fee_payer: walletAddress,
symbol: 'SOL',
side: 'Long' as TradeSide,
adjustment_type: 'CloseAll' as const,
};
return await sorApi.closePosition(request);
}
import { Keypair, VersionedTransaction } from '@solana/web3.js';
import bs58 from 'bs58';
async function executeTradeWithSigning() {
// Get transaction instructions
const txResponse = await sorApi.increasePosition({
fee_payer: walletAddress,
symbol: 'SOL',
side: 'Long',
size: 1.0,
collateral: 10.0,
size_denomination: 'SOL',
collateral_denomination: 'USDC',
adjustment_type: 'Increase',
});
// Create keypair from private key
const privateKeyBytes = bs58.decode(process.env.WALLET_PRIVATE_KEY!);
const keypair = Keypair.fromSecretKey(privateKeyBytes);
// Define signing function
const signTransaction = async (tx: VersionedTransaction) => {
tx.sign([keypair]);
return tx;
};
// Execute the transaction
const result = await sorApi.executeTransaction(txResponse, signTransaction);
console.log('Transaction signature:', result.signature);
return result;
}
async function getAllPositions() {
const positions = await sorApi.getPositions(walletAddress);
positions.positions.forEach(pos => {
console.log(`${pos.symbol} ${pos.side}: ${pos.quantity} @ ${pos.entry_price}`);
console.log(` Platform: ${pos.platform}`);
console.log(` PnL: ${pos.unrealized_pnl}`);
console.log(` Liquidation: ${pos.liquidation_price}`);
});
return positions;
}
async function getDriftPositions() {
const positions = await sorApi.getPositions(walletAddress, {
platforms: ['DRIFT'],
});
return positions;
}
async function getFlashAndAdrenaPositions() {
const positions = await sorApi.getPositions(walletAddress, {
platforms: ['FLASH', 'ADRENA'],
});
return positions;
}
async function getSolPositions() {
const positions = await sorApi.getPositions(walletAddress, {
symbols: ['SOL-PERP'],
});
return positions;
}
Ranger provides an MCP (Model Context Protocol) server for AI agent integration.
Clone ranger-agent-kit and follow its README for setup.
The Ranger MCP server exposes these tools:
SOR Tools:
sor_get_trade_quote - Get pricing quotessor_increase_position - Open/increase positionssor_decrease_position - Reduce positionssor_close_position - Close positionsData API Tools:
data_get_positions - Fetch current positionsdata_get_trade_history - Trading historydata_get_liquidations - Liquidation data and signalsdata_get_funding_rates - Funding rate analyticsimport asyncio
from ranger_mcp_agent.examples.mean_reversion_agent import run_mean_reversion_agent
async def main():
# Run a mean reversion trading strategy
await run_mean_reversion_agent()
if __name__ == "__main__":
asyncio.run(main())
cd ranger-agent-kit/perps-mcp
cp .env.example .env
# Edit .env with your API credentials
python -m ranger_mcp
class SorApi {
constructor(config: SorSdkConfig);
// Get quote for a trade
getOrderMetadata(request: OrderMetadataRequest): Promise<OrderMetadataResponse>;
// Open or increase a position
increasePosition(request: IncreasePositionRequest): Promise<TransactionResponse>;
// Reduce a position
decreasePosition(request: DecreasePositionRequest): Promise<TransactionResponse>;
// Close a position
closePosition(request: ClosePositionRequest): Promise<TransactionResponse>;
// Get positions for a wallet
getPositions(
publicKey: string,
options?: {
platforms?: string[];
symbols?: string[];
startDate?: string;
endDate?: string;
}
): Promise<PositionsResponse>;
// Execute a signed transaction
executeTransaction(
transactionResponse: TransactionResponse,
signTransaction: (tx: VersionedTransaction) => Promise<VersionedTransaction>
): Promise<{ signature: string }>;
// Get Solana connection
getConnection(): Connection;
}
interface SorSdkConfig {
apiKey: string;
sorApiBaseUrl?: string; // Default: Ranger SOR API
dataApiBaseUrl?: string; // Default: Ranger Data API
solanaRpcUrl?: string; // Default: Mainnet RPC
}
interface BaseRequest {
fee_payer: string;
symbol: string;
side: TradeSide;
size_denomination?: string;
collateral_denomination?: string;
}
interface IncreasePositionRequest extends BaseRequest {
size: number;
collateral: number;
size_denomination: string;
collateral_denomination: string;
adjustment_type: 'Increase';
}
interface DecreasePositionRequest extends BaseRequest {
size: number;
collateral: number;
size_denomination: string;
collateral_denomination: string;
adjustment_type: 'DecreaseFlash' | 'DecreaseJupiter' | 'DecreaseDrift' | 'DecreaseAdrena';
}
interface ClosePositionRequest extends BaseRequest {
adjustment_type: 'CloseFlash' | 'CloseJupiter' | 'CloseDrift' | 'CloseAdrena' | 'CloseAll';
}
interface TransactionResponse {
message: string; // Base64-encoded transaction
meta?: {
executed_price?: number;
executed_size?: number;
executed_collateral?: number;
venues_used?: string[];
};
}
interface PositionsResponse {
positions: Position[];
}
Ranger aggregates perpetual markets across:
| Protocol | Markets |
|----------|---------|
| Drift | SOL, BTC, ETH, and 20+ assets |
| Flash | SOL, BTC, ETH |
| Adrena | SOL, BTC, ETH |
| Jupiter | SOL, BTC, ETH |
try {
const response = await sorApi.increasePosition(request);
} catch (error) {
if (error.error_code) {
// API error
console.error('API Error:', error.message);
console.error('Error code:', error.error_code);
} else {
// Network or other error
throw error;
}
}
getOrderMetadata to compare pricing across venues.ranger-finance/
├── SKILL.md # This file
├── resources/
│ ├── api-reference.md # API endpoint reference
│ └── types-reference.md # Complete TypeScript types
├── examples/
│ ├── basic/
│ │ └── example.ts # Basic trade operations
│ ├── positions/
│ │ └── example.ts # Position queries and management
│ └── transactions/
│ └── example.ts # Transaction signing flow
├── templates/
│ └── setup.ts # Ready-to-use setup template
└── docs/
├── troubleshooting.md # Common issues and solutions
└── ai-agent-integration.md # AI agent setup guide
Python library for accessing, analyzing, and extracting data from SEC EDGAR filings. Use when working with SEC filings, financial statements (income statement, balance sheet, cash flow), XBRL financial data, insider trading (Form 4), institutional holdings (13F), company financials, annual/quarterly reports (10-K, 10-Q), proxy statements (DEF 14A), 8-K current events, company screening by ticker/CIK/industry, multi-period financial analysis, or any SEC regulatory filings.
Use this skill when the user asks to list, create, inspect, update, disable, re-enable, or revoke AltLLM Portal API keys for external agents or applications. Do NOT use for wallet login, billing history, or payment links.
Use this skill when the user asks to log in or out with a wallet session, fetch a wallet sign-in challenge, verify an externally signed challenge, or troubleshoot AltLLM Portal wallet login for the local altllm CLI. Do NOT use for API key management, billing history, or payment links.
Use this umbrella skill when the request spans multiple AltLLM Portal CLI domains, or when you need to navigate the local altllm CLI in this repository across auth, API keys, billing history, NOWPayments payment links, and related x402 Portal top-up guidance.
Build with the ChainGPT Web3 AI developer platform. Full API/SDK reference and project scaffolding for: Web3 AI Chatbot & LLM, AI NFT Generator, Smart Contract Generator, Smart Contract Auditor, AI Crypto News, AgenticOS Twitter agents, and Solidity LLM. Use when building blockchain apps, Web3 chatbots, NFT tools, smart contract tools, crypto news feeds, AI agents, or integrating any ChainGPT API. Triggers: chaingpt, web3 ai, nft generator, smart contract audit, crypto news api, agenticos, solidity llm, cgpt, blockchain ai, token analytics.
TypeScript SDK for the Payment HTTP Authentication Scheme. Handles 402 Payment Required flows with Tempo, Stripe, and other payment methods. Use when integrating payments or mppx into a client or server application.
>- Guide for developing with near-api-js v7 - the JavaScript/TypeScript library for NEAR blockchain interaction. (3) calling smart contracts, (4) managing accounts and keys, (5) working with NEAR RPC API, (6) handling FT/NFT tokens on NEAR, (7) using NEAR cryptographic operations (KeyPair, signing), (8) converting between NEAR units (yocto, gas), (9) gasless/meta transactions with relayers, (10) NEP-413 message signing for authentication, (11) storage deposit management for FT contracts. Triggers on any NEAR blockchain development tasks.
TypeScript library for NEAR Protocol blockchain interaction. Use this skill when writing code that interacts with NEAR Protocol, including viewing contract data, calling contract methods, sending NEAR tokens, building transactions, creating type-safe contract wrappers, integrating wallets (Wallet Selector, HOT Connect), React hooks and providers (@near-kit/react), managing keys, testing with sandbox, meta-transactions (NEP-366), and message signing (NEP-413).
Take sendaifun/ranger-finance from the repository into ~/.claude/skills for personal
use, or into .claude/skills inside a project.
The agent identifies a skill by the name field in its header. Two skills with the
same name cannot sit side by side — one of them will be ignored.
The instructions reference npm.
Without those the skill loads but fails at the first command.