Consolidate Python ignore rules into root gitignore
This commit is contained in:
@@ -0,0 +1,199 @@
|
||||
# HIT-EA Specification (English)
|
||||
|
||||
## 1. Overview
|
||||
|
||||
- This EA sends confirmed H4 OHLC data to an external Python process for market-state analysis and confirmed H1 OHLC data for entry candidate generation.
|
||||
- The MQL5 side reads Python output files and places pending orders only after checking the H4 market state, H1 candidate prices, M15 confirmation filter, spread, and broker distance constraints.
|
||||
- For backtest reproducibility, OHLC export uses `OHLC_START_SHIFT = 1`, so the forming bar is excluded and only closed bars are passed to Python.
|
||||
- For live resilience, the EA tracks external-process running files, process IDs, exit codes, and timeouts to prevent duplicate launches and CSV overwrites.
|
||||
|
||||
## 2. Indicators
|
||||
|
||||
- No standard or custom indicators are used.
|
||||
- OHLC data is retrieved with `CopyRates(_Symbol, timeframe, OHLC_START_SHIFT, HISTORY_BARS, rates)`.
|
||||
- M15 entry confirmation uses the latest closed bar, the previous closed bar, average range, candle direction, rejection shape, and distance to the candidate entry price.
|
||||
|
||||
## 3. Parameters
|
||||
|
||||
### input
|
||||
|
||||
- `lot_size = 0.01`: Order volume.
|
||||
- `spread_limit = 60`: Maximum allowed spread in points.
|
||||
- `magic_number = 10001`: Magic number used to identify this EA's orders and positions.
|
||||
- `initial_order = 0`: Enables initial H4/H1 processing on startup when set to `1`.
|
||||
- `use_m15_entry_filter = true`: Enables M15 closed-bar entry timing confirmation.
|
||||
- `m15_entry_zone_atr_multiplier = 1.50`: Allowed proximity multiplier based on the M15 average range.
|
||||
- `use_m15_imbalance_confirmation = true`: Adds M15 impulse confirmation for T1/T3 trend-following candidates.
|
||||
- `m15_imbalance_avg_body_period = 20`: Average-body period used by M15 impulse confirmation.
|
||||
- `m15_imbalance_sensitivity = 2.0`: Required multiple of the average body for M15 impulse confirmation.
|
||||
- `m15_imbalance_min_avg_body_points = 1.0`: Minimum M15 average body in points.
|
||||
- `use_m15_imbalance_debug_log = false`: Enables detailed M15 impulse-confirmation logs.
|
||||
- `input_entry_max_candidate_age_minutes = 45`: Maximum age, in minutes, for using an H1 candidate for new execution. This blocks delayed entries when M15 confirmation appears too late.
|
||||
- `input_sltp_manager_enabled = false`: Enables UI-driven existing-position SL management through `CSLTPManager`.
|
||||
- `input_sltp_show_panel = true`: Shows the SLTP control panel on the chart.
|
||||
- `input_sltp_use_breakeven = false`: Enables normal break-even.
|
||||
- `input_sltp_breakeven_trigger_pips = 30.0`: Profit threshold for normal break-even.
|
||||
- `input_sltp_breakeven_buffer_pips = 0.0`: Profit-side entry buffer used by normal break-even.
|
||||
- `input_sltp_use_elapsed_breakeven = false`: Enables elapsed-time break-even.
|
||||
- `input_sltp_elapsed_breakeven_hours = 4.0`: Holding time required before elapsed-time break-even is allowed.
|
||||
- `input_sltp_elapsed_breakeven_buffer_pips = 0.0`: Profit-side entry buffer used by elapsed-time break-even.
|
||||
- `input_sltp_use_active_trailing = false`: Enables active step trailing.
|
||||
- `input_sltp_active_breakeven_pips = 30.0`: Profit threshold that starts active trailing.
|
||||
- `input_sltp_active_stop_loss_offset_pips = 5.0`: Initial locked profit offset from entry.
|
||||
- `input_sltp_active_step_trigger_pips = 10.0`: Additional profit interval required for each SL step.
|
||||
- `input_sltp_active_step_move_pips = 5.0`: SL movement added per completed step.
|
||||
- `input_sltp_use_tp_progress_stop = false`: Enables TP-progress-based SL locking.
|
||||
- `input_sltp_tp_progress_trigger_percent = 70.0`: TP progress required before the SL lock is applied.
|
||||
- `input_sltp_tp_progress_sl_lock_percent = 30.0`: Entry-to-TP distance percentage locked by SL.
|
||||
- `input_sltp_use_high_volatility_limit = false`: Enables short-term high-volatility SL tightening.
|
||||
|
||||
### Main Constants
|
||||
|
||||
- `POSITION_LIMIT = 48`: Maximum number of this EA's pending orders plus positions.
|
||||
- `ENTRY_H1_LIMIT = 1`: Pending-order lifetime in H1 bars.
|
||||
- `CLOSE_H1_LIMIT = 12`: Position lifetime in H1 bars.
|
||||
- `HISTORY_BARS = 72`: Number of OHLC bars exported to Python.
|
||||
- `OHLC_START_SHIFT = 1`: Shift used to export closed bars only.
|
||||
- `M15_CONFIRM_BARS = 30`: Number of M15 bars used for average-range calculation.
|
||||
- `ENTRY_RETRY_SECONDS = 60`: Retry interval for entry checks.
|
||||
- `ENTRY_RETRY_LIMIT = 10`: Maximum retry count for one H1 candidate set.
|
||||
- `TARGET_SIZE = 13`: Number of numeric values expected in `target_prices.txt`.
|
||||
- `PYTHON_TIMEOUT_SECONDS = 600`: External Python wait threshold.
|
||||
|
||||
### Python Entry-Candidate Guard
|
||||
|
||||
- After H1 candidate generation, Python invalidates any `entry` that is too far from the current price.
|
||||
- The maximum distance is `max(H1 EATR * 0.65, 5.00)`. A strategy beyond that limit is rewritten to `0.00,0.00,0.00`.
|
||||
- This post-filter is intended to reduce delayed entries from deep limit orders or distant breakout waits after M15 confirmation arrives late.
|
||||
|
||||
## 4. File Layout
|
||||
|
||||
- `Experts/MyProject/HIT-EA_refactor_ver5.mq5`: EA entry point. Keeps `OnInit`, `OnDeinit`, `OnTick`, inputs, global state, and DLL imports.
|
||||
- `Include/MyLib/Common/HITRuntimeController.mqh`: Tick flow, H4/H1/M15 update control, status comments, and spread checks.
|
||||
- `Include/MyLib/Signals/HITEntrySignal.mqh`: Entry preconditions, order-type price validation, M15 filter, and retry-state updates.
|
||||
- `Include/MyLib/Common/HITExternalProcess.mqh`: done/running files, external process handles, PID recovery, exit-code checks, and timeout recovery.
|
||||
- `Include/MyLib/Signals/HITPythonSignalGateway.mqh`: OHLC CSV export, Python batch launch, and `trend_state.txt` / `target_prices.txt` loading.
|
||||
- `Include/MyLib/Trading/HITTradeManager.mqh`: Order sending, filling policy, pending-order expiration, order/position counting, expired order cancellation, and expired position closing.
|
||||
- `Include/MyLib/Trading/SLTPManager.mqh`: Existing-position break-even, elapsed-time break-even, active trailing, TP-progress SL, and high-volatility SL management.
|
||||
- `Include/MyLib/Panel/SLTPManagerPanel.mqh`: Chart panel that toggles `CSLTPManager` features, validates numeric inputs, and applies settings to the EA.
|
||||
|
||||
## 5. Python Integration Files
|
||||
|
||||
### H4 Trend Analysis
|
||||
|
||||
- MQL5 output: `ohlc_H4.csv`
|
||||
- Python output: `trend_state.txt`
|
||||
- Done marker: `process_done_trend.txt`
|
||||
- Running marker: `process_running_trend.txt`
|
||||
- Batch file: `C:\ea_py\bat\get_trend_reply.bat`
|
||||
|
||||
### H1 Entry Candidate Generation
|
||||
|
||||
- MQL5 output: `ohlc_H1.csv`
|
||||
- Python output: `target_prices.txt`
|
||||
- Done marker: `process_done_entry.txt`
|
||||
- Running marker: `process_running_entry.txt`
|
||||
- Batch file: `C:\ea_py\bat\get_entry_reply.bat`
|
||||
|
||||
`target_prices.txt` must contain 13 lines:
|
||||
|
||||
```text
|
||||
Line 1: res_chk
|
||||
Lines 2-4: T1 Buy Stop entry/tp/sl
|
||||
Lines 5-7: T2 Buy Limit entry/tp/sl
|
||||
Lines 8-10: T3 Sell Stop entry/tp/sl
|
||||
Lines 11-13: T4 Sell Limit entry/tp/sl
|
||||
```
|
||||
|
||||
## 6. Entry Conditions
|
||||
|
||||
New entries are allowed only when all conditions below are satisfied:
|
||||
|
||||
- Spread is less than or equal to `spread_limit`.
|
||||
- H4 trend analysis is complete and `trend_state.txt` can be loaded.
|
||||
- H1 entry candidate generation is complete and `target_prices.txt` can be loaded.
|
||||
- `res_chk = 1`.
|
||||
- The H1 candidate set has not expired under `ENTRY_H1_LIMIT`.
|
||||
- The H1 candidate set has not exceeded `input_entry_max_candidate_age_minutes` since it was loaded.
|
||||
- The selected order type has valid `entry/tp/sl` values greater than `0.0`.
|
||||
- The order type is allowed by the H4 `market_state`.
|
||||
- The order-type price relationship and broker minimum distance rules are satisfied.
|
||||
- When `use_m15_entry_filter = true`, the M15 closed-bar timing confirmation is satisfied.
|
||||
- This EA's pending orders plus positions are below `POSITION_LIMIT`.
|
||||
|
||||
### market_state and Allowed Order Types
|
||||
|
||||
- `0 MARKET_LOW_VOL_RANGE`: Allows T2 Buy Limit / T4 Sell Limit.
|
||||
- `1 MARKET_HIGH_VOL_RANGE`: Allows T2 Buy Limit / T4 Sell Limit.
|
||||
- `2 MARKET_LOW_VOL_UP`: Allows T1 Buy Stop / T2 Buy Limit.
|
||||
- `3 MARKET_HIGH_VOL_UP`: Allows T1 Buy Stop / T2 Buy Limit.
|
||||
- `4 MARKET_LOW_VOL_DOWN`: Allows T3 Sell Stop / T4 Sell Limit.
|
||||
- `5 MARKET_HIGH_VOL_DOWN`: Allows T3 Sell Stop / T4 Sell Limit.
|
||||
- `6 MARKET_ABNORMAL_VOL_STOP`: Blocks new entries.
|
||||
|
||||
### Order-Type Price Rules
|
||||
|
||||
- T1 Buy Stop: `Ask < entry`, `tp > entry`, `sl < entry`
|
||||
- T2 Buy Limit: `Ask > entry`, `tp > entry`, `sl < entry`
|
||||
- T3 Sell Stop: `Bid > entry`, `tp < entry`, `sl > entry`
|
||||
- T4 Sell Limit: `Bid < entry`, `tp < entry`, `sl > entry`
|
||||
|
||||
## 7. Exit Conditions
|
||||
|
||||
- Pending orders are cancelled after `ENTRY_H1_LIMIT * PeriodSeconds(PERIOD_H1)` has elapsed from setup time.
|
||||
- Positions are closed after `CLOSE_H1_LIMIT * PeriodSeconds(PERIOD_H1)` has elapsed from entry time.
|
||||
- Time-limit handling runs early in `OnTick` and is independent of Python readiness or spread checks.
|
||||
- On EA removal, `OnDeinit()` releases external-process state and the SLTP panel, then clears the chart status text with `Comment("")` and `ChartRedraw(0)`.
|
||||
- When `input_sltp_manager_enabled` or the panel `Manager` toggle is ON, the EA runs `CSLTPManager::ManagePositions()` and `HighVolatilityLimit()` after time-limit handling. Existing-position SL protection therefore continues while Python results are pending or new entries are skipped.
|
||||
- Normal break-even and active trailing are mutually exclusive. The panel turns one mode off when the other is enabled, and `CSLTPManager::ValidateSettings()` also validates the exclusion.
|
||||
|
||||
## 7.1 SLTP Control Panel
|
||||
|
||||
- The panel is created when `input_sltp_show_panel = true` and appears near the chart's upper-right area.
|
||||
- If panel creation fails, the EA logs the failure and continues with the already-applied input-based SLTP settings.
|
||||
- The `Manager` button toggles all SLTP management. When OFF, panel values remain stored but `OnTick` does not modify SL values.
|
||||
- The `BreakEven`, `Elapsed BE`, `Active Trail`, `TP Progress`, and `High Vol` buttons toggle each `CSLTPManager` feature.
|
||||
- Numeric fields are validated when `APPLY` is pressed. Invalid or out-of-range values show a `MessageBox`, are logged, and revert to the previous valid value.
|
||||
- Settings are copied into `CSLTPManager` only after `APPLY` succeeds. The EA then calls `ValidateSettings()`; if validation fails, SLTP management is stopped and the reason is logged.
|
||||
|
||||
## 8. Risk Management
|
||||
|
||||
- Managed orders and positions are limited to matching `_Symbol` and `magic_number`.
|
||||
- `POSITION_LIMIT` counts only this EA's orders and positions, not the full account.
|
||||
- The EA selects the filling policy from `SYMBOL_FILLING_MODE`, preferring IOC, then FOK, then RETURN.
|
||||
- Pending orders receive server-side expiration when the broker supports it.
|
||||
- `OrderSend` return values and `MqlTradeResult.retcode` are checked. Failures are logged with `GetLastError()` or the retcode.
|
||||
- SLTP management only targets existing positions matching `_Symbol` and `magic_number`, and it preserves each position's current TP.
|
||||
- SL changes are sent only when the candidate improves protection relative to the current SL and satisfies broker stop-level and freeze-level constraints.
|
||||
|
||||
## 9. Error Handling
|
||||
|
||||
- If `trend_state.txt` is missing, unreadable, or outside `0..6`, the EA uses `MARKET_ABNORMAL_VOL_STOP`.
|
||||
- If `target_prices.txt` is missing, unreadable, or shorter than 13 lines, the EA uses `res_chk = 0`.
|
||||
- If a Python process exits with a non-zero code, the code is logged and the next trigger may retry.
|
||||
- If only a stale running marker remains, the EA attempts PID recovery. If recovery fails and the marker is timed out, it removes the stale marker.
|
||||
|
||||
## 10. Changelog
|
||||
|
||||
### 2026-05-13
|
||||
|
||||
- Added a Python-side H1 EATR distance guard that invalidates candidates farther than `max(H1 EATR * 0.65, 5.00)` from the current price before they are passed to MT5.
|
||||
- Added `input_entry_max_candidate_age_minutes = 45` on the EA side so stale H1 candidates are not executed when M15 confirmation arrives late.
|
||||
- Added H1 candidate age to entry skip logs to make delayed entries, M15 rejection, and price mismatch easier to diagnose.
|
||||
|
||||
### 2026-05-05
|
||||
|
||||
- Added `Comment("")` and `ChartRedraw(0)` to `OnDeinit()` so the chart status comment is removed when the EA is deleted.
|
||||
- Connected `CSLTPManager` and the dedicated chart panel `SLTPManagerPanel.mqh` to `HIT-EA_refactor_ver5.mq5`, allowing UI control of break-even, elapsed-time break-even, active trailing, TP-progress SL, and high-volatility SL tightening.
|
||||
- Added SLTP management immediately after time-limit handling in `OnTick`, so existing-position protection continues independently of Python readiness and spread checks.
|
||||
- Added SLTP panel inputs, mutual exclusion for normal break-even versus active trailing, and numeric validation on `APPLY`.
|
||||
- Split the function implementations from `HIT-EA_refactor_ver5.mq5` into purpose-specific `.mqh` files.
|
||||
- Kept `OnInit`, `OnDeinit`, `OnTick`, inputs, and global state in the EA source while moving behavior functions under `Include/MyLib/`.
|
||||
- Updated the specification to match the current `CreateProcessW` Python process tracking, M15 filter, `market_state` range `0..6`, and `spread_limit = 60`.
|
||||
|
||||
### 2026-05-02
|
||||
|
||||
- Added entry suppression when `res_chk = 0`.
|
||||
- Moved time-limit handling before Python readiness and spread checks.
|
||||
- Split startup flags for H4 and H1 initial processing.
|
||||
- Switched OHLC retrieval to `CopyRates` and exported closed bars only.
|
||||
@@ -0,0 +1,180 @@
|
||||
# HIT-EA Specification (English)
|
||||
|
||||
## 1. Overview
|
||||
|
||||
- This EA sends confirmed H4 OHLC data to an external Python process for market-state analysis and confirmed H1 OHLC data for entry candidate generation.
|
||||
- The MQL5 side reads Python output files and places pending orders only after checking the H4 market state, H1 candidate prices, M15 confirmation filter, spread, and broker distance constraints.
|
||||
- For backtest reproducibility, OHLC export uses `OHLC_START_SHIFT = 1`, so the forming bar is excluded and only closed bars are passed to Python.
|
||||
- For live resilience, the EA tracks external-process running files, process IDs, exit codes, and timeouts to prevent duplicate launches and CSV overwrites.
|
||||
|
||||
## 2. Indicators
|
||||
|
||||
- No standard or custom indicators are used.
|
||||
- OHLC data is retrieved with `CopyRates(_Symbol, timeframe, OHLC_START_SHIFT, HISTORY_BARS, rates)`.
|
||||
- M15 entry confirmation uses the latest closed bar, the previous closed bar, average range, candle direction, rejection shape, and distance to the candidate entry price.
|
||||
|
||||
## 3. Parameters
|
||||
|
||||
### input
|
||||
|
||||
- `lot_size = 0.01`: Order volume.
|
||||
- `spread_limit = 60`: Maximum allowed spread in points.
|
||||
- `magic_number = 10001`: Magic number used to identify this EA's orders and positions.
|
||||
- `initial_order = 0`: Enables initial H4/H1 processing on startup when set to `1`.
|
||||
- `use_m15_entry_filter = true`: Enables M15 closed-bar entry timing confirmation.
|
||||
- `m15_entry_zone_atr_multiplier = 1.50`: Allowed proximity multiplier based on the M15 average range.
|
||||
- `input_sltp_manager_enabled = false`: Enables UI-driven existing-position SL management through `CSLTPManager`.
|
||||
- `input_sltp_show_panel = true`: Shows the SLTP control panel on the chart.
|
||||
- `input_sltp_use_breakeven = false`: Enables normal break-even.
|
||||
- `input_sltp_breakeven_trigger_pips = 30.0`: Profit threshold for normal break-even.
|
||||
- `input_sltp_breakeven_buffer_pips = 0.0`: Profit-side entry buffer used by normal break-even.
|
||||
- `input_sltp_use_elapsed_breakeven = false`: Enables elapsed-time break-even.
|
||||
- `input_sltp_elapsed_breakeven_hours = 4.0`: Holding time required before elapsed-time break-even is allowed.
|
||||
- `input_sltp_elapsed_breakeven_buffer_pips = 0.0`: Profit-side entry buffer used by elapsed-time break-even.
|
||||
- `input_sltp_use_active_trailing = false`: Enables active step trailing.
|
||||
- `input_sltp_active_breakeven_pips = 30.0`: Profit threshold that starts active trailing.
|
||||
- `input_sltp_active_stop_loss_offset_pips = 5.0`: Initial locked profit offset from entry.
|
||||
- `input_sltp_active_step_trigger_pips = 10.0`: Additional profit interval required for each SL step.
|
||||
- `input_sltp_active_step_move_pips = 5.0`: SL movement added per completed step.
|
||||
- `input_sltp_use_tp_progress_stop = false`: Enables TP-progress-based SL locking.
|
||||
- `input_sltp_tp_progress_trigger_percent = 70.0`: TP progress required before the SL lock is applied.
|
||||
- `input_sltp_tp_progress_sl_lock_percent = 30.0`: Entry-to-TP distance percentage locked by SL.
|
||||
- `input_sltp_use_high_volatility_limit = false`: Enables short-term high-volatility SL tightening.
|
||||
|
||||
### Main Constants
|
||||
|
||||
- `POSITION_LIMIT = 48`: Maximum number of this EA's pending orders plus positions.
|
||||
- `ENTRY_H1_LIMIT = 1`: Pending-order lifetime in H1 bars.
|
||||
- `CLOSE_H1_LIMIT = 12`: Position lifetime in H1 bars.
|
||||
- `HISTORY_BARS = 72`: Number of OHLC bars exported to Python.
|
||||
- `OHLC_START_SHIFT = 1`: Shift used to export closed bars only.
|
||||
- `M15_CONFIRM_BARS = 20`: Number of M15 bars used for average-range calculation.
|
||||
- `ENTRY_RETRY_SECONDS = 60`: Retry interval for entry checks.
|
||||
- `ENTRY_RETRY_LIMIT = 10`: Maximum retry count for one H1 candidate set.
|
||||
- `TARGET_SIZE = 13`: Number of numeric values expected in `target_prices.txt`.
|
||||
- `PYTHON_TIMEOUT_SECONDS = 600`: External Python wait threshold.
|
||||
|
||||
## 4. File Layout
|
||||
|
||||
- `Experts/MyProject/HIT-EA_refactor_ver5.mq5`: EA entry point. Keeps `OnInit`, `OnDeinit`, `OnTick`, inputs, global state, and DLL imports.
|
||||
- `Include/MyLib/Common/HITRuntimeController.mqh`: Tick flow, H4/H1/M15 update control, status comments, and spread checks.
|
||||
- `Include/MyLib/Signals/HITEntrySignal.mqh`: Entry preconditions, order-type price validation, M15 filter, and retry-state updates.
|
||||
- `Include/MyLib/Common/HITExternalProcess.mqh`: done/running files, external process handles, PID recovery, exit-code checks, and timeout recovery.
|
||||
- `Include/MyLib/Signals/HITPythonSignalGateway.mqh`: OHLC CSV export, Python batch launch, and `trend_state.txt` / `target_prices.txt` loading.
|
||||
- `Include/MyLib/Trading/HITTradeManager.mqh`: Order sending, filling policy, pending-order expiration, order/position counting, expired order cancellation, and expired position closing.
|
||||
- `Include/MyLib/Trading/SLTPManager.mqh`: Existing-position break-even, elapsed-time break-even, active trailing, TP-progress SL, and high-volatility SL management.
|
||||
- `Include/MyLib/Panel/SLTPManagerPanel.mqh`: Chart panel that toggles `CSLTPManager` features, validates numeric inputs, and applies settings to the EA.
|
||||
|
||||
## 5. Python Integration Files
|
||||
|
||||
### H4 Trend Analysis
|
||||
|
||||
- MQL5 output: `ohlc_H4.csv`
|
||||
- Python output: `trend_state.txt`
|
||||
- Done marker: `process_done_trend.txt`
|
||||
- Running marker: `process_running_trend.txt`
|
||||
- Batch file: `C:\ea_py\bat\get_trend_reply.bat`
|
||||
|
||||
### H1 Entry Candidate Generation
|
||||
|
||||
- MQL5 output: `ohlc_H1.csv`
|
||||
- Python output: `target_prices.txt`
|
||||
- Done marker: `process_done_entry.txt`
|
||||
- Running marker: `process_running_entry.txt`
|
||||
- Batch file: `C:\ea_py\bat\get_entry_reply.bat`
|
||||
|
||||
`target_prices.txt` must contain 13 lines:
|
||||
|
||||
```text
|
||||
Line 1: res_chk
|
||||
Lines 2-4: T1 Buy Stop entry/tp/sl
|
||||
Lines 5-7: T2 Buy Limit entry/tp/sl
|
||||
Lines 8-10: T3 Sell Stop entry/tp/sl
|
||||
Lines 11-13: T4 Sell Limit entry/tp/sl
|
||||
```
|
||||
|
||||
## 6. Entry Conditions
|
||||
|
||||
New entries are allowed only when all conditions below are satisfied:
|
||||
|
||||
- Spread is less than or equal to `spread_limit`.
|
||||
- H4 trend analysis is complete and `trend_state.txt` can be loaded.
|
||||
- H1 entry candidate generation is complete and `target_prices.txt` can be loaded.
|
||||
- `res_chk = 1`.
|
||||
- The H1 candidate set has not expired under `ENTRY_H1_LIMIT`.
|
||||
- The selected order type has valid `entry/tp/sl` values greater than `0.0`.
|
||||
- The order type is allowed by the H4 `market_state`.
|
||||
- The order-type price relationship and broker minimum distance rules are satisfied.
|
||||
- When `use_m15_entry_filter = true`, the M15 closed-bar timing confirmation is satisfied.
|
||||
- This EA's pending orders plus positions are below `POSITION_LIMIT`.
|
||||
|
||||
### market_state and Allowed Order Types
|
||||
|
||||
- `0 MARKET_LOW_VOL_RANGE`: Allows T2 Buy Limit / T4 Sell Limit.
|
||||
- `1 MARKET_HIGH_VOL_RANGE`: Allows T2 Buy Limit / T4 Sell Limit.
|
||||
- `2 MARKET_LOW_VOL_UP`: Allows T1 Buy Stop / T2 Buy Limit.
|
||||
- `3 MARKET_HIGH_VOL_UP`: Allows T1 Buy Stop / T2 Buy Limit.
|
||||
- `4 MARKET_LOW_VOL_DOWN`: Allows T3 Sell Stop / T4 Sell Limit.
|
||||
- `5 MARKET_HIGH_VOL_DOWN`: Allows T3 Sell Stop / T4 Sell Limit.
|
||||
- `6 MARKET_ABNORMAL_VOL_STOP`: Blocks new entries.
|
||||
|
||||
### Order-Type Price Rules
|
||||
|
||||
- T1 Buy Stop: `Ask < entry`, `tp > entry`, `sl < entry`
|
||||
- T2 Buy Limit: `Ask > entry`, `tp > entry`, `sl < entry`
|
||||
- T3 Sell Stop: `Bid > entry`, `tp < entry`, `sl > entry`
|
||||
- T4 Sell Limit: `Bid < entry`, `tp < entry`, `sl > entry`
|
||||
|
||||
## 7. Exit Conditions
|
||||
|
||||
- Pending orders are cancelled after `ENTRY_H1_LIMIT * PeriodSeconds(PERIOD_H1)` has elapsed from setup time.
|
||||
- Positions are closed after `CLOSE_H1_LIMIT * PeriodSeconds(PERIOD_H1)` has elapsed from entry time.
|
||||
- Time-limit handling runs early in `OnTick` and is independent of Python readiness or spread checks.
|
||||
- On EA removal, `OnDeinit()` releases external-process state and the SLTP panel, then clears the chart status text with `Comment("")` and `ChartRedraw(0)`.
|
||||
- When `input_sltp_manager_enabled` or the panel `Manager` toggle is ON, the EA runs `CSLTPManager::ManagePositions()` and `HighVolatilityLimit()` after time-limit handling. Existing-position SL protection therefore continues while Python results are pending or new entries are skipped.
|
||||
- Normal break-even and active trailing are mutually exclusive. The panel turns one mode off when the other is enabled, and `CSLTPManager::ValidateSettings()` also validates the exclusion.
|
||||
|
||||
## 7.1 SLTP Control Panel
|
||||
|
||||
- The panel is created when `input_sltp_show_panel = true` and appears near the chart's upper-right area.
|
||||
- If panel creation fails, the EA logs the failure and continues with the already-applied input-based SLTP settings.
|
||||
- The `Manager` button toggles all SLTP management. When OFF, panel values remain stored but `OnTick` does not modify SL values.
|
||||
- The `BreakEven`, `Elapsed BE`, `Active Trail`, `TP Progress`, and `High Vol` buttons toggle each `CSLTPManager` feature.
|
||||
- Numeric fields are validated when `APPLY` is pressed. Invalid or out-of-range values show a `MessageBox`, are logged, and revert to the previous valid value.
|
||||
- Settings are copied into `CSLTPManager` only after `APPLY` succeeds. The EA then calls `ValidateSettings()`; if validation fails, SLTP management is stopped and the reason is logged.
|
||||
|
||||
## 8. Risk Management
|
||||
|
||||
- Managed orders and positions are limited to matching `_Symbol` and `magic_number`.
|
||||
- `POSITION_LIMIT` counts only this EA's orders and positions, not the full account.
|
||||
- The EA selects the filling policy from `SYMBOL_FILLING_MODE`, preferring IOC, then FOK, then RETURN.
|
||||
- Pending orders receive server-side expiration when the broker supports it.
|
||||
- `OrderSend` return values and `MqlTradeResult.retcode` are checked. Failures are logged with `GetLastError()` or the retcode.
|
||||
- SLTP management only targets existing positions matching `_Symbol` and `magic_number`, and it preserves each position's current TP.
|
||||
- SL changes are sent only when the candidate improves protection relative to the current SL and satisfies broker stop-level and freeze-level constraints.
|
||||
|
||||
## 9. Error Handling
|
||||
|
||||
- If `trend_state.txt` is missing, unreadable, or outside `0..6`, the EA uses `MARKET_ABNORMAL_VOL_STOP`.
|
||||
- If `target_prices.txt` is missing, unreadable, or shorter than 13 lines, the EA uses `res_chk = 0`.
|
||||
- If a Python process exits with a non-zero code, the code is logged and the next trigger may retry.
|
||||
- If only a stale running marker remains, the EA attempts PID recovery. If recovery fails and the marker is timed out, it removes the stale marker.
|
||||
|
||||
## 10. Changelog
|
||||
|
||||
### 2026-05-05
|
||||
|
||||
- Added `Comment("")` and `ChartRedraw(0)` to `OnDeinit()` so the chart status comment is removed when the EA is deleted.
|
||||
- Connected `CSLTPManager` and the dedicated chart panel `SLTPManagerPanel.mqh` to `HIT-EA_refactor_ver5.mq5`, allowing UI control of break-even, elapsed-time break-even, active trailing, TP-progress SL, and high-volatility SL tightening.
|
||||
- Added SLTP management immediately after time-limit handling in `OnTick`, so existing-position protection continues independently of Python readiness and spread checks.
|
||||
- Added SLTP panel inputs, mutual exclusion for normal break-even versus active trailing, and numeric validation on `APPLY`.
|
||||
- Split the function implementations from `HIT-EA_refactor_ver5.mq5` into purpose-specific `.mqh` files.
|
||||
- Kept `OnInit`, `OnDeinit`, `OnTick`, inputs, and global state in the EA source while moving behavior functions under `Include/MyLib/`.
|
||||
- Updated the specification to match the current `CreateProcessW` Python process tracking, M15 filter, `market_state` range `0..6`, and `spread_limit = 60`.
|
||||
|
||||
### 2026-05-02
|
||||
|
||||
- Added entry suppression when `res_chk = 0`.
|
||||
- Moved time-limit handling before Python readiness and spread checks.
|
||||
- Split startup flags for H4 and H1 initial processing.
|
||||
- Switched OHLC retrieval to `CopyRates` and exported closed bars only.
|
||||
@@ -0,0 +1,231 @@
|
||||
# HIT-EA 仕様書(日本語)
|
||||
|
||||
## 1. 概要
|
||||
|
||||
- 本EAは、H4の確定足OHLCから外部Pythonで相場状態を判定し、H1の確定足OHLCからエントリー候補価格を生成する。
|
||||
- MQL5側はPythonの出力ファイルを読み込み、H4相場状態、H1候補価格、M15確定足フィルタ、スプレッド、ブローカー距離制約を確認したうえでペンディング注文を発行する。
|
||||
- バックテスト再現性のため、Pythonへ渡すOHLCは `OHLC_START_SHIFT = 1` により形成中バーを除外し、確定足だけを使用する。
|
||||
- ライブ実行時の耐性として、外部プロセスの `running` ファイル、プロセスID、終了コード、タイムアウトを監視し、二重起動とCSV上書きを抑止する。
|
||||
|
||||
## 2. 使用インジケータ
|
||||
|
||||
- 標準インジケータおよびカスタムインジケータは未使用。
|
||||
- OHLCは `CopyRates(_Symbol, timeframe, OHLC_START_SHIFT, HISTORY_BARS, rates)` で取得する。
|
||||
- M15エントリー確認は、直近確定足と1本前の確定足のローソク足形状、平均レンジ、候補価格との距離から判定する。
|
||||
|
||||
## 3. パラメータ設定
|
||||
|
||||
### input
|
||||
|
||||
- `lot_size = 0.01`: 注文ロット。
|
||||
- `spread_limit = 60`: 許容スプレッド(point)。
|
||||
- `magic_number = 10001`: EA識別用マジックナンバー。
|
||||
- `initial_order = 0`: 起動直後の初回H4/H1処理を実行するか。`1` で有効。
|
||||
- `use_m15_entry_filter = true`: M15確定足によるエントリータイミング確認を使用するか。
|
||||
- `m15_entry_zone_atr_multiplier = 1.50`: M15平均レンジに対する候補価格接近許容倍率。
|
||||
- `use_m15_imbalance_confirmation = true`: T1/T3の順張り候補に対して、M15確定足の初動確認を追加するか。
|
||||
- `m15_imbalance_avg_body_period = 20`: M15初動確認で使う平均実体計算期間。
|
||||
- `m15_imbalance_sensitivity = 2.0`: M15初動確認で現在足実体が平均実体を上回る必要倍率。
|
||||
- `m15_imbalance_min_avg_body_points = 1.0`: M15平均実体の最小値(point)。
|
||||
- `use_m15_imbalance_debug_log = false`: M15初動確認の詳細ログを出すか。
|
||||
- `input_entry_max_candidate_age_minutes = 45`: H1候補価格を新規発注に使用できる最大経過分数。古い候補でM15条件が後から整った場合の遅延エントリーを抑止する。
|
||||
- `input_position_limit = 10`: 自EAの未約定注文 + ポジション数の実運用上限。内部上限 `POSITION_LIMIT` を超える指定は丸める。
|
||||
- `use_split_entry_zone = false`: H1予測ゾーンを使った分割エントリーを有効化するか。
|
||||
- `split_entry_count = 3`: 分割エントリー本数。1〜10に丸めて使用する。
|
||||
- `split_lot_mode = SPLIT_LOT_TOTAL`: 分割ロット配分モード。`SPLIT_LOT_TOTAL` は総ロットをN分割、`SPLIT_LOT_FIXED` は各注文に固定ロットを使う。
|
||||
- `split_total_lot_size = 0.09`: 総量分割モードの合計ロット。
|
||||
- `split_fixed_lot_size = 0.01`: 固定ロットモードの1注文ロット。
|
||||
- `cancel_old_split_pending_on_new_zone = true`: 新しいH1ゾーン読込時に、同じEAの古い分割pending注文を取消するか。
|
||||
- `input_sltp_manager_enabled = false`: UI連動の `CSLTPManager` による既存ポジションSL管理を有効化するか。
|
||||
- `input_sltp_show_panel = true`: チャート上にSLTP操作パネルを表示するか。
|
||||
- `input_sltp_use_breakeven = false`: 通常ブレークイーブンを有効化するか。
|
||||
- `input_sltp_breakeven_trigger_pips = 30.0`: 通常ブレークイーブンを開始する含み益pips。
|
||||
- `input_sltp_breakeven_buffer_pips = 0.0`: 通常ブレークイーブン時に建値から利益方向へずらすpips。
|
||||
- `input_sltp_use_elapsed_breakeven = false`: 保有時間ベースのブレークイーブンを有効化するか。
|
||||
- `input_sltp_elapsed_breakeven_hours = 4.0`: 保有時間ベースのブレークイーブンを許可するまでの保有時間。
|
||||
- `input_sltp_elapsed_breakeven_buffer_pips = 0.0`: 保有時間ベースのブレークイーブン時に建値から利益方向へずらすpips。
|
||||
- `input_sltp_use_active_trailing = false`: アクティブトレーリングを有効化するか。
|
||||
- `input_sltp_active_breakeven_pips = 30.0`: アクティブトレーリング開始pips。
|
||||
- `input_sltp_active_stop_loss_offset_pips = 5.0`: 開始時に建値から固定する利益pips。
|
||||
- `input_sltp_active_step_trigger_pips = 10.0`: SLを1段進めるために必要な追加利益pips。
|
||||
- `input_sltp_active_step_move_pips = 5.0`: 1段ごとにSLを利益方向へ動かすpips。
|
||||
- `input_sltp_use_tp_progress_stop = false`: TP進捗率に応じたSL固定を有効化するか。
|
||||
- `input_sltp_tp_progress_trigger_percent = 70.0`: TP進捗率SLを開始する進捗率。
|
||||
- `input_sltp_tp_progress_sl_lock_percent = 30.0`: 建値からTPまでの距離のうちSLで固定する割合。
|
||||
- `input_sltp_use_high_volatility_limit = false`: 短時間急変時のSL引き締めを有効化するか。
|
||||
|
||||
### 主要定数
|
||||
|
||||
- `POSITION_LIMIT = 48`: 自EAの未約定注文 + ポジション数の上限。
|
||||
- `ENTRY_H1_LIMIT = 1`: 未約定注文の有効期限(H1本数)。
|
||||
- `CLOSE_H1_LIMIT = 12`: ポジションの時間制限クローズ(H1本数)。
|
||||
- `HISTORY_BARS = 72`: Pythonへ渡すOHLC本数。
|
||||
- `OHLC_START_SHIFT = 1`: 確定足からOHLCを取得するためのシフト。
|
||||
- `M15_CONFIRM_BARS = 30`: M15平均レンジ計算に使う足数。
|
||||
- `ENTRY_RETRY_SECONDS = 60`: エントリー判定リトライ間隔。
|
||||
- `ENTRY_RETRY_LIMIT = 10`: H1候補価格に対する最大リトライ回数。
|
||||
- `TARGET_SIZE = 13`: `target_prices.txt` から読み込む数値数。
|
||||
- `TARGET_ZONE_SCHEMA_VERSION = 2`: `target_zones.txt` の形式バージョン。
|
||||
- `PYTHON_TIMEOUT_SECONDS = 600`: Python完了待ちの監視上限。
|
||||
|
||||
### Python側エントリー候補ガード
|
||||
|
||||
- H1候補価格生成後、Python側で現在価格から遠すぎる `entry` を無効化する。
|
||||
- 距離上限は `max(H1 EATR * 0.65, 5.00)` とし、上限を超えた戦略は `0.00,0.00,0.00` に補正する。
|
||||
- このガードは、深い指値や遠いブレイク待ちがM15確認後に遅れて発注されることを抑えるための後処理である。
|
||||
|
||||
## 4. ファイル構成
|
||||
|
||||
- `Experts/MyProject/HIT-EA_refactor_ver6.mq5`: EAエントリーポイント。`OnInit`, `OnDeinit`, `OnTick`、input、グローバル状態、DLL importを保持する。
|
||||
- `Include/MyLib/Common/HITRuntimeController.mqh`: ティック処理、H4/H1/M15更新制御、ステータス表示、スプレッド判定。
|
||||
- `Include/MyLib/Signals/HITEntrySignal.mqh`: エントリー前提条件、注文タイプ別価格判定、M15フィルタ、リトライ状態更新。
|
||||
- `Include/MyLib/Common/HITExternalProcess.mqh`: done/runningファイル、外部プロセスハンドル、PID復元、終了コード確認、タイムアウト復旧。
|
||||
- `Include/MyLib/Signals/HITPythonSignalGateway.mqh`: OHLC CSV出力、Pythonバッチ起動、`trend_state.txt` / `target_prices.txt` / `target_zones.txt` 読込。
|
||||
- `Include/MyLib/Trading/HITTradeManager.mqh`: 注文送信、執行ポリシー、有効期限設定、注文/ポジション数集計、期限切れ取消/クローズ。
|
||||
- `Include/MyLib/Trading/SLTPManager.mqh`: 既存ポジションに対するブレークイーブン、時間経過BE、アクティブトレーリング、TP進捗SL、急変時SL引き締めを管理する。
|
||||
- `Include/MyLib/Panel/SLTPManagerPanel.mqh`: `CSLTPManager` の各設定をチャート上で切り替え、数値入力を検証してEAへ反映する操作パネル。
|
||||
|
||||
## 5. Python連携ファイル
|
||||
|
||||
### H4トレンド判定
|
||||
|
||||
- MQL5出力: `ohlc_H4.csv`
|
||||
- Python出力: `trend_state.txt`
|
||||
- 完了フラグ: `process_done_trend.txt`
|
||||
- 実行中フラグ: `process_running_trend.txt`
|
||||
- 起動バッチ: `C:\ea_py\bat\get_trend_reply.bat`
|
||||
|
||||
### H1エントリー価格生成
|
||||
|
||||
- MQL5出力: `ohlc_H1.csv`
|
||||
- Python出力: `target_prices.txt`, `target_zones.txt`
|
||||
- 完了フラグ: `process_done_entry.txt`
|
||||
- 実行中フラグ: `process_running_entry.txt`
|
||||
- 起動バッチ: `C:\ea_py\bat\get_entry_reply.bat`
|
||||
|
||||
`target_prices.txt` は13行構成とする。
|
||||
|
||||
```text
|
||||
1行目: res_chk
|
||||
2-4行目: T1 Buy Stop の entry/tp/sl
|
||||
5-7行目: T2 Buy Limit の entry/tp/sl
|
||||
8-10行目: T3 Sell Stop の entry/tp/sl
|
||||
11-13行目: T4 Sell Limit の entry/tp/sl
|
||||
```
|
||||
|
||||
`target_zones.txt` は分割エントリー用の7行構成とする。
|
||||
|
||||
```text
|
||||
1行目: schema_version(2)
|
||||
2行目: res_chk
|
||||
3行目: candidate_id(H1確定足時刻由来)
|
||||
4行目: T1 Buy Stop の strategy, zone_low, zone_high, tp, sl
|
||||
5行目: T2 Buy Limit の strategy, zone_low, zone_high, tp, sl
|
||||
6行目: T3 Sell Stop の strategy, zone_low, zone_high, tp, sl
|
||||
7行目: T4 Sell Limit の strategy, zone_low, zone_high, tp, sl
|
||||
```
|
||||
|
||||
Pythonは `target_prices.txt` と `target_zones.txt` の両方を書き終えてから `process_done_entry.txt` を作成する。分割エントリーが無効な場合、EAは従来どおり `target_prices.txt` を使用する。
|
||||
|
||||
## 6. エントリー条件
|
||||
|
||||
新規エントリーは、以下をすべて満たす場合のみ行う。
|
||||
|
||||
- スプレッドが `spread_limit` 以下。
|
||||
- H4トレンド判定結果が完了済みで、`trend_state.txt` を読み込める。
|
||||
- H1候補価格生成が完了済みで、`target_prices.txt` を読み込める。
|
||||
- `res_chk = 1`。
|
||||
- H1候補価格が `ENTRY_H1_LIMIT` 内で期限切れではない。
|
||||
- H1候補価格の読込から `input_entry_max_candidate_age_minutes` 分を超えていない。
|
||||
- 対象注文タイプの `entry/tp/sl` がすべて `0.0` より大きい。
|
||||
- H4 `market_state` に対して注文タイプが許可されている。
|
||||
- 注文タイプごとの価格整合条件とブローカー最小距離制約を満たす。
|
||||
- `use_m15_entry_filter = true` の場合、M15確定足の方向・反発・接近条件を満たす。
|
||||
- 自EAの注文 + ポジション数が `input_position_limit` 未満。
|
||||
- 分割エントリー有効時は `target_zones.txt` の `res_chk = 1`、予測ゾーンの価格整合、分割ロットの `SYMBOL_VOLUME_MIN/MAX/STEP` 適合、同一 `candidate_id` + slot の重複注文/ポジション不存在を満たす。
|
||||
|
||||
### market_state と注文タイプ
|
||||
|
||||
- `0 MARKET_LOW_VOL_RANGE`: T2 Buy Limit / T4 Sell Limit を許可。
|
||||
- `1 MARKET_HIGH_VOL_RANGE`: T2 Buy Limit / T4 Sell Limit を許可。
|
||||
- `2 MARKET_LOW_VOL_UP`: T1 Buy Stop / T2 Buy Limit を許可。
|
||||
- `3 MARKET_HIGH_VOL_UP`: T1 Buy Stop / T2 Buy Limit を許可。
|
||||
- `4 MARKET_LOW_VOL_DOWN`: T3 Sell Stop / T4 Sell Limit を許可。
|
||||
- `5 MARKET_HIGH_VOL_DOWN`: T3 Sell Stop / T4 Sell Limit を許可。
|
||||
- `6 MARKET_ABNORMAL_VOL_STOP`: 新規注文を停止。
|
||||
|
||||
### 注文タイプごとの価格整合条件
|
||||
|
||||
- T1 Buy Stop: `Ask < entry`, `tp > entry`, `sl < entry`
|
||||
- T2 Buy Limit: `Ask > entry`, `tp > entry`, `sl < entry`
|
||||
- T3 Sell Stop: `Bid > entry`, `tp < entry`, `sl > entry`
|
||||
- T4 Sell Limit: `Bid < entry`, `tp < entry`, `sl > entry`
|
||||
|
||||
## 7. エグジット条件
|
||||
|
||||
- 未約定注文は、注文作成時刻から `ENTRY_H1_LIMIT * PeriodSeconds(PERIOD_H1)` 以上経過した場合に取消する。
|
||||
- 保有ポジションは、建玉時刻から `CLOSE_H1_LIMIT * PeriodSeconds(PERIOD_H1)` 以上経過した場合にクローズする。
|
||||
- 時間制限処理は `OnTick` の早い段階で実行し、Python完了待ちやスプレッド判定に依存させない。
|
||||
- EA削除時は `OnDeinit()` で外部プロセス状態とSLTPパネルを解放し、`Comment("")` と `ChartRedraw(0)` によりチャート上のステータス表示を消去する。
|
||||
- `input_sltp_manager_enabled` またはパネルの `Manager` がONの場合、時間制限処理後に `CSLTPManager::ManagePositions()` と `HighVolatilityLimit()` を実行する。これにより、Python結果待ちや新規注文停止中でも既存ポジションのSL保護を継続する。
|
||||
- 通常ブレークイーブンとアクティブトレーリングは同時有効化しない。パネル上では片方をONにするともう片方をOFFにし、`CSLTPManager::ValidateSettings()` でも排他条件を検証する。
|
||||
|
||||
## 7.1 SLTP操作パネル
|
||||
|
||||
- パネルは `input_sltp_show_panel = true` の場合に作成され、チャート右上に表示される。
|
||||
- パネル生成に失敗した場合はログへ出力し、EA本体はinputで反映済みのSLTP設定のまま継続する。
|
||||
- `Manager` ボタンでSLTP管理全体のON/OFFを切り替える。OFFの場合、パネル値は保持するが `OnTick` でSL変更は行わない。
|
||||
- `BreakEven`, `Elapsed BE`, `Active Trail`, `TP Progress`, `High Vol` ボタンで各機能を切り替える。
|
||||
- 数値入力欄は `APPLY` 押下時に範囲検証される。範囲外または数値以外の場合は `MessageBox` とログで通知し、直前の有効値へ戻す。
|
||||
- `APPLY` 成功時のみEA内部の `CSLTPManager` 設定へ反映する。反映後は `ValidateSettings()` を通し、失敗した場合はSLTP管理を停止してログへ理由を出力する。
|
||||
|
||||
## 8. リスク管理
|
||||
|
||||
- 注文/ポジション管理対象は `_Symbol` と `magic_number` が一致するものに限定する。
|
||||
- `input_position_limit` は口座全体ではなく、自EA対象分のみを数える。内部の絶対上限は `POSITION_LIMIT` とする。
|
||||
- 送信時は `SYMBOL_FILLING_MODE` を参照し、IOC、FOK、RETURNの順で利用可能な執行ポリシーを選択する。
|
||||
- ペンディング注文には、ブローカーが対応する場合にサーバー側の期限を設定する。
|
||||
- `OrderSend` の戻り値と `MqlTradeResult.retcode` を確認し、失敗時は `GetLastError()` またはretcodeをログへ出力する。
|
||||
- 分割エントリーの注文コメントには `candidate_id` とslot番号を入れ、同一slotの二重発注を抑止する。
|
||||
- SLTP管理は `_Symbol` と `magic_number` が一致する既存ポジションのみを対象とし、TPは既存値を維持する。
|
||||
- SL変更は既存SLより利益保護方向へ改善する場合だけ実行し、ブローカーのstop level / freeze levelを満たさない候補は送信しない。
|
||||
|
||||
## 9. 異常系の扱い
|
||||
|
||||
- `trend_state.txt` が存在しない、読み込めない、または `0..6` 以外の場合は `MARKET_ABNORMAL_VOL_STOP` として扱う。
|
||||
- `target_prices.txt` が存在しない、読み込めない、または13行未満の場合は `res_chk = 0` として扱う。
|
||||
- 分割エントリー有効時に `target_zones.txt` が存在しない、schema不一致、7行未満、または `res_chk != 1` の場合は新規注文を停止する。
|
||||
- Pythonプロセスが異常終了した場合、終了コードをログへ出力し、次回トリガーで再実行できる状態に戻す。
|
||||
- `running` ファイルだけが残っている場合は、PIDからプロセス復元を試みる。復元できずタイムアウト済みなら古いマーカーとして削除する。
|
||||
|
||||
## 10. 変更履歴
|
||||
|
||||
### 2026-05-24
|
||||
|
||||
- Python側で `target_zones.txt` を追加出力し、既存 `target_prices.txt` と両方を書き終えてから `process_done_entry.txt` を作成する仕様にした。
|
||||
- EA側に `use_split_entry_zone`、`split_entry_count`、`split_lot_mode`、`split_total_lot_size`、`split_fixed_lot_size`、`input_position_limit` を追加した。
|
||||
- 分割エントリー有効時は、H1予測ゾーンをN本に分割し、総ロット分割または固定ロットでpending注文を出せるようにした。
|
||||
- `candidate_id` + slot番号で分割注文を識別し、同一slotの二重発注を抑止する仕様を追加した。
|
||||
|
||||
### 2026-05-13
|
||||
|
||||
- Python側にH1 EATRベースの候補距離ガードを追加し、現在価格から `max(H1 EATR * 0.65, 5.00)` を超える候補をMT5へ渡す前に無効化する仕様を追加。
|
||||
- EA側に `input_entry_max_candidate_age_minutes = 45` を追加し、M15確認が遅れて整った古いH1候補で新規発注しないようにした。
|
||||
- エントリー見送りログへH1候補の経過秒数を追加し、遅延・M15未確認・価格不整合の原因を追跡しやすくした。
|
||||
|
||||
### 2026-05-05
|
||||
|
||||
- EA削除後にチャート左上のステータスコメントが残らないよう、`OnDeinit()` で `Comment("")` と `ChartRedraw(0)` を実行する終了処理を追加。
|
||||
- `HIT-EA_refactor_ver5.mq5` に `CSLTPManager` と専用チャートパネル `SLTPManagerPanel.mqh` を接続し、UIからブレークイーブン、時間経過BE、アクティブトレーリング、TP進捗SL、急変時SL引き締めを操作できるようにした。
|
||||
- SLTP管理を `OnTick` の時間制限処理直後に実行し、Python結果待ちやスプレッド判定に依存せず既存ポジション保護を継続する仕様を追加。
|
||||
- SLTPパネル用inputと、通常ブレークイーブン/アクティブトレーリングの排他検証、`APPLY` 時の数値検証を追加。
|
||||
- `HIT-EA_refactor_ver5.mq5` の関数群を用途別 `.mqh` に分割。
|
||||
- `OnInit`, `OnDeinit`, `OnTick`、input、グローバル状態はEA本体に残し、動作ロジックは `Include/MyLib/` 配下へ移動。
|
||||
- 現行コードに合わせて、`CreateProcessW` ベースのPythonプロセス監視、M15フィルタ、`market_state` 0..6、`spread_limit = 60` を仕様へ反映。
|
||||
|
||||
### 2026-05-02
|
||||
|
||||
- `res_chk=0` 時にエントリー送信を抑止する分岐を追加。
|
||||
- 時間制限処理を、Python完了待ち・スプレッド制限より前に移動。
|
||||
- `initial_order` の初回処理フラグをH4用・H1用に分離。
|
||||
- OHLC取得を `CopyRates` 中心に変更し、確定足のみをPythonへ渡す仕様に変更。
|
||||
@@ -0,0 +1,180 @@
|
||||
# HIT-EA 仕様書(日本語)
|
||||
|
||||
## 1. 概要
|
||||
|
||||
- 本EAは、H4の確定足OHLCから外部Pythonで相場状態を判定し、H1の確定足OHLCからエントリー候補価格を生成する。
|
||||
- MQL5側はPythonの出力ファイルを読み込み、H4相場状態、H1候補価格、M15確定足フィルタ、スプレッド、ブローカー距離制約を確認したうえでペンディング注文を発行する。
|
||||
- バックテスト再現性のため、Pythonへ渡すOHLCは `OHLC_START_SHIFT = 1` により形成中バーを除外し、確定足だけを使用する。
|
||||
- ライブ実行時の耐性として、外部プロセスの `running` ファイル、プロセスID、終了コード、タイムアウトを監視し、二重起動とCSV上書きを抑止する。
|
||||
|
||||
## 2. 使用インジケータ
|
||||
|
||||
- 標準インジケータおよびカスタムインジケータは未使用。
|
||||
- OHLCは `CopyRates(_Symbol, timeframe, OHLC_START_SHIFT, HISTORY_BARS, rates)` で取得する。
|
||||
- M15エントリー確認は、直近確定足と1本前の確定足のローソク足形状、平均レンジ、候補価格との距離から判定する。
|
||||
|
||||
## 3. パラメータ設定
|
||||
|
||||
### input
|
||||
|
||||
- `lot_size = 0.01`: 注文ロット。
|
||||
- `spread_limit = 60`: 許容スプレッド(point)。
|
||||
- `magic_number = 10001`: EA識別用マジックナンバー。
|
||||
- `initial_order = 0`: 起動直後の初回H4/H1処理を実行するか。`1` で有効。
|
||||
- `use_m15_entry_filter = true`: M15確定足によるエントリータイミング確認を使用するか。
|
||||
- `m15_entry_zone_atr_multiplier = 1.50`: M15平均レンジに対する候補価格接近許容倍率。
|
||||
- `input_sltp_manager_enabled = false`: UI連動の `CSLTPManager` による既存ポジションSL管理を有効化するか。
|
||||
- `input_sltp_show_panel = true`: チャート上にSLTP操作パネルを表示するか。
|
||||
- `input_sltp_use_breakeven = false`: 通常ブレークイーブンを有効化するか。
|
||||
- `input_sltp_breakeven_trigger_pips = 30.0`: 通常ブレークイーブンを開始する含み益pips。
|
||||
- `input_sltp_breakeven_buffer_pips = 0.0`: 通常ブレークイーブン時に建値から利益方向へずらすpips。
|
||||
- `input_sltp_use_elapsed_breakeven = false`: 保有時間ベースのブレークイーブンを有効化するか。
|
||||
- `input_sltp_elapsed_breakeven_hours = 4.0`: 保有時間ベースのブレークイーブンを許可するまでの保有時間。
|
||||
- `input_sltp_elapsed_breakeven_buffer_pips = 0.0`: 保有時間ベースのブレークイーブン時に建値から利益方向へずらすpips。
|
||||
- `input_sltp_use_active_trailing = false`: アクティブトレーリングを有効化するか。
|
||||
- `input_sltp_active_breakeven_pips = 30.0`: アクティブトレーリング開始pips。
|
||||
- `input_sltp_active_stop_loss_offset_pips = 5.0`: 開始時に建値から固定する利益pips。
|
||||
- `input_sltp_active_step_trigger_pips = 10.0`: SLを1段進めるために必要な追加利益pips。
|
||||
- `input_sltp_active_step_move_pips = 5.0`: 1段ごとにSLを利益方向へ動かすpips。
|
||||
- `input_sltp_use_tp_progress_stop = false`: TP進捗率に応じたSL固定を有効化するか。
|
||||
- `input_sltp_tp_progress_trigger_percent = 70.0`: TP進捗率SLを開始する進捗率。
|
||||
- `input_sltp_tp_progress_sl_lock_percent = 30.0`: 建値からTPまでの距離のうちSLで固定する割合。
|
||||
- `input_sltp_use_high_volatility_limit = false`: 短時間急変時のSL引き締めを有効化するか。
|
||||
|
||||
### 主要定数
|
||||
|
||||
- `POSITION_LIMIT = 48`: 自EAの未約定注文 + ポジション数の上限。
|
||||
- `ENTRY_H1_LIMIT = 1`: 未約定注文の有効期限(H1本数)。
|
||||
- `CLOSE_H1_LIMIT = 12`: ポジションの時間制限クローズ(H1本数)。
|
||||
- `HISTORY_BARS = 72`: Pythonへ渡すOHLC本数。
|
||||
- `OHLC_START_SHIFT = 1`: 確定足からOHLCを取得するためのシフト。
|
||||
- `M15_CONFIRM_BARS = 20`: M15平均レンジ計算に使う足数。
|
||||
- `ENTRY_RETRY_SECONDS = 60`: エントリー判定リトライ間隔。
|
||||
- `ENTRY_RETRY_LIMIT = 10`: H1候補価格に対する最大リトライ回数。
|
||||
- `TARGET_SIZE = 13`: `target_prices.txt` から読み込む数値数。
|
||||
- `PYTHON_TIMEOUT_SECONDS = 600`: Python完了待ちの監視上限。
|
||||
|
||||
## 4. ファイル構成
|
||||
|
||||
- `Experts/MyProject/HIT-EA_refactor_ver5.mq5`: EAエントリーポイント。`OnInit`, `OnDeinit`, `OnTick`、input、グローバル状態、DLL importを保持する。
|
||||
- `Include/MyLib/Common/HITRuntimeController.mqh`: ティック処理、H4/H1/M15更新制御、ステータス表示、スプレッド判定。
|
||||
- `Include/MyLib/Signals/HITEntrySignal.mqh`: エントリー前提条件、注文タイプ別価格判定、M15フィルタ、リトライ状態更新。
|
||||
- `Include/MyLib/Common/HITExternalProcess.mqh`: done/runningファイル、外部プロセスハンドル、PID復元、終了コード確認、タイムアウト復旧。
|
||||
- `Include/MyLib/Signals/HITPythonSignalGateway.mqh`: OHLC CSV出力、Pythonバッチ起動、`trend_state.txt` / `target_prices.txt` 読込。
|
||||
- `Include/MyLib/Trading/HITTradeManager.mqh`: 注文送信、執行ポリシー、有効期限設定、注文/ポジション数集計、期限切れ取消/クローズ。
|
||||
- `Include/MyLib/Trading/SLTPManager.mqh`: 既存ポジションに対するブレークイーブン、時間経過BE、アクティブトレーリング、TP進捗SL、急変時SL引き締めを管理する。
|
||||
- `Include/MyLib/Panel/SLTPManagerPanel.mqh`: `CSLTPManager` の各設定をチャート上で切り替え、数値入力を検証してEAへ反映する操作パネル。
|
||||
|
||||
## 5. Python連携ファイル
|
||||
|
||||
### H4トレンド判定
|
||||
|
||||
- MQL5出力: `ohlc_H4.csv`
|
||||
- Python出力: `trend_state.txt`
|
||||
- 完了フラグ: `process_done_trend.txt`
|
||||
- 実行中フラグ: `process_running_trend.txt`
|
||||
- 起動バッチ: `C:\ea_py\bat\get_trend_reply.bat`
|
||||
|
||||
### H1エントリー価格生成
|
||||
|
||||
- MQL5出力: `ohlc_H1.csv`
|
||||
- Python出力: `target_prices.txt`
|
||||
- 完了フラグ: `process_done_entry.txt`
|
||||
- 実行中フラグ: `process_running_entry.txt`
|
||||
- 起動バッチ: `C:\ea_py\bat\get_entry_reply.bat`
|
||||
|
||||
`target_prices.txt` は13行構成とする。
|
||||
|
||||
```text
|
||||
1行目: res_chk
|
||||
2-4行目: T1 Buy Stop の entry/tp/sl
|
||||
5-7行目: T2 Buy Limit の entry/tp/sl
|
||||
8-10行目: T3 Sell Stop の entry/tp/sl
|
||||
11-13行目: T4 Sell Limit の entry/tp/sl
|
||||
```
|
||||
|
||||
## 6. エントリー条件
|
||||
|
||||
新規エントリーは、以下をすべて満たす場合のみ行う。
|
||||
|
||||
- スプレッドが `spread_limit` 以下。
|
||||
- H4トレンド判定結果が完了済みで、`trend_state.txt` を読み込める。
|
||||
- H1候補価格生成が完了済みで、`target_prices.txt` を読み込める。
|
||||
- `res_chk = 1`。
|
||||
- H1候補価格が `ENTRY_H1_LIMIT` 内で期限切れではない。
|
||||
- 対象注文タイプの `entry/tp/sl` がすべて `0.0` より大きい。
|
||||
- H4 `market_state` に対して注文タイプが許可されている。
|
||||
- 注文タイプごとの価格整合条件とブローカー最小距離制約を満たす。
|
||||
- `use_m15_entry_filter = true` の場合、M15確定足の方向・反発・接近条件を満たす。
|
||||
- 自EAの注文 + ポジション数が `POSITION_LIMIT` 未満。
|
||||
|
||||
### market_state と注文タイプ
|
||||
|
||||
- `0 MARKET_LOW_VOL_RANGE`: T2 Buy Limit / T4 Sell Limit を許可。
|
||||
- `1 MARKET_HIGH_VOL_RANGE`: T2 Buy Limit / T4 Sell Limit を許可。
|
||||
- `2 MARKET_LOW_VOL_UP`: T1 Buy Stop / T2 Buy Limit を許可。
|
||||
- `3 MARKET_HIGH_VOL_UP`: T1 Buy Stop / T2 Buy Limit を許可。
|
||||
- `4 MARKET_LOW_VOL_DOWN`: T3 Sell Stop / T4 Sell Limit を許可。
|
||||
- `5 MARKET_HIGH_VOL_DOWN`: T3 Sell Stop / T4 Sell Limit を許可。
|
||||
- `6 MARKET_ABNORMAL_VOL_STOP`: 新規注文を停止。
|
||||
|
||||
### 注文タイプごとの価格整合条件
|
||||
|
||||
- T1 Buy Stop: `Ask < entry`, `tp > entry`, `sl < entry`
|
||||
- T2 Buy Limit: `Ask > entry`, `tp > entry`, `sl < entry`
|
||||
- T3 Sell Stop: `Bid > entry`, `tp < entry`, `sl > entry`
|
||||
- T4 Sell Limit: `Bid < entry`, `tp < entry`, `sl > entry`
|
||||
|
||||
## 7. エグジット条件
|
||||
|
||||
- 未約定注文は、注文作成時刻から `ENTRY_H1_LIMIT * PeriodSeconds(PERIOD_H1)` 以上経過した場合に取消する。
|
||||
- 保有ポジションは、建玉時刻から `CLOSE_H1_LIMIT * PeriodSeconds(PERIOD_H1)` 以上経過した場合にクローズする。
|
||||
- 時間制限処理は `OnTick` の早い段階で実行し、Python完了待ちやスプレッド判定に依存させない。
|
||||
- EA削除時は `OnDeinit()` で外部プロセス状態とSLTPパネルを解放し、`Comment("")` と `ChartRedraw(0)` によりチャート上のステータス表示を消去する。
|
||||
- `input_sltp_manager_enabled` またはパネルの `Manager` がONの場合、時間制限処理後に `CSLTPManager::ManagePositions()` と `HighVolatilityLimit()` を実行する。これにより、Python結果待ちや新規注文停止中でも既存ポジションのSL保護を継続する。
|
||||
- 通常ブレークイーブンとアクティブトレーリングは同時有効化しない。パネル上では片方をONにするともう片方をOFFにし、`CSLTPManager::ValidateSettings()` でも排他条件を検証する。
|
||||
|
||||
## 7.1 SLTP操作パネル
|
||||
|
||||
- パネルは `input_sltp_show_panel = true` の場合に作成され、チャート右上に表示される。
|
||||
- パネル生成に失敗した場合はログへ出力し、EA本体はinputで反映済みのSLTP設定のまま継続する。
|
||||
- `Manager` ボタンでSLTP管理全体のON/OFFを切り替える。OFFの場合、パネル値は保持するが `OnTick` でSL変更は行わない。
|
||||
- `BreakEven`, `Elapsed BE`, `Active Trail`, `TP Progress`, `High Vol` ボタンで各機能を切り替える。
|
||||
- 数値入力欄は `APPLY` 押下時に範囲検証される。範囲外または数値以外の場合は `MessageBox` とログで通知し、直前の有効値へ戻す。
|
||||
- `APPLY` 成功時のみEA内部の `CSLTPManager` 設定へ反映する。反映後は `ValidateSettings()` を通し、失敗した場合はSLTP管理を停止してログへ理由を出力する。
|
||||
|
||||
## 8. リスク管理
|
||||
|
||||
- 注文/ポジション管理対象は `_Symbol` と `magic_number` が一致するものに限定する。
|
||||
- `POSITION_LIMIT` は口座全体ではなく、自EA対象分のみを数える。
|
||||
- 送信時は `SYMBOL_FILLING_MODE` を参照し、IOC、FOK、RETURNの順で利用可能な執行ポリシーを選択する。
|
||||
- ペンディング注文には、ブローカーが対応する場合にサーバー側の期限を設定する。
|
||||
- `OrderSend` の戻り値と `MqlTradeResult.retcode` を確認し、失敗時は `GetLastError()` またはretcodeをログへ出力する。
|
||||
- SLTP管理は `_Symbol` と `magic_number` が一致する既存ポジションのみを対象とし、TPは既存値を維持する。
|
||||
- SL変更は既存SLより利益保護方向へ改善する場合だけ実行し、ブローカーのstop level / freeze levelを満たさない候補は送信しない。
|
||||
|
||||
## 9. 異常系の扱い
|
||||
|
||||
- `trend_state.txt` が存在しない、読み込めない、または `0..6` 以外の場合は `MARKET_ABNORMAL_VOL_STOP` として扱う。
|
||||
- `target_prices.txt` が存在しない、読み込めない、または13行未満の場合は `res_chk = 0` として扱う。
|
||||
- Pythonプロセスが異常終了した場合、終了コードをログへ出力し、次回トリガーで再実行できる状態に戻す。
|
||||
- `running` ファイルだけが残っている場合は、PIDからプロセス復元を試みる。復元できずタイムアウト済みなら古いマーカーとして削除する。
|
||||
|
||||
## 10. 変更履歴
|
||||
|
||||
### 2026-05-05
|
||||
|
||||
- EA削除後にチャート左上のステータスコメントが残らないよう、`OnDeinit()` で `Comment("")` と `ChartRedraw(0)` を実行する終了処理を追加。
|
||||
- `HIT-EA_refactor_ver5.mq5` に `CSLTPManager` と専用チャートパネル `SLTPManagerPanel.mqh` を接続し、UIからブレークイーブン、時間経過BE、アクティブトレーリング、TP進捗SL、急変時SL引き締めを操作できるようにした。
|
||||
- SLTP管理を `OnTick` の時間制限処理直後に実行し、Python結果待ちやスプレッド判定に依存せず既存ポジション保護を継続する仕様を追加。
|
||||
- SLTPパネル用inputと、通常ブレークイーブン/アクティブトレーリングの排他検証、`APPLY` 時の数値検証を追加。
|
||||
- `HIT-EA_refactor_ver5.mq5` の関数群を用途別 `.mqh` に分割。
|
||||
- `OnInit`, `OnDeinit`, `OnTick`、input、グローバル状態はEA本体に残し、動作ロジックは `Include/MyLib/` 配下へ移動。
|
||||
- 現行コードに合わせて、`CreateProcessW` ベースのPythonプロセス監視、M15フィルタ、`market_state` 0..6、`spread_limit = 60` を仕様へ反映。
|
||||
|
||||
### 2026-05-02
|
||||
|
||||
- `res_chk=0` 時にエントリー送信を抑止する分岐を追加。
|
||||
- 時間制限処理を、Python完了待ち・スプレッド制限より前に移動。
|
||||
- `initial_order` の初回処理フラグをH4用・H1用に分離。
|
||||
- OHLC取得を `CopyRates` 中心に変更し、確定足のみをPythonへ渡す仕様に変更。
|
||||
@@ -0,0 +1,56 @@
|
||||
# SLTPManager Specification
|
||||
|
||||
## 1. Overview
|
||||
`SLTPManager.mqh` provides a reusable MQL5 stop-loss manager for Expert Advisors. It scans all open positions, selects only positions matching a configured symbol and magic number, and updates SL values with `CTrade::PositionModify()` while preserving each position's existing TP.
|
||||
|
||||
## 2. Indicators
|
||||
- No standard or custom indicators are used.
|
||||
- The manager uses `SYMBOL_DIGITS`, `SYMBOL_POINT`, `SYMBOL_TRADE_STOPS_LEVEL`, `SYMBOL_TRADE_FREEZE_LEVEL`, and live bid/ask ticks from the configured symbol.
|
||||
|
||||
## 3. Inputs and Settings
|
||||
The reusable class stores settings through setter methods rather than direct `input` declarations. `SLTPManagerSample.mq5` exposes the following example inputs:
|
||||
|
||||
- `input_magic_number`: Magic number used to select managed positions.
|
||||
- `input_slippage_points`: Deviation in points passed to `CTrade`.
|
||||
- `input_use_breakeven`: Enables the normal break-even mode.
|
||||
- `input_breakeven_trigger_pips`: Profit threshold for normal break-even.
|
||||
- `input_breakeven_buffer_pips`: Profit-side SL buffer from entry after normal break-even triggers.
|
||||
- `input_use_elapsed_breakeven`: Enables elapsed-time break-even.
|
||||
- `input_elapsed_breakeven_hours`: Holding time required before the time-based break-even move is allowed. Fractional hours are supported.
|
||||
- `input_elapsed_breakeven_buffer_pips`: Profit-side SL buffer from entry after elapsed-time break-even triggers.
|
||||
- `input_use_active_trailing`: Enables active break-even plus step trailing.
|
||||
- `input_active_breakeven_pips`: Profit threshold for the first active break-even move.
|
||||
- `input_active_stop_loss_offset_pips`: Locked profit offset from entry at activation.
|
||||
- `input_active_step_trigger_pips`: Additional profit interval required for each trailing step.
|
||||
- `input_active_step_move_pips`: SL movement added per completed trailing step.
|
||||
- `input_use_tp_progress_stop`: Enables TP-progress-based SL locking.
|
||||
- `input_tp_progress_trigger_percent`: Current price progress toward TP required before locking SL.
|
||||
- `input_tp_progress_sl_lock_percent`: Entry-to-TP percentage where SL is moved after the trigger.
|
||||
|
||||
## 4. Entry and Exit Conditions
|
||||
- The manager does not open or close positions.
|
||||
- `ManagePositions()` scans `PositionsTotal()` and processes only positions where `POSITION_MAGIC` equals the configured magic number and `POSITION_SYMBOL` equals the configured symbol.
|
||||
- BUY profit calculations use Bid and price increases as the favorable direction.
|
||||
- SELL profit calculations use Ask and price decreases as the favorable direction.
|
||||
- Normal break-even moves SL to entry plus/minus the configured buffer once profit reaches the trigger. BUY positions use entry + `input_breakeven_buffer_pips`, and SELL positions use entry - `input_breakeven_buffer_pips`.
|
||||
- Elapsed-time break-even uses the position `POSITION_TIME` and the current tick time. When holding time is at least `input_elapsed_breakeven_hours` and the current rate has crossed the entry price, SL moves to entry plus/minus `input_elapsed_breakeven_buffer_pips`. BUY positions require Bid above entry, and SELL positions require Ask below entry.
|
||||
- Active trailing first moves SL to the active offset once profit reaches `input_active_breakeven_pips`, then adds `input_active_step_move_pips` for every completed `input_active_step_trigger_pips`.
|
||||
- TP-progress locking runs only when TP exists and the TP is in the correct profit direction.
|
||||
|
||||
## 5. Risk Management
|
||||
- SL updates are monotonic: BUY stops only move upward and SELL stops only move downward.
|
||||
- When multiple rules produce candidates on the same tick, BUY uses the highest candidate and SELL uses the lowest candidate.
|
||||
- TP is never changed; the current TP is passed back unchanged during `PositionModify()`.
|
||||
- Pip conversion follows the existing `AdjustPoint()` convention: `GOLD` / `XAUUSD` use `1 pip = 0.1`, 2/3-digit symbols use `0.01`, and 4/5-digit symbols use `0.0001`.
|
||||
- Candidate SL prices are normalized with `NormalizeDouble()` using the symbol digits.
|
||||
- Broker stop and freeze levels are checked with `SYMBOL_TRADE_STOPS_LEVEL`, `SYMBOL_TRADE_FREEZE_LEVEL`, and `SYMBOL_POINT` before modification.
|
||||
- `ValidateSettings()` rejects simultaneous normal break-even and active trailing because those modes are mutually exclusive.
|
||||
- Elapsed-time break-even can be enabled or disabled independently from normal break-even and active trailing. If multiple candidates are valid, the existing best-candidate selection rule is used.
|
||||
- `ValidateSettings()` checks that elapsed-time break-even hours and buffer pips are non-negative.
|
||||
- Failed SL modifications log ticket, symbol, magic number, trade retcode, `GetLastError()`, and requested SL.
|
||||
|
||||
## 6. Changelog
|
||||
- 2026-05-05: Aligned pip conversion with the existing `AdjustPoint()` convention so `GOLD` / `XAUUSD` use `1 pip = 0.1`. A panel input of `2.0` pips now maps to a `0.2` price distance on `GOLD`.
|
||||
- 2026-05-05: Added elapsed-time break-even settings `input_use_elapsed_breakeven`, `input_elapsed_breakeven_hours`, and `input_elapsed_breakeven_buffer_pips`, allowing an independent SL move to entry plus/minus buffer after the configured holding time when the current rate has crossed entry.
|
||||
- 2026-05-05: Added the configurable normal break-even buffer `input_breakeven_buffer_pips` and clarified that SL moves to entry plus/minus the buffer after the trigger.
|
||||
- 2026-05-05: Added reusable `CSLTPManager`, example EA `SLTPManagerSample.mq5`, normal break-even, active trailing, TP-progress SL locking, monotonic SL selection, broker stop/freeze checks, and validation for mutually exclusive modes.
|
||||
@@ -0,0 +1,56 @@
|
||||
# SLTPManager 仕様書
|
||||
|
||||
## 1. 概要
|
||||
`SLTPManager.mqh` は、複数EAから再利用できる MQL5 用ストップロス管理ライブラリです。全ポジションを走査し、指定されたシンボルとマジックナンバーに一致するポジションのみを対象に、既存TPを維持したまま `CTrade::PositionModify()` で SL を更新します。
|
||||
|
||||
## 2. 使用インジケータ
|
||||
- 標準・カスタムインジケータは使用しません。
|
||||
- 対象シンボルの `SYMBOL_DIGITS`, `SYMBOL_POINT`, `SYMBOL_TRADE_STOPS_LEVEL`, `SYMBOL_TRADE_FREEZE_LEVEL` と Bid/Ask tick を使用します。
|
||||
|
||||
## 3. パラメータ設定
|
||||
共通クラス自体は `input` を持たず、setter 経由で設定値を保持します。利用例の `SLTPManagerSample.mq5` では以下の input を定義しています。
|
||||
|
||||
- `input_magic_number`: 管理対象ポジションを識別するマジックナンバー。
|
||||
- `input_slippage_points`: `CTrade` に設定する許容偏差ポイント。
|
||||
- `input_use_breakeven`: 通常ブレークイーブンを有効化します。
|
||||
- `input_breakeven_trigger_pips`: 通常ブレークイーブンを開始する含み益幅。
|
||||
- `input_breakeven_buffer_pips`: 通常ブレークイーブン時に建値から利益方向へ SL をずらすバッファー幅。
|
||||
- `input_use_elapsed_breakeven`: 保有時間ベースのブレークイーブンを有効化します。
|
||||
- `input_elapsed_breakeven_hours`: 建値超過時のSL移動を許可するまでの保有時間。小数指定も可能です。
|
||||
- `input_elapsed_breakeven_buffer_pips`: 保有時間ベースのブレークイーブン時に建値から利益方向へ SL をずらすバッファー幅。
|
||||
- `input_use_active_trailing`: アクティブ・ブレークイーブン兼トレーリングを有効化します。
|
||||
- `input_active_breakeven_pips`: 最初の建値移動を開始する含み益幅。
|
||||
- `input_active_stop_loss_offset_pips`: 起動時に建値から確保する利益幅。
|
||||
- `input_active_step_trigger_pips`: トレーリングを1段進めるために必要な追加利益幅。
|
||||
- `input_active_step_move_pips`: 1段ごとに SL を有利方向へ動かす幅。
|
||||
- `input_use_tp_progress_stop`: TP到達率に応じた SL 更新を有効化します。
|
||||
- `input_tp_progress_trigger_percent`: TP到達率SLを起動する現在価格のTP到達率。
|
||||
- `input_tp_progress_sl_lock_percent`: 起動後に SL を移動する建値からTPまでの割合。
|
||||
|
||||
## 4. エントリー/エグジット条件
|
||||
- このライブラリは新規エントリーや決済を行いません。
|
||||
- `ManagePositions()` は `PositionsTotal()` で全ポジションを走査し、`POSITION_MAGIC` と `POSITION_SYMBOL` が設定値に一致するポジションのみ処理します。
|
||||
- BUY の利益計算は Bid を基準にし、価格上昇方向を利益方向とします。
|
||||
- SELL の利益計算は Ask を基準にし、価格下落方向を利益方向とします。
|
||||
- 通常ブレークイーブンは、含み益が指定pipsへ到達した時点で SL を建値 +/- バッファーへ移動します。BUY は建値 + `input_breakeven_buffer_pips`、SELL は建値 - `input_breakeven_buffer_pips` へ設定します。
|
||||
- 保有時間ベースのブレークイーブンは、ポジションの `POSITION_TIME` から現在tick時刻までが `input_elapsed_breakeven_hours` 以上で、かつ現在レートが建値を超えている場合に SL を建値 +/- `input_elapsed_breakeven_buffer_pips` へ移動します。BUY は Bid が建値を上回る場合、SELL は Ask が建値を下回る場合のみ対象です。
|
||||
- アクティブトレーリングは、`input_active_breakeven_pips` 到達時に SL を建値付近へ移動し、その後 `input_active_step_trigger_pips` ごとに `input_active_step_move_pips` 分だけ SL を更新します。
|
||||
- TP到達率SLは、TPが設定され、かつTPが利益方向にあるポジションのみ対象にします。
|
||||
|
||||
## 5. リスク管理
|
||||
- SL は BUY では上方向、SELL では下方向の改善時のみ更新します。
|
||||
- 複数条件が同時に成立した場合、BUY は最も高いSL候補、SELL は最も低いSL候補を採用します。
|
||||
- TP は変更せず、`PositionModify()` 実行時も現在TPをそのまま渡します。
|
||||
- pips換算は既存の `AdjustPoint()` 仕様に合わせ、`GOLD` / `XAUUSD` は `1 pip = 0.1`、2/3桁シンボルは `0.01`、4/5桁シンボルは `0.0001` として扱います。
|
||||
- SL候補は `NormalizeDouble()` により対象シンボルの桁数へ正規化します。
|
||||
- 更新前に `SYMBOL_TRADE_STOPS_LEVEL`, `SYMBOL_TRADE_FREEZE_LEVEL`, `SYMBOL_POINT` を使ってブローカー制約を確認します。
|
||||
- `ValidateSettings()` は通常ブレークイーブンとアクティブトレーリングの同時ONを設定エラーとして拒否します。
|
||||
- 保有時間ベースのブレークイーブンは通常ブレークイーブンやアクティブトレーリングとは独立してON/OFFでき、同時成立時は既存の最良SL候補選択に従います。
|
||||
- `ValidateSettings()` は保有時間ベースのブレークイーブンについて、保有時間とバッファーpipsが負値でないことを検証します。
|
||||
- SL更新失敗時は ticket、symbol、magic number、trade retcode、`GetLastError()`、要求SLをログ出力します。
|
||||
|
||||
## 6. 変更履歴
|
||||
- 2026-05-05: pips換算を既存の `AdjustPoint()` 仕様に合わせ、`GOLD` / `XAUUSD` は `1 pip = 0.1` として扱うように変更。パネルで入力した `2.0` pips が `GOLD` で `0.2` の価格幅として反映される。
|
||||
- 2026-05-05: 保有時間ベースのブレークイーブン設定 `input_use_elapsed_breakeven`, `input_elapsed_breakeven_hours`, `input_elapsed_breakeven_buffer_pips` を追加し、指定時間経過後に現在レートが建値を超えていればSLを建値 +/− バッファーへ移動する独立機能を追加。
|
||||
- 2026-05-05: 通常ブレークイーブンに任意pipsのバッファー設定 `input_breakeven_buffer_pips` を追加し、SLを建値 +/− バッファーへ移動する仕様として明確化。
|
||||
- 2026-05-05: 再利用可能な `CSLTPManager`、利用例EA `SLTPManagerSample.mq5`、通常ブレークイーブン、アクティブトレーリング、TP到達率SL、単調なSL候補選択、stop/freeze level 検証、排他設定の検証を追加。
|
||||
@@ -0,0 +1,55 @@
|
||||
# TradingPanel Specification
|
||||
|
||||
## 1. Overview
|
||||
`TradingPanel.mq5` is an MQL5 Expert Advisor that manages `_Symbol` positions for a configured magic number. It provides chart-panel controls for key SL/TP parameters and manages timed exits, break-even stops, step-based trailing stops, and aggregate break-even lines.
|
||||
|
||||
## 2. Indicators
|
||||
- The EA keeps a Deviation Band related handle/value for display.
|
||||
- SuperTrend-based stop management, display text, and timeframe combo boxes are not used.
|
||||
|
||||
## 3. Inputs
|
||||
- `exit_time_interval`: Holding time in hours before timed close. The panel value is converted to seconds inside `UpdateInputValues()`.
|
||||
- `slippage`: Allowed slippage.
|
||||
- `magic_number`: Magic number used to identify managed positions.
|
||||
- `take_profit_pips`: Initial TP distance.
|
||||
- `default_sl`: Initial SL distance.
|
||||
- `stop_offset_pips`: Stop-loss offset.
|
||||
- `enable_breakeven`: Enables break-even handling in `ManageStops()`.
|
||||
- `breakeven_pips`: Profit threshold for break-even activation.
|
||||
- `stop_loss_offset_pips`: Margin from entry price for the break-even SL.
|
||||
- `step_trigger_pips`: Profit interval used to calculate trailing steps.
|
||||
- `step_move_pips`: SL movement per trailing step.
|
||||
- `tp_edit_pips`: Default panel increment/decrement for TP edits.
|
||||
- `range_pips`: Range display setting.
|
||||
- `isTradingTimeEnabled`, `TradeStartHour`, `TradeStartMin`, `TradeEndHour`, `TradeEndMin`: Trading-time filter settings.
|
||||
|
||||
## 4. Entry and Exit Conditions
|
||||
- `CloseTimedPositions()` closes matching `_Symbol` and magic-number positions only when `timelimit_exit` is ON and the current time has reached the position entry time plus `exit_time_interval`. The check runs from both `OnTick()` and `OnTimer()` independently of the trading-time filter.
|
||||
- `ApplyInitialStops()` scans existing positions on EA startup and trade-transaction detection. For positions matching `_Symbol` and `magic_number`, it backfills only missing SL/TP values from `default_sl` / `take_profit_pips`. Existing SL/TP values are not overwritten.
|
||||
- `ManageStops(enable_breakeven)` scans both BUY and SELL positions in a single call.
|
||||
- When `enable_breakeven=true`, trailing does not start before profit reaches `breakeven_pips`. Once reached, the EA moves SL to entry +/- `stop_loss_offset_pips`, then switches to step-based trailing.
|
||||
- When `enable_breakeven=false`, the EA skips the break-even move and starts step-based trailing once profit reaches `step_trigger_pips`.
|
||||
- The trailing SL is calculated from the entry price using the number of completed profit steps and `step_move_pips`.
|
||||
|
||||
## 5. Risk Management
|
||||
- Stop management and timed close are limited to positions matching `_Symbol` and `magic_number`.
|
||||
- Initial SL/TP backfill places BUY SL `default_sl` pips below entry and TP `take_profit_pips` pips above entry. For SELL positions, SL is placed `default_sl` pips above entry and TP `take_profit_pips` pips below entry.
|
||||
- Before each SL/TP update, the EA checks `SYMBOL_TRADE_STOPS_LEVEL` and `SYMBOL_TRADE_FREEZE_LEVEL`. These broker constraints are point-based, so the checks use `SYMBOL_POINT`.
|
||||
- `CTrade::PositionModify()` return values are checked. On failure, the EA logs the retcode, `GetLastError()`, and the requested SL.
|
||||
- SL updates are monotonic: BUY stops only move upward and SELL stops only move downward.
|
||||
|
||||
## 6. Internal Structure
|
||||
- `Experts/MyProject/TradingPanel.mq5`: Keeps the event entry points, including `OnInit()`, `OnDeinit()`, `OnTimer()`, `OnTick()`, `OnChartEvent()`, `OnTradeTransaction()`, and trading-time checks.
|
||||
- `Include/MyLib/Panel/TradingPanelPanel.mqh`: Defines `CTradingPanelPanel`, which owns the chart panel, input validation, button state updates, and TP adjustment actions.
|
||||
- `Include/MyLib/Common/TradingPanelSymbolUtils.mqh`: Provides shared pip conversion and order filling policy helpers.
|
||||
- `Include/MyLib/Trading/TradingPanelTradingManagers.mqh`: Defines `CTradingPanelStopManager`, `CTradingPanelPositionManager`, and `CTradingPanelBreakEvenLineManager` for SL/TP management, timed exits, position counting, and aggregate break-even line handling.
|
||||
|
||||
## 7. Changelog
|
||||
- 2026-05-04: Added initial SL/TP backfill for existing positions matching `_Symbol` and `magic_number` on EA startup and trade-transaction detection. The EA now preserves existing SL/TP values, skips candidates that are too close to stop/freeze levels, and logs skipped or failed updates.
|
||||
- 2026-05-03: Refactored the EA for readability and maintainability. The main `.mq5` now focuses on event entry points, while panel handling, stop management, position management, aggregate break-even lines, and symbol helpers are split into imported `.mqh` classes/helpers.
|
||||
- 2026-05-03: Renamed the EA to `TradingPanel`. Updated the EA source, external `.mqh` files under MyLib, specification filenames, and internal references to use the `TradingPanel` name consistently.
|
||||
- 2026-05-03: Changed `ManageStops()` to `ManageStops(bool breakeven_enabled)`. Added argument-based break-even ON/OFF behavior and switched to BE-gated step trailing when enabled. Removed SuperTrend-based stop management, display references, timeframe combo boxes, and unused `check_expand_pips`.
|
||||
- 2026-05-03: Renamed `order_interval` to `exit_time_interval` and changed the input unit to hours. `UpdateInputValues()` now converts it to seconds, and timed close runs only when `timelimit_exit` is ON and `entry_time + exit_time_interval` has been reached.
|
||||
- 2026-05-03: Made timed close independent from the trading-time filter and monitored it from `OnTimer()` as well. Added `_Symbol` filtering to timed close. Corrected stop/freeze level checks to point units and centralized SL modification failure logging.
|
||||
- 2026-05-03: Removed unused inputs, globals, constants, DLL import, and unused panel component declarations.
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
# TradingPanel 仕様書
|
||||
|
||||
## 1. 概要
|
||||
`TradingPanel.mq5` は、指定マジックナンバーの `_Symbol` ポジションを管理する MQL5 Expert Advisor です。チャート上の操作パネルから主要な SL/TP 設定を変更し、ポジション保有時間、ブレークイーブン、ステップ式トレールストップ、総建値ラインを管理します。
|
||||
|
||||
## 2. 使用インジケータ
|
||||
- Deviation Band 系の値表示用ハンドルを保持します。
|
||||
- SuperTrend 関連のストップ管理・表示・コンボボックスは使用しません。
|
||||
|
||||
## 3. パラメータ設定
|
||||
- `exit_time_interval`: 時間制限クローズまでの保有時間(時間)。パネル入力値は `UpdateInputValues()` 内で秒へ変換されます。
|
||||
- `slippage`: 許容スリッページ。
|
||||
- `magic_number`: 管理対象ポジションを識別するマジックナンバー。
|
||||
- `take_profit_pips`: 初期 TP 幅。
|
||||
- `default_sl`: 初期 SL 幅。
|
||||
- `stop_offset_pips`: SL オフセット。
|
||||
- `enable_breakeven`: `ManageStops()` のブレークイーブン処理を有効化する。
|
||||
- `breakeven_pips`: ブレークイーブン判定に使う含み益幅。
|
||||
- `stop_loss_offset_pips`: 建値から SL を置くマージン。
|
||||
- `step_trigger_pips`: トレール更新を判定する利益ステップ。
|
||||
- `step_move_pips`: 1 ステップごとに SL を有利方向へ動かす幅。
|
||||
- `tp_edit_pips`: パネルから TP を増減する初期幅。
|
||||
- `range_pips`: レンジ判定表示用設定。
|
||||
- `isTradingTimeEnabled`, `TradeStartHour`, `TradeStartMin`, `TradeEndHour`, `TradeEndMin`: 取引時間制限。
|
||||
|
||||
## 4. エントリー/エグジット条件
|
||||
- `CloseTimedPositions()` は、`timelimit_exit` が ON の場合のみ、ポジションの建値時刻に `exit_time_interval` を加算した時刻へ到達した対象マジックナンバーかつ `_Symbol` のポジションを成行でクローズします。この監視は取引時間フィルターとは独立して `OnTick()` と `OnTimer()` から実行します。
|
||||
- `ApplyInitialStops()` は、EA 起動時および取引トランザクション検知時に、対象マジックナンバーかつ `_Symbol` の既存ポジションを走査し、未設定の SL/TP のみ `default_sl` / `take_profit_pips` から補完します。既に設定済みの SL/TP は上書きしません。
|
||||
- `ManageStops(enable_breakeven)` は BUY/SELL 両方のポジションを 1 回の呼び出しで走査します。
|
||||
- `enable_breakeven=true` の場合、含み益が `breakeven_pips` 未満の間はトレールへ移行しません。閾値到達後、SL を建値 +/- `stop_loss_offset_pips` に更新し、その後ステップ式トレールへ移行します。
|
||||
- `enable_breakeven=false` の場合、建値移動は行わず、含み益が `step_trigger_pips` 以上になった時点でステップ式トレールを開始します。
|
||||
- トレール SL は、含み益のステップ数に応じて建値から `step_move_pips` 単位で有利方向へ更新します。
|
||||
|
||||
## 5. リスク管理
|
||||
- すべてのストップ管理および時間制限クローズ対象は `_Symbol` かつ `magic_number` が一致するポジションに限定します。
|
||||
- 初期 SL/TP 補完は、BUY では建値から `default_sl` pips 下に SL、`take_profit_pips` pips 上に TP を置き、SELL では建値から `default_sl` pips 上に SL、`take_profit_pips` pips 下に TP を置きます。
|
||||
- SL/TP 更新前に `SYMBOL_TRADE_STOPS_LEVEL` と `SYMBOL_TRADE_FREEZE_LEVEL` を確認します。これらのブローカー制約はポイント単位のため、判定には `SYMBOL_POINT` を使用します。
|
||||
- `CTrade::PositionModify()` の戻り値を確認し、失敗時は retcode、`GetLastError()`、設定予定 SL をログ出力します。
|
||||
- SL は BUY では上方向、SELL では下方向の改善時のみ更新します。
|
||||
|
||||
## 6. 内部構成
|
||||
- `Experts/MyProject/TradingPanel.mq5`: `OnInit()`, `OnDeinit()`, `OnTimer()`, `OnTick()`, `OnChartEvent()`, `OnTradeTransaction()` のイベント入口と取引時間判定を保持します。
|
||||
- `Include/MyLib/Panel/TradingPanelPanel.mqh`: `CTradingPanelPanel` として操作パネル、入力値検証、ボタン状態管理、TP 調整イベントの生成を担当します。
|
||||
- `Include/MyLib/Common/TradingPanelSymbolUtils.mqh`: pips 換算と注文執行ポリシー取得の共通関数を提供します。
|
||||
- `Include/MyLib/Trading/TradingPanelTradingManagers.mqh`: `CTradingPanelStopManager`, `CTradingPanelPositionManager`, `CTradingPanelBreakEvenLineManager` を定義し、SL/TP 管理、時間制限クローズ、ポジション集計、総建値ライン管理を担当します。
|
||||
|
||||
## 7. 変更履歴
|
||||
- 2026-05-04: EA 起動時および取引トランザクション検知時に、対象 `_Symbol` と `magic_number` が一致する既存ポジションへ未設定の初期 SL/TP を補完する処理を追加。既存 SL/TP は上書きせず、stop/freeze level に近い候補はスキップしてログ出力する仕様を追加。
|
||||
- 2026-05-03: 可読性・保守性向上のため、EA 本体をイベント入口中心へ整理し、パネル、ストップ管理、ポジション管理、総建値ライン管理、シンボル共通処理を `.mqh` のクラス/共通関数へ分割。
|
||||
- 2026-05-03: EA 名を `TradingPanel` に変更。EA 本体、MyLib 配下の外部 `.mqh`、仕様書ファイル名と内部参照を `TradingPanel` 名へ統一。
|
||||
- 2026-05-03: `ManageStops()` を `ManageStops(bool breakeven_enabled)` に変更。ブレークイーブン ON/OFF を引数で切り替え、BE ON 時は `breakeven_pips` 到達後にステップ式トレールへ移行する仕様へ変更。SuperTrend ベースのストップ管理・表示・コンボボックスを削除し、未使用の `check_expand_pips` を削除。
|
||||
- 2026-05-03: `order_interval` を `exit_time_interval` に変更し、時間単位の入力へ変更。`UpdateInputValues()` で秒へ変換し、`timelimit_exit` ON 時のみ `entry_time + exit_time_interval` 到達で時間制限クローズする仕様へ変更。
|
||||
- 2026-05-03: 時間制限クローズを取引時間フィルターから独立させ、`OnTimer()` でも監視するよう変更。時間制限クローズに `_Symbol` フィルターを追加。stop/freeze level 判定をポイント単位へ修正し、SL 更新失敗ログを共通化。
|
||||
- 2026-05-03: 未使用の input、グローバル変数、未使用定数、未使用 DLL import、未使用パネル部品宣言を削除。
|
||||
|
||||
@@ -0,0 +1,387 @@
|
||||
# Codex用 MQL5 SL/TP管理ファイル作成指示
|
||||
|
||||
## 目的
|
||||
|
||||
`TradingPanelTradingManagers.mqh` を参考にして、他のEAでも再利用できる
|
||||
SL/TP管理用の共通 `.mqh` ファイルを作成する。
|
||||
|
||||
作成ファイル名の例:
|
||||
|
||||
```text
|
||||
SLTPManager.mqh
|
||||
```
|
||||
|
||||
このファイルは、EA本体から `#include` して使用できる構成にする。
|
||||
|
||||
---
|
||||
|
||||
## 基本方針
|
||||
|
||||
- MQL5で実装する。
|
||||
- `CTrade` を使用してポジションのSL/TPを更新する。
|
||||
- 既存EAに依存しすぎない汎用的な設計にする。
|
||||
- クラス化して、他EAから再利用しやすい構成にする。
|
||||
- TPは原則として変更しない。
|
||||
- SL更新のみを行う。
|
||||
- エラー時は `Print()` で分かりやすくログを出力する。
|
||||
- コンパイルエラーが出ないMQL5コードにする。
|
||||
|
||||
---
|
||||
|
||||
## 管理対象ポジション
|
||||
|
||||
以下の条件を満たすポジションのみ管理対象にする。
|
||||
|
||||
1. `POSITION_MAGIC` が指定された magic number と一致する
|
||||
2. `POSITION_SYMBOL` が指定された symbol と一致する
|
||||
|
||||
実装では `PositionsTotal()` を使用して全ポジションを走査し、
|
||||
条件に一致するポジションのみ処理する。
|
||||
|
||||
BUY / SELL の両方に対応する。
|
||||
|
||||
---
|
||||
|
||||
## BUY / SELL の基準価格
|
||||
|
||||
利益pipsやSL更新位置の計算では、BUY / SELL の方向を正しく扱う。
|
||||
|
||||
- BUYポジション
|
||||
- 現在価格は `Bid` を基準にする。
|
||||
- 利益方向は価格上昇方向。
|
||||
- SELLポジション
|
||||
- 現在価格は `Ask` を基準にする。
|
||||
- 利益方向は価格下落方向。
|
||||
|
||||
---
|
||||
|
||||
## pips計算
|
||||
|
||||
pipsから価格差への変換関数を用意する。
|
||||
|
||||
例:
|
||||
|
||||
- 5桁・3桁銘柄では `Point * 10`
|
||||
- 4桁・2桁銘柄では `Point`
|
||||
|
||||
ただし、XAUUSDなどの銘柄でも使えるように、
|
||||
対象シンボルの以下の情報を使用して計算する。
|
||||
|
||||
```mql5
|
||||
SYMBOL_DIGITS
|
||||
SYMBOL_POINT
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## SL更新時の安全条件
|
||||
|
||||
SLは不利な方向へ戻さない。
|
||||
|
||||
BUYの場合:
|
||||
|
||||
- 新しいSLが現在SLより上の場合のみ更新する。
|
||||
- 現在SLが未設定の場合は更新可能。
|
||||
|
||||
SELLの場合:
|
||||
|
||||
- 新しいSLが現在SLより下の場合のみ更新する。
|
||||
- 現在SLが未設定の場合は更新可能。
|
||||
|
||||
また、以下も考慮する。
|
||||
|
||||
- `SYMBOL_TRADE_STOPS_LEVEL`
|
||||
- `SYMBOL_TRADE_FREEZE_LEVEL`
|
||||
- `NormalizeDouble()`
|
||||
- `PositionModify()` 失敗時のログ出力
|
||||
|
||||
---
|
||||
|
||||
# 機能要件
|
||||
|
||||
## 1. 通常ブレークイーブン機能
|
||||
|
||||
ブレークイーブン設定を実装する。
|
||||
|
||||
### パラメーター例
|
||||
|
||||
```mql5
|
||||
bool use_breakeven;
|
||||
double breakeven_trigger_pips;
|
||||
double breakeven_offset_pips;
|
||||
```
|
||||
|
||||
### 動作
|
||||
|
||||
- `use_breakeven == true` の場合のみ動作する。
|
||||
- 現在利益が `breakeven_trigger_pips` 以上になったらSLを建値付近へ移動する。
|
||||
- SLの移動先は以下とする。
|
||||
|
||||
BUYの場合:
|
||||
|
||||
```text
|
||||
entry_price + breakeven_offset_pips
|
||||
```
|
||||
|
||||
SELLの場合:
|
||||
|
||||
```text
|
||||
entry_price - breakeven_offset_pips
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. アクティブ・ブレークイーブン兼トレーリング機能
|
||||
|
||||
ブレークイーブン到達後に、段階的にSLを更新する機能を実装する。
|
||||
|
||||
### パラメーター
|
||||
|
||||
```mql5
|
||||
bool use_active_trailing;
|
||||
double active_breakeven_pips;
|
||||
double active_stop_loss_offset_pips;
|
||||
double active_step_trigger_pips;
|
||||
double active_step_move_pips;
|
||||
```
|
||||
|
||||
### パラメーターの意味
|
||||
|
||||
#### `active_breakeven_pips`
|
||||
|
||||
建値移動を開始する利益幅をpipsで指定する。
|
||||
|
||||
#### `active_stop_loss_offset_pips`
|
||||
|
||||
確保する利益として、建値からずらす幅をpipsで指定する。
|
||||
|
||||
#### `active_step_trigger_pips`
|
||||
|
||||
トレーリングを1段進めるために必要な利益間隔をpipsで指定する。
|
||||
|
||||
#### `active_step_move_pips`
|
||||
|
||||
1段ごとにSLを移動する幅をpipsで指定する。
|
||||
|
||||
### 動作
|
||||
|
||||
- `use_active_trailing == true` の場合のみ動作する。
|
||||
- 利益が `active_breakeven_pips` に到達したら、まずSLを建値付近へ移動する。
|
||||
- その後、利益が `active_step_trigger_pips` 増えるごとに、SLを `active_step_move_pips` ずつ利益方向へ移動する。
|
||||
- SLは不利な方向へ戻さない。
|
||||
|
||||
### 計算例
|
||||
|
||||
BUYの場合:
|
||||
|
||||
```text
|
||||
entry_price = 100.000
|
||||
active_breakeven_pips = 20
|
||||
active_stop_loss_offset_pips = 2
|
||||
active_step_trigger_pips = 10
|
||||
active_step_move_pips = 5
|
||||
```
|
||||
|
||||
利益が20pips到達:
|
||||
|
||||
```text
|
||||
SL = entry_price + 2pips
|
||||
```
|
||||
|
||||
利益が30pips到達:
|
||||
|
||||
```text
|
||||
SL = entry_price + 7pips
|
||||
```
|
||||
|
||||
利益が40pips到達:
|
||||
|
||||
```text
|
||||
SL = entry_price + 12pips
|
||||
```
|
||||
|
||||
SELLの場合は逆方向で計算する。
|
||||
|
||||
---
|
||||
|
||||
## 3. 通常ブレークイーブンとアクティブトレーリングの排他制御
|
||||
|
||||
以下の2つは同時にONにできない。
|
||||
|
||||
```mql5
|
||||
use_breakeven
|
||||
use_active_trailing
|
||||
```
|
||||
|
||||
両方が `true` の場合は、初期化時にエラーとして扱う。
|
||||
|
||||
例:
|
||||
|
||||
```mql5
|
||||
bool ValidateSettings()
|
||||
```
|
||||
|
||||
を用意し、両方ONの場合は `false` を返して `Print()` でエラーを出す。
|
||||
|
||||
EA側では `ValidateSettings()` が `false` の場合、`INIT_FAILED` を返す想定にする。
|
||||
|
||||
---
|
||||
|
||||
## 4. TP到達率に応じたSL更新機能
|
||||
|
||||
建値とTPの距離に対する現在価格の到達割合に応じて、SLを更新する機能を実装する。
|
||||
|
||||
### パラメーター例
|
||||
|
||||
```mql5
|
||||
bool use_tp_progress_stop;
|
||||
double tp_progress_trigger_percent;
|
||||
double tp_progress_sl_lock_percent;
|
||||
```
|
||||
|
||||
### 動作
|
||||
|
||||
- `use_tp_progress_stop == true` の場合のみ動作する。
|
||||
- TPが設定されているポジションのみ対象にする。
|
||||
- エントリー価格からTPまでの距離を100%とする。
|
||||
- 現在価格が `tp_progress_trigger_percent` に到達したら、SLを `tp_progress_sl_lock_percent` の位置へ移動する。
|
||||
- 通常ブレークイーブン、アクティブトレーリングとは独立して動作する。
|
||||
- ただし、SLは不利な方向へ戻さない。
|
||||
|
||||
### BUYの例
|
||||
|
||||
```text
|
||||
entry_price = 100.000
|
||||
take_profit = 110.000
|
||||
tp_progress_trigger_percent = 50
|
||||
tp_progress_sl_lock_percent = 20
|
||||
```
|
||||
|
||||
現在価格が105.000に到達したら、SLを102.000へ移動する。
|
||||
|
||||
### SELLの例
|
||||
|
||||
```text
|
||||
entry_price = 100.000
|
||||
take_profit = 90.000
|
||||
tp_progress_trigger_percent = 50
|
||||
tp_progress_sl_lock_percent = 20
|
||||
```
|
||||
|
||||
現在価格が95.000に到達したら、SLを98.000へ移動する。
|
||||
|
||||
---
|
||||
|
||||
## 5. 複数条件が同時に成立した場合
|
||||
|
||||
複数のSL更新候補がある場合は、最も有利なSLのみを採用する。
|
||||
|
||||
BUYの場合:
|
||||
|
||||
- 候補SLの中で最も高い価格を採用する。
|
||||
|
||||
SELLの場合:
|
||||
|
||||
- 候補SLの中で最も低い価格を採用する。
|
||||
|
||||
その上で、現在SLより有利な場合のみ `PositionModify()` を実行する。
|
||||
|
||||
---
|
||||
|
||||
# 想定するクラス構成
|
||||
|
||||
例:
|
||||
|
||||
```mql5
|
||||
class CSLTPManager
|
||||
{
|
||||
private:
|
||||
ulong m_magic;
|
||||
string m_symbol;
|
||||
|
||||
public:
|
||||
CSLTPManager();
|
||||
|
||||
void SetMagicNumber(ulong magic);
|
||||
void SetSymbol(string symbol);
|
||||
|
||||
bool ValidateSettings();
|
||||
void ManagePositions();
|
||||
|
||||
private:
|
||||
bool IsTargetPosition();
|
||||
double PipToPrice(double pips);
|
||||
double GetProfitPips(ENUM_POSITION_TYPE type, double open_price);
|
||||
bool ModifyStopLoss(ulong ticket, double new_sl, double current_tp);
|
||||
|
||||
bool CalcBreakevenSL(...);
|
||||
bool CalcActiveTrailingSL(...);
|
||||
bool CalcTpProgressSL(...);
|
||||
};
|
||||
```
|
||||
|
||||
実際の引数や構成は、MQL5としてコンパイルしやすい形に調整してよい。
|
||||
|
||||
---
|
||||
|
||||
# EA側での使用例
|
||||
|
||||
作成した `.mqh` をEAから利用する簡単なサンプルも作成する。
|
||||
|
||||
```mql5
|
||||
#include "SLTPManager.mqh"
|
||||
|
||||
input ulong MagicNumber = 123456;
|
||||
|
||||
CSLTPManager sltp_manager;
|
||||
|
||||
int OnInit()
|
||||
{
|
||||
sltp_manager.SetMagicNumber(MagicNumber);
|
||||
sltp_manager.SetSymbol(_Symbol);
|
||||
|
||||
if(!sltp_manager.ValidateSettings())
|
||||
{
|
||||
Print("SLTPManager settings are invalid.");
|
||||
return INIT_FAILED;
|
||||
}
|
||||
|
||||
return INIT_SUCCEEDED;
|
||||
}
|
||||
|
||||
void OnTick()
|
||||
{
|
||||
sltp_manager.ManagePositions();
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# 注意事項
|
||||
|
||||
- 既存ポジションのTPは変更しない。
|
||||
- SL更新に失敗した場合は、以下をログ出力する。
|
||||
- ticket番号
|
||||
- symbol
|
||||
- magic number
|
||||
- エラーコード
|
||||
- BUYとSELLの計算方向を間違えない。
|
||||
- 現在SLより不利なSLには更新しない。
|
||||
- TP未設定のポジションではTP到達率によるSL更新は行わない。
|
||||
- `PositionModify()` 前に価格を `NormalizeDouble()` する。
|
||||
- `SYMBOL_TRADE_STOPS_LEVEL` と `SYMBOL_TRADE_FREEZE_LEVEL` を考慮する。
|
||||
- コンパイルエラーが出ないMQL5コードにする。
|
||||
|
||||
---
|
||||
|
||||
# 実装時の推奨判断
|
||||
|
||||
| 項目 | 方針 |
|
||||
|---|---|
|
||||
| `use_breakeven` と `use_active_trailing` が両方ON | `ValidateSettings()` で `false` を返す |
|
||||
| EA初期化時に設定エラー | `INIT_FAILED` にする |
|
||||
| TP到達率SLとブレークイーブンが同時成立 | より有利なSLを採用 |
|
||||
| TP未設定時 | TP到達率SLはスキップ |
|
||||
| SL未設定時 | 条件成立なら新規設定 |
|
||||
| TP変更 | しない |
|
||||
| 対象ポジション | magic number + symbol 一致のみ |
|
||||
Reference in New Issue
Block a user