PIPSBUNNY GOLD SCALPER 1.0 (MQL5 source version 1.000)
====================================================
NEW, SEPARATE ROBOT. Demo-first; no performance claims.

WHAT IT DOES
Gold impulse scalper for XAUUSDm (Exness) / GOLD (XM) and related gold symbols.
Uses M1 internally even if attached to another chart period. Attach to M1.
Default 3 separate trades per signal; configurable 3 to 10 (choose 4 if preferred).
Only one batch active. Other account positions/pending orders block new entries.
Requires USD-denominated HEDGING account, not ZAR or a cent account.
The bot has no website/API dependency and sends no data to an external service.

This is directional impulse trading, not two-sided market making or exchange HFT.
No actual order book, aggressor-volume feed or institutional order-flow feed is used.
Gold quote ticks are proxies and may differ substantially between brokers.
Sequential synchronous market requests are used. No microsecond latency promise.

EXACT SIGNAL (checked on incoming ticks in EVERY eligible M1 candle)
- Wait at least 10 seconds into current M1 candle.
- Current body >= 0.35 * completed M1 ATR(14) * sensitivity.
- Body >= 65% of current candle range.
- Current tick-volume-per-second >= 1.5 * sensitivity * mean tick rate
  across the previous 20 completed M1 candles.
- Last approximately 10 seconds of broker bid-price ticks: at least 8 directional
  changes and (up changes - down changes)/(up changes + down changes) >= 0.60
  for BUY, <= -0.60 for SELL. Flat quotes do not count as directional changes.
- Body and tick direction must agree. No signal means no trade.
- No immediate entry on attachment; wait for next M1 candle.
- Spread, risk, margin and permissions are checked before each child order.
- Maximum one attempted batch per candle; failed/partial batches are never topped up.

THREE-CANDLE EXIT
The ENTRY CANDLE is candle 1, even when entered partway through it.
Example: entry at 12:00:20 -> candle 1 ends 12:01, candle 2 ends 12:02,
candle 3 ends 12:03. Close at first available tick at/after 12:03.
This is approximately 2-3 minutes, NOT three full minutes after entry.
No new batch in the candle in which the old batch finishes. In the example,
new signal assessment resumes at 12:04. Failed closes retry on subsequent ticks.
Counts actual M1 bars via history, not wall-clock minutes during market closures.
No ticks, no connection or disabled Algo Trading can delay software exits.
Broker-side stop losses remain attached; optional monetary TP is software-managed.

DEFAULT INPUTS
AllowLiveTrading = false (keep false for demo testing)
LotSize = 0.01: MAXIMUM per child, automatically reduced to fit risk.
TradesPerSignal = 3: choose 4 or up to 10. This is the TradesPerEntry setting
  from your specification, using one name to avoid conflicting duplicate inputs.
HoldDurationCandles = 3 (can choose 4)
StopLossInUSD = 3.00
RiskPerTrade = false: $3 estimated total batch risk, split among children.
  With 3 children: $1 each. With 4: $0.75 each. With 10: $0.30 each.
  true: $3 EACH, so 3 children target $9 and 10 children target $30 total.
TakeProfitInUSD = 0: disabled. Positive value is net TOTAL batch profit target.
ImpulseSensitivityThreshold = 1.0: higher needs stronger impulse/activity.
MaxSpreadPips = 5.0
MaxSlippagePips = 2.0
PipSize = 0.10: ONE pip is explicitly 0.10 in gold PRICE, independent of digits.
  Thus 5 spread pips = 0.50 price spread; 2 slippage pips = 0.20 price distance.
  Check your broker's convention before changing this.
StopATR = 1.0
CostReserveUSDPerLot = 10.0: assumed ROUND-TRIP commission/fee reserve per 1 lot.
  Set to match broker costs; this is an estimate, not a broker fee quote.
Magic = 26102010 (keep unchanged while trades exist)

RISK IMPLEMENTATION AND LIMITS
Each order has a broker-side SL at least one completed-bar ATR away, expanded
when broker minimum stop distance/spread requires it. Stops rounded outward to
valid tick size. Volume rounded down to broker step and capped by LotSize.
OrderCalcProfit estimates loss using adverse slippage allowance, plus fee reserve.
Minimum volume above risk budget -> skip; NEVER round volume up to force trades.
Remaining batch margin must fit within 80% of current free margin.
Actual confirmed fills checked against their allocated stop budget; excess risk
triggers batch closure. Software also closes on combined realized + unrealized
batch loss of configured batch budget, or positive optional net batch TP.
A realized stopped-out child still counts toward batch P&L. Commission, fees and
swap assigned to this symbol/magic are included where reported in deal history.
Broker standalone fee adjustments without symbol/magic may not be attributed.
No exact $3 maximum is guaranteed: gaps, slippage, commission differences,
latency and outages can cause a larger loss. Market-execution brokers may ignore
requested deviation. Do not confuse estimated stop risk with a guaranteed cap.
On a $10 account $3 is 30% of starting funds; many entries will be unaffordable.

INSTALL ON WINDOWS MT5
1. Extract this entire ZIP first.
2. MT5 -> File -> Open Data Folder -> MQL5 -> Experts.
3. Create folder PIPSBUNNY_GOLD. Copy PIPSBUNNY_GOLD_SCALPER.mq5 AND
   ImpulseRules.mqh into that SAME folder.
4. Press F4 (MetaEditor), open the .mq5 file and press F7 to compile.
   This package contains source, NOT a precompiled .ex5 file.
5. On a USD hedging DEMO account open XAUUSDm or GOLD, timeframe M1.
6. Remove the old EA from that chart. Use one PIPSBUNNY instance only.
7. Attach new EA. Keep AllowLiveTrading=false. Allow Algo Trading in EA settings
   and turn the terminal's Algo Trading button on. No DLLs or WebRequest needed.
8. Keep PC awake, MT5 open and internet connected. Website/Android cannot execute
   this EA. Android MT5 can monitor the same account while the PC runs it.

TEST BEFORE CONSIDERING LIVE
First compile in MetaEditor. Then Ctrl+R -> Strategy Tester -> this EA -> gold/M1,
'Every tick based on real ticks', USD hedging environment, realistic deposit,
spread, commission and execution delay. Use broker tick history. Test both
trending and choppy periods and forward-test on demo. OHLC-only tests are not
suitable for this intrabar strategy. Check Trade, History and Experts tabs.
Verify BUY/SELL signals, batch counts, first-tick three-candle closes, failed
orders, disconnect recovery, and restart with open positions. No live release
or profitability claim is made by the included source-level tests.

RECOVERY / DIAGNOSTICS
Read chart status and Experts log. Common reasons: no qualifying impulse,
spread too wide, minimum lot too risky, low margin, other exposure, permissions.
After ANY failed/partial/uncertain market-order result, new entries HALT. Existing
owned positions continue to be managed. Check Trade AND History, confirm there
are no unresolved broker orders, and close/reconcile any remaining positions.
Only when fully flat: remove EA, press F3 (terminal Global Variables), locate
PBG.<account>.<symbol>.<magic>.halt and set it to 0, then reattach.
A terminal crash may leave .lock nonzero. Confirm no other chart is running this
EA, then set only .lock to 0 and reattach to recover batch management.
Do not erase .bar/.start/.hold/.risk/.target/.exit while positions exist.
Batch timing/risk/exit state survives normal EA reattachment in the same terminal.
Changing terminal, magic or deleting global state loses recovery metadata:
owned positions with missing state are closed when possible. Do not run the same
magic from different terminals: instance lock is terminal-local, not broker-wide.
Positions from other EAs/manual trading are not closed by this EA.

VALIDATION INCLUDED
22 tests run against the SAME pure signal/duration/budget predicates included by
the EA. These cover bull/bear symmetry, weak/conflicting ticks, body and activity
thresholds, invalid data, 3/4-candle boundaries and per-batch/per-trade budgets.
MetaEditor compilation, broker execution and performance backtests have NOT been
run in this environment. Source review/tests do not establish trading readiness.

Primary API references:
https://www.mql5.com/en/docs/trading/ordercalcprofit
https://www.mql5.com/en/docs/series/copyticks
https://www.mql5.com/en/docs/standardlibrary/tradeclasses/ctrade
