# Order Splitting Modules for MQL5

This folder contains two reusable MQL5 order splitting modules:

- `OrderSplitting_Simple.mqh`
- `OrderSplitting_Advanced.mqh`

Both modules split one normal strategy entry into several smaller positions. Position 1 is opened by your strategy as normal. The module then opens positions 2 through N after a configurable delay. When position 1 closes for a non-SL reason, the module closes the remaining split positions sequentially.

The goal is to reduce immediate market impact and make larger position sizes more practical. The trade-off is that delayed entries may produce a worse average entry if price moves against you before all split legs are filled.

## Which Version Should You Use?

### Simple Version

Use `OrderSplitting_Simple.mqh` when:

- your EA uses market orders
- your EA trades one symbol per chart
- your EA has one long entry path and one short entry path
- you want the easiest version to understand and install
- you do not need pending-order support

This is the best version for most public users.

It includes:

- symbol-aware lot alignment
- broker-aware filling mode selection
- open/close retcode logging
- separate entry and close timers
- optional split EOD close
- clean include-style installation

### Advanced Version

Use `OrderSplitting_Advanced.mqh` when:

- your EA uses pending orders
- you want stronger ticket and position tracking
- you want a stuck-chain failsafe
- you want the module to force-close remaining split legs if pos1 hits SL
- you are comfortable integrating slightly more code

It includes everything in the simple version, plus:

- pending-order registration
- pending-to-position fallback detection
- position identifier tracking
- force-close cleanup after pos1 SL
- `SplitChainTimeout`

The advanced version is better for production use, but the simple version is easier for beginners.

## Important Assumptions

These modules are designed for:

- MQL5 Expert Advisors
- hedging accounts where each split leg can exist as its own position
- single-symbol chart EAs
- one active long split chain and one active short split chain at a time

If your EA trades multiple symbols from one chart, has several independent buy/sell gates, or runs on a netting account, you should adapt the state arrays by symbol, magic number, or entry gate.

## What The Inputs Mean

The simple version uses `OS_` input names. The advanced version uses `OSA_` input names.

Common inputs:

- `UseSplitEntry`: turns order splitting on or off.
- `SplitCount`: total number of positions. `1` means no split. `3` means pos1 plus two extra split legs.
- `SplitDelaySeconds`: delay between each split entry and each split close.
- `SplitSlippagePoints`: maximum allowed deviation for split orders, in points.
- `UseSplitEODClose`: enables time-based split closes.
- `EODCloseTimeSplits`: time to close positions 2 through N.
- `EODCloseTimePos1`: time to close position 1.
- `MagicNumber`: magic number used by split orders.

Advanced-only input:

- `SplitChainTimeout`: number of seconds before the module force-closes remaining split legs if a close chain gets stuck. `0` disables the timeout.

## How It Works Behind The Scenes

1. Your strategy calculates its normal full lot size.
2. The module divides that lot size by `SplitCount`.
3. Your strategy opens position 1 using its normal entry logic.
4. You register that first ticket with the module.
5. On each tick, the module waits for `SplitDelaySeconds`.
6. It opens the next split leg at market with the same SL and no TP.
7. Positions 2 through N do not have their own TP.
8. Position 1 remains the controlling trade.
9. If position 1 closes by TP, manual close, EOD close, or another non-SL reason, the module closes the remaining split positions in sequence.
10. If position 1 closes by SL, the simple version resets the chain; the advanced version also tries to close any remaining split legs.

## Manual Installation: Simple Version

### 1. Add the include

Put `OrderSplitting_Simple.mqh` beside your EA or inside your MetaTrader `MQL5/Include` folder.

Near the top of your EA, add:

```mql5
#include "OrderSplitting_Simple.mqh"
```

### 2. Initialise the module

Inside your EA's `OnInit()`:

```mql5
OS_Init();
```

Example:

```mql5
int OnInit()
{
   OS_Init();
   return INIT_SUCCEEDED;
}
```

### 3. Run the manager every tick

Inside `OnTick()`, before new entry logic:

```mql5
OS_Manage();
```

Do not wrap this in day/month/spread filters. The manager must keep running so it can close and clean up existing split positions.

### 4. Adjust the lot size before entry

Where your EA calculates the normal lot size, pass it through:

```mql5
lots = OS_AdjustLots(lots);
```

This turns one full-size trade into one split-sized trade.

### 5. Register the first opened position

After a buy order opens:

```mql5
if(ticket > 0 && OS_UseSplitEntry)
   OS_RegisterLong((ulong)ticket);
```

After a sell order opens:

```mql5
if(ticket > 0 && OS_UseSplitEntry)
   OS_RegisterShort((ulong)ticket);
```

The `ticket` must be the position ticket returned by your EA's order open logic.

## Manual Installation: Advanced Version

### 1. Add the include

Put `OrderSplitting_Advanced.mqh` beside your EA or inside your MetaTrader `MQL5/Include` folder.

Near the top of your EA, add:

```mql5
#include "OrderSplitting_Advanced.mqh"
```

### 2. Initialise the module

Inside `OnInit()`:

```mql5
OSA_Init();
```

### 3. Run the manager every tick

Inside `OnTick()`, before new entry logic:

```mql5
OSA_Manage();
```

### 4. Adjust the lot size before entry

Before sending the first order:

```mql5
lots = OSA_AdjustLots(lots);
```

### 5. Register market entries

After a buy market position opens:

```mql5
if(ticket > 0 && OSA_UseSplitEntry)
   OSA_RegisterMarketLong((ulong)ticket);
```

After a sell market position opens:

```mql5
if(ticket > 0 && OSA_UseSplitEntry)
   OSA_RegisterMarketShort((ulong)ticket);
```

### 6. Register pending entries

After placing a buy pending order:

```mql5
if(orderTicket > 0 && OSA_UseSplitEntry)
   OSA_RegisterPendingLong((ulong)orderTicket, sl, lots);
```

After placing a sell pending order:

```mql5
if(orderTicket > 0 && OSA_UseSplitEntry)
   OSA_RegisterPendingShort((ulong)orderTicket, sl, lots);
```

For pending entries, `sl` should be the stop-loss price level and `lots` should already be the split-adjusted lot size.

## Adding It With An AI Agent

You can also hand the module and these instructions to an AI coding agent and ask it to integrate the code into your EA.

A good prompt is:

```text
Please integrate OrderSplitting_Advanced.mqh into this MQL5 EA.

Requirements:
- include the module
- call OSA_Init() from OnInit()
- call OSA_Manage() early in OnTick(), before new entries
- pass the strategy lot size through OSA_AdjustLots() before entry orders
- register buy market entries with OSA_RegisterMarketLong(ticket)
- register sell market entries with OSA_RegisterMarketShort(ticket)
- if the EA uses pending orders, register them with OSA_RegisterPendingLong/Short(orderTicket, sl, lots)
- do not wrap OSA_Manage() inside entry filters
- preserve all existing strategy logic
```

For a simpler market-order-only EA, replace `Advanced` / `OSA_` with `Simple` / `OS_`.

AI integration should work well because the modules expose a small set of functions and avoid requiring users to paste large blocks into several places manually. You should still compile the EA in MetaEditor and run a backtest or demo test after any automated edit.

## Pros

- Reduces immediate market impact.
- Can increase practical capacity.
- Avoids sending one large visible ticket.
- Keeps the original strategy entry as the controlling position.
- Lets split exits happen gradually instead of all at once.

## Cons

- Average entry can be worse if price moves against you during the delay.
- Split legs may fill at different prices.
- More orders means more execution points and more possible broker rejections.
- Tick timing can make backtest and live behaviour differ.
- Restarting the EA can lose in-memory split state.
- Multi-symbol and multi-gate strategies need extra adaptation.

## Safety Notes

- Test on a demo account before using live.
- Use a hedging account where possible.
- Make sure your broker allows multiple positions on the same symbol.
- Check that your minimum lot size supports your chosen `SplitCount`.
- Do not use very high `SplitDelaySeconds` unless you accept the extra entry drift.
- Keep `SplitCount` practical. More splits are not always better.
- If your EA has a global close-all function, make sure it does not accidentally bulk-close split positions 2 through N before the split manager handles them.

## Compile Status

Both modules were compile-tested with MetaEditor64 using small harness EAs:

- `OrderSplitting_Simple.mqh`: 0 errors, 0 warnings
- `OrderSplitting_Advanced.mqh`: 0 errors, 0 warnings

Compile success does not replace strategy testing. Always test the final EA after integration.
