Skip to main content
Skip to main content
Version: Next 🚧

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:

  1. Login to AngelOne portal
  2. Go to API settings
  3. Add your server IP to whitelist
  4. 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:

  1. Check API app permissions in Kite Connect
  2. Ensure "Place orders" permission is enabled
  3. 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:

  1. Login to Dhan portal
  2. Activate required segments (Equity, F&O, Commodity)
  3. 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

CodeErrorCauseFix
AB1001Invalid API KeyWrong credentialsRegenerate API key
AB1002Session expiredTimeoutReconnect
AB1003Rate limit exceededToo many requestsSlow down
AB1004Invalid symbolWrong formatCheck symbol format
AB1005Insufficient fundsLow balanceAdd funds
AB1006Order rejectedRMS rulesCheck risk parameters

Zerodha Error Codes

CodeErrorCauseFix
TokenExceptionInvalid tokenExpired tokenGenerate new token
InputExceptionInvalid inputWrong parametersCheck request format
NetworkExceptionNetwork errorConnection issueRetry request
OrderExceptionOrder failedOrder rejectedCheck order details

Upstox Error Codes

CodeErrorCauseFix
401UnauthorizedInvalid tokenRegenerate token
400Bad RequestInvalid parametersCheck request
429Too Many RequestsRate limitSlow down
500Server ErrorUpstox issueRetry 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

  1. Monitor Connection Status: Set up alerts for connection failures
  2. Rotate Credentials Regularly: Update API keys every 3-6 months
  3. Implement Retry Logic: Auto-retry failed requests with exponential backoff
  4. Log All API Calls: Keep detailed logs for debugging
  5. Test in Paper Mode First: Validate connection before live trading
  6. Keep Backup Broker: Have secondary broker configured
  7. Monitor Rate Limits: Track API usage to avoid limits
  8. Set Up Health Checks: Periodic connection tests
  9. Document Issues: Keep record of errors and solutions
  10. Stay Updated: Monitor broker API changes and updates

Getting Help

Broker Support Contacts

AngelOne:

Zerodha:

Upstox:

Dhan:

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"
}
}