Skip to content

Peterksharma/kalshiStream

Repository files navigation

Kalshi Trading Bot

A sophisticated automated trading bot for Kalshi, featuring real-time market data via WebSocket, comprehensive REST API integration, and multiple trading strategies.

Features

  • Real-time Market Data: WebSocket connection for live market updates across all available channels
  • Complete API Coverage: Full Kalshi REST API integration with all endpoints
  • Multiple Trading Strategies: Built-in mean reversion strategy with extensible framework
  • Advanced Risk Management: Configurable position sizing, stop-loss, and take-profit
  • Comprehensive Logging: Winston-based logging with file rotation and configurable levels
  • Health Monitoring: Automatic health checks and performance reporting
  • CLI Interface: Interactive command-line interface for bot control
  • Graceful Shutdown: Proper cleanup and position management on exit
  • Configurable WebSocket: Auto-subscription, reconnection, and channel management

Prerequisites

  • Node.js 18+
  • Kalshi account with API access
  • RSA private key for API authentication

Installation

  1. Clone the repository:
git clone <repository-url>
cd kalshi-trading-bot
  1. Install dependencies:
npm install
  1. Configure your environment:
cp env.example .env
  1. Edit .env with your configuration:
# Kalshi API Configuration
KALSHI_API_KEY_ID=your_api_key_id_here
KALSHI_PRIVATE_KEY_PATH=./testKey.txt
KALSHI_BASE_URL=https://demo-api.kalshi.co
KALSHI_WS_URL=wss://demo-stream.kalshi.co

# Trading Bot Configuration
TRADING_ENABLED=false
MAX_POSITION_SIZE=100
RISK_PERCENTAGE=2
STOP_LOSS_PERCENTAGE=5
TAKE_PROFIT_PERCENTAGE=10

# WebSocket Configuration
WS_AUTO_SUBSCRIBE=true
WS_DEFAULT_CHANNELS=market_ticker,orderbook_updates,public_trades

# Logging Configuration
LOG_LEVEL=info
LOG_FILE=./logs/trading-bot.log

Configuration

API Keys Setup

  1. Generate API Key:

    • Log into your Kalshi account
    • Navigate to Account Settings → Profile
    • Click "Create New API Key"
    • Save the private key and key ID
  2. Configure Bot:

    • Set KALSHI_API_KEY_ID to your key ID
    • Ensure KALSHI_PRIVATE_KEY_PATH points to your private key file
    • Use demo URLs for testing, production URLs for live trading

WebSocket Channels

The bot supports all available Kalshi WebSocket channels:

  • Market Data: market_ticker, orderbook_updates, public_trades, market_candlesticks
  • User Data: user_fills, market_positions, order_updates
  • System: market_lifecycle, event_lifecycle, exchange_status
  • Specialized: multivariate_lookups, structured_targets

REST API Endpoints

Complete coverage of all Kalshi API endpoints:

  • API Keys: Create, manage, and delete API keys
  • Communications: Quotes, RFQs, and communications
  • Market Data: Events, markets, trades, order books, candlesticks
  • Exchange Info: Announcements, schedule, status
  • Portfolio: Balance, positions, orders, fills, settlements
  • Collections: Multivariate events and structured targets

Trading Parameters

  • TRADING_ENABLED: Set to true to enable actual trading
  • MAX_POSITION_SIZE: Maximum contracts per position
  • RISK_PERCENTAGE: Maximum risk per trade as percentage of portfolio
  • STOP_LOSS_PERCENTAGE: Automatic stop-loss percentage
  • TAKE_PROFIT_PERCENTAGE: Automatic take-profit percentage

Usage

Starting the Bot

# Start with trading enabled
npm start

# Start in development mode with auto-restart
npm run dev

CLI Commands

Once the bot is running, use these commands:

  • status - Show application and trading bot status
  • start - Start trading (if not already running)
  • stop - Stop trading
  • strategies - Show strategy performance metrics
  • help - Show available commands
  • quit - Exit the application

Example Session

$ npm start

=== Kalshi Trading Bot CLI ===
Type "help" for available commands
Type "quit" to exit

> status

=== Application Status ===
PID: 12345
Uptime: 5 minutes
Memory: 45 MB
Trading Bot Running: true
WebSocket Connected: true
Active Strategies: 1/1
WebSocket Subscriptions: 3

> strategies

=== Strategy Information ===

MEAN REVERSION:
  Active: true
  Total Trades: 12
  Win Rate: 75.00%
  PnL: 150.50
  Positions: 2
  Open Orders: 1

> quit
Exiting...

Trading Strategies

Mean Reversion Strategy

The built-in mean reversion strategy:

  • Entry Logic: Enters positions when price deviates significantly from moving averages
  • Exit Logic: Exits when price returns to mean, hits stop-loss, or reaches take-profit
  • Risk Management: Configurable position sizing and risk limits
  • Parameters:
    • lookbackPeriod: Number of periods for moving average calculation
    • deviationThreshold: Standard deviations for entry signals
    • positionSize: Base position size in contracts
    • maxPositions: Maximum concurrent positions

Adding Custom Strategies

Extend the BaseStrategy class to create custom strategies:

import BaseStrategy from './strategies/baseStrategy.js';

class CustomStrategy extends BaseStrategy {
  constructor(api, websocket, options = {}) {
    super('Custom Strategy', api, websocket);
    // Initialize strategy-specific parameters
  }

  async executeStrategy() {
    // Implement your trading logic
  }

  onMarketUpdate(message) {
    // Handle market data updates
  }
}

Architecture

src/
├── api/           # REST API client with all endpoints
├── websocket/     # WebSocket client for real-time data
├── strategies/    # Trading strategies (BaseStrategy + MeanReversion)
├── utils/         # Authentication, logging utilities
├── config/        # Environment configuration management
├── tradingBot.js  # Main bot orchestrator
└── index.js       # Application entry point with CLI

Key Components

  • KalshiApi: Handles all API calls with proper RSA signature authentication
  • KalshiWebSocket: Manages real-time connections with auto-reconnection and channel management
  • BaseStrategy: Abstract base class for all trading strategies
  • MeanReversionStrategy: Built-in strategy using moving averages and volatility
  • TradingBot: Main orchestrator managing strategies and connections
  • CLI: Interactive commands for bot control

WebSocket Integration

Channel Management

// Subscribe to specific channels
bot.subscribeToChannel('market_ticker', { market_id: 'MARKET_ID' });
bot.subscribeToChannel('orderbook_updates', { market_id: 'MARKET_ID' });

// Unsubscribe from channels
bot.unsubscribeFromChannel('market_ticker');

// Get WebSocket information
const wsInfo = bot.getWebSocketInfo();
console.log('Available channels:', wsInfo.availableChannels);
console.log('Active subscriptions:', wsInfo.subscriptions);

Message Handling

The bot automatically handles all message types:

  • Market Data: Ticker updates, orderbook changes, trade notifications
  • User Data: Fill updates, position changes, order status updates
  • System Events: Market lifecycle, exchange status, error messages

Logging

The bot uses Winston for comprehensive logging:

  • Console Output: Colored, formatted logs for development
  • File Logs: Rotating log files in ./logs/ directory
  • Error Logs: Separate error log file for debugging
  • API Logs: Request/response logging with timing
  • Configurable Levels: Set log verbosity via LOG_LEVEL

Log files are automatically rotated when they reach the configured size limit.

Risk Management

Built-in Protections

  • Position Limits: Maximum position size per market
  • Portfolio Risk: Percentage-based risk per trade
  • Stop-Loss: Automatic position closure at loss threshold
  • Take-Profit: Automatic position closure at profit target
  • Order Validation: Pre-trade risk checks
  • WebSocket Health: Automatic reconnection and health monitoring

Best Practices

  1. Start with Demo: Test thoroughly on demo environment
  2. Small Positions: Begin with small position sizes
  3. Monitor Performance: Regular review of strategy performance
  4. Set Limits: Use conservative risk parameters initially
  5. Backup Plans: Have manual override procedures ready
  6. Health Monitoring: Monitor WebSocket connection and API health

Advanced Configuration

WebSocket Settings

# Connection behavior
WS_RECONNECT_ATTEMPTS=5
WS_RECONNECT_DELAY=1000
WS_HEARTBEAT_INTERVAL=30000
WS_CONNECTION_TIMEOUT=10000

# Auto-subscription
WS_AUTO_SUBSCRIBE=true
WS_DEFAULT_CHANNELS=market_ticker,orderbook_updates,public_trades

Strategy Parameters

# Mean Reversion Strategy
MR_LOOKBACK_PERIOD=20
MR_DEVIATION_THRESHOLD=2.0
MR_POSITION_SIZE=10
MR_MAX_POSITIONS=5
MR_STOP_LOSS=0.05
MR_TAKE_PROFIT=0.10

Monitoring Configuration

# Health checks and reporting
HEALTH_CHECK_INTERVAL=60000
PERFORMANCE_REPORT_INTERVAL=300000
METRICS_RETENTION=86400000

Development

Project Structure

├── package.json           # Dependencies and scripts
├── env.example           # Environment configuration template
├── examples/             # Advanced configuration examples
├── src/                  # Source code
│   ├── config/          # Configuration management
│   ├── utils/           # Utilities and helpers
│   ├── api/             # API client with all endpoints
│   ├── websocket/       # WebSocket client with channel management
│   ├── strategies/      # Trading strategies
│   ├── tradingBot.js    # Main bot class
│   └── index.js         # Application entry point
├── logs/                 # Log files (auto-created)
└── README.md            # This file

Adding Dependencies

npm install <package-name>

Running Tests

npm test

Code Style

  • Use ES6+ features (import/export, async/await)
  • Follow JSDoc comment standards
  • Maintain consistent error handling patterns
  • Use descriptive variable and function names

Troubleshooting

Common Issues

  1. API Authentication Failed

    • Verify API key ID and private key path
    • Ensure private key file is readable
    • Check API key permissions
  2. WebSocket Connection Issues

    • Verify WebSocket URL configuration
    • Check network connectivity
    • Review firewall settings
    • Check reconnection settings
  3. Strategy Not Trading

    • Check TRADING_ENABLED setting
    • Verify strategy parameters
    • Review log files for errors
    • Check WebSocket subscriptions
  4. Performance Issues

    • Monitor memory usage
    • Check log rotation settings
    • Review strategy execution frequency
    • Verify WebSocket channel subscriptions

Debug Mode

Set LOG_LEVEL=debug in your .env file for detailed logging.

Support

For issues and questions:

  1. Check the logs in ./logs/ directory
  2. Review configuration settings
  3. Test with demo environment first
  4. Check Kalshi API documentation
  5. Verify WebSocket channel configurations

License

This project is licensed under the ISC License.

Disclaimer

This software is for educational and informational purposes. Trading involves substantial risk of loss and is not suitable for all investors. Past performance does not guarantee future results. Always test thoroughly in a demo environment before using with real funds.

Contributing

Contributions are welcome! Please:

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests if applicable
  5. Submit a pull request

Changelog

v1.1.0

  • Complete WebSocket channel support
  • Full REST API endpoint coverage
  • Enhanced configuration management
  • Advanced WebSocket message handling
  • Improved health monitoring
  • Strategy-specific configuration options

v1.0.0

  • Initial release
  • Mean reversion trading strategy
  • WebSocket and REST API integration
  • Comprehensive logging and monitoring
  • CLI interface
  • Risk management framework

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors