Skip to content

svim-labs/ai-stock-trader

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 

Repository files navigation

AI Stock Trading Agent

An AI-powered stock trading agent that uses the Model Context Protocol (MCP) to interact with trading systems through natural language. The agent supports multiple LLM providers (OpenAI, Anthropic, Google Gemini, etc.) and connects to MCP servers via SSE transport for seamless trading operations.

Features

  • 🤖 Multi-LLM Support: Works with OpenAI, Anthropic Claude, Google Gemini, and other providers via LiteLLM
  • 🔌 MCP Integration: Connects to MCP servers via SSE transport for tool discovery and execution
  • 💬 Natural Language Interface: Interact with trading tools using plain English
  • 🎨 Beautiful CLI: Rich terminal UI with markdown rendering and formatted output
  • 🔄 Multi-turn Conversations: Maintains context across multiple tool calls
  • 🔐 Wallet Integration: Automatic wallet address derivation and transaction signing
  • Rate Limiting: Automatic retry and backoff for rate-limited API calls
  • 🔗 Multi-chain Support: Supports Ethereum, Base, Arbitrum, BNB Chain, and Solana

Architecture

User → CLI → LiteLLM → LLM Provider (OpenAI/Anthropic/Gemini)
                ↓
            Tool Calls
                ↓
         MCP Server (mcp.sivm.io:8080/sse)
                ↓
            Tool Results
                ↓
         Transaction Signing (if needed)
                ↓
         Final Response → User

Prerequisites

  • Python 3.11 or higher
  • At least one LLM API key:
    • OpenAI API key (for GPT models)
    • Anthropic API key (for Claude models)
    • Google Gemini API key (for Gemini models)

Installation

  1. Clone or navigate to the project directory

  2. Install dependencies

    pip install -e .

    Or using uv (recommended):

    uv pip install -e .
  3. Configure environment variables

    Copy the example environment file:

    cp .env.example .env

    Edit .env and add at least one API key:

    # Pick at least one LLM provider
    OPENAI_API_KEY=sk-...
    # OR
    ANTHROPIC_API_KEY=sk-ant-...
    # OR
    GEMINI_API_KEY=...
    
    # Model to use (litellm format)
    LITELLM_MODEL=openai/gpt-4o
    
    # MCP Server URL (default shown)
    MCP_SSE_URL=http://mcp.sivm.io:8080/sse
    
    # Wallet Private Key (optional, but required for trading)
    # WARNING: Keep this secure! Never commit to version control.
    WALLET_PRIVATE_KEY=your-private-key-here
    
    # Default Blockchain (optional)
    # Supported: ethereum, base, arbitrum, bnb, solana
    DEFAULT_BLOCKCHAIN=ethereum

Usage

Important: First, make sure the package is installed:

pip install -e .

Then run the agent using one of these methods:

Method 1: Using the installed script (recommended)

stock-trader

Method 2: Using Python module syntax

python -m src.main

Method 3: Direct Python execution

python src/main.py

Note: If you get "No module named src.main" error, make sure you:

  1. Have installed the package: pip install -e .
  2. Are running from the project root directory
  3. Have activated your virtual environment (if using one)

Example Queries

Once the agent is running, you can interact with it using natural language:

You: I want to buy 1 MSFT with 100 USDC
Agent: [Processes request, calls trading tools, signs transaction, returns result]

You: Show me my portfolio
Agent: [Retrieves and displays portfolio information]

You: What's the current price of AAPL?
Agent: [Fetches and displays current price]

Available Commands

  • /help - Show help message
  • /tools - List all available trading tools from MCP server
  • /model <name> - Change LLM model (e.g., /model anthropic/claude-sonnet-4-20250514)
  • /reset - Reset conversation history
  • /clear - Clear screen
  • /quit or /exit - Exit the application

Supported Models

The agent supports any model that LiteLLM supports. Common examples:

OpenAI

  • openai/gpt-4o
  • openai/gpt-4-turbo
  • openai/gpt-3.5-turbo

Anthropic

  • anthropic/claude-sonnet-4-20250514
  • anthropic/claude-3-5-sonnet-20241022
  • anthropic/claude-3-opus-20240229

Google Gemini

  • google/gemini-1.5-flash (recommended - uses Google AI Studio API)
  • google/gemini-1.5-pro
  • google/gemini-2.0-flash-exp

Note: Use google/ prefix instead of gemini/ to use Google AI Studio API. The gemini/ prefix uses Vertex AI which has compatibility issues with litellm.

Configuration

Environment Variables

Variable Description Required
OPENAI_API_KEY OpenAI API key Yes (if using OpenAI models)
ANTHROPIC_API_KEY Anthropic API key Yes (if using Anthropic models)
GEMINI_API_KEY Google Gemini API key Yes (if using Gemini models)
LITELLM_MODEL Model to use (litellm format) No (default: openai/gpt-4o)
MCP_SSE_URL MCP server SSE endpoint URL No (default: http://mcp.sivm.io:8080/sse)
WALLET_PRIVATE_KEY Wallet private key for trading operations No (optional, but required for trading)
DEFAULT_BLOCKCHAIN Default blockchain for trading (ethereum, base, arbitrum, bnb, solana) No (default: ethereum)

Wallet Configuration

The agent can automatically use a configured wallet for trading operations:

  1. Add your wallet private key to .env:

    WALLET_PRIVATE_KEY=your-private-key-here
  2. Automatic features:

    • Wallet address derivation (Ethereum and Solana)
    • Automatic wallet address injection in trading tool calls
    • Transaction signing for multiple chains
  3. Supported chains:

    • Ethereum (chainId: 1)
    • Base (chainId: 8453)
    • Arbitrum (chainId: 42161)
    • BNB Chain (chainId: 56)
    • Solana

Transaction Signing

The agent includes a built-in transaction signing tool that automatically signs transactions returned by create_order:

  • Automatic signing: When create_order returns a transaction, the agent automatically signs it
  • Multi-chain support: Supports Ethereum, Base, Arbitrum, BNB Chain, and Solana
  • EIP-1559 support: Handles both legacy and EIP-1559 transaction formats
  • Auto-fill missing fields: Automatically fills missing gas, gasPrice, and nonce fields (with warnings)

How It Works

  1. Connection: The agent connects to the MCP server via SSE transport
  2. Tool Discovery: It discovers all available trading tools from the MCP server
  3. Query Processing: When you submit a query:
    • The query is sent to the LLM along with tool definitions
    • The LLM decides which tools (if any) to call
    • Tools are executed via the MCP server
    • If a transaction is returned, it's automatically signed
    • Results are sent back to the LLM
    • The LLM generates a final response
  4. Multi-turn: The agent maintains conversation context, allowing for follow-up questions

Rate Limiting

The agent includes automatic rate limiting with:

  • Automatic retry: Retries up to 3 times on rate limit errors
  • Smart waiting: Parses wait time from error messages (e.g., "try again in 18.288s")
  • Exponential backoff: Uses exponential backoff if no wait time is specified
  • User-friendly errors: Provides clear error messages when rate limits are exceeded

Project Structure

ai-stock-trader/
├── src/
│   ├── __init__.py
│   ├── main.py          # CLI entry point
│   ├── agent.py         # Core agent logic (LLM + tool calling)
│   ├── mcp_client.py    # MCP SSE client
│   ├── config.py        # Configuration management
│   ├── wallet_utils.py  # Wallet address derivation and transaction signing
│   └── rate_limiter.py  # Rate limiting and retry logic
├── .env.example         # Environment variable template
├── pyproject.toml       # Project dependencies
└── README.md            # This file

Troubleshooting

Connection Issues

If you see "Failed to connect to MCP server":

  • Verify the MCP server URL is correct in .env
  • Check that the MCP server is accessible from your network
  • Ensure the server supports SSE transport

API Key Errors

If you see API key errors:

  • Verify your API key is correct in .env
  • Ensure the API key matches the model provider you're using
  • Check that your API key has sufficient credits/quota

Rate Limit Errors

If you see rate limit errors:

  • The agent will automatically retry with exponential backoff
  • Check your API usage limits
  • Consider upgrading your API plan or using a different model

Transaction Signing Errors

If transaction signing fails:

  • Ensure eth-account is installed: pip install eth-account
  • For Solana, ensure solders is installed: pip install solders
  • Check that the transaction object from create_order includes all required fields
  • Verify your wallet private key is correct

Tool Execution Errors

If tools fail to execute:

  • Check the MCP server logs for errors
  • Verify tool arguments are correct
  • Ensure you have necessary permissions for the trading operations

Development

Running Tests

# Add test framework and run tests
pytest

Adding New Features

  1. MCP tools are discovered automatically from the server
  2. To add new LLM providers, ensure LiteLLM supports them and add the API key to .env
  3. To customize the agent behavior, modify src/agent.py
  4. To add new blockchain support, extend src/wallet_utils.py

Security Notes

  • Never commit .env file: It contains sensitive API keys and private keys
  • Keep private keys secure: Wallet private keys give full access to your funds
  • Use environment variables: Never hardcode credentials in source code
  • Review transactions: Always review transactions before signing

License

MIT License

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Acknowledgments

About

This is an example of AI agent using Svim Stock MCP

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages