Ranger Finance 标志

Ranger Finance

组织
sendaifun
ranger-finance

Ranger Finance SDK,用于在 Solana 上构建永续期货交易应用。它是 Solana 上首个永续合约聚合器,可汇集多个永续合约协议(Drift、Flash、Adrena、Jupiter)的流动性。适用于集成永续合约交易、智能订单路由和仓位管理,或构建 AI 交易智能体。

Add to TypingMind

概览

发布者sendaifun
代码仓库skills
技能名称ranger-finance
星标数
128
复刻数
81
附带文件
8
许可协议Apache-2.0
链接
  • Markdown 格式的指令

    模型按需加载 SKILL.md 文件,因此只有在请求确实与该技能匹配时才会消耗 Token。

  • 兼容任何大语言模型

    AI 技能采用纯 Markdown,而非特定提供商的代码,因此可搭配 GPT、Claude、Gemini、Grok 或本地模型使用。

  • 8 个附带文件

    模型执行任务时可读取的脚本、模板和参考资料。这些文件为只读文件,绝不会被执行。

  • 开源

    由 sendaifun 发布于 GitHub。请在安装前查看技能的源文件。

安装

在 TypingMind 中安装 Ranger Finance AI 技能,即可搭配任意大语言模型使用;也可以将其放入其他支持读取 SKILL.md 的智能体中。

1

安装到 TypingMind

TypingMind 可直接从 GitHub 文件夹安装技能:读取 SKILL.md,打包资源文件,并将结果保存在本地。

  1. 打开应用,前往“插件 → 技能”。
  2. 选择“从 GitHub 安装”。
  3. 粘贴下方的技能文件夹 URL 并确认。
    https://github.com/sendaifun/skills/tree/main/skills/ranger-finance
  4. 请在每个需要使用该技能的聊天中启用它。
依次选择“插件 → 技能 → 添加技能 → 从 GitHub URL 导入”,然后粘贴文件夹 URL 并点击“继续”。
2

安装到其他智能体

任何支持 Agent Skills 格式的智能体都可以使用此技能,只需将文件夹复制到该智能体的技能目录中。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/sendaifun/skills.git /tmp/skills
mkdir -p .claude/skills
cp -r /tmp/skills/skills/ranger-finance .claude/skills/ranger-finance
复制后,请重启 Claude Code,以加载新技能。

在 TypingMind 中使用此技能

在任意 TypingMind 聊天中启用 Ranger Finance,后续即可交由模型处理。技能的名称和描述会放在系统提示词中,一旦请求匹配,模型就会自动加载完整指令,无需您手动调用,且在实际使用前不会消耗 Token。

一旦请求与技能匹配,模型就会自动加载 Ranger Finance。

兼容任何 AI 模型

AI 技能是纯 Markdown 指令,而非特定提供商的代码,因此 Ranger Finance 不局限于最初适配的模型。只需在 TypingMind 中安装一次,即可搭配 GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 或您自行运行的本地模型使用,全程使用您自己的 API 密钥。

  • 仅在需要时加载

    系统提示词中仅包含技能名称和描述。首次遇到匹配的请求时才会加载完整指令,因此技能未使用时,这些指令不会消耗 Token。

  • 在聊天中切换模型

    技能是指令而非代码,因此切换模型不会导致技能失效,新模型会读取同一个 SKILL.md。

技能指令

这是模型会加载的 SKILL.md 内容。请在安装前阅读,因为技能就是模型将遵循的指令。

Ranger Finance SDK Development Guide

A comprehensive guide for building Solana applications with Ranger Finance - the first perpetual futures aggregator on Solana.

Overview

Ranger Finance is a Smart Order Router (SOR) that aggregates perpetual futures trading across multiple Solana protocols:

  • Drift Protocol: Leading perps DEX on Solana
  • Flash Trade: High-performance perpetuals
  • Adrena: Leverage trading protocol
  • Jupiter Perps: Jupiter's perpetuals platform

Key Benefits

  • Best Execution: Automatically routes orders to venues with best pricing
  • Unified API: Single interface for all supported perp protocols
  • Position Aggregation: View and manage positions across all venues
  • AI Agent Support: Built-in MCP server for AI trading agents

Quick Start

Installation (TypeScript)

bash
# Clone the SDK demo
git clone https://github.com/ranger-finance/sor-ts-demo.git
cd sor-ts-demo
npm install

Environment Setup

Create a .env file:

bash
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

Basic Setup

typescript
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';

Core Concepts

1. Trade Sides

typescript
type TradeSide = 'Long' | 'Short';

2. Adjustment Types

typescript
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

3. Position Interface

typescript
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'
}

4. Quote Response

typescript
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;
}

Trading Operations

Get a Quote

Before executing a trade, get a quote to see pricing across venues:

typescript
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;
}

Open/Increase a Position

typescript
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);
}

Decrease a Position

typescript
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 a Position

typescript
// 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);
}

Sign and Execute Transaction

typescript
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;
}

Position Management

Fetch All Positions

typescript
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;
}

Filter Positions by Platform

typescript
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;
}

Filter Positions by Symbol

typescript
async function getSolPositions() {
  const positions = await sorApi.getPositions(walletAddress, {
    symbols: ['SOL-PERP'],
  });

  return positions;
}

AI Agent Integration

Ranger provides an MCP (Model Context Protocol) server for AI agent integration.

Installation (Python)

Clone ranger-agent-kit and follow its README for setup.

MCP Server Tools

The Ranger MCP server exposes these tools:

SOR Tools:

  • sor_get_trade_quote - Get pricing quotes
  • sor_increase_position - Open/increase positions
  • sor_decrease_position - Reduce positions
  • sor_close_position - Close positions

Data API Tools:

  • data_get_positions - Fetch current positions
  • data_get_trade_history - Trading history
  • data_get_liquidations - Liquidation data and signals
  • data_get_funding_rates - Funding rate analytics

Example: Mean Reversion Agent

python
import 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())

Starting the MCP Server

bash
cd ranger-agent-kit/perps-mcp
cp .env.example .env
# Edit .env with your API credentials
python -m ranger_mcp

API Reference

SorApi Class

typescript
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;
}

Configuration

typescript
interface SorSdkConfig {
  apiKey: string;
  sorApiBaseUrl?: string;   // Default: Ranger SOR API
  dataApiBaseUrl?: string;  // Default: Ranger Data API
  solanaRpcUrl?: string;    // Default: Mainnet RPC
}

Request Types

typescript
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';
}

Response Types

typescript
interface TransactionResponse {
  message: string;  // Base64-encoded transaction
  meta?: {
    executed_price?: number;
    executed_size?: number;
    executed_collateral?: number;
    venues_used?: string[];
  };
}

interface PositionsResponse {
  positions: Position[];
}

Supported Markets

Ranger aggregates perpetual markets across:

ProtocolMarkets
DriftSOL, BTC, ETH, and 20+ assets
FlashSOL, BTC, ETH
AdrenaSOL, BTC, ETH
JupiterSOL, BTC, ETH

Error Handling

typescript
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;
  }
}

Best Practices

  1. Always Get Quotes First: Before executing trades, use getOrderMetadata to compare pricing across venues.

  2. Handle Transaction Signing Securely: Never hardcode private keys. Use environment variables or secure key management.

  3. Monitor Positions: Regularly fetch positions to track PnL and liquidation prices.

  4. Use Appropriate Venue: When decreasing/closing, choose the venue where your position exists.

  5. Set Appropriate Collateral: Consider leverage when setting collateral. Higher collateral = lower liquidation risk.

Resources

Skill Structure

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

附带文件

技能加载后,模型会按需读取这些文件。它们仅作为可读文件提供,绝不会被执行。

常见问题

Ranger Finance AI 技能有什么作用?

Ranger Finance SDK,用于在 Solana 上构建永续期货交易应用。它是 Solana 上首个永续合约聚合器,可汇集多个永续合约协议(Drift、Flash、Adrena、Jupiter)的流动性。适用于集成永续合约交易、智能订单路由和仓位管理,或构建 AI 交易智能体。

为什么在 TypingMind 中使用 Ranger Finance?

因为您只需安装一次,就能搭配任何模型使用。Ranger Finance 采用纯 Markdown 格式,而非特定提供商专用的代码,因此同一技能可用于 GPT-5、Claude、Gemini、Grok 或本地模型。您甚至可以在聊天中途切换模型,而不会影响技能的正常使用。TypingMind 使用您自己的 API 密钥,因此您直接向提供商付费,而不是按席位订阅;您的技能和聊天记录也都保留在您自己的存储空间中。

如何在 TypingMind 中安装 Ranger Finance?

在 TypingMind 中打开“插件 → 技能 → 从 GitHub 安装”,然后粘贴 https://github.com/sendaifun/skills/tree/main/skills/ranger-finance。TypingMind 会读取其中的 SKILL.md,打包相关文件,并将其安装为技能,供您在各个聊天中按需启用。

哪些 AI 模型可以使用 Ranger Finance?

您在 TypingMind 中连接的任何模型都可以。AI 技能采用纯 Markdown 指令,而非特定提供商专用的代码,因此 GPT、Claude、Gemini、Grok 和本地模型都能在请求匹配时加载此技能。

Ranger Finance 可以搭配多少个 AI 模型使用?

数量不限。只要模型支持技能,您就可以将它与 Ranger Finance 搭配使用。GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 等模型都可以通过您自己的 API 密钥接入 TypingMind。

Ranger Finance AI 技能免费吗?

是的。sendaifun 已在 GitHub 上根据 Apache-2.0 许可证发布了该技能。您只需向自己的 AI 提供商支付所用 Token 的费用。

什么是 AI 技能?

AI 技能是一组可复用的指令,用于教会 AI 模型完成某项特定任务。它遵循开放的 Agent Skills 格式:包含名称和描述的 SKILL.md 文件,以及模型可能需要的脚本、模板或参考文件。模型仅在您的请求与技能匹配时才会读取这些指令,因此已安装的技能在使用前不会产生任何费用。

AI 技能与插件或 MCP 服务器有何不同?

插件或 MCP 服务器为模型提供可调用的新工具,也就是在某处运行并返回结果的代码。AI 技能则为模型提供知识和流程:如何处理任务、遵循哪些步骤,以及怎样的输出才算优质。技能采用纯 Markdown 格式,因此不需要服务器、API 密钥或运行时环境,并且适用于任何模型。

查看全部

立即创建您自己的 AI 工作区

订阅我们的电子简报,获取新功能和后续赠奖活动的通知 👇