Logo Ranger Finance

Ranger Finance

Tổ chức
sendaifun
ranger-finance

Ranger Finance SDK để xây dựng ứng dụng giao dịch hợp đồng tương lai vĩnh cửu trên Solana. Đây là bộ tổng hợp hợp đồng vĩnh cửu đầu tiên trên Solana — tổng hợp thanh khoản từ nhiều giao thức hợp đồng vĩnh cửu (Drift, Flash, Adrena, Jupiter). Dùng khi tích hợp giao dịch hợp đồng vĩnh cửu, định tuyến lệnh thông minh, quản lý vị thế hoặc xây dựng tác nhân AI giao dịch.

Add to TypingMind

Tổng quan

Nhà phát hànhsendaifun
Kho mãskills
Tên kỹ năngranger-finance
Sao
128
Bản fork
81
Tệp đi kèm
8
Giấy phépApache-2.0
Liên kết
  • Hướng dẫn bằng Markdown

    Tệp SKILL.md được mô hình tải khi cần, nên chỉ tốn token khi có yêu cầu thực sự phù hợp.

  • Dùng được với mọi LLM

    Kỹ năng AI dùng hướng dẫn viết bằng Markdown thay vì mã dành riêng cho một nhà cung cấp, nên dùng được với GPT, Claude, Gemini, Grok hoặc mô hình cục bộ.

  • 8 tệp đi kèm

    Các tập lệnh, mẫu và tài liệu tham khảo mà mô hình có thể đọc khi làm việc. Các tệp chỉ cho phép đọc và không bao giờ được thực thi.

  • Mã nguồn mở

    Được sendaifun công bố trên GitHub. Hãy đọc các tệp nguồn trước khi cài đặt.

Cài đặt

Cài đặt kỹ năng AI Ranger Finance trong TypingMind để dùng với bất kỳ LLM nào, hoặc thêm vào một tác nhân AI khác có thể đọc SKILL.md.

1

Cài đặt trong TypingMind

TypingMind cài đặt kỹ năng trực tiếp từ thư mục GitHub — đọc SKILL.md, đóng gói các tệp tài nguyên và lưu kết quả trên máy.

  1. Mở ứng dụng và vào Plugin → Kỹ năng.
  2. Chọn "Cài đặt từ GitHub".
  3. Dán URL của thư mục kỹ năng được hiển thị bên dưới rồi xác nhận.
    https://github.com/sendaifun/skills/tree/main/skills/ranger-finance
  4. Bật kỹ năng trong từng cuộc trò chuyện mà bạn muốn sử dụng kỹ năng đó.
Plugin → Kỹ năng → Thêm kỹ năng → Từ URL GitHub, sau đó dán URL thư mục và nhấn Tiếp tục.
2

Cài đặt trong tác nhân AI khác

Bất kỳ tác nhân AI nào đọc được định dạng Agent Skills đều có thể dùng kỹ năng này — hãy sao chép thư mục vào thư mục kỹ năng của tác nhân AI đó.

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
Khởi động lại Claude Code sau khi sao chép để ứng dụng nhận kỹ năng mới.

Sử dụng trong TypingMind

Bật Ranger Finance trong bất kỳ cuộc trò chuyện nào trên TypingMind, mô hình sẽ tự xử lý phần còn lại. Tên và mô tả của kỹ năng nằm trong prompt hệ thống. Ngay khi có yêu cầu phù hợp, mô hình tự tải toàn bộ hướng dẫn — bạn không cần gọi thủ công và kỹ năng không tốn token cho đến khi thực sự được dùng.

Mô hình tự nạp Ranger Finance ngay khi có yêu cầu phù hợp.

Dùng được với mọi mô hình AI

Kỹ năng AI là các hướng dẫn Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên bạn có thể dùng Ranger Finance với cả những mô hình khác ngoài mô hình ban đầu. Chỉ cần cài đặt một lần trong TypingMind rồi dùng với GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama hoặc mô hình cục bộ do bạn tự chạy — tất cả đều dùng khóa API của riêng bạn.

  • Chỉ tải khi cần

    Prompt hệ thống chỉ chứa tên và mô tả. Hướng dẫn được tải khi có yêu cầu phù hợp đầu tiên, nên khi kỹ năng chưa được dùng, bạn không tốn token cho phần hướng dẫn.

  • Đổi mô hình ngay trong cuộc trò chuyện

    Vì kỹ năng là hướng dẫn chứ không phải mã, việc đổi mô hình không làm kỹ năng ngừng hoạt động — mô hình tiếp theo vẫn đọc cùng tệp SKILL.md.

Hướng dẫn của kỹ năng

Đây là nội dung SKILL.md mà mô hình tải. Hãy đọc trước khi cài đặt — kỹ năng là những hướng dẫn mà mô hình của bạn sẽ làm theo.

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

Tệp đi kèm

Khi kỹ năng đã được tải, mô hình có thể đọc các tệp này nếu cần. Các tệp này chỉ dùng để đọc và không bao giờ được thực thi.

Câu hỏi thường gặp

Kỹ năng AI Ranger Finance làm được gì?

Ranger Finance SDK để xây dựng ứng dụng giao dịch hợp đồng tương lai vĩnh cửu trên Solana. Đây là bộ tổng hợp hợp đồng vĩnh cửu đầu tiên trên Solana — tổng hợp thanh khoản từ nhiều giao thức hợp đồng vĩnh cửu (Drift, Flash, Adrena, Jupiter). Dùng khi tích hợp giao dịch hợp đồng vĩnh cửu, định tuyến lệnh thông minh, quản lý vị thế hoặc xây dựng tác nhân AI giao dịch.

Vì sao nên dùng Ranger Finance trên TypingMind?

Vì bạn chỉ cần cài một lần rồi dùng với bất kỳ mô hình nào. Ranger Finance là nội dung Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên cùng một kỹ năng có thể chạy trên GPT-5, Claude, Gemini, Grok hoặc mô hình trên thiết bị — và bạn có thể đổi mô hình ngay trong cuộc trò chuyện mà kỹ năng vẫn hoạt động. TypingMind dùng khóa API riêng của bạn, nên bạn thanh toán trực tiếp cho nhà cung cấp thay vì trả phí thuê bao theo suất người dùng, đồng thời kỹ năng và các cuộc trò chuyện vẫn nằm trong bộ lưu trữ của bạn.

Làm thế nào để cài Ranger Finance trong TypingMind?

Mở Plugin → Kỹ năng → Cài đặt từ GitHub trong TypingMind rồi dán https://github.com/sendaifun/skills/tree/main/skills/ranger-finance. TypingMind đọc tệp SKILL.md, đóng gói các tệp đi kèm rồi cài đặt cả gói dưới dạng một kỹ năng mà bạn có thể bật cho từng cuộc trò chuyện.

Những mô hình AI nào có thể dùng Ranger Finance?

Bất kỳ mô hình nào bạn kết nối trong TypingMind. Kỹ năng AI là các hướng dẫn bằng Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên GPT, Claude, Gemini, Grok và các mô hình chạy trên thiết bị đều có thể tải kỹ năng này khi có yêu cầu phù hợp.

Có thể dùng Ranger Finance với bao nhiêu mô hình AI?

Bao nhiêu cũng được. Miễn là mô hình hỗ trợ kỹ năng, bạn có thể dùng Ranger Finance với mô hình đó — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama và nhiều mô hình khác — tất cả đều trên TypingMind với khóa API riêng của bạn.

Kỹ năng AI Ranger Finance có miễn phí không?

Có. Kỹ năng này được sendaifun phát hành trên GitHub theo giấy phép Apache-2.0. Bạn chỉ trả tiền cho nhà cung cấp AI của mình theo số token đã dùng.

Kỹ năng AI là gì?

Kỹ năng AI là một gói hướng dẫn có thể tái sử dụng, chỉ cho mô hình AI cách thực hiện một tác vụ cụ thể. Kỹ năng tuân theo định dạng mở Agent Skills: một tệp SKILL.md chứa tên và mô tả, cùng các tập lệnh, mẫu hoặc tệp tham khảo mà mô hình có thể cần. Mô hình chỉ đọc hướng dẫn khi yêu cầu của bạn phù hợp với kỹ năng, nên kỹ năng đã cài đặt không phát sinh chi phí cho đến khi được sử dụng.

Kỹ năng AI khác gì với plugin hoặc máy chủ MCP?

Plugin hoặc máy chủ MCP cung cấp các công cụ mới mà mô hình có thể gọi. Khi mô hình gọi một công cụ, mã của công cụ đó chạy ở đâu đó và trả về kết quả. Còn kỹ năng AI cung cấp kiến thức và quy trình: cách tiếp cận tác vụ, các bước cần thực hiện và những tiêu chí mà kết quả cần đáp ứng. Kỹ năng chỉ là nội dung Markdown, nên không cần máy chủ, khóa API hay môi trường thực thi và hoạt động với mọi mô hình.

Xem tất cả

Tạo ngay không gian làm việc AI riêng

Đăng ký bản tin của chúng tôi để nhận thông báo về tính năng mới và các đợt tặng quà sắp tới 👇