How to Fix Order Execution Issues
Problem
Your algorithm is generating signals but orders are not being executed, failing, or being rejected by the broker.
Troubleshooting Checklist
1. Check Broker Connection
Verify: Is your broker account connected and authenticated?
// Check broker connection status
GET /api/brokers/connections
// Response
{
"connections": [
{
"broker": "angelone",
"status": "connected",
"lastSync": "2024-01-15T10:30:00Z",
"apiKeyValid": true
}
]
}
Connection Status:
"connected": Active and working"disconnected": Not connected"error": Connection failed"expired": Authentication expired
Fix Disconnected:
// Reconnect broker
POST /api/brokers/connect
{
"broker": "angelone",
"apiKey": "YOUR_API_KEY",
"apiSecret": "YOUR_API_SECRET",
"clientId": "YOUR_CLIENT_ID"
}
Common Connection Issues:
- API credentials expired → Regenerate from broker portal
- Session timeout → Reconnect
- IP whitelist → Add your server IP to broker whitelist
- 2FA required → Complete 2FA authentication
2. Verify Broker Rate Limits
Check: Are you hitting broker API rate limits?
Rate Limits by Broker:
| Broker | Order Placement | Market Data | Session |
|---|---|---|---|
| AngelOne | 1 req/sec | 1 req/sec | 10 req/min |
| Zerodha | 10 req/sec | 3 req/sec | No limit |
| Upstox | 10 req/sec | 25 req/sec | No limit |
| Dhan | 10 req/sec | 10 req/sec | No limit |
Symptoms of Rate Limiting:
- Orders fail with "Too Many Requests" error
- Intermittent order failures
- Delays in order execution
Fix:
// Check rate limit status
GET /api/brokers/rate-limits
// Response
{
"broker": "angelone",
"orderPlacement": {
"limit": 1,
"remaining": 0,
"resetAt": "2024-01-15T10:30:01Z"
}
}
Solutions:
- Reduce trading frequency
- Increase timeframe (5m → 15m)
- Limit number of symbols
- Use batch order placement (if supported)
3. Check Daily Loss Limit
Verify: Have you reached your daily loss limit?
// Check daily P&L
GET /api/trading/algorithms/:id/daily-pnl
// Response
{
"dailyPnL": -4800,
"maxDailyLoss": -5000,
"remaining": -200,
"circuitBreakerActive": false
}
Issue: If daily loss approaches or exceeds limit, new orders are blocked.
Fix:
// Option 1: Increase daily loss limit (if appropriate)
PATCH /api/trading/algorithms/:id
{
"riskParameters": {
"maxDailyLoss": 10000
}
}
// Option 2: Reset for new trading day
// (Automatically resets at market open)
// Option 3: Stop trading for the day
POST /api/trading/algorithms/:id/stop
Warning: Only increase limits if you understand the risk!
4. Verify Risk Parameters
Check: Do risk parameters allow the order?
{
"riskParameters": {
"maxPositionSize": 5.0, // % of capital
"stopLoss": 2.0, // Required stop loss %
"maxOpenPositions": 3,
"riskRewardRatio": 2.0
}
}
Common Violations:
Position Size Too Large:
// Account balance: ₹100,000
// Max position size: 5%
// Maximum allowed: ₹5,000
// Order: ₹8,000 → REJECTED
// Fix: Reduce quantity or increase maxPositionSize
Stop Loss Missing:
// Risk parameters require 2% stop loss
// Order without stop loss → REJECTED
// Fix: Ensure exit conditions include stop loss
{
"exitConditions": {
"stopLoss": {
"enabled": true,
"type": "percentage",
"percentage": 2.0
}
}
}
Too Many Open Positions:
// Max open positions: 3
// Current open: 3
// New order → REJECTED
// Fix: Close a position or increase limit
{
"riskParameters": {
"maxOpenPositions": 5
}
}
5. Check Broker-Specific Requirements
AngelOne
Common Issues:
- Product type mismatch
- Insufficient margin
- Symbol format incorrect
- Auto square-off time
Fix:
{
"executionSettings": {
"broker": "angelone",
"productType": "INTRADAY", // or "DELIVERY"
"orderType": "MARKET",
"exchange": "NSE"
},
"indianMarketSettings": {
"enabled": true,
"autoSquareOff": {
"enabled": true,
"minutesBeforeClose": 15 // Square off at 15:15
}
}
}
Zerodha
Common Issues:
- Order margin shortfall
- Freeze quantity exceeded
- Invalid order type for instrument
Fix:
{
"executionSettings": {
"broker": "zerodha",
"productType": "MIS", // Intraday
"orderType": "LIMIT", // Use LIMIT for better fills
"exchange": "NSE"
}
}
Upstox
Common Issues:
- API version mismatch
- Invalid instrument token
- Order placement outside market hours
Fix:
{
"executionSettings": {
"broker": "upstox",
"productType": "I", // Intraday
"orderType": "MARKET",
"exchange": "NSE"
}
}
Dhan
Common Issues:
- Segment not activated
- Insufficient funds
- Invalid security ID
Fix:
{
"executionSettings": {
"broker": "dhan",
"productType": "INTRADAY",
"orderType": "MARKET",
"exchange": "NSE"
}
}
6. Verify Symbol Format
Check: Is the symbol format correct for your broker?
// Correct formats by exchange
const symbolFormats = {
NSE: 'NSE:RELIANCE',
BSE: 'BSE:SENSEX',
MCX: 'MCX:CRUDEOIL25JANFUT',
NCDEX: 'NCDEX:SOYBEAN25JANFUT'
}
// Common mistakes
const wrongFormats = [
'RELIANCE', // Missing exchange
'NSE-RELIANCE', // Wrong separator
'nse:reliance', // Wrong case
'NSE:RELIANCE.EQ' // Extra suffix
]
Fix:
// Validate symbol format
function validateSymbol(symbol) {
const pattern = /^(NSE|BSE|MCX|NCDEX):[A-Z0-9]+$/
return pattern.test(symbol)
}
// Example
validateSymbol('NSE:RELIANCE') // ✓ true
validateSymbol('RELIANCE') // ✗ false
7. Check Market Hours
Verify: Are you trading during market hours?
Indian Market Hours:
| Exchange | Regular Session | Pre-Open | Post-Close |
|---|---|---|---|
| NSE/BSE | 09:15 - 15:30 | 09:00 - 09:15 | 15:40 - 16:00 |
| MCX | 09:00 - 23:30 | - | - |
| NCDEX | 10:00 - 17:00 | - | - |
Fix:
{
"executionSettings": {
"timeFilters": {
"enabled": true,
"tradingHours": {
"start": "09:15",
"end": "15:30"
},
"tradingDays": ["monday", "tuesday", "wednesday", "thursday", "friday"]
}
}
}
8. Review Order Type Settings
Check: Is the order type appropriate?
{
"executionSettings": {
"orderType": "MARKET" // or "LIMIT", "STOP", "STOP_LIMIT"
}
}
Order Type Issues:
MARKET Orders:
- ✓ Fast execution
- ✗ Slippage risk
- ✗ May not work for illiquid stocks
LIMIT Orders:
- ✓ Price control
- ✗ May not fill
- ✗ Requires price specification
Fix:
// For liquid stocks - use MARKET
{
"executionSettings": {
"orderType": "MARKET"
}
}
// For illiquid stocks - use LIMIT
{
"executionSettings": {
"orderType": "LIMIT",
"limitPriceOffset": 0.1 // 0.1% from current price
}
}
9. Check Insufficient Funds
Verify: Do you have sufficient balance?
// Check account balance
GET /api/brokers/balance
// Response
{
"availableBalance": 45000,
"usedMargin": 55000,
"totalBalance": 100000
}
Calculate Required Margin:
function calculateRequiredMargin(order, productType) {
const { symbol, quantity, price } = order
// Intraday: ~20% margin
// Delivery: 100% margin
const marginMultiplier = productType === 'INTRADAY' ? 0.2 : 1.0
const orderValue = quantity * price
const requiredMargin = orderValue * marginMultiplier
return requiredMargin
}
// Example
const order = { symbol: 'NSE:RELIANCE', quantity: 100, price: 2500 }
const margin = calculateRequiredMargin(order, 'INTRADAY')
// Required: ₹50,000 (₹2,50,000 × 20%)
Fix:
- Reduce position size
- Close existing positions
- Add funds to account
- Use intraday product type (lower margin)
10. Review Order Logs
Check: What do the order logs say?
// Get order history
GET /api/trading/orders?algorithmId=algo_123&status=rejected
// Response
{
"orders": [
{
"id": "order_123",
"symbol": "NSE:RELIANCE",
"status": "rejected",
"rejectionReason": "RMS: Margin Exceeds, Required: 50000, Available: 45000",
"timestamp": "2024-01-15T10:30:00Z"
}
]
}
Common Rejection Reasons:
| Reason | Cause | Fix |
|---|---|---|
| Margin Exceeds | Insufficient funds | Add funds or reduce size |
| Invalid Symbol | Symbol not found | Check symbol format |
| Market Closed | Outside trading hours | Wait for market open |
| Rate Limit | Too many requests | Slow down requests |
| Freeze Quantity | Quantity too large | Reduce quantity |
| Invalid Product | Wrong product type | Check product type |
Diagnostic Script
async function diagnoseOrderIssues(algorithmId) {
const issues = []
// 1. Check broker connection
const connections = await fetch('/api/brokers/connections')
.then(r => r.json())
const connection = connections.connections[0]
if (connection.status !== 'connected') {
issues.push({
issue: 'Broker not connected',
status: connection.status,
fix: 'Reconnect broker account'
})
}
// 2. Check rate limits
const rateLimits = await fetch('/api/brokers/rate-limits')
.then(r => r.json())
if (rateLimits.orderPlacement.remaining === 0) {
issues.push({
issue: 'Rate limit reached',
resetAt: rateLimits.orderPlacement.resetAt,
fix: 'Wait for rate limit reset or reduce trading frequency'
})
}
// 3. Check daily loss
const dailyPnL = await fetch(`/api/trading/algorithms/${algorithmId}/daily-pnl`)
.then(r => r.json())
if (dailyPnL.circuitBreakerActive) {
issues.push({
issue: 'Daily loss limit reached',
dailyPnL: dailyPnL.dailyPnL,
maxDailyLoss: dailyPnL.maxDailyLoss,
fix: 'Stop trading for today or increase limit'
})
}
// 4. Check balance
const balance = await fetch('/api/brokers/balance')
.then(r => r.json())
if (balance.availableBalance < 10000) {
issues.push({
issue: 'Low account balance',
available: balance.availableBalance,
fix: 'Add funds to account'
})
}
// 5. Check recent rejections
const orders = await fetch(
`/api/trading/orders?algorithmId=${algorithmId}&status=rejected&limit=10`
).then(r => r.json())
if (orders.orders.length > 0) {
const rejectionReasons = orders.orders.map(o => o.rejectionReason)
issues.push({
issue: 'Recent order rejections',
count: orders.orders.length,
reasons: [...new Set(rejectionReasons)],
fix: 'Review rejection reasons and fix underlying issues'
})
}
// Report
if (issues.length === 0) {
console.log('✓ No obvious issues found')
console.log('Check broker portal for additional details')
} else {
console.log(`Found ${issues.length} potential issues:`)
issues.forEach((issue, i) => {
console.log(`\n${i + 1}. ${issue.issue}`)
console.log(' Fix:', issue.fix)
})
}
return issues
}
// Run diagnostic
diagnoseOrderIssues('algo_123')
Testing Order Execution
Test with Paper Trading
{
"executionSettings": {
"mode": "paper" // Test without real money
}
}
Benefits:
- No real money risk
- Same order flow as live
- Identifies configuration issues
- Tests broker integration
Test with Small Quantities
{
"positionSizing": {
"method": "fixed_quantity",
"quantity": 1 // Minimum quantity
}
}
Benefits:
- Minimal risk
- Validates order flow
- Tests broker connection
- Confirms symbol format
Prevention Checklist
Before going live:
- Broker connection tested and working
- Rate limits understood and configured
- Risk parameters set appropriately
- Daily loss limit configured
- Sufficient account balance
- Symbol formats validated
- Order types tested
- Market hours configured
- Paper trading successful
- Small quantity test passed