Broker Integration
Introduction
x3Algo integrates with major Indian brokers to execute live trades. Understanding how broker integration works, including API rate limits, symbol formats, and broker-specific features, is essential for successful automated trading.
Supported Brokers
AngelOne (Angel Broking)
API: SmartAPI Features:
- Real-time market data
- Order placement and modification
- Position tracking
- Historical data access
Rate Limits:
Order Placement: 10 requests/second
Market Data: 1 request/second
Historical Data: 3 requests/second
Strengths:
- Good API documentation
- Reliable execution
- Competitive brokerage
- Wide instrument coverage
Zerodha
API: Kite Connect Features:
- Comprehensive API
- WebSocket streaming
- Historical data
- Postback notifications
Rate Limits:
Order Placement: 10 requests/second
Market Data: 1 request/second
Historical Data: 3 requests/second
Strengths:
- Most popular API
- Excellent documentation
- Active developer community
- Robust infrastructure
Upstox
API: Upstox API v2 Features:
- REST API
- WebSocket feeds
- Historical data
- Order management
Rate Limits:
Order Placement: 10 requests/second
Market Data: 1 request/second
Historical Data: 3 requests/second
Strengths:
- Modern API design
- Good performance
- Competitive pricing
- Mobile-first approach
Dhan
API: Dhan API Features:
- Trading API
- Market data feeds
- Order tracking
- Portfolio management
Rate Limits:
Order Placement: 10 requests/second
Market Data: 1 request/second
Historical Data: 3 requests/second
Strengths:
- New-age broker
- Innovative features
- Good API support
- Competitive rates
How Broker Integration Works
Authentication Flow
1. API Credentials:
User provides:
- API Key
- API Secret
- Client ID (broker-specific)
2. Token Generation:
x3Algo → Broker API: Login request
Broker API → x3Algo: Access token
x3Algo: Stores encrypted token
3. Token Refresh:
Tokens expire daily
Automatic refresh before expiry
Re-authentication if refresh fails
Security:
- Credentials encrypted at rest
- Tokens stored securely
- HTTPS for all communication
- No credential logging
Order Execution Flow
1. Signal Generation:
Algorithm detects entry condition
Calculates position size
Prepares order parameters
2. Order Validation:
Check risk parameters
Verify margin availability
Validate order parameters
Apply rate limiting
3. Order Placement:
x3Algo → Broker API: Place order request
Broker API: Validates and places order
Broker API → x3Algo: Order confirmation
4. Order Tracking:
Monitor order status
Handle partial fills
Track execution price
Update position records
5. Position Management:
Track open positions
Monitor P&L
Apply exit conditions
Manage stop losses
Rate Limiting
Why Rate Limits Exist
Broker Protection:
- Prevent API abuse
- Ensure fair access
- Maintain system stability
- Comply with exchange rules
Consequences of Exceeding:
- API requests rejected
- Temporary account suspension
- Order placement failures
- Data feed interruptions
Rate Limit Implementation
Per-Broker Limits:
{
"angelone": {
"orderPlacement": {
"limit": 10,
"window": 1000 // 1 second
},
"marketData": {
"limit": 1,
"window": 1000
}
}
}
x3Algo Rate Limiter:
Tracks requests per broker
Queues excess requests
Implements exponential backoff
Retries failed requests
Best Practices:
1. Batch operations when possible
2. Cache market data
3. Avoid unnecessary API calls
4. Use WebSocket for real-time data
5. Implement request queuing
Handling Rate Limits
Automatic Handling:
Request → Rate Limiter → Queue if needed → Execute
Retry Logic:
Attempt 1: Immediate
Attempt 2: Wait 1 second
Attempt 3: Wait 2 seconds
Attempt 4: Wait 4 seconds
Max Attempts: 3-5
Error Handling:
Rate Limit Error → Queue request → Retry with backoff
Persistent Failure → Alert user → Pause algorithm
Symbol Translation
Exchange Symbol Formats
NSE Equity:
x3Algo: NSE:RELIANCE
AngelOne: RELIANCE-EQ
Zerodha: NSE:RELIANCE
Upstox: NSE_EQ|INE002A01018
Dhan: 2885 (security ID)
NSE Futures:
x3Algo: NSE:NIFTY24DEC24500CE
AngelOne: NIFTY24DEC24500CE
Zerodha: NFO:NIFTY24DEC24500CE
Format: SYMBOL[YY][MMM][STRIKE][CE/PE]
MCX Commodities:
x3Algo: MCX:CRUDEOIL25JANFUT
AngelOne: CRUDEOIL25JANFUT
Zerodha: MCX:CRUDEOIL25JANFUT
Format: SYMBOL[YY][MMM]FUT
Translation Layer
x3Algo Handles:
User Input: NSE:RELIANCE
↓
Internal Format: Standardized
↓
Broker Translation: Broker-specific format
↓
Broker API: RELIANCE-EQ (AngelOne)
Benefits:
- Consistent user experience
- Broker-agnostic configuration
- Easy broker switching
- Reduced errors
Broker Comparison
Feature Comparison
| Feature | AngelOne | Zerodha | Upstox | Dhan |
|---|---|---|---|---|
| API Quality | Good | Excellent | Good | Good |
| Documentation | Good | Excellent | Good | Good |
| Rate Limits | Standard | Standard | Standard | Standard |
| WebSocket | Yes | Yes | Yes | Yes |
| Historical Data | Yes | Yes | Yes | Yes |
| Brokerage | Low | Low | Low | Low |
| Support | Good | Excellent | Good | Good |
Brokerage Charges
Equity Intraday:
AngelOne: ₹20 or 0.25% (whichever lower)
Zerodha: ₹20 or 0.03% (whichever lower)
Upstox: ₹20 or 0.05% (whichever lower)
Dhan: ₹20 or 0.03% (whichever lower)
Equity Delivery:
AngelOne: 0.5% or ₹20 (whichever lower)
Zerodha: 0%
Upstox: 0.25%
Dhan: 0%
F&O:
AngelOne: ₹20 per order
Zerodha: ₹20 per order
Upstox: ₹20 per order
Dhan: ₹20 per order
API Reliability
Uptime:
AngelOne: 99.5%+
Zerodha: 99.9%+
Upstox: 99.5%+
Dhan: 99.5%+
Response Time:
Order Placement: <100ms (all brokers)
Market Data: <50ms (all brokers)
Historical Data: <500ms (all brokers)
Choosing a Broker
For Beginners:
Recommended: Zerodha
Reasons:
- Best documentation
- Large community
- Reliable API
- Good support
For Active Traders:
Recommended: AngelOne or Zerodha
Reasons:
- Low brokerage
- Fast execution
- Good API limits
- Reliable infrastructure
For Cost-Conscious:
Recommended: Zerodha or Dhan
Reasons:
- Zero delivery brokerage
- Low F&O charges
- No hidden fees
Connection Management
Initial Setup
1. Broker Account:
Open trading account
Enable API access
Generate API credentials
Note client ID
2. x3Algo Configuration:
Navigate to Settings → Broker Integration
Select broker
Enter API credentials
Test connection
3. Verification:
Test order placement (paper mode)
Verify market data feed
Check position tracking
Confirm P&L calculation
Connection Monitoring
Health Checks:
Periodic ping to broker API
Monitor response times
Track error rates
Alert on failures
Auto-Reconnection:
Detect disconnection
Wait for cooldown period
Attempt reconnection
Retry with exponential backoff
Alert if persistent failure
Error Handling
Common Errors:
1. Authentication Failure:
Cause: Expired token, invalid credentials
Action: Re-authenticate, refresh token
Prevention: Automatic token refresh
2. Rate Limit Exceeded:
Cause: Too many requests
Action: Queue requests, implement backoff
Prevention: Rate limiter
3. Order Rejection:
Cause: Insufficient margin, invalid parameters
Action: Log error, alert user
Prevention: Pre-validation
4. Network Timeout:
Cause: Network issues, broker downtime
Action: Retry with backoff
Prevention: Timeout configuration
Best Practices
1. Credential Security
Do:
- Store credentials encrypted
- Use environment variables
- Rotate API keys regularly
- Limit API permissions
Don't:
- Share credentials
- Commit to version control
- Log credentials
- Use in multiple places
2. Rate Limit Management
Do:
- Implement request queuing
- Use exponential backoff
- Cache market data
- Batch operations
Don't:
- Ignore rate limits
- Retry immediately
- Make unnecessary calls
- Spam API
3. Error Handling
Do:
- Log all errors
- Implement retries
- Alert on critical failures
- Graceful degradation
Don't:
- Ignore errors
- Retry indefinitely
- Crash on failure
- Hide errors from user
4. Testing
Do:
- Test in paper mode first
- Verify all order types
- Test error scenarios
- Monitor for issues
Don't:
- Test in live mode
- Skip edge cases
- Assume it works
- Deploy without testing
Troubleshooting
Connection Issues
Symptoms:
- Cannot connect to broker
- Authentication failures
- Timeout errors
Solutions:
- Verify API credentials
- Check broker API status
- Test network connectivity
- Review error logs
- Contact broker support
Order Execution Issues
Symptoms:
- Orders not placed
- Partial fills
- Unexpected rejections
Solutions:
- Check margin availability
- Verify order parameters
- Review risk limits
- Check rate limits
- Validate symbol format
Data Feed Issues
Symptoms:
- Stale market data
- Missing candles
- Delayed updates
Solutions:
- Check WebSocket connection
- Verify subscription
- Review rate limits
- Test data feed
- Switch to backup source
Summary
Key Takeaways:
- Four Brokers: AngelOne, Zerodha, Upstox, Dhan supported
- Rate Limits: 10 orders/sec, 1 market data/sec
- Symbol Translation: Automatic broker-specific formatting
- Security: Encrypted credentials, secure token storage
- Reliability: Auto-reconnection, error handling
- Testing: Always test in paper mode first
- Monitoring: Track connection health, error rates
- Best Practices: Respect rate limits, handle errors gracefully
- Broker Choice: Zerodha for beginners, AngelOne for active traders
- Support: Comprehensive error handling and logging
Broker Integration Checklist:
- Broker account opened
- API access enabled
- Credentials configured in x3Algo
- Connection tested
- Paper trading validated
- Rate limits understood
- Error handling configured
- Monitoring enabled
- Backup plan ready
Related Documentation
- How to Setup Execution Settings - Broker configuration
- How to Debug Broker Connection - Troubleshooting guide
- Indian Market Specifics - Market regulations
- Paper to Live Trading Transition - Safe deployment