How to Debug Broker Connection
Problem
You're experiencing issues connecting to your broker, receiving API errors, or having trouble authenticating your broker account.
Prerequisites
- Broker account with API access enabled
- API credentials (API Key, API Secret, Client ID)
- Understanding of your broker's API requirements
Broker-Specific Debugging
AngelOne (Angel Broking)
Common Issues
1. Authentication Failed
Error: "Invalid API Key" or "Authentication failed"
Causes:
- API Key expired or regenerated
- Wrong API credentials
- Session expired
Fix:
// Regenerate API credentials
// 1. Login to AngelOne portal
// 2. Go to API section
// 3. Generate new API Key and Secret
// 4. Update in x3Algo
POST /api/brokers/connect
{
"broker": "angelone",
"apiKey": "NEW_API_KEY",
"apiSecret": "NEW_API_SECRET",
"clientId": "YOUR_CLIENT_ID"
}
2. Rate Limit Exceeded
Error: "Too many requests" or "Rate limit exceeded"
AngelOne Rate Limits:
- Order placement: 1 request/second
- Market data: 1 request/second
- Session APIs: 10 requests/minute
Fix:
// Check rate limit status
GET /api/brokers/angelone/rate-limits
// Response
{
"orderPlacement": {
"limit": 1,
"remaining": 0,
"resetAt": "2024-01-15T10:30:01Z"
}
}
// Solution: Reduce trading frequency
{
"timeframe": "15m" // Instead of 5m or 1m
}
3. Invalid Symbol Format
Error: "Invalid trading symbol"
AngelOne Symbol Format:
// ✓ Correct formats
const validSymbols = [
'NSE:RELIANCE',
'BSE:SENSEX',
'MCX:CRUDEOIL25JANFUT',
'NCDEX:SOYBEAN25JANFUT'
]
// ✗ Wrong formats
const invalidSymbols = [
'RELIANCE', // Missing exchange
'NSE-RELIANCE', // Wrong separator
'NSE:RELIANCE-EQ' // Extra suffix
]
4. Session Timeout
Error: "Session expired" or "Invalid session"
Cause: AngelOne sessions expire after inactivity
Fix:
// Reconnect broker
POST /api/brokers/angelone/reconnect
{
"clientId": "YOUR_CLIENT_ID",
"password": "YOUR_PASSWORD",
"totp": "123456" // If 2FA enabled
}
5. IP Whitelist
Error: "IP not whitelisted"
Fix:
- Login to AngelOne portal
- Go to API settings
- Add your server IP to whitelist
- Wait 5-10 minutes for changes to propagate
AngelOne Diagnostic Script
async function diagnoseAngelOne() {
const checks = []
// 1. Check connection
const connection = await fetch('/api/brokers/connections')
.then(r => r.json())
const angelone = connection.connections.find(c => c.broker === 'angelone')
checks.push({
check: 'Connection Status',
status: angelone?.status || 'not_connected',
pass: angelone?.status === 'connected'
})
// 2. Check API key validity
checks.push({
check: 'API Key Valid',
status: angelone?.apiKeyValid ? 'valid' : 'invalid',
pass: angelone?.apiKeyValid
})
// 3. Check rate limits
const rateLimits = await fetch('/api/brokers/angelone/rate-limits')
.then(r => r.json())
checks.push({
check: 'Rate Limits',
status: `${rateLimits.orderPlacement.remaining}/${rateLimits.orderPlacement.limit}`,
pass: rateLimits.orderPlacement.remaining > 0
})
// 4. Test market data fetch
try {
await fetch('/api/brokers/angelone/market-data?symbol=NSE:RELIANCE')
checks.push({
check: 'Market Data Access',
status: 'working',
pass: true
})
} catch (error) {
checks.push({
check: 'Market Data Access',
status: error.message,
pass: false
})
}
// Report
console.log('AngelOne Diagnostic Results:')
checks.forEach(check => {
const icon = check.pass ? '✓' : '✗'
console.log(`${icon} ${check.check}: ${check.status}`)
})
return checks
}
Zerodha (Kite Connect)
Common Issues
1. Invalid API Key
Error: "Invalid API credentials"
Fix:
// Get API credentials from Kite Connect portal
// https://kite.trade/
POST /api/brokers/connect
{
"broker": "zerodha",
"apiKey": "YOUR_API_KEY",
"apiSecret": "YOUR_API_SECRET"
}
2. Request Token Expired
Error: "Token is invalid or has expired"
Cause: Zerodha request tokens expire after single use
Fix:
// Generate new request token
// 1. Login to Kite Connect
// 2. Authorize app
// 3. Get new request token
// 4. Exchange for access token
POST /api/brokers/zerodha/token
{
"requestToken": "NEW_REQUEST_TOKEN"
}
3. Insufficient Permissions
Error: "Insufficient permissions"
Fix:
- Check API app permissions in Kite Connect
- Ensure "Place orders" permission is enabled
- Regenerate API credentials if needed
4. Order Margin Shortfall
Error: "Margin exceeds available funds"
Fix:
// Check available margin
GET /api/brokers/zerodha/margins
// Response
{
"equity": {
"available": 45000,
"utilised": 55000
}
}
// Solution: Reduce position size or add funds
Zerodha Rate Limits:
- Order placement: 10 requests/second
- Market data: 3 requests/second
- No session limit
Upstox
Common Issues
1. Invalid Access Token
Error: "Unauthorized" or "Invalid token"
Fix:
// Regenerate access token
POST /api/brokers/upstox/token
{
"code": "AUTHORIZATION_CODE"
}
2. API Version Mismatch
Error: "API version not supported"
Fix:
// Ensure using Upstox API v2
const config = {
apiVersion: 'v2',
baseUrl: 'https://api.upstox.com/v2'
}
3. Invalid Instrument Token
Error: "Invalid instrument token"
Fix:
// Get correct instrument token
GET /api/brokers/upstox/instruments?symbol=NSE:RELIANCE
// Use returned instrument_token in orders
Upstox Rate Limits:
- Order placement: 10 requests/second
- Market data: 25 requests/second
Dhan
Common Issues
1. Segment Not Activated
Error: "Segment not activated"
Fix:
- Login to Dhan portal
- Activate required segments (Equity, F&O, Commodity)
- Wait for activation confirmation
2. Insufficient Funds
Error: "Insufficient balance"
Fix:
// Check balance
GET /api/brokers/dhan/balance
// Add funds through Dhan portal
3. Invalid Security ID
Error: "Invalid security ID"
Fix:
// Get correct security ID
GET /api/brokers/dhan/securities?symbol=NSE:RELIANCE
// Use returned security_id in orders
Dhan Rate Limits:
- Order placement: 10 requests/second
- Market data: 10 requests/second
General Debugging Steps
1. Verify API Credentials
// Test API credentials
POST /api/brokers/test-connection
{
"broker": "angelone",
"apiKey": "YOUR_API_KEY",
"apiSecret": "YOUR_API_SECRET",
"clientId": "YOUR_CLIENT_ID"
}
// Response
{
"success": true,
"message": "Connection successful",
"details": {
"broker": "angelone",
"clientId": "YOUR_CLIENT_ID",
"accountStatus": "active"
}
}
2. Check Network Connectivity
# Test broker API endpoint
curl -I https://apiconnect.angelbroking.com/rest/secure/angelbroking/user/v1/getProfile
# Expected: HTTP 200 or 401 (not 404 or timeout)
3. Review API Logs
// Get recent API calls
GET /api/brokers/logs?broker=angelone&limit=50
// Response
{
"logs": [
{
"timestamp": "2024-01-15T10:30:00Z",
"endpoint": "/order/place",
"method": "POST",
"statusCode": 429,
"error": "Rate limit exceeded",
"duration": 150
}
]
}
4. Test with Postman/cURL
# Test AngelOne authentication
curl -X POST https://apiconnect.angelbroking.com/rest/auth/angelbroking/user/v1/loginByPassword \
-H "Content-Type: application/json" \
-H "X-ClientLocalIP: YOUR_IP" \
-H "X-ClientPublicIP: YOUR_IP" \
-H "X-MACAddress: YOUR_MAC" \
-H "X-PrivateKey: YOUR_API_KEY" \
-d '{
"clientcode": "YOUR_CLIENT_ID",
"password": "YOUR_PASSWORD"
}'
5. Check Broker Status
// Check if broker API is operational
GET /api/brokers/status
// Response
{
"brokers": [
{
"name": "angelone",
"status": "operational",
"lastChecked": "2024-01-15T10:30:00Z"
},
{
"name": "zerodha",
"status": "degraded",
"lastChecked": "2024-01-15T10:30:00Z",
"message": "Experiencing high latency"
}
]
}
Common Error Codes
AngelOne Error Codes
| Code | Error | Cause | Fix |
|---|---|---|---|
| AB1001 | Invalid API Key | Wrong credentials | Regenerate API key |
| AB1002 | Session expired | Timeout | Reconnect |
| AB1003 | Rate limit exceeded | Too many requests | Slow down |
| AB1004 | Invalid symbol | Wrong format | Check symbol format |
| AB1005 | Insufficient funds | Low balance | Add funds |
| AB1006 | Order rejected | RMS rules | Check risk parameters |
Zerodha Error Codes
| Code | Error | Cause | Fix |
|---|---|---|---|
| TokenException | Invalid token | Expired token | Generate new token |
| InputException | Invalid input | Wrong parameters | Check request format |
| NetworkException | Network error | Connection issue | Retry request |
| OrderException | Order failed | Order rejected | Check order details |
Upstox Error Codes
| Code | Error | Cause | Fix |
|---|---|---|---|
| 401 | Unauthorized | Invalid token | Regenerate token |
| 400 | Bad Request | Invalid parameters | Check request |
| 429 | Too Many Requests | Rate limit | Slow down |
| 500 | Server Error | Upstox issue | Retry later |
Troubleshooting Checklist
- API credentials are correct and not expired
- Broker account is active and funded
- Required segments are activated
- IP address is whitelisted (if required)
- Rate limits are not exceeded
- Symbol format is correct
- Network connectivity is working
- Broker API is operational
- Session is not expired
- 2FA is completed (if required)
Prevention Tips
- Monitor Connection Status: Set up alerts for connection failures
- Rotate Credentials Regularly: Update API keys every 3-6 months
- Implement Retry Logic: Auto-retry failed requests with exponential backoff
- Log All API Calls: Keep detailed logs for debugging
- Test in Paper Mode First: Validate connection before live trading
- Keep Backup Broker: Have secondary broker configured
- Monitor Rate Limits: Track API usage to avoid limits
- Set Up Health Checks: Periodic connection tests
- Document Issues: Keep record of errors and solutions
- Stay Updated: Monitor broker API changes and updates
Getting Help
Broker Support Contacts
AngelOne:
- Email: smartapi@angelbroking.com
- Phone: 1800-209-9191
- Portal: https://smartapi.angelbroking.com
Zerodha:
- Email: kiteconnect@zerodha.com
- Forum: https://kite.trade/forum
- Docs: https://kite.trade/docs
Upstox:
Dhan:
- Email: api@dhan.co
- Docs: https://api.dhan.co
x3Algo Support
// Create support ticket with diagnostic info
POST /api/support/tickets
{
"subject": "Broker Connection Issue - AngelOne",
"description": "Unable to connect to AngelOne API",
"broker": "angelone",
"diagnostics": {
"connectionStatus": "failed",
"errorCode": "AB1001",
"errorMessage": "Invalid API Key",
"lastSuccessfulConnection": "2024-01-14T15:30:00Z"
}
}