Corsaro Documentation

Comprehensive guides and tutorials to help you build AI-powered trading solutions with Corsaro.

Advanced Strategies

Create custom trading strategies with powerful pattern recognition and technical indicators.

AI-Powered

Intelligent trading assistant that learns from your trades and adapts to market conditions.

Helius Integration

Built-in support for Helius API to handle blockchain transactions efficiently.

Installation

Corsaro can be installed via npm or yarn. It requires Node.js version 16 or later.

Terminal
bash
# Install via npm
npm install corsaro

# Or using yarn
yarn add corsaro

Dependencies

Corsaro has peer dependencies on @helius-labs/helius and @solana/web3.js for blockchain interactions.

Quick Start

Get started quickly with a basic trading bot that uses a simple moving average crossover strategy.

src/index.ts
typescript
import { Corsaro, Networks } from 'corsaro';
import { Connection } from '@helius-labs/helius';

// Initialize Helius connection
const connection = new Connection(
  "https://mainnet.helius-rpc.com/?api-key=YOUR_API_KEY"
);

// Initialize Corsaro with Helius connection
const corsaro = new Corsaro({
  network: Networks.MAINNET,
  connection,
  walletPrivateKey: process.env.WALLET_PRIVATE_KEY,
});

// Create a simple trading strategy
const strategy = corsaro.createStrategy({
  name: 'SMA Crossover',
  params: {
    fastPeriod: 10,
    slowPeriod: 30,
  },
  execute: async (data) => {
    // Your strategy logic here
    const { fastMA, slowMA } = data;
    
    if (fastMA > slowMA) {
      return corsaro.signals.BUY;
    } else if (fastMA < slowMA) {
      return corsaro.signals.SELL;
    }
    
    return corsaro.signals.HOLD;
  }
});

// Start the trading agent
corsaro.start();

Initialize Corsaro

Create a new Corsaro instance with your Helius connection and wallet settings.

Define Strategy

Create a trading strategy with parameters and execution logic.

Execute Trades

Corsaro automatically executes trades based on your strategy signals.

Monitor Performance

Track your strategy's performance and adjust parameters as needed.

Configuration

Corsaro is highly configurable to suit different trading styles and requirements.

OptionTypeDescriptionDefault
networkstringNetwork to connect to (mainnet, devnet)mainnet
connectionConnectionHelius Connection instance-
walletPrivateKeystringPrivate key for transactions-
debugbooleanEnable debug loggingfalse
backtestbooleanRun in backtest modefalse

Trading Strategies

Build custom trading strategies by extending the Strategy class or use the simplified function-based approach.

src/custom-strategy.ts
typescript
// Creating a custom trading strategy
import { Corsaro, Strategy } from 'corsaro';

class CustomStrategy extends Strategy {
  constructor(params) {
    super('Custom Strategy', params);
    this.requiredData = ['ohlcv', 'volume'];
  }
  
  async initialize() {
    // Set up indicators or load models
    this.rsi = this.indicators.rsi(this.params.rsiPeriod);
    this.ema = this.indicators.ema(this.params.emaPeriod);
    
    // Optional: Load ML model
    await this.loadModel('/path/to/model');
  }
  
  async execute(data) {
    // Your strategy logic here
    const { close, volume } = data;
    const rsiValue = this.rsi.calculate(close);
    const emaValue = this.ema.calculate(close);
    
    if (rsiValue < 30 && close > emaValue) {
      return this.signals.BUY;
    } else if (rsiValue > 70 && close < emaValue) {
      return this.signals.SELL;
    }
    
    return this.signals.HOLD;
  }
}

// Register your custom strategy
corsaro.registerStrategy(new CustomStrategy({
  rsiPeriod: 14,
  emaPeriod: 21,
}));

Strategy Lifecycle

  1. 1initialize() is called once when the strategy is registered
  2. 2execute() is called on each data update
  3. 3Return a signal (BUY, SELL, HOLD) from execute()
  4. 4Corsaro handles the execution of trades based on signals

Helius Integration

Corsaro uses Helius for fast, reliable blockchain transactions and data queries.

src/helius-trading.ts
typescript
// Trading with Helius
import { Corsaro } from 'corsaro';
import { Connection, TransactionBuilder } from '@helius-labs/helius';
import { PublicKey } from '@solana/web3.js';

// Initialize with your Helius API key
const connection = new Connection(
  "https://mainnet.helius-rpc.com/?api-key=YOUR_API_KEY"
);

const corsaro = new Corsaro({
  network: 'mainnet',
  connection,
  walletPrivateKey: process.env.WALLET_PRIVATE_KEY,
});

// Example: Creating a trade order using Helius
async function placeTrade(tokenAddress, amount, side) {
  const tokenMint = new PublicKey(tokenAddress);
  
  const txBuilder = new TransactionBuilder(connection);
  
  if (side === 'buy') {
    // Create a buy order for the token
    await txBuilder.addInstruction({
      swapExactSOLForTokens: {
        amountIn: amount,
        tokenMint,
      }
    });
  } else {
    // Create a sell order for the token
    await txBuilder.addInstruction({
      swapExactTokensForSOL: {
        amountIn: amount,
        tokenMint,
      }
    });
  }
  
  // Sign and send the transaction
  const signature = await txBuilder.buildAndExecute();
  
  console.log(`Trade executed: ${signature}`);
  return signature;
}

// Use in your Corsaro strategy
corsaro.createStrategy({
  name: 'Helius Trading Strategy',
  params: {
    tokenAddress: 'So11111111111111111111111111111111111111112',
    tradeAmount: 0.1, // SOL
  },
  execute: async (data) => {
    const { signal, params } = data;
    
    if (signal === corsaro.signals.BUY) {
      await placeTrade(params.tokenAddress, params.tradeAmount, 'buy');
    } else if (signal === corsaro.signals.SELL) {
      await placeTrade(params.tokenAddress, params.tradeAmount, 'sell');
    }
  }
});

Setting Up Helius

  1. 1Sign up for a Helius API key at helius.xyz
  2. 2Install Helius SDK: npm install @helius-labs/helius
  3. 3Create a connection with your API key
  4. 4Pass the connection to Corsaro during initialization

AI Trading Assistant

Corsaro includes an advanced AI trading assistant that can learn from your trading patterns and help optimize your strategies.

src/ai-assistant.ts
typescript
// Using Corsaro AI Assistant
import { Corsaro } from 'corsaro';

const corsaro = new Corsaro({
  // Your configuration here
});

// Enable AI Trading Assistant
corsaro.enableAI({
  // Customize AI behavior
  riskTolerance: 'medium',
  tradingStyle: 'momentum',
  maxDrawdown: 0.15, // 15%
  
  // Learn from your manual trades
  learnFromHistory: true,
  
  // Rules
  rules: [
    'Never trade more than 5% of portfolio value',
    'Avoid trading during high volatility',
    'Always use stop loss at 2% below entry'
  ]
});

// The AI assistant will analyze your trading patterns
// and provide suggestions or execute trades

Learning Mode

The AI analyzes your manual trades to understand your trading style and preferences.

Advisory Mode

Receive suggestions and alerts based on market conditions and your trading rules.

Strategy Enhancement

AI can suggest optimizations to your existing strategies based on performance data.

Autonomous Trading

Enable the AI to execute trades automatically based on learned patterns (Corsaro+ only).

API Reference

Corsaro Class

new Corsaro(options)

constructor

Creates a new Corsaro trading agent instance.

Parameters:

options
object
Configuration options for the trading agent
Example:
const corsaro = new Corsaro({ network: 'mainnet', connection: new Connection('https://mainnet.helius-rpc.com/?api-key=YOUR_API_KEY'), walletPrivateKey: process.env.WALLET_PRIVATE_KEY, });

corsaro.createStrategy(options)

method

Creates a new trading strategy from configuration options.

Parameters:

options
object
Strategy configuration including name, parameters, and execution logic
Example:
const strategy = corsaro.createStrategy({ name: 'SMA Crossover', params: { fastPeriod: 10, slowPeriod: 30 }, execute: async (data) => { /* strategy logic */ } });

corsaro.registerStrategy(strategy)

method

Registers a custom Strategy instance with Corsaro.

Parameters:

strategy
Strategy
A Strategy class instance
Example:
corsaro.registerStrategy(new CustomStrategy({ rsiPeriod: 14, emaPeriod: 21 }));

corsaro.start()

method

Starts the trading agent, which begins executing strategies and placing trades.

Example:
corsaro.start();

corsaro.stop()

method

Stops the trading agent, canceling any pending operations.

Example:
corsaro.stop();

corsaro.enableAI(options)

method

Enables the AI trading assistant with the specified options.

Parameters:

options
object
AI configuration including risk tolerance, trading style, and rules
Example:
corsaro.enableAI({ riskTolerance: 'medium', tradingStyle: 'momentum', rules: ['Never trade more than 5% of portfolio'] });

Strategy Class

new Strategy(name, params)

constructor

Creates a new Strategy instance that can be extended for custom strategies.

Parameters:

name
string
Name of the strategy
params
object
Strategy parameters
Example:
class MyStrategy extends Strategy { constructor(params) { super('My Custom Strategy', params); } }

strategy.initialize()

method

Called once when the strategy is registered. Used to set up indicators or load models.

Example:
async initialize() { this.rsi = this.indicators.rsi(this.params.rsiPeriod); await this.loadModel('/path/to/model'); }

strategy.execute(data)

method

Called for each data update to generate trading signals.

Parameters:

data
object
Market data object with price, volume, and other indicators
Example:
async execute(data) { const rsiValue = this.rsi.calculate(data.close); if (rsiValue < 30) return this.signals.BUY; if (rsiValue > 70) return this.signals.SELL; return this.signals.HOLD; }

strategy.signals

property

Trading signal constants to return from execute().

Example:
// Available signals this.signals.BUY this.signals.SELL this.signals.HOLD

strategy.indicators

property

Built-in technical indicators for strategy development.

Example:
// Available indicators this.indicators.sma(period) this.indicators.ema(period) this.indicators.rsi(period) this.indicators.macd(fastPeriod, slowPeriod, signalPeriod) // Many more available...