Add trading session helpers and extend ThrottledHistoryUpdater (#25)
* Add trading session helpers and extend ThrottledHistoryUpdater Introduce mt5cli.trading with mt5_trading_session() for Mt5TradingClient lifecycle management and reusable operational helpers for position-side detection, margin/volume sizing, and protective order price derivation. Extend ThrottledHistoryUpdater to validate inputs before updates and to optionally suppress ValueError, OSError, and missing-method errors without advancing the throttle timestamp. Export the new helpers from mt5cli.__init__, add unit tests with mocked clients, and document migration guidance for downstream projects such as mteor. Co-authored-by: Daichi Narushima <dceoy@users.noreply.github.com> * Narrow ThrottledHistoryUpdater suppress_errors handling (#27) * Narrow ThrottledHistoryUpdater suppress_errors for MT5 capability only Remove broad AttributeError/TypeError handling from recoverable errors. Add _is_mt5_client_capability_error() to detect missing history API methods or non-callable client attributes by message and attribute name. Generic AttributeError/TypeError values always propagate even when suppress_errors=True. Update docs and tests accordingly. Co-authored-by: Daichi Narushima <dceoy@users.noreply.github.com> * Detect non-callable history client methods in suppress_errors Address review feedback: when a history API attribute exists but is not callable, Python raises a generic TypeError. Inspect the traceback for mt5cli.history client call sites so these capability mismatches are still suppressed without matching all TypeError values. Co-authored-by: Daichi Narushima <dceoy@users.noreply.github.com> --------- Co-authored-by: Cursor Agent <cursoragent@cursor.com> Co-authored-by: Daichi Narushima <dceoy@users.noreply.github.com> * Address PR review feedback on trading helpers - Resolve history module path once at import time - Only treat non-callable TypeErrors as capability errors at the raise site - Validate SL/TP ratios in determine_order_limits - Add tests for margin_free edge cases, body-raise shutdown, and internal TypeError propagation - Clarify ThrottledHistoryUpdater suppress_errors docs - Split README migration example into trading vs read-only history sessions Co-authored-by: Daichi Narushima <dceoy@users.noreply.github.com> * Tighten protective ratio validation and clamp negative margin_free Add _require_protective_ratio enforcing 0 <= ratio < 1 for SL/TP limits so a ratio of 1.0 cannot produce zero protective prices. Clamp negative margin_free to 0.0 in calculate_margin_and_volume before sizing. Add boundary and negative-margin tests; document constraints in trading API docs. Co-authored-by: Daichi Narushima <dceoy@users.noreply.github.com> --------- Co-authored-by: Cursor Agent <cursoragent@cursor.com> Co-authored-by: Daichi Narushima <dceoy@users.noreply.github.com>
This commit is contained in:
+7
-2
@@ -18,6 +18,10 @@ Utility module providing constants, enums, Click parameter types, and helper fun
|
||||
|
||||
Programmatic SDK for read-only MetaTrader 5 data collection. Returns pandas DataFrames and provides `collect_history` for SQLite bulk collection.
|
||||
|
||||
### [Trading](trading.md)
|
||||
|
||||
Trading-capable session management and operational helpers built on `pdmt5.Mt5TradingClient`. Complements the read-only SDK without changing existing `Mt5CliClient` behavior.
|
||||
|
||||
### [History Collection (SQLite)](history.md)
|
||||
|
||||
SQLite storage helpers for the `collect-history` command schema, incremental updates, deduplication, indexes, and optional views.
|
||||
@@ -28,8 +32,9 @@ The package follows a simple architecture built on top of pdmt5:
|
||||
|
||||
1. **CLI Layer** (`cli.py`): Typer application with subcommands that delegate to the SDK and export results.
|
||||
2. **SDK Layer** (`sdk.py`): Read-only data access functions, `Mt5CliClient`, and `collect_history` orchestration.
|
||||
3. **Utils Layer** (`utils.py`): Constants, enums, custom Click parameter types, parsing helpers, and format detection/export utilities.
|
||||
4. **Data Layer** (via `pdmt5`): Uses `Mt5DataClient` and `Mt5Config` from the pdmt5 package for all MetaTrader 5 data access.
|
||||
3. **Trading Layer** (`trading.py`): Trading-capable sessions and operational helpers on `Mt5TradingClient`.
|
||||
4. **Utils Layer** (`utils.py`): Constants, enums, custom Click parameter types, parsing helpers, and format detection/export utilities.
|
||||
5. **Data Layer** (via `pdmt5`): Uses `Mt5DataClient`, `Mt5TradingClient`, and `Mt5Config` from the pdmt5 package for MetaTrader 5 access.
|
||||
|
||||
## Usage Guidelines
|
||||
|
||||
|
||||
+14
-3
@@ -98,6 +98,17 @@ finally:
|
||||
client.shutdown()
|
||||
```
|
||||
|
||||
By default `Mt5TradingError`, `Mt5RuntimeError`, and `sqlite3.Error` propagate so
|
||||
the caller controls logging; pass `suppress_errors=True` to swallow them and
|
||||
return `False` without advancing the throttle.
|
||||
By default recoverable errors (`Mt5TradingError`, `Mt5RuntimeError`,
|
||||
`sqlite3.Error`, `ValueError`, `OSError`, and MT5 client capability
|
||||
`AttributeError` / `TypeError` for history API methods) propagate so the caller
|
||||
controls logging; pass `suppress_errors=True` to swallow them and return
|
||||
`False` without advancing the throttle. Other `AttributeError` / `TypeError`
|
||||
values always propagate. Input validation (`_resolve_update_history_request`)
|
||||
runs before any MT5 or SQLite calls, but when `suppress_errors=True` the
|
||||
resulting `ValueError` is suppressed along with other recoverable errors.
|
||||
|
||||
## Trading-capable sessions
|
||||
|
||||
For order placement and trading calculations, use the dedicated
|
||||
[Trading module](trading.md). The read-only `Mt5CliClient` and `mt5_session()`
|
||||
helpers in this module are unchanged.
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
# Trading Module
|
||||
|
||||
::: mt5cli.trading
|
||||
|
||||
## Trading-capable MT5 sessions
|
||||
|
||||
`mt5_trading_session()` complements the read-only `mt5_session()` helper in
|
||||
`sdk.py`. It yields a connected `pdmt5.Mt5TradingClient`, uses
|
||||
`Mt5Config.path` to launch the terminal when configured, and always calls
|
||||
`shutdown()` on exit.
|
||||
|
||||
```python
|
||||
from pdmt5 import Mt5Config
|
||||
|
||||
from mt5cli import mt5_trading_session
|
||||
|
||||
with mt5_trading_session(
|
||||
Mt5Config(path=r"C:\Program Files\MetaTrader 5\terminal64.exe", login=12345),
|
||||
retry_count=2,
|
||||
) as client:
|
||||
positions = client.positions_get_as_df(symbol="EURUSD")
|
||||
```
|
||||
|
||||
The read-only `Mt5CliClient` / `mt5_session()` API is unchanged.
|
||||
|
||||
## Operational trading helpers
|
||||
|
||||
These helpers are strategy-agnostic and do not depend on signal detection,
|
||||
betting logic, or scheduling code in downstream applications.
|
||||
|
||||
```python
|
||||
from mt5cli import (
|
||||
calculate_margin_and_volume,
|
||||
detect_position_side,
|
||||
determine_order_limits,
|
||||
)
|
||||
|
||||
side = detect_position_side(client, "EURUSD")
|
||||
sizing = calculate_margin_and_volume(
|
||||
client,
|
||||
"EURUSD",
|
||||
unit_margin_ratio=0.5,
|
||||
preserved_margin_ratio=0.2,
|
||||
)
|
||||
limits = determine_order_limits(
|
||||
client,
|
||||
"EURUSD",
|
||||
side="long",
|
||||
stop_loss_limit_ratio=0.01,
|
||||
take_profit_limit_ratio=0.02,
|
||||
)
|
||||
```
|
||||
|
||||
Protective ratios must satisfy ``0 <= ratio < 1``; ``0`` omits that level.
|
||||
``calculate_margin_and_volume()`` clamps negative ``margin_free`` to ``0.0``
|
||||
before sizing.
|
||||
|
||||
## Migration from mteor-local helpers
|
||||
|
||||
| mteor-local concern | mt5cli replacement |
|
||||
| -------------------------------------------------------- | ----------------------------------------------- |
|
||||
| Manual terminal spawn/kill around trading code | `mt5_trading_session()` |
|
||||
| Local position-side detection | `detect_position_side()` |
|
||||
| Local margin/volume sizing | `calculate_margin_and_volume()` |
|
||||
| Local SL/TP price derivation | `determine_order_limits()` |
|
||||
| Throttled SQLite history loop with ad-hoc error handling | `ThrottledHistoryUpdater(suppress_errors=True)` |
|
||||
|
||||
Keep read-only data collection on `mt5_session()` / `Mt5CliClient`; use
|
||||
`mt5_trading_session()` only where order placement or trading calculations are
|
||||
required.
|
||||
Reference in New Issue
Block a user