Strategy Management
The Strategy Module is a core component of the OpenAlgo platform that enables users to create, manage, and execute automated trading strategies through webhooks. This document provides a comprehensive overview of the strategy module's features, architecture, and usage.
Overview
The Strategy Module allows traders to:
Create and manage trading strategies
Configure multiple symbols per strategy
Set up intraday and positional trading modes
Control trading hours and auto square-off times
Integrate with trading platforms via webhooks
Execute trades based on external signals
Core Components
1. Strategy Blueprint (strategy.py
)
strategy.py
)The strategy blueprint handles all HTTP routes and business logic for strategy management:
Route Management: Handles all
/strategy/*
endpointsOrder Processing: Manages order queues with rate limiting
Time Management: Handles trading hours and square-off scheduling
Webhook Processing: Processes incoming trading signals
2. Database Models (strategy_db.py
)
strategy_db.py
)Two main database models manage strategy data:
Strategy Model
id
: Unique identifiername
: Strategy namewebhook_id
: Unique UUID for webhook identificationuser_id
: Associated userplatform
: Trading platform (e.g., tradingview)is_active
: Strategy activation statusis_intraday
: Intraday/Positional modetrading_mode
: LONG/SHORT/BOTHstart_time
: Trading start timeend_time
: Trading end timesquareoff_time
: Auto square-off time
StrategySymbolMapping Model
Links symbols to strategies
Configures trading parameters per symbol
Manages exchange and product type settings
Features
1. Strategy Management
Create new strategies
Toggle strategy activation
Delete strategies
View strategy details
Configure trading times
2. Symbol Configuration
Add/remove symbols to strategies
Configure quantity per symbol
Set product type (MIS/CNC/NRML)
Choose exchange
3. Trading Controls
Intraday/Positional mode selection
Trading direction control (LONG/SHORT/BOTH)
Trading hours configuration
Automatic square-off scheduling
4. Webhook Integration
The module processes webhook signals from trading platforms with the following format:
Signal Keywords:
BUY
: Long entrySELL
: Long exitSHORT
: Short entryCOVER
: Short cover
Rate Limiting
The module implements sophisticated rate limiting:
Regular orders: Max 10 orders per second
Smart orders: 1 order per second
Separate queues for different order types
Security Features
Session validation for all routes
Unique webhook IDs per strategy
User-specific strategy isolation
API key management for trading platforms
Best Practices
Strategy Naming:
Use descriptive names
Include relevant indicators/timeframes
Follow naming conventions
Symbol Configuration:
Verify exchange and product type compatibility
Set appropriate position sizes
Test with small quantities first
Trading Hours:
Set conservative trading hours
Allow buffer for square-off
Consider market timing restrictions
Webhook Setup:
Use secure webhook URLs
Include proper signal keywords
Test signals before live trading
Error Handling
The module implements comprehensive error handling:
Database transaction management
Order placement retries
Invalid signal filtering
Rate limit compliance
Integration Points
Trading Platforms:
TradingView
ChartInk
Custom platforms (via webhook API)
Broker Integration:
Supports multiple Indian brokers
Product type validation per exchange
Order type compatibility checks
Performance Considerations
Efficient order queue processing
Rate limit compliance
Database connection pooling
Background task scheduling
TradingView Webhook Configuration
Setting Up TradingView Alerts
Create Alert in TradingView:
Go to TradingView Chart
Click "Alerts" icon
Select "Create Alert"
Alert Settings:
Name: Include signal keyword (BUY/SELL/SHORT/COVER)
Condition: Set your trading condition
Message: Configure webhook message (see format below)
Webhook URL:
[BASE_URL]/strategy/webhook/[YOUR_WEBHOOK_ID]
Webhook Message Formats
The webhook message format varies based on the trading mode of your strategy:
1. Long Only Mode
2. Short Only Mode
3. Both Modes (Long & Short)
TradingView Alert Message Setup
Alert Message Format for Long/Short Only Mode:
Alert Message Format for Both Modes:
Signal Actions by Trading Mode
Long Only Mode:
BUY
: Opens a long positionSELL
: Closes the long position
Short Only Mode:
SELL
: Opens a short positionBUY
: Closes the short position
Both Modes:
BUY
with positive position_size: Opens/Increases long positionSELL
with positive position_size: Opens/Increases short positionBUY
with zero position_size: Closes short positionSELL
with zero position_size: Closes long position
Important Notes:
Symbol Format:
Use the exact symbol as configured in your strategy
Symbols are case-sensitive
Must match with the configured exchange
Position Size:
Required only for "BOTH" trading mode
Must be included in every webhook message for "BOTH" mode
Represents the desired position size
Action Values:
Must be uppercase: "BUY" or "SELL"
Action interpretation depends on trading mode
Sample Python Code
Here are examples of how to send webhook requests using Python:
1. Basic Long/Short Mode Example
2. Both Mode Example
3. Error Handling Example
How Webhook Processing Works
Signal Reception:
Webhook endpoint receives TradingView alert
Validates webhook ID and message format
Checks strategy status and trading hours
Order Processing:
Matches symbol with strategy configuration
Validates trading mode compatibility
Applies position sizing rules
Routes to appropriate order queue
Rate Limiting:
Regular orders: Max 10/second
Smart orders: 1/second
Queue management for order bursts
Position Management:
Tracks open positions per symbol
Handles partial fills
Manages stop-loss and target orders
Implements square-off rules
Best Practices for Webhook Usage
Alert Naming:
Use clear, consistent naming patterns
Include strategy identifier
Add signal type in name
Message Formatting:
Use proper JSON syntax
Include all required fields
Add custom fields for strategy-specific data
Error Handling:
Set up retry mechanism in TradingView
Monitor webhook delivery status
Implement fallback signals
Testing:
Test with paper trading first
Verify webhook connectivity
Validate all signal types
Check position tracking
Future Enhancements
Planned improvements include:
Advanced order types
Strategy templates
Performance analytics
Risk management features
Multi-account support
Last updated