# Pending Orders

## Intelligent Pending Order Expiry System

BananaEA features a **sophisticated 5-method expiry system** for pending orders, ensuring orders don't remain open indefinitely in changing market conditions.

***

## Overview: Pending Order Lifecycle

**What are pending orders?**

* Orders placed in advance at specific price levels
* Executed automatically when price reaches entry level
* **Risk:** Market conditions may change before execution
* **Solution:** Automatic expiry/cancellation based on multiple criteria

**BananaEA's expiry methods:**

1. **Bar Count Expiry** — Cancel after X bars (default, time-based)
2. **Opposite Signal Expiry** — Cancel on reverse signal (smart, pattern-based)
3. **EMA Crossover Expiry** — Cancel on trend change (MA-based)
4. **Session Close Expiry** — Cancel at specific hour (session-based)
5. **Combined Methods** — Use multiple methods simultaneously

***

## Method 1: Bar Count Expiry (Default - Recommended)

### `UseCancelAfterBars` - Enable Bar Count Expiry

**What it does:** Automatically cancels pending orders after specified number of bars.

**Configuration:**

* **Default:** true (enabled)
* **Purpose:** Prevents stale orders from old signals
* **Best for:** All trading styles (universal solution)

### `CancelAfterBars` - Expiry Bar Count

**What it does:** Number of bars before pending order is cancelled.

**Configuration:**

* **Default:** 5 bars
* **Range:** 1–50 bars
* **Calculation:** Starts counting from order placement bar

**How it works:**

```
M5 Chart Example:
CancelAfterBars = 5

Signal at 10:00 → Pending order placed
10:05 (1 bar) → Order still active
10:10 (2 bars) → Order still active
10:15 (3 bars) → Order still active
10:20 (4 bars) → Order still active
10:25 (5 bars) → Order CANCELLED (expired)
```

**Timeframe-specific recommendations:**

| Timeframe | Recommended Bars | Time Duration | Use Case                |
| --------- | ---------------- | ------------- | ----------------------- |
| M1        | 10-15 bars       | 10-15 minutes | Scalping (tight expiry) |
| M5        | 5-10 bars        | 25-50 minutes | Day trading (default)   |
| M15       | 3-6 bars         | 45-90 minutes | Intraday swing          |
| M30       | 2-4 bars         | 1-2 hours     | Session trading         |
| H1        | 2-3 bars         | 2-3 hours     | Multi-session           |
| H4        | 1-2 bars         | 4-8 hours     | Swing trading           |
| D1        | 1-2 bars         | 1-2 days      | Position trading        |

**Advantages:**

* ✅ Simple and predictable
* ✅ Works on all symbols/timeframes
* ✅ Prevents order buildup
* ✅ Time-based risk management

**Disadvantages:**

* ❌ Doesn't consider market conditions
* ❌ Fixed time may be too short/long
* ❌ Ignores price action changes

**Best practices:**

* **Conservative:** 3-5 bars (standard, prevents stale orders)
* **Balanced:** 5-10 bars (default, allows time for entry)
* **Aggressive:** 10-20 bars (patient, waits for better fills)

***

## Method 2: Opposite Signal Expiry (Smart - Pattern-Based)

### `CancelOnOppositeSignal` - Opposite Signal Cancellation

**What it does:** Cancels pending BUY orders when SELL signal appears (and vice versa).

**Configuration:**

* **Default:** true (enabled, highly recommended)
* **Logic:** Market reversal invalidates old entry
* **Best for:** Pattern-based trading, trend following

**How it works:**

```
10:00 → BUY signal detected → Pending BUY order placed
10:05 → No activity
10:10 → SELL signal detected → Pending BUY order CANCELLED
         (Market reversed, BUY entry no longer valid)
```

**Real-world example:**

```
DAX M5:
09:00 → Bu1 (BananaBuy #1) signal → Pending BUY at 18,520
09:15 → Price hasn't reached 18,520 yet (order still pending)
09:20 → Be1 (BananaSell #1) signal appears (market reversed)
         → Pending BUY order CANCELLED immediately
         → EA can place new SELL order if conditions met
```

**Advantages:**

* ✅ Smart pattern-based cancellation
* ✅ Adapts to market reversals
* ✅ Prevents counter-trend entries
* ✅ Allows fresh signals to take priority

**Disadvantages:**

* ❌ May cancel good entries during choppy markets
* ❌ Requires valid opposite signals

**Best for:**

* Pattern traders (BananaEA optimized strategies)
* Trend following systems
* Low-volatility markets (clear directional moves)

**⚠️ Recommended:** Keep enabled (true) for most strategies

***

## Method 3: EMA Crossover Expiry (Trend-Based)

### `CancelOnEMACrossover` - MA Crossover Cancellation

**What it does:** Cancels pending orders when EMA crossover indicates trend change.

**Configuration:**

* **Default:** false (disabled)
* **Purpose:** Cancel orders when trend shifts
* **Best for:** MA-based strategies, trend followers

**How it works:**

```
Uses Filter_EMA_Fast (9) and Filter_EMA_Slow (21) crossover:

BUY order pending:
- Fast EMA crosses BELOW Slow EMA → Trend turned bearish
- Pending BUY order CANCELLED

SELL order pending:
- Fast EMA crosses ABOVE Slow EMA → Trend turned bullish
- Pending SELL order CANCELLED
```

**Integration with EMA filter:**

```
Signal Configuration:
UseFilter_EMA = true
Filter_EMA_Fast = 9
Filter_EMA_Slow = 21

CancelOnEMACrossover = true

Result:
- Only trade with EMA trend
- Cancel orders when trend reverses
- Professional MA-based risk management
```

**Advantages:**

* ✅ Trend-aware cancellation
* ✅ Works with existing EMA filter
* ✅ Reduces counter-trend entries
* ✅ Professional MA-based approach

**Disadvantages:**

* ❌ Requires EMA filter enabled
* ❌ May cancel too early in ranging markets
* ❌ Lag from MA calculation

**Best for:**

* MA-based strategies
* Trend following systems
* Medium-to-long-term trading (H1+)

**When to enable:**

* Using `UseFilter_EMA = true` in signal configuration
* Trading trending markets (Forex majors, indices)
* Want strict trend alignment

**When to disable (default):**

* Not using EMA filters
* Trading ranging/choppy markets
* Pattern-based strategies without MA dependency

***

## Method 4: Session Close Expiry (Time-Based)

### `CancelPendingsAtSessionClose` - Session-Based Cancellation

**What it does:** Cancels all pending orders at specific hour each day.

**Configuration:**

* **Default:** false (disabled)
* **Purpose:** Clean slate at session transitions
* **Best for:** Session-specific trading, daily reset

### `PendingCancelHour` - Daily Cancellation Hour

**What it does:** Hour (0-23) when all pending orders are cancelled.

**Configuration:**

* **Default:** 20 (8:00 PM server time)
* **Range:** 0–23 (24-hour format)
* **Timezone:** Broker server time (usually GMT/UTC+2/UTC+3)

**How it works:**

```
CancelPendingsAtSessionClose = true
PendingCancelHour = 20 (8:00 PM)

Throughout the day:
- Multiple pending orders may accumulate
- Market conditions change

At 8:00 PM server time:
- ALL pending orders cancelled
- Clean slate for next session
- Fresh signals only
```

**Session-specific configurations:**

| Trading Style        | Cancel Hour | Reasoning                          |
| -------------------- | ----------- | ---------------------------------- |
| **European Session** | 16-17       | End of London session              |
| **US Session**       | 20-21       | End of New York session            |
| **Asian Session**    | 8-9         | End of Tokyo/Sydney session        |
| **Multi-Session**    | 23-0        | Daily reset at midnight            |
| **DAX Trading**      | 17          | DAX closes at 5:30 PM (clear by 5) |
| **Forex 24h**        | 23          | End of trading day                 |

**Real-world example:**

```
DAX M5 Trading:
CancelPendingsAtSessionClose = true
PendingCancelHour = 17 (5:00 PM)

Scenario:
10:00 → Pending BUY order placed
15:00 → Pending SELL order placed
17:00 → Both orders CANCELLED (DAX session over)
18:00 → Fresh start for next trading day
```

**Advantages:**

* ✅ Clean daily reset
* ✅ Prevents overnight pending orders
* ✅ Session-specific risk management
* ✅ No stale orders accumulation

**Disadvantages:**

* ❌ Cancels potentially good entries
* ❌ Requires correct broker timezone knowledge
* ❌ May not suit 24-hour strategies

**Best for:**

* Session traders (European/US/Asian specific)
* Index trading (DAX, NAS100 with specific hours)
* Prop firm challenges (daily reset)
* Conservative risk management

**When to enable:**

* Trading specific sessions only
* Don't want overnight pending orders
* Prop firm rules require daily closure

**When to disable (default):**

* 24-hour Forex trading
* Multi-session strategies
* Using other expiry methods

***

## Combined Methods Strategy

### Using Multiple Expiry Methods Together

**BananaEA allows combining all 5 methods for comprehensive pending order management:**

**Conservative approach (recommended):**

```
UseCancelAfterBars = true
CancelAfterBars = 5                    // 5 bars maximum age

CancelOnOppositeSignal = true          // Cancel on reversal

CancelOnEMACrossover = false           // Not using MA filter
CancelPendingsAtSessionClose = false   // 24-hour trading

Result:
- Orders expire after 5 bars OR
- Orders cancelled on opposite signal (whichever comes first)
- Smart time-based + pattern-based protection
```

**Aggressive MA-based approach:**

```
UseCancelAfterBars = true
CancelAfterBars = 10                   // Longer patience

CancelOnOppositeSignal = true          // Cancel on reversal
CancelOnEMACrossover = true            // Cancel on MA cross

CancelPendingsAtSessionClose = false

Result:
- Orders expire after 10 bars OR
- Opposite signal OR
- EMA crossover (whichever comes first)
- Triple-layer protection
```

**Session-specific approach:**

```
UseCancelAfterBars = true
CancelAfterBars = 8

CancelOnOppositeSignal = true
CancelOnEMACrossover = false

CancelPendingsAtSessionClose = true
PendingCancelHour = 17                 // End of session

Result:
- Orders expire after 8 bars OR
- Opposite signal OR
- 5:00 PM session close (whichever comes first)
- Perfect for DAX/index session trading
```

***

## Best Practices

### Choosing Expiry Settings

**For scalping (M1-M5):**

```
UseCancelAfterBars = true
CancelAfterBars = 5-10              // Quick expiry
CancelOnOppositeSignal = true       // Pattern-based
CancelOnEMACrossover = false        // Too much lag
CancelPendingsAtSessionClose = false
```

**For day trading (M15-H1):**

```
UseCancelAfterBars = true
CancelAfterBars = 3-6               // Medium expiry
CancelOnOppositeSignal = true
CancelOnEMACrossover = true         // If using MA filter
CancelPendingsAtSessionClose = false
```

**For swing trading (H4-D1):**

```
UseCancelAfterBars = true
CancelAfterBars = 2-3               // Longer valid time
CancelOnOppositeSignal = true
CancelOnEMACrossover = true
CancelPendingsAtSessionClose = false
```

**For session-specific trading:**

```
UseCancelAfterBars = true
CancelAfterBars = 5
CancelOnOppositeSignal = true
CancelOnEMACrossover = false
CancelPendingsAtSessionClose = true
PendingCancelHour = 17              // Session end
```

***

## Troubleshooting

### Issue: Orders Cancel Too Quickly

**Check:**

1. **CancelAfterBars too low**
   * Solution: Increase to 8-10 bars
   * Test: Monitor how long signals remain valid
2. **CancelOnOppositeSignal too sensitive**
   * Solution: Review signal quality (choppy markets?)
   * Consider: Disable in ranging markets
3. **CancelOnEMACrossover triggers frequently**
   * Solution: Use slower MA periods
   * Or disable if not MA-based strategy

### Issue: Too Many Pending Orders Accumulate

**Check:**

1. **CancelAfterBars too high**
   * Solution: Reduce to 5-7 bars
   * Risk: Old signals remain active too long
2. **No expiry methods enabled**
   * Solution: Enable UseCancelAfterBars = true
   * Minimum: Use bar count expiry
3. **Session close not configured**
   * Solution: Enable CancelPendingsAtSessionClose
   * Set appropriate PendingCancelHour

### Issue: Good Entries Being Cancelled

**Check:**

1. **Multiple expiry methods conflicting**
   * Solution: Disable least important method
   * Keep: Bar count + Opposite signal (minimum)
2. **CancelAfterBars too aggressive**
   * Solution: Increase bar count
   * Allow: More time for price to reach entry
3. **EMA crossover too quick**
   * Solution: Disable CancelOnEMACrossover
   * Or use longer MA periods

***

## Related Settings

* [**Signal Configuration**](https://itradeaims.gitbook.io/banana-ea/complete-user-guide/settings-guide/signal-configuration) — Order entry buffers and signal types
* [**Trading Hours & Filters**](https://github.com/itradeaims/bananaEA-dev/blob/dev/gitbook/complete-user-guide/settings-guide/trading-hours-filters.md) — Session filtering and EMA configuration
* [**General Settings**](https://itradeaims.gitbook.io/banana-ea/complete-user-guide/settings-guide/general-settings) — OrderType (pending vs market orders)

***

## Quick Reference

### Pending Order Expiry Parameters

| Parameter                      | Default | Purpose                            |
| ------------------------------ | ------- | ---------------------------------- |
| `UseCancelAfterBars`           | true    | Enable bar count expiry            |
| `CancelAfterBars`              | 5 bars  | Number of bars before cancellation |
| `CancelOnOppositeSignal`       | true    | Cancel on reverse signal           |
| `CancelOnEMACrossover`         | false   | Cancel on MA trend change          |
| `CancelPendingsAtSessionClose` | false   | Cancel at specific hour            |
| `PendingCancelHour`            | 20      | Hour for daily cancellation (0-23) |

### Recommended Starter Configuration

```
// Conservative pending order management (BananaEA default)
UseCancelAfterBars = true
CancelAfterBars = 5                    // 5 bars expiry (M5 = 25 minutes)

CancelOnOppositeSignal = true          // Smart pattern-based cancellation

CancelOnEMACrossover = false           // Disabled (not using MA filter)

CancelPendingsAtSessionClose = false   // Disabled (24-hour trading)
PendingCancelHour = 20                 // Not used (session close disabled)

Result:
- Pending orders cancelled after 5 bars OR on opposite signal
- Simple, effective, works for most strategies
- Prevents stale orders without over-cancellation
```

**💡 Download optimized pending order settings:** <https://my.itradeaims.net/latest-optimization-sets/>
