A sophisticated automated trading bot for Kalshi, featuring real-time market data via WebSocket, comprehensive REST API integration, and multiple trading strategies.
- 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
- Node.js 18+
- Kalshi account with API access
- RSA private key for API authentication
- Clone the repository:
git clone <repository-url>
cd kalshi-trading-bot- Install dependencies:
npm install- Configure your environment:
cp env.example .env- Edit
.envwith 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-
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
-
Configure Bot:
- Set
KALSHI_API_KEY_IDto your key ID - Ensure
KALSHI_PRIVATE_KEY_PATHpoints to your private key file - Use demo URLs for testing, production URLs for live trading
- Set
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
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_ENABLED: Set to
trueto 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
# Start with trading enabled
npm start
# Start in development mode with auto-restart
npm run devOnce the bot is running, use these commands:
status- Show application and trading bot statusstart- Start trading (if not already running)stop- Stop tradingstrategies- Show strategy performance metricshelp- Show available commandsquit- Exit the application
$ 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...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 calculationdeviationThreshold: Standard deviations for entry signalspositionSize: Base position size in contractsmaxPositions: Maximum concurrent positions
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
}
}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
- 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
// 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);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
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.
- 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
- Start with Demo: Test thoroughly on demo environment
- Small Positions: Begin with small position sizes
- Monitor Performance: Regular review of strategy performance
- Set Limits: Use conservative risk parameters initially
- Backup Plans: Have manual override procedures ready
- Health Monitoring: Monitor WebSocket connection and API health
# 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# 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# Health checks and reporting
HEALTH_CHECK_INTERVAL=60000
PERFORMANCE_REPORT_INTERVAL=300000
METRICS_RETENTION=86400000├── 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
npm install <package-name>npm test- Use ES6+ features (import/export, async/await)
- Follow JSDoc comment standards
- Maintain consistent error handling patterns
- Use descriptive variable and function names
-
API Authentication Failed
- Verify API key ID and private key path
- Ensure private key file is readable
- Check API key permissions
-
WebSocket Connection Issues
- Verify WebSocket URL configuration
- Check network connectivity
- Review firewall settings
- Check reconnection settings
-
Strategy Not Trading
- Check
TRADING_ENABLEDsetting - Verify strategy parameters
- Review log files for errors
- Check WebSocket subscriptions
- Check
-
Performance Issues
- Monitor memory usage
- Check log rotation settings
- Review strategy execution frequency
- Verify WebSocket channel subscriptions
Set LOG_LEVEL=debug in your .env file for detailed logging.
For issues and questions:
- Check the logs in
./logs/directory - Review configuration settings
- Test with demo environment first
- Check Kalshi API documentation
- Verify WebSocket channel configurations
This project is licensed under the ISC License.
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.
Contributions are welcome! Please:
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests if applicable
- Submit a pull request
- Complete WebSocket channel support
- Full REST API endpoint coverage
- Enhanced configuration management
- Advanced WebSocket message handling
- Improved health monitoring
- Strategy-specific configuration options
- Initial release
- Mean reversion trading strategy
- WebSocket and REST API integration
- Comprehensive logging and monitoring
- CLI interface
- Risk management framework