From 39a883c279f5629bb84ed80821d6293cb62c2c04 Mon Sep 17 00:00:00 2001 From: dceoy Date: Wed, 24 Jun 2026 17:08:58 +0000 Subject: [PATCH] deploy: 71b99ada26405403d549c4ae92dc607990d1f64d --- api/cli/index.html | 1400 ++++++++++------- api/public-contract/index.html | 17 +- api/trading/index.html | 2655 ++++++++++++++++---------------- index.html | 2 +- objects.inv | Bin 4461 -> 4508 bytes search/search_index.json | 2 +- 6 files changed, 2178 insertions(+), 1898 deletions(-) diff --git a/api/cli/index.html b/api/cli/index.html index 66546f9..3aaf680 100644 --- a/api/cli/index.html +++ b/api/cli/index.html @@ -246,13 +246,219 @@
Source code in mt5cli/cli.py -
379
-380
+              
@app.command()
-def account_info(ctx: typer.Context) -> None:
-    """Export account information."""
-    _export_command(ctx, lambda client: client.account_info())
+382
+383
@app.command()
+def account_info(ctx: typer.Context) -> None:
+    """Export account information."""
+    _export_command(ctx, lambda client: client.account_info())
+
+ +
+ + + +
+ + +

+ close_positions + + +

+
close_positions(
+    ctx: Context,
+    symbol: Annotated[
+        list[str] | None,
+        Option(
+            "--symbol",
+            "-s",
+            help="Symbol to close (repeat for multiple symbols).",
+        ),
+    ] = None,
+    ticket: Annotated[
+        list[int] | None,
+        Option(
+            "--ticket",
+            "-t",
+            help="Position ticket to close (repeat for multiple tickets).",
+        ),
+    ] = None,
+    dry_run: Annotated[
+        bool,
+        Option(
+            "--dry-run",
+            help="Preview close orders without executing them.",
+        ),
+    ] = False,
+    yes: Annotated[
+        bool,
+        Option(
+            "--yes", help="Confirm live position closing."
+        ),
+    ] = False,
+) -> None
+
+ +
+ +

Close open positions by symbol or ticket.

+

Delegates to :func:mt5cli.trading.close_open_positions. At least one +--symbol or --ticket must be provided to avoid accidentally closing +all positions. Use --dry-run to preview without executing; --yes is +required for live execution.

+

order-send is the expert raw-request path. close-positions is the +safer high-level helper that builds correct close requests automatically.

+ + +

Raises:

+ + + + + + + + + + + + + +
TypeDescription
+ BadParameter + +
+

If neither --symbol nor --ticket is given, +or if --yes is missing for a live (non-dry-run) run.

+
+
+ + +
+ Source code in mt5cli/cli.py +
@app.command()
+def close_positions(
+    ctx: typer.Context,
+    symbol: Annotated[
+        list[str] | None,
+        typer.Option(
+            "--symbol",
+            "-s",
+            help="Symbol to close (repeat for multiple symbols).",
+        ),
+    ] = None,
+    ticket: Annotated[
+        list[int] | None,
+        typer.Option(
+            "--ticket",
+            "-t",
+            help="Position ticket to close (repeat for multiple tickets).",
+        ),
+    ] = None,
+    dry_run: Annotated[
+        bool,
+        typer.Option("--dry-run", help="Preview close orders without executing them."),
+    ] = False,
+    yes: Annotated[
+        bool,
+        typer.Option("--yes", help="Confirm live position closing."),
+    ] = False,
+) -> None:
+    """Close open positions by symbol or ticket.
+
+    Delegates to :func:`mt5cli.trading.close_open_positions`. At least one
+    ``--symbol`` or ``--ticket`` must be provided to avoid accidentally closing
+    all positions. Use ``--dry-run`` to preview without executing; ``--yes`` is
+    required for live execution.
+
+    ``order-send`` is the expert raw-request path. ``close-positions`` is the
+    safer high-level helper that builds correct close requests automatically.
+
+    Raises:
+        typer.BadParameter: If neither ``--symbol`` nor ``--ticket`` is given,
+            or if ``--yes`` is missing for a live (non-dry-run) run.
+    """
+    if not symbol and not ticket:
+        msg = "Provide at least one --symbol or --ticket to close positions."
+        raise typer.BadParameter(msg)
+    if not dry_run and not yes:
+        msg = "Pass --yes to close live positions."
+        raise typer.BadParameter(msg, param_hint="--yes")
+    export_ctx = _get_export_context(ctx)
+    client = create_trading_client(config=export_ctx.config)
+    try:
+        results = close_open_positions(
+            client,
+            symbols=list(symbol) if symbol else None,
+            tickets=list(ticket) if ticket else None,
+            dry_run=dry_run,
+        )
+    finally:
+        client.shutdown()
+    df = _execution_results_to_df(results)
+    _execute_export(ctx, lambda: df)
 
@@ -388,85 +594,7 @@ views cash_events and positions_reconstructed are deri
Source code in mt5cli/cli.py -
603
-604
-605
-606
-607
-608
-609
-610
-611
-612
-613
-614
-615
-616
-617
-618
-619
-620
-621
-622
-623
-624
-625
-626
-627
-628
-629
-630
-631
-632
-633
-634
-635
-636
-637
-638
-639
-640
-641
-642
-643
-644
-645
-646
-647
-648
-649
-650
-651
-652
-653
-654
-655
-656
-657
-658
-659
-660
-661
-662
-663
-664
-665
-666
-667
-668
-669
-670
-671
-672
-673
-674
-675
-676
-677
-678
-679
-680
-681
+              
681
 682
 683
 684
@@ -482,101 +610,179 @@ views cash_events and positions_reconstructed are deri
 694
 695
 696
-697
@app.command()
-def collect_history(
-    ctx: typer.Context,
-    symbol: Annotated[
-        list[str],
-        typer.Option(
-            "--symbol",
-            "-s",
-            help="Symbol to collect (repeat for multiple symbols).",
-        ),
-    ],
-    date_from: Annotated[
-        datetime,
-        typer.Option(click_type=DATETIME_TYPE, help="Start date."),
-    ],
-    date_to: Annotated[
-        datetime,
-        typer.Option(click_type=DATETIME_TYPE, help="End date."),
-    ],
-    dataset: Annotated[
-        list[Dataset] | None,
-        typer.Option(
-            "--dataset",
-            help=(
-                "Dataset to include (repeat for multiple)."
-                " Defaults to all: rates, ticks, history-orders, history-deals."
-            ),
-        ),
-    ] = None,
-    timeframe: Annotated[
-        int,
-        typer.Option(
-            click_type=TIMEFRAME_TYPE,
-            help="Rates timeframe (e.g., M1, H1, D1).",
-        ),
-    ] = 1,
-    flags: Annotated[
-        int,
-        typer.Option(
-            click_type=TICK_FLAGS_TYPE,
-            help="Tick copy flags (ALL, INFO, TRADE, or integer).",
-        ),
-    ] = "ALL",  # pyright: ignore[reportArgumentType]
-    if_exists: Annotated[
-        IfExists,
-        typer.Option(
-            "--if-exists",
-            help="Behavior when a target table already exists.",
-        ),
-    ] = IfExists.FAIL,
-    with_views: Annotated[
-        bool,
-        typer.Option(
-            "--with-views",
-            help=(
-                "Add cash_events and positions_reconstructed SQLite views"
-                " derived from history_deals."
-            ),
-        ),
-    ] = False,
-) -> None:
-    """Collect historical datasets into a single SQLite database.
-
-    Tables written depend on ``--dataset``: ``rates``, ``ticks``,
-    ``history_orders``, ``history_deals``. History datasets are fetched per
-    symbol and concatenated. Rates rows carry the requested ``timeframe`` so
-    appended runs at different timeframes remain distinguishable.
-
-    With ``--with-views`` (requires the ``history-deals`` dataset), optional
-    views ``cash_events`` and ``positions_reconstructed`` are derived from
-    ``history_deals`` when the required columns are present.
-
-    Raises:
-        typer.BadParameter: If the output format is not SQLite3.
-    """
-    export_ctx = _get_export_context(ctx)
-    if export_ctx.output_format != "sqlite3":
-        msg = (
-            "collect-history requires SQLite3 output."
-            " Use a .db/.sqlite/.sqlite3 extension or --format sqlite3."
-        )
-        raise typer.BadParameter(msg)
-    datasets = set(dataset) if dataset else set(Dataset)
-    sdk.collect_history(
-        output=export_ctx.output,
-        symbols=symbol,
-        date_from=date_from,
-        date_to=date_to,
-        datasets=datasets,
-        timeframe=timeframe,
-        flags=flags,
-        if_exists=if_exists,
-        with_views=with_views,
-        config=export_ctx.config,
-    )
+697
+698
+699
+700
+701
+702
+703
+704
+705
+706
+707
+708
+709
+710
+711
+712
+713
+714
+715
+716
+717
+718
+719
+720
+721
+722
+723
+724
+725
+726
+727
+728
+729
+730
+731
+732
+733
+734
+735
+736
+737
+738
+739
+740
+741
+742
+743
+744
+745
+746
+747
+748
+749
+750
+751
+752
+753
+754
+755
+756
+757
+758
+759
+760
+761
+762
+763
+764
+765
+766
+767
+768
+769
+770
+771
+772
+773
+774
+775
@app.command()
+def collect_history(
+    ctx: typer.Context,
+    symbol: Annotated[
+        list[str],
+        typer.Option(
+            "--symbol",
+            "-s",
+            help="Symbol to collect (repeat for multiple symbols).",
+        ),
+    ],
+    date_from: Annotated[
+        datetime,
+        typer.Option(click_type=DATETIME_TYPE, help="Start date."),
+    ],
+    date_to: Annotated[
+        datetime,
+        typer.Option(click_type=DATETIME_TYPE, help="End date."),
+    ],
+    dataset: Annotated[
+        list[Dataset] | None,
+        typer.Option(
+            "--dataset",
+            help=(
+                "Dataset to include (repeat for multiple)."
+                " Defaults to all: rates, ticks, history-orders, history-deals."
+            ),
+        ),
+    ] = None,
+    timeframe: Annotated[
+        int,
+        typer.Option(
+            click_type=TIMEFRAME_TYPE,
+            help="Rates timeframe (e.g., M1, H1, D1).",
+        ),
+    ] = 1,
+    flags: Annotated[
+        int,
+        typer.Option(
+            click_type=TICK_FLAGS_TYPE,
+            help="Tick copy flags (ALL, INFO, TRADE, or integer).",
+        ),
+    ] = "ALL",  # pyright: ignore[reportArgumentType]
+    if_exists: Annotated[
+        IfExists,
+        typer.Option(
+            "--if-exists",
+            help="Behavior when a target table already exists.",
+        ),
+    ] = IfExists.FAIL,
+    with_views: Annotated[
+        bool,
+        typer.Option(
+            "--with-views",
+            help=(
+                "Add cash_events and positions_reconstructed SQLite views"
+                " derived from history_deals."
+            ),
+        ),
+    ] = False,
+) -> None:
+    """Collect historical datasets into a single SQLite database.
+
+    Tables written depend on ``--dataset``: ``rates``, ``ticks``,
+    ``history_orders``, ``history_deals``. History datasets are fetched per
+    symbol and concatenated. Rates rows carry the requested ``timeframe`` so
+    appended runs at different timeframes remain distinguishable.
+
+    With ``--with-views`` (requires the ``history-deals`` dataset), optional
+    views ``cash_events`` and ``positions_reconstructed`` are derived from
+    ``history_deals`` when the required columns are present.
+
+    Raises:
+        typer.BadParameter: If the output format is not SQLite3.
+    """
+    export_ctx = _get_export_context(ctx)
+    if export_ctx.output_format != "sqlite3":
+        msg = (
+            "collect-history requires SQLite3 output."
+            " Use a .db/.sqlite/.sqlite3 extension or --format sqlite3."
+        )
+        raise typer.BadParameter(msg)
+    datasets = set(dataset) if dataset else set(Dataset)
+    sdk.collect_history(
+        output=export_ctx.output,
+        symbols=symbol,
+        date_from=date_from,
+        date_to=date_to,
+        datasets=datasets,
+        timeframe=timeframe,
+        flags=flags,
+        if_exists=if_exists,
+        with_views=with_views,
+        config=export_ctx.config,
+    )
 
@@ -635,8 +841,7 @@ views cash_events and positions_reconstructed are deri
Source code in mt5cli/cli.py -
479
-480
+              
480
 481
 482
 483
@@ -662,34 +867,35 @@ views cash_events and positions_reconstructed are deri
 503
 504
 505
-506
@app.command()
-def history_deals(
-    ctx: typer.Context,
-    date_from: Annotated[
-        datetime | None,
-        typer.Option(click_type=DATETIME_TYPE, help="Start date."),
-    ] = None,
-    date_to: Annotated[
-        datetime | None,
-        typer.Option(click_type=DATETIME_TYPE, help="End date."),
-    ] = None,
-    group: Annotated[str | None, typer.Option(help="Group filter.")] = None,
-    symbol: Annotated[str | None, typer.Option(help="Symbol filter.")] = None,
-    ticket: Annotated[int | None, typer.Option(help="Order ticket.")] = None,
-    position: Annotated[int | None, typer.Option(help="Position ticket.")] = None,
-) -> None:
-    """Export historical deals."""
-    _export_command(
-        ctx,
-        lambda client: client.history_deals(
-            date_from=date_from,
-            date_to=date_to,
-            group=group,
-            symbol=symbol,
-            ticket=ticket,
-            position=position,
-        ),
-    )
+506
+507
@app.command()
+def history_deals(
+    ctx: typer.Context,
+    date_from: Annotated[
+        datetime | None,
+        typer.Option(click_type=DATETIME_TYPE, help="Start date."),
+    ] = None,
+    date_to: Annotated[
+        datetime | None,
+        typer.Option(click_type=DATETIME_TYPE, help="End date."),
+    ] = None,
+    group: Annotated[str | None, typer.Option(help="Group filter.")] = None,
+    symbol: Annotated[str | None, typer.Option(help="Symbol filter.")] = None,
+    ticket: Annotated[int | None, typer.Option(help="Order ticket.")] = None,
+    position: Annotated[int | None, typer.Option(help="Position ticket.")] = None,
+) -> None:
+    """Export historical deals."""
+    _export_command(
+        ctx,
+        lambda client: client.history_deals(
+            date_from=date_from,
+            date_to=date_to,
+            group=group,
+            symbol=symbol,
+            ticket=ticket,
+            position=position,
+        ),
+    )
 
@@ -748,8 +954,7 @@ views cash_events and positions_reconstructed are deri
Source code in mt5cli/cli.py -
449
-450
+              
450
 451
 452
 453
@@ -775,34 +980,35 @@ views cash_events and positions_reconstructed are deri
 473
 474
 475
-476
@app.command()
-def history_orders(
-    ctx: typer.Context,
-    date_from: Annotated[
-        datetime | None,
-        typer.Option(click_type=DATETIME_TYPE, help="Start date."),
-    ] = None,
-    date_to: Annotated[
-        datetime | None,
-        typer.Option(click_type=DATETIME_TYPE, help="End date."),
-    ] = None,
-    group: Annotated[str | None, typer.Option(help="Group filter.")] = None,
-    symbol: Annotated[str | None, typer.Option(help="Symbol filter.")] = None,
-    ticket: Annotated[int | None, typer.Option(help="Order ticket.")] = None,
-    position: Annotated[int | None, typer.Option(help="Position ticket.")] = None,
-) -> None:
-    """Export historical orders."""
-    _export_command(
-        ctx,
-        lambda client: client.history_orders(
-            date_from=date_from,
-            date_to=date_to,
-            group=group,
-            symbol=symbol,
-            ticket=ticket,
-            position=position,
-        ),
-    )
+476
+477
@app.command()
+def history_orders(
+    ctx: typer.Context,
+    date_from: Annotated[
+        datetime | None,
+        typer.Option(click_type=DATETIME_TYPE, help="Start date."),
+    ] = None,
+    date_to: Annotated[
+        datetime | None,
+        typer.Option(click_type=DATETIME_TYPE, help="End date."),
+    ] = None,
+    group: Annotated[str | None, typer.Option(help="Group filter.")] = None,
+    symbol: Annotated[str | None, typer.Option(help="Symbol filter.")] = None,
+    ticket: Annotated[int | None, typer.Option(help="Order ticket.")] = None,
+    position: Annotated[int | None, typer.Option(help="Position ticket.")] = None,
+) -> None:
+    """Export historical orders."""
+    _export_command(
+        ctx,
+        lambda client: client.history_orders(
+            date_from=date_from,
+            date_to=date_to,
+            group=group,
+            symbol=symbol,
+            ticket=ticket,
+            position=position,
+        ),
+    )
 
@@ -827,13 +1033,13 @@ views cash_events and positions_reconstructed are deri
Source code in mt5cli/cli.py -
544
-545
+              
@app.command()
-def last_error(ctx: typer.Context) -> None:
-    """Export the last error information."""
-    _export_command(ctx, lambda client: client.last_error())
+547
+548
@app.command()
+def last_error(ctx: typer.Context) -> None:
+    """Export the last error information."""
+    _export_command(ctx, lambda client: client.last_error())
 
@@ -879,8 +1085,7 @@ views cash_events and positions_reconstructed are deri
Source code in mt5cli/cli.py -
238
-239
+              
239
 240
 241
 242
@@ -905,33 +1110,34 @@ views cash_events and positions_reconstructed are deri
 261
 262
 263
-264
@app.command()
-def latest_rates(
-    ctx: typer.Context,
-    symbol: Annotated[str, typer.Option(help="Symbol name.")],
-    timeframe: Annotated[
-        int,
-        typer.Option(
-            click_type=TIMEFRAME_TYPE,
-            help="Timeframe.",
-        ),
-    ],
-    count: Annotated[int, typer.Option(help="Number of records.")],
-    start_pos: Annotated[
-        int,
-        typer.Option(help="Start position (0 = current bar)."),
-    ] = 0,
-) -> None:
-    """Export latest rates from a start position."""
-    _export_command(
-        ctx,
-        lambda client: client.latest_rates(
-            symbol,
-            timeframe,
-            count,
-            start_pos=start_pos,
-        ),
-    )
+264
+265
@app.command()
+def latest_rates(
+    ctx: typer.Context,
+    symbol: Annotated[str, typer.Option(help="Symbol name.")],
+    timeframe: Annotated[
+        int,
+        typer.Option(
+            click_type=TIMEFRAME_TYPE,
+            help="Timeframe.",
+        ),
+    ],
+    count: Annotated[int, typer.Option(help="Number of records.")],
+    start_pos: Annotated[
+        int,
+        typer.Option(help="Start position (0 = current bar)."),
+    ] = 0,
+) -> None:
+    """Export latest rates from a start position."""
+    _export_command(
+        ctx,
+        lambda client: client.latest_rates(
+            symbol,
+            timeframe,
+            count,
+            start_pos=start_pos,
+        ),
+    )
 
@@ -956,11 +1162,11 @@ views cash_events and positions_reconstructed are deri
Source code in mt5cli/cli.py -
def main() -> None:
-    """Run the mt5cli CLI."""
-    app()
+              
def main() -> None:
+    """Run the mt5cli CLI."""
+    app()
 
@@ -988,19 +1194,19 @@ views cash_events and positions_reconstructed are deri
Source code in mt5cli/cli.py -
559
-560
+              
@app.command()
-def market_book(
-    ctx: typer.Context,
-    symbol: Annotated[str, typer.Option(help="Symbol name.")],
-) -> None:
-    """Export market depth (order book) for a symbol."""
-    _export_command(ctx, lambda client: client.market_book(symbol))
+565
+566
@app.command()
+def market_book(
+    ctx: typer.Context,
+    symbol: Annotated[str, typer.Option(help="Symbol name.")],
+) -> None:
+    """Export market depth (order book) for a symbol."""
+    _export_command(ctx, lambda client: client.market_book(symbol))
 
@@ -1028,19 +1234,19 @@ views cash_events and positions_reconstructed are deri
Source code in mt5cli/cli.py -
412
-413
+              
@app.command()
-def minimum_margins(
-    ctx: typer.Context,
-    symbol: Annotated[str, typer.Option(help="Symbol name.")],
-) -> None:
-    """Export minimum-volume buy and sell margin requirements."""
-    _export_command(ctx, lambda client: client.minimum_margins(symbol))
+418
+419
@app.command()
+def minimum_margins(
+    ctx: typer.Context,
+    symbol: Annotated[str, typer.Option(help="Symbol name.")],
+) -> None:
+    """Export minimum-volume buy and sell margin requirements."""
+    _export_command(ctx, lambda client: client.minimum_margins(symbol))
 
@@ -1065,13 +1271,13 @@ views cash_events and positions_reconstructed are deri
Source code in mt5cli/cli.py -
532
-533
+              
@app.command()
-def mt5_summary(ctx: typer.Context) -> None:
-    """Export a compact terminal/account status summary."""
-    _export_command(ctx, lambda client: client.mt5_summary_as_df())
+535
+536
@app.command()
+def mt5_summary(ctx: typer.Context) -> None:
+    """Export a compact terminal/account status summary."""
+    _export_command(ctx, lambda client: client.mt5_summary_as_df())
 
@@ -1110,8 +1316,7 @@ views cash_events and positions_reconstructed are deri
Source code in mt5cli/cli.py -
568
-569
+              
569
 570
 571
 572
@@ -1119,16 +1324,17 @@ views cash_events and positions_reconstructed are deri
 574
 575
 576
-577
@app.command()
-def order_check(
-    ctx: typer.Context,
-    request: Annotated[
-        dict[str, Any],
-        typer.Option(click_type=REQUEST_TYPE, help=_REQUEST_OPTION_HELP),
-    ],
-) -> None:
-    """Check funds sufficiency for a trading operation."""
-    _export_command(ctx, lambda client: client.order_check(request))
+577
+578
@app.command()
+def order_check(
+    ctx: typer.Context,
+    request: Annotated[
+        dict[str, Any],
+        typer.Option(click_type=REQUEST_TYPE, help=_REQUEST_OPTION_HELP),
+    ],
+) -> None:
+    """Check funds sufficiency for a trading operation."""
+    _export_command(ctx, lambda client: client.order_check(request))
 
@@ -1196,8 +1402,7 @@ views cash_events and positions_reconstructed are deri
Source code in mt5cli/cli.py -
580
-581
+              
581
 582
 583
 584
@@ -1216,27 +1421,28 @@ views cash_events and positions_reconstructed are deri
 597
 598
 599
-600
@app.command()
-def order_send(
-    ctx: typer.Context,
-    request: Annotated[
-        dict[str, Any],
-        typer.Option(click_type=REQUEST_TYPE, help=_REQUEST_OPTION_HELP),
-    ],
-    yes: Annotated[
-        bool,
-        typer.Option("--yes", help="Confirm the live trade request."),
-    ] = False,
-) -> None:
-    """Send a trading operation request to the trade server.
-
-    Raises:
-        typer.BadParameter: If --yes is not provided.
-    """
-    if not yes:
-        msg = "Pass --yes to send a live trade request."
-        raise typer.BadParameter(msg, param_hint="--yes")
-    _export_command(ctx, lambda client: client.order_send(request))
+600
+601
@app.command()
+def order_send(
+    ctx: typer.Context,
+    request: Annotated[
+        dict[str, Any],
+        typer.Option(click_type=REQUEST_TYPE, help=_REQUEST_OPTION_HELP),
+    ],
+    yes: Annotated[
+        bool,
+        typer.Option("--yes", help="Confirm the live trade request."),
+    ] = False,
+) -> None:
+    """Send a trading operation request to the trade server.
+
+    Raises:
+        typer.BadParameter: If --yes is not provided.
+    """
+    if not yes:
+        msg = "Pass --yes to send a live trade request."
+        raise typer.BadParameter(msg, param_hint="--yes")
+    _export_command(ctx, lambda client: client.order_send(request))
 
@@ -1272,8 +1478,7 @@ views cash_events and positions_reconstructed are deri
Source code in mt5cli/cli.py -
421
-422
+              
422
 423
 424
 425
@@ -1283,18 +1488,19 @@ views cash_events and positions_reconstructed are deri
 429
 430
 431
-432
@app.command()
-def orders(
-    ctx: typer.Context,
-    symbol: Annotated[str | None, typer.Option(help="Symbol filter.")] = None,
-    group: Annotated[str | None, typer.Option(help="Group filter.")] = None,
-    ticket: Annotated[int | None, typer.Option(help="Ticket filter.")] = None,
-) -> None:
-    """Export active orders."""
-    _export_command(
-        ctx,
-        lambda client: client.orders(symbol=symbol, group=group, ticket=ticket),
-    )
+432
+433
@app.command()
+def orders(
+    ctx: typer.Context,
+    symbol: Annotated[str | None, typer.Option(help="Symbol filter.")] = None,
+    group: Annotated[str | None, typer.Option(help="Group filter.")] = None,
+    ticket: Annotated[int | None, typer.Option(help="Ticket filter.")] = None,
+) -> None:
+    """Export active orders."""
+    _export_command(
+        ctx,
+        lambda client: client.orders(symbol=symbol, group=group, ticket=ticket),
+    )
 
@@ -1330,8 +1536,7 @@ views cash_events and positions_reconstructed are deri
Source code in mt5cli/cli.py -
435
-436
+              
436
 437
 438
 439
@@ -1341,18 +1546,19 @@ views cash_events and positions_reconstructed are deri
 443
 444
 445
-446
@app.command()
-def positions(
-    ctx: typer.Context,
-    symbol: Annotated[str | None, typer.Option(help="Symbol filter.")] = None,
-    group: Annotated[str | None, typer.Option(help="Group filter.")] = None,
-    ticket: Annotated[int | None, typer.Option(help="Ticket filter.")] = None,
-) -> None:
-    """Export open positions."""
-    _export_command(
-        ctx,
-        lambda client: client.positions(symbol=symbol, group=group, ticket=ticket),
-    )
+446
+447
@app.command()
+def positions(
+    ctx: typer.Context,
+    symbol: Annotated[str | None, typer.Option(help="Symbol filter.")] = None,
+    group: Annotated[str | None, typer.Option(help="Group filter.")] = None,
+    ticket: Annotated[int | None, typer.Option(help="Ticket filter.")] = None,
+) -> None:
+    """Export open positions."""
+    _export_command(
+        ctx,
+        lambda client: client.positions(symbol=symbol, group=group, ticket=ticket),
+    )
 
@@ -1407,8 +1613,7 @@ views cash_events and positions_reconstructed are deri
Source code in mt5cli/cli.py -
185
-186
+              
186
 187
 188
 189
@@ -1431,31 +1636,32 @@ views cash_events and positions_reconstructed are deri
 206
 207
 208
-209
@app.command()
-def rates_from(
-    ctx: typer.Context,
-    symbol: Annotated[str, typer.Option(help="Symbol name.")],
-    timeframe: Annotated[
-        int,
-        typer.Option(
-            click_type=TIMEFRAME_TYPE,
-            help="Timeframe (e.g., M1, H1, D1, or integer).",
-        ),
-    ],
-    date_from: Annotated[
-        datetime,
-        typer.Option(
-            click_type=DATETIME_TYPE,
-            help="Start date in ISO 8601 format.",
-        ),
-    ],
-    count: Annotated[int, typer.Option(help="Number of records.")],
-) -> None:
-    """Export rates from a start date."""
-    _export_command(
-        ctx,
-        lambda client: client.copy_rates_from(symbol, timeframe, date_from, count),
-    )
+209
+210
@app.command()
+def rates_from(
+    ctx: typer.Context,
+    symbol: Annotated[str, typer.Option(help="Symbol name.")],
+    timeframe: Annotated[
+        int,
+        typer.Option(
+            click_type=TIMEFRAME_TYPE,
+            help="Timeframe (e.g., M1, H1, D1, or integer).",
+        ),
+    ],
+    date_from: Annotated[
+        datetime,
+        typer.Option(
+            click_type=DATETIME_TYPE,
+            help="Start date in ISO 8601 format.",
+        ),
+    ],
+    count: Annotated[int, typer.Option(help="Number of records.")],
+) -> None:
+    """Export rates from a start date."""
+    _export_command(
+        ctx,
+        lambda client: client.copy_rates_from(symbol, timeframe, date_from, count),
+    )
 
@@ -1501,8 +1707,7 @@ views cash_events and positions_reconstructed are deri
Source code in mt5cli/cli.py -
212
-213
+              
213
 214
 215
 216
@@ -1524,30 +1729,31 @@ views cash_events and positions_reconstructed are deri
 232
 233
 234
-235
@app.command()
-def rates_from_pos(
-    ctx: typer.Context,
-    symbol: Annotated[str, typer.Option(help="Symbol name.")],
-    timeframe: Annotated[
-        int,
-        typer.Option(
-            click_type=TIMEFRAME_TYPE,
-            help="Timeframe.",
-        ),
-    ],
-    start_pos: Annotated[int, typer.Option(help="Start position (0 = current bar).")],
-    count: Annotated[int, typer.Option(help="Number of records.")],
-) -> None:
-    """Export rates from a start position."""
-    _export_command(
-        ctx,
-        lambda client: client.copy_rates_from_pos(
-            symbol,
-            timeframe,
-            start_pos,
-            count,
-        ),
-    )
+235
+236
@app.command()
+def rates_from_pos(
+    ctx: typer.Context,
+    symbol: Annotated[str, typer.Option(help="Symbol name.")],
+    timeframe: Annotated[
+        int,
+        typer.Option(
+            click_type=TIMEFRAME_TYPE,
+            help="Timeframe.",
+        ),
+    ],
+    start_pos: Annotated[int, typer.Option(help="Start position (0 = current bar).")],
+    count: Annotated[int, typer.Option(help="Number of records.")],
+) -> None:
+    """Export rates from a start position."""
+    _export_command(
+        ctx,
+        lambda client: client.copy_rates_from_pos(
+            symbol,
+            timeframe,
+            start_pos,
+            count,
+        ),
+    )
 
@@ -1606,8 +1812,7 @@ views cash_events and positions_reconstructed are deri
Source code in mt5cli/cli.py -
267
-268
+              
268
 269
 270
 271
@@ -1630,31 +1835,32 @@ views cash_events and positions_reconstructed are deri
 288
 289
 290
-291
@app.command()
-def rates_range(
-    ctx: typer.Context,
-    symbol: Annotated[str, typer.Option(help="Symbol name.")],
-    timeframe: Annotated[
-        int,
-        typer.Option(
-            click_type=TIMEFRAME_TYPE,
-            help="Timeframe.",
-        ),
-    ],
-    date_from: Annotated[
-        datetime,
-        typer.Option(click_type=DATETIME_TYPE, help="Start date."),
-    ],
-    date_to: Annotated[
-        datetime,
-        typer.Option(click_type=DATETIME_TYPE, help="End date."),
-    ],
-) -> None:
-    """Export rates for a date range."""
-    _export_command(
-        ctx,
-        lambda client: client.copy_rates_range(symbol, timeframe, date_from, date_to),
-    )
+291
+292
@app.command()
+def rates_range(
+    ctx: typer.Context,
+    symbol: Annotated[str, typer.Option(help="Symbol name.")],
+    timeframe: Annotated[
+        int,
+        typer.Option(
+            click_type=TIMEFRAME_TYPE,
+            help="Timeframe.",
+        ),
+    ],
+    date_from: Annotated[
+        datetime,
+        typer.Option(click_type=DATETIME_TYPE, help="Start date."),
+    ],
+    date_to: Annotated[
+        datetime,
+        typer.Option(click_type=DATETIME_TYPE, help="End date."),
+    ],
+) -> None:
+    """Export rates for a date range."""
+    _export_command(
+        ctx,
+        lambda client: client.copy_rates_range(symbol, timeframe, date_from, date_to),
+    )
 
@@ -1702,8 +1908,7 @@ views cash_events and positions_reconstructed are deri
Source code in mt5cli/cli.py -
509
-510
+              
510
 511
 512
 513
@@ -1722,27 +1927,28 @@ views cash_events and positions_reconstructed are deri
 526
 527
 528
-529
@app.command()
-def recent_history_deals(
-    ctx: typer.Context,
-    hours: Annotated[float, typer.Option(help="Lookback window in hours.")],
-    date_to: Annotated[
-        datetime | None,
-        typer.Option(click_type=DATETIME_TYPE, help="Window end date."),
-    ] = None,
-    group: Annotated[str | None, typer.Option(help="Group filter.")] = None,
-    symbol: Annotated[str | None, typer.Option(help="Symbol filter.")] = None,
-) -> None:
-    """Export historical deals from a recent trailing window."""
-    _export_command(
-        ctx,
-        lambda client: client.recent_history_deals(
-            hours,
-            date_to=date_to,
-            group=group,
-            symbol=symbol,
-        ),
-    )
+529
+530
@app.command()
+def recent_history_deals(
+    ctx: typer.Context,
+    hours: Annotated[float, typer.Option(help="Lookback window in hours.")],
+    date_to: Annotated[
+        datetime | None,
+        typer.Option(click_type=DATETIME_TYPE, help="Window end date."),
+    ] = None,
+    group: Annotated[str | None, typer.Option(help="Group filter.")] = None,
+    symbol: Annotated[str | None, typer.Option(help="Symbol filter.")] = None,
+) -> None:
+    """Export historical deals from a recent trailing window."""
+    _export_command(
+        ctx,
+        lambda client: client.recent_history_deals(
+            hours,
+            date_to=date_to,
+            group=group,
+            symbol=symbol,
+        ),
+    )
 
@@ -1770,19 +1976,19 @@ views cash_events and positions_reconstructed are deri
Source code in mt5cli/cli.py -
403
-404
+              
@app.command()
-def symbol_info(
-    ctx: typer.Context,
-    symbol: Annotated[str, typer.Option(help="Symbol name.")],
-) -> None:
-    """Export symbol details."""
-    _export_command(ctx, lambda client: client.symbol_info(symbol))
+409
+410
@app.command()
+def symbol_info(
+    ctx: typer.Context,
+    symbol: Annotated[str, typer.Option(help="Symbol name.")],
+) -> None:
+    """Export symbol details."""
+    _export_command(ctx, lambda client: client.symbol_info(symbol))
 
@@ -1810,19 +2016,19 @@ views cash_events and positions_reconstructed are deri
Source code in mt5cli/cli.py -
550
-551
+              
@app.command()
-def symbol_info_tick(
-    ctx: typer.Context,
-    symbol: Annotated[str, typer.Option(help="Symbol name.")],
-) -> None:
-    """Export the last tick for a symbol."""
-    _export_command(ctx, lambda client: client.symbol_info_tick(symbol))
+556
+557
@app.command()
+def symbol_info_tick(
+    ctx: typer.Context,
+    symbol: Annotated[str, typer.Option(help="Symbol name.")],
+) -> None:
+    """Export the last tick for a symbol."""
+    _export_command(ctx, lambda client: client.symbol_info_tick(symbol))
 
@@ -1853,8 +2059,7 @@ views cash_events and positions_reconstructed are deri
Source code in mt5cli/cli.py -
391
-392
+              
392
 393
 394
 395
@@ -1862,16 +2067,17 @@ views cash_events and positions_reconstructed are deri
 397
 398
 399
-400
@app.command()
-def symbols(
-    ctx: typer.Context,
-    group: Annotated[
-        str | None,
-        typer.Option(help="Symbol group filter (e.g., *USD*)."),
-    ] = None,
-) -> None:
-    """Export symbol list."""
-    _export_command(ctx, lambda client: client.symbols(group=group))
+400
+401
@app.command()
+def symbols(
+    ctx: typer.Context,
+    group: Annotated[
+        str | None,
+        typer.Option(help="Symbol group filter (e.g., *USD*)."),
+    ] = None,
+) -> None:
+    """Export symbol list."""
+    _export_command(ctx, lambda client: client.symbols(group=group))
 
@@ -1896,13 +2102,13 @@ views cash_events and positions_reconstructed are deri
Source code in mt5cli/cli.py -
385
-386
+              
@app.command()
-def terminal_info(ctx: typer.Context) -> None:
-    """Export terminal information."""
-    _export_command(ctx, lambda client: client.terminal_info())
+388
+389
@app.command()
+def terminal_info(ctx: typer.Context) -> None:
+    """Export terminal information."""
+    _export_command(ctx, lambda client: client.terminal_info())
 
@@ -1954,8 +2160,7 @@ views cash_events and positions_reconstructed are deri
Source code in mt5cli/cli.py -
294
-295
+              
295
 296
 297
 298
@@ -1975,28 +2180,29 @@ views cash_events and positions_reconstructed are deri
 312
 313
 314
-315
@app.command()
-def ticks_from(
-    ctx: typer.Context,
-    symbol: Annotated[str, typer.Option(help="Symbol name.")],
-    date_from: Annotated[
-        datetime,
-        typer.Option(click_type=DATETIME_TYPE, help="Start date."),
-    ],
-    count: Annotated[int, typer.Option(help="Number of ticks.")],
-    flags: Annotated[
-        int,
-        typer.Option(
-            click_type=TICK_FLAGS_TYPE,
-            help="Tick flags (ALL, INFO, TRADE, or integer).",
-        ),
-    ],
-) -> None:
-    """Export ticks from a start date."""
-    _export_command(
-        ctx,
-        lambda client: client.copy_ticks_from(symbol, date_from, count, flags),
-    )
+315
+316
@app.command()
+def ticks_from(
+    ctx: typer.Context,
+    symbol: Annotated[str, typer.Option(help="Symbol name.")],
+    date_from: Annotated[
+        datetime,
+        typer.Option(click_type=DATETIME_TYPE, help="Start date."),
+    ],
+    count: Annotated[int, typer.Option(help="Number of ticks.")],
+    flags: Annotated[
+        int,
+        typer.Option(
+            click_type=TICK_FLAGS_TYPE,
+            help="Tick flags (ALL, INFO, TRADE, or integer).",
+        ),
+    ],
+) -> None:
+    """Export ticks from a start date."""
+    _export_command(
+        ctx,
+        lambda client: client.copy_ticks_from(symbol, date_from, count, flags),
+    )
 
@@ -2055,8 +2261,7 @@ views cash_events and positions_reconstructed are deri
Source code in mt5cli/cli.py -
318
-319
+              
319
 320
 321
 322
@@ -2076,28 +2281,29 @@ views cash_events and positions_reconstructed are deri
 336
 337
 338
-339
@app.command()
-def ticks_range(
-    ctx: typer.Context,
-    symbol: Annotated[str, typer.Option(help="Symbol name.")],
-    date_from: Annotated[
-        datetime,
-        typer.Option(click_type=DATETIME_TYPE, help="Start date."),
-    ],
-    date_to: Annotated[
-        datetime,
-        typer.Option(click_type=DATETIME_TYPE, help="End date."),
-    ],
-    flags: Annotated[
-        int,
-        typer.Option(click_type=TICK_FLAGS_TYPE, help="Tick flags."),
-    ],
-) -> None:
-    """Export ticks for a date range."""
-    _export_command(
-        ctx,
-        lambda client: client.copy_ticks_range(symbol, date_from, date_to, flags),
-    )
+339
+340
@app.command()
+def ticks_range(
+    ctx: typer.Context,
+    symbol: Annotated[str, typer.Option(help="Symbol name.")],
+    date_from: Annotated[
+        datetime,
+        typer.Option(click_type=DATETIME_TYPE, help="Start date."),
+    ],
+    date_to: Annotated[
+        datetime,
+        typer.Option(click_type=DATETIME_TYPE, help="End date."),
+    ],
+    flags: Annotated[
+        int,
+        typer.Option(click_type=TICK_FLAGS_TYPE, help="Tick flags."),
+    ],
+) -> None:
+    """Export ticks for a date range."""
+    _export_command(
+        ctx,
+        lambda client: client.copy_ticks_range(symbol, date_from, date_to, flags),
+    )
 
@@ -2156,8 +2362,7 @@ views cash_events and positions_reconstructed are deri
Source code in mt5cli/cli.py -
342
-343
+              
343
 344
 345
 346
@@ -2190,41 +2395,42 @@ views cash_events and positions_reconstructed are deri
 373
 374
 375
-376
@app.command()
-def ticks_recent(
-    ctx: typer.Context,
-    symbol: Annotated[str, typer.Option(help="Symbol name.")],
-    seconds: Annotated[
-        float,
-        typer.Option(help="Lookback window in seconds."),
-    ],
-    date_to: Annotated[
-        datetime | None,
-        typer.Option(click_type=DATETIME_TYPE, help="Window end date."),
-    ] = None,
-    count: Annotated[
-        int,
-        typer.Option(help="Maximum number of ticks to return."),
-    ] = 10000,
-    flags: Annotated[
-        int,
-        typer.Option(
-            click_type=TICK_FLAGS_TYPE,
-            help="Tick flags (ALL, INFO, TRADE, or integer).",
-        ),
-    ] = "ALL",  # pyright: ignore[reportArgumentType]
-) -> None:
-    """Export ticks from a recent time window."""
-    _export_command(
-        ctx,
-        lambda client: client.recent_ticks(
-            symbol,
-            seconds,
-            date_to=date_to,
-            count=count,
-            flags=flags,
-        ),
-    )
+376
+377
@app.command()
+def ticks_recent(
+    ctx: typer.Context,
+    symbol: Annotated[str, typer.Option(help="Symbol name.")],
+    seconds: Annotated[
+        float,
+        typer.Option(help="Lookback window in seconds."),
+    ],
+    date_to: Annotated[
+        datetime | None,
+        typer.Option(click_type=DATETIME_TYPE, help="Window end date."),
+    ] = None,
+    count: Annotated[
+        int,
+        typer.Option(help="Maximum number of ticks to return."),
+    ] = 10000,
+    flags: Annotated[
+        int,
+        typer.Option(
+            click_type=TICK_FLAGS_TYPE,
+            help="Tick flags (ALL, INFO, TRADE, or integer).",
+        ),
+    ] = "ALL",  # pyright: ignore[reportArgumentType]
+) -> None:
+    """Export ticks from a recent time window."""
+    _export_command(
+        ctx,
+        lambda client: client.recent_ticks(
+            symbol,
+            seconds,
+            date_to=date_to,
+            count=count,
+            flags=flags,
+        ),
+    )
 
@@ -2249,13 +2455,13 @@ views cash_events and positions_reconstructed are deri
Source code in mt5cli/cli.py -
+ + + +
538
-539
+              
@app.command()
-def version(ctx: typer.Context) -> None:
-    """Export MetaTrader5 version information."""
-    _export_command(ctx, lambda client: client.version())
+541
+542
@app.command()
+def version(ctx: typer.Context) -> None:
+    """Export MetaTrader5 version information."""
+    _export_command(ctx, lambda client: client.version())
 
diff --git a/api/public-contract/index.html b/api/public-contract/index.html index 9af736d..13a96be 100644 --- a/api/public-contract/index.html +++ b/api/public-contract/index.html @@ -425,6 +425,10 @@ strategy entries, exits, Kelly sizing, or signal logic.

OrderSide, OrderFillingMode, OrderTimeMode, PositionSide, ExecutionStatus Typed enums for order helpers
ProjectionModeLiteral type for calculate_symbol_group_margin_ratio projection

MT5Client.order_send() and CLI order-send --yes are live execution paths.

@@ -546,6 +550,12 @@ the MT5 SDK helper.

+

calculate_symbol_group_margin_ratio supports an optional projection_mode +parameter ("add" by default). Pass projection_mode="replace_symbol" to +subtract current exposure for new_symbol before adding the candidate margin — +useful for reversal-style projections. mt5cli only calculates broker-facing +exposure; downstream applications own thresholds, risk guard actions, and +strategy policy.

CLI commands

The Typer application in mt5cli.cli exposes file-export commands documented in CLI Module and the project README. CLI commands:

@@ -556,7 +566,12 @@ the MT5 SDK helper.

  • Delegate to the same Python APIs described here; they are not duplicated business logic.
  • -

    order-send requires --yes before placing live trades.

    +

    order-send is the expert raw-request path; it requires --yes and a fully +constructed request payload. close-positions is the safer high-level helper +that closes open positions by --symbol or --ticket using +close_open_positions(). Both order-send --yes and close-positions --yes +are live execution paths. close-positions --dry-run previews close orders +without placing them and does not require --yes.

    Internal helpers (not stable)

    Do not import these for downstream contracts; they may change without a semver notice:

    diff --git a/api/trading/index.html b/api/trading/index.html index 9a09473..e3e6e76 100644 --- a/api/trading/index.html +++ b/api/trading/index.html @@ -347,6 +347,28 @@ +

    + ProjectionMode + + + + module-attribute + + +

    +
    ProjectionMode = Literal['add', 'replace_symbol']
    +
    + +
    + +
    + +
    + +
    + + +

    __all__ @@ -366,36 +388,37 @@ "OrderSide", "OrderTimeMode", "PositionSide", - "calculate_account_projected_margin_ratio", - "calculate_margin_and_volume", - "calculate_new_position_margin_ratio", - "calculate_positions_margin", - "calculate_positions_margin_by_symbol", - "calculate_positions_margin_safe", - "calculate_projected_margin_ratio", - "calculate_spread_ratio", - "calculate_symbol_group_margin_ratio", - "calculate_trailing_stop_updates", - "calculate_volume_by_margin", - "close_open_positions", - "create_trading_client", - "detect_position_side", - "determine_order_limits", - "ensure_symbol_selected", - "estimate_order_margin", - "extract_tick_price", - "fetch_latest_closed_rates_for_trading_client", - "fetch_latest_closed_rates_indexed", - "get_account_snapshot", - "get_positions_frame", - "get_symbol_snapshot", - "get_tick_snapshot", - "mt5_trading_session", - "normalize_order_volume", - "place_market_order", - "update_sltp_for_open_positions", - "update_trailing_stop_loss_for_open_positions", -] + "ProjectionMode", + "calculate_account_projected_margin_ratio", + "calculate_margin_and_volume", + "calculate_new_position_margin_ratio", + "calculate_positions_margin", + "calculate_positions_margin_by_symbol", + "calculate_positions_margin_safe", + "calculate_projected_margin_ratio", + "calculate_spread_ratio", + "calculate_symbol_group_margin_ratio", + "calculate_trailing_stop_updates", + "calculate_volume_by_margin", + "close_open_positions", + "create_trading_client", + "detect_position_side", + "determine_order_limits", + "ensure_symbol_selected", + "estimate_order_margin", + "extract_tick_price", + "fetch_latest_closed_rates_for_trading_client", + "fetch_latest_closed_rates_indexed", + "get_account_snapshot", + "get_positions_frame", + "get_symbol_snapshot", + "get_tick_snapshot", + "mt5_trading_session", + "normalize_order_volume", + "place_market_order", + "update_sltp_for_open_positions", + "update_trailing_stop_loss_for_open_positions", +]

    @@ -1034,9 +1057,7 @@ and positive volume are all supplied.

    Source code in mt5cli/trading.py -
    866
    -867
    -868
    +              
    868
     869
     870
     871
    @@ -1059,32 +1080,34 @@ and positive volume are all supplied.

    888 889 890 -891
    def calculate_account_projected_margin_ratio(
    -    client: Mt5TradingClient,
    -    *,
    -    symbol: str | None = None,
    -    new_position_side: OrderSide | None = None,
    -    new_position_volume: float = 0.0,
    -) -> float:
    -    """Return account-wide current plus optional new-position margin over equity.
    -
    -    Current exposure comes from the broker account snapshot ``margin`` field so
    -    unrelated open positions remain in the baseline. Optional projected
    -    exposure is added via :func:`estimate_order_margin` only when a symbol, side,
    -    and positive volume are all supplied.
    -
    -    """
    -    account = get_account_snapshot(client)
    -    equity = _required_account_number(account, "equity", allow_zero=False)
    -    margin = _required_account_number(account, "margin", allow_zero=True)
    -    if symbol is not None and new_position_side is not None and new_position_volume > 0:
    -        margin += estimate_order_margin(
    -            client,
    -            symbol,
    -            new_position_side,
    -            new_position_volume,
    -        )
    -    return margin / equity
    +891
    +892
    +893
    def calculate_account_projected_margin_ratio(
    +    client: Mt5TradingClient,
    +    *,
    +    symbol: str | None = None,
    +    new_position_side: OrderSide | None = None,
    +    new_position_volume: float = 0.0,
    +) -> float:
    +    """Return account-wide current plus optional new-position margin over equity.
    +
    +    Current exposure comes from the broker account snapshot ``margin`` field so
    +    unrelated open positions remain in the baseline. Optional projected
    +    exposure is added via :func:`estimate_order_margin` only when a symbol, side,
    +    and positive volume are all supplied.
    +
    +    """
    +    account = get_account_snapshot(client)
    +    equity = _required_account_number(account, "equity", allow_zero=False)
    +    margin = _required_account_number(account, "margin", allow_zero=True)
    +    if symbol is not None and new_position_side is not None and new_position_volume > 0:
    +        margin += estimate_order_margin(
    +            client,
    +            symbol,
    +            new_position_side,
    +            new_position_volume,
    +        )
    +    return margin / equity
     
    @@ -1241,20 +1264,7 @@ side when the post-reserve margin can afford it.

    Source code in mt5cli/trading.py -
     977
    - 978
    - 979
    - 980
    - 981
    - 982
    - 983
    - 984
    - 985
    - 986
    - 987
    - 988
    - 989
    - 990
    +              
     990
      991
      992
      993
    @@ -1305,71 +1315,84 @@ side when the post-reserve margin can afford it.

    1038 1039 1040 -1041
    def calculate_margin_and_volume(
    -    client: Mt5TradingClient,
    -    symbol: str,
    -    unit_margin_ratio: float,
    -    preserved_margin_ratio: float,
    -) -> MarginVolume:
    -    """Calculate tradable margin and volumes from account free margin.
    -
    -    Applies ``preserved_margin_ratio`` to keep a reserve off ``margin_free``,
    -    then allocates ``unit_margin_ratio`` of the remainder as the margin budget
    -    for proportional volume sizing on both buy and sell sides. A
    -    ``unit_margin_ratio`` of ``0`` requests exactly one minimum valid unit per
    -    side when the post-reserve margin can afford it.
    -
    -    Args:
    -        client: Connected ``Mt5TradingClient`` instance.
    -        symbol: Symbol used for minimum-lot margin and volume calculations.
    -        unit_margin_ratio: Fraction of post-reserve margin to allocate per unit.
    -        preserved_margin_ratio: Fraction of ``margin_free`` to preserve.
    -
    -    Returns:
    -        Dictionary with ``margin_free``, ``available_margin``, ``trade_margin``,
    -        ``buy_volume``, and ``sell_volume``. Negative ``margin_free`` values are
    -        clamped to ``0.0`` before sizing.
    -    """
    -    _require_unit_ratio(unit_margin_ratio, "unit_margin_ratio")
    -    _require_unit_ratio(preserved_margin_ratio, "preserved_margin_ratio")
    -
    -    account = client.account_info_as_dict()
    -    margin_free = max(0.0, float(account.get("margin_free") or 0.0))
    -    available_margin = margin_free * (1.0 - preserved_margin_ratio)
    -    trade_margin = available_margin * unit_margin_ratio
    -    if unit_margin_ratio == 0:
    -        buy_volume = _calculate_min_volume_if_affordable(
    -            client,
    -            symbol,
    -            available_margin,
    -            "BUY",
    -        )
    -        sell_volume = _calculate_min_volume_if_affordable(
    -            client,
    -            symbol,
    -            available_margin,
    -            "SELL",
    -        )
    -    else:
    -        buy_volume = calculate_volume_by_margin(client, symbol, trade_margin, "BUY")
    -        sell_volume = calculate_volume_by_margin(client, symbol, trade_margin, "SELL")
    -    try:
    -        symbol_info = get_symbol_snapshot(client, symbol)
    -        volume_min = float(symbol_info.get("volume_min") or 0.0)
    -        volume_max = float(symbol_info.get("volume_max") or 0.0)
    -        volume_step = float(symbol_info.get("volume_step") or 0.0)
    -    except AttributeError:
    -        volume_min = volume_max = volume_step = 0.0
    -    return {
    -        "margin_free": margin_free,
    -        "available_margin": available_margin,
    -        "trade_margin": trade_margin,
    -        "buy_volume": float(buy_volume),
    -        "sell_volume": float(sell_volume),
    -        "volume_min": volume_min,
    -        "volume_max": volume_max,
    -        "volume_step": volume_step,
    -    }
    +1041
    +1042
    +1043
    +1044
    +1045
    +1046
    +1047
    +1048
    +1049
    +1050
    +1051
    +1052
    +1053
    +1054
    def calculate_margin_and_volume(
    +    client: Mt5TradingClient,
    +    symbol: str,
    +    unit_margin_ratio: float,
    +    preserved_margin_ratio: float,
    +) -> MarginVolume:
    +    """Calculate tradable margin and volumes from account free margin.
    +
    +    Applies ``preserved_margin_ratio`` to keep a reserve off ``margin_free``,
    +    then allocates ``unit_margin_ratio`` of the remainder as the margin budget
    +    for proportional volume sizing on both buy and sell sides. A
    +    ``unit_margin_ratio`` of ``0`` requests exactly one minimum valid unit per
    +    side when the post-reserve margin can afford it.
    +
    +    Args:
    +        client: Connected ``Mt5TradingClient`` instance.
    +        symbol: Symbol used for minimum-lot margin and volume calculations.
    +        unit_margin_ratio: Fraction of post-reserve margin to allocate per unit.
    +        preserved_margin_ratio: Fraction of ``margin_free`` to preserve.
    +
    +    Returns:
    +        Dictionary with ``margin_free``, ``available_margin``, ``trade_margin``,
    +        ``buy_volume``, and ``sell_volume``. Negative ``margin_free`` values are
    +        clamped to ``0.0`` before sizing.
    +    """
    +    _require_unit_ratio(unit_margin_ratio, "unit_margin_ratio")
    +    _require_unit_ratio(preserved_margin_ratio, "preserved_margin_ratio")
    +
    +    account = client.account_info_as_dict()
    +    margin_free = max(0.0, float(account.get("margin_free") or 0.0))
    +    available_margin = margin_free * (1.0 - preserved_margin_ratio)
    +    trade_margin = available_margin * unit_margin_ratio
    +    if unit_margin_ratio == 0:
    +        buy_volume = _calculate_min_volume_if_affordable(
    +            client,
    +            symbol,
    +            available_margin,
    +            "BUY",
    +        )
    +        sell_volume = _calculate_min_volume_if_affordable(
    +            client,
    +            symbol,
    +            available_margin,
    +            "SELL",
    +        )
    +    else:
    +        buy_volume = calculate_volume_by_margin(client, symbol, trade_margin, "BUY")
    +        sell_volume = calculate_volume_by_margin(client, symbol, trade_margin, "SELL")
    +    try:
    +        symbol_info = get_symbol_snapshot(client, symbol)
    +        volume_min = float(symbol_info.get("volume_min") or 0.0)
    +        volume_max = float(symbol_info.get("volume_max") or 0.0)
    +        volume_step = float(symbol_info.get("volume_step") or 0.0)
    +    except AttributeError:
    +        volume_min = volume_max = volume_step = 0.0
    +    return {
    +        "margin_free": margin_free,
    +        "available_margin": available_margin,
    +        "trade_margin": trade_margin,
    +        "buy_volume": float(buy_volume),
    +        "sell_volume": float(sell_volume),
    +        "volume_min": volume_min,
    +        "volume_max": volume_max,
    +        "volume_step": volume_step,
    +    }
     
    @@ -1428,9 +1451,7 @@ side when the post-reserve margin can afford it.

    Source code in mt5cli/trading.py -
    801
    -802
    -803
    +              
    803
     804
     805
     806
    @@ -1460,39 +1481,41 @@ side when the post-reserve margin can afford it.

    830 831 832 -833
    def calculate_new_position_margin_ratio(
    -    client: Mt5TradingClient,
    -    *,
    -    symbol: str,
    -    new_position_side: OrderSide | None = None,
    -    new_position_volume: float = 0.0,
    -) -> float:
    -    """Return total margin/equity ratio after an optional hypothetical position.
    -
    -    Raises:
    -        Mt5TradingError: If equity or required tick data is invalid.
    -    """
    -    account = get_account_snapshot(client)
    -    equity = float(account.get("equity") or 0.0)
    -    if equity <= 0:
    -        msg = "Account equity must be positive to calculate margin ratio."
    -        raise Mt5TradingError(msg)
    -    margin = float(account.get("margin") or 0.0)
    -    if new_position_side is not None and new_position_volume > 0:
    -        side = _normalize_order_side(new_position_side)
    -        price = extract_tick_price(
    -            get_tick_snapshot(client, symbol), "ask" if side == "BUY" else "bid"
    -        )
    -        if price is None:
    -            msg = f"Tick price is unavailable for {symbol!r}."
    -            raise Mt5TradingError(msg)
    -        order_type = (
    -            client.mt5.ORDER_TYPE_BUY if side == "BUY" else client.mt5.ORDER_TYPE_SELL
    -        )
    -        margin += float(
    -            client.order_calc_margin(order_type, symbol, new_position_volume, price),
    -        )
    -    return margin / equity
    +833
    +834
    +835
    def calculate_new_position_margin_ratio(
    +    client: Mt5TradingClient,
    +    *,
    +    symbol: str,
    +    new_position_side: OrderSide | None = None,
    +    new_position_volume: float = 0.0,
    +) -> float:
    +    """Return total margin/equity ratio after an optional hypothetical position.
    +
    +    Raises:
    +        Mt5TradingError: If equity or required tick data is invalid.
    +    """
    +    account = get_account_snapshot(client)
    +    equity = float(account.get("equity") or 0.0)
    +    if equity <= 0:
    +        msg = "Account equity must be positive to calculate margin ratio."
    +        raise Mt5TradingError(msg)
    +    margin = float(account.get("margin") or 0.0)
    +    if new_position_side is not None and new_position_volume > 0:
    +        side = _normalize_order_side(new_position_side)
    +        price = extract_tick_price(
    +            get_tick_snapshot(client, symbol), "ask" if side == "BUY" else "bid"
    +        )
    +        if price is None:
    +            msg = f"Tick price is unavailable for {symbol!r}."
    +            raise Mt5TradingError(msg)
    +        order_type = (
    +            client.mt5.ORDER_TYPE_BUY if side == "BUY" else client.mt5.ORDER_TYPE_SELL
    +        )
    +        margin += float(
    +            client.order_calc_margin(order_type, symbol, new_position_volume, price),
    +        )
    +    return margin / equity
     
    @@ -1592,9 +1615,7 @@ included.

    Source code in mt5cli/trading.py -
    678
    -679
    -680
    +              
    680
     681
     682
     683
    @@ -1631,46 +1652,48 @@ included.

    714 715 716 -717
    def calculate_positions_margin(
    -    client: Mt5TradingClient,
    -    *,
    -    symbols: Sequence[str] | None = None,
    -) -> float:
    -    """Return the sum of estimated current margin for open positions.
    -
    -    Args:
    -        client: Connected ``Mt5TradingClient`` instance.
    -        symbols: Optional symbol filter. When omitted, all open positions are
    -            included.
    -
    -    Returns:
    -        Total estimated margin, or ``0.0`` when no matching positions exist.
    -    """
    -    frame = get_positions_frame(client)
    -    if frame.empty or "symbol" not in frame.columns:
    -        return 0.0
    -    if symbols is not None:
    -        frame = frame[frame["symbol"].isin(list(symbols))]
    -    if frame.empty:
    -        return 0.0
    -    grouped_volumes: dict[tuple[str, OrderSide], float] = {}
    -    for _, row in frame.iterrows():
    -        symbol = row.get("symbol")
    -        if not isinstance(symbol, str) or not symbol:
    -            continue
    -        volume = row.get("volume")
    -        if not _is_positive_finite_number(volume):
    -            continue
    -        order_side = _order_side_from_position_type(client, row.get("type"))
    -        if order_side is None:
    -            continue
    -        key = (symbol, order_side)
    -        finite_volume = float(cast("float | int", volume))
    -        grouped_volumes[key] = grouped_volumes.get(key, 0.0) + finite_volume
    -    total = 0.0
    -    for (symbol, order_side), volume in grouped_volumes.items():
    -        total += estimate_order_margin(client, symbol, order_side, volume)
    -    return total
    +717
    +718
    +719
    def calculate_positions_margin(
    +    client: Mt5TradingClient,
    +    *,
    +    symbols: Sequence[str] | None = None,
    +) -> float:
    +    """Return the sum of estimated current margin for open positions.
    +
    +    Args:
    +        client: Connected ``Mt5TradingClient`` instance.
    +        symbols: Optional symbol filter. When omitted, all open positions are
    +            included.
    +
    +    Returns:
    +        Total estimated margin, or ``0.0`` when no matching positions exist.
    +    """
    +    frame = get_positions_frame(client)
    +    if frame.empty or "symbol" not in frame.columns:
    +        return 0.0
    +    if symbols is not None:
    +        frame = frame[frame["symbol"].isin(list(symbols))]
    +    if frame.empty:
    +        return 0.0
    +    grouped_volumes: dict[tuple[str, OrderSide], float] = {}
    +    for _, row in frame.iterrows():
    +        symbol = row.get("symbol")
    +        if not isinstance(symbol, str) or not symbol:
    +            continue
    +        volume = row.get("volume")
    +        if not _is_positive_finite_number(volume):
    +            continue
    +        order_side = _order_side_from_position_type(client, row.get("type"))
    +        if order_side is None:
    +            continue
    +        key = (symbol, order_side)
    +        finite_volume = float(cast("float | int", volume))
    +        grouped_volumes[key] = grouped_volumes.get(key, 0.0) + finite_volume
    +    total = 0.0
    +    for (symbol, order_side), volume in grouped_volumes.items():
    +        total += estimate_order_margin(client, symbol, order_side, volume)
    +    return total
     
    @@ -1857,9 +1880,7 @@ When False, re-raise the first failure.

    Source code in mt5cli/trading.py -
    720
    -721
    -722
    +              
    722
     723
     724
     725
    @@ -1897,47 +1918,49 @@ When False, re-raise the first failure.

    757 758 759 -760
    def calculate_positions_margin_by_symbol(
    -    client: Mt5TradingClient,
    -    *,
    -    symbols: Sequence[str],
    -    suppress_errors: bool = True,
    -) -> dict[str, float]:
    -    """Return per-symbol estimated margin for open positions.
    -
    -    Computes margin for each unique input symbol independently using the strict
    -    :func:`calculate_positions_margin` helper. Duplicates are deduplicated in
    -    first-seen order.
    -
    -    Args:
    -        client: Connected ``Mt5TradingClient`` instance.
    -        symbols: Symbols to compute margin for.
    -        suppress_errors: When ``True``, log and skip symbols that raise
    -            ``Mt5TradingError``, ``Mt5RuntimeError``, or ``AttributeError``.
    -            When ``False``, re-raise the first failure.
    -
    -    Returns:
    -        Mapping of symbol to margin total in first-seen unique-symbol order.
    -        Returns an empty dict when ``symbols`` is empty or all symbols fail
    -        with ``suppress_errors=True``.
    -
    -    Raises:
    -        Mt5TradingError: When a symbol raises ``Mt5TradingError`` and
    -            ``suppress_errors=False``.
    -        Mt5RuntimeError: When a symbol raises ``Mt5RuntimeError`` and
    +760
    +761
    +762
    def calculate_positions_margin_by_symbol(
    +    client: Mt5TradingClient,
    +    *,
    +    symbols: Sequence[str],
    +    suppress_errors: bool = True,
    +) -> dict[str, float]:
    +    """Return per-symbol estimated margin for open positions.
    +
    +    Computes margin for each unique input symbol independently using the strict
    +    :func:`calculate_positions_margin` helper. Duplicates are deduplicated in
    +    first-seen order.
    +
    +    Args:
    +        client: Connected ``Mt5TradingClient`` instance.
    +        symbols: Symbols to compute margin for.
    +        suppress_errors: When ``True``, log and skip symbols that raise
    +            ``Mt5TradingError``, ``Mt5RuntimeError``, or ``AttributeError``.
    +            When ``False``, re-raise the first failure.
    +
    +    Returns:
    +        Mapping of symbol to margin total in first-seen unique-symbol order.
    +        Returns an empty dict when ``symbols`` is empty or all symbols fail
    +        with ``suppress_errors=True``.
    +
    +    Raises:
    +        Mt5TradingError: When a symbol raises ``Mt5TradingError`` and
                 ``suppress_errors=False``.
    -        AttributeError: When a symbol raises ``AttributeError`` and
    +        Mt5RuntimeError: When a symbol raises ``Mt5RuntimeError`` and
                 ``suppress_errors=False``.
    -    """
    -    result: dict[str, float] = {}
    -    for symbol in dict.fromkeys(symbols):
    -        try:
    -            result[symbol] = calculate_positions_margin(client, symbols=[symbol])
    -        except (Mt5TradingError, Mt5RuntimeError, AttributeError) as exc:
    -            if not suppress_errors:
    -                raise
    -            _logger.warning("Skipping margin for %r: %s", symbol, exc)
    -    return result
    +        AttributeError: When a symbol raises ``AttributeError`` and
    +            ``suppress_errors=False``.
    +    """
    +    result: dict[str, float] = {}
    +    for symbol in dict.fromkeys(symbols):
    +        try:
    +            result[symbol] = calculate_positions_margin(client, symbols=[symbol])
    +        except (Mt5TradingError, Mt5RuntimeError, AttributeError) as exc:
    +            if not suppress_errors:
    +                raise
    +            _logger.warning("Skipping margin for %r: %s", symbol, exc)
    +    return result
     
    @@ -2036,9 +2059,7 @@ When False, re-raise the first failure.

    Source code in mt5cli/trading.py -
    763
    -764
    -765
    +              
    765
     766
     767
     768
    @@ -2056,27 +2077,29 @@ When False, re-raise the first failure.

    780 781 782 -783
    def calculate_positions_margin_safe(
    -    client: Mt5TradingClient,
    -    *,
    -    symbols: Sequence[str],
    -) -> float:
    -    """Return the total estimated margin for open positions across symbols.
    -
    -    Internally calls :func:`calculate_positions_margin_by_symbol` with
    -    ``suppress_errors=True``. Failed symbols are silently skipped.
    -
    -    Args:
    -        client: Connected ``Mt5TradingClient`` instance.
    -        symbols: Symbols to include.
    -
    -    Returns:
    -        Sum of per-symbol margins; ``0.0`` when no symbols or all fail.
    -    """
    -    return sum(
    -        calculate_positions_margin_by_symbol(client, symbols=symbols).values(),
    -        0.0,
    -    )
    +783
    +784
    +785
    def calculate_positions_margin_safe(
    +    client: Mt5TradingClient,
    +    *,
    +    symbols: Sequence[str],
    +) -> float:
    +    """Return the total estimated margin for open positions across symbols.
    +
    +    Internally calls :func:`calculate_positions_margin_by_symbol` with
    +    ``suppress_errors=True``. Failed symbols are silently skipped.
    +
    +    Args:
    +        client: Connected ``Mt5TradingClient`` instance.
    +        symbols: Symbols to include.
    +
    +    Returns:
    +        Sum of per-symbol margins; ``0.0`` when no symbols or all fail.
    +    """
    +    return sum(
    +        calculate_positions_margin_by_symbol(client, symbols=symbols).values(),
    +        0.0,
    +    )
     
    @@ -2118,9 +2141,7 @@ the composed MT5 helpers propagate to the caller.

    Source code in mt5cli/trading.py -
    894
    -895
    -896
    +              
    896
     897
     898
     899
    @@ -2144,33 +2165,35 @@ the composed MT5 helpers propagate to the caller.

    917 918 919 -920
    def calculate_projected_margin_ratio(
    -    client: Mt5TradingClient,
    -    *,
    -    symbol: str,
    -    new_position_side: OrderSide | None = None,
    -    new_position_volume: float = 0.0,
    -) -> float:
    -    """Return estimated current plus optional new-position margin over equity.
    -
    -    Current exposure is estimated from open positions with
    -    :func:`calculate_positions_margin`. Optional projected exposure is added via
    -    :func:`estimate_order_margin`. Thresholds and guard actions are intentionally
    -    left to downstream applications.
    -
    -    Account equity, position margin, and optional projected margin errors from
    -    the composed MT5 helpers propagate to the caller.
    -    """
    -    equity = _account_equity(client)
    -    margin = calculate_positions_margin(client, symbols=[symbol])
    -    if new_position_side is not None and new_position_volume > 0:
    -        margin += estimate_order_margin(
    -            client,
    -            symbol,
    -            new_position_side,
    -            new_position_volume,
    -        )
    -    return margin / equity
    +920
    +921
    +922
    def calculate_projected_margin_ratio(
    +    client: Mt5TradingClient,
    +    *,
    +    symbol: str,
    +    new_position_side: OrderSide | None = None,
    +    new_position_volume: float = 0.0,
    +) -> float:
    +    """Return estimated current plus optional new-position margin over equity.
    +
    +    Current exposure is estimated from open positions with
    +    :func:`calculate_positions_margin`. Optional projected exposure is added via
    +    :func:`estimate_order_margin`. Thresholds and guard actions are intentionally
    +    left to downstream applications.
    +
    +    Account equity, position margin, and optional projected margin errors from
    +    the composed MT5 helpers propagate to the caller.
    +    """
    +    equity = _account_equity(client)
    +    margin = calculate_positions_margin(client, symbols=[symbol])
    +    if new_position_side is not None and new_position_volume > 0:
    +        margin += estimate_order_margin(
    +            client,
    +            symbol,
    +            new_position_side,
    +            new_position_volume,
    +        )
    +    return margin / equity
     
    @@ -2220,9 +2243,7 @@ the composed MT5 helpers propagate to the caller.

    Source code in mt5cli/trading.py -
    786
    -787
    -788
    +              
    788
     789
     790
     791
    @@ -2232,19 +2253,21 @@ the composed MT5 helpers propagate to the caller.

    795 796 797 -798
    def calculate_spread_ratio(client: Mt5TradingClient, symbol: str) -> float:
    -    """Return ``(ask - bid) / ((ask + bid) / 2)`` for the latest tick.
    -
    -    Raises:
    -        Mt5TradingError: If bid or ask is unavailable.
    -    """
    -    tick = get_tick_snapshot(client, symbol)
    -    bid = extract_tick_price(tick, "bid")
    -    ask = extract_tick_price(tick, "ask")
    -    if bid is None or ask is None:
    -        msg = f"Tick bid/ask is unavailable for {symbol!r}."
    -        raise Mt5TradingError(msg)
    -    return (ask - bid) / ((ask + bid) / 2.0)
    +798
    +799
    +800
    def calculate_spread_ratio(client: Mt5TradingClient, symbol: str) -> float:
    +    """Return ``(ask - bid) / ((ask + bid) / 2)`` for the latest tick.
    +
    +    Raises:
    +        Mt5TradingError: If bid or ask is unavailable.
    +    """
    +    tick = get_tick_snapshot(client, symbol)
    +    bid = extract_tick_price(tick, "bid")
    +    ask = extract_tick_price(tick, "ask")
    +    if bid is None or ask is None:
    +        msg = f"Tick bid/ask is unavailable for {symbol!r}."
    +        raise Mt5TradingError(msg)
    +    return (ask - bid) / ((ask + bid) / 2.0)
     
    @@ -2272,7 +2295,13 @@ the composed MT5 helpers propagate to the caller.

    (mt5cli.trading.OrderSide)" href="#mt5cli.trading.OrderSide">OrderSide | None = None, new_position_volume: float = 0.0, suppress_errors: bool = True, -) -> float + projection_mode: ProjectionMode = "add", +) -> float
    @@ -2280,8 +2309,16 @@ the composed MT5 helpers propagate to the caller.

    Return estimated symbol-group margin over account equity.

    Per-symbol current exposure is summed with :func:calculate_positions_margin_by_symbol. When new_symbol is inside -the input symbol group, optional projected order margin is added for that -symbol. Invalid equity always raises to fail closed.

    +the input symbol group and candidate side/volume are provided, projected order +margin is applied according to projection_mode:

    +
      +
    • "add" (default): adds candidate margin to the group total.
    • +
    • "replace_symbol": subtracts current margin for new_symbol, then + adds candidate margin. Useful for reversal-style projections where the new + order is intended to replace existing exposure for that symbol.
    • +
    +

    If the candidate margin estimation fails, the subtraction is also skipped so +the operation is atomic. Invalid equity always raises to fail closed.

    Raises:

    @@ -2333,9 +2370,7 @@ lookup or projected margin lookup fails and suppress_errors is
    Source code in mt5cli/trading.py -
    923
    -924
    -925
    +              
    925
     926
     927
     928
    @@ -2384,58 +2419,82 @@ lookup or projected margin lookup fails and suppress_errors is
     971
     972
     973
    -974
    def calculate_symbol_group_margin_ratio(
    -    client: Mt5TradingClient,
    -    *,
    -    symbols: Sequence[str],
    -    new_symbol: str | None = None,
    -    new_position_side: OrderSide | None = None,
    -    new_position_volume: float = 0.0,
    -    suppress_errors: bool = True,
    -) -> float:
    -    """Return estimated symbol-group margin over account equity.
    -
    -    Per-symbol current exposure is summed with
    -    :func:`calculate_positions_margin_by_symbol`. When ``new_symbol`` is inside
    -    the input symbol group, optional projected order margin is added for that
    -    symbol. Invalid equity always raises to fail closed.
    -
    -    Raises:
    -        AttributeError: When symbol margin lookup or projected margin lookup
    -            fails and ``suppress_errors`` is ``False``.
    -        Mt5RuntimeError: When symbol margin lookup or projected margin lookup
    -            fails and ``suppress_errors`` is ``False``.
    -        Mt5TradingError: When account equity is invalid, or when symbol margin
    -            lookup or projected margin lookup fails and ``suppress_errors`` is
    -            ``False``.
    -    """
    -    equity = _account_equity(client)
    -    unique_symbols = list(dict.fromkeys(symbols))
    -    margin = sum(
    -        calculate_positions_margin_by_symbol(
    -            client,
    -            symbols=unique_symbols,
    -            suppress_errors=suppress_errors,
    -        ).values(),
    -        0.0,
    -    )
    -    if (
    -        new_symbol in unique_symbols
    -        and new_position_side is not None
    -        and new_position_volume > 0
    -    ):
    -        try:
    -            margin += estimate_order_margin(
    -                client,
    -                new_symbol,
    -                new_position_side,
    -                new_position_volume,
    -            )
    -        except (Mt5TradingError, Mt5RuntimeError, AttributeError):
    -            if not suppress_errors:
    -                raise
    -            _logger.warning("Skipping projected margin for %r.", new_symbol)
    -    return margin / equity
    +974
    +975
    +976
    +977
    +978
    +979
    +980
    +981
    +982
    +983
    +984
    +985
    +986
    +987
    def calculate_symbol_group_margin_ratio(
    +    client: Mt5TradingClient,
    +    *,
    +    symbols: Sequence[str],
    +    new_symbol: str | None = None,
    +    new_position_side: OrderSide | None = None,
    +    new_position_volume: float = 0.0,
    +    suppress_errors: bool = True,
    +    projection_mode: ProjectionMode = "add",
    +) -> float:
    +    """Return estimated symbol-group margin over account equity.
    +
    +    Per-symbol current exposure is summed with
    +    :func:`calculate_positions_margin_by_symbol`. When ``new_symbol`` is inside
    +    the input symbol group and candidate side/volume are provided, projected order
    +    margin is applied according to ``projection_mode``:
    +
    +    - ``"add"`` (default): adds candidate margin to the group total.
    +    - ``"replace_symbol"``: subtracts current margin for ``new_symbol``, then
    +      adds candidate margin. Useful for reversal-style projections where the new
    +      order is intended to replace existing exposure for that symbol.
    +
    +    If the candidate margin estimation fails, the subtraction is also skipped so
    +    the operation is atomic. Invalid equity always raises to fail closed.
    +
    +    Raises:
    +        AttributeError: When symbol margin lookup or projected margin lookup
    +            fails and ``suppress_errors`` is ``False``.
    +        Mt5RuntimeError: When symbol margin lookup or projected margin lookup
    +            fails and ``suppress_errors`` is ``False``.
    +        Mt5TradingError: When account equity is invalid, or when symbol margin
    +            lookup or projected margin lookup fails and ``suppress_errors`` is
    +            ``False``.
    +    """
    +    equity = _account_equity(client)
    +    unique_symbols = list(dict.fromkeys(symbols))
    +    per_symbol = calculate_positions_margin_by_symbol(
    +        client,
    +        symbols=unique_symbols,
    +        suppress_errors=suppress_errors,
    +    )
    +    margin = sum(per_symbol.values(), 0.0)
    +    if (
    +        new_symbol in unique_symbols
    +        and new_position_side is not None
    +        and new_position_volume > 0
    +    ):
    +        try:
    +            candidate_margin = estimate_order_margin(
    +                client,
    +                new_symbol,
    +                new_position_side,
    +                new_position_volume,
    +            )
    +        except (Mt5TradingError, Mt5RuntimeError, AttributeError):
    +            if not suppress_errors:
    +                raise
    +            _logger.warning("Skipping projected margin for %r.", new_symbol)
    +        else:
    +            if projection_mode == "replace_symbol":
    +                margin -= per_symbol.get(new_symbol, 0.0)
    +            margin += candidate_margin
    +    return margin / equity
     
    @@ -2470,20 +2529,7 @@ missing side-specific tick price are skipped.

    Source code in mt5cli/trading.py -
    1380
    -1381
    -1382
    -1383
    -1384
    -1385
    -1386
    -1387
    -1388
    -1389
    -1390
    -1391
    -1392
    -1393
    +              
    1393
     1394
     1395
     1396
    @@ -2512,49 +2558,62 @@ missing side-specific tick price are skipped.

    1419 1420 1421 -1422
    def calculate_trailing_stop_updates(
    -    client: Mt5TradingClient,
    -    *,
    -    symbol: str,
    -    trailing_stop_ratio: float,
    -) -> dict[int, float]:
    -    """Return per-ticket trailing stop-loss updates for open symbol positions.
    -
    -    Buy positions trail from bid using ``bid * (1 - trailing_stop_ratio)``.
    -    Sell positions trail from ask using ``ask * (1 + trailing_stop_ratio)``.
    -    Existing stop losses are preserved when they are already more favorable.
    -    Missing symbol metadata returns an empty update map. Positions with a
    -    missing side-specific tick price are skipped.
    -    """
    -    _require_protective_ratio(trailing_stop_ratio, "trailing_stop_ratio")
    -    positions = get_positions_frame(client, symbol=symbol)
    -    if positions.empty:
    -        return {}
    -    tick = get_tick_snapshot(client, symbol)
    -    bid = extract_tick_price(tick, "bid")
    -    ask = extract_tick_price(tick, "ask")
    -    digits = _symbol_digits(client, symbol)
    -    if digits is None:
    -        return {}
    -
    -    updates: dict[int, float] = {}
    -    for row in positions.to_dict("records"):
    -        ticket = _position_ticket(row.get("ticket"))
    -        if ticket is None:
    -            continue
    -        next_sl = _trailing_stop_loss(
    -            client,
    -            position_type=row.get("type"),
    -            current_sl=_current_stop_loss(row.get("sl")),
    -            bid=bid,
    -            ask=ask,
    -            digits=digits,
    -            trailing_stop_ratio=trailing_stop_ratio,
    -        )
    -        if next_sl is None:
    -            continue
    -        updates[ticket] = next_sl
    -    return updates
    +1422
    +1423
    +1424
    +1425
    +1426
    +1427
    +1428
    +1429
    +1430
    +1431
    +1432
    +1433
    +1434
    +1435
    def calculate_trailing_stop_updates(
    +    client: Mt5TradingClient,
    +    *,
    +    symbol: str,
    +    trailing_stop_ratio: float,
    +) -> dict[int, float]:
    +    """Return per-ticket trailing stop-loss updates for open symbol positions.
    +
    +    Buy positions trail from bid using ``bid * (1 - trailing_stop_ratio)``.
    +    Sell positions trail from ask using ``ask * (1 + trailing_stop_ratio)``.
    +    Existing stop losses are preserved when they are already more favorable.
    +    Missing symbol metadata returns an empty update map. Positions with a
    +    missing side-specific tick price are skipped.
    +    """
    +    _require_protective_ratio(trailing_stop_ratio, "trailing_stop_ratio")
    +    positions = get_positions_frame(client, symbol=symbol)
    +    if positions.empty:
    +        return {}
    +    tick = get_tick_snapshot(client, symbol)
    +    bid = extract_tick_price(tick, "bid")
    +    ask = extract_tick_price(tick, "ask")
    +    digits = _symbol_digits(client, symbol)
    +    if digits is None:
    +        return {}
    +
    +    updates: dict[int, float] = {}
    +    for row in positions.to_dict("records"):
    +        ticket = _position_ticket(row.get("ticket"))
    +        if ticket is None:
    +            continue
    +        next_sl = _trailing_stop_loss(
    +            client,
    +            position_type=row.get("type"),
    +            current_sl=_current_stop_loss(row.get("sl")),
    +            bid=bid,
    +            ask=ask,
    +            digits=digits,
    +            trailing_stop_ratio=trailing_stop_ratio,
    +        )
    +        if next_sl is None:
    +            continue
    +        updates[ticket] = next_sl
    +    return updates
     
    @@ -2655,20 +2714,7 @@ missing side-specific tick price are skipped.

    Source code in mt5cli/trading.py -
    1044
    -1045
    -1046
    -1047
    -1048
    -1049
    -1050
    -1051
    -1052
    -1053
    -1054
    -1055
    -1056
    -1057
    +              
    1057
     1058
     1059
     1060
    @@ -2724,76 +2770,89 @@ missing side-specific tick price are skipped.

    1110 1111 1112 -1113
    def calculate_volume_by_margin(
    -    client: Mt5TradingClient,
    -    symbol: str,
    -    available_margin: float,
    -    order_side: OrderSide,
    -) -> float:
    -    """Calculate max normalized volume affordable for one side.
    -
    -    Returns:
    -        Largest stepped volume whose actual margin (from ``order_calc_margin``)
    -        fits within ``available_margin``, rounded down to symbol volume
    -        constraints; ``0.0`` when no affordable step exists.
    -
    -    Raises:
    -        Mt5TradingError: If symbol volume constraints or tick data are invalid.
    -    """
    -    if available_margin <= 0:
    -        return 0.0
    -    symbol_info = get_symbol_snapshot(client, symbol)
    -    volume_min = float(symbol_info.get("volume_min") or 0.0)
    -    volume_max = float(symbol_info.get("volume_max") or 0.0)
    -    volume_step = float(symbol_info.get("volume_step") or volume_min or 0.0)
    -    if volume_min <= 0 or volume_step <= 0:
    -        msg = f"Invalid volume constraints for {symbol!r}."
    -        raise Mt5TradingError(msg)
    -    side = _normalize_order_side(order_side)
    -    price = extract_tick_price(
    -        get_tick_snapshot(client, symbol), "ask" if side == "BUY" else "bid"
    -    )
    -    if price is None:
    -        msg = f"Tick price is unavailable for {symbol!r}."
    -        raise Mt5TradingError(msg)
    -    order_type = (
    -        client.mt5.ORDER_TYPE_BUY if side == "BUY" else client.mt5.ORDER_TYPE_SELL
    -    )
    -    min_margin = float(client.order_calc_margin(order_type, symbol, volume_min, price))
    -    if min_margin <= 0 or min_margin > available_margin:
    -        return 0.0
    -    lo = 0
    -    hi = int(
    -        max(
    -            0,
    -            floor(
    -                (
    -                    (
    -                        min(available_margin / min_margin * volume_min, volume_max)
    -                        if volume_max > 0
    -                        else available_margin / min_margin * volume_min
    -                    )
    -                    - volume_min
    -                )
    -                / volume_step
    -                + 1e-12
    -            ),
    -        )
    -    )
    -    best = -1
    -
    -    while lo <= hi:
    -        mid = (lo + hi) // 2
    -        normalized = round(volume_min + mid * volume_step, 10)
    -        actual = float(client.order_calc_margin(order_type, symbol, normalized, price))
    -
    -        if actual > 0 and actual <= available_margin:
    -            best = mid
    -            lo = mid + 1
    -        else:
    -            hi = mid - 1
    -
    -    return round(volume_min + best * volume_step, 10) if best >= 0 else 0.0
    +1113
    +1114
    +1115
    +1116
    +1117
    +1118
    +1119
    +1120
    +1121
    +1122
    +1123
    +1124
    +1125
    +1126
    def calculate_volume_by_margin(
    +    client: Mt5TradingClient,
    +    symbol: str,
    +    available_margin: float,
    +    order_side: OrderSide,
    +) -> float:
    +    """Calculate max normalized volume affordable for one side.
    +
    +    Returns:
    +        Largest stepped volume whose actual margin (from ``order_calc_margin``)
    +        fits within ``available_margin``, rounded down to symbol volume
    +        constraints; ``0.0`` when no affordable step exists.
    +
    +    Raises:
    +        Mt5TradingError: If symbol volume constraints or tick data are invalid.
    +    """
    +    if available_margin <= 0:
    +        return 0.0
    +    symbol_info = get_symbol_snapshot(client, symbol)
    +    volume_min = float(symbol_info.get("volume_min") or 0.0)
    +    volume_max = float(symbol_info.get("volume_max") or 0.0)
    +    volume_step = float(symbol_info.get("volume_step") or volume_min or 0.0)
    +    if volume_min <= 0 or volume_step <= 0:
    +        msg = f"Invalid volume constraints for {symbol!r}."
    +        raise Mt5TradingError(msg)
    +    side = _normalize_order_side(order_side)
    +    price = extract_tick_price(
    +        get_tick_snapshot(client, symbol), "ask" if side == "BUY" else "bid"
    +    )
    +    if price is None:
    +        msg = f"Tick price is unavailable for {symbol!r}."
    +        raise Mt5TradingError(msg)
    +    order_type = (
    +        client.mt5.ORDER_TYPE_BUY if side == "BUY" else client.mt5.ORDER_TYPE_SELL
    +    )
    +    min_margin = float(client.order_calc_margin(order_type, symbol, volume_min, price))
    +    if min_margin <= 0 or min_margin > available_margin:
    +        return 0.0
    +    lo = 0
    +    hi = int(
    +        max(
    +            0,
    +            floor(
    +                (
    +                    (
    +                        min(available_margin / min_margin * volume_min, volume_max)
    +                        if volume_max > 0
    +                        else available_margin / min_margin * volume_min
    +                    )
    +                    - volume_min
    +                )
    +                / volume_step
    +                + 1e-12
    +            ),
    +        )
    +    )
    +    best = -1
    +
    +    while lo <= hi:
    +        mid = (lo + hi) // 2
    +        normalized = round(volume_min + mid * volume_step, 10)
    +        actual = float(client.order_calc_margin(order_type, symbol, normalized, price))
    +
    +        if actual > 0 and actual <= available_margin:
    +            best = mid
    +            lo = mid + 1
    +        else:
    +            hi = mid - 1
    +
    +    return round(volume_min + best * volume_step, 10) if best >= 0 else 0.0
     
    @@ -2847,20 +2906,7 @@ missing side-specific tick price are skipped.

    Source code in mt5cli/trading.py -
    1304
    -1305
    -1306
    -1307
    -1308
    -1309
    -1310
    -1311
    -1312
    -1313
    -1314
    -1315
    -1316
    -1317
    +              
    1317
     1318
     1319
     1320
    @@ -2877,37 +2923,50 @@ missing side-specific tick price are skipped.

    1331 1332 1333 -1334
    def close_open_positions(
    -    client: Mt5TradingClient,
    -    *,
    -    symbols: str | list[str] | None = None,
    -    tickets: list[int] | None = None,
    -    dry_run: bool = False,
    -) -> list[OrderExecutionResult]:
    -    """Close matching open positions.
    -
    -    Returns:
    -        Normalized execution results for matching positions.
    -    """
    -    positions = _filter_positions(
    -        get_positions_frame(client),
    -        symbols=symbols,
    -        tickets=tickets,
    -    )
    -    results: list[OrderExecutionResult] = []
    -    for row in positions.to_dict("records"):
    -        pos_type = row["type"]
    -        side: OrderSide = "SELL" if pos_type == client.mt5.POSITION_TYPE_BUY else "BUY"
    -        result = place_market_order(
    -            client,
    -            symbol=str(row["symbol"]),
    -            volume=float(row["volume"]),
    -            order_side=side,
    -            position=int(row["ticket"]),
    -            dry_run=dry_run,
    -        )
    -        results.append(result)
    -    return results
    +1334
    +1335
    +1336
    +1337
    +1338
    +1339
    +1340
    +1341
    +1342
    +1343
    +1344
    +1345
    +1346
    +1347
    def close_open_positions(
    +    client: Mt5TradingClient,
    +    *,
    +    symbols: str | list[str] | None = None,
    +    tickets: list[int] | None = None,
    +    dry_run: bool = False,
    +) -> list[OrderExecutionResult]:
    +    """Close matching open positions.
    +
    +    Returns:
    +        Normalized execution results for matching positions.
    +    """
    +    positions = _filter_positions(
    +        get_positions_frame(client),
    +        symbols=symbols,
    +        tickets=tickets,
    +    )
    +    results: list[OrderExecutionResult] = []
    +    for row in positions.to_dict("records"):
    +        pos_type = row["type"]
    +        side: OrderSide = "SELL" if pos_type == client.mt5.POSITION_TYPE_BUY else "BUY"
    +        result = place_market_order(
    +            client,
    +            symbol=str(row["symbol"]),
    +            volume=float(row["volume"]),
    +            order_side=side,
    +            position=int(row["ticket"]),
    +            dry_run=dry_run,
    +        )
    +        results.append(result)
    +    return results
     
    @@ -2941,9 +3000,7 @@ missing side-specific tick price are skipped.

    Source code in mt5cli/trading.py -
    511
    -512
    -513
    +              
    513
     514
     515
     516
    @@ -2966,32 +3023,34 @@ missing side-specific tick price are skipped.

    533 534 535 -536
    def create_trading_client(
    -    *,
    -    config: Mt5Config | None = None,
    -    login: int | str | None = None,
    -    password: str | None = None,
    -    server: str | None = None,
    -    path: str | None = None,
    -    timeout: int | None = None,
    -    retry_count: int = 0,
    -) -> Mt5TradingClient:
    -    """Return an initialized and logged-in trading client."""
    -    mt5_config = _resolve_config(
    -        config=config,
    -        login=login,
    -        password=password,
    -        server=server,
    -        path=path,
    -        timeout=timeout,
    -    )
    -    client = Mt5TradingClient(config=mt5_config, retry_count=retry_count)
    -    try:
    -        client.initialize_and_login_mt5()
    -    except Exception:
    -        client.shutdown()
    -        raise
    -    return client
    +536
    +537
    +538
    def create_trading_client(
    +    *,
    +    config: Mt5Config | None = None,
    +    login: int | str | None = None,
    +    password: str | None = None,
    +    server: str | None = None,
    +    path: str | None = None,
    +    timeout: int | None = None,
    +    retry_count: int = 0,
    +) -> Mt5TradingClient:
    +    """Return an initialized and logged-in trading client."""
    +    mt5_config = _resolve_config(
    +        config=config,
    +        login=login,
    +        password=password,
    +        server=server,
    +        path=path,
    +        timeout=timeout,
    +    )
    +    client = Mt5TradingClient(config=mt5_config, retry_count=retry_count)
    +    try:
    +        client.initialize_and_login_mt5()
    +    except Exception:
    +        client.shutdown()
    +        raise
    +    return client
     
    @@ -3128,9 +3187,7 @@ missing side-specific tick price are skipped.

    Source code in mt5cli/trading.py -
    539
    -540
    -541
    +              
    541
     542
     543
     544
    @@ -3155,34 +3212,36 @@ missing side-specific tick price are skipped.

    563 564 565 -566
    def detect_position_side(
    -    client: Mt5TradingClient,
    -    symbol: str,
    -) -> PositionSide | None:
    -    """Detect the net open position side for a symbol.
    -
    -    Args:
    -        client: Connected ``Mt5TradingClient`` instance.
    -        symbol: Symbol to inspect.
    -
    -    Returns:
    -        ``"long"`` when there are buy positions and no sell positions,
    -        ``"short"`` when there are sell positions and no buy positions, or
    -        ``None`` when no positions or mixed exposure exists.
    -    """
    -    positions = get_positions_frame(client, symbol=symbol)
    -    if positions.empty:
    -        return None
    -
    -    buy_type = client.mt5.POSITION_TYPE_BUY
    -    sell_type = client.mt5.POSITION_TYPE_SELL
    -    buy_volume = _sum_position_volume(positions, buy_type)
    -    sell_volume = _sum_position_volume(positions, sell_type)
    -    if buy_volume > 0 and sell_volume == 0:
    -        return "long"
    -    if sell_volume > 0 and buy_volume == 0:
    -        return "short"
    -    return None
    +566
    +567
    +568
    def detect_position_side(
    +    client: Mt5TradingClient,
    +    symbol: str,
    +) -> PositionSide | None:
    +    """Detect the net open position side for a symbol.
    +
    +    Args:
    +        client: Connected ``Mt5TradingClient`` instance.
    +        symbol: Symbol to inspect.
    +
    +    Returns:
    +        ``"long"`` when there are buy positions and no sell positions,
    +        ``"short"`` when there are sell positions and no buy positions, or
    +        ``None`` when no positions or mixed exposure exists.
    +    """
    +    positions = get_positions_frame(client, symbol=symbol)
    +    if positions.empty:
    +        return None
    +
    +    buy_type = client.mt5.POSITION_TYPE_BUY
    +    sell_type = client.mt5.POSITION_TYPE_SELL
    +    buy_volume = _sum_position_volume(positions, buy_type)
    +    sell_volume = _sum_position_volume(positions, sell_type)
    +    if buy_volume > 0 and sell_volume == 0:
    +        return "long"
    +    if sell_volume > 0 and buy_volume == 0:
    +        return "short"
    +    return None
     
    @@ -3378,20 +3437,7 @@ prices violate available trade_stops_level pre-validation.

    Source code in mt5cli/trading.py -
    1116
    -1117
    -1118
    -1119
    -1120
    -1121
    -1122
    -1123
    -1124
    -1125
    -1126
    -1127
    -1128
    -1129
    +              
    1129
     1130
     1131
     1132
    @@ -3455,84 +3501,97 @@ prices violate available trade_stops_level pre-validation.

    1190 1191 1192 -1193
    def determine_order_limits(
    -    client: Mt5TradingClient,
    -    symbol: str,
    -    side: PositionSide | str,
    -    stop_loss_limit_ratio: float | None = None,
    -    take_profit_limit_ratio: float | None = None,
    -) -> OrderLimits:
    -    """Derive entry and protective order prices from current market quotes.
    -
    -    Args:
    -        client: Connected ``Mt5TradingClient`` instance.
    -        symbol: Symbol used for the quote lookup.
    -        side: Position side as ``"long"``/``"short"`` (``"buy"``/``"sell"``
    -            aliases are accepted).
    -        stop_loss_limit_ratio: Relative distance from entry for stop loss in
    -            ``[0, 1)``. A value of ``0`` omits the stop loss.
    -        take_profit_limit_ratio: Relative distance from entry for take profit in
    -            ``[0, 1)``. A value of ``0`` omits the take profit.
    -
    -    Returns:
    -        Dictionary with ``entry``, ``stop_loss``, and ``take_profit`` keys.
    -        Omitted protective levels are returned as ``None``.
    -
    -    Raises:
    -        Mt5TradingError: If required tick data is invalid or computed SL/TP
    -            prices violate available ``trade_stops_level`` pre-validation.
    -    """
    -    stop_loss_ratio = stop_loss_limit_ratio or 0.0
    -    take_profit_ratio = take_profit_limit_ratio or 0.0
    -    _require_protective_ratio(stop_loss_ratio, "stop_loss_limit_ratio")
    -    _require_protective_ratio(take_profit_ratio, "take_profit_limit_ratio")
    -    normalized_side = _position_side_from_order_side(side)
    -    tick = get_tick_snapshot(client, symbol)
    -    entry_key = "ask" if normalized_side == "long" else "bid"
    -    entry = extract_tick_price(tick, entry_key)
    -    if entry is None:
    -        msg = f"Tick price is unavailable for {symbol!r}."
    -        raise Mt5TradingError(msg)
    -    try:
    -        symbol_info = get_symbol_snapshot(client, symbol)
    -    except (AttributeError, KeyError, TypeError, ValueError):
    -        symbol_info = {}
    -    try:
    -        digits = int(symbol_info.get("digits") or 8)
    -    except (TypeError, ValueError):
    -        digits = 8
    -    min_distance = _minimum_stop_distance(symbol_info)
    -
    -    stop_loss: float | None = None
    -    if stop_loss_ratio > 0:
    -        if normalized_side == "long":
    -            stop_loss = entry * (1.0 - stop_loss_ratio)
    -        else:
    -            stop_loss = entry * (1.0 + stop_loss_ratio)
    -        stop_loss = round(stop_loss, digits)
    -
    -    take_profit: float | None = None
    -    if take_profit_ratio > 0:
    -        if normalized_side == "long":
    -            take_profit = entry * (1.0 + take_profit_ratio)
    -        else:
    -            take_profit = entry * (1.0 - take_profit_ratio)
    -        take_profit = round(take_profit, digits)
    -
    -    _validate_protective_prices(
    -        symbol=symbol,
    -        side=normalized_side,
    -        entry=entry,
    -        stop_loss=stop_loss,
    -        take_profit=take_profit,
    -        min_distance=min_distance,
    -    )
    -
    -    return {
    -        "entry": entry,
    -        "stop_loss": stop_loss,
    -        "take_profit": take_profit,
    -    }
    +1193
    +1194
    +1195
    +1196
    +1197
    +1198
    +1199
    +1200
    +1201
    +1202
    +1203
    +1204
    +1205
    +1206
    def determine_order_limits(
    +    client: Mt5TradingClient,
    +    symbol: str,
    +    side: PositionSide | str,
    +    stop_loss_limit_ratio: float | None = None,
    +    take_profit_limit_ratio: float | None = None,
    +) -> OrderLimits:
    +    """Derive entry and protective order prices from current market quotes.
    +
    +    Args:
    +        client: Connected ``Mt5TradingClient`` instance.
    +        symbol: Symbol used for the quote lookup.
    +        side: Position side as ``"long"``/``"short"`` (``"buy"``/``"sell"``
    +            aliases are accepted).
    +        stop_loss_limit_ratio: Relative distance from entry for stop loss in
    +            ``[0, 1)``. A value of ``0`` omits the stop loss.
    +        take_profit_limit_ratio: Relative distance from entry for take profit in
    +            ``[0, 1)``. A value of ``0`` omits the take profit.
    +
    +    Returns:
    +        Dictionary with ``entry``, ``stop_loss``, and ``take_profit`` keys.
    +        Omitted protective levels are returned as ``None``.
    +
    +    Raises:
    +        Mt5TradingError: If required tick data is invalid or computed SL/TP
    +            prices violate available ``trade_stops_level`` pre-validation.
    +    """
    +    stop_loss_ratio = stop_loss_limit_ratio or 0.0
    +    take_profit_ratio = take_profit_limit_ratio or 0.0
    +    _require_protective_ratio(stop_loss_ratio, "stop_loss_limit_ratio")
    +    _require_protective_ratio(take_profit_ratio, "take_profit_limit_ratio")
    +    normalized_side = _position_side_from_order_side(side)
    +    tick = get_tick_snapshot(client, symbol)
    +    entry_key = "ask" if normalized_side == "long" else "bid"
    +    entry = extract_tick_price(tick, entry_key)
    +    if entry is None:
    +        msg = f"Tick price is unavailable for {symbol!r}."
    +        raise Mt5TradingError(msg)
    +    try:
    +        symbol_info = get_symbol_snapshot(client, symbol)
    +    except (AttributeError, KeyError, TypeError, ValueError):
    +        symbol_info = {}
    +    try:
    +        digits = int(symbol_info.get("digits") or 8)
    +    except (TypeError, ValueError):
    +        digits = 8
    +    min_distance = _minimum_stop_distance(symbol_info)
    +
    +    stop_loss: float | None = None
    +    if stop_loss_ratio > 0:
    +        if normalized_side == "long":
    +            stop_loss = entry * (1.0 - stop_loss_ratio)
    +        else:
    +            stop_loss = entry * (1.0 + stop_loss_ratio)
    +        stop_loss = round(stop_loss, digits)
    +
    +    take_profit: float | None = None
    +    if take_profit_ratio > 0:
    +        if normalized_side == "long":
    +            take_profit = entry * (1.0 + take_profit_ratio)
    +        else:
    +            take_profit = entry * (1.0 - take_profit_ratio)
    +        take_profit = round(take_profit, digits)
    +
    +    _validate_protective_prices(
    +        symbol=symbol,
    +        side=normalized_side,
    +        entry=entry,
    +        stop_loss=stop_loss,
    +        take_profit=take_profit,
    +        min_distance=min_distance,
    +    )
    +
    +    return {
    +        "entry": entry,
    +        "stop_loss": stop_loss,
    +        "take_profit": take_profit,
    +    }
     
    @@ -3630,9 +3689,7 @@ prices violate available trade_stops_level pre-validation.

    Source code in mt5cli/trading.py -
    221
    -222
    -223
    +              
    223
     224
     225
     226
    @@ -3653,30 +3710,32 @@ prices violate available trade_stops_level pre-validation.

    241 242 243 -244
    def ensure_symbol_selected(client: Mt5TradingClient, symbol: str) -> None:
    -    """Ensure a symbol is visible in Market Watch before sending orders.
    -
    -    Args:
    -        client: Connected ``Mt5TradingClient`` instance.
    -        symbol: Symbol to select.
    -
    -    Raises:
    -        Mt5TradingError: If the symbol cannot be selected in Market Watch or
    -            ``symbol_select`` is unavailable on the client.
    -    """
    -    snapshot = get_symbol_snapshot(client, symbol)
    -    if snapshot.get("visible"):
    -        return
    -    select = getattr(client, "symbol_select", None)
    -    if not callable(select):
    -        msg = "MT5 client is missing required method: symbol_select"
    -        raise Mt5TradingError(msg)
    -    if select(symbol, enable=True):
    -        return
    -    last_error = getattr(client, "last_error", None)
    -    detail = f" ({last_error()})" if callable(last_error) else ""
    -    msg = f"Failed to select symbol {symbol!r} in Market Watch{detail}."
    -    raise Mt5TradingError(msg)
    +244
    +245
    +246
    def ensure_symbol_selected(client: Mt5TradingClient, symbol: str) -> None:
    +    """Ensure a symbol is visible in Market Watch before sending orders.
    +
    +    Args:
    +        client: Connected ``Mt5TradingClient`` instance.
    +        symbol: Symbol to select.
    +
    +    Raises:
    +        Mt5TradingError: If the symbol cannot be selected in Market Watch or
    +            ``symbol_select`` is unavailable on the client.
    +    """
    +    snapshot = get_symbol_snapshot(client, symbol)
    +    if snapshot.get("visible"):
    +        return
    +    select = getattr(client, "symbol_select", None)
    +    if not callable(select):
    +        msg = "MT5 client is missing required method: symbol_select"
    +        raise Mt5TradingError(msg)
    +    if select(symbol, enable=True):
    +        return
    +    last_error = getattr(client, "last_error", None)
    +    detail = f" ({last_error()})" if callable(last_error) else ""
    +    msg = f"Failed to select symbol {symbol!r} in Market Watch{detail}."
    +    raise Mt5TradingError(msg)
     
    @@ -3757,9 +3816,7 @@ prices violate available trade_stops_level pre-validation.

    Source code in mt5cli/trading.py -
    640
    -641
    -642
    +              
    642
     643
     644
     645
    @@ -3792,42 +3849,44 @@ prices violate available trade_stops_level pre-validation.

    672 673 674 -675
    def estimate_order_margin(
    -    client: Mt5TradingClient,
    -    symbol: str,
    -    order_side: OrderSide | str,
    -    volume: float,
    -) -> float:
    -    """Estimate required margin for one order at the current market price.
    -
    -    Returns:
    -        Positive finite margin required for the order at the current quote.
    -
    -    Raises:
    -        Mt5TradingError: If volume, tick data, or margin estimation is invalid.
    -    """
    -    if not _is_positive_finite_number(volume):
    -        msg = "Volume must be a positive finite number to estimate order margin."
    -        raise Mt5TradingError(msg)
    -    side = _normalize_order_side(order_side)
    -    tick = get_tick_snapshot(client, symbol)
    -    price = extract_tick_price(tick, "ask" if side == "BUY" else "bid")
    -    if price is None:
    -        msg = f"Tick price is unavailable for {symbol!r}."
    -        raise Mt5TradingError(msg)
    -    order_type = (
    -        client.mt5.ORDER_TYPE_BUY if side == "BUY" else client.mt5.ORDER_TYPE_SELL
    -    )
    -    raw_margin = client.order_calc_margin(order_type, symbol, volume, price)
    -    try:
    -        margin = float(raw_margin)
    -    except (TypeError, ValueError) as exc:
    -        msg = f"Margin estimate is invalid for {symbol!r}."
    -        raise Mt5TradingError(msg) from exc
    -    if margin <= 0 or not isfinite(margin):
    -        msg = f"Margin estimate is invalid for {symbol!r}."
    -        raise Mt5TradingError(msg)
    -    return margin
    +675
    +676
    +677
    def estimate_order_margin(
    +    client: Mt5TradingClient,
    +    symbol: str,
    +    order_side: OrderSide | str,
    +    volume: float,
    +) -> float:
    +    """Estimate required margin for one order at the current market price.
    +
    +    Returns:
    +        Positive finite margin required for the order at the current quote.
    +
    +    Raises:
    +        Mt5TradingError: If volume, tick data, or margin estimation is invalid.
    +    """
    +    if not _is_positive_finite_number(volume):
    +        msg = "Volume must be a positive finite number to estimate order margin."
    +        raise Mt5TradingError(msg)
    +    side = _normalize_order_side(order_side)
    +    tick = get_tick_snapshot(client, symbol)
    +    price = extract_tick_price(tick, "ask" if side == "BUY" else "bid")
    +    if price is None:
    +        msg = f"Tick price is unavailable for {symbol!r}."
    +        raise Mt5TradingError(msg)
    +    order_type = (
    +        client.mt5.ORDER_TYPE_BUY if side == "BUY" else client.mt5.ORDER_TYPE_SELL
    +    )
    +    raw_margin = client.order_calc_margin(order_type, symbol, volume, price)
    +    try:
    +        margin = float(raw_margin)
    +    except (TypeError, ValueError) as exc:
    +        msg = f"Margin estimate is invalid for {symbol!r}."
    +        raise Mt5TradingError(msg) from exc
    +    if margin <= 0 or not isfinite(margin):
    +        msg = f"Margin estimate is invalid for {symbol!r}."
    +        raise Mt5TradingError(msg)
    +    return margin
     
    @@ -3857,9 +3916,7 @@ Booleans are treated as non-numeric and return None.

    Source code in mt5cli/trading.py -
    436
    -437
    -438
    +              
    438
     439
     440
     441
    @@ -3878,28 +3935,30 @@ Booleans are treated as non-numeric and return None.

    454 455 456 -457
    def extract_tick_price(tick: Mapping[str, object], key: str) -> float | None:
    -    """Return a positive finite float from tick[key], or None if invalid.
    -
    -    Accepts int, float, or numeric string values. Returns None when the key is
    -    missing, the value is None, non-numeric, NaN, infinite, zero, or negative.
    -    Booleans are treated as non-numeric and return None.
    -    """
    -    value = tick.get(key)
    -    if value is None or isinstance(value, bool):
    -        return None
    -    if isinstance(value, int | float):
    -        price = float(value)
    -    elif isinstance(value, str):
    -        try:
    -            price = float(value)
    -        except ValueError:
    -            return None
    -    else:
    -        return None
    -    if not isfinite(price) or price <= 0:
    +457
    +458
    +459
    def extract_tick_price(tick: Mapping[str, object], key: str) -> float | None:
    +    """Return a positive finite float from tick[key], or None if invalid.
    +
    +    Accepts int, float, or numeric string values. Returns None when the key is
    +    missing, the value is None, non-numeric, NaN, infinite, zero, or negative.
    +    Booleans are treated as non-numeric and return None.
    +    """
    +    value = tick.get(key)
    +    if value is None or isinstance(value, bool):
    +        return None
    +    if isinstance(value, int | float):
    +        price = float(value)
    +    elif isinstance(value, str):
    +        try:
    +            price = float(value)
    +        except ValueError:
    +            return None
    +    else:
             return None
    -    return price
    +    if not isfinite(price) or price <= 0:
    +        return None
    +    return price
     
    @@ -3987,20 +4046,7 @@ malformed, or the time column is missing.

    Source code in mt5cli/trading.py -
    1520
    -1521
    -1522
    -1523
    -1524
    -1525
    -1526
    -1527
    -1528
    -1529
    -1530
    -1531
    -1532
    -1533
    +              
    1533
     1534
     1535
     1536
    @@ -4030,50 +4076,63 @@ malformed, or the time column is missing.

    1560 1561 1562 -1563
    def fetch_latest_closed_rates_for_trading_client(
    -    client: Mt5TradingClient,
    -    *,
    -    symbol: str,
    -    granularity: str,
    -    count: int,
    -) -> pd.DataFrame:
    -    """Fetch the latest closed bars from a connected trading client.
    -
    -    Returns:
    -        Up to ``count`` closed bars ordered oldest to newest.
    -
    -    Raises:
    -        ValueError: If ``count`` is not positive, rate data is empty or
    -            malformed, or the ``time`` column is missing.
    -        Mt5TradingError: If the trading client cannot fetch rate data.
    -    """
    -    if count <= 0:
    -        msg = "count must be positive."
    -        raise ValueError(msg)
    -    fetch_method = getattr(client, "fetch_latest_rates_as_df", None)
    -    if not callable(fetch_method):
    -        msg = "MT5 trading client cannot fetch rate data."
    -        raise Mt5TradingError(msg)
    -    fetched = fetch_method(symbol, granularity, count + 1)
    -    if not isinstance(fetched, pd.DataFrame):
    -        msg = (
    -            f"Malformed rate data for {symbol!r} at granularity {granularity!r}: "
    -            "expected a DataFrame."
    -        )
    -        raise ValueError(msg)  # noqa: TRY004
    -    frame = fetched
    -    frame = _ensure_rate_time_column(frame)
    -    if "time" not in frame.columns:
    -        msg = f"Rate data is missing a time column for {symbol!r}."
    -        raise ValueError(msg)
    -    closed = drop_forming_rate_bar(frame)
    -    if closed.empty:
    -        msg = (
    -            f"Rate data is empty for {symbol!r} at granularity {granularity!r} "
    -            f"with count {count}."
    -        )
    -        raise ValueError(msg)
    -    return closed.tail(count).reset_index(drop=True)
    +1563
    +1564
    +1565
    +1566
    +1567
    +1568
    +1569
    +1570
    +1571
    +1572
    +1573
    +1574
    +1575
    +1576
    def fetch_latest_closed_rates_for_trading_client(
    +    client: Mt5TradingClient,
    +    *,
    +    symbol: str,
    +    granularity: str,
    +    count: int,
    +) -> pd.DataFrame:
    +    """Fetch the latest closed bars from a connected trading client.
    +
    +    Returns:
    +        Up to ``count`` closed bars ordered oldest to newest.
    +
    +    Raises:
    +        ValueError: If ``count`` is not positive, rate data is empty or
    +            malformed, or the ``time`` column is missing.
    +        Mt5TradingError: If the trading client cannot fetch rate data.
    +    """
    +    if count <= 0:
    +        msg = "count must be positive."
    +        raise ValueError(msg)
    +    fetch_method = getattr(client, "fetch_latest_rates_as_df", None)
    +    if not callable(fetch_method):
    +        msg = "MT5 trading client cannot fetch rate data."
    +        raise Mt5TradingError(msg)
    +    fetched = fetch_method(symbol, granularity, count + 1)
    +    if not isinstance(fetched, pd.DataFrame):
    +        msg = (
    +            f"Malformed rate data for {symbol!r} at granularity {granularity!r}: "
    +            "expected a DataFrame."
    +        )
    +        raise ValueError(msg)  # noqa: TRY004
    +    frame = fetched
    +    frame = _ensure_rate_time_column(frame)
    +    if "time" not in frame.columns:
    +        msg = f"Rate data is missing a time column for {symbol!r}."
    +        raise ValueError(msg)
    +    closed = drop_forming_rate_bar(frame)
    +    if closed.empty:
    +        msg = (
    +            f"Rate data is empty for {symbol!r} at granularity {granularity!r} "
    +            f"with count {count}."
    +        )
    +        raise ValueError(msg)
    +    return closed.tail(count).reset_index(drop=True)
     
    @@ -4256,20 +4315,7 @@ is invalid or unparseable.

    Source code in mt5cli/trading.py -
    1605
    -1606
    -1607
    -1608
    -1609
    -1610
    -1611
    -1612
    -1613
    -1614
    -1615
    -1616
    -1617
    -1618
    +              
    1618
     1619
     1620
     1621
    @@ -4300,51 +4346,64 @@ is invalid or unparseable.

    1646 1647 1648 -1649
    def fetch_latest_closed_rates_indexed(
    -    client: Mt5TradingClient,
    -    *,
    -    symbol: str,
    -    granularity: str,
    -    count: int,
    -) -> pd.DataFrame:
    -    """Fetch the latest closed bars with a UTC DatetimeIndex from a trading client.
    -
    -    Internally reuses :func:`fetch_latest_closed_rates_for_trading_client` for
    -    closed-bar detection and validation, then converts the ``time`` column to a
    -    UTC-aware :class:`~pandas.DatetimeIndex` named ``"time"`` and drops the
    -    original column. Intended for downstream time-series consumers that require
    -    a datetime index rather than a ``time`` column.
    -
    -    Args:
    -        client: Connected trading client with rate-fetch capability.
    -        symbol: Symbol name.
    -        granularity: Timeframe string (for example ``"M1"``, ``"H1"``).
    -        count: Maximum number of closed bars to return.
    -
    -    Returns:
    -        Up to ``count`` closed bars ordered oldest to newest, with a
    -        UTC-aware ``DatetimeIndex`` named ``"time"``. The original ``time``
    -        column is dropped.
    -
    -    Raises:
    -        ValueError: If ``count`` is not positive, rate data is empty or
    -            malformed, the ``time`` column is missing, or timestamp data
    -            is invalid or unparseable.
    -    """
    -    frame = fetch_latest_closed_rates_for_trading_client(
    -        client,
    -        symbol=symbol,
    -        granularity=granularity,
    -        count=count,
    -    )
    -    if "time" not in frame.columns:
    -        msg = f"Rate data is missing a time column for {symbol!r}."
    -        raise ValueError(msg)
    -    idx = _rate_time_to_utc(frame["time"], symbol)
    -    idx.name = "time"
    -    result = frame.drop(columns=["time"])
    -    result.index = idx
    -    return result
    +1649
    +1650
    +1651
    +1652
    +1653
    +1654
    +1655
    +1656
    +1657
    +1658
    +1659
    +1660
    +1661
    +1662
    def fetch_latest_closed_rates_indexed(
    +    client: Mt5TradingClient,
    +    *,
    +    symbol: str,
    +    granularity: str,
    +    count: int,
    +) -> pd.DataFrame:
    +    """Fetch the latest closed bars with a UTC DatetimeIndex from a trading client.
    +
    +    Internally reuses :func:`fetch_latest_closed_rates_for_trading_client` for
    +    closed-bar detection and validation, then converts the ``time`` column to a
    +    UTC-aware :class:`~pandas.DatetimeIndex` named ``"time"`` and drops the
    +    original column. Intended for downstream time-series consumers that require
    +    a datetime index rather than a ``time`` column.
    +
    +    Args:
    +        client: Connected trading client with rate-fetch capability.
    +        symbol: Symbol name.
    +        granularity: Timeframe string (for example ``"M1"``, ``"H1"``).
    +        count: Maximum number of closed bars to return.
    +
    +    Returns:
    +        Up to ``count`` closed bars ordered oldest to newest, with a
    +        UTC-aware ``DatetimeIndex`` named ``"time"``. The original ``time``
    +        column is dropped.
    +
    +    Raises:
    +        ValueError: If ``count`` is not positive, rate data is empty or
    +            malformed, the ``time`` column is missing, or timestamp data
    +            is invalid or unparseable.
    +    """
    +    frame = fetch_latest_closed_rates_for_trading_client(
    +        client,
    +        symbol=symbol,
    +        granularity=granularity,
    +        count=count,
    +    )
    +    if "time" not in frame.columns:
    +        msg = f"Rate data is missing a time column for {symbol!r}."
    +        raise ValueError(msg)
    +    idx = _rate_time_to_utc(frame["time"], symbol)
    +    idx.name = "time"
    +    result = frame.drop(columns=["time"])
    +    result.index = idx
    +    return result
     
    @@ -4371,23 +4430,23 @@ is invalid or unparseable.

    Source code in mt5cli/trading.py -
    569
    -570
    -571
    +              
    def get_account_snapshot(
    -    client: Mt5TradingClient,
    -) -> dict[str, float | int | str | None]:
    -    """Return normalized account state with stable keys."""
    -    value = _call_snapshot_method(client, "account_info_as_dict", "account_info")
    -    return cast(
    -        "dict[str, float | int | str | None]",
    -        _snapshot_from_value(value, _ACCOUNT_SNAPSHOT_FIELDS),
    -    )
    +577
    +578
    +579
    def get_account_snapshot(
    +    client: Mt5TradingClient,
    +) -> dict[str, float | int | str | None]:
    +    """Return normalized account state with stable keys."""
    +    value = _call_snapshot_method(client, "account_info_as_dict", "account_info")
    +    return cast(
    +        "dict[str, float | int | str | None]",
    +        _snapshot_from_value(value, _ACCOUNT_SNAPSHOT_FIELDS),
    +    )
     
    @@ -4414,25 +4473,25 @@ is invalid or unparseable.

    Source code in mt5cli/trading.py -
    606
    -607
    -608
    +              
    def get_positions_frame(
    -    client: Mt5TradingClient,
    -    symbol: str | None = None,
    -) -> pd.DataFrame:
    -    """Return open positions as a DataFrame with stable baseline columns."""
    -    frame = client.positions_get_as_df(symbol=symbol)
    -    for column in POSITION_COLUMNS:
    -        if column not in frame.columns:
    -            frame[column] = pd.Series(dtype="object")
    -    return frame
    +615
    +616
    +617
    def get_positions_frame(
    +    client: Mt5TradingClient,
    +    symbol: str | None = None,
    +) -> pd.DataFrame:
    +    """Return open positions as a DataFrame with stable baseline columns."""
    +    frame = client.positions_get_as_df(symbol=symbol)
    +    for column in POSITION_COLUMNS:
    +        if column not in frame.columns:
    +            frame[column] = pd.Series(dtype="object")
    +    return frame
     
    @@ -4459,25 +4518,25 @@ is invalid or unparseable.

    Source code in mt5cli/trading.py -
    580
    -581
    -582
    +              
    def get_symbol_snapshot(
    -    client: Mt5TradingClient,
    -    symbol: str,
    -) -> dict[str, float | int | str | bool | None]:
    -    """Return normalized symbol metadata required for trading decisions."""
    -    method = getattr(client, "symbol_info_as_dict", None)
    -    value = method(symbol=symbol) if callable(method) else client.symbol_info(symbol)
    -    snapshot = _snapshot_from_value(value, _SYMBOL_SNAPSHOT_FIELDS)
    -    snapshot["symbol"] = snapshot.get("symbol") or symbol
    -    return cast("dict[str, float | int | str | bool | None]", snapshot)
    +589
    +590
    +591
    def get_symbol_snapshot(
    +    client: Mt5TradingClient,
    +    symbol: str,
    +) -> dict[str, float | int | str | bool | None]:
    +    """Return normalized symbol metadata required for trading decisions."""
    +    method = getattr(client, "symbol_info_as_dict", None)
    +    value = method(symbol=symbol) if callable(method) else client.symbol_info(symbol)
    +    snapshot = _snapshot_from_value(value, _SYMBOL_SNAPSHOT_FIELDS)
    +    snapshot["symbol"] = snapshot.get("symbol") or symbol
    +    return cast("dict[str, float | int | str | bool | None]", snapshot)
     
    @@ -4504,9 +4563,7 @@ is invalid or unparseable.

    Source code in mt5cli/trading.py -
    592
    -593
    -594
    +              
    594
     595
     596
     597
    @@ -4515,18 +4572,20 @@ is invalid or unparseable.

    600 601 602 -603
    def get_tick_snapshot(
    -    client: Mt5TradingClient,
    -    symbol: str,
    -) -> dict[str, float | int | None]:
    -    """Return normalized latest tick data, including bid, ask, and timestamp."""
    -    method = getattr(client, "symbol_info_tick_as_dict", None)
    -    value = (
    -        method(symbol=symbol) if callable(method) else client.symbol_info_tick(symbol)
    -    )
    -    snapshot = _snapshot_from_value(value, _TICK_SNAPSHOT_FIELDS)
    -    snapshot["symbol"] = snapshot.get("symbol") or symbol
    -    return cast("dict[str, float | int | None]", snapshot)
    +603
    +604
    +605
    def get_tick_snapshot(
    +    client: Mt5TradingClient,
    +    symbol: str,
    +) -> dict[str, float | int | None]:
    +    """Return normalized latest tick data, including bid, ask, and timestamp."""
    +    method = getattr(client, "symbol_info_tick_as_dict", None)
    +    value = (
    +        method(symbol=symbol) if callable(method) else client.symbol_info_tick(symbol)
    +    )
    +    snapshot = _snapshot_from_value(value, _TICK_SNAPSHOT_FIELDS)
    +    snapshot["symbol"] = snapshot.get("symbol") or symbol
    +    return cast("dict[str, float | int | None]", snapshot)
     
    @@ -4716,20 +4775,7 @@ attaches to a running terminal.

    Source code in mt5cli/trading.py -
    1652
    -1653
    -1654
    -1655
    -1656
    -1657
    -1658
    -1659
    -1660
    -1661
    -1662
    -1663
    -1664
    -1665
    +              
    1665
     1666
     1667
     1668
    @@ -4760,51 +4806,64 @@ attaches to a running terminal.

    1693 1694 1695 -1696
    @contextmanager
    -def mt5_trading_session(
    -    config: Mt5Config | None = None,
    -    *,
    -    login: int | str | None = None,
    -    password: str | None = None,
    -    server: str | None = None,
    -    path: str | None = None,
    -    timeout: int | None = None,
    -    retry_count: int = 0,
    -) -> Iterator[Mt5TradingClient]:
    -    """Open a trading-capable MT5 session and always shut down safely.
    -
    -    Launches the MetaTrader 5 terminal using ``Mt5Config.path`` when set,
    -    initializes and logs in via ``initialize_and_login_mt5()``, yields a
    -    connected :class:`~pdmt5.Mt5TradingClient`, and calls ``shutdown()`` on
    -    exit even when an error is raised inside the context.
    -
    -    Args:
    -        config: MT5 connection configuration. Defaults to an empty config that
    -            attaches to a running terminal.
    -        login: Optional trading account login.
    -        password: Optional trading account password.
    -        server: Optional trading server name.
    -        path: Optional terminal executable path.
    -        timeout: Optional connection timeout in milliseconds.
    -        retry_count: Number of initialization retries passed to
    -            ``Mt5TradingClient``.
    -
    -    Yields:
    -        Connected ``Mt5TradingClient`` bound to the session.
    -    """
    -    client = create_trading_client(
    -        config=config,
    -        login=login,
    -        password=password,
    -        server=server,
    -        path=path,
    -        timeout=timeout,
    -        retry_count=retry_count,
    -    )
    -    try:
    -        yield client
    -    finally:
    -        client.shutdown()
    +1696
    +1697
    +1698
    +1699
    +1700
    +1701
    +1702
    +1703
    +1704
    +1705
    +1706
    +1707
    +1708
    +1709
    @contextmanager
    +def mt5_trading_session(
    +    config: Mt5Config | None = None,
    +    *,
    +    login: int | str | None = None,
    +    password: str | None = None,
    +    server: str | None = None,
    +    path: str | None = None,
    +    timeout: int | None = None,
    +    retry_count: int = 0,
    +) -> Iterator[Mt5TradingClient]:
    +    """Open a trading-capable MT5 session and always shut down safely.
    +
    +    Launches the MetaTrader 5 terminal using ``Mt5Config.path`` when set,
    +    initializes and logs in via ``initialize_and_login_mt5()``, yields a
    +    connected :class:`~pdmt5.Mt5TradingClient`, and calls ``shutdown()`` on
    +    exit even when an error is raised inside the context.
    +
    +    Args:
    +        config: MT5 connection configuration. Defaults to an empty config that
    +            attaches to a running terminal.
    +        login: Optional trading account login.
    +        password: Optional trading account password.
    +        server: Optional trading server name.
    +        path: Optional terminal executable path.
    +        timeout: Optional connection timeout in milliseconds.
    +        retry_count: Number of initialization retries passed to
    +            ``Mt5TradingClient``.
    +
    +    Yields:
    +        Connected ``Mt5TradingClient`` bound to the session.
    +    """
    +    client = create_trading_client(
    +        config=config,
    +        login=login,
    +        password=password,
    +        server=server,
    +        path=path,
    +        timeout=timeout,
    +        retry_count=retry_count,
    +    )
    +    try:
    +        yield client
    +    finally:
    +        client.shutdown()
     
    @@ -4888,9 +4947,7 @@ attaches to a running terminal.

    Source code in mt5cli/trading.py -
    306
    -307
    -308
    +              
    308
     309
     310
     311
    @@ -4917,36 +4974,38 @@ attaches to a running terminal.

    332 333 334 -335
    def normalize_order_volume(
    -    volume: float,
    -    *,
    -    volume_min: float,
    -    volume_max: float,
    -    volume_step: float,
    -) -> float:
    -    """Normalize a requested order volume to broker volume constraints.
    -
    -    Returns:
    -        Volume floored to the nearest valid broker step from ``volume_min``,
    -        capped at ``volume_max`` when finite and positive, and rounded
    -        deterministically. Returns ``0.0`` when inputs or constraints are
    -        invalid, non-finite, or the capped request is below ``volume_min``.
    -    """
    -    if not _is_finite_number(volume):
    -        return 0.0
    -    if not _is_positive_finite_number(volume_min):
    +335
    +336
    +337
    def normalize_order_volume(
    +    volume: float,
    +    *,
    +    volume_min: float,
    +    volume_max: float,
    +    volume_step: float,
    +) -> float:
    +    """Normalize a requested order volume to broker volume constraints.
    +
    +    Returns:
    +        Volume floored to the nearest valid broker step from ``volume_min``,
    +        capped at ``volume_max`` when finite and positive, and rounded
    +        deterministically. Returns ``0.0`` when inputs or constraints are
    +        invalid, non-finite, or the capped request is below ``volume_min``.
    +    """
    +    if not _is_finite_number(volume):
             return 0.0
    -    if not _is_positive_finite_number(volume_step):
    +    if not _is_positive_finite_number(volume_min):
             return 0.0
    -    has_volume_cap = _is_positive_finite_number(volume_max)
    -    capped = min(volume, volume_max) if has_volume_cap else volume
    -    if capped < volume_min:
    -        return 0.0
    -    steps = floor(((capped - volume_min) / volume_step) + 1e-12)
    -    normalized = volume_min + max(0, steps) * volume_step
    -    if has_volume_cap:
    -        normalized = min(normalized, volume_max)
    -    return round(normalized, 10)
    +    if not _is_positive_finite_number(volume_step):
    +        return 0.0
    +    has_volume_cap = _is_positive_finite_number(volume_max)
    +    capped = min(volume, volume_max) if has_volume_cap else volume
    +    if capped < volume_min:
    +        return 0.0
    +    steps = floor(((capped - volume_min) / volume_step) + 1e-12)
    +    normalized = volume_min + max(0, steps) * volume_step
    +    if has_volume_cap:
    +        normalized = min(normalized, volume_max)
    +    return round(normalized, 10)
     
    @@ -5048,20 +5107,7 @@ details for callers to inspect.

    Source code in mt5cli/trading.py -
    1196
    -1197
    -1198
    -1199
    -1200
    -1201
    -1202
    -1203
    -1204
    -1205
    -1206
    -1207
    -1208
    -1209
    +              
    1209
     1210
     1211
     1212
    @@ -5138,97 +5184,110 @@ details for callers to inspect.

    1283 1284 1285 -1286
    def place_market_order(
    -    client: Mt5TradingClient,
    -    *,
    -    symbol: str,
    -    volume: float,
    -    order_side: OrderSide,
    -    order_filling_mode: OrderFillingMode = "IOC",
    -    order_time_mode: OrderTimeMode = "GTC",
    -    sl: float | None = None,
    -    tp: float | None = None,
    -    position: int | None = None,
    -    dry_run: bool = False,
    -) -> OrderExecutionResult:
    -    """Place one normalized market order or return a dry-run result.
    -
    -    ``pdmt5.Mt5TradingClient.order_send()`` raises only when MT5 returns no
    -    response. When MT5 returns a response with a known non-success retcode, this
    -    helper returns ``status="failed"`` and keeps the normalized response
    -    details for callers to inspect.
    -
    -    Returns:
    -        Normalized execution result containing request and response details.
    -
    -    Raises:
    -        Mt5TradingError: If volume or required tick data is invalid.
    -    """
    -    if volume <= 0:
    -        msg = "volume must be positive."
    -        raise Mt5TradingError(msg)
    -    side = _normalize_order_side(order_side)
    -    if not dry_run:
    -        ensure_symbol_selected(client, symbol)
    -    tick = get_tick_snapshot(client, symbol)
    -    price = extract_tick_price(tick, "ask" if side == "BUY" else "bid")
    -    if price is None:
    -        msg = f"Tick price is unavailable for {symbol!r}."
    -        raise Mt5TradingError(msg)
    -    request = {
    -        "action": client.mt5.TRADE_ACTION_DEAL,
    -        "symbol": symbol,
    -        "volume": volume,
    -        "type": (
    -            client.mt5.ORDER_TYPE_BUY if side == "BUY" else client.mt5.ORDER_TYPE_SELL
    -        ),
    -        "price": price,
    -        "type_filling": _resolve_mt5_constant(
    -            client.mt5,
    -            "ORDER_FILLING",
    -            order_filling_mode,
    -            _ORDER_FILLING_MODES,
    -        ),
    -        "type_time": _resolve_mt5_constant(
    -            client.mt5,
    -            "ORDER_TIME",
    -            order_time_mode,
    -            _ORDER_TIME_MODES,
    +1286
    +1287
    +1288
    +1289
    +1290
    +1291
    +1292
    +1293
    +1294
    +1295
    +1296
    +1297
    +1298
    +1299
    def place_market_order(
    +    client: Mt5TradingClient,
    +    *,
    +    symbol: str,
    +    volume: float,
    +    order_side: OrderSide,
    +    order_filling_mode: OrderFillingMode = "IOC",
    +    order_time_mode: OrderTimeMode = "GTC",
    +    sl: float | None = None,
    +    tp: float | None = None,
    +    position: int | None = None,
    +    dry_run: bool = False,
    +) -> OrderExecutionResult:
    +    """Place one normalized market order or return a dry-run result.
    +
    +    ``pdmt5.Mt5TradingClient.order_send()`` raises only when MT5 returns no
    +    response. When MT5 returns a response with a known non-success retcode, this
    +    helper returns ``status="failed"`` and keeps the normalized response
    +    details for callers to inspect.
    +
    +    Returns:
    +        Normalized execution result containing request and response details.
    +
    +    Raises:
    +        Mt5TradingError: If volume or required tick data is invalid.
    +    """
    +    if volume <= 0:
    +        msg = "volume must be positive."
    +        raise Mt5TradingError(msg)
    +    side = _normalize_order_side(order_side)
    +    if not dry_run:
    +        ensure_symbol_selected(client, symbol)
    +    tick = get_tick_snapshot(client, symbol)
    +    price = extract_tick_price(tick, "ask" if side == "BUY" else "bid")
    +    if price is None:
    +        msg = f"Tick price is unavailable for {symbol!r}."
    +        raise Mt5TradingError(msg)
    +    request = {
    +        "action": client.mt5.TRADE_ACTION_DEAL,
    +        "symbol": symbol,
    +        "volume": volume,
    +        "type": (
    +            client.mt5.ORDER_TYPE_BUY if side == "BUY" else client.mt5.ORDER_TYPE_SELL
             ),
    -    }
    -    if sl is not None:
    -        request["sl"] = sl
    -    if tp is not None:
    -        request["tp"] = tp
    -    if position is not None:
    -        request["position"] = position
    -    if dry_run:
    -        return {
    -            "status": "dry_run",
    -            "symbol": symbol,
    -            "order_side": side,
    -            "volume": volume,
    -            "retcode": None,
    -            "comment": None,
    -            "request": cast("dict[str, object]", request),
    -            "response": None,
    -            "dry_run": True,
    -        }
    -    response = client.order_send(request)
    -    response_dict = _snapshot_from_value(response, ())
    -    raw_retcode = response_dict.get("retcode")
    -    retcode = _optional_int(raw_retcode)
    -    return {
    -        "status": _order_status_from_retcode(client.mt5, raw_retcode),
    -        "symbol": symbol,
    -        "order_side": side,
    -        "volume": volume,
    -        "retcode": retcode,
    -        "comment": _optional_str(response_dict.get("comment")),
    -        "request": cast("dict[str, object]", request),
    -        "response": response_dict,
    -        "dry_run": False,
    -    }
    +        "price": price,
    +        "type_filling": _resolve_mt5_constant(
    +            client.mt5,
    +            "ORDER_FILLING",
    +            order_filling_mode,
    +            _ORDER_FILLING_MODES,
    +        ),
    +        "type_time": _resolve_mt5_constant(
    +            client.mt5,
    +            "ORDER_TIME",
    +            order_time_mode,
    +            _ORDER_TIME_MODES,
    +        ),
    +    }
    +    if sl is not None:
    +        request["sl"] = sl
    +    if tp is not None:
    +        request["tp"] = tp
    +    if position is not None:
    +        request["position"] = position
    +    if dry_run:
    +        return {
    +            "status": "dry_run",
    +            "symbol": symbol,
    +            "order_side": side,
    +            "volume": volume,
    +            "retcode": None,
    +            "comment": None,
    +            "request": cast("dict[str, object]", request),
    +            "response": None,
    +            "dry_run": True,
    +        }
    +    response = client.order_send(request)
    +    response_dict = _snapshot_from_value(response, ())
    +    raw_retcode = response_dict.get("retcode")
    +    retcode = _optional_int(raw_retcode)
    +    return {
    +        "status": _order_status_from_retcode(client.mt5, raw_retcode),
    +        "symbol": symbol,
    +        "order_side": side,
    +        "volume": volume,
    +        "retcode": retcode,
    +        "comment": _optional_str(response_dict.get("comment")),
    +        "request": cast("dict[str, object]", request),
    +        "response": response_dict,
    +        "dry_run": False,
    +    }
     
    @@ -5284,20 +5343,7 @@ details for callers to inspect.

    Source code in mt5cli/trading.py -
    1456
    -1457
    -1458
    -1459
    -1460
    -1461
    -1462
    -1463
    -1464
    -1465
    -1466
    -1467
    -1468
    -1469
    +              
    1469
     1470
     1471
     1472
    @@ -5345,68 +5391,81 @@ details for callers to inspect.

    1514 1515 1516 -1517
    def update_sltp_for_open_positions(
    -    client: Mt5TradingClient,
    -    *,
    -    symbol: str | None = None,
    -    tickets: list[int] | None = None,
    -    stop_loss: float | None = None,
    -    take_profit: float | None = None,
    -    dry_run: bool = False,
    -) -> list[OrderExecutionResult]:
    -    """Update SL/TP for matching open positions.
    -
    -    Returns:
    -        Normalized execution results for matching positions.
    -    """
    -    positions = _filter_positions(
    -        get_positions_frame(client),
    -        symbols=symbol,
    -        tickets=tickets,
    -    )
    -    results: list[OrderExecutionResult] = []
    -    for row in positions.to_dict("records"):
    -        request = {
    -            "action": client.mt5.TRADE_ACTION_SLTP,
    -            "symbol": row["symbol"],
    -            "position": row["ticket"],
    -        }
    -        sl = _optional_price(row.get("sl") if stop_loss is None else stop_loss)
    -        tp = _optional_price(row.get("tp") if take_profit is None else take_profit)
    -        if sl is not None:
    -            request["sl"] = sl
    -        if tp is not None:
    -            request["tp"] = tp
    -        if dry_run:
    -            response = None
    -            status: ExecutionStatus = "dry_run"
    -        else:
    -            ensure_symbol_selected(client, str(row["symbol"]))
    -            response = _snapshot_from_value(client.order_send(request), ())
    -            status = _order_status_from_retcode(
    -                client.mt5,
    -                response.get("retcode"),
    -            )
    -        results.append(
    -            {
    -                "status": status,
    -                "symbol": str(row["symbol"]),
    -                "order_side": "BUY"
    -                if row["type"] == client.mt5.POSITION_TYPE_BUY
    -                else "SELL",
    -                "volume": float(row["volume"]),
    -                "retcode": None
    -                if response is None
    -                else _optional_int(response.get("retcode")),
    -                "comment": None
    -                if response is None
    -                else _optional_str(response.get("comment")),
    -                "request": cast("dict[str, object]", request),
    -                "response": response,
    -                "dry_run": dry_run,
    -            },
    -        )
    -    return results
    +1517
    +1518
    +1519
    +1520
    +1521
    +1522
    +1523
    +1524
    +1525
    +1526
    +1527
    +1528
    +1529
    +1530
    def update_sltp_for_open_positions(
    +    client: Mt5TradingClient,
    +    *,
    +    symbol: str | None = None,
    +    tickets: list[int] | None = None,
    +    stop_loss: float | None = None,
    +    take_profit: float | None = None,
    +    dry_run: bool = False,
    +) -> list[OrderExecutionResult]:
    +    """Update SL/TP for matching open positions.
    +
    +    Returns:
    +        Normalized execution results for matching positions.
    +    """
    +    positions = _filter_positions(
    +        get_positions_frame(client),
    +        symbols=symbol,
    +        tickets=tickets,
    +    )
    +    results: list[OrderExecutionResult] = []
    +    for row in positions.to_dict("records"):
    +        request = {
    +            "action": client.mt5.TRADE_ACTION_SLTP,
    +            "symbol": row["symbol"],
    +            "position": row["ticket"],
    +        }
    +        sl = _optional_price(row.get("sl") if stop_loss is None else stop_loss)
    +        tp = _optional_price(row.get("tp") if take_profit is None else take_profit)
    +        if sl is not None:
    +            request["sl"] = sl
    +        if tp is not None:
    +            request["tp"] = tp
    +        if dry_run:
    +            response = None
    +            status: ExecutionStatus = "dry_run"
    +        else:
    +            ensure_symbol_selected(client, str(row["symbol"]))
    +            response = _snapshot_from_value(client.order_send(request), ())
    +            status = _order_status_from_retcode(
    +                client.mt5,
    +                response.get("retcode"),
    +            )
    +        results.append(
    +            {
    +                "status": status,
    +                "symbol": str(row["symbol"]),
    +                "order_side": "BUY"
    +                if row["type"] == client.mt5.POSITION_TYPE_BUY
    +                else "SELL",
    +                "volume": float(row["volume"]),
    +                "retcode": None
    +                if response is None
    +                else _optional_int(response.get("retcode")),
    +                "comment": None
    +                if response is None
    +                else _optional_str(response.get("comment")),
    +                "request": cast("dict[str, object]", request),
    +                "response": response,
    +                "dry_run": dry_run,
    +            },
    +        )
    +    return results
     
    @@ -5460,20 +5519,7 @@ details for callers to inspect.

    Source code in mt5cli/trading.py -
    1425
    -1426
    -1427
    -1428
    -1429
    -1430
    -1431
    -1432
    -1433
    -1434
    -1435
    -1436
    -1437
    -1438
    +              
    1438
     1439
     1440
     1441
    @@ -5488,35 +5534,48 @@ details for callers to inspect.

    1450 1451 1452 -1453
    def update_trailing_stop_loss_for_open_positions(
    -    client: Mt5TradingClient,
    -    *,
    -    symbol: str,
    -    trailing_stop_ratio: float,
    -    dry_run: bool = False,
    -) -> list[OrderExecutionResult]:
    -    """Update open positions whose trailing stop loss should move favorably.
    -
    -    Returns:
    -        Normalized execution results for positions that need an SL update.
    -    """
    -    updates = calculate_trailing_stop_updates(
    -        client,
    -        symbol=symbol,
    -        trailing_stop_ratio=trailing_stop_ratio,
    -    )
    -    results: list[OrderExecutionResult] = []
    -    for ticket, stop_loss in updates.items():
    -        results.extend(
    -            update_sltp_for_open_positions(
    -                client,
    -                symbol=symbol,
    -                tickets=[ticket],
    -                stop_loss=stop_loss,
    -                dry_run=dry_run,
    -            ),
    -        )
    -    return results
    +1453
    +1454
    +1455
    +1456
    +1457
    +1458
    +1459
    +1460
    +1461
    +1462
    +1463
    +1464
    +1465
    +1466
    def update_trailing_stop_loss_for_open_positions(
    +    client: Mt5TradingClient,
    +    *,
    +    symbol: str,
    +    trailing_stop_ratio: float,
    +    dry_run: bool = False,
    +) -> list[OrderExecutionResult]:
    +    """Update open positions whose trailing stop loss should move favorably.
    +
    +    Returns:
    +        Normalized execution results for positions that need an SL update.
    +    """
    +    updates = calculate_trailing_stop_updates(
    +        client,
    +        symbol=symbol,
    +        trailing_stop_ratio=trailing_stop_ratio,
    +    )
    +    results: list[OrderExecutionResult] = []
    +    for ticket, stop_loss in updates.items():
    +        results.extend(
    +            update_sltp_for_open_positions(
    +                client,
    +                symbol=symbol,
    +                tickets=[ticket],
    +                stop_loss=stop_loss,
    +                dry_run=dry_run,
    +            ),
    +        )
    +    return results
     
    diff --git a/index.html b/index.html index d2c4191..f9e0f81 100644 --- a/index.html +++ b/index.html @@ -653,5 +653,5 @@ diff --git a/objects.inv b/objects.inv index 78847b813f7ac3710b94a3aebafa7ac449cde608..e5c60ac746586eef16eb996fb5b896635640c85a 100644 GIT binary patch delta 4398 zcmV+}5z+4LBAg?Tmw$?`Q7YNWWp9c#N>tX@YQ{Wft1oLM-zH6RRHx7Ukcfexe;x}4h<}uQ%8Ko*1}?_2yhRYa znE{%zPWF5N=$}n-qhG!9v~9AoST{-2ib-3VI@xB$-eCHlXDWlc-mP9U(FkmPOnF22 zba(&v9lPE9#x~ctEB5jJ=JV|x_8L3H1}^{dG0%80yIyJcTf@^oj*1V2q~2%6UuE7N z_!Q#0T9#%YHGc}es_U|zg7|C7D|LB?77o9%gchwV3ZAMmk0e$46%^U2U0<|{zD$8?O^tRk`fwHUy}7=>bG*AQ+DtY8OObV*4S&9cmSh0cLu1jXPi5`?$R_saz+qFe^lN>y&xPd&i zS-xdyS%2)ZJph461xqwR$zG1Lrn@Bq0J?4@Acnv%8UN0TM2|dl^dL9zG|AI8SARTS zph`dPe9I2qu*JHL8!+g4U(iUP68+zkV#{945KFc@rvRo3c`d5Gmss9ZHw`d-EGYVt zQ5I(qgdz6y#>Csd{*8a?BuOLpl4NHP5Ul>qC-f|CP6x zD-RNCm)`^Ru?B;Aroe}C+vfbkFUN7^=O53kGUt~Un^iZ0ZoWLM5aYI8-bO8)6P{)w zr+@ytDfc)0h38WW)F4yVA}pV=z3-f$qqj}fHdpEyKworAW6_j@xLR+p&w*9k0vXS4 zjb%+06Ws0U>hS{qgiZt&%;~+kUy!7#j8S)~G%p2bWyOnO*r0SFkQ^`ovpv-+^IQ%m ztoO>WDmgIdzEf3>rRGJzwg%K&Cbqm$^?%x#hj;2nJDy)#XCe7(Rn`qtH)>bI&Z>(# zlUm^Z;;}7Ha_ogaYD)DMV@2})ZFEPD7Rb@8>AY;TjdH)&)1bf;eMlyQps#5Cl{f6E zEWctES&<#uLqAMn>n{J7iS{5x*eAKW{7g<1)2}3j;CgWsE5NpZ`u=uzmhI~DKz|mf zzJesGlVZ=Y3ZBYWn#H^sa#lQYOu$+5M4&xKLYF;KuqH#_dM(4Yqv5rDiW5@BRAorF zQwu0}rdM?L2Pt`x&#x+hD&1qJer4wq%}PRU6k2l5nEY41j0~~Pq8F!ULNEL^Yogd% z=SCBkh%7w3UNkdt9M_!#0Kyc=@PC;+u2v;YQ{xQSOH}}}dSi|*4#l_SXhXBEk#4L* zpbXAmUYa$n514XvELck;Im%Fco5p&#sqPA=dS6J+Z2<=q-;21%C`6rYao7mp3=pjJ zYPT7OgNQIOQu^@my$P}xak+{J3uCFrfXB1M7@5dDh8)f)#>hyDGQbkSwtu??W_p0z zSkO@pzGorF83!QWu;4r6n~r5(2mN4#9gq<;*>$9mrnJ^=!sT%zER3Zn19JzR zW<~2mrbL_t-$io!{|LM-b{m0Qa|HeW*(r!IwFb@R%LtCQ+_~Wy5_+8g zxZ*R(l-c!*T)5{v^SZp};(wlJiO$tPTQNiRV{vD9+q;oZZ)`8!t~O8Vtf5#zz)%&~ zmGyCFRxC7cpbmQit2rznm2XEPh#5!jw({fPNeAvWP7%6{$#%- z=GU&?A*kbpXlu^eCWYS1pnUX5&Z8Bu5VNHQ?O4Y`L=>e;YT0k79e+#r3J?L(WQQdP zHO{hKp6taU$brun=dq05efgdh+wwbwKwV~VuPj6@B>2}3=t~8j)dBKifP4N=pYD5R z`0u-;bmHBl{?{h3M)U!I$jX9p3$C0$uBZDfH*uH*JOCIB)MeE*NnNQf0P88K36Wc{ z-r)OAx_7|^&pTg>P=9|1U}|7G3j8{I#k~W_fD^LQQLWHdiyYkn>j%7v%a{$6<0y_Z zNCC%UQ^c;&YXZX+VogARvD8@oX5uD<6|j2|)?s6Cu)M6>XDQ{wmptX1scD64^EM0{ zT!xNw`~!vc4%^?;zp$oc;#;0IOYkGe$dG*BQoS_6sya(49e*w$HsBp^(r0KEff&!+ z+AzLzvZKd45*ASz=`rzFQZF558MAxdn3!8pB$aqBDQyMi7JLZAbUoQV_Ec@5kE2jr zwWn$e-93$wU|Tz2eKQ=)067B~^l16P8pMp3a5gJ@nzLvF?CRq4&4&GXz24kEeqknz zYdz`cy){~Vuzzh#S`y4?IDFeyYv~#D>CotHhf%4CQ*sby-<71T`L{N!)k>HOOf4cQ z-=BHS3DV^;oWMa7!o?d@(p8XezuHZoZS|8d!%_h95{$Igly`w#HliUQ*4+TB9K`$j zA!(ioFVPS{d1t+Tn2<}Ym?4v@;>FhCoP=wXwEIIh^M98eSHp|rNNKlp*-I-HTz}^DrJU3HrQDww~HV;krkp z>wuSt**K;Ko><~wf~%bZ-+odAExscM{ zw~@>VhSuK0+@orS{nnO^X>_)g4}7-EIJFy8BY#c3oeu3}h$!wzxv{x?{ zV!T@?G*EvtVnMybqdK?+muH|XszF&;J+RYot< zEUAig{J6ZN+o;iABlI>}}@ z4S)Zh(M0F~dVLUzff)!e81_@J7GaXxq|2Eh+8bkxFiLKr*{r5YLN?vHIJhO)!a z>+Ya1%#EEcSn#Wa%+7Vo;q3C%}2+m*Jev%0ipw z2+?d`8?Tv9t4CXiB*5T1Pzmu$YuuuW&1{$|G(!?n7|0$Q2E0c`QfKN%e6=E514roj z6hq{uX9d^?2+fKpgp*Gh0?s+Do`3J=dpdeMTJ2tB`#K+A{{pMFl7jp)xIuOqID0m# zxY{VvalhkNI-sc}{=4kE$TA&oL68Vuzi3~dA{yqO1eLn;W!oTBOJkrEV|g&p>@XtY z#yir101qQV{OSlE3Tgw{#)A6bi8eIHO5K50xsT1nAsi`*C>Ym4C>+C^e}9L9h^_`U zvqcaTO1*>zIP+Hp3Ep&N2=%gu+MjeREDvTN3nRSg$S87P!5RsPzk9w^WI-`9{}+}s zUjahu{kg#?a#x}-BqOT!p%h|4fID*+B%PkL0n3Earjw=TcqtCP!?rV7FoK4Cp*NaB>l>s%eG!pv9e1Qy8s|$ z4f1W@HtaL%VzpIOb0J3OwIXX}FDOPrPSU3SrmLIPXU&PMO?RfvgpCFuTGSJMA8ZFY z2FH{hDw&qNPB}9ZE<~)EC9!A`K6D`22qX#T$@Qs-`8MK!&ZHA)9Dl{tqUF6FF&Sh0>DR`s zun62`Trf$Fm=^~_7Jq0`s#(O*y9m}s9wlQpdz zT6poox^SWAGAHy5Bf=r6Dm7BcS#XQ)v+3(KkxMkRRhgKDn11#~n=#lT?fa4@Dzp_J z)ENi=v*knphJq&;Fs4ArU`%fl%{L2=+ev4$vh!^$w8S4eL4VN0@ec?97{P$h*#S*d zF%*Ggk;2m}mz)DM>w;mp&p5y*u+fKGFQ_&<{10yd!&j ze+*>i8=K=IXS1^B<^z-KCTUtR8F_rl+iq>_FLQ8fJb%z*b?3=TlI1#F+vMdOjg@H5 zQ~NeLLl#5mKS{f*c{D{|36p*ZxWj9;5#ZpZFm6SfA@Dh^B?Z!p393!f-5GSZkla|X{B}_N8hyuC(WD5CJ?kHDT zu0A+@+kamSWN+F@Z%is^(i5*`=kg)fegvhqy|(*0c3uh*sc(|6-M7nk8To-+XY>oT zk@G9!1%9|+UvIAO?;NKYywZN%pIFle{V8`TBvuuk1$q@H3%NKFoiP-?qy3g>h8#YV ze%xnpeC&Si!TQ=hV0%bXY@zey6jC95dXv8WB!6`qwvmAZU0wO_q1r9aPV$r(+_T*1JpcR>nOYq3;tR5Wx>Lgc-rl zCg2c(k0T%;?;D5__>KXsuHml}AQ=AK>0v;067wZ!C?$EA7tA$|L-;a^;|RXQ;W&aj zKYw^wAIeS>CLl7fgdu@!6=6WXjwSM@d*hb%VLi<5nw3)d#dK|i^sd`J8b=YJLDJ*use>D0XyR;9lR@!lEORU zE~!esuv%{@UCrkD<0p1?bMePIO2uw39?%*%(?3>4sGf6$!Y>Q$4!d-SU0tlyyCRe*gdg delta 4350 zcmVdg6N=(sB*q+)AxK%?U%vp!0SU4j z=mw=d#1%<+p9c5=G=N6)*!-I2+1YuTmTl2&E1ABlzW*!D6Q$n$@-C^epVa>APyaaf z#q|F>MSuKZ_`}D|$Io}-)8@<8$oEN;oYd))JSJ)+^gmApBY#B8K4ryzQ3H%|D(?`K zY!-l~tdmDM0{WkAajW0F$h2*;ve-6B)2dlpnmXBM#iPXxKQB}kcX`;nWU5ir`q=W8 z@ag9E&l_>Q`&H~NuQ%eu?bYY&8|pPi#1^jq@*&S;vAAAo_gl;Bf1DH_2}%8!75^#o z_9*8N>}olhk$=<}_@=JQdJd8=sjST99a}j5$`LxWvM6L~%0xnE`YHRil64Y~p2?@= zZFlS9uv4vN-qw3r+XwVssy1(^cM8{E0$1V5b z*o`!z>uUjn*xN!z0+ks4o)mlWY)3`5-6aJuRp@I`4KMckrs6cf^r@g4N=8{+KnRA! z!*`*+A0Nv6RZLEB6yqv6$k(ykksy<=_w3T2S$|d4GTE;%`gTJdr$AX7uR_?9(KqA2TQl4t+bw^$md4{Dd+ zY4ov1gL!7a$8z81^4-s;apk9fym!i+eLUZ7x)F5u?2?zpL`` zN`F4fd`^KHWXn2)^^>g5A#IzgZ7$4RB3~9q zaeq#KhGqf>hWc0dBb-!~HHw!?%RJXTs~8*LR%FNaICSUKy6gWHsy%8E^)c%%zt9t!^eaoDWWVl46;NAXT_0lk z?#_xsT^`v2<7Tl$by7S^szRo^Qx-9AhMv7m22gNzHxu+84x{6mC`6NyZ+$PLwtqv< zUiDL)uqtLM!@8ZlfOBUCMR$LQl4t$=ni8ba19tBJbYu6TBsAQUC1*nDfAz~K2EcLy zS57vx=o-7OsNPovdwKS2F48^x;s>e-rS2*pr9P}J)>~@y@Q?M7o z$0$ObU2)h5;0!RV3~JmA;vf=COq4!+d~ZVRMKD*9U|}lt81Q(O6eBaa#}ML-QjAQb zBm*K*Vt-g+W&q&Ef{t?VJqtO`GywaC1>YIi`9u9XqG&93+HUD;3LS z1mrD8H|9b@uM+@Qd?A@LyM9qBe9p71OR1zND_IC%Z-TC4L-G;sSwF)X=qeVdVJzk83tr`wr~IBz9jb7Snm+j$wIZY6m642?`2Rvc_f#+>Qso``hj*< zV<9SvQYE$SH_Xl&z5>L6G}&Pc|M}B>&kVno!>+Lz5%IAc9YR69#lP}y((r2=0HTK2GGb*x zxdS)OpX{gmBDW!a3_JiB4b)}THOXA5E>P$psTmPQu-@W_PI_>`mCQR|i&1|BFgGwC z1%6q);@$yd#3|kBn15FESBo8m0P9D*jUQMHl+$Q~_mBb(^W})Ks9pvGi{51*z%X5^ zem8Ry!V1{E2ia@~lAf!KBftZ@);>${|RV!T9S7~zfc`cVQ8d&L5o zRFy3Dh;tIIQPMshyP3c4xEfiU9_M~G4frErV&HfO3x5C~;|L>$No|^_Cn2AuS&TEN zILc}Js2`nG9Aq3SjbmG=rf$21^!RFZ7bq={m7ZceWVso442)a9z3GkeESPZTk4-2gRy$#~UcK*pnSt8?=A zy2oB9{eKEJzBS4aeA@2SuH&^+@c0}4J)@Zr0eXE9j)4UTFc|hz zsDBn=5^fT6W|;P-7;B6dKMRJ;@*`x?pja%D%6Fu5s&PT&U|KMKHYQxw6CrEBkXnYfj(%)emz)-)d%FYgf000AMf&~9c`2v8V z)oQka;KtVjyt0050l$*5p=az>a>QNYm5DmZW`w~5QL2%F?*7)5SkTn2(Lb62sr1w zdcK+OiS%~7+CA&`bv}Oo3#!^l3V-tR=mxoE;Kagp*b426(lc6$qzHA$UYHbXZVXO}ZS{z0s+;}7%2=Fix#4kwjP*5AlxfRq0 zPqdLaPU;S_3O_azhd@#iaWL3HC>q0?e}{vJt_C%;MGzE9y+j6}`Ky8iZ-2Tnf_mLU z?N2%umIpJCg%RF#WE?rLU`>R?-#uR{vY?ol|BK35t^g7B{@h?3IhH7l$cU4u%H1L}XDO?;P$liaUCb-iex zKvx{gqHM|{OV{vphxm}BUw_3@+16_+R(1(fR{)f*LB1c_Mtw#xR$EoIRBCcwE3#JZ zf?_1(RoXP%baS(YtT~aj>CUv-u+add7Y&5pM%#go0h!W6CDT&YsT6j?MTj+XBn~aY zhYlngfh6H1wmuaz-$on|O*%owaa=84-is9+JfVdT8s$I7O=#lhFn^KLmbjTpi@5`E~@K$_CXB_;`7K#821y3+gOo5QmSieoQ z+$=n8C%s>kU2bEMCH~L}h8~W8AOOG!27=BFXyS^Y=m(E(xqrt;*PNZ--ED3@Mp!$$ zIKRA#(cN$EuFgMf7*hCqLp)cr@uUqjRWNA- z5d$V|AZoFs4O}^pw84i!7TG)sQXT^$z;_y%Ol0AMn2D0#t?QxO!i?V0-d*<6FX<9WK zd3;LvWA{AWS@N7@c^|HA^KwqcN;2o6{XRKE7DE_5oqu|$Wi&!bJ$SFHMW1VB-L)7# zmU>KH))H3NK{c{sAi8hH+b8l~sy1&pj~1lY-pTPO7hV_}v)A2h-4<&x!&g#x3dSz2Vv!3`~ zcBUWl-hYqa)OOHzUvbV$r6ToB^0oWM_90_GklT!Zp>}$H#k|0Gx7*9zyI8*(+}`)Ia%UgUcbo2j^6tysX69z2 z8h9@_P~5u@Ox1#Wz#%cT{~OYvd%r;;uUd3e7!r~>wSgBp0B7n5C;k5}?p z=F|qA%AbAQ{Py{GrjfJF{r&AdS9E!Ead*qr{CR$Vb9qCppKqg^q5(F!NitxAo1}v` zw@FfXV;hs2915H5j?>lbEjgux*x{)NS*(wD8lpAu)T{PBnX0mb0LxL{I$aR2}S diff --git a/search/search_index.json b/search/search_index.json index 12fa7d2..fc87576 100644 --- a/search/search_index.json +++ b/search/search_index.json @@ -1 +1 @@ -{"config":{"indexing":"full","lang":["en"],"min_search_length":3,"prebuild_index":false,"separator":"[\\s\\-]+"},"docs":[{"location":"","text":"mt5cli \u00b6 Generic MT5 data and execution infrastructure for Python applications. Overview \u00b6 mt5cli provides a stable MT5Client Python API, standardized dataset schemas, storage helpers, and a CLI for exporting MetaTrader 5 data. It is built on top of pdmt5 , a pandas-based data handler for MetaTrader 5. Architecture \u00b6 pdmt5 \u2014 canonical MT5 client, DataFrame/trading primitives, and MT5 constant parsing ( TIMEFRAME_* , COPY_TICKS_* , order types). mt5cli \u2014 public MT5Client API, schema contracts, storage helpers, CLI commands, and SQLite history collection built on pdmt5. mt5api \u2014 sibling HTTP adapter for remote MT5 access; not a dependency of mt5cli. Features \u00b6 Multi-format export : CSV, JSON, Parquet, and SQLite3 output formats Auto-detection : Format detection from file extensions Comprehensive data access : Rates, ticks, account info, symbols, orders, positions, and trading history Flexible timeframes : Named timeframes (M1, H1, D1, etc.) and numeric values Connection management : Optional credentials, server, and timeout configuration SQLite rate loading : Load mt5cli-managed rate tables/views for offline workflows Installation \u00b6 pip install mt5cli Python API for downstream packages \u00b6 Import MT5Client for generic MT5 data access, schema normalization, and optional order primitives. from datetime import UTC , datetime from pathlib import Path from mt5cli import ( DataKind , Dataset , MT5Client , build_config , collect_history , export_dataframe , load_rate_data , minimum_margins , mt5_session , normalize_dataframe , recent_ticks , resolve_rate_view_name , ) # Persistent session for multiple calls with mt5_session ( build_config ( login = 12345 , server = \"Broker-Demo\" )) as client : rates = client . copy_rates_range ( \"EURUSD\" , timeframe = \"H1\" , date_from = \"2024-01-01\" , date_to = \"2024-02-01\" , ) positions = client . positions () check = client . order_check ({ \"action\" : 1 , \"symbol\" : \"EURUSD\" , \"volume\" : 0.1 }) # Normalize MT5 frames to the public schema contract before storage closed_rates = normalize_dataframe ( rates , DataKind . rates , symbol = \"EURUSD\" , timeframe = \"H1\" ) export_dataframe ( closed_rates , Path ( \"rates.csv\" ), \"csv\" ) # Offline rate loading from mt5cli-managed SQLite history view = resolve_rate_view_name ( Path ( \"history.db\" ), \"EURUSD\" , \"M1\" , require_existing = True ) offline_rates = load_rate_data ( Path ( \"history.db\" ), view , count = 1000 ) # One-off helpers still work without instantiating a client ticks = recent_ticks ( \"EURUSD\" , seconds = 300 ) margins = minimum_margins ( \"EURUSD\" ) collect_history ( Path ( \"history.db\" ), symbols = [ \"EURUSD\" , \"GBPUSD\" ], date_from = datetime ( 2024 , 1 , 1 , tzinfo = UTC ), date_to = datetime ( 2024 , 2 , 1 , tzinfo = UTC ), datasets = { Dataset . rates , Dataset . history_deals }, ) Schema contracts live in mt5cli.schemas ( DataKind , validate_schema , normalize_dataframe ). Storage helpers are re-exported from mt5cli.storage and the package root. MT5Client.order_send() is a live execution primitive: it can place real trades on the connected account. mt5cli does not implement strategy logic, signal generation, backtesting, or optimization \u2014 downstream applications must gate live execution explicitly (the CLI requires --yes for order-send ). MT5Client.mt5_summary() returns structured nested Python values. Use MT5Client.mt5_summary_as_df() when you need a one-row DataFrame for export. Quick Start \u00b6 # Export account information to CSV mt5cli -o account.csv account-info # Export EURUSD M1 rates to Parquet mt5cli -o rates.parquet rates-from --symbol EURUSD --timeframe M1 \\ --date-from 2024 -01-01 --count 1000 # Export ticks to JSON mt5cli -o ticks.json ticks-from --symbol EURUSD \\ --date-from 2024 -01-01 --count 500 --flags ALL # Export symbols to SQLite3 with custom table name mt5cli -o data.db --table symbols symbols --group \"*USD*\" # Export with connection credentials mt5cli --login 12345 --password mypass --server MyBroker-Demo \\ -o positions.csv positions Commands \u00b6 Rates \u00b6 Command Description rates-from Export rates from a start date rates-from-pos Export rates from a start position latest-rates Export latest rates rates-range Export rates for a date range Ticks \u00b6 Command Description ticks-from Export ticks from a start date ticks-range Export ticks for a date range ticks-recent Export ticks from a trailing window Information \u00b6 Command Description account-info Export account information terminal-info Export terminal information version Export MetaTrader 5 version information last-error Export the last error information symbols Export symbol list symbol-info Export symbol details symbol-info-tick Export the last tick for a symbol minimum-margins Export minimum-volume margin summary market-book Export market depth (order book) Trading \u00b6 Command Description orders Export active orders positions Export open positions history-orders Export historical orders history-deals Export historical deals recent-history-deals Export historical deals from a trailing window mt5-summary Export terminal/account status summary order-check Check funds sufficiency for a trade request order-send Send a trade request to the trade server ( --yes required) Use order-check to validate a request payload before running order-send --yes . Bulk Collection \u00b6 Command Description collect-history Collect rates, ticks, history-orders, and history-deals for one or more symbols into a single SQLite database (optional cash-event/position views) mt5cli -o history.db collect-history \\ --symbol EURUSD --symbol GBPUSD \\ --date-from 2024 -01-01 --date-to 2024 -02-01 \\ --dataset rates --dataset history-deals \\ --timeframe M1 --flags ALL --if-exists append --with-views collect-history options: Option Default Description --symbol/-s required Symbol to collect (repeat for multiple). --date-from required Start date in ISO 8601. --date-to required End date in ISO 8601. --dataset all four Repeatable: rates , ticks , history-orders , history-deals . --timeframe M1 Rates timeframe; recorded in a timeframe column on the rates table. --flags ALL Tick copy flags forwarded to copy_ticks_range . --if-exists fail append , replace , or fail when a target table already exists. --with-views off Add cash_events and positions_reconstructed views (requires the history-deals dataset). History orders and deals are fetched per symbol and concatenated, so the symbol filter is applied consistently across all datasets. The cash_events view is derived from symbol-filtered history_deals , so account-level cash events with empty or non-matching symbols may be excluded. The positions_reconstructed view excludes positions with no closing deal, uses volume-weighted open/close prices, and reports reversal deals ( DEAL_ENTRY_INOUT ) via volume_reversal / reversal_count . See the History schema diagram for a sample ER layout of the resulting database. Global Options \u00b6 Option Description -o, --output Output file path (required) -f, --format Output format (auto-detected from extension if omitted) --table Table name for SQLite3 output (default: \"data\") --login Trading account login --password Trading account password --server Trading server name --path Path to MetaTrader5 terminal EXE file --timeout Connection timeout in milliseconds --log-level Logging level (DEBUG, INFO, WARNING, ERROR) Requirements \u00b6 Python 3.11+ Windows OS (MetaTrader 5 requirement) MetaTrader 5 platform API Reference \u00b6 Browse the API documentation for detailed module information: CLI Module - CLI application with export commands SDK Module - Programmatic read-only data collection API Utils Module - Constants, parameter types, parsers, and export utilities Development \u00b6 This project follows strict code quality standards: Type hints required (strict mode) Comprehensive linting with Ruff Test coverage tracking Google-style docstrings License \u00b6 MIT License - see LICENSE file for details.","title":"Home"},{"location":"#mt5cli","text":"Generic MT5 data and execution infrastructure for Python applications.","title":"mt5cli"},{"location":"#overview","text":"mt5cli provides a stable MT5Client Python API, standardized dataset schemas, storage helpers, and a CLI for exporting MetaTrader 5 data. It is built on top of pdmt5 , a pandas-based data handler for MetaTrader 5.","title":"Overview"},{"location":"#architecture","text":"pdmt5 \u2014 canonical MT5 client, DataFrame/trading primitives, and MT5 constant parsing ( TIMEFRAME_* , COPY_TICKS_* , order types). mt5cli \u2014 public MT5Client API, schema contracts, storage helpers, CLI commands, and SQLite history collection built on pdmt5. mt5api \u2014 sibling HTTP adapter for remote MT5 access; not a dependency of mt5cli.","title":"Architecture"},{"location":"#features","text":"Multi-format export : CSV, JSON, Parquet, and SQLite3 output formats Auto-detection : Format detection from file extensions Comprehensive data access : Rates, ticks, account info, symbols, orders, positions, and trading history Flexible timeframes : Named timeframes (M1, H1, D1, etc.) and numeric values Connection management : Optional credentials, server, and timeout configuration SQLite rate loading : Load mt5cli-managed rate tables/views for offline workflows","title":"Features"},{"location":"#installation","text":"pip install mt5cli","title":"Installation"},{"location":"#python-api-for-downstream-packages","text":"Import MT5Client for generic MT5 data access, schema normalization, and optional order primitives. from datetime import UTC , datetime from pathlib import Path from mt5cli import ( DataKind , Dataset , MT5Client , build_config , collect_history , export_dataframe , load_rate_data , minimum_margins , mt5_session , normalize_dataframe , recent_ticks , resolve_rate_view_name , ) # Persistent session for multiple calls with mt5_session ( build_config ( login = 12345 , server = \"Broker-Demo\" )) as client : rates = client . copy_rates_range ( \"EURUSD\" , timeframe = \"H1\" , date_from = \"2024-01-01\" , date_to = \"2024-02-01\" , ) positions = client . positions () check = client . order_check ({ \"action\" : 1 , \"symbol\" : \"EURUSD\" , \"volume\" : 0.1 }) # Normalize MT5 frames to the public schema contract before storage closed_rates = normalize_dataframe ( rates , DataKind . rates , symbol = \"EURUSD\" , timeframe = \"H1\" ) export_dataframe ( closed_rates , Path ( \"rates.csv\" ), \"csv\" ) # Offline rate loading from mt5cli-managed SQLite history view = resolve_rate_view_name ( Path ( \"history.db\" ), \"EURUSD\" , \"M1\" , require_existing = True ) offline_rates = load_rate_data ( Path ( \"history.db\" ), view , count = 1000 ) # One-off helpers still work without instantiating a client ticks = recent_ticks ( \"EURUSD\" , seconds = 300 ) margins = minimum_margins ( \"EURUSD\" ) collect_history ( Path ( \"history.db\" ), symbols = [ \"EURUSD\" , \"GBPUSD\" ], date_from = datetime ( 2024 , 1 , 1 , tzinfo = UTC ), date_to = datetime ( 2024 , 2 , 1 , tzinfo = UTC ), datasets = { Dataset . rates , Dataset . history_deals }, ) Schema contracts live in mt5cli.schemas ( DataKind , validate_schema , normalize_dataframe ). Storage helpers are re-exported from mt5cli.storage and the package root. MT5Client.order_send() is a live execution primitive: it can place real trades on the connected account. mt5cli does not implement strategy logic, signal generation, backtesting, or optimization \u2014 downstream applications must gate live execution explicitly (the CLI requires --yes for order-send ). MT5Client.mt5_summary() returns structured nested Python values. Use MT5Client.mt5_summary_as_df() when you need a one-row DataFrame for export.","title":"Python API for downstream packages"},{"location":"#quick-start","text":"# Export account information to CSV mt5cli -o account.csv account-info # Export EURUSD M1 rates to Parquet mt5cli -o rates.parquet rates-from --symbol EURUSD --timeframe M1 \\ --date-from 2024 -01-01 --count 1000 # Export ticks to JSON mt5cli -o ticks.json ticks-from --symbol EURUSD \\ --date-from 2024 -01-01 --count 500 --flags ALL # Export symbols to SQLite3 with custom table name mt5cli -o data.db --table symbols symbols --group \"*USD*\" # Export with connection credentials mt5cli --login 12345 --password mypass --server MyBroker-Demo \\ -o positions.csv positions","title":"Quick Start"},{"location":"#commands","text":"","title":"Commands"},{"location":"#rates","text":"Command Description rates-from Export rates from a start date rates-from-pos Export rates from a start position latest-rates Export latest rates rates-range Export rates for a date range","title":"Rates"},{"location":"#ticks","text":"Command Description ticks-from Export ticks from a start date ticks-range Export ticks for a date range ticks-recent Export ticks from a trailing window","title":"Ticks"},{"location":"#information","text":"Command Description account-info Export account information terminal-info Export terminal information version Export MetaTrader 5 version information last-error Export the last error information symbols Export symbol list symbol-info Export symbol details symbol-info-tick Export the last tick for a symbol minimum-margins Export minimum-volume margin summary market-book Export market depth (order book)","title":"Information"},{"location":"#trading","text":"Command Description orders Export active orders positions Export open positions history-orders Export historical orders history-deals Export historical deals recent-history-deals Export historical deals from a trailing window mt5-summary Export terminal/account status summary order-check Check funds sufficiency for a trade request order-send Send a trade request to the trade server ( --yes required) Use order-check to validate a request payload before running order-send --yes .","title":"Trading"},{"location":"#bulk-collection","text":"Command Description collect-history Collect rates, ticks, history-orders, and history-deals for one or more symbols into a single SQLite database (optional cash-event/position views) mt5cli -o history.db collect-history \\ --symbol EURUSD --symbol GBPUSD \\ --date-from 2024 -01-01 --date-to 2024 -02-01 \\ --dataset rates --dataset history-deals \\ --timeframe M1 --flags ALL --if-exists append --with-views collect-history options: Option Default Description --symbol/-s required Symbol to collect (repeat for multiple). --date-from required Start date in ISO 8601. --date-to required End date in ISO 8601. --dataset all four Repeatable: rates , ticks , history-orders , history-deals . --timeframe M1 Rates timeframe; recorded in a timeframe column on the rates table. --flags ALL Tick copy flags forwarded to copy_ticks_range . --if-exists fail append , replace , or fail when a target table already exists. --with-views off Add cash_events and positions_reconstructed views (requires the history-deals dataset). History orders and deals are fetched per symbol and concatenated, so the symbol filter is applied consistently across all datasets. The cash_events view is derived from symbol-filtered history_deals , so account-level cash events with empty or non-matching symbols may be excluded. The positions_reconstructed view excludes positions with no closing deal, uses volume-weighted open/close prices, and reports reversal deals ( DEAL_ENTRY_INOUT ) via volume_reversal / reversal_count . See the History schema diagram for a sample ER layout of the resulting database.","title":"Bulk Collection"},{"location":"#global-options","text":"Option Description -o, --output Output file path (required) -f, --format Output format (auto-detected from extension if omitted) --table Table name for SQLite3 output (default: \"data\") --login Trading account login --password Trading account password --server Trading server name --path Path to MetaTrader5 terminal EXE file --timeout Connection timeout in milliseconds --log-level Logging level (DEBUG, INFO, WARNING, ERROR)","title":"Global Options"},{"location":"#requirements","text":"Python 3.11+ Windows OS (MetaTrader 5 requirement) MetaTrader 5 platform","title":"Requirements"},{"location":"#api-reference","text":"Browse the API documentation for detailed module information: CLI Module - CLI application with export commands SDK Module - Programmatic read-only data collection API Utils Module - Constants, parameter types, parsers, and export utilities","title":"API Reference"},{"location":"#development","text":"This project follows strict code quality standards: Type hints required (strict mode) Comprehensive linting with Ruff Test coverage tracking Google-style docstrings","title":"Development"},{"location":"#license","text":"MIT License - see LICENSE file for details.","title":"License"},{"location":"api/","text":"API Reference \u00b6 This section documents the mt5cli public Python API and CLI modules. Start with the Public API Contract for the stable downstream SDK surface, CLI boundary, internal modules, and out-of-scope strategy responsibilities. Public API layers \u00b6 Module Purpose Public API Contract Stable downstream SDK exports, CLI boundary, and out-of-scope items Client MT5Client session abstraction for data access and order primitives Schemas Canonical DataFrame contracts and normalization helpers Storage CSV/JSON/Parquet/SQLite export and history collection helpers Converters Symbol, timeframe, timezone, and date-range utilities Exceptions Stable mt5cli exception types and MT5 error normalization SDK Module-level fetch helpers, multi-account collectors, incremental history Trading Trading-capable sessions and operational helpers History Collection (SQLite) SQLite schema, incremental writes, dedup, and rate views CLI Typer commands that delegate to the Python API Utils Parsing helpers and Click parameter types Architecture overview \u00b6 flowchart TD App[\"Downstream application\"] --> Client[\"MT5Client\"] CLI[\"mt5cli CLI\"] --> Client Client --> SDK[\"sdk / pdmt5\"] Client --> Schemas[\"schemas\"] Storage[\"storage\"] --> History[\"history SQLite\"] Storage --> Utils[\"utils export\"] SDK --> PDMT5[\"pdmt5.Mt5DataClient\"] Downstream packages should depend on the package root exports documented in the Public API Contract ( MT5Client , DataKind , normalize_dataframe , collect_history , load_rate_data , resolve_rate_view_name , etc.) rather than private modules. MT5Client.order_send() is a live execution primitive that can place real trades. mt5cli exposes minimal execution helpers only; strategy logic, signals, backtests, and optimization remain out of scope and must be implemented downstream with explicit execution gating. Quick start \u00b6 from mt5cli import MT5Client , build_config , mt5_session with mt5_session ( build_config ( login = 12345 )) as client : rates = client . copy_rates_range ( \"EURUSD\" , \"H1\" , \"2024-01-01\" , \"2024-02-01\" ) positions = client . positions () mt5cli -o account.csv account-info mt5cli -o rates.parquet rates-range --symbol EURUSD --timeframe H1 \\ --date-from 2024 -01-01 --date-to 2024 -02-01 See individual module pages for detailed usage examples.","title":"Overview"},{"location":"api/#api-reference","text":"This section documents the mt5cli public Python API and CLI modules. Start with the Public API Contract for the stable downstream SDK surface, CLI boundary, internal modules, and out-of-scope strategy responsibilities.","title":"API Reference"},{"location":"api/#public-api-layers","text":"Module Purpose Public API Contract Stable downstream SDK exports, CLI boundary, and out-of-scope items Client MT5Client session abstraction for data access and order primitives Schemas Canonical DataFrame contracts and normalization helpers Storage CSV/JSON/Parquet/SQLite export and history collection helpers Converters Symbol, timeframe, timezone, and date-range utilities Exceptions Stable mt5cli exception types and MT5 error normalization SDK Module-level fetch helpers, multi-account collectors, incremental history Trading Trading-capable sessions and operational helpers History Collection (SQLite) SQLite schema, incremental writes, dedup, and rate views CLI Typer commands that delegate to the Python API Utils Parsing helpers and Click parameter types","title":"Public API layers"},{"location":"api/#architecture-overview","text":"flowchart TD App[\"Downstream application\"] --> Client[\"MT5Client\"] CLI[\"mt5cli CLI\"] --> Client Client --> SDK[\"sdk / pdmt5\"] Client --> Schemas[\"schemas\"] Storage[\"storage\"] --> History[\"history SQLite\"] Storage --> Utils[\"utils export\"] SDK --> PDMT5[\"pdmt5.Mt5DataClient\"] Downstream packages should depend on the package root exports documented in the Public API Contract ( MT5Client , DataKind , normalize_dataframe , collect_history , load_rate_data , resolve_rate_view_name , etc.) rather than private modules. MT5Client.order_send() is a live execution primitive that can place real trades. mt5cli exposes minimal execution helpers only; strategy logic, signals, backtests, and optimization remain out of scope and must be implemented downstream with explicit execution gating.","title":"Architecture overview"},{"location":"api/#quick-start","text":"from mt5cli import MT5Client , build_config , mt5_session with mt5_session ( build_config ( login = 12345 )) as client : rates = client . copy_rates_range ( \"EURUSD\" , \"H1\" , \"2024-01-01\" , \"2024-02-01\" ) positions = client . positions () mt5cli -o account.csv account-info mt5cli -o rates.parquet rates-range --symbol EURUSD --timeframe H1 \\ --date-from 2024 -01-01 --date-to 2024 -02-01 See individual module pages for detailed usage examples.","title":"Quick start"},{"location":"api/cli/","text":"CLI Module \u00b6 mt5cli.cli \u00b6 Command-line interface for MetaTrader 5 data export. app module-attribute \u00b6 app = Typer ( name = \"mt5cli\" , help = \"Export MetaTrader5 data to CSV, JSON, Parquet, or SQLite3.\" , ) logger module-attribute \u00b6 logger = getLogger ( __name__ ) account_info \u00b6 account_info ( ctx : Context ) -> None Export account information. Source code in mt5cli/cli.py 379 380 381 382 @app . command () def account_info ( ctx : typer . Context ) -> None : \"\"\"Export account information.\"\"\" _export_command ( ctx , lambda client : client . account_info ()) collect_history \u00b6 collect_history ( ctx : Context , symbol : Annotated [ list [ str ], Option ( \"--symbol\" , \"-s\" , help = \"Symbol to collect (repeat for multiple symbols).\" , ), ], date_from : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], date_to : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ], dataset : Annotated [ list [ Dataset ] | None , Option ( \"--dataset\" , help = \"Dataset to include (repeat for multiple). Defaults to all: rates, ticks, history-orders, history-deals.\" , ), ] = None , timeframe : Annotated [ int , Option ( click_type = TIMEFRAME_TYPE , help = \"Rates timeframe (e.g., M1, H1, D1).\" , ), ] = 1 , flags : Annotated [ int , Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick copy flags (ALL, INFO, TRADE, or integer).\" , ), ] = \"ALL\" , if_exists : Annotated [ IfExists , Option ( \"--if-exists\" , help = \"Behavior when a target table already exists.\" , ), ] = FAIL , with_views : Annotated [ bool , Option ( \"--with-views\" , help = \"Add cash_events and positions_reconstructed SQLite views derived from history_deals.\" , ), ] = False , ) -> None Collect historical datasets into a single SQLite database. Tables written depend on --dataset : rates , ticks , history_orders , history_deals . History datasets are fetched per symbol and concatenated. Rates rows carry the requested timeframe so appended runs at different timeframes remain distinguishable. With --with-views (requires the history-deals dataset), optional views cash_events and positions_reconstructed are derived from history_deals when the required columns are present. Raises: Type Description BadParameter If the output format is not SQLite3. Source code in mt5cli/cli.py 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 @app . command () def collect_history ( ctx : typer . Context , symbol : Annotated [ list [ str ], typer . Option ( \"--symbol\" , \"-s\" , help = \"Symbol to collect (repeat for multiple symbols).\" , ), ], date_from : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], date_to : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ], dataset : Annotated [ list [ Dataset ] | None , typer . Option ( \"--dataset\" , help = ( \"Dataset to include (repeat for multiple).\" \" Defaults to all: rates, ticks, history-orders, history-deals.\" ), ), ] = None , timeframe : Annotated [ int , typer . Option ( click_type = TIMEFRAME_TYPE , help = \"Rates timeframe (e.g., M1, H1, D1).\" , ), ] = 1 , flags : Annotated [ int , typer . Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick copy flags (ALL, INFO, TRADE, or integer).\" , ), ] = \"ALL\" , # pyright: ignore[reportArgumentType] if_exists : Annotated [ IfExists , typer . Option ( \"--if-exists\" , help = \"Behavior when a target table already exists.\" , ), ] = IfExists . FAIL , with_views : Annotated [ bool , typer . Option ( \"--with-views\" , help = ( \"Add cash_events and positions_reconstructed SQLite views\" \" derived from history_deals.\" ), ), ] = False , ) -> None : \"\"\"Collect historical datasets into a single SQLite database. Tables written depend on ``--dataset``: ``rates``, ``ticks``, ``history_orders``, ``history_deals``. History datasets are fetched per symbol and concatenated. Rates rows carry the requested ``timeframe`` so appended runs at different timeframes remain distinguishable. With ``--with-views`` (requires the ``history-deals`` dataset), optional views ``cash_events`` and ``positions_reconstructed`` are derived from ``history_deals`` when the required columns are present. Raises: typer.BadParameter: If the output format is not SQLite3. \"\"\" export_ctx = _get_export_context ( ctx ) if export_ctx . output_format != \"sqlite3\" : msg = ( \"collect-history requires SQLite3 output.\" \" Use a .db/.sqlite/.sqlite3 extension or --format sqlite3.\" ) raise typer . BadParameter ( msg ) datasets = set ( dataset ) if dataset else set ( Dataset ) sdk . collect_history ( output = export_ctx . output , symbols = symbol , date_from = date_from , date_to = date_to , datasets = datasets , timeframe = timeframe , flags = flags , if_exists = if_exists , with_views = with_views , config = export_ctx . config , ) history_deals \u00b6 history_deals ( ctx : Context , date_from : Annotated [ datetime | None , Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ] = None , date_to : Annotated [ datetime | None , Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ] = None , group : Annotated [ str | None , Option ( help = \"Group filter.\" ) ] = None , symbol : Annotated [ str | None , Option ( help = \"Symbol filter.\" ) ] = None , ticket : Annotated [ int | None , Option ( help = \"Order ticket.\" ) ] = None , position : Annotated [ int | None , Option ( help = \"Position ticket.\" ) ] = None , ) -> None Export historical deals. Source code in mt5cli/cli.py 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 @app . command () def history_deals ( ctx : typer . Context , date_from : Annotated [ datetime | None , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ] = None , date_to : Annotated [ datetime | None , typer . Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ] = None , group : Annotated [ str | None , typer . Option ( help = \"Group filter.\" )] = None , symbol : Annotated [ str | None , typer . Option ( help = \"Symbol filter.\" )] = None , ticket : Annotated [ int | None , typer . Option ( help = \"Order ticket.\" )] = None , position : Annotated [ int | None , typer . Option ( help = \"Position ticket.\" )] = None , ) -> None : \"\"\"Export historical deals.\"\"\" _export_command ( ctx , lambda client : client . history_deals ( date_from = date_from , date_to = date_to , group = group , symbol = symbol , ticket = ticket , position = position , ), ) history_orders \u00b6 history_orders ( ctx : Context , date_from : Annotated [ datetime | None , Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ] = None , date_to : Annotated [ datetime | None , Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ] = None , group : Annotated [ str | None , Option ( help = \"Group filter.\" ) ] = None , symbol : Annotated [ str | None , Option ( help = \"Symbol filter.\" ) ] = None , ticket : Annotated [ int | None , Option ( help = \"Order ticket.\" ) ] = None , position : Annotated [ int | None , Option ( help = \"Position ticket.\" ) ] = None , ) -> None Export historical orders. Source code in mt5cli/cli.py 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 @app . command () def history_orders ( ctx : typer . Context , date_from : Annotated [ datetime | None , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ] = None , date_to : Annotated [ datetime | None , typer . Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ] = None , group : Annotated [ str | None , typer . Option ( help = \"Group filter.\" )] = None , symbol : Annotated [ str | None , typer . Option ( help = \"Symbol filter.\" )] = None , ticket : Annotated [ int | None , typer . Option ( help = \"Order ticket.\" )] = None , position : Annotated [ int | None , typer . Option ( help = \"Position ticket.\" )] = None , ) -> None : \"\"\"Export historical orders.\"\"\" _export_command ( ctx , lambda client : client . history_orders ( date_from = date_from , date_to = date_to , group = group , symbol = symbol , ticket = ticket , position = position , ), ) last_error \u00b6 last_error ( ctx : Context ) -> None Export the last error information. Source code in mt5cli/cli.py 544 545 546 547 @app . command () def last_error ( ctx : typer . Context ) -> None : \"\"\"Export the last error information.\"\"\" _export_command ( ctx , lambda client : client . last_error ()) latest_rates \u00b6 latest_rates ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe.\" ), ], count : Annotated [ int , Option ( help = \"Number of records.\" ) ], start_pos : Annotated [ int , Option ( help = \"Start position (0 = current bar).\" ), ] = 0 , ) -> None Export latest rates from a start position. Source code in mt5cli/cli.py 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 @app . command () def latest_rates ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , typer . Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe.\" , ), ], count : Annotated [ int , typer . Option ( help = \"Number of records.\" )], start_pos : Annotated [ int , typer . Option ( help = \"Start position (0 = current bar).\" ), ] = 0 , ) -> None : \"\"\"Export latest rates from a start position.\"\"\" _export_command ( ctx , lambda client : client . latest_rates ( symbol , timeframe , count , start_pos = start_pos , ), ) main \u00b6 main () -> None Run the mt5cli CLI. Source code in mt5cli/cli.py 700 701 702 def main () -> None : \"\"\"Run the mt5cli CLI.\"\"\" app () market_book \u00b6 market_book ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], ) -> None Export market depth (order book) for a symbol. Source code in mt5cli/cli.py 559 560 561 562 563 564 565 @app . command () def market_book ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], ) -> None : \"\"\"Export market depth (order book) for a symbol.\"\"\" _export_command ( ctx , lambda client : client . market_book ( symbol )) minimum_margins \u00b6 minimum_margins ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], ) -> None Export minimum-volume buy and sell margin requirements. Source code in mt5cli/cli.py 412 413 414 415 416 417 418 @app . command () def minimum_margins ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], ) -> None : \"\"\"Export minimum-volume buy and sell margin requirements.\"\"\" _export_command ( ctx , lambda client : client . minimum_margins ( symbol )) mt5_summary \u00b6 mt5_summary ( ctx : Context ) -> None Export a compact terminal/account status summary. Source code in mt5cli/cli.py 532 533 534 535 @app . command () def mt5_summary ( ctx : typer . Context ) -> None : \"\"\"Export a compact terminal/account status summary.\"\"\" _export_command ( ctx , lambda client : client . mt5_summary_as_df ()) order_check \u00b6 order_check ( ctx : Context , request : Annotated [ dict [ str , Any ], Option ( click_type = REQUEST_TYPE , help = _REQUEST_OPTION_HELP , ), ], ) -> None Check funds sufficiency for a trading operation. Source code in mt5cli/cli.py 568 569 570 571 572 573 574 575 576 577 @app . command () def order_check ( ctx : typer . Context , request : Annotated [ dict [ str , Any ], typer . Option ( click_type = REQUEST_TYPE , help = _REQUEST_OPTION_HELP ), ], ) -> None : \"\"\"Check funds sufficiency for a trading operation.\"\"\" _export_command ( ctx , lambda client : client . order_check ( request )) order_send \u00b6 order_send ( ctx : Context , request : Annotated [ dict [ str , Any ], Option ( click_type = REQUEST_TYPE , help = _REQUEST_OPTION_HELP , ), ], yes : Annotated [ bool , Option ( \"--yes\" , help = \"Confirm the live trade request.\" ), ] = False , ) -> None Send a trading operation request to the trade server. Raises: Type Description BadParameter If --yes is not provided. Source code in mt5cli/cli.py 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 @app . command () def order_send ( ctx : typer . Context , request : Annotated [ dict [ str , Any ], typer . Option ( click_type = REQUEST_TYPE , help = _REQUEST_OPTION_HELP ), ], yes : Annotated [ bool , typer . Option ( \"--yes\" , help = \"Confirm the live trade request.\" ), ] = False , ) -> None : \"\"\"Send a trading operation request to the trade server. Raises: typer.BadParameter: If --yes is not provided. \"\"\" if not yes : msg = \"Pass --yes to send a live trade request.\" raise typer . BadParameter ( msg , param_hint = \"--yes\" ) _export_command ( ctx , lambda client : client . order_send ( request )) orders \u00b6 orders ( ctx : Context , symbol : Annotated [ str | None , Option ( help = \"Symbol filter.\" ) ] = None , group : Annotated [ str | None , Option ( help = \"Group filter.\" ) ] = None , ticket : Annotated [ int | None , Option ( help = \"Ticket filter.\" ) ] = None , ) -> None Export active orders. Source code in mt5cli/cli.py 421 422 423 424 425 426 427 428 429 430 431 432 @app . command () def orders ( ctx : typer . Context , symbol : Annotated [ str | None , typer . Option ( help = \"Symbol filter.\" )] = None , group : Annotated [ str | None , typer . Option ( help = \"Group filter.\" )] = None , ticket : Annotated [ int | None , typer . Option ( help = \"Ticket filter.\" )] = None , ) -> None : \"\"\"Export active orders.\"\"\" _export_command ( ctx , lambda client : client . orders ( symbol = symbol , group = group , ticket = ticket ), ) positions \u00b6 positions ( ctx : Context , symbol : Annotated [ str | None , Option ( help = \"Symbol filter.\" ) ] = None , group : Annotated [ str | None , Option ( help = \"Group filter.\" ) ] = None , ticket : Annotated [ int | None , Option ( help = \"Ticket filter.\" ) ] = None , ) -> None Export open positions. Source code in mt5cli/cli.py 435 436 437 438 439 440 441 442 443 444 445 446 @app . command () def positions ( ctx : typer . Context , symbol : Annotated [ str | None , typer . Option ( help = \"Symbol filter.\" )] = None , group : Annotated [ str | None , typer . Option ( help = \"Group filter.\" )] = None , ticket : Annotated [ int | None , typer . Option ( help = \"Ticket filter.\" )] = None , ) -> None : \"\"\"Export open positions.\"\"\" _export_command ( ctx , lambda client : client . positions ( symbol = symbol , group = group , ticket = ticket ), ) rates_from \u00b6 rates_from ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe (e.g., M1, H1, D1, or integer).\" , ), ], date_from : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"Start date in ISO 8601 format.\" , ), ], count : Annotated [ int , Option ( help = \"Number of records.\" ) ], ) -> None Export rates from a start date. Source code in mt5cli/cli.py 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 @app . command () def rates_from ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , typer . Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe (e.g., M1, H1, D1, or integer).\" , ), ], date_from : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date in ISO 8601 format.\" , ), ], count : Annotated [ int , typer . Option ( help = \"Number of records.\" )], ) -> None : \"\"\"Export rates from a start date.\"\"\" _export_command ( ctx , lambda client : client . copy_rates_from ( symbol , timeframe , date_from , count ), ) rates_from_pos \u00b6 rates_from_pos ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe.\" ), ], start_pos : Annotated [ int , Option ( help = \"Start position (0 = current bar).\" ), ], count : Annotated [ int , Option ( help = \"Number of records.\" ) ], ) -> None Export rates from a start position. Source code in mt5cli/cli.py 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 @app . command () def rates_from_pos ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , typer . Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe.\" , ), ], start_pos : Annotated [ int , typer . Option ( help = \"Start position (0 = current bar).\" )], count : Annotated [ int , typer . Option ( help = \"Number of records.\" )], ) -> None : \"\"\"Export rates from a start position.\"\"\" _export_command ( ctx , lambda client : client . copy_rates_from_pos ( symbol , timeframe , start_pos , count , ), ) rates_range \u00b6 rates_range ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe.\" ), ], date_from : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], date_to : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ], ) -> None Export rates for a date range. Source code in mt5cli/cli.py 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 @app . command () def rates_range ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , typer . Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe.\" , ), ], date_from : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], date_to : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ], ) -> None : \"\"\"Export rates for a date range.\"\"\" _export_command ( ctx , lambda client : client . copy_rates_range ( symbol , timeframe , date_from , date_to ), ) recent_history_deals \u00b6 recent_history_deals ( ctx : Context , hours : Annotated [ float , Option ( help = \"Lookback window in hours.\" ) ], date_to : Annotated [ datetime | None , Option ( click_type = DATETIME_TYPE , help = \"Window end date.\" , ), ] = None , group : Annotated [ str | None , Option ( help = \"Group filter.\" ) ] = None , symbol : Annotated [ str | None , Option ( help = \"Symbol filter.\" ) ] = None , ) -> None Export historical deals from a recent trailing window. Source code in mt5cli/cli.py 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 @app . command () def recent_history_deals ( ctx : typer . Context , hours : Annotated [ float , typer . Option ( help = \"Lookback window in hours.\" )], date_to : Annotated [ datetime | None , typer . Option ( click_type = DATETIME_TYPE , help = \"Window end date.\" ), ] = None , group : Annotated [ str | None , typer . Option ( help = \"Group filter.\" )] = None , symbol : Annotated [ str | None , typer . Option ( help = \"Symbol filter.\" )] = None , ) -> None : \"\"\"Export historical deals from a recent trailing window.\"\"\" _export_command ( ctx , lambda client : client . recent_history_deals ( hours , date_to = date_to , group = group , symbol = symbol , ), ) symbol_info \u00b6 symbol_info ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], ) -> None Export symbol details. Source code in mt5cli/cli.py 403 404 405 406 407 408 409 @app . command () def symbol_info ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], ) -> None : \"\"\"Export symbol details.\"\"\" _export_command ( ctx , lambda client : client . symbol_info ( symbol )) symbol_info_tick \u00b6 symbol_info_tick ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], ) -> None Export the last tick for a symbol. Source code in mt5cli/cli.py 550 551 552 553 554 555 556 @app . command () def symbol_info_tick ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], ) -> None : \"\"\"Export the last tick for a symbol.\"\"\" _export_command ( ctx , lambda client : client . symbol_info_tick ( symbol )) symbols \u00b6 symbols ( ctx : Context , group : Annotated [ str | None , Option ( help = \"Symbol group filter (e.g., *USD*).\" ), ] = None , ) -> None Export symbol list. Source code in mt5cli/cli.py 391 392 393 394 395 396 397 398 399 400 @app . command () def symbols ( ctx : typer . Context , group : Annotated [ str | None , typer . Option ( help = \"Symbol group filter (e.g., *USD*).\" ), ] = None , ) -> None : \"\"\"Export symbol list.\"\"\" _export_command ( ctx , lambda client : client . symbols ( group = group )) terminal_info \u00b6 terminal_info ( ctx : Context ) -> None Export terminal information. Source code in mt5cli/cli.py 385 386 387 388 @app . command () def terminal_info ( ctx : typer . Context ) -> None : \"\"\"Export terminal information.\"\"\" _export_command ( ctx , lambda client : client . terminal_info ()) ticks_from \u00b6 ticks_from ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], date_from : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], count : Annotated [ int , Option ( help = \"Number of ticks.\" )], flags : Annotated [ int , Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick flags (ALL, INFO, TRADE, or integer).\" , ), ], ) -> None Export ticks from a start date. Source code in mt5cli/cli.py 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 @app . command () def ticks_from ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], date_from : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], count : Annotated [ int , typer . Option ( help = \"Number of ticks.\" )], flags : Annotated [ int , typer . Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick flags (ALL, INFO, TRADE, or integer).\" , ), ], ) -> None : \"\"\"Export ticks from a start date.\"\"\" _export_command ( ctx , lambda client : client . copy_ticks_from ( symbol , date_from , count , flags ), ) ticks_range \u00b6 ticks_range ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], date_from : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], date_to : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ], flags : Annotated [ int , Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick flags.\" ), ], ) -> None Export ticks for a date range. Source code in mt5cli/cli.py 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 @app . command () def ticks_range ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], date_from : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], date_to : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ], flags : Annotated [ int , typer . Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick flags.\" ), ], ) -> None : \"\"\"Export ticks for a date range.\"\"\" _export_command ( ctx , lambda client : client . copy_ticks_range ( symbol , date_from , date_to , flags ), ) ticks_recent \u00b6 ticks_recent ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], seconds : Annotated [ float , Option ( help = \"Lookback window in seconds.\" ) ], date_to : Annotated [ datetime | None , Option ( click_type = DATETIME_TYPE , help = \"Window end date.\" , ), ] = None , count : Annotated [ int , Option ( help = \"Maximum number of ticks to return.\" ), ] = 10000 , flags : Annotated [ int , Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick flags (ALL, INFO, TRADE, or integer).\" , ), ] = \"ALL\" , ) -> None Export ticks from a recent time window. Source code in mt5cli/cli.py 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 @app . command () def ticks_recent ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], seconds : Annotated [ float , typer . Option ( help = \"Lookback window in seconds.\" ), ], date_to : Annotated [ datetime | None , typer . Option ( click_type = DATETIME_TYPE , help = \"Window end date.\" ), ] = None , count : Annotated [ int , typer . Option ( help = \"Maximum number of ticks to return.\" ), ] = 10000 , flags : Annotated [ int , typer . Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick flags (ALL, INFO, TRADE, or integer).\" , ), ] = \"ALL\" , # pyright: ignore[reportArgumentType] ) -> None : \"\"\"Export ticks from a recent time window.\"\"\" _export_command ( ctx , lambda client : client . recent_ticks ( symbol , seconds , date_to = date_to , count = count , flags = flags , ), ) version \u00b6 version ( ctx : Context ) -> None Export MetaTrader5 version information. Source code in mt5cli/cli.py 538 539 540 541 @app . command () def version ( ctx : typer . Context ) -> None : \"\"\"Export MetaTrader5 version information.\"\"\" _export_command ( ctx , lambda client : client . version ())","title":"CLI"},{"location":"api/cli/#cli-module","text":"","title":"CLI Module"},{"location":"api/cli/#mt5cli.cli","text":"Command-line interface for MetaTrader 5 data export.","title":"cli"},{"location":"api/cli/#mt5cli.cli.app","text":"app = Typer ( name = \"mt5cli\" , help = \"Export MetaTrader5 data to CSV, JSON, Parquet, or SQLite3.\" , )","title":"app"},{"location":"api/cli/#mt5cli.cli.logger","text":"logger = getLogger ( __name__ )","title":"logger"},{"location":"api/cli/#mt5cli.cli.account_info","text":"account_info ( ctx : Context ) -> None Export account information. Source code in mt5cli/cli.py 379 380 381 382 @app . command () def account_info ( ctx : typer . Context ) -> None : \"\"\"Export account information.\"\"\" _export_command ( ctx , lambda client : client . account_info ())","title":"account_info"},{"location":"api/cli/#mt5cli.cli.collect_history","text":"collect_history ( ctx : Context , symbol : Annotated [ list [ str ], Option ( \"--symbol\" , \"-s\" , help = \"Symbol to collect (repeat for multiple symbols).\" , ), ], date_from : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], date_to : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ], dataset : Annotated [ list [ Dataset ] | None , Option ( \"--dataset\" , help = \"Dataset to include (repeat for multiple). Defaults to all: rates, ticks, history-orders, history-deals.\" , ), ] = None , timeframe : Annotated [ int , Option ( click_type = TIMEFRAME_TYPE , help = \"Rates timeframe (e.g., M1, H1, D1).\" , ), ] = 1 , flags : Annotated [ int , Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick copy flags (ALL, INFO, TRADE, or integer).\" , ), ] = \"ALL\" , if_exists : Annotated [ IfExists , Option ( \"--if-exists\" , help = \"Behavior when a target table already exists.\" , ), ] = FAIL , with_views : Annotated [ bool , Option ( \"--with-views\" , help = \"Add cash_events and positions_reconstructed SQLite views derived from history_deals.\" , ), ] = False , ) -> None Collect historical datasets into a single SQLite database. Tables written depend on --dataset : rates , ticks , history_orders , history_deals . History datasets are fetched per symbol and concatenated. Rates rows carry the requested timeframe so appended runs at different timeframes remain distinguishable. With --with-views (requires the history-deals dataset), optional views cash_events and positions_reconstructed are derived from history_deals when the required columns are present. Raises: Type Description BadParameter If the output format is not SQLite3. Source code in mt5cli/cli.py 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 @app . command () def collect_history ( ctx : typer . Context , symbol : Annotated [ list [ str ], typer . Option ( \"--symbol\" , \"-s\" , help = \"Symbol to collect (repeat for multiple symbols).\" , ), ], date_from : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], date_to : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ], dataset : Annotated [ list [ Dataset ] | None , typer . Option ( \"--dataset\" , help = ( \"Dataset to include (repeat for multiple).\" \" Defaults to all: rates, ticks, history-orders, history-deals.\" ), ), ] = None , timeframe : Annotated [ int , typer . Option ( click_type = TIMEFRAME_TYPE , help = \"Rates timeframe (e.g., M1, H1, D1).\" , ), ] = 1 , flags : Annotated [ int , typer . Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick copy flags (ALL, INFO, TRADE, or integer).\" , ), ] = \"ALL\" , # pyright: ignore[reportArgumentType] if_exists : Annotated [ IfExists , typer . Option ( \"--if-exists\" , help = \"Behavior when a target table already exists.\" , ), ] = IfExists . FAIL , with_views : Annotated [ bool , typer . Option ( \"--with-views\" , help = ( \"Add cash_events and positions_reconstructed SQLite views\" \" derived from history_deals.\" ), ), ] = False , ) -> None : \"\"\"Collect historical datasets into a single SQLite database. Tables written depend on ``--dataset``: ``rates``, ``ticks``, ``history_orders``, ``history_deals``. History datasets are fetched per symbol and concatenated. Rates rows carry the requested ``timeframe`` so appended runs at different timeframes remain distinguishable. With ``--with-views`` (requires the ``history-deals`` dataset), optional views ``cash_events`` and ``positions_reconstructed`` are derived from ``history_deals`` when the required columns are present. Raises: typer.BadParameter: If the output format is not SQLite3. \"\"\" export_ctx = _get_export_context ( ctx ) if export_ctx . output_format != \"sqlite3\" : msg = ( \"collect-history requires SQLite3 output.\" \" Use a .db/.sqlite/.sqlite3 extension or --format sqlite3.\" ) raise typer . BadParameter ( msg ) datasets = set ( dataset ) if dataset else set ( Dataset ) sdk . collect_history ( output = export_ctx . output , symbols = symbol , date_from = date_from , date_to = date_to , datasets = datasets , timeframe = timeframe , flags = flags , if_exists = if_exists , with_views = with_views , config = export_ctx . config , )","title":"collect_history"},{"location":"api/cli/#mt5cli.cli.history_deals","text":"history_deals ( ctx : Context , date_from : Annotated [ datetime | None , Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ] = None , date_to : Annotated [ datetime | None , Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ] = None , group : Annotated [ str | None , Option ( help = \"Group filter.\" ) ] = None , symbol : Annotated [ str | None , Option ( help = \"Symbol filter.\" ) ] = None , ticket : Annotated [ int | None , Option ( help = \"Order ticket.\" ) ] = None , position : Annotated [ int | None , Option ( help = \"Position ticket.\" ) ] = None , ) -> None Export historical deals. Source code in mt5cli/cli.py 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 @app . command () def history_deals ( ctx : typer . Context , date_from : Annotated [ datetime | None , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ] = None , date_to : Annotated [ datetime | None , typer . Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ] = None , group : Annotated [ str | None , typer . Option ( help = \"Group filter.\" )] = None , symbol : Annotated [ str | None , typer . Option ( help = \"Symbol filter.\" )] = None , ticket : Annotated [ int | None , typer . Option ( help = \"Order ticket.\" )] = None , position : Annotated [ int | None , typer . Option ( help = \"Position ticket.\" )] = None , ) -> None : \"\"\"Export historical deals.\"\"\" _export_command ( ctx , lambda client : client . history_deals ( date_from = date_from , date_to = date_to , group = group , symbol = symbol , ticket = ticket , position = position , ), )","title":"history_deals"},{"location":"api/cli/#mt5cli.cli.history_orders","text":"history_orders ( ctx : Context , date_from : Annotated [ datetime | None , Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ] = None , date_to : Annotated [ datetime | None , Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ] = None , group : Annotated [ str | None , Option ( help = \"Group filter.\" ) ] = None , symbol : Annotated [ str | None , Option ( help = \"Symbol filter.\" ) ] = None , ticket : Annotated [ int | None , Option ( help = \"Order ticket.\" ) ] = None , position : Annotated [ int | None , Option ( help = \"Position ticket.\" ) ] = None , ) -> None Export historical orders. Source code in mt5cli/cli.py 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 @app . command () def history_orders ( ctx : typer . Context , date_from : Annotated [ datetime | None , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ] = None , date_to : Annotated [ datetime | None , typer . Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ] = None , group : Annotated [ str | None , typer . Option ( help = \"Group filter.\" )] = None , symbol : Annotated [ str | None , typer . Option ( help = \"Symbol filter.\" )] = None , ticket : Annotated [ int | None , typer . Option ( help = \"Order ticket.\" )] = None , position : Annotated [ int | None , typer . Option ( help = \"Position ticket.\" )] = None , ) -> None : \"\"\"Export historical orders.\"\"\" _export_command ( ctx , lambda client : client . history_orders ( date_from = date_from , date_to = date_to , group = group , symbol = symbol , ticket = ticket , position = position , ), )","title":"history_orders"},{"location":"api/cli/#mt5cli.cli.last_error","text":"last_error ( ctx : Context ) -> None Export the last error information. Source code in mt5cli/cli.py 544 545 546 547 @app . command () def last_error ( ctx : typer . Context ) -> None : \"\"\"Export the last error information.\"\"\" _export_command ( ctx , lambda client : client . last_error ())","title":"last_error"},{"location":"api/cli/#mt5cli.cli.latest_rates","text":"latest_rates ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe.\" ), ], count : Annotated [ int , Option ( help = \"Number of records.\" ) ], start_pos : Annotated [ int , Option ( help = \"Start position (0 = current bar).\" ), ] = 0 , ) -> None Export latest rates from a start position. Source code in mt5cli/cli.py 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 @app . command () def latest_rates ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , typer . Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe.\" , ), ], count : Annotated [ int , typer . Option ( help = \"Number of records.\" )], start_pos : Annotated [ int , typer . Option ( help = \"Start position (0 = current bar).\" ), ] = 0 , ) -> None : \"\"\"Export latest rates from a start position.\"\"\" _export_command ( ctx , lambda client : client . latest_rates ( symbol , timeframe , count , start_pos = start_pos , ), )","title":"latest_rates"},{"location":"api/cli/#mt5cli.cli.main","text":"main () -> None Run the mt5cli CLI. Source code in mt5cli/cli.py 700 701 702 def main () -> None : \"\"\"Run the mt5cli CLI.\"\"\" app ()","title":"main"},{"location":"api/cli/#mt5cli.cli.market_book","text":"market_book ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], ) -> None Export market depth (order book) for a symbol. Source code in mt5cli/cli.py 559 560 561 562 563 564 565 @app . command () def market_book ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], ) -> None : \"\"\"Export market depth (order book) for a symbol.\"\"\" _export_command ( ctx , lambda client : client . market_book ( symbol ))","title":"market_book"},{"location":"api/cli/#mt5cli.cli.minimum_margins","text":"minimum_margins ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], ) -> None Export minimum-volume buy and sell margin requirements. Source code in mt5cli/cli.py 412 413 414 415 416 417 418 @app . command () def minimum_margins ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], ) -> None : \"\"\"Export minimum-volume buy and sell margin requirements.\"\"\" _export_command ( ctx , lambda client : client . minimum_margins ( symbol ))","title":"minimum_margins"},{"location":"api/cli/#mt5cli.cli.mt5_summary","text":"mt5_summary ( ctx : Context ) -> None Export a compact terminal/account status summary. Source code in mt5cli/cli.py 532 533 534 535 @app . command () def mt5_summary ( ctx : typer . Context ) -> None : \"\"\"Export a compact terminal/account status summary.\"\"\" _export_command ( ctx , lambda client : client . mt5_summary_as_df ())","title":"mt5_summary"},{"location":"api/cli/#mt5cli.cli.order_check","text":"order_check ( ctx : Context , request : Annotated [ dict [ str , Any ], Option ( click_type = REQUEST_TYPE , help = _REQUEST_OPTION_HELP , ), ], ) -> None Check funds sufficiency for a trading operation. Source code in mt5cli/cli.py 568 569 570 571 572 573 574 575 576 577 @app . command () def order_check ( ctx : typer . Context , request : Annotated [ dict [ str , Any ], typer . Option ( click_type = REQUEST_TYPE , help = _REQUEST_OPTION_HELP ), ], ) -> None : \"\"\"Check funds sufficiency for a trading operation.\"\"\" _export_command ( ctx , lambda client : client . order_check ( request ))","title":"order_check"},{"location":"api/cli/#mt5cli.cli.order_send","text":"order_send ( ctx : Context , request : Annotated [ dict [ str , Any ], Option ( click_type = REQUEST_TYPE , help = _REQUEST_OPTION_HELP , ), ], yes : Annotated [ bool , Option ( \"--yes\" , help = \"Confirm the live trade request.\" ), ] = False , ) -> None Send a trading operation request to the trade server. Raises: Type Description BadParameter If --yes is not provided. Source code in mt5cli/cli.py 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 @app . command () def order_send ( ctx : typer . Context , request : Annotated [ dict [ str , Any ], typer . Option ( click_type = REQUEST_TYPE , help = _REQUEST_OPTION_HELP ), ], yes : Annotated [ bool , typer . Option ( \"--yes\" , help = \"Confirm the live trade request.\" ), ] = False , ) -> None : \"\"\"Send a trading operation request to the trade server. Raises: typer.BadParameter: If --yes is not provided. \"\"\" if not yes : msg = \"Pass --yes to send a live trade request.\" raise typer . BadParameter ( msg , param_hint = \"--yes\" ) _export_command ( ctx , lambda client : client . order_send ( request ))","title":"order_send"},{"location":"api/cli/#mt5cli.cli.orders","text":"orders ( ctx : Context , symbol : Annotated [ str | None , Option ( help = \"Symbol filter.\" ) ] = None , group : Annotated [ str | None , Option ( help = \"Group filter.\" ) ] = None , ticket : Annotated [ int | None , Option ( help = \"Ticket filter.\" ) ] = None , ) -> None Export active orders. Source code in mt5cli/cli.py 421 422 423 424 425 426 427 428 429 430 431 432 @app . command () def orders ( ctx : typer . Context , symbol : Annotated [ str | None , typer . Option ( help = \"Symbol filter.\" )] = None , group : Annotated [ str | None , typer . Option ( help = \"Group filter.\" )] = None , ticket : Annotated [ int | None , typer . Option ( help = \"Ticket filter.\" )] = None , ) -> None : \"\"\"Export active orders.\"\"\" _export_command ( ctx , lambda client : client . orders ( symbol = symbol , group = group , ticket = ticket ), )","title":"orders"},{"location":"api/cli/#mt5cli.cli.positions","text":"positions ( ctx : Context , symbol : Annotated [ str | None , Option ( help = \"Symbol filter.\" ) ] = None , group : Annotated [ str | None , Option ( help = \"Group filter.\" ) ] = None , ticket : Annotated [ int | None , Option ( help = \"Ticket filter.\" ) ] = None , ) -> None Export open positions. Source code in mt5cli/cli.py 435 436 437 438 439 440 441 442 443 444 445 446 @app . command () def positions ( ctx : typer . Context , symbol : Annotated [ str | None , typer . Option ( help = \"Symbol filter.\" )] = None , group : Annotated [ str | None , typer . Option ( help = \"Group filter.\" )] = None , ticket : Annotated [ int | None , typer . Option ( help = \"Ticket filter.\" )] = None , ) -> None : \"\"\"Export open positions.\"\"\" _export_command ( ctx , lambda client : client . positions ( symbol = symbol , group = group , ticket = ticket ), )","title":"positions"},{"location":"api/cli/#mt5cli.cli.rates_from","text":"rates_from ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe (e.g., M1, H1, D1, or integer).\" , ), ], date_from : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"Start date in ISO 8601 format.\" , ), ], count : Annotated [ int , Option ( help = \"Number of records.\" ) ], ) -> None Export rates from a start date. Source code in mt5cli/cli.py 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 @app . command () def rates_from ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , typer . Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe (e.g., M1, H1, D1, or integer).\" , ), ], date_from : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date in ISO 8601 format.\" , ), ], count : Annotated [ int , typer . Option ( help = \"Number of records.\" )], ) -> None : \"\"\"Export rates from a start date.\"\"\" _export_command ( ctx , lambda client : client . copy_rates_from ( symbol , timeframe , date_from , count ), )","title":"rates_from"},{"location":"api/cli/#mt5cli.cli.rates_from_pos","text":"rates_from_pos ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe.\" ), ], start_pos : Annotated [ int , Option ( help = \"Start position (0 = current bar).\" ), ], count : Annotated [ int , Option ( help = \"Number of records.\" ) ], ) -> None Export rates from a start position. Source code in mt5cli/cli.py 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 @app . command () def rates_from_pos ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , typer . Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe.\" , ), ], start_pos : Annotated [ int , typer . Option ( help = \"Start position (0 = current bar).\" )], count : Annotated [ int , typer . Option ( help = \"Number of records.\" )], ) -> None : \"\"\"Export rates from a start position.\"\"\" _export_command ( ctx , lambda client : client . copy_rates_from_pos ( symbol , timeframe , start_pos , count , ), )","title":"rates_from_pos"},{"location":"api/cli/#mt5cli.cli.rates_range","text":"rates_range ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe.\" ), ], date_from : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], date_to : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ], ) -> None Export rates for a date range. Source code in mt5cli/cli.py 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 @app . command () def rates_range ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , typer . Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe.\" , ), ], date_from : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], date_to : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ], ) -> None : \"\"\"Export rates for a date range.\"\"\" _export_command ( ctx , lambda client : client . copy_rates_range ( symbol , timeframe , date_from , date_to ), )","title":"rates_range"},{"location":"api/cli/#mt5cli.cli.recent_history_deals","text":"recent_history_deals ( ctx : Context , hours : Annotated [ float , Option ( help = \"Lookback window in hours.\" ) ], date_to : Annotated [ datetime | None , Option ( click_type = DATETIME_TYPE , help = \"Window end date.\" , ), ] = None , group : Annotated [ str | None , Option ( help = \"Group filter.\" ) ] = None , symbol : Annotated [ str | None , Option ( help = \"Symbol filter.\" ) ] = None , ) -> None Export historical deals from a recent trailing window. Source code in mt5cli/cli.py 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 @app . command () def recent_history_deals ( ctx : typer . Context , hours : Annotated [ float , typer . Option ( help = \"Lookback window in hours.\" )], date_to : Annotated [ datetime | None , typer . Option ( click_type = DATETIME_TYPE , help = \"Window end date.\" ), ] = None , group : Annotated [ str | None , typer . Option ( help = \"Group filter.\" )] = None , symbol : Annotated [ str | None , typer . Option ( help = \"Symbol filter.\" )] = None , ) -> None : \"\"\"Export historical deals from a recent trailing window.\"\"\" _export_command ( ctx , lambda client : client . recent_history_deals ( hours , date_to = date_to , group = group , symbol = symbol , ), )","title":"recent_history_deals"},{"location":"api/cli/#mt5cli.cli.symbol_info","text":"symbol_info ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], ) -> None Export symbol details. Source code in mt5cli/cli.py 403 404 405 406 407 408 409 @app . command () def symbol_info ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], ) -> None : \"\"\"Export symbol details.\"\"\" _export_command ( ctx , lambda client : client . symbol_info ( symbol ))","title":"symbol_info"},{"location":"api/cli/#mt5cli.cli.symbol_info_tick","text":"symbol_info_tick ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], ) -> None Export the last tick for a symbol. Source code in mt5cli/cli.py 550 551 552 553 554 555 556 @app . command () def symbol_info_tick ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], ) -> None : \"\"\"Export the last tick for a symbol.\"\"\" _export_command ( ctx , lambda client : client . symbol_info_tick ( symbol ))","title":"symbol_info_tick"},{"location":"api/cli/#mt5cli.cli.symbols","text":"symbols ( ctx : Context , group : Annotated [ str | None , Option ( help = \"Symbol group filter (e.g., *USD*).\" ), ] = None , ) -> None Export symbol list. Source code in mt5cli/cli.py 391 392 393 394 395 396 397 398 399 400 @app . command () def symbols ( ctx : typer . Context , group : Annotated [ str | None , typer . Option ( help = \"Symbol group filter (e.g., *USD*).\" ), ] = None , ) -> None : \"\"\"Export symbol list.\"\"\" _export_command ( ctx , lambda client : client . symbols ( group = group ))","title":"symbols"},{"location":"api/cli/#mt5cli.cli.terminal_info","text":"terminal_info ( ctx : Context ) -> None Export terminal information. Source code in mt5cli/cli.py 385 386 387 388 @app . command () def terminal_info ( ctx : typer . Context ) -> None : \"\"\"Export terminal information.\"\"\" _export_command ( ctx , lambda client : client . terminal_info ())","title":"terminal_info"},{"location":"api/cli/#mt5cli.cli.ticks_from","text":"ticks_from ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], date_from : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], count : Annotated [ int , Option ( help = \"Number of ticks.\" )], flags : Annotated [ int , Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick flags (ALL, INFO, TRADE, or integer).\" , ), ], ) -> None Export ticks from a start date. Source code in mt5cli/cli.py 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 @app . command () def ticks_from ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], date_from : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], count : Annotated [ int , typer . Option ( help = \"Number of ticks.\" )], flags : Annotated [ int , typer . Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick flags (ALL, INFO, TRADE, or integer).\" , ), ], ) -> None : \"\"\"Export ticks from a start date.\"\"\" _export_command ( ctx , lambda client : client . copy_ticks_from ( symbol , date_from , count , flags ), )","title":"ticks_from"},{"location":"api/cli/#mt5cli.cli.ticks_range","text":"ticks_range ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], date_from : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], date_to : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ], flags : Annotated [ int , Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick flags.\" ), ], ) -> None Export ticks for a date range. Source code in mt5cli/cli.py 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 @app . command () def ticks_range ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], date_from : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], date_to : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ], flags : Annotated [ int , typer . Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick flags.\" ), ], ) -> None : \"\"\"Export ticks for a date range.\"\"\" _export_command ( ctx , lambda client : client . copy_ticks_range ( symbol , date_from , date_to , flags ), )","title":"ticks_range"},{"location":"api/cli/#mt5cli.cli.ticks_recent","text":"ticks_recent ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], seconds : Annotated [ float , Option ( help = \"Lookback window in seconds.\" ) ], date_to : Annotated [ datetime | None , Option ( click_type = DATETIME_TYPE , help = \"Window end date.\" , ), ] = None , count : Annotated [ int , Option ( help = \"Maximum number of ticks to return.\" ), ] = 10000 , flags : Annotated [ int , Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick flags (ALL, INFO, TRADE, or integer).\" , ), ] = \"ALL\" , ) -> None Export ticks from a recent time window. Source code in mt5cli/cli.py 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 @app . command () def ticks_recent ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], seconds : Annotated [ float , typer . Option ( help = \"Lookback window in seconds.\" ), ], date_to : Annotated [ datetime | None , typer . Option ( click_type = DATETIME_TYPE , help = \"Window end date.\" ), ] = None , count : Annotated [ int , typer . Option ( help = \"Maximum number of ticks to return.\" ), ] = 10000 , flags : Annotated [ int , typer . Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick flags (ALL, INFO, TRADE, or integer).\" , ), ] = \"ALL\" , # pyright: ignore[reportArgumentType] ) -> None : \"\"\"Export ticks from a recent time window.\"\"\" _export_command ( ctx , lambda client : client . recent_ticks ( symbol , seconds , date_to = date_to , count = count , flags = flags , ), )","title":"ticks_recent"},{"location":"api/cli/#mt5cli.cli.version","text":"version ( ctx : Context ) -> None Export MetaTrader5 version information. Source code in mt5cli/cli.py 538 539 540 541 @app . command () def version ( ctx : typer . Context ) -> None : \"\"\"Export MetaTrader5 version information.\"\"\" _export_command ( ctx , lambda client : client . version ())","title":"version"},{"location":"api/client/","text":"Client \u00b6 mt5cli.client \u00b6 Stable public client abstraction for MT5 data and execution operations. __all__ module-attribute \u00b6 __all__ = [ 'MT5Client' , 'build_config' , 'mt5_session' ] MT5Client \u00b6 MT5Client ( * , path : str | None = None , login : int | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , retry_count : int = 3 , config : Mt5Config | None = None , client : Mt5DataClient | None = None , ) Bases: Mt5CliClient Public client for generic MT5 data access and order primitives. Extends the read-only SDK client with optional order check/send helpers and exposes the same connection lifecycle as :func: mt5_session . mt5cli intentionally exposes minimal execution primitives only. Trading decisions, signals, strategies, backtests, and optimization remain the responsibility of downstream applications. Source code in mt5cli/sdk.py 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 def __init__ ( self , * , path : str | None = None , login : int | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , retry_count : int = 3 , config : Mt5Config | None = None , client : Mt5DataClient | None = None , ) -> None : \"\"\"Initialize the SDK client. Args: path: Path to MetaTrader5 terminal EXE file. login: Trading account login. password: Trading account password. server: Trading server name. timeout: Connection timeout in milliseconds. retry_count: Number of MT5 initialization retries for sessions opened by this client. config: Optional pre-built ``Mt5Config`` (overrides other args). client: Optional already-connected ``Mt5DataClient``. Injected clients are reused as-is and are not initialized or shut down. \"\"\" self . _config = config or build_config ( path = path , login = login , password = password , server = server , timeout = timeout , ) self . _retry_count = retry_count self . _client = client self . _owns_client = client is None from_connected_client classmethod \u00b6 from_connected_client ( client : Mt5DataClient ) -> Self Bind to an already-connected Mt5DataClient without owning it. Returns: Type Description Self Client wrapper bound to the injected connection. Source code in mt5cli/client.py 63 64 65 66 67 68 69 70 @classmethod def from_connected_client ( cls , client : Mt5DataClient ) -> Self : \"\"\"Bind to an already-connected ``Mt5DataClient`` without owning it. Returns: Client wrapper bound to the injected connection. \"\"\" return cls ( client = client ) order_check \u00b6 order_check ( request : dict [ str , Any ]) -> DataFrame Check funds sufficiency for a trade request. Parameters: Name Type Description Default request dict [ str , Any ] MT5 order request dictionary. required Returns: Type Description DataFrame One-row DataFrame with the order-check result. Source code in mt5cli/client.py 34 35 36 37 38 39 40 41 42 43 def order_check ( self , request : dict [ str , Any ]) -> pd . DataFrame : \"\"\"Check funds sufficiency for a trade request. Args: request: MT5 order request dictionary. Returns: One-row DataFrame with the order-check result. \"\"\" return self . _fetch ( lambda client : client . order_check_as_df ( request = request )) order_send \u00b6 order_send ( request : dict [ str , Any ]) -> DataFrame Send a live trade request to the MT5 trade server. Warning This is a live execution primitive. A successful call can place, modify, or close real trades on the connected account. Downstream applications must gate usage explicitly (for example behind manual confirmation or application-specific risk controls). mt5cli does not implement strategy logic, signal generation, or trade sizing. Parameters: Name Type Description Default request dict [ str , Any ] MT5 order request dictionary. required Returns: Type Description DataFrame One-row DataFrame with the order-send result. Source code in mt5cli/client.py 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 def order_send ( self , request : dict [ str , Any ]) -> pd . DataFrame : \"\"\"Send a live trade request to the MT5 trade server. Warning: This is a live execution primitive. A successful call can place, modify, or close real trades on the connected account. Downstream applications must gate usage explicitly (for example behind manual confirmation or application-specific risk controls). mt5cli does not implement strategy logic, signal generation, or trade sizing. Args: request: MT5 order request dictionary. Returns: One-row DataFrame with the order-send result. \"\"\" return self . _fetch ( lambda client : client . order_send_as_df ( request = request )) build_config \u00b6 build_config ( * , path : str | None = None , login : int | str | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , allow_whole_dollar_env : bool = False , ) -> Mt5Config Build an Mt5Config from optional connection parameters. Parameters: Name Type Description Default path str | None Optional terminal executable path. None login int | str | None Optional trading account login. Integers are preserved. String values are coerced: empty or whitespace-only strings become None ; numeric strings such as \"12345\" are converted to int ; non-numeric strings raise ValueError . When allow_whole_dollar_env=True , $ENV_NAME and ${ENV_NAME} placeholders are expanded before coercion. None password str | None Optional trading account password. None server str | None Optional trading server name. None timeout int | None Optional connection timeout in milliseconds. None allow_whole_dollar_env bool When True , string parameters that are exactly $ENV_NAME are expanded from the environment. Applies to path , login , password , and server . Default False preserves existing behavior. False Returns: Type Description Mt5Config Configured Mt5Config instance. Source code in mt5cli/sdk.py 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 def build_config ( * , path : str | None = None , login : int | str | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , allow_whole_dollar_env : bool = False , ) -> Mt5Config : \"\"\"Build an ``Mt5Config`` from optional connection parameters. Args: path: Optional terminal executable path. login: Optional trading account login. Integers are preserved. String values are coerced: empty or whitespace-only strings become ``None``; numeric strings such as ``\"12345\"`` are converted to ``int``; non-numeric strings raise ``ValueError``. When ``allow_whole_dollar_env=True``, ``$ENV_NAME`` and ``${ENV_NAME}`` placeholders are expanded before coercion. password: Optional trading account password. server: Optional trading server name. timeout: Optional connection timeout in milliseconds. allow_whole_dollar_env: When ``True``, string parameters that are exactly ``$ENV_NAME`` are expanded from the environment. Applies to ``path``, ``login``, ``password``, and ``server``. Default ``False`` preserves existing behavior. Returns: Configured ``Mt5Config`` instance. \"\"\" if allow_whole_dollar_env : if path is not None : path = substitute_env_placeholders ( path , allow_whole_dollar_env = True ) if isinstance ( login , str ): login = substitute_env_placeholders ( login , allow_whole_dollar_env = True ) if password is not None : password = substitute_env_placeholders ( password , allow_whole_dollar_env = True ) if server is not None : server = substitute_env_placeholders ( server , allow_whole_dollar_env = True ) return Mt5Config ( path = path , login = _coerce_login ( login ), password = password , server = server , timeout = timeout , ) mt5_session \u00b6 mt5_session ( config : Mt5Config | None = None , ) -> Iterator [ MT5Client ] Open an MT5 terminal session and yield a connected :class: MT5Client . Parameters: Name Type Description Default config Mt5Config | None MT5 connection configuration. Defaults to an empty config that attaches to a running terminal. None Yields: Name Type Description Connected MT5Client class: MT5Client bound to the session. Source code in mt5cli/client.py 73 74 75 76 77 78 79 80 81 82 83 84 85 86 @contextmanager def mt5_session ( config : Mt5Config | None = None ) -> Iterator [ MT5Client ]: \"\"\"Open an MT5 terminal session and yield a connected :class:`MT5Client`. Args: config: MT5 connection configuration. Defaults to an empty config that attaches to a running terminal. Yields: Connected :class:`MT5Client` bound to the session. \"\"\" mt5_config = config or build_config () with connected_client ( mt5_config ) as client : yield MT5Client . from_connected_client ( client )","title":"Client"},{"location":"api/client/#client","text":"","title":"Client"},{"location":"api/client/#mt5cli.client","text":"Stable public client abstraction for MT5 data and execution operations.","title":"client"},{"location":"api/client/#mt5cli.client.__all__","text":"__all__ = [ 'MT5Client' , 'build_config' , 'mt5_session' ]","title":"__all__"},{"location":"api/client/#mt5cli.client.MT5Client","text":"MT5Client ( * , path : str | None = None , login : int | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , retry_count : int = 3 , config : Mt5Config | None = None , client : Mt5DataClient | None = None , ) Bases: Mt5CliClient Public client for generic MT5 data access and order primitives. Extends the read-only SDK client with optional order check/send helpers and exposes the same connection lifecycle as :func: mt5_session . mt5cli intentionally exposes minimal execution primitives only. Trading decisions, signals, strategies, backtests, and optimization remain the responsibility of downstream applications. Source code in mt5cli/sdk.py 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 def __init__ ( self , * , path : str | None = None , login : int | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , retry_count : int = 3 , config : Mt5Config | None = None , client : Mt5DataClient | None = None , ) -> None : \"\"\"Initialize the SDK client. Args: path: Path to MetaTrader5 terminal EXE file. login: Trading account login. password: Trading account password. server: Trading server name. timeout: Connection timeout in milliseconds. retry_count: Number of MT5 initialization retries for sessions opened by this client. config: Optional pre-built ``Mt5Config`` (overrides other args). client: Optional already-connected ``Mt5DataClient``. Injected clients are reused as-is and are not initialized or shut down. \"\"\" self . _config = config or build_config ( path = path , login = login , password = password , server = server , timeout = timeout , ) self . _retry_count = retry_count self . _client = client self . _owns_client = client is None","title":"MT5Client"},{"location":"api/client/#mt5cli.client.MT5Client.from_connected_client","text":"from_connected_client ( client : Mt5DataClient ) -> Self Bind to an already-connected Mt5DataClient without owning it. Returns: Type Description Self Client wrapper bound to the injected connection. Source code in mt5cli/client.py 63 64 65 66 67 68 69 70 @classmethod def from_connected_client ( cls , client : Mt5DataClient ) -> Self : \"\"\"Bind to an already-connected ``Mt5DataClient`` without owning it. Returns: Client wrapper bound to the injected connection. \"\"\" return cls ( client = client )","title":"from_connected_client"},{"location":"api/client/#mt5cli.client.MT5Client.order_check","text":"order_check ( request : dict [ str , Any ]) -> DataFrame Check funds sufficiency for a trade request. Parameters: Name Type Description Default request dict [ str , Any ] MT5 order request dictionary. required Returns: Type Description DataFrame One-row DataFrame with the order-check result. Source code in mt5cli/client.py 34 35 36 37 38 39 40 41 42 43 def order_check ( self , request : dict [ str , Any ]) -> pd . DataFrame : \"\"\"Check funds sufficiency for a trade request. Args: request: MT5 order request dictionary. Returns: One-row DataFrame with the order-check result. \"\"\" return self . _fetch ( lambda client : client . order_check_as_df ( request = request ))","title":"order_check"},{"location":"api/client/#mt5cli.client.MT5Client.order_send","text":"order_send ( request : dict [ str , Any ]) -> DataFrame Send a live trade request to the MT5 trade server. Warning This is a live execution primitive. A successful call can place, modify, or close real trades on the connected account. Downstream applications must gate usage explicitly (for example behind manual confirmation or application-specific risk controls). mt5cli does not implement strategy logic, signal generation, or trade sizing. Parameters: Name Type Description Default request dict [ str , Any ] MT5 order request dictionary. required Returns: Type Description DataFrame One-row DataFrame with the order-send result. Source code in mt5cli/client.py 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 def order_send ( self , request : dict [ str , Any ]) -> pd . DataFrame : \"\"\"Send a live trade request to the MT5 trade server. Warning: This is a live execution primitive. A successful call can place, modify, or close real trades on the connected account. Downstream applications must gate usage explicitly (for example behind manual confirmation or application-specific risk controls). mt5cli does not implement strategy logic, signal generation, or trade sizing. Args: request: MT5 order request dictionary. Returns: One-row DataFrame with the order-send result. \"\"\" return self . _fetch ( lambda client : client . order_send_as_df ( request = request ))","title":"order_send"},{"location":"api/client/#mt5cli.client.build_config","text":"build_config ( * , path : str | None = None , login : int | str | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , allow_whole_dollar_env : bool = False , ) -> Mt5Config Build an Mt5Config from optional connection parameters. Parameters: Name Type Description Default path str | None Optional terminal executable path. None login int | str | None Optional trading account login. Integers are preserved. String values are coerced: empty or whitespace-only strings become None ; numeric strings such as \"12345\" are converted to int ; non-numeric strings raise ValueError . When allow_whole_dollar_env=True , $ENV_NAME and ${ENV_NAME} placeholders are expanded before coercion. None password str | None Optional trading account password. None server str | None Optional trading server name. None timeout int | None Optional connection timeout in milliseconds. None allow_whole_dollar_env bool When True , string parameters that are exactly $ENV_NAME are expanded from the environment. Applies to path , login , password , and server . Default False preserves existing behavior. False Returns: Type Description Mt5Config Configured Mt5Config instance. Source code in mt5cli/sdk.py 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 def build_config ( * , path : str | None = None , login : int | str | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , allow_whole_dollar_env : bool = False , ) -> Mt5Config : \"\"\"Build an ``Mt5Config`` from optional connection parameters. Args: path: Optional terminal executable path. login: Optional trading account login. Integers are preserved. String values are coerced: empty or whitespace-only strings become ``None``; numeric strings such as ``\"12345\"`` are converted to ``int``; non-numeric strings raise ``ValueError``. When ``allow_whole_dollar_env=True``, ``$ENV_NAME`` and ``${ENV_NAME}`` placeholders are expanded before coercion. password: Optional trading account password. server: Optional trading server name. timeout: Optional connection timeout in milliseconds. allow_whole_dollar_env: When ``True``, string parameters that are exactly ``$ENV_NAME`` are expanded from the environment. Applies to ``path``, ``login``, ``password``, and ``server``. Default ``False`` preserves existing behavior. Returns: Configured ``Mt5Config`` instance. \"\"\" if allow_whole_dollar_env : if path is not None : path = substitute_env_placeholders ( path , allow_whole_dollar_env = True ) if isinstance ( login , str ): login = substitute_env_placeholders ( login , allow_whole_dollar_env = True ) if password is not None : password = substitute_env_placeholders ( password , allow_whole_dollar_env = True ) if server is not None : server = substitute_env_placeholders ( server , allow_whole_dollar_env = True ) return Mt5Config ( path = path , login = _coerce_login ( login ), password = password , server = server , timeout = timeout , )","title":"build_config"},{"location":"api/client/#mt5cli.client.mt5_session","text":"mt5_session ( config : Mt5Config | None = None , ) -> Iterator [ MT5Client ] Open an MT5 terminal session and yield a connected :class: MT5Client . Parameters: Name Type Description Default config Mt5Config | None MT5 connection configuration. Defaults to an empty config that attaches to a running terminal. None Yields: Name Type Description Connected MT5Client class: MT5Client bound to the session. Source code in mt5cli/client.py 73 74 75 76 77 78 79 80 81 82 83 84 85 86 @contextmanager def mt5_session ( config : Mt5Config | None = None ) -> Iterator [ MT5Client ]: \"\"\"Open an MT5 terminal session and yield a connected :class:`MT5Client`. Args: config: MT5 connection configuration. Defaults to an empty config that attaches to a running terminal. Yields: Connected :class:`MT5Client` bound to the session. \"\"\" mt5_config = config or build_config () with connected_client ( mt5_config ) as client : yield MT5Client . from_connected_client ( client )","title":"mt5_session"},{"location":"api/converters/","text":"Converters \u00b6 mt5cli.converters \u00b6 Shared conversion helpers for MT5 symbols, timeframes, and date ranges. __all__ module-attribute \u00b6 __all__ = [ \"ensure_utc\" , \"granularity_name\" , \"normalize_symbol\" , \"normalize_symbols\" , \"parse_date_range\" , \"parse_datetime\" , \"parse_tick_flags\" , \"parse_timeframe\" , \"recent_window\" , ] ensure_utc \u00b6 ensure_utc ( value : datetime | str ) -> datetime Return a timezone-aware UTC datetime. Parameters: Name Type Description Default value datetime | str Datetime instance or ISO 8601 string. required Returns: Type Description datetime UTC-aware datetime. Source code in mt5cli/converters.py 69 70 71 72 73 74 75 76 77 78 79 80 81 82 def ensure_utc ( value : datetime | str ) -> datetime : \"\"\"Return a timezone-aware UTC datetime. Args: value: Datetime instance or ISO 8601 string. Returns: UTC-aware datetime. \"\"\" if isinstance ( value , str ): return parse_datetime ( value ) if value . tzinfo is None : return value . replace ( tzinfo = UTC ) return value . astimezone ( UTC ) granularity_name \u00b6 granularity_name ( timeframe : int | str ) -> str Return a short granularity label for a timeframe integer or name. Parameters: Name Type Description Default timeframe int | str MT5 timeframe as integer or name (for example M1 ). required Returns: Type Description str Short name such as M1 or the stringified integer when unknown. Source code in mt5cli/converters.py 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 def granularity_name ( timeframe : int | str ) -> str : \"\"\"Return a short granularity label for a timeframe integer or name. Args: timeframe: MT5 timeframe as integer or name (for example ``M1``). Returns: Short name such as ``M1`` or the stringified integer when unknown. \"\"\" tf = parse_timeframe ( timeframe ) try : name = _get_timeframe_name ( tf ) except ValueError : return str ( tf ) return name . removeprefix ( \"TIMEFRAME_\" ) normalize_symbol \u00b6 normalize_symbol ( symbol : str ) -> str Normalize a broker symbol name for MT5 API calls. Strips surrounding whitespace while preserving broker-specific casing and suffixes (for example XAUUSDm , US500.cash , or EURUSD.r ). Parameters: Name Type Description Default symbol str Raw symbol name. required Returns: Type Description str Normalized symbol string. Raises: Type Description ValueError If the symbol is empty after normalization. Source code in mt5cli/converters.py 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 def normalize_symbol ( symbol : str ) -> str : \"\"\"Normalize a broker symbol name for MT5 API calls. Strips surrounding whitespace while preserving broker-specific casing and suffixes (for example ``XAUUSDm``, ``US500.cash``, or ``EURUSD.r``). Args: symbol: Raw symbol name. Returns: Normalized symbol string. Raises: ValueError: If the symbol is empty after normalization. \"\"\" normalized = symbol . strip () if not normalized : msg = \"Symbol must not be empty.\" raise ValueError ( msg ) return normalized normalize_symbols \u00b6 normalize_symbols ( symbols : Sequence [ str ]) -> list [ str ] Normalize a sequence of broker symbol names. Parameters: Name Type Description Default symbols Sequence [ str ] Raw symbol names. required Returns: Type Description list [ str ] List of normalized, de-duplicated symbols preserving first-seen order. Source code in mt5cli/converters.py 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 def normalize_symbols ( symbols : Sequence [ str ]) -> list [ str ]: \"\"\"Normalize a sequence of broker symbol names. Args: symbols: Raw symbol names. Returns: List of normalized, de-duplicated symbols preserving first-seen order. \"\"\" seen : set [ str ] = set () resolved : list [ str ] = [] for symbol in symbols : normalized = normalize_symbol ( symbol ) if normalized not in seen : seen . add ( normalized ) resolved . append ( normalized ) return resolved parse_date_range \u00b6 parse_date_range ( date_from : datetime | str , date_to : datetime | str ) -> tuple [ datetime , datetime ] Parse and validate an inclusive UTC date range. Parameters: Name Type Description Default date_from datetime | str Range start as datetime or ISO 8601 string. required date_to datetime | str Range end as datetime or ISO 8601 string. required Returns: Type Description tuple [ datetime , datetime ] Tuple of UTC-aware (start, end) datetimes. Raises: Type Description ValueError If date_from is after date_to . Source code in mt5cli/converters.py 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 def parse_date_range ( date_from : datetime | str , date_to : datetime | str , ) -> tuple [ datetime , datetime ]: \"\"\"Parse and validate an inclusive UTC date range. Args: date_from: Range start as datetime or ISO 8601 string. date_to: Range end as datetime or ISO 8601 string. Returns: Tuple of UTC-aware ``(start, end)`` datetimes. Raises: ValueError: If ``date_from`` is after ``date_to``. \"\"\" start = ensure_utc ( date_from ) end = ensure_utc ( date_to ) if start > end : msg = ( f \"date_from ( { start . isoformat () } ) must not be after \" f \"date_to ( { end . isoformat () } ).\" ) raise ValueError ( msg ) return start , end parse_datetime \u00b6 parse_datetime ( value : str ) -> datetime Parse an ISO 8601 datetime string to a timezone-aware datetime. Parameters: Name Type Description Default value str ISO 8601 datetime string (e.g., '2024-01-01' or '2024-01-01T12:00:00+00:00'). required Returns: Type Description datetime Parsed datetime with UTC timezone if no timezone is specified. Raises: Type Description ValueError If the string cannot be parsed. Source code in mt5cli/utils.py 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 def parse_datetime ( value : str ) -> datetime : \"\"\"Parse an ISO 8601 datetime string to a timezone-aware datetime. Args: value: ISO 8601 datetime string (e.g., '2024-01-01' or '2024-01-01T12:00:00+00:00'). Returns: Parsed datetime with UTC timezone if no timezone is specified. Raises: ValueError: If the string cannot be parsed. \"\"\" try : dt = datetime . fromisoformat ( value ) except ValueError : msg = f \"Invalid datetime format: ' { value } '. Use ISO 8601 format.\" raise ValueError ( msg ) from None if dt . tzinfo is None : dt = dt . replace ( tzinfo = UTC ) return dt parse_tick_flags \u00b6 parse_tick_flags ( value : object ) -> int Parse tick flags string or integer value. Parameters: Name Type Description Default value object Tick flag name (ALL, INFO, TRADE, COPY_TICKS_*) or integer value. required Returns: Type Description int Integer tick flag value compatible with MetaTrader 5 COPY_TICKS_* . Raises: Type Description ValueError If the flag is invalid. Source code in mt5cli/utils.py 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 def parse_tick_flags ( value : object ) -> int : \"\"\"Parse tick flags string or integer value. Args: value: Tick flag name (ALL, INFO, TRADE, COPY_TICKS_*) or integer value. Returns: Integer tick flag value compatible with MetaTrader 5 ``COPY_TICKS_*``. Raises: ValueError: If the flag is invalid. \"\"\" try : return _parse_copy_ticks ( value ) except ValueError : display = value if isinstance ( value , str ) else repr ( value ) valid = \", \" . join ( _TICK_FLAG_NAMES ) msg = ( f \"Invalid tick flags: ' { display } '. \" f \"Use one of: { valid } , or a supported integer.\" ) raise ValueError ( msg ) from None parse_timeframe \u00b6 parse_timeframe ( value : object ) -> int Parse a timeframe string or integer value. Parameters: Name Type Description Default value object Timeframe name (e.g., 'M1', 'H1', 'D1') or integer value. required Returns: Type Description int Integer timeframe value. Raises: Type Description ValueError If the timeframe is invalid. Source code in mt5cli/utils.py 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 def parse_timeframe ( value : object ) -> int : \"\"\"Parse a timeframe string or integer value. Args: value: Timeframe name (e.g., 'M1', 'H1', 'D1') or integer value. Returns: Integer timeframe value. Raises: ValueError: If the timeframe is invalid. \"\"\" try : return _parse_timeframe ( value ) except ValueError : display = value if isinstance ( value , str ) else repr ( value ) valid = \", \" . join ( TIMEFRAME_NAMES ) msg = ( f \"Invalid timeframe: ' { display } '. \" f \"Use one of: { valid } , or a supported integer.\" ) raise ValueError ( msg ) from None recent_window \u00b6 recent_window ( * , hours : float | None = None , seconds : float | None = None , date_to : datetime | str | None = None , ) -> tuple [ datetime , datetime ] Build a trailing UTC window ending at date_to or now. Exactly one of hours or seconds must be provided. Parameters: Name Type Description Default hours float | None Trailing window length in hours. None seconds float | None Trailing window length in seconds. None date_to datetime | str | None Window end. Defaults to current UTC time. None Returns: Type Description tuple [ datetime , datetime ] Tuple of UTC-aware (start, end) datetimes. Raises: Type Description ValueError If neither or both window lengths are provided, or if a length is not positive. Source code in mt5cli/converters.py 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 def recent_window ( * , hours : float | None = None , seconds : float | None = None , date_to : datetime | str | None = None , ) -> tuple [ datetime , datetime ]: \"\"\"Build a trailing UTC window ending at ``date_to`` or now. Exactly one of ``hours`` or ``seconds`` must be provided. Args: hours: Trailing window length in hours. seconds: Trailing window length in seconds. date_to: Window end. Defaults to current UTC time. Returns: Tuple of UTC-aware ``(start, end)`` datetimes. Raises: ValueError: If neither or both window lengths are provided, or if a length is not positive. \"\"\" if ( hours is None ) == ( seconds is None ): msg = \"Provide exactly one of hours or seconds.\" raise ValueError ( msg ) if hours is not None : length = timedelta ( hours = hours ) else : length = timedelta ( seconds = seconds if seconds is not None else 0 ) if length . total_seconds () <= 0 : msg = \"Window length must be positive.\" raise ValueError ( msg ) end = ensure_utc ( date_to ) if date_to is not None else datetime . now ( UTC ) return end - length , end","title":"Converters"},{"location":"api/converters/#converters","text":"","title":"Converters"},{"location":"api/converters/#mt5cli.converters","text":"Shared conversion helpers for MT5 symbols, timeframes, and date ranges.","title":"converters"},{"location":"api/converters/#mt5cli.converters.__all__","text":"__all__ = [ \"ensure_utc\" , \"granularity_name\" , \"normalize_symbol\" , \"normalize_symbols\" , \"parse_date_range\" , \"parse_datetime\" , \"parse_tick_flags\" , \"parse_timeframe\" , \"recent_window\" , ]","title":"__all__"},{"location":"api/converters/#mt5cli.converters.ensure_utc","text":"ensure_utc ( value : datetime | str ) -> datetime Return a timezone-aware UTC datetime. Parameters: Name Type Description Default value datetime | str Datetime instance or ISO 8601 string. required Returns: Type Description datetime UTC-aware datetime. Source code in mt5cli/converters.py 69 70 71 72 73 74 75 76 77 78 79 80 81 82 def ensure_utc ( value : datetime | str ) -> datetime : \"\"\"Return a timezone-aware UTC datetime. Args: value: Datetime instance or ISO 8601 string. Returns: UTC-aware datetime. \"\"\" if isinstance ( value , str ): return parse_datetime ( value ) if value . tzinfo is None : return value . replace ( tzinfo = UTC ) return value . astimezone ( UTC )","title":"ensure_utc"},{"location":"api/converters/#mt5cli.converters.granularity_name","text":"granularity_name ( timeframe : int | str ) -> str Return a short granularity label for a timeframe integer or name. Parameters: Name Type Description Default timeframe int | str MT5 timeframe as integer or name (for example M1 ). required Returns: Type Description str Short name such as M1 or the stringified integer when unknown. Source code in mt5cli/converters.py 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 def granularity_name ( timeframe : int | str ) -> str : \"\"\"Return a short granularity label for a timeframe integer or name. Args: timeframe: MT5 timeframe as integer or name (for example ``M1``). Returns: Short name such as ``M1`` or the stringified integer when unknown. \"\"\" tf = parse_timeframe ( timeframe ) try : name = _get_timeframe_name ( tf ) except ValueError : return str ( tf ) return name . removeprefix ( \"TIMEFRAME_\" )","title":"granularity_name"},{"location":"api/converters/#mt5cli.converters.normalize_symbol","text":"normalize_symbol ( symbol : str ) -> str Normalize a broker symbol name for MT5 API calls. Strips surrounding whitespace while preserving broker-specific casing and suffixes (for example XAUUSDm , US500.cash , or EURUSD.r ). Parameters: Name Type Description Default symbol str Raw symbol name. required Returns: Type Description str Normalized symbol string. Raises: Type Description ValueError If the symbol is empty after normalization. Source code in mt5cli/converters.py 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 def normalize_symbol ( symbol : str ) -> str : \"\"\"Normalize a broker symbol name for MT5 API calls. Strips surrounding whitespace while preserving broker-specific casing and suffixes (for example ``XAUUSDm``, ``US500.cash``, or ``EURUSD.r``). Args: symbol: Raw symbol name. Returns: Normalized symbol string. Raises: ValueError: If the symbol is empty after normalization. \"\"\" normalized = symbol . strip () if not normalized : msg = \"Symbol must not be empty.\" raise ValueError ( msg ) return normalized","title":"normalize_symbol"},{"location":"api/converters/#mt5cli.converters.normalize_symbols","text":"normalize_symbols ( symbols : Sequence [ str ]) -> list [ str ] Normalize a sequence of broker symbol names. Parameters: Name Type Description Default symbols Sequence [ str ] Raw symbol names. required Returns: Type Description list [ str ] List of normalized, de-duplicated symbols preserving first-seen order. Source code in mt5cli/converters.py 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 def normalize_symbols ( symbols : Sequence [ str ]) -> list [ str ]: \"\"\"Normalize a sequence of broker symbol names. Args: symbols: Raw symbol names. Returns: List of normalized, de-duplicated symbols preserving first-seen order. \"\"\" seen : set [ str ] = set () resolved : list [ str ] = [] for symbol in symbols : normalized = normalize_symbol ( symbol ) if normalized not in seen : seen . add ( normalized ) resolved . append ( normalized ) return resolved","title":"normalize_symbols"},{"location":"api/converters/#mt5cli.converters.parse_date_range","text":"parse_date_range ( date_from : datetime | str , date_to : datetime | str ) -> tuple [ datetime , datetime ] Parse and validate an inclusive UTC date range. Parameters: Name Type Description Default date_from datetime | str Range start as datetime or ISO 8601 string. required date_to datetime | str Range end as datetime or ISO 8601 string. required Returns: Type Description tuple [ datetime , datetime ] Tuple of UTC-aware (start, end) datetimes. Raises: Type Description ValueError If date_from is after date_to . Source code in mt5cli/converters.py 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 def parse_date_range ( date_from : datetime | str , date_to : datetime | str , ) -> tuple [ datetime , datetime ]: \"\"\"Parse and validate an inclusive UTC date range. Args: date_from: Range start as datetime or ISO 8601 string. date_to: Range end as datetime or ISO 8601 string. Returns: Tuple of UTC-aware ``(start, end)`` datetimes. Raises: ValueError: If ``date_from`` is after ``date_to``. \"\"\" start = ensure_utc ( date_from ) end = ensure_utc ( date_to ) if start > end : msg = ( f \"date_from ( { start . isoformat () } ) must not be after \" f \"date_to ( { end . isoformat () } ).\" ) raise ValueError ( msg ) return start , end","title":"parse_date_range"},{"location":"api/converters/#mt5cli.converters.parse_datetime","text":"parse_datetime ( value : str ) -> datetime Parse an ISO 8601 datetime string to a timezone-aware datetime. Parameters: Name Type Description Default value str ISO 8601 datetime string (e.g., '2024-01-01' or '2024-01-01T12:00:00+00:00'). required Returns: Type Description datetime Parsed datetime with UTC timezone if no timezone is specified. Raises: Type Description ValueError If the string cannot be parsed. Source code in mt5cli/utils.py 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 def parse_datetime ( value : str ) -> datetime : \"\"\"Parse an ISO 8601 datetime string to a timezone-aware datetime. Args: value: ISO 8601 datetime string (e.g., '2024-01-01' or '2024-01-01T12:00:00+00:00'). Returns: Parsed datetime with UTC timezone if no timezone is specified. Raises: ValueError: If the string cannot be parsed. \"\"\" try : dt = datetime . fromisoformat ( value ) except ValueError : msg = f \"Invalid datetime format: ' { value } '. Use ISO 8601 format.\" raise ValueError ( msg ) from None if dt . tzinfo is None : dt = dt . replace ( tzinfo = UTC ) return dt","title":"parse_datetime"},{"location":"api/converters/#mt5cli.converters.parse_tick_flags","text":"parse_tick_flags ( value : object ) -> int Parse tick flags string or integer value. Parameters: Name Type Description Default value object Tick flag name (ALL, INFO, TRADE, COPY_TICKS_*) or integer value. required Returns: Type Description int Integer tick flag value compatible with MetaTrader 5 COPY_TICKS_* . Raises: Type Description ValueError If the flag is invalid. Source code in mt5cli/utils.py 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 def parse_tick_flags ( value : object ) -> int : \"\"\"Parse tick flags string or integer value. Args: value: Tick flag name (ALL, INFO, TRADE, COPY_TICKS_*) or integer value. Returns: Integer tick flag value compatible with MetaTrader 5 ``COPY_TICKS_*``. Raises: ValueError: If the flag is invalid. \"\"\" try : return _parse_copy_ticks ( value ) except ValueError : display = value if isinstance ( value , str ) else repr ( value ) valid = \", \" . join ( _TICK_FLAG_NAMES ) msg = ( f \"Invalid tick flags: ' { display } '. \" f \"Use one of: { valid } , or a supported integer.\" ) raise ValueError ( msg ) from None","title":"parse_tick_flags"},{"location":"api/converters/#mt5cli.converters.parse_timeframe","text":"parse_timeframe ( value : object ) -> int Parse a timeframe string or integer value. Parameters: Name Type Description Default value object Timeframe name (e.g., 'M1', 'H1', 'D1') or integer value. required Returns: Type Description int Integer timeframe value. Raises: Type Description ValueError If the timeframe is invalid. Source code in mt5cli/utils.py 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 def parse_timeframe ( value : object ) -> int : \"\"\"Parse a timeframe string or integer value. Args: value: Timeframe name (e.g., 'M1', 'H1', 'D1') or integer value. Returns: Integer timeframe value. Raises: ValueError: If the timeframe is invalid. \"\"\" try : return _parse_timeframe ( value ) except ValueError : display = value if isinstance ( value , str ) else repr ( value ) valid = \", \" . join ( TIMEFRAME_NAMES ) msg = ( f \"Invalid timeframe: ' { display } '. \" f \"Use one of: { valid } , or a supported integer.\" ) raise ValueError ( msg ) from None","title":"parse_timeframe"},{"location":"api/converters/#mt5cli.converters.recent_window","text":"recent_window ( * , hours : float | None = None , seconds : float | None = None , date_to : datetime | str | None = None , ) -> tuple [ datetime , datetime ] Build a trailing UTC window ending at date_to or now. Exactly one of hours or seconds must be provided. Parameters: Name Type Description Default hours float | None Trailing window length in hours. None seconds float | None Trailing window length in seconds. None date_to datetime | str | None Window end. Defaults to current UTC time. None Returns: Type Description tuple [ datetime , datetime ] Tuple of UTC-aware (start, end) datetimes. Raises: Type Description ValueError If neither or both window lengths are provided, or if a length is not positive. Source code in mt5cli/converters.py 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 def recent_window ( * , hours : float | None = None , seconds : float | None = None , date_to : datetime | str | None = None , ) -> tuple [ datetime , datetime ]: \"\"\"Build a trailing UTC window ending at ``date_to`` or now. Exactly one of ``hours`` or ``seconds`` must be provided. Args: hours: Trailing window length in hours. seconds: Trailing window length in seconds. date_to: Window end. Defaults to current UTC time. Returns: Tuple of UTC-aware ``(start, end)`` datetimes. Raises: ValueError: If neither or both window lengths are provided, or if a length is not positive. \"\"\" if ( hours is None ) == ( seconds is None ): msg = \"Provide exactly one of hours or seconds.\" raise ValueError ( msg ) if hours is not None : length = timedelta ( hours = hours ) else : length = timedelta ( seconds = seconds if seconds is not None else 0 ) if length . total_seconds () <= 0 : msg = \"Window length must be positive.\" raise ValueError ( msg ) end = ensure_utc ( date_to ) if date_to is not None else datetime . now ( UTC ) return end - length , end","title":"recent_window"},{"location":"api/exceptions/","text":"Exceptions \u00b6 mt5cli.exceptions \u00b6 Normalized exception types for MT5 and mt5cli operations. T module-attribute \u00b6 T = TypeVar ( 'T' ) __all__ module-attribute \u00b6 __all__ = [ \"Mt5CliError\" , \"Mt5ConnectionError\" , \"Mt5OperationError\" , \"Mt5SchemaError\" , \"call_with_normalized_errors\" , \"is_recoverable_mt5_error\" , \"normalize_mt5_exception\" , ] Mt5CliError \u00b6 Bases: Exception Base exception for mt5cli public API errors. Mt5ConnectionError \u00b6 Bases: Mt5CliError Raised when MT5 initialization, login, or shutdown fails. Mt5OperationError \u00b6 Bases: Mt5CliError Raised when an MT5 data or trading operation fails. Mt5SchemaError \u00b6 Bases: Mt5CliError Raised when a DataFrame does not match an expected dataset schema. call_with_normalized_errors \u00b6 call_with_normalized_errors ( fn : Callable [[], T ]) -> T Run fn and map recoverable MT5 errors to mt5cli types. Parameters: Name Type Description Default fn Callable [[], T ] Callable performing MT5 work. required Returns: Type Description T Value returned by fn . Source code in mt5cli/exceptions.py 77 78 79 80 81 82 83 84 85 86 87 88 89 90 def call_with_normalized_errors ( fn : Callable [[], T ]) -> T : \"\"\"Run ``fn`` and map recoverable MT5 errors to mt5cli types. Args: fn: Callable performing MT5 work. Returns: Value returned by ``fn``. \"\"\" try : return fn () except _RECOVERABLE_MT5_ERRORS as exc : normalized = normalize_mt5_exception ( exc ) raise normalized from exc is_recoverable_mt5_error \u00b6 is_recoverable_mt5_error ( exc : BaseException ) -> bool Return whether an exception is a transient MT5 failure worth retrying. Parameters: Name Type Description Default exc BaseException Exception raised by MT5 or pdmt5. required Returns: Type Description bool True for Mt5RuntimeError and Mt5TradingError . Source code in mt5cli/exceptions.py 46 47 48 49 50 51 52 53 54 55 def is_recoverable_mt5_error ( exc : BaseException ) -> bool : \"\"\"Return whether an exception is a transient MT5 failure worth retrying. Args: exc: Exception raised by MT5 or pdmt5. Returns: True for ``Mt5RuntimeError`` and ``Mt5TradingError``. \"\"\" return isinstance ( exc , _RECOVERABLE_MT5_ERRORS ) normalize_mt5_exception \u00b6 normalize_mt5_exception ( exc : BaseException ) -> Mt5CliError Map pdmt5/MT5 exceptions to stable mt5cli exception types. Parameters: Name Type Description Default exc BaseException Original exception from MT5 or pdmt5. required Returns: Type Description Mt5CliError Mt5ConnectionError for runtime failures, Mt5OperationError for Mt5CliError trading failures, or the original exception when it is not recognized. Source code in mt5cli/exceptions.py 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 def normalize_mt5_exception ( exc : BaseException ) -> Mt5CliError : \"\"\"Map pdmt5/MT5 exceptions to stable mt5cli exception types. Args: exc: Original exception from MT5 or pdmt5. Returns: ``Mt5ConnectionError`` for runtime failures, ``Mt5OperationError`` for trading failures, or the original exception when it is not recognized. \"\"\" if isinstance ( exc , Mt5TradingError ): return Mt5OperationError ( str ( exc )) if isinstance ( exc , Mt5RuntimeError ): return Mt5ConnectionError ( str ( exc )) if isinstance ( exc , Mt5CliError ): return exc return Mt5CliError ( str ( exc ))","title":"Exceptions"},{"location":"api/exceptions/#exceptions","text":"","title":"Exceptions"},{"location":"api/exceptions/#mt5cli.exceptions","text":"Normalized exception types for MT5 and mt5cli operations.","title":"exceptions"},{"location":"api/exceptions/#mt5cli.exceptions.T","text":"T = TypeVar ( 'T' )","title":"T"},{"location":"api/exceptions/#mt5cli.exceptions.__all__","text":"__all__ = [ \"Mt5CliError\" , \"Mt5ConnectionError\" , \"Mt5OperationError\" , \"Mt5SchemaError\" , \"call_with_normalized_errors\" , \"is_recoverable_mt5_error\" , \"normalize_mt5_exception\" , ]","title":"__all__"},{"location":"api/exceptions/#mt5cli.exceptions.Mt5CliError","text":"Bases: Exception Base exception for mt5cli public API errors.","title":"Mt5CliError"},{"location":"api/exceptions/#mt5cli.exceptions.Mt5ConnectionError","text":"Bases: Mt5CliError Raised when MT5 initialization, login, or shutdown fails.","title":"Mt5ConnectionError"},{"location":"api/exceptions/#mt5cli.exceptions.Mt5OperationError","text":"Bases: Mt5CliError Raised when an MT5 data or trading operation fails.","title":"Mt5OperationError"},{"location":"api/exceptions/#mt5cli.exceptions.Mt5SchemaError","text":"Bases: Mt5CliError Raised when a DataFrame does not match an expected dataset schema.","title":"Mt5SchemaError"},{"location":"api/exceptions/#mt5cli.exceptions.call_with_normalized_errors","text":"call_with_normalized_errors ( fn : Callable [[], T ]) -> T Run fn and map recoverable MT5 errors to mt5cli types. Parameters: Name Type Description Default fn Callable [[], T ] Callable performing MT5 work. required Returns: Type Description T Value returned by fn . Source code in mt5cli/exceptions.py 77 78 79 80 81 82 83 84 85 86 87 88 89 90 def call_with_normalized_errors ( fn : Callable [[], T ]) -> T : \"\"\"Run ``fn`` and map recoverable MT5 errors to mt5cli types. Args: fn: Callable performing MT5 work. Returns: Value returned by ``fn``. \"\"\" try : return fn () except _RECOVERABLE_MT5_ERRORS as exc : normalized = normalize_mt5_exception ( exc ) raise normalized from exc","title":"call_with_normalized_errors"},{"location":"api/exceptions/#mt5cli.exceptions.is_recoverable_mt5_error","text":"is_recoverable_mt5_error ( exc : BaseException ) -> bool Return whether an exception is a transient MT5 failure worth retrying. Parameters: Name Type Description Default exc BaseException Exception raised by MT5 or pdmt5. required Returns: Type Description bool True for Mt5RuntimeError and Mt5TradingError . Source code in mt5cli/exceptions.py 46 47 48 49 50 51 52 53 54 55 def is_recoverable_mt5_error ( exc : BaseException ) -> bool : \"\"\"Return whether an exception is a transient MT5 failure worth retrying. Args: exc: Exception raised by MT5 or pdmt5. Returns: True for ``Mt5RuntimeError`` and ``Mt5TradingError``. \"\"\" return isinstance ( exc , _RECOVERABLE_MT5_ERRORS )","title":"is_recoverable_mt5_error"},{"location":"api/exceptions/#mt5cli.exceptions.normalize_mt5_exception","text":"normalize_mt5_exception ( exc : BaseException ) -> Mt5CliError Map pdmt5/MT5 exceptions to stable mt5cli exception types. Parameters: Name Type Description Default exc BaseException Original exception from MT5 or pdmt5. required Returns: Type Description Mt5CliError Mt5ConnectionError for runtime failures, Mt5OperationError for Mt5CliError trading failures, or the original exception when it is not recognized. Source code in mt5cli/exceptions.py 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 def normalize_mt5_exception ( exc : BaseException ) -> Mt5CliError : \"\"\"Map pdmt5/MT5 exceptions to stable mt5cli exception types. Args: exc: Original exception from MT5 or pdmt5. Returns: ``Mt5ConnectionError`` for runtime failures, ``Mt5OperationError`` for trading failures, or the original exception when it is not recognized. \"\"\" if isinstance ( exc , Mt5TradingError ): return Mt5OperationError ( str ( exc )) if isinstance ( exc , Mt5RuntimeError ): return Mt5ConnectionError ( str ( exc )) if isinstance ( exc , Mt5CliError ): return exc return Mt5CliError ( str ( exc ))","title":"normalize_mt5_exception"},{"location":"api/history/","text":"History Collection (SQLite) \u00b6 mt5cli.history \u00b6 SQLite storage helpers for the collect-history incremental data pipeline. DEFAULT_HISTORY_TIMEFRAMES module-attribute \u00b6 DEFAULT_HISTORY_TIMEFRAMES : tuple [ str , ... ] = ( TIMEFRAME_NAMES ) SqliteConnOrPath module-attribute \u00b6 SqliteConnOrPath = Connection | Path | str logger module-attribute \u00b6 logger = getLogger ( __name__ ) DedupScope dataclass \u00b6 DedupScope ( where : str , params : tuple [ object , ... ], required_columns : frozenset [ str ], ) Scoped deduplication predicate and the columns it references. Attributes: Name Type Description where str SQL predicate appended to the duplicate-removal query. params tuple [ object , ...] Parameters bound to the scope predicate. required_columns frozenset [ str ] Columns that must be present in the written table for the scope to run. params instance-attribute \u00b6 params : tuple [ object , ... ] required_columns instance-attribute \u00b6 required_columns : frozenset [ str ] where instance-attribute \u00b6 where : str RateTarget dataclass \u00b6 RateTarget ( symbol : str | None , timeframe : int | str ) A single rate series identified by symbol and timeframe. Attributes: Name Type Description symbol str | None MT5 symbol name, or None when the rate series is addressed only by an explicit table (for example a custom SQLite view). timeframe int | str MT5 timeframe as an integer or name (for example M1 ). symbol instance-attribute \u00b6 symbol : str | None timeframe instance-attribute \u00b6 timeframe : int | str timeframe_int property \u00b6 timeframe_int : int Return the timeframe as its integer MT5 value. __post_init__ \u00b6 __post_init__ () -> None Normalize accepted timeframe aliases to the stored integer value. Source code in mt5cli/history.py 544 545 546 547 def __post_init__ ( self ) -> None : \"\"\"Normalize accepted timeframe aliases to the stored integer value.\"\"\" if not isinstance ( self . timeframe , int ): object . __setattr__ ( self , \"timeframe\" , parse_timeframe ( self . timeframe )) append_dataframe \u00b6 append_dataframe ( conn : Connection , frame : DataFrame , table_name : str , if_exists : IfExists , ) -> bool Append a DataFrame to SQLite when it has a schema. Returns: Type Description bool True if a table was written, False if the frame had no columns. Source code in mt5cli/history.py 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 def append_dataframe ( conn : sqlite3 . Connection , frame : pd . DataFrame , table_name : str , if_exists : IfExists , ) -> bool : \"\"\"Append a DataFrame to SQLite when it has a schema. Returns: True if a table was written, False if the frame had no columns. \"\"\" if len ( frame . columns ) == 0 : logger . warning ( \"Skipping %s : dataset returned no columns\" , table_name ) return False frame . to_sql ( # type: ignore[reportUnknownMemberType] table_name , conn , if_exists = if_exists . value , index = False , chunksize = 50_000 , ) return True augment_written_columns_from_sqlite \u00b6 augment_written_columns_from_sqlite ( conn : Connection , datasets : set [ Dataset ], written_columns : dict [ Dataset , set [ str ]], ) -> None Add existing table columns to the written column map. Source code in mt5cli/history.py 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 def augment_written_columns_from_sqlite ( conn : sqlite3 . Connection , datasets : set [ Dataset ], written_columns : dict [ Dataset , set [ str ]], ) -> None : \"\"\"Add existing table columns to the written column map.\"\"\" for dataset in datasets : columns = get_table_columns ( conn , dataset . table_name ) if not columns : continue if dataset in written_columns : written_columns [ dataset ] . update ( columns ) else : written_columns [ dataset ] = columns build_rate_targets \u00b6 build_rate_targets ( symbols : Sequence [ str ], timeframes : Sequence [ int | str ], * , allow_missing_symbol : bool = False , ) -> list [ RateTarget ] Build rate targets for every symbol and timeframe combination. Parameters: Name Type Description Default symbols Sequence [ str ] MT5 symbol names. May be empty when allow_missing_symbol . required timeframes Sequence [ int | str ] MT5 timeframes as integers or names (for example M1 ). required allow_missing_symbol bool When True and symbols is empty, build targets with symbol=None for each timeframe instead of raising. False Returns: Type Description list [ RateTarget ] Targets in row-major order: every timeframe for the first symbol, then list [ RateTarget ] every timeframe for the next symbol, and so on. Raises: Type Description ValueError If timeframes is empty, or symbols is empty and allow_missing_symbol is False. Source code in mt5cli/history.py 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 def build_rate_targets ( symbols : Sequence [ str ], timeframes : Sequence [ int | str ], * , allow_missing_symbol : bool = False , ) -> list [ RateTarget ]: \"\"\"Build rate targets for every symbol and timeframe combination. Args: symbols: MT5 symbol names. May be empty when ``allow_missing_symbol``. timeframes: MT5 timeframes as integers or names (for example ``M1``). allow_missing_symbol: When True and ``symbols`` is empty, build targets with ``symbol=None`` for each timeframe instead of raising. Returns: Targets in row-major order: every timeframe for the first symbol, then every timeframe for the next symbol, and so on. Raises: ValueError: If ``timeframes`` is empty, or ``symbols`` is empty and ``allow_missing_symbol`` is False. \"\"\" if not timeframes : msg = \"At least one timeframe is required.\" raise ValueError ( msg ) if not symbols : if not allow_missing_symbol : msg = \"At least one symbol is required.\" raise ValueError ( msg ) return [ RateTarget ( symbol = None , timeframe = tf ) for tf in timeframes ] return [ RateTarget ( symbol = symbol , timeframe = tf ) for symbol in symbols for tf in timeframes ] build_rate_view_name \u00b6 build_rate_view_name ( * , symbol : str , granularity : str , granularity_count : int , timeframe : int , ) -> str Return a collision-free offline optimize view name. View names always include the timeframe integer after a __ separator so a symbol such as EURUSD_M1 cannot collide with EURUSD at timeframe M1 . Source code in mt5cli/history.py 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 def build_rate_view_name ( * , symbol : str , granularity : str , granularity_count : int , timeframe : int , ) -> str : \"\"\"Return a collision-free offline optimize view name. View names always include the timeframe integer after a ``__`` separator so a symbol such as ``EURUSD_M1`` cannot collide with ``EURUSD`` at timeframe ``M1``. \"\"\" if granularity_count == 1 : return f \"rate_ { symbol } __ { timeframe } \" return f \"rate_ { symbol } __ { granularity } _ { timeframe } \" create_cash_events_view \u00b6 create_cash_events_view ( conn : Connection , deals_columns : set [ str ] ) -> bool Create the cash_events SQLite view derived from history_deals. Returns: Type Description bool True if the view was created, False if required columns are missing. Source code in mt5cli/history.py 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 def create_cash_events_view ( conn : sqlite3 . Connection , deals_columns : set [ str ], ) -> bool : \"\"\"Create the cash_events SQLite view derived from history_deals. Returns: True if the view was created, False if required columns are missing. \"\"\" if \"type\" not in deals_columns : logger . warning ( \"Skipping cash_events view: history_deals.type is missing\" ) return False conn . execute ( \"DROP VIEW IF EXISTS cash_events\" ) conn . execute ( \"CREATE VIEW cash_events AS\" # noqa: S608 f \" SELECT * FROM history_deals WHERE type NOT IN { _TRADE_DEAL_TYPES_SQL } \" , ) return True create_history_indexes \u00b6 create_history_indexes ( conn : Connection , written_columns : dict [ Dataset , set [ str ]], ) -> None Create useful indexes for collected history tables when present. Source code in mt5cli/history.py 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 def create_history_indexes ( conn : sqlite3 . Connection , written_columns : dict [ Dataset , set [ str ]], ) -> None : \"\"\"Create useful indexes for collected history tables when present.\"\"\" if { \"symbol\" , \"timeframe\" , \"time\" } . issubset ( written_columns . get ( Dataset . rates , set ()), ): conn . execute ( \"CREATE INDEX IF NOT EXISTS idx_rates_symbol_timeframe_time\" \" ON rates(symbol, timeframe, time)\" , ) if { \"symbol\" , \"time\" } . issubset ( written_columns . get ( Dataset . ticks , set ())): conn . execute ( \"CREATE INDEX IF NOT EXISTS idx_ticks_symbol_time ON ticks(symbol, time)\" , ) if { \"position_id\" , \"symbol\" } . issubset ( written_columns . get ( Dataset . history_deals , set ()), ): conn . execute ( \"CREATE INDEX IF NOT EXISTS idx_history_deals_position_symbol\" \" ON history_deals(position_id, symbol)\" , ) create_positions_reconstructed_view \u00b6 create_positions_reconstructed_view ( conn : Connection , deals_columns : set [ str ] ) -> bool Create the positions_reconstructed SQLite view derived from history_deals. Returns: Type Description bool True if the view was created, False if required columns are missing. Source code in mt5cli/history.py 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 def create_positions_reconstructed_view ( conn : sqlite3 . Connection , deals_columns : set [ str ], ) -> bool : \"\"\"Create the positions_reconstructed SQLite view derived from history_deals. Returns: True if the view was created, False if required columns are missing. \"\"\" if not _POSITIONS_VIEW_REQUIRED_COLUMNS . issubset ( deals_columns ): missing = \", \" . join ( sorted ( _POSITIONS_VIEW_REQUIRED_COLUMNS - deals_columns )) logger . warning ( \"Skipping positions_reconstructed view: history_deals missing columns: %s \" , missing , ) return False conn . execute ( \"DROP VIEW IF EXISTS positions_reconstructed\" ) conn . execute ( \"CREATE VIEW positions_reconstructed AS\" # noqa: S608 \" SELECT\" \" position_id,\" \" symbol,\" \" MIN(CASE WHEN entry = 0 THEN time END) AS open_time,\" \" MAX(CASE WHEN entry IN (1, 2, 3) THEN time END) AS close_time,\" \" MIN(CASE WHEN entry = 0 THEN type END) AS direction,\" \" SUM(CASE WHEN entry = 0 THEN volume ELSE 0 END) AS volume_open,\" \" SUM(CASE WHEN entry IN (1, 2, 3) THEN volume ELSE 0 END) AS volume_close,\" \" SUM(CASE WHEN entry = 2 THEN volume ELSE 0 END) AS volume_reversal,\" \" CASE\" \" WHEN SUM(CASE WHEN entry = 0 THEN volume ELSE 0 END) > 0\" \" THEN SUM(CASE WHEN entry = 0 THEN price * volume ELSE 0 END)\" \" / SUM(CASE WHEN entry = 0 THEN volume ELSE 0 END)\" \" END AS open_price,\" \" CASE\" \" WHEN SUM(CASE WHEN entry IN (1, 2, 3) THEN volume ELSE 0 END) > 0\" \" THEN SUM(CASE WHEN entry IN (1, 2, 3) THEN price * volume ELSE 0 END)\" \" / SUM(CASE WHEN entry IN (1, 2, 3) THEN volume ELSE 0 END)\" \" END AS close_price,\" \" SUM(profit) AS total_profit,\" \" SUM(CASE WHEN entry = 2 THEN 1 ELSE 0 END) AS reversal_count,\" \" COUNT(*) AS deals_count\" \" FROM history_deals\" f \" WHERE type IN { _TRADE_DEAL_TYPES_SQL } AND position_id != 0\" \" GROUP BY position_id, symbol\" \" HAVING SUM(CASE WHEN entry IN (1, 2, 3) THEN 1 ELSE 0 END) > 0\" , ) return True create_rate_compatibility_views \u00b6 create_rate_compatibility_views ( conn : Connection ) -> None Create rate compatibility views from the normalized rates table. Source code in mt5cli/history.py 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 def create_rate_compatibility_views ( conn : sqlite3 . Connection ) -> None : \"\"\"Create rate compatibility views from the normalized rates table.\"\"\" columns = get_table_columns ( conn , Dataset . rates . table_name ) if not { \"symbol\" , \"timeframe\" , \"time\" } . issubset ( columns ): return drop_rate_compatibility_views ( conn ) select_columns = sorted ( columns - { \"symbol\" , \"timeframe\" }) quoted_columns = \", \" . join ( f '\" { column } \"' for column in select_columns ) rows = conn . execute ( \"SELECT DISTINCT symbol, timeframe FROM rates ORDER BY symbol, timeframe\" , ) . fetchall () timeframes_by_symbol : dict [ str , list [ int ]] = {} for symbol , timeframe in rows : timeframes_by_symbol . setdefault ( str ( symbol ), []) . append ( int ( timeframe )) for symbol , timeframes in timeframes_by_symbol . items (): for timeframe in timeframes : granularity = resolve_granularity_name ( timeframe ) view_name = build_rate_view_name ( symbol = symbol , granularity = granularity , granularity_count = len ( timeframes ), timeframe = timeframe , ) quoted_view_name = quote_sqlite_identifier ( view_name ) escaped_symbol = symbol . replace ( \"'\" , \"''\" ) conn . execute ( f \"CREATE VIEW { quoted_view_name } AS\" # noqa: S608 f \" SELECT { quoted_columns } FROM rates\" f \" WHERE symbol = ' { escaped_symbol } '\" f \" AND timeframe = { timeframe } \" , ) deduplicate_history_tables \u00b6 deduplicate_history_tables ( conn : Connection , written_columns : dict [ Dataset , set [ str ]], written_tables : set [ Dataset ], dedup_scopes : Mapping [ Dataset , Sequence [ DedupScope ]] | None = None , ) -> None Deduplicate appended history tables by stable identifiers. Scopes whose required columns are not present in the written table are skipped. If all scopes for a dataset are skipped, the table receives one unscoped deduplication pass instead. Source code in mt5cli/history.py 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 def deduplicate_history_tables ( conn : sqlite3 . Connection , written_columns : dict [ Dataset , set [ str ]], written_tables : set [ Dataset ], dedup_scopes : Mapping [ Dataset , Sequence [ DedupScope ]] | None = None , ) -> None : \"\"\"Deduplicate appended history tables by stable identifiers. Scopes whose required columns are not present in the written table are skipped. If all scopes for a dataset are skipped, the table receives one unscoped deduplication pass instead. \"\"\" cursor = conn . cursor () for dataset in written_tables : columns = written_columns . get ( dataset , set ()) table = dataset . table_name keys = next ( ( candidate for candidate in _HISTORY_DEDUP_KEYS [ dataset ] if set ( candidate ) . issubset ( columns ) ), None , ) if keys is None : logger . warning ( \"Skipping %s deduplication: no supported key columns\" , table , ) continue raw_scopes : Sequence [ DedupScope ] = ( dedup_scopes . get ( dataset , ()) if dedup_scopes else () ) scopes = [ scope for scope in raw_scopes if scope . required_columns <= columns ] if scopes : for scope in scopes : drop_duplicates_in_table ( cursor , table , list ( keys ), keep = \"last\" , scope_where = scope . where , scope_params = scope . params , ) continue drop_duplicates_in_table ( cursor , table , list ( keys ), keep = \"last\" ) drop_duplicates_in_table \u00b6 drop_duplicates_in_table ( cursor : Cursor , table : str , ids : list [ str ], * , keep : Literal [ \"first\" , \"last\" ] = \"last\" , scope_where : str | None = None , scope_params : tuple [ object , ... ] = (), ) -> None Remove duplicate rows, keeping the first or last ROWID per key group. Raises: Type Description ValueError If the table or column names are invalid. Source code in mt5cli/history.py 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 def drop_duplicates_in_table ( cursor : sqlite3 . Cursor , table : str , ids : list [ str ], * , keep : Literal [ \"first\" , \"last\" ] = \"last\" , scope_where : str | None = None , scope_params : tuple [ object , ... ] = (), ) -> None : \"\"\"Remove duplicate rows, keeping the first or last ROWID per key group. Raises: ValueError: If the table or column names are invalid. \"\"\" if not table . isidentifier (): msg = f \"Invalid table name: { table } \" raise ValueError ( msg ) if invalid := { column for column in ids if not column . isidentifier ()}: msg = f \"Invalid column names: { ', ' . join ( sorted ( invalid )) } \" raise ValueError ( msg ) ids_csv = \", \" . join ( f '\" { column } \"' for column in ids ) rowid_selector = \"MIN\" if keep == \"first\" else \"MAX\" if scope_where : delete_sql = ( f \"DELETE FROM { table } WHERE { scope_where } AND ROWID NOT IN\" # noqa: S608 f \" (SELECT { rowid_selector } (ROWID) FROM { table } WHERE { scope_where } \" f \" GROUP BY { ids_csv } )\" ) cursor . execute ( delete_sql , scope_params + scope_params ) return cursor . execute ( f \"DELETE FROM { table } WHERE ROWID NOT IN\" # noqa: S608 f \" (SELECT { rowid_selector } (ROWID) FROM { table } GROUP BY { ids_csv } )\" , ) drop_forming_rate_bar \u00b6 drop_forming_rate_bar ( df_rate : DataFrame ) -> DataFrame Return closed bars from chronologically ordered MT5 rate data. MetaTrader 5 copy_rates_from_pos(start_pos=0) includes the still-forming current bar as the last row. Slice it off so downstream logic only sees completed bars. Empty frames and single-row frames return empty results. Parameters: Name Type Description Default df_rate DataFrame Rate data ordered oldest-to-newest with the forming bar last. required Returns: Type Description DataFrame A new DataFrame with all rows except the last. Index and columns are DataFrame preserved. The input frame is not modified. Source code in mt5cli/history.py 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 def drop_forming_rate_bar ( df_rate : pd . DataFrame ) -> pd . DataFrame : \"\"\"Return closed bars from chronologically ordered MT5 rate data. MetaTrader 5 ``copy_rates_from_pos(start_pos=0)`` includes the still-forming current bar as the last row. Slice it off so downstream logic only sees completed bars. Empty frames and single-row frames return empty results. Args: df_rate: Rate data ordered oldest-to-newest with the forming bar last. Returns: A new DataFrame with all rows except the last. Index and columns are preserved. The input frame is not modified. \"\"\" return df_rate . iloc [: - 1 ] . copy () drop_rate_compatibility_views \u00b6 drop_rate_compatibility_views ( conn : Connection ) -> None Drop all mt5cli-managed rate_* compatibility views. Source code in mt5cli/history.py 1355 1356 1357 1358 1359 1360 1361 1362 def drop_rate_compatibility_views ( conn : sqlite3 . Connection ) -> None : \"\"\"Drop all mt5cli-managed ``rate_*`` compatibility views.\"\"\" rows = conn . execute ( \"SELECT name FROM sqlite_master WHERE type = 'view' AND name GLOB 'rate_*'\" , ) . fetchall () for ( view_name ,) in rows : quoted_view_name = quote_sqlite_identifier ( str ( view_name )) conn . execute ( f \"DROP VIEW IF EXISTS { quoted_view_name } \" ) filter_incremental_history_deals_frame \u00b6 filter_incremental_history_deals_frame ( frame : DataFrame , symbols : Sequence [ str ], start_by_symbol : dict [ str , datetime ], account_event_start : datetime , ) -> DataFrame Filter incrementally fetched history_deals by symbol and event start times. Returns: Type Description DataFrame Rows for selected symbols at or after each symbol start, plus account DataFrame events at or after account_event_start . Source code in mt5cli/history.py 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 def filter_incremental_history_deals_frame ( frame : pd . DataFrame , symbols : Sequence [ str ], start_by_symbol : dict [ str , datetime ], account_event_start : datetime , ) -> pd . DataFrame : \"\"\"Filter incrementally fetched history_deals by symbol and event start times. Returns: Rows for selected symbols at or after each symbol start, plus account events at or after ``account_event_start``. \"\"\" if frame . empty : return frame . copy () parsed_times = _frame_parsed_times ( frame ) time_valid = parsed_times . notna () account_event_mask = _history_deals_account_event_mask ( frame ) account_keep = account_event_mask & ( parsed_times >= account_event_start ) trade_keep = pd . Series ( data = False , index = frame . index ) if \"symbol\" in frame . columns : for symbol in symbols : trade_keep |= ( ( frame [ \"symbol\" ] == symbol ) & ( parsed_times >= start_by_symbol [ symbol ]) & ~ account_event_mask ) keep = ( account_keep | trade_keep ) & time_valid return frame . loc [ keep ] . copy () filter_trade_history_frame \u00b6 filter_trade_history_frame ( frame : DataFrame , symbols : Sequence [ str ], * , include_account_events : bool , ) -> DataFrame Filter trade history rows to selected symbols and account events. Returns: Type Description DataFrame Filtered history rows. Source code in mt5cli/history.py 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 def filter_trade_history_frame ( frame : pd . DataFrame , symbols : Sequence [ str ], * , include_account_events : bool , ) -> pd . DataFrame : \"\"\"Filter trade history rows to selected symbols and account events. Returns: Filtered history rows. \"\"\" if \"symbol\" not in frame . columns : return frame symbol_mask = frame [ \"symbol\" ] . isin ( symbols ) if not include_account_events : return frame . loc [ symbol_mask ] . copy () account_event_mask = _history_deals_account_event_mask ( frame ) return frame . loc [ symbol_mask | account_event_mask ] . copy () get_history_deals_account_event_start_datetime \u00b6 get_history_deals_account_event_start_datetime ( conn : Connection , * , fallback_start : datetime ) -> datetime Return the next update start for account-level history_deals rows. Source code in mt5cli/history.py 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 def get_history_deals_account_event_start_datetime ( conn : sqlite3 . Connection , * , fallback_start : datetime , ) -> datetime : \"\"\"Return the next update start for account-level history_deals rows.\"\"\" table = Dataset . history_deals . table_name columns = get_table_columns ( conn , table ) if \"time\" not in columns : return fallback_start if \"type\" in columns : where_clause = f \"type NOT IN { _TRADE_DEAL_TYPES_SQL } \" elif \"symbol\" in columns : where_clause = \"symbol IS NULL OR symbol = ''\" else : return fallback_start row = conn . execute ( f \"SELECT MAX(time) FROM { table } WHERE { where_clause } \" , # noqa: S608 ) . fetchone () parsed = parse_sqlite_timestamp ( row [ 0 ] if row else None ) return parsed if parsed is not None else fallback_start get_incremental_start_datetime \u00b6 get_incremental_start_datetime ( conn : Connection , dataset : Dataset , * , symbol : str , timeframe : int | None , fallback_start : datetime , ) -> datetime Return the next update start datetime from existing MAX(time). Source code in mt5cli/history.py 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 def get_incremental_start_datetime ( conn : sqlite3 . Connection , dataset : Dataset , * , symbol : str , timeframe : int | None , fallback_start : datetime , ) -> datetime : \"\"\"Return the next update start datetime from existing MAX(time).\"\"\" timeframes = [ timeframe ] if timeframe is not None else None starts = load_incremental_start_datetimes ( conn , dataset , symbols = [ symbol ], timeframes = timeframes , fallback_start = fallback_start , ) return starts [ symbol , timeframe ] get_table_columns \u00b6 get_table_columns ( conn : Connection , table : str ) -> set [ str ] Return existing SQLite columns for a table. Source code in mt5cli/history.py 838 839 840 841 842 def get_table_columns ( conn : sqlite3 . Connection , table : str ) -> set [ str ]: \"\"\"Return existing SQLite columns for a table.\"\"\" quoted_table = quote_sqlite_identifier ( table ) rows = conn . execute ( f \"PRAGMA table_info( { quoted_table } )\" ) . fetchall () return { str ( row [ 1 ]) for row in rows } load_incremental_start_datetimes \u00b6 load_incremental_start_datetimes ( conn : Connection , dataset : Dataset , * , symbols : Sequence [ str ], timeframes : Sequence [ int ] | None = None , fallback_start : datetime , ) -> dict [ tuple [ str , int | None ], datetime ] Return next update start datetimes keyed by symbol and optional timeframe. Source code in mt5cli/history.py 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 def load_incremental_start_datetimes ( conn : sqlite3 . Connection , dataset : Dataset , * , symbols : Sequence [ str ], timeframes : Sequence [ int ] | None = None , fallback_start : datetime , ) -> dict [ tuple [ str , int | None ], datetime ]: \"\"\"Return next update start datetimes keyed by symbol and optional timeframe.\"\"\" table = dataset . table_name columns = get_table_columns ( conn , table ) if dataset is Dataset . rates and columns : _validate_rates_schema ( columns ) if \"time\" not in columns : if dataset is Dataset . rates and timeframes is not None : return { ( symbol , timeframe ): fallback_start for symbol in symbols for timeframe in timeframes } return {( symbol , None ): fallback_start for symbol in symbols } parsed_by_key : dict [ tuple [ str , int | None ], datetime ] = {} if ( dataset is Dataset . rates and timeframes is not None and { \"symbol\" , \"timeframe\" } . issubset ( columns ) ): symbol_placeholders = \", \" . join ( \"?\" for _ in symbols ) timeframe_placeholders = \", \" . join ( \"?\" for _ in timeframes ) grouped_rates_query = ( \"SELECT symbol, timeframe, MAX(time) FROM \" # noqa: S608 f \" { table } WHERE symbol IN ( { symbol_placeholders } )\" f \" AND timeframe IN ( { timeframe_placeholders } )\" \" GROUP BY symbol, timeframe\" ) rows = conn . execute ( grouped_rates_query , [ * symbols , * timeframes ], ) . fetchall () for row_symbol , row_timeframe , max_time in rows : parsed = parse_sqlite_timestamp ( max_time ) if parsed is not None : parsed_by_key [ str ( row_symbol ), int ( row_timeframe )] = parsed return { ( symbol , timeframe ): parsed_by_key . get ( ( symbol , timeframe ), fallback_start , ) for symbol in symbols for timeframe in timeframes } if \"symbol\" in columns : symbol_placeholders = \", \" . join ( \"?\" for _ in symbols ) rows = conn . execute ( f \"SELECT symbol, MAX(time) FROM { table } \" # noqa: S608 f \" WHERE symbol IN ( { symbol_placeholders } ) GROUP BY symbol\" , list ( symbols ), ) . fetchall () for row_symbol , max_time in rows : parsed = parse_sqlite_timestamp ( max_time ) if parsed is not None : parsed_by_key [ str ( row_symbol ), None ] = parsed return { ( symbol , None ): parsed_by_key . get (( symbol , None ), fallback_start ) for symbol in symbols } row = conn . execute ( f \"SELECT MAX(time) FROM { table } \" ) . fetchone () # noqa: S608 parsed = parse_sqlite_timestamp ( row [ 0 ] if row else None ) shared_start = parsed if parsed is not None else fallback_start return {( symbol , None ): shared_start for symbol in symbols } load_rate_data \u00b6 load_rate_data ( conn_or_path : SqliteConnOrPath , table : str , count : int | None = None , ) -> DataFrame Load rate-like data from a SQLite database path or connection. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath SQLite database path or open connection. required table str Source table or view name. required count int | None Optional number of most recent rows to load. None Returns: Type Description DataFrame DataFrame indexed by ascending time . Source code in mt5cli/history.py 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 def load_rate_data ( conn_or_path : SqliteConnOrPath , table : str , count : int | None = None , ) -> pd . DataFrame : \"\"\"Load rate-like data from a SQLite database path or connection. Args: conn_or_path: SQLite database path or open connection. table: Source table or view name. count: Optional number of most recent rows to load. Returns: DataFrame indexed by ascending ``time``. \"\"\" conn , should_close = _open_existing_sqlite_database ( conn_or_path ) try : return load_rate_data_from_connection ( conn , table , count = count ) finally : if should_close : conn . close () load_rate_data_from_connection \u00b6 load_rate_data_from_connection ( connection : Connection , table : str , count : int | None = None , ) -> DataFrame Load rate-like data from a SQLite table or view. Parameters: Name Type Description Default connection Connection Open SQLite connection. required table str Source table or view name. required count int | None Optional number of most recent rows to load. None Returns: Type Description DataFrame DataFrame indexed by ascending time . Raises: Type Description ValueError If inputs, schema, timestamps are invalid, or the table or view contains no rows. Source code in mt5cli/history.py 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 def load_rate_data_from_connection ( connection : sqlite3 . Connection , table : str , count : int | None = None , ) -> pd . DataFrame : \"\"\"Load rate-like data from a SQLite table or view. Args: connection: Open SQLite connection. table: Source table or view name. count: Optional number of most recent rows to load. Returns: DataFrame indexed by ascending ``time``. Raises: ValueError: If inputs, schema, timestamps are invalid, or the table or view contains no rows. \"\"\" table_name = _validate_rate_load_request ( table , count ) columns = get_table_columns ( connection , table_name ) _ensure_rate_columns ( columns , table_name ) quoted_table = quote_sqlite_identifier ( table_name ) if count is None : frame = cast ( \"pd.DataFrame\" , pd . read_sql_query ( # type: ignore[reportUnknownMemberType] f \"SELECT * FROM { quoted_table } ORDER BY time ASC\" , # noqa: S608 connection , ), ) else : frame = cast ( \"pd.DataFrame\" , pd . read_sql_query ( # type: ignore[reportUnknownMemberType] f \"SELECT * FROM { quoted_table } ORDER BY time DESC LIMIT ?\" , # noqa: S608 connection , params = ( count ,), ), ) if frame . empty : msg = f \"SQLite table or view { table_name !r} contains no rows.\" raise ValueError ( msg ) return _parse_rate_time_index ( frame , table_name ) load_rate_series_by_granularity \u00b6 load_rate_series_by_granularity ( conn_or_path : SqliteConnOrPath , symbols : Sequence [ str ], granularities : Sequence [ int | str ], count : int , * , explicit_tables : Sequence [ str ] | None = None , allow_missing_symbol : bool = False , ) -> dict [ tuple [ str | None , str ], DataFrame ] Load rate series keyed by symbol and string granularity name. Builds targets with :func: build_rate_targets and loads them with :func: load_rate_series_from_sqlite , then rekeys the result by granularity name (for example M1 ) instead of the integer timeframe to reduce downstream boilerplate. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath SQLite database path or open connection. required symbols Sequence [ str ] MT5 symbol names. May be empty when allow_missing_symbol . required granularities Sequence [ int | str ] MT5 timeframes as integers or names (for example M1 ). required count int Number of most recent rows to load per series. required explicit_tables Sequence [ str ] | None Optional explicit table or view names matching the built targets in row-major order. Required when symbols are omitted. None allow_missing_symbol bool When True and symbols is empty, build targets with symbol=None for each granularity instead of raising. False Returns: Type Description dict [ tuple [ str | None, str ], DataFrame ] Mapping keyed by (symbol | None, granularity_name) to each rate dict [ tuple [ str | None, str ], DataFrame ] DataFrame. Propagates ValueError (via :func: build_rate_targets and dict [ tuple [ str | None, str ], DataFrame ] func: load_rate_series_from_sqlite ) when inputs are empty or invalid, dict [ tuple [ str | None, str ], DataFrame ] table resolution fails, or duplicate targets are present. Source code in mt5cli/history.py 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 def load_rate_series_by_granularity ( conn_or_path : SqliteConnOrPath , symbols : Sequence [ str ], granularities : Sequence [ int | str ], count : int , * , explicit_tables : Sequence [ str ] | None = None , allow_missing_symbol : bool = False , ) -> dict [ tuple [ str | None , str ], pd . DataFrame ]: \"\"\"Load rate series keyed by symbol and string granularity name. Builds targets with :func:`build_rate_targets` and loads them with :func:`load_rate_series_from_sqlite`, then rekeys the result by granularity name (for example ``M1``) instead of the integer timeframe to reduce downstream boilerplate. Args: conn_or_path: SQLite database path or open connection. symbols: MT5 symbol names. May be empty when ``allow_missing_symbol``. granularities: MT5 timeframes as integers or names (for example ``M1``). count: Number of most recent rows to load per series. explicit_tables: Optional explicit table or view names matching the built targets in row-major order. Required when symbols are omitted. allow_missing_symbol: When True and ``symbols`` is empty, build targets with ``symbol=None`` for each granularity instead of raising. Returns: Mapping keyed by ``(symbol | None, granularity_name)`` to each rate DataFrame. Propagates ``ValueError`` (via :func:`build_rate_targets` and :func:`load_rate_series_from_sqlite`) when inputs are empty or invalid, table resolution fails, or duplicate targets are present. \"\"\" targets = build_rate_targets ( symbols , granularities , allow_missing_symbol = allow_missing_symbol , ) series = load_rate_series_from_sqlite ( conn_or_path , targets , count , explicit_tables = explicit_tables , ) return { ( symbol , resolve_granularity_name ( timeframe )): frame for ( symbol , timeframe ), frame in series . items () } load_rate_series_from_sqlite \u00b6 load_rate_series_from_sqlite ( conn_or_path : SqliteConnOrPath , targets : None = None , count : int | None = None , explicit_tables : None = None , * , table : str , ) -> DataFrame load_rate_series_from_sqlite ( conn_or_path : SqliteConnOrPath , targets : None = None , count : int | None = None , explicit_tables : Sequence [ str ] | None = None , * , table : None = None , ) -> dict [ tuple [ str | None , int ], DataFrame ] load_rate_series_from_sqlite ( conn_or_path : SqliteConnOrPath , targets : Sequence [ RateTarget ], count : int , explicit_tables : Sequence [ str ] | None = None , * , table : None = None , ) -> dict [ tuple [ str | None , int ], DataFrame ] load_rate_series_from_sqlite ( conn_or_path : SqliteConnOrPath , targets : Sequence [ RateTarget ] | None = None , count : int | None = None , explicit_tables : Sequence [ str ] | None = None , * , table : str | None = None , ) -> dict [ tuple [ str | None , int ], DataFrame ] | DataFrame Load one table/view or multiple rate series from a SQLite database. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath SQLite database path or open connection. required targets Sequence [ RateTarget ] | None Rate targets to load. Each (symbol, timeframe_int) pair must be unique. Omit when loading a single explicit table . None count int | None Optional number of most recent rows to load per series. None explicit_tables Sequence [ str ] | None Optional explicit table or view names matching targets. When omitted, managed rate_* compatibility views must already exist in the database. None table str | None Optional single table or view name to load directly. None Returns: Type Description dict [ tuple [ str | None, int ], DataFrame ] | DataFrame A DataFrame when table is provided, otherwise a mapping keyed by dict [ tuple [ str | None, int ], DataFrame ] | DataFrame (symbol, timeframe_int) to each rate DataFrame. Raises: Type Description ValueError If count is not positive, targets are empty, duplicate (symbol, timeframe_int) pairs are present, or table resolution fails. Source code in mt5cli/history.py 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 def load_rate_series_from_sqlite ( conn_or_path : SqliteConnOrPath , targets : Sequence [ RateTarget ] | None = None , count : int | None = None , explicit_tables : Sequence [ str ] | None = None , * , table : str | None = None , ) -> dict [ tuple [ str | None , int ], pd . DataFrame ] | pd . DataFrame : \"\"\"Load one table/view or multiple rate series from a SQLite database. Args: conn_or_path: SQLite database path or open connection. targets: Rate targets to load. Each ``(symbol, timeframe_int)`` pair must be unique. Omit when loading a single explicit ``table``. count: Optional number of most recent rows to load per series. explicit_tables: Optional explicit table or view names matching targets. When omitted, managed ``rate_*`` compatibility views must already exist in the database. table: Optional single table or view name to load directly. Returns: A DataFrame when ``table`` is provided, otherwise a mapping keyed by ``(symbol, timeframe_int)`` to each rate DataFrame. Raises: ValueError: If ``count`` is not positive, targets are empty, duplicate ``(symbol, timeframe_int)`` pairs are present, or table resolution fails. \"\"\" if table is not None : return load_rate_data ( conn_or_path , table , count = count ) if count is None or count <= 0 : msg = \"count must be positive.\" raise ValueError ( msg ) if targets is None : msg = \"targets are required when table is not provided.\" raise ValueError ( msg ) target_list = list ( targets ) if not target_list : msg = \"At least one rate target is required.\" raise ValueError ( msg ) if explicit_tables is None and any ( target . symbol is None for target in target_list ): msg = ( \"Cannot resolve a rate table for a target without a symbol; \" \"provide explicit_tables.\" ) raise ValueError ( msg ) seen_keys : set [ tuple [ str | None , int ]] = set () for target in target_list : key = ( target . symbol , target . timeframe_int ) if key in seen_keys : symbol_repr = repr ( target . symbol ) msg = f \"Duplicate rate target: ( { symbol_repr } , { target . timeframe_int } )\" raise ValueError ( msg ) seen_keys . add ( key ) tables = ( resolve_rate_tables ( None , target_list , explicit_tables ) if explicit_tables is not None else None ) conn , should_close = _open_existing_sqlite_database ( conn_or_path ) try : resolved_tables = tables or resolve_rate_tables ( conn , target_list , require_existing = True , ) return { ( target . symbol , target . timeframe_int ): load_rate_data_from_connection ( conn , table , count = count , ) for target , table in zip ( target_list , resolved_tables , strict = True ) } finally : if should_close : conn . close () parse_sqlite_timestamp \u00b6 parse_sqlite_timestamp ( value : object ) -> datetime | None Parse a SQLite history timestamp value. Returns: Type Description datetime | None Parsed timezone-aware datetime, or None when parsing fails. Source code in mt5cli/history.py 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 def parse_sqlite_timestamp ( value : object ) -> datetime | None : \"\"\"Parse a SQLite history timestamp value. Returns: Parsed timezone-aware datetime, or None when parsing fails. \"\"\" if value is None : return None if isinstance ( value , datetime ): return value if value . tzinfo is not None else value . replace ( tzinfo = UTC ) if isinstance ( value , int | float ): return datetime . fromtimestamp ( float ( value ), tz = UTC ) if isinstance ( value , str ): return _parse_string_sqlite_timestamp ( value ) logger . warning ( \"Ignoring unsupported history timestamp type: %s \" , type ( value )) return None quote_sqlite_identifier \u00b6 quote_sqlite_identifier ( identifier : str ) -> str Return a safely quoted SQLite identifier using double quotes. Source code in mt5cli/history.py 56 57 58 def quote_sqlite_identifier ( identifier : str ) -> str : \"\"\"Return a safely quoted SQLite identifier using double quotes.\"\"\" return '\"' + identifier . replace ( '\"' , '\"\"' ) + '\"' record_written_columns \u00b6 record_written_columns ( written_columns : dict [ Dataset , set [ str ]], dataset : Dataset , frame : DataFrame , ) -> None Remember columns for datasets written during collection. Source code in mt5cli/history.py 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 def record_written_columns ( written_columns : dict [ Dataset , set [ str ]], dataset : Dataset , frame : pd . DataFrame , ) -> None : \"\"\"Remember columns for datasets written during collection.\"\"\" columns = set ( frame . columns ) if dataset in written_columns : written_columns [ dataset ] . update ( columns ) else : written_columns [ dataset ] = columns resolve_granularity_name \u00b6 resolve_granularity_name ( timeframe : int ) -> str Return a granularity name for a timeframe integer when known. Source code in mt5cli/history.py 101 102 103 104 105 106 107 def resolve_granularity_name ( timeframe : int ) -> str : \"\"\"Return a granularity name for a timeframe integer when known.\"\"\" try : name = _get_timeframe_name ( timeframe ) except ValueError : return str ( timeframe ) return name . removeprefix ( \"TIMEFRAME_\" ) resolve_history_datasets \u00b6 resolve_history_datasets ( datasets : set [ Dataset ] | None , ) -> set [ Dataset ] Resolve configured history datasets. Returns: Type Description set [ Dataset ] All supported datasets when datasets is None, otherwise the set [ Dataset ] configured selection (which may be empty). Source code in mt5cli/history.py 61 62 63 64 65 66 67 68 69 70 def resolve_history_datasets ( datasets : set [ Dataset ] | None ) -> set [ Dataset ]: \"\"\"Resolve configured history datasets. Returns: All supported datasets when ``datasets`` is None, otherwise the configured selection (which may be empty). \"\"\" if datasets is None : return set ( Dataset ) return set ( datasets ) resolve_history_tick_flags \u00b6 resolve_history_tick_flags ( flags : int | str ) -> int Resolve tick copy flags from an integer or name. Returns: Type Description int Integer tick flag value. Source code in mt5cli/history.py 92 93 94 95 96 97 98 def resolve_history_tick_flags ( flags : int | str ) -> int : \"\"\"Resolve tick copy flags from an integer or name. Returns: Integer tick flag value. \"\"\" return parse_tick_flags ( flags ) resolve_history_timeframes \u00b6 resolve_history_timeframes ( timeframes : Sequence [ int | str ] | None , ) -> list [ int ] Resolve rate timeframes, deduplicating aliases for the same integer. Returns: Type Description list [ int ] Ordered list of unique timeframe integers. Source code in mt5cli/history.py 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 def resolve_history_timeframes ( timeframes : Sequence [ int | str ] | None , ) -> list [ int ]: \"\"\"Resolve rate timeframes, deduplicating aliases for the same integer. Returns: Ordered list of unique timeframe integers. \"\"\" raw = timeframes if timeframes is not None else DEFAULT_HISTORY_TIMEFRAMES seen : set [ int ] = set () resolved : list [ int ] = [] for value in raw : tf = parse_timeframe ( value ) if tf not in seen : seen . add ( tf ) resolved . append ( tf ) return resolved resolve_rate_table_name \u00b6 resolve_rate_table_name ( symbol : str , granularity : str ) -> str Return the canonical normalized SQLite rate table name. The normalized history table stores all symbols and timeframes in rates ; use :func: resolve_rate_view_name for per-symbol compatibility view names. Returns: Type Description str Canonical normalized rates table name. Raises: Type Description ValueError If symbol or granularity is invalid. Source code in mt5cli/history.py 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 def resolve_rate_table_name ( symbol : str , granularity : str ) -> str : \"\"\"Return the canonical normalized SQLite rate table name. The normalized history table stores all symbols and timeframes in ``rates``; use :func:`resolve_rate_view_name` for per-symbol compatibility view names. Returns: Canonical normalized rates table name. Raises: ValueError: If ``symbol`` or ``granularity`` is invalid. \"\"\" parse_timeframe ( granularity ) if not symbol . strip (): msg = \"symbol must not be empty.\" raise ValueError ( msg ) return Dataset . rates . table_name resolve_rate_tables \u00b6 resolve_rate_tables ( conn_or_path : SqliteConnOrPath | None , targets : Sequence [ RateTarget ], explicit_tables : Sequence [ str ] | None = None , * , require_existing : bool = False , ) -> list [ str ] Resolve SQLite table or view names for rate targets. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath | None SQLite database path or open connection. May be None when explicit_tables is provided, or when require_existing is False and deterministic default view names are sufficient. required targets Sequence [ RateTarget ] Rate targets to resolve. required explicit_tables Sequence [ str ] | None Optional explicit table or view names. When provided, they are used as-is and must match the number of targets. None require_existing bool When True, require the database and managed views to exist for each symbol target. Ignored when explicit_tables is provided. False Returns: Type Description list [ str ] Table or view names aligned with targets . Raises: Type Description ValueError If targets is empty, explicit_tables length does not match the target count, a target without a symbol is resolved without an explicit table, or require_existing is True and the database or a managed view is missing. Source code in mt5cli/history.py 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 def resolve_rate_tables ( conn_or_path : SqliteConnOrPath | None , targets : Sequence [ RateTarget ], explicit_tables : Sequence [ str ] | None = None , * , require_existing : bool = False , ) -> list [ str ]: \"\"\"Resolve SQLite table or view names for rate targets. Args: conn_or_path: SQLite database path or open connection. May be None when ``explicit_tables`` is provided, or when ``require_existing`` is False and deterministic default view names are sufficient. targets: Rate targets to resolve. explicit_tables: Optional explicit table or view names. When provided, they are used as-is and must match the number of targets. require_existing: When True, require the database and managed views to exist for each symbol target. Ignored when ``explicit_tables`` is provided. Returns: Table or view names aligned with ``targets``. Raises: ValueError: If ``targets`` is empty, ``explicit_tables`` length does not match the target count, a target without a symbol is resolved without an explicit table, or ``require_existing`` is True and the database or a managed view is missing. \"\"\" target_list = list ( targets ) if not target_list : msg = \"At least one rate target is required.\" raise ValueError ( msg ) if explicit_tables is not None : tables = list ( explicit_tables ) if len ( tables ) != len ( target_list ): msg = ( f \"Expected { len ( target_list ) } explicit table(s) \" f \"to match the targets, got { len ( tables ) } .\" ) raise ValueError ( msg ) return tables if any ( target . symbol is None for target in target_list ): msg = ( \"Cannot resolve a rate table for a target without a symbol; \" \"provide explicit_tables.\" ) raise ValueError ( msg ) conn , should_close = _open_history_connection ( conn_or_path ) try : if conn is None : if require_existing : path = ( conn_or_path if isinstance ( conn_or_path , ( Path , str )) else \"database\" ) msg = f \"SQLite database not found: { path } \" raise ValueError ( msg ) timeframe_counts = None existing_views : set [ str ] = set () else : timeframe_counts = _load_rates_timeframe_counts ( conn ) existing_views = _load_existing_rate_views ( conn ) resolved : list [ str ] = [] for target in target_list : symbol = cast ( \"str\" , target . symbol ) timeframe = target . timeframe_int resolved . append ( _resolve_rate_view_name_from_context ( symbol = symbol , timeframe = timeframe , granularity_name = resolve_granularity_name ( timeframe ), timeframe_counts = timeframe_counts , existing_views = existing_views , require_existing = require_existing , ), ) return resolved finally : if should_close and conn is not None : conn . close () resolve_rate_view_name \u00b6 resolve_rate_view_name ( conn_or_path : SqliteConnOrPath | None , symbol : str , granularity : str , * , require_existing : bool = False , ) -> str Resolve the mt5cli-managed rate compatibility view name. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath | None SQLite database path or open connection. When None or a non-existing path and require_existing is False, the deterministic default view name is returned without creating a database file. required symbol str Symbol stored in the normalized rates table. required granularity str Timeframe name (for example M1 ) or integer string. required require_existing bool When True, require the database and a managed view to exist. False Returns: Type Description str View name such as rate_EURUSD__1 or rate_EURUSD__M1_1 . Raises: Type Description ValueError If require_existing is True and the database or view is missing. Source code in mt5cli/history.py 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 def resolve_rate_view_name ( conn_or_path : SqliteConnOrPath | None , symbol : str , granularity : str , * , require_existing : bool = False , ) -> str : \"\"\"Resolve the mt5cli-managed rate compatibility view name. Args: conn_or_path: SQLite database path or open connection. When None or a non-existing path and ``require_existing`` is False, the deterministic default view name is returned without creating a database file. symbol: Symbol stored in the normalized ``rates`` table. granularity: Timeframe name (for example ``M1``) or integer string. require_existing: When True, require the database and a managed view to exist. Returns: View name such as ``rate_EURUSD__1`` or ``rate_EURUSD__M1_1``. Raises: ValueError: If ``require_existing`` is True and the database or view is missing. \"\"\" timeframe = parse_timeframe ( granularity ) granularity_name = resolve_granularity_name ( timeframe ) conn , should_close = _open_history_connection ( conn_or_path ) try : if conn is None : if require_existing : path = ( conn_or_path if isinstance ( conn_or_path , ( Path , str )) else \"database\" ) msg = f \"SQLite database not found: { path } \" raise ValueError ( msg ) return build_rate_view_name ( symbol = symbol , granularity = granularity_name , granularity_count = 1 , timeframe = timeframe , ) return _resolve_rate_view_name_from_context ( symbol = symbol , timeframe = timeframe , granularity_name = granularity_name , timeframe_counts = _load_rates_timeframe_counts ( conn ), existing_views = _load_existing_rate_views ( conn ), require_existing = require_existing , ) finally : if should_close and conn is not None : conn . close () resolve_rate_view_names \u00b6 resolve_rate_view_names ( conn_or_path : SqliteConnOrPath | None , symbols : Sequence [ str ], granularities : Sequence [ str ], * , require_existing : bool = False , ) -> list [ str ] Resolve rate compatibility view names for symbol and granularity pairs. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath | None SQLite database path or open connection. When None or a non-existing path and require_existing is False, deterministic default view names are returned without creating a database file. required symbols Sequence [ str ] Symbols stored in the normalized rates table. required granularities Sequence [ str ] Timeframe names (for example M1 ) or integer strings. required require_existing bool When True, require the database and managed views to exist. False Returns: Type Description list [ str ] View names in row-major order: every granularity for the first list [ str ] symbol, then every granularity for the next symbol, and so on. Source code in mt5cli/history.py 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 def resolve_rate_view_names ( conn_or_path : SqliteConnOrPath | None , symbols : Sequence [ str ], granularities : Sequence [ str ], * , require_existing : bool = False , ) -> list [ str ]: \"\"\"Resolve rate compatibility view names for symbol and granularity pairs. Args: conn_or_path: SQLite database path or open connection. When None or a non-existing path and ``require_existing`` is False, deterministic default view names are returned without creating a database file. symbols: Symbols stored in the normalized ``rates`` table. granularities: Timeframe names (for example ``M1``) or integer strings. require_existing: When True, require the database and managed views to exist. Returns: View names in row-major order: every ``granularity`` for the first symbol, then every granularity for the next symbol, and so on. \"\"\" conn , should_close = _open_history_connection ( conn_or_path ) try : if conn is None : return [ resolve_rate_view_name ( conn_or_path , symbol , granularity , require_existing = require_existing , ) for symbol in symbols for granularity in granularities ] timeframe_counts = _load_rates_timeframe_counts ( conn ) existing_views = _load_existing_rate_views ( conn ) resolved : list [ str ] = [] for symbol in symbols : for granularity in granularities : timeframe = parse_timeframe ( granularity ) resolved . append ( _resolve_rate_view_name_from_context ( symbol = symbol , timeframe = timeframe , granularity_name = resolve_granularity_name ( timeframe ), timeframe_counts = timeframe_counts , existing_views = existing_views , require_existing = require_existing , ), ) return resolved finally : if should_close and conn is not None : conn . close () write_collected_datasets \u00b6 write_collected_datasets ( conn : Connection , client : Mt5DataClient , symbols : Sequence [ str ], datasets : set [ Dataset ], timeframe : int , flags : int , date_from : datetime , date_to : datetime , if_exists : IfExists , ) -> tuple [ set [ Dataset ], dict [ Dataset , set [ str ]]] Collect selected datasets and stream each symbol frame into SQLite. Returns: Type Description tuple [ set [ Dataset ], dict [ Dataset , set [ str ]]] Written datasets and their columns. Source code in mt5cli/history.py 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 def write_collected_datasets ( conn : sqlite3 . Connection , client : Mt5DataClient , symbols : Sequence [ str ], datasets : set [ Dataset ], timeframe : int , flags : int , date_from : datetime , date_to : datetime , if_exists : IfExists , ) -> tuple [ set [ Dataset ], dict [ Dataset , set [ str ]]]: \"\"\"Collect selected datasets and stream each symbol frame into SQLite. Returns: Written datasets and their columns. \"\"\" written_columns : dict [ Dataset , set [ str ]] = {} written_tables : set [ Dataset ] = set () if Dataset . rates in datasets and write_rates_dataset ( conn , client , symbols , timeframe , date_from , date_to , if_exists , written_columns , ): written_tables . add ( Dataset . rates ) if Dataset . ticks in datasets and write_ticks_dataset ( conn , client , symbols , flags , date_from , date_to , if_exists , written_columns , ): written_tables . add ( Dataset . ticks ) if Dataset . history_orders in datasets and write_history_dataset ( conn , client . history_orders_get_as_df , Dataset . history_orders , symbols , date_from , date_to , if_exists , written_columns , include_account_events = False , ): written_tables . add ( Dataset . history_orders ) if Dataset . history_deals in datasets and write_history_dataset ( conn , client . history_deals_get_as_df , Dataset . history_deals , symbols , date_from , date_to , if_exists , written_columns , include_account_events = False , ): written_tables . add ( Dataset . history_deals ) return written_tables , written_columns write_history_dataset \u00b6 write_history_dataset ( conn : Connection , fetch : Callable [ ... , DataFrame ], dataset : Dataset , symbols : Sequence [ str ], date_from : datetime , date_to : datetime , if_exists : IfExists , written_columns : dict [ Dataset , set [ str ]], * , include_account_events : bool = False , ) -> bool Stream a history dataset into SQLite. Returns: Type Description bool True if the target table was written. Source code in mt5cli/history.py 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 def write_history_dataset ( conn : sqlite3 . Connection , fetch : Callable [ ... , pd . DataFrame ], dataset : Dataset , symbols : Sequence [ str ], date_from : datetime , date_to : datetime , if_exists : IfExists , written_columns : dict [ Dataset , set [ str ]], * , include_account_events : bool = False , ) -> bool : \"\"\"Stream a history dataset into SQLite. Returns: True if the target table was written. \"\"\" table_exists = False if include_account_events : frame = filter_trade_history_frame ( fetch ( date_from = date_from , date_to = date_to ), symbols , include_account_events = True , ) return write_streamed_frame ( conn , frame , dataset , table_exists , if_exists , written_columns , ) def _fetch_history_frame ( sym : str ) -> pd . DataFrame : return filter_trade_history_frame ( fetch ( date_from = date_from , date_to = date_to , symbol = sym ), [ sym ], include_account_events = False , ) return _stream_symbol_frames ( conn , symbols , dataset , if_exists , written_columns , _fetch_history_frame , ) write_incremental_datasets \u00b6 write_incremental_datasets ( conn : Connection , client : Mt5DataClient , symbols : Sequence [ str ], selected_datasets : set [ Dataset ], resolved_timeframes : list [ int ], resolved_tick_flags : int , fallback_start : datetime , end_date : datetime , * , deduplicate : bool , create_rate_views : bool , with_views : bool , include_account_events : bool , ) -> tuple [ set [ Dataset ], dict [ Dataset , set [ str ]]] Append selected datasets incrementally and refresh indexes and views. Returns: Type Description tuple [ set [ Dataset ], dict [ Dataset , set [ str ]]] Written datasets and their columns. Source code in mt5cli/history.py 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 def write_incremental_datasets ( # noqa: PLR0913 conn : sqlite3 . Connection , client : Mt5DataClient , symbols : Sequence [ str ], selected_datasets : set [ Dataset ], resolved_timeframes : list [ int ], resolved_tick_flags : int , fallback_start : datetime , end_date : datetime , * , deduplicate : bool , create_rate_views : bool , with_views : bool , include_account_events : bool , ) -> tuple [ set [ Dataset ], dict [ Dataset , set [ str ]]]: \"\"\"Append selected datasets incrementally and refresh indexes and views. Returns: Written datasets and their columns. \"\"\" written_columns : dict [ Dataset , set [ str ]] = {} written_tables : set [ Dataset ] = set () dedup_scopes : dict [ Dataset , list [ DedupScope ]] = {} if Dataset . rates in selected_datasets : _write_incremental_rates ( conn , client , symbols , resolved_timeframes , fallback_start , end_date , written_columns , written_tables , dedup_scopes , ) if Dataset . ticks in selected_datasets : _write_incremental_ticks ( conn , client , symbols , resolved_tick_flags , fallback_start , end_date , written_columns , written_tables , dedup_scopes , ) if Dataset . history_orders in selected_datasets : _write_incremental_history_orders ( conn , client , symbols , fallback_start , end_date , written_columns , written_tables , dedup_scopes , ) if Dataset . history_deals in selected_datasets : _write_incremental_history_deals ( conn , client , symbols , fallback_start , end_date , written_columns , written_tables , dedup_scopes , include_account_events = include_account_events , ) _finalize_incremental_writes ( conn , selected_datasets , written_columns , written_tables , dedup_scopes , deduplicate = deduplicate , create_rate_views = create_rate_views , with_views = with_views , ) return written_tables , written_columns write_rates_dataset \u00b6 write_rates_dataset ( conn : Connection , client : Mt5DataClient , symbols : Sequence [ str ], timeframe : int , date_from : datetime , date_to : datetime , if_exists : IfExists , written_columns : dict [ Dataset , set [ str ]], ) -> bool Stream rates frames into SQLite. Returns: Type Description bool True if the rates table was written. Source code in mt5cli/history.py 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 def write_rates_dataset ( conn : sqlite3 . Connection , client : Mt5DataClient , symbols : Sequence [ str ], timeframe : int , date_from : datetime , date_to : datetime , if_exists : IfExists , written_columns : dict [ Dataset , set [ str ]], ) -> bool : \"\"\"Stream rates frames into SQLite. Returns: True if the rates table was written. \"\"\" def _fetch_rates_frame ( sym : str ) -> pd . DataFrame : frame = client . copy_rates_range_as_df ( symbol = sym , timeframe = timeframe , date_from = date_from , date_to = date_to , ) . drop ( columns = [ \"symbol\" , \"timeframe\" ], errors = \"ignore\" ) if len ( frame . columns ) != 0 : frame . insert ( 0 , \"symbol\" , sym ) frame . insert ( 1 , \"timeframe\" , timeframe ) return frame return _stream_symbol_frames ( conn , symbols , Dataset . rates , if_exists , written_columns , _fetch_rates_frame , ) write_streamed_frame \u00b6 write_streamed_frame ( conn : Connection , frame : DataFrame , dataset : Dataset , table_exists : bool , if_exists : IfExists , written_columns : dict [ Dataset , set [ str ]], ) -> bool Write one streamed dataset frame and track table state. Returns: Type Description bool True if the dataset table exists after this write attempt. Source code in mt5cli/history.py 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 def write_streamed_frame ( conn : sqlite3 . Connection , frame : pd . DataFrame , dataset : Dataset , table_exists : bool , if_exists : IfExists , written_columns : dict [ Dataset , set [ str ]], ) -> bool : \"\"\"Write one streamed dataset frame and track table state. Returns: True if the dataset table exists after this write attempt. \"\"\" write_mode = IfExists . APPEND if table_exists else if_exists if append_dataframe ( conn , frame , dataset . table_name , write_mode ): record_written_columns ( written_columns , dataset , frame ) return True return table_exists write_ticks_dataset \u00b6 write_ticks_dataset ( conn : Connection , client : Mt5DataClient , symbols : Sequence [ str ], flags : int , date_from : datetime , date_to : datetime , if_exists : IfExists , written_columns : dict [ Dataset , set [ str ]], ) -> bool Stream ticks frames into SQLite. Returns: Type Description bool True if the ticks table was written. Source code in mt5cli/history.py 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 def write_ticks_dataset ( conn : sqlite3 . Connection , client : Mt5DataClient , symbols : Sequence [ str ], flags : int , date_from : datetime , date_to : datetime , if_exists : IfExists , written_columns : dict [ Dataset , set [ str ]], ) -> bool : \"\"\"Stream ticks frames into SQLite. Returns: True if the ticks table was written. \"\"\" def _fetch_ticks_frame ( sym : str ) -> pd . DataFrame : frame = client . copy_ticks_range_as_df ( symbol = sym , date_from = date_from , date_to = date_to , flags = flags , ) . drop ( columns = [ \"symbol\" ], errors = \"ignore\" ) if len ( frame . columns ) != 0 : frame . insert ( 0 , \"symbol\" , sym ) return frame return _stream_symbol_frames ( conn , symbols , Dataset . ticks , if_exists , written_columns , _fetch_ticks_frame , ) collect-history schema \u00b6 The collect-history command (and the matching collect_history SDK function) writes selected MT5 datasets into one SQLite database. Each dataset becomes a table; column names and types mirror the pdmt5 DataFrame schema for that export, with two additions: symbol is prepended on every table. timeframe is prepended on rates so appended runs at different bar sizes stay distinguishable. SQLite does not declare foreign keys. Rows are linked logically by symbol , time windows, and (for deals) position_id / order . Duplicate rows are removed on append using dataset-specific keys (for example ticket on history tables, or (symbol, timeframe, time) on rates). Optional views are created when --with-views is set and the history-deals dataset was written. Entity-relationship diagram \u00b6 Sample layout for a full collection with --with-views : erDiagram rates { TEXT symbol \"dedup key\" INTEGER timeframe \"dedup key\" TEXT time \"dedup key\" REAL open REAL high REAL low REAL close INTEGER tick_volume INTEGER spread INTEGER real_volume } ticks { TEXT symbol \"dedup key\" TEXT time \"dedup key\" INTEGER time_msc \"dedup key (preferred)\" REAL bid REAL ask REAL last INTEGER volume INTEGER flags REAL volume_real } history_orders { INTEGER ticket \"dedup key\" TEXT symbol TEXT time INTEGER type INTEGER state REAL volume_initial REAL price_open REAL price_current INTEGER magic } history_deals { INTEGER ticket \"dedup key\" INTEGER order INTEGER position_id \"groups position view\" TEXT symbol TEXT time INTEGER type \"0/1 trade, else cash event\" INTEGER entry \"0 IN, 1 OUT, 2 INOUT, 3 OUT_BY\" REAL volume REAL price REAL profit REAL commission REAL swap REAL fee } cash_events { INTEGER ticket TEXT symbol TEXT time INTEGER type REAL profit } positions_reconstructed { INTEGER position_id TEXT symbol TEXT open_time TEXT close_time INTEGER direction REAL volume_open REAL volume_close REAL volume_reversal REAL open_price REAL close_price REAL total_profit INTEGER reversal_count INTEGER deals_count } rates ||--o{ history_deals : \"symbol (logical)\" ticks ||--o{ history_deals : \"symbol (logical)\" history_orders ||--o{ history_deals : \"order ~ ticket (logical)\" history_deals ||--|| cash_events : \"VIEW: type NOT IN (0,1)\" history_deals ||--o{ positions_reconstructed : \"VIEW: GROUP BY position_id\" Tables and views \u00b6 Object Kind Source Notes rates table copy_rates_range Indexed on (symbol, timeframe, time) when columns exist. ticks table copy_ticks_range Indexed on (symbol, time) when columns exist. history_orders table history_orders_get Fetched per --symbol , then concatenated. history_deals table history_deals_get Fetched per --symbol , then concatenated. Indexed on (position_id, symbol) when present. cash_events view history_deals Non-trade deal types (deposits, balance ops, etc.). Requires type column. positions_reconstructed view history_deals One row per closed position_id ; volume-weighted prices and reversal stats. Column sets can vary with terminal and pdmt5 version. Views are skipped with a warning when required columns are missing. Incremental collection \u00b6 The update_history SDK path uses the same base tables and optional cash_events / positions_reconstructed views. It additionally maintains rate___ compatibility views when create_rate_views=True . Rate view resolution \u00b6 Downstream tools can resolve mt5cli-managed compatibility view names from an existing SQLite history database without creating files or guessing naming schemes: from pathlib import Path from mt5cli.history import resolve_rate_view_name , resolve_rate_view_names # Single symbol and granularity view = resolve_rate_view_name ( Path ( \"history.db\" ), \"EURUSD\" , \"M1\" ) # Batch resolution in row-major order views = resolve_rate_view_names ( Path ( \"history.db\" ), [ \"EURUSD\" , \"GBPUSD\" ], [ \"M1\" , \"H1\" ], ) Resolution rules: Returns rate___ when a symbol stores one timeframe. Returns rate____ when multiple timeframes are stored for the same symbol. When multiple naming candidates apply, prefers an existing managed rate_*__* view from the candidate list. Falls back to single-timeframe naming when the database path is missing or rates metadata is unavailable. Pass require_existing=True to raise ValueError instead of returning a best-guess name when the database or view is missing. Accepts either a SQLite path or an open sqlite3.Connection . Rate data loading \u00b6 The canonical normalized rate table is rates ; compatibility views are named with rate___ for single-timeframe symbols or rate____ when a symbol has multiple stored timeframes. resolve_rate_table_name() returns rates , while resolve_rate_view_name() returns the per-symbol compatibility view name. Use load_rate_data() or load_rate_series_from_sqlite(..., table=...) to load a single table or view from a SQLite path. Use load_rate_series_by_granularity() to load multiple instrument/granularity targets without hard-coding view names: from pathlib import Path from mt5cli import ( load_rate_data , load_rate_series_by_granularity , load_rate_series_from_sqlite , resolve_rate_table_name , ) from mt5cli.history import resolve_rate_view_name view = resolve_rate_view_name ( Path ( \"history.db\" ), \"EURUSD\" , \"M1\" , require_existing = True ) rates = load_rate_data ( Path ( \"history.db\" ), view , count = 1000 ) same_rates = load_rate_series_from_sqlite ( Path ( \"history.db\" ), table = view , count = 1000 ) table = resolve_rate_table_name ( \"EURUSD\" , \"M1\" ) # \"rates\" series = load_rate_series_by_granularity ( Path ( \"history.db\" ), symbols = [ \"EURUSD\" , \"GBPUSD\" ], granularities = [ \"M1\" , \"H1\" ], count = 500 , ) count returns the latest rows while preserving chronological order. Missing tables/views and mismatched explicit_tables lengths raise ValueError with the requested database target in the message. The loader accepts close-based OHLC rate data or tick-like bid/ask data. It validates that time exists, parses timestamps with pandas, and returns a DataFrame indexed by ascending DatetimeIndex named time . Multi-series rate loading \u00b6 For loading many rate series at once, build neutral RateTarget pairs and load them from SQLite in one call. View names are resolved via the same compatibility-view rules, or you can pass explicit_tables to bypass resolution: from pathlib import Path from mt5cli import build_rate_targets , load_rate_series_from_sqlite targets = build_rate_targets ([ \"EURUSD\" , \"GBPUSD\" ], [ \"M1\" , \"H1\" ]) series = load_rate_series_from_sqlite ( Path ( \"history.db\" ), targets , count = 1000 ) frame = series [ \"EURUSD\" , 1 ] # keyed by (symbol, integer timeframe) build_rate_targets() returns RateTarget(symbol, timeframe) pairs in row-major order, normalizing timeframe names such as \"M1\" to their integer values; set allow_missing_symbol=True to address series solely by explicit_tables (targets carry symbol=None ). resolve_rate_tables() maps targets to table or view names and validates that any explicit_tables count matches the target count. Pass require_existing=True to raise ValueError instead of returning a best-guess name when the database or managed view is missing. When explicit_tables is provided, names are returned as-is and require_existing is ignored. load_rate_series_from_sqlite() returns a mapping keyed by (symbol, integer timeframe) . Unless explicit_tables is supplied, it requires existing managed rate_* compatibility views and raises ValueError when they are missing. Duplicate (symbol, timeframe) targets are rejected. load_rate_series_by_granularity() is a thin wrapper that builds the targets, loads the series, and rekeys the result by granularity name to avoid converting integer timeframes downstream: from mt5cli import load_rate_series_by_granularity series = load_rate_series_by_granularity ( \"history.db\" , [ \"EURUSD\" ], [ \"M1\" , \"H1\" ], count = 1000 ) frame = series [ \"EURUSD\" , \"M1\" ] # keyed by (symbol | None, granularity_name)","title":"History Collection (SQLite)"},{"location":"api/history/#history-collection-sqlite","text":"","title":"History Collection (SQLite)"},{"location":"api/history/#mt5cli.history","text":"SQLite storage helpers for the collect-history incremental data pipeline.","title":"history"},{"location":"api/history/#mt5cli.history.DEFAULT_HISTORY_TIMEFRAMES","text":"DEFAULT_HISTORY_TIMEFRAMES : tuple [ str , ... ] = ( TIMEFRAME_NAMES )","title":"DEFAULT_HISTORY_TIMEFRAMES"},{"location":"api/history/#mt5cli.history.SqliteConnOrPath","text":"SqliteConnOrPath = Connection | Path | str","title":"SqliteConnOrPath"},{"location":"api/history/#mt5cli.history.logger","text":"logger = getLogger ( __name__ )","title":"logger"},{"location":"api/history/#mt5cli.history.DedupScope","text":"DedupScope ( where : str , params : tuple [ object , ... ], required_columns : frozenset [ str ], ) Scoped deduplication predicate and the columns it references. Attributes: Name Type Description where str SQL predicate appended to the duplicate-removal query. params tuple [ object , ...] Parameters bound to the scope predicate. required_columns frozenset [ str ] Columns that must be present in the written table for the scope to run.","title":"DedupScope"},{"location":"api/history/#mt5cli.history.DedupScope.params","text":"params : tuple [ object , ... ]","title":"params"},{"location":"api/history/#mt5cli.history.DedupScope.required_columns","text":"required_columns : frozenset [ str ]","title":"required_columns"},{"location":"api/history/#mt5cli.history.DedupScope.where","text":"where : str","title":"where"},{"location":"api/history/#mt5cli.history.RateTarget","text":"RateTarget ( symbol : str | None , timeframe : int | str ) A single rate series identified by symbol and timeframe. Attributes: Name Type Description symbol str | None MT5 symbol name, or None when the rate series is addressed only by an explicit table (for example a custom SQLite view). timeframe int | str MT5 timeframe as an integer or name (for example M1 ).","title":"RateTarget"},{"location":"api/history/#mt5cli.history.RateTarget.symbol","text":"symbol : str | None","title":"symbol"},{"location":"api/history/#mt5cli.history.RateTarget.timeframe","text":"timeframe : int | str","title":"timeframe"},{"location":"api/history/#mt5cli.history.RateTarget.timeframe_int","text":"timeframe_int : int Return the timeframe as its integer MT5 value.","title":"timeframe_int"},{"location":"api/history/#mt5cli.history.RateTarget.__post_init__","text":"__post_init__ () -> None Normalize accepted timeframe aliases to the stored integer value. Source code in mt5cli/history.py 544 545 546 547 def __post_init__ ( self ) -> None : \"\"\"Normalize accepted timeframe aliases to the stored integer value.\"\"\" if not isinstance ( self . timeframe , int ): object . __setattr__ ( self , \"timeframe\" , parse_timeframe ( self . timeframe ))","title":"__post_init__"},{"location":"api/history/#mt5cli.history.append_dataframe","text":"append_dataframe ( conn : Connection , frame : DataFrame , table_name : str , if_exists : IfExists , ) -> bool Append a DataFrame to SQLite when it has a schema. Returns: Type Description bool True if a table was written, False if the frame had no columns. Source code in mt5cli/history.py 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 def append_dataframe ( conn : sqlite3 . Connection , frame : pd . DataFrame , table_name : str , if_exists : IfExists , ) -> bool : \"\"\"Append a DataFrame to SQLite when it has a schema. Returns: True if a table was written, False if the frame had no columns. \"\"\" if len ( frame . columns ) == 0 : logger . warning ( \"Skipping %s : dataset returned no columns\" , table_name ) return False frame . to_sql ( # type: ignore[reportUnknownMemberType] table_name , conn , if_exists = if_exists . value , index = False , chunksize = 50_000 , ) return True","title":"append_dataframe"},{"location":"api/history/#mt5cli.history.augment_written_columns_from_sqlite","text":"augment_written_columns_from_sqlite ( conn : Connection , datasets : set [ Dataset ], written_columns : dict [ Dataset , set [ str ]], ) -> None Add existing table columns to the written column map. Source code in mt5cli/history.py 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 def augment_written_columns_from_sqlite ( conn : sqlite3 . Connection , datasets : set [ Dataset ], written_columns : dict [ Dataset , set [ str ]], ) -> None : \"\"\"Add existing table columns to the written column map.\"\"\" for dataset in datasets : columns = get_table_columns ( conn , dataset . table_name ) if not columns : continue if dataset in written_columns : written_columns [ dataset ] . update ( columns ) else : written_columns [ dataset ] = columns","title":"augment_written_columns_from_sqlite"},{"location":"api/history/#mt5cli.history.build_rate_targets","text":"build_rate_targets ( symbols : Sequence [ str ], timeframes : Sequence [ int | str ], * , allow_missing_symbol : bool = False , ) -> list [ RateTarget ] Build rate targets for every symbol and timeframe combination. Parameters: Name Type Description Default symbols Sequence [ str ] MT5 symbol names. May be empty when allow_missing_symbol . required timeframes Sequence [ int | str ] MT5 timeframes as integers or names (for example M1 ). required allow_missing_symbol bool When True and symbols is empty, build targets with symbol=None for each timeframe instead of raising. False Returns: Type Description list [ RateTarget ] Targets in row-major order: every timeframe for the first symbol, then list [ RateTarget ] every timeframe for the next symbol, and so on. Raises: Type Description ValueError If timeframes is empty, or symbols is empty and allow_missing_symbol is False. Source code in mt5cli/history.py 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 def build_rate_targets ( symbols : Sequence [ str ], timeframes : Sequence [ int | str ], * , allow_missing_symbol : bool = False , ) -> list [ RateTarget ]: \"\"\"Build rate targets for every symbol and timeframe combination. Args: symbols: MT5 symbol names. May be empty when ``allow_missing_symbol``. timeframes: MT5 timeframes as integers or names (for example ``M1``). allow_missing_symbol: When True and ``symbols`` is empty, build targets with ``symbol=None`` for each timeframe instead of raising. Returns: Targets in row-major order: every timeframe for the first symbol, then every timeframe for the next symbol, and so on. Raises: ValueError: If ``timeframes`` is empty, or ``symbols`` is empty and ``allow_missing_symbol`` is False. \"\"\" if not timeframes : msg = \"At least one timeframe is required.\" raise ValueError ( msg ) if not symbols : if not allow_missing_symbol : msg = \"At least one symbol is required.\" raise ValueError ( msg ) return [ RateTarget ( symbol = None , timeframe = tf ) for tf in timeframes ] return [ RateTarget ( symbol = symbol , timeframe = tf ) for symbol in symbols for tf in timeframes ]","title":"build_rate_targets"},{"location":"api/history/#mt5cli.history.build_rate_view_name","text":"build_rate_view_name ( * , symbol : str , granularity : str , granularity_count : int , timeframe : int , ) -> str Return a collision-free offline optimize view name. View names always include the timeframe integer after a __ separator so a symbol such as EURUSD_M1 cannot collide with EURUSD at timeframe M1 . Source code in mt5cli/history.py 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 def build_rate_view_name ( * , symbol : str , granularity : str , granularity_count : int , timeframe : int , ) -> str : \"\"\"Return a collision-free offline optimize view name. View names always include the timeframe integer after a ``__`` separator so a symbol such as ``EURUSD_M1`` cannot collide with ``EURUSD`` at timeframe ``M1``. \"\"\" if granularity_count == 1 : return f \"rate_ { symbol } __ { timeframe } \" return f \"rate_ { symbol } __ { granularity } _ { timeframe } \"","title":"build_rate_view_name"},{"location":"api/history/#mt5cli.history.create_cash_events_view","text":"create_cash_events_view ( conn : Connection , deals_columns : set [ str ] ) -> bool Create the cash_events SQLite view derived from history_deals. Returns: Type Description bool True if the view was created, False if required columns are missing. Source code in mt5cli/history.py 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 def create_cash_events_view ( conn : sqlite3 . Connection , deals_columns : set [ str ], ) -> bool : \"\"\"Create the cash_events SQLite view derived from history_deals. Returns: True if the view was created, False if required columns are missing. \"\"\" if \"type\" not in deals_columns : logger . warning ( \"Skipping cash_events view: history_deals.type is missing\" ) return False conn . execute ( \"DROP VIEW IF EXISTS cash_events\" ) conn . execute ( \"CREATE VIEW cash_events AS\" # noqa: S608 f \" SELECT * FROM history_deals WHERE type NOT IN { _TRADE_DEAL_TYPES_SQL } \" , ) return True","title":"create_cash_events_view"},{"location":"api/history/#mt5cli.history.create_history_indexes","text":"create_history_indexes ( conn : Connection , written_columns : dict [ Dataset , set [ str ]], ) -> None Create useful indexes for collected history tables when present. Source code in mt5cli/history.py 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 def create_history_indexes ( conn : sqlite3 . Connection , written_columns : dict [ Dataset , set [ str ]], ) -> None : \"\"\"Create useful indexes for collected history tables when present.\"\"\" if { \"symbol\" , \"timeframe\" , \"time\" } . issubset ( written_columns . get ( Dataset . rates , set ()), ): conn . execute ( \"CREATE INDEX IF NOT EXISTS idx_rates_symbol_timeframe_time\" \" ON rates(symbol, timeframe, time)\" , ) if { \"symbol\" , \"time\" } . issubset ( written_columns . get ( Dataset . ticks , set ())): conn . execute ( \"CREATE INDEX IF NOT EXISTS idx_ticks_symbol_time ON ticks(symbol, time)\" , ) if { \"position_id\" , \"symbol\" } . issubset ( written_columns . get ( Dataset . history_deals , set ()), ): conn . execute ( \"CREATE INDEX IF NOT EXISTS idx_history_deals_position_symbol\" \" ON history_deals(position_id, symbol)\" , )","title":"create_history_indexes"},{"location":"api/history/#mt5cli.history.create_positions_reconstructed_view","text":"create_positions_reconstructed_view ( conn : Connection , deals_columns : set [ str ] ) -> bool Create the positions_reconstructed SQLite view derived from history_deals. Returns: Type Description bool True if the view was created, False if required columns are missing. Source code in mt5cli/history.py 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 def create_positions_reconstructed_view ( conn : sqlite3 . Connection , deals_columns : set [ str ], ) -> bool : \"\"\"Create the positions_reconstructed SQLite view derived from history_deals. Returns: True if the view was created, False if required columns are missing. \"\"\" if not _POSITIONS_VIEW_REQUIRED_COLUMNS . issubset ( deals_columns ): missing = \", \" . join ( sorted ( _POSITIONS_VIEW_REQUIRED_COLUMNS - deals_columns )) logger . warning ( \"Skipping positions_reconstructed view: history_deals missing columns: %s \" , missing , ) return False conn . execute ( \"DROP VIEW IF EXISTS positions_reconstructed\" ) conn . execute ( \"CREATE VIEW positions_reconstructed AS\" # noqa: S608 \" SELECT\" \" position_id,\" \" symbol,\" \" MIN(CASE WHEN entry = 0 THEN time END) AS open_time,\" \" MAX(CASE WHEN entry IN (1, 2, 3) THEN time END) AS close_time,\" \" MIN(CASE WHEN entry = 0 THEN type END) AS direction,\" \" SUM(CASE WHEN entry = 0 THEN volume ELSE 0 END) AS volume_open,\" \" SUM(CASE WHEN entry IN (1, 2, 3) THEN volume ELSE 0 END) AS volume_close,\" \" SUM(CASE WHEN entry = 2 THEN volume ELSE 0 END) AS volume_reversal,\" \" CASE\" \" WHEN SUM(CASE WHEN entry = 0 THEN volume ELSE 0 END) > 0\" \" THEN SUM(CASE WHEN entry = 0 THEN price * volume ELSE 0 END)\" \" / SUM(CASE WHEN entry = 0 THEN volume ELSE 0 END)\" \" END AS open_price,\" \" CASE\" \" WHEN SUM(CASE WHEN entry IN (1, 2, 3) THEN volume ELSE 0 END) > 0\" \" THEN SUM(CASE WHEN entry IN (1, 2, 3) THEN price * volume ELSE 0 END)\" \" / SUM(CASE WHEN entry IN (1, 2, 3) THEN volume ELSE 0 END)\" \" END AS close_price,\" \" SUM(profit) AS total_profit,\" \" SUM(CASE WHEN entry = 2 THEN 1 ELSE 0 END) AS reversal_count,\" \" COUNT(*) AS deals_count\" \" FROM history_deals\" f \" WHERE type IN { _TRADE_DEAL_TYPES_SQL } AND position_id != 0\" \" GROUP BY position_id, symbol\" \" HAVING SUM(CASE WHEN entry IN (1, 2, 3) THEN 1 ELSE 0 END) > 0\" , ) return True","title":"create_positions_reconstructed_view"},{"location":"api/history/#mt5cli.history.create_rate_compatibility_views","text":"create_rate_compatibility_views ( conn : Connection ) -> None Create rate compatibility views from the normalized rates table. Source code in mt5cli/history.py 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 def create_rate_compatibility_views ( conn : sqlite3 . Connection ) -> None : \"\"\"Create rate compatibility views from the normalized rates table.\"\"\" columns = get_table_columns ( conn , Dataset . rates . table_name ) if not { \"symbol\" , \"timeframe\" , \"time\" } . issubset ( columns ): return drop_rate_compatibility_views ( conn ) select_columns = sorted ( columns - { \"symbol\" , \"timeframe\" }) quoted_columns = \", \" . join ( f '\" { column } \"' for column in select_columns ) rows = conn . execute ( \"SELECT DISTINCT symbol, timeframe FROM rates ORDER BY symbol, timeframe\" , ) . fetchall () timeframes_by_symbol : dict [ str , list [ int ]] = {} for symbol , timeframe in rows : timeframes_by_symbol . setdefault ( str ( symbol ), []) . append ( int ( timeframe )) for symbol , timeframes in timeframes_by_symbol . items (): for timeframe in timeframes : granularity = resolve_granularity_name ( timeframe ) view_name = build_rate_view_name ( symbol = symbol , granularity = granularity , granularity_count = len ( timeframes ), timeframe = timeframe , ) quoted_view_name = quote_sqlite_identifier ( view_name ) escaped_symbol = symbol . replace ( \"'\" , \"''\" ) conn . execute ( f \"CREATE VIEW { quoted_view_name } AS\" # noqa: S608 f \" SELECT { quoted_columns } FROM rates\" f \" WHERE symbol = ' { escaped_symbol } '\" f \" AND timeframe = { timeframe } \" , )","title":"create_rate_compatibility_views"},{"location":"api/history/#mt5cli.history.deduplicate_history_tables","text":"deduplicate_history_tables ( conn : Connection , written_columns : dict [ Dataset , set [ str ]], written_tables : set [ Dataset ], dedup_scopes : Mapping [ Dataset , Sequence [ DedupScope ]] | None = None , ) -> None Deduplicate appended history tables by stable identifiers. Scopes whose required columns are not present in the written table are skipped. If all scopes for a dataset are skipped, the table receives one unscoped deduplication pass instead. Source code in mt5cli/history.py 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 def deduplicate_history_tables ( conn : sqlite3 . Connection , written_columns : dict [ Dataset , set [ str ]], written_tables : set [ Dataset ], dedup_scopes : Mapping [ Dataset , Sequence [ DedupScope ]] | None = None , ) -> None : \"\"\"Deduplicate appended history tables by stable identifiers. Scopes whose required columns are not present in the written table are skipped. If all scopes for a dataset are skipped, the table receives one unscoped deduplication pass instead. \"\"\" cursor = conn . cursor () for dataset in written_tables : columns = written_columns . get ( dataset , set ()) table = dataset . table_name keys = next ( ( candidate for candidate in _HISTORY_DEDUP_KEYS [ dataset ] if set ( candidate ) . issubset ( columns ) ), None , ) if keys is None : logger . warning ( \"Skipping %s deduplication: no supported key columns\" , table , ) continue raw_scopes : Sequence [ DedupScope ] = ( dedup_scopes . get ( dataset , ()) if dedup_scopes else () ) scopes = [ scope for scope in raw_scopes if scope . required_columns <= columns ] if scopes : for scope in scopes : drop_duplicates_in_table ( cursor , table , list ( keys ), keep = \"last\" , scope_where = scope . where , scope_params = scope . params , ) continue drop_duplicates_in_table ( cursor , table , list ( keys ), keep = \"last\" )","title":"deduplicate_history_tables"},{"location":"api/history/#mt5cli.history.drop_duplicates_in_table","text":"drop_duplicates_in_table ( cursor : Cursor , table : str , ids : list [ str ], * , keep : Literal [ \"first\" , \"last\" ] = \"last\" , scope_where : str | None = None , scope_params : tuple [ object , ... ] = (), ) -> None Remove duplicate rows, keeping the first or last ROWID per key group. Raises: Type Description ValueError If the table or column names are invalid. Source code in mt5cli/history.py 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 def drop_duplicates_in_table ( cursor : sqlite3 . Cursor , table : str , ids : list [ str ], * , keep : Literal [ \"first\" , \"last\" ] = \"last\" , scope_where : str | None = None , scope_params : tuple [ object , ... ] = (), ) -> None : \"\"\"Remove duplicate rows, keeping the first or last ROWID per key group. Raises: ValueError: If the table or column names are invalid. \"\"\" if not table . isidentifier (): msg = f \"Invalid table name: { table } \" raise ValueError ( msg ) if invalid := { column for column in ids if not column . isidentifier ()}: msg = f \"Invalid column names: { ', ' . join ( sorted ( invalid )) } \" raise ValueError ( msg ) ids_csv = \", \" . join ( f '\" { column } \"' for column in ids ) rowid_selector = \"MIN\" if keep == \"first\" else \"MAX\" if scope_where : delete_sql = ( f \"DELETE FROM { table } WHERE { scope_where } AND ROWID NOT IN\" # noqa: S608 f \" (SELECT { rowid_selector } (ROWID) FROM { table } WHERE { scope_where } \" f \" GROUP BY { ids_csv } )\" ) cursor . execute ( delete_sql , scope_params + scope_params ) return cursor . execute ( f \"DELETE FROM { table } WHERE ROWID NOT IN\" # noqa: S608 f \" (SELECT { rowid_selector } (ROWID) FROM { table } GROUP BY { ids_csv } )\" , )","title":"drop_duplicates_in_table"},{"location":"api/history/#mt5cli.history.drop_forming_rate_bar","text":"drop_forming_rate_bar ( df_rate : DataFrame ) -> DataFrame Return closed bars from chronologically ordered MT5 rate data. MetaTrader 5 copy_rates_from_pos(start_pos=0) includes the still-forming current bar as the last row. Slice it off so downstream logic only sees completed bars. Empty frames and single-row frames return empty results. Parameters: Name Type Description Default df_rate DataFrame Rate data ordered oldest-to-newest with the forming bar last. required Returns: Type Description DataFrame A new DataFrame with all rows except the last. Index and columns are DataFrame preserved. The input frame is not modified. Source code in mt5cli/history.py 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 def drop_forming_rate_bar ( df_rate : pd . DataFrame ) -> pd . DataFrame : \"\"\"Return closed bars from chronologically ordered MT5 rate data. MetaTrader 5 ``copy_rates_from_pos(start_pos=0)`` includes the still-forming current bar as the last row. Slice it off so downstream logic only sees completed bars. Empty frames and single-row frames return empty results. Args: df_rate: Rate data ordered oldest-to-newest with the forming bar last. Returns: A new DataFrame with all rows except the last. Index and columns are preserved. The input frame is not modified. \"\"\" return df_rate . iloc [: - 1 ] . copy ()","title":"drop_forming_rate_bar"},{"location":"api/history/#mt5cli.history.drop_rate_compatibility_views","text":"drop_rate_compatibility_views ( conn : Connection ) -> None Drop all mt5cli-managed rate_* compatibility views. Source code in mt5cli/history.py 1355 1356 1357 1358 1359 1360 1361 1362 def drop_rate_compatibility_views ( conn : sqlite3 . Connection ) -> None : \"\"\"Drop all mt5cli-managed ``rate_*`` compatibility views.\"\"\" rows = conn . execute ( \"SELECT name FROM sqlite_master WHERE type = 'view' AND name GLOB 'rate_*'\" , ) . fetchall () for ( view_name ,) in rows : quoted_view_name = quote_sqlite_identifier ( str ( view_name )) conn . execute ( f \"DROP VIEW IF EXISTS { quoted_view_name } \" )","title":"drop_rate_compatibility_views"},{"location":"api/history/#mt5cli.history.filter_incremental_history_deals_frame","text":"filter_incremental_history_deals_frame ( frame : DataFrame , symbols : Sequence [ str ], start_by_symbol : dict [ str , datetime ], account_event_start : datetime , ) -> DataFrame Filter incrementally fetched history_deals by symbol and event start times. Returns: Type Description DataFrame Rows for selected symbols at or after each symbol start, plus account DataFrame events at or after account_event_start . Source code in mt5cli/history.py 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 def filter_incremental_history_deals_frame ( frame : pd . DataFrame , symbols : Sequence [ str ], start_by_symbol : dict [ str , datetime ], account_event_start : datetime , ) -> pd . DataFrame : \"\"\"Filter incrementally fetched history_deals by symbol and event start times. Returns: Rows for selected symbols at or after each symbol start, plus account events at or after ``account_event_start``. \"\"\" if frame . empty : return frame . copy () parsed_times = _frame_parsed_times ( frame ) time_valid = parsed_times . notna () account_event_mask = _history_deals_account_event_mask ( frame ) account_keep = account_event_mask & ( parsed_times >= account_event_start ) trade_keep = pd . Series ( data = False , index = frame . index ) if \"symbol\" in frame . columns : for symbol in symbols : trade_keep |= ( ( frame [ \"symbol\" ] == symbol ) & ( parsed_times >= start_by_symbol [ symbol ]) & ~ account_event_mask ) keep = ( account_keep | trade_keep ) & time_valid return frame . loc [ keep ] . copy ()","title":"filter_incremental_history_deals_frame"},{"location":"api/history/#mt5cli.history.filter_trade_history_frame","text":"filter_trade_history_frame ( frame : DataFrame , symbols : Sequence [ str ], * , include_account_events : bool , ) -> DataFrame Filter trade history rows to selected symbols and account events. Returns: Type Description DataFrame Filtered history rows. Source code in mt5cli/history.py 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 def filter_trade_history_frame ( frame : pd . DataFrame , symbols : Sequence [ str ], * , include_account_events : bool , ) -> pd . DataFrame : \"\"\"Filter trade history rows to selected symbols and account events. Returns: Filtered history rows. \"\"\" if \"symbol\" not in frame . columns : return frame symbol_mask = frame [ \"symbol\" ] . isin ( symbols ) if not include_account_events : return frame . loc [ symbol_mask ] . copy () account_event_mask = _history_deals_account_event_mask ( frame ) return frame . loc [ symbol_mask | account_event_mask ] . copy ()","title":"filter_trade_history_frame"},{"location":"api/history/#mt5cli.history.get_history_deals_account_event_start_datetime","text":"get_history_deals_account_event_start_datetime ( conn : Connection , * , fallback_start : datetime ) -> datetime Return the next update start for account-level history_deals rows. Source code in mt5cli/history.py 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 def get_history_deals_account_event_start_datetime ( conn : sqlite3 . Connection , * , fallback_start : datetime , ) -> datetime : \"\"\"Return the next update start for account-level history_deals rows.\"\"\" table = Dataset . history_deals . table_name columns = get_table_columns ( conn , table ) if \"time\" not in columns : return fallback_start if \"type\" in columns : where_clause = f \"type NOT IN { _TRADE_DEAL_TYPES_SQL } \" elif \"symbol\" in columns : where_clause = \"symbol IS NULL OR symbol = ''\" else : return fallback_start row = conn . execute ( f \"SELECT MAX(time) FROM { table } WHERE { where_clause } \" , # noqa: S608 ) . fetchone () parsed = parse_sqlite_timestamp ( row [ 0 ] if row else None ) return parsed if parsed is not None else fallback_start","title":"get_history_deals_account_event_start_datetime"},{"location":"api/history/#mt5cli.history.get_incremental_start_datetime","text":"get_incremental_start_datetime ( conn : Connection , dataset : Dataset , * , symbol : str , timeframe : int | None , fallback_start : datetime , ) -> datetime Return the next update start datetime from existing MAX(time). Source code in mt5cli/history.py 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 def get_incremental_start_datetime ( conn : sqlite3 . Connection , dataset : Dataset , * , symbol : str , timeframe : int | None , fallback_start : datetime , ) -> datetime : \"\"\"Return the next update start datetime from existing MAX(time).\"\"\" timeframes = [ timeframe ] if timeframe is not None else None starts = load_incremental_start_datetimes ( conn , dataset , symbols = [ symbol ], timeframes = timeframes , fallback_start = fallback_start , ) return starts [ symbol , timeframe ]","title":"get_incremental_start_datetime"},{"location":"api/history/#mt5cli.history.get_table_columns","text":"get_table_columns ( conn : Connection , table : str ) -> set [ str ] Return existing SQLite columns for a table. Source code in mt5cli/history.py 838 839 840 841 842 def get_table_columns ( conn : sqlite3 . Connection , table : str ) -> set [ str ]: \"\"\"Return existing SQLite columns for a table.\"\"\" quoted_table = quote_sqlite_identifier ( table ) rows = conn . execute ( f \"PRAGMA table_info( { quoted_table } )\" ) . fetchall () return { str ( row [ 1 ]) for row in rows }","title":"get_table_columns"},{"location":"api/history/#mt5cli.history.load_incremental_start_datetimes","text":"load_incremental_start_datetimes ( conn : Connection , dataset : Dataset , * , symbols : Sequence [ str ], timeframes : Sequence [ int ] | None = None , fallback_start : datetime , ) -> dict [ tuple [ str , int | None ], datetime ] Return next update start datetimes keyed by symbol and optional timeframe. Source code in mt5cli/history.py 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 def load_incremental_start_datetimes ( conn : sqlite3 . Connection , dataset : Dataset , * , symbols : Sequence [ str ], timeframes : Sequence [ int ] | None = None , fallback_start : datetime , ) -> dict [ tuple [ str , int | None ], datetime ]: \"\"\"Return next update start datetimes keyed by symbol and optional timeframe.\"\"\" table = dataset . table_name columns = get_table_columns ( conn , table ) if dataset is Dataset . rates and columns : _validate_rates_schema ( columns ) if \"time\" not in columns : if dataset is Dataset . rates and timeframes is not None : return { ( symbol , timeframe ): fallback_start for symbol in symbols for timeframe in timeframes } return {( symbol , None ): fallback_start for symbol in symbols } parsed_by_key : dict [ tuple [ str , int | None ], datetime ] = {} if ( dataset is Dataset . rates and timeframes is not None and { \"symbol\" , \"timeframe\" } . issubset ( columns ) ): symbol_placeholders = \", \" . join ( \"?\" for _ in symbols ) timeframe_placeholders = \", \" . join ( \"?\" for _ in timeframes ) grouped_rates_query = ( \"SELECT symbol, timeframe, MAX(time) FROM \" # noqa: S608 f \" { table } WHERE symbol IN ( { symbol_placeholders } )\" f \" AND timeframe IN ( { timeframe_placeholders } )\" \" GROUP BY symbol, timeframe\" ) rows = conn . execute ( grouped_rates_query , [ * symbols , * timeframes ], ) . fetchall () for row_symbol , row_timeframe , max_time in rows : parsed = parse_sqlite_timestamp ( max_time ) if parsed is not None : parsed_by_key [ str ( row_symbol ), int ( row_timeframe )] = parsed return { ( symbol , timeframe ): parsed_by_key . get ( ( symbol , timeframe ), fallback_start , ) for symbol in symbols for timeframe in timeframes } if \"symbol\" in columns : symbol_placeholders = \", \" . join ( \"?\" for _ in symbols ) rows = conn . execute ( f \"SELECT symbol, MAX(time) FROM { table } \" # noqa: S608 f \" WHERE symbol IN ( { symbol_placeholders } ) GROUP BY symbol\" , list ( symbols ), ) . fetchall () for row_symbol , max_time in rows : parsed = parse_sqlite_timestamp ( max_time ) if parsed is not None : parsed_by_key [ str ( row_symbol ), None ] = parsed return { ( symbol , None ): parsed_by_key . get (( symbol , None ), fallback_start ) for symbol in symbols } row = conn . execute ( f \"SELECT MAX(time) FROM { table } \" ) . fetchone () # noqa: S608 parsed = parse_sqlite_timestamp ( row [ 0 ] if row else None ) shared_start = parsed if parsed is not None else fallback_start return {( symbol , None ): shared_start for symbol in symbols }","title":"load_incremental_start_datetimes"},{"location":"api/history/#mt5cli.history.load_rate_data","text":"load_rate_data ( conn_or_path : SqliteConnOrPath , table : str , count : int | None = None , ) -> DataFrame Load rate-like data from a SQLite database path or connection. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath SQLite database path or open connection. required table str Source table or view name. required count int | None Optional number of most recent rows to load. None Returns: Type Description DataFrame DataFrame indexed by ascending time . Source code in mt5cli/history.py 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 def load_rate_data ( conn_or_path : SqliteConnOrPath , table : str , count : int | None = None , ) -> pd . DataFrame : \"\"\"Load rate-like data from a SQLite database path or connection. Args: conn_or_path: SQLite database path or open connection. table: Source table or view name. count: Optional number of most recent rows to load. Returns: DataFrame indexed by ascending ``time``. \"\"\" conn , should_close = _open_existing_sqlite_database ( conn_or_path ) try : return load_rate_data_from_connection ( conn , table , count = count ) finally : if should_close : conn . close ()","title":"load_rate_data"},{"location":"api/history/#mt5cli.history.load_rate_data_from_connection","text":"load_rate_data_from_connection ( connection : Connection , table : str , count : int | None = None , ) -> DataFrame Load rate-like data from a SQLite table or view. Parameters: Name Type Description Default connection Connection Open SQLite connection. required table str Source table or view name. required count int | None Optional number of most recent rows to load. None Returns: Type Description DataFrame DataFrame indexed by ascending time . Raises: Type Description ValueError If inputs, schema, timestamps are invalid, or the table or view contains no rows. Source code in mt5cli/history.py 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 def load_rate_data_from_connection ( connection : sqlite3 . Connection , table : str , count : int | None = None , ) -> pd . DataFrame : \"\"\"Load rate-like data from a SQLite table or view. Args: connection: Open SQLite connection. table: Source table or view name. count: Optional number of most recent rows to load. Returns: DataFrame indexed by ascending ``time``. Raises: ValueError: If inputs, schema, timestamps are invalid, or the table or view contains no rows. \"\"\" table_name = _validate_rate_load_request ( table , count ) columns = get_table_columns ( connection , table_name ) _ensure_rate_columns ( columns , table_name ) quoted_table = quote_sqlite_identifier ( table_name ) if count is None : frame = cast ( \"pd.DataFrame\" , pd . read_sql_query ( # type: ignore[reportUnknownMemberType] f \"SELECT * FROM { quoted_table } ORDER BY time ASC\" , # noqa: S608 connection , ), ) else : frame = cast ( \"pd.DataFrame\" , pd . read_sql_query ( # type: ignore[reportUnknownMemberType] f \"SELECT * FROM { quoted_table } ORDER BY time DESC LIMIT ?\" , # noqa: S608 connection , params = ( count ,), ), ) if frame . empty : msg = f \"SQLite table or view { table_name !r} contains no rows.\" raise ValueError ( msg ) return _parse_rate_time_index ( frame , table_name )","title":"load_rate_data_from_connection"},{"location":"api/history/#mt5cli.history.load_rate_series_by_granularity","text":"load_rate_series_by_granularity ( conn_or_path : SqliteConnOrPath , symbols : Sequence [ str ], granularities : Sequence [ int | str ], count : int , * , explicit_tables : Sequence [ str ] | None = None , allow_missing_symbol : bool = False , ) -> dict [ tuple [ str | None , str ], DataFrame ] Load rate series keyed by symbol and string granularity name. Builds targets with :func: build_rate_targets and loads them with :func: load_rate_series_from_sqlite , then rekeys the result by granularity name (for example M1 ) instead of the integer timeframe to reduce downstream boilerplate. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath SQLite database path or open connection. required symbols Sequence [ str ] MT5 symbol names. May be empty when allow_missing_symbol . required granularities Sequence [ int | str ] MT5 timeframes as integers or names (for example M1 ). required count int Number of most recent rows to load per series. required explicit_tables Sequence [ str ] | None Optional explicit table or view names matching the built targets in row-major order. Required when symbols are omitted. None allow_missing_symbol bool When True and symbols is empty, build targets with symbol=None for each granularity instead of raising. False Returns: Type Description dict [ tuple [ str | None, str ], DataFrame ] Mapping keyed by (symbol | None, granularity_name) to each rate dict [ tuple [ str | None, str ], DataFrame ] DataFrame. Propagates ValueError (via :func: build_rate_targets and dict [ tuple [ str | None, str ], DataFrame ] func: load_rate_series_from_sqlite ) when inputs are empty or invalid, dict [ tuple [ str | None, str ], DataFrame ] table resolution fails, or duplicate targets are present. Source code in mt5cli/history.py 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 def load_rate_series_by_granularity ( conn_or_path : SqliteConnOrPath , symbols : Sequence [ str ], granularities : Sequence [ int | str ], count : int , * , explicit_tables : Sequence [ str ] | None = None , allow_missing_symbol : bool = False , ) -> dict [ tuple [ str | None , str ], pd . DataFrame ]: \"\"\"Load rate series keyed by symbol and string granularity name. Builds targets with :func:`build_rate_targets` and loads them with :func:`load_rate_series_from_sqlite`, then rekeys the result by granularity name (for example ``M1``) instead of the integer timeframe to reduce downstream boilerplate. Args: conn_or_path: SQLite database path or open connection. symbols: MT5 symbol names. May be empty when ``allow_missing_symbol``. granularities: MT5 timeframes as integers or names (for example ``M1``). count: Number of most recent rows to load per series. explicit_tables: Optional explicit table or view names matching the built targets in row-major order. Required when symbols are omitted. allow_missing_symbol: When True and ``symbols`` is empty, build targets with ``symbol=None`` for each granularity instead of raising. Returns: Mapping keyed by ``(symbol | None, granularity_name)`` to each rate DataFrame. Propagates ``ValueError`` (via :func:`build_rate_targets` and :func:`load_rate_series_from_sqlite`) when inputs are empty or invalid, table resolution fails, or duplicate targets are present. \"\"\" targets = build_rate_targets ( symbols , granularities , allow_missing_symbol = allow_missing_symbol , ) series = load_rate_series_from_sqlite ( conn_or_path , targets , count , explicit_tables = explicit_tables , ) return { ( symbol , resolve_granularity_name ( timeframe )): frame for ( symbol , timeframe ), frame in series . items () }","title":"load_rate_series_by_granularity"},{"location":"api/history/#mt5cli.history.load_rate_series_from_sqlite","text":"load_rate_series_from_sqlite ( conn_or_path : SqliteConnOrPath , targets : None = None , count : int | None = None , explicit_tables : None = None , * , table : str , ) -> DataFrame load_rate_series_from_sqlite ( conn_or_path : SqliteConnOrPath , targets : None = None , count : int | None = None , explicit_tables : Sequence [ str ] | None = None , * , table : None = None , ) -> dict [ tuple [ str | None , int ], DataFrame ] load_rate_series_from_sqlite ( conn_or_path : SqliteConnOrPath , targets : Sequence [ RateTarget ], count : int , explicit_tables : Sequence [ str ] | None = None , * , table : None = None , ) -> dict [ tuple [ str | None , int ], DataFrame ] load_rate_series_from_sqlite ( conn_or_path : SqliteConnOrPath , targets : Sequence [ RateTarget ] | None = None , count : int | None = None , explicit_tables : Sequence [ str ] | None = None , * , table : str | None = None , ) -> dict [ tuple [ str | None , int ], DataFrame ] | DataFrame Load one table/view or multiple rate series from a SQLite database. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath SQLite database path or open connection. required targets Sequence [ RateTarget ] | None Rate targets to load. Each (symbol, timeframe_int) pair must be unique. Omit when loading a single explicit table . None count int | None Optional number of most recent rows to load per series. None explicit_tables Sequence [ str ] | None Optional explicit table or view names matching targets. When omitted, managed rate_* compatibility views must already exist in the database. None table str | None Optional single table or view name to load directly. None Returns: Type Description dict [ tuple [ str | None, int ], DataFrame ] | DataFrame A DataFrame when table is provided, otherwise a mapping keyed by dict [ tuple [ str | None, int ], DataFrame ] | DataFrame (symbol, timeframe_int) to each rate DataFrame. Raises: Type Description ValueError If count is not positive, targets are empty, duplicate (symbol, timeframe_int) pairs are present, or table resolution fails. Source code in mt5cli/history.py 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 def load_rate_series_from_sqlite ( conn_or_path : SqliteConnOrPath , targets : Sequence [ RateTarget ] | None = None , count : int | None = None , explicit_tables : Sequence [ str ] | None = None , * , table : str | None = None , ) -> dict [ tuple [ str | None , int ], pd . DataFrame ] | pd . DataFrame : \"\"\"Load one table/view or multiple rate series from a SQLite database. Args: conn_or_path: SQLite database path or open connection. targets: Rate targets to load. Each ``(symbol, timeframe_int)`` pair must be unique. Omit when loading a single explicit ``table``. count: Optional number of most recent rows to load per series. explicit_tables: Optional explicit table or view names matching targets. When omitted, managed ``rate_*`` compatibility views must already exist in the database. table: Optional single table or view name to load directly. Returns: A DataFrame when ``table`` is provided, otherwise a mapping keyed by ``(symbol, timeframe_int)`` to each rate DataFrame. Raises: ValueError: If ``count`` is not positive, targets are empty, duplicate ``(symbol, timeframe_int)`` pairs are present, or table resolution fails. \"\"\" if table is not None : return load_rate_data ( conn_or_path , table , count = count ) if count is None or count <= 0 : msg = \"count must be positive.\" raise ValueError ( msg ) if targets is None : msg = \"targets are required when table is not provided.\" raise ValueError ( msg ) target_list = list ( targets ) if not target_list : msg = \"At least one rate target is required.\" raise ValueError ( msg ) if explicit_tables is None and any ( target . symbol is None for target in target_list ): msg = ( \"Cannot resolve a rate table for a target without a symbol; \" \"provide explicit_tables.\" ) raise ValueError ( msg ) seen_keys : set [ tuple [ str | None , int ]] = set () for target in target_list : key = ( target . symbol , target . timeframe_int ) if key in seen_keys : symbol_repr = repr ( target . symbol ) msg = f \"Duplicate rate target: ( { symbol_repr } , { target . timeframe_int } )\" raise ValueError ( msg ) seen_keys . add ( key ) tables = ( resolve_rate_tables ( None , target_list , explicit_tables ) if explicit_tables is not None else None ) conn , should_close = _open_existing_sqlite_database ( conn_or_path ) try : resolved_tables = tables or resolve_rate_tables ( conn , target_list , require_existing = True , ) return { ( target . symbol , target . timeframe_int ): load_rate_data_from_connection ( conn , table , count = count , ) for target , table in zip ( target_list , resolved_tables , strict = True ) } finally : if should_close : conn . close ()","title":"load_rate_series_from_sqlite"},{"location":"api/history/#mt5cli.history.parse_sqlite_timestamp","text":"parse_sqlite_timestamp ( value : object ) -> datetime | None Parse a SQLite history timestamp value. Returns: Type Description datetime | None Parsed timezone-aware datetime, or None when parsing fails. Source code in mt5cli/history.py 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 def parse_sqlite_timestamp ( value : object ) -> datetime | None : \"\"\"Parse a SQLite history timestamp value. Returns: Parsed timezone-aware datetime, or None when parsing fails. \"\"\" if value is None : return None if isinstance ( value , datetime ): return value if value . tzinfo is not None else value . replace ( tzinfo = UTC ) if isinstance ( value , int | float ): return datetime . fromtimestamp ( float ( value ), tz = UTC ) if isinstance ( value , str ): return _parse_string_sqlite_timestamp ( value ) logger . warning ( \"Ignoring unsupported history timestamp type: %s \" , type ( value )) return None","title":"parse_sqlite_timestamp"},{"location":"api/history/#mt5cli.history.quote_sqlite_identifier","text":"quote_sqlite_identifier ( identifier : str ) -> str Return a safely quoted SQLite identifier using double quotes. Source code in mt5cli/history.py 56 57 58 def quote_sqlite_identifier ( identifier : str ) -> str : \"\"\"Return a safely quoted SQLite identifier using double quotes.\"\"\" return '\"' + identifier . replace ( '\"' , '\"\"' ) + '\"'","title":"quote_sqlite_identifier"},{"location":"api/history/#mt5cli.history.record_written_columns","text":"record_written_columns ( written_columns : dict [ Dataset , set [ str ]], dataset : Dataset , frame : DataFrame , ) -> None Remember columns for datasets written during collection. Source code in mt5cli/history.py 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 def record_written_columns ( written_columns : dict [ Dataset , set [ str ]], dataset : Dataset , frame : pd . DataFrame , ) -> None : \"\"\"Remember columns for datasets written during collection.\"\"\" columns = set ( frame . columns ) if dataset in written_columns : written_columns [ dataset ] . update ( columns ) else : written_columns [ dataset ] = columns","title":"record_written_columns"},{"location":"api/history/#mt5cli.history.resolve_granularity_name","text":"resolve_granularity_name ( timeframe : int ) -> str Return a granularity name for a timeframe integer when known. Source code in mt5cli/history.py 101 102 103 104 105 106 107 def resolve_granularity_name ( timeframe : int ) -> str : \"\"\"Return a granularity name for a timeframe integer when known.\"\"\" try : name = _get_timeframe_name ( timeframe ) except ValueError : return str ( timeframe ) return name . removeprefix ( \"TIMEFRAME_\" )","title":"resolve_granularity_name"},{"location":"api/history/#mt5cli.history.resolve_history_datasets","text":"resolve_history_datasets ( datasets : set [ Dataset ] | None , ) -> set [ Dataset ] Resolve configured history datasets. Returns: Type Description set [ Dataset ] All supported datasets when datasets is None, otherwise the set [ Dataset ] configured selection (which may be empty). Source code in mt5cli/history.py 61 62 63 64 65 66 67 68 69 70 def resolve_history_datasets ( datasets : set [ Dataset ] | None ) -> set [ Dataset ]: \"\"\"Resolve configured history datasets. Returns: All supported datasets when ``datasets`` is None, otherwise the configured selection (which may be empty). \"\"\" if datasets is None : return set ( Dataset ) return set ( datasets )","title":"resolve_history_datasets"},{"location":"api/history/#mt5cli.history.resolve_history_tick_flags","text":"resolve_history_tick_flags ( flags : int | str ) -> int Resolve tick copy flags from an integer or name. Returns: Type Description int Integer tick flag value. Source code in mt5cli/history.py 92 93 94 95 96 97 98 def resolve_history_tick_flags ( flags : int | str ) -> int : \"\"\"Resolve tick copy flags from an integer or name. Returns: Integer tick flag value. \"\"\" return parse_tick_flags ( flags )","title":"resolve_history_tick_flags"},{"location":"api/history/#mt5cli.history.resolve_history_timeframes","text":"resolve_history_timeframes ( timeframes : Sequence [ int | str ] | None , ) -> list [ int ] Resolve rate timeframes, deduplicating aliases for the same integer. Returns: Type Description list [ int ] Ordered list of unique timeframe integers. Source code in mt5cli/history.py 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 def resolve_history_timeframes ( timeframes : Sequence [ int | str ] | None , ) -> list [ int ]: \"\"\"Resolve rate timeframes, deduplicating aliases for the same integer. Returns: Ordered list of unique timeframe integers. \"\"\" raw = timeframes if timeframes is not None else DEFAULT_HISTORY_TIMEFRAMES seen : set [ int ] = set () resolved : list [ int ] = [] for value in raw : tf = parse_timeframe ( value ) if tf not in seen : seen . add ( tf ) resolved . append ( tf ) return resolved","title":"resolve_history_timeframes"},{"location":"api/history/#mt5cli.history.resolve_rate_table_name","text":"resolve_rate_table_name ( symbol : str , granularity : str ) -> str Return the canonical normalized SQLite rate table name. The normalized history table stores all symbols and timeframes in rates ; use :func: resolve_rate_view_name for per-symbol compatibility view names. Returns: Type Description str Canonical normalized rates table name. Raises: Type Description ValueError If symbol or granularity is invalid. Source code in mt5cli/history.py 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 def resolve_rate_table_name ( symbol : str , granularity : str ) -> str : \"\"\"Return the canonical normalized SQLite rate table name. The normalized history table stores all symbols and timeframes in ``rates``; use :func:`resolve_rate_view_name` for per-symbol compatibility view names. Returns: Canonical normalized rates table name. Raises: ValueError: If ``symbol`` or ``granularity`` is invalid. \"\"\" parse_timeframe ( granularity ) if not symbol . strip (): msg = \"symbol must not be empty.\" raise ValueError ( msg ) return Dataset . rates . table_name","title":"resolve_rate_table_name"},{"location":"api/history/#mt5cli.history.resolve_rate_tables","text":"resolve_rate_tables ( conn_or_path : SqliteConnOrPath | None , targets : Sequence [ RateTarget ], explicit_tables : Sequence [ str ] | None = None , * , require_existing : bool = False , ) -> list [ str ] Resolve SQLite table or view names for rate targets. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath | None SQLite database path or open connection. May be None when explicit_tables is provided, or when require_existing is False and deterministic default view names are sufficient. required targets Sequence [ RateTarget ] Rate targets to resolve. required explicit_tables Sequence [ str ] | None Optional explicit table or view names. When provided, they are used as-is and must match the number of targets. None require_existing bool When True, require the database and managed views to exist for each symbol target. Ignored when explicit_tables is provided. False Returns: Type Description list [ str ] Table or view names aligned with targets . Raises: Type Description ValueError If targets is empty, explicit_tables length does not match the target count, a target without a symbol is resolved without an explicit table, or require_existing is True and the database or a managed view is missing. Source code in mt5cli/history.py 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 def resolve_rate_tables ( conn_or_path : SqliteConnOrPath | None , targets : Sequence [ RateTarget ], explicit_tables : Sequence [ str ] | None = None , * , require_existing : bool = False , ) -> list [ str ]: \"\"\"Resolve SQLite table or view names for rate targets. Args: conn_or_path: SQLite database path or open connection. May be None when ``explicit_tables`` is provided, or when ``require_existing`` is False and deterministic default view names are sufficient. targets: Rate targets to resolve. explicit_tables: Optional explicit table or view names. When provided, they are used as-is and must match the number of targets. require_existing: When True, require the database and managed views to exist for each symbol target. Ignored when ``explicit_tables`` is provided. Returns: Table or view names aligned with ``targets``. Raises: ValueError: If ``targets`` is empty, ``explicit_tables`` length does not match the target count, a target without a symbol is resolved without an explicit table, or ``require_existing`` is True and the database or a managed view is missing. \"\"\" target_list = list ( targets ) if not target_list : msg = \"At least one rate target is required.\" raise ValueError ( msg ) if explicit_tables is not None : tables = list ( explicit_tables ) if len ( tables ) != len ( target_list ): msg = ( f \"Expected { len ( target_list ) } explicit table(s) \" f \"to match the targets, got { len ( tables ) } .\" ) raise ValueError ( msg ) return tables if any ( target . symbol is None for target in target_list ): msg = ( \"Cannot resolve a rate table for a target without a symbol; \" \"provide explicit_tables.\" ) raise ValueError ( msg ) conn , should_close = _open_history_connection ( conn_or_path ) try : if conn is None : if require_existing : path = ( conn_or_path if isinstance ( conn_or_path , ( Path , str )) else \"database\" ) msg = f \"SQLite database not found: { path } \" raise ValueError ( msg ) timeframe_counts = None existing_views : set [ str ] = set () else : timeframe_counts = _load_rates_timeframe_counts ( conn ) existing_views = _load_existing_rate_views ( conn ) resolved : list [ str ] = [] for target in target_list : symbol = cast ( \"str\" , target . symbol ) timeframe = target . timeframe_int resolved . append ( _resolve_rate_view_name_from_context ( symbol = symbol , timeframe = timeframe , granularity_name = resolve_granularity_name ( timeframe ), timeframe_counts = timeframe_counts , existing_views = existing_views , require_existing = require_existing , ), ) return resolved finally : if should_close and conn is not None : conn . close ()","title":"resolve_rate_tables"},{"location":"api/history/#mt5cli.history.resolve_rate_view_name","text":"resolve_rate_view_name ( conn_or_path : SqliteConnOrPath | None , symbol : str , granularity : str , * , require_existing : bool = False , ) -> str Resolve the mt5cli-managed rate compatibility view name. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath | None SQLite database path or open connection. When None or a non-existing path and require_existing is False, the deterministic default view name is returned without creating a database file. required symbol str Symbol stored in the normalized rates table. required granularity str Timeframe name (for example M1 ) or integer string. required require_existing bool When True, require the database and a managed view to exist. False Returns: Type Description str View name such as rate_EURUSD__1 or rate_EURUSD__M1_1 . Raises: Type Description ValueError If require_existing is True and the database or view is missing. Source code in mt5cli/history.py 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 def resolve_rate_view_name ( conn_or_path : SqliteConnOrPath | None , symbol : str , granularity : str , * , require_existing : bool = False , ) -> str : \"\"\"Resolve the mt5cli-managed rate compatibility view name. Args: conn_or_path: SQLite database path or open connection. When None or a non-existing path and ``require_existing`` is False, the deterministic default view name is returned without creating a database file. symbol: Symbol stored in the normalized ``rates`` table. granularity: Timeframe name (for example ``M1``) or integer string. require_existing: When True, require the database and a managed view to exist. Returns: View name such as ``rate_EURUSD__1`` or ``rate_EURUSD__M1_1``. Raises: ValueError: If ``require_existing`` is True and the database or view is missing. \"\"\" timeframe = parse_timeframe ( granularity ) granularity_name = resolve_granularity_name ( timeframe ) conn , should_close = _open_history_connection ( conn_or_path ) try : if conn is None : if require_existing : path = ( conn_or_path if isinstance ( conn_or_path , ( Path , str )) else \"database\" ) msg = f \"SQLite database not found: { path } \" raise ValueError ( msg ) return build_rate_view_name ( symbol = symbol , granularity = granularity_name , granularity_count = 1 , timeframe = timeframe , ) return _resolve_rate_view_name_from_context ( symbol = symbol , timeframe = timeframe , granularity_name = granularity_name , timeframe_counts = _load_rates_timeframe_counts ( conn ), existing_views = _load_existing_rate_views ( conn ), require_existing = require_existing , ) finally : if should_close and conn is not None : conn . close ()","title":"resolve_rate_view_name"},{"location":"api/history/#mt5cli.history.resolve_rate_view_names","text":"resolve_rate_view_names ( conn_or_path : SqliteConnOrPath | None , symbols : Sequence [ str ], granularities : Sequence [ str ], * , require_existing : bool = False , ) -> list [ str ] Resolve rate compatibility view names for symbol and granularity pairs. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath | None SQLite database path or open connection. When None or a non-existing path and require_existing is False, deterministic default view names are returned without creating a database file. required symbols Sequence [ str ] Symbols stored in the normalized rates table. required granularities Sequence [ str ] Timeframe names (for example M1 ) or integer strings. required require_existing bool When True, require the database and managed views to exist. False Returns: Type Description list [ str ] View names in row-major order: every granularity for the first list [ str ] symbol, then every granularity for the next symbol, and so on. Source code in mt5cli/history.py 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 def resolve_rate_view_names ( conn_or_path : SqliteConnOrPath | None , symbols : Sequence [ str ], granularities : Sequence [ str ], * , require_existing : bool = False , ) -> list [ str ]: \"\"\"Resolve rate compatibility view names for symbol and granularity pairs. Args: conn_or_path: SQLite database path or open connection. When None or a non-existing path and ``require_existing`` is False, deterministic default view names are returned without creating a database file. symbols: Symbols stored in the normalized ``rates`` table. granularities: Timeframe names (for example ``M1``) or integer strings. require_existing: When True, require the database and managed views to exist. Returns: View names in row-major order: every ``granularity`` for the first symbol, then every granularity for the next symbol, and so on. \"\"\" conn , should_close = _open_history_connection ( conn_or_path ) try : if conn is None : return [ resolve_rate_view_name ( conn_or_path , symbol , granularity , require_existing = require_existing , ) for symbol in symbols for granularity in granularities ] timeframe_counts = _load_rates_timeframe_counts ( conn ) existing_views = _load_existing_rate_views ( conn ) resolved : list [ str ] = [] for symbol in symbols : for granularity in granularities : timeframe = parse_timeframe ( granularity ) resolved . append ( _resolve_rate_view_name_from_context ( symbol = symbol , timeframe = timeframe , granularity_name = resolve_granularity_name ( timeframe ), timeframe_counts = timeframe_counts , existing_views = existing_views , require_existing = require_existing , ), ) return resolved finally : if should_close and conn is not None : conn . close ()","title":"resolve_rate_view_names"},{"location":"api/history/#mt5cli.history.write_collected_datasets","text":"write_collected_datasets ( conn : Connection , client : Mt5DataClient , symbols : Sequence [ str ], datasets : set [ Dataset ], timeframe : int , flags : int , date_from : datetime , date_to : datetime , if_exists : IfExists , ) -> tuple [ set [ Dataset ], dict [ Dataset , set [ str ]]] Collect selected datasets and stream each symbol frame into SQLite. Returns: Type Description tuple [ set [ Dataset ], dict [ Dataset , set [ str ]]] Written datasets and their columns. Source code in mt5cli/history.py 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 def write_collected_datasets ( conn : sqlite3 . Connection , client : Mt5DataClient , symbols : Sequence [ str ], datasets : set [ Dataset ], timeframe : int , flags : int , date_from : datetime , date_to : datetime , if_exists : IfExists , ) -> tuple [ set [ Dataset ], dict [ Dataset , set [ str ]]]: \"\"\"Collect selected datasets and stream each symbol frame into SQLite. Returns: Written datasets and their columns. \"\"\" written_columns : dict [ Dataset , set [ str ]] = {} written_tables : set [ Dataset ] = set () if Dataset . rates in datasets and write_rates_dataset ( conn , client , symbols , timeframe , date_from , date_to , if_exists , written_columns , ): written_tables . add ( Dataset . rates ) if Dataset . ticks in datasets and write_ticks_dataset ( conn , client , symbols , flags , date_from , date_to , if_exists , written_columns , ): written_tables . add ( Dataset . ticks ) if Dataset . history_orders in datasets and write_history_dataset ( conn , client . history_orders_get_as_df , Dataset . history_orders , symbols , date_from , date_to , if_exists , written_columns , include_account_events = False , ): written_tables . add ( Dataset . history_orders ) if Dataset . history_deals in datasets and write_history_dataset ( conn , client . history_deals_get_as_df , Dataset . history_deals , symbols , date_from , date_to , if_exists , written_columns , include_account_events = False , ): written_tables . add ( Dataset . history_deals ) return written_tables , written_columns","title":"write_collected_datasets"},{"location":"api/history/#mt5cli.history.write_history_dataset","text":"write_history_dataset ( conn : Connection , fetch : Callable [ ... , DataFrame ], dataset : Dataset , symbols : Sequence [ str ], date_from : datetime , date_to : datetime , if_exists : IfExists , written_columns : dict [ Dataset , set [ str ]], * , include_account_events : bool = False , ) -> bool Stream a history dataset into SQLite. Returns: Type Description bool True if the target table was written. Source code in mt5cli/history.py 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 def write_history_dataset ( conn : sqlite3 . Connection , fetch : Callable [ ... , pd . DataFrame ], dataset : Dataset , symbols : Sequence [ str ], date_from : datetime , date_to : datetime , if_exists : IfExists , written_columns : dict [ Dataset , set [ str ]], * , include_account_events : bool = False , ) -> bool : \"\"\"Stream a history dataset into SQLite. Returns: True if the target table was written. \"\"\" table_exists = False if include_account_events : frame = filter_trade_history_frame ( fetch ( date_from = date_from , date_to = date_to ), symbols , include_account_events = True , ) return write_streamed_frame ( conn , frame , dataset , table_exists , if_exists , written_columns , ) def _fetch_history_frame ( sym : str ) -> pd . DataFrame : return filter_trade_history_frame ( fetch ( date_from = date_from , date_to = date_to , symbol = sym ), [ sym ], include_account_events = False , ) return _stream_symbol_frames ( conn , symbols , dataset , if_exists , written_columns , _fetch_history_frame , )","title":"write_history_dataset"},{"location":"api/history/#mt5cli.history.write_incremental_datasets","text":"write_incremental_datasets ( conn : Connection , client : Mt5DataClient , symbols : Sequence [ str ], selected_datasets : set [ Dataset ], resolved_timeframes : list [ int ], resolved_tick_flags : int , fallback_start : datetime , end_date : datetime , * , deduplicate : bool , create_rate_views : bool , with_views : bool , include_account_events : bool , ) -> tuple [ set [ Dataset ], dict [ Dataset , set [ str ]]] Append selected datasets incrementally and refresh indexes and views. Returns: Type Description tuple [ set [ Dataset ], dict [ Dataset , set [ str ]]] Written datasets and their columns. Source code in mt5cli/history.py 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 def write_incremental_datasets ( # noqa: PLR0913 conn : sqlite3 . Connection , client : Mt5DataClient , symbols : Sequence [ str ], selected_datasets : set [ Dataset ], resolved_timeframes : list [ int ], resolved_tick_flags : int , fallback_start : datetime , end_date : datetime , * , deduplicate : bool , create_rate_views : bool , with_views : bool , include_account_events : bool , ) -> tuple [ set [ Dataset ], dict [ Dataset , set [ str ]]]: \"\"\"Append selected datasets incrementally and refresh indexes and views. Returns: Written datasets and their columns. \"\"\" written_columns : dict [ Dataset , set [ str ]] = {} written_tables : set [ Dataset ] = set () dedup_scopes : dict [ Dataset , list [ DedupScope ]] = {} if Dataset . rates in selected_datasets : _write_incremental_rates ( conn , client , symbols , resolved_timeframes , fallback_start , end_date , written_columns , written_tables , dedup_scopes , ) if Dataset . ticks in selected_datasets : _write_incremental_ticks ( conn , client , symbols , resolved_tick_flags , fallback_start , end_date , written_columns , written_tables , dedup_scopes , ) if Dataset . history_orders in selected_datasets : _write_incremental_history_orders ( conn , client , symbols , fallback_start , end_date , written_columns , written_tables , dedup_scopes , ) if Dataset . history_deals in selected_datasets : _write_incremental_history_deals ( conn , client , symbols , fallback_start , end_date , written_columns , written_tables , dedup_scopes , include_account_events = include_account_events , ) _finalize_incremental_writes ( conn , selected_datasets , written_columns , written_tables , dedup_scopes , deduplicate = deduplicate , create_rate_views = create_rate_views , with_views = with_views , ) return written_tables , written_columns","title":"write_incremental_datasets"},{"location":"api/history/#mt5cli.history.write_rates_dataset","text":"write_rates_dataset ( conn : Connection , client : Mt5DataClient , symbols : Sequence [ str ], timeframe : int , date_from : datetime , date_to : datetime , if_exists : IfExists , written_columns : dict [ Dataset , set [ str ]], ) -> bool Stream rates frames into SQLite. Returns: Type Description bool True if the rates table was written. Source code in mt5cli/history.py 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 def write_rates_dataset ( conn : sqlite3 . Connection , client : Mt5DataClient , symbols : Sequence [ str ], timeframe : int , date_from : datetime , date_to : datetime , if_exists : IfExists , written_columns : dict [ Dataset , set [ str ]], ) -> bool : \"\"\"Stream rates frames into SQLite. Returns: True if the rates table was written. \"\"\" def _fetch_rates_frame ( sym : str ) -> pd . DataFrame : frame = client . copy_rates_range_as_df ( symbol = sym , timeframe = timeframe , date_from = date_from , date_to = date_to , ) . drop ( columns = [ \"symbol\" , \"timeframe\" ], errors = \"ignore\" ) if len ( frame . columns ) != 0 : frame . insert ( 0 , \"symbol\" , sym ) frame . insert ( 1 , \"timeframe\" , timeframe ) return frame return _stream_symbol_frames ( conn , symbols , Dataset . rates , if_exists , written_columns , _fetch_rates_frame , )","title":"write_rates_dataset"},{"location":"api/history/#mt5cli.history.write_streamed_frame","text":"write_streamed_frame ( conn : Connection , frame : DataFrame , dataset : Dataset , table_exists : bool , if_exists : IfExists , written_columns : dict [ Dataset , set [ str ]], ) -> bool Write one streamed dataset frame and track table state. Returns: Type Description bool True if the dataset table exists after this write attempt. Source code in mt5cli/history.py 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 def write_streamed_frame ( conn : sqlite3 . Connection , frame : pd . DataFrame , dataset : Dataset , table_exists : bool , if_exists : IfExists , written_columns : dict [ Dataset , set [ str ]], ) -> bool : \"\"\"Write one streamed dataset frame and track table state. Returns: True if the dataset table exists after this write attempt. \"\"\" write_mode = IfExists . APPEND if table_exists else if_exists if append_dataframe ( conn , frame , dataset . table_name , write_mode ): record_written_columns ( written_columns , dataset , frame ) return True return table_exists","title":"write_streamed_frame"},{"location":"api/history/#mt5cli.history.write_ticks_dataset","text":"write_ticks_dataset ( conn : Connection , client : Mt5DataClient , symbols : Sequence [ str ], flags : int , date_from : datetime , date_to : datetime , if_exists : IfExists , written_columns : dict [ Dataset , set [ str ]], ) -> bool Stream ticks frames into SQLite. Returns: Type Description bool True if the ticks table was written. Source code in mt5cli/history.py 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 def write_ticks_dataset ( conn : sqlite3 . Connection , client : Mt5DataClient , symbols : Sequence [ str ], flags : int , date_from : datetime , date_to : datetime , if_exists : IfExists , written_columns : dict [ Dataset , set [ str ]], ) -> bool : \"\"\"Stream ticks frames into SQLite. Returns: True if the ticks table was written. \"\"\" def _fetch_ticks_frame ( sym : str ) -> pd . DataFrame : frame = client . copy_ticks_range_as_df ( symbol = sym , date_from = date_from , date_to = date_to , flags = flags , ) . drop ( columns = [ \"symbol\" ], errors = \"ignore\" ) if len ( frame . columns ) != 0 : frame . insert ( 0 , \"symbol\" , sym ) return frame return _stream_symbol_frames ( conn , symbols , Dataset . ticks , if_exists , written_columns , _fetch_ticks_frame , )","title":"write_ticks_dataset"},{"location":"api/history/#collect-history-schema","text":"The collect-history command (and the matching collect_history SDK function) writes selected MT5 datasets into one SQLite database. Each dataset becomes a table; column names and types mirror the pdmt5 DataFrame schema for that export, with two additions: symbol is prepended on every table. timeframe is prepended on rates so appended runs at different bar sizes stay distinguishable. SQLite does not declare foreign keys. Rows are linked logically by symbol , time windows, and (for deals) position_id / order . Duplicate rows are removed on append using dataset-specific keys (for example ticket on history tables, or (symbol, timeframe, time) on rates). Optional views are created when --with-views is set and the history-deals dataset was written.","title":"collect-history schema"},{"location":"api/history/#entity-relationship-diagram","text":"Sample layout for a full collection with --with-views : erDiagram rates { TEXT symbol \"dedup key\" INTEGER timeframe \"dedup key\" TEXT time \"dedup key\" REAL open REAL high REAL low REAL close INTEGER tick_volume INTEGER spread INTEGER real_volume } ticks { TEXT symbol \"dedup key\" TEXT time \"dedup key\" INTEGER time_msc \"dedup key (preferred)\" REAL bid REAL ask REAL last INTEGER volume INTEGER flags REAL volume_real } history_orders { INTEGER ticket \"dedup key\" TEXT symbol TEXT time INTEGER type INTEGER state REAL volume_initial REAL price_open REAL price_current INTEGER magic } history_deals { INTEGER ticket \"dedup key\" INTEGER order INTEGER position_id \"groups position view\" TEXT symbol TEXT time INTEGER type \"0/1 trade, else cash event\" INTEGER entry \"0 IN, 1 OUT, 2 INOUT, 3 OUT_BY\" REAL volume REAL price REAL profit REAL commission REAL swap REAL fee } cash_events { INTEGER ticket TEXT symbol TEXT time INTEGER type REAL profit } positions_reconstructed { INTEGER position_id TEXT symbol TEXT open_time TEXT close_time INTEGER direction REAL volume_open REAL volume_close REAL volume_reversal REAL open_price REAL close_price REAL total_profit INTEGER reversal_count INTEGER deals_count } rates ||--o{ history_deals : \"symbol (logical)\" ticks ||--o{ history_deals : \"symbol (logical)\" history_orders ||--o{ history_deals : \"order ~ ticket (logical)\" history_deals ||--|| cash_events : \"VIEW: type NOT IN (0,1)\" history_deals ||--o{ positions_reconstructed : \"VIEW: GROUP BY position_id\"","title":"Entity-relationship diagram"},{"location":"api/history/#tables-and-views","text":"Object Kind Source Notes rates table copy_rates_range Indexed on (symbol, timeframe, time) when columns exist. ticks table copy_ticks_range Indexed on (symbol, time) when columns exist. history_orders table history_orders_get Fetched per --symbol , then concatenated. history_deals table history_deals_get Fetched per --symbol , then concatenated. Indexed on (position_id, symbol) when present. cash_events view history_deals Non-trade deal types (deposits, balance ops, etc.). Requires type column. positions_reconstructed view history_deals One row per closed position_id ; volume-weighted prices and reversal stats. Column sets can vary with terminal and pdmt5 version. Views are skipped with a warning when required columns are missing.","title":"Tables and views"},{"location":"api/history/#incremental-collection","text":"The update_history SDK path uses the same base tables and optional cash_events / positions_reconstructed views. It additionally maintains rate___ compatibility views when create_rate_views=True .","title":"Incremental collection"},{"location":"api/history/#rate-view-resolution","text":"Downstream tools can resolve mt5cli-managed compatibility view names from an existing SQLite history database without creating files or guessing naming schemes: from pathlib import Path from mt5cli.history import resolve_rate_view_name , resolve_rate_view_names # Single symbol and granularity view = resolve_rate_view_name ( Path ( \"history.db\" ), \"EURUSD\" , \"M1\" ) # Batch resolution in row-major order views = resolve_rate_view_names ( Path ( \"history.db\" ), [ \"EURUSD\" , \"GBPUSD\" ], [ \"M1\" , \"H1\" ], ) Resolution rules: Returns rate___ when a symbol stores one timeframe. Returns rate____ when multiple timeframes are stored for the same symbol. When multiple naming candidates apply, prefers an existing managed rate_*__* view from the candidate list. Falls back to single-timeframe naming when the database path is missing or rates metadata is unavailable. Pass require_existing=True to raise ValueError instead of returning a best-guess name when the database or view is missing. Accepts either a SQLite path or an open sqlite3.Connection .","title":"Rate view resolution"},{"location":"api/history/#rate-data-loading","text":"The canonical normalized rate table is rates ; compatibility views are named with rate___ for single-timeframe symbols or rate____ when a symbol has multiple stored timeframes. resolve_rate_table_name() returns rates , while resolve_rate_view_name() returns the per-symbol compatibility view name. Use load_rate_data() or load_rate_series_from_sqlite(..., table=...) to load a single table or view from a SQLite path. Use load_rate_series_by_granularity() to load multiple instrument/granularity targets without hard-coding view names: from pathlib import Path from mt5cli import ( load_rate_data , load_rate_series_by_granularity , load_rate_series_from_sqlite , resolve_rate_table_name , ) from mt5cli.history import resolve_rate_view_name view = resolve_rate_view_name ( Path ( \"history.db\" ), \"EURUSD\" , \"M1\" , require_existing = True ) rates = load_rate_data ( Path ( \"history.db\" ), view , count = 1000 ) same_rates = load_rate_series_from_sqlite ( Path ( \"history.db\" ), table = view , count = 1000 ) table = resolve_rate_table_name ( \"EURUSD\" , \"M1\" ) # \"rates\" series = load_rate_series_by_granularity ( Path ( \"history.db\" ), symbols = [ \"EURUSD\" , \"GBPUSD\" ], granularities = [ \"M1\" , \"H1\" ], count = 500 , ) count returns the latest rows while preserving chronological order. Missing tables/views and mismatched explicit_tables lengths raise ValueError with the requested database target in the message. The loader accepts close-based OHLC rate data or tick-like bid/ask data. It validates that time exists, parses timestamps with pandas, and returns a DataFrame indexed by ascending DatetimeIndex named time .","title":"Rate data loading"},{"location":"api/history/#multi-series-rate-loading","text":"For loading many rate series at once, build neutral RateTarget pairs and load them from SQLite in one call. View names are resolved via the same compatibility-view rules, or you can pass explicit_tables to bypass resolution: from pathlib import Path from mt5cli import build_rate_targets , load_rate_series_from_sqlite targets = build_rate_targets ([ \"EURUSD\" , \"GBPUSD\" ], [ \"M1\" , \"H1\" ]) series = load_rate_series_from_sqlite ( Path ( \"history.db\" ), targets , count = 1000 ) frame = series [ \"EURUSD\" , 1 ] # keyed by (symbol, integer timeframe) build_rate_targets() returns RateTarget(symbol, timeframe) pairs in row-major order, normalizing timeframe names such as \"M1\" to their integer values; set allow_missing_symbol=True to address series solely by explicit_tables (targets carry symbol=None ). resolve_rate_tables() maps targets to table or view names and validates that any explicit_tables count matches the target count. Pass require_existing=True to raise ValueError instead of returning a best-guess name when the database or managed view is missing. When explicit_tables is provided, names are returned as-is and require_existing is ignored. load_rate_series_from_sqlite() returns a mapping keyed by (symbol, integer timeframe) . Unless explicit_tables is supplied, it requires existing managed rate_* compatibility views and raises ValueError when they are missing. Duplicate (symbol, timeframe) targets are rejected. load_rate_series_by_granularity() is a thin wrapper that builds the targets, loads the series, and rekeys the result by granularity name to avoid converting integer timeframes downstream: from mt5cli import load_rate_series_by_granularity series = load_rate_series_by_granularity ( \"history.db\" , [ \"EURUSD\" ], [ \"M1\" , \"H1\" ], count = 1000 ) frame = series [ \"EURUSD\" , \"M1\" ] # keyed by (symbol | None, granularity_name)","title":"Multi-series rate loading"},{"location":"api/public-contract/","text":"Public API Contract \u00b6 mt5cli is the generic MT5 data and execution infrastructure layer for downstream Python applications. The intended dependency direction is: downstream app -> mt5cli -> pdmt5 -> MetaTrader 5 Downstream packages should import from the package root ( from mt5cli import ... ) and use the public tier sets in mt5cli.contract to distinguish API stability. CLI commands mirror the same behavior but are not importable Python APIs. Public API tiers \u00b6 mt5cli classifies package-root imports by intended downstream use: Tier Contract set Meaning Stable core STABLE_SDK_EXPORTS Preferred SDK surface for downstream MT5 infrastructure adapters. Changes require a deliberate compatibility path. Secondary public SECONDARY_PUBLIC_EXPORTS Public helpers for CLI/export/schema integrations and lower-level MT5 wrappers. Importable, but less central to the downstream trading SDK. Stable downstream SDK API \u00b6 These names are exported from mt5cli and covered by the contract in mt5cli.STABLE_SDK_EXPORTS (defined in mt5cli.contract ). Session lifecycle and configuration \u00b6 Symbol Role MT5Client Read-only data client with optional order_check / order_send build_config Build pdmt5.Mt5Config from connection fields; login accepts int \\| str \\| None \u2014 numeric strings are coerced to int , blank strings are treated as unset, and ${ENV_VAR} / $ENV_NAME placeholders in string parameters are expanded when allow_whole_dollar_env=True mt5_session Context manager: initialize, login, yield client, shutdown create_trading_client , mt5_trading_session Trading-capable pdmt5.Mt5TradingClient lifecycle AccountSpec Generic account group: symbols plus optional credentials resolve_account_spec , resolve_account_specs Merge overrides and expand ${ENV_VAR} placeholders; opt-in allow_whole_dollar_env for bare $NAME substitute_env_placeholders Replace ${NAME} substrings from the environment; opt-in allow_whole_dollar_env for whole-value $NAME substitute_mapping_values Recursively traverse a dict/list/scalar structure and substitute ${ENV_VAR} placeholders for caller-selected mapping keys only; optionally normalise blank strings to None for a separate caller-selected key set; does not hard-code any application-specific key names Credential resolution is generic: any environment variable name may appear inside ${...} . mt5cli does not hard-code application-specific keys such as mt5_login or mt5_exe . Pass allow_whole_dollar_env=True to substitute_env_placeholders() , substitute_mapping_values() , resolve_account_spec() , resolve_account_specs() , and build_config() to additionally expand strings whose entire value is a bare $ENV_NAME identifier. Partial strings such as \"plan$pass\" , \"abc$ENV\" , or \"$ENV-suffix\" are never expanded \u2014 only an exact $IDENTIFIER whole-string match qualifies. Default is False to preserve backward compatibility. Closed-bar rate helpers \u00b6 MetaTrader 5 returns the still-forming bar as the last row when start_pos=0 . Use these helpers instead of reimplementing bar trimming or timestamp normalization in downstream apps. Symbol Role drop_forming_rate_bar Remove the last row from chronologically ordered rate data fetch_latest_closed_rates Single connected client: fetch count + 1 , drop forming bar fetch_latest_closed_rates_for_trading_client Closed bars from an active Mt5TradingClient session; returns RangeIndex fetch_latest_closed_rates_indexed Same as above but returns a UTC DatetimeIndex named \"time\" (no time column) collect_latest_closed_rates_for_accounts Multi-account closed bars with optional retry wrapper collect_latest_closed_rates_by_granularity Same data keyed by (symbol, granularity_name) collect_latest_rates_for_accounts_with_retries Bounded exponential backoff for transient MT5 errors SQLite history collection and rate loading \u00b6 Symbol Role collect_history One-shot date-range export into SQLite update_history , update_history_with_config Incremental append from MAX(time) cursors ThrottledHistoryUpdater Minimum interval between successful incremental updates; optional update_backend injection resolve_history_datasets , resolve_history_timeframes , resolve_history_tick_flags History pipeline configuration build_rate_view_name , resolve_rate_table_name , resolve_rate_view_name , resolve_rate_view_names , resolve_rate_tables Map symbols/timeframes to mt5cli-managed table or view names RateTarget , build_rate_targets Neutral (symbol, timeframe) series descriptors load_rate_data , load_rate_data_from_connection Load one table/view into a time-indexed DataFrame load_rate_series_from_sqlite , load_rate_series_by_granularity Load one or many series; fail clearly when managed views are missing Pass require_existing=True to rate view resolution helpers when downstream code must fail instead of receiving a best-guess view name. Multi-series loaders require existing managed rate_*__* views unless explicit_tables is supplied. See History Collection (SQLite) for schema, view naming, and ER diagrams. Trading and sizing primitives (generic) \u00b6 These helpers implement broker-facing calculations only. They do not encode strategy entries, exits, Kelly sizing, or signal logic. Symbol Role get_account_snapshot , get_symbol_snapshot , get_tick_snapshot , get_positions_frame Normalized account/symbol/tick/position views extract_tick_price Positive finite bid/ask extraction from tick mappings detect_position_side Net long / short / flat from open positions calculate_spread_ratio Relative bid-ask spread calculate_margin_and_volume , calculate_volume_by_margin , calculate_new_position_margin_ratio Margin budget and volume sizing normalize_order_volume , estimate_order_margin , calculate_positions_margin Broker volume normalization and margin totals calculate_positions_margin_by_symbol Per-symbol margin map (resilient, first-seen order) calculate_positions_margin_safe Summed total margin across symbols (failed symbols skipped) calculate_projected_margin_ratio Estimated symbol-scoped margin/equity after optional new exposure calculate_account_projected_margin_ratio Account snapshot margin/equity after optional new exposure calculate_symbol_group_margin_ratio Estimated symbol-group margin/equity with optional exposure determine_order_limits SL/TP price levels from ratios calculate_trailing_stop_updates Per-ticket generic trailing stop-loss update plan ensure_symbol_selected Select/verify Market Watch visibility place_market_order , close_open_positions , update_sltp_for_open_positions , update_trailing_stop_loss_for_open_positions Order execution helpers ( dry_run supported) MarginVolume , OrderLimits , OrderExecutionResult Typed return contracts for order helpers OrderSide , OrderFillingMode , OrderTimeMode , PositionSide , ExecutionStatus Typed enums for order helpers MT5Client.order_send() and CLI order-send --yes are live execution paths. Order helpers validate broker stop-level distance in determine_order_limits() and raise Mt5TradingError when computed SL/TP prices are too close to the entry quote. Validation uses trade_stops_level * point from the current quote and symbol metadata as a pre-check only; it does not guarantee live order acceptance after price movement and does not inspect trade_freeze_level . Live place_market_order() and SL/TP updates call ensure_symbol_selected() so hidden symbols are added to Market Watch before sending requests. Failed, malformed, or unknown broker retcodes are fail-closed and returned as status=\"failed\" with normalized request / response details; dry_run=True never calls ensure_symbol_selected() or order_send() . Errors and MT5 type re-exports \u00b6 Symbol Role Mt5CliError , Mt5ConnectionError , Mt5OperationError , Mt5SchemaError Stable mt5cli exception types normalize_mt5_exception , call_with_normalized_errors , is_recoverable_mt5_error Error normalization and retry classification Mt5Config , Mt5RuntimeError , Mt5TradingClient , Mt5TradingError Re-exported pdmt5 types for adapter convenience Secondary public exports \u00b6 These names remain importable from mt5cli and are covered by SECONDARY_PUBLIC_EXPORTS , but they are oriented toward CLI/export/schema integrations, parsing, and lower-level MT5 access rather than the stable core SDK surface. Prefer the stable symbols above for downstream infrastructure adapters. Read-only MT5 data wrappers \u00b6 Module-level helpers open a transient connection per call. Prefer mt5_session or MT5Client when making many requests in one process. Area Symbols Rates copy_rates_from , copy_rates_from_pos , copy_rates_range , latest_rates , collect_latest_rates Ticks copy_ticks_from , copy_ticks_range , recent_ticks Account / terminal account_info , terminal_info , mt5_version , last_error , mt5_summary , mt5_summary_as_df Symbols / market symbols , symbol_info , symbol_info_tick , market_book , minimum_margins Trading state (read) orders , positions , history_orders , history_deals , recent_history_deals Multi-account rates collect_latest_rates_for_accounts Use mt5_version for MetaTrader 5 terminal version data. The name version at the package root refers to importlib.metadata.version (package metadata), not the MT5 SDK helper. Schema, export, and parser helpers \u00b6 Area Symbols Dataset contracts DataKind , Dataset , IfExists , DEDUP_KEYS , REQUIRED_COLUMNS , TIME_COLUMNS , KNOWN_MT5_TIME_COLUMNS Schema normalization normalize_dataframe , normalize_time_columns , schema_columns , validate_schema Export helpers detect_format , export_dataframe , export_dataframe_to_sqlite Symbol parsing normalize_symbol , normalize_symbols Time parsing ensure_utc , parse_date_range , parse_datetime , recent_window MT5 parsing maps granularity_name , parse_tick_flags , parse_timeframe , TICK_FLAG_MAP , TIMEFRAME_MAP Trading data shapes POSITION_COLUMNS CLI commands \u00b6 The Typer application in mt5cli.cli exposes file-export commands documented in CLI Module and the project README. CLI commands: Require -o/--output and write CSV, JSON, Parquet, or SQLite. Accept global MT5 connection options ( --login , --password , --server , --path , --timeout ). Delegate to the same Python APIs described here; they are not duplicated business logic. order-send requires --yes before placing live trades. Internal helpers (not stable) \u00b6 Do not import these for downstream contracts; they may change without a semver notice: Module Examples mt5cli.sdk connected_client , _run_with_client , private coercion helpers mt5cli.history write_*_dataset , deduplicate_history_tables , parse_sqlite_timestamp mt5cli.retry retry_with_backoff mt5cli.cli Typer command handlers and Click parameter types Leading-underscore names Any _ -prefixed function or method Use the package-root stable exports instead of reaching into submodule internals. Explicitly out of scope \u00b6 mt5cli must not implement downstream strategy or research responsibilities. The following belong in consuming applications, not in mt5cli: Signal detection (for example AR-GARCH or other model-specific triggers) Backtesting, walk-forward analysis, or parameter optimization Strategy-specific risk policy, position sizing systems, or Kelly fractions Entry/exit decision logic or YAML strategy semantics Application-specific credential schema keys wired into mt5cli internals mt5cli provides connection lifecycle, normalized data access, SQLite history machinery, closed-bar helpers, generic margin/volume/spread/SL/TP utilities, and optional order primitives so downstream apps can focus on strategy code behind their own adapter layer. Contract verification \u00b6 tests/test_contracts.py asserts that every name in the stable and secondary tier sets is importable from mt5cli , documents key closed-bar, rate-view, SQLite loading, account-resolution, and trading-session behaviors, and keeps the tier sets aligned with __all__ .","title":"Public API Contract"},{"location":"api/public-contract/#public-api-contract","text":"mt5cli is the generic MT5 data and execution infrastructure layer for downstream Python applications. The intended dependency direction is: downstream app -> mt5cli -> pdmt5 -> MetaTrader 5 Downstream packages should import from the package root ( from mt5cli import ... ) and use the public tier sets in mt5cli.contract to distinguish API stability. CLI commands mirror the same behavior but are not importable Python APIs.","title":"Public API Contract"},{"location":"api/public-contract/#public-api-tiers","text":"mt5cli classifies package-root imports by intended downstream use: Tier Contract set Meaning Stable core STABLE_SDK_EXPORTS Preferred SDK surface for downstream MT5 infrastructure adapters. Changes require a deliberate compatibility path. Secondary public SECONDARY_PUBLIC_EXPORTS Public helpers for CLI/export/schema integrations and lower-level MT5 wrappers. Importable, but less central to the downstream trading SDK.","title":"Public API tiers"},{"location":"api/public-contract/#stable-downstream-sdk-api","text":"These names are exported from mt5cli and covered by the contract in mt5cli.STABLE_SDK_EXPORTS (defined in mt5cli.contract ).","title":"Stable downstream SDK API"},{"location":"api/public-contract/#session-lifecycle-and-configuration","text":"Symbol Role MT5Client Read-only data client with optional order_check / order_send build_config Build pdmt5.Mt5Config from connection fields; login accepts int \\| str \\| None \u2014 numeric strings are coerced to int , blank strings are treated as unset, and ${ENV_VAR} / $ENV_NAME placeholders in string parameters are expanded when allow_whole_dollar_env=True mt5_session Context manager: initialize, login, yield client, shutdown create_trading_client , mt5_trading_session Trading-capable pdmt5.Mt5TradingClient lifecycle AccountSpec Generic account group: symbols plus optional credentials resolve_account_spec , resolve_account_specs Merge overrides and expand ${ENV_VAR} placeholders; opt-in allow_whole_dollar_env for bare $NAME substitute_env_placeholders Replace ${NAME} substrings from the environment; opt-in allow_whole_dollar_env for whole-value $NAME substitute_mapping_values Recursively traverse a dict/list/scalar structure and substitute ${ENV_VAR} placeholders for caller-selected mapping keys only; optionally normalise blank strings to None for a separate caller-selected key set; does not hard-code any application-specific key names Credential resolution is generic: any environment variable name may appear inside ${...} . mt5cli does not hard-code application-specific keys such as mt5_login or mt5_exe . Pass allow_whole_dollar_env=True to substitute_env_placeholders() , substitute_mapping_values() , resolve_account_spec() , resolve_account_specs() , and build_config() to additionally expand strings whose entire value is a bare $ENV_NAME identifier. Partial strings such as \"plan$pass\" , \"abc$ENV\" , or \"$ENV-suffix\" are never expanded \u2014 only an exact $IDENTIFIER whole-string match qualifies. Default is False to preserve backward compatibility.","title":"Session lifecycle and configuration"},{"location":"api/public-contract/#closed-bar-rate-helpers","text":"MetaTrader 5 returns the still-forming bar as the last row when start_pos=0 . Use these helpers instead of reimplementing bar trimming or timestamp normalization in downstream apps. Symbol Role drop_forming_rate_bar Remove the last row from chronologically ordered rate data fetch_latest_closed_rates Single connected client: fetch count + 1 , drop forming bar fetch_latest_closed_rates_for_trading_client Closed bars from an active Mt5TradingClient session; returns RangeIndex fetch_latest_closed_rates_indexed Same as above but returns a UTC DatetimeIndex named \"time\" (no time column) collect_latest_closed_rates_for_accounts Multi-account closed bars with optional retry wrapper collect_latest_closed_rates_by_granularity Same data keyed by (symbol, granularity_name) collect_latest_rates_for_accounts_with_retries Bounded exponential backoff for transient MT5 errors","title":"Closed-bar rate helpers"},{"location":"api/public-contract/#sqlite-history-collection-and-rate-loading","text":"Symbol Role collect_history One-shot date-range export into SQLite update_history , update_history_with_config Incremental append from MAX(time) cursors ThrottledHistoryUpdater Minimum interval between successful incremental updates; optional update_backend injection resolve_history_datasets , resolve_history_timeframes , resolve_history_tick_flags History pipeline configuration build_rate_view_name , resolve_rate_table_name , resolve_rate_view_name , resolve_rate_view_names , resolve_rate_tables Map symbols/timeframes to mt5cli-managed table or view names RateTarget , build_rate_targets Neutral (symbol, timeframe) series descriptors load_rate_data , load_rate_data_from_connection Load one table/view into a time-indexed DataFrame load_rate_series_from_sqlite , load_rate_series_by_granularity Load one or many series; fail clearly when managed views are missing Pass require_existing=True to rate view resolution helpers when downstream code must fail instead of receiving a best-guess view name. Multi-series loaders require existing managed rate_*__* views unless explicit_tables is supplied. See History Collection (SQLite) for schema, view naming, and ER diagrams.","title":"SQLite history collection and rate loading"},{"location":"api/public-contract/#trading-and-sizing-primitives-generic","text":"These helpers implement broker-facing calculations only. They do not encode strategy entries, exits, Kelly sizing, or signal logic. Symbol Role get_account_snapshot , get_symbol_snapshot , get_tick_snapshot , get_positions_frame Normalized account/symbol/tick/position views extract_tick_price Positive finite bid/ask extraction from tick mappings detect_position_side Net long / short / flat from open positions calculate_spread_ratio Relative bid-ask spread calculate_margin_and_volume , calculate_volume_by_margin , calculate_new_position_margin_ratio Margin budget and volume sizing normalize_order_volume , estimate_order_margin , calculate_positions_margin Broker volume normalization and margin totals calculate_positions_margin_by_symbol Per-symbol margin map (resilient, first-seen order) calculate_positions_margin_safe Summed total margin across symbols (failed symbols skipped) calculate_projected_margin_ratio Estimated symbol-scoped margin/equity after optional new exposure calculate_account_projected_margin_ratio Account snapshot margin/equity after optional new exposure calculate_symbol_group_margin_ratio Estimated symbol-group margin/equity with optional exposure determine_order_limits SL/TP price levels from ratios calculate_trailing_stop_updates Per-ticket generic trailing stop-loss update plan ensure_symbol_selected Select/verify Market Watch visibility place_market_order , close_open_positions , update_sltp_for_open_positions , update_trailing_stop_loss_for_open_positions Order execution helpers ( dry_run supported) MarginVolume , OrderLimits , OrderExecutionResult Typed return contracts for order helpers OrderSide , OrderFillingMode , OrderTimeMode , PositionSide , ExecutionStatus Typed enums for order helpers MT5Client.order_send() and CLI order-send --yes are live execution paths. Order helpers validate broker stop-level distance in determine_order_limits() and raise Mt5TradingError when computed SL/TP prices are too close to the entry quote. Validation uses trade_stops_level * point from the current quote and symbol metadata as a pre-check only; it does not guarantee live order acceptance after price movement and does not inspect trade_freeze_level . Live place_market_order() and SL/TP updates call ensure_symbol_selected() so hidden symbols are added to Market Watch before sending requests. Failed, malformed, or unknown broker retcodes are fail-closed and returned as status=\"failed\" with normalized request / response details; dry_run=True never calls ensure_symbol_selected() or order_send() .","title":"Trading and sizing primitives (generic)"},{"location":"api/public-contract/#errors-and-mt5-type-re-exports","text":"Symbol Role Mt5CliError , Mt5ConnectionError , Mt5OperationError , Mt5SchemaError Stable mt5cli exception types normalize_mt5_exception , call_with_normalized_errors , is_recoverable_mt5_error Error normalization and retry classification Mt5Config , Mt5RuntimeError , Mt5TradingClient , Mt5TradingError Re-exported pdmt5 types for adapter convenience","title":"Errors and MT5 type re-exports"},{"location":"api/public-contract/#secondary-public-exports","text":"These names remain importable from mt5cli and are covered by SECONDARY_PUBLIC_EXPORTS , but they are oriented toward CLI/export/schema integrations, parsing, and lower-level MT5 access rather than the stable core SDK surface. Prefer the stable symbols above for downstream infrastructure adapters.","title":"Secondary public exports"},{"location":"api/public-contract/#read-only-mt5-data-wrappers","text":"Module-level helpers open a transient connection per call. Prefer mt5_session or MT5Client when making many requests in one process. Area Symbols Rates copy_rates_from , copy_rates_from_pos , copy_rates_range , latest_rates , collect_latest_rates Ticks copy_ticks_from , copy_ticks_range , recent_ticks Account / terminal account_info , terminal_info , mt5_version , last_error , mt5_summary , mt5_summary_as_df Symbols / market symbols , symbol_info , symbol_info_tick , market_book , minimum_margins Trading state (read) orders , positions , history_orders , history_deals , recent_history_deals Multi-account rates collect_latest_rates_for_accounts Use mt5_version for MetaTrader 5 terminal version data. The name version at the package root refers to importlib.metadata.version (package metadata), not the MT5 SDK helper.","title":"Read-only MT5 data wrappers"},{"location":"api/public-contract/#schema-export-and-parser-helpers","text":"Area Symbols Dataset contracts DataKind , Dataset , IfExists , DEDUP_KEYS , REQUIRED_COLUMNS , TIME_COLUMNS , KNOWN_MT5_TIME_COLUMNS Schema normalization normalize_dataframe , normalize_time_columns , schema_columns , validate_schema Export helpers detect_format , export_dataframe , export_dataframe_to_sqlite Symbol parsing normalize_symbol , normalize_symbols Time parsing ensure_utc , parse_date_range , parse_datetime , recent_window MT5 parsing maps granularity_name , parse_tick_flags , parse_timeframe , TICK_FLAG_MAP , TIMEFRAME_MAP Trading data shapes POSITION_COLUMNS","title":"Schema, export, and parser helpers"},{"location":"api/public-contract/#cli-commands","text":"The Typer application in mt5cli.cli exposes file-export commands documented in CLI Module and the project README. CLI commands: Require -o/--output and write CSV, JSON, Parquet, or SQLite. Accept global MT5 connection options ( --login , --password , --server , --path , --timeout ). Delegate to the same Python APIs described here; they are not duplicated business logic. order-send requires --yes before placing live trades.","title":"CLI commands"},{"location":"api/public-contract/#internal-helpers-not-stable","text":"Do not import these for downstream contracts; they may change without a semver notice: Module Examples mt5cli.sdk connected_client , _run_with_client , private coercion helpers mt5cli.history write_*_dataset , deduplicate_history_tables , parse_sqlite_timestamp mt5cli.retry retry_with_backoff mt5cli.cli Typer command handlers and Click parameter types Leading-underscore names Any _ -prefixed function or method Use the package-root stable exports instead of reaching into submodule internals.","title":"Internal helpers (not stable)"},{"location":"api/public-contract/#explicitly-out-of-scope","text":"mt5cli must not implement downstream strategy or research responsibilities. The following belong in consuming applications, not in mt5cli: Signal detection (for example AR-GARCH or other model-specific triggers) Backtesting, walk-forward analysis, or parameter optimization Strategy-specific risk policy, position sizing systems, or Kelly fractions Entry/exit decision logic or YAML strategy semantics Application-specific credential schema keys wired into mt5cli internals mt5cli provides connection lifecycle, normalized data access, SQLite history machinery, closed-bar helpers, generic margin/volume/spread/SL/TP utilities, and optional order primitives so downstream apps can focus on strategy code behind their own adapter layer.","title":"Explicitly out of scope"},{"location":"api/public-contract/#contract-verification","text":"tests/test_contracts.py asserts that every name in the stable and secondary tier sets is importable from mt5cli , documents key closed-bar, rate-view, SQLite loading, account-resolution, and trading-session behaviors, and keeps the tier sets aligned with __all__ .","title":"Contract verification"},{"location":"api/schemas/","text":"Schemas \u00b6 mt5cli.schemas \u00b6 Canonical DataFrame schemas for MT5 market and account datasets. DEDUP_KEYS module-attribute \u00b6 DEDUP_KEYS : dict [ DataKind , tuple [ tuple [ str , ... ], ... ]] = { rates : ( ( \"symbol\" , \"timeframe\" , \"time\" ), ( \"symbol\" , \"time\" ), ), ticks : (( \"symbol\" , \"time_msc\" ), ( \"symbol\" , \"time\" )), history_orders : ( ( \"ticket\" ,), ( \"symbol\" , \"time\" , \"type\" ), ), history_deals : ( ( \"ticket\" ,), ( \"symbol\" , \"time\" , \"type\" , \"entry\" ), ), } KNOWN_MT5_TIME_COLUMNS module-attribute \u00b6 KNOWN_MT5_TIME_COLUMNS : Final [ frozenset [ str ]] = frozenset ({ \"time\" , \"time_setup\" , \"time_setup_msc\" , \"time_done\" , \"time_done_msc\" , \"time_msc\" , }) REQUIRED_COLUMNS module-attribute \u00b6 REQUIRED_COLUMNS : dict [ DataKind , frozenset [ str ]] = { rates : frozenset ({ \"time\" , \"open\" , \"high\" , \"low\" , \"close\" , \"tick_volume\" , \"spread\" , \"real_volume\" , }), ticks : frozenset ({ \"time\" , \"bid\" , \"ask\" , \"last\" , \"volume\" , \"time_msc\" , \"flags\" , \"volume_real\" , }), orders : frozenset ({ \"ticket\" , \"time_setup\" , \"type\" , \"state\" , \"symbol\" , \"volume_current\" , \"price_open\" , }), positions : frozenset ({ \"ticket\" , \"time\" , \"type\" , \"symbol\" , \"volume\" , \"price_open\" , \"price_current\" , \"profit\" , }), history_orders : frozenset ({ \"ticket\" , \"time_setup\" , \"type\" , \"state\" , \"symbol\" , \"volume_initial\" , \"price_open\" , }), history_deals : frozenset ({ \"ticket\" , \"order\" , \"time\" , \"type\" , \"entry\" , \"symbol\" , \"volume\" , \"price\" , \"profit\" , }), } TIME_COLUMNS module-attribute \u00b6 TIME_COLUMNS : dict [ DataKind , frozenset [ str ]] = { kind : ( REQUIRED_COLUMNS [ kind ] & _TIME_COLUMN_NAMES | get ( kind , frozenset ()) ) for kind in DataKind } __all__ module-attribute \u00b6 __all__ = [ \"DEDUP_KEYS\" , \"KNOWN_MT5_TIME_COLUMNS\" , \"REQUIRED_COLUMNS\" , \"TIME_COLUMNS\" , \"DataKind\" , \"normalize_dataframe\" , \"normalize_time_columns\" , \"schema_columns\" , \"validate_schema\" , ] DataKind \u00b6 Bases: StrEnum Supported MT5 dataset kinds with canonical column contracts. history_deals class-attribute instance-attribute \u00b6 history_deals = 'history_deals' history_orders class-attribute instance-attribute \u00b6 history_orders = 'history_orders' orders class-attribute instance-attribute \u00b6 orders = 'orders' positions class-attribute instance-attribute \u00b6 positions = 'positions' rates class-attribute instance-attribute \u00b6 rates = 'rates' ticks class-attribute instance-attribute \u00b6 ticks = 'ticks' ensure_utc_columns \u00b6 ensure_utc_columns ( frame : DataFrame , columns : Iterable [ str ] ) -> DataFrame Return a copy with selected columns coerced to UTC datetimes. Parameters: Name Type Description Default frame DataFrame Source DataFrame. required columns Iterable [ str ] Column names to coerce. required Returns: Type Description DataFrame DataFrame copy with UTC-aware datetime columns. Source code in mt5cli/schemas.py 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 def ensure_utc_columns ( frame : pd . DataFrame , columns : Iterable [ str ]) -> pd . DataFrame : \"\"\"Return a copy with selected columns coerced to UTC datetimes. Args: frame: Source DataFrame. columns: Column names to coerce. Returns: DataFrame copy with UTC-aware datetime columns. \"\"\" normalized = frame . copy () for column in columns : if column not in normalized . columns : continue if column in _TIME_COLUMN_NAMES : normalized [ column ] = _coerce_mt5_time_column ( normalized [ column ], column ) else : normalized [ column ] = pd . to_datetime ( normalized [ column ], utc = True , errors = \"coerce\" ) return normalized normalize_dataframe \u00b6 normalize_dataframe ( frame : DataFrame , kind : DataKind , * , symbol : str | None = None , timeframe : int | str | None = None , sort : bool = True , ) -> DataFrame Normalize MT5 DataFrame columns, timestamps, and storage metadata. Ensures UTC timestamps, optionally injects symbol / timeframe for storage-oriented datasets, and sorts chronologically when a time column exists. Parameters: Name Type Description Default frame DataFrame Source DataFrame from MT5 or pdmt5. required kind DataKind Dataset kind guiding normalization rules. required symbol str | None Optional symbol to inject when missing. None timeframe int | str | None Optional timeframe integer or name to inject for rates. None sort bool Whether to sort by time or time_msc when present. True Returns: Type Description DataFrame Normalized DataFrame copy. Source code in mt5cli/schemas.py 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 def normalize_dataframe ( frame : pd . DataFrame , kind : DataKind , * , symbol : str | None = None , timeframe : int | str | None = None , sort : bool = True , ) -> pd . DataFrame : \"\"\"Normalize MT5 DataFrame columns, timestamps, and storage metadata. Ensures UTC timestamps, optionally injects ``symbol`` / ``timeframe`` for storage-oriented datasets, and sorts chronologically when a ``time`` column exists. Args: frame: Source DataFrame from MT5 or pdmt5. kind: Dataset kind guiding normalization rules. symbol: Optional symbol to inject when missing. timeframe: Optional timeframe integer or name to inject for rates. sort: Whether to sort by ``time`` or ``time_msc`` when present. Returns: Normalized DataFrame copy. \"\"\" if frame . empty and len ( frame . columns ) == 0 : return frame . copy () normalized = normalize_time_columns ( frame , kind ) if symbol is not None and \"symbol\" not in normalized . columns : normalized . insert ( 0 , \"symbol\" , normalize_symbol ( symbol )) if timeframe is not None and kind is DataKind . rates : tf = parse_timeframe ( timeframe ) if \"timeframe\" not in normalized . columns : insert_at = 1 if \"symbol\" in normalized . columns else 0 normalized . insert ( insert_at , \"timeframe\" , tf ) validate_schema ( normalized , kind ) if sort : if \"time\" in normalized . columns : normalized = normalized . sort_values ( \"time\" , kind = \"stable\" ) elif \"time_msc\" in normalized . columns : normalized = normalized . sort_values ( \"time_msc\" , kind = \"stable\" ) normalized = normalized . reset_index ( drop = True ) return normalized normalize_time_columns \u00b6 normalize_time_columns ( frame : DataFrame , kind : DataKind ) -> DataFrame Coerce dataset time columns to UTC-aware datetimes when present. Any column in :data: KNOWN_MT5_TIME_COLUMNS that is present in frame is normalized. Numeric MT5 epoch values use seconds for time , time_setup , and time_done , and milliseconds for *_msc columns. Parameters: Name Type Description Default frame DataFrame Source DataFrame from MT5 or pdmt5. required kind DataKind Dataset kind (retained for API compatibility). required Returns: Type Description DataFrame DataFrame copy with normalized time columns. Source code in mt5cli/schemas.py 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 def normalize_time_columns ( frame : pd . DataFrame , kind : DataKind ) -> pd . DataFrame : \"\"\"Coerce dataset time columns to UTC-aware datetimes when present. Any column in :data:`KNOWN_MT5_TIME_COLUMNS` that is present in ``frame`` is normalized. Numeric MT5 epoch values use seconds for ``time``, ``time_setup``, and ``time_done``, and milliseconds for ``*_msc`` columns. Args: frame: Source DataFrame from MT5 or pdmt5. kind: Dataset kind (retained for API compatibility). Returns: DataFrame copy with normalized time columns. \"\"\" del kind normalized = frame . copy () for column in normalized . columns : if column not in _TIME_COLUMN_NAMES : continue normalized [ column ] = _coerce_mt5_time_column ( normalized [ column ], column ) return normalized schema_columns \u00b6 schema_columns ( kind : DataKind ) -> frozenset [ str ] Return required column names for a dataset kind. Parameters: Name Type Description Default kind DataKind Dataset kind. required Returns: Type Description frozenset [ str ] Required column names for kind . Source code in mt5cli/schemas.py 141 142 143 144 145 146 147 148 149 150 def schema_columns ( kind : DataKind ) -> frozenset [ str ]: \"\"\"Return required column names for a dataset kind. Args: kind: Dataset kind. Returns: Required column names for ``kind``. \"\"\" return REQUIRED_COLUMNS [ kind ] validate_schema \u00b6 validate_schema ( frame : DataFrame , kind : DataKind , * , extra_required : Iterable [ str ] | None = None , ) -> None Validate that a DataFrame includes required columns for a dataset kind. Parameters: Name Type Description Default frame DataFrame DataFrame to validate. required kind DataKind Expected dataset kind. required extra_required Iterable [ str ] | None Additional columns that must be present (for example symbol and timeframe on stored rate history). None Raises: Type Description Mt5SchemaError If required columns are missing. Source code in mt5cli/schemas.py 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 def validate_schema ( frame : pd . DataFrame , kind : DataKind , * , extra_required : Iterable [ str ] | None = None , ) -> None : \"\"\"Validate that a DataFrame includes required columns for a dataset kind. Args: frame: DataFrame to validate. kind: Expected dataset kind. extra_required: Additional columns that must be present (for example ``symbol`` and ``timeframe`` on stored rate history). Raises: Mt5SchemaError: If required columns are missing. \"\"\" if frame . empty and len ( frame . columns ) == 0 : return required = set ( REQUIRED_COLUMNS [ kind ]) if extra_required is not None : required . update ( extra_required ) missing = required - set ( frame . columns ) if missing : msg = ( f \" { kind . value } schema is missing required columns: \" f \" { ', ' . join ( sorted ( missing )) } .\" ) raise Mt5SchemaError ( msg )","title":"Schemas"},{"location":"api/schemas/#schemas","text":"","title":"Schemas"},{"location":"api/schemas/#mt5cli.schemas","text":"Canonical DataFrame schemas for MT5 market and account datasets.","title":"schemas"},{"location":"api/schemas/#mt5cli.schemas.DEDUP_KEYS","text":"DEDUP_KEYS : dict [ DataKind , tuple [ tuple [ str , ... ], ... ]] = { rates : ( ( \"symbol\" , \"timeframe\" , \"time\" ), ( \"symbol\" , \"time\" ), ), ticks : (( \"symbol\" , \"time_msc\" ), ( \"symbol\" , \"time\" )), history_orders : ( ( \"ticket\" ,), ( \"symbol\" , \"time\" , \"type\" ), ), history_deals : ( ( \"ticket\" ,), ( \"symbol\" , \"time\" , \"type\" , \"entry\" ), ), }","title":"DEDUP_KEYS"},{"location":"api/schemas/#mt5cli.schemas.KNOWN_MT5_TIME_COLUMNS","text":"KNOWN_MT5_TIME_COLUMNS : Final [ frozenset [ str ]] = frozenset ({ \"time\" , \"time_setup\" , \"time_setup_msc\" , \"time_done\" , \"time_done_msc\" , \"time_msc\" , })","title":"KNOWN_MT5_TIME_COLUMNS"},{"location":"api/schemas/#mt5cli.schemas.REQUIRED_COLUMNS","text":"REQUIRED_COLUMNS : dict [ DataKind , frozenset [ str ]] = { rates : frozenset ({ \"time\" , \"open\" , \"high\" , \"low\" , \"close\" , \"tick_volume\" , \"spread\" , \"real_volume\" , }), ticks : frozenset ({ \"time\" , \"bid\" , \"ask\" , \"last\" , \"volume\" , \"time_msc\" , \"flags\" , \"volume_real\" , }), orders : frozenset ({ \"ticket\" , \"time_setup\" , \"type\" , \"state\" , \"symbol\" , \"volume_current\" , \"price_open\" , }), positions : frozenset ({ \"ticket\" , \"time\" , \"type\" , \"symbol\" , \"volume\" , \"price_open\" , \"price_current\" , \"profit\" , }), history_orders : frozenset ({ \"ticket\" , \"time_setup\" , \"type\" , \"state\" , \"symbol\" , \"volume_initial\" , \"price_open\" , }), history_deals : frozenset ({ \"ticket\" , \"order\" , \"time\" , \"type\" , \"entry\" , \"symbol\" , \"volume\" , \"price\" , \"profit\" , }), }","title":"REQUIRED_COLUMNS"},{"location":"api/schemas/#mt5cli.schemas.TIME_COLUMNS","text":"TIME_COLUMNS : dict [ DataKind , frozenset [ str ]] = { kind : ( REQUIRED_COLUMNS [ kind ] & _TIME_COLUMN_NAMES | get ( kind , frozenset ()) ) for kind in DataKind }","title":"TIME_COLUMNS"},{"location":"api/schemas/#mt5cli.schemas.__all__","text":"__all__ = [ \"DEDUP_KEYS\" , \"KNOWN_MT5_TIME_COLUMNS\" , \"REQUIRED_COLUMNS\" , \"TIME_COLUMNS\" , \"DataKind\" , \"normalize_dataframe\" , \"normalize_time_columns\" , \"schema_columns\" , \"validate_schema\" , ]","title":"__all__"},{"location":"api/schemas/#mt5cli.schemas.DataKind","text":"Bases: StrEnum Supported MT5 dataset kinds with canonical column contracts.","title":"DataKind"},{"location":"api/schemas/#mt5cli.schemas.DataKind.history_deals","text":"history_deals = 'history_deals'","title":"history_deals"},{"location":"api/schemas/#mt5cli.schemas.DataKind.history_orders","text":"history_orders = 'history_orders'","title":"history_orders"},{"location":"api/schemas/#mt5cli.schemas.DataKind.orders","text":"orders = 'orders'","title":"orders"},{"location":"api/schemas/#mt5cli.schemas.DataKind.positions","text":"positions = 'positions'","title":"positions"},{"location":"api/schemas/#mt5cli.schemas.DataKind.rates","text":"rates = 'rates'","title":"rates"},{"location":"api/schemas/#mt5cli.schemas.DataKind.ticks","text":"ticks = 'ticks'","title":"ticks"},{"location":"api/schemas/#mt5cli.schemas.ensure_utc_columns","text":"ensure_utc_columns ( frame : DataFrame , columns : Iterable [ str ] ) -> DataFrame Return a copy with selected columns coerced to UTC datetimes. Parameters: Name Type Description Default frame DataFrame Source DataFrame. required columns Iterable [ str ] Column names to coerce. required Returns: Type Description DataFrame DataFrame copy with UTC-aware datetime columns. Source code in mt5cli/schemas.py 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 def ensure_utc_columns ( frame : pd . DataFrame , columns : Iterable [ str ]) -> pd . DataFrame : \"\"\"Return a copy with selected columns coerced to UTC datetimes. Args: frame: Source DataFrame. columns: Column names to coerce. Returns: DataFrame copy with UTC-aware datetime columns. \"\"\" normalized = frame . copy () for column in columns : if column not in normalized . columns : continue if column in _TIME_COLUMN_NAMES : normalized [ column ] = _coerce_mt5_time_column ( normalized [ column ], column ) else : normalized [ column ] = pd . to_datetime ( normalized [ column ], utc = True , errors = \"coerce\" ) return normalized","title":"ensure_utc_columns"},{"location":"api/schemas/#mt5cli.schemas.normalize_dataframe","text":"normalize_dataframe ( frame : DataFrame , kind : DataKind , * , symbol : str | None = None , timeframe : int | str | None = None , sort : bool = True , ) -> DataFrame Normalize MT5 DataFrame columns, timestamps, and storage metadata. Ensures UTC timestamps, optionally injects symbol / timeframe for storage-oriented datasets, and sorts chronologically when a time column exists. Parameters: Name Type Description Default frame DataFrame Source DataFrame from MT5 or pdmt5. required kind DataKind Dataset kind guiding normalization rules. required symbol str | None Optional symbol to inject when missing. None timeframe int | str | None Optional timeframe integer or name to inject for rates. None sort bool Whether to sort by time or time_msc when present. True Returns: Type Description DataFrame Normalized DataFrame copy. Source code in mt5cli/schemas.py 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 def normalize_dataframe ( frame : pd . DataFrame , kind : DataKind , * , symbol : str | None = None , timeframe : int | str | None = None , sort : bool = True , ) -> pd . DataFrame : \"\"\"Normalize MT5 DataFrame columns, timestamps, and storage metadata. Ensures UTC timestamps, optionally injects ``symbol`` / ``timeframe`` for storage-oriented datasets, and sorts chronologically when a ``time`` column exists. Args: frame: Source DataFrame from MT5 or pdmt5. kind: Dataset kind guiding normalization rules. symbol: Optional symbol to inject when missing. timeframe: Optional timeframe integer or name to inject for rates. sort: Whether to sort by ``time`` or ``time_msc`` when present. Returns: Normalized DataFrame copy. \"\"\" if frame . empty and len ( frame . columns ) == 0 : return frame . copy () normalized = normalize_time_columns ( frame , kind ) if symbol is not None and \"symbol\" not in normalized . columns : normalized . insert ( 0 , \"symbol\" , normalize_symbol ( symbol )) if timeframe is not None and kind is DataKind . rates : tf = parse_timeframe ( timeframe ) if \"timeframe\" not in normalized . columns : insert_at = 1 if \"symbol\" in normalized . columns else 0 normalized . insert ( insert_at , \"timeframe\" , tf ) validate_schema ( normalized , kind ) if sort : if \"time\" in normalized . columns : normalized = normalized . sort_values ( \"time\" , kind = \"stable\" ) elif \"time_msc\" in normalized . columns : normalized = normalized . sort_values ( \"time_msc\" , kind = \"stable\" ) normalized = normalized . reset_index ( drop = True ) return normalized","title":"normalize_dataframe"},{"location":"api/schemas/#mt5cli.schemas.normalize_time_columns","text":"normalize_time_columns ( frame : DataFrame , kind : DataKind ) -> DataFrame Coerce dataset time columns to UTC-aware datetimes when present. Any column in :data: KNOWN_MT5_TIME_COLUMNS that is present in frame is normalized. Numeric MT5 epoch values use seconds for time , time_setup , and time_done , and milliseconds for *_msc columns. Parameters: Name Type Description Default frame DataFrame Source DataFrame from MT5 or pdmt5. required kind DataKind Dataset kind (retained for API compatibility). required Returns: Type Description DataFrame DataFrame copy with normalized time columns. Source code in mt5cli/schemas.py 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 def normalize_time_columns ( frame : pd . DataFrame , kind : DataKind ) -> pd . DataFrame : \"\"\"Coerce dataset time columns to UTC-aware datetimes when present. Any column in :data:`KNOWN_MT5_TIME_COLUMNS` that is present in ``frame`` is normalized. Numeric MT5 epoch values use seconds for ``time``, ``time_setup``, and ``time_done``, and milliseconds for ``*_msc`` columns. Args: frame: Source DataFrame from MT5 or pdmt5. kind: Dataset kind (retained for API compatibility). Returns: DataFrame copy with normalized time columns. \"\"\" del kind normalized = frame . copy () for column in normalized . columns : if column not in _TIME_COLUMN_NAMES : continue normalized [ column ] = _coerce_mt5_time_column ( normalized [ column ], column ) return normalized","title":"normalize_time_columns"},{"location":"api/schemas/#mt5cli.schemas.schema_columns","text":"schema_columns ( kind : DataKind ) -> frozenset [ str ] Return required column names for a dataset kind. Parameters: Name Type Description Default kind DataKind Dataset kind. required Returns: Type Description frozenset [ str ] Required column names for kind . Source code in mt5cli/schemas.py 141 142 143 144 145 146 147 148 149 150 def schema_columns ( kind : DataKind ) -> frozenset [ str ]: \"\"\"Return required column names for a dataset kind. Args: kind: Dataset kind. Returns: Required column names for ``kind``. \"\"\" return REQUIRED_COLUMNS [ kind ]","title":"schema_columns"},{"location":"api/schemas/#mt5cli.schemas.validate_schema","text":"validate_schema ( frame : DataFrame , kind : DataKind , * , extra_required : Iterable [ str ] | None = None , ) -> None Validate that a DataFrame includes required columns for a dataset kind. Parameters: Name Type Description Default frame DataFrame DataFrame to validate. required kind DataKind Expected dataset kind. required extra_required Iterable [ str ] | None Additional columns that must be present (for example symbol and timeframe on stored rate history). None Raises: Type Description Mt5SchemaError If required columns are missing. Source code in mt5cli/schemas.py 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 def validate_schema ( frame : pd . DataFrame , kind : DataKind , * , extra_required : Iterable [ str ] | None = None , ) -> None : \"\"\"Validate that a DataFrame includes required columns for a dataset kind. Args: frame: DataFrame to validate. kind: Expected dataset kind. extra_required: Additional columns that must be present (for example ``symbol`` and ``timeframe`` on stored rate history). Raises: Mt5SchemaError: If required columns are missing. \"\"\" if frame . empty and len ( frame . columns ) == 0 : return required = set ( REQUIRED_COLUMNS [ kind ]) if extra_required is not None : required . update ( extra_required ) missing = required - set ( frame . columns ) if missing : msg = ( f \" { kind . value } schema is missing required columns: \" f \" { ', ' . join ( sorted ( missing )) } .\" ) raise Mt5SchemaError ( msg )","title":"validate_schema"},{"location":"api/sdk/","text":"SDK Module \u00b6 mt5cli.sdk \u00b6 Programmatic SDK for MetaTrader 5 data collection. T module-attribute \u00b6 T = TypeVar ( 'T' ) UpdateHistoryBackend module-attribute \u00b6 UpdateHistoryBackend = Callable [ ... , None ] __all__ module-attribute \u00b6 __all__ = [ \"AccountSpec\" , \"Mt5CliClient\" , \"ThrottledHistoryUpdater\" , \"account_info\" , \"build_config\" , \"collect_history\" , \"collect_latest_closed_rates_by_granularity\" , \"collect_latest_closed_rates_for_accounts\" , \"collect_latest_rates\" , \"collect_latest_rates_for_accounts\" , \"collect_latest_rates_for_accounts_with_retries\" , \"connected_client\" , \"copy_rates_from\" , \"copy_rates_from_pos\" , \"copy_rates_range\" , \"copy_ticks_from\" , \"copy_ticks_range\" , \"fetch_latest_closed_rates\" , \"history_deals\" , \"history_orders\" , \"last_error\" , \"latest_rates\" , \"market_book\" , \"minimum_margins\" , \"mt5_session\" , \"mt5_summary\" , \"mt5_summary_as_df\" , \"orders\" , \"positions\" , \"recent_history_deals\" , \"recent_ticks\" , \"resolve_account_spec\" , \"resolve_account_specs\" , \"substitute_env_placeholders\" , \"substitute_mapping_values\" , \"symbol_info\" , \"symbol_info_tick\" , \"symbols\" , \"terminal_info\" , \"update_history\" , \"update_history_with_config\" , \"version\" , ] logger module-attribute \u00b6 logger = getLogger ( __name__ ) AccountSpec dataclass \u00b6 AccountSpec ( symbols : Sequence [ str ], login : int | str | None = None , password : str | None = None , server : str | None = None , path : str | None = None , timeout : int | None = None , ) Connection parameters and symbols for one MT5 account group. Attributes: Name Type Description symbols Sequence [ str ] Symbols to load latest rates for under this account. login int | str | None Trading account login. String values are coerced to int when non-empty. password str | None Trading account password. server str | None Trading server name. path str | None Path to the MetaTrader5 terminal EXE file. timeout int | None Connection timeout in milliseconds. login class-attribute instance-attribute \u00b6 login : int | str | None = field ( default = None , repr = False ) password class-attribute instance-attribute \u00b6 password : str | None = field ( default = None , repr = False ) path class-attribute instance-attribute \u00b6 path : str | None = None server class-attribute instance-attribute \u00b6 server : str | None = None symbols instance-attribute \u00b6 symbols : Sequence [ str ] timeout class-attribute instance-attribute \u00b6 timeout : int | None = None Mt5CliClient \u00b6 Mt5CliClient ( * , path : str | None = None , login : int | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , retry_count : int = 3 , config : Mt5Config | None = None , client : Mt5DataClient | None = None , ) Programmatic client for read-only MetaTrader 5 data access. Initialize the SDK client. Parameters: Name Type Description Default path str | None Path to MetaTrader5 terminal EXE file. None login int | None Trading account login. None password str | None Trading account password. None server str | None Trading server name. None timeout int | None Connection timeout in milliseconds. None retry_count int Number of MT5 initialization retries for sessions opened by this client. 3 config Mt5Config | None Optional pre-built Mt5Config (overrides other args). None client Mt5DataClient | None Optional already-connected Mt5DataClient . Injected clients are reused as-is and are not initialized or shut down. None Source code in mt5cli/sdk.py 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 def __init__ ( self , * , path : str | None = None , login : int | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , retry_count : int = 3 , config : Mt5Config | None = None , client : Mt5DataClient | None = None , ) -> None : \"\"\"Initialize the SDK client. Args: path: Path to MetaTrader5 terminal EXE file. login: Trading account login. password: Trading account password. server: Trading server name. timeout: Connection timeout in milliseconds. retry_count: Number of MT5 initialization retries for sessions opened by this client. config: Optional pre-built ``Mt5Config`` (overrides other args). client: Optional already-connected ``Mt5DataClient``. Injected clients are reused as-is and are not initialized or shut down. \"\"\" self . _config = config or build_config ( path = path , login = login , password = password , server = server , timeout = timeout , ) self . _retry_count = retry_count self . _client = client self . _owns_client = client is None config property \u00b6 config : Mt5Config Return the underlying MT5 configuration. __enter__ \u00b6 __enter__ () -> Self Open a persistent MT5 connection for multiple calls. Returns: Type Description Self This client instance. Source code in mt5cli/sdk.py 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 def __enter__ ( self ) -> Self : \"\"\"Open a persistent MT5 connection for multiple calls. Returns: This client instance. \"\"\" if self . _client is not None : return self client = Mt5DataClient ( config = self . _config , retry_count = self . _retry_count ) try : client . initialize_and_login_mt5 () except Exception : client . shutdown () raise self . _client = client self . _owns_client = True # only set when this method created the client return self __exit__ \u00b6 __exit__ ( exc_type : type [ BaseException ] | None , exc : BaseException | None , tb : object , ) -> None Shut down the persistent MT5 connection. Source code in mt5cli/sdk.py 486 487 488 489 490 491 492 493 494 495 def __exit__ ( self , exc_type : type [ BaseException ] | None , exc : BaseException | None , tb : object , ) -> None : \"\"\"Shut down the persistent MT5 connection.\"\"\" if self . _client is not None and self . _owns_client : self . _client . shutdown () self . _client = None account_info \u00b6 account_info () -> DataFrame Return account information. Source code in mt5cli/sdk.py 649 650 651 def account_info ( self ) -> pd . DataFrame : \"\"\"Return account information.\"\"\" return self . _fetch ( lambda c : c . account_info_as_df ()) collect_latest_rates \u00b6 collect_latest_rates ( symbols : Sequence [ str ], timeframes : Sequence [ int | str ], * , count : int , start_pos : int = 0 , ) -> dict [ tuple [ str , int ], DataFrame ] Return latest rates for each symbol/timeframe pair. Returns: Type Description dict [ tuple [ str , int ], DataFrame ] Mapping keyed by (symbol, timeframe_int) . Raises: Type Description ValueError If count is not positive or inputs are empty. Source code in mt5cli/sdk.py 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 def collect_latest_rates ( self , symbols : Sequence [ str ], timeframes : Sequence [ int | str ], * , count : int , start_pos : int = 0 , ) -> dict [ tuple [ str , int ], pd . DataFrame ]: \"\"\"Return latest rates for each symbol/timeframe pair. Returns: Mapping keyed by ``(symbol, timeframe_int)``. Raises: ValueError: If ``count`` is not positive or inputs are empty. \"\"\" _require_positive ( count , \"count\" ) if not symbols : msg = \"At least one symbol is required.\" raise ValueError ( msg ) if not timeframes : msg = \"At least one timeframe is required.\" raise ValueError ( msg ) resolved_timeframes = [ _coerce_timeframe ( timeframe ) for timeframe in timeframes ] return self . _fetch_value ( lambda c : { ( symbol , timeframe ): c . copy_rates_from_pos_as_df ( symbol = symbol , timeframe = timeframe , start_pos = start_pos , count = count , ) for symbol in symbols for timeframe in resolved_timeframes }, ) copy_rates_from \u00b6 copy_rates_from ( symbol : str , timeframe : int | str , date_from : datetime | str , count : int , ) -> DataFrame Return rates starting from a date. Source code in mt5cli/sdk.py 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 def copy_rates_from ( self , symbol : str , timeframe : int | str , date_from : datetime | str , count : int , ) -> pd . DataFrame : \"\"\"Return rates starting from a date.\"\"\" tf = _coerce_timeframe ( timeframe ) start = _require_datetime ( date_from ) return self . _fetch ( lambda c : c . copy_rates_from_as_df ( symbol = symbol , timeframe = tf , date_from = start , count = count , ), ) copy_rates_from_pos \u00b6 copy_rates_from_pos ( symbol : str , timeframe : int | str , start_pos : int , count : int , ) -> DataFrame Return rates starting from a bar position. Source code in mt5cli/sdk.py 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 def copy_rates_from_pos ( self , symbol : str , timeframe : int | str , start_pos : int , count : int , ) -> pd . DataFrame : \"\"\"Return rates starting from a bar position.\"\"\" tf = _coerce_timeframe ( timeframe ) return self . _fetch ( lambda c : c . copy_rates_from_pos_as_df ( symbol = symbol , timeframe = tf , start_pos = start_pos , count = count , ), ) copy_rates_range \u00b6 copy_rates_range ( symbol : str , timeframe : int | str , date_from : datetime | str , date_to : datetime | str , ) -> DataFrame Return rates for a date range. Source code in mt5cli/sdk.py 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 def copy_rates_range ( self , symbol : str , timeframe : int | str , date_from : datetime | str , date_to : datetime | str , ) -> pd . DataFrame : \"\"\"Return rates for a date range.\"\"\" tf = _coerce_timeframe ( timeframe ) start = _require_datetime ( date_from ) end = _require_datetime ( date_to ) return self . _fetch ( lambda c : c . copy_rates_range_as_df ( symbol = symbol , timeframe = tf , date_from = start , date_to = end , ), ) copy_ticks_from \u00b6 copy_ticks_from ( symbol : str , date_from : datetime | str , count : int , flags : int | str , ) -> DataFrame Return ticks starting from a date. Source code in mt5cli/sdk.py 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 def copy_ticks_from ( self , symbol : str , date_from : datetime | str , count : int , flags : int | str , ) -> pd . DataFrame : \"\"\"Return ticks starting from a date.\"\"\" start = _require_datetime ( date_from ) tick_flags = _coerce_tick_flags ( flags ) return self . _fetch ( lambda c : c . copy_ticks_from_as_df ( symbol = symbol , date_from = start , count = count , flags = tick_flags , ), ) copy_ticks_range \u00b6 copy_ticks_range ( symbol : str , date_from : datetime | str , date_to : datetime | str , flags : int | str , ) -> DataFrame Return ticks for a date range. Source code in mt5cli/sdk.py 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 def copy_ticks_range ( self , symbol : str , date_from : datetime | str , date_to : datetime | str , flags : int | str , ) -> pd . DataFrame : \"\"\"Return ticks for a date range.\"\"\" start = _require_datetime ( date_from ) end = _require_datetime ( date_to ) tick_flags = _coerce_tick_flags ( flags ) return self . _fetch ( lambda c : c . copy_ticks_range_as_df ( symbol = symbol , date_from = start , date_to = end , flags = tick_flags , ), ) from_connected_client classmethod \u00b6 from_connected_client ( client : Mt5DataClient ) -> Self Bind to an already-connected Mt5DataClient without owning it. The returned Mt5CliClient never initializes or shuts down the injected client, including when used as a context manager. Returns: Type Description Self Client wrapper bound to the injected connection. Source code in mt5cli/sdk.py 451 452 453 454 455 456 457 458 459 460 461 @classmethod def from_connected_client ( cls , client : Mt5DataClient ) -> Self : \"\"\"Bind to an already-connected ``Mt5DataClient`` without owning it. The returned ``Mt5CliClient`` never initializes or shuts down the injected client, including when used as a context manager. Returns: Client wrapper bound to the injected connection. \"\"\" return cls ( client = client ) history_deals \u00b6 history_deals ( date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , ) -> DataFrame Return historical deals. Source code in mt5cli/sdk.py 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 def history_deals ( self , date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , ) -> pd . DataFrame : \"\"\"Return historical deals.\"\"\" start = _coerce_datetime ( date_from ) end = _coerce_datetime ( date_to ) return self . _fetch ( lambda c : c . history_deals_get_as_df ( date_from = start , date_to = end , group = group , symbol = symbol , ticket = ticket , position = position , ), ) history_orders \u00b6 history_orders ( date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , ) -> DataFrame Return historical orders. Source code in mt5cli/sdk.py 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 def history_orders ( self , date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , ) -> pd . DataFrame : \"\"\"Return historical orders.\"\"\" start = _coerce_datetime ( date_from ) end = _coerce_datetime ( date_to ) return self . _fetch ( lambda c : c . history_orders_get_as_df ( date_from = start , date_to = end , group = group , symbol = symbol , ticket = ticket , position = position , ), ) last_error \u00b6 last_error () -> DataFrame Return the last error information. Source code in mt5cli/sdk.py 763 764 765 def last_error ( self ) -> pd . DataFrame : \"\"\"Return the last error information.\"\"\" return self . _fetch ( lambda c : c . last_error_as_df ()) latest_rates \u00b6 latest_rates ( symbol : str , timeframe : int | str , count : int , start_pos : int = 0 , ) -> DataFrame Return the latest rates from a bar position. Source code in mt5cli/sdk.py 542 543 544 545 546 547 548 549 550 551 def latest_rates ( self , symbol : str , timeframe : int | str , count : int , start_pos : int = 0 , ) -> pd . DataFrame : \"\"\"Return the latest rates from a bar position.\"\"\" _require_positive ( count , \"count\" ) return self . copy_rates_from_pos ( symbol , timeframe , start_pos , count ) market_book \u00b6 market_book ( symbol : str ) -> DataFrame Return market depth for a symbol. Source code in mt5cli/sdk.py 771 772 773 def market_book ( self , symbol : str ) -> pd . DataFrame : \"\"\"Return market depth for a symbol.\"\"\" return self . _fetch ( lambda c : c . market_book_get_as_df ( symbol = symbol )) minimum_margins \u00b6 minimum_margins ( symbol : str ) -> DataFrame Return minimum-volume buy and sell margin requirements. Parameters: Name Type Description Default symbol str Symbol name. required Returns: Type Description DataFrame One-row DataFrame with columns symbol , account_currency , DataFrame volume_min , buy_margin , and sell_margin . Source code in mt5cli/sdk.py 814 815 816 817 818 819 820 821 822 823 824 def minimum_margins ( self , symbol : str ) -> pd . DataFrame : \"\"\"Return minimum-volume buy and sell margin requirements. Args: symbol: Symbol name. Returns: One-row DataFrame with columns ``symbol``, ``account_currency``, ``volume_min``, ``buy_margin``, and ``sell_margin``. \"\"\" return self . _fetch ( lambda c : _fetch_minimum_margins ( c , symbol )) mt5_summary \u00b6 mt5_summary () -> dict [ str , object ] Return a compact terminal/account status summary. Source code in mt5cli/sdk.py 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 def mt5_summary ( self ) -> dict [ str , object ]: \"\"\"Return a compact terminal/account status summary.\"\"\" def _summary ( client : Mt5DataClient ) -> dict [ str , object ]: return { \"version\" : _plain_mt5_value ( _call_required_client_method ( client , \"version\" ), ), \"terminal_info\" : _plain_mt5_value ( _call_required_client_method ( client , \"terminal_info\" ), ), \"account_info\" : _plain_mt5_value ( _call_required_client_method ( client , \"account_info\" ), ), \"symbols_total\" : _plain_mt5_value ( _call_required_client_method ( client , \"symbols_total\" ), ), } return self . _fetch_value ( _summary ) mt5_summary_as_df \u00b6 mt5_summary_as_df () -> DataFrame Return an export-safe one-row terminal/account summary DataFrame. Source code in mt5cli/sdk.py 847 848 849 850 851 852 853 854 855 856 857 def mt5_summary_as_df ( self ) -> pd . DataFrame : \"\"\"Return an export-safe one-row terminal/account summary DataFrame.\"\"\" summary = self . mt5_summary () return pd . DataFrame ( [ { key : _mt5_summary_export_value ( value ) for key , value in summary . items () }, ], ) orders \u00b6 orders ( symbol : str | None = None , group : str | None = None , ticket : int | None = None , ) -> DataFrame Return active orders. Source code in mt5cli/sdk.py 665 666 667 668 669 670 671 672 673 674 675 676 677 678 def orders ( self , symbol : str | None = None , group : str | None = None , ticket : int | None = None , ) -> pd . DataFrame : \"\"\"Return active orders.\"\"\" return self . _fetch ( lambda c : c . orders_get_as_df ( symbol = symbol , group = group , ticket = ticket , ), ) positions \u00b6 positions ( symbol : str | None = None , group : str | None = None , ticket : int | None = None , ) -> DataFrame Return open positions. Source code in mt5cli/sdk.py 680 681 682 683 684 685 686 687 688 689 690 691 692 693 def positions ( self , symbol : str | None = None , group : str | None = None , ticket : int | None = None , ) -> pd . DataFrame : \"\"\"Return open positions.\"\"\" return self . _fetch ( lambda c : c . positions_get_as_df ( symbol = symbol , group = group , ticket = ticket , ), ) recent_history_deals \u00b6 recent_history_deals ( hours : float , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ) -> DataFrame Return historical deals from a recent trailing window. Source code in mt5cli/sdk.py 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 def recent_history_deals ( self , hours : float , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ) -> pd . DataFrame : \"\"\"Return historical deals from a recent trailing window.\"\"\" _require_positive ( hours , \"hours\" ) end = _require_datetime ( date_to ) if date_to is not None else datetime . now ( UTC ) start = end - timedelta ( hours = hours ) return self . history_deals ( date_from = start , date_to = end , group = group , symbol = symbol , ) recent_ticks \u00b6 recent_ticks ( symbol : str , seconds : float , * , date_to : datetime | str | None = None , count : int = 10000 , flags : int | str = \"ALL\" , ) -> DataFrame Return ticks from a recent time window. Parameters: Name Type Description Default symbol str Symbol name. required seconds float Lookback window in seconds ending at date_to . required date_to datetime | str | None Window end time. When None , uses the latest symbol_info_tick().time rather than wall-clock now. None count int Maximum ticks to return. Values <= 0 return the full window without trimming. Positive values keep the most recent ticks; when the window is sparse, copy_ticks_from avoids fetching the entire range. 10000 flags int | str Tick flags as ALL , INFO , TRADE , or an integer. 'ALL' Returns: Type Description DataFrame Tick DataFrame with MT5 tick columns such as time , bid , DataFrame ask , last , and volume . Source code in mt5cli/sdk.py 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 def recent_ticks ( self , symbol : str , seconds : float , * , date_to : datetime | str | None = None , count : int = 10000 , flags : int | str = \"ALL\" , ) -> pd . DataFrame : \"\"\"Return ticks from a recent time window. Args: symbol: Symbol name. seconds: Lookback window in seconds ending at ``date_to``. date_to: Window end time. When ``None``, uses the latest ``symbol_info_tick().time`` rather than wall-clock now. count: Maximum ticks to return. Values ``<= 0`` return the full window without trimming. Positive values keep the most recent ticks; when the window is sparse, ``copy_ticks_from`` avoids fetching the entire range. flags: Tick flags as ``ALL``, ``INFO``, ``TRADE``, or an integer. Returns: Tick DataFrame with MT5 tick columns such as ``time``, ``bid``, ``ask``, ``last``, and ``volume``. \"\"\" tick_flags = _coerce_tick_flags ( flags ) end = _coerce_datetime ( date_to ) return self . _fetch ( lambda c : _fetch_recent_ticks ( c , symbol , seconds , end , count , tick_flags , ), ) symbol_info \u00b6 symbol_info ( symbol : str ) -> DataFrame Return details for one symbol. Source code in mt5cli/sdk.py 661 662 663 def symbol_info ( self , symbol : str ) -> pd . DataFrame : \"\"\"Return details for one symbol.\"\"\" return self . _fetch ( lambda c : c . symbol_info_as_df ( symbol = symbol )) symbol_info_tick \u00b6 symbol_info_tick ( symbol : str ) -> DataFrame Return the last tick for a symbol. Source code in mt5cli/sdk.py 767 768 769 def symbol_info_tick ( self , symbol : str ) -> pd . DataFrame : \"\"\"Return the last tick for a symbol.\"\"\" return self . _fetch ( lambda c : c . symbol_info_tick_as_df ( symbol = symbol )) symbols \u00b6 symbols ( group : str | None = None ) -> DataFrame Return the symbol list. Source code in mt5cli/sdk.py 657 658 659 def symbols ( self , group : str | None = None ) -> pd . DataFrame : \"\"\"Return the symbol list.\"\"\" return self . _fetch ( lambda c : c . symbols_get_as_df ( group = group )) terminal_info \u00b6 terminal_info () -> DataFrame Return terminal information. Source code in mt5cli/sdk.py 653 654 655 def terminal_info ( self ) -> pd . DataFrame : \"\"\"Return terminal information.\"\"\" return self . _fetch ( lambda c : c . terminal_info_as_df ()) version \u00b6 version () -> DataFrame Return MetaTrader5 version information. Source code in mt5cli/sdk.py 759 760 761 def version ( self ) -> pd . DataFrame : \"\"\"Return MetaTrader5 version information.\"\"\" return self . _fetch ( lambda c : c . version_as_df ()) ThrottledHistoryUpdater \u00b6 ThrottledHistoryUpdater ( * , output : Path | str , datasets : set [ Dataset ] | None = None , timeframes : Sequence [ int | str ] | None = None , flags : int | str = \"ALL\" , lookback_hours : float = 24.0 , with_views : bool = False , include_account_events : bool = True , interval_seconds : float = 0.0 , suppress_errors : bool = False , update_backend : UpdateHistoryBackend | None = None , ) Throttled incremental SQLite history updater for long-running apps. Wraps :func: update_history (or a custom update_backend ) with a minimum interval between successful updates, so a tight application loop can call :meth: update every iteration without re-fetching MT5 history more often than desired. Timing uses a monotonic clock, so it is unaffected by wall-clock changes. Downstream applications may pass update_backend to substitute the default :func: update_history implementation\u2014for example to add application-specific logging, metrics, or test doubles\u2014without monkey- patching mt5cli.sdk.update_history . Initialize the throttled updater. Parameters: Name Type Description Default output Path | str SQLite database path. required datasets set [ Dataset ] | None Datasets to include (defaults to all). None timeframes Sequence [ int | str ] | None Rate timeframes to update (defaults to all fixed MT5 timeframes). None flags int | str Tick copy flags as integer or name (e.g. ALL ). 'ALL' lookback_hours float First-run lookback when a table has no prior rows. 24.0 with_views bool Create cash_events and positions_reconstructed views. False include_account_events bool Include account-level cash events. True interval_seconds float Minimum seconds between successful updates. Values <= 0 update on every call. 0.0 suppress_errors bool When True, recoverable errors ( Mt5TradingError , Mt5RuntimeError , sqlite3.Error , ValueError , OSError , and MT5 client capability AttributeError / TypeError for history API methods) raised during an update are swallowed and :meth: update returns False without advancing the throttle. Other AttributeError / TypeError values always propagate. When False (default), recoverable errors propagate so callers control logging. False update_backend UpdateHistoryBackend | None Callable invoked instead of :func: update_history when :meth: update runs. Receives the same keyword arguments as :func: update_history ( client , output , symbols , datasets , timeframes , flags , lookback_hours , with_views , include_account_events ). Defaults to :func: update_history . None Source code in mt5cli/sdk.py 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 def __init__ ( self , * , output : Path | str , datasets : set [ Dataset ] | None = None , timeframes : Sequence [ int | str ] | None = None , flags : int | str = \"ALL\" , lookback_hours : float = 24.0 , with_views : bool = False , include_account_events : bool = True , interval_seconds : float = 0.0 , suppress_errors : bool = False , update_backend : UpdateHistoryBackend | None = None , ) -> None : \"\"\"Initialize the throttled updater. Args: output: SQLite database path. datasets: Datasets to include (defaults to all). timeframes: Rate timeframes to update (defaults to all fixed MT5 timeframes). flags: Tick copy flags as integer or name (e.g. ``ALL``). lookback_hours: First-run lookback when a table has no prior rows. with_views: Create ``cash_events`` and ``positions_reconstructed`` views. include_account_events: Include account-level cash events. interval_seconds: Minimum seconds between successful updates. Values ``<= 0`` update on every call. suppress_errors: When True, recoverable errors (``Mt5TradingError``, ``Mt5RuntimeError``, ``sqlite3.Error``, ``ValueError``, ``OSError``, and MT5 client capability ``AttributeError`` / ``TypeError`` for history API methods) raised during an update are swallowed and :meth:`update` returns False without advancing the throttle. Other ``AttributeError`` / ``TypeError`` values always propagate. When False (default), recoverable errors propagate so callers control logging. update_backend: Callable invoked instead of :func:`update_history` when :meth:`update` runs. Receives the same keyword arguments as :func:`update_history` (``client``, ``output``, ``symbols``, ``datasets``, ``timeframes``, ``flags``, ``lookback_hours``, ``with_views``, ``include_account_events``). Defaults to :func:`update_history`. \"\"\" self . output = output self . datasets = datasets self . timeframes = timeframes self . flags = flags self . lookback_hours = lookback_hours self . with_views = with_views self . include_account_events = include_account_events self . interval_seconds = interval_seconds self . suppress_errors = suppress_errors self . update_backend = ( update_history if update_backend is None else update_backend ) self . _last_update_monotonic : float | None = None datasets instance-attribute \u00b6 datasets = datasets flags instance-attribute \u00b6 flags = flags include_account_events instance-attribute \u00b6 include_account_events = include_account_events interval_seconds instance-attribute \u00b6 interval_seconds = interval_seconds last_update_monotonic property \u00b6 last_update_monotonic : float | None Return the monotonic timestamp of the last successful update. lookback_hours instance-attribute \u00b6 lookback_hours = lookback_hours output instance-attribute \u00b6 output = output suppress_errors instance-attribute \u00b6 suppress_errors = suppress_errors timeframes instance-attribute \u00b6 timeframes = timeframes update_backend instance-attribute \u00b6 update_backend = ( update_history if update_backend is None else update_backend ) with_views instance-attribute \u00b6 with_views = with_views should_update \u00b6 should_update () -> bool Return whether enough time has elapsed to run another update. Returns: Type Description bool True when interval_seconds <= 0 , when no update has succeeded bool yet, or when at least interval_seconds have elapsed since the bool last successful update. Source code in mt5cli/sdk.py 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 def should_update ( self ) -> bool : \"\"\"Return whether enough time has elapsed to run another update. Returns: True when ``interval_seconds <= 0``, when no update has succeeded yet, or when at least ``interval_seconds`` have elapsed since the last successful update. \"\"\" if self . interval_seconds <= 0 or self . _last_update_monotonic is None : return True return ( time . monotonic () - self . _last_update_monotonic ) >= self . interval_seconds update \u00b6 update ( client : Mt5DataClient , symbols : Sequence [ str ] ) -> bool Run a throttled incremental history update. Parameters: Name Type Description Default client Mt5DataClient Connected MT5 data client. required symbols Sequence [ str ] Symbols to update. required Returns: Type Description bool True if an update ran successfully, False if it was throttled or bool (when suppress_errors is True) failed with a recoverable error. bool When suppress_errors is False, recoverable update failures bool propagate to the caller. Raises: Type Description AttributeError MT5 client capability mismatch when suppress_errors is False, or any other attribute error. TypeError MT5 client capability mismatch when suppress_errors is False, or any other type error. Source code in mt5cli/sdk.py 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 def update ( self , client : Mt5DataClient , symbols : Sequence [ str ]) -> bool : \"\"\"Run a throttled incremental history update. Args: client: Connected MT5 data client. symbols: Symbols to update. Returns: True if an update ran successfully, False if it was throttled or (when ``suppress_errors`` is True) failed with a recoverable error. When ``suppress_errors`` is False, recoverable update failures propagate to the caller. Raises: AttributeError: MT5 client capability mismatch when ``suppress_errors`` is False, or any other attribute error. TypeError: MT5 client capability mismatch when ``suppress_errors`` is False, or any other type error. \"\"\" if not self . should_update (): return False try : _resolve_update_history_request ( output = self . output , symbols = symbols , datasets = self . datasets , timeframes = self . timeframes , flags = self . flags , lookback_hours = self . lookback_hours , date_to = None , ) self . update_backend ( client = client , output = self . output , symbols = symbols , datasets = self . datasets , timeframes = self . timeframes , flags = self . flags , lookback_hours = self . lookback_hours , with_views = self . with_views , include_account_events = self . include_account_events , ) except _RECOVERABLE_HISTORY_UPDATE_ERRORS : if self . suppress_errors : logger . warning ( \"Suppressed history update error\" , exc_info = True ) return False raise except ( AttributeError , TypeError ) as exc : if self . suppress_errors and _is_mt5_client_capability_error ( exc ): logger . warning ( \"Suppressed history update error\" , exc_info = True ) return False raise self . _last_update_monotonic = time . monotonic () return True account_info \u00b6 account_info ( * , config : Mt5Config | None = None ) -> DataFrame Return account information. Source code in mt5cli/sdk.py 1956 1957 1958 def account_info ( * , config : Mt5Config | None = None ) -> pd . DataFrame : \"\"\"Return account information.\"\"\" return _make_client ( config = config ) . account_info () build_config \u00b6 build_config ( * , path : str | None = None , login : int | str | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , allow_whole_dollar_env : bool = False , ) -> Mt5Config Build an Mt5Config from optional connection parameters. Parameters: Name Type Description Default path str | None Optional terminal executable path. None login int | str | None Optional trading account login. Integers are preserved. String values are coerced: empty or whitespace-only strings become None ; numeric strings such as \"12345\" are converted to int ; non-numeric strings raise ValueError . When allow_whole_dollar_env=True , $ENV_NAME and ${ENV_NAME} placeholders are expanded before coercion. None password str | None Optional trading account password. None server str | None Optional trading server name. None timeout int | None Optional connection timeout in milliseconds. None allow_whole_dollar_env bool When True , string parameters that are exactly $ENV_NAME are expanded from the environment. Applies to path , login , password , and server . Default False preserves existing behavior. False Returns: Type Description Mt5Config Configured Mt5Config instance. Source code in mt5cli/sdk.py 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 def build_config ( * , path : str | None = None , login : int | str | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , allow_whole_dollar_env : bool = False , ) -> Mt5Config : \"\"\"Build an ``Mt5Config`` from optional connection parameters. Args: path: Optional terminal executable path. login: Optional trading account login. Integers are preserved. String values are coerced: empty or whitespace-only strings become ``None``; numeric strings such as ``\"12345\"`` are converted to ``int``; non-numeric strings raise ``ValueError``. When ``allow_whole_dollar_env=True``, ``$ENV_NAME`` and ``${ENV_NAME}`` placeholders are expanded before coercion. password: Optional trading account password. server: Optional trading server name. timeout: Optional connection timeout in milliseconds. allow_whole_dollar_env: When ``True``, string parameters that are exactly ``$ENV_NAME`` are expanded from the environment. Applies to ``path``, ``login``, ``password``, and ``server``. Default ``False`` preserves existing behavior. Returns: Configured ``Mt5Config`` instance. \"\"\" if allow_whole_dollar_env : if path is not None : path = substitute_env_placeholders ( path , allow_whole_dollar_env = True ) if isinstance ( login , str ): login = substitute_env_placeholders ( login , allow_whole_dollar_env = True ) if password is not None : password = substitute_env_placeholders ( password , allow_whole_dollar_env = True ) if server is not None : server = substitute_env_placeholders ( server , allow_whole_dollar_env = True ) return Mt5Config ( path = path , login = _coerce_login ( login ), password = password , server = server , timeout = timeout , ) collect_history \u00b6 collect_history ( output : Path , symbols : list [ str ], date_from : datetime | str , date_to : datetime | str , * , datasets : set [ Dataset ] | None = None , timeframe : int | str = 1 , flags : int | str = \"ALL\" , if_exists : IfExists = FAIL , with_views : bool = False , config : Mt5Config | None = None , ) -> None Collect historical datasets into a single SQLite database. Parameters: Name Type Description Default output Path SQLite database path. required symbols list [ str ] Symbols to collect. required date_from datetime | str Start date. required date_to datetime | str End date. required datasets set [ Dataset ] | None Datasets to include (defaults to all). None timeframe int | str Rates timeframe as integer or name (e.g. M1 ). 1 flags int | str Tick copy flags as integer or name (e.g. ALL ). 'ALL' if_exists IfExists Behavior when a target table already exists. FAIL with_views bool Create cash_events and positions_reconstructed views. False config Mt5Config | None MT5 connection configuration. None Source code in mt5cli/sdk.py 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 def collect_history ( output : Path , symbols : list [ str ], date_from : datetime | str , date_to : datetime | str , * , datasets : set [ Dataset ] | None = None , timeframe : int | str = 1 , flags : int | str = \"ALL\" , if_exists : IfExists = IfExists . FAIL , with_views : bool = False , config : Mt5Config | None = None , ) -> None : \"\"\"Collect historical datasets into a single SQLite database. Args: output: SQLite database path. symbols: Symbols to collect. date_from: Start date. date_to: End date. datasets: Datasets to include (defaults to all). timeframe: Rates timeframe as integer or name (e.g. ``M1``). flags: Tick copy flags as integer or name (e.g. ``ALL``). if_exists: Behavior when a target table already exists. with_views: Create ``cash_events`` and ``positions_reconstructed`` views. config: MT5 connection configuration. \"\"\" start = _require_datetime ( date_from ) end = _require_datetime ( date_to ) selected = datasets if datasets is not None else set ( Dataset ) tf = _coerce_timeframe ( timeframe ) tick_flags = _coerce_tick_flags ( flags ) mt5_config = config or build_config () with connected_client ( mt5_config ) as client , sqlite3 . connect ( output ) as conn : conn . execute ( \"PRAGMA journal_mode=WAL\" ) conn . execute ( \"PRAGMA synchronous=NORMAL\" ) written_tables , written_columns = write_collected_datasets ( conn , client , symbols , selected , tf , tick_flags , start , end , if_exists , ) create_history_indexes ( conn , written_columns ) if with_views and Dataset . history_deals in written_tables : create_cash_events_view ( conn , written_columns [ Dataset . history_deals ]) create_positions_reconstructed_view ( conn , written_columns [ Dataset . history_deals ], ) elif with_views : logger . warning ( \"--with-views ignored: history_deals table was not written\" , ) logger . info ( \"Collected %s for %d symbol(s) into %s \" , \", \" . join ( sorted ( ds . value for ds in selected )), len ( symbols ), output , ) collect_latest_closed_rates_by_granularity \u00b6 collect_latest_closed_rates_by_granularity ( accounts : Sequence [ AccountSpec ], granularities : Sequence [ int | str ], count : int , * , start_pos : int = 0 , base_config : Mt5Config | None = None , retry_count : int = 0 , backoff_base : float = 2.0 , ) -> dict [ tuple [ str , str ], DataFrame ] Collect latest closed rate bars keyed by symbol and granularity name. Thin wrapper around :func: collect_latest_closed_rates_for_accounts that rekeys the result by granularity name (for example M1 ) instead of the integer timeframe. Parameters: Name Type Description Default accounts Sequence [ AccountSpec ] Account groups to read. Each must define at least one symbol. required granularities Sequence [ int | str ] MT5 timeframes as integers or names (for example M1 ). required count int Number of closed bars to return per symbol/timeframe. required start_pos int Initial bar position offset passed to the underlying collector. 0 base_config Mt5Config | None Optional base configuration whose fields fill any value not set on an individual account. None retry_count int Maximum number of retries after the first attempt. 0 disables retries. 0 backoff_base float Base for exponential backoff between retry attempts. 2.0 Returns: Type Description dict [ tuple [ str , str ], DataFrame ] Mapping keyed by (symbol, granularity_name) . Propagates dict [ tuple [ str , str ], DataFrame ] ValueError from :func: collect_latest_closed_rates_for_accounts . Source code in mt5cli/sdk.py 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 def collect_latest_closed_rates_by_granularity ( accounts : Sequence [ AccountSpec ], granularities : Sequence [ int | str ], count : int , * , start_pos : int = 0 , base_config : Mt5Config | None = None , retry_count : int = 0 , backoff_base : float = 2.0 , ) -> dict [ tuple [ str , str ], pd . DataFrame ]: \"\"\"Collect latest closed rate bars keyed by symbol and granularity name. Thin wrapper around :func:`collect_latest_closed_rates_for_accounts` that rekeys the result by granularity name (for example ``M1``) instead of the integer timeframe. Args: accounts: Account groups to read. Each must define at least one symbol. granularities: MT5 timeframes as integers or names (for example ``M1``). count: Number of closed bars to return per symbol/timeframe. start_pos: Initial bar position offset passed to the underlying collector. base_config: Optional base configuration whose fields fill any value not set on an individual account. retry_count: Maximum number of retries after the first attempt. ``0`` disables retries. backoff_base: Base for exponential backoff between retry attempts. Returns: Mapping keyed by ``(symbol, granularity_name)``. Propagates ``ValueError`` from :func:`collect_latest_closed_rates_for_accounts`. \"\"\" loaded = collect_latest_closed_rates_for_accounts ( accounts , granularities , count , start_pos = start_pos , base_config = base_config , retry_count = retry_count , backoff_base = backoff_base , ) return { ( symbol , resolve_granularity_name ( timeframe )): frame for ( symbol , timeframe ), frame in loaded . items () } collect_latest_closed_rates_for_accounts \u00b6 collect_latest_closed_rates_for_accounts ( accounts : Sequence [ AccountSpec ], timeframes : Sequence [ int | str ], count : int , * , start_pos : int = 0 , base_config : Mt5Config | None = None , retry_count : int = 0 , backoff_base : float = 2.0 , ) -> dict [ tuple [ str , int ], DataFrame ] Collect latest closed rate bars across multiple MT5 account groups. When start_pos is 0 (the default), MetaTrader 5 includes the still-forming current bar as the last row. This helper fetches count + 1 bars, drops that bar with :func: drop_forming_rate_bar , and validates that each resulting frame is non-empty. When start_pos is greater than zero the forming bar is not in range, so only count bars are fetched and no row is dropped. Wraps :func: collect_latest_rates_for_accounts_with_retries for transient MT5 error handling. Parameters: Name Type Description Default accounts Sequence [ AccountSpec ] Account groups to read. Each must define at least one symbol. required timeframes Sequence [ int | str ] MT5 timeframes as integers or names (for example M1 ). required count int Number of closed bars to return per symbol/timeframe. required start_pos int Initial bar position offset passed to the underlying collector. 0 base_config Mt5Config | None Optional base configuration whose fields fill any value not set on an individual account. None retry_count int Maximum number of retries after the first attempt. 0 disables retries. 0 backoff_base float Base for exponential backoff between retry attempts. 2.0 Returns: Type Description dict [ tuple [ str , int ], DataFrame ] Mapping keyed by (symbol, timeframe_int) . Raises: Type Description ValueError If inputs are invalid, or any series is empty (after dropping the still-forming bar when start_pos is 0 ). Source code in mt5cli/sdk.py 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 def collect_latest_closed_rates_for_accounts ( accounts : Sequence [ AccountSpec ], timeframes : Sequence [ int | str ], count : int , * , start_pos : int = 0 , base_config : Mt5Config | None = None , retry_count : int = 0 , backoff_base : float = 2.0 , ) -> dict [ tuple [ str , int ], pd . DataFrame ]: \"\"\"Collect latest closed rate bars across multiple MT5 account groups. When ``start_pos`` is ``0`` (the default), MetaTrader 5 includes the still-forming current bar as the last row. This helper fetches ``count + 1`` bars, drops that bar with :func:`drop_forming_rate_bar`, and validates that each resulting frame is non-empty. When ``start_pos`` is greater than zero the forming bar is not in range, so only ``count`` bars are fetched and no row is dropped. Wraps :func:`collect_latest_rates_for_accounts_with_retries` for transient MT5 error handling. Args: accounts: Account groups to read. Each must define at least one symbol. timeframes: MT5 timeframes as integers or names (for example ``M1``). count: Number of closed bars to return per symbol/timeframe. start_pos: Initial bar position offset passed to the underlying collector. base_config: Optional base configuration whose fields fill any value not set on an individual account. retry_count: Maximum number of retries after the first attempt. ``0`` disables retries. backoff_base: Base for exponential backoff between retry attempts. Returns: Mapping keyed by ``(symbol, timeframe_int)``. Raises: ValueError: If inputs are invalid, or any series is empty (after dropping the still-forming bar when ``start_pos`` is ``0``). \"\"\" _require_positive ( count , \"count\" ) _require_non_negative ( start_pos , \"start_pos\" ) fetch_count = count + 1 if start_pos == 0 else count loaded = collect_latest_rates_for_accounts_with_retries ( accounts , timeframes , fetch_count , start_pos = start_pos , base_config = base_config , retry_count = retry_count , backoff_base = backoff_base , ) result : dict [ tuple [ str , int ], pd . DataFrame ] = {} for key , df_rate in loaded . items (): closed = drop_forming_rate_bar ( df_rate ) if start_pos == 0 else df_rate if closed . empty : symbol , timeframe = key msg = f \"Rate data is empty for { symbol !r} at timeframe { timeframe } .\" raise ValueError ( msg ) result [ key ] = closed return result collect_latest_rates \u00b6 collect_latest_rates ( symbols : Sequence [ str ], timeframes : Sequence [ int | str ], * , count : int , start_pos : int = 0 , config : Mt5Config | None = None , ) -> dict [ tuple [ str , int ], DataFrame ] Return latest rates for each symbol/timeframe pair. Source code in mt5cli/sdk.py 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 def collect_latest_rates ( symbols : Sequence [ str ], timeframes : Sequence [ int | str ], * , count : int , start_pos : int = 0 , config : Mt5Config | None = None , ) -> dict [ tuple [ str , int ], pd . DataFrame ]: \"\"\"Return latest rates for each symbol/timeframe pair.\"\"\" return _make_client ( config = config ) . collect_latest_rates ( symbols , timeframes , count = count , start_pos = start_pos , ) collect_latest_rates_for_accounts \u00b6 collect_latest_rates_for_accounts ( accounts : Sequence [ AccountSpec ], timeframes : Sequence [ int | str ], count : int , * , start_pos : int = 0 , base_config : Mt5Config | None = None , ) -> dict [ tuple [ str , int ], DataFrame ] Collect latest rates across multiple MT5 account groups. Each account is connected in turn, its symbols are read for every timeframe, and the resulting frames are merged into a single mapping. Parameters: Name Type Description Default accounts Sequence [ AccountSpec ] Account groups to read. Each must define at least one symbol. required timeframes Sequence [ int | str ] MT5 timeframes as integers or names (for example M1 ). required count int Number of most recent bars to read per symbol/timeframe. required start_pos int Initial bar position offset. 0 base_config Mt5Config | None Optional base configuration whose fields fill any value not set on an individual account. None Returns: Type Description dict [ tuple [ str , int ], DataFrame ] Mapping keyed by (symbol, timeframe_int) . When accounts share a dict [ tuple [ str , int ], DataFrame ] symbol/timeframe pair, the last account processed wins. Raises: Type Description ValueError If accounts , timeframes , or any account's symbols are empty, or count is not positive. Source code in mt5cli/sdk.py 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 def collect_latest_rates_for_accounts ( accounts : Sequence [ AccountSpec ], timeframes : Sequence [ int | str ], count : int , * , start_pos : int = 0 , base_config : Mt5Config | None = None , ) -> dict [ tuple [ str , int ], pd . DataFrame ]: \"\"\"Collect latest rates across multiple MT5 account groups. Each account is connected in turn, its symbols are read for every timeframe, and the resulting frames are merged into a single mapping. Args: accounts: Account groups to read. Each must define at least one symbol. timeframes: MT5 timeframes as integers or names (for example ``M1``). count: Number of most recent bars to read per symbol/timeframe. start_pos: Initial bar position offset. base_config: Optional base configuration whose fields fill any value not set on an individual account. Returns: Mapping keyed by ``(symbol, timeframe_int)``. When accounts share a symbol/timeframe pair, the last account processed wins. Raises: ValueError: If ``accounts``, ``timeframes``, or any account's symbols are empty, or ``count`` is not positive. \"\"\" account_list = list ( accounts ) if not account_list : msg = \"At least one account is required.\" raise ValueError ( msg ) if not timeframes : msg = \"At least one timeframe is required.\" raise ValueError ( msg ) if any ( not account . symbols for account in account_list ): msg = \"Each account requires at least one symbol.\" raise ValueError ( msg ) _require_positive ( count , \"count\" ) result : dict [ tuple [ str , int ], pd . DataFrame ] = {} for account in account_list : config = _build_account_config ( account , base_config ) with Mt5CliClient ( config = config ) as client : result . update ( client . collect_latest_rates ( account . symbols , timeframes , count = count , start_pos = start_pos , ), ) return result collect_latest_rates_for_accounts_with_retries \u00b6 collect_latest_rates_for_accounts_with_retries ( accounts : Sequence [ AccountSpec ], timeframes : Sequence [ int | str ], count : int , * , start_pos : int = 0 , base_config : Mt5Config | None = None , retry_count : int = 0 , backoff_base : float = 2.0 , ) -> dict [ tuple [ str , int ], DataFrame ] Collect latest rates across accounts, retrying transient MT5 failures. Wraps :func: collect_latest_rates_for_accounts with bounded exponential backoff. Only pdmt5.Mt5TradingError and pdmt5.Mt5RuntimeError are retried; other exceptions propagate immediately. The final failure is re-raised once retries are exhausted. Parameters: Name Type Description Default accounts Sequence [ AccountSpec ] Account groups to read. Each must define at least one symbol. required timeframes Sequence [ int | str ] MT5 timeframes as integers or names (for example M1 ). required count int Number of most recent bars to read per symbol/timeframe. required start_pos int Initial bar position offset. 0 base_config Mt5Config | None Optional base configuration whose fields fill any value not set on an individual account. None retry_count int Maximum number of retries after the first attempt. 0 disables retries. 0 backoff_base float Base for exponential backoff. The delay before retry attempt n (1-indexed) is backoff_base ** n seconds. 2.0 Returns: Type Description dict [ tuple [ str , int ], DataFrame ] Mapping keyed by (symbol, timeframe_int) . Propagates ValueError dict [ tuple [ str , int ], DataFrame ] for invalid inputs (see :func: collect_latest_rates_for_accounts ) and dict [ tuple [ str , int ], DataFrame ] re-raises the last pdmt5.Mt5TradingError or pdmt5.Mt5RuntimeError dict [ tuple [ str , int ], DataFrame ] once retries are exhausted. Source code in mt5cli/sdk.py 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 def collect_latest_rates_for_accounts_with_retries ( accounts : Sequence [ AccountSpec ], timeframes : Sequence [ int | str ], count : int , * , start_pos : int = 0 , base_config : Mt5Config | None = None , retry_count : int = 0 , backoff_base : float = 2.0 , ) -> dict [ tuple [ str , int ], pd . DataFrame ]: \"\"\"Collect latest rates across accounts, retrying transient MT5 failures. Wraps :func:`collect_latest_rates_for_accounts` with bounded exponential backoff. Only ``pdmt5.Mt5TradingError`` and ``pdmt5.Mt5RuntimeError`` are retried; other exceptions propagate immediately. The final failure is re-raised once retries are exhausted. Args: accounts: Account groups to read. Each must define at least one symbol. timeframes: MT5 timeframes as integers or names (for example ``M1``). count: Number of most recent bars to read per symbol/timeframe. start_pos: Initial bar position offset. base_config: Optional base configuration whose fields fill any value not set on an individual account. retry_count: Maximum number of retries after the first attempt. ``0`` disables retries. backoff_base: Base for exponential backoff. The delay before retry attempt ``n`` (1-indexed) is ``backoff_base ** n`` seconds. Returns: Mapping keyed by ``(symbol, timeframe_int)``. Propagates ``ValueError`` for invalid inputs (see :func:`collect_latest_rates_for_accounts`) and re-raises the last ``pdmt5.Mt5TradingError`` or ``pdmt5.Mt5RuntimeError`` once retries are exhausted. \"\"\" def _collect () -> dict [ tuple [ str , int ], pd . DataFrame ]: return collect_latest_rates_for_accounts ( accounts , timeframes , count , start_pos = start_pos , base_config = base_config , ) return retry_with_backoff ( _collect , retry_count = retry_count , backoff_base = backoff_base , operation = \"Rate collection\" , ) connected_client \u00b6 connected_client ( config : Mt5Config , ) -> Iterator [ Mt5DataClient ] Initialize MT5, yield a connected client, and always shut down. Parameters: Name Type Description Default config Mt5Config MT5 connection configuration. required Yields: Type Description Mt5DataClient Connected Mt5DataClient instance. Source code in mt5cli/sdk.py 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 @contextmanager def connected_client ( config : Mt5Config ) -> Iterator [ Mt5DataClient ]: \"\"\"Initialize MT5, yield a connected client, and always shut down. Args: config: MT5 connection configuration. Yields: Connected ``Mt5DataClient`` instance. \"\"\" client = Mt5DataClient ( config = config ) try : client . initialize_and_login_mt5 () yield client finally : client . shutdown () copy_rates_from \u00b6 copy_rates_from ( symbol : str , timeframe : int | str , date_from : datetime | str , count : int , * , config : Mt5Config | None = None , ) -> DataFrame Return rates starting from a date. Source code in mt5cli/sdk.py 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 def copy_rates_from ( symbol : str , timeframe : int | str , date_from : datetime | str , count : int , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return rates starting from a date.\"\"\" return _make_client ( config = config ) . copy_rates_from ( symbol , timeframe , date_from , count , ) copy_rates_from_pos \u00b6 copy_rates_from_pos ( symbol : str , timeframe : int | str , start_pos : int , count : int , * , config : Mt5Config | None = None , ) -> DataFrame Return rates starting from a bar position. Source code in mt5cli/sdk.py 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 def copy_rates_from_pos ( symbol : str , timeframe : int | str , start_pos : int , count : int , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return rates starting from a bar position.\"\"\" return _make_client ( config = config ) . copy_rates_from_pos ( symbol , timeframe , start_pos , count , ) copy_rates_range \u00b6 copy_rates_range ( symbol : str , timeframe : int | str , date_from : datetime | str , date_to : datetime | str , * , config : Mt5Config | None = None , ) -> DataFrame Return rates for a date range. Source code in mt5cli/sdk.py 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 def copy_rates_range ( symbol : str , timeframe : int | str , date_from : datetime | str , date_to : datetime | str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return rates for a date range.\"\"\" return _make_client ( config = config ) . copy_rates_range ( symbol , timeframe , date_from , date_to , ) copy_ticks_from \u00b6 copy_ticks_from ( symbol : str , date_from : datetime | str , count : int , flags : int | str , * , config : Mt5Config | None = None , ) -> DataFrame Return ticks starting from a date. Source code in mt5cli/sdk.py 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 def copy_ticks_from ( symbol : str , date_from : datetime | str , count : int , flags : int | str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return ticks starting from a date.\"\"\" return _make_client ( config = config ) . copy_ticks_from ( symbol , date_from , count , flags , ) copy_ticks_range \u00b6 copy_ticks_range ( symbol : str , date_from : datetime | str , date_to : datetime | str , flags : int | str , * , config : Mt5Config | None = None , ) -> DataFrame Return ticks for a date range. Source code in mt5cli/sdk.py 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 def copy_ticks_range ( symbol : str , date_from : datetime | str , date_to : datetime | str , flags : int | str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return ticks for a date range.\"\"\" return _make_client ( config = config ) . copy_ticks_range ( symbol , date_from , date_to , flags , ) fetch_latest_closed_rates \u00b6 fetch_latest_closed_rates ( client : Mt5CliClient , * , symbol : str , granularity : str , count : int , ) -> DataFrame Fetch up to count most recent closed bars, oldest to newest. Returns: Type Description DataFrame Closed rate bars ordered oldest to newest. Raises: Type Description ValueError If count is not positive or no closed bars are returned. Source code in mt5cli/sdk.py 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 def fetch_latest_closed_rates ( client : Mt5CliClient , * , symbol : str , granularity : str , count : int , ) -> pd . DataFrame : \"\"\"Fetch up to ``count`` most recent closed bars, oldest to newest. Returns: Closed rate bars ordered oldest to newest. Raises: ValueError: If ``count`` is not positive or no closed bars are returned. \"\"\" _require_positive ( count , \"count\" ) frame = client . latest_rates ( symbol , granularity , count + 1 , start_pos = 0 ) closed = drop_forming_rate_bar ( frame ) if closed . empty : msg = ( f \"Rate data is empty for { symbol !r} at granularity { granularity !r} \" f \"with count { count } .\" ) raise ValueError ( msg ) return closed . tail ( count ) . reset_index ( drop = True ) history_deals \u00b6 history_deals ( date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , * , config : Mt5Config | None = None , ) -> DataFrame Return historical deals. Source code in mt5cli/sdk.py 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 def history_deals ( date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return historical deals.\"\"\" return _make_client ( config = config ) . history_deals ( date_from = date_from , date_to = date_to , group = group , symbol = symbol , ticket = ticket , position = position , ) history_orders \u00b6 history_orders ( date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , * , config : Mt5Config | None = None , ) -> DataFrame Return historical orders. Source code in mt5cli/sdk.py 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 def history_orders ( date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return historical orders.\"\"\" return _make_client ( config = config ) . history_orders ( date_from = date_from , date_to = date_to , group = group , symbol = symbol , ticket = ticket , position = position , ) last_error \u00b6 last_error ( * , config : Mt5Config | None = None ) -> DataFrame Return the last error information. Source code in mt5cli/sdk.py 2078 2079 2080 def last_error ( * , config : Mt5Config | None = None ) -> pd . DataFrame : \"\"\"Return the last error information.\"\"\" return _make_client ( config = config ) . last_error () latest_rates \u00b6 latest_rates ( symbol : str , timeframe : int | str , count : int , start_pos : int = 0 , * , config : Mt5Config | None = None , ) -> DataFrame Return the latest rates from a bar position. Source code in mt5cli/sdk.py 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 def latest_rates ( symbol : str , timeframe : int | str , count : int , start_pos : int = 0 , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return the latest rates from a bar position.\"\"\" return _make_client ( config = config ) . latest_rates ( symbol , timeframe , count , start_pos = start_pos , ) market_book \u00b6 market_book ( symbol : str , * , config : Mt5Config | None = None ) -> DataFrame Return market depth for a symbol. Source code in mt5cli/sdk.py 2092 2093 2094 2095 2096 2097 2098 def market_book ( symbol : str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return market depth for a symbol.\"\"\" return _make_client ( config = config ) . market_book ( symbol ) minimum_margins \u00b6 minimum_margins ( symbol : str , * , config : Mt5Config | None = None ) -> DataFrame Return minimum-volume buy and sell margin requirements. See Mt5CliClient.minimum_margins for return details. Source code in mt5cli/sdk.py 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 def minimum_margins ( symbol : str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return minimum-volume buy and sell margin requirements. See ``Mt5CliClient.minimum_margins`` for return details. \"\"\" return _make_client ( config = config ) . minimum_margins ( symbol ) mt5_session \u00b6 mt5_session ( config : Mt5Config | None = None , ) -> Iterator [ Mt5CliClient ] Open an MT5 terminal session and yield a connected client. Launches the MetaTrader 5 terminal using Mt5Config.path (when set), logs in, yields a connected :class: Mt5CliClient , and always shuts the terminal down on exit. Parameters: Name Type Description Default config Mt5Config | None MT5 connection configuration. Defaults to an empty config that attaches to a running terminal. None Yields: Type Description Mt5CliClient Connected Mt5CliClient bound to the session. Source code in mt5cli/sdk.py 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 @contextmanager def mt5_session ( config : Mt5Config | None = None ) -> Iterator [ Mt5CliClient ]: \"\"\"Open an MT5 terminal session and yield a connected client. Launches the MetaTrader 5 terminal using ``Mt5Config.path`` (when set), logs in, yields a connected :class:`Mt5CliClient`, and always shuts the terminal down on exit. Args: config: MT5 connection configuration. Defaults to an empty config that attaches to a running terminal. Yields: Connected ``Mt5CliClient`` bound to the session. \"\"\" mt5_config = config or build_config () with connected_client ( mt5_config ) as client : yield Mt5CliClient . from_connected_client ( client ) mt5_summary \u00b6 mt5_summary ( * , config : Mt5Config | None = None ) -> dict [ str , object ] Return a compact terminal/account status summary. Source code in mt5cli/sdk.py 2135 2136 2137 def mt5_summary ( * , config : Mt5Config | None = None ) -> dict [ str , object ]: \"\"\"Return a compact terminal/account status summary.\"\"\" return _make_client ( config = config ) . mt5_summary () mt5_summary_as_df \u00b6 mt5_summary_as_df ( * , config : Mt5Config | None = None ) -> DataFrame Return an export-safe terminal/account status summary DataFrame. Source code in mt5cli/sdk.py 2140 2141 2142 def mt5_summary_as_df ( * , config : Mt5Config | None = None ) -> pd . DataFrame : \"\"\"Return an export-safe terminal/account status summary DataFrame.\"\"\" return _make_client ( config = config ) . mt5_summary_as_df () orders \u00b6 orders ( symbol : str | None = None , group : str | None = None , ticket : int | None = None , * , config : Mt5Config | None = None , ) -> DataFrame Return active orders. Source code in mt5cli/sdk.py 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 def orders ( symbol : str | None = None , group : str | None = None , ticket : int | None = None , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return active orders.\"\"\" return _make_client ( config = config ) . orders ( symbol = symbol , group = group , ticket = ticket , ) positions \u00b6 positions ( symbol : str | None = None , group : str | None = None , ticket : int | None = None , * , config : Mt5Config | None = None , ) -> DataFrame Return open positions. Source code in mt5cli/sdk.py 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 def positions ( symbol : str | None = None , group : str | None = None , ticket : int | None = None , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return open positions.\"\"\" return _make_client ( config = config ) . positions ( symbol = symbol , group = group , ticket = ticket , ) recent_history_deals \u00b6 recent_history_deals ( hours : float , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , * , config : Mt5Config | None = None , ) -> DataFrame Return historical deals from a recent trailing window. Source code in mt5cli/sdk.py 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 def recent_history_deals ( hours : float , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return historical deals from a recent trailing window.\"\"\" return _make_client ( config = config ) . recent_history_deals ( hours , date_to = date_to , group = group , symbol = symbol , ) recent_ticks \u00b6 recent_ticks ( symbol : str , seconds : float , * , date_to : datetime | str | None = None , count : int = 10000 , flags : int | str = \"ALL\" , config : Mt5Config | None = None , ) -> DataFrame Return ticks from a recent time window ending at date_to or now. See Mt5CliClient.recent_ticks for parameter and return details. Source code in mt5cli/sdk.py 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 def recent_ticks ( symbol : str , seconds : float , * , date_to : datetime | str | None = None , count : int = 10000 , flags : int | str = \"ALL\" , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return ticks from a recent time window ending at ``date_to`` or now. See ``Mt5CliClient.recent_ticks`` for parameter and return details. \"\"\" return _make_client ( config = config ) . recent_ticks ( symbol , seconds , date_to = date_to , count = count , flags = flags , ) resolve_account_spec \u00b6 resolve_account_spec ( account : AccountSpec , * , login : int | str | None = None , password : str | None = None , server : str | None = None , path : str | None = None , timeout : int | None = None , allow_whole_dollar_env : bool = False , ) -> AccountSpec Resolve an account's credentials from overrides and ${ENV_VAR} values. Explicit override arguments take precedence over the corresponding :class: AccountSpec fields. The resolved string fields ( login , password , server , path ) have any ${ENV_VAR} placeholders substituted from the environment. Parameters: Name Type Description Default account AccountSpec Source account specification. required login int | str | None Optional explicit login override. None password str | None Optional explicit password override. None server str | None Optional explicit server override. None path str | None Optional explicit terminal path override. None timeout int | None Optional explicit connection timeout override. None allow_whole_dollar_env bool When True , string fields that are exactly $ENV_NAME are also expanded from the environment. Default False preserves existing behavior. False Returns: Type Description AccountSpec A new :class: AccountSpec with resolved credentials and the original AccountSpec symbols preserved. Raises ValueError (via AccountSpec func: substitute_env_placeholders ) if a referenced environment AccountSpec variable is not set. Source code in mt5cli/sdk.py 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 def resolve_account_spec ( account : AccountSpec , * , login : int | str | None = None , password : str | None = None , server : str | None = None , path : str | None = None , timeout : int | None = None , allow_whole_dollar_env : bool = False , ) -> AccountSpec : \"\"\"Resolve an account's credentials from overrides and ``${ENV_VAR}`` values. Explicit override arguments take precedence over the corresponding :class:`AccountSpec` fields. The resolved string fields (``login``, ``password``, ``server``, ``path``) have any ``${ENV_VAR}`` placeholders substituted from the environment. Args: account: Source account specification. login: Optional explicit login override. password: Optional explicit password override. server: Optional explicit server override. path: Optional explicit terminal path override. timeout: Optional explicit connection timeout override. allow_whole_dollar_env: When ``True``, string fields that are exactly ``$ENV_NAME`` are also expanded from the environment. Default ``False`` preserves existing behavior. Returns: A new :class:`AccountSpec` with resolved credentials and the original symbols preserved. Raises ``ValueError`` (via :func:`substitute_env_placeholders`) if a referenced environment variable is not set. \"\"\" return AccountSpec ( symbols = account . symbols , login = _resolve_login ( login , account . login , allow_whole_dollar_env = allow_whole_dollar_env ), password = _resolve_field ( password , account . password , allow_whole_dollar_env = allow_whole_dollar_env ), server = _resolve_field ( server , account . server , allow_whole_dollar_env = allow_whole_dollar_env ), path = _resolve_field ( path , account . path , allow_whole_dollar_env = allow_whole_dollar_env ), timeout = timeout if timeout is not None else account . timeout , ) resolve_account_specs \u00b6 resolve_account_specs ( accounts : Sequence [ AccountSpec ], * , login : int | str | None = None , password : str | None = None , server : str | None = None , path : str | None = None , timeout : int | None = None , allow_whole_dollar_env : bool = False , ) -> list [ AccountSpec ] Resolve credentials for multiple accounts. Applies the same overrides and ${ENV_VAR} substitution as :func: resolve_account_spec to every account. Parameters: Name Type Description Default accounts Sequence [ AccountSpec ] Source account specifications. required login int | str | None Optional explicit login override applied to each account. None password str | None Optional explicit password override applied to each account. None server str | None Optional explicit server override applied to each account. None path str | None Optional explicit terminal path override applied to each account. None timeout int | None Optional explicit timeout override applied to each account. None allow_whole_dollar_env bool When True , string fields that are exactly $ENV_NAME are also expanded from the environment. Default False preserves existing behavior. False Returns: Type Description list [ AccountSpec ] Resolved account specifications in the original order. Raises list [ AccountSpec ] ValueError (via :func: substitute_env_placeholders ) if a referenced list [ AccountSpec ] environment variable is not set. Source code in mt5cli/sdk.py 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 def resolve_account_specs ( accounts : Sequence [ AccountSpec ], * , login : int | str | None = None , password : str | None = None , server : str | None = None , path : str | None = None , timeout : int | None = None , allow_whole_dollar_env : bool = False , ) -> list [ AccountSpec ]: \"\"\"Resolve credentials for multiple accounts. Applies the same overrides and ``${ENV_VAR}`` substitution as :func:`resolve_account_spec` to every account. Args: accounts: Source account specifications. login: Optional explicit login override applied to each account. password: Optional explicit password override applied to each account. server: Optional explicit server override applied to each account. path: Optional explicit terminal path override applied to each account. timeout: Optional explicit timeout override applied to each account. allow_whole_dollar_env: When ``True``, string fields that are exactly ``$ENV_NAME`` are also expanded from the environment. Default ``False`` preserves existing behavior. Returns: Resolved account specifications in the original order. Raises ``ValueError`` (via :func:`substitute_env_placeholders`) if a referenced environment variable is not set. \"\"\" return [ resolve_account_spec ( account , login = login , password = password , server = server , path = path , timeout = timeout , allow_whole_dollar_env = allow_whole_dollar_env , ) for account in accounts ] substitute_env_placeholders \u00b6 substitute_env_placeholders ( value : str , * , allow_whole_dollar_env : bool = False ) -> str Replace ${ENV_VAR} placeholders in a string with environment values. Parameters: Name Type Description Default value str String that may contain one or more ${ENV_VAR} placeholders. required allow_whole_dollar_env bool When True , a string that is exactly $ENV_NAME (the whole value and nothing else) is also expanded from the environment. Partial occurrences such as \"plan$pass\" or \"$ENV-suffix\" are left unchanged. False Returns: Type Description str The string with every placeholder replaced by its environment value. Raises: Type Description ValueError If a referenced environment variable is not set. Source code in mt5cli/sdk.py 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 def substitute_env_placeholders ( value : str , * , allow_whole_dollar_env : bool = False , ) -> str : \"\"\"Replace ``${ENV_VAR}`` placeholders in a string with environment values. Args: value: String that may contain one or more ``${ENV_VAR}`` placeholders. allow_whole_dollar_env: When ``True``, a string that is exactly ``$ENV_NAME`` (the whole value and nothing else) is also expanded from the environment. Partial occurrences such as ``\"plan$pass\"`` or ``\"$ENV-suffix\"`` are left unchanged. Returns: The string with every placeholder replaced by its environment value. Raises: ValueError: If a referenced environment variable is not set. \"\"\" if allow_whole_dollar_env : m = _WHOLE_DOLLAR_PATTERN . match ( value ) if m : name = m . group ( \"name\" ) if name not in os . environ : msg = f \"Environment variable { name !r} is not set.\" raise ValueError ( msg ) return os . environ [ name ] parts : list [ str ] = [] last_end = 0 for match in _ENV_PLACEHOLDER_PATTERN . finditer ( value ): parts . append ( value [ last_end : match . start ()]) name = match . group ( \"name\" ) if name not in os . environ : msg = f \"Environment variable { name !r} is not set.\" raise ValueError ( msg ) parts . append ( os . environ [ name ]) last_end = match . end () parts . append ( value [ last_end :]) return \"\" . join ( parts ) substitute_mapping_values \u00b6 substitute_mapping_values ( data : object , * , keys : Collection [ str ], allow_whole_dollar_env : bool = False , blank_string_keys_as_none : Collection [ str ] = (), ) -> object Recursively substitute environment placeholders for selected mapping keys. Traverses nested dicts and lists, expanding ${ENV_VAR} (and $ENV_NAME when allow_whole_dollar_env=True ) in string values whose immediate parent dict key is in keys . Fields whose key is not in keys are preserved exactly, including literal dollar signs. Strings that are direct elements of a list are never substituted; substitution only applies to strings that are immediate dict values. This is a generic downstream config utility. Key names such as mt5_login or mt5_password must be supplied by the caller; mt5cli does not hard-code any application-specific key names. Callers are responsible for ensuring data has bounded nesting depth; deeply nested or self-referential structures will hit Python's recursion limit. Parameters: Name Type Description Default data object Arbitrarily nested dict/list/scalar value to process. required keys Collection [ str ] Mapping keys whose string values receive placeholder substitution. required allow_whole_dollar_env bool When True , a string that is exactly $ENV_NAME (whole value) is also expanded from the environment in addition to ${ENV_NAME} placeholders. Default False expands ${ENV_NAME} only. False blank_string_keys_as_none Collection [ str ] Mapping keys for which blank strings (after any substitution) are normalised to None . A key may appear in blank_string_keys_as_none without also appearing in keys . () Returns: Type Description object The processed value. Dicts and lists are rebuilt into new object containers with selected string values substituted and object blank-normalised. Scalar inputs (non-dict, non-list) are object returned as-is. Source code in mt5cli/sdk.py 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 def substitute_mapping_values ( data : object , * , keys : Collection [ str ], allow_whole_dollar_env : bool = False , blank_string_keys_as_none : Collection [ str ] = (), ) -> object : \"\"\"Recursively substitute environment placeholders for selected mapping keys. Traverses nested dicts and lists, expanding ``${ENV_VAR}`` (and ``$ENV_NAME`` when ``allow_whole_dollar_env=True``) in string values whose immediate parent dict key is in ``keys``. Fields whose key is not in ``keys`` are preserved exactly, including literal dollar signs. Strings that are direct elements of a list are never substituted; substitution only applies to strings that are immediate dict values. This is a generic downstream config utility. Key names such as ``mt5_login`` or ``mt5_password`` must be supplied by the caller; mt5cli does not hard-code any application-specific key names. Callers are responsible for ensuring ``data`` has bounded nesting depth; deeply nested or self-referential structures will hit Python's recursion limit. Args: data: Arbitrarily nested dict/list/scalar value to process. keys: Mapping keys whose string values receive placeholder substitution. allow_whole_dollar_env: When ``True``, a string that is exactly ``$ENV_NAME`` (whole value) is also expanded from the environment in addition to ``${ENV_NAME}`` placeholders. Default ``False`` expands ``${ENV_NAME}`` only. blank_string_keys_as_none: Mapping keys for which blank strings (after any substitution) are normalised to ``None``. A key may appear in ``blank_string_keys_as_none`` without also appearing in ``keys``. Returns: The processed value. Dicts and lists are rebuilt into new containers with selected string values substituted and blank-normalised. Scalar inputs (non-dict, non-list) are returned as-is. \"\"\" keys_set : frozenset [ str ] = frozenset ( keys ) blank_keys_set : frozenset [ str ] = frozenset ( blank_string_keys_as_none ) def _visit ( node : object , current_key : str | None ) -> object : if isinstance ( node , dict ): typed = cast ( \"dict[object, object]\" , node ) return { k : _visit ( v , k if isinstance ( k , str ) else None ) for k , v in typed . items () } if isinstance ( node , list ): typed_list = cast ( \"list[object]\" , node ) return [ _visit ( item , None ) for item in typed_list ] if not isinstance ( node , str ): return node text = node if current_key in keys_set : text = substitute_env_placeholders ( node , allow_whole_dollar_env = allow_whole_dollar_env ) if current_key in blank_keys_set and not text . strip (): return None return text return _visit ( data , None ) symbol_info \u00b6 symbol_info ( symbol : str , * , config : Mt5Config | None = None ) -> DataFrame Return details for one symbol. Source code in mt5cli/sdk.py 1975 1976 1977 1978 1979 1980 1981 def symbol_info ( symbol : str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return details for one symbol.\"\"\" return _make_client ( config = config ) . symbol_info ( symbol ) symbol_info_tick \u00b6 symbol_info_tick ( symbol : str , * , config : Mt5Config | None = None ) -> DataFrame Return the last tick for a symbol. Source code in mt5cli/sdk.py 2083 2084 2085 2086 2087 2088 2089 def symbol_info_tick ( symbol : str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return the last tick for a symbol.\"\"\" return _make_client ( config = config ) . symbol_info_tick ( symbol ) symbols \u00b6 symbols ( group : str | None = None , * , config : Mt5Config | None = None , ) -> DataFrame Return the symbol list. Source code in mt5cli/sdk.py 1966 1967 1968 1969 1970 1971 1972 def symbols ( group : str | None = None , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return the symbol list.\"\"\" return _make_client ( config = config ) . symbols ( group = group ) terminal_info \u00b6 terminal_info ( * , config : Mt5Config | None = None ) -> DataFrame Return terminal information. Source code in mt5cli/sdk.py 1961 1962 1963 def terminal_info ( * , config : Mt5Config | None = None ) -> pd . DataFrame : \"\"\"Return terminal information.\"\"\" return _make_client ( config = config ) . terminal_info () update_history \u00b6 update_history ( * , client : Mt5DataClient , output : Path | str , symbols : Sequence [ str ], datasets : set [ Dataset ] | None = None , timeframes : Sequence [ int | str ] | None = None , flags : int | str = \"ALL\" , lookback_hours : float = 24.0 , date_to : datetime | str | None = None , deduplicate : bool = True , create_rate_views : bool = True , with_views : bool = False , include_account_events : bool = True , ) -> None Incrementally append MT5 history into a SQLite database. Uses an already-connected Mt5DataClient and does not create or close the MT5 connection. For first-time tables, data is fetched from date_to - lookback_hours . Subsequent runs resume from existing MAX(time) per symbol (and timeframe for rates); when include_account_events=True , account-level deals use a separate cursor over type NOT IN (0, 1) / empty-symbol rows. Parameters: Name Type Description Default client Mt5DataClient Connected MT5 data client. required output Path | str SQLite database path. required symbols Sequence [ str ] Symbols to update. required datasets set [ Dataset ] | None Datasets to include (defaults to all). None timeframes Sequence [ int | str ] | None Rate timeframes to update (defaults to all fixed MT5 timeframes when None). None flags int | str Tick copy flags as integer or name (e.g. ALL ). 'ALL' lookback_hours float First-run lookback when a table has no prior rows. 24.0 date_to datetime | str | None Optional update end datetime. Defaults to now (UTC). None deduplicate bool Remove duplicate rows after append, keeping latest ROWID. True create_rate_views bool Create rate___ views. True with_views bool Create cash_events and positions_reconstructed views. False include_account_events bool Include account-level cash events in history_deals when True. True Source code in mt5cli/sdk.py 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 def update_history ( # noqa: PLR0913 * , client : Mt5DataClient , output : Path | str , symbols : Sequence [ str ], datasets : set [ Dataset ] | None = None , timeframes : Sequence [ int | str ] | None = None , flags : int | str = \"ALL\" , lookback_hours : float = 24.0 , date_to : datetime | str | None = None , deduplicate : bool = True , create_rate_views : bool = True , with_views : bool = False , include_account_events : bool = True , ) -> None : \"\"\"Incrementally append MT5 history into a SQLite database. Uses an already-connected ``Mt5DataClient`` and does not create or close the MT5 connection. For first-time tables, data is fetched from ``date_to - lookback_hours``. Subsequent runs resume from existing ``MAX(time)`` per symbol (and timeframe for rates); when ``include_account_events=True``, account-level deals use a separate cursor over ``type NOT IN (0, 1)`` / empty-symbol rows. Args: client: Connected MT5 data client. output: SQLite database path. symbols: Symbols to update. datasets: Datasets to include (defaults to all). timeframes: Rate timeframes to update (defaults to all fixed MT5 timeframes when None). flags: Tick copy flags as integer or name (e.g. ``ALL``). lookback_hours: First-run lookback when a table has no prior rows. date_to: Optional update end datetime. Defaults to now (UTC). deduplicate: Remove duplicate rows after append, keeping latest ROWID. create_rate_views: Create ``rate___`` views. with_views: Create ``cash_events`` and ``positions_reconstructed`` views. include_account_events: Include account-level cash events in ``history_deals`` when True. \"\"\" request = _resolve_update_history_request ( output = output , symbols = symbols , datasets = datasets , timeframes = timeframes , flags = flags , lookback_hours = lookback_hours , date_to = date_to , ) if request is None : return logger . info ( \"Updating history in SQLite: symbols= %s , datasets= %s , path= %s \" , list ( symbols ), sorted ( dataset . value for dataset in request . selected ), request . output_path , ) with sqlite3 . connect ( request . output_path ) as conn : conn . execute ( \"PRAGMA journal_mode=WAL\" ) conn . execute ( \"PRAGMA synchronous=NORMAL\" ) write_incremental_datasets ( conn , client , symbols , request . selected , request . resolved_timeframes , request . resolved_tick_flags , request . fallback_start , request . end , deduplicate = deduplicate , create_rate_views = create_rate_views , with_views = with_views , include_account_events = include_account_events , ) update_history_with_config \u00b6 update_history_with_config ( * , output : Path | str , symbols : Sequence [ str ], config : Mt5Config | None = None , datasets : set [ Dataset ] | None = None , timeframes : Sequence [ int | str ] | None = None , flags : int | str = \"ALL\" , lookback_hours : float = 24.0 , date_to : datetime | str | None = None , deduplicate : bool = True , create_rate_views : bool = True , with_views : bool = False , include_account_events : bool = True , ) -> None Incrementally append MT5 history, opening and closing the MT5 connection. Convenience wrapper around :func: update_history for standalone use. Source code in mt5cli/sdk.py 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 def update_history_with_config ( # noqa: PLR0913 * , output : Path | str , symbols : Sequence [ str ], config : Mt5Config | None = None , datasets : set [ Dataset ] | None = None , timeframes : Sequence [ int | str ] | None = None , flags : int | str = \"ALL\" , lookback_hours : float = 24.0 , date_to : datetime | str | None = None , deduplicate : bool = True , create_rate_views : bool = True , with_views : bool = False , include_account_events : bool = True , ) -> None : \"\"\"Incrementally append MT5 history, opening and closing the MT5 connection. Convenience wrapper around :func:`update_history` for standalone use. \"\"\" request = _resolve_update_history_request ( output = output , symbols = symbols , datasets = datasets , timeframes = timeframes , flags = flags , lookback_hours = lookback_hours , date_to = date_to , ) if request is None : return mt5_config = config or build_config () with connected_client ( mt5_config ) as client : update_history ( client = client , output = output , symbols = symbols , datasets = datasets , timeframes = timeframes , flags = flags , lookback_hours = lookback_hours , date_to = date_to , deduplicate = deduplicate , create_rate_views = create_rate_views , with_views = with_views , include_account_events = include_account_events , ) version \u00b6 version ( * , config : Mt5Config | None = None ) -> DataFrame Return MetaTrader5 version information. Source code in mt5cli/sdk.py 2073 2074 2075 def version ( * , config : Mt5Config | None = None ) -> pd . DataFrame : \"\"\"Return MetaTrader5 version information.\"\"\" return _make_client ( config = config ) . version () Resilient multi-account orchestration \u00b6 The SDK ships strategy-agnostic helpers for building long-running collectors on top of the read-only client. None of them depend on a particular trading application. Retrying transient rate collection \u00b6 collect_latest_rates_for_accounts_with_retries() wraps collect_latest_rates_for_accounts() with bounded exponential backoff. Only pdmt5.Mt5TradingError and pdmt5.Mt5RuntimeError are retried; the final failure is re-raised once retry_count is exhausted. from mt5cli import AccountSpec , collect_latest_rates_for_accounts_with_retries accounts = [ AccountSpec ( symbols = [ \"EURUSD\" ], login = 12345 )] rates = collect_latest_rates_for_accounts_with_retries ( accounts , [ \"M1\" , \"H1\" ], count = 500 , retry_count = 3 , backoff_base = 2 , # sleeps 2s, 4s, 8s between attempts ) Latest closed rate bars \u00b6 MetaTrader 5 start_pos=0 includes the still-forming current bar as the last row. fetch_latest_closed_rates() handles one connected MT5Client ; use fetch_latest_closed_rates_for_trading_client() from an active Mt5TradingClient session. Multi-account helpers fetch count + 1 bars, drop that row with drop_forming_rate_bar() , and validate each series is non-empty. Returned frames are ordered oldest-to-newest and may contain fewer than count rows only when MT5 returns fewer closed bars. from mt5cli import ( AccountSpec , collect_latest_closed_rates_by_granularity , fetch_latest_closed_rates , ) closed = fetch_latest_closed_rates ( client , symbol = \"EURUSD\" , granularity = \"M1\" , count = 500 , ) rates = collect_latest_closed_rates_by_granularity ( [ AccountSpec ( symbols = [ \"EURUSD\" ], login = 12345 )], [ \"M1\" , \"H1\" ], count = 500 , retry_count = 3 , ) closed_m1 = rates [ \"EURUSD\" , \"M1\" ] Use collect_latest_closed_rates_by_granularity() when callers prefer keys such as (\"EURUSD\", \"M1\") instead of integer timeframes. Resolving credentials and ${ENV_VAR} placeholders \u00b6 resolve_account_spec() / resolve_account_specs() merge explicit override values over AccountSpec fields and expand ${ENV_VAR} placeholders, keeping secrets out of plan/config files. A missing environment variable raises ValueError . import os from mt5cli import AccountSpec , resolve_account_specs os . environ [ \"MT5_LOGIN\" ] = \"12345\" os . environ [ \"MT5_PASSWORD\" ] = \"secret\" accounts = [ AccountSpec ( symbols = [ \"EURUSD\" ], login = \"$ {MT5_LOGIN} \" , password = \"$ {MT5_PASSWORD} \" ) ] resolved = resolve_account_specs ( accounts , server = \"Broker-Demo\" ) # resolved[0].login == \"12345\", resolved[0].server == \"Broker-Demo\" Pass allow_whole_dollar_env=True to also expand strings whose entire value is a bare $ENV_NAME identifier (no braces). This opt-in covers substitute_env_placeholders() , resolve_account_spec() , resolve_account_specs() , and build_config() . Note: build_config cannot expand login because that parameter is int | None ; use resolve_account_spec for a string login placeholder. Partial strings such as \"plan$pass\" , \"abc$ENV\" , or \"$ENV-suffix\" are never expanded \u2014 only an exact $IDENTIFIER whole-string match qualifies. The default is False to preserve backward compatibility. import os from mt5cli import AccountSpec , resolve_account_specs os . environ [ \"MT5_PASSWORD\" ] = \"secret\" accounts = [ AccountSpec ( symbols = [ \"EURUSD\" ], password = \"$MT5_PASSWORD\" )] resolved = resolve_account_specs ( accounts , allow_whole_dollar_env = True ) # resolved[0].password == \"secret\" Throttled incremental history updates \u00b6 ThrottledHistoryUpdater wraps update_history() with a minimum interval between successful runs (using a monotonic clock), so an application loop can call it every iteration without over-fetching. from pdmt5 import Mt5Config , Mt5DataClient from mt5cli import Dataset , ThrottledHistoryUpdater updater = ThrottledHistoryUpdater ( output = \"history.db\" , datasets = { Dataset . rates }, timeframes = [ \"M1\" ], interval_seconds = 60 , # <= 0 updates on every call ) client = Mt5DataClient ( config = Mt5Config ( login = 12345 )) client . initialize_and_login_mt5 () try : while True : updater . update ( client , [ \"EURUSD\" , \"GBPUSD\" ]) # no-op until 60s elapse # ... do other work; break when shutting down ... finally : client . shutdown () Pass update_backend to substitute the default update_history implementation without monkey-patching mt5cli.sdk.update_history . The callable receives the same keyword arguments as update_history ( client , output , symbols , datasets , timeframes , flags , lookback_hours , with_views , include_account_events ). The resolved backend is stored on updater.update_backend for inspection or subclassing. from mt5cli import ThrottledHistoryUpdater , update_history def app_update_history ( ** kwargs ) -> None : update_history ( ** kwargs ) # or delegate to application-specific logic updater = ThrottledHistoryUpdater ( output = \"history.db\" , interval_seconds = 60 , update_backend = app_update_history , ) 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 \u00b6 For order placement and trading calculations, use the dedicated Trading module . Use mt5_session() / MT5Client for read-only collection.","title":"SDK"},{"location":"api/sdk/#sdk-module","text":"","title":"SDK Module"},{"location":"api/sdk/#mt5cli.sdk","text":"Programmatic SDK for MetaTrader 5 data collection.","title":"sdk"},{"location":"api/sdk/#mt5cli.sdk.T","text":"T = TypeVar ( 'T' )","title":"T"},{"location":"api/sdk/#mt5cli.sdk.UpdateHistoryBackend","text":"UpdateHistoryBackend = Callable [ ... , None ]","title":"UpdateHistoryBackend"},{"location":"api/sdk/#mt5cli.sdk.__all__","text":"__all__ = [ \"AccountSpec\" , \"Mt5CliClient\" , \"ThrottledHistoryUpdater\" , \"account_info\" , \"build_config\" , \"collect_history\" , \"collect_latest_closed_rates_by_granularity\" , \"collect_latest_closed_rates_for_accounts\" , \"collect_latest_rates\" , \"collect_latest_rates_for_accounts\" , \"collect_latest_rates_for_accounts_with_retries\" , \"connected_client\" , \"copy_rates_from\" , \"copy_rates_from_pos\" , \"copy_rates_range\" , \"copy_ticks_from\" , \"copy_ticks_range\" , \"fetch_latest_closed_rates\" , \"history_deals\" , \"history_orders\" , \"last_error\" , \"latest_rates\" , \"market_book\" , \"minimum_margins\" , \"mt5_session\" , \"mt5_summary\" , \"mt5_summary_as_df\" , \"orders\" , \"positions\" , \"recent_history_deals\" , \"recent_ticks\" , \"resolve_account_spec\" , \"resolve_account_specs\" , \"substitute_env_placeholders\" , \"substitute_mapping_values\" , \"symbol_info\" , \"symbol_info_tick\" , \"symbols\" , \"terminal_info\" , \"update_history\" , \"update_history_with_config\" , \"version\" , ]","title":"__all__"},{"location":"api/sdk/#mt5cli.sdk.logger","text":"logger = getLogger ( __name__ )","title":"logger"},{"location":"api/sdk/#mt5cli.sdk.AccountSpec","text":"AccountSpec ( symbols : Sequence [ str ], login : int | str | None = None , password : str | None = None , server : str | None = None , path : str | None = None , timeout : int | None = None , ) Connection parameters and symbols for one MT5 account group. Attributes: Name Type Description symbols Sequence [ str ] Symbols to load latest rates for under this account. login int | str | None Trading account login. String values are coerced to int when non-empty. password str | None Trading account password. server str | None Trading server name. path str | None Path to the MetaTrader5 terminal EXE file. timeout int | None Connection timeout in milliseconds.","title":"AccountSpec"},{"location":"api/sdk/#mt5cli.sdk.AccountSpec.login","text":"login : int | str | None = field ( default = None , repr = False )","title":"login"},{"location":"api/sdk/#mt5cli.sdk.AccountSpec.password","text":"password : str | None = field ( default = None , repr = False )","title":"password"},{"location":"api/sdk/#mt5cli.sdk.AccountSpec.path","text":"path : str | None = None","title":"path"},{"location":"api/sdk/#mt5cli.sdk.AccountSpec.server","text":"server : str | None = None","title":"server"},{"location":"api/sdk/#mt5cli.sdk.AccountSpec.symbols","text":"symbols : Sequence [ str ]","title":"symbols"},{"location":"api/sdk/#mt5cli.sdk.AccountSpec.timeout","text":"timeout : int | None = None","title":"timeout"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient","text":"Mt5CliClient ( * , path : str | None = None , login : int | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , retry_count : int = 3 , config : Mt5Config | None = None , client : Mt5DataClient | None = None , ) Programmatic client for read-only MetaTrader 5 data access. Initialize the SDK client. Parameters: Name Type Description Default path str | None Path to MetaTrader5 terminal EXE file. None login int | None Trading account login. None password str | None Trading account password. None server str | None Trading server name. None timeout int | None Connection timeout in milliseconds. None retry_count int Number of MT5 initialization retries for sessions opened by this client. 3 config Mt5Config | None Optional pre-built Mt5Config (overrides other args). None client Mt5DataClient | None Optional already-connected Mt5DataClient . Injected clients are reused as-is and are not initialized or shut down. None Source code in mt5cli/sdk.py 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 def __init__ ( self , * , path : str | None = None , login : int | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , retry_count : int = 3 , config : Mt5Config | None = None , client : Mt5DataClient | None = None , ) -> None : \"\"\"Initialize the SDK client. Args: path: Path to MetaTrader5 terminal EXE file. login: Trading account login. password: Trading account password. server: Trading server name. timeout: Connection timeout in milliseconds. retry_count: Number of MT5 initialization retries for sessions opened by this client. config: Optional pre-built ``Mt5Config`` (overrides other args). client: Optional already-connected ``Mt5DataClient``. Injected clients are reused as-is and are not initialized or shut down. \"\"\" self . _config = config or build_config ( path = path , login = login , password = password , server = server , timeout = timeout , ) self . _retry_count = retry_count self . _client = client self . _owns_client = client is None","title":"Mt5CliClient"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.config","text":"config : Mt5Config Return the underlying MT5 configuration.","title":"config"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.__enter__","text":"__enter__ () -> Self Open a persistent MT5 connection for multiple calls. Returns: Type Description Self This client instance. Source code in mt5cli/sdk.py 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 def __enter__ ( self ) -> Self : \"\"\"Open a persistent MT5 connection for multiple calls. Returns: This client instance. \"\"\" if self . _client is not None : return self client = Mt5DataClient ( config = self . _config , retry_count = self . _retry_count ) try : client . initialize_and_login_mt5 () except Exception : client . shutdown () raise self . _client = client self . _owns_client = True # only set when this method created the client return self","title":"__enter__"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.__exit__","text":"__exit__ ( exc_type : type [ BaseException ] | None , exc : BaseException | None , tb : object , ) -> None Shut down the persistent MT5 connection. Source code in mt5cli/sdk.py 486 487 488 489 490 491 492 493 494 495 def __exit__ ( self , exc_type : type [ BaseException ] | None , exc : BaseException | None , tb : object , ) -> None : \"\"\"Shut down the persistent MT5 connection.\"\"\" if self . _client is not None and self . _owns_client : self . _client . shutdown () self . _client = None","title":"__exit__"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.account_info","text":"account_info () -> DataFrame Return account information. Source code in mt5cli/sdk.py 649 650 651 def account_info ( self ) -> pd . DataFrame : \"\"\"Return account information.\"\"\" return self . _fetch ( lambda c : c . account_info_as_df ())","title":"account_info"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.collect_latest_rates","text":"collect_latest_rates ( symbols : Sequence [ str ], timeframes : Sequence [ int | str ], * , count : int , start_pos : int = 0 , ) -> dict [ tuple [ str , int ], DataFrame ] Return latest rates for each symbol/timeframe pair. Returns: Type Description dict [ tuple [ str , int ], DataFrame ] Mapping keyed by (symbol, timeframe_int) . Raises: Type Description ValueError If count is not positive or inputs are empty. Source code in mt5cli/sdk.py 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 def collect_latest_rates ( self , symbols : Sequence [ str ], timeframes : Sequence [ int | str ], * , count : int , start_pos : int = 0 , ) -> dict [ tuple [ str , int ], pd . DataFrame ]: \"\"\"Return latest rates for each symbol/timeframe pair. Returns: Mapping keyed by ``(symbol, timeframe_int)``. Raises: ValueError: If ``count`` is not positive or inputs are empty. \"\"\" _require_positive ( count , \"count\" ) if not symbols : msg = \"At least one symbol is required.\" raise ValueError ( msg ) if not timeframes : msg = \"At least one timeframe is required.\" raise ValueError ( msg ) resolved_timeframes = [ _coerce_timeframe ( timeframe ) for timeframe in timeframes ] return self . _fetch_value ( lambda c : { ( symbol , timeframe ): c . copy_rates_from_pos_as_df ( symbol = symbol , timeframe = timeframe , start_pos = start_pos , count = count , ) for symbol in symbols for timeframe in resolved_timeframes }, )","title":"collect_latest_rates"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.copy_rates_from","text":"copy_rates_from ( symbol : str , timeframe : int | str , date_from : datetime | str , count : int , ) -> DataFrame Return rates starting from a date. Source code in mt5cli/sdk.py 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 def copy_rates_from ( self , symbol : str , timeframe : int | str , date_from : datetime | str , count : int , ) -> pd . DataFrame : \"\"\"Return rates starting from a date.\"\"\" tf = _coerce_timeframe ( timeframe ) start = _require_datetime ( date_from ) return self . _fetch ( lambda c : c . copy_rates_from_as_df ( symbol = symbol , timeframe = tf , date_from = start , count = count , ), )","title":"copy_rates_from"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.copy_rates_from_pos","text":"copy_rates_from_pos ( symbol : str , timeframe : int | str , start_pos : int , count : int , ) -> DataFrame Return rates starting from a bar position. Source code in mt5cli/sdk.py 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 def copy_rates_from_pos ( self , symbol : str , timeframe : int | str , start_pos : int , count : int , ) -> pd . DataFrame : \"\"\"Return rates starting from a bar position.\"\"\" tf = _coerce_timeframe ( timeframe ) return self . _fetch ( lambda c : c . copy_rates_from_pos_as_df ( symbol = symbol , timeframe = tf , start_pos = start_pos , count = count , ), )","title":"copy_rates_from_pos"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.copy_rates_range","text":"copy_rates_range ( symbol : str , timeframe : int | str , date_from : datetime | str , date_to : datetime | str , ) -> DataFrame Return rates for a date range. Source code in mt5cli/sdk.py 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 def copy_rates_range ( self , symbol : str , timeframe : int | str , date_from : datetime | str , date_to : datetime | str , ) -> pd . DataFrame : \"\"\"Return rates for a date range.\"\"\" tf = _coerce_timeframe ( timeframe ) start = _require_datetime ( date_from ) end = _require_datetime ( date_to ) return self . _fetch ( lambda c : c . copy_rates_range_as_df ( symbol = symbol , timeframe = tf , date_from = start , date_to = end , ), )","title":"copy_rates_range"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.copy_ticks_from","text":"copy_ticks_from ( symbol : str , date_from : datetime | str , count : int , flags : int | str , ) -> DataFrame Return ticks starting from a date. Source code in mt5cli/sdk.py 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 def copy_ticks_from ( self , symbol : str , date_from : datetime | str , count : int , flags : int | str , ) -> pd . DataFrame : \"\"\"Return ticks starting from a date.\"\"\" start = _require_datetime ( date_from ) tick_flags = _coerce_tick_flags ( flags ) return self . _fetch ( lambda c : c . copy_ticks_from_as_df ( symbol = symbol , date_from = start , count = count , flags = tick_flags , ), )","title":"copy_ticks_from"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.copy_ticks_range","text":"copy_ticks_range ( symbol : str , date_from : datetime | str , date_to : datetime | str , flags : int | str , ) -> DataFrame Return ticks for a date range. Source code in mt5cli/sdk.py 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 def copy_ticks_range ( self , symbol : str , date_from : datetime | str , date_to : datetime | str , flags : int | str , ) -> pd . DataFrame : \"\"\"Return ticks for a date range.\"\"\" start = _require_datetime ( date_from ) end = _require_datetime ( date_to ) tick_flags = _coerce_tick_flags ( flags ) return self . _fetch ( lambda c : c . copy_ticks_range_as_df ( symbol = symbol , date_from = start , date_to = end , flags = tick_flags , ), )","title":"copy_ticks_range"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.from_connected_client","text":"from_connected_client ( client : Mt5DataClient ) -> Self Bind to an already-connected Mt5DataClient without owning it. The returned Mt5CliClient never initializes or shuts down the injected client, including when used as a context manager. Returns: Type Description Self Client wrapper bound to the injected connection. Source code in mt5cli/sdk.py 451 452 453 454 455 456 457 458 459 460 461 @classmethod def from_connected_client ( cls , client : Mt5DataClient ) -> Self : \"\"\"Bind to an already-connected ``Mt5DataClient`` without owning it. The returned ``Mt5CliClient`` never initializes or shuts down the injected client, including when used as a context manager. Returns: Client wrapper bound to the injected connection. \"\"\" return cls ( client = client )","title":"from_connected_client"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.history_deals","text":"history_deals ( date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , ) -> DataFrame Return historical deals. Source code in mt5cli/sdk.py 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 def history_deals ( self , date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , ) -> pd . DataFrame : \"\"\"Return historical deals.\"\"\" start = _coerce_datetime ( date_from ) end = _coerce_datetime ( date_to ) return self . _fetch ( lambda c : c . history_deals_get_as_df ( date_from = start , date_to = end , group = group , symbol = symbol , ticket = ticket , position = position , ), )","title":"history_deals"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.history_orders","text":"history_orders ( date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , ) -> DataFrame Return historical orders. Source code in mt5cli/sdk.py 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 def history_orders ( self , date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , ) -> pd . DataFrame : \"\"\"Return historical orders.\"\"\" start = _coerce_datetime ( date_from ) end = _coerce_datetime ( date_to ) return self . _fetch ( lambda c : c . history_orders_get_as_df ( date_from = start , date_to = end , group = group , symbol = symbol , ticket = ticket , position = position , ), )","title":"history_orders"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.last_error","text":"last_error () -> DataFrame Return the last error information. Source code in mt5cli/sdk.py 763 764 765 def last_error ( self ) -> pd . DataFrame : \"\"\"Return the last error information.\"\"\" return self . _fetch ( lambda c : c . last_error_as_df ())","title":"last_error"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.latest_rates","text":"latest_rates ( symbol : str , timeframe : int | str , count : int , start_pos : int = 0 , ) -> DataFrame Return the latest rates from a bar position. Source code in mt5cli/sdk.py 542 543 544 545 546 547 548 549 550 551 def latest_rates ( self , symbol : str , timeframe : int | str , count : int , start_pos : int = 0 , ) -> pd . DataFrame : \"\"\"Return the latest rates from a bar position.\"\"\" _require_positive ( count , \"count\" ) return self . copy_rates_from_pos ( symbol , timeframe , start_pos , count )","title":"latest_rates"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.market_book","text":"market_book ( symbol : str ) -> DataFrame Return market depth for a symbol. Source code in mt5cli/sdk.py 771 772 773 def market_book ( self , symbol : str ) -> pd . DataFrame : \"\"\"Return market depth for a symbol.\"\"\" return self . _fetch ( lambda c : c . market_book_get_as_df ( symbol = symbol ))","title":"market_book"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.minimum_margins","text":"minimum_margins ( symbol : str ) -> DataFrame Return minimum-volume buy and sell margin requirements. Parameters: Name Type Description Default symbol str Symbol name. required Returns: Type Description DataFrame One-row DataFrame with columns symbol , account_currency , DataFrame volume_min , buy_margin , and sell_margin . Source code in mt5cli/sdk.py 814 815 816 817 818 819 820 821 822 823 824 def minimum_margins ( self , symbol : str ) -> pd . DataFrame : \"\"\"Return minimum-volume buy and sell margin requirements. Args: symbol: Symbol name. Returns: One-row DataFrame with columns ``symbol``, ``account_currency``, ``volume_min``, ``buy_margin``, and ``sell_margin``. \"\"\" return self . _fetch ( lambda c : _fetch_minimum_margins ( c , symbol ))","title":"minimum_margins"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.mt5_summary","text":"mt5_summary () -> dict [ str , object ] Return a compact terminal/account status summary. Source code in mt5cli/sdk.py 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 def mt5_summary ( self ) -> dict [ str , object ]: \"\"\"Return a compact terminal/account status summary.\"\"\" def _summary ( client : Mt5DataClient ) -> dict [ str , object ]: return { \"version\" : _plain_mt5_value ( _call_required_client_method ( client , \"version\" ), ), \"terminal_info\" : _plain_mt5_value ( _call_required_client_method ( client , \"terminal_info\" ), ), \"account_info\" : _plain_mt5_value ( _call_required_client_method ( client , \"account_info\" ), ), \"symbols_total\" : _plain_mt5_value ( _call_required_client_method ( client , \"symbols_total\" ), ), } return self . _fetch_value ( _summary )","title":"mt5_summary"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.mt5_summary_as_df","text":"mt5_summary_as_df () -> DataFrame Return an export-safe one-row terminal/account summary DataFrame. Source code in mt5cli/sdk.py 847 848 849 850 851 852 853 854 855 856 857 def mt5_summary_as_df ( self ) -> pd . DataFrame : \"\"\"Return an export-safe one-row terminal/account summary DataFrame.\"\"\" summary = self . mt5_summary () return pd . DataFrame ( [ { key : _mt5_summary_export_value ( value ) for key , value in summary . items () }, ], )","title":"mt5_summary_as_df"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.orders","text":"orders ( symbol : str | None = None , group : str | None = None , ticket : int | None = None , ) -> DataFrame Return active orders. Source code in mt5cli/sdk.py 665 666 667 668 669 670 671 672 673 674 675 676 677 678 def orders ( self , symbol : str | None = None , group : str | None = None , ticket : int | None = None , ) -> pd . DataFrame : \"\"\"Return active orders.\"\"\" return self . _fetch ( lambda c : c . orders_get_as_df ( symbol = symbol , group = group , ticket = ticket , ), )","title":"orders"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.positions","text":"positions ( symbol : str | None = None , group : str | None = None , ticket : int | None = None , ) -> DataFrame Return open positions. Source code in mt5cli/sdk.py 680 681 682 683 684 685 686 687 688 689 690 691 692 693 def positions ( self , symbol : str | None = None , group : str | None = None , ticket : int | None = None , ) -> pd . DataFrame : \"\"\"Return open positions.\"\"\" return self . _fetch ( lambda c : c . positions_get_as_df ( symbol = symbol , group = group , ticket = ticket , ), )","title":"positions"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.recent_history_deals","text":"recent_history_deals ( hours : float , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ) -> DataFrame Return historical deals from a recent trailing window. Source code in mt5cli/sdk.py 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 def recent_history_deals ( self , hours : float , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ) -> pd . DataFrame : \"\"\"Return historical deals from a recent trailing window.\"\"\" _require_positive ( hours , \"hours\" ) end = _require_datetime ( date_to ) if date_to is not None else datetime . now ( UTC ) start = end - timedelta ( hours = hours ) return self . history_deals ( date_from = start , date_to = end , group = group , symbol = symbol , )","title":"recent_history_deals"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.recent_ticks","text":"recent_ticks ( symbol : str , seconds : float , * , date_to : datetime | str | None = None , count : int = 10000 , flags : int | str = \"ALL\" , ) -> DataFrame Return ticks from a recent time window. Parameters: Name Type Description Default symbol str Symbol name. required seconds float Lookback window in seconds ending at date_to . required date_to datetime | str | None Window end time. When None , uses the latest symbol_info_tick().time rather than wall-clock now. None count int Maximum ticks to return. Values <= 0 return the full window without trimming. Positive values keep the most recent ticks; when the window is sparse, copy_ticks_from avoids fetching the entire range. 10000 flags int | str Tick flags as ALL , INFO , TRADE , or an integer. 'ALL' Returns: Type Description DataFrame Tick DataFrame with MT5 tick columns such as time , bid , DataFrame ask , last , and volume . Source code in mt5cli/sdk.py 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 def recent_ticks ( self , symbol : str , seconds : float , * , date_to : datetime | str | None = None , count : int = 10000 , flags : int | str = \"ALL\" , ) -> pd . DataFrame : \"\"\"Return ticks from a recent time window. Args: symbol: Symbol name. seconds: Lookback window in seconds ending at ``date_to``. date_to: Window end time. When ``None``, uses the latest ``symbol_info_tick().time`` rather than wall-clock now. count: Maximum ticks to return. Values ``<= 0`` return the full window without trimming. Positive values keep the most recent ticks; when the window is sparse, ``copy_ticks_from`` avoids fetching the entire range. flags: Tick flags as ``ALL``, ``INFO``, ``TRADE``, or an integer. Returns: Tick DataFrame with MT5 tick columns such as ``time``, ``bid``, ``ask``, ``last``, and ``volume``. \"\"\" tick_flags = _coerce_tick_flags ( flags ) end = _coerce_datetime ( date_to ) return self . _fetch ( lambda c : _fetch_recent_ticks ( c , symbol , seconds , end , count , tick_flags , ), )","title":"recent_ticks"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.symbol_info","text":"symbol_info ( symbol : str ) -> DataFrame Return details for one symbol. Source code in mt5cli/sdk.py 661 662 663 def symbol_info ( self , symbol : str ) -> pd . DataFrame : \"\"\"Return details for one symbol.\"\"\" return self . _fetch ( lambda c : c . symbol_info_as_df ( symbol = symbol ))","title":"symbol_info"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.symbol_info_tick","text":"symbol_info_tick ( symbol : str ) -> DataFrame Return the last tick for a symbol. Source code in mt5cli/sdk.py 767 768 769 def symbol_info_tick ( self , symbol : str ) -> pd . DataFrame : \"\"\"Return the last tick for a symbol.\"\"\" return self . _fetch ( lambda c : c . symbol_info_tick_as_df ( symbol = symbol ))","title":"symbol_info_tick"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.symbols","text":"symbols ( group : str | None = None ) -> DataFrame Return the symbol list. Source code in mt5cli/sdk.py 657 658 659 def symbols ( self , group : str | None = None ) -> pd . DataFrame : \"\"\"Return the symbol list.\"\"\" return self . _fetch ( lambda c : c . symbols_get_as_df ( group = group ))","title":"symbols"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.terminal_info","text":"terminal_info () -> DataFrame Return terminal information. Source code in mt5cli/sdk.py 653 654 655 def terminal_info ( self ) -> pd . DataFrame : \"\"\"Return terminal information.\"\"\" return self . _fetch ( lambda c : c . terminal_info_as_df ())","title":"terminal_info"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.version","text":"version () -> DataFrame Return MetaTrader5 version information. Source code in mt5cli/sdk.py 759 760 761 def version ( self ) -> pd . DataFrame : \"\"\"Return MetaTrader5 version information.\"\"\" return self . _fetch ( lambda c : c . version_as_df ())","title":"version"},{"location":"api/sdk/#mt5cli.sdk.ThrottledHistoryUpdater","text":"ThrottledHistoryUpdater ( * , output : Path | str , datasets : set [ Dataset ] | None = None , timeframes : Sequence [ int | str ] | None = None , flags : int | str = \"ALL\" , lookback_hours : float = 24.0 , with_views : bool = False , include_account_events : bool = True , interval_seconds : float = 0.0 , suppress_errors : bool = False , update_backend : UpdateHistoryBackend | None = None , ) Throttled incremental SQLite history updater for long-running apps. Wraps :func: update_history (or a custom update_backend ) with a minimum interval between successful updates, so a tight application loop can call :meth: update every iteration without re-fetching MT5 history more often than desired. Timing uses a monotonic clock, so it is unaffected by wall-clock changes. Downstream applications may pass update_backend to substitute the default :func: update_history implementation\u2014for example to add application-specific logging, metrics, or test doubles\u2014without monkey- patching mt5cli.sdk.update_history . Initialize the throttled updater. Parameters: Name Type Description Default output Path | str SQLite database path. required datasets set [ Dataset ] | None Datasets to include (defaults to all). None timeframes Sequence [ int | str ] | None Rate timeframes to update (defaults to all fixed MT5 timeframes). None flags int | str Tick copy flags as integer or name (e.g. ALL ). 'ALL' lookback_hours float First-run lookback when a table has no prior rows. 24.0 with_views bool Create cash_events and positions_reconstructed views. False include_account_events bool Include account-level cash events. True interval_seconds float Minimum seconds between successful updates. Values <= 0 update on every call. 0.0 suppress_errors bool When True, recoverable errors ( Mt5TradingError , Mt5RuntimeError , sqlite3.Error , ValueError , OSError , and MT5 client capability AttributeError / TypeError for history API methods) raised during an update are swallowed and :meth: update returns False without advancing the throttle. Other AttributeError / TypeError values always propagate. When False (default), recoverable errors propagate so callers control logging. False update_backend UpdateHistoryBackend | None Callable invoked instead of :func: update_history when :meth: update runs. Receives the same keyword arguments as :func: update_history ( client , output , symbols , datasets , timeframes , flags , lookback_hours , with_views , include_account_events ). Defaults to :func: update_history . None Source code in mt5cli/sdk.py 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 def __init__ ( self , * , output : Path | str , datasets : set [ Dataset ] | None = None , timeframes : Sequence [ int | str ] | None = None , flags : int | str = \"ALL\" , lookback_hours : float = 24.0 , with_views : bool = False , include_account_events : bool = True , interval_seconds : float = 0.0 , suppress_errors : bool = False , update_backend : UpdateHistoryBackend | None = None , ) -> None : \"\"\"Initialize the throttled updater. Args: output: SQLite database path. datasets: Datasets to include (defaults to all). timeframes: Rate timeframes to update (defaults to all fixed MT5 timeframes). flags: Tick copy flags as integer or name (e.g. ``ALL``). lookback_hours: First-run lookback when a table has no prior rows. with_views: Create ``cash_events`` and ``positions_reconstructed`` views. include_account_events: Include account-level cash events. interval_seconds: Minimum seconds between successful updates. Values ``<= 0`` update on every call. suppress_errors: When True, recoverable errors (``Mt5TradingError``, ``Mt5RuntimeError``, ``sqlite3.Error``, ``ValueError``, ``OSError``, and MT5 client capability ``AttributeError`` / ``TypeError`` for history API methods) raised during an update are swallowed and :meth:`update` returns False without advancing the throttle. Other ``AttributeError`` / ``TypeError`` values always propagate. When False (default), recoverable errors propagate so callers control logging. update_backend: Callable invoked instead of :func:`update_history` when :meth:`update` runs. Receives the same keyword arguments as :func:`update_history` (``client``, ``output``, ``symbols``, ``datasets``, ``timeframes``, ``flags``, ``lookback_hours``, ``with_views``, ``include_account_events``). Defaults to :func:`update_history`. \"\"\" self . output = output self . datasets = datasets self . timeframes = timeframes self . flags = flags self . lookback_hours = lookback_hours self . with_views = with_views self . include_account_events = include_account_events self . interval_seconds = interval_seconds self . suppress_errors = suppress_errors self . update_backend = ( update_history if update_backend is None else update_backend ) self . _last_update_monotonic : float | None = None","title":"ThrottledHistoryUpdater"},{"location":"api/sdk/#mt5cli.sdk.ThrottledHistoryUpdater.datasets","text":"datasets = datasets","title":"datasets"},{"location":"api/sdk/#mt5cli.sdk.ThrottledHistoryUpdater.flags","text":"flags = flags","title":"flags"},{"location":"api/sdk/#mt5cli.sdk.ThrottledHistoryUpdater.include_account_events","text":"include_account_events = include_account_events","title":"include_account_events"},{"location":"api/sdk/#mt5cli.sdk.ThrottledHistoryUpdater.interval_seconds","text":"interval_seconds = interval_seconds","title":"interval_seconds"},{"location":"api/sdk/#mt5cli.sdk.ThrottledHistoryUpdater.last_update_monotonic","text":"last_update_monotonic : float | None Return the monotonic timestamp of the last successful update.","title":"last_update_monotonic"},{"location":"api/sdk/#mt5cli.sdk.ThrottledHistoryUpdater.lookback_hours","text":"lookback_hours = lookback_hours","title":"lookback_hours"},{"location":"api/sdk/#mt5cli.sdk.ThrottledHistoryUpdater.output","text":"output = output","title":"output"},{"location":"api/sdk/#mt5cli.sdk.ThrottledHistoryUpdater.suppress_errors","text":"suppress_errors = suppress_errors","title":"suppress_errors"},{"location":"api/sdk/#mt5cli.sdk.ThrottledHistoryUpdater.timeframes","text":"timeframes = timeframes","title":"timeframes"},{"location":"api/sdk/#mt5cli.sdk.ThrottledHistoryUpdater.update_backend","text":"update_backend = ( update_history if update_backend is None else update_backend )","title":"update_backend"},{"location":"api/sdk/#mt5cli.sdk.ThrottledHistoryUpdater.with_views","text":"with_views = with_views","title":"with_views"},{"location":"api/sdk/#mt5cli.sdk.ThrottledHistoryUpdater.should_update","text":"should_update () -> bool Return whether enough time has elapsed to run another update. Returns: Type Description bool True when interval_seconds <= 0 , when no update has succeeded bool yet, or when at least interval_seconds have elapsed since the bool last successful update. Source code in mt5cli/sdk.py 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 def should_update ( self ) -> bool : \"\"\"Return whether enough time has elapsed to run another update. Returns: True when ``interval_seconds <= 0``, when no update has succeeded yet, or when at least ``interval_seconds`` have elapsed since the last successful update. \"\"\" if self . interval_seconds <= 0 or self . _last_update_monotonic is None : return True return ( time . monotonic () - self . _last_update_monotonic ) >= self . interval_seconds","title":"should_update"},{"location":"api/sdk/#mt5cli.sdk.ThrottledHistoryUpdater.update","text":"update ( client : Mt5DataClient , symbols : Sequence [ str ] ) -> bool Run a throttled incremental history update. Parameters: Name Type Description Default client Mt5DataClient Connected MT5 data client. required symbols Sequence [ str ] Symbols to update. required Returns: Type Description bool True if an update ran successfully, False if it was throttled or bool (when suppress_errors is True) failed with a recoverable error. bool When suppress_errors is False, recoverable update failures bool propagate to the caller. Raises: Type Description AttributeError MT5 client capability mismatch when suppress_errors is False, or any other attribute error. TypeError MT5 client capability mismatch when suppress_errors is False, or any other type error. Source code in mt5cli/sdk.py 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 def update ( self , client : Mt5DataClient , symbols : Sequence [ str ]) -> bool : \"\"\"Run a throttled incremental history update. Args: client: Connected MT5 data client. symbols: Symbols to update. Returns: True if an update ran successfully, False if it was throttled or (when ``suppress_errors`` is True) failed with a recoverable error. When ``suppress_errors`` is False, recoverable update failures propagate to the caller. Raises: AttributeError: MT5 client capability mismatch when ``suppress_errors`` is False, or any other attribute error. TypeError: MT5 client capability mismatch when ``suppress_errors`` is False, or any other type error. \"\"\" if not self . should_update (): return False try : _resolve_update_history_request ( output = self . output , symbols = symbols , datasets = self . datasets , timeframes = self . timeframes , flags = self . flags , lookback_hours = self . lookback_hours , date_to = None , ) self . update_backend ( client = client , output = self . output , symbols = symbols , datasets = self . datasets , timeframes = self . timeframes , flags = self . flags , lookback_hours = self . lookback_hours , with_views = self . with_views , include_account_events = self . include_account_events , ) except _RECOVERABLE_HISTORY_UPDATE_ERRORS : if self . suppress_errors : logger . warning ( \"Suppressed history update error\" , exc_info = True ) return False raise except ( AttributeError , TypeError ) as exc : if self . suppress_errors and _is_mt5_client_capability_error ( exc ): logger . warning ( \"Suppressed history update error\" , exc_info = True ) return False raise self . _last_update_monotonic = time . monotonic () return True","title":"update"},{"location":"api/sdk/#mt5cli.sdk.account_info","text":"account_info ( * , config : Mt5Config | None = None ) -> DataFrame Return account information. Source code in mt5cli/sdk.py 1956 1957 1958 def account_info ( * , config : Mt5Config | None = None ) -> pd . DataFrame : \"\"\"Return account information.\"\"\" return _make_client ( config = config ) . account_info ()","title":"account_info"},{"location":"api/sdk/#mt5cli.sdk.build_config","text":"build_config ( * , path : str | None = None , login : int | str | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , allow_whole_dollar_env : bool = False , ) -> Mt5Config Build an Mt5Config from optional connection parameters. Parameters: Name Type Description Default path str | None Optional terminal executable path. None login int | str | None Optional trading account login. Integers are preserved. String values are coerced: empty or whitespace-only strings become None ; numeric strings such as \"12345\" are converted to int ; non-numeric strings raise ValueError . When allow_whole_dollar_env=True , $ENV_NAME and ${ENV_NAME} placeholders are expanded before coercion. None password str | None Optional trading account password. None server str | None Optional trading server name. None timeout int | None Optional connection timeout in milliseconds. None allow_whole_dollar_env bool When True , string parameters that are exactly $ENV_NAME are expanded from the environment. Applies to path , login , password , and server . Default False preserves existing behavior. False Returns: Type Description Mt5Config Configured Mt5Config instance. Source code in mt5cli/sdk.py 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 def build_config ( * , path : str | None = None , login : int | str | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , allow_whole_dollar_env : bool = False , ) -> Mt5Config : \"\"\"Build an ``Mt5Config`` from optional connection parameters. Args: path: Optional terminal executable path. login: Optional trading account login. Integers are preserved. String values are coerced: empty or whitespace-only strings become ``None``; numeric strings such as ``\"12345\"`` are converted to ``int``; non-numeric strings raise ``ValueError``. When ``allow_whole_dollar_env=True``, ``$ENV_NAME`` and ``${ENV_NAME}`` placeholders are expanded before coercion. password: Optional trading account password. server: Optional trading server name. timeout: Optional connection timeout in milliseconds. allow_whole_dollar_env: When ``True``, string parameters that are exactly ``$ENV_NAME`` are expanded from the environment. Applies to ``path``, ``login``, ``password``, and ``server``. Default ``False`` preserves existing behavior. Returns: Configured ``Mt5Config`` instance. \"\"\" if allow_whole_dollar_env : if path is not None : path = substitute_env_placeholders ( path , allow_whole_dollar_env = True ) if isinstance ( login , str ): login = substitute_env_placeholders ( login , allow_whole_dollar_env = True ) if password is not None : password = substitute_env_placeholders ( password , allow_whole_dollar_env = True ) if server is not None : server = substitute_env_placeholders ( server , allow_whole_dollar_env = True ) return Mt5Config ( path = path , login = _coerce_login ( login ), password = password , server = server , timeout = timeout , )","title":"build_config"},{"location":"api/sdk/#mt5cli.sdk.collect_history","text":"collect_history ( output : Path , symbols : list [ str ], date_from : datetime | str , date_to : datetime | str , * , datasets : set [ Dataset ] | None = None , timeframe : int | str = 1 , flags : int | str = \"ALL\" , if_exists : IfExists = FAIL , with_views : bool = False , config : Mt5Config | None = None , ) -> None Collect historical datasets into a single SQLite database. Parameters: Name Type Description Default output Path SQLite database path. required symbols list [ str ] Symbols to collect. required date_from datetime | str Start date. required date_to datetime | str End date. required datasets set [ Dataset ] | None Datasets to include (defaults to all). None timeframe int | str Rates timeframe as integer or name (e.g. M1 ). 1 flags int | str Tick copy flags as integer or name (e.g. ALL ). 'ALL' if_exists IfExists Behavior when a target table already exists. FAIL with_views bool Create cash_events and positions_reconstructed views. False config Mt5Config | None MT5 connection configuration. None Source code in mt5cli/sdk.py 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 def collect_history ( output : Path , symbols : list [ str ], date_from : datetime | str , date_to : datetime | str , * , datasets : set [ Dataset ] | None = None , timeframe : int | str = 1 , flags : int | str = \"ALL\" , if_exists : IfExists = IfExists . FAIL , with_views : bool = False , config : Mt5Config | None = None , ) -> None : \"\"\"Collect historical datasets into a single SQLite database. Args: output: SQLite database path. symbols: Symbols to collect. date_from: Start date. date_to: End date. datasets: Datasets to include (defaults to all). timeframe: Rates timeframe as integer or name (e.g. ``M1``). flags: Tick copy flags as integer or name (e.g. ``ALL``). if_exists: Behavior when a target table already exists. with_views: Create ``cash_events`` and ``positions_reconstructed`` views. config: MT5 connection configuration. \"\"\" start = _require_datetime ( date_from ) end = _require_datetime ( date_to ) selected = datasets if datasets is not None else set ( Dataset ) tf = _coerce_timeframe ( timeframe ) tick_flags = _coerce_tick_flags ( flags ) mt5_config = config or build_config () with connected_client ( mt5_config ) as client , sqlite3 . connect ( output ) as conn : conn . execute ( \"PRAGMA journal_mode=WAL\" ) conn . execute ( \"PRAGMA synchronous=NORMAL\" ) written_tables , written_columns = write_collected_datasets ( conn , client , symbols , selected , tf , tick_flags , start , end , if_exists , ) create_history_indexes ( conn , written_columns ) if with_views and Dataset . history_deals in written_tables : create_cash_events_view ( conn , written_columns [ Dataset . history_deals ]) create_positions_reconstructed_view ( conn , written_columns [ Dataset . history_deals ], ) elif with_views : logger . warning ( \"--with-views ignored: history_deals table was not written\" , ) logger . info ( \"Collected %s for %d symbol(s) into %s \" , \", \" . join ( sorted ( ds . value for ds in selected )), len ( symbols ), output , )","title":"collect_history"},{"location":"api/sdk/#mt5cli.sdk.collect_latest_closed_rates_by_granularity","text":"collect_latest_closed_rates_by_granularity ( accounts : Sequence [ AccountSpec ], granularities : Sequence [ int | str ], count : int , * , start_pos : int = 0 , base_config : Mt5Config | None = None , retry_count : int = 0 , backoff_base : float = 2.0 , ) -> dict [ tuple [ str , str ], DataFrame ] Collect latest closed rate bars keyed by symbol and granularity name. Thin wrapper around :func: collect_latest_closed_rates_for_accounts that rekeys the result by granularity name (for example M1 ) instead of the integer timeframe. Parameters: Name Type Description Default accounts Sequence [ AccountSpec ] Account groups to read. Each must define at least one symbol. required granularities Sequence [ int | str ] MT5 timeframes as integers or names (for example M1 ). required count int Number of closed bars to return per symbol/timeframe. required start_pos int Initial bar position offset passed to the underlying collector. 0 base_config Mt5Config | None Optional base configuration whose fields fill any value not set on an individual account. None retry_count int Maximum number of retries after the first attempt. 0 disables retries. 0 backoff_base float Base for exponential backoff between retry attempts. 2.0 Returns: Type Description dict [ tuple [ str , str ], DataFrame ] Mapping keyed by (symbol, granularity_name) . Propagates dict [ tuple [ str , str ], DataFrame ] ValueError from :func: collect_latest_closed_rates_for_accounts . Source code in mt5cli/sdk.py 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 def collect_latest_closed_rates_by_granularity ( accounts : Sequence [ AccountSpec ], granularities : Sequence [ int | str ], count : int , * , start_pos : int = 0 , base_config : Mt5Config | None = None , retry_count : int = 0 , backoff_base : float = 2.0 , ) -> dict [ tuple [ str , str ], pd . DataFrame ]: \"\"\"Collect latest closed rate bars keyed by symbol and granularity name. Thin wrapper around :func:`collect_latest_closed_rates_for_accounts` that rekeys the result by granularity name (for example ``M1``) instead of the integer timeframe. Args: accounts: Account groups to read. Each must define at least one symbol. granularities: MT5 timeframes as integers or names (for example ``M1``). count: Number of closed bars to return per symbol/timeframe. start_pos: Initial bar position offset passed to the underlying collector. base_config: Optional base configuration whose fields fill any value not set on an individual account. retry_count: Maximum number of retries after the first attempt. ``0`` disables retries. backoff_base: Base for exponential backoff between retry attempts. Returns: Mapping keyed by ``(symbol, granularity_name)``. Propagates ``ValueError`` from :func:`collect_latest_closed_rates_for_accounts`. \"\"\" loaded = collect_latest_closed_rates_for_accounts ( accounts , granularities , count , start_pos = start_pos , base_config = base_config , retry_count = retry_count , backoff_base = backoff_base , ) return { ( symbol , resolve_granularity_name ( timeframe )): frame for ( symbol , timeframe ), frame in loaded . items () }","title":"collect_latest_closed_rates_by_granularity"},{"location":"api/sdk/#mt5cli.sdk.collect_latest_closed_rates_for_accounts","text":"collect_latest_closed_rates_for_accounts ( accounts : Sequence [ AccountSpec ], timeframes : Sequence [ int | str ], count : int , * , start_pos : int = 0 , base_config : Mt5Config | None = None , retry_count : int = 0 , backoff_base : float = 2.0 , ) -> dict [ tuple [ str , int ], DataFrame ] Collect latest closed rate bars across multiple MT5 account groups. When start_pos is 0 (the default), MetaTrader 5 includes the still-forming current bar as the last row. This helper fetches count + 1 bars, drops that bar with :func: drop_forming_rate_bar , and validates that each resulting frame is non-empty. When start_pos is greater than zero the forming bar is not in range, so only count bars are fetched and no row is dropped. Wraps :func: collect_latest_rates_for_accounts_with_retries for transient MT5 error handling. Parameters: Name Type Description Default accounts Sequence [ AccountSpec ] Account groups to read. Each must define at least one symbol. required timeframes Sequence [ int | str ] MT5 timeframes as integers or names (for example M1 ). required count int Number of closed bars to return per symbol/timeframe. required start_pos int Initial bar position offset passed to the underlying collector. 0 base_config Mt5Config | None Optional base configuration whose fields fill any value not set on an individual account. None retry_count int Maximum number of retries after the first attempt. 0 disables retries. 0 backoff_base float Base for exponential backoff between retry attempts. 2.0 Returns: Type Description dict [ tuple [ str , int ], DataFrame ] Mapping keyed by (symbol, timeframe_int) . Raises: Type Description ValueError If inputs are invalid, or any series is empty (after dropping the still-forming bar when start_pos is 0 ). Source code in mt5cli/sdk.py 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 def collect_latest_closed_rates_for_accounts ( accounts : Sequence [ AccountSpec ], timeframes : Sequence [ int | str ], count : int , * , start_pos : int = 0 , base_config : Mt5Config | None = None , retry_count : int = 0 , backoff_base : float = 2.0 , ) -> dict [ tuple [ str , int ], pd . DataFrame ]: \"\"\"Collect latest closed rate bars across multiple MT5 account groups. When ``start_pos`` is ``0`` (the default), MetaTrader 5 includes the still-forming current bar as the last row. This helper fetches ``count + 1`` bars, drops that bar with :func:`drop_forming_rate_bar`, and validates that each resulting frame is non-empty. When ``start_pos`` is greater than zero the forming bar is not in range, so only ``count`` bars are fetched and no row is dropped. Wraps :func:`collect_latest_rates_for_accounts_with_retries` for transient MT5 error handling. Args: accounts: Account groups to read. Each must define at least one symbol. timeframes: MT5 timeframes as integers or names (for example ``M1``). count: Number of closed bars to return per symbol/timeframe. start_pos: Initial bar position offset passed to the underlying collector. base_config: Optional base configuration whose fields fill any value not set on an individual account. retry_count: Maximum number of retries after the first attempt. ``0`` disables retries. backoff_base: Base for exponential backoff between retry attempts. Returns: Mapping keyed by ``(symbol, timeframe_int)``. Raises: ValueError: If inputs are invalid, or any series is empty (after dropping the still-forming bar when ``start_pos`` is ``0``). \"\"\" _require_positive ( count , \"count\" ) _require_non_negative ( start_pos , \"start_pos\" ) fetch_count = count + 1 if start_pos == 0 else count loaded = collect_latest_rates_for_accounts_with_retries ( accounts , timeframes , fetch_count , start_pos = start_pos , base_config = base_config , retry_count = retry_count , backoff_base = backoff_base , ) result : dict [ tuple [ str , int ], pd . DataFrame ] = {} for key , df_rate in loaded . items (): closed = drop_forming_rate_bar ( df_rate ) if start_pos == 0 else df_rate if closed . empty : symbol , timeframe = key msg = f \"Rate data is empty for { symbol !r} at timeframe { timeframe } .\" raise ValueError ( msg ) result [ key ] = closed return result","title":"collect_latest_closed_rates_for_accounts"},{"location":"api/sdk/#mt5cli.sdk.collect_latest_rates","text":"collect_latest_rates ( symbols : Sequence [ str ], timeframes : Sequence [ int | str ], * , count : int , start_pos : int = 0 , config : Mt5Config | None = None , ) -> dict [ tuple [ str , int ], DataFrame ] Return latest rates for each symbol/timeframe pair. Source code in mt5cli/sdk.py 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 def collect_latest_rates ( symbols : Sequence [ str ], timeframes : Sequence [ int | str ], * , count : int , start_pos : int = 0 , config : Mt5Config | None = None , ) -> dict [ tuple [ str , int ], pd . DataFrame ]: \"\"\"Return latest rates for each symbol/timeframe pair.\"\"\" return _make_client ( config = config ) . collect_latest_rates ( symbols , timeframes , count = count , start_pos = start_pos , )","title":"collect_latest_rates"},{"location":"api/sdk/#mt5cli.sdk.collect_latest_rates_for_accounts","text":"collect_latest_rates_for_accounts ( accounts : Sequence [ AccountSpec ], timeframes : Sequence [ int | str ], count : int , * , start_pos : int = 0 , base_config : Mt5Config | None = None , ) -> dict [ tuple [ str , int ], DataFrame ] Collect latest rates across multiple MT5 account groups. Each account is connected in turn, its symbols are read for every timeframe, and the resulting frames are merged into a single mapping. Parameters: Name Type Description Default accounts Sequence [ AccountSpec ] Account groups to read. Each must define at least one symbol. required timeframes Sequence [ int | str ] MT5 timeframes as integers or names (for example M1 ). required count int Number of most recent bars to read per symbol/timeframe. required start_pos int Initial bar position offset. 0 base_config Mt5Config | None Optional base configuration whose fields fill any value not set on an individual account. None Returns: Type Description dict [ tuple [ str , int ], DataFrame ] Mapping keyed by (symbol, timeframe_int) . When accounts share a dict [ tuple [ str , int ], DataFrame ] symbol/timeframe pair, the last account processed wins. Raises: Type Description ValueError If accounts , timeframes , or any account's symbols are empty, or count is not positive. Source code in mt5cli/sdk.py 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 def collect_latest_rates_for_accounts ( accounts : Sequence [ AccountSpec ], timeframes : Sequence [ int | str ], count : int , * , start_pos : int = 0 , base_config : Mt5Config | None = None , ) -> dict [ tuple [ str , int ], pd . DataFrame ]: \"\"\"Collect latest rates across multiple MT5 account groups. Each account is connected in turn, its symbols are read for every timeframe, and the resulting frames are merged into a single mapping. Args: accounts: Account groups to read. Each must define at least one symbol. timeframes: MT5 timeframes as integers or names (for example ``M1``). count: Number of most recent bars to read per symbol/timeframe. start_pos: Initial bar position offset. base_config: Optional base configuration whose fields fill any value not set on an individual account. Returns: Mapping keyed by ``(symbol, timeframe_int)``. When accounts share a symbol/timeframe pair, the last account processed wins. Raises: ValueError: If ``accounts``, ``timeframes``, or any account's symbols are empty, or ``count`` is not positive. \"\"\" account_list = list ( accounts ) if not account_list : msg = \"At least one account is required.\" raise ValueError ( msg ) if not timeframes : msg = \"At least one timeframe is required.\" raise ValueError ( msg ) if any ( not account . symbols for account in account_list ): msg = \"Each account requires at least one symbol.\" raise ValueError ( msg ) _require_positive ( count , \"count\" ) result : dict [ tuple [ str , int ], pd . DataFrame ] = {} for account in account_list : config = _build_account_config ( account , base_config ) with Mt5CliClient ( config = config ) as client : result . update ( client . collect_latest_rates ( account . symbols , timeframes , count = count , start_pos = start_pos , ), ) return result","title":"collect_latest_rates_for_accounts"},{"location":"api/sdk/#mt5cli.sdk.collect_latest_rates_for_accounts_with_retries","text":"collect_latest_rates_for_accounts_with_retries ( accounts : Sequence [ AccountSpec ], timeframes : Sequence [ int | str ], count : int , * , start_pos : int = 0 , base_config : Mt5Config | None = None , retry_count : int = 0 , backoff_base : float = 2.0 , ) -> dict [ tuple [ str , int ], DataFrame ] Collect latest rates across accounts, retrying transient MT5 failures. Wraps :func: collect_latest_rates_for_accounts with bounded exponential backoff. Only pdmt5.Mt5TradingError and pdmt5.Mt5RuntimeError are retried; other exceptions propagate immediately. The final failure is re-raised once retries are exhausted. Parameters: Name Type Description Default accounts Sequence [ AccountSpec ] Account groups to read. Each must define at least one symbol. required timeframes Sequence [ int | str ] MT5 timeframes as integers or names (for example M1 ). required count int Number of most recent bars to read per symbol/timeframe. required start_pos int Initial bar position offset. 0 base_config Mt5Config | None Optional base configuration whose fields fill any value not set on an individual account. None retry_count int Maximum number of retries after the first attempt. 0 disables retries. 0 backoff_base float Base for exponential backoff. The delay before retry attempt n (1-indexed) is backoff_base ** n seconds. 2.0 Returns: Type Description dict [ tuple [ str , int ], DataFrame ] Mapping keyed by (symbol, timeframe_int) . Propagates ValueError dict [ tuple [ str , int ], DataFrame ] for invalid inputs (see :func: collect_latest_rates_for_accounts ) and dict [ tuple [ str , int ], DataFrame ] re-raises the last pdmt5.Mt5TradingError or pdmt5.Mt5RuntimeError dict [ tuple [ str , int ], DataFrame ] once retries are exhausted. Source code in mt5cli/sdk.py 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 def collect_latest_rates_for_accounts_with_retries ( accounts : Sequence [ AccountSpec ], timeframes : Sequence [ int | str ], count : int , * , start_pos : int = 0 , base_config : Mt5Config | None = None , retry_count : int = 0 , backoff_base : float = 2.0 , ) -> dict [ tuple [ str , int ], pd . DataFrame ]: \"\"\"Collect latest rates across accounts, retrying transient MT5 failures. Wraps :func:`collect_latest_rates_for_accounts` with bounded exponential backoff. Only ``pdmt5.Mt5TradingError`` and ``pdmt5.Mt5RuntimeError`` are retried; other exceptions propagate immediately. The final failure is re-raised once retries are exhausted. Args: accounts: Account groups to read. Each must define at least one symbol. timeframes: MT5 timeframes as integers or names (for example ``M1``). count: Number of most recent bars to read per symbol/timeframe. start_pos: Initial bar position offset. base_config: Optional base configuration whose fields fill any value not set on an individual account. retry_count: Maximum number of retries after the first attempt. ``0`` disables retries. backoff_base: Base for exponential backoff. The delay before retry attempt ``n`` (1-indexed) is ``backoff_base ** n`` seconds. Returns: Mapping keyed by ``(symbol, timeframe_int)``. Propagates ``ValueError`` for invalid inputs (see :func:`collect_latest_rates_for_accounts`) and re-raises the last ``pdmt5.Mt5TradingError`` or ``pdmt5.Mt5RuntimeError`` once retries are exhausted. \"\"\" def _collect () -> dict [ tuple [ str , int ], pd . DataFrame ]: return collect_latest_rates_for_accounts ( accounts , timeframes , count , start_pos = start_pos , base_config = base_config , ) return retry_with_backoff ( _collect , retry_count = retry_count , backoff_base = backoff_base , operation = \"Rate collection\" , )","title":"collect_latest_rates_for_accounts_with_retries"},{"location":"api/sdk/#mt5cli.sdk.connected_client","text":"connected_client ( config : Mt5Config , ) -> Iterator [ Mt5DataClient ] Initialize MT5, yield a connected client, and always shut down. Parameters: Name Type Description Default config Mt5Config MT5 connection configuration. required Yields: Type Description Mt5DataClient Connected Mt5DataClient instance. Source code in mt5cli/sdk.py 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 @contextmanager def connected_client ( config : Mt5Config ) -> Iterator [ Mt5DataClient ]: \"\"\"Initialize MT5, yield a connected client, and always shut down. Args: config: MT5 connection configuration. Yields: Connected ``Mt5DataClient`` instance. \"\"\" client = Mt5DataClient ( config = config ) try : client . initialize_and_login_mt5 () yield client finally : client . shutdown ()","title":"connected_client"},{"location":"api/sdk/#mt5cli.sdk.copy_rates_from","text":"copy_rates_from ( symbol : str , timeframe : int | str , date_from : datetime | str , count : int , * , config : Mt5Config | None = None , ) -> DataFrame Return rates starting from a date. Source code in mt5cli/sdk.py 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 def copy_rates_from ( symbol : str , timeframe : int | str , date_from : datetime | str , count : int , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return rates starting from a date.\"\"\" return _make_client ( config = config ) . copy_rates_from ( symbol , timeframe , date_from , count , )","title":"copy_rates_from"},{"location":"api/sdk/#mt5cli.sdk.copy_rates_from_pos","text":"copy_rates_from_pos ( symbol : str , timeframe : int | str , start_pos : int , count : int , * , config : Mt5Config | None = None , ) -> DataFrame Return rates starting from a bar position. Source code in mt5cli/sdk.py 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 def copy_rates_from_pos ( symbol : str , timeframe : int | str , start_pos : int , count : int , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return rates starting from a bar position.\"\"\" return _make_client ( config = config ) . copy_rates_from_pos ( symbol , timeframe , start_pos , count , )","title":"copy_rates_from_pos"},{"location":"api/sdk/#mt5cli.sdk.copy_rates_range","text":"copy_rates_range ( symbol : str , timeframe : int | str , date_from : datetime | str , date_to : datetime | str , * , config : Mt5Config | None = None , ) -> DataFrame Return rates for a date range. Source code in mt5cli/sdk.py 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 def copy_rates_range ( symbol : str , timeframe : int | str , date_from : datetime | str , date_to : datetime | str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return rates for a date range.\"\"\" return _make_client ( config = config ) . copy_rates_range ( symbol , timeframe , date_from , date_to , )","title":"copy_rates_range"},{"location":"api/sdk/#mt5cli.sdk.copy_ticks_from","text":"copy_ticks_from ( symbol : str , date_from : datetime | str , count : int , flags : int | str , * , config : Mt5Config | None = None , ) -> DataFrame Return ticks starting from a date. Source code in mt5cli/sdk.py 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 def copy_ticks_from ( symbol : str , date_from : datetime | str , count : int , flags : int | str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return ticks starting from a date.\"\"\" return _make_client ( config = config ) . copy_ticks_from ( symbol , date_from , count , flags , )","title":"copy_ticks_from"},{"location":"api/sdk/#mt5cli.sdk.copy_ticks_range","text":"copy_ticks_range ( symbol : str , date_from : datetime | str , date_to : datetime | str , flags : int | str , * , config : Mt5Config | None = None , ) -> DataFrame Return ticks for a date range. Source code in mt5cli/sdk.py 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 def copy_ticks_range ( symbol : str , date_from : datetime | str , date_to : datetime | str , flags : int | str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return ticks for a date range.\"\"\" return _make_client ( config = config ) . copy_ticks_range ( symbol , date_from , date_to , flags , )","title":"copy_ticks_range"},{"location":"api/sdk/#mt5cli.sdk.fetch_latest_closed_rates","text":"fetch_latest_closed_rates ( client : Mt5CliClient , * , symbol : str , granularity : str , count : int , ) -> DataFrame Fetch up to count most recent closed bars, oldest to newest. Returns: Type Description DataFrame Closed rate bars ordered oldest to newest. Raises: Type Description ValueError If count is not positive or no closed bars are returned. Source code in mt5cli/sdk.py 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 def fetch_latest_closed_rates ( client : Mt5CliClient , * , symbol : str , granularity : str , count : int , ) -> pd . DataFrame : \"\"\"Fetch up to ``count`` most recent closed bars, oldest to newest. Returns: Closed rate bars ordered oldest to newest. Raises: ValueError: If ``count`` is not positive or no closed bars are returned. \"\"\" _require_positive ( count , \"count\" ) frame = client . latest_rates ( symbol , granularity , count + 1 , start_pos = 0 ) closed = drop_forming_rate_bar ( frame ) if closed . empty : msg = ( f \"Rate data is empty for { symbol !r} at granularity { granularity !r} \" f \"with count { count } .\" ) raise ValueError ( msg ) return closed . tail ( count ) . reset_index ( drop = True )","title":"fetch_latest_closed_rates"},{"location":"api/sdk/#mt5cli.sdk.history_deals","text":"history_deals ( date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , * , config : Mt5Config | None = None , ) -> DataFrame Return historical deals. Source code in mt5cli/sdk.py 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 def history_deals ( date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return historical deals.\"\"\" return _make_client ( config = config ) . history_deals ( date_from = date_from , date_to = date_to , group = group , symbol = symbol , ticket = ticket , position = position , )","title":"history_deals"},{"location":"api/sdk/#mt5cli.sdk.history_orders","text":"history_orders ( date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , * , config : Mt5Config | None = None , ) -> DataFrame Return historical orders. Source code in mt5cli/sdk.py 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 def history_orders ( date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return historical orders.\"\"\" return _make_client ( config = config ) . history_orders ( date_from = date_from , date_to = date_to , group = group , symbol = symbol , ticket = ticket , position = position , )","title":"history_orders"},{"location":"api/sdk/#mt5cli.sdk.last_error","text":"last_error ( * , config : Mt5Config | None = None ) -> DataFrame Return the last error information. Source code in mt5cli/sdk.py 2078 2079 2080 def last_error ( * , config : Mt5Config | None = None ) -> pd . DataFrame : \"\"\"Return the last error information.\"\"\" return _make_client ( config = config ) . last_error ()","title":"last_error"},{"location":"api/sdk/#mt5cli.sdk.latest_rates","text":"latest_rates ( symbol : str , timeframe : int | str , count : int , start_pos : int = 0 , * , config : Mt5Config | None = None , ) -> DataFrame Return the latest rates from a bar position. Source code in mt5cli/sdk.py 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 def latest_rates ( symbol : str , timeframe : int | str , count : int , start_pos : int = 0 , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return the latest rates from a bar position.\"\"\" return _make_client ( config = config ) . latest_rates ( symbol , timeframe , count , start_pos = start_pos , )","title":"latest_rates"},{"location":"api/sdk/#mt5cli.sdk.market_book","text":"market_book ( symbol : str , * , config : Mt5Config | None = None ) -> DataFrame Return market depth for a symbol. Source code in mt5cli/sdk.py 2092 2093 2094 2095 2096 2097 2098 def market_book ( symbol : str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return market depth for a symbol.\"\"\" return _make_client ( config = config ) . market_book ( symbol )","title":"market_book"},{"location":"api/sdk/#mt5cli.sdk.minimum_margins","text":"minimum_margins ( symbol : str , * , config : Mt5Config | None = None ) -> DataFrame Return minimum-volume buy and sell margin requirements. See Mt5CliClient.minimum_margins for return details. Source code in mt5cli/sdk.py 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 def minimum_margins ( symbol : str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return minimum-volume buy and sell margin requirements. See ``Mt5CliClient.minimum_margins`` for return details. \"\"\" return _make_client ( config = config ) . minimum_margins ( symbol )","title":"minimum_margins"},{"location":"api/sdk/#mt5cli.sdk.mt5_session","text":"mt5_session ( config : Mt5Config | None = None , ) -> Iterator [ Mt5CliClient ] Open an MT5 terminal session and yield a connected client. Launches the MetaTrader 5 terminal using Mt5Config.path (when set), logs in, yields a connected :class: Mt5CliClient , and always shuts the terminal down on exit. Parameters: Name Type Description Default config Mt5Config | None MT5 connection configuration. Defaults to an empty config that attaches to a running terminal. None Yields: Type Description Mt5CliClient Connected Mt5CliClient bound to the session. Source code in mt5cli/sdk.py 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 @contextmanager def mt5_session ( config : Mt5Config | None = None ) -> Iterator [ Mt5CliClient ]: \"\"\"Open an MT5 terminal session and yield a connected client. Launches the MetaTrader 5 terminal using ``Mt5Config.path`` (when set), logs in, yields a connected :class:`Mt5CliClient`, and always shuts the terminal down on exit. Args: config: MT5 connection configuration. Defaults to an empty config that attaches to a running terminal. Yields: Connected ``Mt5CliClient`` bound to the session. \"\"\" mt5_config = config or build_config () with connected_client ( mt5_config ) as client : yield Mt5CliClient . from_connected_client ( client )","title":"mt5_session"},{"location":"api/sdk/#mt5cli.sdk.mt5_summary","text":"mt5_summary ( * , config : Mt5Config | None = None ) -> dict [ str , object ] Return a compact terminal/account status summary. Source code in mt5cli/sdk.py 2135 2136 2137 def mt5_summary ( * , config : Mt5Config | None = None ) -> dict [ str , object ]: \"\"\"Return a compact terminal/account status summary.\"\"\" return _make_client ( config = config ) . mt5_summary ()","title":"mt5_summary"},{"location":"api/sdk/#mt5cli.sdk.mt5_summary_as_df","text":"mt5_summary_as_df ( * , config : Mt5Config | None = None ) -> DataFrame Return an export-safe terminal/account status summary DataFrame. Source code in mt5cli/sdk.py 2140 2141 2142 def mt5_summary_as_df ( * , config : Mt5Config | None = None ) -> pd . DataFrame : \"\"\"Return an export-safe terminal/account status summary DataFrame.\"\"\" return _make_client ( config = config ) . mt5_summary_as_df ()","title":"mt5_summary_as_df"},{"location":"api/sdk/#mt5cli.sdk.orders","text":"orders ( symbol : str | None = None , group : str | None = None , ticket : int | None = None , * , config : Mt5Config | None = None , ) -> DataFrame Return active orders. Source code in mt5cli/sdk.py 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 def orders ( symbol : str | None = None , group : str | None = None , ticket : int | None = None , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return active orders.\"\"\" return _make_client ( config = config ) . orders ( symbol = symbol , group = group , ticket = ticket , )","title":"orders"},{"location":"api/sdk/#mt5cli.sdk.positions","text":"positions ( symbol : str | None = None , group : str | None = None , ticket : int | None = None , * , config : Mt5Config | None = None , ) -> DataFrame Return open positions. Source code in mt5cli/sdk.py 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 def positions ( symbol : str | None = None , group : str | None = None , ticket : int | None = None , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return open positions.\"\"\" return _make_client ( config = config ) . positions ( symbol = symbol , group = group , ticket = ticket , )","title":"positions"},{"location":"api/sdk/#mt5cli.sdk.recent_history_deals","text":"recent_history_deals ( hours : float , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , * , config : Mt5Config | None = None , ) -> DataFrame Return historical deals from a recent trailing window. Source code in mt5cli/sdk.py 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 def recent_history_deals ( hours : float , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return historical deals from a recent trailing window.\"\"\" return _make_client ( config = config ) . recent_history_deals ( hours , date_to = date_to , group = group , symbol = symbol , )","title":"recent_history_deals"},{"location":"api/sdk/#mt5cli.sdk.recent_ticks","text":"recent_ticks ( symbol : str , seconds : float , * , date_to : datetime | str | None = None , count : int = 10000 , flags : int | str = \"ALL\" , config : Mt5Config | None = None , ) -> DataFrame Return ticks from a recent time window ending at date_to or now. See Mt5CliClient.recent_ticks for parameter and return details. Source code in mt5cli/sdk.py 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 def recent_ticks ( symbol : str , seconds : float , * , date_to : datetime | str | None = None , count : int = 10000 , flags : int | str = \"ALL\" , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return ticks from a recent time window ending at ``date_to`` or now. See ``Mt5CliClient.recent_ticks`` for parameter and return details. \"\"\" return _make_client ( config = config ) . recent_ticks ( symbol , seconds , date_to = date_to , count = count , flags = flags , )","title":"recent_ticks"},{"location":"api/sdk/#mt5cli.sdk.resolve_account_spec","text":"resolve_account_spec ( account : AccountSpec , * , login : int | str | None = None , password : str | None = None , server : str | None = None , path : str | None = None , timeout : int | None = None , allow_whole_dollar_env : bool = False , ) -> AccountSpec Resolve an account's credentials from overrides and ${ENV_VAR} values. Explicit override arguments take precedence over the corresponding :class: AccountSpec fields. The resolved string fields ( login , password , server , path ) have any ${ENV_VAR} placeholders substituted from the environment. Parameters: Name Type Description Default account AccountSpec Source account specification. required login int | str | None Optional explicit login override. None password str | None Optional explicit password override. None server str | None Optional explicit server override. None path str | None Optional explicit terminal path override. None timeout int | None Optional explicit connection timeout override. None allow_whole_dollar_env bool When True , string fields that are exactly $ENV_NAME are also expanded from the environment. Default False preserves existing behavior. False Returns: Type Description AccountSpec A new :class: AccountSpec with resolved credentials and the original AccountSpec symbols preserved. Raises ValueError (via AccountSpec func: substitute_env_placeholders ) if a referenced environment AccountSpec variable is not set. Source code in mt5cli/sdk.py 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 def resolve_account_spec ( account : AccountSpec , * , login : int | str | None = None , password : str | None = None , server : str | None = None , path : str | None = None , timeout : int | None = None , allow_whole_dollar_env : bool = False , ) -> AccountSpec : \"\"\"Resolve an account's credentials from overrides and ``${ENV_VAR}`` values. Explicit override arguments take precedence over the corresponding :class:`AccountSpec` fields. The resolved string fields (``login``, ``password``, ``server``, ``path``) have any ``${ENV_VAR}`` placeholders substituted from the environment. Args: account: Source account specification. login: Optional explicit login override. password: Optional explicit password override. server: Optional explicit server override. path: Optional explicit terminal path override. timeout: Optional explicit connection timeout override. allow_whole_dollar_env: When ``True``, string fields that are exactly ``$ENV_NAME`` are also expanded from the environment. Default ``False`` preserves existing behavior. Returns: A new :class:`AccountSpec` with resolved credentials and the original symbols preserved. Raises ``ValueError`` (via :func:`substitute_env_placeholders`) if a referenced environment variable is not set. \"\"\" return AccountSpec ( symbols = account . symbols , login = _resolve_login ( login , account . login , allow_whole_dollar_env = allow_whole_dollar_env ), password = _resolve_field ( password , account . password , allow_whole_dollar_env = allow_whole_dollar_env ), server = _resolve_field ( server , account . server , allow_whole_dollar_env = allow_whole_dollar_env ), path = _resolve_field ( path , account . path , allow_whole_dollar_env = allow_whole_dollar_env ), timeout = timeout if timeout is not None else account . timeout , )","title":"resolve_account_spec"},{"location":"api/sdk/#mt5cli.sdk.resolve_account_specs","text":"resolve_account_specs ( accounts : Sequence [ AccountSpec ], * , login : int | str | None = None , password : str | None = None , server : str | None = None , path : str | None = None , timeout : int | None = None , allow_whole_dollar_env : bool = False , ) -> list [ AccountSpec ] Resolve credentials for multiple accounts. Applies the same overrides and ${ENV_VAR} substitution as :func: resolve_account_spec to every account. Parameters: Name Type Description Default accounts Sequence [ AccountSpec ] Source account specifications. required login int | str | None Optional explicit login override applied to each account. None password str | None Optional explicit password override applied to each account. None server str | None Optional explicit server override applied to each account. None path str | None Optional explicit terminal path override applied to each account. None timeout int | None Optional explicit timeout override applied to each account. None allow_whole_dollar_env bool When True , string fields that are exactly $ENV_NAME are also expanded from the environment. Default False preserves existing behavior. False Returns: Type Description list [ AccountSpec ] Resolved account specifications in the original order. Raises list [ AccountSpec ] ValueError (via :func: substitute_env_placeholders ) if a referenced list [ AccountSpec ] environment variable is not set. Source code in mt5cli/sdk.py 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 def resolve_account_specs ( accounts : Sequence [ AccountSpec ], * , login : int | str | None = None , password : str | None = None , server : str | None = None , path : str | None = None , timeout : int | None = None , allow_whole_dollar_env : bool = False , ) -> list [ AccountSpec ]: \"\"\"Resolve credentials for multiple accounts. Applies the same overrides and ``${ENV_VAR}`` substitution as :func:`resolve_account_spec` to every account. Args: accounts: Source account specifications. login: Optional explicit login override applied to each account. password: Optional explicit password override applied to each account. server: Optional explicit server override applied to each account. path: Optional explicit terminal path override applied to each account. timeout: Optional explicit timeout override applied to each account. allow_whole_dollar_env: When ``True``, string fields that are exactly ``$ENV_NAME`` are also expanded from the environment. Default ``False`` preserves existing behavior. Returns: Resolved account specifications in the original order. Raises ``ValueError`` (via :func:`substitute_env_placeholders`) if a referenced environment variable is not set. \"\"\" return [ resolve_account_spec ( account , login = login , password = password , server = server , path = path , timeout = timeout , allow_whole_dollar_env = allow_whole_dollar_env , ) for account in accounts ]","title":"resolve_account_specs"},{"location":"api/sdk/#mt5cli.sdk.substitute_env_placeholders","text":"substitute_env_placeholders ( value : str , * , allow_whole_dollar_env : bool = False ) -> str Replace ${ENV_VAR} placeholders in a string with environment values. Parameters: Name Type Description Default value str String that may contain one or more ${ENV_VAR} placeholders. required allow_whole_dollar_env bool When True , a string that is exactly $ENV_NAME (the whole value and nothing else) is also expanded from the environment. Partial occurrences such as \"plan$pass\" or \"$ENV-suffix\" are left unchanged. False Returns: Type Description str The string with every placeholder replaced by its environment value. Raises: Type Description ValueError If a referenced environment variable is not set. Source code in mt5cli/sdk.py 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 def substitute_env_placeholders ( value : str , * , allow_whole_dollar_env : bool = False , ) -> str : \"\"\"Replace ``${ENV_VAR}`` placeholders in a string with environment values. Args: value: String that may contain one or more ``${ENV_VAR}`` placeholders. allow_whole_dollar_env: When ``True``, a string that is exactly ``$ENV_NAME`` (the whole value and nothing else) is also expanded from the environment. Partial occurrences such as ``\"plan$pass\"`` or ``\"$ENV-suffix\"`` are left unchanged. Returns: The string with every placeholder replaced by its environment value. Raises: ValueError: If a referenced environment variable is not set. \"\"\" if allow_whole_dollar_env : m = _WHOLE_DOLLAR_PATTERN . match ( value ) if m : name = m . group ( \"name\" ) if name not in os . environ : msg = f \"Environment variable { name !r} is not set.\" raise ValueError ( msg ) return os . environ [ name ] parts : list [ str ] = [] last_end = 0 for match in _ENV_PLACEHOLDER_PATTERN . finditer ( value ): parts . append ( value [ last_end : match . start ()]) name = match . group ( \"name\" ) if name not in os . environ : msg = f \"Environment variable { name !r} is not set.\" raise ValueError ( msg ) parts . append ( os . environ [ name ]) last_end = match . end () parts . append ( value [ last_end :]) return \"\" . join ( parts )","title":"substitute_env_placeholders"},{"location":"api/sdk/#mt5cli.sdk.substitute_mapping_values","text":"substitute_mapping_values ( data : object , * , keys : Collection [ str ], allow_whole_dollar_env : bool = False , blank_string_keys_as_none : Collection [ str ] = (), ) -> object Recursively substitute environment placeholders for selected mapping keys. Traverses nested dicts and lists, expanding ${ENV_VAR} (and $ENV_NAME when allow_whole_dollar_env=True ) in string values whose immediate parent dict key is in keys . Fields whose key is not in keys are preserved exactly, including literal dollar signs. Strings that are direct elements of a list are never substituted; substitution only applies to strings that are immediate dict values. This is a generic downstream config utility. Key names such as mt5_login or mt5_password must be supplied by the caller; mt5cli does not hard-code any application-specific key names. Callers are responsible for ensuring data has bounded nesting depth; deeply nested or self-referential structures will hit Python's recursion limit. Parameters: Name Type Description Default data object Arbitrarily nested dict/list/scalar value to process. required keys Collection [ str ] Mapping keys whose string values receive placeholder substitution. required allow_whole_dollar_env bool When True , a string that is exactly $ENV_NAME (whole value) is also expanded from the environment in addition to ${ENV_NAME} placeholders. Default False expands ${ENV_NAME} only. False blank_string_keys_as_none Collection [ str ] Mapping keys for which blank strings (after any substitution) are normalised to None . A key may appear in blank_string_keys_as_none without also appearing in keys . () Returns: Type Description object The processed value. Dicts and lists are rebuilt into new object containers with selected string values substituted and object blank-normalised. Scalar inputs (non-dict, non-list) are object returned as-is. Source code in mt5cli/sdk.py 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 def substitute_mapping_values ( data : object , * , keys : Collection [ str ], allow_whole_dollar_env : bool = False , blank_string_keys_as_none : Collection [ str ] = (), ) -> object : \"\"\"Recursively substitute environment placeholders for selected mapping keys. Traverses nested dicts and lists, expanding ``${ENV_VAR}`` (and ``$ENV_NAME`` when ``allow_whole_dollar_env=True``) in string values whose immediate parent dict key is in ``keys``. Fields whose key is not in ``keys`` are preserved exactly, including literal dollar signs. Strings that are direct elements of a list are never substituted; substitution only applies to strings that are immediate dict values. This is a generic downstream config utility. Key names such as ``mt5_login`` or ``mt5_password`` must be supplied by the caller; mt5cli does not hard-code any application-specific key names. Callers are responsible for ensuring ``data`` has bounded nesting depth; deeply nested or self-referential structures will hit Python's recursion limit. Args: data: Arbitrarily nested dict/list/scalar value to process. keys: Mapping keys whose string values receive placeholder substitution. allow_whole_dollar_env: When ``True``, a string that is exactly ``$ENV_NAME`` (whole value) is also expanded from the environment in addition to ``${ENV_NAME}`` placeholders. Default ``False`` expands ``${ENV_NAME}`` only. blank_string_keys_as_none: Mapping keys for which blank strings (after any substitution) are normalised to ``None``. A key may appear in ``blank_string_keys_as_none`` without also appearing in ``keys``. Returns: The processed value. Dicts and lists are rebuilt into new containers with selected string values substituted and blank-normalised. Scalar inputs (non-dict, non-list) are returned as-is. \"\"\" keys_set : frozenset [ str ] = frozenset ( keys ) blank_keys_set : frozenset [ str ] = frozenset ( blank_string_keys_as_none ) def _visit ( node : object , current_key : str | None ) -> object : if isinstance ( node , dict ): typed = cast ( \"dict[object, object]\" , node ) return { k : _visit ( v , k if isinstance ( k , str ) else None ) for k , v in typed . items () } if isinstance ( node , list ): typed_list = cast ( \"list[object]\" , node ) return [ _visit ( item , None ) for item in typed_list ] if not isinstance ( node , str ): return node text = node if current_key in keys_set : text = substitute_env_placeholders ( node , allow_whole_dollar_env = allow_whole_dollar_env ) if current_key in blank_keys_set and not text . strip (): return None return text return _visit ( data , None )","title":"substitute_mapping_values"},{"location":"api/sdk/#mt5cli.sdk.symbol_info","text":"symbol_info ( symbol : str , * , config : Mt5Config | None = None ) -> DataFrame Return details for one symbol. Source code in mt5cli/sdk.py 1975 1976 1977 1978 1979 1980 1981 def symbol_info ( symbol : str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return details for one symbol.\"\"\" return _make_client ( config = config ) . symbol_info ( symbol )","title":"symbol_info"},{"location":"api/sdk/#mt5cli.sdk.symbol_info_tick","text":"symbol_info_tick ( symbol : str , * , config : Mt5Config | None = None ) -> DataFrame Return the last tick for a symbol. Source code in mt5cli/sdk.py 2083 2084 2085 2086 2087 2088 2089 def symbol_info_tick ( symbol : str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return the last tick for a symbol.\"\"\" return _make_client ( config = config ) . symbol_info_tick ( symbol )","title":"symbol_info_tick"},{"location":"api/sdk/#mt5cli.sdk.symbols","text":"symbols ( group : str | None = None , * , config : Mt5Config | None = None , ) -> DataFrame Return the symbol list. Source code in mt5cli/sdk.py 1966 1967 1968 1969 1970 1971 1972 def symbols ( group : str | None = None , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return the symbol list.\"\"\" return _make_client ( config = config ) . symbols ( group = group )","title":"symbols"},{"location":"api/sdk/#mt5cli.sdk.terminal_info","text":"terminal_info ( * , config : Mt5Config | None = None ) -> DataFrame Return terminal information. Source code in mt5cli/sdk.py 1961 1962 1963 def terminal_info ( * , config : Mt5Config | None = None ) -> pd . DataFrame : \"\"\"Return terminal information.\"\"\" return _make_client ( config = config ) . terminal_info ()","title":"terminal_info"},{"location":"api/sdk/#mt5cli.sdk.update_history","text":"update_history ( * , client : Mt5DataClient , output : Path | str , symbols : Sequence [ str ], datasets : set [ Dataset ] | None = None , timeframes : Sequence [ int | str ] | None = None , flags : int | str = \"ALL\" , lookback_hours : float = 24.0 , date_to : datetime | str | None = None , deduplicate : bool = True , create_rate_views : bool = True , with_views : bool = False , include_account_events : bool = True , ) -> None Incrementally append MT5 history into a SQLite database. Uses an already-connected Mt5DataClient and does not create or close the MT5 connection. For first-time tables, data is fetched from date_to - lookback_hours . Subsequent runs resume from existing MAX(time) per symbol (and timeframe for rates); when include_account_events=True , account-level deals use a separate cursor over type NOT IN (0, 1) / empty-symbol rows. Parameters: Name Type Description Default client Mt5DataClient Connected MT5 data client. required output Path | str SQLite database path. required symbols Sequence [ str ] Symbols to update. required datasets set [ Dataset ] | None Datasets to include (defaults to all). None timeframes Sequence [ int | str ] | None Rate timeframes to update (defaults to all fixed MT5 timeframes when None). None flags int | str Tick copy flags as integer or name (e.g. ALL ). 'ALL' lookback_hours float First-run lookback when a table has no prior rows. 24.0 date_to datetime | str | None Optional update end datetime. Defaults to now (UTC). None deduplicate bool Remove duplicate rows after append, keeping latest ROWID. True create_rate_views bool Create rate___ views. True with_views bool Create cash_events and positions_reconstructed views. False include_account_events bool Include account-level cash events in history_deals when True. True Source code in mt5cli/sdk.py 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 def update_history ( # noqa: PLR0913 * , client : Mt5DataClient , output : Path | str , symbols : Sequence [ str ], datasets : set [ Dataset ] | None = None , timeframes : Sequence [ int | str ] | None = None , flags : int | str = \"ALL\" , lookback_hours : float = 24.0 , date_to : datetime | str | None = None , deduplicate : bool = True , create_rate_views : bool = True , with_views : bool = False , include_account_events : bool = True , ) -> None : \"\"\"Incrementally append MT5 history into a SQLite database. Uses an already-connected ``Mt5DataClient`` and does not create or close the MT5 connection. For first-time tables, data is fetched from ``date_to - lookback_hours``. Subsequent runs resume from existing ``MAX(time)`` per symbol (and timeframe for rates); when ``include_account_events=True``, account-level deals use a separate cursor over ``type NOT IN (0, 1)`` / empty-symbol rows. Args: client: Connected MT5 data client. output: SQLite database path. symbols: Symbols to update. datasets: Datasets to include (defaults to all). timeframes: Rate timeframes to update (defaults to all fixed MT5 timeframes when None). flags: Tick copy flags as integer or name (e.g. ``ALL``). lookback_hours: First-run lookback when a table has no prior rows. date_to: Optional update end datetime. Defaults to now (UTC). deduplicate: Remove duplicate rows after append, keeping latest ROWID. create_rate_views: Create ``rate___`` views. with_views: Create ``cash_events`` and ``positions_reconstructed`` views. include_account_events: Include account-level cash events in ``history_deals`` when True. \"\"\" request = _resolve_update_history_request ( output = output , symbols = symbols , datasets = datasets , timeframes = timeframes , flags = flags , lookback_hours = lookback_hours , date_to = date_to , ) if request is None : return logger . info ( \"Updating history in SQLite: symbols= %s , datasets= %s , path= %s \" , list ( symbols ), sorted ( dataset . value for dataset in request . selected ), request . output_path , ) with sqlite3 . connect ( request . output_path ) as conn : conn . execute ( \"PRAGMA journal_mode=WAL\" ) conn . execute ( \"PRAGMA synchronous=NORMAL\" ) write_incremental_datasets ( conn , client , symbols , request . selected , request . resolved_timeframes , request . resolved_tick_flags , request . fallback_start , request . end , deduplicate = deduplicate , create_rate_views = create_rate_views , with_views = with_views , include_account_events = include_account_events , )","title":"update_history"},{"location":"api/sdk/#mt5cli.sdk.update_history_with_config","text":"update_history_with_config ( * , output : Path | str , symbols : Sequence [ str ], config : Mt5Config | None = None , datasets : set [ Dataset ] | None = None , timeframes : Sequence [ int | str ] | None = None , flags : int | str = \"ALL\" , lookback_hours : float = 24.0 , date_to : datetime | str | None = None , deduplicate : bool = True , create_rate_views : bool = True , with_views : bool = False , include_account_events : bool = True , ) -> None Incrementally append MT5 history, opening and closing the MT5 connection. Convenience wrapper around :func: update_history for standalone use. Source code in mt5cli/sdk.py 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 def update_history_with_config ( # noqa: PLR0913 * , output : Path | str , symbols : Sequence [ str ], config : Mt5Config | None = None , datasets : set [ Dataset ] | None = None , timeframes : Sequence [ int | str ] | None = None , flags : int | str = \"ALL\" , lookback_hours : float = 24.0 , date_to : datetime | str | None = None , deduplicate : bool = True , create_rate_views : bool = True , with_views : bool = False , include_account_events : bool = True , ) -> None : \"\"\"Incrementally append MT5 history, opening and closing the MT5 connection. Convenience wrapper around :func:`update_history` for standalone use. \"\"\" request = _resolve_update_history_request ( output = output , symbols = symbols , datasets = datasets , timeframes = timeframes , flags = flags , lookback_hours = lookback_hours , date_to = date_to , ) if request is None : return mt5_config = config or build_config () with connected_client ( mt5_config ) as client : update_history ( client = client , output = output , symbols = symbols , datasets = datasets , timeframes = timeframes , flags = flags , lookback_hours = lookback_hours , date_to = date_to , deduplicate = deduplicate , create_rate_views = create_rate_views , with_views = with_views , include_account_events = include_account_events , )","title":"update_history_with_config"},{"location":"api/sdk/#mt5cli.sdk.version","text":"version ( * , config : Mt5Config | None = None ) -> DataFrame Return MetaTrader5 version information. Source code in mt5cli/sdk.py 2073 2074 2075 def version ( * , config : Mt5Config | None = None ) -> pd . DataFrame : \"\"\"Return MetaTrader5 version information.\"\"\" return _make_client ( config = config ) . version ()","title":"version"},{"location":"api/sdk/#resilient-multi-account-orchestration","text":"The SDK ships strategy-agnostic helpers for building long-running collectors on top of the read-only client. None of them depend on a particular trading application.","title":"Resilient multi-account orchestration"},{"location":"api/sdk/#retrying-transient-rate-collection","text":"collect_latest_rates_for_accounts_with_retries() wraps collect_latest_rates_for_accounts() with bounded exponential backoff. Only pdmt5.Mt5TradingError and pdmt5.Mt5RuntimeError are retried; the final failure is re-raised once retry_count is exhausted. from mt5cli import AccountSpec , collect_latest_rates_for_accounts_with_retries accounts = [ AccountSpec ( symbols = [ \"EURUSD\" ], login = 12345 )] rates = collect_latest_rates_for_accounts_with_retries ( accounts , [ \"M1\" , \"H1\" ], count = 500 , retry_count = 3 , backoff_base = 2 , # sleeps 2s, 4s, 8s between attempts )","title":"Retrying transient rate collection"},{"location":"api/sdk/#latest-closed-rate-bars","text":"MetaTrader 5 start_pos=0 includes the still-forming current bar as the last row. fetch_latest_closed_rates() handles one connected MT5Client ; use fetch_latest_closed_rates_for_trading_client() from an active Mt5TradingClient session. Multi-account helpers fetch count + 1 bars, drop that row with drop_forming_rate_bar() , and validate each series is non-empty. Returned frames are ordered oldest-to-newest and may contain fewer than count rows only when MT5 returns fewer closed bars. from mt5cli import ( AccountSpec , collect_latest_closed_rates_by_granularity , fetch_latest_closed_rates , ) closed = fetch_latest_closed_rates ( client , symbol = \"EURUSD\" , granularity = \"M1\" , count = 500 , ) rates = collect_latest_closed_rates_by_granularity ( [ AccountSpec ( symbols = [ \"EURUSD\" ], login = 12345 )], [ \"M1\" , \"H1\" ], count = 500 , retry_count = 3 , ) closed_m1 = rates [ \"EURUSD\" , \"M1\" ] Use collect_latest_closed_rates_by_granularity() when callers prefer keys such as (\"EURUSD\", \"M1\") instead of integer timeframes.","title":"Latest closed rate bars"},{"location":"api/sdk/#resolving-credentials-and-env_var-placeholders","text":"resolve_account_spec() / resolve_account_specs() merge explicit override values over AccountSpec fields and expand ${ENV_VAR} placeholders, keeping secrets out of plan/config files. A missing environment variable raises ValueError . import os from mt5cli import AccountSpec , resolve_account_specs os . environ [ \"MT5_LOGIN\" ] = \"12345\" os . environ [ \"MT5_PASSWORD\" ] = \"secret\" accounts = [ AccountSpec ( symbols = [ \"EURUSD\" ], login = \"$ {MT5_LOGIN} \" , password = \"$ {MT5_PASSWORD} \" ) ] resolved = resolve_account_specs ( accounts , server = \"Broker-Demo\" ) # resolved[0].login == \"12345\", resolved[0].server == \"Broker-Demo\" Pass allow_whole_dollar_env=True to also expand strings whose entire value is a bare $ENV_NAME identifier (no braces). This opt-in covers substitute_env_placeholders() , resolve_account_spec() , resolve_account_specs() , and build_config() . Note: build_config cannot expand login because that parameter is int | None ; use resolve_account_spec for a string login placeholder. Partial strings such as \"plan$pass\" , \"abc$ENV\" , or \"$ENV-suffix\" are never expanded \u2014 only an exact $IDENTIFIER whole-string match qualifies. The default is False to preserve backward compatibility. import os from mt5cli import AccountSpec , resolve_account_specs os . environ [ \"MT5_PASSWORD\" ] = \"secret\" accounts = [ AccountSpec ( symbols = [ \"EURUSD\" ], password = \"$MT5_PASSWORD\" )] resolved = resolve_account_specs ( accounts , allow_whole_dollar_env = True ) # resolved[0].password == \"secret\"","title":"Resolving credentials and ${ENV_VAR} placeholders"},{"location":"api/sdk/#throttled-incremental-history-updates","text":"ThrottledHistoryUpdater wraps update_history() with a minimum interval between successful runs (using a monotonic clock), so an application loop can call it every iteration without over-fetching. from pdmt5 import Mt5Config , Mt5DataClient from mt5cli import Dataset , ThrottledHistoryUpdater updater = ThrottledHistoryUpdater ( output = \"history.db\" , datasets = { Dataset . rates }, timeframes = [ \"M1\" ], interval_seconds = 60 , # <= 0 updates on every call ) client = Mt5DataClient ( config = Mt5Config ( login = 12345 )) client . initialize_and_login_mt5 () try : while True : updater . update ( client , [ \"EURUSD\" , \"GBPUSD\" ]) # no-op until 60s elapse # ... do other work; break when shutting down ... finally : client . shutdown () Pass update_backend to substitute the default update_history implementation without monkey-patching mt5cli.sdk.update_history . The callable receives the same keyword arguments as update_history ( client , output , symbols , datasets , timeframes , flags , lookback_hours , with_views , include_account_events ). The resolved backend is stored on updater.update_backend for inspection or subclassing. from mt5cli import ThrottledHistoryUpdater , update_history def app_update_history ( ** kwargs ) -> None : update_history ( ** kwargs ) # or delegate to application-specific logic updater = ThrottledHistoryUpdater ( output = \"history.db\" , interval_seconds = 60 , update_backend = app_update_history , ) 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.","title":"Throttled incremental history updates"},{"location":"api/sdk/#trading-capable-sessions","text":"For order placement and trading calculations, use the dedicated Trading module . Use mt5_session() / MT5Client for read-only collection.","title":"Trading-capable sessions"},{"location":"api/storage/","text":"Storage \u00b6 mt5cli.storage \u00b6 Generic storage helpers for MT5 market and account history. __all__ module-attribute \u00b6 __all__ = [ \"Dataset\" , \"IfExists\" , \"OutputFormat\" , \"RateTarget\" , \"build_rate_targets\" , \"build_rate_view_name\" , \"collect_history\" , \"detect_format\" , \"drop_forming_rate_bar\" , \"export_dataframe\" , \"export_dataframe_to_sqlite\" , \"load_rate_data\" , \"load_rate_data_from_connection\" , \"load_rate_series_by_granularity\" , \"load_rate_series_from_sqlite\" , \"resolve_rate_tables\" , \"resolve_rate_view_name\" , \"resolve_rate_view_names\" , \"update_history\" , \"update_history_with_config\" , ] Dataset \u00b6 Bases: StrEnum Datasets supported by the collect-history command. history_deals class-attribute instance-attribute \u00b6 history_deals = 'history-deals' history_orders class-attribute instance-attribute \u00b6 history_orders = 'history-orders' rates class-attribute instance-attribute \u00b6 rates = 'rates' table_name property \u00b6 table_name : str Return the SQLite table name for this dataset. ticks class-attribute instance-attribute \u00b6 ticks = 'ticks' IfExists \u00b6 Bases: StrEnum SQLite table conflict behavior for the collect-history command. APPEND class-attribute instance-attribute \u00b6 APPEND = 'append' FAIL class-attribute instance-attribute \u00b6 FAIL = 'fail' REPLACE class-attribute instance-attribute \u00b6 REPLACE = 'replace' OutputFormat \u00b6 Bases: StrEnum Supported output file formats. csv class-attribute instance-attribute \u00b6 csv = 'csv' json class-attribute instance-attribute \u00b6 json = 'json' parquet class-attribute instance-attribute \u00b6 parquet = 'parquet' sqlite3 class-attribute instance-attribute \u00b6 sqlite3 = 'sqlite3' RateTarget dataclass \u00b6 RateTarget ( symbol : str | None , timeframe : int | str ) A single rate series identified by symbol and timeframe. Attributes: Name Type Description symbol str | None MT5 symbol name, or None when the rate series is addressed only by an explicit table (for example a custom SQLite view). timeframe int | str MT5 timeframe as an integer or name (for example M1 ). symbol instance-attribute \u00b6 symbol : str | None timeframe instance-attribute \u00b6 timeframe : int | str timeframe_int property \u00b6 timeframe_int : int Return the timeframe as its integer MT5 value. __post_init__ \u00b6 __post_init__ () -> None Normalize accepted timeframe aliases to the stored integer value. Source code in mt5cli/history.py 544 545 546 547 def __post_init__ ( self ) -> None : \"\"\"Normalize accepted timeframe aliases to the stored integer value.\"\"\" if not isinstance ( self . timeframe , int ): object . __setattr__ ( self , \"timeframe\" , parse_timeframe ( self . timeframe )) build_rate_targets \u00b6 build_rate_targets ( symbols : Sequence [ str ], timeframes : Sequence [ int | str ], * , allow_missing_symbol : bool = False , ) -> list [ RateTarget ] Build rate targets for every symbol and timeframe combination. Parameters: Name Type Description Default symbols Sequence [ str ] MT5 symbol names. May be empty when allow_missing_symbol . required timeframes Sequence [ int | str ] MT5 timeframes as integers or names (for example M1 ). required allow_missing_symbol bool When True and symbols is empty, build targets with symbol=None for each timeframe instead of raising. False Returns: Type Description list [ RateTarget ] Targets in row-major order: every timeframe for the first symbol, then list [ RateTarget ] every timeframe for the next symbol, and so on. Raises: Type Description ValueError If timeframes is empty, or symbols is empty and allow_missing_symbol is False. Source code in mt5cli/history.py 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 def build_rate_targets ( symbols : Sequence [ str ], timeframes : Sequence [ int | str ], * , allow_missing_symbol : bool = False , ) -> list [ RateTarget ]: \"\"\"Build rate targets for every symbol and timeframe combination. Args: symbols: MT5 symbol names. May be empty when ``allow_missing_symbol``. timeframes: MT5 timeframes as integers or names (for example ``M1``). allow_missing_symbol: When True and ``symbols`` is empty, build targets with ``symbol=None`` for each timeframe instead of raising. Returns: Targets in row-major order: every timeframe for the first symbol, then every timeframe for the next symbol, and so on. Raises: ValueError: If ``timeframes`` is empty, or ``symbols`` is empty and ``allow_missing_symbol`` is False. \"\"\" if not timeframes : msg = \"At least one timeframe is required.\" raise ValueError ( msg ) if not symbols : if not allow_missing_symbol : msg = \"At least one symbol is required.\" raise ValueError ( msg ) return [ RateTarget ( symbol = None , timeframe = tf ) for tf in timeframes ] return [ RateTarget ( symbol = symbol , timeframe = tf ) for symbol in symbols for tf in timeframes ] build_rate_view_name \u00b6 build_rate_view_name ( * , symbol : str , granularity : str , granularity_count : int , timeframe : int , ) -> str Return a collision-free offline optimize view name. View names always include the timeframe integer after a __ separator so a symbol such as EURUSD_M1 cannot collide with EURUSD at timeframe M1 . Source code in mt5cli/history.py 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 def build_rate_view_name ( * , symbol : str , granularity : str , granularity_count : int , timeframe : int , ) -> str : \"\"\"Return a collision-free offline optimize view name. View names always include the timeframe integer after a ``__`` separator so a symbol such as ``EURUSD_M1`` cannot collide with ``EURUSD`` at timeframe ``M1``. \"\"\" if granularity_count == 1 : return f \"rate_ { symbol } __ { timeframe } \" return f \"rate_ { symbol } __ { granularity } _ { timeframe } \" collect_history \u00b6 collect_history ( output : Path , symbols : list [ str ], date_from : datetime | str , date_to : datetime | str , * , datasets : set [ Dataset ] | None = None , timeframe : int | str = 1 , flags : int | str = \"ALL\" , if_exists : IfExists = FAIL , with_views : bool = False , config : Mt5Config | None = None , ) -> None Collect historical datasets into a single SQLite database. Parameters: Name Type Description Default output Path SQLite database path. required symbols list [ str ] Symbols to collect. required date_from datetime | str Start date. required date_to datetime | str End date. required datasets set [ Dataset ] | None Datasets to include (defaults to all). None timeframe int | str Rates timeframe as integer or name (e.g. M1 ). 1 flags int | str Tick copy flags as integer or name (e.g. ALL ). 'ALL' if_exists IfExists Behavior when a target table already exists. FAIL with_views bool Create cash_events and positions_reconstructed views. False config Mt5Config | None MT5 connection configuration. None Source code in mt5cli/sdk.py 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 def collect_history ( output : Path , symbols : list [ str ], date_from : datetime | str , date_to : datetime | str , * , datasets : set [ Dataset ] | None = None , timeframe : int | str = 1 , flags : int | str = \"ALL\" , if_exists : IfExists = IfExists . FAIL , with_views : bool = False , config : Mt5Config | None = None , ) -> None : \"\"\"Collect historical datasets into a single SQLite database. Args: output: SQLite database path. symbols: Symbols to collect. date_from: Start date. date_to: End date. datasets: Datasets to include (defaults to all). timeframe: Rates timeframe as integer or name (e.g. ``M1``). flags: Tick copy flags as integer or name (e.g. ``ALL``). if_exists: Behavior when a target table already exists. with_views: Create ``cash_events`` and ``positions_reconstructed`` views. config: MT5 connection configuration. \"\"\" start = _require_datetime ( date_from ) end = _require_datetime ( date_to ) selected = datasets if datasets is not None else set ( Dataset ) tf = _coerce_timeframe ( timeframe ) tick_flags = _coerce_tick_flags ( flags ) mt5_config = config or build_config () with connected_client ( mt5_config ) as client , sqlite3 . connect ( output ) as conn : conn . execute ( \"PRAGMA journal_mode=WAL\" ) conn . execute ( \"PRAGMA synchronous=NORMAL\" ) written_tables , written_columns = write_collected_datasets ( conn , client , symbols , selected , tf , tick_flags , start , end , if_exists , ) create_history_indexes ( conn , written_columns ) if with_views and Dataset . history_deals in written_tables : create_cash_events_view ( conn , written_columns [ Dataset . history_deals ]) create_positions_reconstructed_view ( conn , written_columns [ Dataset . history_deals ], ) elif with_views : logger . warning ( \"--with-views ignored: history_deals table was not written\" , ) logger . info ( \"Collected %s for %d symbol(s) into %s \" , \", \" . join ( sorted ( ds . value for ds in selected )), len ( symbols ), output , ) detect_format \u00b6 detect_format ( output_path : Path , explicit_format : str | None = None ) -> str Detect the output format from a file extension or explicit format string. Parameters: Name Type Description Default output_path Path Path to the output file. required explicit_format str | None Explicitly specified format, if any. None Returns: Type Description str The detected format string. Raises: Type Description ValueError If the format cannot be determined. Source code in mt5cli/utils.py 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 def detect_format ( output_path : Path , explicit_format : str | None = None , ) -> str : \"\"\"Detect the output format from a file extension or explicit format string. Args: output_path: Path to the output file. explicit_format: Explicitly specified format, if any. Returns: The detected format string. Raises: ValueError: If the format cannot be determined. \"\"\" if explicit_format is not None : return explicit_format suffix = output_path . suffix . lower () if suffix in _FORMAT_EXTENSIONS : return _FORMAT_EXTENSIONS [ suffix ] msg = ( f \"Cannot detect format from extension ' { suffix } '.\" \" Use --format to specify the output format.\" ) raise ValueError ( msg ) drop_forming_rate_bar \u00b6 drop_forming_rate_bar ( df_rate : DataFrame ) -> DataFrame Return closed bars from chronologically ordered MT5 rate data. MetaTrader 5 copy_rates_from_pos(start_pos=0) includes the still-forming current bar as the last row. Slice it off so downstream logic only sees completed bars. Empty frames and single-row frames return empty results. Parameters: Name Type Description Default df_rate DataFrame Rate data ordered oldest-to-newest with the forming bar last. required Returns: Type Description DataFrame A new DataFrame with all rows except the last. Index and columns are DataFrame preserved. The input frame is not modified. Source code in mt5cli/history.py 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 def drop_forming_rate_bar ( df_rate : pd . DataFrame ) -> pd . DataFrame : \"\"\"Return closed bars from chronologically ordered MT5 rate data. MetaTrader 5 ``copy_rates_from_pos(start_pos=0)`` includes the still-forming current bar as the last row. Slice it off so downstream logic only sees completed bars. Empty frames and single-row frames return empty results. Args: df_rate: Rate data ordered oldest-to-newest with the forming bar last. Returns: A new DataFrame with all rows except the last. Index and columns are preserved. The input frame is not modified. \"\"\" return df_rate . iloc [: - 1 ] . copy () export_dataframe \u00b6 export_dataframe ( df : DataFrame , output_path : Path , output_format : str , table_name : str = \"data\" , ) -> None Export a pandas DataFrame to the specified file format. Parameters: Name Type Description Default df DataFrame DataFrame to export. required output_path Path Path to the output file. required output_format str Output format (csv, json, parquet, or sqlite3). required table_name str Table name for SQLite3 output. 'data' Raises: Type Description ValueError If the output format is not supported. Source code in mt5cli/utils.py 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 def export_dataframe ( df : pd . DataFrame , output_path : Path , output_format : str , table_name : str = \"data\" , ) -> None : \"\"\"Export a pandas DataFrame to the specified file format. Args: df: DataFrame to export. output_path: Path to the output file. output_format: Output format (csv, json, parquet, or sqlite3). table_name: Table name for SQLite3 output. Raises: ValueError: If the output format is not supported. \"\"\" if output_format == \"csv\" : df . to_csv ( output_path , index = False ) elif output_format == \"json\" : df . to_json ( output_path , orient = \"records\" , date_format = \"iso\" , indent = 2 , ) elif output_format == \"parquet\" : df . to_parquet ( output_path , index = False ) elif output_format == \"sqlite3\" : export_dataframe_to_sqlite ( df , output_path , table_name , if_exists = IfExists . REPLACE , index = False , ) else : msg = f \"Unsupported output format: { output_format } \" raise ValueError ( msg ) export_dataframe_to_sqlite \u00b6 export_dataframe_to_sqlite ( df : DataFrame , output_path : Path , table_name : str = \"data\" , * , if_exists : IfExists = APPEND , index : bool = False , index_label : str | None = None , deduplicate_on : Sequence [ str ] | None = None , ) -> None Write a DataFrame to SQLite with configurable append and deduplication. Parameters: Name Type Description Default df DataFrame DataFrame to export. required output_path Path SQLite database path. required table_name str Target table name. 'data' if_exists IfExists Conflict behavior when the table already exists. APPEND index bool Whether to write the DataFrame index as a column. False index_label str | None Column name for the index when index=True . None deduplicate_on Sequence [ str ] | None Optional key columns to deduplicate after writing, keeping the latest ROWID per key group. Deduplication scans the full table, so repeated appends cost O(table size); index the key columns when appending frequently. None Source code in mt5cli/utils.py 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 def export_dataframe_to_sqlite ( df : pd . DataFrame , output_path : Path , table_name : str = \"data\" , * , if_exists : IfExists = IfExists . APPEND , index : bool = False , index_label : str | None = None , deduplicate_on : Sequence [ str ] | None = None , ) -> None : \"\"\"Write a DataFrame to SQLite with configurable append and deduplication. Args: df: DataFrame to export. output_path: SQLite database path. table_name: Target table name. if_exists: Conflict behavior when the table already exists. index: Whether to write the DataFrame index as a column. index_label: Column name for the index when ``index=True``. deduplicate_on: Optional key columns to deduplicate after writing, keeping the latest ``ROWID`` per key group. Deduplication scans the full table, so repeated appends cost O(table size); index the key columns when appending frequently. \"\"\" with sqlite3 . connect ( output_path ) as conn : df . to_sql ( # type: ignore[reportUnknownMemberType] table_name , conn , if_exists = if_exists . value , index = index , index_label = index_label , ) if deduplicate_on : from .history import drop_duplicates_in_table # noqa: PLC0415 drop_duplicates_in_table ( conn . cursor (), table_name , list ( deduplicate_on ), keep = \"last\" , ) conn . commit () load_rate_data \u00b6 load_rate_data ( conn_or_path : SqliteConnOrPath , table : str , count : int | None = None , ) -> DataFrame Load rate-like data from a SQLite database path or connection. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath SQLite database path or open connection. required table str Source table or view name. required count int | None Optional number of most recent rows to load. None Returns: Type Description DataFrame DataFrame indexed by ascending time . Source code in mt5cli/history.py 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 def load_rate_data ( conn_or_path : SqliteConnOrPath , table : str , count : int | None = None , ) -> pd . DataFrame : \"\"\"Load rate-like data from a SQLite database path or connection. Args: conn_or_path: SQLite database path or open connection. table: Source table or view name. count: Optional number of most recent rows to load. Returns: DataFrame indexed by ascending ``time``. \"\"\" conn , should_close = _open_existing_sqlite_database ( conn_or_path ) try : return load_rate_data_from_connection ( conn , table , count = count ) finally : if should_close : conn . close () load_rate_data_from_connection \u00b6 load_rate_data_from_connection ( connection : Connection , table : str , count : int | None = None , ) -> DataFrame Load rate-like data from a SQLite table or view. Parameters: Name Type Description Default connection Connection Open SQLite connection. required table str Source table or view name. required count int | None Optional number of most recent rows to load. None Returns: Type Description DataFrame DataFrame indexed by ascending time . Raises: Type Description ValueError If inputs, schema, timestamps are invalid, or the table or view contains no rows. Source code in mt5cli/history.py 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 def load_rate_data_from_connection ( connection : sqlite3 . Connection , table : str , count : int | None = None , ) -> pd . DataFrame : \"\"\"Load rate-like data from a SQLite table or view. Args: connection: Open SQLite connection. table: Source table or view name. count: Optional number of most recent rows to load. Returns: DataFrame indexed by ascending ``time``. Raises: ValueError: If inputs, schema, timestamps are invalid, or the table or view contains no rows. \"\"\" table_name = _validate_rate_load_request ( table , count ) columns = get_table_columns ( connection , table_name ) _ensure_rate_columns ( columns , table_name ) quoted_table = quote_sqlite_identifier ( table_name ) if count is None : frame = cast ( \"pd.DataFrame\" , pd . read_sql_query ( # type: ignore[reportUnknownMemberType] f \"SELECT * FROM { quoted_table } ORDER BY time ASC\" , # noqa: S608 connection , ), ) else : frame = cast ( \"pd.DataFrame\" , pd . read_sql_query ( # type: ignore[reportUnknownMemberType] f \"SELECT * FROM { quoted_table } ORDER BY time DESC LIMIT ?\" , # noqa: S608 connection , params = ( count ,), ), ) if frame . empty : msg = f \"SQLite table or view { table_name !r} contains no rows.\" raise ValueError ( msg ) return _parse_rate_time_index ( frame , table_name ) load_rate_series_by_granularity \u00b6 load_rate_series_by_granularity ( conn_or_path : SqliteConnOrPath , symbols : Sequence [ str ], granularities : Sequence [ int | str ], count : int , * , explicit_tables : Sequence [ str ] | None = None , allow_missing_symbol : bool = False , ) -> dict [ tuple [ str | None , str ], DataFrame ] Load rate series keyed by symbol and string granularity name. Builds targets with :func: build_rate_targets and loads them with :func: load_rate_series_from_sqlite , then rekeys the result by granularity name (for example M1 ) instead of the integer timeframe to reduce downstream boilerplate. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath SQLite database path or open connection. required symbols Sequence [ str ] MT5 symbol names. May be empty when allow_missing_symbol . required granularities Sequence [ int | str ] MT5 timeframes as integers or names (for example M1 ). required count int Number of most recent rows to load per series. required explicit_tables Sequence [ str ] | None Optional explicit table or view names matching the built targets in row-major order. Required when symbols are omitted. None allow_missing_symbol bool When True and symbols is empty, build targets with symbol=None for each granularity instead of raising. False Returns: Type Description dict [ tuple [ str | None, str ], DataFrame ] Mapping keyed by (symbol | None, granularity_name) to each rate dict [ tuple [ str | None, str ], DataFrame ] DataFrame. Propagates ValueError (via :func: build_rate_targets and dict [ tuple [ str | None, str ], DataFrame ] func: load_rate_series_from_sqlite ) when inputs are empty or invalid, dict [ tuple [ str | None, str ], DataFrame ] table resolution fails, or duplicate targets are present. Source code in mt5cli/history.py 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 def load_rate_series_by_granularity ( conn_or_path : SqliteConnOrPath , symbols : Sequence [ str ], granularities : Sequence [ int | str ], count : int , * , explicit_tables : Sequence [ str ] | None = None , allow_missing_symbol : bool = False , ) -> dict [ tuple [ str | None , str ], pd . DataFrame ]: \"\"\"Load rate series keyed by symbol and string granularity name. Builds targets with :func:`build_rate_targets` and loads them with :func:`load_rate_series_from_sqlite`, then rekeys the result by granularity name (for example ``M1``) instead of the integer timeframe to reduce downstream boilerplate. Args: conn_or_path: SQLite database path or open connection. symbols: MT5 symbol names. May be empty when ``allow_missing_symbol``. granularities: MT5 timeframes as integers or names (for example ``M1``). count: Number of most recent rows to load per series. explicit_tables: Optional explicit table or view names matching the built targets in row-major order. Required when symbols are omitted. allow_missing_symbol: When True and ``symbols`` is empty, build targets with ``symbol=None`` for each granularity instead of raising. Returns: Mapping keyed by ``(symbol | None, granularity_name)`` to each rate DataFrame. Propagates ``ValueError`` (via :func:`build_rate_targets` and :func:`load_rate_series_from_sqlite`) when inputs are empty or invalid, table resolution fails, or duplicate targets are present. \"\"\" targets = build_rate_targets ( symbols , granularities , allow_missing_symbol = allow_missing_symbol , ) series = load_rate_series_from_sqlite ( conn_or_path , targets , count , explicit_tables = explicit_tables , ) return { ( symbol , resolve_granularity_name ( timeframe )): frame for ( symbol , timeframe ), frame in series . items () } load_rate_series_from_sqlite \u00b6 load_rate_series_from_sqlite ( conn_or_path : SqliteConnOrPath , targets : None = None , count : int | None = None , explicit_tables : None = None , * , table : str , ) -> DataFrame load_rate_series_from_sqlite ( conn_or_path : SqliteConnOrPath , targets : None = None , count : int | None = None , explicit_tables : Sequence [ str ] | None = None , * , table : None = None , ) -> dict [ tuple [ str | None , int ], DataFrame ] load_rate_series_from_sqlite ( conn_or_path : SqliteConnOrPath , targets : Sequence [ RateTarget ], count : int , explicit_tables : Sequence [ str ] | None = None , * , table : None = None , ) -> dict [ tuple [ str | None , int ], DataFrame ] load_rate_series_from_sqlite ( conn_or_path : SqliteConnOrPath , targets : Sequence [ RateTarget ] | None = None , count : int | None = None , explicit_tables : Sequence [ str ] | None = None , * , table : str | None = None , ) -> dict [ tuple [ str | None , int ], DataFrame ] | DataFrame Load one table/view or multiple rate series from a SQLite database. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath SQLite database path or open connection. required targets Sequence [ RateTarget ] | None Rate targets to load. Each (symbol, timeframe_int) pair must be unique. Omit when loading a single explicit table . None count int | None Optional number of most recent rows to load per series. None explicit_tables Sequence [ str ] | None Optional explicit table or view names matching targets. When omitted, managed rate_* compatibility views must already exist in the database. None table str | None Optional single table or view name to load directly. None Returns: Type Description dict [ tuple [ str | None, int ], DataFrame ] | DataFrame A DataFrame when table is provided, otherwise a mapping keyed by dict [ tuple [ str | None, int ], DataFrame ] | DataFrame (symbol, timeframe_int) to each rate DataFrame. Raises: Type Description ValueError If count is not positive, targets are empty, duplicate (symbol, timeframe_int) pairs are present, or table resolution fails. Source code in mt5cli/history.py 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 def load_rate_series_from_sqlite ( conn_or_path : SqliteConnOrPath , targets : Sequence [ RateTarget ] | None = None , count : int | None = None , explicit_tables : Sequence [ str ] | None = None , * , table : str | None = None , ) -> dict [ tuple [ str | None , int ], pd . DataFrame ] | pd . DataFrame : \"\"\"Load one table/view or multiple rate series from a SQLite database. Args: conn_or_path: SQLite database path or open connection. targets: Rate targets to load. Each ``(symbol, timeframe_int)`` pair must be unique. Omit when loading a single explicit ``table``. count: Optional number of most recent rows to load per series. explicit_tables: Optional explicit table or view names matching targets. When omitted, managed ``rate_*`` compatibility views must already exist in the database. table: Optional single table or view name to load directly. Returns: A DataFrame when ``table`` is provided, otherwise a mapping keyed by ``(symbol, timeframe_int)`` to each rate DataFrame. Raises: ValueError: If ``count`` is not positive, targets are empty, duplicate ``(symbol, timeframe_int)`` pairs are present, or table resolution fails. \"\"\" if table is not None : return load_rate_data ( conn_or_path , table , count = count ) if count is None or count <= 0 : msg = \"count must be positive.\" raise ValueError ( msg ) if targets is None : msg = \"targets are required when table is not provided.\" raise ValueError ( msg ) target_list = list ( targets ) if not target_list : msg = \"At least one rate target is required.\" raise ValueError ( msg ) if explicit_tables is None and any ( target . symbol is None for target in target_list ): msg = ( \"Cannot resolve a rate table for a target without a symbol; \" \"provide explicit_tables.\" ) raise ValueError ( msg ) seen_keys : set [ tuple [ str | None , int ]] = set () for target in target_list : key = ( target . symbol , target . timeframe_int ) if key in seen_keys : symbol_repr = repr ( target . symbol ) msg = f \"Duplicate rate target: ( { symbol_repr } , { target . timeframe_int } )\" raise ValueError ( msg ) seen_keys . add ( key ) tables = ( resolve_rate_tables ( None , target_list , explicit_tables ) if explicit_tables is not None else None ) conn , should_close = _open_existing_sqlite_database ( conn_or_path ) try : resolved_tables = tables or resolve_rate_tables ( conn , target_list , require_existing = True , ) return { ( target . symbol , target . timeframe_int ): load_rate_data_from_connection ( conn , table , count = count , ) for target , table in zip ( target_list , resolved_tables , strict = True ) } finally : if should_close : conn . close () resolve_rate_tables \u00b6 resolve_rate_tables ( conn_or_path : SqliteConnOrPath | None , targets : Sequence [ RateTarget ], explicit_tables : Sequence [ str ] | None = None , * , require_existing : bool = False , ) -> list [ str ] Resolve SQLite table or view names for rate targets. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath | None SQLite database path or open connection. May be None when explicit_tables is provided, or when require_existing is False and deterministic default view names are sufficient. required targets Sequence [ RateTarget ] Rate targets to resolve. required explicit_tables Sequence [ str ] | None Optional explicit table or view names. When provided, they are used as-is and must match the number of targets. None require_existing bool When True, require the database and managed views to exist for each symbol target. Ignored when explicit_tables is provided. False Returns: Type Description list [ str ] Table or view names aligned with targets . Raises: Type Description ValueError If targets is empty, explicit_tables length does not match the target count, a target without a symbol is resolved without an explicit table, or require_existing is True and the database or a managed view is missing. Source code in mt5cli/history.py 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 def resolve_rate_tables ( conn_or_path : SqliteConnOrPath | None , targets : Sequence [ RateTarget ], explicit_tables : Sequence [ str ] | None = None , * , require_existing : bool = False , ) -> list [ str ]: \"\"\"Resolve SQLite table or view names for rate targets. Args: conn_or_path: SQLite database path or open connection. May be None when ``explicit_tables`` is provided, or when ``require_existing`` is False and deterministic default view names are sufficient. targets: Rate targets to resolve. explicit_tables: Optional explicit table or view names. When provided, they are used as-is and must match the number of targets. require_existing: When True, require the database and managed views to exist for each symbol target. Ignored when ``explicit_tables`` is provided. Returns: Table or view names aligned with ``targets``. Raises: ValueError: If ``targets`` is empty, ``explicit_tables`` length does not match the target count, a target without a symbol is resolved without an explicit table, or ``require_existing`` is True and the database or a managed view is missing. \"\"\" target_list = list ( targets ) if not target_list : msg = \"At least one rate target is required.\" raise ValueError ( msg ) if explicit_tables is not None : tables = list ( explicit_tables ) if len ( tables ) != len ( target_list ): msg = ( f \"Expected { len ( target_list ) } explicit table(s) \" f \"to match the targets, got { len ( tables ) } .\" ) raise ValueError ( msg ) return tables if any ( target . symbol is None for target in target_list ): msg = ( \"Cannot resolve a rate table for a target without a symbol; \" \"provide explicit_tables.\" ) raise ValueError ( msg ) conn , should_close = _open_history_connection ( conn_or_path ) try : if conn is None : if require_existing : path = ( conn_or_path if isinstance ( conn_or_path , ( Path , str )) else \"database\" ) msg = f \"SQLite database not found: { path } \" raise ValueError ( msg ) timeframe_counts = None existing_views : set [ str ] = set () else : timeframe_counts = _load_rates_timeframe_counts ( conn ) existing_views = _load_existing_rate_views ( conn ) resolved : list [ str ] = [] for target in target_list : symbol = cast ( \"str\" , target . symbol ) timeframe = target . timeframe_int resolved . append ( _resolve_rate_view_name_from_context ( symbol = symbol , timeframe = timeframe , granularity_name = resolve_granularity_name ( timeframe ), timeframe_counts = timeframe_counts , existing_views = existing_views , require_existing = require_existing , ), ) return resolved finally : if should_close and conn is not None : conn . close () resolve_rate_view_name \u00b6 resolve_rate_view_name ( conn_or_path : SqliteConnOrPath | None , symbol : str , granularity : str , * , require_existing : bool = False , ) -> str Resolve the mt5cli-managed rate compatibility view name. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath | None SQLite database path or open connection. When None or a non-existing path and require_existing is False, the deterministic default view name is returned without creating a database file. required symbol str Symbol stored in the normalized rates table. required granularity str Timeframe name (for example M1 ) or integer string. required require_existing bool When True, require the database and a managed view to exist. False Returns: Type Description str View name such as rate_EURUSD__1 or rate_EURUSD__M1_1 . Raises: Type Description ValueError If require_existing is True and the database or view is missing. Source code in mt5cli/history.py 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 def resolve_rate_view_name ( conn_or_path : SqliteConnOrPath | None , symbol : str , granularity : str , * , require_existing : bool = False , ) -> str : \"\"\"Resolve the mt5cli-managed rate compatibility view name. Args: conn_or_path: SQLite database path or open connection. When None or a non-existing path and ``require_existing`` is False, the deterministic default view name is returned without creating a database file. symbol: Symbol stored in the normalized ``rates`` table. granularity: Timeframe name (for example ``M1``) or integer string. require_existing: When True, require the database and a managed view to exist. Returns: View name such as ``rate_EURUSD__1`` or ``rate_EURUSD__M1_1``. Raises: ValueError: If ``require_existing`` is True and the database or view is missing. \"\"\" timeframe = parse_timeframe ( granularity ) granularity_name = resolve_granularity_name ( timeframe ) conn , should_close = _open_history_connection ( conn_or_path ) try : if conn is None : if require_existing : path = ( conn_or_path if isinstance ( conn_or_path , ( Path , str )) else \"database\" ) msg = f \"SQLite database not found: { path } \" raise ValueError ( msg ) return build_rate_view_name ( symbol = symbol , granularity = granularity_name , granularity_count = 1 , timeframe = timeframe , ) return _resolve_rate_view_name_from_context ( symbol = symbol , timeframe = timeframe , granularity_name = granularity_name , timeframe_counts = _load_rates_timeframe_counts ( conn ), existing_views = _load_existing_rate_views ( conn ), require_existing = require_existing , ) finally : if should_close and conn is not None : conn . close () resolve_rate_view_names \u00b6 resolve_rate_view_names ( conn_or_path : SqliteConnOrPath | None , symbols : Sequence [ str ], granularities : Sequence [ str ], * , require_existing : bool = False , ) -> list [ str ] Resolve rate compatibility view names for symbol and granularity pairs. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath | None SQLite database path or open connection. When None or a non-existing path and require_existing is False, deterministic default view names are returned without creating a database file. required symbols Sequence [ str ] Symbols stored in the normalized rates table. required granularities Sequence [ str ] Timeframe names (for example M1 ) or integer strings. required require_existing bool When True, require the database and managed views to exist. False Returns: Type Description list [ str ] View names in row-major order: every granularity for the first list [ str ] symbol, then every granularity for the next symbol, and so on. Source code in mt5cli/history.py 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 def resolve_rate_view_names ( conn_or_path : SqliteConnOrPath | None , symbols : Sequence [ str ], granularities : Sequence [ str ], * , require_existing : bool = False , ) -> list [ str ]: \"\"\"Resolve rate compatibility view names for symbol and granularity pairs. Args: conn_or_path: SQLite database path or open connection. When None or a non-existing path and ``require_existing`` is False, deterministic default view names are returned without creating a database file. symbols: Symbols stored in the normalized ``rates`` table. granularities: Timeframe names (for example ``M1``) or integer strings. require_existing: When True, require the database and managed views to exist. Returns: View names in row-major order: every ``granularity`` for the first symbol, then every granularity for the next symbol, and so on. \"\"\" conn , should_close = _open_history_connection ( conn_or_path ) try : if conn is None : return [ resolve_rate_view_name ( conn_or_path , symbol , granularity , require_existing = require_existing , ) for symbol in symbols for granularity in granularities ] timeframe_counts = _load_rates_timeframe_counts ( conn ) existing_views = _load_existing_rate_views ( conn ) resolved : list [ str ] = [] for symbol in symbols : for granularity in granularities : timeframe = parse_timeframe ( granularity ) resolved . append ( _resolve_rate_view_name_from_context ( symbol = symbol , timeframe = timeframe , granularity_name = resolve_granularity_name ( timeframe ), timeframe_counts = timeframe_counts , existing_views = existing_views , require_existing = require_existing , ), ) return resolved finally : if should_close and conn is not None : conn . close () update_history \u00b6 update_history ( * , client : Mt5DataClient , output : Path | str , symbols : Sequence [ str ], datasets : set [ Dataset ] | None = None , timeframes : Sequence [ int | str ] | None = None , flags : int | str = \"ALL\" , lookback_hours : float = 24.0 , date_to : datetime | str | None = None , deduplicate : bool = True , create_rate_views : bool = True , with_views : bool = False , include_account_events : bool = True , ) -> None Incrementally append MT5 history into a SQLite database. Uses an already-connected Mt5DataClient and does not create or close the MT5 connection. For first-time tables, data is fetched from date_to - lookback_hours . Subsequent runs resume from existing MAX(time) per symbol (and timeframe for rates); when include_account_events=True , account-level deals use a separate cursor over type NOT IN (0, 1) / empty-symbol rows. Parameters: Name Type Description Default client Mt5DataClient Connected MT5 data client. required output Path | str SQLite database path. required symbols Sequence [ str ] Symbols to update. required datasets set [ Dataset ] | None Datasets to include (defaults to all). None timeframes Sequence [ int | str ] | None Rate timeframes to update (defaults to all fixed MT5 timeframes when None). None flags int | str Tick copy flags as integer or name (e.g. ALL ). 'ALL' lookback_hours float First-run lookback when a table has no prior rows. 24.0 date_to datetime | str | None Optional update end datetime. Defaults to now (UTC). None deduplicate bool Remove duplicate rows after append, keeping latest ROWID. True create_rate_views bool Create rate___ views. True with_views bool Create cash_events and positions_reconstructed views. False include_account_events bool Include account-level cash events in history_deals when True. True Source code in mt5cli/sdk.py 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 def update_history ( # noqa: PLR0913 * , client : Mt5DataClient , output : Path | str , symbols : Sequence [ str ], datasets : set [ Dataset ] | None = None , timeframes : Sequence [ int | str ] | None = None , flags : int | str = \"ALL\" , lookback_hours : float = 24.0 , date_to : datetime | str | None = None , deduplicate : bool = True , create_rate_views : bool = True , with_views : bool = False , include_account_events : bool = True , ) -> None : \"\"\"Incrementally append MT5 history into a SQLite database. Uses an already-connected ``Mt5DataClient`` and does not create or close the MT5 connection. For first-time tables, data is fetched from ``date_to - lookback_hours``. Subsequent runs resume from existing ``MAX(time)`` per symbol (and timeframe for rates); when ``include_account_events=True``, account-level deals use a separate cursor over ``type NOT IN (0, 1)`` / empty-symbol rows. Args: client: Connected MT5 data client. output: SQLite database path. symbols: Symbols to update. datasets: Datasets to include (defaults to all). timeframes: Rate timeframes to update (defaults to all fixed MT5 timeframes when None). flags: Tick copy flags as integer or name (e.g. ``ALL``). lookback_hours: First-run lookback when a table has no prior rows. date_to: Optional update end datetime. Defaults to now (UTC). deduplicate: Remove duplicate rows after append, keeping latest ROWID. create_rate_views: Create ``rate___`` views. with_views: Create ``cash_events`` and ``positions_reconstructed`` views. include_account_events: Include account-level cash events in ``history_deals`` when True. \"\"\" request = _resolve_update_history_request ( output = output , symbols = symbols , datasets = datasets , timeframes = timeframes , flags = flags , lookback_hours = lookback_hours , date_to = date_to , ) if request is None : return logger . info ( \"Updating history in SQLite: symbols= %s , datasets= %s , path= %s \" , list ( symbols ), sorted ( dataset . value for dataset in request . selected ), request . output_path , ) with sqlite3 . connect ( request . output_path ) as conn : conn . execute ( \"PRAGMA journal_mode=WAL\" ) conn . execute ( \"PRAGMA synchronous=NORMAL\" ) write_incremental_datasets ( conn , client , symbols , request . selected , request . resolved_timeframes , request . resolved_tick_flags , request . fallback_start , request . end , deduplicate = deduplicate , create_rate_views = create_rate_views , with_views = with_views , include_account_events = include_account_events , ) update_history_with_config \u00b6 update_history_with_config ( * , output : Path | str , symbols : Sequence [ str ], config : Mt5Config | None = None , datasets : set [ Dataset ] | None = None , timeframes : Sequence [ int | str ] | None = None , flags : int | str = \"ALL\" , lookback_hours : float = 24.0 , date_to : datetime | str | None = None , deduplicate : bool = True , create_rate_views : bool = True , with_views : bool = False , include_account_events : bool = True , ) -> None Incrementally append MT5 history, opening and closing the MT5 connection. Convenience wrapper around :func: update_history for standalone use. Source code in mt5cli/sdk.py 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 def update_history_with_config ( # noqa: PLR0913 * , output : Path | str , symbols : Sequence [ str ], config : Mt5Config | None = None , datasets : set [ Dataset ] | None = None , timeframes : Sequence [ int | str ] | None = None , flags : int | str = \"ALL\" , lookback_hours : float = 24.0 , date_to : datetime | str | None = None , deduplicate : bool = True , create_rate_views : bool = True , with_views : bool = False , include_account_events : bool = True , ) -> None : \"\"\"Incrementally append MT5 history, opening and closing the MT5 connection. Convenience wrapper around :func:`update_history` for standalone use. \"\"\" request = _resolve_update_history_request ( output = output , symbols = symbols , datasets = datasets , timeframes = timeframes , flags = flags , lookback_hours = lookback_hours , date_to = date_to , ) if request is None : return mt5_config = config or build_config () with connected_client ( mt5_config ) as client : update_history ( client = client , output = output , symbols = symbols , datasets = datasets , timeframes = timeframes , flags = flags , lookback_hours = lookback_hours , date_to = date_to , deduplicate = deduplicate , create_rate_views = create_rate_views , with_views = with_views , include_account_events = include_account_events , )","title":"Storage"},{"location":"api/storage/#storage","text":"","title":"Storage"},{"location":"api/storage/#mt5cli.storage","text":"Generic storage helpers for MT5 market and account history.","title":"storage"},{"location":"api/storage/#mt5cli.storage.__all__","text":"__all__ = [ \"Dataset\" , \"IfExists\" , \"OutputFormat\" , \"RateTarget\" , \"build_rate_targets\" , \"build_rate_view_name\" , \"collect_history\" , \"detect_format\" , \"drop_forming_rate_bar\" , \"export_dataframe\" , \"export_dataframe_to_sqlite\" , \"load_rate_data\" , \"load_rate_data_from_connection\" , \"load_rate_series_by_granularity\" , \"load_rate_series_from_sqlite\" , \"resolve_rate_tables\" , \"resolve_rate_view_name\" , \"resolve_rate_view_names\" , \"update_history\" , \"update_history_with_config\" , ]","title":"__all__"},{"location":"api/storage/#mt5cli.storage.Dataset","text":"Bases: StrEnum Datasets supported by the collect-history command.","title":"Dataset"},{"location":"api/storage/#mt5cli.storage.Dataset.history_deals","text":"history_deals = 'history-deals'","title":"history_deals"},{"location":"api/storage/#mt5cli.storage.Dataset.history_orders","text":"history_orders = 'history-orders'","title":"history_orders"},{"location":"api/storage/#mt5cli.storage.Dataset.rates","text":"rates = 'rates'","title":"rates"},{"location":"api/storage/#mt5cli.storage.Dataset.table_name","text":"table_name : str Return the SQLite table name for this dataset.","title":"table_name"},{"location":"api/storage/#mt5cli.storage.Dataset.ticks","text":"ticks = 'ticks'","title":"ticks"},{"location":"api/storage/#mt5cli.storage.IfExists","text":"Bases: StrEnum SQLite table conflict behavior for the collect-history command.","title":"IfExists"},{"location":"api/storage/#mt5cli.storage.IfExists.APPEND","text":"APPEND = 'append'","title":"APPEND"},{"location":"api/storage/#mt5cli.storage.IfExists.FAIL","text":"FAIL = 'fail'","title":"FAIL"},{"location":"api/storage/#mt5cli.storage.IfExists.REPLACE","text":"REPLACE = 'replace'","title":"REPLACE"},{"location":"api/storage/#mt5cli.storage.OutputFormat","text":"Bases: StrEnum Supported output file formats.","title":"OutputFormat"},{"location":"api/storage/#mt5cli.storage.OutputFormat.csv","text":"csv = 'csv'","title":"csv"},{"location":"api/storage/#mt5cli.storage.OutputFormat.json","text":"json = 'json'","title":"json"},{"location":"api/storage/#mt5cli.storage.OutputFormat.parquet","text":"parquet = 'parquet'","title":"parquet"},{"location":"api/storage/#mt5cli.storage.OutputFormat.sqlite3","text":"sqlite3 = 'sqlite3'","title":"sqlite3"},{"location":"api/storage/#mt5cli.storage.RateTarget","text":"RateTarget ( symbol : str | None , timeframe : int | str ) A single rate series identified by symbol and timeframe. Attributes: Name Type Description symbol str | None MT5 symbol name, or None when the rate series is addressed only by an explicit table (for example a custom SQLite view). timeframe int | str MT5 timeframe as an integer or name (for example M1 ).","title":"RateTarget"},{"location":"api/storage/#mt5cli.storage.RateTarget.symbol","text":"symbol : str | None","title":"symbol"},{"location":"api/storage/#mt5cli.storage.RateTarget.timeframe","text":"timeframe : int | str","title":"timeframe"},{"location":"api/storage/#mt5cli.storage.RateTarget.timeframe_int","text":"timeframe_int : int Return the timeframe as its integer MT5 value.","title":"timeframe_int"},{"location":"api/storage/#mt5cli.storage.RateTarget.__post_init__","text":"__post_init__ () -> None Normalize accepted timeframe aliases to the stored integer value. Source code in mt5cli/history.py 544 545 546 547 def __post_init__ ( self ) -> None : \"\"\"Normalize accepted timeframe aliases to the stored integer value.\"\"\" if not isinstance ( self . timeframe , int ): object . __setattr__ ( self , \"timeframe\" , parse_timeframe ( self . timeframe ))","title":"__post_init__"},{"location":"api/storage/#mt5cli.storage.build_rate_targets","text":"build_rate_targets ( symbols : Sequence [ str ], timeframes : Sequence [ int | str ], * , allow_missing_symbol : bool = False , ) -> list [ RateTarget ] Build rate targets for every symbol and timeframe combination. Parameters: Name Type Description Default symbols Sequence [ str ] MT5 symbol names. May be empty when allow_missing_symbol . required timeframes Sequence [ int | str ] MT5 timeframes as integers or names (for example M1 ). required allow_missing_symbol bool When True and symbols is empty, build targets with symbol=None for each timeframe instead of raising. False Returns: Type Description list [ RateTarget ] Targets in row-major order: every timeframe for the first symbol, then list [ RateTarget ] every timeframe for the next symbol, and so on. Raises: Type Description ValueError If timeframes is empty, or symbols is empty and allow_missing_symbol is False. Source code in mt5cli/history.py 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 def build_rate_targets ( symbols : Sequence [ str ], timeframes : Sequence [ int | str ], * , allow_missing_symbol : bool = False , ) -> list [ RateTarget ]: \"\"\"Build rate targets for every symbol and timeframe combination. Args: symbols: MT5 symbol names. May be empty when ``allow_missing_symbol``. timeframes: MT5 timeframes as integers or names (for example ``M1``). allow_missing_symbol: When True and ``symbols`` is empty, build targets with ``symbol=None`` for each timeframe instead of raising. Returns: Targets in row-major order: every timeframe for the first symbol, then every timeframe for the next symbol, and so on. Raises: ValueError: If ``timeframes`` is empty, or ``symbols`` is empty and ``allow_missing_symbol`` is False. \"\"\" if not timeframes : msg = \"At least one timeframe is required.\" raise ValueError ( msg ) if not symbols : if not allow_missing_symbol : msg = \"At least one symbol is required.\" raise ValueError ( msg ) return [ RateTarget ( symbol = None , timeframe = tf ) for tf in timeframes ] return [ RateTarget ( symbol = symbol , timeframe = tf ) for symbol in symbols for tf in timeframes ]","title":"build_rate_targets"},{"location":"api/storage/#mt5cli.storage.build_rate_view_name","text":"build_rate_view_name ( * , symbol : str , granularity : str , granularity_count : int , timeframe : int , ) -> str Return a collision-free offline optimize view name. View names always include the timeframe integer after a __ separator so a symbol such as EURUSD_M1 cannot collide with EURUSD at timeframe M1 . Source code in mt5cli/history.py 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 def build_rate_view_name ( * , symbol : str , granularity : str , granularity_count : int , timeframe : int , ) -> str : \"\"\"Return a collision-free offline optimize view name. View names always include the timeframe integer after a ``__`` separator so a symbol such as ``EURUSD_M1`` cannot collide with ``EURUSD`` at timeframe ``M1``. \"\"\" if granularity_count == 1 : return f \"rate_ { symbol } __ { timeframe } \" return f \"rate_ { symbol } __ { granularity } _ { timeframe } \"","title":"build_rate_view_name"},{"location":"api/storage/#mt5cli.storage.collect_history","text":"collect_history ( output : Path , symbols : list [ str ], date_from : datetime | str , date_to : datetime | str , * , datasets : set [ Dataset ] | None = None , timeframe : int | str = 1 , flags : int | str = \"ALL\" , if_exists : IfExists = FAIL , with_views : bool = False , config : Mt5Config | None = None , ) -> None Collect historical datasets into a single SQLite database. Parameters: Name Type Description Default output Path SQLite database path. required symbols list [ str ] Symbols to collect. required date_from datetime | str Start date. required date_to datetime | str End date. required datasets set [ Dataset ] | None Datasets to include (defaults to all). None timeframe int | str Rates timeframe as integer or name (e.g. M1 ). 1 flags int | str Tick copy flags as integer or name (e.g. ALL ). 'ALL' if_exists IfExists Behavior when a target table already exists. FAIL with_views bool Create cash_events and positions_reconstructed views. False config Mt5Config | None MT5 connection configuration. None Source code in mt5cli/sdk.py 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 def collect_history ( output : Path , symbols : list [ str ], date_from : datetime | str , date_to : datetime | str , * , datasets : set [ Dataset ] | None = None , timeframe : int | str = 1 , flags : int | str = \"ALL\" , if_exists : IfExists = IfExists . FAIL , with_views : bool = False , config : Mt5Config | None = None , ) -> None : \"\"\"Collect historical datasets into a single SQLite database. Args: output: SQLite database path. symbols: Symbols to collect. date_from: Start date. date_to: End date. datasets: Datasets to include (defaults to all). timeframe: Rates timeframe as integer or name (e.g. ``M1``). flags: Tick copy flags as integer or name (e.g. ``ALL``). if_exists: Behavior when a target table already exists. with_views: Create ``cash_events`` and ``positions_reconstructed`` views. config: MT5 connection configuration. \"\"\" start = _require_datetime ( date_from ) end = _require_datetime ( date_to ) selected = datasets if datasets is not None else set ( Dataset ) tf = _coerce_timeframe ( timeframe ) tick_flags = _coerce_tick_flags ( flags ) mt5_config = config or build_config () with connected_client ( mt5_config ) as client , sqlite3 . connect ( output ) as conn : conn . execute ( \"PRAGMA journal_mode=WAL\" ) conn . execute ( \"PRAGMA synchronous=NORMAL\" ) written_tables , written_columns = write_collected_datasets ( conn , client , symbols , selected , tf , tick_flags , start , end , if_exists , ) create_history_indexes ( conn , written_columns ) if with_views and Dataset . history_deals in written_tables : create_cash_events_view ( conn , written_columns [ Dataset . history_deals ]) create_positions_reconstructed_view ( conn , written_columns [ Dataset . history_deals ], ) elif with_views : logger . warning ( \"--with-views ignored: history_deals table was not written\" , ) logger . info ( \"Collected %s for %d symbol(s) into %s \" , \", \" . join ( sorted ( ds . value for ds in selected )), len ( symbols ), output , )","title":"collect_history"},{"location":"api/storage/#mt5cli.storage.detect_format","text":"detect_format ( output_path : Path , explicit_format : str | None = None ) -> str Detect the output format from a file extension or explicit format string. Parameters: Name Type Description Default output_path Path Path to the output file. required explicit_format str | None Explicitly specified format, if any. None Returns: Type Description str The detected format string. Raises: Type Description ValueError If the format cannot be determined. Source code in mt5cli/utils.py 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 def detect_format ( output_path : Path , explicit_format : str | None = None , ) -> str : \"\"\"Detect the output format from a file extension or explicit format string. Args: output_path: Path to the output file. explicit_format: Explicitly specified format, if any. Returns: The detected format string. Raises: ValueError: If the format cannot be determined. \"\"\" if explicit_format is not None : return explicit_format suffix = output_path . suffix . lower () if suffix in _FORMAT_EXTENSIONS : return _FORMAT_EXTENSIONS [ suffix ] msg = ( f \"Cannot detect format from extension ' { suffix } '.\" \" Use --format to specify the output format.\" ) raise ValueError ( msg )","title":"detect_format"},{"location":"api/storage/#mt5cli.storage.drop_forming_rate_bar","text":"drop_forming_rate_bar ( df_rate : DataFrame ) -> DataFrame Return closed bars from chronologically ordered MT5 rate data. MetaTrader 5 copy_rates_from_pos(start_pos=0) includes the still-forming current bar as the last row. Slice it off so downstream logic only sees completed bars. Empty frames and single-row frames return empty results. Parameters: Name Type Description Default df_rate DataFrame Rate data ordered oldest-to-newest with the forming bar last. required Returns: Type Description DataFrame A new DataFrame with all rows except the last. Index and columns are DataFrame preserved. The input frame is not modified. Source code in mt5cli/history.py 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 def drop_forming_rate_bar ( df_rate : pd . DataFrame ) -> pd . DataFrame : \"\"\"Return closed bars from chronologically ordered MT5 rate data. MetaTrader 5 ``copy_rates_from_pos(start_pos=0)`` includes the still-forming current bar as the last row. Slice it off so downstream logic only sees completed bars. Empty frames and single-row frames return empty results. Args: df_rate: Rate data ordered oldest-to-newest with the forming bar last. Returns: A new DataFrame with all rows except the last. Index and columns are preserved. The input frame is not modified. \"\"\" return df_rate . iloc [: - 1 ] . copy ()","title":"drop_forming_rate_bar"},{"location":"api/storage/#mt5cli.storage.export_dataframe","text":"export_dataframe ( df : DataFrame , output_path : Path , output_format : str , table_name : str = \"data\" , ) -> None Export a pandas DataFrame to the specified file format. Parameters: Name Type Description Default df DataFrame DataFrame to export. required output_path Path Path to the output file. required output_format str Output format (csv, json, parquet, or sqlite3). required table_name str Table name for SQLite3 output. 'data' Raises: Type Description ValueError If the output format is not supported. Source code in mt5cli/utils.py 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 def export_dataframe ( df : pd . DataFrame , output_path : Path , output_format : str , table_name : str = \"data\" , ) -> None : \"\"\"Export a pandas DataFrame to the specified file format. Args: df: DataFrame to export. output_path: Path to the output file. output_format: Output format (csv, json, parquet, or sqlite3). table_name: Table name for SQLite3 output. Raises: ValueError: If the output format is not supported. \"\"\" if output_format == \"csv\" : df . to_csv ( output_path , index = False ) elif output_format == \"json\" : df . to_json ( output_path , orient = \"records\" , date_format = \"iso\" , indent = 2 , ) elif output_format == \"parquet\" : df . to_parquet ( output_path , index = False ) elif output_format == \"sqlite3\" : export_dataframe_to_sqlite ( df , output_path , table_name , if_exists = IfExists . REPLACE , index = False , ) else : msg = f \"Unsupported output format: { output_format } \" raise ValueError ( msg )","title":"export_dataframe"},{"location":"api/storage/#mt5cli.storage.export_dataframe_to_sqlite","text":"export_dataframe_to_sqlite ( df : DataFrame , output_path : Path , table_name : str = \"data\" , * , if_exists : IfExists = APPEND , index : bool = False , index_label : str | None = None , deduplicate_on : Sequence [ str ] | None = None , ) -> None Write a DataFrame to SQLite with configurable append and deduplication. Parameters: Name Type Description Default df DataFrame DataFrame to export. required output_path Path SQLite database path. required table_name str Target table name. 'data' if_exists IfExists Conflict behavior when the table already exists. APPEND index bool Whether to write the DataFrame index as a column. False index_label str | None Column name for the index when index=True . None deduplicate_on Sequence [ str ] | None Optional key columns to deduplicate after writing, keeping the latest ROWID per key group. Deduplication scans the full table, so repeated appends cost O(table size); index the key columns when appending frequently. None Source code in mt5cli/utils.py 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 def export_dataframe_to_sqlite ( df : pd . DataFrame , output_path : Path , table_name : str = \"data\" , * , if_exists : IfExists = IfExists . APPEND , index : bool = False , index_label : str | None = None , deduplicate_on : Sequence [ str ] | None = None , ) -> None : \"\"\"Write a DataFrame to SQLite with configurable append and deduplication. Args: df: DataFrame to export. output_path: SQLite database path. table_name: Target table name. if_exists: Conflict behavior when the table already exists. index: Whether to write the DataFrame index as a column. index_label: Column name for the index when ``index=True``. deduplicate_on: Optional key columns to deduplicate after writing, keeping the latest ``ROWID`` per key group. Deduplication scans the full table, so repeated appends cost O(table size); index the key columns when appending frequently. \"\"\" with sqlite3 . connect ( output_path ) as conn : df . to_sql ( # type: ignore[reportUnknownMemberType] table_name , conn , if_exists = if_exists . value , index = index , index_label = index_label , ) if deduplicate_on : from .history import drop_duplicates_in_table # noqa: PLC0415 drop_duplicates_in_table ( conn . cursor (), table_name , list ( deduplicate_on ), keep = \"last\" , ) conn . commit ()","title":"export_dataframe_to_sqlite"},{"location":"api/storage/#mt5cli.storage.load_rate_data","text":"load_rate_data ( conn_or_path : SqliteConnOrPath , table : str , count : int | None = None , ) -> DataFrame Load rate-like data from a SQLite database path or connection. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath SQLite database path or open connection. required table str Source table or view name. required count int | None Optional number of most recent rows to load. None Returns: Type Description DataFrame DataFrame indexed by ascending time . Source code in mt5cli/history.py 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 def load_rate_data ( conn_or_path : SqliteConnOrPath , table : str , count : int | None = None , ) -> pd . DataFrame : \"\"\"Load rate-like data from a SQLite database path or connection. Args: conn_or_path: SQLite database path or open connection. table: Source table or view name. count: Optional number of most recent rows to load. Returns: DataFrame indexed by ascending ``time``. \"\"\" conn , should_close = _open_existing_sqlite_database ( conn_or_path ) try : return load_rate_data_from_connection ( conn , table , count = count ) finally : if should_close : conn . close ()","title":"load_rate_data"},{"location":"api/storage/#mt5cli.storage.load_rate_data_from_connection","text":"load_rate_data_from_connection ( connection : Connection , table : str , count : int | None = None , ) -> DataFrame Load rate-like data from a SQLite table or view. Parameters: Name Type Description Default connection Connection Open SQLite connection. required table str Source table or view name. required count int | None Optional number of most recent rows to load. None Returns: Type Description DataFrame DataFrame indexed by ascending time . Raises: Type Description ValueError If inputs, schema, timestamps are invalid, or the table or view contains no rows. Source code in mt5cli/history.py 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 def load_rate_data_from_connection ( connection : sqlite3 . Connection , table : str , count : int | None = None , ) -> pd . DataFrame : \"\"\"Load rate-like data from a SQLite table or view. Args: connection: Open SQLite connection. table: Source table or view name. count: Optional number of most recent rows to load. Returns: DataFrame indexed by ascending ``time``. Raises: ValueError: If inputs, schema, timestamps are invalid, or the table or view contains no rows. \"\"\" table_name = _validate_rate_load_request ( table , count ) columns = get_table_columns ( connection , table_name ) _ensure_rate_columns ( columns , table_name ) quoted_table = quote_sqlite_identifier ( table_name ) if count is None : frame = cast ( \"pd.DataFrame\" , pd . read_sql_query ( # type: ignore[reportUnknownMemberType] f \"SELECT * FROM { quoted_table } ORDER BY time ASC\" , # noqa: S608 connection , ), ) else : frame = cast ( \"pd.DataFrame\" , pd . read_sql_query ( # type: ignore[reportUnknownMemberType] f \"SELECT * FROM { quoted_table } ORDER BY time DESC LIMIT ?\" , # noqa: S608 connection , params = ( count ,), ), ) if frame . empty : msg = f \"SQLite table or view { table_name !r} contains no rows.\" raise ValueError ( msg ) return _parse_rate_time_index ( frame , table_name )","title":"load_rate_data_from_connection"},{"location":"api/storage/#mt5cli.storage.load_rate_series_by_granularity","text":"load_rate_series_by_granularity ( conn_or_path : SqliteConnOrPath , symbols : Sequence [ str ], granularities : Sequence [ int | str ], count : int , * , explicit_tables : Sequence [ str ] | None = None , allow_missing_symbol : bool = False , ) -> dict [ tuple [ str | None , str ], DataFrame ] Load rate series keyed by symbol and string granularity name. Builds targets with :func: build_rate_targets and loads them with :func: load_rate_series_from_sqlite , then rekeys the result by granularity name (for example M1 ) instead of the integer timeframe to reduce downstream boilerplate. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath SQLite database path or open connection. required symbols Sequence [ str ] MT5 symbol names. May be empty when allow_missing_symbol . required granularities Sequence [ int | str ] MT5 timeframes as integers or names (for example M1 ). required count int Number of most recent rows to load per series. required explicit_tables Sequence [ str ] | None Optional explicit table or view names matching the built targets in row-major order. Required when symbols are omitted. None allow_missing_symbol bool When True and symbols is empty, build targets with symbol=None for each granularity instead of raising. False Returns: Type Description dict [ tuple [ str | None, str ], DataFrame ] Mapping keyed by (symbol | None, granularity_name) to each rate dict [ tuple [ str | None, str ], DataFrame ] DataFrame. Propagates ValueError (via :func: build_rate_targets and dict [ tuple [ str | None, str ], DataFrame ] func: load_rate_series_from_sqlite ) when inputs are empty or invalid, dict [ tuple [ str | None, str ], DataFrame ] table resolution fails, or duplicate targets are present. Source code in mt5cli/history.py 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 def load_rate_series_by_granularity ( conn_or_path : SqliteConnOrPath , symbols : Sequence [ str ], granularities : Sequence [ int | str ], count : int , * , explicit_tables : Sequence [ str ] | None = None , allow_missing_symbol : bool = False , ) -> dict [ tuple [ str | None , str ], pd . DataFrame ]: \"\"\"Load rate series keyed by symbol and string granularity name. Builds targets with :func:`build_rate_targets` and loads them with :func:`load_rate_series_from_sqlite`, then rekeys the result by granularity name (for example ``M1``) instead of the integer timeframe to reduce downstream boilerplate. Args: conn_or_path: SQLite database path or open connection. symbols: MT5 symbol names. May be empty when ``allow_missing_symbol``. granularities: MT5 timeframes as integers or names (for example ``M1``). count: Number of most recent rows to load per series. explicit_tables: Optional explicit table or view names matching the built targets in row-major order. Required when symbols are omitted. allow_missing_symbol: When True and ``symbols`` is empty, build targets with ``symbol=None`` for each granularity instead of raising. Returns: Mapping keyed by ``(symbol | None, granularity_name)`` to each rate DataFrame. Propagates ``ValueError`` (via :func:`build_rate_targets` and :func:`load_rate_series_from_sqlite`) when inputs are empty or invalid, table resolution fails, or duplicate targets are present. \"\"\" targets = build_rate_targets ( symbols , granularities , allow_missing_symbol = allow_missing_symbol , ) series = load_rate_series_from_sqlite ( conn_or_path , targets , count , explicit_tables = explicit_tables , ) return { ( symbol , resolve_granularity_name ( timeframe )): frame for ( symbol , timeframe ), frame in series . items () }","title":"load_rate_series_by_granularity"},{"location":"api/storage/#mt5cli.storage.load_rate_series_from_sqlite","text":"load_rate_series_from_sqlite ( conn_or_path : SqliteConnOrPath , targets : None = None , count : int | None = None , explicit_tables : None = None , * , table : str , ) -> DataFrame load_rate_series_from_sqlite ( conn_or_path : SqliteConnOrPath , targets : None = None , count : int | None = None , explicit_tables : Sequence [ str ] | None = None , * , table : None = None , ) -> dict [ tuple [ str | None , int ], DataFrame ] load_rate_series_from_sqlite ( conn_or_path : SqliteConnOrPath , targets : Sequence [ RateTarget ], count : int , explicit_tables : Sequence [ str ] | None = None , * , table : None = None , ) -> dict [ tuple [ str | None , int ], DataFrame ] load_rate_series_from_sqlite ( conn_or_path : SqliteConnOrPath , targets : Sequence [ RateTarget ] | None = None , count : int | None = None , explicit_tables : Sequence [ str ] | None = None , * , table : str | None = None , ) -> dict [ tuple [ str | None , int ], DataFrame ] | DataFrame Load one table/view or multiple rate series from a SQLite database. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath SQLite database path or open connection. required targets Sequence [ RateTarget ] | None Rate targets to load. Each (symbol, timeframe_int) pair must be unique. Omit when loading a single explicit table . None count int | None Optional number of most recent rows to load per series. None explicit_tables Sequence [ str ] | None Optional explicit table or view names matching targets. When omitted, managed rate_* compatibility views must already exist in the database. None table str | None Optional single table or view name to load directly. None Returns: Type Description dict [ tuple [ str | None, int ], DataFrame ] | DataFrame A DataFrame when table is provided, otherwise a mapping keyed by dict [ tuple [ str | None, int ], DataFrame ] | DataFrame (symbol, timeframe_int) to each rate DataFrame. Raises: Type Description ValueError If count is not positive, targets are empty, duplicate (symbol, timeframe_int) pairs are present, or table resolution fails. Source code in mt5cli/history.py 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 def load_rate_series_from_sqlite ( conn_or_path : SqliteConnOrPath , targets : Sequence [ RateTarget ] | None = None , count : int | None = None , explicit_tables : Sequence [ str ] | None = None , * , table : str | None = None , ) -> dict [ tuple [ str | None , int ], pd . DataFrame ] | pd . DataFrame : \"\"\"Load one table/view or multiple rate series from a SQLite database. Args: conn_or_path: SQLite database path or open connection. targets: Rate targets to load. Each ``(symbol, timeframe_int)`` pair must be unique. Omit when loading a single explicit ``table``. count: Optional number of most recent rows to load per series. explicit_tables: Optional explicit table or view names matching targets. When omitted, managed ``rate_*`` compatibility views must already exist in the database. table: Optional single table or view name to load directly. Returns: A DataFrame when ``table`` is provided, otherwise a mapping keyed by ``(symbol, timeframe_int)`` to each rate DataFrame. Raises: ValueError: If ``count`` is not positive, targets are empty, duplicate ``(symbol, timeframe_int)`` pairs are present, or table resolution fails. \"\"\" if table is not None : return load_rate_data ( conn_or_path , table , count = count ) if count is None or count <= 0 : msg = \"count must be positive.\" raise ValueError ( msg ) if targets is None : msg = \"targets are required when table is not provided.\" raise ValueError ( msg ) target_list = list ( targets ) if not target_list : msg = \"At least one rate target is required.\" raise ValueError ( msg ) if explicit_tables is None and any ( target . symbol is None for target in target_list ): msg = ( \"Cannot resolve a rate table for a target without a symbol; \" \"provide explicit_tables.\" ) raise ValueError ( msg ) seen_keys : set [ tuple [ str | None , int ]] = set () for target in target_list : key = ( target . symbol , target . timeframe_int ) if key in seen_keys : symbol_repr = repr ( target . symbol ) msg = f \"Duplicate rate target: ( { symbol_repr } , { target . timeframe_int } )\" raise ValueError ( msg ) seen_keys . add ( key ) tables = ( resolve_rate_tables ( None , target_list , explicit_tables ) if explicit_tables is not None else None ) conn , should_close = _open_existing_sqlite_database ( conn_or_path ) try : resolved_tables = tables or resolve_rate_tables ( conn , target_list , require_existing = True , ) return { ( target . symbol , target . timeframe_int ): load_rate_data_from_connection ( conn , table , count = count , ) for target , table in zip ( target_list , resolved_tables , strict = True ) } finally : if should_close : conn . close ()","title":"load_rate_series_from_sqlite"},{"location":"api/storage/#mt5cli.storage.resolve_rate_tables","text":"resolve_rate_tables ( conn_or_path : SqliteConnOrPath | None , targets : Sequence [ RateTarget ], explicit_tables : Sequence [ str ] | None = None , * , require_existing : bool = False , ) -> list [ str ] Resolve SQLite table or view names for rate targets. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath | None SQLite database path or open connection. May be None when explicit_tables is provided, or when require_existing is False and deterministic default view names are sufficient. required targets Sequence [ RateTarget ] Rate targets to resolve. required explicit_tables Sequence [ str ] | None Optional explicit table or view names. When provided, they are used as-is and must match the number of targets. None require_existing bool When True, require the database and managed views to exist for each symbol target. Ignored when explicit_tables is provided. False Returns: Type Description list [ str ] Table or view names aligned with targets . Raises: Type Description ValueError If targets is empty, explicit_tables length does not match the target count, a target without a symbol is resolved without an explicit table, or require_existing is True and the database or a managed view is missing. Source code in mt5cli/history.py 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 def resolve_rate_tables ( conn_or_path : SqliteConnOrPath | None , targets : Sequence [ RateTarget ], explicit_tables : Sequence [ str ] | None = None , * , require_existing : bool = False , ) -> list [ str ]: \"\"\"Resolve SQLite table or view names for rate targets. Args: conn_or_path: SQLite database path or open connection. May be None when ``explicit_tables`` is provided, or when ``require_existing`` is False and deterministic default view names are sufficient. targets: Rate targets to resolve. explicit_tables: Optional explicit table or view names. When provided, they are used as-is and must match the number of targets. require_existing: When True, require the database and managed views to exist for each symbol target. Ignored when ``explicit_tables`` is provided. Returns: Table or view names aligned with ``targets``. Raises: ValueError: If ``targets`` is empty, ``explicit_tables`` length does not match the target count, a target without a symbol is resolved without an explicit table, or ``require_existing`` is True and the database or a managed view is missing. \"\"\" target_list = list ( targets ) if not target_list : msg = \"At least one rate target is required.\" raise ValueError ( msg ) if explicit_tables is not None : tables = list ( explicit_tables ) if len ( tables ) != len ( target_list ): msg = ( f \"Expected { len ( target_list ) } explicit table(s) \" f \"to match the targets, got { len ( tables ) } .\" ) raise ValueError ( msg ) return tables if any ( target . symbol is None for target in target_list ): msg = ( \"Cannot resolve a rate table for a target without a symbol; \" \"provide explicit_tables.\" ) raise ValueError ( msg ) conn , should_close = _open_history_connection ( conn_or_path ) try : if conn is None : if require_existing : path = ( conn_or_path if isinstance ( conn_or_path , ( Path , str )) else \"database\" ) msg = f \"SQLite database not found: { path } \" raise ValueError ( msg ) timeframe_counts = None existing_views : set [ str ] = set () else : timeframe_counts = _load_rates_timeframe_counts ( conn ) existing_views = _load_existing_rate_views ( conn ) resolved : list [ str ] = [] for target in target_list : symbol = cast ( \"str\" , target . symbol ) timeframe = target . timeframe_int resolved . append ( _resolve_rate_view_name_from_context ( symbol = symbol , timeframe = timeframe , granularity_name = resolve_granularity_name ( timeframe ), timeframe_counts = timeframe_counts , existing_views = existing_views , require_existing = require_existing , ), ) return resolved finally : if should_close and conn is not None : conn . close ()","title":"resolve_rate_tables"},{"location":"api/storage/#mt5cli.storage.resolve_rate_view_name","text":"resolve_rate_view_name ( conn_or_path : SqliteConnOrPath | None , symbol : str , granularity : str , * , require_existing : bool = False , ) -> str Resolve the mt5cli-managed rate compatibility view name. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath | None SQLite database path or open connection. When None or a non-existing path and require_existing is False, the deterministic default view name is returned without creating a database file. required symbol str Symbol stored in the normalized rates table. required granularity str Timeframe name (for example M1 ) or integer string. required require_existing bool When True, require the database and a managed view to exist. False Returns: Type Description str View name such as rate_EURUSD__1 or rate_EURUSD__M1_1 . Raises: Type Description ValueError If require_existing is True and the database or view is missing. Source code in mt5cli/history.py 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 def resolve_rate_view_name ( conn_or_path : SqliteConnOrPath | None , symbol : str , granularity : str , * , require_existing : bool = False , ) -> str : \"\"\"Resolve the mt5cli-managed rate compatibility view name. Args: conn_or_path: SQLite database path or open connection. When None or a non-existing path and ``require_existing`` is False, the deterministic default view name is returned without creating a database file. symbol: Symbol stored in the normalized ``rates`` table. granularity: Timeframe name (for example ``M1``) or integer string. require_existing: When True, require the database and a managed view to exist. Returns: View name such as ``rate_EURUSD__1`` or ``rate_EURUSD__M1_1``. Raises: ValueError: If ``require_existing`` is True and the database or view is missing. \"\"\" timeframe = parse_timeframe ( granularity ) granularity_name = resolve_granularity_name ( timeframe ) conn , should_close = _open_history_connection ( conn_or_path ) try : if conn is None : if require_existing : path = ( conn_or_path if isinstance ( conn_or_path , ( Path , str )) else \"database\" ) msg = f \"SQLite database not found: { path } \" raise ValueError ( msg ) return build_rate_view_name ( symbol = symbol , granularity = granularity_name , granularity_count = 1 , timeframe = timeframe , ) return _resolve_rate_view_name_from_context ( symbol = symbol , timeframe = timeframe , granularity_name = granularity_name , timeframe_counts = _load_rates_timeframe_counts ( conn ), existing_views = _load_existing_rate_views ( conn ), require_existing = require_existing , ) finally : if should_close and conn is not None : conn . close ()","title":"resolve_rate_view_name"},{"location":"api/storage/#mt5cli.storage.resolve_rate_view_names","text":"resolve_rate_view_names ( conn_or_path : SqliteConnOrPath | None , symbols : Sequence [ str ], granularities : Sequence [ str ], * , require_existing : bool = False , ) -> list [ str ] Resolve rate compatibility view names for symbol and granularity pairs. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath | None SQLite database path or open connection. When None or a non-existing path and require_existing is False, deterministic default view names are returned without creating a database file. required symbols Sequence [ str ] Symbols stored in the normalized rates table. required granularities Sequence [ str ] Timeframe names (for example M1 ) or integer strings. required require_existing bool When True, require the database and managed views to exist. False Returns: Type Description list [ str ] View names in row-major order: every granularity for the first list [ str ] symbol, then every granularity for the next symbol, and so on. Source code in mt5cli/history.py 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 def resolve_rate_view_names ( conn_or_path : SqliteConnOrPath | None , symbols : Sequence [ str ], granularities : Sequence [ str ], * , require_existing : bool = False , ) -> list [ str ]: \"\"\"Resolve rate compatibility view names for symbol and granularity pairs. Args: conn_or_path: SQLite database path or open connection. When None or a non-existing path and ``require_existing`` is False, deterministic default view names are returned without creating a database file. symbols: Symbols stored in the normalized ``rates`` table. granularities: Timeframe names (for example ``M1``) or integer strings. require_existing: When True, require the database and managed views to exist. Returns: View names in row-major order: every ``granularity`` for the first symbol, then every granularity for the next symbol, and so on. \"\"\" conn , should_close = _open_history_connection ( conn_or_path ) try : if conn is None : return [ resolve_rate_view_name ( conn_or_path , symbol , granularity , require_existing = require_existing , ) for symbol in symbols for granularity in granularities ] timeframe_counts = _load_rates_timeframe_counts ( conn ) existing_views = _load_existing_rate_views ( conn ) resolved : list [ str ] = [] for symbol in symbols : for granularity in granularities : timeframe = parse_timeframe ( granularity ) resolved . append ( _resolve_rate_view_name_from_context ( symbol = symbol , timeframe = timeframe , granularity_name = resolve_granularity_name ( timeframe ), timeframe_counts = timeframe_counts , existing_views = existing_views , require_existing = require_existing , ), ) return resolved finally : if should_close and conn is not None : conn . close ()","title":"resolve_rate_view_names"},{"location":"api/storage/#mt5cli.storage.update_history","text":"update_history ( * , client : Mt5DataClient , output : Path | str , symbols : Sequence [ str ], datasets : set [ Dataset ] | None = None , timeframes : Sequence [ int | str ] | None = None , flags : int | str = \"ALL\" , lookback_hours : float = 24.0 , date_to : datetime | str | None = None , deduplicate : bool = True , create_rate_views : bool = True , with_views : bool = False , include_account_events : bool = True , ) -> None Incrementally append MT5 history into a SQLite database. Uses an already-connected Mt5DataClient and does not create or close the MT5 connection. For first-time tables, data is fetched from date_to - lookback_hours . Subsequent runs resume from existing MAX(time) per symbol (and timeframe for rates); when include_account_events=True , account-level deals use a separate cursor over type NOT IN (0, 1) / empty-symbol rows. Parameters: Name Type Description Default client Mt5DataClient Connected MT5 data client. required output Path | str SQLite database path. required symbols Sequence [ str ] Symbols to update. required datasets set [ Dataset ] | None Datasets to include (defaults to all). None timeframes Sequence [ int | str ] | None Rate timeframes to update (defaults to all fixed MT5 timeframes when None). None flags int | str Tick copy flags as integer or name (e.g. ALL ). 'ALL' lookback_hours float First-run lookback when a table has no prior rows. 24.0 date_to datetime | str | None Optional update end datetime. Defaults to now (UTC). None deduplicate bool Remove duplicate rows after append, keeping latest ROWID. True create_rate_views bool Create rate___ views. True with_views bool Create cash_events and positions_reconstructed views. False include_account_events bool Include account-level cash events in history_deals when True. True Source code in mt5cli/sdk.py 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 def update_history ( # noqa: PLR0913 * , client : Mt5DataClient , output : Path | str , symbols : Sequence [ str ], datasets : set [ Dataset ] | None = None , timeframes : Sequence [ int | str ] | None = None , flags : int | str = \"ALL\" , lookback_hours : float = 24.0 , date_to : datetime | str | None = None , deduplicate : bool = True , create_rate_views : bool = True , with_views : bool = False , include_account_events : bool = True , ) -> None : \"\"\"Incrementally append MT5 history into a SQLite database. Uses an already-connected ``Mt5DataClient`` and does not create or close the MT5 connection. For first-time tables, data is fetched from ``date_to - lookback_hours``. Subsequent runs resume from existing ``MAX(time)`` per symbol (and timeframe for rates); when ``include_account_events=True``, account-level deals use a separate cursor over ``type NOT IN (0, 1)`` / empty-symbol rows. Args: client: Connected MT5 data client. output: SQLite database path. symbols: Symbols to update. datasets: Datasets to include (defaults to all). timeframes: Rate timeframes to update (defaults to all fixed MT5 timeframes when None). flags: Tick copy flags as integer or name (e.g. ``ALL``). lookback_hours: First-run lookback when a table has no prior rows. date_to: Optional update end datetime. Defaults to now (UTC). deduplicate: Remove duplicate rows after append, keeping latest ROWID. create_rate_views: Create ``rate___`` views. with_views: Create ``cash_events`` and ``positions_reconstructed`` views. include_account_events: Include account-level cash events in ``history_deals`` when True. \"\"\" request = _resolve_update_history_request ( output = output , symbols = symbols , datasets = datasets , timeframes = timeframes , flags = flags , lookback_hours = lookback_hours , date_to = date_to , ) if request is None : return logger . info ( \"Updating history in SQLite: symbols= %s , datasets= %s , path= %s \" , list ( symbols ), sorted ( dataset . value for dataset in request . selected ), request . output_path , ) with sqlite3 . connect ( request . output_path ) as conn : conn . execute ( \"PRAGMA journal_mode=WAL\" ) conn . execute ( \"PRAGMA synchronous=NORMAL\" ) write_incremental_datasets ( conn , client , symbols , request . selected , request . resolved_timeframes , request . resolved_tick_flags , request . fallback_start , request . end , deduplicate = deduplicate , create_rate_views = create_rate_views , with_views = with_views , include_account_events = include_account_events , )","title":"update_history"},{"location":"api/storage/#mt5cli.storage.update_history_with_config","text":"update_history_with_config ( * , output : Path | str , symbols : Sequence [ str ], config : Mt5Config | None = None , datasets : set [ Dataset ] | None = None , timeframes : Sequence [ int | str ] | None = None , flags : int | str = \"ALL\" , lookback_hours : float = 24.0 , date_to : datetime | str | None = None , deduplicate : bool = True , create_rate_views : bool = True , with_views : bool = False , include_account_events : bool = True , ) -> None Incrementally append MT5 history, opening and closing the MT5 connection. Convenience wrapper around :func: update_history for standalone use. Source code in mt5cli/sdk.py 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 def update_history_with_config ( # noqa: PLR0913 * , output : Path | str , symbols : Sequence [ str ], config : Mt5Config | None = None , datasets : set [ Dataset ] | None = None , timeframes : Sequence [ int | str ] | None = None , flags : int | str = \"ALL\" , lookback_hours : float = 24.0 , date_to : datetime | str | None = None , deduplicate : bool = True , create_rate_views : bool = True , with_views : bool = False , include_account_events : bool = True , ) -> None : \"\"\"Incrementally append MT5 history, opening and closing the MT5 connection. Convenience wrapper around :func:`update_history` for standalone use. \"\"\" request = _resolve_update_history_request ( output = output , symbols = symbols , datasets = datasets , timeframes = timeframes , flags = flags , lookback_hours = lookback_hours , date_to = date_to , ) if request is None : return mt5_config = config or build_config () with connected_client ( mt5_config ) as client : update_history ( client = client , output = output , symbols = symbols , datasets = datasets , timeframes = timeframes , flags = flags , lookback_hours = lookback_hours , date_to = date_to , deduplicate = deduplicate , create_rate_views = create_rate_views , with_views = with_views , include_account_events = include_account_events , )","title":"update_history_with_config"},{"location":"api/trading/","text":"Trading Module \u00b6 mt5cli.trading \u00b6 Trading-capable MetaTrader 5 session helpers and operational utilities. ExecutionStatus module-attribute \u00b6 ExecutionStatus = Literal [ \"executed\" , \"dry_run\" , \"skipped\" , \"failed\" ] OrderFillingMode module-attribute \u00b6 OrderFillingMode = Literal [ 'IOC' , 'FOK' , 'RETURN' ] OrderSide module-attribute \u00b6 OrderSide = Literal [ 'BUY' , 'SELL' ] OrderTimeMode module-attribute \u00b6 OrderTimeMode = Literal [ \"GTC\" , \"DAY\" , \"SPECIFIED\" , \"SPECIFIED_DAY\" ] POSITION_COLUMNS module-attribute \u00b6 POSITION_COLUMNS = ( \"ticket\" , \"time\" , \"symbol\" , \"type\" , \"volume\" , \"price_open\" , \"sl\" , \"tp\" , \"price_current\" , \"profit\" , \"swap\" , \"comment\" , ) PositionSide module-attribute \u00b6 PositionSide = Literal [ 'long' , 'short' ] __all__ module-attribute \u00b6 __all__ = [ \"POSITION_COLUMNS\" , \"ExecutionStatus\" , \"MarginVolume\" , \"OrderExecutionResult\" , \"OrderFillingMode\" , \"OrderLimits\" , \"OrderSide\" , \"OrderTimeMode\" , \"PositionSide\" , \"calculate_account_projected_margin_ratio\" , \"calculate_margin_and_volume\" , \"calculate_new_position_margin_ratio\" , \"calculate_positions_margin\" , \"calculate_positions_margin_by_symbol\" , \"calculate_positions_margin_safe\" , \"calculate_projected_margin_ratio\" , \"calculate_spread_ratio\" , \"calculate_symbol_group_margin_ratio\" , \"calculate_trailing_stop_updates\" , \"calculate_volume_by_margin\" , \"close_open_positions\" , \"create_trading_client\" , \"detect_position_side\" , \"determine_order_limits\" , \"ensure_symbol_selected\" , \"estimate_order_margin\" , \"extract_tick_price\" , \"fetch_latest_closed_rates_for_trading_client\" , \"fetch_latest_closed_rates_indexed\" , \"get_account_snapshot\" , \"get_positions_frame\" , \"get_symbol_snapshot\" , \"get_tick_snapshot\" , \"mt5_trading_session\" , \"normalize_order_volume\" , \"place_market_order\" , \"update_sltp_for_open_positions\" , \"update_trailing_stop_loss_for_open_positions\" , ] MarginVolume \u00b6 Bases: TypedDict Affordable volume bounds derived from account margin and symbol constraints. available_margin instance-attribute \u00b6 available_margin : float buy_volume instance-attribute \u00b6 buy_volume : float margin_free instance-attribute \u00b6 margin_free : float sell_volume instance-attribute \u00b6 sell_volume : float trade_margin instance-attribute \u00b6 trade_margin : float volume_max instance-attribute \u00b6 volume_max : float volume_min instance-attribute \u00b6 volume_min : float volume_step instance-attribute \u00b6 volume_step : float OrderExecutionResult \u00b6 Bases: TypedDict Normalized result from market-order and position-management helpers. comment instance-attribute \u00b6 comment : str | None dry_run instance-attribute \u00b6 dry_run : bool order_side instance-attribute \u00b6 order_side : OrderSide request instance-attribute \u00b6 request : dict [ str , object ] response instance-attribute \u00b6 response : dict [ str , object ] | None retcode instance-attribute \u00b6 retcode : int | None status instance-attribute \u00b6 status : ExecutionStatus symbol instance-attribute \u00b6 symbol : str volume instance-attribute \u00b6 volume : float OrderLimits \u00b6 Bases: TypedDict Protective order prices derived from current quotes and ratio parameters. entry instance-attribute \u00b6 entry : float stop_loss instance-attribute \u00b6 stop_loss : float | None take_profit instance-attribute \u00b6 take_profit : float | None calculate_account_projected_margin_ratio \u00b6 calculate_account_projected_margin_ratio ( client : Mt5TradingClient , * , symbol : str | None = None , new_position_side : OrderSide | None = None , new_position_volume : float = 0.0 , ) -> float Return account-wide current plus optional new-position margin over equity. Current exposure comes from the broker account snapshot margin field so unrelated open positions remain in the baseline. Optional projected exposure is added via :func: estimate_order_margin only when a symbol, side, and positive volume are all supplied. Source code in mt5cli/trading.py 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 def calculate_account_projected_margin_ratio ( client : Mt5TradingClient , * , symbol : str | None = None , new_position_side : OrderSide | None = None , new_position_volume : float = 0.0 , ) -> float : \"\"\"Return account-wide current plus optional new-position margin over equity. Current exposure comes from the broker account snapshot ``margin`` field so unrelated open positions remain in the baseline. Optional projected exposure is added via :func:`estimate_order_margin` only when a symbol, side, and positive volume are all supplied. \"\"\" account = get_account_snapshot ( client ) equity = _required_account_number ( account , \"equity\" , allow_zero = False ) margin = _required_account_number ( account , \"margin\" , allow_zero = True ) if symbol is not None and new_position_side is not None and new_position_volume > 0 : margin += estimate_order_margin ( client , symbol , new_position_side , new_position_volume , ) return margin / equity calculate_margin_and_volume \u00b6 calculate_margin_and_volume ( client : Mt5TradingClient , symbol : str , unit_margin_ratio : float , preserved_margin_ratio : float , ) -> MarginVolume Calculate tradable margin and volumes from account free margin. Applies preserved_margin_ratio to keep a reserve off margin_free , then allocates unit_margin_ratio of the remainder as the margin budget for proportional volume sizing on both buy and sell sides. A unit_margin_ratio of 0 requests exactly one minimum valid unit per side when the post-reserve margin can afford it. Parameters: Name Type Description Default client Mt5TradingClient Connected Mt5TradingClient instance. required symbol str Symbol used for minimum-lot margin and volume calculations. required unit_margin_ratio float Fraction of post-reserve margin to allocate per unit. required preserved_margin_ratio float Fraction of margin_free to preserve. required Returns: Type Description MarginVolume Dictionary with margin_free , available_margin , trade_margin , MarginVolume buy_volume , and sell_volume . Negative margin_free values are MarginVolume clamped to 0.0 before sizing. Source code in mt5cli/trading.py 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 def calculate_margin_and_volume ( client : Mt5TradingClient , symbol : str , unit_margin_ratio : float , preserved_margin_ratio : float , ) -> MarginVolume : \"\"\"Calculate tradable margin and volumes from account free margin. Applies ``preserved_margin_ratio`` to keep a reserve off ``margin_free``, then allocates ``unit_margin_ratio`` of the remainder as the margin budget for proportional volume sizing on both buy and sell sides. A ``unit_margin_ratio`` of ``0`` requests exactly one minimum valid unit per side when the post-reserve margin can afford it. Args: client: Connected ``Mt5TradingClient`` instance. symbol: Symbol used for minimum-lot margin and volume calculations. unit_margin_ratio: Fraction of post-reserve margin to allocate per unit. preserved_margin_ratio: Fraction of ``margin_free`` to preserve. Returns: Dictionary with ``margin_free``, ``available_margin``, ``trade_margin``, ``buy_volume``, and ``sell_volume``. Negative ``margin_free`` values are clamped to ``0.0`` before sizing. \"\"\" _require_unit_ratio ( unit_margin_ratio , \"unit_margin_ratio\" ) _require_unit_ratio ( preserved_margin_ratio , \"preserved_margin_ratio\" ) account = client . account_info_as_dict () margin_free = max ( 0.0 , float ( account . get ( \"margin_free\" ) or 0.0 )) available_margin = margin_free * ( 1.0 - preserved_margin_ratio ) trade_margin = available_margin * unit_margin_ratio if unit_margin_ratio == 0 : buy_volume = _calculate_min_volume_if_affordable ( client , symbol , available_margin , \"BUY\" , ) sell_volume = _calculate_min_volume_if_affordable ( client , symbol , available_margin , \"SELL\" , ) else : buy_volume = calculate_volume_by_margin ( client , symbol , trade_margin , \"BUY\" ) sell_volume = calculate_volume_by_margin ( client , symbol , trade_margin , \"SELL\" ) try : symbol_info = get_symbol_snapshot ( client , symbol ) volume_min = float ( symbol_info . get ( \"volume_min\" ) or 0.0 ) volume_max = float ( symbol_info . get ( \"volume_max\" ) or 0.0 ) volume_step = float ( symbol_info . get ( \"volume_step\" ) or 0.0 ) except AttributeError : volume_min = volume_max = volume_step = 0.0 return { \"margin_free\" : margin_free , \"available_margin\" : available_margin , \"trade_margin\" : trade_margin , \"buy_volume\" : float ( buy_volume ), \"sell_volume\" : float ( sell_volume ), \"volume_min\" : volume_min , \"volume_max\" : volume_max , \"volume_step\" : volume_step , } calculate_new_position_margin_ratio \u00b6 calculate_new_position_margin_ratio ( client : Mt5TradingClient , * , symbol : str , new_position_side : OrderSide | None = None , new_position_volume : float = 0.0 , ) -> float Return total margin/equity ratio after an optional hypothetical position. Raises: Type Description Mt5TradingError If equity or required tick data is invalid. Source code in mt5cli/trading.py 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 def calculate_new_position_margin_ratio ( client : Mt5TradingClient , * , symbol : str , new_position_side : OrderSide | None = None , new_position_volume : float = 0.0 , ) -> float : \"\"\"Return total margin/equity ratio after an optional hypothetical position. Raises: Mt5TradingError: If equity or required tick data is invalid. \"\"\" account = get_account_snapshot ( client ) equity = float ( account . get ( \"equity\" ) or 0.0 ) if equity <= 0 : msg = \"Account equity must be positive to calculate margin ratio.\" raise Mt5TradingError ( msg ) margin = float ( account . get ( \"margin\" ) or 0.0 ) if new_position_side is not None and new_position_volume > 0 : side = _normalize_order_side ( new_position_side ) price = extract_tick_price ( get_tick_snapshot ( client , symbol ), \"ask\" if side == \"BUY\" else \"bid\" ) if price is None : msg = f \"Tick price is unavailable for { symbol !r} .\" raise Mt5TradingError ( msg ) order_type = ( client . mt5 . ORDER_TYPE_BUY if side == \"BUY\" else client . mt5 . ORDER_TYPE_SELL ) margin += float ( client . order_calc_margin ( order_type , symbol , new_position_volume , price ), ) return margin / equity calculate_positions_margin \u00b6 calculate_positions_margin ( client : Mt5TradingClient , * , symbols : Sequence [ str ] | None = None , ) -> float Return the sum of estimated current margin for open positions. Parameters: Name Type Description Default client Mt5TradingClient Connected Mt5TradingClient instance. required symbols Sequence [ str ] | None Optional symbol filter. When omitted, all open positions are included. None Returns: Type Description float Total estimated margin, or 0.0 when no matching positions exist. Source code in mt5cli/trading.py 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 def calculate_positions_margin ( client : Mt5TradingClient , * , symbols : Sequence [ str ] | None = None , ) -> float : \"\"\"Return the sum of estimated current margin for open positions. Args: client: Connected ``Mt5TradingClient`` instance. symbols: Optional symbol filter. When omitted, all open positions are included. Returns: Total estimated margin, or ``0.0`` when no matching positions exist. \"\"\" frame = get_positions_frame ( client ) if frame . empty or \"symbol\" not in frame . columns : return 0.0 if symbols is not None : frame = frame [ frame [ \"symbol\" ] . isin ( list ( symbols ))] if frame . empty : return 0.0 grouped_volumes : dict [ tuple [ str , OrderSide ], float ] = {} for _ , row in frame . iterrows (): symbol = row . get ( \"symbol\" ) if not isinstance ( symbol , str ) or not symbol : continue volume = row . get ( \"volume\" ) if not _is_positive_finite_number ( volume ): continue order_side = _order_side_from_position_type ( client , row . get ( \"type\" )) if order_side is None : continue key = ( symbol , order_side ) finite_volume = float ( cast ( \"float | int\" , volume )) grouped_volumes [ key ] = grouped_volumes . get ( key , 0.0 ) + finite_volume total = 0.0 for ( symbol , order_side ), volume in grouped_volumes . items (): total += estimate_order_margin ( client , symbol , order_side , volume ) return total calculate_positions_margin_by_symbol \u00b6 calculate_positions_margin_by_symbol ( client : Mt5TradingClient , * , symbols : Sequence [ str ], suppress_errors : bool = True , ) -> dict [ str , float ] Return per-symbol estimated margin for open positions. Computes margin for each unique input symbol independently using the strict :func: calculate_positions_margin helper. Duplicates are deduplicated in first-seen order. Parameters: Name Type Description Default client Mt5TradingClient Connected Mt5TradingClient instance. required symbols Sequence [ str ] Symbols to compute margin for. required suppress_errors bool When True , log and skip symbols that raise Mt5TradingError , Mt5RuntimeError , or AttributeError . When False , re-raise the first failure. True Returns: Type Description dict [ str , float ] Mapping of symbol to margin total in first-seen unique-symbol order. dict [ str , float ] Returns an empty dict when symbols is empty or all symbols fail dict [ str , float ] with suppress_errors=True . Raises: Type Description Mt5TradingError When a symbol raises Mt5TradingError and suppress_errors=False . Mt5RuntimeError When a symbol raises Mt5RuntimeError and suppress_errors=False . AttributeError When a symbol raises AttributeError and suppress_errors=False . Source code in mt5cli/trading.py 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 def calculate_positions_margin_by_symbol ( client : Mt5TradingClient , * , symbols : Sequence [ str ], suppress_errors : bool = True , ) -> dict [ str , float ]: \"\"\"Return per-symbol estimated margin for open positions. Computes margin for each unique input symbol independently using the strict :func:`calculate_positions_margin` helper. Duplicates are deduplicated in first-seen order. Args: client: Connected ``Mt5TradingClient`` instance. symbols: Symbols to compute margin for. suppress_errors: When ``True``, log and skip symbols that raise ``Mt5TradingError``, ``Mt5RuntimeError``, or ``AttributeError``. When ``False``, re-raise the first failure. Returns: Mapping of symbol to margin total in first-seen unique-symbol order. Returns an empty dict when ``symbols`` is empty or all symbols fail with ``suppress_errors=True``. Raises: Mt5TradingError: When a symbol raises ``Mt5TradingError`` and ``suppress_errors=False``. Mt5RuntimeError: When a symbol raises ``Mt5RuntimeError`` and ``suppress_errors=False``. AttributeError: When a symbol raises ``AttributeError`` and ``suppress_errors=False``. \"\"\" result : dict [ str , float ] = {} for symbol in dict . fromkeys ( symbols ): try : result [ symbol ] = calculate_positions_margin ( client , symbols = [ symbol ]) except ( Mt5TradingError , Mt5RuntimeError , AttributeError ) as exc : if not suppress_errors : raise _logger . warning ( \"Skipping margin for %r : %s \" , symbol , exc ) return result calculate_positions_margin_safe \u00b6 calculate_positions_margin_safe ( client : Mt5TradingClient , * , symbols : Sequence [ str ] ) -> float Return the total estimated margin for open positions across symbols. Internally calls :func: calculate_positions_margin_by_symbol with suppress_errors=True . Failed symbols are silently skipped. Parameters: Name Type Description Default client Mt5TradingClient Connected Mt5TradingClient instance. required symbols Sequence [ str ] Symbols to include. required Returns: Type Description float Sum of per-symbol margins; 0.0 when no symbols or all fail. Source code in mt5cli/trading.py 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 def calculate_positions_margin_safe ( client : Mt5TradingClient , * , symbols : Sequence [ str ], ) -> float : \"\"\"Return the total estimated margin for open positions across symbols. Internally calls :func:`calculate_positions_margin_by_symbol` with ``suppress_errors=True``. Failed symbols are silently skipped. Args: client: Connected ``Mt5TradingClient`` instance. symbols: Symbols to include. Returns: Sum of per-symbol margins; ``0.0`` when no symbols or all fail. \"\"\" return sum ( calculate_positions_margin_by_symbol ( client , symbols = symbols ) . values (), 0.0 , ) calculate_projected_margin_ratio \u00b6 calculate_projected_margin_ratio ( client : Mt5TradingClient , * , symbol : str , new_position_side : OrderSide | None = None , new_position_volume : float = 0.0 , ) -> float Return estimated current plus optional new-position margin over equity. Current exposure is estimated from open positions with :func: calculate_positions_margin . Optional projected exposure is added via :func: estimate_order_margin . Thresholds and guard actions are intentionally left to downstream applications. Account equity, position margin, and optional projected margin errors from the composed MT5 helpers propagate to the caller. Source code in mt5cli/trading.py 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 def calculate_projected_margin_ratio ( client : Mt5TradingClient , * , symbol : str , new_position_side : OrderSide | None = None , new_position_volume : float = 0.0 , ) -> float : \"\"\"Return estimated current plus optional new-position margin over equity. Current exposure is estimated from open positions with :func:`calculate_positions_margin`. Optional projected exposure is added via :func:`estimate_order_margin`. Thresholds and guard actions are intentionally left to downstream applications. Account equity, position margin, and optional projected margin errors from the composed MT5 helpers propagate to the caller. \"\"\" equity = _account_equity ( client ) margin = calculate_positions_margin ( client , symbols = [ symbol ]) if new_position_side is not None and new_position_volume > 0 : margin += estimate_order_margin ( client , symbol , new_position_side , new_position_volume , ) return margin / equity calculate_spread_ratio \u00b6 calculate_spread_ratio ( client : Mt5TradingClient , symbol : str ) -> float Return (ask - bid) / ((ask + bid) / 2) for the latest tick. Raises: Type Description Mt5TradingError If bid or ask is unavailable. Source code in mt5cli/trading.py 786 787 788 789 790 791 792 793 794 795 796 797 798 def calculate_spread_ratio ( client : Mt5TradingClient , symbol : str ) -> float : \"\"\"Return ``(ask - bid) / ((ask + bid) / 2)`` for the latest tick. Raises: Mt5TradingError: If bid or ask is unavailable. \"\"\" tick = get_tick_snapshot ( client , symbol ) bid = extract_tick_price ( tick , \"bid\" ) ask = extract_tick_price ( tick , \"ask\" ) if bid is None or ask is None : msg = f \"Tick bid/ask is unavailable for { symbol !r} .\" raise Mt5TradingError ( msg ) return ( ask - bid ) / (( ask + bid ) / 2.0 ) calculate_symbol_group_margin_ratio \u00b6 calculate_symbol_group_margin_ratio ( client : Mt5TradingClient , * , symbols : Sequence [ str ], new_symbol : str | None = None , new_position_side : OrderSide | None = None , new_position_volume : float = 0.0 , suppress_errors : bool = True , ) -> float Return estimated symbol-group margin over account equity. Per-symbol current exposure is summed with :func: calculate_positions_margin_by_symbol . When new_symbol is inside the input symbol group, optional projected order margin is added for that symbol. Invalid equity always raises to fail closed. Raises: Type Description AttributeError When symbol margin lookup or projected margin lookup fails and suppress_errors is False . Mt5RuntimeError When symbol margin lookup or projected margin lookup fails and suppress_errors is False . Mt5TradingError When account equity is invalid, or when symbol margin lookup or projected margin lookup fails and suppress_errors is False . Source code in mt5cli/trading.py 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 def calculate_symbol_group_margin_ratio ( client : Mt5TradingClient , * , symbols : Sequence [ str ], new_symbol : str | None = None , new_position_side : OrderSide | None = None , new_position_volume : float = 0.0 , suppress_errors : bool = True , ) -> float : \"\"\"Return estimated symbol-group margin over account equity. Per-symbol current exposure is summed with :func:`calculate_positions_margin_by_symbol`. When ``new_symbol`` is inside the input symbol group, optional projected order margin is added for that symbol. Invalid equity always raises to fail closed. Raises: AttributeError: When symbol margin lookup or projected margin lookup fails and ``suppress_errors`` is ``False``. Mt5RuntimeError: When symbol margin lookup or projected margin lookup fails and ``suppress_errors`` is ``False``. Mt5TradingError: When account equity is invalid, or when symbol margin lookup or projected margin lookup fails and ``suppress_errors`` is ``False``. \"\"\" equity = _account_equity ( client ) unique_symbols = list ( dict . fromkeys ( symbols )) margin = sum ( calculate_positions_margin_by_symbol ( client , symbols = unique_symbols , suppress_errors = suppress_errors , ) . values (), 0.0 , ) if ( new_symbol in unique_symbols and new_position_side is not None and new_position_volume > 0 ): try : margin += estimate_order_margin ( client , new_symbol , new_position_side , new_position_volume , ) except ( Mt5TradingError , Mt5RuntimeError , AttributeError ): if not suppress_errors : raise _logger . warning ( \"Skipping projected margin for %r .\" , new_symbol ) return margin / equity calculate_trailing_stop_updates \u00b6 calculate_trailing_stop_updates ( client : Mt5TradingClient , * , symbol : str , trailing_stop_ratio : float , ) -> dict [ int , float ] Return per-ticket trailing stop-loss updates for open symbol positions. Buy positions trail from bid using bid * (1 - trailing_stop_ratio) . Sell positions trail from ask using ask * (1 + trailing_stop_ratio) . Existing stop losses are preserved when they are already more favorable. Missing symbol metadata returns an empty update map. Positions with a missing side-specific tick price are skipped. Source code in mt5cli/trading.py 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 def calculate_trailing_stop_updates ( client : Mt5TradingClient , * , symbol : str , trailing_stop_ratio : float , ) -> dict [ int , float ]: \"\"\"Return per-ticket trailing stop-loss updates for open symbol positions. Buy positions trail from bid using ``bid * (1 - trailing_stop_ratio)``. Sell positions trail from ask using ``ask * (1 + trailing_stop_ratio)``. Existing stop losses are preserved when they are already more favorable. Missing symbol metadata returns an empty update map. Positions with a missing side-specific tick price are skipped. \"\"\" _require_protective_ratio ( trailing_stop_ratio , \"trailing_stop_ratio\" ) positions = get_positions_frame ( client , symbol = symbol ) if positions . empty : return {} tick = get_tick_snapshot ( client , symbol ) bid = extract_tick_price ( tick , \"bid\" ) ask = extract_tick_price ( tick , \"ask\" ) digits = _symbol_digits ( client , symbol ) if digits is None : return {} updates : dict [ int , float ] = {} for row in positions . to_dict ( \"records\" ): ticket = _position_ticket ( row . get ( \"ticket\" )) if ticket is None : continue next_sl = _trailing_stop_loss ( client , position_type = row . get ( \"type\" ), current_sl = _current_stop_loss ( row . get ( \"sl\" )), bid = bid , ask = ask , digits = digits , trailing_stop_ratio = trailing_stop_ratio , ) if next_sl is None : continue updates [ ticket ] = next_sl return updates calculate_volume_by_margin \u00b6 calculate_volume_by_margin ( client : Mt5TradingClient , symbol : str , available_margin : float , order_side : OrderSide , ) -> float Calculate max normalized volume affordable for one side. Returns: Type Description float Largest stepped volume whose actual margin (from order_calc_margin ) float fits within available_margin , rounded down to symbol volume float constraints; 0.0 when no affordable step exists. Raises: Type Description Mt5TradingError If symbol volume constraints or tick data are invalid. Source code in mt5cli/trading.py 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 def calculate_volume_by_margin ( client : Mt5TradingClient , symbol : str , available_margin : float , order_side : OrderSide , ) -> float : \"\"\"Calculate max normalized volume affordable for one side. Returns: Largest stepped volume whose actual margin (from ``order_calc_margin``) fits within ``available_margin``, rounded down to symbol volume constraints; ``0.0`` when no affordable step exists. Raises: Mt5TradingError: If symbol volume constraints or tick data are invalid. \"\"\" if available_margin <= 0 : return 0.0 symbol_info = get_symbol_snapshot ( client , symbol ) volume_min = float ( symbol_info . get ( \"volume_min\" ) or 0.0 ) volume_max = float ( symbol_info . get ( \"volume_max\" ) or 0.0 ) volume_step = float ( symbol_info . get ( \"volume_step\" ) or volume_min or 0.0 ) if volume_min <= 0 or volume_step <= 0 : msg = f \"Invalid volume constraints for { symbol !r} .\" raise Mt5TradingError ( msg ) side = _normalize_order_side ( order_side ) price = extract_tick_price ( get_tick_snapshot ( client , symbol ), \"ask\" if side == \"BUY\" else \"bid\" ) if price is None : msg = f \"Tick price is unavailable for { symbol !r} .\" raise Mt5TradingError ( msg ) order_type = ( client . mt5 . ORDER_TYPE_BUY if side == \"BUY\" else client . mt5 . ORDER_TYPE_SELL ) min_margin = float ( client . order_calc_margin ( order_type , symbol , volume_min , price )) if min_margin <= 0 or min_margin > available_margin : return 0.0 lo = 0 hi = int ( max ( 0 , floor ( ( ( min ( available_margin / min_margin * volume_min , volume_max ) if volume_max > 0 else available_margin / min_margin * volume_min ) - volume_min ) / volume_step + 1e-12 ), ) ) best = - 1 while lo <= hi : mid = ( lo + hi ) // 2 normalized = round ( volume_min + mid * volume_step , 10 ) actual = float ( client . order_calc_margin ( order_type , symbol , normalized , price )) if actual > 0 and actual <= available_margin : best = mid lo = mid + 1 else : hi = mid - 1 return round ( volume_min + best * volume_step , 10 ) if best >= 0 else 0.0 close_open_positions \u00b6 close_open_positions ( client : Mt5TradingClient , * , symbols : str | list [ str ] | None = None , tickets : list [ int ] | None = None , dry_run : bool = False , ) -> list [ OrderExecutionResult ] Close matching open positions. Returns: Type Description list [ OrderExecutionResult ] Normalized execution results for matching positions. Source code in mt5cli/trading.py 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 def close_open_positions ( client : Mt5TradingClient , * , symbols : str | list [ str ] | None = None , tickets : list [ int ] | None = None , dry_run : bool = False , ) -> list [ OrderExecutionResult ]: \"\"\"Close matching open positions. Returns: Normalized execution results for matching positions. \"\"\" positions = _filter_positions ( get_positions_frame ( client ), symbols = symbols , tickets = tickets , ) results : list [ OrderExecutionResult ] = [] for row in positions . to_dict ( \"records\" ): pos_type = row [ \"type\" ] side : OrderSide = \"SELL\" if pos_type == client . mt5 . POSITION_TYPE_BUY else \"BUY\" result = place_market_order ( client , symbol = str ( row [ \"symbol\" ]), volume = float ( row [ \"volume\" ]), order_side = side , position = int ( row [ \"ticket\" ]), dry_run = dry_run , ) results . append ( result ) return results create_trading_client \u00b6 create_trading_client ( * , config : Mt5Config | None = None , login : int | str | None = None , password : str | None = None , server : str | None = None , path : str | None = None , timeout : int | None = None , retry_count : int = 0 , ) -> Mt5TradingClient Return an initialized and logged-in trading client. Source code in mt5cli/trading.py 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 def create_trading_client ( * , config : Mt5Config | None = None , login : int | str | None = None , password : str | None = None , server : str | None = None , path : str | None = None , timeout : int | None = None , retry_count : int = 0 , ) -> Mt5TradingClient : \"\"\"Return an initialized and logged-in trading client.\"\"\" mt5_config = _resolve_config ( config = config , login = login , password = password , server = server , path = path , timeout = timeout , ) client = Mt5TradingClient ( config = mt5_config , retry_count = retry_count ) try : client . initialize_and_login_mt5 () except Exception : client . shutdown () raise return client detect_position_side \u00b6 detect_position_side ( client : Mt5TradingClient , symbol : str ) -> PositionSide | None Detect the net open position side for a symbol. Parameters: Name Type Description Default client Mt5TradingClient Connected Mt5TradingClient instance. required symbol str Symbol to inspect. required Returns: Type Description PositionSide | None \"long\" when there are buy positions and no sell positions, PositionSide | None \"short\" when there are sell positions and no buy positions, or PositionSide | None None when no positions or mixed exposure exists. Source code in mt5cli/trading.py 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 def detect_position_side ( client : Mt5TradingClient , symbol : str , ) -> PositionSide | None : \"\"\"Detect the net open position side for a symbol. Args: client: Connected ``Mt5TradingClient`` instance. symbol: Symbol to inspect. Returns: ``\"long\"`` when there are buy positions and no sell positions, ``\"short\"`` when there are sell positions and no buy positions, or ``None`` when no positions or mixed exposure exists. \"\"\" positions = get_positions_frame ( client , symbol = symbol ) if positions . empty : return None buy_type = client . mt5 . POSITION_TYPE_BUY sell_type = client . mt5 . POSITION_TYPE_SELL buy_volume = _sum_position_volume ( positions , buy_type ) sell_volume = _sum_position_volume ( positions , sell_type ) if buy_volume > 0 and sell_volume == 0 : return \"long\" if sell_volume > 0 and buy_volume == 0 : return \"short\" return None determine_order_limits \u00b6 determine_order_limits ( client : Mt5TradingClient , symbol : str , side : PositionSide | str , stop_loss_limit_ratio : float | None = None , take_profit_limit_ratio : float | None = None , ) -> OrderLimits Derive entry and protective order prices from current market quotes. Parameters: Name Type Description Default client Mt5TradingClient Connected Mt5TradingClient instance. required symbol str Symbol used for the quote lookup. required side PositionSide | str Position side as \"long\" / \"short\" ( \"buy\" / \"sell\" aliases are accepted). required stop_loss_limit_ratio float | None Relative distance from entry for stop loss in [0, 1) . A value of 0 omits the stop loss. None take_profit_limit_ratio float | None Relative distance from entry for take profit in [0, 1) . A value of 0 omits the take profit. None Returns: Type Description OrderLimits Dictionary with entry , stop_loss , and take_profit keys. OrderLimits Omitted protective levels are returned as None . Raises: Type Description Mt5TradingError If required tick data is invalid or computed SL/TP prices violate available trade_stops_level pre-validation. Source code in mt5cli/trading.py 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 def determine_order_limits ( client : Mt5TradingClient , symbol : str , side : PositionSide | str , stop_loss_limit_ratio : float | None = None , take_profit_limit_ratio : float | None = None , ) -> OrderLimits : \"\"\"Derive entry and protective order prices from current market quotes. Args: client: Connected ``Mt5TradingClient`` instance. symbol: Symbol used for the quote lookup. side: Position side as ``\"long\"``/``\"short\"`` (``\"buy\"``/``\"sell\"`` aliases are accepted). stop_loss_limit_ratio: Relative distance from entry for stop loss in ``[0, 1)``. A value of ``0`` omits the stop loss. take_profit_limit_ratio: Relative distance from entry for take profit in ``[0, 1)``. A value of ``0`` omits the take profit. Returns: Dictionary with ``entry``, ``stop_loss``, and ``take_profit`` keys. Omitted protective levels are returned as ``None``. Raises: Mt5TradingError: If required tick data is invalid or computed SL/TP prices violate available ``trade_stops_level`` pre-validation. \"\"\" stop_loss_ratio = stop_loss_limit_ratio or 0.0 take_profit_ratio = take_profit_limit_ratio or 0.0 _require_protective_ratio ( stop_loss_ratio , \"stop_loss_limit_ratio\" ) _require_protective_ratio ( take_profit_ratio , \"take_profit_limit_ratio\" ) normalized_side = _position_side_from_order_side ( side ) tick = get_tick_snapshot ( client , symbol ) entry_key = \"ask\" if normalized_side == \"long\" else \"bid\" entry = extract_tick_price ( tick , entry_key ) if entry is None : msg = f \"Tick price is unavailable for { symbol !r} .\" raise Mt5TradingError ( msg ) try : symbol_info = get_symbol_snapshot ( client , symbol ) except ( AttributeError , KeyError , TypeError , ValueError ): symbol_info = {} try : digits = int ( symbol_info . get ( \"digits\" ) or 8 ) except ( TypeError , ValueError ): digits = 8 min_distance = _minimum_stop_distance ( symbol_info ) stop_loss : float | None = None if stop_loss_ratio > 0 : if normalized_side == \"long\" : stop_loss = entry * ( 1.0 - stop_loss_ratio ) else : stop_loss = entry * ( 1.0 + stop_loss_ratio ) stop_loss = round ( stop_loss , digits ) take_profit : float | None = None if take_profit_ratio > 0 : if normalized_side == \"long\" : take_profit = entry * ( 1.0 + take_profit_ratio ) else : take_profit = entry * ( 1.0 - take_profit_ratio ) take_profit = round ( take_profit , digits ) _validate_protective_prices ( symbol = symbol , side = normalized_side , entry = entry , stop_loss = stop_loss , take_profit = take_profit , min_distance = min_distance , ) return { \"entry\" : entry , \"stop_loss\" : stop_loss , \"take_profit\" : take_profit , } ensure_symbol_selected \u00b6 ensure_symbol_selected ( client : Mt5TradingClient , symbol : str ) -> None Ensure a symbol is visible in Market Watch before sending orders. Parameters: Name Type Description Default client Mt5TradingClient Connected Mt5TradingClient instance. required symbol str Symbol to select. required Raises: Type Description Mt5TradingError If the symbol cannot be selected in Market Watch or symbol_select is unavailable on the client. Source code in mt5cli/trading.py 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 def ensure_symbol_selected ( client : Mt5TradingClient , symbol : str ) -> None : \"\"\"Ensure a symbol is visible in Market Watch before sending orders. Args: client: Connected ``Mt5TradingClient`` instance. symbol: Symbol to select. Raises: Mt5TradingError: If the symbol cannot be selected in Market Watch or ``symbol_select`` is unavailable on the client. \"\"\" snapshot = get_symbol_snapshot ( client , symbol ) if snapshot . get ( \"visible\" ): return select = getattr ( client , \"symbol_select\" , None ) if not callable ( select ): msg = \"MT5 client is missing required method: symbol_select\" raise Mt5TradingError ( msg ) if select ( symbol , enable = True ): return last_error = getattr ( client , \"last_error\" , None ) detail = f \" ( { last_error () } )\" if callable ( last_error ) else \"\" msg = f \"Failed to select symbol { symbol !r} in Market Watch { detail } .\" raise Mt5TradingError ( msg ) estimate_order_margin \u00b6 estimate_order_margin ( client : Mt5TradingClient , symbol : str , order_side : OrderSide | str , volume : float , ) -> float Estimate required margin for one order at the current market price. Returns: Type Description float Positive finite margin required for the order at the current quote. Raises: Type Description Mt5TradingError If volume, tick data, or margin estimation is invalid. Source code in mt5cli/trading.py 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 def estimate_order_margin ( client : Mt5TradingClient , symbol : str , order_side : OrderSide | str , volume : float , ) -> float : \"\"\"Estimate required margin for one order at the current market price. Returns: Positive finite margin required for the order at the current quote. Raises: Mt5TradingError: If volume, tick data, or margin estimation is invalid. \"\"\" if not _is_positive_finite_number ( volume ): msg = \"Volume must be a positive finite number to estimate order margin.\" raise Mt5TradingError ( msg ) side = _normalize_order_side ( order_side ) tick = get_tick_snapshot ( client , symbol ) price = extract_tick_price ( tick , \"ask\" if side == \"BUY\" else \"bid\" ) if price is None : msg = f \"Tick price is unavailable for { symbol !r} .\" raise Mt5TradingError ( msg ) order_type = ( client . mt5 . ORDER_TYPE_BUY if side == \"BUY\" else client . mt5 . ORDER_TYPE_SELL ) raw_margin = client . order_calc_margin ( order_type , symbol , volume , price ) try : margin = float ( raw_margin ) except ( TypeError , ValueError ) as exc : msg = f \"Margin estimate is invalid for { symbol !r} .\" raise Mt5TradingError ( msg ) from exc if margin <= 0 or not isfinite ( margin ): msg = f \"Margin estimate is invalid for { symbol !r} .\" raise Mt5TradingError ( msg ) return margin extract_tick_price \u00b6 extract_tick_price ( tick : Mapping [ str , object ], key : str ) -> float | None Return a positive finite float from tick[key], or None if invalid. Accepts int, float, or numeric string values. Returns None when the key is missing, the value is None, non-numeric, NaN, infinite, zero, or negative. Booleans are treated as non-numeric and return None. Source code in mt5cli/trading.py 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 def extract_tick_price ( tick : Mapping [ str , object ], key : str ) -> float | None : \"\"\"Return a positive finite float from tick[key], or None if invalid. Accepts int, float, or numeric string values. Returns None when the key is missing, the value is None, non-numeric, NaN, infinite, zero, or negative. Booleans are treated as non-numeric and return None. \"\"\" value = tick . get ( key ) if value is None or isinstance ( value , bool ): return None if isinstance ( value , int | float ): price = float ( value ) elif isinstance ( value , str ): try : price = float ( value ) except ValueError : return None else : return None if not isfinite ( price ) or price <= 0 : return None return price fetch_latest_closed_rates_for_trading_client \u00b6 fetch_latest_closed_rates_for_trading_client ( client : Mt5TradingClient , * , symbol : str , granularity : str , count : int , ) -> DataFrame Fetch the latest closed bars from a connected trading client. Returns: Type Description DataFrame Up to count closed bars ordered oldest to newest. Raises: Type Description ValueError If count is not positive, rate data is empty or malformed, or the time column is missing. Mt5TradingError If the trading client cannot fetch rate data. Source code in mt5cli/trading.py 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 def fetch_latest_closed_rates_for_trading_client ( client : Mt5TradingClient , * , symbol : str , granularity : str , count : int , ) -> pd . DataFrame : \"\"\"Fetch the latest closed bars from a connected trading client. Returns: Up to ``count`` closed bars ordered oldest to newest. Raises: ValueError: If ``count`` is not positive, rate data is empty or malformed, or the ``time`` column is missing. Mt5TradingError: If the trading client cannot fetch rate data. \"\"\" if count <= 0 : msg = \"count must be positive.\" raise ValueError ( msg ) fetch_method = getattr ( client , \"fetch_latest_rates_as_df\" , None ) if not callable ( fetch_method ): msg = \"MT5 trading client cannot fetch rate data.\" raise Mt5TradingError ( msg ) fetched = fetch_method ( symbol , granularity , count + 1 ) if not isinstance ( fetched , pd . DataFrame ): msg = ( f \"Malformed rate data for { symbol !r} at granularity { granularity !r} : \" \"expected a DataFrame.\" ) raise ValueError ( msg ) # noqa: TRY004 frame = fetched frame = _ensure_rate_time_column ( frame ) if \"time\" not in frame . columns : msg = f \"Rate data is missing a time column for { symbol !r} .\" raise ValueError ( msg ) closed = drop_forming_rate_bar ( frame ) if closed . empty : msg = ( f \"Rate data is empty for { symbol !r} at granularity { granularity !r} \" f \"with count { count } .\" ) raise ValueError ( msg ) return closed . tail ( count ) . reset_index ( drop = True ) fetch_latest_closed_rates_indexed \u00b6 fetch_latest_closed_rates_indexed ( client : Mt5TradingClient , * , symbol : str , granularity : str , count : int , ) -> DataFrame Fetch the latest closed bars with a UTC DatetimeIndex from a trading client. Internally reuses :func: fetch_latest_closed_rates_for_trading_client for closed-bar detection and validation, then converts the time column to a UTC-aware :class: ~pandas.DatetimeIndex named \"time\" and drops the original column. Intended for downstream time-series consumers that require a datetime index rather than a time column. Parameters: Name Type Description Default client Mt5TradingClient Connected trading client with rate-fetch capability. required symbol str Symbol name. required granularity str Timeframe string (for example \"M1\" , \"H1\" ). required count int Maximum number of closed bars to return. required Returns: Type Description DataFrame Up to count closed bars ordered oldest to newest, with a DataFrame UTC-aware DatetimeIndex named \"time\" . The original time DataFrame column is dropped. Raises: Type Description ValueError If count is not positive, rate data is empty or malformed, the time column is missing, or timestamp data is invalid or unparseable. Source code in mt5cli/trading.py 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 def fetch_latest_closed_rates_indexed ( client : Mt5TradingClient , * , symbol : str , granularity : str , count : int , ) -> pd . DataFrame : \"\"\"Fetch the latest closed bars with a UTC DatetimeIndex from a trading client. Internally reuses :func:`fetch_latest_closed_rates_for_trading_client` for closed-bar detection and validation, then converts the ``time`` column to a UTC-aware :class:`~pandas.DatetimeIndex` named ``\"time\"`` and drops the original column. Intended for downstream time-series consumers that require a datetime index rather than a ``time`` column. Args: client: Connected trading client with rate-fetch capability. symbol: Symbol name. granularity: Timeframe string (for example ``\"M1\"``, ``\"H1\"``). count: Maximum number of closed bars to return. Returns: Up to ``count`` closed bars ordered oldest to newest, with a UTC-aware ``DatetimeIndex`` named ``\"time\"``. The original ``time`` column is dropped. Raises: ValueError: If ``count`` is not positive, rate data is empty or malformed, the ``time`` column is missing, or timestamp data is invalid or unparseable. \"\"\" frame = fetch_latest_closed_rates_for_trading_client ( client , symbol = symbol , granularity = granularity , count = count , ) if \"time\" not in frame . columns : msg = f \"Rate data is missing a time column for { symbol !r} .\" raise ValueError ( msg ) idx = _rate_time_to_utc ( frame [ \"time\" ], symbol ) idx . name = \"time\" result = frame . drop ( columns = [ \"time\" ]) result . index = idx return result get_account_snapshot \u00b6 get_account_snapshot ( client : Mt5TradingClient , ) -> dict [ str , float | int | str | None ] Return normalized account state with stable keys. Source code in mt5cli/trading.py 569 570 571 572 573 574 575 576 577 def get_account_snapshot ( client : Mt5TradingClient , ) -> dict [ str , float | int | str | None ]: \"\"\"Return normalized account state with stable keys.\"\"\" value = _call_snapshot_method ( client , \"account_info_as_dict\" , \"account_info\" ) return cast ( \"dict[str, float | int | str | None]\" , _snapshot_from_value ( value , _ACCOUNT_SNAPSHOT_FIELDS ), ) get_positions_frame \u00b6 get_positions_frame ( client : Mt5TradingClient , symbol : str | None = None ) -> DataFrame Return open positions as a DataFrame with stable baseline columns. Source code in mt5cli/trading.py 606 607 608 609 610 611 612 613 614 615 def get_positions_frame ( client : Mt5TradingClient , symbol : str | None = None , ) -> pd . DataFrame : \"\"\"Return open positions as a DataFrame with stable baseline columns.\"\"\" frame = client . positions_get_as_df ( symbol = symbol ) for column in POSITION_COLUMNS : if column not in frame . columns : frame [ column ] = pd . Series ( dtype = \"object\" ) return frame get_symbol_snapshot \u00b6 get_symbol_snapshot ( client : Mt5TradingClient , symbol : str ) -> dict [ str , float | int | str | bool | None ] Return normalized symbol metadata required for trading decisions. Source code in mt5cli/trading.py 580 581 582 583 584 585 586 587 588 589 def get_symbol_snapshot ( client : Mt5TradingClient , symbol : str , ) -> dict [ str , float | int | str | bool | None ]: \"\"\"Return normalized symbol metadata required for trading decisions.\"\"\" method = getattr ( client , \"symbol_info_as_dict\" , None ) value = method ( symbol = symbol ) if callable ( method ) else client . symbol_info ( symbol ) snapshot = _snapshot_from_value ( value , _SYMBOL_SNAPSHOT_FIELDS ) snapshot [ \"symbol\" ] = snapshot . get ( \"symbol\" ) or symbol return cast ( \"dict[str, float | int | str | bool | None]\" , snapshot ) get_tick_snapshot \u00b6 get_tick_snapshot ( client : Mt5TradingClient , symbol : str ) -> dict [ str , float | int | None ] Return normalized latest tick data, including bid, ask, and timestamp. Source code in mt5cli/trading.py 592 593 594 595 596 597 598 599 600 601 602 603 def get_tick_snapshot ( client : Mt5TradingClient , symbol : str , ) -> dict [ str , float | int | None ]: \"\"\"Return normalized latest tick data, including bid, ask, and timestamp.\"\"\" method = getattr ( client , \"symbol_info_tick_as_dict\" , None ) value = ( method ( symbol = symbol ) if callable ( method ) else client . symbol_info_tick ( symbol ) ) snapshot = _snapshot_from_value ( value , _TICK_SNAPSHOT_FIELDS ) snapshot [ \"symbol\" ] = snapshot . get ( \"symbol\" ) or symbol return cast ( \"dict[str, float | int | None]\" , snapshot ) mt5_trading_session \u00b6 mt5_trading_session ( config : Mt5Config | None = None , * , login : int | str | None = None , password : str | None = None , server : str | None = None , path : str | None = None , timeout : int | None = None , retry_count : int = 0 , ) -> Iterator [ Mt5TradingClient ] Open a trading-capable MT5 session and always shut down safely. Launches the MetaTrader 5 terminal using Mt5Config.path when set, initializes and logs in via initialize_and_login_mt5() , yields a connected :class: ~pdmt5.Mt5TradingClient , and calls shutdown() on exit even when an error is raised inside the context. Parameters: Name Type Description Default config Mt5Config | None MT5 connection configuration. Defaults to an empty config that attaches to a running terminal. None login int | str | None Optional trading account login. None password str | None Optional trading account password. None server str | None Optional trading server name. None path str | None Optional terminal executable path. None timeout int | None Optional connection timeout in milliseconds. None retry_count int Number of initialization retries passed to Mt5TradingClient . 0 Yields: Type Description Mt5TradingClient Connected Mt5TradingClient bound to the session. Source code in mt5cli/trading.py 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 @contextmanager def mt5_trading_session ( config : Mt5Config | None = None , * , login : int | str | None = None , password : str | None = None , server : str | None = None , path : str | None = None , timeout : int | None = None , retry_count : int = 0 , ) -> Iterator [ Mt5TradingClient ]: \"\"\"Open a trading-capable MT5 session and always shut down safely. Launches the MetaTrader 5 terminal using ``Mt5Config.path`` when set, initializes and logs in via ``initialize_and_login_mt5()``, yields a connected :class:`~pdmt5.Mt5TradingClient`, and calls ``shutdown()`` on exit even when an error is raised inside the context. Args: config: MT5 connection configuration. Defaults to an empty config that attaches to a running terminal. login: Optional trading account login. password: Optional trading account password. server: Optional trading server name. path: Optional terminal executable path. timeout: Optional connection timeout in milliseconds. retry_count: Number of initialization retries passed to ``Mt5TradingClient``. Yields: Connected ``Mt5TradingClient`` bound to the session. \"\"\" client = create_trading_client ( config = config , login = login , password = password , server = server , path = path , timeout = timeout , retry_count = retry_count , ) try : yield client finally : client . shutdown () normalize_order_volume \u00b6 normalize_order_volume ( volume : float , * , volume_min : float , volume_max : float , volume_step : float , ) -> float Normalize a requested order volume to broker volume constraints. Returns: Type Description float Volume floored to the nearest valid broker step from volume_min , float capped at volume_max when finite and positive, and rounded float deterministically. Returns 0.0 when inputs or constraints are float invalid, non-finite, or the capped request is below volume_min . Source code in mt5cli/trading.py 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 def normalize_order_volume ( volume : float , * , volume_min : float , volume_max : float , volume_step : float , ) -> float : \"\"\"Normalize a requested order volume to broker volume constraints. Returns: Volume floored to the nearest valid broker step from ``volume_min``, capped at ``volume_max`` when finite and positive, and rounded deterministically. Returns ``0.0`` when inputs or constraints are invalid, non-finite, or the capped request is below ``volume_min``. \"\"\" if not _is_finite_number ( volume ): return 0.0 if not _is_positive_finite_number ( volume_min ): return 0.0 if not _is_positive_finite_number ( volume_step ): return 0.0 has_volume_cap = _is_positive_finite_number ( volume_max ) capped = min ( volume , volume_max ) if has_volume_cap else volume if capped < volume_min : return 0.0 steps = floor ((( capped - volume_min ) / volume_step ) + 1e-12 ) normalized = volume_min + max ( 0 , steps ) * volume_step if has_volume_cap : normalized = min ( normalized , volume_max ) return round ( normalized , 10 ) place_market_order \u00b6 place_market_order ( client : Mt5TradingClient , * , symbol : str , volume : float , order_side : OrderSide , order_filling_mode : OrderFillingMode = \"IOC\" , order_time_mode : OrderTimeMode = \"GTC\" , sl : float | None = None , tp : float | None = None , position : int | None = None , dry_run : bool = False , ) -> OrderExecutionResult Place one normalized market order or return a dry-run result. pdmt5.Mt5TradingClient.order_send() raises only when MT5 returns no response. When MT5 returns a response with a known non-success retcode, this helper returns status=\"failed\" and keeps the normalized response details for callers to inspect. Returns: Type Description OrderExecutionResult Normalized execution result containing request and response details. Raises: Type Description Mt5TradingError If volume or required tick data is invalid. Source code in mt5cli/trading.py 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 def place_market_order ( client : Mt5TradingClient , * , symbol : str , volume : float , order_side : OrderSide , order_filling_mode : OrderFillingMode = \"IOC\" , order_time_mode : OrderTimeMode = \"GTC\" , sl : float | None = None , tp : float | None = None , position : int | None = None , dry_run : bool = False , ) -> OrderExecutionResult : \"\"\"Place one normalized market order or return a dry-run result. ``pdmt5.Mt5TradingClient.order_send()`` raises only when MT5 returns no response. When MT5 returns a response with a known non-success retcode, this helper returns ``status=\"failed\"`` and keeps the normalized response details for callers to inspect. Returns: Normalized execution result containing request and response details. Raises: Mt5TradingError: If volume or required tick data is invalid. \"\"\" if volume <= 0 : msg = \"volume must be positive.\" raise Mt5TradingError ( msg ) side = _normalize_order_side ( order_side ) if not dry_run : ensure_symbol_selected ( client , symbol ) tick = get_tick_snapshot ( client , symbol ) price = extract_tick_price ( tick , \"ask\" if side == \"BUY\" else \"bid\" ) if price is None : msg = f \"Tick price is unavailable for { symbol !r} .\" raise Mt5TradingError ( msg ) request = { \"action\" : client . mt5 . TRADE_ACTION_DEAL , \"symbol\" : symbol , \"volume\" : volume , \"type\" : ( client . mt5 . ORDER_TYPE_BUY if side == \"BUY\" else client . mt5 . ORDER_TYPE_SELL ), \"price\" : price , \"type_filling\" : _resolve_mt5_constant ( client . mt5 , \"ORDER_FILLING\" , order_filling_mode , _ORDER_FILLING_MODES , ), \"type_time\" : _resolve_mt5_constant ( client . mt5 , \"ORDER_TIME\" , order_time_mode , _ORDER_TIME_MODES , ), } if sl is not None : request [ \"sl\" ] = sl if tp is not None : request [ \"tp\" ] = tp if position is not None : request [ \"position\" ] = position if dry_run : return { \"status\" : \"dry_run\" , \"symbol\" : symbol , \"order_side\" : side , \"volume\" : volume , \"retcode\" : None , \"comment\" : None , \"request\" : cast ( \"dict[str, object]\" , request ), \"response\" : None , \"dry_run\" : True , } response = client . order_send ( request ) response_dict = _snapshot_from_value ( response , ()) raw_retcode = response_dict . get ( \"retcode\" ) retcode = _optional_int ( raw_retcode ) return { \"status\" : _order_status_from_retcode ( client . mt5 , raw_retcode ), \"symbol\" : symbol , \"order_side\" : side , \"volume\" : volume , \"retcode\" : retcode , \"comment\" : _optional_str ( response_dict . get ( \"comment\" )), \"request\" : cast ( \"dict[str, object]\" , request ), \"response\" : response_dict , \"dry_run\" : False , } update_sltp_for_open_positions \u00b6 update_sltp_for_open_positions ( client : Mt5TradingClient , * , symbol : str | None = None , tickets : list [ int ] | None = None , stop_loss : float | None = None , take_profit : float | None = None , dry_run : bool = False , ) -> list [ OrderExecutionResult ] Update SL/TP for matching open positions. Returns: Type Description list [ OrderExecutionResult ] Normalized execution results for matching positions. Source code in mt5cli/trading.py 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 def update_sltp_for_open_positions ( client : Mt5TradingClient , * , symbol : str | None = None , tickets : list [ int ] | None = None , stop_loss : float | None = None , take_profit : float | None = None , dry_run : bool = False , ) -> list [ OrderExecutionResult ]: \"\"\"Update SL/TP for matching open positions. Returns: Normalized execution results for matching positions. \"\"\" positions = _filter_positions ( get_positions_frame ( client ), symbols = symbol , tickets = tickets , ) results : list [ OrderExecutionResult ] = [] for row in positions . to_dict ( \"records\" ): request = { \"action\" : client . mt5 . TRADE_ACTION_SLTP , \"symbol\" : row [ \"symbol\" ], \"position\" : row [ \"ticket\" ], } sl = _optional_price ( row . get ( \"sl\" ) if stop_loss is None else stop_loss ) tp = _optional_price ( row . get ( \"tp\" ) if take_profit is None else take_profit ) if sl is not None : request [ \"sl\" ] = sl if tp is not None : request [ \"tp\" ] = tp if dry_run : response = None status : ExecutionStatus = \"dry_run\" else : ensure_symbol_selected ( client , str ( row [ \"symbol\" ])) response = _snapshot_from_value ( client . order_send ( request ), ()) status = _order_status_from_retcode ( client . mt5 , response . get ( \"retcode\" ), ) results . append ( { \"status\" : status , \"symbol\" : str ( row [ \"symbol\" ]), \"order_side\" : \"BUY\" if row [ \"type\" ] == client . mt5 . POSITION_TYPE_BUY else \"SELL\" , \"volume\" : float ( row [ \"volume\" ]), \"retcode\" : None if response is None else _optional_int ( response . get ( \"retcode\" )), \"comment\" : None if response is None else _optional_str ( response . get ( \"comment\" )), \"request\" : cast ( \"dict[str, object]\" , request ), \"response\" : response , \"dry_run\" : dry_run , }, ) return results update_trailing_stop_loss_for_open_positions \u00b6 update_trailing_stop_loss_for_open_positions ( client : Mt5TradingClient , * , symbol : str , trailing_stop_ratio : float , dry_run : bool = False , ) -> list [ OrderExecutionResult ] Update open positions whose trailing stop loss should move favorably. Returns: Type Description list [ OrderExecutionResult ] Normalized execution results for positions that need an SL update. Source code in mt5cli/trading.py 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 def update_trailing_stop_loss_for_open_positions ( client : Mt5TradingClient , * , symbol : str , trailing_stop_ratio : float , dry_run : bool = False , ) -> list [ OrderExecutionResult ]: \"\"\"Update open positions whose trailing stop loss should move favorably. Returns: Normalized execution results for positions that need an SL update. \"\"\" updates = calculate_trailing_stop_updates ( client , symbol = symbol , trailing_stop_ratio = trailing_stop_ratio , ) results : list [ OrderExecutionResult ] = [] for ticket , stop_loss in updates . items (): results . extend ( update_sltp_for_open_positions ( client , symbol = symbol , tickets = [ ticket ], stop_loss = stop_loss , dry_run = dry_run , ), ) return results Trading-capable MT5 sessions \u00b6 create_trading_client() and mt5_trading_session() complement the read-only mt5_session() helper in sdk.py . They return or yield an initialized pdmt5.Mt5TradingClient , use Mt5Config.path to launch the terminal when configured, and mt5_trading_session() always calls shutdown() on exit. from mt5cli import create_trading_client , mt5_trading_session with mt5_trading_session ( path = r \"C:\\Program Files\\MetaTrader 5\\terminal64.exe\" , login = \"12345\" , password = \"secret\" , server = \"Broker-Demo\" , retry_count = 2 , ) as client : positions = client . positions_get_as_df ( symbol = \"EURUSD\" ) client = create_trading_client ( login = 12345 , server = \"Broker-Demo\" ) try : account = client . account_info_as_dict () finally : client . shutdown () login accepts int , numeric str , or an empty string; empty strings are treated as unset. path , password , server , and timeout are forwarded to pdmt5.Mt5Config , and omitted timeout values keep the lower-level default. Use mt5_session() / MT5Client for read-only data collection. State and order helpers \u00b6 These helpers are strategy-agnostic and do not depend on signal detection, betting logic, or scheduling code in downstream applications. from mt5cli import ( calculate_positions_margin , calculate_spread_ratio , calculate_margin_and_volume , close_open_positions , detect_position_side , determine_order_limits , estimate_order_margin , fetch_latest_closed_rates_for_trading_client , fetch_latest_closed_rates_indexed , get_account_snapshot , get_positions_frame , get_symbol_snapshot , get_tick_snapshot , normalize_order_volume , place_market_order , ) account = get_account_snapshot ( client ) symbol = get_symbol_snapshot ( client , \"EURUSD\" ) tick = get_tick_snapshot ( client , \"EURUSD\" ) positions = get_positions_frame ( client , \"EURUSD\" ) side = detect_position_side ( client , \"EURUSD\" ) spread_ratio = calculate_spread_ratio ( client , \"EURUSD\" ) volume = normalize_order_volume ( 0.15 , volume_min = symbol [ \"volume_min\" ], volume_max = symbol [ \"volume_max\" ], volume_step = symbol [ \"volume_step\" ], ) buy_margin = ( estimate_order_margin ( client , \"EURUSD\" , \"BUY\" , volume ) if volume > 0 else 0.0 ) open_margin = calculate_positions_margin ( client , symbols = [ \"EURUSD\" ]) closed_bars = fetch_latest_closed_rates_for_trading_client ( client , symbol = \"EURUSD\" , granularity = \"M1\" , count = 100 , ) # Or fetch with a UTC DatetimeIndex instead of a \"time\" column: indexed_bars = fetch_latest_closed_rates_indexed ( client , symbol = \"EURUSD\" , granularity = \"M1\" , count = 100 , ) # indexed_bars.index is a UTC-aware DatetimeIndex named \"time\" 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 , ) preview = place_market_order ( client , symbol = \"EURUSD\" , volume = sizing [ \"buy_volume\" ], order_side = \"BUY\" , sl = limits [ \"stop_loss\" ], tp = limits [ \"take_profit\" ], dry_run = True , ) closed = close_open_positions ( client , symbols = \"EURUSD\" , dry_run = True ) detect_position_side() returns long for buy-only exposure, short for sell-only exposure, and None for no positions or mixed long/short exposure. calculate_spread_ratio() uses (ask - bid) / ((ask + bid) / 2) and raises Mt5TradingError when bid or ask is missing or non-positive. normalize_order_volume() returns 0.0 for invalid constraints or sub-minimum requests; check the result before calling estimate_order_margin() , which requires a positive finite volume. calculate_positions_margin() silently skips rows with missing symbols, non-positive volumes, non-finite volumes, or unsupported position types, but propagates Mt5TradingError from estimate_order_margin() when a valid row encounters invalid tick data or margin results from the broker. SL/TP ratios for determine_order_limits() must satisfy 0 <= ratio < 1 ; 0 omits that level. SL/TP prices are rounded with symbol digits metadata when available. determine_order_limits() pre-validates computed SL/TP prices against available trade_stops_level * point metadata when present; violations raise Mt5TradingError . This is a planning helper only: it does not guarantee broker acceptance because live validation can still depend on price movement, bid/ask side, freeze levels, and server-side rules, and it does not validate trade_freeze_level . When symbol metadata cannot be loaded, protective prices still round with digits=8 and stop-level validation is skipped. unit_margin_ratio and preserved_margin_ratio for calculate_margin_and_volume() accept 0 <= ratio <= 1 ; unit_margin_ratio=0 requests one minimum valid unit when the post-reserve margin can afford it. Negative margin_free is clamped to 0.0 before sizing. Execution helpers return normalized OrderExecutionResult dictionaries containing the request, response, status, retcode, and dry_run flag; dry_run=True never sends an order or mutates Market Watch visibility. ensure_symbol_selected() adds hidden symbols to Market Watch before live order placement and SL/TP updates. Failed, malformed, or unknown broker retcodes are fail-closed and returned as status=\"failed\" while keeping the normalized response for inspection. Order planning return contracts \u00b6 from mt5cli import MarginVolume , OrderLimits , OrderExecutionResult sizing : MarginVolume = calculate_margin_and_volume ( client , \"EURUSD\" , unit_margin_ratio = 0.5 , preserved_margin_ratio = 0.2 , ) limits : OrderLimits = determine_order_limits ( client , \"EURUSD\" , side = \"long\" , stop_loss_limit_ratio = 0.01 , take_profit_limit_ratio = 0.02 , ) preview : OrderExecutionResult = place_market_order ( client , symbol = \"EURUSD\" , volume = sizing [ \"buy_volume\" ], order_side = \"BUY\" , sl = limits [ \"stop_loss\" ], tp = limits [ \"take_profit\" ], dry_run = True , ) updates : list [ OrderExecutionResult ] = update_sltp_for_open_positions ( client , symbol = \"EURUSD\" , stop_loss = limits [ \"stop_loss\" ], dry_run = True , ) Closes issue #33: strategy-neutral order planning and execution helpers exposed through the stable package root without embedding entry/exit policy. Migration from application-local helpers \u00b6 Application-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 broker volume step normalization normalize_order_volume() Local order or position margin estimation estimate_order_margin() , calculate_positions_margin() Local closed-bar fetch from a trading session fetch_latest_closed_rates_for_trading_client() , fetch_latest_closed_rates_indexed() 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() / MT5Client ; use mt5_trading_session() only where order placement or trading calculations are required.","title":"Trading"},{"location":"api/trading/#trading-module","text":"","title":"Trading Module"},{"location":"api/trading/#mt5cli.trading","text":"Trading-capable MetaTrader 5 session helpers and operational utilities.","title":"trading"},{"location":"api/trading/#mt5cli.trading.ExecutionStatus","text":"ExecutionStatus = Literal [ \"executed\" , \"dry_run\" , \"skipped\" , \"failed\" ]","title":"ExecutionStatus"},{"location":"api/trading/#mt5cli.trading.OrderFillingMode","text":"OrderFillingMode = Literal [ 'IOC' , 'FOK' , 'RETURN' ]","title":"OrderFillingMode"},{"location":"api/trading/#mt5cli.trading.OrderSide","text":"OrderSide = Literal [ 'BUY' , 'SELL' ]","title":"OrderSide"},{"location":"api/trading/#mt5cli.trading.OrderTimeMode","text":"OrderTimeMode = Literal [ \"GTC\" , \"DAY\" , \"SPECIFIED\" , \"SPECIFIED_DAY\" ]","title":"OrderTimeMode"},{"location":"api/trading/#mt5cli.trading.POSITION_COLUMNS","text":"POSITION_COLUMNS = ( \"ticket\" , \"time\" , \"symbol\" , \"type\" , \"volume\" , \"price_open\" , \"sl\" , \"tp\" , \"price_current\" , \"profit\" , \"swap\" , \"comment\" , )","title":"POSITION_COLUMNS"},{"location":"api/trading/#mt5cli.trading.PositionSide","text":"PositionSide = Literal [ 'long' , 'short' ]","title":"PositionSide"},{"location":"api/trading/#mt5cli.trading.__all__","text":"__all__ = [ \"POSITION_COLUMNS\" , \"ExecutionStatus\" , \"MarginVolume\" , \"OrderExecutionResult\" , \"OrderFillingMode\" , \"OrderLimits\" , \"OrderSide\" , \"OrderTimeMode\" , \"PositionSide\" , \"calculate_account_projected_margin_ratio\" , \"calculate_margin_and_volume\" , \"calculate_new_position_margin_ratio\" , \"calculate_positions_margin\" , \"calculate_positions_margin_by_symbol\" , \"calculate_positions_margin_safe\" , \"calculate_projected_margin_ratio\" , \"calculate_spread_ratio\" , \"calculate_symbol_group_margin_ratio\" , \"calculate_trailing_stop_updates\" , \"calculate_volume_by_margin\" , \"close_open_positions\" , \"create_trading_client\" , \"detect_position_side\" , \"determine_order_limits\" , \"ensure_symbol_selected\" , \"estimate_order_margin\" , \"extract_tick_price\" , \"fetch_latest_closed_rates_for_trading_client\" , \"fetch_latest_closed_rates_indexed\" , \"get_account_snapshot\" , \"get_positions_frame\" , \"get_symbol_snapshot\" , \"get_tick_snapshot\" , \"mt5_trading_session\" , \"normalize_order_volume\" , \"place_market_order\" , \"update_sltp_for_open_positions\" , \"update_trailing_stop_loss_for_open_positions\" , ]","title":"__all__"},{"location":"api/trading/#mt5cli.trading.MarginVolume","text":"Bases: TypedDict Affordable volume bounds derived from account margin and symbol constraints.","title":"MarginVolume"},{"location":"api/trading/#mt5cli.trading.MarginVolume.available_margin","text":"available_margin : float","title":"available_margin"},{"location":"api/trading/#mt5cli.trading.MarginVolume.buy_volume","text":"buy_volume : float","title":"buy_volume"},{"location":"api/trading/#mt5cli.trading.MarginVolume.margin_free","text":"margin_free : float","title":"margin_free"},{"location":"api/trading/#mt5cli.trading.MarginVolume.sell_volume","text":"sell_volume : float","title":"sell_volume"},{"location":"api/trading/#mt5cli.trading.MarginVolume.trade_margin","text":"trade_margin : float","title":"trade_margin"},{"location":"api/trading/#mt5cli.trading.MarginVolume.volume_max","text":"volume_max : float","title":"volume_max"},{"location":"api/trading/#mt5cli.trading.MarginVolume.volume_min","text":"volume_min : float","title":"volume_min"},{"location":"api/trading/#mt5cli.trading.MarginVolume.volume_step","text":"volume_step : float","title":"volume_step"},{"location":"api/trading/#mt5cli.trading.OrderExecutionResult","text":"Bases: TypedDict Normalized result from market-order and position-management helpers.","title":"OrderExecutionResult"},{"location":"api/trading/#mt5cli.trading.OrderExecutionResult.comment","text":"comment : str | None","title":"comment"},{"location":"api/trading/#mt5cli.trading.OrderExecutionResult.dry_run","text":"dry_run : bool","title":"dry_run"},{"location":"api/trading/#mt5cli.trading.OrderExecutionResult.order_side","text":"order_side : OrderSide","title":"order_side"},{"location":"api/trading/#mt5cli.trading.OrderExecutionResult.request","text":"request : dict [ str , object ]","title":"request"},{"location":"api/trading/#mt5cli.trading.OrderExecutionResult.response","text":"response : dict [ str , object ] | None","title":"response"},{"location":"api/trading/#mt5cli.trading.OrderExecutionResult.retcode","text":"retcode : int | None","title":"retcode"},{"location":"api/trading/#mt5cli.trading.OrderExecutionResult.status","text":"status : ExecutionStatus","title":"status"},{"location":"api/trading/#mt5cli.trading.OrderExecutionResult.symbol","text":"symbol : str","title":"symbol"},{"location":"api/trading/#mt5cli.trading.OrderExecutionResult.volume","text":"volume : float","title":"volume"},{"location":"api/trading/#mt5cli.trading.OrderLimits","text":"Bases: TypedDict Protective order prices derived from current quotes and ratio parameters.","title":"OrderLimits"},{"location":"api/trading/#mt5cli.trading.OrderLimits.entry","text":"entry : float","title":"entry"},{"location":"api/trading/#mt5cli.trading.OrderLimits.stop_loss","text":"stop_loss : float | None","title":"stop_loss"},{"location":"api/trading/#mt5cli.trading.OrderLimits.take_profit","text":"take_profit : float | None","title":"take_profit"},{"location":"api/trading/#mt5cli.trading.calculate_account_projected_margin_ratio","text":"calculate_account_projected_margin_ratio ( client : Mt5TradingClient , * , symbol : str | None = None , new_position_side : OrderSide | None = None , new_position_volume : float = 0.0 , ) -> float Return account-wide current plus optional new-position margin over equity. Current exposure comes from the broker account snapshot margin field so unrelated open positions remain in the baseline. Optional projected exposure is added via :func: estimate_order_margin only when a symbol, side, and positive volume are all supplied. Source code in mt5cli/trading.py 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 def calculate_account_projected_margin_ratio ( client : Mt5TradingClient , * , symbol : str | None = None , new_position_side : OrderSide | None = None , new_position_volume : float = 0.0 , ) -> float : \"\"\"Return account-wide current plus optional new-position margin over equity. Current exposure comes from the broker account snapshot ``margin`` field so unrelated open positions remain in the baseline. Optional projected exposure is added via :func:`estimate_order_margin` only when a symbol, side, and positive volume are all supplied. \"\"\" account = get_account_snapshot ( client ) equity = _required_account_number ( account , \"equity\" , allow_zero = False ) margin = _required_account_number ( account , \"margin\" , allow_zero = True ) if symbol is not None and new_position_side is not None and new_position_volume > 0 : margin += estimate_order_margin ( client , symbol , new_position_side , new_position_volume , ) return margin / equity","title":"calculate_account_projected_margin_ratio"},{"location":"api/trading/#mt5cli.trading.calculate_margin_and_volume","text":"calculate_margin_and_volume ( client : Mt5TradingClient , symbol : str , unit_margin_ratio : float , preserved_margin_ratio : float , ) -> MarginVolume Calculate tradable margin and volumes from account free margin. Applies preserved_margin_ratio to keep a reserve off margin_free , then allocates unit_margin_ratio of the remainder as the margin budget for proportional volume sizing on both buy and sell sides. A unit_margin_ratio of 0 requests exactly one minimum valid unit per side when the post-reserve margin can afford it. Parameters: Name Type Description Default client Mt5TradingClient Connected Mt5TradingClient instance. required symbol str Symbol used for minimum-lot margin and volume calculations. required unit_margin_ratio float Fraction of post-reserve margin to allocate per unit. required preserved_margin_ratio float Fraction of margin_free to preserve. required Returns: Type Description MarginVolume Dictionary with margin_free , available_margin , trade_margin , MarginVolume buy_volume , and sell_volume . Negative margin_free values are MarginVolume clamped to 0.0 before sizing. Source code in mt5cli/trading.py 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 def calculate_margin_and_volume ( client : Mt5TradingClient , symbol : str , unit_margin_ratio : float , preserved_margin_ratio : float , ) -> MarginVolume : \"\"\"Calculate tradable margin and volumes from account free margin. Applies ``preserved_margin_ratio`` to keep a reserve off ``margin_free``, then allocates ``unit_margin_ratio`` of the remainder as the margin budget for proportional volume sizing on both buy and sell sides. A ``unit_margin_ratio`` of ``0`` requests exactly one minimum valid unit per side when the post-reserve margin can afford it. Args: client: Connected ``Mt5TradingClient`` instance. symbol: Symbol used for minimum-lot margin and volume calculations. unit_margin_ratio: Fraction of post-reserve margin to allocate per unit. preserved_margin_ratio: Fraction of ``margin_free`` to preserve. Returns: Dictionary with ``margin_free``, ``available_margin``, ``trade_margin``, ``buy_volume``, and ``sell_volume``. Negative ``margin_free`` values are clamped to ``0.0`` before sizing. \"\"\" _require_unit_ratio ( unit_margin_ratio , \"unit_margin_ratio\" ) _require_unit_ratio ( preserved_margin_ratio , \"preserved_margin_ratio\" ) account = client . account_info_as_dict () margin_free = max ( 0.0 , float ( account . get ( \"margin_free\" ) or 0.0 )) available_margin = margin_free * ( 1.0 - preserved_margin_ratio ) trade_margin = available_margin * unit_margin_ratio if unit_margin_ratio == 0 : buy_volume = _calculate_min_volume_if_affordable ( client , symbol , available_margin , \"BUY\" , ) sell_volume = _calculate_min_volume_if_affordable ( client , symbol , available_margin , \"SELL\" , ) else : buy_volume = calculate_volume_by_margin ( client , symbol , trade_margin , \"BUY\" ) sell_volume = calculate_volume_by_margin ( client , symbol , trade_margin , \"SELL\" ) try : symbol_info = get_symbol_snapshot ( client , symbol ) volume_min = float ( symbol_info . get ( \"volume_min\" ) or 0.0 ) volume_max = float ( symbol_info . get ( \"volume_max\" ) or 0.0 ) volume_step = float ( symbol_info . get ( \"volume_step\" ) or 0.0 ) except AttributeError : volume_min = volume_max = volume_step = 0.0 return { \"margin_free\" : margin_free , \"available_margin\" : available_margin , \"trade_margin\" : trade_margin , \"buy_volume\" : float ( buy_volume ), \"sell_volume\" : float ( sell_volume ), \"volume_min\" : volume_min , \"volume_max\" : volume_max , \"volume_step\" : volume_step , }","title":"calculate_margin_and_volume"},{"location":"api/trading/#mt5cli.trading.calculate_new_position_margin_ratio","text":"calculate_new_position_margin_ratio ( client : Mt5TradingClient , * , symbol : str , new_position_side : OrderSide | None = None , new_position_volume : float = 0.0 , ) -> float Return total margin/equity ratio after an optional hypothetical position. Raises: Type Description Mt5TradingError If equity or required tick data is invalid. Source code in mt5cli/trading.py 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 def calculate_new_position_margin_ratio ( client : Mt5TradingClient , * , symbol : str , new_position_side : OrderSide | None = None , new_position_volume : float = 0.0 , ) -> float : \"\"\"Return total margin/equity ratio after an optional hypothetical position. Raises: Mt5TradingError: If equity or required tick data is invalid. \"\"\" account = get_account_snapshot ( client ) equity = float ( account . get ( \"equity\" ) or 0.0 ) if equity <= 0 : msg = \"Account equity must be positive to calculate margin ratio.\" raise Mt5TradingError ( msg ) margin = float ( account . get ( \"margin\" ) or 0.0 ) if new_position_side is not None and new_position_volume > 0 : side = _normalize_order_side ( new_position_side ) price = extract_tick_price ( get_tick_snapshot ( client , symbol ), \"ask\" if side == \"BUY\" else \"bid\" ) if price is None : msg = f \"Tick price is unavailable for { symbol !r} .\" raise Mt5TradingError ( msg ) order_type = ( client . mt5 . ORDER_TYPE_BUY if side == \"BUY\" else client . mt5 . ORDER_TYPE_SELL ) margin += float ( client . order_calc_margin ( order_type , symbol , new_position_volume , price ), ) return margin / equity","title":"calculate_new_position_margin_ratio"},{"location":"api/trading/#mt5cli.trading.calculate_positions_margin","text":"calculate_positions_margin ( client : Mt5TradingClient , * , symbols : Sequence [ str ] | None = None , ) -> float Return the sum of estimated current margin for open positions. Parameters: Name Type Description Default client Mt5TradingClient Connected Mt5TradingClient instance. required symbols Sequence [ str ] | None Optional symbol filter. When omitted, all open positions are included. None Returns: Type Description float Total estimated margin, or 0.0 when no matching positions exist. Source code in mt5cli/trading.py 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 def calculate_positions_margin ( client : Mt5TradingClient , * , symbols : Sequence [ str ] | None = None , ) -> float : \"\"\"Return the sum of estimated current margin for open positions. Args: client: Connected ``Mt5TradingClient`` instance. symbols: Optional symbol filter. When omitted, all open positions are included. Returns: Total estimated margin, or ``0.0`` when no matching positions exist. \"\"\" frame = get_positions_frame ( client ) if frame . empty or \"symbol\" not in frame . columns : return 0.0 if symbols is not None : frame = frame [ frame [ \"symbol\" ] . isin ( list ( symbols ))] if frame . empty : return 0.0 grouped_volumes : dict [ tuple [ str , OrderSide ], float ] = {} for _ , row in frame . iterrows (): symbol = row . get ( \"symbol\" ) if not isinstance ( symbol , str ) or not symbol : continue volume = row . get ( \"volume\" ) if not _is_positive_finite_number ( volume ): continue order_side = _order_side_from_position_type ( client , row . get ( \"type\" )) if order_side is None : continue key = ( symbol , order_side ) finite_volume = float ( cast ( \"float | int\" , volume )) grouped_volumes [ key ] = grouped_volumes . get ( key , 0.0 ) + finite_volume total = 0.0 for ( symbol , order_side ), volume in grouped_volumes . items (): total += estimate_order_margin ( client , symbol , order_side , volume ) return total","title":"calculate_positions_margin"},{"location":"api/trading/#mt5cli.trading.calculate_positions_margin_by_symbol","text":"calculate_positions_margin_by_symbol ( client : Mt5TradingClient , * , symbols : Sequence [ str ], suppress_errors : bool = True , ) -> dict [ str , float ] Return per-symbol estimated margin for open positions. Computes margin for each unique input symbol independently using the strict :func: calculate_positions_margin helper. Duplicates are deduplicated in first-seen order. Parameters: Name Type Description Default client Mt5TradingClient Connected Mt5TradingClient instance. required symbols Sequence [ str ] Symbols to compute margin for. required suppress_errors bool When True , log and skip symbols that raise Mt5TradingError , Mt5RuntimeError , or AttributeError . When False , re-raise the first failure. True Returns: Type Description dict [ str , float ] Mapping of symbol to margin total in first-seen unique-symbol order. dict [ str , float ] Returns an empty dict when symbols is empty or all symbols fail dict [ str , float ] with suppress_errors=True . Raises: Type Description Mt5TradingError When a symbol raises Mt5TradingError and suppress_errors=False . Mt5RuntimeError When a symbol raises Mt5RuntimeError and suppress_errors=False . AttributeError When a symbol raises AttributeError and suppress_errors=False . Source code in mt5cli/trading.py 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 def calculate_positions_margin_by_symbol ( client : Mt5TradingClient , * , symbols : Sequence [ str ], suppress_errors : bool = True , ) -> dict [ str , float ]: \"\"\"Return per-symbol estimated margin for open positions. Computes margin for each unique input symbol independently using the strict :func:`calculate_positions_margin` helper. Duplicates are deduplicated in first-seen order. Args: client: Connected ``Mt5TradingClient`` instance. symbols: Symbols to compute margin for. suppress_errors: When ``True``, log and skip symbols that raise ``Mt5TradingError``, ``Mt5RuntimeError``, or ``AttributeError``. When ``False``, re-raise the first failure. Returns: Mapping of symbol to margin total in first-seen unique-symbol order. Returns an empty dict when ``symbols`` is empty or all symbols fail with ``suppress_errors=True``. Raises: Mt5TradingError: When a symbol raises ``Mt5TradingError`` and ``suppress_errors=False``. Mt5RuntimeError: When a symbol raises ``Mt5RuntimeError`` and ``suppress_errors=False``. AttributeError: When a symbol raises ``AttributeError`` and ``suppress_errors=False``. \"\"\" result : dict [ str , float ] = {} for symbol in dict . fromkeys ( symbols ): try : result [ symbol ] = calculate_positions_margin ( client , symbols = [ symbol ]) except ( Mt5TradingError , Mt5RuntimeError , AttributeError ) as exc : if not suppress_errors : raise _logger . warning ( \"Skipping margin for %r : %s \" , symbol , exc ) return result","title":"calculate_positions_margin_by_symbol"},{"location":"api/trading/#mt5cli.trading.calculate_positions_margin_safe","text":"calculate_positions_margin_safe ( client : Mt5TradingClient , * , symbols : Sequence [ str ] ) -> float Return the total estimated margin for open positions across symbols. Internally calls :func: calculate_positions_margin_by_symbol with suppress_errors=True . Failed symbols are silently skipped. Parameters: Name Type Description Default client Mt5TradingClient Connected Mt5TradingClient instance. required symbols Sequence [ str ] Symbols to include. required Returns: Type Description float Sum of per-symbol margins; 0.0 when no symbols or all fail. Source code in mt5cli/trading.py 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 def calculate_positions_margin_safe ( client : Mt5TradingClient , * , symbols : Sequence [ str ], ) -> float : \"\"\"Return the total estimated margin for open positions across symbols. Internally calls :func:`calculate_positions_margin_by_symbol` with ``suppress_errors=True``. Failed symbols are silently skipped. Args: client: Connected ``Mt5TradingClient`` instance. symbols: Symbols to include. Returns: Sum of per-symbol margins; ``0.0`` when no symbols or all fail. \"\"\" return sum ( calculate_positions_margin_by_symbol ( client , symbols = symbols ) . values (), 0.0 , )","title":"calculate_positions_margin_safe"},{"location":"api/trading/#mt5cli.trading.calculate_projected_margin_ratio","text":"calculate_projected_margin_ratio ( client : Mt5TradingClient , * , symbol : str , new_position_side : OrderSide | None = None , new_position_volume : float = 0.0 , ) -> float Return estimated current plus optional new-position margin over equity. Current exposure is estimated from open positions with :func: calculate_positions_margin . Optional projected exposure is added via :func: estimate_order_margin . Thresholds and guard actions are intentionally left to downstream applications. Account equity, position margin, and optional projected margin errors from the composed MT5 helpers propagate to the caller. Source code in mt5cli/trading.py 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 def calculate_projected_margin_ratio ( client : Mt5TradingClient , * , symbol : str , new_position_side : OrderSide | None = None , new_position_volume : float = 0.0 , ) -> float : \"\"\"Return estimated current plus optional new-position margin over equity. Current exposure is estimated from open positions with :func:`calculate_positions_margin`. Optional projected exposure is added via :func:`estimate_order_margin`. Thresholds and guard actions are intentionally left to downstream applications. Account equity, position margin, and optional projected margin errors from the composed MT5 helpers propagate to the caller. \"\"\" equity = _account_equity ( client ) margin = calculate_positions_margin ( client , symbols = [ symbol ]) if new_position_side is not None and new_position_volume > 0 : margin += estimate_order_margin ( client , symbol , new_position_side , new_position_volume , ) return margin / equity","title":"calculate_projected_margin_ratio"},{"location":"api/trading/#mt5cli.trading.calculate_spread_ratio","text":"calculate_spread_ratio ( client : Mt5TradingClient , symbol : str ) -> float Return (ask - bid) / ((ask + bid) / 2) for the latest tick. Raises: Type Description Mt5TradingError If bid or ask is unavailable. Source code in mt5cli/trading.py 786 787 788 789 790 791 792 793 794 795 796 797 798 def calculate_spread_ratio ( client : Mt5TradingClient , symbol : str ) -> float : \"\"\"Return ``(ask - bid) / ((ask + bid) / 2)`` for the latest tick. Raises: Mt5TradingError: If bid or ask is unavailable. \"\"\" tick = get_tick_snapshot ( client , symbol ) bid = extract_tick_price ( tick , \"bid\" ) ask = extract_tick_price ( tick , \"ask\" ) if bid is None or ask is None : msg = f \"Tick bid/ask is unavailable for { symbol !r} .\" raise Mt5TradingError ( msg ) return ( ask - bid ) / (( ask + bid ) / 2.0 )","title":"calculate_spread_ratio"},{"location":"api/trading/#mt5cli.trading.calculate_symbol_group_margin_ratio","text":"calculate_symbol_group_margin_ratio ( client : Mt5TradingClient , * , symbols : Sequence [ str ], new_symbol : str | None = None , new_position_side : OrderSide | None = None , new_position_volume : float = 0.0 , suppress_errors : bool = True , ) -> float Return estimated symbol-group margin over account equity. Per-symbol current exposure is summed with :func: calculate_positions_margin_by_symbol . When new_symbol is inside the input symbol group, optional projected order margin is added for that symbol. Invalid equity always raises to fail closed. Raises: Type Description AttributeError When symbol margin lookup or projected margin lookup fails and suppress_errors is False . Mt5RuntimeError When symbol margin lookup or projected margin lookup fails and suppress_errors is False . Mt5TradingError When account equity is invalid, or when symbol margin lookup or projected margin lookup fails and suppress_errors is False . Source code in mt5cli/trading.py 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 def calculate_symbol_group_margin_ratio ( client : Mt5TradingClient , * , symbols : Sequence [ str ], new_symbol : str | None = None , new_position_side : OrderSide | None = None , new_position_volume : float = 0.0 , suppress_errors : bool = True , ) -> float : \"\"\"Return estimated symbol-group margin over account equity. Per-symbol current exposure is summed with :func:`calculate_positions_margin_by_symbol`. When ``new_symbol`` is inside the input symbol group, optional projected order margin is added for that symbol. Invalid equity always raises to fail closed. Raises: AttributeError: When symbol margin lookup or projected margin lookup fails and ``suppress_errors`` is ``False``. Mt5RuntimeError: When symbol margin lookup or projected margin lookup fails and ``suppress_errors`` is ``False``. Mt5TradingError: When account equity is invalid, or when symbol margin lookup or projected margin lookup fails and ``suppress_errors`` is ``False``. \"\"\" equity = _account_equity ( client ) unique_symbols = list ( dict . fromkeys ( symbols )) margin = sum ( calculate_positions_margin_by_symbol ( client , symbols = unique_symbols , suppress_errors = suppress_errors , ) . values (), 0.0 , ) if ( new_symbol in unique_symbols and new_position_side is not None and new_position_volume > 0 ): try : margin += estimate_order_margin ( client , new_symbol , new_position_side , new_position_volume , ) except ( Mt5TradingError , Mt5RuntimeError , AttributeError ): if not suppress_errors : raise _logger . warning ( \"Skipping projected margin for %r .\" , new_symbol ) return margin / equity","title":"calculate_symbol_group_margin_ratio"},{"location":"api/trading/#mt5cli.trading.calculate_trailing_stop_updates","text":"calculate_trailing_stop_updates ( client : Mt5TradingClient , * , symbol : str , trailing_stop_ratio : float , ) -> dict [ int , float ] Return per-ticket trailing stop-loss updates for open symbol positions. Buy positions trail from bid using bid * (1 - trailing_stop_ratio) . Sell positions trail from ask using ask * (1 + trailing_stop_ratio) . Existing stop losses are preserved when they are already more favorable. Missing symbol metadata returns an empty update map. Positions with a missing side-specific tick price are skipped. Source code in mt5cli/trading.py 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 def calculate_trailing_stop_updates ( client : Mt5TradingClient , * , symbol : str , trailing_stop_ratio : float , ) -> dict [ int , float ]: \"\"\"Return per-ticket trailing stop-loss updates for open symbol positions. Buy positions trail from bid using ``bid * (1 - trailing_stop_ratio)``. Sell positions trail from ask using ``ask * (1 + trailing_stop_ratio)``. Existing stop losses are preserved when they are already more favorable. Missing symbol metadata returns an empty update map. Positions with a missing side-specific tick price are skipped. \"\"\" _require_protective_ratio ( trailing_stop_ratio , \"trailing_stop_ratio\" ) positions = get_positions_frame ( client , symbol = symbol ) if positions . empty : return {} tick = get_tick_snapshot ( client , symbol ) bid = extract_tick_price ( tick , \"bid\" ) ask = extract_tick_price ( tick , \"ask\" ) digits = _symbol_digits ( client , symbol ) if digits is None : return {} updates : dict [ int , float ] = {} for row in positions . to_dict ( \"records\" ): ticket = _position_ticket ( row . get ( \"ticket\" )) if ticket is None : continue next_sl = _trailing_stop_loss ( client , position_type = row . get ( \"type\" ), current_sl = _current_stop_loss ( row . get ( \"sl\" )), bid = bid , ask = ask , digits = digits , trailing_stop_ratio = trailing_stop_ratio , ) if next_sl is None : continue updates [ ticket ] = next_sl return updates","title":"calculate_trailing_stop_updates"},{"location":"api/trading/#mt5cli.trading.calculate_volume_by_margin","text":"calculate_volume_by_margin ( client : Mt5TradingClient , symbol : str , available_margin : float , order_side : OrderSide , ) -> float Calculate max normalized volume affordable for one side. Returns: Type Description float Largest stepped volume whose actual margin (from order_calc_margin ) float fits within available_margin , rounded down to symbol volume float constraints; 0.0 when no affordable step exists. Raises: Type Description Mt5TradingError If symbol volume constraints or tick data are invalid. Source code in mt5cli/trading.py 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 def calculate_volume_by_margin ( client : Mt5TradingClient , symbol : str , available_margin : float , order_side : OrderSide , ) -> float : \"\"\"Calculate max normalized volume affordable for one side. Returns: Largest stepped volume whose actual margin (from ``order_calc_margin``) fits within ``available_margin``, rounded down to symbol volume constraints; ``0.0`` when no affordable step exists. Raises: Mt5TradingError: If symbol volume constraints or tick data are invalid. \"\"\" if available_margin <= 0 : return 0.0 symbol_info = get_symbol_snapshot ( client , symbol ) volume_min = float ( symbol_info . get ( \"volume_min\" ) or 0.0 ) volume_max = float ( symbol_info . get ( \"volume_max\" ) or 0.0 ) volume_step = float ( symbol_info . get ( \"volume_step\" ) or volume_min or 0.0 ) if volume_min <= 0 or volume_step <= 0 : msg = f \"Invalid volume constraints for { symbol !r} .\" raise Mt5TradingError ( msg ) side = _normalize_order_side ( order_side ) price = extract_tick_price ( get_tick_snapshot ( client , symbol ), \"ask\" if side == \"BUY\" else \"bid\" ) if price is None : msg = f \"Tick price is unavailable for { symbol !r} .\" raise Mt5TradingError ( msg ) order_type = ( client . mt5 . ORDER_TYPE_BUY if side == \"BUY\" else client . mt5 . ORDER_TYPE_SELL ) min_margin = float ( client . order_calc_margin ( order_type , symbol , volume_min , price )) if min_margin <= 0 or min_margin > available_margin : return 0.0 lo = 0 hi = int ( max ( 0 , floor ( ( ( min ( available_margin / min_margin * volume_min , volume_max ) if volume_max > 0 else available_margin / min_margin * volume_min ) - volume_min ) / volume_step + 1e-12 ), ) ) best = - 1 while lo <= hi : mid = ( lo + hi ) // 2 normalized = round ( volume_min + mid * volume_step , 10 ) actual = float ( client . order_calc_margin ( order_type , symbol , normalized , price )) if actual > 0 and actual <= available_margin : best = mid lo = mid + 1 else : hi = mid - 1 return round ( volume_min + best * volume_step , 10 ) if best >= 0 else 0.0","title":"calculate_volume_by_margin"},{"location":"api/trading/#mt5cli.trading.close_open_positions","text":"close_open_positions ( client : Mt5TradingClient , * , symbols : str | list [ str ] | None = None , tickets : list [ int ] | None = None , dry_run : bool = False , ) -> list [ OrderExecutionResult ] Close matching open positions. Returns: Type Description list [ OrderExecutionResult ] Normalized execution results for matching positions. Source code in mt5cli/trading.py 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 def close_open_positions ( client : Mt5TradingClient , * , symbols : str | list [ str ] | None = None , tickets : list [ int ] | None = None , dry_run : bool = False , ) -> list [ OrderExecutionResult ]: \"\"\"Close matching open positions. Returns: Normalized execution results for matching positions. \"\"\" positions = _filter_positions ( get_positions_frame ( client ), symbols = symbols , tickets = tickets , ) results : list [ OrderExecutionResult ] = [] for row in positions . to_dict ( \"records\" ): pos_type = row [ \"type\" ] side : OrderSide = \"SELL\" if pos_type == client . mt5 . POSITION_TYPE_BUY else \"BUY\" result = place_market_order ( client , symbol = str ( row [ \"symbol\" ]), volume = float ( row [ \"volume\" ]), order_side = side , position = int ( row [ \"ticket\" ]), dry_run = dry_run , ) results . append ( result ) return results","title":"close_open_positions"},{"location":"api/trading/#mt5cli.trading.create_trading_client","text":"create_trading_client ( * , config : Mt5Config | None = None , login : int | str | None = None , password : str | None = None , server : str | None = None , path : str | None = None , timeout : int | None = None , retry_count : int = 0 , ) -> Mt5TradingClient Return an initialized and logged-in trading client. Source code in mt5cli/trading.py 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 def create_trading_client ( * , config : Mt5Config | None = None , login : int | str | None = None , password : str | None = None , server : str | None = None , path : str | None = None , timeout : int | None = None , retry_count : int = 0 , ) -> Mt5TradingClient : \"\"\"Return an initialized and logged-in trading client.\"\"\" mt5_config = _resolve_config ( config = config , login = login , password = password , server = server , path = path , timeout = timeout , ) client = Mt5TradingClient ( config = mt5_config , retry_count = retry_count ) try : client . initialize_and_login_mt5 () except Exception : client . shutdown () raise return client","title":"create_trading_client"},{"location":"api/trading/#mt5cli.trading.detect_position_side","text":"detect_position_side ( client : Mt5TradingClient , symbol : str ) -> PositionSide | None Detect the net open position side for a symbol. Parameters: Name Type Description Default client Mt5TradingClient Connected Mt5TradingClient instance. required symbol str Symbol to inspect. required Returns: Type Description PositionSide | None \"long\" when there are buy positions and no sell positions, PositionSide | None \"short\" when there are sell positions and no buy positions, or PositionSide | None None when no positions or mixed exposure exists. Source code in mt5cli/trading.py 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 def detect_position_side ( client : Mt5TradingClient , symbol : str , ) -> PositionSide | None : \"\"\"Detect the net open position side for a symbol. Args: client: Connected ``Mt5TradingClient`` instance. symbol: Symbol to inspect. Returns: ``\"long\"`` when there are buy positions and no sell positions, ``\"short\"`` when there are sell positions and no buy positions, or ``None`` when no positions or mixed exposure exists. \"\"\" positions = get_positions_frame ( client , symbol = symbol ) if positions . empty : return None buy_type = client . mt5 . POSITION_TYPE_BUY sell_type = client . mt5 . POSITION_TYPE_SELL buy_volume = _sum_position_volume ( positions , buy_type ) sell_volume = _sum_position_volume ( positions , sell_type ) if buy_volume > 0 and sell_volume == 0 : return \"long\" if sell_volume > 0 and buy_volume == 0 : return \"short\" return None","title":"detect_position_side"},{"location":"api/trading/#mt5cli.trading.determine_order_limits","text":"determine_order_limits ( client : Mt5TradingClient , symbol : str , side : PositionSide | str , stop_loss_limit_ratio : float | None = None , take_profit_limit_ratio : float | None = None , ) -> OrderLimits Derive entry and protective order prices from current market quotes. Parameters: Name Type Description Default client Mt5TradingClient Connected Mt5TradingClient instance. required symbol str Symbol used for the quote lookup. required side PositionSide | str Position side as \"long\" / \"short\" ( \"buy\" / \"sell\" aliases are accepted). required stop_loss_limit_ratio float | None Relative distance from entry for stop loss in [0, 1) . A value of 0 omits the stop loss. None take_profit_limit_ratio float | None Relative distance from entry for take profit in [0, 1) . A value of 0 omits the take profit. None Returns: Type Description OrderLimits Dictionary with entry , stop_loss , and take_profit keys. OrderLimits Omitted protective levels are returned as None . Raises: Type Description Mt5TradingError If required tick data is invalid or computed SL/TP prices violate available trade_stops_level pre-validation. Source code in mt5cli/trading.py 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 def determine_order_limits ( client : Mt5TradingClient , symbol : str , side : PositionSide | str , stop_loss_limit_ratio : float | None = None , take_profit_limit_ratio : float | None = None , ) -> OrderLimits : \"\"\"Derive entry and protective order prices from current market quotes. Args: client: Connected ``Mt5TradingClient`` instance. symbol: Symbol used for the quote lookup. side: Position side as ``\"long\"``/``\"short\"`` (``\"buy\"``/``\"sell\"`` aliases are accepted). stop_loss_limit_ratio: Relative distance from entry for stop loss in ``[0, 1)``. A value of ``0`` omits the stop loss. take_profit_limit_ratio: Relative distance from entry for take profit in ``[0, 1)``. A value of ``0`` omits the take profit. Returns: Dictionary with ``entry``, ``stop_loss``, and ``take_profit`` keys. Omitted protective levels are returned as ``None``. Raises: Mt5TradingError: If required tick data is invalid or computed SL/TP prices violate available ``trade_stops_level`` pre-validation. \"\"\" stop_loss_ratio = stop_loss_limit_ratio or 0.0 take_profit_ratio = take_profit_limit_ratio or 0.0 _require_protective_ratio ( stop_loss_ratio , \"stop_loss_limit_ratio\" ) _require_protective_ratio ( take_profit_ratio , \"take_profit_limit_ratio\" ) normalized_side = _position_side_from_order_side ( side ) tick = get_tick_snapshot ( client , symbol ) entry_key = \"ask\" if normalized_side == \"long\" else \"bid\" entry = extract_tick_price ( tick , entry_key ) if entry is None : msg = f \"Tick price is unavailable for { symbol !r} .\" raise Mt5TradingError ( msg ) try : symbol_info = get_symbol_snapshot ( client , symbol ) except ( AttributeError , KeyError , TypeError , ValueError ): symbol_info = {} try : digits = int ( symbol_info . get ( \"digits\" ) or 8 ) except ( TypeError , ValueError ): digits = 8 min_distance = _minimum_stop_distance ( symbol_info ) stop_loss : float | None = None if stop_loss_ratio > 0 : if normalized_side == \"long\" : stop_loss = entry * ( 1.0 - stop_loss_ratio ) else : stop_loss = entry * ( 1.0 + stop_loss_ratio ) stop_loss = round ( stop_loss , digits ) take_profit : float | None = None if take_profit_ratio > 0 : if normalized_side == \"long\" : take_profit = entry * ( 1.0 + take_profit_ratio ) else : take_profit = entry * ( 1.0 - take_profit_ratio ) take_profit = round ( take_profit , digits ) _validate_protective_prices ( symbol = symbol , side = normalized_side , entry = entry , stop_loss = stop_loss , take_profit = take_profit , min_distance = min_distance , ) return { \"entry\" : entry , \"stop_loss\" : stop_loss , \"take_profit\" : take_profit , }","title":"determine_order_limits"},{"location":"api/trading/#mt5cli.trading.ensure_symbol_selected","text":"ensure_symbol_selected ( client : Mt5TradingClient , symbol : str ) -> None Ensure a symbol is visible in Market Watch before sending orders. Parameters: Name Type Description Default client Mt5TradingClient Connected Mt5TradingClient instance. required symbol str Symbol to select. required Raises: Type Description Mt5TradingError If the symbol cannot be selected in Market Watch or symbol_select is unavailable on the client. Source code in mt5cli/trading.py 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 def ensure_symbol_selected ( client : Mt5TradingClient , symbol : str ) -> None : \"\"\"Ensure a symbol is visible in Market Watch before sending orders. Args: client: Connected ``Mt5TradingClient`` instance. symbol: Symbol to select. Raises: Mt5TradingError: If the symbol cannot be selected in Market Watch or ``symbol_select`` is unavailable on the client. \"\"\" snapshot = get_symbol_snapshot ( client , symbol ) if snapshot . get ( \"visible\" ): return select = getattr ( client , \"symbol_select\" , None ) if not callable ( select ): msg = \"MT5 client is missing required method: symbol_select\" raise Mt5TradingError ( msg ) if select ( symbol , enable = True ): return last_error = getattr ( client , \"last_error\" , None ) detail = f \" ( { last_error () } )\" if callable ( last_error ) else \"\" msg = f \"Failed to select symbol { symbol !r} in Market Watch { detail } .\" raise Mt5TradingError ( msg )","title":"ensure_symbol_selected"},{"location":"api/trading/#mt5cli.trading.estimate_order_margin","text":"estimate_order_margin ( client : Mt5TradingClient , symbol : str , order_side : OrderSide | str , volume : float , ) -> float Estimate required margin for one order at the current market price. Returns: Type Description float Positive finite margin required for the order at the current quote. Raises: Type Description Mt5TradingError If volume, tick data, or margin estimation is invalid. Source code in mt5cli/trading.py 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 def estimate_order_margin ( client : Mt5TradingClient , symbol : str , order_side : OrderSide | str , volume : float , ) -> float : \"\"\"Estimate required margin for one order at the current market price. Returns: Positive finite margin required for the order at the current quote. Raises: Mt5TradingError: If volume, tick data, or margin estimation is invalid. \"\"\" if not _is_positive_finite_number ( volume ): msg = \"Volume must be a positive finite number to estimate order margin.\" raise Mt5TradingError ( msg ) side = _normalize_order_side ( order_side ) tick = get_tick_snapshot ( client , symbol ) price = extract_tick_price ( tick , \"ask\" if side == \"BUY\" else \"bid\" ) if price is None : msg = f \"Tick price is unavailable for { symbol !r} .\" raise Mt5TradingError ( msg ) order_type = ( client . mt5 . ORDER_TYPE_BUY if side == \"BUY\" else client . mt5 . ORDER_TYPE_SELL ) raw_margin = client . order_calc_margin ( order_type , symbol , volume , price ) try : margin = float ( raw_margin ) except ( TypeError , ValueError ) as exc : msg = f \"Margin estimate is invalid for { symbol !r} .\" raise Mt5TradingError ( msg ) from exc if margin <= 0 or not isfinite ( margin ): msg = f \"Margin estimate is invalid for { symbol !r} .\" raise Mt5TradingError ( msg ) return margin","title":"estimate_order_margin"},{"location":"api/trading/#mt5cli.trading.extract_tick_price","text":"extract_tick_price ( tick : Mapping [ str , object ], key : str ) -> float | None Return a positive finite float from tick[key], or None if invalid. Accepts int, float, or numeric string values. Returns None when the key is missing, the value is None, non-numeric, NaN, infinite, zero, or negative. Booleans are treated as non-numeric and return None. Source code in mt5cli/trading.py 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 def extract_tick_price ( tick : Mapping [ str , object ], key : str ) -> float | None : \"\"\"Return a positive finite float from tick[key], or None if invalid. Accepts int, float, or numeric string values. Returns None when the key is missing, the value is None, non-numeric, NaN, infinite, zero, or negative. Booleans are treated as non-numeric and return None. \"\"\" value = tick . get ( key ) if value is None or isinstance ( value , bool ): return None if isinstance ( value , int | float ): price = float ( value ) elif isinstance ( value , str ): try : price = float ( value ) except ValueError : return None else : return None if not isfinite ( price ) or price <= 0 : return None return price","title":"extract_tick_price"},{"location":"api/trading/#mt5cli.trading.fetch_latest_closed_rates_for_trading_client","text":"fetch_latest_closed_rates_for_trading_client ( client : Mt5TradingClient , * , symbol : str , granularity : str , count : int , ) -> DataFrame Fetch the latest closed bars from a connected trading client. Returns: Type Description DataFrame Up to count closed bars ordered oldest to newest. Raises: Type Description ValueError If count is not positive, rate data is empty or malformed, or the time column is missing. Mt5TradingError If the trading client cannot fetch rate data. Source code in mt5cli/trading.py 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 def fetch_latest_closed_rates_for_trading_client ( client : Mt5TradingClient , * , symbol : str , granularity : str , count : int , ) -> pd . DataFrame : \"\"\"Fetch the latest closed bars from a connected trading client. Returns: Up to ``count`` closed bars ordered oldest to newest. Raises: ValueError: If ``count`` is not positive, rate data is empty or malformed, or the ``time`` column is missing. Mt5TradingError: If the trading client cannot fetch rate data. \"\"\" if count <= 0 : msg = \"count must be positive.\" raise ValueError ( msg ) fetch_method = getattr ( client , \"fetch_latest_rates_as_df\" , None ) if not callable ( fetch_method ): msg = \"MT5 trading client cannot fetch rate data.\" raise Mt5TradingError ( msg ) fetched = fetch_method ( symbol , granularity , count + 1 ) if not isinstance ( fetched , pd . DataFrame ): msg = ( f \"Malformed rate data for { symbol !r} at granularity { granularity !r} : \" \"expected a DataFrame.\" ) raise ValueError ( msg ) # noqa: TRY004 frame = fetched frame = _ensure_rate_time_column ( frame ) if \"time\" not in frame . columns : msg = f \"Rate data is missing a time column for { symbol !r} .\" raise ValueError ( msg ) closed = drop_forming_rate_bar ( frame ) if closed . empty : msg = ( f \"Rate data is empty for { symbol !r} at granularity { granularity !r} \" f \"with count { count } .\" ) raise ValueError ( msg ) return closed . tail ( count ) . reset_index ( drop = True )","title":"fetch_latest_closed_rates_for_trading_client"},{"location":"api/trading/#mt5cli.trading.fetch_latest_closed_rates_indexed","text":"fetch_latest_closed_rates_indexed ( client : Mt5TradingClient , * , symbol : str , granularity : str , count : int , ) -> DataFrame Fetch the latest closed bars with a UTC DatetimeIndex from a trading client. Internally reuses :func: fetch_latest_closed_rates_for_trading_client for closed-bar detection and validation, then converts the time column to a UTC-aware :class: ~pandas.DatetimeIndex named \"time\" and drops the original column. Intended for downstream time-series consumers that require a datetime index rather than a time column. Parameters: Name Type Description Default client Mt5TradingClient Connected trading client with rate-fetch capability. required symbol str Symbol name. required granularity str Timeframe string (for example \"M1\" , \"H1\" ). required count int Maximum number of closed bars to return. required Returns: Type Description DataFrame Up to count closed bars ordered oldest to newest, with a DataFrame UTC-aware DatetimeIndex named \"time\" . The original time DataFrame column is dropped. Raises: Type Description ValueError If count is not positive, rate data is empty or malformed, the time column is missing, or timestamp data is invalid or unparseable. Source code in mt5cli/trading.py 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 def fetch_latest_closed_rates_indexed ( client : Mt5TradingClient , * , symbol : str , granularity : str , count : int , ) -> pd . DataFrame : \"\"\"Fetch the latest closed bars with a UTC DatetimeIndex from a trading client. Internally reuses :func:`fetch_latest_closed_rates_for_trading_client` for closed-bar detection and validation, then converts the ``time`` column to a UTC-aware :class:`~pandas.DatetimeIndex` named ``\"time\"`` and drops the original column. Intended for downstream time-series consumers that require a datetime index rather than a ``time`` column. Args: client: Connected trading client with rate-fetch capability. symbol: Symbol name. granularity: Timeframe string (for example ``\"M1\"``, ``\"H1\"``). count: Maximum number of closed bars to return. Returns: Up to ``count`` closed bars ordered oldest to newest, with a UTC-aware ``DatetimeIndex`` named ``\"time\"``. The original ``time`` column is dropped. Raises: ValueError: If ``count`` is not positive, rate data is empty or malformed, the ``time`` column is missing, or timestamp data is invalid or unparseable. \"\"\" frame = fetch_latest_closed_rates_for_trading_client ( client , symbol = symbol , granularity = granularity , count = count , ) if \"time\" not in frame . columns : msg = f \"Rate data is missing a time column for { symbol !r} .\" raise ValueError ( msg ) idx = _rate_time_to_utc ( frame [ \"time\" ], symbol ) idx . name = \"time\" result = frame . drop ( columns = [ \"time\" ]) result . index = idx return result","title":"fetch_latest_closed_rates_indexed"},{"location":"api/trading/#mt5cli.trading.get_account_snapshot","text":"get_account_snapshot ( client : Mt5TradingClient , ) -> dict [ str , float | int | str | None ] Return normalized account state with stable keys. Source code in mt5cli/trading.py 569 570 571 572 573 574 575 576 577 def get_account_snapshot ( client : Mt5TradingClient , ) -> dict [ str , float | int | str | None ]: \"\"\"Return normalized account state with stable keys.\"\"\" value = _call_snapshot_method ( client , \"account_info_as_dict\" , \"account_info\" ) return cast ( \"dict[str, float | int | str | None]\" , _snapshot_from_value ( value , _ACCOUNT_SNAPSHOT_FIELDS ), )","title":"get_account_snapshot"},{"location":"api/trading/#mt5cli.trading.get_positions_frame","text":"get_positions_frame ( client : Mt5TradingClient , symbol : str | None = None ) -> DataFrame Return open positions as a DataFrame with stable baseline columns. Source code in mt5cli/trading.py 606 607 608 609 610 611 612 613 614 615 def get_positions_frame ( client : Mt5TradingClient , symbol : str | None = None , ) -> pd . DataFrame : \"\"\"Return open positions as a DataFrame with stable baseline columns.\"\"\" frame = client . positions_get_as_df ( symbol = symbol ) for column in POSITION_COLUMNS : if column not in frame . columns : frame [ column ] = pd . Series ( dtype = \"object\" ) return frame","title":"get_positions_frame"},{"location":"api/trading/#mt5cli.trading.get_symbol_snapshot","text":"get_symbol_snapshot ( client : Mt5TradingClient , symbol : str ) -> dict [ str , float | int | str | bool | None ] Return normalized symbol metadata required for trading decisions. Source code in mt5cli/trading.py 580 581 582 583 584 585 586 587 588 589 def get_symbol_snapshot ( client : Mt5TradingClient , symbol : str , ) -> dict [ str , float | int | str | bool | None ]: \"\"\"Return normalized symbol metadata required for trading decisions.\"\"\" method = getattr ( client , \"symbol_info_as_dict\" , None ) value = method ( symbol = symbol ) if callable ( method ) else client . symbol_info ( symbol ) snapshot = _snapshot_from_value ( value , _SYMBOL_SNAPSHOT_FIELDS ) snapshot [ \"symbol\" ] = snapshot . get ( \"symbol\" ) or symbol return cast ( \"dict[str, float | int | str | bool | None]\" , snapshot )","title":"get_symbol_snapshot"},{"location":"api/trading/#mt5cli.trading.get_tick_snapshot","text":"get_tick_snapshot ( client : Mt5TradingClient , symbol : str ) -> dict [ str , float | int | None ] Return normalized latest tick data, including bid, ask, and timestamp. Source code in mt5cli/trading.py 592 593 594 595 596 597 598 599 600 601 602 603 def get_tick_snapshot ( client : Mt5TradingClient , symbol : str , ) -> dict [ str , float | int | None ]: \"\"\"Return normalized latest tick data, including bid, ask, and timestamp.\"\"\" method = getattr ( client , \"symbol_info_tick_as_dict\" , None ) value = ( method ( symbol = symbol ) if callable ( method ) else client . symbol_info_tick ( symbol ) ) snapshot = _snapshot_from_value ( value , _TICK_SNAPSHOT_FIELDS ) snapshot [ \"symbol\" ] = snapshot . get ( \"symbol\" ) or symbol return cast ( \"dict[str, float | int | None]\" , snapshot )","title":"get_tick_snapshot"},{"location":"api/trading/#mt5cli.trading.mt5_trading_session","text":"mt5_trading_session ( config : Mt5Config | None = None , * , login : int | str | None = None , password : str | None = None , server : str | None = None , path : str | None = None , timeout : int | None = None , retry_count : int = 0 , ) -> Iterator [ Mt5TradingClient ] Open a trading-capable MT5 session and always shut down safely. Launches the MetaTrader 5 terminal using Mt5Config.path when set, initializes and logs in via initialize_and_login_mt5() , yields a connected :class: ~pdmt5.Mt5TradingClient , and calls shutdown() on exit even when an error is raised inside the context. Parameters: Name Type Description Default config Mt5Config | None MT5 connection configuration. Defaults to an empty config that attaches to a running terminal. None login int | str | None Optional trading account login. None password str | None Optional trading account password. None server str | None Optional trading server name. None path str | None Optional terminal executable path. None timeout int | None Optional connection timeout in milliseconds. None retry_count int Number of initialization retries passed to Mt5TradingClient . 0 Yields: Type Description Mt5TradingClient Connected Mt5TradingClient bound to the session. Source code in mt5cli/trading.py 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 @contextmanager def mt5_trading_session ( config : Mt5Config | None = None , * , login : int | str | None = None , password : str | None = None , server : str | None = None , path : str | None = None , timeout : int | None = None , retry_count : int = 0 , ) -> Iterator [ Mt5TradingClient ]: \"\"\"Open a trading-capable MT5 session and always shut down safely. Launches the MetaTrader 5 terminal using ``Mt5Config.path`` when set, initializes and logs in via ``initialize_and_login_mt5()``, yields a connected :class:`~pdmt5.Mt5TradingClient`, and calls ``shutdown()`` on exit even when an error is raised inside the context. Args: config: MT5 connection configuration. Defaults to an empty config that attaches to a running terminal. login: Optional trading account login. password: Optional trading account password. server: Optional trading server name. path: Optional terminal executable path. timeout: Optional connection timeout in milliseconds. retry_count: Number of initialization retries passed to ``Mt5TradingClient``. Yields: Connected ``Mt5TradingClient`` bound to the session. \"\"\" client = create_trading_client ( config = config , login = login , password = password , server = server , path = path , timeout = timeout , retry_count = retry_count , ) try : yield client finally : client . shutdown ()","title":"mt5_trading_session"},{"location":"api/trading/#mt5cli.trading.normalize_order_volume","text":"normalize_order_volume ( volume : float , * , volume_min : float , volume_max : float , volume_step : float , ) -> float Normalize a requested order volume to broker volume constraints. Returns: Type Description float Volume floored to the nearest valid broker step from volume_min , float capped at volume_max when finite and positive, and rounded float deterministically. Returns 0.0 when inputs or constraints are float invalid, non-finite, or the capped request is below volume_min . Source code in mt5cli/trading.py 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 def normalize_order_volume ( volume : float , * , volume_min : float , volume_max : float , volume_step : float , ) -> float : \"\"\"Normalize a requested order volume to broker volume constraints. Returns: Volume floored to the nearest valid broker step from ``volume_min``, capped at ``volume_max`` when finite and positive, and rounded deterministically. Returns ``0.0`` when inputs or constraints are invalid, non-finite, or the capped request is below ``volume_min``. \"\"\" if not _is_finite_number ( volume ): return 0.0 if not _is_positive_finite_number ( volume_min ): return 0.0 if not _is_positive_finite_number ( volume_step ): return 0.0 has_volume_cap = _is_positive_finite_number ( volume_max ) capped = min ( volume , volume_max ) if has_volume_cap else volume if capped < volume_min : return 0.0 steps = floor ((( capped - volume_min ) / volume_step ) + 1e-12 ) normalized = volume_min + max ( 0 , steps ) * volume_step if has_volume_cap : normalized = min ( normalized , volume_max ) return round ( normalized , 10 )","title":"normalize_order_volume"},{"location":"api/trading/#mt5cli.trading.place_market_order","text":"place_market_order ( client : Mt5TradingClient , * , symbol : str , volume : float , order_side : OrderSide , order_filling_mode : OrderFillingMode = \"IOC\" , order_time_mode : OrderTimeMode = \"GTC\" , sl : float | None = None , tp : float | None = None , position : int | None = None , dry_run : bool = False , ) -> OrderExecutionResult Place one normalized market order or return a dry-run result. pdmt5.Mt5TradingClient.order_send() raises only when MT5 returns no response. When MT5 returns a response with a known non-success retcode, this helper returns status=\"failed\" and keeps the normalized response details for callers to inspect. Returns: Type Description OrderExecutionResult Normalized execution result containing request and response details. Raises: Type Description Mt5TradingError If volume or required tick data is invalid. Source code in mt5cli/trading.py 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 def place_market_order ( client : Mt5TradingClient , * , symbol : str , volume : float , order_side : OrderSide , order_filling_mode : OrderFillingMode = \"IOC\" , order_time_mode : OrderTimeMode = \"GTC\" , sl : float | None = None , tp : float | None = None , position : int | None = None , dry_run : bool = False , ) -> OrderExecutionResult : \"\"\"Place one normalized market order or return a dry-run result. ``pdmt5.Mt5TradingClient.order_send()`` raises only when MT5 returns no response. When MT5 returns a response with a known non-success retcode, this helper returns ``status=\"failed\"`` and keeps the normalized response details for callers to inspect. Returns: Normalized execution result containing request and response details. Raises: Mt5TradingError: If volume or required tick data is invalid. \"\"\" if volume <= 0 : msg = \"volume must be positive.\" raise Mt5TradingError ( msg ) side = _normalize_order_side ( order_side ) if not dry_run : ensure_symbol_selected ( client , symbol ) tick = get_tick_snapshot ( client , symbol ) price = extract_tick_price ( tick , \"ask\" if side == \"BUY\" else \"bid\" ) if price is None : msg = f \"Tick price is unavailable for { symbol !r} .\" raise Mt5TradingError ( msg ) request = { \"action\" : client . mt5 . TRADE_ACTION_DEAL , \"symbol\" : symbol , \"volume\" : volume , \"type\" : ( client . mt5 . ORDER_TYPE_BUY if side == \"BUY\" else client . mt5 . ORDER_TYPE_SELL ), \"price\" : price , \"type_filling\" : _resolve_mt5_constant ( client . mt5 , \"ORDER_FILLING\" , order_filling_mode , _ORDER_FILLING_MODES , ), \"type_time\" : _resolve_mt5_constant ( client . mt5 , \"ORDER_TIME\" , order_time_mode , _ORDER_TIME_MODES , ), } if sl is not None : request [ \"sl\" ] = sl if tp is not None : request [ \"tp\" ] = tp if position is not None : request [ \"position\" ] = position if dry_run : return { \"status\" : \"dry_run\" , \"symbol\" : symbol , \"order_side\" : side , \"volume\" : volume , \"retcode\" : None , \"comment\" : None , \"request\" : cast ( \"dict[str, object]\" , request ), \"response\" : None , \"dry_run\" : True , } response = client . order_send ( request ) response_dict = _snapshot_from_value ( response , ()) raw_retcode = response_dict . get ( \"retcode\" ) retcode = _optional_int ( raw_retcode ) return { \"status\" : _order_status_from_retcode ( client . mt5 , raw_retcode ), \"symbol\" : symbol , \"order_side\" : side , \"volume\" : volume , \"retcode\" : retcode , \"comment\" : _optional_str ( response_dict . get ( \"comment\" )), \"request\" : cast ( \"dict[str, object]\" , request ), \"response\" : response_dict , \"dry_run\" : False , }","title":"place_market_order"},{"location":"api/trading/#mt5cli.trading.update_sltp_for_open_positions","text":"update_sltp_for_open_positions ( client : Mt5TradingClient , * , symbol : str | None = None , tickets : list [ int ] | None = None , stop_loss : float | None = None , take_profit : float | None = None , dry_run : bool = False , ) -> list [ OrderExecutionResult ] Update SL/TP for matching open positions. Returns: Type Description list [ OrderExecutionResult ] Normalized execution results for matching positions. Source code in mt5cli/trading.py 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 def update_sltp_for_open_positions ( client : Mt5TradingClient , * , symbol : str | None = None , tickets : list [ int ] | None = None , stop_loss : float | None = None , take_profit : float | None = None , dry_run : bool = False , ) -> list [ OrderExecutionResult ]: \"\"\"Update SL/TP for matching open positions. Returns: Normalized execution results for matching positions. \"\"\" positions = _filter_positions ( get_positions_frame ( client ), symbols = symbol , tickets = tickets , ) results : list [ OrderExecutionResult ] = [] for row in positions . to_dict ( \"records\" ): request = { \"action\" : client . mt5 . TRADE_ACTION_SLTP , \"symbol\" : row [ \"symbol\" ], \"position\" : row [ \"ticket\" ], } sl = _optional_price ( row . get ( \"sl\" ) if stop_loss is None else stop_loss ) tp = _optional_price ( row . get ( \"tp\" ) if take_profit is None else take_profit ) if sl is not None : request [ \"sl\" ] = sl if tp is not None : request [ \"tp\" ] = tp if dry_run : response = None status : ExecutionStatus = \"dry_run\" else : ensure_symbol_selected ( client , str ( row [ \"symbol\" ])) response = _snapshot_from_value ( client . order_send ( request ), ()) status = _order_status_from_retcode ( client . mt5 , response . get ( \"retcode\" ), ) results . append ( { \"status\" : status , \"symbol\" : str ( row [ \"symbol\" ]), \"order_side\" : \"BUY\" if row [ \"type\" ] == client . mt5 . POSITION_TYPE_BUY else \"SELL\" , \"volume\" : float ( row [ \"volume\" ]), \"retcode\" : None if response is None else _optional_int ( response . get ( \"retcode\" )), \"comment\" : None if response is None else _optional_str ( response . get ( \"comment\" )), \"request\" : cast ( \"dict[str, object]\" , request ), \"response\" : response , \"dry_run\" : dry_run , }, ) return results","title":"update_sltp_for_open_positions"},{"location":"api/trading/#mt5cli.trading.update_trailing_stop_loss_for_open_positions","text":"update_trailing_stop_loss_for_open_positions ( client : Mt5TradingClient , * , symbol : str , trailing_stop_ratio : float , dry_run : bool = False , ) -> list [ OrderExecutionResult ] Update open positions whose trailing stop loss should move favorably. Returns: Type Description list [ OrderExecutionResult ] Normalized execution results for positions that need an SL update. Source code in mt5cli/trading.py 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 def update_trailing_stop_loss_for_open_positions ( client : Mt5TradingClient , * , symbol : str , trailing_stop_ratio : float , dry_run : bool = False , ) -> list [ OrderExecutionResult ]: \"\"\"Update open positions whose trailing stop loss should move favorably. Returns: Normalized execution results for positions that need an SL update. \"\"\" updates = calculate_trailing_stop_updates ( client , symbol = symbol , trailing_stop_ratio = trailing_stop_ratio , ) results : list [ OrderExecutionResult ] = [] for ticket , stop_loss in updates . items (): results . extend ( update_sltp_for_open_positions ( client , symbol = symbol , tickets = [ ticket ], stop_loss = stop_loss , dry_run = dry_run , ), ) return results","title":"update_trailing_stop_loss_for_open_positions"},{"location":"api/trading/#trading-capable-mt5-sessions","text":"create_trading_client() and mt5_trading_session() complement the read-only mt5_session() helper in sdk.py . They return or yield an initialized pdmt5.Mt5TradingClient , use Mt5Config.path to launch the terminal when configured, and mt5_trading_session() always calls shutdown() on exit. from mt5cli import create_trading_client , mt5_trading_session with mt5_trading_session ( path = r \"C:\\Program Files\\MetaTrader 5\\terminal64.exe\" , login = \"12345\" , password = \"secret\" , server = \"Broker-Demo\" , retry_count = 2 , ) as client : positions = client . positions_get_as_df ( symbol = \"EURUSD\" ) client = create_trading_client ( login = 12345 , server = \"Broker-Demo\" ) try : account = client . account_info_as_dict () finally : client . shutdown () login accepts int , numeric str , or an empty string; empty strings are treated as unset. path , password , server , and timeout are forwarded to pdmt5.Mt5Config , and omitted timeout values keep the lower-level default. Use mt5_session() / MT5Client for read-only data collection.","title":"Trading-capable MT5 sessions"},{"location":"api/trading/#state-and-order-helpers","text":"These helpers are strategy-agnostic and do not depend on signal detection, betting logic, or scheduling code in downstream applications. from mt5cli import ( calculate_positions_margin , calculate_spread_ratio , calculate_margin_and_volume , close_open_positions , detect_position_side , determine_order_limits , estimate_order_margin , fetch_latest_closed_rates_for_trading_client , fetch_latest_closed_rates_indexed , get_account_snapshot , get_positions_frame , get_symbol_snapshot , get_tick_snapshot , normalize_order_volume , place_market_order , ) account = get_account_snapshot ( client ) symbol = get_symbol_snapshot ( client , \"EURUSD\" ) tick = get_tick_snapshot ( client , \"EURUSD\" ) positions = get_positions_frame ( client , \"EURUSD\" ) side = detect_position_side ( client , \"EURUSD\" ) spread_ratio = calculate_spread_ratio ( client , \"EURUSD\" ) volume = normalize_order_volume ( 0.15 , volume_min = symbol [ \"volume_min\" ], volume_max = symbol [ \"volume_max\" ], volume_step = symbol [ \"volume_step\" ], ) buy_margin = ( estimate_order_margin ( client , \"EURUSD\" , \"BUY\" , volume ) if volume > 0 else 0.0 ) open_margin = calculate_positions_margin ( client , symbols = [ \"EURUSD\" ]) closed_bars = fetch_latest_closed_rates_for_trading_client ( client , symbol = \"EURUSD\" , granularity = \"M1\" , count = 100 , ) # Or fetch with a UTC DatetimeIndex instead of a \"time\" column: indexed_bars = fetch_latest_closed_rates_indexed ( client , symbol = \"EURUSD\" , granularity = \"M1\" , count = 100 , ) # indexed_bars.index is a UTC-aware DatetimeIndex named \"time\" 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 , ) preview = place_market_order ( client , symbol = \"EURUSD\" , volume = sizing [ \"buy_volume\" ], order_side = \"BUY\" , sl = limits [ \"stop_loss\" ], tp = limits [ \"take_profit\" ], dry_run = True , ) closed = close_open_positions ( client , symbols = \"EURUSD\" , dry_run = True ) detect_position_side() returns long for buy-only exposure, short for sell-only exposure, and None for no positions or mixed long/short exposure. calculate_spread_ratio() uses (ask - bid) / ((ask + bid) / 2) and raises Mt5TradingError when bid or ask is missing or non-positive. normalize_order_volume() returns 0.0 for invalid constraints or sub-minimum requests; check the result before calling estimate_order_margin() , which requires a positive finite volume. calculate_positions_margin() silently skips rows with missing symbols, non-positive volumes, non-finite volumes, or unsupported position types, but propagates Mt5TradingError from estimate_order_margin() when a valid row encounters invalid tick data or margin results from the broker. SL/TP ratios for determine_order_limits() must satisfy 0 <= ratio < 1 ; 0 omits that level. SL/TP prices are rounded with symbol digits metadata when available. determine_order_limits() pre-validates computed SL/TP prices against available trade_stops_level * point metadata when present; violations raise Mt5TradingError . This is a planning helper only: it does not guarantee broker acceptance because live validation can still depend on price movement, bid/ask side, freeze levels, and server-side rules, and it does not validate trade_freeze_level . When symbol metadata cannot be loaded, protective prices still round with digits=8 and stop-level validation is skipped. unit_margin_ratio and preserved_margin_ratio for calculate_margin_and_volume() accept 0 <= ratio <= 1 ; unit_margin_ratio=0 requests one minimum valid unit when the post-reserve margin can afford it. Negative margin_free is clamped to 0.0 before sizing. Execution helpers return normalized OrderExecutionResult dictionaries containing the request, response, status, retcode, and dry_run flag; dry_run=True never sends an order or mutates Market Watch visibility. ensure_symbol_selected() adds hidden symbols to Market Watch before live order placement and SL/TP updates. Failed, malformed, or unknown broker retcodes are fail-closed and returned as status=\"failed\" while keeping the normalized response for inspection.","title":"State and order helpers"},{"location":"api/trading/#order-planning-return-contracts","text":"from mt5cli import MarginVolume , OrderLimits , OrderExecutionResult sizing : MarginVolume = calculate_margin_and_volume ( client , \"EURUSD\" , unit_margin_ratio = 0.5 , preserved_margin_ratio = 0.2 , ) limits : OrderLimits = determine_order_limits ( client , \"EURUSD\" , side = \"long\" , stop_loss_limit_ratio = 0.01 , take_profit_limit_ratio = 0.02 , ) preview : OrderExecutionResult = place_market_order ( client , symbol = \"EURUSD\" , volume = sizing [ \"buy_volume\" ], order_side = \"BUY\" , sl = limits [ \"stop_loss\" ], tp = limits [ \"take_profit\" ], dry_run = True , ) updates : list [ OrderExecutionResult ] = update_sltp_for_open_positions ( client , symbol = \"EURUSD\" , stop_loss = limits [ \"stop_loss\" ], dry_run = True , ) Closes issue #33: strategy-neutral order planning and execution helpers exposed through the stable package root without embedding entry/exit policy.","title":"Order planning return contracts"},{"location":"api/trading/#migration-from-application-local-helpers","text":"Application-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 broker volume step normalization normalize_order_volume() Local order or position margin estimation estimate_order_margin() , calculate_positions_margin() Local closed-bar fetch from a trading session fetch_latest_closed_rates_for_trading_client() , fetch_latest_closed_rates_indexed() 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() / MT5Client ; use mt5_trading_session() only where order placement or trading calculations are required.","title":"Migration from application-local helpers"},{"location":"api/utils/","text":"Utils Module \u00b6 mt5cli.utils \u00b6 Utility constants, types, and functions for the mt5cli package. DATETIME_TYPE module-attribute \u00b6 DATETIME_TYPE = _DateTimeType () REQUEST_TYPE module-attribute \u00b6 REQUEST_TYPE = _RequestType () TICK_FLAGS_TYPE module-attribute \u00b6 TICK_FLAGS_TYPE = _TickFlagsType () TICK_FLAG_MAP module-attribute \u00b6 TICK_FLAG_MAP : dict [ str , int ] = dict ( COPY_TICKS_MAP ) TIMEFRAME_NAMES module-attribute \u00b6 TIMEFRAME_NAMES : tuple [ str , ... ] = tuple ( name for name in TIMEFRAME_MAP if not startswith ( \"TIMEFRAME_\" ) ) TIMEFRAME_TYPE module-attribute \u00b6 TIMEFRAME_TYPE = _TimeframeType () Dataset \u00b6 Bases: StrEnum Datasets supported by the collect-history command. history_deals class-attribute instance-attribute \u00b6 history_deals = 'history-deals' history_orders class-attribute instance-attribute \u00b6 history_orders = 'history-orders' rates class-attribute instance-attribute \u00b6 rates = 'rates' table_name property \u00b6 table_name : str Return the SQLite table name for this dataset. ticks class-attribute instance-attribute \u00b6 ticks = 'ticks' IfExists \u00b6 Bases: StrEnum SQLite table conflict behavior for the collect-history command. APPEND class-attribute instance-attribute \u00b6 APPEND = 'append' FAIL class-attribute instance-attribute \u00b6 FAIL = 'fail' REPLACE class-attribute instance-attribute \u00b6 REPLACE = 'replace' LogLevel \u00b6 Bases: StrEnum Logging verbosity levels. DEBUG class-attribute instance-attribute \u00b6 DEBUG = 'DEBUG' ERROR class-attribute instance-attribute \u00b6 ERROR = 'ERROR' INFO class-attribute instance-attribute \u00b6 INFO = 'INFO' WARNING class-attribute instance-attribute \u00b6 WARNING = 'WARNING' OutputFormat \u00b6 Bases: StrEnum Supported output file formats. csv class-attribute instance-attribute \u00b6 csv = 'csv' json class-attribute instance-attribute \u00b6 json = 'json' parquet class-attribute instance-attribute \u00b6 parquet = 'parquet' sqlite3 class-attribute instance-attribute \u00b6 sqlite3 = 'sqlite3' coerce_login \u00b6 coerce_login ( login : int | str | None ) -> int | None Coerce a login value to int, treating empty strings as unset. Returns: Type Description int | None Integer login, or None when unset or an empty string. Source code in mt5cli/utils.py 244 245 246 247 248 249 250 251 252 253 254 255 def coerce_login ( login : int | str | None ) -> int | None : \"\"\"Coerce a login value to int, treating empty strings as unset. Returns: Integer login, or None when unset or an empty string. \"\"\" if login is None or isinstance ( login , int ): return login text = login . strip () if not text : return None return int ( text ) detect_format \u00b6 detect_format ( output_path : Path , explicit_format : str | None = None ) -> str Detect the output format from a file extension or explicit format string. Parameters: Name Type Description Default output_path Path Path to the output file. required explicit_format str | None Explicitly specified format, if any. None Returns: Type Description str The detected format string. Raises: Type Description ValueError If the format cannot be determined. Source code in mt5cli/utils.py 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 def detect_format ( output_path : Path , explicit_format : str | None = None , ) -> str : \"\"\"Detect the output format from a file extension or explicit format string. Args: output_path: Path to the output file. explicit_format: Explicitly specified format, if any. Returns: The detected format string. Raises: ValueError: If the format cannot be determined. \"\"\" if explicit_format is not None : return explicit_format suffix = output_path . suffix . lower () if suffix in _FORMAT_EXTENSIONS : return _FORMAT_EXTENSIONS [ suffix ] msg = ( f \"Cannot detect format from extension ' { suffix } '.\" \" Use --format to specify the output format.\" ) raise ValueError ( msg ) export_dataframe \u00b6 export_dataframe ( df : DataFrame , output_path : Path , output_format : str , table_name : str = \"data\" , ) -> None Export a pandas DataFrame to the specified file format. Parameters: Name Type Description Default df DataFrame DataFrame to export. required output_path Path Path to the output file. required output_format str Output format (csv, json, parquet, or sqlite3). required table_name str Table name for SQLite3 output. 'data' Raises: Type Description ValueError If the output format is not supported. Source code in mt5cli/utils.py 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 def export_dataframe ( df : pd . DataFrame , output_path : Path , output_format : str , table_name : str = \"data\" , ) -> None : \"\"\"Export a pandas DataFrame to the specified file format. Args: df: DataFrame to export. output_path: Path to the output file. output_format: Output format (csv, json, parquet, or sqlite3). table_name: Table name for SQLite3 output. Raises: ValueError: If the output format is not supported. \"\"\" if output_format == \"csv\" : df . to_csv ( output_path , index = False ) elif output_format == \"json\" : df . to_json ( output_path , orient = \"records\" , date_format = \"iso\" , indent = 2 , ) elif output_format == \"parquet\" : df . to_parquet ( output_path , index = False ) elif output_format == \"sqlite3\" : export_dataframe_to_sqlite ( df , output_path , table_name , if_exists = IfExists . REPLACE , index = False , ) else : msg = f \"Unsupported output format: { output_format } \" raise ValueError ( msg ) export_dataframe_to_sqlite \u00b6 export_dataframe_to_sqlite ( df : DataFrame , output_path : Path , table_name : str = \"data\" , * , if_exists : IfExists = APPEND , index : bool = False , index_label : str | None = None , deduplicate_on : Sequence [ str ] | None = None , ) -> None Write a DataFrame to SQLite with configurable append and deduplication. Parameters: Name Type Description Default df DataFrame DataFrame to export. required output_path Path SQLite database path. required table_name str Target table name. 'data' if_exists IfExists Conflict behavior when the table already exists. APPEND index bool Whether to write the DataFrame index as a column. False index_label str | None Column name for the index when index=True . None deduplicate_on Sequence [ str ] | None Optional key columns to deduplicate after writing, keeping the latest ROWID per key group. Deduplication scans the full table, so repeated appends cost O(table size); index the key columns when appending frequently. None Source code in mt5cli/utils.py 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 def export_dataframe_to_sqlite ( df : pd . DataFrame , output_path : Path , table_name : str = \"data\" , * , if_exists : IfExists = IfExists . APPEND , index : bool = False , index_label : str | None = None , deduplicate_on : Sequence [ str ] | None = None , ) -> None : \"\"\"Write a DataFrame to SQLite with configurable append and deduplication. Args: df: DataFrame to export. output_path: SQLite database path. table_name: Target table name. if_exists: Conflict behavior when the table already exists. index: Whether to write the DataFrame index as a column. index_label: Column name for the index when ``index=True``. deduplicate_on: Optional key columns to deduplicate after writing, keeping the latest ``ROWID`` per key group. Deduplication scans the full table, so repeated appends cost O(table size); index the key columns when appending frequently. \"\"\" with sqlite3 . connect ( output_path ) as conn : df . to_sql ( # type: ignore[reportUnknownMemberType] table_name , conn , if_exists = if_exists . value , index = index , index_label = index_label , ) if deduplicate_on : from .history import drop_duplicates_in_table # noqa: PLC0415 drop_duplicates_in_table ( conn . cursor (), table_name , list ( deduplicate_on ), keep = \"last\" , ) conn . commit () parse_datetime \u00b6 parse_datetime ( value : str ) -> datetime Parse an ISO 8601 datetime string to a timezone-aware datetime. Parameters: Name Type Description Default value str ISO 8601 datetime string (e.g., '2024-01-01' or '2024-01-01T12:00:00+00:00'). required Returns: Type Description datetime Parsed datetime with UTC timezone if no timezone is specified. Raises: Type Description ValueError If the string cannot be parsed. Source code in mt5cli/utils.py 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 def parse_datetime ( value : str ) -> datetime : \"\"\"Parse an ISO 8601 datetime string to a timezone-aware datetime. Args: value: ISO 8601 datetime string (e.g., '2024-01-01' or '2024-01-01T12:00:00+00:00'). Returns: Parsed datetime with UTC timezone if no timezone is specified. Raises: ValueError: If the string cannot be parsed. \"\"\" try : dt = datetime . fromisoformat ( value ) except ValueError : msg = f \"Invalid datetime format: ' { value } '. Use ISO 8601 format.\" raise ValueError ( msg ) from None if dt . tzinfo is None : dt = dt . replace ( tzinfo = UTC ) return dt parse_request \u00b6 parse_request ( value : str ) -> dict [ str , Any ] Parse a JSON-formatted order request string or file reference. Parameters: Name Type Description Default value str JSON object string, or '@path' to read JSON from a file. required Returns: Type Description dict [ str , Any ] Parsed request dictionary. Raises: Type Description ValueError If the request file cannot be read or the value is not a JSON object. Source code in mt5cli/utils.py 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 def parse_request ( value : str ) -> dict [ str , Any ]: \"\"\"Parse a JSON-formatted order request string or file reference. Args: value: JSON object string, or '@path' to read JSON from a file. Returns: Parsed request dictionary. Raises: ValueError: If the request file cannot be read or the value is not a JSON object. \"\"\" if value . startswith ( \"@\" ): path = Path ( value [ 1 :]) try : text = path . read_text ( encoding = \"utf-8\" ) except ( OSError , UnicodeDecodeError ) as exc : msg = f \"Failed to read JSON request file ' { path } ': { exc } \" raise ValueError ( msg ) from exc else : text = value try : parsed : object = json . loads ( text ) except json . JSONDecodeError as exc : msg = f \"Invalid JSON request: { exc } \" raise ValueError ( msg ) from exc if not _is_request_dict ( parsed ): msg = \"Order request must be a JSON object.\" raise ValueError ( msg ) return parsed parse_tick_flags \u00b6 parse_tick_flags ( value : object ) -> int Parse tick flags string or integer value. Parameters: Name Type Description Default value object Tick flag name (ALL, INFO, TRADE, COPY_TICKS_*) or integer value. required Returns: Type Description int Integer tick flag value compatible with MetaTrader 5 COPY_TICKS_* . Raises: Type Description ValueError If the flag is invalid. Source code in mt5cli/utils.py 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 def parse_tick_flags ( value : object ) -> int : \"\"\"Parse tick flags string or integer value. Args: value: Tick flag name (ALL, INFO, TRADE, COPY_TICKS_*) or integer value. Returns: Integer tick flag value compatible with MetaTrader 5 ``COPY_TICKS_*``. Raises: ValueError: If the flag is invalid. \"\"\" try : return _parse_copy_ticks ( value ) except ValueError : display = value if isinstance ( value , str ) else repr ( value ) valid = \", \" . join ( _TICK_FLAG_NAMES ) msg = ( f \"Invalid tick flags: ' { display } '. \" f \"Use one of: { valid } , or a supported integer.\" ) raise ValueError ( msg ) from None parse_timeframe \u00b6 parse_timeframe ( value : object ) -> int Parse a timeframe string or integer value. Parameters: Name Type Description Default value object Timeframe name (e.g., 'M1', 'H1', 'D1') or integer value. required Returns: Type Description int Integer timeframe value. Raises: Type Description ValueError If the timeframe is invalid. Source code in mt5cli/utils.py 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 def parse_timeframe ( value : object ) -> int : \"\"\"Parse a timeframe string or integer value. Args: value: Timeframe name (e.g., 'M1', 'H1', 'D1') or integer value. Returns: Integer timeframe value. Raises: ValueError: If the timeframe is invalid. \"\"\" try : return _parse_timeframe ( value ) except ValueError : display = value if isinstance ( value , str ) else repr ( value ) valid = \", \" . join ( TIMEFRAME_NAMES ) msg = ( f \"Invalid timeframe: ' { display } '. \" f \"Use one of: { valid } , or a supported integer.\" ) raise ValueError ( msg ) from None","title":"Utils"},{"location":"api/utils/#utils-module","text":"","title":"Utils Module"},{"location":"api/utils/#mt5cli.utils","text":"Utility constants, types, and functions for the mt5cli package.","title":"utils"},{"location":"api/utils/#mt5cli.utils.DATETIME_TYPE","text":"DATETIME_TYPE = _DateTimeType ()","title":"DATETIME_TYPE"},{"location":"api/utils/#mt5cli.utils.REQUEST_TYPE","text":"REQUEST_TYPE = _RequestType ()","title":"REQUEST_TYPE"},{"location":"api/utils/#mt5cli.utils.TICK_FLAGS_TYPE","text":"TICK_FLAGS_TYPE = _TickFlagsType ()","title":"TICK_FLAGS_TYPE"},{"location":"api/utils/#mt5cli.utils.TICK_FLAG_MAP","text":"TICK_FLAG_MAP : dict [ str , int ] = dict ( COPY_TICKS_MAP )","title":"TICK_FLAG_MAP"},{"location":"api/utils/#mt5cli.utils.TIMEFRAME_NAMES","text":"TIMEFRAME_NAMES : tuple [ str , ... ] = tuple ( name for name in TIMEFRAME_MAP if not startswith ( \"TIMEFRAME_\" ) )","title":"TIMEFRAME_NAMES"},{"location":"api/utils/#mt5cli.utils.TIMEFRAME_TYPE","text":"TIMEFRAME_TYPE = _TimeframeType ()","title":"TIMEFRAME_TYPE"},{"location":"api/utils/#mt5cli.utils.Dataset","text":"Bases: StrEnum Datasets supported by the collect-history command.","title":"Dataset"},{"location":"api/utils/#mt5cli.utils.Dataset.history_deals","text":"history_deals = 'history-deals'","title":"history_deals"},{"location":"api/utils/#mt5cli.utils.Dataset.history_orders","text":"history_orders = 'history-orders'","title":"history_orders"},{"location":"api/utils/#mt5cli.utils.Dataset.rates","text":"rates = 'rates'","title":"rates"},{"location":"api/utils/#mt5cli.utils.Dataset.table_name","text":"table_name : str Return the SQLite table name for this dataset.","title":"table_name"},{"location":"api/utils/#mt5cli.utils.Dataset.ticks","text":"ticks = 'ticks'","title":"ticks"},{"location":"api/utils/#mt5cli.utils.IfExists","text":"Bases: StrEnum SQLite table conflict behavior for the collect-history command.","title":"IfExists"},{"location":"api/utils/#mt5cli.utils.IfExists.APPEND","text":"APPEND = 'append'","title":"APPEND"},{"location":"api/utils/#mt5cli.utils.IfExists.FAIL","text":"FAIL = 'fail'","title":"FAIL"},{"location":"api/utils/#mt5cli.utils.IfExists.REPLACE","text":"REPLACE = 'replace'","title":"REPLACE"},{"location":"api/utils/#mt5cli.utils.LogLevel","text":"Bases: StrEnum Logging verbosity levels.","title":"LogLevel"},{"location":"api/utils/#mt5cli.utils.LogLevel.DEBUG","text":"DEBUG = 'DEBUG'","title":"DEBUG"},{"location":"api/utils/#mt5cli.utils.LogLevel.ERROR","text":"ERROR = 'ERROR'","title":"ERROR"},{"location":"api/utils/#mt5cli.utils.LogLevel.INFO","text":"INFO = 'INFO'","title":"INFO"},{"location":"api/utils/#mt5cli.utils.LogLevel.WARNING","text":"WARNING = 'WARNING'","title":"WARNING"},{"location":"api/utils/#mt5cli.utils.OutputFormat","text":"Bases: StrEnum Supported output file formats.","title":"OutputFormat"},{"location":"api/utils/#mt5cli.utils.OutputFormat.csv","text":"csv = 'csv'","title":"csv"},{"location":"api/utils/#mt5cli.utils.OutputFormat.json","text":"json = 'json'","title":"json"},{"location":"api/utils/#mt5cli.utils.OutputFormat.parquet","text":"parquet = 'parquet'","title":"parquet"},{"location":"api/utils/#mt5cli.utils.OutputFormat.sqlite3","text":"sqlite3 = 'sqlite3'","title":"sqlite3"},{"location":"api/utils/#mt5cli.utils.coerce_login","text":"coerce_login ( login : int | str | None ) -> int | None Coerce a login value to int, treating empty strings as unset. Returns: Type Description int | None Integer login, or None when unset or an empty string. Source code in mt5cli/utils.py 244 245 246 247 248 249 250 251 252 253 254 255 def coerce_login ( login : int | str | None ) -> int | None : \"\"\"Coerce a login value to int, treating empty strings as unset. Returns: Integer login, or None when unset or an empty string. \"\"\" if login is None or isinstance ( login , int ): return login text = login . strip () if not text : return None return int ( text )","title":"coerce_login"},{"location":"api/utils/#mt5cli.utils.detect_format","text":"detect_format ( output_path : Path , explicit_format : str | None = None ) -> str Detect the output format from a file extension or explicit format string. Parameters: Name Type Description Default output_path Path Path to the output file. required explicit_format str | None Explicitly specified format, if any. None Returns: Type Description str The detected format string. Raises: Type Description ValueError If the format cannot be determined. Source code in mt5cli/utils.py 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 def detect_format ( output_path : Path , explicit_format : str | None = None , ) -> str : \"\"\"Detect the output format from a file extension or explicit format string. Args: output_path: Path to the output file. explicit_format: Explicitly specified format, if any. Returns: The detected format string. Raises: ValueError: If the format cannot be determined. \"\"\" if explicit_format is not None : return explicit_format suffix = output_path . suffix . lower () if suffix in _FORMAT_EXTENSIONS : return _FORMAT_EXTENSIONS [ suffix ] msg = ( f \"Cannot detect format from extension ' { suffix } '.\" \" Use --format to specify the output format.\" ) raise ValueError ( msg )","title":"detect_format"},{"location":"api/utils/#mt5cli.utils.export_dataframe","text":"export_dataframe ( df : DataFrame , output_path : Path , output_format : str , table_name : str = \"data\" , ) -> None Export a pandas DataFrame to the specified file format. Parameters: Name Type Description Default df DataFrame DataFrame to export. required output_path Path Path to the output file. required output_format str Output format (csv, json, parquet, or sqlite3). required table_name str Table name for SQLite3 output. 'data' Raises: Type Description ValueError If the output format is not supported. Source code in mt5cli/utils.py 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 def export_dataframe ( df : pd . DataFrame , output_path : Path , output_format : str , table_name : str = \"data\" , ) -> None : \"\"\"Export a pandas DataFrame to the specified file format. Args: df: DataFrame to export. output_path: Path to the output file. output_format: Output format (csv, json, parquet, or sqlite3). table_name: Table name for SQLite3 output. Raises: ValueError: If the output format is not supported. \"\"\" if output_format == \"csv\" : df . to_csv ( output_path , index = False ) elif output_format == \"json\" : df . to_json ( output_path , orient = \"records\" , date_format = \"iso\" , indent = 2 , ) elif output_format == \"parquet\" : df . to_parquet ( output_path , index = False ) elif output_format == \"sqlite3\" : export_dataframe_to_sqlite ( df , output_path , table_name , if_exists = IfExists . REPLACE , index = False , ) else : msg = f \"Unsupported output format: { output_format } \" raise ValueError ( msg )","title":"export_dataframe"},{"location":"api/utils/#mt5cli.utils.export_dataframe_to_sqlite","text":"export_dataframe_to_sqlite ( df : DataFrame , output_path : Path , table_name : str = \"data\" , * , if_exists : IfExists = APPEND , index : bool = False , index_label : str | None = None , deduplicate_on : Sequence [ str ] | None = None , ) -> None Write a DataFrame to SQLite with configurable append and deduplication. Parameters: Name Type Description Default df DataFrame DataFrame to export. required output_path Path SQLite database path. required table_name str Target table name. 'data' if_exists IfExists Conflict behavior when the table already exists. APPEND index bool Whether to write the DataFrame index as a column. False index_label str | None Column name for the index when index=True . None deduplicate_on Sequence [ str ] | None Optional key columns to deduplicate after writing, keeping the latest ROWID per key group. Deduplication scans the full table, so repeated appends cost O(table size); index the key columns when appending frequently. None Source code in mt5cli/utils.py 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 def export_dataframe_to_sqlite ( df : pd . DataFrame , output_path : Path , table_name : str = \"data\" , * , if_exists : IfExists = IfExists . APPEND , index : bool = False , index_label : str | None = None , deduplicate_on : Sequence [ str ] | None = None , ) -> None : \"\"\"Write a DataFrame to SQLite with configurable append and deduplication. Args: df: DataFrame to export. output_path: SQLite database path. table_name: Target table name. if_exists: Conflict behavior when the table already exists. index: Whether to write the DataFrame index as a column. index_label: Column name for the index when ``index=True``. deduplicate_on: Optional key columns to deduplicate after writing, keeping the latest ``ROWID`` per key group. Deduplication scans the full table, so repeated appends cost O(table size); index the key columns when appending frequently. \"\"\" with sqlite3 . connect ( output_path ) as conn : df . to_sql ( # type: ignore[reportUnknownMemberType] table_name , conn , if_exists = if_exists . value , index = index , index_label = index_label , ) if deduplicate_on : from .history import drop_duplicates_in_table # noqa: PLC0415 drop_duplicates_in_table ( conn . cursor (), table_name , list ( deduplicate_on ), keep = \"last\" , ) conn . commit ()","title":"export_dataframe_to_sqlite"},{"location":"api/utils/#mt5cli.utils.parse_datetime","text":"parse_datetime ( value : str ) -> datetime Parse an ISO 8601 datetime string to a timezone-aware datetime. Parameters: Name Type Description Default value str ISO 8601 datetime string (e.g., '2024-01-01' or '2024-01-01T12:00:00+00:00'). required Returns: Type Description datetime Parsed datetime with UTC timezone if no timezone is specified. Raises: Type Description ValueError If the string cannot be parsed. Source code in mt5cli/utils.py 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 def parse_datetime ( value : str ) -> datetime : \"\"\"Parse an ISO 8601 datetime string to a timezone-aware datetime. Args: value: ISO 8601 datetime string (e.g., '2024-01-01' or '2024-01-01T12:00:00+00:00'). Returns: Parsed datetime with UTC timezone if no timezone is specified. Raises: ValueError: If the string cannot be parsed. \"\"\" try : dt = datetime . fromisoformat ( value ) except ValueError : msg = f \"Invalid datetime format: ' { value } '. Use ISO 8601 format.\" raise ValueError ( msg ) from None if dt . tzinfo is None : dt = dt . replace ( tzinfo = UTC ) return dt","title":"parse_datetime"},{"location":"api/utils/#mt5cli.utils.parse_request","text":"parse_request ( value : str ) -> dict [ str , Any ] Parse a JSON-formatted order request string or file reference. Parameters: Name Type Description Default value str JSON object string, or '@path' to read JSON from a file. required Returns: Type Description dict [ str , Any ] Parsed request dictionary. Raises: Type Description ValueError If the request file cannot be read or the value is not a JSON object. Source code in mt5cli/utils.py 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 def parse_request ( value : str ) -> dict [ str , Any ]: \"\"\"Parse a JSON-formatted order request string or file reference. Args: value: JSON object string, or '@path' to read JSON from a file. Returns: Parsed request dictionary. Raises: ValueError: If the request file cannot be read or the value is not a JSON object. \"\"\" if value . startswith ( \"@\" ): path = Path ( value [ 1 :]) try : text = path . read_text ( encoding = \"utf-8\" ) except ( OSError , UnicodeDecodeError ) as exc : msg = f \"Failed to read JSON request file ' { path } ': { exc } \" raise ValueError ( msg ) from exc else : text = value try : parsed : object = json . loads ( text ) except json . JSONDecodeError as exc : msg = f \"Invalid JSON request: { exc } \" raise ValueError ( msg ) from exc if not _is_request_dict ( parsed ): msg = \"Order request must be a JSON object.\" raise ValueError ( msg ) return parsed","title":"parse_request"},{"location":"api/utils/#mt5cli.utils.parse_tick_flags","text":"parse_tick_flags ( value : object ) -> int Parse tick flags string or integer value. Parameters: Name Type Description Default value object Tick flag name (ALL, INFO, TRADE, COPY_TICKS_*) or integer value. required Returns: Type Description int Integer tick flag value compatible with MetaTrader 5 COPY_TICKS_* . Raises: Type Description ValueError If the flag is invalid. Source code in mt5cli/utils.py 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 def parse_tick_flags ( value : object ) -> int : \"\"\"Parse tick flags string or integer value. Args: value: Tick flag name (ALL, INFO, TRADE, COPY_TICKS_*) or integer value. Returns: Integer tick flag value compatible with MetaTrader 5 ``COPY_TICKS_*``. Raises: ValueError: If the flag is invalid. \"\"\" try : return _parse_copy_ticks ( value ) except ValueError : display = value if isinstance ( value , str ) else repr ( value ) valid = \", \" . join ( _TICK_FLAG_NAMES ) msg = ( f \"Invalid tick flags: ' { display } '. \" f \"Use one of: { valid } , or a supported integer.\" ) raise ValueError ( msg ) from None","title":"parse_tick_flags"},{"location":"api/utils/#mt5cli.utils.parse_timeframe","text":"parse_timeframe ( value : object ) -> int Parse a timeframe string or integer value. Parameters: Name Type Description Default value object Timeframe name (e.g., 'M1', 'H1', 'D1') or integer value. required Returns: Type Description int Integer timeframe value. Raises: Type Description ValueError If the timeframe is invalid. Source code in mt5cli/utils.py 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 def parse_timeframe ( value : object ) -> int : \"\"\"Parse a timeframe string or integer value. Args: value: Timeframe name (e.g., 'M1', 'H1', 'D1') or integer value. Returns: Integer timeframe value. Raises: ValueError: If the timeframe is invalid. \"\"\" try : return _parse_timeframe ( value ) except ValueError : display = value if isinstance ( value , str ) else repr ( value ) valid = \", \" . join ( TIMEFRAME_NAMES ) msg = ( f \"Invalid timeframe: ' { display } '. \" f \"Use one of: { valid } , or a supported integer.\" ) raise ValueError ( msg ) from None","title":"parse_timeframe"}]} \ No newline at end of file +{"config":{"indexing":"full","lang":["en"],"min_search_length":3,"prebuild_index":false,"separator":"[\\s\\-]+"},"docs":[{"location":"","text":"mt5cli \u00b6 Generic MT5 data and execution infrastructure for Python applications. Overview \u00b6 mt5cli provides a stable MT5Client Python API, standardized dataset schemas, storage helpers, and a CLI for exporting MetaTrader 5 data. It is built on top of pdmt5 , a pandas-based data handler for MetaTrader 5. Architecture \u00b6 pdmt5 \u2014 canonical MT5 client, DataFrame/trading primitives, and MT5 constant parsing ( TIMEFRAME_* , COPY_TICKS_* , order types). mt5cli \u2014 public MT5Client API, schema contracts, storage helpers, CLI commands, and SQLite history collection built on pdmt5. mt5api \u2014 sibling HTTP adapter for remote MT5 access; not a dependency of mt5cli. Features \u00b6 Multi-format export : CSV, JSON, Parquet, and SQLite3 output formats Auto-detection : Format detection from file extensions Comprehensive data access : Rates, ticks, account info, symbols, orders, positions, and trading history Flexible timeframes : Named timeframes (M1, H1, D1, etc.) and numeric values Connection management : Optional credentials, server, and timeout configuration SQLite rate loading : Load mt5cli-managed rate tables/views for offline workflows Installation \u00b6 pip install mt5cli Python API for downstream packages \u00b6 Import MT5Client for generic MT5 data access, schema normalization, and optional order primitives. from datetime import UTC , datetime from pathlib import Path from mt5cli import ( DataKind , Dataset , MT5Client , build_config , collect_history , export_dataframe , load_rate_data , minimum_margins , mt5_session , normalize_dataframe , recent_ticks , resolve_rate_view_name , ) # Persistent session for multiple calls with mt5_session ( build_config ( login = 12345 , server = \"Broker-Demo\" )) as client : rates = client . copy_rates_range ( \"EURUSD\" , timeframe = \"H1\" , date_from = \"2024-01-01\" , date_to = \"2024-02-01\" , ) positions = client . positions () check = client . order_check ({ \"action\" : 1 , \"symbol\" : \"EURUSD\" , \"volume\" : 0.1 }) # Normalize MT5 frames to the public schema contract before storage closed_rates = normalize_dataframe ( rates , DataKind . rates , symbol = \"EURUSD\" , timeframe = \"H1\" ) export_dataframe ( closed_rates , Path ( \"rates.csv\" ), \"csv\" ) # Offline rate loading from mt5cli-managed SQLite history view = resolve_rate_view_name ( Path ( \"history.db\" ), \"EURUSD\" , \"M1\" , require_existing = True ) offline_rates = load_rate_data ( Path ( \"history.db\" ), view , count = 1000 ) # One-off helpers still work without instantiating a client ticks = recent_ticks ( \"EURUSD\" , seconds = 300 ) margins = minimum_margins ( \"EURUSD\" ) collect_history ( Path ( \"history.db\" ), symbols = [ \"EURUSD\" , \"GBPUSD\" ], date_from = datetime ( 2024 , 1 , 1 , tzinfo = UTC ), date_to = datetime ( 2024 , 2 , 1 , tzinfo = UTC ), datasets = { Dataset . rates , Dataset . history_deals }, ) Schema contracts live in mt5cli.schemas ( DataKind , validate_schema , normalize_dataframe ). Storage helpers are re-exported from mt5cli.storage and the package root. MT5Client.order_send() is a live execution primitive: it can place real trades on the connected account. mt5cli does not implement strategy logic, signal generation, backtesting, or optimization \u2014 downstream applications must gate live execution explicitly (the CLI requires --yes for order-send ). MT5Client.mt5_summary() returns structured nested Python values. Use MT5Client.mt5_summary_as_df() when you need a one-row DataFrame for export. Quick Start \u00b6 # Export account information to CSV mt5cli -o account.csv account-info # Export EURUSD M1 rates to Parquet mt5cli -o rates.parquet rates-from --symbol EURUSD --timeframe M1 \\ --date-from 2024 -01-01 --count 1000 # Export ticks to JSON mt5cli -o ticks.json ticks-from --symbol EURUSD \\ --date-from 2024 -01-01 --count 500 --flags ALL # Export symbols to SQLite3 with custom table name mt5cli -o data.db --table symbols symbols --group \"*USD*\" # Export with connection credentials mt5cli --login 12345 --password mypass --server MyBroker-Demo \\ -o positions.csv positions Commands \u00b6 Rates \u00b6 Command Description rates-from Export rates from a start date rates-from-pos Export rates from a start position latest-rates Export latest rates rates-range Export rates for a date range Ticks \u00b6 Command Description ticks-from Export ticks from a start date ticks-range Export ticks for a date range ticks-recent Export ticks from a trailing window Information \u00b6 Command Description account-info Export account information terminal-info Export terminal information version Export MetaTrader 5 version information last-error Export the last error information symbols Export symbol list symbol-info Export symbol details symbol-info-tick Export the last tick for a symbol minimum-margins Export minimum-volume margin summary market-book Export market depth (order book) Trading \u00b6 Command Description orders Export active orders positions Export open positions history-orders Export historical orders history-deals Export historical deals recent-history-deals Export historical deals from a trailing window mt5-summary Export terminal/account status summary order-check Check funds sufficiency for a trade request order-send Send a trade request to the trade server ( --yes required) Use order-check to validate a request payload before running order-send --yes . Bulk Collection \u00b6 Command Description collect-history Collect rates, ticks, history-orders, and history-deals for one or more symbols into a single SQLite database (optional cash-event/position views) mt5cli -o history.db collect-history \\ --symbol EURUSD --symbol GBPUSD \\ --date-from 2024 -01-01 --date-to 2024 -02-01 \\ --dataset rates --dataset history-deals \\ --timeframe M1 --flags ALL --if-exists append --with-views collect-history options: Option Default Description --symbol/-s required Symbol to collect (repeat for multiple). --date-from required Start date in ISO 8601. --date-to required End date in ISO 8601. --dataset all four Repeatable: rates , ticks , history-orders , history-deals . --timeframe M1 Rates timeframe; recorded in a timeframe column on the rates table. --flags ALL Tick copy flags forwarded to copy_ticks_range . --if-exists fail append , replace , or fail when a target table already exists. --with-views off Add cash_events and positions_reconstructed views (requires the history-deals dataset). History orders and deals are fetched per symbol and concatenated, so the symbol filter is applied consistently across all datasets. The cash_events view is derived from symbol-filtered history_deals , so account-level cash events with empty or non-matching symbols may be excluded. The positions_reconstructed view excludes positions with no closing deal, uses volume-weighted open/close prices, and reports reversal deals ( DEAL_ENTRY_INOUT ) via volume_reversal / reversal_count . See the History schema diagram for a sample ER layout of the resulting database. Global Options \u00b6 Option Description -o, --output Output file path (required) -f, --format Output format (auto-detected from extension if omitted) --table Table name for SQLite3 output (default: \"data\") --login Trading account login --password Trading account password --server Trading server name --path Path to MetaTrader5 terminal EXE file --timeout Connection timeout in milliseconds --log-level Logging level (DEBUG, INFO, WARNING, ERROR) Requirements \u00b6 Python 3.11+ Windows OS (MetaTrader 5 requirement) MetaTrader 5 platform API Reference \u00b6 Browse the API documentation for detailed module information: CLI Module - CLI application with export commands SDK Module - Programmatic read-only data collection API Utils Module - Constants, parameter types, parsers, and export utilities Development \u00b6 This project follows strict code quality standards: Type hints required (strict mode) Comprehensive linting with Ruff Test coverage tracking Google-style docstrings License \u00b6 MIT License - see LICENSE file for details.","title":"Home"},{"location":"#mt5cli","text":"Generic MT5 data and execution infrastructure for Python applications.","title":"mt5cli"},{"location":"#overview","text":"mt5cli provides a stable MT5Client Python API, standardized dataset schemas, storage helpers, and a CLI for exporting MetaTrader 5 data. It is built on top of pdmt5 , a pandas-based data handler for MetaTrader 5.","title":"Overview"},{"location":"#architecture","text":"pdmt5 \u2014 canonical MT5 client, DataFrame/trading primitives, and MT5 constant parsing ( TIMEFRAME_* , COPY_TICKS_* , order types). mt5cli \u2014 public MT5Client API, schema contracts, storage helpers, CLI commands, and SQLite history collection built on pdmt5. mt5api \u2014 sibling HTTP adapter for remote MT5 access; not a dependency of mt5cli.","title":"Architecture"},{"location":"#features","text":"Multi-format export : CSV, JSON, Parquet, and SQLite3 output formats Auto-detection : Format detection from file extensions Comprehensive data access : Rates, ticks, account info, symbols, orders, positions, and trading history Flexible timeframes : Named timeframes (M1, H1, D1, etc.) and numeric values Connection management : Optional credentials, server, and timeout configuration SQLite rate loading : Load mt5cli-managed rate tables/views for offline workflows","title":"Features"},{"location":"#installation","text":"pip install mt5cli","title":"Installation"},{"location":"#python-api-for-downstream-packages","text":"Import MT5Client for generic MT5 data access, schema normalization, and optional order primitives. from datetime import UTC , datetime from pathlib import Path from mt5cli import ( DataKind , Dataset , MT5Client , build_config , collect_history , export_dataframe , load_rate_data , minimum_margins , mt5_session , normalize_dataframe , recent_ticks , resolve_rate_view_name , ) # Persistent session for multiple calls with mt5_session ( build_config ( login = 12345 , server = \"Broker-Demo\" )) as client : rates = client . copy_rates_range ( \"EURUSD\" , timeframe = \"H1\" , date_from = \"2024-01-01\" , date_to = \"2024-02-01\" , ) positions = client . positions () check = client . order_check ({ \"action\" : 1 , \"symbol\" : \"EURUSD\" , \"volume\" : 0.1 }) # Normalize MT5 frames to the public schema contract before storage closed_rates = normalize_dataframe ( rates , DataKind . rates , symbol = \"EURUSD\" , timeframe = \"H1\" ) export_dataframe ( closed_rates , Path ( \"rates.csv\" ), \"csv\" ) # Offline rate loading from mt5cli-managed SQLite history view = resolve_rate_view_name ( Path ( \"history.db\" ), \"EURUSD\" , \"M1\" , require_existing = True ) offline_rates = load_rate_data ( Path ( \"history.db\" ), view , count = 1000 ) # One-off helpers still work without instantiating a client ticks = recent_ticks ( \"EURUSD\" , seconds = 300 ) margins = minimum_margins ( \"EURUSD\" ) collect_history ( Path ( \"history.db\" ), symbols = [ \"EURUSD\" , \"GBPUSD\" ], date_from = datetime ( 2024 , 1 , 1 , tzinfo = UTC ), date_to = datetime ( 2024 , 2 , 1 , tzinfo = UTC ), datasets = { Dataset . rates , Dataset . history_deals }, ) Schema contracts live in mt5cli.schemas ( DataKind , validate_schema , normalize_dataframe ). Storage helpers are re-exported from mt5cli.storage and the package root. MT5Client.order_send() is a live execution primitive: it can place real trades on the connected account. mt5cli does not implement strategy logic, signal generation, backtesting, or optimization \u2014 downstream applications must gate live execution explicitly (the CLI requires --yes for order-send ). MT5Client.mt5_summary() returns structured nested Python values. Use MT5Client.mt5_summary_as_df() when you need a one-row DataFrame for export.","title":"Python API for downstream packages"},{"location":"#quick-start","text":"# Export account information to CSV mt5cli -o account.csv account-info # Export EURUSD M1 rates to Parquet mt5cli -o rates.parquet rates-from --symbol EURUSD --timeframe M1 \\ --date-from 2024 -01-01 --count 1000 # Export ticks to JSON mt5cli -o ticks.json ticks-from --symbol EURUSD \\ --date-from 2024 -01-01 --count 500 --flags ALL # Export symbols to SQLite3 with custom table name mt5cli -o data.db --table symbols symbols --group \"*USD*\" # Export with connection credentials mt5cli --login 12345 --password mypass --server MyBroker-Demo \\ -o positions.csv positions","title":"Quick Start"},{"location":"#commands","text":"","title":"Commands"},{"location":"#rates","text":"Command Description rates-from Export rates from a start date rates-from-pos Export rates from a start position latest-rates Export latest rates rates-range Export rates for a date range","title":"Rates"},{"location":"#ticks","text":"Command Description ticks-from Export ticks from a start date ticks-range Export ticks for a date range ticks-recent Export ticks from a trailing window","title":"Ticks"},{"location":"#information","text":"Command Description account-info Export account information terminal-info Export terminal information version Export MetaTrader 5 version information last-error Export the last error information symbols Export symbol list symbol-info Export symbol details symbol-info-tick Export the last tick for a symbol minimum-margins Export minimum-volume margin summary market-book Export market depth (order book)","title":"Information"},{"location":"#trading","text":"Command Description orders Export active orders positions Export open positions history-orders Export historical orders history-deals Export historical deals recent-history-deals Export historical deals from a trailing window mt5-summary Export terminal/account status summary order-check Check funds sufficiency for a trade request order-send Send a trade request to the trade server ( --yes required) Use order-check to validate a request payload before running order-send --yes .","title":"Trading"},{"location":"#bulk-collection","text":"Command Description collect-history Collect rates, ticks, history-orders, and history-deals for one or more symbols into a single SQLite database (optional cash-event/position views) mt5cli -o history.db collect-history \\ --symbol EURUSD --symbol GBPUSD \\ --date-from 2024 -01-01 --date-to 2024 -02-01 \\ --dataset rates --dataset history-deals \\ --timeframe M1 --flags ALL --if-exists append --with-views collect-history options: Option Default Description --symbol/-s required Symbol to collect (repeat for multiple). --date-from required Start date in ISO 8601. --date-to required End date in ISO 8601. --dataset all four Repeatable: rates , ticks , history-orders , history-deals . --timeframe M1 Rates timeframe; recorded in a timeframe column on the rates table. --flags ALL Tick copy flags forwarded to copy_ticks_range . --if-exists fail append , replace , or fail when a target table already exists. --with-views off Add cash_events and positions_reconstructed views (requires the history-deals dataset). History orders and deals are fetched per symbol and concatenated, so the symbol filter is applied consistently across all datasets. The cash_events view is derived from symbol-filtered history_deals , so account-level cash events with empty or non-matching symbols may be excluded. The positions_reconstructed view excludes positions with no closing deal, uses volume-weighted open/close prices, and reports reversal deals ( DEAL_ENTRY_INOUT ) via volume_reversal / reversal_count . See the History schema diagram for a sample ER layout of the resulting database.","title":"Bulk Collection"},{"location":"#global-options","text":"Option Description -o, --output Output file path (required) -f, --format Output format (auto-detected from extension if omitted) --table Table name for SQLite3 output (default: \"data\") --login Trading account login --password Trading account password --server Trading server name --path Path to MetaTrader5 terminal EXE file --timeout Connection timeout in milliseconds --log-level Logging level (DEBUG, INFO, WARNING, ERROR)","title":"Global Options"},{"location":"#requirements","text":"Python 3.11+ Windows OS (MetaTrader 5 requirement) MetaTrader 5 platform","title":"Requirements"},{"location":"#api-reference","text":"Browse the API documentation for detailed module information: CLI Module - CLI application with export commands SDK Module - Programmatic read-only data collection API Utils Module - Constants, parameter types, parsers, and export utilities","title":"API Reference"},{"location":"#development","text":"This project follows strict code quality standards: Type hints required (strict mode) Comprehensive linting with Ruff Test coverage tracking Google-style docstrings","title":"Development"},{"location":"#license","text":"MIT License - see LICENSE file for details.","title":"License"},{"location":"api/","text":"API Reference \u00b6 This section documents the mt5cli public Python API and CLI modules. Start with the Public API Contract for the stable downstream SDK surface, CLI boundary, internal modules, and out-of-scope strategy responsibilities. Public API layers \u00b6 Module Purpose Public API Contract Stable downstream SDK exports, CLI boundary, and out-of-scope items Client MT5Client session abstraction for data access and order primitives Schemas Canonical DataFrame contracts and normalization helpers Storage CSV/JSON/Parquet/SQLite export and history collection helpers Converters Symbol, timeframe, timezone, and date-range utilities Exceptions Stable mt5cli exception types and MT5 error normalization SDK Module-level fetch helpers, multi-account collectors, incremental history Trading Trading-capable sessions and operational helpers History Collection (SQLite) SQLite schema, incremental writes, dedup, and rate views CLI Typer commands that delegate to the Python API Utils Parsing helpers and Click parameter types Architecture overview \u00b6 flowchart TD App[\"Downstream application\"] --> Client[\"MT5Client\"] CLI[\"mt5cli CLI\"] --> Client Client --> SDK[\"sdk / pdmt5\"] Client --> Schemas[\"schemas\"] Storage[\"storage\"] --> History[\"history SQLite\"] Storage --> Utils[\"utils export\"] SDK --> PDMT5[\"pdmt5.Mt5DataClient\"] Downstream packages should depend on the package root exports documented in the Public API Contract ( MT5Client , DataKind , normalize_dataframe , collect_history , load_rate_data , resolve_rate_view_name , etc.) rather than private modules. MT5Client.order_send() is a live execution primitive that can place real trades. mt5cli exposes minimal execution helpers only; strategy logic, signals, backtests, and optimization remain out of scope and must be implemented downstream with explicit execution gating. Quick start \u00b6 from mt5cli import MT5Client , build_config , mt5_session with mt5_session ( build_config ( login = 12345 )) as client : rates = client . copy_rates_range ( \"EURUSD\" , \"H1\" , \"2024-01-01\" , \"2024-02-01\" ) positions = client . positions () mt5cli -o account.csv account-info mt5cli -o rates.parquet rates-range --symbol EURUSD --timeframe H1 \\ --date-from 2024 -01-01 --date-to 2024 -02-01 See individual module pages for detailed usage examples.","title":"Overview"},{"location":"api/#api-reference","text":"This section documents the mt5cli public Python API and CLI modules. Start with the Public API Contract for the stable downstream SDK surface, CLI boundary, internal modules, and out-of-scope strategy responsibilities.","title":"API Reference"},{"location":"api/#public-api-layers","text":"Module Purpose Public API Contract Stable downstream SDK exports, CLI boundary, and out-of-scope items Client MT5Client session abstraction for data access and order primitives Schemas Canonical DataFrame contracts and normalization helpers Storage CSV/JSON/Parquet/SQLite export and history collection helpers Converters Symbol, timeframe, timezone, and date-range utilities Exceptions Stable mt5cli exception types and MT5 error normalization SDK Module-level fetch helpers, multi-account collectors, incremental history Trading Trading-capable sessions and operational helpers History Collection (SQLite) SQLite schema, incremental writes, dedup, and rate views CLI Typer commands that delegate to the Python API Utils Parsing helpers and Click parameter types","title":"Public API layers"},{"location":"api/#architecture-overview","text":"flowchart TD App[\"Downstream application\"] --> Client[\"MT5Client\"] CLI[\"mt5cli CLI\"] --> Client Client --> SDK[\"sdk / pdmt5\"] Client --> Schemas[\"schemas\"] Storage[\"storage\"] --> History[\"history SQLite\"] Storage --> Utils[\"utils export\"] SDK --> PDMT5[\"pdmt5.Mt5DataClient\"] Downstream packages should depend on the package root exports documented in the Public API Contract ( MT5Client , DataKind , normalize_dataframe , collect_history , load_rate_data , resolve_rate_view_name , etc.) rather than private modules. MT5Client.order_send() is a live execution primitive that can place real trades. mt5cli exposes minimal execution helpers only; strategy logic, signals, backtests, and optimization remain out of scope and must be implemented downstream with explicit execution gating.","title":"Architecture overview"},{"location":"api/#quick-start","text":"from mt5cli import MT5Client , build_config , mt5_session with mt5_session ( build_config ( login = 12345 )) as client : rates = client . copy_rates_range ( \"EURUSD\" , \"H1\" , \"2024-01-01\" , \"2024-02-01\" ) positions = client . positions () mt5cli -o account.csv account-info mt5cli -o rates.parquet rates-range --symbol EURUSD --timeframe H1 \\ --date-from 2024 -01-01 --date-to 2024 -02-01 See individual module pages for detailed usage examples.","title":"Quick start"},{"location":"api/cli/","text":"CLI Module \u00b6 mt5cli.cli \u00b6 Command-line interface for MetaTrader 5 data export. app module-attribute \u00b6 app = Typer ( name = \"mt5cli\" , help = \"Export MetaTrader5 data to CSV, JSON, Parquet, or SQLite3.\" , ) logger module-attribute \u00b6 logger = getLogger ( __name__ ) account_info \u00b6 account_info ( ctx : Context ) -> None Export account information. Source code in mt5cli/cli.py 380 381 382 383 @app . command () def account_info ( ctx : typer . Context ) -> None : \"\"\"Export account information.\"\"\" _export_command ( ctx , lambda client : client . account_info ()) close_positions \u00b6 close_positions ( ctx : Context , symbol : Annotated [ list [ str ] | None , Option ( \"--symbol\" , \"-s\" , help = \"Symbol to close (repeat for multiple symbols).\" , ), ] = None , ticket : Annotated [ list [ int ] | None , Option ( \"--ticket\" , \"-t\" , help = \"Position ticket to close (repeat for multiple tickets).\" , ), ] = None , dry_run : Annotated [ bool , Option ( \"--dry-run\" , help = \"Preview close orders without executing them.\" , ), ] = False , yes : Annotated [ bool , Option ( \"--yes\" , help = \"Confirm live position closing.\" ), ] = False , ) -> None Close open positions by symbol or ticket. Delegates to :func: mt5cli.trading.close_open_positions . At least one --symbol or --ticket must be provided to avoid accidentally closing all positions. Use --dry-run to preview without executing; --yes is required for live execution. order-send is the expert raw-request path. close-positions is the safer high-level helper that builds correct close requests automatically. Raises: Type Description BadParameter If neither --symbol nor --ticket is given, or if --yes is missing for a live (non-dry-run) run. Source code in mt5cli/cli.py 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 @app . command () def close_positions ( ctx : typer . Context , symbol : Annotated [ list [ str ] | None , typer . Option ( \"--symbol\" , \"-s\" , help = \"Symbol to close (repeat for multiple symbols).\" , ), ] = None , ticket : Annotated [ list [ int ] | None , typer . Option ( \"--ticket\" , \"-t\" , help = \"Position ticket to close (repeat for multiple tickets).\" , ), ] = None , dry_run : Annotated [ bool , typer . Option ( \"--dry-run\" , help = \"Preview close orders without executing them.\" ), ] = False , yes : Annotated [ bool , typer . Option ( \"--yes\" , help = \"Confirm live position closing.\" ), ] = False , ) -> None : \"\"\"Close open positions by symbol or ticket. Delegates to :func:`mt5cli.trading.close_open_positions`. At least one ``--symbol`` or ``--ticket`` must be provided to avoid accidentally closing all positions. Use ``--dry-run`` to preview without executing; ``--yes`` is required for live execution. ``order-send`` is the expert raw-request path. ``close-positions`` is the safer high-level helper that builds correct close requests automatically. Raises: typer.BadParameter: If neither ``--symbol`` nor ``--ticket`` is given, or if ``--yes`` is missing for a live (non-dry-run) run. \"\"\" if not symbol and not ticket : msg = \"Provide at least one --symbol or --ticket to close positions.\" raise typer . BadParameter ( msg ) if not dry_run and not yes : msg = \"Pass --yes to close live positions.\" raise typer . BadParameter ( msg , param_hint = \"--yes\" ) export_ctx = _get_export_context ( ctx ) client = create_trading_client ( config = export_ctx . config ) try : results = close_open_positions ( client , symbols = list ( symbol ) if symbol else None , tickets = list ( ticket ) if ticket else None , dry_run = dry_run , ) finally : client . shutdown () df = _execution_results_to_df ( results ) _execute_export ( ctx , lambda : df ) collect_history \u00b6 collect_history ( ctx : Context , symbol : Annotated [ list [ str ], Option ( \"--symbol\" , \"-s\" , help = \"Symbol to collect (repeat for multiple symbols).\" , ), ], date_from : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], date_to : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ], dataset : Annotated [ list [ Dataset ] | None , Option ( \"--dataset\" , help = \"Dataset to include (repeat for multiple). Defaults to all: rates, ticks, history-orders, history-deals.\" , ), ] = None , timeframe : Annotated [ int , Option ( click_type = TIMEFRAME_TYPE , help = \"Rates timeframe (e.g., M1, H1, D1).\" , ), ] = 1 , flags : Annotated [ int , Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick copy flags (ALL, INFO, TRADE, or integer).\" , ), ] = \"ALL\" , if_exists : Annotated [ IfExists , Option ( \"--if-exists\" , help = \"Behavior when a target table already exists.\" , ), ] = FAIL , with_views : Annotated [ bool , Option ( \"--with-views\" , help = \"Add cash_events and positions_reconstructed SQLite views derived from history_deals.\" , ), ] = False , ) -> None Collect historical datasets into a single SQLite database. Tables written depend on --dataset : rates , ticks , history_orders , history_deals . History datasets are fetched per symbol and concatenated. Rates rows carry the requested timeframe so appended runs at different timeframes remain distinguishable. With --with-views (requires the history-deals dataset), optional views cash_events and positions_reconstructed are derived from history_deals when the required columns are present. Raises: Type Description BadParameter If the output format is not SQLite3. Source code in mt5cli/cli.py 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 @app . command () def collect_history ( ctx : typer . Context , symbol : Annotated [ list [ str ], typer . Option ( \"--symbol\" , \"-s\" , help = \"Symbol to collect (repeat for multiple symbols).\" , ), ], date_from : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], date_to : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ], dataset : Annotated [ list [ Dataset ] | None , typer . Option ( \"--dataset\" , help = ( \"Dataset to include (repeat for multiple).\" \" Defaults to all: rates, ticks, history-orders, history-deals.\" ), ), ] = None , timeframe : Annotated [ int , typer . Option ( click_type = TIMEFRAME_TYPE , help = \"Rates timeframe (e.g., M1, H1, D1).\" , ), ] = 1 , flags : Annotated [ int , typer . Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick copy flags (ALL, INFO, TRADE, or integer).\" , ), ] = \"ALL\" , # pyright: ignore[reportArgumentType] if_exists : Annotated [ IfExists , typer . Option ( \"--if-exists\" , help = \"Behavior when a target table already exists.\" , ), ] = IfExists . FAIL , with_views : Annotated [ bool , typer . Option ( \"--with-views\" , help = ( \"Add cash_events and positions_reconstructed SQLite views\" \" derived from history_deals.\" ), ), ] = False , ) -> None : \"\"\"Collect historical datasets into a single SQLite database. Tables written depend on ``--dataset``: ``rates``, ``ticks``, ``history_orders``, ``history_deals``. History datasets are fetched per symbol and concatenated. Rates rows carry the requested ``timeframe`` so appended runs at different timeframes remain distinguishable. With ``--with-views`` (requires the ``history-deals`` dataset), optional views ``cash_events`` and ``positions_reconstructed`` are derived from ``history_deals`` when the required columns are present. Raises: typer.BadParameter: If the output format is not SQLite3. \"\"\" export_ctx = _get_export_context ( ctx ) if export_ctx . output_format != \"sqlite3\" : msg = ( \"collect-history requires SQLite3 output.\" \" Use a .db/.sqlite/.sqlite3 extension or --format sqlite3.\" ) raise typer . BadParameter ( msg ) datasets = set ( dataset ) if dataset else set ( Dataset ) sdk . collect_history ( output = export_ctx . output , symbols = symbol , date_from = date_from , date_to = date_to , datasets = datasets , timeframe = timeframe , flags = flags , if_exists = if_exists , with_views = with_views , config = export_ctx . config , ) history_deals \u00b6 history_deals ( ctx : Context , date_from : Annotated [ datetime | None , Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ] = None , date_to : Annotated [ datetime | None , Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ] = None , group : Annotated [ str | None , Option ( help = \"Group filter.\" ) ] = None , symbol : Annotated [ str | None , Option ( help = \"Symbol filter.\" ) ] = None , ticket : Annotated [ int | None , Option ( help = \"Order ticket.\" ) ] = None , position : Annotated [ int | None , Option ( help = \"Position ticket.\" ) ] = None , ) -> None Export historical deals. Source code in mt5cli/cli.py 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 @app . command () def history_deals ( ctx : typer . Context , date_from : Annotated [ datetime | None , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ] = None , date_to : Annotated [ datetime | None , typer . Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ] = None , group : Annotated [ str | None , typer . Option ( help = \"Group filter.\" )] = None , symbol : Annotated [ str | None , typer . Option ( help = \"Symbol filter.\" )] = None , ticket : Annotated [ int | None , typer . Option ( help = \"Order ticket.\" )] = None , position : Annotated [ int | None , typer . Option ( help = \"Position ticket.\" )] = None , ) -> None : \"\"\"Export historical deals.\"\"\" _export_command ( ctx , lambda client : client . history_deals ( date_from = date_from , date_to = date_to , group = group , symbol = symbol , ticket = ticket , position = position , ), ) history_orders \u00b6 history_orders ( ctx : Context , date_from : Annotated [ datetime | None , Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ] = None , date_to : Annotated [ datetime | None , Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ] = None , group : Annotated [ str | None , Option ( help = \"Group filter.\" ) ] = None , symbol : Annotated [ str | None , Option ( help = \"Symbol filter.\" ) ] = None , ticket : Annotated [ int | None , Option ( help = \"Order ticket.\" ) ] = None , position : Annotated [ int | None , Option ( help = \"Position ticket.\" ) ] = None , ) -> None Export historical orders. Source code in mt5cli/cli.py 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 @app . command () def history_orders ( ctx : typer . Context , date_from : Annotated [ datetime | None , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ] = None , date_to : Annotated [ datetime | None , typer . Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ] = None , group : Annotated [ str | None , typer . Option ( help = \"Group filter.\" )] = None , symbol : Annotated [ str | None , typer . Option ( help = \"Symbol filter.\" )] = None , ticket : Annotated [ int | None , typer . Option ( help = \"Order ticket.\" )] = None , position : Annotated [ int | None , typer . Option ( help = \"Position ticket.\" )] = None , ) -> None : \"\"\"Export historical orders.\"\"\" _export_command ( ctx , lambda client : client . history_orders ( date_from = date_from , date_to = date_to , group = group , symbol = symbol , ticket = ticket , position = position , ), ) last_error \u00b6 last_error ( ctx : Context ) -> None Export the last error information. Source code in mt5cli/cli.py 545 546 547 548 @app . command () def last_error ( ctx : typer . Context ) -> None : \"\"\"Export the last error information.\"\"\" _export_command ( ctx , lambda client : client . last_error ()) latest_rates \u00b6 latest_rates ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe.\" ), ], count : Annotated [ int , Option ( help = \"Number of records.\" ) ], start_pos : Annotated [ int , Option ( help = \"Start position (0 = current bar).\" ), ] = 0 , ) -> None Export latest rates from a start position. Source code in mt5cli/cli.py 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 @app . command () def latest_rates ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , typer . Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe.\" , ), ], count : Annotated [ int , typer . Option ( help = \"Number of records.\" )], start_pos : Annotated [ int , typer . Option ( help = \"Start position (0 = current bar).\" ), ] = 0 , ) -> None : \"\"\"Export latest rates from a start position.\"\"\" _export_command ( ctx , lambda client : client . latest_rates ( symbol , timeframe , count , start_pos = start_pos , ), ) main \u00b6 main () -> None Run the mt5cli CLI. Source code in mt5cli/cli.py 778 779 780 def main () -> None : \"\"\"Run the mt5cli CLI.\"\"\" app () market_book \u00b6 market_book ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], ) -> None Export market depth (order book) for a symbol. Source code in mt5cli/cli.py 560 561 562 563 564 565 566 @app . command () def market_book ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], ) -> None : \"\"\"Export market depth (order book) for a symbol.\"\"\" _export_command ( ctx , lambda client : client . market_book ( symbol )) minimum_margins \u00b6 minimum_margins ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], ) -> None Export minimum-volume buy and sell margin requirements. Source code in mt5cli/cli.py 413 414 415 416 417 418 419 @app . command () def minimum_margins ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], ) -> None : \"\"\"Export minimum-volume buy and sell margin requirements.\"\"\" _export_command ( ctx , lambda client : client . minimum_margins ( symbol )) mt5_summary \u00b6 mt5_summary ( ctx : Context ) -> None Export a compact terminal/account status summary. Source code in mt5cli/cli.py 533 534 535 536 @app . command () def mt5_summary ( ctx : typer . Context ) -> None : \"\"\"Export a compact terminal/account status summary.\"\"\" _export_command ( ctx , lambda client : client . mt5_summary_as_df ()) order_check \u00b6 order_check ( ctx : Context , request : Annotated [ dict [ str , Any ], Option ( click_type = REQUEST_TYPE , help = _REQUEST_OPTION_HELP , ), ], ) -> None Check funds sufficiency for a trading operation. Source code in mt5cli/cli.py 569 570 571 572 573 574 575 576 577 578 @app . command () def order_check ( ctx : typer . Context , request : Annotated [ dict [ str , Any ], typer . Option ( click_type = REQUEST_TYPE , help = _REQUEST_OPTION_HELP ), ], ) -> None : \"\"\"Check funds sufficiency for a trading operation.\"\"\" _export_command ( ctx , lambda client : client . order_check ( request )) order_send \u00b6 order_send ( ctx : Context , request : Annotated [ dict [ str , Any ], Option ( click_type = REQUEST_TYPE , help = _REQUEST_OPTION_HELP , ), ], yes : Annotated [ bool , Option ( \"--yes\" , help = \"Confirm the live trade request.\" ), ] = False , ) -> None Send a trading operation request to the trade server. Raises: Type Description BadParameter If --yes is not provided. Source code in mt5cli/cli.py 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 @app . command () def order_send ( ctx : typer . Context , request : Annotated [ dict [ str , Any ], typer . Option ( click_type = REQUEST_TYPE , help = _REQUEST_OPTION_HELP ), ], yes : Annotated [ bool , typer . Option ( \"--yes\" , help = \"Confirm the live trade request.\" ), ] = False , ) -> None : \"\"\"Send a trading operation request to the trade server. Raises: typer.BadParameter: If --yes is not provided. \"\"\" if not yes : msg = \"Pass --yes to send a live trade request.\" raise typer . BadParameter ( msg , param_hint = \"--yes\" ) _export_command ( ctx , lambda client : client . order_send ( request )) orders \u00b6 orders ( ctx : Context , symbol : Annotated [ str | None , Option ( help = \"Symbol filter.\" ) ] = None , group : Annotated [ str | None , Option ( help = \"Group filter.\" ) ] = None , ticket : Annotated [ int | None , Option ( help = \"Ticket filter.\" ) ] = None , ) -> None Export active orders. Source code in mt5cli/cli.py 422 423 424 425 426 427 428 429 430 431 432 433 @app . command () def orders ( ctx : typer . Context , symbol : Annotated [ str | None , typer . Option ( help = \"Symbol filter.\" )] = None , group : Annotated [ str | None , typer . Option ( help = \"Group filter.\" )] = None , ticket : Annotated [ int | None , typer . Option ( help = \"Ticket filter.\" )] = None , ) -> None : \"\"\"Export active orders.\"\"\" _export_command ( ctx , lambda client : client . orders ( symbol = symbol , group = group , ticket = ticket ), ) positions \u00b6 positions ( ctx : Context , symbol : Annotated [ str | None , Option ( help = \"Symbol filter.\" ) ] = None , group : Annotated [ str | None , Option ( help = \"Group filter.\" ) ] = None , ticket : Annotated [ int | None , Option ( help = \"Ticket filter.\" ) ] = None , ) -> None Export open positions. Source code in mt5cli/cli.py 436 437 438 439 440 441 442 443 444 445 446 447 @app . command () def positions ( ctx : typer . Context , symbol : Annotated [ str | None , typer . Option ( help = \"Symbol filter.\" )] = None , group : Annotated [ str | None , typer . Option ( help = \"Group filter.\" )] = None , ticket : Annotated [ int | None , typer . Option ( help = \"Ticket filter.\" )] = None , ) -> None : \"\"\"Export open positions.\"\"\" _export_command ( ctx , lambda client : client . positions ( symbol = symbol , group = group , ticket = ticket ), ) rates_from \u00b6 rates_from ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe (e.g., M1, H1, D1, or integer).\" , ), ], date_from : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"Start date in ISO 8601 format.\" , ), ], count : Annotated [ int , Option ( help = \"Number of records.\" ) ], ) -> None Export rates from a start date. Source code in mt5cli/cli.py 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 @app . command () def rates_from ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , typer . Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe (e.g., M1, H1, D1, or integer).\" , ), ], date_from : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date in ISO 8601 format.\" , ), ], count : Annotated [ int , typer . Option ( help = \"Number of records.\" )], ) -> None : \"\"\"Export rates from a start date.\"\"\" _export_command ( ctx , lambda client : client . copy_rates_from ( symbol , timeframe , date_from , count ), ) rates_from_pos \u00b6 rates_from_pos ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe.\" ), ], start_pos : Annotated [ int , Option ( help = \"Start position (0 = current bar).\" ), ], count : Annotated [ int , Option ( help = \"Number of records.\" ) ], ) -> None Export rates from a start position. Source code in mt5cli/cli.py 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 @app . command () def rates_from_pos ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , typer . Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe.\" , ), ], start_pos : Annotated [ int , typer . Option ( help = \"Start position (0 = current bar).\" )], count : Annotated [ int , typer . Option ( help = \"Number of records.\" )], ) -> None : \"\"\"Export rates from a start position.\"\"\" _export_command ( ctx , lambda client : client . copy_rates_from_pos ( symbol , timeframe , start_pos , count , ), ) rates_range \u00b6 rates_range ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe.\" ), ], date_from : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], date_to : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ], ) -> None Export rates for a date range. Source code in mt5cli/cli.py 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 @app . command () def rates_range ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , typer . Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe.\" , ), ], date_from : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], date_to : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ], ) -> None : \"\"\"Export rates for a date range.\"\"\" _export_command ( ctx , lambda client : client . copy_rates_range ( symbol , timeframe , date_from , date_to ), ) recent_history_deals \u00b6 recent_history_deals ( ctx : Context , hours : Annotated [ float , Option ( help = \"Lookback window in hours.\" ) ], date_to : Annotated [ datetime | None , Option ( click_type = DATETIME_TYPE , help = \"Window end date.\" , ), ] = None , group : Annotated [ str | None , Option ( help = \"Group filter.\" ) ] = None , symbol : Annotated [ str | None , Option ( help = \"Symbol filter.\" ) ] = None , ) -> None Export historical deals from a recent trailing window. Source code in mt5cli/cli.py 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 @app . command () def recent_history_deals ( ctx : typer . Context , hours : Annotated [ float , typer . Option ( help = \"Lookback window in hours.\" )], date_to : Annotated [ datetime | None , typer . Option ( click_type = DATETIME_TYPE , help = \"Window end date.\" ), ] = None , group : Annotated [ str | None , typer . Option ( help = \"Group filter.\" )] = None , symbol : Annotated [ str | None , typer . Option ( help = \"Symbol filter.\" )] = None , ) -> None : \"\"\"Export historical deals from a recent trailing window.\"\"\" _export_command ( ctx , lambda client : client . recent_history_deals ( hours , date_to = date_to , group = group , symbol = symbol , ), ) symbol_info \u00b6 symbol_info ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], ) -> None Export symbol details. Source code in mt5cli/cli.py 404 405 406 407 408 409 410 @app . command () def symbol_info ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], ) -> None : \"\"\"Export symbol details.\"\"\" _export_command ( ctx , lambda client : client . symbol_info ( symbol )) symbol_info_tick \u00b6 symbol_info_tick ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], ) -> None Export the last tick for a symbol. Source code in mt5cli/cli.py 551 552 553 554 555 556 557 @app . command () def symbol_info_tick ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], ) -> None : \"\"\"Export the last tick for a symbol.\"\"\" _export_command ( ctx , lambda client : client . symbol_info_tick ( symbol )) symbols \u00b6 symbols ( ctx : Context , group : Annotated [ str | None , Option ( help = \"Symbol group filter (e.g., *USD*).\" ), ] = None , ) -> None Export symbol list. Source code in mt5cli/cli.py 392 393 394 395 396 397 398 399 400 401 @app . command () def symbols ( ctx : typer . Context , group : Annotated [ str | None , typer . Option ( help = \"Symbol group filter (e.g., *USD*).\" ), ] = None , ) -> None : \"\"\"Export symbol list.\"\"\" _export_command ( ctx , lambda client : client . symbols ( group = group )) terminal_info \u00b6 terminal_info ( ctx : Context ) -> None Export terminal information. Source code in mt5cli/cli.py 386 387 388 389 @app . command () def terminal_info ( ctx : typer . Context ) -> None : \"\"\"Export terminal information.\"\"\" _export_command ( ctx , lambda client : client . terminal_info ()) ticks_from \u00b6 ticks_from ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], date_from : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], count : Annotated [ int , Option ( help = \"Number of ticks.\" )], flags : Annotated [ int , Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick flags (ALL, INFO, TRADE, or integer).\" , ), ], ) -> None Export ticks from a start date. Source code in mt5cli/cli.py 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 @app . command () def ticks_from ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], date_from : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], count : Annotated [ int , typer . Option ( help = \"Number of ticks.\" )], flags : Annotated [ int , typer . Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick flags (ALL, INFO, TRADE, or integer).\" , ), ], ) -> None : \"\"\"Export ticks from a start date.\"\"\" _export_command ( ctx , lambda client : client . copy_ticks_from ( symbol , date_from , count , flags ), ) ticks_range \u00b6 ticks_range ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], date_from : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], date_to : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ], flags : Annotated [ int , Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick flags.\" ), ], ) -> None Export ticks for a date range. Source code in mt5cli/cli.py 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 @app . command () def ticks_range ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], date_from : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], date_to : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ], flags : Annotated [ int , typer . Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick flags.\" ), ], ) -> None : \"\"\"Export ticks for a date range.\"\"\" _export_command ( ctx , lambda client : client . copy_ticks_range ( symbol , date_from , date_to , flags ), ) ticks_recent \u00b6 ticks_recent ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], seconds : Annotated [ float , Option ( help = \"Lookback window in seconds.\" ) ], date_to : Annotated [ datetime | None , Option ( click_type = DATETIME_TYPE , help = \"Window end date.\" , ), ] = None , count : Annotated [ int , Option ( help = \"Maximum number of ticks to return.\" ), ] = 10000 , flags : Annotated [ int , Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick flags (ALL, INFO, TRADE, or integer).\" , ), ] = \"ALL\" , ) -> None Export ticks from a recent time window. Source code in mt5cli/cli.py 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 @app . command () def ticks_recent ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], seconds : Annotated [ float , typer . Option ( help = \"Lookback window in seconds.\" ), ], date_to : Annotated [ datetime | None , typer . Option ( click_type = DATETIME_TYPE , help = \"Window end date.\" ), ] = None , count : Annotated [ int , typer . Option ( help = \"Maximum number of ticks to return.\" ), ] = 10000 , flags : Annotated [ int , typer . Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick flags (ALL, INFO, TRADE, or integer).\" , ), ] = \"ALL\" , # pyright: ignore[reportArgumentType] ) -> None : \"\"\"Export ticks from a recent time window.\"\"\" _export_command ( ctx , lambda client : client . recent_ticks ( symbol , seconds , date_to = date_to , count = count , flags = flags , ), ) version \u00b6 version ( ctx : Context ) -> None Export MetaTrader5 version information. Source code in mt5cli/cli.py 539 540 541 542 @app . command () def version ( ctx : typer . Context ) -> None : \"\"\"Export MetaTrader5 version information.\"\"\" _export_command ( ctx , lambda client : client . version ())","title":"CLI"},{"location":"api/cli/#cli-module","text":"","title":"CLI Module"},{"location":"api/cli/#mt5cli.cli","text":"Command-line interface for MetaTrader 5 data export.","title":"cli"},{"location":"api/cli/#mt5cli.cli.app","text":"app = Typer ( name = \"mt5cli\" , help = \"Export MetaTrader5 data to CSV, JSON, Parquet, or SQLite3.\" , )","title":"app"},{"location":"api/cli/#mt5cli.cli.logger","text":"logger = getLogger ( __name__ )","title":"logger"},{"location":"api/cli/#mt5cli.cli.account_info","text":"account_info ( ctx : Context ) -> None Export account information. Source code in mt5cli/cli.py 380 381 382 383 @app . command () def account_info ( ctx : typer . Context ) -> None : \"\"\"Export account information.\"\"\" _export_command ( ctx , lambda client : client . account_info ())","title":"account_info"},{"location":"api/cli/#mt5cli.cli.close_positions","text":"close_positions ( ctx : Context , symbol : Annotated [ list [ str ] | None , Option ( \"--symbol\" , \"-s\" , help = \"Symbol to close (repeat for multiple symbols).\" , ), ] = None , ticket : Annotated [ list [ int ] | None , Option ( \"--ticket\" , \"-t\" , help = \"Position ticket to close (repeat for multiple tickets).\" , ), ] = None , dry_run : Annotated [ bool , Option ( \"--dry-run\" , help = \"Preview close orders without executing them.\" , ), ] = False , yes : Annotated [ bool , Option ( \"--yes\" , help = \"Confirm live position closing.\" ), ] = False , ) -> None Close open positions by symbol or ticket. Delegates to :func: mt5cli.trading.close_open_positions . At least one --symbol or --ticket must be provided to avoid accidentally closing all positions. Use --dry-run to preview without executing; --yes is required for live execution. order-send is the expert raw-request path. close-positions is the safer high-level helper that builds correct close requests automatically. Raises: Type Description BadParameter If neither --symbol nor --ticket is given, or if --yes is missing for a live (non-dry-run) run. Source code in mt5cli/cli.py 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 @app . command () def close_positions ( ctx : typer . Context , symbol : Annotated [ list [ str ] | None , typer . Option ( \"--symbol\" , \"-s\" , help = \"Symbol to close (repeat for multiple symbols).\" , ), ] = None , ticket : Annotated [ list [ int ] | None , typer . Option ( \"--ticket\" , \"-t\" , help = \"Position ticket to close (repeat for multiple tickets).\" , ), ] = None , dry_run : Annotated [ bool , typer . Option ( \"--dry-run\" , help = \"Preview close orders without executing them.\" ), ] = False , yes : Annotated [ bool , typer . Option ( \"--yes\" , help = \"Confirm live position closing.\" ), ] = False , ) -> None : \"\"\"Close open positions by symbol or ticket. Delegates to :func:`mt5cli.trading.close_open_positions`. At least one ``--symbol`` or ``--ticket`` must be provided to avoid accidentally closing all positions. Use ``--dry-run`` to preview without executing; ``--yes`` is required for live execution. ``order-send`` is the expert raw-request path. ``close-positions`` is the safer high-level helper that builds correct close requests automatically. Raises: typer.BadParameter: If neither ``--symbol`` nor ``--ticket`` is given, or if ``--yes`` is missing for a live (non-dry-run) run. \"\"\" if not symbol and not ticket : msg = \"Provide at least one --symbol or --ticket to close positions.\" raise typer . BadParameter ( msg ) if not dry_run and not yes : msg = \"Pass --yes to close live positions.\" raise typer . BadParameter ( msg , param_hint = \"--yes\" ) export_ctx = _get_export_context ( ctx ) client = create_trading_client ( config = export_ctx . config ) try : results = close_open_positions ( client , symbols = list ( symbol ) if symbol else None , tickets = list ( ticket ) if ticket else None , dry_run = dry_run , ) finally : client . shutdown () df = _execution_results_to_df ( results ) _execute_export ( ctx , lambda : df )","title":"close_positions"},{"location":"api/cli/#mt5cli.cli.collect_history","text":"collect_history ( ctx : Context , symbol : Annotated [ list [ str ], Option ( \"--symbol\" , \"-s\" , help = \"Symbol to collect (repeat for multiple symbols).\" , ), ], date_from : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], date_to : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ], dataset : Annotated [ list [ Dataset ] | None , Option ( \"--dataset\" , help = \"Dataset to include (repeat for multiple). Defaults to all: rates, ticks, history-orders, history-deals.\" , ), ] = None , timeframe : Annotated [ int , Option ( click_type = TIMEFRAME_TYPE , help = \"Rates timeframe (e.g., M1, H1, D1).\" , ), ] = 1 , flags : Annotated [ int , Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick copy flags (ALL, INFO, TRADE, or integer).\" , ), ] = \"ALL\" , if_exists : Annotated [ IfExists , Option ( \"--if-exists\" , help = \"Behavior when a target table already exists.\" , ), ] = FAIL , with_views : Annotated [ bool , Option ( \"--with-views\" , help = \"Add cash_events and positions_reconstructed SQLite views derived from history_deals.\" , ), ] = False , ) -> None Collect historical datasets into a single SQLite database. Tables written depend on --dataset : rates , ticks , history_orders , history_deals . History datasets are fetched per symbol and concatenated. Rates rows carry the requested timeframe so appended runs at different timeframes remain distinguishable. With --with-views (requires the history-deals dataset), optional views cash_events and positions_reconstructed are derived from history_deals when the required columns are present. Raises: Type Description BadParameter If the output format is not SQLite3. Source code in mt5cli/cli.py 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 @app . command () def collect_history ( ctx : typer . Context , symbol : Annotated [ list [ str ], typer . Option ( \"--symbol\" , \"-s\" , help = \"Symbol to collect (repeat for multiple symbols).\" , ), ], date_from : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], date_to : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ], dataset : Annotated [ list [ Dataset ] | None , typer . Option ( \"--dataset\" , help = ( \"Dataset to include (repeat for multiple).\" \" Defaults to all: rates, ticks, history-orders, history-deals.\" ), ), ] = None , timeframe : Annotated [ int , typer . Option ( click_type = TIMEFRAME_TYPE , help = \"Rates timeframe (e.g., M1, H1, D1).\" , ), ] = 1 , flags : Annotated [ int , typer . Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick copy flags (ALL, INFO, TRADE, or integer).\" , ), ] = \"ALL\" , # pyright: ignore[reportArgumentType] if_exists : Annotated [ IfExists , typer . Option ( \"--if-exists\" , help = \"Behavior when a target table already exists.\" , ), ] = IfExists . FAIL , with_views : Annotated [ bool , typer . Option ( \"--with-views\" , help = ( \"Add cash_events and positions_reconstructed SQLite views\" \" derived from history_deals.\" ), ), ] = False , ) -> None : \"\"\"Collect historical datasets into a single SQLite database. Tables written depend on ``--dataset``: ``rates``, ``ticks``, ``history_orders``, ``history_deals``. History datasets are fetched per symbol and concatenated. Rates rows carry the requested ``timeframe`` so appended runs at different timeframes remain distinguishable. With ``--with-views`` (requires the ``history-deals`` dataset), optional views ``cash_events`` and ``positions_reconstructed`` are derived from ``history_deals`` when the required columns are present. Raises: typer.BadParameter: If the output format is not SQLite3. \"\"\" export_ctx = _get_export_context ( ctx ) if export_ctx . output_format != \"sqlite3\" : msg = ( \"collect-history requires SQLite3 output.\" \" Use a .db/.sqlite/.sqlite3 extension or --format sqlite3.\" ) raise typer . BadParameter ( msg ) datasets = set ( dataset ) if dataset else set ( Dataset ) sdk . collect_history ( output = export_ctx . output , symbols = symbol , date_from = date_from , date_to = date_to , datasets = datasets , timeframe = timeframe , flags = flags , if_exists = if_exists , with_views = with_views , config = export_ctx . config , )","title":"collect_history"},{"location":"api/cli/#mt5cli.cli.history_deals","text":"history_deals ( ctx : Context , date_from : Annotated [ datetime | None , Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ] = None , date_to : Annotated [ datetime | None , Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ] = None , group : Annotated [ str | None , Option ( help = \"Group filter.\" ) ] = None , symbol : Annotated [ str | None , Option ( help = \"Symbol filter.\" ) ] = None , ticket : Annotated [ int | None , Option ( help = \"Order ticket.\" ) ] = None , position : Annotated [ int | None , Option ( help = \"Position ticket.\" ) ] = None , ) -> None Export historical deals. Source code in mt5cli/cli.py 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 @app . command () def history_deals ( ctx : typer . Context , date_from : Annotated [ datetime | None , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ] = None , date_to : Annotated [ datetime | None , typer . Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ] = None , group : Annotated [ str | None , typer . Option ( help = \"Group filter.\" )] = None , symbol : Annotated [ str | None , typer . Option ( help = \"Symbol filter.\" )] = None , ticket : Annotated [ int | None , typer . Option ( help = \"Order ticket.\" )] = None , position : Annotated [ int | None , typer . Option ( help = \"Position ticket.\" )] = None , ) -> None : \"\"\"Export historical deals.\"\"\" _export_command ( ctx , lambda client : client . history_deals ( date_from = date_from , date_to = date_to , group = group , symbol = symbol , ticket = ticket , position = position , ), )","title":"history_deals"},{"location":"api/cli/#mt5cli.cli.history_orders","text":"history_orders ( ctx : Context , date_from : Annotated [ datetime | None , Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ] = None , date_to : Annotated [ datetime | None , Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ] = None , group : Annotated [ str | None , Option ( help = \"Group filter.\" ) ] = None , symbol : Annotated [ str | None , Option ( help = \"Symbol filter.\" ) ] = None , ticket : Annotated [ int | None , Option ( help = \"Order ticket.\" ) ] = None , position : Annotated [ int | None , Option ( help = \"Position ticket.\" ) ] = None , ) -> None Export historical orders. Source code in mt5cli/cli.py 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 @app . command () def history_orders ( ctx : typer . Context , date_from : Annotated [ datetime | None , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ] = None , date_to : Annotated [ datetime | None , typer . Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ] = None , group : Annotated [ str | None , typer . Option ( help = \"Group filter.\" )] = None , symbol : Annotated [ str | None , typer . Option ( help = \"Symbol filter.\" )] = None , ticket : Annotated [ int | None , typer . Option ( help = \"Order ticket.\" )] = None , position : Annotated [ int | None , typer . Option ( help = \"Position ticket.\" )] = None , ) -> None : \"\"\"Export historical orders.\"\"\" _export_command ( ctx , lambda client : client . history_orders ( date_from = date_from , date_to = date_to , group = group , symbol = symbol , ticket = ticket , position = position , ), )","title":"history_orders"},{"location":"api/cli/#mt5cli.cli.last_error","text":"last_error ( ctx : Context ) -> None Export the last error information. Source code in mt5cli/cli.py 545 546 547 548 @app . command () def last_error ( ctx : typer . Context ) -> None : \"\"\"Export the last error information.\"\"\" _export_command ( ctx , lambda client : client . last_error ())","title":"last_error"},{"location":"api/cli/#mt5cli.cli.latest_rates","text":"latest_rates ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe.\" ), ], count : Annotated [ int , Option ( help = \"Number of records.\" ) ], start_pos : Annotated [ int , Option ( help = \"Start position (0 = current bar).\" ), ] = 0 , ) -> None Export latest rates from a start position. Source code in mt5cli/cli.py 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 @app . command () def latest_rates ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , typer . Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe.\" , ), ], count : Annotated [ int , typer . Option ( help = \"Number of records.\" )], start_pos : Annotated [ int , typer . Option ( help = \"Start position (0 = current bar).\" ), ] = 0 , ) -> None : \"\"\"Export latest rates from a start position.\"\"\" _export_command ( ctx , lambda client : client . latest_rates ( symbol , timeframe , count , start_pos = start_pos , ), )","title":"latest_rates"},{"location":"api/cli/#mt5cli.cli.main","text":"main () -> None Run the mt5cli CLI. Source code in mt5cli/cli.py 778 779 780 def main () -> None : \"\"\"Run the mt5cli CLI.\"\"\" app ()","title":"main"},{"location":"api/cli/#mt5cli.cli.market_book","text":"market_book ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], ) -> None Export market depth (order book) for a symbol. Source code in mt5cli/cli.py 560 561 562 563 564 565 566 @app . command () def market_book ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], ) -> None : \"\"\"Export market depth (order book) for a symbol.\"\"\" _export_command ( ctx , lambda client : client . market_book ( symbol ))","title":"market_book"},{"location":"api/cli/#mt5cli.cli.minimum_margins","text":"minimum_margins ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], ) -> None Export minimum-volume buy and sell margin requirements. Source code in mt5cli/cli.py 413 414 415 416 417 418 419 @app . command () def minimum_margins ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], ) -> None : \"\"\"Export minimum-volume buy and sell margin requirements.\"\"\" _export_command ( ctx , lambda client : client . minimum_margins ( symbol ))","title":"minimum_margins"},{"location":"api/cli/#mt5cli.cli.mt5_summary","text":"mt5_summary ( ctx : Context ) -> None Export a compact terminal/account status summary. Source code in mt5cli/cli.py 533 534 535 536 @app . command () def mt5_summary ( ctx : typer . Context ) -> None : \"\"\"Export a compact terminal/account status summary.\"\"\" _export_command ( ctx , lambda client : client . mt5_summary_as_df ())","title":"mt5_summary"},{"location":"api/cli/#mt5cli.cli.order_check","text":"order_check ( ctx : Context , request : Annotated [ dict [ str , Any ], Option ( click_type = REQUEST_TYPE , help = _REQUEST_OPTION_HELP , ), ], ) -> None Check funds sufficiency for a trading operation. Source code in mt5cli/cli.py 569 570 571 572 573 574 575 576 577 578 @app . command () def order_check ( ctx : typer . Context , request : Annotated [ dict [ str , Any ], typer . Option ( click_type = REQUEST_TYPE , help = _REQUEST_OPTION_HELP ), ], ) -> None : \"\"\"Check funds sufficiency for a trading operation.\"\"\" _export_command ( ctx , lambda client : client . order_check ( request ))","title":"order_check"},{"location":"api/cli/#mt5cli.cli.order_send","text":"order_send ( ctx : Context , request : Annotated [ dict [ str , Any ], Option ( click_type = REQUEST_TYPE , help = _REQUEST_OPTION_HELP , ), ], yes : Annotated [ bool , Option ( \"--yes\" , help = \"Confirm the live trade request.\" ), ] = False , ) -> None Send a trading operation request to the trade server. Raises: Type Description BadParameter If --yes is not provided. Source code in mt5cli/cli.py 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 @app . command () def order_send ( ctx : typer . Context , request : Annotated [ dict [ str , Any ], typer . Option ( click_type = REQUEST_TYPE , help = _REQUEST_OPTION_HELP ), ], yes : Annotated [ bool , typer . Option ( \"--yes\" , help = \"Confirm the live trade request.\" ), ] = False , ) -> None : \"\"\"Send a trading operation request to the trade server. Raises: typer.BadParameter: If --yes is not provided. \"\"\" if not yes : msg = \"Pass --yes to send a live trade request.\" raise typer . BadParameter ( msg , param_hint = \"--yes\" ) _export_command ( ctx , lambda client : client . order_send ( request ))","title":"order_send"},{"location":"api/cli/#mt5cli.cli.orders","text":"orders ( ctx : Context , symbol : Annotated [ str | None , Option ( help = \"Symbol filter.\" ) ] = None , group : Annotated [ str | None , Option ( help = \"Group filter.\" ) ] = None , ticket : Annotated [ int | None , Option ( help = \"Ticket filter.\" ) ] = None , ) -> None Export active orders. Source code in mt5cli/cli.py 422 423 424 425 426 427 428 429 430 431 432 433 @app . command () def orders ( ctx : typer . Context , symbol : Annotated [ str | None , typer . Option ( help = \"Symbol filter.\" )] = None , group : Annotated [ str | None , typer . Option ( help = \"Group filter.\" )] = None , ticket : Annotated [ int | None , typer . Option ( help = \"Ticket filter.\" )] = None , ) -> None : \"\"\"Export active orders.\"\"\" _export_command ( ctx , lambda client : client . orders ( symbol = symbol , group = group , ticket = ticket ), )","title":"orders"},{"location":"api/cli/#mt5cli.cli.positions","text":"positions ( ctx : Context , symbol : Annotated [ str | None , Option ( help = \"Symbol filter.\" ) ] = None , group : Annotated [ str | None , Option ( help = \"Group filter.\" ) ] = None , ticket : Annotated [ int | None , Option ( help = \"Ticket filter.\" ) ] = None , ) -> None Export open positions. Source code in mt5cli/cli.py 436 437 438 439 440 441 442 443 444 445 446 447 @app . command () def positions ( ctx : typer . Context , symbol : Annotated [ str | None , typer . Option ( help = \"Symbol filter.\" )] = None , group : Annotated [ str | None , typer . Option ( help = \"Group filter.\" )] = None , ticket : Annotated [ int | None , typer . Option ( help = \"Ticket filter.\" )] = None , ) -> None : \"\"\"Export open positions.\"\"\" _export_command ( ctx , lambda client : client . positions ( symbol = symbol , group = group , ticket = ticket ), )","title":"positions"},{"location":"api/cli/#mt5cli.cli.rates_from","text":"rates_from ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe (e.g., M1, H1, D1, or integer).\" , ), ], date_from : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"Start date in ISO 8601 format.\" , ), ], count : Annotated [ int , Option ( help = \"Number of records.\" ) ], ) -> None Export rates from a start date. Source code in mt5cli/cli.py 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 @app . command () def rates_from ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , typer . Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe (e.g., M1, H1, D1, or integer).\" , ), ], date_from : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date in ISO 8601 format.\" , ), ], count : Annotated [ int , typer . Option ( help = \"Number of records.\" )], ) -> None : \"\"\"Export rates from a start date.\"\"\" _export_command ( ctx , lambda client : client . copy_rates_from ( symbol , timeframe , date_from , count ), )","title":"rates_from"},{"location":"api/cli/#mt5cli.cli.rates_from_pos","text":"rates_from_pos ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe.\" ), ], start_pos : Annotated [ int , Option ( help = \"Start position (0 = current bar).\" ), ], count : Annotated [ int , Option ( help = \"Number of records.\" ) ], ) -> None Export rates from a start position. Source code in mt5cli/cli.py 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 @app . command () def rates_from_pos ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , typer . Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe.\" , ), ], start_pos : Annotated [ int , typer . Option ( help = \"Start position (0 = current bar).\" )], count : Annotated [ int , typer . Option ( help = \"Number of records.\" )], ) -> None : \"\"\"Export rates from a start position.\"\"\" _export_command ( ctx , lambda client : client . copy_rates_from_pos ( symbol , timeframe , start_pos , count , ), )","title":"rates_from_pos"},{"location":"api/cli/#mt5cli.cli.rates_range","text":"rates_range ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe.\" ), ], date_from : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], date_to : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ], ) -> None Export rates for a date range. Source code in mt5cli/cli.py 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 @app . command () def rates_range ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], timeframe : Annotated [ int , typer . Option ( click_type = TIMEFRAME_TYPE , help = \"Timeframe.\" , ), ], date_from : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], date_to : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ], ) -> None : \"\"\"Export rates for a date range.\"\"\" _export_command ( ctx , lambda client : client . copy_rates_range ( symbol , timeframe , date_from , date_to ), )","title":"rates_range"},{"location":"api/cli/#mt5cli.cli.recent_history_deals","text":"recent_history_deals ( ctx : Context , hours : Annotated [ float , Option ( help = \"Lookback window in hours.\" ) ], date_to : Annotated [ datetime | None , Option ( click_type = DATETIME_TYPE , help = \"Window end date.\" , ), ] = None , group : Annotated [ str | None , Option ( help = \"Group filter.\" ) ] = None , symbol : Annotated [ str | None , Option ( help = \"Symbol filter.\" ) ] = None , ) -> None Export historical deals from a recent trailing window. Source code in mt5cli/cli.py 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 @app . command () def recent_history_deals ( ctx : typer . Context , hours : Annotated [ float , typer . Option ( help = \"Lookback window in hours.\" )], date_to : Annotated [ datetime | None , typer . Option ( click_type = DATETIME_TYPE , help = \"Window end date.\" ), ] = None , group : Annotated [ str | None , typer . Option ( help = \"Group filter.\" )] = None , symbol : Annotated [ str | None , typer . Option ( help = \"Symbol filter.\" )] = None , ) -> None : \"\"\"Export historical deals from a recent trailing window.\"\"\" _export_command ( ctx , lambda client : client . recent_history_deals ( hours , date_to = date_to , group = group , symbol = symbol , ), )","title":"recent_history_deals"},{"location":"api/cli/#mt5cli.cli.symbol_info","text":"symbol_info ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], ) -> None Export symbol details. Source code in mt5cli/cli.py 404 405 406 407 408 409 410 @app . command () def symbol_info ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], ) -> None : \"\"\"Export symbol details.\"\"\" _export_command ( ctx , lambda client : client . symbol_info ( symbol ))","title":"symbol_info"},{"location":"api/cli/#mt5cli.cli.symbol_info_tick","text":"symbol_info_tick ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], ) -> None Export the last tick for a symbol. Source code in mt5cli/cli.py 551 552 553 554 555 556 557 @app . command () def symbol_info_tick ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], ) -> None : \"\"\"Export the last tick for a symbol.\"\"\" _export_command ( ctx , lambda client : client . symbol_info_tick ( symbol ))","title":"symbol_info_tick"},{"location":"api/cli/#mt5cli.cli.symbols","text":"symbols ( ctx : Context , group : Annotated [ str | None , Option ( help = \"Symbol group filter (e.g., *USD*).\" ), ] = None , ) -> None Export symbol list. Source code in mt5cli/cli.py 392 393 394 395 396 397 398 399 400 401 @app . command () def symbols ( ctx : typer . Context , group : Annotated [ str | None , typer . Option ( help = \"Symbol group filter (e.g., *USD*).\" ), ] = None , ) -> None : \"\"\"Export symbol list.\"\"\" _export_command ( ctx , lambda client : client . symbols ( group = group ))","title":"symbols"},{"location":"api/cli/#mt5cli.cli.terminal_info","text":"terminal_info ( ctx : Context ) -> None Export terminal information. Source code in mt5cli/cli.py 386 387 388 389 @app . command () def terminal_info ( ctx : typer . Context ) -> None : \"\"\"Export terminal information.\"\"\" _export_command ( ctx , lambda client : client . terminal_info ())","title":"terminal_info"},{"location":"api/cli/#mt5cli.cli.ticks_from","text":"ticks_from ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], date_from : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], count : Annotated [ int , Option ( help = \"Number of ticks.\" )], flags : Annotated [ int , Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick flags (ALL, INFO, TRADE, or integer).\" , ), ], ) -> None Export ticks from a start date. Source code in mt5cli/cli.py 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 @app . command () def ticks_from ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], date_from : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], count : Annotated [ int , typer . Option ( help = \"Number of ticks.\" )], flags : Annotated [ int , typer . Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick flags (ALL, INFO, TRADE, or integer).\" , ), ], ) -> None : \"\"\"Export ticks from a start date.\"\"\" _export_command ( ctx , lambda client : client . copy_ticks_from ( symbol , date_from , count , flags ), )","title":"ticks_from"},{"location":"api/cli/#mt5cli.cli.ticks_range","text":"ticks_range ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], date_from : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], date_to : Annotated [ datetime , Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ], flags : Annotated [ int , Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick flags.\" ), ], ) -> None Export ticks for a date range. Source code in mt5cli/cli.py 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 @app . command () def ticks_range ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], date_from : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"Start date.\" ), ], date_to : Annotated [ datetime , typer . Option ( click_type = DATETIME_TYPE , help = \"End date.\" ), ], flags : Annotated [ int , typer . Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick flags.\" ), ], ) -> None : \"\"\"Export ticks for a date range.\"\"\" _export_command ( ctx , lambda client : client . copy_ticks_range ( symbol , date_from , date_to , flags ), )","title":"ticks_range"},{"location":"api/cli/#mt5cli.cli.ticks_recent","text":"ticks_recent ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], seconds : Annotated [ float , Option ( help = \"Lookback window in seconds.\" ) ], date_to : Annotated [ datetime | None , Option ( click_type = DATETIME_TYPE , help = \"Window end date.\" , ), ] = None , count : Annotated [ int , Option ( help = \"Maximum number of ticks to return.\" ), ] = 10000 , flags : Annotated [ int , Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick flags (ALL, INFO, TRADE, or integer).\" , ), ] = \"ALL\" , ) -> None Export ticks from a recent time window. Source code in mt5cli/cli.py 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 @app . command () def ticks_recent ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], seconds : Annotated [ float , typer . Option ( help = \"Lookback window in seconds.\" ), ], date_to : Annotated [ datetime | None , typer . Option ( click_type = DATETIME_TYPE , help = \"Window end date.\" ), ] = None , count : Annotated [ int , typer . Option ( help = \"Maximum number of ticks to return.\" ), ] = 10000 , flags : Annotated [ int , typer . Option ( click_type = TICK_FLAGS_TYPE , help = \"Tick flags (ALL, INFO, TRADE, or integer).\" , ), ] = \"ALL\" , # pyright: ignore[reportArgumentType] ) -> None : \"\"\"Export ticks from a recent time window.\"\"\" _export_command ( ctx , lambda client : client . recent_ticks ( symbol , seconds , date_to = date_to , count = count , flags = flags , ), )","title":"ticks_recent"},{"location":"api/cli/#mt5cli.cli.version","text":"version ( ctx : Context ) -> None Export MetaTrader5 version information. Source code in mt5cli/cli.py 539 540 541 542 @app . command () def version ( ctx : typer . Context ) -> None : \"\"\"Export MetaTrader5 version information.\"\"\" _export_command ( ctx , lambda client : client . version ())","title":"version"},{"location":"api/client/","text":"Client \u00b6 mt5cli.client \u00b6 Stable public client abstraction for MT5 data and execution operations. __all__ module-attribute \u00b6 __all__ = [ 'MT5Client' , 'build_config' , 'mt5_session' ] MT5Client \u00b6 MT5Client ( * , path : str | None = None , login : int | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , retry_count : int = 3 , config : Mt5Config | None = None , client : Mt5DataClient | None = None , ) Bases: Mt5CliClient Public client for generic MT5 data access and order primitives. Extends the read-only SDK client with optional order check/send helpers and exposes the same connection lifecycle as :func: mt5_session . mt5cli intentionally exposes minimal execution primitives only. Trading decisions, signals, strategies, backtests, and optimization remain the responsibility of downstream applications. Source code in mt5cli/sdk.py 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 def __init__ ( self , * , path : str | None = None , login : int | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , retry_count : int = 3 , config : Mt5Config | None = None , client : Mt5DataClient | None = None , ) -> None : \"\"\"Initialize the SDK client. Args: path: Path to MetaTrader5 terminal EXE file. login: Trading account login. password: Trading account password. server: Trading server name. timeout: Connection timeout in milliseconds. retry_count: Number of MT5 initialization retries for sessions opened by this client. config: Optional pre-built ``Mt5Config`` (overrides other args). client: Optional already-connected ``Mt5DataClient``. Injected clients are reused as-is and are not initialized or shut down. \"\"\" self . _config = config or build_config ( path = path , login = login , password = password , server = server , timeout = timeout , ) self . _retry_count = retry_count self . _client = client self . _owns_client = client is None from_connected_client classmethod \u00b6 from_connected_client ( client : Mt5DataClient ) -> Self Bind to an already-connected Mt5DataClient without owning it. Returns: Type Description Self Client wrapper bound to the injected connection. Source code in mt5cli/client.py 63 64 65 66 67 68 69 70 @classmethod def from_connected_client ( cls , client : Mt5DataClient ) -> Self : \"\"\"Bind to an already-connected ``Mt5DataClient`` without owning it. Returns: Client wrapper bound to the injected connection. \"\"\" return cls ( client = client ) order_check \u00b6 order_check ( request : dict [ str , Any ]) -> DataFrame Check funds sufficiency for a trade request. Parameters: Name Type Description Default request dict [ str , Any ] MT5 order request dictionary. required Returns: Type Description DataFrame One-row DataFrame with the order-check result. Source code in mt5cli/client.py 34 35 36 37 38 39 40 41 42 43 def order_check ( self , request : dict [ str , Any ]) -> pd . DataFrame : \"\"\"Check funds sufficiency for a trade request. Args: request: MT5 order request dictionary. Returns: One-row DataFrame with the order-check result. \"\"\" return self . _fetch ( lambda client : client . order_check_as_df ( request = request )) order_send \u00b6 order_send ( request : dict [ str , Any ]) -> DataFrame Send a live trade request to the MT5 trade server. Warning This is a live execution primitive. A successful call can place, modify, or close real trades on the connected account. Downstream applications must gate usage explicitly (for example behind manual confirmation or application-specific risk controls). mt5cli does not implement strategy logic, signal generation, or trade sizing. Parameters: Name Type Description Default request dict [ str , Any ] MT5 order request dictionary. required Returns: Type Description DataFrame One-row DataFrame with the order-send result. Source code in mt5cli/client.py 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 def order_send ( self , request : dict [ str , Any ]) -> pd . DataFrame : \"\"\"Send a live trade request to the MT5 trade server. Warning: This is a live execution primitive. A successful call can place, modify, or close real trades on the connected account. Downstream applications must gate usage explicitly (for example behind manual confirmation or application-specific risk controls). mt5cli does not implement strategy logic, signal generation, or trade sizing. Args: request: MT5 order request dictionary. Returns: One-row DataFrame with the order-send result. \"\"\" return self . _fetch ( lambda client : client . order_send_as_df ( request = request )) build_config \u00b6 build_config ( * , path : str | None = None , login : int | str | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , allow_whole_dollar_env : bool = False , ) -> Mt5Config Build an Mt5Config from optional connection parameters. Parameters: Name Type Description Default path str | None Optional terminal executable path. None login int | str | None Optional trading account login. Integers are preserved. String values are coerced: empty or whitespace-only strings become None ; numeric strings such as \"12345\" are converted to int ; non-numeric strings raise ValueError . When allow_whole_dollar_env=True , $ENV_NAME and ${ENV_NAME} placeholders are expanded before coercion. None password str | None Optional trading account password. None server str | None Optional trading server name. None timeout int | None Optional connection timeout in milliseconds. None allow_whole_dollar_env bool When True , string parameters that are exactly $ENV_NAME are expanded from the environment. Applies to path , login , password , and server . Default False preserves existing behavior. False Returns: Type Description Mt5Config Configured Mt5Config instance. Source code in mt5cli/sdk.py 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 def build_config ( * , path : str | None = None , login : int | str | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , allow_whole_dollar_env : bool = False , ) -> Mt5Config : \"\"\"Build an ``Mt5Config`` from optional connection parameters. Args: path: Optional terminal executable path. login: Optional trading account login. Integers are preserved. String values are coerced: empty or whitespace-only strings become ``None``; numeric strings such as ``\"12345\"`` are converted to ``int``; non-numeric strings raise ``ValueError``. When ``allow_whole_dollar_env=True``, ``$ENV_NAME`` and ``${ENV_NAME}`` placeholders are expanded before coercion. password: Optional trading account password. server: Optional trading server name. timeout: Optional connection timeout in milliseconds. allow_whole_dollar_env: When ``True``, string parameters that are exactly ``$ENV_NAME`` are expanded from the environment. Applies to ``path``, ``login``, ``password``, and ``server``. Default ``False`` preserves existing behavior. Returns: Configured ``Mt5Config`` instance. \"\"\" if allow_whole_dollar_env : if path is not None : path = substitute_env_placeholders ( path , allow_whole_dollar_env = True ) if isinstance ( login , str ): login = substitute_env_placeholders ( login , allow_whole_dollar_env = True ) if password is not None : password = substitute_env_placeholders ( password , allow_whole_dollar_env = True ) if server is not None : server = substitute_env_placeholders ( server , allow_whole_dollar_env = True ) return Mt5Config ( path = path , login = _coerce_login ( login ), password = password , server = server , timeout = timeout , ) mt5_session \u00b6 mt5_session ( config : Mt5Config | None = None , ) -> Iterator [ MT5Client ] Open an MT5 terminal session and yield a connected :class: MT5Client . Parameters: Name Type Description Default config Mt5Config | None MT5 connection configuration. Defaults to an empty config that attaches to a running terminal. None Yields: Name Type Description Connected MT5Client class: MT5Client bound to the session. Source code in mt5cli/client.py 73 74 75 76 77 78 79 80 81 82 83 84 85 86 @contextmanager def mt5_session ( config : Mt5Config | None = None ) -> Iterator [ MT5Client ]: \"\"\"Open an MT5 terminal session and yield a connected :class:`MT5Client`. Args: config: MT5 connection configuration. Defaults to an empty config that attaches to a running terminal. Yields: Connected :class:`MT5Client` bound to the session. \"\"\" mt5_config = config or build_config () with connected_client ( mt5_config ) as client : yield MT5Client . from_connected_client ( client )","title":"Client"},{"location":"api/client/#client","text":"","title":"Client"},{"location":"api/client/#mt5cli.client","text":"Stable public client abstraction for MT5 data and execution operations.","title":"client"},{"location":"api/client/#mt5cli.client.__all__","text":"__all__ = [ 'MT5Client' , 'build_config' , 'mt5_session' ]","title":"__all__"},{"location":"api/client/#mt5cli.client.MT5Client","text":"MT5Client ( * , path : str | None = None , login : int | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , retry_count : int = 3 , config : Mt5Config | None = None , client : Mt5DataClient | None = None , ) Bases: Mt5CliClient Public client for generic MT5 data access and order primitives. Extends the read-only SDK client with optional order check/send helpers and exposes the same connection lifecycle as :func: mt5_session . mt5cli intentionally exposes minimal execution primitives only. Trading decisions, signals, strategies, backtests, and optimization remain the responsibility of downstream applications. Source code in mt5cli/sdk.py 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 def __init__ ( self , * , path : str | None = None , login : int | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , retry_count : int = 3 , config : Mt5Config | None = None , client : Mt5DataClient | None = None , ) -> None : \"\"\"Initialize the SDK client. Args: path: Path to MetaTrader5 terminal EXE file. login: Trading account login. password: Trading account password. server: Trading server name. timeout: Connection timeout in milliseconds. retry_count: Number of MT5 initialization retries for sessions opened by this client. config: Optional pre-built ``Mt5Config`` (overrides other args). client: Optional already-connected ``Mt5DataClient``. Injected clients are reused as-is and are not initialized or shut down. \"\"\" self . _config = config or build_config ( path = path , login = login , password = password , server = server , timeout = timeout , ) self . _retry_count = retry_count self . _client = client self . _owns_client = client is None","title":"MT5Client"},{"location":"api/client/#mt5cli.client.MT5Client.from_connected_client","text":"from_connected_client ( client : Mt5DataClient ) -> Self Bind to an already-connected Mt5DataClient without owning it. Returns: Type Description Self Client wrapper bound to the injected connection. Source code in mt5cli/client.py 63 64 65 66 67 68 69 70 @classmethod def from_connected_client ( cls , client : Mt5DataClient ) -> Self : \"\"\"Bind to an already-connected ``Mt5DataClient`` without owning it. Returns: Client wrapper bound to the injected connection. \"\"\" return cls ( client = client )","title":"from_connected_client"},{"location":"api/client/#mt5cli.client.MT5Client.order_check","text":"order_check ( request : dict [ str , Any ]) -> DataFrame Check funds sufficiency for a trade request. Parameters: Name Type Description Default request dict [ str , Any ] MT5 order request dictionary. required Returns: Type Description DataFrame One-row DataFrame with the order-check result. Source code in mt5cli/client.py 34 35 36 37 38 39 40 41 42 43 def order_check ( self , request : dict [ str , Any ]) -> pd . DataFrame : \"\"\"Check funds sufficiency for a trade request. Args: request: MT5 order request dictionary. Returns: One-row DataFrame with the order-check result. \"\"\" return self . _fetch ( lambda client : client . order_check_as_df ( request = request ))","title":"order_check"},{"location":"api/client/#mt5cli.client.MT5Client.order_send","text":"order_send ( request : dict [ str , Any ]) -> DataFrame Send a live trade request to the MT5 trade server. Warning This is a live execution primitive. A successful call can place, modify, or close real trades on the connected account. Downstream applications must gate usage explicitly (for example behind manual confirmation or application-specific risk controls). mt5cli does not implement strategy logic, signal generation, or trade sizing. Parameters: Name Type Description Default request dict [ str , Any ] MT5 order request dictionary. required Returns: Type Description DataFrame One-row DataFrame with the order-send result. Source code in mt5cli/client.py 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 def order_send ( self , request : dict [ str , Any ]) -> pd . DataFrame : \"\"\"Send a live trade request to the MT5 trade server. Warning: This is a live execution primitive. A successful call can place, modify, or close real trades on the connected account. Downstream applications must gate usage explicitly (for example behind manual confirmation or application-specific risk controls). mt5cli does not implement strategy logic, signal generation, or trade sizing. Args: request: MT5 order request dictionary. Returns: One-row DataFrame with the order-send result. \"\"\" return self . _fetch ( lambda client : client . order_send_as_df ( request = request ))","title":"order_send"},{"location":"api/client/#mt5cli.client.build_config","text":"build_config ( * , path : str | None = None , login : int | str | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , allow_whole_dollar_env : bool = False , ) -> Mt5Config Build an Mt5Config from optional connection parameters. Parameters: Name Type Description Default path str | None Optional terminal executable path. None login int | str | None Optional trading account login. Integers are preserved. String values are coerced: empty or whitespace-only strings become None ; numeric strings such as \"12345\" are converted to int ; non-numeric strings raise ValueError . When allow_whole_dollar_env=True , $ENV_NAME and ${ENV_NAME} placeholders are expanded before coercion. None password str | None Optional trading account password. None server str | None Optional trading server name. None timeout int | None Optional connection timeout in milliseconds. None allow_whole_dollar_env bool When True , string parameters that are exactly $ENV_NAME are expanded from the environment. Applies to path , login , password , and server . Default False preserves existing behavior. False Returns: Type Description Mt5Config Configured Mt5Config instance. Source code in mt5cli/sdk.py 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 def build_config ( * , path : str | None = None , login : int | str | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , allow_whole_dollar_env : bool = False , ) -> Mt5Config : \"\"\"Build an ``Mt5Config`` from optional connection parameters. Args: path: Optional terminal executable path. login: Optional trading account login. Integers are preserved. String values are coerced: empty or whitespace-only strings become ``None``; numeric strings such as ``\"12345\"`` are converted to ``int``; non-numeric strings raise ``ValueError``. When ``allow_whole_dollar_env=True``, ``$ENV_NAME`` and ``${ENV_NAME}`` placeholders are expanded before coercion. password: Optional trading account password. server: Optional trading server name. timeout: Optional connection timeout in milliseconds. allow_whole_dollar_env: When ``True``, string parameters that are exactly ``$ENV_NAME`` are expanded from the environment. Applies to ``path``, ``login``, ``password``, and ``server``. Default ``False`` preserves existing behavior. Returns: Configured ``Mt5Config`` instance. \"\"\" if allow_whole_dollar_env : if path is not None : path = substitute_env_placeholders ( path , allow_whole_dollar_env = True ) if isinstance ( login , str ): login = substitute_env_placeholders ( login , allow_whole_dollar_env = True ) if password is not None : password = substitute_env_placeholders ( password , allow_whole_dollar_env = True ) if server is not None : server = substitute_env_placeholders ( server , allow_whole_dollar_env = True ) return Mt5Config ( path = path , login = _coerce_login ( login ), password = password , server = server , timeout = timeout , )","title":"build_config"},{"location":"api/client/#mt5cli.client.mt5_session","text":"mt5_session ( config : Mt5Config | None = None , ) -> Iterator [ MT5Client ] Open an MT5 terminal session and yield a connected :class: MT5Client . Parameters: Name Type Description Default config Mt5Config | None MT5 connection configuration. Defaults to an empty config that attaches to a running terminal. None Yields: Name Type Description Connected MT5Client class: MT5Client bound to the session. Source code in mt5cli/client.py 73 74 75 76 77 78 79 80 81 82 83 84 85 86 @contextmanager def mt5_session ( config : Mt5Config | None = None ) -> Iterator [ MT5Client ]: \"\"\"Open an MT5 terminal session and yield a connected :class:`MT5Client`. Args: config: MT5 connection configuration. Defaults to an empty config that attaches to a running terminal. Yields: Connected :class:`MT5Client` bound to the session. \"\"\" mt5_config = config or build_config () with connected_client ( mt5_config ) as client : yield MT5Client . from_connected_client ( client )","title":"mt5_session"},{"location":"api/converters/","text":"Converters \u00b6 mt5cli.converters \u00b6 Shared conversion helpers for MT5 symbols, timeframes, and date ranges. __all__ module-attribute \u00b6 __all__ = [ \"ensure_utc\" , \"granularity_name\" , \"normalize_symbol\" , \"normalize_symbols\" , \"parse_date_range\" , \"parse_datetime\" , \"parse_tick_flags\" , \"parse_timeframe\" , \"recent_window\" , ] ensure_utc \u00b6 ensure_utc ( value : datetime | str ) -> datetime Return a timezone-aware UTC datetime. Parameters: Name Type Description Default value datetime | str Datetime instance or ISO 8601 string. required Returns: Type Description datetime UTC-aware datetime. Source code in mt5cli/converters.py 69 70 71 72 73 74 75 76 77 78 79 80 81 82 def ensure_utc ( value : datetime | str ) -> datetime : \"\"\"Return a timezone-aware UTC datetime. Args: value: Datetime instance or ISO 8601 string. Returns: UTC-aware datetime. \"\"\" if isinstance ( value , str ): return parse_datetime ( value ) if value . tzinfo is None : return value . replace ( tzinfo = UTC ) return value . astimezone ( UTC ) granularity_name \u00b6 granularity_name ( timeframe : int | str ) -> str Return a short granularity label for a timeframe integer or name. Parameters: Name Type Description Default timeframe int | str MT5 timeframe as integer or name (for example M1 ). required Returns: Type Description str Short name such as M1 or the stringified integer when unknown. Source code in mt5cli/converters.py 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 def granularity_name ( timeframe : int | str ) -> str : \"\"\"Return a short granularity label for a timeframe integer or name. Args: timeframe: MT5 timeframe as integer or name (for example ``M1``). Returns: Short name such as ``M1`` or the stringified integer when unknown. \"\"\" tf = parse_timeframe ( timeframe ) try : name = _get_timeframe_name ( tf ) except ValueError : return str ( tf ) return name . removeprefix ( \"TIMEFRAME_\" ) normalize_symbol \u00b6 normalize_symbol ( symbol : str ) -> str Normalize a broker symbol name for MT5 API calls. Strips surrounding whitespace while preserving broker-specific casing and suffixes (for example XAUUSDm , US500.cash , or EURUSD.r ). Parameters: Name Type Description Default symbol str Raw symbol name. required Returns: Type Description str Normalized symbol string. Raises: Type Description ValueError If the symbol is empty after normalization. Source code in mt5cli/converters.py 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 def normalize_symbol ( symbol : str ) -> str : \"\"\"Normalize a broker symbol name for MT5 API calls. Strips surrounding whitespace while preserving broker-specific casing and suffixes (for example ``XAUUSDm``, ``US500.cash``, or ``EURUSD.r``). Args: symbol: Raw symbol name. Returns: Normalized symbol string. Raises: ValueError: If the symbol is empty after normalization. \"\"\" normalized = symbol . strip () if not normalized : msg = \"Symbol must not be empty.\" raise ValueError ( msg ) return normalized normalize_symbols \u00b6 normalize_symbols ( symbols : Sequence [ str ]) -> list [ str ] Normalize a sequence of broker symbol names. Parameters: Name Type Description Default symbols Sequence [ str ] Raw symbol names. required Returns: Type Description list [ str ] List of normalized, de-duplicated symbols preserving first-seen order. Source code in mt5cli/converters.py 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 def normalize_symbols ( symbols : Sequence [ str ]) -> list [ str ]: \"\"\"Normalize a sequence of broker symbol names. Args: symbols: Raw symbol names. Returns: List of normalized, de-duplicated symbols preserving first-seen order. \"\"\" seen : set [ str ] = set () resolved : list [ str ] = [] for symbol in symbols : normalized = normalize_symbol ( symbol ) if normalized not in seen : seen . add ( normalized ) resolved . append ( normalized ) return resolved parse_date_range \u00b6 parse_date_range ( date_from : datetime | str , date_to : datetime | str ) -> tuple [ datetime , datetime ] Parse and validate an inclusive UTC date range. Parameters: Name Type Description Default date_from datetime | str Range start as datetime or ISO 8601 string. required date_to datetime | str Range end as datetime or ISO 8601 string. required Returns: Type Description tuple [ datetime , datetime ] Tuple of UTC-aware (start, end) datetimes. Raises: Type Description ValueError If date_from is after date_to . Source code in mt5cli/converters.py 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 def parse_date_range ( date_from : datetime | str , date_to : datetime | str , ) -> tuple [ datetime , datetime ]: \"\"\"Parse and validate an inclusive UTC date range. Args: date_from: Range start as datetime or ISO 8601 string. date_to: Range end as datetime or ISO 8601 string. Returns: Tuple of UTC-aware ``(start, end)`` datetimes. Raises: ValueError: If ``date_from`` is after ``date_to``. \"\"\" start = ensure_utc ( date_from ) end = ensure_utc ( date_to ) if start > end : msg = ( f \"date_from ( { start . isoformat () } ) must not be after \" f \"date_to ( { end . isoformat () } ).\" ) raise ValueError ( msg ) return start , end parse_datetime \u00b6 parse_datetime ( value : str ) -> datetime Parse an ISO 8601 datetime string to a timezone-aware datetime. Parameters: Name Type Description Default value str ISO 8601 datetime string (e.g., '2024-01-01' or '2024-01-01T12:00:00+00:00'). required Returns: Type Description datetime Parsed datetime with UTC timezone if no timezone is specified. Raises: Type Description ValueError If the string cannot be parsed. Source code in mt5cli/utils.py 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 def parse_datetime ( value : str ) -> datetime : \"\"\"Parse an ISO 8601 datetime string to a timezone-aware datetime. Args: value: ISO 8601 datetime string (e.g., '2024-01-01' or '2024-01-01T12:00:00+00:00'). Returns: Parsed datetime with UTC timezone if no timezone is specified. Raises: ValueError: If the string cannot be parsed. \"\"\" try : dt = datetime . fromisoformat ( value ) except ValueError : msg = f \"Invalid datetime format: ' { value } '. Use ISO 8601 format.\" raise ValueError ( msg ) from None if dt . tzinfo is None : dt = dt . replace ( tzinfo = UTC ) return dt parse_tick_flags \u00b6 parse_tick_flags ( value : object ) -> int Parse tick flags string or integer value. Parameters: Name Type Description Default value object Tick flag name (ALL, INFO, TRADE, COPY_TICKS_*) or integer value. required Returns: Type Description int Integer tick flag value compatible with MetaTrader 5 COPY_TICKS_* . Raises: Type Description ValueError If the flag is invalid. Source code in mt5cli/utils.py 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 def parse_tick_flags ( value : object ) -> int : \"\"\"Parse tick flags string or integer value. Args: value: Tick flag name (ALL, INFO, TRADE, COPY_TICKS_*) or integer value. Returns: Integer tick flag value compatible with MetaTrader 5 ``COPY_TICKS_*``. Raises: ValueError: If the flag is invalid. \"\"\" try : return _parse_copy_ticks ( value ) except ValueError : display = value if isinstance ( value , str ) else repr ( value ) valid = \", \" . join ( _TICK_FLAG_NAMES ) msg = ( f \"Invalid tick flags: ' { display } '. \" f \"Use one of: { valid } , or a supported integer.\" ) raise ValueError ( msg ) from None parse_timeframe \u00b6 parse_timeframe ( value : object ) -> int Parse a timeframe string or integer value. Parameters: Name Type Description Default value object Timeframe name (e.g., 'M1', 'H1', 'D1') or integer value. required Returns: Type Description int Integer timeframe value. Raises: Type Description ValueError If the timeframe is invalid. Source code in mt5cli/utils.py 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 def parse_timeframe ( value : object ) -> int : \"\"\"Parse a timeframe string or integer value. Args: value: Timeframe name (e.g., 'M1', 'H1', 'D1') or integer value. Returns: Integer timeframe value. Raises: ValueError: If the timeframe is invalid. \"\"\" try : return _parse_timeframe ( value ) except ValueError : display = value if isinstance ( value , str ) else repr ( value ) valid = \", \" . join ( TIMEFRAME_NAMES ) msg = ( f \"Invalid timeframe: ' { display } '. \" f \"Use one of: { valid } , or a supported integer.\" ) raise ValueError ( msg ) from None recent_window \u00b6 recent_window ( * , hours : float | None = None , seconds : float | None = None , date_to : datetime | str | None = None , ) -> tuple [ datetime , datetime ] Build a trailing UTC window ending at date_to or now. Exactly one of hours or seconds must be provided. Parameters: Name Type Description Default hours float | None Trailing window length in hours. None seconds float | None Trailing window length in seconds. None date_to datetime | str | None Window end. Defaults to current UTC time. None Returns: Type Description tuple [ datetime , datetime ] Tuple of UTC-aware (start, end) datetimes. Raises: Type Description ValueError If neither or both window lengths are provided, or if a length is not positive. Source code in mt5cli/converters.py 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 def recent_window ( * , hours : float | None = None , seconds : float | None = None , date_to : datetime | str | None = None , ) -> tuple [ datetime , datetime ]: \"\"\"Build a trailing UTC window ending at ``date_to`` or now. Exactly one of ``hours`` or ``seconds`` must be provided. Args: hours: Trailing window length in hours. seconds: Trailing window length in seconds. date_to: Window end. Defaults to current UTC time. Returns: Tuple of UTC-aware ``(start, end)`` datetimes. Raises: ValueError: If neither or both window lengths are provided, or if a length is not positive. \"\"\" if ( hours is None ) == ( seconds is None ): msg = \"Provide exactly one of hours or seconds.\" raise ValueError ( msg ) if hours is not None : length = timedelta ( hours = hours ) else : length = timedelta ( seconds = seconds if seconds is not None else 0 ) if length . total_seconds () <= 0 : msg = \"Window length must be positive.\" raise ValueError ( msg ) end = ensure_utc ( date_to ) if date_to is not None else datetime . now ( UTC ) return end - length , end","title":"Converters"},{"location":"api/converters/#converters","text":"","title":"Converters"},{"location":"api/converters/#mt5cli.converters","text":"Shared conversion helpers for MT5 symbols, timeframes, and date ranges.","title":"converters"},{"location":"api/converters/#mt5cli.converters.__all__","text":"__all__ = [ \"ensure_utc\" , \"granularity_name\" , \"normalize_symbol\" , \"normalize_symbols\" , \"parse_date_range\" , \"parse_datetime\" , \"parse_tick_flags\" , \"parse_timeframe\" , \"recent_window\" , ]","title":"__all__"},{"location":"api/converters/#mt5cli.converters.ensure_utc","text":"ensure_utc ( value : datetime | str ) -> datetime Return a timezone-aware UTC datetime. Parameters: Name Type Description Default value datetime | str Datetime instance or ISO 8601 string. required Returns: Type Description datetime UTC-aware datetime. Source code in mt5cli/converters.py 69 70 71 72 73 74 75 76 77 78 79 80 81 82 def ensure_utc ( value : datetime | str ) -> datetime : \"\"\"Return a timezone-aware UTC datetime. Args: value: Datetime instance or ISO 8601 string. Returns: UTC-aware datetime. \"\"\" if isinstance ( value , str ): return parse_datetime ( value ) if value . tzinfo is None : return value . replace ( tzinfo = UTC ) return value . astimezone ( UTC )","title":"ensure_utc"},{"location":"api/converters/#mt5cli.converters.granularity_name","text":"granularity_name ( timeframe : int | str ) -> str Return a short granularity label for a timeframe integer or name. Parameters: Name Type Description Default timeframe int | str MT5 timeframe as integer or name (for example M1 ). required Returns: Type Description str Short name such as M1 or the stringified integer when unknown. Source code in mt5cli/converters.py 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 def granularity_name ( timeframe : int | str ) -> str : \"\"\"Return a short granularity label for a timeframe integer or name. Args: timeframe: MT5 timeframe as integer or name (for example ``M1``). Returns: Short name such as ``M1`` or the stringified integer when unknown. \"\"\" tf = parse_timeframe ( timeframe ) try : name = _get_timeframe_name ( tf ) except ValueError : return str ( tf ) return name . removeprefix ( \"TIMEFRAME_\" )","title":"granularity_name"},{"location":"api/converters/#mt5cli.converters.normalize_symbol","text":"normalize_symbol ( symbol : str ) -> str Normalize a broker symbol name for MT5 API calls. Strips surrounding whitespace while preserving broker-specific casing and suffixes (for example XAUUSDm , US500.cash , or EURUSD.r ). Parameters: Name Type Description Default symbol str Raw symbol name. required Returns: Type Description str Normalized symbol string. Raises: Type Description ValueError If the symbol is empty after normalization. Source code in mt5cli/converters.py 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 def normalize_symbol ( symbol : str ) -> str : \"\"\"Normalize a broker symbol name for MT5 API calls. Strips surrounding whitespace while preserving broker-specific casing and suffixes (for example ``XAUUSDm``, ``US500.cash``, or ``EURUSD.r``). Args: symbol: Raw symbol name. Returns: Normalized symbol string. Raises: ValueError: If the symbol is empty after normalization. \"\"\" normalized = symbol . strip () if not normalized : msg = \"Symbol must not be empty.\" raise ValueError ( msg ) return normalized","title":"normalize_symbol"},{"location":"api/converters/#mt5cli.converters.normalize_symbols","text":"normalize_symbols ( symbols : Sequence [ str ]) -> list [ str ] Normalize a sequence of broker symbol names. Parameters: Name Type Description Default symbols Sequence [ str ] Raw symbol names. required Returns: Type Description list [ str ] List of normalized, de-duplicated symbols preserving first-seen order. Source code in mt5cli/converters.py 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 def normalize_symbols ( symbols : Sequence [ str ]) -> list [ str ]: \"\"\"Normalize a sequence of broker symbol names. Args: symbols: Raw symbol names. Returns: List of normalized, de-duplicated symbols preserving first-seen order. \"\"\" seen : set [ str ] = set () resolved : list [ str ] = [] for symbol in symbols : normalized = normalize_symbol ( symbol ) if normalized not in seen : seen . add ( normalized ) resolved . append ( normalized ) return resolved","title":"normalize_symbols"},{"location":"api/converters/#mt5cli.converters.parse_date_range","text":"parse_date_range ( date_from : datetime | str , date_to : datetime | str ) -> tuple [ datetime , datetime ] Parse and validate an inclusive UTC date range. Parameters: Name Type Description Default date_from datetime | str Range start as datetime or ISO 8601 string. required date_to datetime | str Range end as datetime or ISO 8601 string. required Returns: Type Description tuple [ datetime , datetime ] Tuple of UTC-aware (start, end) datetimes. Raises: Type Description ValueError If date_from is after date_to . Source code in mt5cli/converters.py 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 def parse_date_range ( date_from : datetime | str , date_to : datetime | str , ) -> tuple [ datetime , datetime ]: \"\"\"Parse and validate an inclusive UTC date range. Args: date_from: Range start as datetime or ISO 8601 string. date_to: Range end as datetime or ISO 8601 string. Returns: Tuple of UTC-aware ``(start, end)`` datetimes. Raises: ValueError: If ``date_from`` is after ``date_to``. \"\"\" start = ensure_utc ( date_from ) end = ensure_utc ( date_to ) if start > end : msg = ( f \"date_from ( { start . isoformat () } ) must not be after \" f \"date_to ( { end . isoformat () } ).\" ) raise ValueError ( msg ) return start , end","title":"parse_date_range"},{"location":"api/converters/#mt5cli.converters.parse_datetime","text":"parse_datetime ( value : str ) -> datetime Parse an ISO 8601 datetime string to a timezone-aware datetime. Parameters: Name Type Description Default value str ISO 8601 datetime string (e.g., '2024-01-01' or '2024-01-01T12:00:00+00:00'). required Returns: Type Description datetime Parsed datetime with UTC timezone if no timezone is specified. Raises: Type Description ValueError If the string cannot be parsed. Source code in mt5cli/utils.py 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 def parse_datetime ( value : str ) -> datetime : \"\"\"Parse an ISO 8601 datetime string to a timezone-aware datetime. Args: value: ISO 8601 datetime string (e.g., '2024-01-01' or '2024-01-01T12:00:00+00:00'). Returns: Parsed datetime with UTC timezone if no timezone is specified. Raises: ValueError: If the string cannot be parsed. \"\"\" try : dt = datetime . fromisoformat ( value ) except ValueError : msg = f \"Invalid datetime format: ' { value } '. Use ISO 8601 format.\" raise ValueError ( msg ) from None if dt . tzinfo is None : dt = dt . replace ( tzinfo = UTC ) return dt","title":"parse_datetime"},{"location":"api/converters/#mt5cli.converters.parse_tick_flags","text":"parse_tick_flags ( value : object ) -> int Parse tick flags string or integer value. Parameters: Name Type Description Default value object Tick flag name (ALL, INFO, TRADE, COPY_TICKS_*) or integer value. required Returns: Type Description int Integer tick flag value compatible with MetaTrader 5 COPY_TICKS_* . Raises: Type Description ValueError If the flag is invalid. Source code in mt5cli/utils.py 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 def parse_tick_flags ( value : object ) -> int : \"\"\"Parse tick flags string or integer value. Args: value: Tick flag name (ALL, INFO, TRADE, COPY_TICKS_*) or integer value. Returns: Integer tick flag value compatible with MetaTrader 5 ``COPY_TICKS_*``. Raises: ValueError: If the flag is invalid. \"\"\" try : return _parse_copy_ticks ( value ) except ValueError : display = value if isinstance ( value , str ) else repr ( value ) valid = \", \" . join ( _TICK_FLAG_NAMES ) msg = ( f \"Invalid tick flags: ' { display } '. \" f \"Use one of: { valid } , or a supported integer.\" ) raise ValueError ( msg ) from None","title":"parse_tick_flags"},{"location":"api/converters/#mt5cli.converters.parse_timeframe","text":"parse_timeframe ( value : object ) -> int Parse a timeframe string or integer value. Parameters: Name Type Description Default value object Timeframe name (e.g., 'M1', 'H1', 'D1') or integer value. required Returns: Type Description int Integer timeframe value. Raises: Type Description ValueError If the timeframe is invalid. Source code in mt5cli/utils.py 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 def parse_timeframe ( value : object ) -> int : \"\"\"Parse a timeframe string or integer value. Args: value: Timeframe name (e.g., 'M1', 'H1', 'D1') or integer value. Returns: Integer timeframe value. Raises: ValueError: If the timeframe is invalid. \"\"\" try : return _parse_timeframe ( value ) except ValueError : display = value if isinstance ( value , str ) else repr ( value ) valid = \", \" . join ( TIMEFRAME_NAMES ) msg = ( f \"Invalid timeframe: ' { display } '. \" f \"Use one of: { valid } , or a supported integer.\" ) raise ValueError ( msg ) from None","title":"parse_timeframe"},{"location":"api/converters/#mt5cli.converters.recent_window","text":"recent_window ( * , hours : float | None = None , seconds : float | None = None , date_to : datetime | str | None = None , ) -> tuple [ datetime , datetime ] Build a trailing UTC window ending at date_to or now. Exactly one of hours or seconds must be provided. Parameters: Name Type Description Default hours float | None Trailing window length in hours. None seconds float | None Trailing window length in seconds. None date_to datetime | str | None Window end. Defaults to current UTC time. None Returns: Type Description tuple [ datetime , datetime ] Tuple of UTC-aware (start, end) datetimes. Raises: Type Description ValueError If neither or both window lengths are provided, or if a length is not positive. Source code in mt5cli/converters.py 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 def recent_window ( * , hours : float | None = None , seconds : float | None = None , date_to : datetime | str | None = None , ) -> tuple [ datetime , datetime ]: \"\"\"Build a trailing UTC window ending at ``date_to`` or now. Exactly one of ``hours`` or ``seconds`` must be provided. Args: hours: Trailing window length in hours. seconds: Trailing window length in seconds. date_to: Window end. Defaults to current UTC time. Returns: Tuple of UTC-aware ``(start, end)`` datetimes. Raises: ValueError: If neither or both window lengths are provided, or if a length is not positive. \"\"\" if ( hours is None ) == ( seconds is None ): msg = \"Provide exactly one of hours or seconds.\" raise ValueError ( msg ) if hours is not None : length = timedelta ( hours = hours ) else : length = timedelta ( seconds = seconds if seconds is not None else 0 ) if length . total_seconds () <= 0 : msg = \"Window length must be positive.\" raise ValueError ( msg ) end = ensure_utc ( date_to ) if date_to is not None else datetime . now ( UTC ) return end - length , end","title":"recent_window"},{"location":"api/exceptions/","text":"Exceptions \u00b6 mt5cli.exceptions \u00b6 Normalized exception types for MT5 and mt5cli operations. T module-attribute \u00b6 T = TypeVar ( 'T' ) __all__ module-attribute \u00b6 __all__ = [ \"Mt5CliError\" , \"Mt5ConnectionError\" , \"Mt5OperationError\" , \"Mt5SchemaError\" , \"call_with_normalized_errors\" , \"is_recoverable_mt5_error\" , \"normalize_mt5_exception\" , ] Mt5CliError \u00b6 Bases: Exception Base exception for mt5cli public API errors. Mt5ConnectionError \u00b6 Bases: Mt5CliError Raised when MT5 initialization, login, or shutdown fails. Mt5OperationError \u00b6 Bases: Mt5CliError Raised when an MT5 data or trading operation fails. Mt5SchemaError \u00b6 Bases: Mt5CliError Raised when a DataFrame does not match an expected dataset schema. call_with_normalized_errors \u00b6 call_with_normalized_errors ( fn : Callable [[], T ]) -> T Run fn and map recoverable MT5 errors to mt5cli types. Parameters: Name Type Description Default fn Callable [[], T ] Callable performing MT5 work. required Returns: Type Description T Value returned by fn . Source code in mt5cli/exceptions.py 77 78 79 80 81 82 83 84 85 86 87 88 89 90 def call_with_normalized_errors ( fn : Callable [[], T ]) -> T : \"\"\"Run ``fn`` and map recoverable MT5 errors to mt5cli types. Args: fn: Callable performing MT5 work. Returns: Value returned by ``fn``. \"\"\" try : return fn () except _RECOVERABLE_MT5_ERRORS as exc : normalized = normalize_mt5_exception ( exc ) raise normalized from exc is_recoverable_mt5_error \u00b6 is_recoverable_mt5_error ( exc : BaseException ) -> bool Return whether an exception is a transient MT5 failure worth retrying. Parameters: Name Type Description Default exc BaseException Exception raised by MT5 or pdmt5. required Returns: Type Description bool True for Mt5RuntimeError and Mt5TradingError . Source code in mt5cli/exceptions.py 46 47 48 49 50 51 52 53 54 55 def is_recoverable_mt5_error ( exc : BaseException ) -> bool : \"\"\"Return whether an exception is a transient MT5 failure worth retrying. Args: exc: Exception raised by MT5 or pdmt5. Returns: True for ``Mt5RuntimeError`` and ``Mt5TradingError``. \"\"\" return isinstance ( exc , _RECOVERABLE_MT5_ERRORS ) normalize_mt5_exception \u00b6 normalize_mt5_exception ( exc : BaseException ) -> Mt5CliError Map pdmt5/MT5 exceptions to stable mt5cli exception types. Parameters: Name Type Description Default exc BaseException Original exception from MT5 or pdmt5. required Returns: Type Description Mt5CliError Mt5ConnectionError for runtime failures, Mt5OperationError for Mt5CliError trading failures, or the original exception when it is not recognized. Source code in mt5cli/exceptions.py 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 def normalize_mt5_exception ( exc : BaseException ) -> Mt5CliError : \"\"\"Map pdmt5/MT5 exceptions to stable mt5cli exception types. Args: exc: Original exception from MT5 or pdmt5. Returns: ``Mt5ConnectionError`` for runtime failures, ``Mt5OperationError`` for trading failures, or the original exception when it is not recognized. \"\"\" if isinstance ( exc , Mt5TradingError ): return Mt5OperationError ( str ( exc )) if isinstance ( exc , Mt5RuntimeError ): return Mt5ConnectionError ( str ( exc )) if isinstance ( exc , Mt5CliError ): return exc return Mt5CliError ( str ( exc ))","title":"Exceptions"},{"location":"api/exceptions/#exceptions","text":"","title":"Exceptions"},{"location":"api/exceptions/#mt5cli.exceptions","text":"Normalized exception types for MT5 and mt5cli operations.","title":"exceptions"},{"location":"api/exceptions/#mt5cli.exceptions.T","text":"T = TypeVar ( 'T' )","title":"T"},{"location":"api/exceptions/#mt5cli.exceptions.__all__","text":"__all__ = [ \"Mt5CliError\" , \"Mt5ConnectionError\" , \"Mt5OperationError\" , \"Mt5SchemaError\" , \"call_with_normalized_errors\" , \"is_recoverable_mt5_error\" , \"normalize_mt5_exception\" , ]","title":"__all__"},{"location":"api/exceptions/#mt5cli.exceptions.Mt5CliError","text":"Bases: Exception Base exception for mt5cli public API errors.","title":"Mt5CliError"},{"location":"api/exceptions/#mt5cli.exceptions.Mt5ConnectionError","text":"Bases: Mt5CliError Raised when MT5 initialization, login, or shutdown fails.","title":"Mt5ConnectionError"},{"location":"api/exceptions/#mt5cli.exceptions.Mt5OperationError","text":"Bases: Mt5CliError Raised when an MT5 data or trading operation fails.","title":"Mt5OperationError"},{"location":"api/exceptions/#mt5cli.exceptions.Mt5SchemaError","text":"Bases: Mt5CliError Raised when a DataFrame does not match an expected dataset schema.","title":"Mt5SchemaError"},{"location":"api/exceptions/#mt5cli.exceptions.call_with_normalized_errors","text":"call_with_normalized_errors ( fn : Callable [[], T ]) -> T Run fn and map recoverable MT5 errors to mt5cli types. Parameters: Name Type Description Default fn Callable [[], T ] Callable performing MT5 work. required Returns: Type Description T Value returned by fn . Source code in mt5cli/exceptions.py 77 78 79 80 81 82 83 84 85 86 87 88 89 90 def call_with_normalized_errors ( fn : Callable [[], T ]) -> T : \"\"\"Run ``fn`` and map recoverable MT5 errors to mt5cli types. Args: fn: Callable performing MT5 work. Returns: Value returned by ``fn``. \"\"\" try : return fn () except _RECOVERABLE_MT5_ERRORS as exc : normalized = normalize_mt5_exception ( exc ) raise normalized from exc","title":"call_with_normalized_errors"},{"location":"api/exceptions/#mt5cli.exceptions.is_recoverable_mt5_error","text":"is_recoverable_mt5_error ( exc : BaseException ) -> bool Return whether an exception is a transient MT5 failure worth retrying. Parameters: Name Type Description Default exc BaseException Exception raised by MT5 or pdmt5. required Returns: Type Description bool True for Mt5RuntimeError and Mt5TradingError . Source code in mt5cli/exceptions.py 46 47 48 49 50 51 52 53 54 55 def is_recoverable_mt5_error ( exc : BaseException ) -> bool : \"\"\"Return whether an exception is a transient MT5 failure worth retrying. Args: exc: Exception raised by MT5 or pdmt5. Returns: True for ``Mt5RuntimeError`` and ``Mt5TradingError``. \"\"\" return isinstance ( exc , _RECOVERABLE_MT5_ERRORS )","title":"is_recoverable_mt5_error"},{"location":"api/exceptions/#mt5cli.exceptions.normalize_mt5_exception","text":"normalize_mt5_exception ( exc : BaseException ) -> Mt5CliError Map pdmt5/MT5 exceptions to stable mt5cli exception types. Parameters: Name Type Description Default exc BaseException Original exception from MT5 or pdmt5. required Returns: Type Description Mt5CliError Mt5ConnectionError for runtime failures, Mt5OperationError for Mt5CliError trading failures, or the original exception when it is not recognized. Source code in mt5cli/exceptions.py 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 def normalize_mt5_exception ( exc : BaseException ) -> Mt5CliError : \"\"\"Map pdmt5/MT5 exceptions to stable mt5cli exception types. Args: exc: Original exception from MT5 or pdmt5. Returns: ``Mt5ConnectionError`` for runtime failures, ``Mt5OperationError`` for trading failures, or the original exception when it is not recognized. \"\"\" if isinstance ( exc , Mt5TradingError ): return Mt5OperationError ( str ( exc )) if isinstance ( exc , Mt5RuntimeError ): return Mt5ConnectionError ( str ( exc )) if isinstance ( exc , Mt5CliError ): return exc return Mt5CliError ( str ( exc ))","title":"normalize_mt5_exception"},{"location":"api/history/","text":"History Collection (SQLite) \u00b6 mt5cli.history \u00b6 SQLite storage helpers for the collect-history incremental data pipeline. DEFAULT_HISTORY_TIMEFRAMES module-attribute \u00b6 DEFAULT_HISTORY_TIMEFRAMES : tuple [ str , ... ] = ( TIMEFRAME_NAMES ) SqliteConnOrPath module-attribute \u00b6 SqliteConnOrPath = Connection | Path | str logger module-attribute \u00b6 logger = getLogger ( __name__ ) DedupScope dataclass \u00b6 DedupScope ( where : str , params : tuple [ object , ... ], required_columns : frozenset [ str ], ) Scoped deduplication predicate and the columns it references. Attributes: Name Type Description where str SQL predicate appended to the duplicate-removal query. params tuple [ object , ...] Parameters bound to the scope predicate. required_columns frozenset [ str ] Columns that must be present in the written table for the scope to run. params instance-attribute \u00b6 params : tuple [ object , ... ] required_columns instance-attribute \u00b6 required_columns : frozenset [ str ] where instance-attribute \u00b6 where : str RateTarget dataclass \u00b6 RateTarget ( symbol : str | None , timeframe : int | str ) A single rate series identified by symbol and timeframe. Attributes: Name Type Description symbol str | None MT5 symbol name, or None when the rate series is addressed only by an explicit table (for example a custom SQLite view). timeframe int | str MT5 timeframe as an integer or name (for example M1 ). symbol instance-attribute \u00b6 symbol : str | None timeframe instance-attribute \u00b6 timeframe : int | str timeframe_int property \u00b6 timeframe_int : int Return the timeframe as its integer MT5 value. __post_init__ \u00b6 __post_init__ () -> None Normalize accepted timeframe aliases to the stored integer value. Source code in mt5cli/history.py 544 545 546 547 def __post_init__ ( self ) -> None : \"\"\"Normalize accepted timeframe aliases to the stored integer value.\"\"\" if not isinstance ( self . timeframe , int ): object . __setattr__ ( self , \"timeframe\" , parse_timeframe ( self . timeframe )) append_dataframe \u00b6 append_dataframe ( conn : Connection , frame : DataFrame , table_name : str , if_exists : IfExists , ) -> bool Append a DataFrame to SQLite when it has a schema. Returns: Type Description bool True if a table was written, False if the frame had no columns. Source code in mt5cli/history.py 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 def append_dataframe ( conn : sqlite3 . Connection , frame : pd . DataFrame , table_name : str , if_exists : IfExists , ) -> bool : \"\"\"Append a DataFrame to SQLite when it has a schema. Returns: True if a table was written, False if the frame had no columns. \"\"\" if len ( frame . columns ) == 0 : logger . warning ( \"Skipping %s : dataset returned no columns\" , table_name ) return False frame . to_sql ( # type: ignore[reportUnknownMemberType] table_name , conn , if_exists = if_exists . value , index = False , chunksize = 50_000 , ) return True augment_written_columns_from_sqlite \u00b6 augment_written_columns_from_sqlite ( conn : Connection , datasets : set [ Dataset ], written_columns : dict [ Dataset , set [ str ]], ) -> None Add existing table columns to the written column map. Source code in mt5cli/history.py 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 def augment_written_columns_from_sqlite ( conn : sqlite3 . Connection , datasets : set [ Dataset ], written_columns : dict [ Dataset , set [ str ]], ) -> None : \"\"\"Add existing table columns to the written column map.\"\"\" for dataset in datasets : columns = get_table_columns ( conn , dataset . table_name ) if not columns : continue if dataset in written_columns : written_columns [ dataset ] . update ( columns ) else : written_columns [ dataset ] = columns build_rate_targets \u00b6 build_rate_targets ( symbols : Sequence [ str ], timeframes : Sequence [ int | str ], * , allow_missing_symbol : bool = False , ) -> list [ RateTarget ] Build rate targets for every symbol and timeframe combination. Parameters: Name Type Description Default symbols Sequence [ str ] MT5 symbol names. May be empty when allow_missing_symbol . required timeframes Sequence [ int | str ] MT5 timeframes as integers or names (for example M1 ). required allow_missing_symbol bool When True and symbols is empty, build targets with symbol=None for each timeframe instead of raising. False Returns: Type Description list [ RateTarget ] Targets in row-major order: every timeframe for the first symbol, then list [ RateTarget ] every timeframe for the next symbol, and so on. Raises: Type Description ValueError If timeframes is empty, or symbols is empty and allow_missing_symbol is False. Source code in mt5cli/history.py 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 def build_rate_targets ( symbols : Sequence [ str ], timeframes : Sequence [ int | str ], * , allow_missing_symbol : bool = False , ) -> list [ RateTarget ]: \"\"\"Build rate targets for every symbol and timeframe combination. Args: symbols: MT5 symbol names. May be empty when ``allow_missing_symbol``. timeframes: MT5 timeframes as integers or names (for example ``M1``). allow_missing_symbol: When True and ``symbols`` is empty, build targets with ``symbol=None`` for each timeframe instead of raising. Returns: Targets in row-major order: every timeframe for the first symbol, then every timeframe for the next symbol, and so on. Raises: ValueError: If ``timeframes`` is empty, or ``symbols`` is empty and ``allow_missing_symbol`` is False. \"\"\" if not timeframes : msg = \"At least one timeframe is required.\" raise ValueError ( msg ) if not symbols : if not allow_missing_symbol : msg = \"At least one symbol is required.\" raise ValueError ( msg ) return [ RateTarget ( symbol = None , timeframe = tf ) for tf in timeframes ] return [ RateTarget ( symbol = symbol , timeframe = tf ) for symbol in symbols for tf in timeframes ] build_rate_view_name \u00b6 build_rate_view_name ( * , symbol : str , granularity : str , granularity_count : int , timeframe : int , ) -> str Return a collision-free offline optimize view name. View names always include the timeframe integer after a __ separator so a symbol such as EURUSD_M1 cannot collide with EURUSD at timeframe M1 . Source code in mt5cli/history.py 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 def build_rate_view_name ( * , symbol : str , granularity : str , granularity_count : int , timeframe : int , ) -> str : \"\"\"Return a collision-free offline optimize view name. View names always include the timeframe integer after a ``__`` separator so a symbol such as ``EURUSD_M1`` cannot collide with ``EURUSD`` at timeframe ``M1``. \"\"\" if granularity_count == 1 : return f \"rate_ { symbol } __ { timeframe } \" return f \"rate_ { symbol } __ { granularity } _ { timeframe } \" create_cash_events_view \u00b6 create_cash_events_view ( conn : Connection , deals_columns : set [ str ] ) -> bool Create the cash_events SQLite view derived from history_deals. Returns: Type Description bool True if the view was created, False if required columns are missing. Source code in mt5cli/history.py 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 def create_cash_events_view ( conn : sqlite3 . Connection , deals_columns : set [ str ], ) -> bool : \"\"\"Create the cash_events SQLite view derived from history_deals. Returns: True if the view was created, False if required columns are missing. \"\"\" if \"type\" not in deals_columns : logger . warning ( \"Skipping cash_events view: history_deals.type is missing\" ) return False conn . execute ( \"DROP VIEW IF EXISTS cash_events\" ) conn . execute ( \"CREATE VIEW cash_events AS\" # noqa: S608 f \" SELECT * FROM history_deals WHERE type NOT IN { _TRADE_DEAL_TYPES_SQL } \" , ) return True create_history_indexes \u00b6 create_history_indexes ( conn : Connection , written_columns : dict [ Dataset , set [ str ]], ) -> None Create useful indexes for collected history tables when present. Source code in mt5cli/history.py 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 def create_history_indexes ( conn : sqlite3 . Connection , written_columns : dict [ Dataset , set [ str ]], ) -> None : \"\"\"Create useful indexes for collected history tables when present.\"\"\" if { \"symbol\" , \"timeframe\" , \"time\" } . issubset ( written_columns . get ( Dataset . rates , set ()), ): conn . execute ( \"CREATE INDEX IF NOT EXISTS idx_rates_symbol_timeframe_time\" \" ON rates(symbol, timeframe, time)\" , ) if { \"symbol\" , \"time\" } . issubset ( written_columns . get ( Dataset . ticks , set ())): conn . execute ( \"CREATE INDEX IF NOT EXISTS idx_ticks_symbol_time ON ticks(symbol, time)\" , ) if { \"position_id\" , \"symbol\" } . issubset ( written_columns . get ( Dataset . history_deals , set ()), ): conn . execute ( \"CREATE INDEX IF NOT EXISTS idx_history_deals_position_symbol\" \" ON history_deals(position_id, symbol)\" , ) create_positions_reconstructed_view \u00b6 create_positions_reconstructed_view ( conn : Connection , deals_columns : set [ str ] ) -> bool Create the positions_reconstructed SQLite view derived from history_deals. Returns: Type Description bool True if the view was created, False if required columns are missing. Source code in mt5cli/history.py 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 def create_positions_reconstructed_view ( conn : sqlite3 . Connection , deals_columns : set [ str ], ) -> bool : \"\"\"Create the positions_reconstructed SQLite view derived from history_deals. Returns: True if the view was created, False if required columns are missing. \"\"\" if not _POSITIONS_VIEW_REQUIRED_COLUMNS . issubset ( deals_columns ): missing = \", \" . join ( sorted ( _POSITIONS_VIEW_REQUIRED_COLUMNS - deals_columns )) logger . warning ( \"Skipping positions_reconstructed view: history_deals missing columns: %s \" , missing , ) return False conn . execute ( \"DROP VIEW IF EXISTS positions_reconstructed\" ) conn . execute ( \"CREATE VIEW positions_reconstructed AS\" # noqa: S608 \" SELECT\" \" position_id,\" \" symbol,\" \" MIN(CASE WHEN entry = 0 THEN time END) AS open_time,\" \" MAX(CASE WHEN entry IN (1, 2, 3) THEN time END) AS close_time,\" \" MIN(CASE WHEN entry = 0 THEN type END) AS direction,\" \" SUM(CASE WHEN entry = 0 THEN volume ELSE 0 END) AS volume_open,\" \" SUM(CASE WHEN entry IN (1, 2, 3) THEN volume ELSE 0 END) AS volume_close,\" \" SUM(CASE WHEN entry = 2 THEN volume ELSE 0 END) AS volume_reversal,\" \" CASE\" \" WHEN SUM(CASE WHEN entry = 0 THEN volume ELSE 0 END) > 0\" \" THEN SUM(CASE WHEN entry = 0 THEN price * volume ELSE 0 END)\" \" / SUM(CASE WHEN entry = 0 THEN volume ELSE 0 END)\" \" END AS open_price,\" \" CASE\" \" WHEN SUM(CASE WHEN entry IN (1, 2, 3) THEN volume ELSE 0 END) > 0\" \" THEN SUM(CASE WHEN entry IN (1, 2, 3) THEN price * volume ELSE 0 END)\" \" / SUM(CASE WHEN entry IN (1, 2, 3) THEN volume ELSE 0 END)\" \" END AS close_price,\" \" SUM(profit) AS total_profit,\" \" SUM(CASE WHEN entry = 2 THEN 1 ELSE 0 END) AS reversal_count,\" \" COUNT(*) AS deals_count\" \" FROM history_deals\" f \" WHERE type IN { _TRADE_DEAL_TYPES_SQL } AND position_id != 0\" \" GROUP BY position_id, symbol\" \" HAVING SUM(CASE WHEN entry IN (1, 2, 3) THEN 1 ELSE 0 END) > 0\" , ) return True create_rate_compatibility_views \u00b6 create_rate_compatibility_views ( conn : Connection ) -> None Create rate compatibility views from the normalized rates table. Source code in mt5cli/history.py 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 def create_rate_compatibility_views ( conn : sqlite3 . Connection ) -> None : \"\"\"Create rate compatibility views from the normalized rates table.\"\"\" columns = get_table_columns ( conn , Dataset . rates . table_name ) if not { \"symbol\" , \"timeframe\" , \"time\" } . issubset ( columns ): return drop_rate_compatibility_views ( conn ) select_columns = sorted ( columns - { \"symbol\" , \"timeframe\" }) quoted_columns = \", \" . join ( f '\" { column } \"' for column in select_columns ) rows = conn . execute ( \"SELECT DISTINCT symbol, timeframe FROM rates ORDER BY symbol, timeframe\" , ) . fetchall () timeframes_by_symbol : dict [ str , list [ int ]] = {} for symbol , timeframe in rows : timeframes_by_symbol . setdefault ( str ( symbol ), []) . append ( int ( timeframe )) for symbol , timeframes in timeframes_by_symbol . items (): for timeframe in timeframes : granularity = resolve_granularity_name ( timeframe ) view_name = build_rate_view_name ( symbol = symbol , granularity = granularity , granularity_count = len ( timeframes ), timeframe = timeframe , ) quoted_view_name = quote_sqlite_identifier ( view_name ) escaped_symbol = symbol . replace ( \"'\" , \"''\" ) conn . execute ( f \"CREATE VIEW { quoted_view_name } AS\" # noqa: S608 f \" SELECT { quoted_columns } FROM rates\" f \" WHERE symbol = ' { escaped_symbol } '\" f \" AND timeframe = { timeframe } \" , ) deduplicate_history_tables \u00b6 deduplicate_history_tables ( conn : Connection , written_columns : dict [ Dataset , set [ str ]], written_tables : set [ Dataset ], dedup_scopes : Mapping [ Dataset , Sequence [ DedupScope ]] | None = None , ) -> None Deduplicate appended history tables by stable identifiers. Scopes whose required columns are not present in the written table are skipped. If all scopes for a dataset are skipped, the table receives one unscoped deduplication pass instead. Source code in mt5cli/history.py 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 def deduplicate_history_tables ( conn : sqlite3 . Connection , written_columns : dict [ Dataset , set [ str ]], written_tables : set [ Dataset ], dedup_scopes : Mapping [ Dataset , Sequence [ DedupScope ]] | None = None , ) -> None : \"\"\"Deduplicate appended history tables by stable identifiers. Scopes whose required columns are not present in the written table are skipped. If all scopes for a dataset are skipped, the table receives one unscoped deduplication pass instead. \"\"\" cursor = conn . cursor () for dataset in written_tables : columns = written_columns . get ( dataset , set ()) table = dataset . table_name keys = next ( ( candidate for candidate in _HISTORY_DEDUP_KEYS [ dataset ] if set ( candidate ) . issubset ( columns ) ), None , ) if keys is None : logger . warning ( \"Skipping %s deduplication: no supported key columns\" , table , ) continue raw_scopes : Sequence [ DedupScope ] = ( dedup_scopes . get ( dataset , ()) if dedup_scopes else () ) scopes = [ scope for scope in raw_scopes if scope . required_columns <= columns ] if scopes : for scope in scopes : drop_duplicates_in_table ( cursor , table , list ( keys ), keep = \"last\" , scope_where = scope . where , scope_params = scope . params , ) continue drop_duplicates_in_table ( cursor , table , list ( keys ), keep = \"last\" ) drop_duplicates_in_table \u00b6 drop_duplicates_in_table ( cursor : Cursor , table : str , ids : list [ str ], * , keep : Literal [ \"first\" , \"last\" ] = \"last\" , scope_where : str | None = None , scope_params : tuple [ object , ... ] = (), ) -> None Remove duplicate rows, keeping the first or last ROWID per key group. Raises: Type Description ValueError If the table or column names are invalid. Source code in mt5cli/history.py 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 def drop_duplicates_in_table ( cursor : sqlite3 . Cursor , table : str , ids : list [ str ], * , keep : Literal [ \"first\" , \"last\" ] = \"last\" , scope_where : str | None = None , scope_params : tuple [ object , ... ] = (), ) -> None : \"\"\"Remove duplicate rows, keeping the first or last ROWID per key group. Raises: ValueError: If the table or column names are invalid. \"\"\" if not table . isidentifier (): msg = f \"Invalid table name: { table } \" raise ValueError ( msg ) if invalid := { column for column in ids if not column . isidentifier ()}: msg = f \"Invalid column names: { ', ' . join ( sorted ( invalid )) } \" raise ValueError ( msg ) ids_csv = \", \" . join ( f '\" { column } \"' for column in ids ) rowid_selector = \"MIN\" if keep == \"first\" else \"MAX\" if scope_where : delete_sql = ( f \"DELETE FROM { table } WHERE { scope_where } AND ROWID NOT IN\" # noqa: S608 f \" (SELECT { rowid_selector } (ROWID) FROM { table } WHERE { scope_where } \" f \" GROUP BY { ids_csv } )\" ) cursor . execute ( delete_sql , scope_params + scope_params ) return cursor . execute ( f \"DELETE FROM { table } WHERE ROWID NOT IN\" # noqa: S608 f \" (SELECT { rowid_selector } (ROWID) FROM { table } GROUP BY { ids_csv } )\" , ) drop_forming_rate_bar \u00b6 drop_forming_rate_bar ( df_rate : DataFrame ) -> DataFrame Return closed bars from chronologically ordered MT5 rate data. MetaTrader 5 copy_rates_from_pos(start_pos=0) includes the still-forming current bar as the last row. Slice it off so downstream logic only sees completed bars. Empty frames and single-row frames return empty results. Parameters: Name Type Description Default df_rate DataFrame Rate data ordered oldest-to-newest with the forming bar last. required Returns: Type Description DataFrame A new DataFrame with all rows except the last. Index and columns are DataFrame preserved. The input frame is not modified. Source code in mt5cli/history.py 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 def drop_forming_rate_bar ( df_rate : pd . DataFrame ) -> pd . DataFrame : \"\"\"Return closed bars from chronologically ordered MT5 rate data. MetaTrader 5 ``copy_rates_from_pos(start_pos=0)`` includes the still-forming current bar as the last row. Slice it off so downstream logic only sees completed bars. Empty frames and single-row frames return empty results. Args: df_rate: Rate data ordered oldest-to-newest with the forming bar last. Returns: A new DataFrame with all rows except the last. Index and columns are preserved. The input frame is not modified. \"\"\" return df_rate . iloc [: - 1 ] . copy () drop_rate_compatibility_views \u00b6 drop_rate_compatibility_views ( conn : Connection ) -> None Drop all mt5cli-managed rate_* compatibility views. Source code in mt5cli/history.py 1355 1356 1357 1358 1359 1360 1361 1362 def drop_rate_compatibility_views ( conn : sqlite3 . Connection ) -> None : \"\"\"Drop all mt5cli-managed ``rate_*`` compatibility views.\"\"\" rows = conn . execute ( \"SELECT name FROM sqlite_master WHERE type = 'view' AND name GLOB 'rate_*'\" , ) . fetchall () for ( view_name ,) in rows : quoted_view_name = quote_sqlite_identifier ( str ( view_name )) conn . execute ( f \"DROP VIEW IF EXISTS { quoted_view_name } \" ) filter_incremental_history_deals_frame \u00b6 filter_incremental_history_deals_frame ( frame : DataFrame , symbols : Sequence [ str ], start_by_symbol : dict [ str , datetime ], account_event_start : datetime , ) -> DataFrame Filter incrementally fetched history_deals by symbol and event start times. Returns: Type Description DataFrame Rows for selected symbols at or after each symbol start, plus account DataFrame events at or after account_event_start . Source code in mt5cli/history.py 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 def filter_incremental_history_deals_frame ( frame : pd . DataFrame , symbols : Sequence [ str ], start_by_symbol : dict [ str , datetime ], account_event_start : datetime , ) -> pd . DataFrame : \"\"\"Filter incrementally fetched history_deals by symbol and event start times. Returns: Rows for selected symbols at or after each symbol start, plus account events at or after ``account_event_start``. \"\"\" if frame . empty : return frame . copy () parsed_times = _frame_parsed_times ( frame ) time_valid = parsed_times . notna () account_event_mask = _history_deals_account_event_mask ( frame ) account_keep = account_event_mask & ( parsed_times >= account_event_start ) trade_keep = pd . Series ( data = False , index = frame . index ) if \"symbol\" in frame . columns : for symbol in symbols : trade_keep |= ( ( frame [ \"symbol\" ] == symbol ) & ( parsed_times >= start_by_symbol [ symbol ]) & ~ account_event_mask ) keep = ( account_keep | trade_keep ) & time_valid return frame . loc [ keep ] . copy () filter_trade_history_frame \u00b6 filter_trade_history_frame ( frame : DataFrame , symbols : Sequence [ str ], * , include_account_events : bool , ) -> DataFrame Filter trade history rows to selected symbols and account events. Returns: Type Description DataFrame Filtered history rows. Source code in mt5cli/history.py 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 def filter_trade_history_frame ( frame : pd . DataFrame , symbols : Sequence [ str ], * , include_account_events : bool , ) -> pd . DataFrame : \"\"\"Filter trade history rows to selected symbols and account events. Returns: Filtered history rows. \"\"\" if \"symbol\" not in frame . columns : return frame symbol_mask = frame [ \"symbol\" ] . isin ( symbols ) if not include_account_events : return frame . loc [ symbol_mask ] . copy () account_event_mask = _history_deals_account_event_mask ( frame ) return frame . loc [ symbol_mask | account_event_mask ] . copy () get_history_deals_account_event_start_datetime \u00b6 get_history_deals_account_event_start_datetime ( conn : Connection , * , fallback_start : datetime ) -> datetime Return the next update start for account-level history_deals rows. Source code in mt5cli/history.py 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 def get_history_deals_account_event_start_datetime ( conn : sqlite3 . Connection , * , fallback_start : datetime , ) -> datetime : \"\"\"Return the next update start for account-level history_deals rows.\"\"\" table = Dataset . history_deals . table_name columns = get_table_columns ( conn , table ) if \"time\" not in columns : return fallback_start if \"type\" in columns : where_clause = f \"type NOT IN { _TRADE_DEAL_TYPES_SQL } \" elif \"symbol\" in columns : where_clause = \"symbol IS NULL OR symbol = ''\" else : return fallback_start row = conn . execute ( f \"SELECT MAX(time) FROM { table } WHERE { where_clause } \" , # noqa: S608 ) . fetchone () parsed = parse_sqlite_timestamp ( row [ 0 ] if row else None ) return parsed if parsed is not None else fallback_start get_incremental_start_datetime \u00b6 get_incremental_start_datetime ( conn : Connection , dataset : Dataset , * , symbol : str , timeframe : int | None , fallback_start : datetime , ) -> datetime Return the next update start datetime from existing MAX(time). Source code in mt5cli/history.py 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 def get_incremental_start_datetime ( conn : sqlite3 . Connection , dataset : Dataset , * , symbol : str , timeframe : int | None , fallback_start : datetime , ) -> datetime : \"\"\"Return the next update start datetime from existing MAX(time).\"\"\" timeframes = [ timeframe ] if timeframe is not None else None starts = load_incremental_start_datetimes ( conn , dataset , symbols = [ symbol ], timeframes = timeframes , fallback_start = fallback_start , ) return starts [ symbol , timeframe ] get_table_columns \u00b6 get_table_columns ( conn : Connection , table : str ) -> set [ str ] Return existing SQLite columns for a table. Source code in mt5cli/history.py 838 839 840 841 842 def get_table_columns ( conn : sqlite3 . Connection , table : str ) -> set [ str ]: \"\"\"Return existing SQLite columns for a table.\"\"\" quoted_table = quote_sqlite_identifier ( table ) rows = conn . execute ( f \"PRAGMA table_info( { quoted_table } )\" ) . fetchall () return { str ( row [ 1 ]) for row in rows } load_incremental_start_datetimes \u00b6 load_incremental_start_datetimes ( conn : Connection , dataset : Dataset , * , symbols : Sequence [ str ], timeframes : Sequence [ int ] | None = None , fallback_start : datetime , ) -> dict [ tuple [ str , int | None ], datetime ] Return next update start datetimes keyed by symbol and optional timeframe. Source code in mt5cli/history.py 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 def load_incremental_start_datetimes ( conn : sqlite3 . Connection , dataset : Dataset , * , symbols : Sequence [ str ], timeframes : Sequence [ int ] | None = None , fallback_start : datetime , ) -> dict [ tuple [ str , int | None ], datetime ]: \"\"\"Return next update start datetimes keyed by symbol and optional timeframe.\"\"\" table = dataset . table_name columns = get_table_columns ( conn , table ) if dataset is Dataset . rates and columns : _validate_rates_schema ( columns ) if \"time\" not in columns : if dataset is Dataset . rates and timeframes is not None : return { ( symbol , timeframe ): fallback_start for symbol in symbols for timeframe in timeframes } return {( symbol , None ): fallback_start for symbol in symbols } parsed_by_key : dict [ tuple [ str , int | None ], datetime ] = {} if ( dataset is Dataset . rates and timeframes is not None and { \"symbol\" , \"timeframe\" } . issubset ( columns ) ): symbol_placeholders = \", \" . join ( \"?\" for _ in symbols ) timeframe_placeholders = \", \" . join ( \"?\" for _ in timeframes ) grouped_rates_query = ( \"SELECT symbol, timeframe, MAX(time) FROM \" # noqa: S608 f \" { table } WHERE symbol IN ( { symbol_placeholders } )\" f \" AND timeframe IN ( { timeframe_placeholders } )\" \" GROUP BY symbol, timeframe\" ) rows = conn . execute ( grouped_rates_query , [ * symbols , * timeframes ], ) . fetchall () for row_symbol , row_timeframe , max_time in rows : parsed = parse_sqlite_timestamp ( max_time ) if parsed is not None : parsed_by_key [ str ( row_symbol ), int ( row_timeframe )] = parsed return { ( symbol , timeframe ): parsed_by_key . get ( ( symbol , timeframe ), fallback_start , ) for symbol in symbols for timeframe in timeframes } if \"symbol\" in columns : symbol_placeholders = \", \" . join ( \"?\" for _ in symbols ) rows = conn . execute ( f \"SELECT symbol, MAX(time) FROM { table } \" # noqa: S608 f \" WHERE symbol IN ( { symbol_placeholders } ) GROUP BY symbol\" , list ( symbols ), ) . fetchall () for row_symbol , max_time in rows : parsed = parse_sqlite_timestamp ( max_time ) if parsed is not None : parsed_by_key [ str ( row_symbol ), None ] = parsed return { ( symbol , None ): parsed_by_key . get (( symbol , None ), fallback_start ) for symbol in symbols } row = conn . execute ( f \"SELECT MAX(time) FROM { table } \" ) . fetchone () # noqa: S608 parsed = parse_sqlite_timestamp ( row [ 0 ] if row else None ) shared_start = parsed if parsed is not None else fallback_start return {( symbol , None ): shared_start for symbol in symbols } load_rate_data \u00b6 load_rate_data ( conn_or_path : SqliteConnOrPath , table : str , count : int | None = None , ) -> DataFrame Load rate-like data from a SQLite database path or connection. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath SQLite database path or open connection. required table str Source table or view name. required count int | None Optional number of most recent rows to load. None Returns: Type Description DataFrame DataFrame indexed by ascending time . Source code in mt5cli/history.py 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 def load_rate_data ( conn_or_path : SqliteConnOrPath , table : str , count : int | None = None , ) -> pd . DataFrame : \"\"\"Load rate-like data from a SQLite database path or connection. Args: conn_or_path: SQLite database path or open connection. table: Source table or view name. count: Optional number of most recent rows to load. Returns: DataFrame indexed by ascending ``time``. \"\"\" conn , should_close = _open_existing_sqlite_database ( conn_or_path ) try : return load_rate_data_from_connection ( conn , table , count = count ) finally : if should_close : conn . close () load_rate_data_from_connection \u00b6 load_rate_data_from_connection ( connection : Connection , table : str , count : int | None = None , ) -> DataFrame Load rate-like data from a SQLite table or view. Parameters: Name Type Description Default connection Connection Open SQLite connection. required table str Source table or view name. required count int | None Optional number of most recent rows to load. None Returns: Type Description DataFrame DataFrame indexed by ascending time . Raises: Type Description ValueError If inputs, schema, timestamps are invalid, or the table or view contains no rows. Source code in mt5cli/history.py 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 def load_rate_data_from_connection ( connection : sqlite3 . Connection , table : str , count : int | None = None , ) -> pd . DataFrame : \"\"\"Load rate-like data from a SQLite table or view. Args: connection: Open SQLite connection. table: Source table or view name. count: Optional number of most recent rows to load. Returns: DataFrame indexed by ascending ``time``. Raises: ValueError: If inputs, schema, timestamps are invalid, or the table or view contains no rows. \"\"\" table_name = _validate_rate_load_request ( table , count ) columns = get_table_columns ( connection , table_name ) _ensure_rate_columns ( columns , table_name ) quoted_table = quote_sqlite_identifier ( table_name ) if count is None : frame = cast ( \"pd.DataFrame\" , pd . read_sql_query ( # type: ignore[reportUnknownMemberType] f \"SELECT * FROM { quoted_table } ORDER BY time ASC\" , # noqa: S608 connection , ), ) else : frame = cast ( \"pd.DataFrame\" , pd . read_sql_query ( # type: ignore[reportUnknownMemberType] f \"SELECT * FROM { quoted_table } ORDER BY time DESC LIMIT ?\" , # noqa: S608 connection , params = ( count ,), ), ) if frame . empty : msg = f \"SQLite table or view { table_name !r} contains no rows.\" raise ValueError ( msg ) return _parse_rate_time_index ( frame , table_name ) load_rate_series_by_granularity \u00b6 load_rate_series_by_granularity ( conn_or_path : SqliteConnOrPath , symbols : Sequence [ str ], granularities : Sequence [ int | str ], count : int , * , explicit_tables : Sequence [ str ] | None = None , allow_missing_symbol : bool = False , ) -> dict [ tuple [ str | None , str ], DataFrame ] Load rate series keyed by symbol and string granularity name. Builds targets with :func: build_rate_targets and loads them with :func: load_rate_series_from_sqlite , then rekeys the result by granularity name (for example M1 ) instead of the integer timeframe to reduce downstream boilerplate. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath SQLite database path or open connection. required symbols Sequence [ str ] MT5 symbol names. May be empty when allow_missing_symbol . required granularities Sequence [ int | str ] MT5 timeframes as integers or names (for example M1 ). required count int Number of most recent rows to load per series. required explicit_tables Sequence [ str ] | None Optional explicit table or view names matching the built targets in row-major order. Required when symbols are omitted. None allow_missing_symbol bool When True and symbols is empty, build targets with symbol=None for each granularity instead of raising. False Returns: Type Description dict [ tuple [ str | None, str ], DataFrame ] Mapping keyed by (symbol | None, granularity_name) to each rate dict [ tuple [ str | None, str ], DataFrame ] DataFrame. Propagates ValueError (via :func: build_rate_targets and dict [ tuple [ str | None, str ], DataFrame ] func: load_rate_series_from_sqlite ) when inputs are empty or invalid, dict [ tuple [ str | None, str ], DataFrame ] table resolution fails, or duplicate targets are present. Source code in mt5cli/history.py 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 def load_rate_series_by_granularity ( conn_or_path : SqliteConnOrPath , symbols : Sequence [ str ], granularities : Sequence [ int | str ], count : int , * , explicit_tables : Sequence [ str ] | None = None , allow_missing_symbol : bool = False , ) -> dict [ tuple [ str | None , str ], pd . DataFrame ]: \"\"\"Load rate series keyed by symbol and string granularity name. Builds targets with :func:`build_rate_targets` and loads them with :func:`load_rate_series_from_sqlite`, then rekeys the result by granularity name (for example ``M1``) instead of the integer timeframe to reduce downstream boilerplate. Args: conn_or_path: SQLite database path or open connection. symbols: MT5 symbol names. May be empty when ``allow_missing_symbol``. granularities: MT5 timeframes as integers or names (for example ``M1``). count: Number of most recent rows to load per series. explicit_tables: Optional explicit table or view names matching the built targets in row-major order. Required when symbols are omitted. allow_missing_symbol: When True and ``symbols`` is empty, build targets with ``symbol=None`` for each granularity instead of raising. Returns: Mapping keyed by ``(symbol | None, granularity_name)`` to each rate DataFrame. Propagates ``ValueError`` (via :func:`build_rate_targets` and :func:`load_rate_series_from_sqlite`) when inputs are empty or invalid, table resolution fails, or duplicate targets are present. \"\"\" targets = build_rate_targets ( symbols , granularities , allow_missing_symbol = allow_missing_symbol , ) series = load_rate_series_from_sqlite ( conn_or_path , targets , count , explicit_tables = explicit_tables , ) return { ( symbol , resolve_granularity_name ( timeframe )): frame for ( symbol , timeframe ), frame in series . items () } load_rate_series_from_sqlite \u00b6 load_rate_series_from_sqlite ( conn_or_path : SqliteConnOrPath , targets : None = None , count : int | None = None , explicit_tables : None = None , * , table : str , ) -> DataFrame load_rate_series_from_sqlite ( conn_or_path : SqliteConnOrPath , targets : None = None , count : int | None = None , explicit_tables : Sequence [ str ] | None = None , * , table : None = None , ) -> dict [ tuple [ str | None , int ], DataFrame ] load_rate_series_from_sqlite ( conn_or_path : SqliteConnOrPath , targets : Sequence [ RateTarget ], count : int , explicit_tables : Sequence [ str ] | None = None , * , table : None = None , ) -> dict [ tuple [ str | None , int ], DataFrame ] load_rate_series_from_sqlite ( conn_or_path : SqliteConnOrPath , targets : Sequence [ RateTarget ] | None = None , count : int | None = None , explicit_tables : Sequence [ str ] | None = None , * , table : str | None = None , ) -> dict [ tuple [ str | None , int ], DataFrame ] | DataFrame Load one table/view or multiple rate series from a SQLite database. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath SQLite database path or open connection. required targets Sequence [ RateTarget ] | None Rate targets to load. Each (symbol, timeframe_int) pair must be unique. Omit when loading a single explicit table . None count int | None Optional number of most recent rows to load per series. None explicit_tables Sequence [ str ] | None Optional explicit table or view names matching targets. When omitted, managed rate_* compatibility views must already exist in the database. None table str | None Optional single table or view name to load directly. None Returns: Type Description dict [ tuple [ str | None, int ], DataFrame ] | DataFrame A DataFrame when table is provided, otherwise a mapping keyed by dict [ tuple [ str | None, int ], DataFrame ] | DataFrame (symbol, timeframe_int) to each rate DataFrame. Raises: Type Description ValueError If count is not positive, targets are empty, duplicate (symbol, timeframe_int) pairs are present, or table resolution fails. Source code in mt5cli/history.py 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 def load_rate_series_from_sqlite ( conn_or_path : SqliteConnOrPath , targets : Sequence [ RateTarget ] | None = None , count : int | None = None , explicit_tables : Sequence [ str ] | None = None , * , table : str | None = None , ) -> dict [ tuple [ str | None , int ], pd . DataFrame ] | pd . DataFrame : \"\"\"Load one table/view or multiple rate series from a SQLite database. Args: conn_or_path: SQLite database path or open connection. targets: Rate targets to load. Each ``(symbol, timeframe_int)`` pair must be unique. Omit when loading a single explicit ``table``. count: Optional number of most recent rows to load per series. explicit_tables: Optional explicit table or view names matching targets. When omitted, managed ``rate_*`` compatibility views must already exist in the database. table: Optional single table or view name to load directly. Returns: A DataFrame when ``table`` is provided, otherwise a mapping keyed by ``(symbol, timeframe_int)`` to each rate DataFrame. Raises: ValueError: If ``count`` is not positive, targets are empty, duplicate ``(symbol, timeframe_int)`` pairs are present, or table resolution fails. \"\"\" if table is not None : return load_rate_data ( conn_or_path , table , count = count ) if count is None or count <= 0 : msg = \"count must be positive.\" raise ValueError ( msg ) if targets is None : msg = \"targets are required when table is not provided.\" raise ValueError ( msg ) target_list = list ( targets ) if not target_list : msg = \"At least one rate target is required.\" raise ValueError ( msg ) if explicit_tables is None and any ( target . symbol is None for target in target_list ): msg = ( \"Cannot resolve a rate table for a target without a symbol; \" \"provide explicit_tables.\" ) raise ValueError ( msg ) seen_keys : set [ tuple [ str | None , int ]] = set () for target in target_list : key = ( target . symbol , target . timeframe_int ) if key in seen_keys : symbol_repr = repr ( target . symbol ) msg = f \"Duplicate rate target: ( { symbol_repr } , { target . timeframe_int } )\" raise ValueError ( msg ) seen_keys . add ( key ) tables = ( resolve_rate_tables ( None , target_list , explicit_tables ) if explicit_tables is not None else None ) conn , should_close = _open_existing_sqlite_database ( conn_or_path ) try : resolved_tables = tables or resolve_rate_tables ( conn , target_list , require_existing = True , ) return { ( target . symbol , target . timeframe_int ): load_rate_data_from_connection ( conn , table , count = count , ) for target , table in zip ( target_list , resolved_tables , strict = True ) } finally : if should_close : conn . close () parse_sqlite_timestamp \u00b6 parse_sqlite_timestamp ( value : object ) -> datetime | None Parse a SQLite history timestamp value. Returns: Type Description datetime | None Parsed timezone-aware datetime, or None when parsing fails. Source code in mt5cli/history.py 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 def parse_sqlite_timestamp ( value : object ) -> datetime | None : \"\"\"Parse a SQLite history timestamp value. Returns: Parsed timezone-aware datetime, or None when parsing fails. \"\"\" if value is None : return None if isinstance ( value , datetime ): return value if value . tzinfo is not None else value . replace ( tzinfo = UTC ) if isinstance ( value , int | float ): return datetime . fromtimestamp ( float ( value ), tz = UTC ) if isinstance ( value , str ): return _parse_string_sqlite_timestamp ( value ) logger . warning ( \"Ignoring unsupported history timestamp type: %s \" , type ( value )) return None quote_sqlite_identifier \u00b6 quote_sqlite_identifier ( identifier : str ) -> str Return a safely quoted SQLite identifier using double quotes. Source code in mt5cli/history.py 56 57 58 def quote_sqlite_identifier ( identifier : str ) -> str : \"\"\"Return a safely quoted SQLite identifier using double quotes.\"\"\" return '\"' + identifier . replace ( '\"' , '\"\"' ) + '\"' record_written_columns \u00b6 record_written_columns ( written_columns : dict [ Dataset , set [ str ]], dataset : Dataset , frame : DataFrame , ) -> None Remember columns for datasets written during collection. Source code in mt5cli/history.py 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 def record_written_columns ( written_columns : dict [ Dataset , set [ str ]], dataset : Dataset , frame : pd . DataFrame , ) -> None : \"\"\"Remember columns for datasets written during collection.\"\"\" columns = set ( frame . columns ) if dataset in written_columns : written_columns [ dataset ] . update ( columns ) else : written_columns [ dataset ] = columns resolve_granularity_name \u00b6 resolve_granularity_name ( timeframe : int ) -> str Return a granularity name for a timeframe integer when known. Source code in mt5cli/history.py 101 102 103 104 105 106 107 def resolve_granularity_name ( timeframe : int ) -> str : \"\"\"Return a granularity name for a timeframe integer when known.\"\"\" try : name = _get_timeframe_name ( timeframe ) except ValueError : return str ( timeframe ) return name . removeprefix ( \"TIMEFRAME_\" ) resolve_history_datasets \u00b6 resolve_history_datasets ( datasets : set [ Dataset ] | None , ) -> set [ Dataset ] Resolve configured history datasets. Returns: Type Description set [ Dataset ] All supported datasets when datasets is None, otherwise the set [ Dataset ] configured selection (which may be empty). Source code in mt5cli/history.py 61 62 63 64 65 66 67 68 69 70 def resolve_history_datasets ( datasets : set [ Dataset ] | None ) -> set [ Dataset ]: \"\"\"Resolve configured history datasets. Returns: All supported datasets when ``datasets`` is None, otherwise the configured selection (which may be empty). \"\"\" if datasets is None : return set ( Dataset ) return set ( datasets ) resolve_history_tick_flags \u00b6 resolve_history_tick_flags ( flags : int | str ) -> int Resolve tick copy flags from an integer or name. Returns: Type Description int Integer tick flag value. Source code in mt5cli/history.py 92 93 94 95 96 97 98 def resolve_history_tick_flags ( flags : int | str ) -> int : \"\"\"Resolve tick copy flags from an integer or name. Returns: Integer tick flag value. \"\"\" return parse_tick_flags ( flags ) resolve_history_timeframes \u00b6 resolve_history_timeframes ( timeframes : Sequence [ int | str ] | None , ) -> list [ int ] Resolve rate timeframes, deduplicating aliases for the same integer. Returns: Type Description list [ int ] Ordered list of unique timeframe integers. Source code in mt5cli/history.py 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 def resolve_history_timeframes ( timeframes : Sequence [ int | str ] | None , ) -> list [ int ]: \"\"\"Resolve rate timeframes, deduplicating aliases for the same integer. Returns: Ordered list of unique timeframe integers. \"\"\" raw = timeframes if timeframes is not None else DEFAULT_HISTORY_TIMEFRAMES seen : set [ int ] = set () resolved : list [ int ] = [] for value in raw : tf = parse_timeframe ( value ) if tf not in seen : seen . add ( tf ) resolved . append ( tf ) return resolved resolve_rate_table_name \u00b6 resolve_rate_table_name ( symbol : str , granularity : str ) -> str Return the canonical normalized SQLite rate table name. The normalized history table stores all symbols and timeframes in rates ; use :func: resolve_rate_view_name for per-symbol compatibility view names. Returns: Type Description str Canonical normalized rates table name. Raises: Type Description ValueError If symbol or granularity is invalid. Source code in mt5cli/history.py 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 def resolve_rate_table_name ( symbol : str , granularity : str ) -> str : \"\"\"Return the canonical normalized SQLite rate table name. The normalized history table stores all symbols and timeframes in ``rates``; use :func:`resolve_rate_view_name` for per-symbol compatibility view names. Returns: Canonical normalized rates table name. Raises: ValueError: If ``symbol`` or ``granularity`` is invalid. \"\"\" parse_timeframe ( granularity ) if not symbol . strip (): msg = \"symbol must not be empty.\" raise ValueError ( msg ) return Dataset . rates . table_name resolve_rate_tables \u00b6 resolve_rate_tables ( conn_or_path : SqliteConnOrPath | None , targets : Sequence [ RateTarget ], explicit_tables : Sequence [ str ] | None = None , * , require_existing : bool = False , ) -> list [ str ] Resolve SQLite table or view names for rate targets. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath | None SQLite database path or open connection. May be None when explicit_tables is provided, or when require_existing is False and deterministic default view names are sufficient. required targets Sequence [ RateTarget ] Rate targets to resolve. required explicit_tables Sequence [ str ] | None Optional explicit table or view names. When provided, they are used as-is and must match the number of targets. None require_existing bool When True, require the database and managed views to exist for each symbol target. Ignored when explicit_tables is provided. False Returns: Type Description list [ str ] Table or view names aligned with targets . Raises: Type Description ValueError If targets is empty, explicit_tables length does not match the target count, a target without a symbol is resolved without an explicit table, or require_existing is True and the database or a managed view is missing. Source code in mt5cli/history.py 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 def resolve_rate_tables ( conn_or_path : SqliteConnOrPath | None , targets : Sequence [ RateTarget ], explicit_tables : Sequence [ str ] | None = None , * , require_existing : bool = False , ) -> list [ str ]: \"\"\"Resolve SQLite table or view names for rate targets. Args: conn_or_path: SQLite database path or open connection. May be None when ``explicit_tables`` is provided, or when ``require_existing`` is False and deterministic default view names are sufficient. targets: Rate targets to resolve. explicit_tables: Optional explicit table or view names. When provided, they are used as-is and must match the number of targets. require_existing: When True, require the database and managed views to exist for each symbol target. Ignored when ``explicit_tables`` is provided. Returns: Table or view names aligned with ``targets``. Raises: ValueError: If ``targets`` is empty, ``explicit_tables`` length does not match the target count, a target without a symbol is resolved without an explicit table, or ``require_existing`` is True and the database or a managed view is missing. \"\"\" target_list = list ( targets ) if not target_list : msg = \"At least one rate target is required.\" raise ValueError ( msg ) if explicit_tables is not None : tables = list ( explicit_tables ) if len ( tables ) != len ( target_list ): msg = ( f \"Expected { len ( target_list ) } explicit table(s) \" f \"to match the targets, got { len ( tables ) } .\" ) raise ValueError ( msg ) return tables if any ( target . symbol is None for target in target_list ): msg = ( \"Cannot resolve a rate table for a target without a symbol; \" \"provide explicit_tables.\" ) raise ValueError ( msg ) conn , should_close = _open_history_connection ( conn_or_path ) try : if conn is None : if require_existing : path = ( conn_or_path if isinstance ( conn_or_path , ( Path , str )) else \"database\" ) msg = f \"SQLite database not found: { path } \" raise ValueError ( msg ) timeframe_counts = None existing_views : set [ str ] = set () else : timeframe_counts = _load_rates_timeframe_counts ( conn ) existing_views = _load_existing_rate_views ( conn ) resolved : list [ str ] = [] for target in target_list : symbol = cast ( \"str\" , target . symbol ) timeframe = target . timeframe_int resolved . append ( _resolve_rate_view_name_from_context ( symbol = symbol , timeframe = timeframe , granularity_name = resolve_granularity_name ( timeframe ), timeframe_counts = timeframe_counts , existing_views = existing_views , require_existing = require_existing , ), ) return resolved finally : if should_close and conn is not None : conn . close () resolve_rate_view_name \u00b6 resolve_rate_view_name ( conn_or_path : SqliteConnOrPath | None , symbol : str , granularity : str , * , require_existing : bool = False , ) -> str Resolve the mt5cli-managed rate compatibility view name. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath | None SQLite database path or open connection. When None or a non-existing path and require_existing is False, the deterministic default view name is returned without creating a database file. required symbol str Symbol stored in the normalized rates table. required granularity str Timeframe name (for example M1 ) or integer string. required require_existing bool When True, require the database and a managed view to exist. False Returns: Type Description str View name such as rate_EURUSD__1 or rate_EURUSD__M1_1 . Raises: Type Description ValueError If require_existing is True and the database or view is missing. Source code in mt5cli/history.py 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 def resolve_rate_view_name ( conn_or_path : SqliteConnOrPath | None , symbol : str , granularity : str , * , require_existing : bool = False , ) -> str : \"\"\"Resolve the mt5cli-managed rate compatibility view name. Args: conn_or_path: SQLite database path or open connection. When None or a non-existing path and ``require_existing`` is False, the deterministic default view name is returned without creating a database file. symbol: Symbol stored in the normalized ``rates`` table. granularity: Timeframe name (for example ``M1``) or integer string. require_existing: When True, require the database and a managed view to exist. Returns: View name such as ``rate_EURUSD__1`` or ``rate_EURUSD__M1_1``. Raises: ValueError: If ``require_existing`` is True and the database or view is missing. \"\"\" timeframe = parse_timeframe ( granularity ) granularity_name = resolve_granularity_name ( timeframe ) conn , should_close = _open_history_connection ( conn_or_path ) try : if conn is None : if require_existing : path = ( conn_or_path if isinstance ( conn_or_path , ( Path , str )) else \"database\" ) msg = f \"SQLite database not found: { path } \" raise ValueError ( msg ) return build_rate_view_name ( symbol = symbol , granularity = granularity_name , granularity_count = 1 , timeframe = timeframe , ) return _resolve_rate_view_name_from_context ( symbol = symbol , timeframe = timeframe , granularity_name = granularity_name , timeframe_counts = _load_rates_timeframe_counts ( conn ), existing_views = _load_existing_rate_views ( conn ), require_existing = require_existing , ) finally : if should_close and conn is not None : conn . close () resolve_rate_view_names \u00b6 resolve_rate_view_names ( conn_or_path : SqliteConnOrPath | None , symbols : Sequence [ str ], granularities : Sequence [ str ], * , require_existing : bool = False , ) -> list [ str ] Resolve rate compatibility view names for symbol and granularity pairs. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath | None SQLite database path or open connection. When None or a non-existing path and require_existing is False, deterministic default view names are returned without creating a database file. required symbols Sequence [ str ] Symbols stored in the normalized rates table. required granularities Sequence [ str ] Timeframe names (for example M1 ) or integer strings. required require_existing bool When True, require the database and managed views to exist. False Returns: Type Description list [ str ] View names in row-major order: every granularity for the first list [ str ] symbol, then every granularity for the next symbol, and so on. Source code in mt5cli/history.py 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 def resolve_rate_view_names ( conn_or_path : SqliteConnOrPath | None , symbols : Sequence [ str ], granularities : Sequence [ str ], * , require_existing : bool = False , ) -> list [ str ]: \"\"\"Resolve rate compatibility view names for symbol and granularity pairs. Args: conn_or_path: SQLite database path or open connection. When None or a non-existing path and ``require_existing`` is False, deterministic default view names are returned without creating a database file. symbols: Symbols stored in the normalized ``rates`` table. granularities: Timeframe names (for example ``M1``) or integer strings. require_existing: When True, require the database and managed views to exist. Returns: View names in row-major order: every ``granularity`` for the first symbol, then every granularity for the next symbol, and so on. \"\"\" conn , should_close = _open_history_connection ( conn_or_path ) try : if conn is None : return [ resolve_rate_view_name ( conn_or_path , symbol , granularity , require_existing = require_existing , ) for symbol in symbols for granularity in granularities ] timeframe_counts = _load_rates_timeframe_counts ( conn ) existing_views = _load_existing_rate_views ( conn ) resolved : list [ str ] = [] for symbol in symbols : for granularity in granularities : timeframe = parse_timeframe ( granularity ) resolved . append ( _resolve_rate_view_name_from_context ( symbol = symbol , timeframe = timeframe , granularity_name = resolve_granularity_name ( timeframe ), timeframe_counts = timeframe_counts , existing_views = existing_views , require_existing = require_existing , ), ) return resolved finally : if should_close and conn is not None : conn . close () write_collected_datasets \u00b6 write_collected_datasets ( conn : Connection , client : Mt5DataClient , symbols : Sequence [ str ], datasets : set [ Dataset ], timeframe : int , flags : int , date_from : datetime , date_to : datetime , if_exists : IfExists , ) -> tuple [ set [ Dataset ], dict [ Dataset , set [ str ]]] Collect selected datasets and stream each symbol frame into SQLite. Returns: Type Description tuple [ set [ Dataset ], dict [ Dataset , set [ str ]]] Written datasets and their columns. Source code in mt5cli/history.py 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 def write_collected_datasets ( conn : sqlite3 . Connection , client : Mt5DataClient , symbols : Sequence [ str ], datasets : set [ Dataset ], timeframe : int , flags : int , date_from : datetime , date_to : datetime , if_exists : IfExists , ) -> tuple [ set [ Dataset ], dict [ Dataset , set [ str ]]]: \"\"\"Collect selected datasets and stream each symbol frame into SQLite. Returns: Written datasets and their columns. \"\"\" written_columns : dict [ Dataset , set [ str ]] = {} written_tables : set [ Dataset ] = set () if Dataset . rates in datasets and write_rates_dataset ( conn , client , symbols , timeframe , date_from , date_to , if_exists , written_columns , ): written_tables . add ( Dataset . rates ) if Dataset . ticks in datasets and write_ticks_dataset ( conn , client , symbols , flags , date_from , date_to , if_exists , written_columns , ): written_tables . add ( Dataset . ticks ) if Dataset . history_orders in datasets and write_history_dataset ( conn , client . history_orders_get_as_df , Dataset . history_orders , symbols , date_from , date_to , if_exists , written_columns , include_account_events = False , ): written_tables . add ( Dataset . history_orders ) if Dataset . history_deals in datasets and write_history_dataset ( conn , client . history_deals_get_as_df , Dataset . history_deals , symbols , date_from , date_to , if_exists , written_columns , include_account_events = False , ): written_tables . add ( Dataset . history_deals ) return written_tables , written_columns write_history_dataset \u00b6 write_history_dataset ( conn : Connection , fetch : Callable [ ... , DataFrame ], dataset : Dataset , symbols : Sequence [ str ], date_from : datetime , date_to : datetime , if_exists : IfExists , written_columns : dict [ Dataset , set [ str ]], * , include_account_events : bool = False , ) -> bool Stream a history dataset into SQLite. Returns: Type Description bool True if the target table was written. Source code in mt5cli/history.py 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 def write_history_dataset ( conn : sqlite3 . Connection , fetch : Callable [ ... , pd . DataFrame ], dataset : Dataset , symbols : Sequence [ str ], date_from : datetime , date_to : datetime , if_exists : IfExists , written_columns : dict [ Dataset , set [ str ]], * , include_account_events : bool = False , ) -> bool : \"\"\"Stream a history dataset into SQLite. Returns: True if the target table was written. \"\"\" table_exists = False if include_account_events : frame = filter_trade_history_frame ( fetch ( date_from = date_from , date_to = date_to ), symbols , include_account_events = True , ) return write_streamed_frame ( conn , frame , dataset , table_exists , if_exists , written_columns , ) def _fetch_history_frame ( sym : str ) -> pd . DataFrame : return filter_trade_history_frame ( fetch ( date_from = date_from , date_to = date_to , symbol = sym ), [ sym ], include_account_events = False , ) return _stream_symbol_frames ( conn , symbols , dataset , if_exists , written_columns , _fetch_history_frame , ) write_incremental_datasets \u00b6 write_incremental_datasets ( conn : Connection , client : Mt5DataClient , symbols : Sequence [ str ], selected_datasets : set [ Dataset ], resolved_timeframes : list [ int ], resolved_tick_flags : int , fallback_start : datetime , end_date : datetime , * , deduplicate : bool , create_rate_views : bool , with_views : bool , include_account_events : bool , ) -> tuple [ set [ Dataset ], dict [ Dataset , set [ str ]]] Append selected datasets incrementally and refresh indexes and views. Returns: Type Description tuple [ set [ Dataset ], dict [ Dataset , set [ str ]]] Written datasets and their columns. Source code in mt5cli/history.py 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 def write_incremental_datasets ( # noqa: PLR0913 conn : sqlite3 . Connection , client : Mt5DataClient , symbols : Sequence [ str ], selected_datasets : set [ Dataset ], resolved_timeframes : list [ int ], resolved_tick_flags : int , fallback_start : datetime , end_date : datetime , * , deduplicate : bool , create_rate_views : bool , with_views : bool , include_account_events : bool , ) -> tuple [ set [ Dataset ], dict [ Dataset , set [ str ]]]: \"\"\"Append selected datasets incrementally and refresh indexes and views. Returns: Written datasets and their columns. \"\"\" written_columns : dict [ Dataset , set [ str ]] = {} written_tables : set [ Dataset ] = set () dedup_scopes : dict [ Dataset , list [ DedupScope ]] = {} if Dataset . rates in selected_datasets : _write_incremental_rates ( conn , client , symbols , resolved_timeframes , fallback_start , end_date , written_columns , written_tables , dedup_scopes , ) if Dataset . ticks in selected_datasets : _write_incremental_ticks ( conn , client , symbols , resolved_tick_flags , fallback_start , end_date , written_columns , written_tables , dedup_scopes , ) if Dataset . history_orders in selected_datasets : _write_incremental_history_orders ( conn , client , symbols , fallback_start , end_date , written_columns , written_tables , dedup_scopes , ) if Dataset . history_deals in selected_datasets : _write_incremental_history_deals ( conn , client , symbols , fallback_start , end_date , written_columns , written_tables , dedup_scopes , include_account_events = include_account_events , ) _finalize_incremental_writes ( conn , selected_datasets , written_columns , written_tables , dedup_scopes , deduplicate = deduplicate , create_rate_views = create_rate_views , with_views = with_views , ) return written_tables , written_columns write_rates_dataset \u00b6 write_rates_dataset ( conn : Connection , client : Mt5DataClient , symbols : Sequence [ str ], timeframe : int , date_from : datetime , date_to : datetime , if_exists : IfExists , written_columns : dict [ Dataset , set [ str ]], ) -> bool Stream rates frames into SQLite. Returns: Type Description bool True if the rates table was written. Source code in mt5cli/history.py 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 def write_rates_dataset ( conn : sqlite3 . Connection , client : Mt5DataClient , symbols : Sequence [ str ], timeframe : int , date_from : datetime , date_to : datetime , if_exists : IfExists , written_columns : dict [ Dataset , set [ str ]], ) -> bool : \"\"\"Stream rates frames into SQLite. Returns: True if the rates table was written. \"\"\" def _fetch_rates_frame ( sym : str ) -> pd . DataFrame : frame = client . copy_rates_range_as_df ( symbol = sym , timeframe = timeframe , date_from = date_from , date_to = date_to , ) . drop ( columns = [ \"symbol\" , \"timeframe\" ], errors = \"ignore\" ) if len ( frame . columns ) != 0 : frame . insert ( 0 , \"symbol\" , sym ) frame . insert ( 1 , \"timeframe\" , timeframe ) return frame return _stream_symbol_frames ( conn , symbols , Dataset . rates , if_exists , written_columns , _fetch_rates_frame , ) write_streamed_frame \u00b6 write_streamed_frame ( conn : Connection , frame : DataFrame , dataset : Dataset , table_exists : bool , if_exists : IfExists , written_columns : dict [ Dataset , set [ str ]], ) -> bool Write one streamed dataset frame and track table state. Returns: Type Description bool True if the dataset table exists after this write attempt. Source code in mt5cli/history.py 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 def write_streamed_frame ( conn : sqlite3 . Connection , frame : pd . DataFrame , dataset : Dataset , table_exists : bool , if_exists : IfExists , written_columns : dict [ Dataset , set [ str ]], ) -> bool : \"\"\"Write one streamed dataset frame and track table state. Returns: True if the dataset table exists after this write attempt. \"\"\" write_mode = IfExists . APPEND if table_exists else if_exists if append_dataframe ( conn , frame , dataset . table_name , write_mode ): record_written_columns ( written_columns , dataset , frame ) return True return table_exists write_ticks_dataset \u00b6 write_ticks_dataset ( conn : Connection , client : Mt5DataClient , symbols : Sequence [ str ], flags : int , date_from : datetime , date_to : datetime , if_exists : IfExists , written_columns : dict [ Dataset , set [ str ]], ) -> bool Stream ticks frames into SQLite. Returns: Type Description bool True if the ticks table was written. Source code in mt5cli/history.py 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 def write_ticks_dataset ( conn : sqlite3 . Connection , client : Mt5DataClient , symbols : Sequence [ str ], flags : int , date_from : datetime , date_to : datetime , if_exists : IfExists , written_columns : dict [ Dataset , set [ str ]], ) -> bool : \"\"\"Stream ticks frames into SQLite. Returns: True if the ticks table was written. \"\"\" def _fetch_ticks_frame ( sym : str ) -> pd . DataFrame : frame = client . copy_ticks_range_as_df ( symbol = sym , date_from = date_from , date_to = date_to , flags = flags , ) . drop ( columns = [ \"symbol\" ], errors = \"ignore\" ) if len ( frame . columns ) != 0 : frame . insert ( 0 , \"symbol\" , sym ) return frame return _stream_symbol_frames ( conn , symbols , Dataset . ticks , if_exists , written_columns , _fetch_ticks_frame , ) collect-history schema \u00b6 The collect-history command (and the matching collect_history SDK function) writes selected MT5 datasets into one SQLite database. Each dataset becomes a table; column names and types mirror the pdmt5 DataFrame schema for that export, with two additions: symbol is prepended on every table. timeframe is prepended on rates so appended runs at different bar sizes stay distinguishable. SQLite does not declare foreign keys. Rows are linked logically by symbol , time windows, and (for deals) position_id / order . Duplicate rows are removed on append using dataset-specific keys (for example ticket on history tables, or (symbol, timeframe, time) on rates). Optional views are created when --with-views is set and the history-deals dataset was written. Entity-relationship diagram \u00b6 Sample layout for a full collection with --with-views : erDiagram rates { TEXT symbol \"dedup key\" INTEGER timeframe \"dedup key\" TEXT time \"dedup key\" REAL open REAL high REAL low REAL close INTEGER tick_volume INTEGER spread INTEGER real_volume } ticks { TEXT symbol \"dedup key\" TEXT time \"dedup key\" INTEGER time_msc \"dedup key (preferred)\" REAL bid REAL ask REAL last INTEGER volume INTEGER flags REAL volume_real } history_orders { INTEGER ticket \"dedup key\" TEXT symbol TEXT time INTEGER type INTEGER state REAL volume_initial REAL price_open REAL price_current INTEGER magic } history_deals { INTEGER ticket \"dedup key\" INTEGER order INTEGER position_id \"groups position view\" TEXT symbol TEXT time INTEGER type \"0/1 trade, else cash event\" INTEGER entry \"0 IN, 1 OUT, 2 INOUT, 3 OUT_BY\" REAL volume REAL price REAL profit REAL commission REAL swap REAL fee } cash_events { INTEGER ticket TEXT symbol TEXT time INTEGER type REAL profit } positions_reconstructed { INTEGER position_id TEXT symbol TEXT open_time TEXT close_time INTEGER direction REAL volume_open REAL volume_close REAL volume_reversal REAL open_price REAL close_price REAL total_profit INTEGER reversal_count INTEGER deals_count } rates ||--o{ history_deals : \"symbol (logical)\" ticks ||--o{ history_deals : \"symbol (logical)\" history_orders ||--o{ history_deals : \"order ~ ticket (logical)\" history_deals ||--|| cash_events : \"VIEW: type NOT IN (0,1)\" history_deals ||--o{ positions_reconstructed : \"VIEW: GROUP BY position_id\" Tables and views \u00b6 Object Kind Source Notes rates table copy_rates_range Indexed on (symbol, timeframe, time) when columns exist. ticks table copy_ticks_range Indexed on (symbol, time) when columns exist. history_orders table history_orders_get Fetched per --symbol , then concatenated. history_deals table history_deals_get Fetched per --symbol , then concatenated. Indexed on (position_id, symbol) when present. cash_events view history_deals Non-trade deal types (deposits, balance ops, etc.). Requires type column. positions_reconstructed view history_deals One row per closed position_id ; volume-weighted prices and reversal stats. Column sets can vary with terminal and pdmt5 version. Views are skipped with a warning when required columns are missing. Incremental collection \u00b6 The update_history SDK path uses the same base tables and optional cash_events / positions_reconstructed views. It additionally maintains rate___ compatibility views when create_rate_views=True . Rate view resolution \u00b6 Downstream tools can resolve mt5cli-managed compatibility view names from an existing SQLite history database without creating files or guessing naming schemes: from pathlib import Path from mt5cli.history import resolve_rate_view_name , resolve_rate_view_names # Single symbol and granularity view = resolve_rate_view_name ( Path ( \"history.db\" ), \"EURUSD\" , \"M1\" ) # Batch resolution in row-major order views = resolve_rate_view_names ( Path ( \"history.db\" ), [ \"EURUSD\" , \"GBPUSD\" ], [ \"M1\" , \"H1\" ], ) Resolution rules: Returns rate___ when a symbol stores one timeframe. Returns rate____ when multiple timeframes are stored for the same symbol. When multiple naming candidates apply, prefers an existing managed rate_*__* view from the candidate list. Falls back to single-timeframe naming when the database path is missing or rates metadata is unavailable. Pass require_existing=True to raise ValueError instead of returning a best-guess name when the database or view is missing. Accepts either a SQLite path or an open sqlite3.Connection . Rate data loading \u00b6 The canonical normalized rate table is rates ; compatibility views are named with rate___ for single-timeframe symbols or rate____ when a symbol has multiple stored timeframes. resolve_rate_table_name() returns rates , while resolve_rate_view_name() returns the per-symbol compatibility view name. Use load_rate_data() or load_rate_series_from_sqlite(..., table=...) to load a single table or view from a SQLite path. Use load_rate_series_by_granularity() to load multiple instrument/granularity targets without hard-coding view names: from pathlib import Path from mt5cli import ( load_rate_data , load_rate_series_by_granularity , load_rate_series_from_sqlite , resolve_rate_table_name , ) from mt5cli.history import resolve_rate_view_name view = resolve_rate_view_name ( Path ( \"history.db\" ), \"EURUSD\" , \"M1\" , require_existing = True ) rates = load_rate_data ( Path ( \"history.db\" ), view , count = 1000 ) same_rates = load_rate_series_from_sqlite ( Path ( \"history.db\" ), table = view , count = 1000 ) table = resolve_rate_table_name ( \"EURUSD\" , \"M1\" ) # \"rates\" series = load_rate_series_by_granularity ( Path ( \"history.db\" ), symbols = [ \"EURUSD\" , \"GBPUSD\" ], granularities = [ \"M1\" , \"H1\" ], count = 500 , ) count returns the latest rows while preserving chronological order. Missing tables/views and mismatched explicit_tables lengths raise ValueError with the requested database target in the message. The loader accepts close-based OHLC rate data or tick-like bid/ask data. It validates that time exists, parses timestamps with pandas, and returns a DataFrame indexed by ascending DatetimeIndex named time . Multi-series rate loading \u00b6 For loading many rate series at once, build neutral RateTarget pairs and load them from SQLite in one call. View names are resolved via the same compatibility-view rules, or you can pass explicit_tables to bypass resolution: from pathlib import Path from mt5cli import build_rate_targets , load_rate_series_from_sqlite targets = build_rate_targets ([ \"EURUSD\" , \"GBPUSD\" ], [ \"M1\" , \"H1\" ]) series = load_rate_series_from_sqlite ( Path ( \"history.db\" ), targets , count = 1000 ) frame = series [ \"EURUSD\" , 1 ] # keyed by (symbol, integer timeframe) build_rate_targets() returns RateTarget(symbol, timeframe) pairs in row-major order, normalizing timeframe names such as \"M1\" to their integer values; set allow_missing_symbol=True to address series solely by explicit_tables (targets carry symbol=None ). resolve_rate_tables() maps targets to table or view names and validates that any explicit_tables count matches the target count. Pass require_existing=True to raise ValueError instead of returning a best-guess name when the database or managed view is missing. When explicit_tables is provided, names are returned as-is and require_existing is ignored. load_rate_series_from_sqlite() returns a mapping keyed by (symbol, integer timeframe) . Unless explicit_tables is supplied, it requires existing managed rate_* compatibility views and raises ValueError when they are missing. Duplicate (symbol, timeframe) targets are rejected. load_rate_series_by_granularity() is a thin wrapper that builds the targets, loads the series, and rekeys the result by granularity name to avoid converting integer timeframes downstream: from mt5cli import load_rate_series_by_granularity series = load_rate_series_by_granularity ( \"history.db\" , [ \"EURUSD\" ], [ \"M1\" , \"H1\" ], count = 1000 ) frame = series [ \"EURUSD\" , \"M1\" ] # keyed by (symbol | None, granularity_name)","title":"History Collection (SQLite)"},{"location":"api/history/#history-collection-sqlite","text":"","title":"History Collection (SQLite)"},{"location":"api/history/#mt5cli.history","text":"SQLite storage helpers for the collect-history incremental data pipeline.","title":"history"},{"location":"api/history/#mt5cli.history.DEFAULT_HISTORY_TIMEFRAMES","text":"DEFAULT_HISTORY_TIMEFRAMES : tuple [ str , ... ] = ( TIMEFRAME_NAMES )","title":"DEFAULT_HISTORY_TIMEFRAMES"},{"location":"api/history/#mt5cli.history.SqliteConnOrPath","text":"SqliteConnOrPath = Connection | Path | str","title":"SqliteConnOrPath"},{"location":"api/history/#mt5cli.history.logger","text":"logger = getLogger ( __name__ )","title":"logger"},{"location":"api/history/#mt5cli.history.DedupScope","text":"DedupScope ( where : str , params : tuple [ object , ... ], required_columns : frozenset [ str ], ) Scoped deduplication predicate and the columns it references. Attributes: Name Type Description where str SQL predicate appended to the duplicate-removal query. params tuple [ object , ...] Parameters bound to the scope predicate. required_columns frozenset [ str ] Columns that must be present in the written table for the scope to run.","title":"DedupScope"},{"location":"api/history/#mt5cli.history.DedupScope.params","text":"params : tuple [ object , ... ]","title":"params"},{"location":"api/history/#mt5cli.history.DedupScope.required_columns","text":"required_columns : frozenset [ str ]","title":"required_columns"},{"location":"api/history/#mt5cli.history.DedupScope.where","text":"where : str","title":"where"},{"location":"api/history/#mt5cli.history.RateTarget","text":"RateTarget ( symbol : str | None , timeframe : int | str ) A single rate series identified by symbol and timeframe. Attributes: Name Type Description symbol str | None MT5 symbol name, or None when the rate series is addressed only by an explicit table (for example a custom SQLite view). timeframe int | str MT5 timeframe as an integer or name (for example M1 ).","title":"RateTarget"},{"location":"api/history/#mt5cli.history.RateTarget.symbol","text":"symbol : str | None","title":"symbol"},{"location":"api/history/#mt5cli.history.RateTarget.timeframe","text":"timeframe : int | str","title":"timeframe"},{"location":"api/history/#mt5cli.history.RateTarget.timeframe_int","text":"timeframe_int : int Return the timeframe as its integer MT5 value.","title":"timeframe_int"},{"location":"api/history/#mt5cli.history.RateTarget.__post_init__","text":"__post_init__ () -> None Normalize accepted timeframe aliases to the stored integer value. Source code in mt5cli/history.py 544 545 546 547 def __post_init__ ( self ) -> None : \"\"\"Normalize accepted timeframe aliases to the stored integer value.\"\"\" if not isinstance ( self . timeframe , int ): object . __setattr__ ( self , \"timeframe\" , parse_timeframe ( self . timeframe ))","title":"__post_init__"},{"location":"api/history/#mt5cli.history.append_dataframe","text":"append_dataframe ( conn : Connection , frame : DataFrame , table_name : str , if_exists : IfExists , ) -> bool Append a DataFrame to SQLite when it has a schema. Returns: Type Description bool True if a table was written, False if the frame had no columns. Source code in mt5cli/history.py 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 def append_dataframe ( conn : sqlite3 . Connection , frame : pd . DataFrame , table_name : str , if_exists : IfExists , ) -> bool : \"\"\"Append a DataFrame to SQLite when it has a schema. Returns: True if a table was written, False if the frame had no columns. \"\"\" if len ( frame . columns ) == 0 : logger . warning ( \"Skipping %s : dataset returned no columns\" , table_name ) return False frame . to_sql ( # type: ignore[reportUnknownMemberType] table_name , conn , if_exists = if_exists . value , index = False , chunksize = 50_000 , ) return True","title":"append_dataframe"},{"location":"api/history/#mt5cli.history.augment_written_columns_from_sqlite","text":"augment_written_columns_from_sqlite ( conn : Connection , datasets : set [ Dataset ], written_columns : dict [ Dataset , set [ str ]], ) -> None Add existing table columns to the written column map. Source code in mt5cli/history.py 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 def augment_written_columns_from_sqlite ( conn : sqlite3 . Connection , datasets : set [ Dataset ], written_columns : dict [ Dataset , set [ str ]], ) -> None : \"\"\"Add existing table columns to the written column map.\"\"\" for dataset in datasets : columns = get_table_columns ( conn , dataset . table_name ) if not columns : continue if dataset in written_columns : written_columns [ dataset ] . update ( columns ) else : written_columns [ dataset ] = columns","title":"augment_written_columns_from_sqlite"},{"location":"api/history/#mt5cli.history.build_rate_targets","text":"build_rate_targets ( symbols : Sequence [ str ], timeframes : Sequence [ int | str ], * , allow_missing_symbol : bool = False , ) -> list [ RateTarget ] Build rate targets for every symbol and timeframe combination. Parameters: Name Type Description Default symbols Sequence [ str ] MT5 symbol names. May be empty when allow_missing_symbol . required timeframes Sequence [ int | str ] MT5 timeframes as integers or names (for example M1 ). required allow_missing_symbol bool When True and symbols is empty, build targets with symbol=None for each timeframe instead of raising. False Returns: Type Description list [ RateTarget ] Targets in row-major order: every timeframe for the first symbol, then list [ RateTarget ] every timeframe for the next symbol, and so on. Raises: Type Description ValueError If timeframes is empty, or symbols is empty and allow_missing_symbol is False. Source code in mt5cli/history.py 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 def build_rate_targets ( symbols : Sequence [ str ], timeframes : Sequence [ int | str ], * , allow_missing_symbol : bool = False , ) -> list [ RateTarget ]: \"\"\"Build rate targets for every symbol and timeframe combination. Args: symbols: MT5 symbol names. May be empty when ``allow_missing_symbol``. timeframes: MT5 timeframes as integers or names (for example ``M1``). allow_missing_symbol: When True and ``symbols`` is empty, build targets with ``symbol=None`` for each timeframe instead of raising. Returns: Targets in row-major order: every timeframe for the first symbol, then every timeframe for the next symbol, and so on. Raises: ValueError: If ``timeframes`` is empty, or ``symbols`` is empty and ``allow_missing_symbol`` is False. \"\"\" if not timeframes : msg = \"At least one timeframe is required.\" raise ValueError ( msg ) if not symbols : if not allow_missing_symbol : msg = \"At least one symbol is required.\" raise ValueError ( msg ) return [ RateTarget ( symbol = None , timeframe = tf ) for tf in timeframes ] return [ RateTarget ( symbol = symbol , timeframe = tf ) for symbol in symbols for tf in timeframes ]","title":"build_rate_targets"},{"location":"api/history/#mt5cli.history.build_rate_view_name","text":"build_rate_view_name ( * , symbol : str , granularity : str , granularity_count : int , timeframe : int , ) -> str Return a collision-free offline optimize view name. View names always include the timeframe integer after a __ separator so a symbol such as EURUSD_M1 cannot collide with EURUSD at timeframe M1 . Source code in mt5cli/history.py 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 def build_rate_view_name ( * , symbol : str , granularity : str , granularity_count : int , timeframe : int , ) -> str : \"\"\"Return a collision-free offline optimize view name. View names always include the timeframe integer after a ``__`` separator so a symbol such as ``EURUSD_M1`` cannot collide with ``EURUSD`` at timeframe ``M1``. \"\"\" if granularity_count == 1 : return f \"rate_ { symbol } __ { timeframe } \" return f \"rate_ { symbol } __ { granularity } _ { timeframe } \"","title":"build_rate_view_name"},{"location":"api/history/#mt5cli.history.create_cash_events_view","text":"create_cash_events_view ( conn : Connection , deals_columns : set [ str ] ) -> bool Create the cash_events SQLite view derived from history_deals. Returns: Type Description bool True if the view was created, False if required columns are missing. Source code in mt5cli/history.py 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 def create_cash_events_view ( conn : sqlite3 . Connection , deals_columns : set [ str ], ) -> bool : \"\"\"Create the cash_events SQLite view derived from history_deals. Returns: True if the view was created, False if required columns are missing. \"\"\" if \"type\" not in deals_columns : logger . warning ( \"Skipping cash_events view: history_deals.type is missing\" ) return False conn . execute ( \"DROP VIEW IF EXISTS cash_events\" ) conn . execute ( \"CREATE VIEW cash_events AS\" # noqa: S608 f \" SELECT * FROM history_deals WHERE type NOT IN { _TRADE_DEAL_TYPES_SQL } \" , ) return True","title":"create_cash_events_view"},{"location":"api/history/#mt5cli.history.create_history_indexes","text":"create_history_indexes ( conn : Connection , written_columns : dict [ Dataset , set [ str ]], ) -> None Create useful indexes for collected history tables when present. Source code in mt5cli/history.py 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 def create_history_indexes ( conn : sqlite3 . Connection , written_columns : dict [ Dataset , set [ str ]], ) -> None : \"\"\"Create useful indexes for collected history tables when present.\"\"\" if { \"symbol\" , \"timeframe\" , \"time\" } . issubset ( written_columns . get ( Dataset . rates , set ()), ): conn . execute ( \"CREATE INDEX IF NOT EXISTS idx_rates_symbol_timeframe_time\" \" ON rates(symbol, timeframe, time)\" , ) if { \"symbol\" , \"time\" } . issubset ( written_columns . get ( Dataset . ticks , set ())): conn . execute ( \"CREATE INDEX IF NOT EXISTS idx_ticks_symbol_time ON ticks(symbol, time)\" , ) if { \"position_id\" , \"symbol\" } . issubset ( written_columns . get ( Dataset . history_deals , set ()), ): conn . execute ( \"CREATE INDEX IF NOT EXISTS idx_history_deals_position_symbol\" \" ON history_deals(position_id, symbol)\" , )","title":"create_history_indexes"},{"location":"api/history/#mt5cli.history.create_positions_reconstructed_view","text":"create_positions_reconstructed_view ( conn : Connection , deals_columns : set [ str ] ) -> bool Create the positions_reconstructed SQLite view derived from history_deals. Returns: Type Description bool True if the view was created, False if required columns are missing. Source code in mt5cli/history.py 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 def create_positions_reconstructed_view ( conn : sqlite3 . Connection , deals_columns : set [ str ], ) -> bool : \"\"\"Create the positions_reconstructed SQLite view derived from history_deals. Returns: True if the view was created, False if required columns are missing. \"\"\" if not _POSITIONS_VIEW_REQUIRED_COLUMNS . issubset ( deals_columns ): missing = \", \" . join ( sorted ( _POSITIONS_VIEW_REQUIRED_COLUMNS - deals_columns )) logger . warning ( \"Skipping positions_reconstructed view: history_deals missing columns: %s \" , missing , ) return False conn . execute ( \"DROP VIEW IF EXISTS positions_reconstructed\" ) conn . execute ( \"CREATE VIEW positions_reconstructed AS\" # noqa: S608 \" SELECT\" \" position_id,\" \" symbol,\" \" MIN(CASE WHEN entry = 0 THEN time END) AS open_time,\" \" MAX(CASE WHEN entry IN (1, 2, 3) THEN time END) AS close_time,\" \" MIN(CASE WHEN entry = 0 THEN type END) AS direction,\" \" SUM(CASE WHEN entry = 0 THEN volume ELSE 0 END) AS volume_open,\" \" SUM(CASE WHEN entry IN (1, 2, 3) THEN volume ELSE 0 END) AS volume_close,\" \" SUM(CASE WHEN entry = 2 THEN volume ELSE 0 END) AS volume_reversal,\" \" CASE\" \" WHEN SUM(CASE WHEN entry = 0 THEN volume ELSE 0 END) > 0\" \" THEN SUM(CASE WHEN entry = 0 THEN price * volume ELSE 0 END)\" \" / SUM(CASE WHEN entry = 0 THEN volume ELSE 0 END)\" \" END AS open_price,\" \" CASE\" \" WHEN SUM(CASE WHEN entry IN (1, 2, 3) THEN volume ELSE 0 END) > 0\" \" THEN SUM(CASE WHEN entry IN (1, 2, 3) THEN price * volume ELSE 0 END)\" \" / SUM(CASE WHEN entry IN (1, 2, 3) THEN volume ELSE 0 END)\" \" END AS close_price,\" \" SUM(profit) AS total_profit,\" \" SUM(CASE WHEN entry = 2 THEN 1 ELSE 0 END) AS reversal_count,\" \" COUNT(*) AS deals_count\" \" FROM history_deals\" f \" WHERE type IN { _TRADE_DEAL_TYPES_SQL } AND position_id != 0\" \" GROUP BY position_id, symbol\" \" HAVING SUM(CASE WHEN entry IN (1, 2, 3) THEN 1 ELSE 0 END) > 0\" , ) return True","title":"create_positions_reconstructed_view"},{"location":"api/history/#mt5cli.history.create_rate_compatibility_views","text":"create_rate_compatibility_views ( conn : Connection ) -> None Create rate compatibility views from the normalized rates table. Source code in mt5cli/history.py 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 def create_rate_compatibility_views ( conn : sqlite3 . Connection ) -> None : \"\"\"Create rate compatibility views from the normalized rates table.\"\"\" columns = get_table_columns ( conn , Dataset . rates . table_name ) if not { \"symbol\" , \"timeframe\" , \"time\" } . issubset ( columns ): return drop_rate_compatibility_views ( conn ) select_columns = sorted ( columns - { \"symbol\" , \"timeframe\" }) quoted_columns = \", \" . join ( f '\" { column } \"' for column in select_columns ) rows = conn . execute ( \"SELECT DISTINCT symbol, timeframe FROM rates ORDER BY symbol, timeframe\" , ) . fetchall () timeframes_by_symbol : dict [ str , list [ int ]] = {} for symbol , timeframe in rows : timeframes_by_symbol . setdefault ( str ( symbol ), []) . append ( int ( timeframe )) for symbol , timeframes in timeframes_by_symbol . items (): for timeframe in timeframes : granularity = resolve_granularity_name ( timeframe ) view_name = build_rate_view_name ( symbol = symbol , granularity = granularity , granularity_count = len ( timeframes ), timeframe = timeframe , ) quoted_view_name = quote_sqlite_identifier ( view_name ) escaped_symbol = symbol . replace ( \"'\" , \"''\" ) conn . execute ( f \"CREATE VIEW { quoted_view_name } AS\" # noqa: S608 f \" SELECT { quoted_columns } FROM rates\" f \" WHERE symbol = ' { escaped_symbol } '\" f \" AND timeframe = { timeframe } \" , )","title":"create_rate_compatibility_views"},{"location":"api/history/#mt5cli.history.deduplicate_history_tables","text":"deduplicate_history_tables ( conn : Connection , written_columns : dict [ Dataset , set [ str ]], written_tables : set [ Dataset ], dedup_scopes : Mapping [ Dataset , Sequence [ DedupScope ]] | None = None , ) -> None Deduplicate appended history tables by stable identifiers. Scopes whose required columns are not present in the written table are skipped. If all scopes for a dataset are skipped, the table receives one unscoped deduplication pass instead. Source code in mt5cli/history.py 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 def deduplicate_history_tables ( conn : sqlite3 . Connection , written_columns : dict [ Dataset , set [ str ]], written_tables : set [ Dataset ], dedup_scopes : Mapping [ Dataset , Sequence [ DedupScope ]] | None = None , ) -> None : \"\"\"Deduplicate appended history tables by stable identifiers. Scopes whose required columns are not present in the written table are skipped. If all scopes for a dataset are skipped, the table receives one unscoped deduplication pass instead. \"\"\" cursor = conn . cursor () for dataset in written_tables : columns = written_columns . get ( dataset , set ()) table = dataset . table_name keys = next ( ( candidate for candidate in _HISTORY_DEDUP_KEYS [ dataset ] if set ( candidate ) . issubset ( columns ) ), None , ) if keys is None : logger . warning ( \"Skipping %s deduplication: no supported key columns\" , table , ) continue raw_scopes : Sequence [ DedupScope ] = ( dedup_scopes . get ( dataset , ()) if dedup_scopes else () ) scopes = [ scope for scope in raw_scopes if scope . required_columns <= columns ] if scopes : for scope in scopes : drop_duplicates_in_table ( cursor , table , list ( keys ), keep = \"last\" , scope_where = scope . where , scope_params = scope . params , ) continue drop_duplicates_in_table ( cursor , table , list ( keys ), keep = \"last\" )","title":"deduplicate_history_tables"},{"location":"api/history/#mt5cli.history.drop_duplicates_in_table","text":"drop_duplicates_in_table ( cursor : Cursor , table : str , ids : list [ str ], * , keep : Literal [ \"first\" , \"last\" ] = \"last\" , scope_where : str | None = None , scope_params : tuple [ object , ... ] = (), ) -> None Remove duplicate rows, keeping the first or last ROWID per key group. Raises: Type Description ValueError If the table or column names are invalid. Source code in mt5cli/history.py 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 def drop_duplicates_in_table ( cursor : sqlite3 . Cursor , table : str , ids : list [ str ], * , keep : Literal [ \"first\" , \"last\" ] = \"last\" , scope_where : str | None = None , scope_params : tuple [ object , ... ] = (), ) -> None : \"\"\"Remove duplicate rows, keeping the first or last ROWID per key group. Raises: ValueError: If the table or column names are invalid. \"\"\" if not table . isidentifier (): msg = f \"Invalid table name: { table } \" raise ValueError ( msg ) if invalid := { column for column in ids if not column . isidentifier ()}: msg = f \"Invalid column names: { ', ' . join ( sorted ( invalid )) } \" raise ValueError ( msg ) ids_csv = \", \" . join ( f '\" { column } \"' for column in ids ) rowid_selector = \"MIN\" if keep == \"first\" else \"MAX\" if scope_where : delete_sql = ( f \"DELETE FROM { table } WHERE { scope_where } AND ROWID NOT IN\" # noqa: S608 f \" (SELECT { rowid_selector } (ROWID) FROM { table } WHERE { scope_where } \" f \" GROUP BY { ids_csv } )\" ) cursor . execute ( delete_sql , scope_params + scope_params ) return cursor . execute ( f \"DELETE FROM { table } WHERE ROWID NOT IN\" # noqa: S608 f \" (SELECT { rowid_selector } (ROWID) FROM { table } GROUP BY { ids_csv } )\" , )","title":"drop_duplicates_in_table"},{"location":"api/history/#mt5cli.history.drop_forming_rate_bar","text":"drop_forming_rate_bar ( df_rate : DataFrame ) -> DataFrame Return closed bars from chronologically ordered MT5 rate data. MetaTrader 5 copy_rates_from_pos(start_pos=0) includes the still-forming current bar as the last row. Slice it off so downstream logic only sees completed bars. Empty frames and single-row frames return empty results. Parameters: Name Type Description Default df_rate DataFrame Rate data ordered oldest-to-newest with the forming bar last. required Returns: Type Description DataFrame A new DataFrame with all rows except the last. Index and columns are DataFrame preserved. The input frame is not modified. Source code in mt5cli/history.py 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 def drop_forming_rate_bar ( df_rate : pd . DataFrame ) -> pd . DataFrame : \"\"\"Return closed bars from chronologically ordered MT5 rate data. MetaTrader 5 ``copy_rates_from_pos(start_pos=0)`` includes the still-forming current bar as the last row. Slice it off so downstream logic only sees completed bars. Empty frames and single-row frames return empty results. Args: df_rate: Rate data ordered oldest-to-newest with the forming bar last. Returns: A new DataFrame with all rows except the last. Index and columns are preserved. The input frame is not modified. \"\"\" return df_rate . iloc [: - 1 ] . copy ()","title":"drop_forming_rate_bar"},{"location":"api/history/#mt5cli.history.drop_rate_compatibility_views","text":"drop_rate_compatibility_views ( conn : Connection ) -> None Drop all mt5cli-managed rate_* compatibility views. Source code in mt5cli/history.py 1355 1356 1357 1358 1359 1360 1361 1362 def drop_rate_compatibility_views ( conn : sqlite3 . Connection ) -> None : \"\"\"Drop all mt5cli-managed ``rate_*`` compatibility views.\"\"\" rows = conn . execute ( \"SELECT name FROM sqlite_master WHERE type = 'view' AND name GLOB 'rate_*'\" , ) . fetchall () for ( view_name ,) in rows : quoted_view_name = quote_sqlite_identifier ( str ( view_name )) conn . execute ( f \"DROP VIEW IF EXISTS { quoted_view_name } \" )","title":"drop_rate_compatibility_views"},{"location":"api/history/#mt5cli.history.filter_incremental_history_deals_frame","text":"filter_incremental_history_deals_frame ( frame : DataFrame , symbols : Sequence [ str ], start_by_symbol : dict [ str , datetime ], account_event_start : datetime , ) -> DataFrame Filter incrementally fetched history_deals by symbol and event start times. Returns: Type Description DataFrame Rows for selected symbols at or after each symbol start, plus account DataFrame events at or after account_event_start . Source code in mt5cli/history.py 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 def filter_incremental_history_deals_frame ( frame : pd . DataFrame , symbols : Sequence [ str ], start_by_symbol : dict [ str , datetime ], account_event_start : datetime , ) -> pd . DataFrame : \"\"\"Filter incrementally fetched history_deals by symbol and event start times. Returns: Rows for selected symbols at or after each symbol start, plus account events at or after ``account_event_start``. \"\"\" if frame . empty : return frame . copy () parsed_times = _frame_parsed_times ( frame ) time_valid = parsed_times . notna () account_event_mask = _history_deals_account_event_mask ( frame ) account_keep = account_event_mask & ( parsed_times >= account_event_start ) trade_keep = pd . Series ( data = False , index = frame . index ) if \"symbol\" in frame . columns : for symbol in symbols : trade_keep |= ( ( frame [ \"symbol\" ] == symbol ) & ( parsed_times >= start_by_symbol [ symbol ]) & ~ account_event_mask ) keep = ( account_keep | trade_keep ) & time_valid return frame . loc [ keep ] . copy ()","title":"filter_incremental_history_deals_frame"},{"location":"api/history/#mt5cli.history.filter_trade_history_frame","text":"filter_trade_history_frame ( frame : DataFrame , symbols : Sequence [ str ], * , include_account_events : bool , ) -> DataFrame Filter trade history rows to selected symbols and account events. Returns: Type Description DataFrame Filtered history rows. Source code in mt5cli/history.py 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 def filter_trade_history_frame ( frame : pd . DataFrame , symbols : Sequence [ str ], * , include_account_events : bool , ) -> pd . DataFrame : \"\"\"Filter trade history rows to selected symbols and account events. Returns: Filtered history rows. \"\"\" if \"symbol\" not in frame . columns : return frame symbol_mask = frame [ \"symbol\" ] . isin ( symbols ) if not include_account_events : return frame . loc [ symbol_mask ] . copy () account_event_mask = _history_deals_account_event_mask ( frame ) return frame . loc [ symbol_mask | account_event_mask ] . copy ()","title":"filter_trade_history_frame"},{"location":"api/history/#mt5cli.history.get_history_deals_account_event_start_datetime","text":"get_history_deals_account_event_start_datetime ( conn : Connection , * , fallback_start : datetime ) -> datetime Return the next update start for account-level history_deals rows. Source code in mt5cli/history.py 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 def get_history_deals_account_event_start_datetime ( conn : sqlite3 . Connection , * , fallback_start : datetime , ) -> datetime : \"\"\"Return the next update start for account-level history_deals rows.\"\"\" table = Dataset . history_deals . table_name columns = get_table_columns ( conn , table ) if \"time\" not in columns : return fallback_start if \"type\" in columns : where_clause = f \"type NOT IN { _TRADE_DEAL_TYPES_SQL } \" elif \"symbol\" in columns : where_clause = \"symbol IS NULL OR symbol = ''\" else : return fallback_start row = conn . execute ( f \"SELECT MAX(time) FROM { table } WHERE { where_clause } \" , # noqa: S608 ) . fetchone () parsed = parse_sqlite_timestamp ( row [ 0 ] if row else None ) return parsed if parsed is not None else fallback_start","title":"get_history_deals_account_event_start_datetime"},{"location":"api/history/#mt5cli.history.get_incremental_start_datetime","text":"get_incremental_start_datetime ( conn : Connection , dataset : Dataset , * , symbol : str , timeframe : int | None , fallback_start : datetime , ) -> datetime Return the next update start datetime from existing MAX(time). Source code in mt5cli/history.py 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 def get_incremental_start_datetime ( conn : sqlite3 . Connection , dataset : Dataset , * , symbol : str , timeframe : int | None , fallback_start : datetime , ) -> datetime : \"\"\"Return the next update start datetime from existing MAX(time).\"\"\" timeframes = [ timeframe ] if timeframe is not None else None starts = load_incremental_start_datetimes ( conn , dataset , symbols = [ symbol ], timeframes = timeframes , fallback_start = fallback_start , ) return starts [ symbol , timeframe ]","title":"get_incremental_start_datetime"},{"location":"api/history/#mt5cli.history.get_table_columns","text":"get_table_columns ( conn : Connection , table : str ) -> set [ str ] Return existing SQLite columns for a table. Source code in mt5cli/history.py 838 839 840 841 842 def get_table_columns ( conn : sqlite3 . Connection , table : str ) -> set [ str ]: \"\"\"Return existing SQLite columns for a table.\"\"\" quoted_table = quote_sqlite_identifier ( table ) rows = conn . execute ( f \"PRAGMA table_info( { quoted_table } )\" ) . fetchall () return { str ( row [ 1 ]) for row in rows }","title":"get_table_columns"},{"location":"api/history/#mt5cli.history.load_incremental_start_datetimes","text":"load_incremental_start_datetimes ( conn : Connection , dataset : Dataset , * , symbols : Sequence [ str ], timeframes : Sequence [ int ] | None = None , fallback_start : datetime , ) -> dict [ tuple [ str , int | None ], datetime ] Return next update start datetimes keyed by symbol and optional timeframe. Source code in mt5cli/history.py 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 def load_incremental_start_datetimes ( conn : sqlite3 . Connection , dataset : Dataset , * , symbols : Sequence [ str ], timeframes : Sequence [ int ] | None = None , fallback_start : datetime , ) -> dict [ tuple [ str , int | None ], datetime ]: \"\"\"Return next update start datetimes keyed by symbol and optional timeframe.\"\"\" table = dataset . table_name columns = get_table_columns ( conn , table ) if dataset is Dataset . rates and columns : _validate_rates_schema ( columns ) if \"time\" not in columns : if dataset is Dataset . rates and timeframes is not None : return { ( symbol , timeframe ): fallback_start for symbol in symbols for timeframe in timeframes } return {( symbol , None ): fallback_start for symbol in symbols } parsed_by_key : dict [ tuple [ str , int | None ], datetime ] = {} if ( dataset is Dataset . rates and timeframes is not None and { \"symbol\" , \"timeframe\" } . issubset ( columns ) ): symbol_placeholders = \", \" . join ( \"?\" for _ in symbols ) timeframe_placeholders = \", \" . join ( \"?\" for _ in timeframes ) grouped_rates_query = ( \"SELECT symbol, timeframe, MAX(time) FROM \" # noqa: S608 f \" { table } WHERE symbol IN ( { symbol_placeholders } )\" f \" AND timeframe IN ( { timeframe_placeholders } )\" \" GROUP BY symbol, timeframe\" ) rows = conn . execute ( grouped_rates_query , [ * symbols , * timeframes ], ) . fetchall () for row_symbol , row_timeframe , max_time in rows : parsed = parse_sqlite_timestamp ( max_time ) if parsed is not None : parsed_by_key [ str ( row_symbol ), int ( row_timeframe )] = parsed return { ( symbol , timeframe ): parsed_by_key . get ( ( symbol , timeframe ), fallback_start , ) for symbol in symbols for timeframe in timeframes } if \"symbol\" in columns : symbol_placeholders = \", \" . join ( \"?\" for _ in symbols ) rows = conn . execute ( f \"SELECT symbol, MAX(time) FROM { table } \" # noqa: S608 f \" WHERE symbol IN ( { symbol_placeholders } ) GROUP BY symbol\" , list ( symbols ), ) . fetchall () for row_symbol , max_time in rows : parsed = parse_sqlite_timestamp ( max_time ) if parsed is not None : parsed_by_key [ str ( row_symbol ), None ] = parsed return { ( symbol , None ): parsed_by_key . get (( symbol , None ), fallback_start ) for symbol in symbols } row = conn . execute ( f \"SELECT MAX(time) FROM { table } \" ) . fetchone () # noqa: S608 parsed = parse_sqlite_timestamp ( row [ 0 ] if row else None ) shared_start = parsed if parsed is not None else fallback_start return {( symbol , None ): shared_start for symbol in symbols }","title":"load_incremental_start_datetimes"},{"location":"api/history/#mt5cli.history.load_rate_data","text":"load_rate_data ( conn_or_path : SqliteConnOrPath , table : str , count : int | None = None , ) -> DataFrame Load rate-like data from a SQLite database path or connection. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath SQLite database path or open connection. required table str Source table or view name. required count int | None Optional number of most recent rows to load. None Returns: Type Description DataFrame DataFrame indexed by ascending time . Source code in mt5cli/history.py 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 def load_rate_data ( conn_or_path : SqliteConnOrPath , table : str , count : int | None = None , ) -> pd . DataFrame : \"\"\"Load rate-like data from a SQLite database path or connection. Args: conn_or_path: SQLite database path or open connection. table: Source table or view name. count: Optional number of most recent rows to load. Returns: DataFrame indexed by ascending ``time``. \"\"\" conn , should_close = _open_existing_sqlite_database ( conn_or_path ) try : return load_rate_data_from_connection ( conn , table , count = count ) finally : if should_close : conn . close ()","title":"load_rate_data"},{"location":"api/history/#mt5cli.history.load_rate_data_from_connection","text":"load_rate_data_from_connection ( connection : Connection , table : str , count : int | None = None , ) -> DataFrame Load rate-like data from a SQLite table or view. Parameters: Name Type Description Default connection Connection Open SQLite connection. required table str Source table or view name. required count int | None Optional number of most recent rows to load. None Returns: Type Description DataFrame DataFrame indexed by ascending time . Raises: Type Description ValueError If inputs, schema, timestamps are invalid, or the table or view contains no rows. Source code in mt5cli/history.py 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 def load_rate_data_from_connection ( connection : sqlite3 . Connection , table : str , count : int | None = None , ) -> pd . DataFrame : \"\"\"Load rate-like data from a SQLite table or view. Args: connection: Open SQLite connection. table: Source table or view name. count: Optional number of most recent rows to load. Returns: DataFrame indexed by ascending ``time``. Raises: ValueError: If inputs, schema, timestamps are invalid, or the table or view contains no rows. \"\"\" table_name = _validate_rate_load_request ( table , count ) columns = get_table_columns ( connection , table_name ) _ensure_rate_columns ( columns , table_name ) quoted_table = quote_sqlite_identifier ( table_name ) if count is None : frame = cast ( \"pd.DataFrame\" , pd . read_sql_query ( # type: ignore[reportUnknownMemberType] f \"SELECT * FROM { quoted_table } ORDER BY time ASC\" , # noqa: S608 connection , ), ) else : frame = cast ( \"pd.DataFrame\" , pd . read_sql_query ( # type: ignore[reportUnknownMemberType] f \"SELECT * FROM { quoted_table } ORDER BY time DESC LIMIT ?\" , # noqa: S608 connection , params = ( count ,), ), ) if frame . empty : msg = f \"SQLite table or view { table_name !r} contains no rows.\" raise ValueError ( msg ) return _parse_rate_time_index ( frame , table_name )","title":"load_rate_data_from_connection"},{"location":"api/history/#mt5cli.history.load_rate_series_by_granularity","text":"load_rate_series_by_granularity ( conn_or_path : SqliteConnOrPath , symbols : Sequence [ str ], granularities : Sequence [ int | str ], count : int , * , explicit_tables : Sequence [ str ] | None = None , allow_missing_symbol : bool = False , ) -> dict [ tuple [ str | None , str ], DataFrame ] Load rate series keyed by symbol and string granularity name. Builds targets with :func: build_rate_targets and loads them with :func: load_rate_series_from_sqlite , then rekeys the result by granularity name (for example M1 ) instead of the integer timeframe to reduce downstream boilerplate. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath SQLite database path or open connection. required symbols Sequence [ str ] MT5 symbol names. May be empty when allow_missing_symbol . required granularities Sequence [ int | str ] MT5 timeframes as integers or names (for example M1 ). required count int Number of most recent rows to load per series. required explicit_tables Sequence [ str ] | None Optional explicit table or view names matching the built targets in row-major order. Required when symbols are omitted. None allow_missing_symbol bool When True and symbols is empty, build targets with symbol=None for each granularity instead of raising. False Returns: Type Description dict [ tuple [ str | None, str ], DataFrame ] Mapping keyed by (symbol | None, granularity_name) to each rate dict [ tuple [ str | None, str ], DataFrame ] DataFrame. Propagates ValueError (via :func: build_rate_targets and dict [ tuple [ str | None, str ], DataFrame ] func: load_rate_series_from_sqlite ) when inputs are empty or invalid, dict [ tuple [ str | None, str ], DataFrame ] table resolution fails, or duplicate targets are present. Source code in mt5cli/history.py 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 def load_rate_series_by_granularity ( conn_or_path : SqliteConnOrPath , symbols : Sequence [ str ], granularities : Sequence [ int | str ], count : int , * , explicit_tables : Sequence [ str ] | None = None , allow_missing_symbol : bool = False , ) -> dict [ tuple [ str | None , str ], pd . DataFrame ]: \"\"\"Load rate series keyed by symbol and string granularity name. Builds targets with :func:`build_rate_targets` and loads them with :func:`load_rate_series_from_sqlite`, then rekeys the result by granularity name (for example ``M1``) instead of the integer timeframe to reduce downstream boilerplate. Args: conn_or_path: SQLite database path or open connection. symbols: MT5 symbol names. May be empty when ``allow_missing_symbol``. granularities: MT5 timeframes as integers or names (for example ``M1``). count: Number of most recent rows to load per series. explicit_tables: Optional explicit table or view names matching the built targets in row-major order. Required when symbols are omitted. allow_missing_symbol: When True and ``symbols`` is empty, build targets with ``symbol=None`` for each granularity instead of raising. Returns: Mapping keyed by ``(symbol | None, granularity_name)`` to each rate DataFrame. Propagates ``ValueError`` (via :func:`build_rate_targets` and :func:`load_rate_series_from_sqlite`) when inputs are empty or invalid, table resolution fails, or duplicate targets are present. \"\"\" targets = build_rate_targets ( symbols , granularities , allow_missing_symbol = allow_missing_symbol , ) series = load_rate_series_from_sqlite ( conn_or_path , targets , count , explicit_tables = explicit_tables , ) return { ( symbol , resolve_granularity_name ( timeframe )): frame for ( symbol , timeframe ), frame in series . items () }","title":"load_rate_series_by_granularity"},{"location":"api/history/#mt5cli.history.load_rate_series_from_sqlite","text":"load_rate_series_from_sqlite ( conn_or_path : SqliteConnOrPath , targets : None = None , count : int | None = None , explicit_tables : None = None , * , table : str , ) -> DataFrame load_rate_series_from_sqlite ( conn_or_path : SqliteConnOrPath , targets : None = None , count : int | None = None , explicit_tables : Sequence [ str ] | None = None , * , table : None = None , ) -> dict [ tuple [ str | None , int ], DataFrame ] load_rate_series_from_sqlite ( conn_or_path : SqliteConnOrPath , targets : Sequence [ RateTarget ], count : int , explicit_tables : Sequence [ str ] | None = None , * , table : None = None , ) -> dict [ tuple [ str | None , int ], DataFrame ] load_rate_series_from_sqlite ( conn_or_path : SqliteConnOrPath , targets : Sequence [ RateTarget ] | None = None , count : int | None = None , explicit_tables : Sequence [ str ] | None = None , * , table : str | None = None , ) -> dict [ tuple [ str | None , int ], DataFrame ] | DataFrame Load one table/view or multiple rate series from a SQLite database. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath SQLite database path or open connection. required targets Sequence [ RateTarget ] | None Rate targets to load. Each (symbol, timeframe_int) pair must be unique. Omit when loading a single explicit table . None count int | None Optional number of most recent rows to load per series. None explicit_tables Sequence [ str ] | None Optional explicit table or view names matching targets. When omitted, managed rate_* compatibility views must already exist in the database. None table str | None Optional single table or view name to load directly. None Returns: Type Description dict [ tuple [ str | None, int ], DataFrame ] | DataFrame A DataFrame when table is provided, otherwise a mapping keyed by dict [ tuple [ str | None, int ], DataFrame ] | DataFrame (symbol, timeframe_int) to each rate DataFrame. Raises: Type Description ValueError If count is not positive, targets are empty, duplicate (symbol, timeframe_int) pairs are present, or table resolution fails. Source code in mt5cli/history.py 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 def load_rate_series_from_sqlite ( conn_or_path : SqliteConnOrPath , targets : Sequence [ RateTarget ] | None = None , count : int | None = None , explicit_tables : Sequence [ str ] | None = None , * , table : str | None = None , ) -> dict [ tuple [ str | None , int ], pd . DataFrame ] | pd . DataFrame : \"\"\"Load one table/view or multiple rate series from a SQLite database. Args: conn_or_path: SQLite database path or open connection. targets: Rate targets to load. Each ``(symbol, timeframe_int)`` pair must be unique. Omit when loading a single explicit ``table``. count: Optional number of most recent rows to load per series. explicit_tables: Optional explicit table or view names matching targets. When omitted, managed ``rate_*`` compatibility views must already exist in the database. table: Optional single table or view name to load directly. Returns: A DataFrame when ``table`` is provided, otherwise a mapping keyed by ``(symbol, timeframe_int)`` to each rate DataFrame. Raises: ValueError: If ``count`` is not positive, targets are empty, duplicate ``(symbol, timeframe_int)`` pairs are present, or table resolution fails. \"\"\" if table is not None : return load_rate_data ( conn_or_path , table , count = count ) if count is None or count <= 0 : msg = \"count must be positive.\" raise ValueError ( msg ) if targets is None : msg = \"targets are required when table is not provided.\" raise ValueError ( msg ) target_list = list ( targets ) if not target_list : msg = \"At least one rate target is required.\" raise ValueError ( msg ) if explicit_tables is None and any ( target . symbol is None for target in target_list ): msg = ( \"Cannot resolve a rate table for a target without a symbol; \" \"provide explicit_tables.\" ) raise ValueError ( msg ) seen_keys : set [ tuple [ str | None , int ]] = set () for target in target_list : key = ( target . symbol , target . timeframe_int ) if key in seen_keys : symbol_repr = repr ( target . symbol ) msg = f \"Duplicate rate target: ( { symbol_repr } , { target . timeframe_int } )\" raise ValueError ( msg ) seen_keys . add ( key ) tables = ( resolve_rate_tables ( None , target_list , explicit_tables ) if explicit_tables is not None else None ) conn , should_close = _open_existing_sqlite_database ( conn_or_path ) try : resolved_tables = tables or resolve_rate_tables ( conn , target_list , require_existing = True , ) return { ( target . symbol , target . timeframe_int ): load_rate_data_from_connection ( conn , table , count = count , ) for target , table in zip ( target_list , resolved_tables , strict = True ) } finally : if should_close : conn . close ()","title":"load_rate_series_from_sqlite"},{"location":"api/history/#mt5cli.history.parse_sqlite_timestamp","text":"parse_sqlite_timestamp ( value : object ) -> datetime | None Parse a SQLite history timestamp value. Returns: Type Description datetime | None Parsed timezone-aware datetime, or None when parsing fails. Source code in mt5cli/history.py 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 def parse_sqlite_timestamp ( value : object ) -> datetime | None : \"\"\"Parse a SQLite history timestamp value. Returns: Parsed timezone-aware datetime, or None when parsing fails. \"\"\" if value is None : return None if isinstance ( value , datetime ): return value if value . tzinfo is not None else value . replace ( tzinfo = UTC ) if isinstance ( value , int | float ): return datetime . fromtimestamp ( float ( value ), tz = UTC ) if isinstance ( value , str ): return _parse_string_sqlite_timestamp ( value ) logger . warning ( \"Ignoring unsupported history timestamp type: %s \" , type ( value )) return None","title":"parse_sqlite_timestamp"},{"location":"api/history/#mt5cli.history.quote_sqlite_identifier","text":"quote_sqlite_identifier ( identifier : str ) -> str Return a safely quoted SQLite identifier using double quotes. Source code in mt5cli/history.py 56 57 58 def quote_sqlite_identifier ( identifier : str ) -> str : \"\"\"Return a safely quoted SQLite identifier using double quotes.\"\"\" return '\"' + identifier . replace ( '\"' , '\"\"' ) + '\"'","title":"quote_sqlite_identifier"},{"location":"api/history/#mt5cli.history.record_written_columns","text":"record_written_columns ( written_columns : dict [ Dataset , set [ str ]], dataset : Dataset , frame : DataFrame , ) -> None Remember columns for datasets written during collection. Source code in mt5cli/history.py 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 def record_written_columns ( written_columns : dict [ Dataset , set [ str ]], dataset : Dataset , frame : pd . DataFrame , ) -> None : \"\"\"Remember columns for datasets written during collection.\"\"\" columns = set ( frame . columns ) if dataset in written_columns : written_columns [ dataset ] . update ( columns ) else : written_columns [ dataset ] = columns","title":"record_written_columns"},{"location":"api/history/#mt5cli.history.resolve_granularity_name","text":"resolve_granularity_name ( timeframe : int ) -> str Return a granularity name for a timeframe integer when known. Source code in mt5cli/history.py 101 102 103 104 105 106 107 def resolve_granularity_name ( timeframe : int ) -> str : \"\"\"Return a granularity name for a timeframe integer when known.\"\"\" try : name = _get_timeframe_name ( timeframe ) except ValueError : return str ( timeframe ) return name . removeprefix ( \"TIMEFRAME_\" )","title":"resolve_granularity_name"},{"location":"api/history/#mt5cli.history.resolve_history_datasets","text":"resolve_history_datasets ( datasets : set [ Dataset ] | None , ) -> set [ Dataset ] Resolve configured history datasets. Returns: Type Description set [ Dataset ] All supported datasets when datasets is None, otherwise the set [ Dataset ] configured selection (which may be empty). Source code in mt5cli/history.py 61 62 63 64 65 66 67 68 69 70 def resolve_history_datasets ( datasets : set [ Dataset ] | None ) -> set [ Dataset ]: \"\"\"Resolve configured history datasets. Returns: All supported datasets when ``datasets`` is None, otherwise the configured selection (which may be empty). \"\"\" if datasets is None : return set ( Dataset ) return set ( datasets )","title":"resolve_history_datasets"},{"location":"api/history/#mt5cli.history.resolve_history_tick_flags","text":"resolve_history_tick_flags ( flags : int | str ) -> int Resolve tick copy flags from an integer or name. Returns: Type Description int Integer tick flag value. Source code in mt5cli/history.py 92 93 94 95 96 97 98 def resolve_history_tick_flags ( flags : int | str ) -> int : \"\"\"Resolve tick copy flags from an integer or name. Returns: Integer tick flag value. \"\"\" return parse_tick_flags ( flags )","title":"resolve_history_tick_flags"},{"location":"api/history/#mt5cli.history.resolve_history_timeframes","text":"resolve_history_timeframes ( timeframes : Sequence [ int | str ] | None , ) -> list [ int ] Resolve rate timeframes, deduplicating aliases for the same integer. Returns: Type Description list [ int ] Ordered list of unique timeframe integers. Source code in mt5cli/history.py 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 def resolve_history_timeframes ( timeframes : Sequence [ int | str ] | None , ) -> list [ int ]: \"\"\"Resolve rate timeframes, deduplicating aliases for the same integer. Returns: Ordered list of unique timeframe integers. \"\"\" raw = timeframes if timeframes is not None else DEFAULT_HISTORY_TIMEFRAMES seen : set [ int ] = set () resolved : list [ int ] = [] for value in raw : tf = parse_timeframe ( value ) if tf not in seen : seen . add ( tf ) resolved . append ( tf ) return resolved","title":"resolve_history_timeframes"},{"location":"api/history/#mt5cli.history.resolve_rate_table_name","text":"resolve_rate_table_name ( symbol : str , granularity : str ) -> str Return the canonical normalized SQLite rate table name. The normalized history table stores all symbols and timeframes in rates ; use :func: resolve_rate_view_name for per-symbol compatibility view names. Returns: Type Description str Canonical normalized rates table name. Raises: Type Description ValueError If symbol or granularity is invalid. Source code in mt5cli/history.py 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 def resolve_rate_table_name ( symbol : str , granularity : str ) -> str : \"\"\"Return the canonical normalized SQLite rate table name. The normalized history table stores all symbols and timeframes in ``rates``; use :func:`resolve_rate_view_name` for per-symbol compatibility view names. Returns: Canonical normalized rates table name. Raises: ValueError: If ``symbol`` or ``granularity`` is invalid. \"\"\" parse_timeframe ( granularity ) if not symbol . strip (): msg = \"symbol must not be empty.\" raise ValueError ( msg ) return Dataset . rates . table_name","title":"resolve_rate_table_name"},{"location":"api/history/#mt5cli.history.resolve_rate_tables","text":"resolve_rate_tables ( conn_or_path : SqliteConnOrPath | None , targets : Sequence [ RateTarget ], explicit_tables : Sequence [ str ] | None = None , * , require_existing : bool = False , ) -> list [ str ] Resolve SQLite table or view names for rate targets. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath | None SQLite database path or open connection. May be None when explicit_tables is provided, or when require_existing is False and deterministic default view names are sufficient. required targets Sequence [ RateTarget ] Rate targets to resolve. required explicit_tables Sequence [ str ] | None Optional explicit table or view names. When provided, they are used as-is and must match the number of targets. None require_existing bool When True, require the database and managed views to exist for each symbol target. Ignored when explicit_tables is provided. False Returns: Type Description list [ str ] Table or view names aligned with targets . Raises: Type Description ValueError If targets is empty, explicit_tables length does not match the target count, a target without a symbol is resolved without an explicit table, or require_existing is True and the database or a managed view is missing. Source code in mt5cli/history.py 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 def resolve_rate_tables ( conn_or_path : SqliteConnOrPath | None , targets : Sequence [ RateTarget ], explicit_tables : Sequence [ str ] | None = None , * , require_existing : bool = False , ) -> list [ str ]: \"\"\"Resolve SQLite table or view names for rate targets. Args: conn_or_path: SQLite database path or open connection. May be None when ``explicit_tables`` is provided, or when ``require_existing`` is False and deterministic default view names are sufficient. targets: Rate targets to resolve. explicit_tables: Optional explicit table or view names. When provided, they are used as-is and must match the number of targets. require_existing: When True, require the database and managed views to exist for each symbol target. Ignored when ``explicit_tables`` is provided. Returns: Table or view names aligned with ``targets``. Raises: ValueError: If ``targets`` is empty, ``explicit_tables`` length does not match the target count, a target without a symbol is resolved without an explicit table, or ``require_existing`` is True and the database or a managed view is missing. \"\"\" target_list = list ( targets ) if not target_list : msg = \"At least one rate target is required.\" raise ValueError ( msg ) if explicit_tables is not None : tables = list ( explicit_tables ) if len ( tables ) != len ( target_list ): msg = ( f \"Expected { len ( target_list ) } explicit table(s) \" f \"to match the targets, got { len ( tables ) } .\" ) raise ValueError ( msg ) return tables if any ( target . symbol is None for target in target_list ): msg = ( \"Cannot resolve a rate table for a target without a symbol; \" \"provide explicit_tables.\" ) raise ValueError ( msg ) conn , should_close = _open_history_connection ( conn_or_path ) try : if conn is None : if require_existing : path = ( conn_or_path if isinstance ( conn_or_path , ( Path , str )) else \"database\" ) msg = f \"SQLite database not found: { path } \" raise ValueError ( msg ) timeframe_counts = None existing_views : set [ str ] = set () else : timeframe_counts = _load_rates_timeframe_counts ( conn ) existing_views = _load_existing_rate_views ( conn ) resolved : list [ str ] = [] for target in target_list : symbol = cast ( \"str\" , target . symbol ) timeframe = target . timeframe_int resolved . append ( _resolve_rate_view_name_from_context ( symbol = symbol , timeframe = timeframe , granularity_name = resolve_granularity_name ( timeframe ), timeframe_counts = timeframe_counts , existing_views = existing_views , require_existing = require_existing , ), ) return resolved finally : if should_close and conn is not None : conn . close ()","title":"resolve_rate_tables"},{"location":"api/history/#mt5cli.history.resolve_rate_view_name","text":"resolve_rate_view_name ( conn_or_path : SqliteConnOrPath | None , symbol : str , granularity : str , * , require_existing : bool = False , ) -> str Resolve the mt5cli-managed rate compatibility view name. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath | None SQLite database path or open connection. When None or a non-existing path and require_existing is False, the deterministic default view name is returned without creating a database file. required symbol str Symbol stored in the normalized rates table. required granularity str Timeframe name (for example M1 ) or integer string. required require_existing bool When True, require the database and a managed view to exist. False Returns: Type Description str View name such as rate_EURUSD__1 or rate_EURUSD__M1_1 . Raises: Type Description ValueError If require_existing is True and the database or view is missing. Source code in mt5cli/history.py 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 def resolve_rate_view_name ( conn_or_path : SqliteConnOrPath | None , symbol : str , granularity : str , * , require_existing : bool = False , ) -> str : \"\"\"Resolve the mt5cli-managed rate compatibility view name. Args: conn_or_path: SQLite database path or open connection. When None or a non-existing path and ``require_existing`` is False, the deterministic default view name is returned without creating a database file. symbol: Symbol stored in the normalized ``rates`` table. granularity: Timeframe name (for example ``M1``) or integer string. require_existing: When True, require the database and a managed view to exist. Returns: View name such as ``rate_EURUSD__1`` or ``rate_EURUSD__M1_1``. Raises: ValueError: If ``require_existing`` is True and the database or view is missing. \"\"\" timeframe = parse_timeframe ( granularity ) granularity_name = resolve_granularity_name ( timeframe ) conn , should_close = _open_history_connection ( conn_or_path ) try : if conn is None : if require_existing : path = ( conn_or_path if isinstance ( conn_or_path , ( Path , str )) else \"database\" ) msg = f \"SQLite database not found: { path } \" raise ValueError ( msg ) return build_rate_view_name ( symbol = symbol , granularity = granularity_name , granularity_count = 1 , timeframe = timeframe , ) return _resolve_rate_view_name_from_context ( symbol = symbol , timeframe = timeframe , granularity_name = granularity_name , timeframe_counts = _load_rates_timeframe_counts ( conn ), existing_views = _load_existing_rate_views ( conn ), require_existing = require_existing , ) finally : if should_close and conn is not None : conn . close ()","title":"resolve_rate_view_name"},{"location":"api/history/#mt5cli.history.resolve_rate_view_names","text":"resolve_rate_view_names ( conn_or_path : SqliteConnOrPath | None , symbols : Sequence [ str ], granularities : Sequence [ str ], * , require_existing : bool = False , ) -> list [ str ] Resolve rate compatibility view names for symbol and granularity pairs. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath | None SQLite database path or open connection. When None or a non-existing path and require_existing is False, deterministic default view names are returned without creating a database file. required symbols Sequence [ str ] Symbols stored in the normalized rates table. required granularities Sequence [ str ] Timeframe names (for example M1 ) or integer strings. required require_existing bool When True, require the database and managed views to exist. False Returns: Type Description list [ str ] View names in row-major order: every granularity for the first list [ str ] symbol, then every granularity for the next symbol, and so on. Source code in mt5cli/history.py 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 def resolve_rate_view_names ( conn_or_path : SqliteConnOrPath | None , symbols : Sequence [ str ], granularities : Sequence [ str ], * , require_existing : bool = False , ) -> list [ str ]: \"\"\"Resolve rate compatibility view names for symbol and granularity pairs. Args: conn_or_path: SQLite database path or open connection. When None or a non-existing path and ``require_existing`` is False, deterministic default view names are returned without creating a database file. symbols: Symbols stored in the normalized ``rates`` table. granularities: Timeframe names (for example ``M1``) or integer strings. require_existing: When True, require the database and managed views to exist. Returns: View names in row-major order: every ``granularity`` for the first symbol, then every granularity for the next symbol, and so on. \"\"\" conn , should_close = _open_history_connection ( conn_or_path ) try : if conn is None : return [ resolve_rate_view_name ( conn_or_path , symbol , granularity , require_existing = require_existing , ) for symbol in symbols for granularity in granularities ] timeframe_counts = _load_rates_timeframe_counts ( conn ) existing_views = _load_existing_rate_views ( conn ) resolved : list [ str ] = [] for symbol in symbols : for granularity in granularities : timeframe = parse_timeframe ( granularity ) resolved . append ( _resolve_rate_view_name_from_context ( symbol = symbol , timeframe = timeframe , granularity_name = resolve_granularity_name ( timeframe ), timeframe_counts = timeframe_counts , existing_views = existing_views , require_existing = require_existing , ), ) return resolved finally : if should_close and conn is not None : conn . close ()","title":"resolve_rate_view_names"},{"location":"api/history/#mt5cli.history.write_collected_datasets","text":"write_collected_datasets ( conn : Connection , client : Mt5DataClient , symbols : Sequence [ str ], datasets : set [ Dataset ], timeframe : int , flags : int , date_from : datetime , date_to : datetime , if_exists : IfExists , ) -> tuple [ set [ Dataset ], dict [ Dataset , set [ str ]]] Collect selected datasets and stream each symbol frame into SQLite. Returns: Type Description tuple [ set [ Dataset ], dict [ Dataset , set [ str ]]] Written datasets and their columns. Source code in mt5cli/history.py 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 def write_collected_datasets ( conn : sqlite3 . Connection , client : Mt5DataClient , symbols : Sequence [ str ], datasets : set [ Dataset ], timeframe : int , flags : int , date_from : datetime , date_to : datetime , if_exists : IfExists , ) -> tuple [ set [ Dataset ], dict [ Dataset , set [ str ]]]: \"\"\"Collect selected datasets and stream each symbol frame into SQLite. Returns: Written datasets and their columns. \"\"\" written_columns : dict [ Dataset , set [ str ]] = {} written_tables : set [ Dataset ] = set () if Dataset . rates in datasets and write_rates_dataset ( conn , client , symbols , timeframe , date_from , date_to , if_exists , written_columns , ): written_tables . add ( Dataset . rates ) if Dataset . ticks in datasets and write_ticks_dataset ( conn , client , symbols , flags , date_from , date_to , if_exists , written_columns , ): written_tables . add ( Dataset . ticks ) if Dataset . history_orders in datasets and write_history_dataset ( conn , client . history_orders_get_as_df , Dataset . history_orders , symbols , date_from , date_to , if_exists , written_columns , include_account_events = False , ): written_tables . add ( Dataset . history_orders ) if Dataset . history_deals in datasets and write_history_dataset ( conn , client . history_deals_get_as_df , Dataset . history_deals , symbols , date_from , date_to , if_exists , written_columns , include_account_events = False , ): written_tables . add ( Dataset . history_deals ) return written_tables , written_columns","title":"write_collected_datasets"},{"location":"api/history/#mt5cli.history.write_history_dataset","text":"write_history_dataset ( conn : Connection , fetch : Callable [ ... , DataFrame ], dataset : Dataset , symbols : Sequence [ str ], date_from : datetime , date_to : datetime , if_exists : IfExists , written_columns : dict [ Dataset , set [ str ]], * , include_account_events : bool = False , ) -> bool Stream a history dataset into SQLite. Returns: Type Description bool True if the target table was written. Source code in mt5cli/history.py 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 def write_history_dataset ( conn : sqlite3 . Connection , fetch : Callable [ ... , pd . DataFrame ], dataset : Dataset , symbols : Sequence [ str ], date_from : datetime , date_to : datetime , if_exists : IfExists , written_columns : dict [ Dataset , set [ str ]], * , include_account_events : bool = False , ) -> bool : \"\"\"Stream a history dataset into SQLite. Returns: True if the target table was written. \"\"\" table_exists = False if include_account_events : frame = filter_trade_history_frame ( fetch ( date_from = date_from , date_to = date_to ), symbols , include_account_events = True , ) return write_streamed_frame ( conn , frame , dataset , table_exists , if_exists , written_columns , ) def _fetch_history_frame ( sym : str ) -> pd . DataFrame : return filter_trade_history_frame ( fetch ( date_from = date_from , date_to = date_to , symbol = sym ), [ sym ], include_account_events = False , ) return _stream_symbol_frames ( conn , symbols , dataset , if_exists , written_columns , _fetch_history_frame , )","title":"write_history_dataset"},{"location":"api/history/#mt5cli.history.write_incremental_datasets","text":"write_incremental_datasets ( conn : Connection , client : Mt5DataClient , symbols : Sequence [ str ], selected_datasets : set [ Dataset ], resolved_timeframes : list [ int ], resolved_tick_flags : int , fallback_start : datetime , end_date : datetime , * , deduplicate : bool , create_rate_views : bool , with_views : bool , include_account_events : bool , ) -> tuple [ set [ Dataset ], dict [ Dataset , set [ str ]]] Append selected datasets incrementally and refresh indexes and views. Returns: Type Description tuple [ set [ Dataset ], dict [ Dataset , set [ str ]]] Written datasets and their columns. Source code in mt5cli/history.py 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 def write_incremental_datasets ( # noqa: PLR0913 conn : sqlite3 . Connection , client : Mt5DataClient , symbols : Sequence [ str ], selected_datasets : set [ Dataset ], resolved_timeframes : list [ int ], resolved_tick_flags : int , fallback_start : datetime , end_date : datetime , * , deduplicate : bool , create_rate_views : bool , with_views : bool , include_account_events : bool , ) -> tuple [ set [ Dataset ], dict [ Dataset , set [ str ]]]: \"\"\"Append selected datasets incrementally and refresh indexes and views. Returns: Written datasets and their columns. \"\"\" written_columns : dict [ Dataset , set [ str ]] = {} written_tables : set [ Dataset ] = set () dedup_scopes : dict [ Dataset , list [ DedupScope ]] = {} if Dataset . rates in selected_datasets : _write_incremental_rates ( conn , client , symbols , resolved_timeframes , fallback_start , end_date , written_columns , written_tables , dedup_scopes , ) if Dataset . ticks in selected_datasets : _write_incremental_ticks ( conn , client , symbols , resolved_tick_flags , fallback_start , end_date , written_columns , written_tables , dedup_scopes , ) if Dataset . history_orders in selected_datasets : _write_incremental_history_orders ( conn , client , symbols , fallback_start , end_date , written_columns , written_tables , dedup_scopes , ) if Dataset . history_deals in selected_datasets : _write_incremental_history_deals ( conn , client , symbols , fallback_start , end_date , written_columns , written_tables , dedup_scopes , include_account_events = include_account_events , ) _finalize_incremental_writes ( conn , selected_datasets , written_columns , written_tables , dedup_scopes , deduplicate = deduplicate , create_rate_views = create_rate_views , with_views = with_views , ) return written_tables , written_columns","title":"write_incremental_datasets"},{"location":"api/history/#mt5cli.history.write_rates_dataset","text":"write_rates_dataset ( conn : Connection , client : Mt5DataClient , symbols : Sequence [ str ], timeframe : int , date_from : datetime , date_to : datetime , if_exists : IfExists , written_columns : dict [ Dataset , set [ str ]], ) -> bool Stream rates frames into SQLite. Returns: Type Description bool True if the rates table was written. Source code in mt5cli/history.py 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 def write_rates_dataset ( conn : sqlite3 . Connection , client : Mt5DataClient , symbols : Sequence [ str ], timeframe : int , date_from : datetime , date_to : datetime , if_exists : IfExists , written_columns : dict [ Dataset , set [ str ]], ) -> bool : \"\"\"Stream rates frames into SQLite. Returns: True if the rates table was written. \"\"\" def _fetch_rates_frame ( sym : str ) -> pd . DataFrame : frame = client . copy_rates_range_as_df ( symbol = sym , timeframe = timeframe , date_from = date_from , date_to = date_to , ) . drop ( columns = [ \"symbol\" , \"timeframe\" ], errors = \"ignore\" ) if len ( frame . columns ) != 0 : frame . insert ( 0 , \"symbol\" , sym ) frame . insert ( 1 , \"timeframe\" , timeframe ) return frame return _stream_symbol_frames ( conn , symbols , Dataset . rates , if_exists , written_columns , _fetch_rates_frame , )","title":"write_rates_dataset"},{"location":"api/history/#mt5cli.history.write_streamed_frame","text":"write_streamed_frame ( conn : Connection , frame : DataFrame , dataset : Dataset , table_exists : bool , if_exists : IfExists , written_columns : dict [ Dataset , set [ str ]], ) -> bool Write one streamed dataset frame and track table state. Returns: Type Description bool True if the dataset table exists after this write attempt. Source code in mt5cli/history.py 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 def write_streamed_frame ( conn : sqlite3 . Connection , frame : pd . DataFrame , dataset : Dataset , table_exists : bool , if_exists : IfExists , written_columns : dict [ Dataset , set [ str ]], ) -> bool : \"\"\"Write one streamed dataset frame and track table state. Returns: True if the dataset table exists after this write attempt. \"\"\" write_mode = IfExists . APPEND if table_exists else if_exists if append_dataframe ( conn , frame , dataset . table_name , write_mode ): record_written_columns ( written_columns , dataset , frame ) return True return table_exists","title":"write_streamed_frame"},{"location":"api/history/#mt5cli.history.write_ticks_dataset","text":"write_ticks_dataset ( conn : Connection , client : Mt5DataClient , symbols : Sequence [ str ], flags : int , date_from : datetime , date_to : datetime , if_exists : IfExists , written_columns : dict [ Dataset , set [ str ]], ) -> bool Stream ticks frames into SQLite. Returns: Type Description bool True if the ticks table was written. Source code in mt5cli/history.py 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 def write_ticks_dataset ( conn : sqlite3 . Connection , client : Mt5DataClient , symbols : Sequence [ str ], flags : int , date_from : datetime , date_to : datetime , if_exists : IfExists , written_columns : dict [ Dataset , set [ str ]], ) -> bool : \"\"\"Stream ticks frames into SQLite. Returns: True if the ticks table was written. \"\"\" def _fetch_ticks_frame ( sym : str ) -> pd . DataFrame : frame = client . copy_ticks_range_as_df ( symbol = sym , date_from = date_from , date_to = date_to , flags = flags , ) . drop ( columns = [ \"symbol\" ], errors = \"ignore\" ) if len ( frame . columns ) != 0 : frame . insert ( 0 , \"symbol\" , sym ) return frame return _stream_symbol_frames ( conn , symbols , Dataset . ticks , if_exists , written_columns , _fetch_ticks_frame , )","title":"write_ticks_dataset"},{"location":"api/history/#collect-history-schema","text":"The collect-history command (and the matching collect_history SDK function) writes selected MT5 datasets into one SQLite database. Each dataset becomes a table; column names and types mirror the pdmt5 DataFrame schema for that export, with two additions: symbol is prepended on every table. timeframe is prepended on rates so appended runs at different bar sizes stay distinguishable. SQLite does not declare foreign keys. Rows are linked logically by symbol , time windows, and (for deals) position_id / order . Duplicate rows are removed on append using dataset-specific keys (for example ticket on history tables, or (symbol, timeframe, time) on rates). Optional views are created when --with-views is set and the history-deals dataset was written.","title":"collect-history schema"},{"location":"api/history/#entity-relationship-diagram","text":"Sample layout for a full collection with --with-views : erDiagram rates { TEXT symbol \"dedup key\" INTEGER timeframe \"dedup key\" TEXT time \"dedup key\" REAL open REAL high REAL low REAL close INTEGER tick_volume INTEGER spread INTEGER real_volume } ticks { TEXT symbol \"dedup key\" TEXT time \"dedup key\" INTEGER time_msc \"dedup key (preferred)\" REAL bid REAL ask REAL last INTEGER volume INTEGER flags REAL volume_real } history_orders { INTEGER ticket \"dedup key\" TEXT symbol TEXT time INTEGER type INTEGER state REAL volume_initial REAL price_open REAL price_current INTEGER magic } history_deals { INTEGER ticket \"dedup key\" INTEGER order INTEGER position_id \"groups position view\" TEXT symbol TEXT time INTEGER type \"0/1 trade, else cash event\" INTEGER entry \"0 IN, 1 OUT, 2 INOUT, 3 OUT_BY\" REAL volume REAL price REAL profit REAL commission REAL swap REAL fee } cash_events { INTEGER ticket TEXT symbol TEXT time INTEGER type REAL profit } positions_reconstructed { INTEGER position_id TEXT symbol TEXT open_time TEXT close_time INTEGER direction REAL volume_open REAL volume_close REAL volume_reversal REAL open_price REAL close_price REAL total_profit INTEGER reversal_count INTEGER deals_count } rates ||--o{ history_deals : \"symbol (logical)\" ticks ||--o{ history_deals : \"symbol (logical)\" history_orders ||--o{ history_deals : \"order ~ ticket (logical)\" history_deals ||--|| cash_events : \"VIEW: type NOT IN (0,1)\" history_deals ||--o{ positions_reconstructed : \"VIEW: GROUP BY position_id\"","title":"Entity-relationship diagram"},{"location":"api/history/#tables-and-views","text":"Object Kind Source Notes rates table copy_rates_range Indexed on (symbol, timeframe, time) when columns exist. ticks table copy_ticks_range Indexed on (symbol, time) when columns exist. history_orders table history_orders_get Fetched per --symbol , then concatenated. history_deals table history_deals_get Fetched per --symbol , then concatenated. Indexed on (position_id, symbol) when present. cash_events view history_deals Non-trade deal types (deposits, balance ops, etc.). Requires type column. positions_reconstructed view history_deals One row per closed position_id ; volume-weighted prices and reversal stats. Column sets can vary with terminal and pdmt5 version. Views are skipped with a warning when required columns are missing.","title":"Tables and views"},{"location":"api/history/#incremental-collection","text":"The update_history SDK path uses the same base tables and optional cash_events / positions_reconstructed views. It additionally maintains rate___ compatibility views when create_rate_views=True .","title":"Incremental collection"},{"location":"api/history/#rate-view-resolution","text":"Downstream tools can resolve mt5cli-managed compatibility view names from an existing SQLite history database without creating files or guessing naming schemes: from pathlib import Path from mt5cli.history import resolve_rate_view_name , resolve_rate_view_names # Single symbol and granularity view = resolve_rate_view_name ( Path ( \"history.db\" ), \"EURUSD\" , \"M1\" ) # Batch resolution in row-major order views = resolve_rate_view_names ( Path ( \"history.db\" ), [ \"EURUSD\" , \"GBPUSD\" ], [ \"M1\" , \"H1\" ], ) Resolution rules: Returns rate___ when a symbol stores one timeframe. Returns rate____ when multiple timeframes are stored for the same symbol. When multiple naming candidates apply, prefers an existing managed rate_*__* view from the candidate list. Falls back to single-timeframe naming when the database path is missing or rates metadata is unavailable. Pass require_existing=True to raise ValueError instead of returning a best-guess name when the database or view is missing. Accepts either a SQLite path or an open sqlite3.Connection .","title":"Rate view resolution"},{"location":"api/history/#rate-data-loading","text":"The canonical normalized rate table is rates ; compatibility views are named with rate___ for single-timeframe symbols or rate____ when a symbol has multiple stored timeframes. resolve_rate_table_name() returns rates , while resolve_rate_view_name() returns the per-symbol compatibility view name. Use load_rate_data() or load_rate_series_from_sqlite(..., table=...) to load a single table or view from a SQLite path. Use load_rate_series_by_granularity() to load multiple instrument/granularity targets without hard-coding view names: from pathlib import Path from mt5cli import ( load_rate_data , load_rate_series_by_granularity , load_rate_series_from_sqlite , resolve_rate_table_name , ) from mt5cli.history import resolve_rate_view_name view = resolve_rate_view_name ( Path ( \"history.db\" ), \"EURUSD\" , \"M1\" , require_existing = True ) rates = load_rate_data ( Path ( \"history.db\" ), view , count = 1000 ) same_rates = load_rate_series_from_sqlite ( Path ( \"history.db\" ), table = view , count = 1000 ) table = resolve_rate_table_name ( \"EURUSD\" , \"M1\" ) # \"rates\" series = load_rate_series_by_granularity ( Path ( \"history.db\" ), symbols = [ \"EURUSD\" , \"GBPUSD\" ], granularities = [ \"M1\" , \"H1\" ], count = 500 , ) count returns the latest rows while preserving chronological order. Missing tables/views and mismatched explicit_tables lengths raise ValueError with the requested database target in the message. The loader accepts close-based OHLC rate data or tick-like bid/ask data. It validates that time exists, parses timestamps with pandas, and returns a DataFrame indexed by ascending DatetimeIndex named time .","title":"Rate data loading"},{"location":"api/history/#multi-series-rate-loading","text":"For loading many rate series at once, build neutral RateTarget pairs and load them from SQLite in one call. View names are resolved via the same compatibility-view rules, or you can pass explicit_tables to bypass resolution: from pathlib import Path from mt5cli import build_rate_targets , load_rate_series_from_sqlite targets = build_rate_targets ([ \"EURUSD\" , \"GBPUSD\" ], [ \"M1\" , \"H1\" ]) series = load_rate_series_from_sqlite ( Path ( \"history.db\" ), targets , count = 1000 ) frame = series [ \"EURUSD\" , 1 ] # keyed by (symbol, integer timeframe) build_rate_targets() returns RateTarget(symbol, timeframe) pairs in row-major order, normalizing timeframe names such as \"M1\" to their integer values; set allow_missing_symbol=True to address series solely by explicit_tables (targets carry symbol=None ). resolve_rate_tables() maps targets to table or view names and validates that any explicit_tables count matches the target count. Pass require_existing=True to raise ValueError instead of returning a best-guess name when the database or managed view is missing. When explicit_tables is provided, names are returned as-is and require_existing is ignored. load_rate_series_from_sqlite() returns a mapping keyed by (symbol, integer timeframe) . Unless explicit_tables is supplied, it requires existing managed rate_* compatibility views and raises ValueError when they are missing. Duplicate (symbol, timeframe) targets are rejected. load_rate_series_by_granularity() is a thin wrapper that builds the targets, loads the series, and rekeys the result by granularity name to avoid converting integer timeframes downstream: from mt5cli import load_rate_series_by_granularity series = load_rate_series_by_granularity ( \"history.db\" , [ \"EURUSD\" ], [ \"M1\" , \"H1\" ], count = 1000 ) frame = series [ \"EURUSD\" , \"M1\" ] # keyed by (symbol | None, granularity_name)","title":"Multi-series rate loading"},{"location":"api/public-contract/","text":"Public API Contract \u00b6 mt5cli is the generic MT5 data and execution infrastructure layer for downstream Python applications. The intended dependency direction is: downstream app -> mt5cli -> pdmt5 -> MetaTrader 5 Downstream packages should import from the package root ( from mt5cli import ... ) and use the public tier sets in mt5cli.contract to distinguish API stability. CLI commands mirror the same behavior but are not importable Python APIs. Public API tiers \u00b6 mt5cli classifies package-root imports by intended downstream use: Tier Contract set Meaning Stable core STABLE_SDK_EXPORTS Preferred SDK surface for downstream MT5 infrastructure adapters. Changes require a deliberate compatibility path. Secondary public SECONDARY_PUBLIC_EXPORTS Public helpers for CLI/export/schema integrations and lower-level MT5 wrappers. Importable, but less central to the downstream trading SDK. Stable downstream SDK API \u00b6 These names are exported from mt5cli and covered by the contract in mt5cli.STABLE_SDK_EXPORTS (defined in mt5cli.contract ). Session lifecycle and configuration \u00b6 Symbol Role MT5Client Read-only data client with optional order_check / order_send build_config Build pdmt5.Mt5Config from connection fields; login accepts int \\| str \\| None \u2014 numeric strings are coerced to int , blank strings are treated as unset, and ${ENV_VAR} / $ENV_NAME placeholders in string parameters are expanded when allow_whole_dollar_env=True mt5_session Context manager: initialize, login, yield client, shutdown create_trading_client , mt5_trading_session Trading-capable pdmt5.Mt5TradingClient lifecycle AccountSpec Generic account group: symbols plus optional credentials resolve_account_spec , resolve_account_specs Merge overrides and expand ${ENV_VAR} placeholders; opt-in allow_whole_dollar_env for bare $NAME substitute_env_placeholders Replace ${NAME} substrings from the environment; opt-in allow_whole_dollar_env for whole-value $NAME substitute_mapping_values Recursively traverse a dict/list/scalar structure and substitute ${ENV_VAR} placeholders for caller-selected mapping keys only; optionally normalise blank strings to None for a separate caller-selected key set; does not hard-code any application-specific key names Credential resolution is generic: any environment variable name may appear inside ${...} . mt5cli does not hard-code application-specific keys such as mt5_login or mt5_exe . Pass allow_whole_dollar_env=True to substitute_env_placeholders() , substitute_mapping_values() , resolve_account_spec() , resolve_account_specs() , and build_config() to additionally expand strings whose entire value is a bare $ENV_NAME identifier. Partial strings such as \"plan$pass\" , \"abc$ENV\" , or \"$ENV-suffix\" are never expanded \u2014 only an exact $IDENTIFIER whole-string match qualifies. Default is False to preserve backward compatibility. Closed-bar rate helpers \u00b6 MetaTrader 5 returns the still-forming bar as the last row when start_pos=0 . Use these helpers instead of reimplementing bar trimming or timestamp normalization in downstream apps. Symbol Role drop_forming_rate_bar Remove the last row from chronologically ordered rate data fetch_latest_closed_rates Single connected client: fetch count + 1 , drop forming bar fetch_latest_closed_rates_for_trading_client Closed bars from an active Mt5TradingClient session; returns RangeIndex fetch_latest_closed_rates_indexed Same as above but returns a UTC DatetimeIndex named \"time\" (no time column) collect_latest_closed_rates_for_accounts Multi-account closed bars with optional retry wrapper collect_latest_closed_rates_by_granularity Same data keyed by (symbol, granularity_name) collect_latest_rates_for_accounts_with_retries Bounded exponential backoff for transient MT5 errors SQLite history collection and rate loading \u00b6 Symbol Role collect_history One-shot date-range export into SQLite update_history , update_history_with_config Incremental append from MAX(time) cursors ThrottledHistoryUpdater Minimum interval between successful incremental updates; optional update_backend injection resolve_history_datasets , resolve_history_timeframes , resolve_history_tick_flags History pipeline configuration build_rate_view_name , resolve_rate_table_name , resolve_rate_view_name , resolve_rate_view_names , resolve_rate_tables Map symbols/timeframes to mt5cli-managed table or view names RateTarget , build_rate_targets Neutral (symbol, timeframe) series descriptors load_rate_data , load_rate_data_from_connection Load one table/view into a time-indexed DataFrame load_rate_series_from_sqlite , load_rate_series_by_granularity Load one or many series; fail clearly when managed views are missing Pass require_existing=True to rate view resolution helpers when downstream code must fail instead of receiving a best-guess view name. Multi-series loaders require existing managed rate_*__* views unless explicit_tables is supplied. See History Collection (SQLite) for schema, view naming, and ER diagrams. Trading and sizing primitives (generic) \u00b6 These helpers implement broker-facing calculations only. They do not encode strategy entries, exits, Kelly sizing, or signal logic. Symbol Role get_account_snapshot , get_symbol_snapshot , get_tick_snapshot , get_positions_frame Normalized account/symbol/tick/position views extract_tick_price Positive finite bid/ask extraction from tick mappings detect_position_side Net long / short / flat from open positions calculate_spread_ratio Relative bid-ask spread calculate_margin_and_volume , calculate_volume_by_margin , calculate_new_position_margin_ratio Margin budget and volume sizing normalize_order_volume , estimate_order_margin , calculate_positions_margin Broker volume normalization and margin totals calculate_positions_margin_by_symbol Per-symbol margin map (resilient, first-seen order) calculate_positions_margin_safe Summed total margin across symbols (failed symbols skipped) calculate_projected_margin_ratio Estimated symbol-scoped margin/equity after optional new exposure calculate_account_projected_margin_ratio Account snapshot margin/equity after optional new exposure calculate_symbol_group_margin_ratio Estimated symbol-group margin/equity with optional exposure determine_order_limits SL/TP price levels from ratios calculate_trailing_stop_updates Per-ticket generic trailing stop-loss update plan ensure_symbol_selected Select/verify Market Watch visibility place_market_order , close_open_positions , update_sltp_for_open_positions , update_trailing_stop_loss_for_open_positions Order execution helpers ( dry_run supported) MarginVolume , OrderLimits , OrderExecutionResult Typed return contracts for order helpers OrderSide , OrderFillingMode , OrderTimeMode , PositionSide , ExecutionStatus Typed enums for order helpers ProjectionMode Literal type for calculate_symbol_group_margin_ratio projection MT5Client.order_send() and CLI order-send --yes are live execution paths. Order helpers validate broker stop-level distance in determine_order_limits() and raise Mt5TradingError when computed SL/TP prices are too close to the entry quote. Validation uses trade_stops_level * point from the current quote and symbol metadata as a pre-check only; it does not guarantee live order acceptance after price movement and does not inspect trade_freeze_level . Live place_market_order() and SL/TP updates call ensure_symbol_selected() so hidden symbols are added to Market Watch before sending requests. Failed, malformed, or unknown broker retcodes are fail-closed and returned as status=\"failed\" with normalized request / response details; dry_run=True never calls ensure_symbol_selected() or order_send() . Errors and MT5 type re-exports \u00b6 Symbol Role Mt5CliError , Mt5ConnectionError , Mt5OperationError , Mt5SchemaError Stable mt5cli exception types normalize_mt5_exception , call_with_normalized_errors , is_recoverable_mt5_error Error normalization and retry classification Mt5Config , Mt5RuntimeError , Mt5TradingClient , Mt5TradingError Re-exported pdmt5 types for adapter convenience Secondary public exports \u00b6 These names remain importable from mt5cli and are covered by SECONDARY_PUBLIC_EXPORTS , but they are oriented toward CLI/export/schema integrations, parsing, and lower-level MT5 access rather than the stable core SDK surface. Prefer the stable symbols above for downstream infrastructure adapters. Read-only MT5 data wrappers \u00b6 Module-level helpers open a transient connection per call. Prefer mt5_session or MT5Client when making many requests in one process. Area Symbols Rates copy_rates_from , copy_rates_from_pos , copy_rates_range , latest_rates , collect_latest_rates Ticks copy_ticks_from , copy_ticks_range , recent_ticks Account / terminal account_info , terminal_info , mt5_version , last_error , mt5_summary , mt5_summary_as_df Symbols / market symbols , symbol_info , symbol_info_tick , market_book , minimum_margins Trading state (read) orders , positions , history_orders , history_deals , recent_history_deals Multi-account rates collect_latest_rates_for_accounts Use mt5_version for MetaTrader 5 terminal version data. The name version at the package root refers to importlib.metadata.version (package metadata), not the MT5 SDK helper. Schema, export, and parser helpers \u00b6 Area Symbols Dataset contracts DataKind , Dataset , IfExists , DEDUP_KEYS , REQUIRED_COLUMNS , TIME_COLUMNS , KNOWN_MT5_TIME_COLUMNS Schema normalization normalize_dataframe , normalize_time_columns , schema_columns , validate_schema Export helpers detect_format , export_dataframe , export_dataframe_to_sqlite Symbol parsing normalize_symbol , normalize_symbols Time parsing ensure_utc , parse_date_range , parse_datetime , recent_window MT5 parsing maps granularity_name , parse_tick_flags , parse_timeframe , TICK_FLAG_MAP , TIMEFRAME_MAP Trading data shapes POSITION_COLUMNS calculate_symbol_group_margin_ratio supports an optional projection_mode parameter ( \"add\" by default). Pass projection_mode=\"replace_symbol\" to subtract current exposure for new_symbol before adding the candidate margin \u2014 useful for reversal-style projections. mt5cli only calculates broker-facing exposure; downstream applications own thresholds, risk guard actions, and strategy policy. CLI commands \u00b6 The Typer application in mt5cli.cli exposes file-export commands documented in CLI Module and the project README. CLI commands: Require -o/--output and write CSV, JSON, Parquet, or SQLite. Accept global MT5 connection options ( --login , --password , --server , --path , --timeout ). Delegate to the same Python APIs described here; they are not duplicated business logic. order-send is the expert raw-request path; it requires --yes and a fully constructed request payload. close-positions is the safer high-level helper that closes open positions by --symbol or --ticket using close_open_positions() . Both order-send --yes and close-positions --yes are live execution paths. close-positions --dry-run previews close orders without placing them and does not require --yes . Internal helpers (not stable) \u00b6 Do not import these for downstream contracts; they may change without a semver notice: Module Examples mt5cli.sdk connected_client , _run_with_client , private coercion helpers mt5cli.history write_*_dataset , deduplicate_history_tables , parse_sqlite_timestamp mt5cli.retry retry_with_backoff mt5cli.cli Typer command handlers and Click parameter types Leading-underscore names Any _ -prefixed function or method Use the package-root stable exports instead of reaching into submodule internals. Explicitly out of scope \u00b6 mt5cli must not implement downstream strategy or research responsibilities. The following belong in consuming applications, not in mt5cli: Signal detection (for example AR-GARCH or other model-specific triggers) Backtesting, walk-forward analysis, or parameter optimization Strategy-specific risk policy, position sizing systems, or Kelly fractions Entry/exit decision logic or YAML strategy semantics Application-specific credential schema keys wired into mt5cli internals mt5cli provides connection lifecycle, normalized data access, SQLite history machinery, closed-bar helpers, generic margin/volume/spread/SL/TP utilities, and optional order primitives so downstream apps can focus on strategy code behind their own adapter layer. Contract verification \u00b6 tests/test_contracts.py asserts that every name in the stable and secondary tier sets is importable from mt5cli , documents key closed-bar, rate-view, SQLite loading, account-resolution, and trading-session behaviors, and keeps the tier sets aligned with __all__ .","title":"Public API Contract"},{"location":"api/public-contract/#public-api-contract","text":"mt5cli is the generic MT5 data and execution infrastructure layer for downstream Python applications. The intended dependency direction is: downstream app -> mt5cli -> pdmt5 -> MetaTrader 5 Downstream packages should import from the package root ( from mt5cli import ... ) and use the public tier sets in mt5cli.contract to distinguish API stability. CLI commands mirror the same behavior but are not importable Python APIs.","title":"Public API Contract"},{"location":"api/public-contract/#public-api-tiers","text":"mt5cli classifies package-root imports by intended downstream use: Tier Contract set Meaning Stable core STABLE_SDK_EXPORTS Preferred SDK surface for downstream MT5 infrastructure adapters. Changes require a deliberate compatibility path. Secondary public SECONDARY_PUBLIC_EXPORTS Public helpers for CLI/export/schema integrations and lower-level MT5 wrappers. Importable, but less central to the downstream trading SDK.","title":"Public API tiers"},{"location":"api/public-contract/#stable-downstream-sdk-api","text":"These names are exported from mt5cli and covered by the contract in mt5cli.STABLE_SDK_EXPORTS (defined in mt5cli.contract ).","title":"Stable downstream SDK API"},{"location":"api/public-contract/#session-lifecycle-and-configuration","text":"Symbol Role MT5Client Read-only data client with optional order_check / order_send build_config Build pdmt5.Mt5Config from connection fields; login accepts int \\| str \\| None \u2014 numeric strings are coerced to int , blank strings are treated as unset, and ${ENV_VAR} / $ENV_NAME placeholders in string parameters are expanded when allow_whole_dollar_env=True mt5_session Context manager: initialize, login, yield client, shutdown create_trading_client , mt5_trading_session Trading-capable pdmt5.Mt5TradingClient lifecycle AccountSpec Generic account group: symbols plus optional credentials resolve_account_spec , resolve_account_specs Merge overrides and expand ${ENV_VAR} placeholders; opt-in allow_whole_dollar_env for bare $NAME substitute_env_placeholders Replace ${NAME} substrings from the environment; opt-in allow_whole_dollar_env for whole-value $NAME substitute_mapping_values Recursively traverse a dict/list/scalar structure and substitute ${ENV_VAR} placeholders for caller-selected mapping keys only; optionally normalise blank strings to None for a separate caller-selected key set; does not hard-code any application-specific key names Credential resolution is generic: any environment variable name may appear inside ${...} . mt5cli does not hard-code application-specific keys such as mt5_login or mt5_exe . Pass allow_whole_dollar_env=True to substitute_env_placeholders() , substitute_mapping_values() , resolve_account_spec() , resolve_account_specs() , and build_config() to additionally expand strings whose entire value is a bare $ENV_NAME identifier. Partial strings such as \"plan$pass\" , \"abc$ENV\" , or \"$ENV-suffix\" are never expanded \u2014 only an exact $IDENTIFIER whole-string match qualifies. Default is False to preserve backward compatibility.","title":"Session lifecycle and configuration"},{"location":"api/public-contract/#closed-bar-rate-helpers","text":"MetaTrader 5 returns the still-forming bar as the last row when start_pos=0 . Use these helpers instead of reimplementing bar trimming or timestamp normalization in downstream apps. Symbol Role drop_forming_rate_bar Remove the last row from chronologically ordered rate data fetch_latest_closed_rates Single connected client: fetch count + 1 , drop forming bar fetch_latest_closed_rates_for_trading_client Closed bars from an active Mt5TradingClient session; returns RangeIndex fetch_latest_closed_rates_indexed Same as above but returns a UTC DatetimeIndex named \"time\" (no time column) collect_latest_closed_rates_for_accounts Multi-account closed bars with optional retry wrapper collect_latest_closed_rates_by_granularity Same data keyed by (symbol, granularity_name) collect_latest_rates_for_accounts_with_retries Bounded exponential backoff for transient MT5 errors","title":"Closed-bar rate helpers"},{"location":"api/public-contract/#sqlite-history-collection-and-rate-loading","text":"Symbol Role collect_history One-shot date-range export into SQLite update_history , update_history_with_config Incremental append from MAX(time) cursors ThrottledHistoryUpdater Minimum interval between successful incremental updates; optional update_backend injection resolve_history_datasets , resolve_history_timeframes , resolve_history_tick_flags History pipeline configuration build_rate_view_name , resolve_rate_table_name , resolve_rate_view_name , resolve_rate_view_names , resolve_rate_tables Map symbols/timeframes to mt5cli-managed table or view names RateTarget , build_rate_targets Neutral (symbol, timeframe) series descriptors load_rate_data , load_rate_data_from_connection Load one table/view into a time-indexed DataFrame load_rate_series_from_sqlite , load_rate_series_by_granularity Load one or many series; fail clearly when managed views are missing Pass require_existing=True to rate view resolution helpers when downstream code must fail instead of receiving a best-guess view name. Multi-series loaders require existing managed rate_*__* views unless explicit_tables is supplied. See History Collection (SQLite) for schema, view naming, and ER diagrams.","title":"SQLite history collection and rate loading"},{"location":"api/public-contract/#trading-and-sizing-primitives-generic","text":"These helpers implement broker-facing calculations only. They do not encode strategy entries, exits, Kelly sizing, or signal logic. Symbol Role get_account_snapshot , get_symbol_snapshot , get_tick_snapshot , get_positions_frame Normalized account/symbol/tick/position views extract_tick_price Positive finite bid/ask extraction from tick mappings detect_position_side Net long / short / flat from open positions calculate_spread_ratio Relative bid-ask spread calculate_margin_and_volume , calculate_volume_by_margin , calculate_new_position_margin_ratio Margin budget and volume sizing normalize_order_volume , estimate_order_margin , calculate_positions_margin Broker volume normalization and margin totals calculate_positions_margin_by_symbol Per-symbol margin map (resilient, first-seen order) calculate_positions_margin_safe Summed total margin across symbols (failed symbols skipped) calculate_projected_margin_ratio Estimated symbol-scoped margin/equity after optional new exposure calculate_account_projected_margin_ratio Account snapshot margin/equity after optional new exposure calculate_symbol_group_margin_ratio Estimated symbol-group margin/equity with optional exposure determine_order_limits SL/TP price levels from ratios calculate_trailing_stop_updates Per-ticket generic trailing stop-loss update plan ensure_symbol_selected Select/verify Market Watch visibility place_market_order , close_open_positions , update_sltp_for_open_positions , update_trailing_stop_loss_for_open_positions Order execution helpers ( dry_run supported) MarginVolume , OrderLimits , OrderExecutionResult Typed return contracts for order helpers OrderSide , OrderFillingMode , OrderTimeMode , PositionSide , ExecutionStatus Typed enums for order helpers ProjectionMode Literal type for calculate_symbol_group_margin_ratio projection MT5Client.order_send() and CLI order-send --yes are live execution paths. Order helpers validate broker stop-level distance in determine_order_limits() and raise Mt5TradingError when computed SL/TP prices are too close to the entry quote. Validation uses trade_stops_level * point from the current quote and symbol metadata as a pre-check only; it does not guarantee live order acceptance after price movement and does not inspect trade_freeze_level . Live place_market_order() and SL/TP updates call ensure_symbol_selected() so hidden symbols are added to Market Watch before sending requests. Failed, malformed, or unknown broker retcodes are fail-closed and returned as status=\"failed\" with normalized request / response details; dry_run=True never calls ensure_symbol_selected() or order_send() .","title":"Trading and sizing primitives (generic)"},{"location":"api/public-contract/#errors-and-mt5-type-re-exports","text":"Symbol Role Mt5CliError , Mt5ConnectionError , Mt5OperationError , Mt5SchemaError Stable mt5cli exception types normalize_mt5_exception , call_with_normalized_errors , is_recoverable_mt5_error Error normalization and retry classification Mt5Config , Mt5RuntimeError , Mt5TradingClient , Mt5TradingError Re-exported pdmt5 types for adapter convenience","title":"Errors and MT5 type re-exports"},{"location":"api/public-contract/#secondary-public-exports","text":"These names remain importable from mt5cli and are covered by SECONDARY_PUBLIC_EXPORTS , but they are oriented toward CLI/export/schema integrations, parsing, and lower-level MT5 access rather than the stable core SDK surface. Prefer the stable symbols above for downstream infrastructure adapters.","title":"Secondary public exports"},{"location":"api/public-contract/#read-only-mt5-data-wrappers","text":"Module-level helpers open a transient connection per call. Prefer mt5_session or MT5Client when making many requests in one process. Area Symbols Rates copy_rates_from , copy_rates_from_pos , copy_rates_range , latest_rates , collect_latest_rates Ticks copy_ticks_from , copy_ticks_range , recent_ticks Account / terminal account_info , terminal_info , mt5_version , last_error , mt5_summary , mt5_summary_as_df Symbols / market symbols , symbol_info , symbol_info_tick , market_book , minimum_margins Trading state (read) orders , positions , history_orders , history_deals , recent_history_deals Multi-account rates collect_latest_rates_for_accounts Use mt5_version for MetaTrader 5 terminal version data. The name version at the package root refers to importlib.metadata.version (package metadata), not the MT5 SDK helper.","title":"Read-only MT5 data wrappers"},{"location":"api/public-contract/#schema-export-and-parser-helpers","text":"Area Symbols Dataset contracts DataKind , Dataset , IfExists , DEDUP_KEYS , REQUIRED_COLUMNS , TIME_COLUMNS , KNOWN_MT5_TIME_COLUMNS Schema normalization normalize_dataframe , normalize_time_columns , schema_columns , validate_schema Export helpers detect_format , export_dataframe , export_dataframe_to_sqlite Symbol parsing normalize_symbol , normalize_symbols Time parsing ensure_utc , parse_date_range , parse_datetime , recent_window MT5 parsing maps granularity_name , parse_tick_flags , parse_timeframe , TICK_FLAG_MAP , TIMEFRAME_MAP Trading data shapes POSITION_COLUMNS calculate_symbol_group_margin_ratio supports an optional projection_mode parameter ( \"add\" by default). Pass projection_mode=\"replace_symbol\" to subtract current exposure for new_symbol before adding the candidate margin \u2014 useful for reversal-style projections. mt5cli only calculates broker-facing exposure; downstream applications own thresholds, risk guard actions, and strategy policy.","title":"Schema, export, and parser helpers"},{"location":"api/public-contract/#cli-commands","text":"The Typer application in mt5cli.cli exposes file-export commands documented in CLI Module and the project README. CLI commands: Require -o/--output and write CSV, JSON, Parquet, or SQLite. Accept global MT5 connection options ( --login , --password , --server , --path , --timeout ). Delegate to the same Python APIs described here; they are not duplicated business logic. order-send is the expert raw-request path; it requires --yes and a fully constructed request payload. close-positions is the safer high-level helper that closes open positions by --symbol or --ticket using close_open_positions() . Both order-send --yes and close-positions --yes are live execution paths. close-positions --dry-run previews close orders without placing them and does not require --yes .","title":"CLI commands"},{"location":"api/public-contract/#internal-helpers-not-stable","text":"Do not import these for downstream contracts; they may change without a semver notice: Module Examples mt5cli.sdk connected_client , _run_with_client , private coercion helpers mt5cli.history write_*_dataset , deduplicate_history_tables , parse_sqlite_timestamp mt5cli.retry retry_with_backoff mt5cli.cli Typer command handlers and Click parameter types Leading-underscore names Any _ -prefixed function or method Use the package-root stable exports instead of reaching into submodule internals.","title":"Internal helpers (not stable)"},{"location":"api/public-contract/#explicitly-out-of-scope","text":"mt5cli must not implement downstream strategy or research responsibilities. The following belong in consuming applications, not in mt5cli: Signal detection (for example AR-GARCH or other model-specific triggers) Backtesting, walk-forward analysis, or parameter optimization Strategy-specific risk policy, position sizing systems, or Kelly fractions Entry/exit decision logic or YAML strategy semantics Application-specific credential schema keys wired into mt5cli internals mt5cli provides connection lifecycle, normalized data access, SQLite history machinery, closed-bar helpers, generic margin/volume/spread/SL/TP utilities, and optional order primitives so downstream apps can focus on strategy code behind their own adapter layer.","title":"Explicitly out of scope"},{"location":"api/public-contract/#contract-verification","text":"tests/test_contracts.py asserts that every name in the stable and secondary tier sets is importable from mt5cli , documents key closed-bar, rate-view, SQLite loading, account-resolution, and trading-session behaviors, and keeps the tier sets aligned with __all__ .","title":"Contract verification"},{"location":"api/schemas/","text":"Schemas \u00b6 mt5cli.schemas \u00b6 Canonical DataFrame schemas for MT5 market and account datasets. DEDUP_KEYS module-attribute \u00b6 DEDUP_KEYS : dict [ DataKind , tuple [ tuple [ str , ... ], ... ]] = { rates : ( ( \"symbol\" , \"timeframe\" , \"time\" ), ( \"symbol\" , \"time\" ), ), ticks : (( \"symbol\" , \"time_msc\" ), ( \"symbol\" , \"time\" )), history_orders : ( ( \"ticket\" ,), ( \"symbol\" , \"time\" , \"type\" ), ), history_deals : ( ( \"ticket\" ,), ( \"symbol\" , \"time\" , \"type\" , \"entry\" ), ), } KNOWN_MT5_TIME_COLUMNS module-attribute \u00b6 KNOWN_MT5_TIME_COLUMNS : Final [ frozenset [ str ]] = frozenset ({ \"time\" , \"time_setup\" , \"time_setup_msc\" , \"time_done\" , \"time_done_msc\" , \"time_msc\" , }) REQUIRED_COLUMNS module-attribute \u00b6 REQUIRED_COLUMNS : dict [ DataKind , frozenset [ str ]] = { rates : frozenset ({ \"time\" , \"open\" , \"high\" , \"low\" , \"close\" , \"tick_volume\" , \"spread\" , \"real_volume\" , }), ticks : frozenset ({ \"time\" , \"bid\" , \"ask\" , \"last\" , \"volume\" , \"time_msc\" , \"flags\" , \"volume_real\" , }), orders : frozenset ({ \"ticket\" , \"time_setup\" , \"type\" , \"state\" , \"symbol\" , \"volume_current\" , \"price_open\" , }), positions : frozenset ({ \"ticket\" , \"time\" , \"type\" , \"symbol\" , \"volume\" , \"price_open\" , \"price_current\" , \"profit\" , }), history_orders : frozenset ({ \"ticket\" , \"time_setup\" , \"type\" , \"state\" , \"symbol\" , \"volume_initial\" , \"price_open\" , }), history_deals : frozenset ({ \"ticket\" , \"order\" , \"time\" , \"type\" , \"entry\" , \"symbol\" , \"volume\" , \"price\" , \"profit\" , }), } TIME_COLUMNS module-attribute \u00b6 TIME_COLUMNS : dict [ DataKind , frozenset [ str ]] = { kind : ( REQUIRED_COLUMNS [ kind ] & _TIME_COLUMN_NAMES | get ( kind , frozenset ()) ) for kind in DataKind } __all__ module-attribute \u00b6 __all__ = [ \"DEDUP_KEYS\" , \"KNOWN_MT5_TIME_COLUMNS\" , \"REQUIRED_COLUMNS\" , \"TIME_COLUMNS\" , \"DataKind\" , \"normalize_dataframe\" , \"normalize_time_columns\" , \"schema_columns\" , \"validate_schema\" , ] DataKind \u00b6 Bases: StrEnum Supported MT5 dataset kinds with canonical column contracts. history_deals class-attribute instance-attribute \u00b6 history_deals = 'history_deals' history_orders class-attribute instance-attribute \u00b6 history_orders = 'history_orders' orders class-attribute instance-attribute \u00b6 orders = 'orders' positions class-attribute instance-attribute \u00b6 positions = 'positions' rates class-attribute instance-attribute \u00b6 rates = 'rates' ticks class-attribute instance-attribute \u00b6 ticks = 'ticks' ensure_utc_columns \u00b6 ensure_utc_columns ( frame : DataFrame , columns : Iterable [ str ] ) -> DataFrame Return a copy with selected columns coerced to UTC datetimes. Parameters: Name Type Description Default frame DataFrame Source DataFrame. required columns Iterable [ str ] Column names to coerce. required Returns: Type Description DataFrame DataFrame copy with UTC-aware datetime columns. Source code in mt5cli/schemas.py 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 def ensure_utc_columns ( frame : pd . DataFrame , columns : Iterable [ str ]) -> pd . DataFrame : \"\"\"Return a copy with selected columns coerced to UTC datetimes. Args: frame: Source DataFrame. columns: Column names to coerce. Returns: DataFrame copy with UTC-aware datetime columns. \"\"\" normalized = frame . copy () for column in columns : if column not in normalized . columns : continue if column in _TIME_COLUMN_NAMES : normalized [ column ] = _coerce_mt5_time_column ( normalized [ column ], column ) else : normalized [ column ] = pd . to_datetime ( normalized [ column ], utc = True , errors = \"coerce\" ) return normalized normalize_dataframe \u00b6 normalize_dataframe ( frame : DataFrame , kind : DataKind , * , symbol : str | None = None , timeframe : int | str | None = None , sort : bool = True , ) -> DataFrame Normalize MT5 DataFrame columns, timestamps, and storage metadata. Ensures UTC timestamps, optionally injects symbol / timeframe for storage-oriented datasets, and sorts chronologically when a time column exists. Parameters: Name Type Description Default frame DataFrame Source DataFrame from MT5 or pdmt5. required kind DataKind Dataset kind guiding normalization rules. required symbol str | None Optional symbol to inject when missing. None timeframe int | str | None Optional timeframe integer or name to inject for rates. None sort bool Whether to sort by time or time_msc when present. True Returns: Type Description DataFrame Normalized DataFrame copy. Source code in mt5cli/schemas.py 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 def normalize_dataframe ( frame : pd . DataFrame , kind : DataKind , * , symbol : str | None = None , timeframe : int | str | None = None , sort : bool = True , ) -> pd . DataFrame : \"\"\"Normalize MT5 DataFrame columns, timestamps, and storage metadata. Ensures UTC timestamps, optionally injects ``symbol`` / ``timeframe`` for storage-oriented datasets, and sorts chronologically when a ``time`` column exists. Args: frame: Source DataFrame from MT5 or pdmt5. kind: Dataset kind guiding normalization rules. symbol: Optional symbol to inject when missing. timeframe: Optional timeframe integer or name to inject for rates. sort: Whether to sort by ``time`` or ``time_msc`` when present. Returns: Normalized DataFrame copy. \"\"\" if frame . empty and len ( frame . columns ) == 0 : return frame . copy () normalized = normalize_time_columns ( frame , kind ) if symbol is not None and \"symbol\" not in normalized . columns : normalized . insert ( 0 , \"symbol\" , normalize_symbol ( symbol )) if timeframe is not None and kind is DataKind . rates : tf = parse_timeframe ( timeframe ) if \"timeframe\" not in normalized . columns : insert_at = 1 if \"symbol\" in normalized . columns else 0 normalized . insert ( insert_at , \"timeframe\" , tf ) validate_schema ( normalized , kind ) if sort : if \"time\" in normalized . columns : normalized = normalized . sort_values ( \"time\" , kind = \"stable\" ) elif \"time_msc\" in normalized . columns : normalized = normalized . sort_values ( \"time_msc\" , kind = \"stable\" ) normalized = normalized . reset_index ( drop = True ) return normalized normalize_time_columns \u00b6 normalize_time_columns ( frame : DataFrame , kind : DataKind ) -> DataFrame Coerce dataset time columns to UTC-aware datetimes when present. Any column in :data: KNOWN_MT5_TIME_COLUMNS that is present in frame is normalized. Numeric MT5 epoch values use seconds for time , time_setup , and time_done , and milliseconds for *_msc columns. Parameters: Name Type Description Default frame DataFrame Source DataFrame from MT5 or pdmt5. required kind DataKind Dataset kind (retained for API compatibility). required Returns: Type Description DataFrame DataFrame copy with normalized time columns. Source code in mt5cli/schemas.py 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 def normalize_time_columns ( frame : pd . DataFrame , kind : DataKind ) -> pd . DataFrame : \"\"\"Coerce dataset time columns to UTC-aware datetimes when present. Any column in :data:`KNOWN_MT5_TIME_COLUMNS` that is present in ``frame`` is normalized. Numeric MT5 epoch values use seconds for ``time``, ``time_setup``, and ``time_done``, and milliseconds for ``*_msc`` columns. Args: frame: Source DataFrame from MT5 or pdmt5. kind: Dataset kind (retained for API compatibility). Returns: DataFrame copy with normalized time columns. \"\"\" del kind normalized = frame . copy () for column in normalized . columns : if column not in _TIME_COLUMN_NAMES : continue normalized [ column ] = _coerce_mt5_time_column ( normalized [ column ], column ) return normalized schema_columns \u00b6 schema_columns ( kind : DataKind ) -> frozenset [ str ] Return required column names for a dataset kind. Parameters: Name Type Description Default kind DataKind Dataset kind. required Returns: Type Description frozenset [ str ] Required column names for kind . Source code in mt5cli/schemas.py 141 142 143 144 145 146 147 148 149 150 def schema_columns ( kind : DataKind ) -> frozenset [ str ]: \"\"\"Return required column names for a dataset kind. Args: kind: Dataset kind. Returns: Required column names for ``kind``. \"\"\" return REQUIRED_COLUMNS [ kind ] validate_schema \u00b6 validate_schema ( frame : DataFrame , kind : DataKind , * , extra_required : Iterable [ str ] | None = None , ) -> None Validate that a DataFrame includes required columns for a dataset kind. Parameters: Name Type Description Default frame DataFrame DataFrame to validate. required kind DataKind Expected dataset kind. required extra_required Iterable [ str ] | None Additional columns that must be present (for example symbol and timeframe on stored rate history). None Raises: Type Description Mt5SchemaError If required columns are missing. Source code in mt5cli/schemas.py 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 def validate_schema ( frame : pd . DataFrame , kind : DataKind , * , extra_required : Iterable [ str ] | None = None , ) -> None : \"\"\"Validate that a DataFrame includes required columns for a dataset kind. Args: frame: DataFrame to validate. kind: Expected dataset kind. extra_required: Additional columns that must be present (for example ``symbol`` and ``timeframe`` on stored rate history). Raises: Mt5SchemaError: If required columns are missing. \"\"\" if frame . empty and len ( frame . columns ) == 0 : return required = set ( REQUIRED_COLUMNS [ kind ]) if extra_required is not None : required . update ( extra_required ) missing = required - set ( frame . columns ) if missing : msg = ( f \" { kind . value } schema is missing required columns: \" f \" { ', ' . join ( sorted ( missing )) } .\" ) raise Mt5SchemaError ( msg )","title":"Schemas"},{"location":"api/schemas/#schemas","text":"","title":"Schemas"},{"location":"api/schemas/#mt5cli.schemas","text":"Canonical DataFrame schemas for MT5 market and account datasets.","title":"schemas"},{"location":"api/schemas/#mt5cli.schemas.DEDUP_KEYS","text":"DEDUP_KEYS : dict [ DataKind , tuple [ tuple [ str , ... ], ... ]] = { rates : ( ( \"symbol\" , \"timeframe\" , \"time\" ), ( \"symbol\" , \"time\" ), ), ticks : (( \"symbol\" , \"time_msc\" ), ( \"symbol\" , \"time\" )), history_orders : ( ( \"ticket\" ,), ( \"symbol\" , \"time\" , \"type\" ), ), history_deals : ( ( \"ticket\" ,), ( \"symbol\" , \"time\" , \"type\" , \"entry\" ), ), }","title":"DEDUP_KEYS"},{"location":"api/schemas/#mt5cli.schemas.KNOWN_MT5_TIME_COLUMNS","text":"KNOWN_MT5_TIME_COLUMNS : Final [ frozenset [ str ]] = frozenset ({ \"time\" , \"time_setup\" , \"time_setup_msc\" , \"time_done\" , \"time_done_msc\" , \"time_msc\" , })","title":"KNOWN_MT5_TIME_COLUMNS"},{"location":"api/schemas/#mt5cli.schemas.REQUIRED_COLUMNS","text":"REQUIRED_COLUMNS : dict [ DataKind , frozenset [ str ]] = { rates : frozenset ({ \"time\" , \"open\" , \"high\" , \"low\" , \"close\" , \"tick_volume\" , \"spread\" , \"real_volume\" , }), ticks : frozenset ({ \"time\" , \"bid\" , \"ask\" , \"last\" , \"volume\" , \"time_msc\" , \"flags\" , \"volume_real\" , }), orders : frozenset ({ \"ticket\" , \"time_setup\" , \"type\" , \"state\" , \"symbol\" , \"volume_current\" , \"price_open\" , }), positions : frozenset ({ \"ticket\" , \"time\" , \"type\" , \"symbol\" , \"volume\" , \"price_open\" , \"price_current\" , \"profit\" , }), history_orders : frozenset ({ \"ticket\" , \"time_setup\" , \"type\" , \"state\" , \"symbol\" , \"volume_initial\" , \"price_open\" , }), history_deals : frozenset ({ \"ticket\" , \"order\" , \"time\" , \"type\" , \"entry\" , \"symbol\" , \"volume\" , \"price\" , \"profit\" , }), }","title":"REQUIRED_COLUMNS"},{"location":"api/schemas/#mt5cli.schemas.TIME_COLUMNS","text":"TIME_COLUMNS : dict [ DataKind , frozenset [ str ]] = { kind : ( REQUIRED_COLUMNS [ kind ] & _TIME_COLUMN_NAMES | get ( kind , frozenset ()) ) for kind in DataKind }","title":"TIME_COLUMNS"},{"location":"api/schemas/#mt5cli.schemas.__all__","text":"__all__ = [ \"DEDUP_KEYS\" , \"KNOWN_MT5_TIME_COLUMNS\" , \"REQUIRED_COLUMNS\" , \"TIME_COLUMNS\" , \"DataKind\" , \"normalize_dataframe\" , \"normalize_time_columns\" , \"schema_columns\" , \"validate_schema\" , ]","title":"__all__"},{"location":"api/schemas/#mt5cli.schemas.DataKind","text":"Bases: StrEnum Supported MT5 dataset kinds with canonical column contracts.","title":"DataKind"},{"location":"api/schemas/#mt5cli.schemas.DataKind.history_deals","text":"history_deals = 'history_deals'","title":"history_deals"},{"location":"api/schemas/#mt5cli.schemas.DataKind.history_orders","text":"history_orders = 'history_orders'","title":"history_orders"},{"location":"api/schemas/#mt5cli.schemas.DataKind.orders","text":"orders = 'orders'","title":"orders"},{"location":"api/schemas/#mt5cli.schemas.DataKind.positions","text":"positions = 'positions'","title":"positions"},{"location":"api/schemas/#mt5cli.schemas.DataKind.rates","text":"rates = 'rates'","title":"rates"},{"location":"api/schemas/#mt5cli.schemas.DataKind.ticks","text":"ticks = 'ticks'","title":"ticks"},{"location":"api/schemas/#mt5cli.schemas.ensure_utc_columns","text":"ensure_utc_columns ( frame : DataFrame , columns : Iterable [ str ] ) -> DataFrame Return a copy with selected columns coerced to UTC datetimes. Parameters: Name Type Description Default frame DataFrame Source DataFrame. required columns Iterable [ str ] Column names to coerce. required Returns: Type Description DataFrame DataFrame copy with UTC-aware datetime columns. Source code in mt5cli/schemas.py 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 def ensure_utc_columns ( frame : pd . DataFrame , columns : Iterable [ str ]) -> pd . DataFrame : \"\"\"Return a copy with selected columns coerced to UTC datetimes. Args: frame: Source DataFrame. columns: Column names to coerce. Returns: DataFrame copy with UTC-aware datetime columns. \"\"\" normalized = frame . copy () for column in columns : if column not in normalized . columns : continue if column in _TIME_COLUMN_NAMES : normalized [ column ] = _coerce_mt5_time_column ( normalized [ column ], column ) else : normalized [ column ] = pd . to_datetime ( normalized [ column ], utc = True , errors = \"coerce\" ) return normalized","title":"ensure_utc_columns"},{"location":"api/schemas/#mt5cli.schemas.normalize_dataframe","text":"normalize_dataframe ( frame : DataFrame , kind : DataKind , * , symbol : str | None = None , timeframe : int | str | None = None , sort : bool = True , ) -> DataFrame Normalize MT5 DataFrame columns, timestamps, and storage metadata. Ensures UTC timestamps, optionally injects symbol / timeframe for storage-oriented datasets, and sorts chronologically when a time column exists. Parameters: Name Type Description Default frame DataFrame Source DataFrame from MT5 or pdmt5. required kind DataKind Dataset kind guiding normalization rules. required symbol str | None Optional symbol to inject when missing. None timeframe int | str | None Optional timeframe integer or name to inject for rates. None sort bool Whether to sort by time or time_msc when present. True Returns: Type Description DataFrame Normalized DataFrame copy. Source code in mt5cli/schemas.py 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 def normalize_dataframe ( frame : pd . DataFrame , kind : DataKind , * , symbol : str | None = None , timeframe : int | str | None = None , sort : bool = True , ) -> pd . DataFrame : \"\"\"Normalize MT5 DataFrame columns, timestamps, and storage metadata. Ensures UTC timestamps, optionally injects ``symbol`` / ``timeframe`` for storage-oriented datasets, and sorts chronologically when a ``time`` column exists. Args: frame: Source DataFrame from MT5 or pdmt5. kind: Dataset kind guiding normalization rules. symbol: Optional symbol to inject when missing. timeframe: Optional timeframe integer or name to inject for rates. sort: Whether to sort by ``time`` or ``time_msc`` when present. Returns: Normalized DataFrame copy. \"\"\" if frame . empty and len ( frame . columns ) == 0 : return frame . copy () normalized = normalize_time_columns ( frame , kind ) if symbol is not None and \"symbol\" not in normalized . columns : normalized . insert ( 0 , \"symbol\" , normalize_symbol ( symbol )) if timeframe is not None and kind is DataKind . rates : tf = parse_timeframe ( timeframe ) if \"timeframe\" not in normalized . columns : insert_at = 1 if \"symbol\" in normalized . columns else 0 normalized . insert ( insert_at , \"timeframe\" , tf ) validate_schema ( normalized , kind ) if sort : if \"time\" in normalized . columns : normalized = normalized . sort_values ( \"time\" , kind = \"stable\" ) elif \"time_msc\" in normalized . columns : normalized = normalized . sort_values ( \"time_msc\" , kind = \"stable\" ) normalized = normalized . reset_index ( drop = True ) return normalized","title":"normalize_dataframe"},{"location":"api/schemas/#mt5cli.schemas.normalize_time_columns","text":"normalize_time_columns ( frame : DataFrame , kind : DataKind ) -> DataFrame Coerce dataset time columns to UTC-aware datetimes when present. Any column in :data: KNOWN_MT5_TIME_COLUMNS that is present in frame is normalized. Numeric MT5 epoch values use seconds for time , time_setup , and time_done , and milliseconds for *_msc columns. Parameters: Name Type Description Default frame DataFrame Source DataFrame from MT5 or pdmt5. required kind DataKind Dataset kind (retained for API compatibility). required Returns: Type Description DataFrame DataFrame copy with normalized time columns. Source code in mt5cli/schemas.py 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 def normalize_time_columns ( frame : pd . DataFrame , kind : DataKind ) -> pd . DataFrame : \"\"\"Coerce dataset time columns to UTC-aware datetimes when present. Any column in :data:`KNOWN_MT5_TIME_COLUMNS` that is present in ``frame`` is normalized. Numeric MT5 epoch values use seconds for ``time``, ``time_setup``, and ``time_done``, and milliseconds for ``*_msc`` columns. Args: frame: Source DataFrame from MT5 or pdmt5. kind: Dataset kind (retained for API compatibility). Returns: DataFrame copy with normalized time columns. \"\"\" del kind normalized = frame . copy () for column in normalized . columns : if column not in _TIME_COLUMN_NAMES : continue normalized [ column ] = _coerce_mt5_time_column ( normalized [ column ], column ) return normalized","title":"normalize_time_columns"},{"location":"api/schemas/#mt5cli.schemas.schema_columns","text":"schema_columns ( kind : DataKind ) -> frozenset [ str ] Return required column names for a dataset kind. Parameters: Name Type Description Default kind DataKind Dataset kind. required Returns: Type Description frozenset [ str ] Required column names for kind . Source code in mt5cli/schemas.py 141 142 143 144 145 146 147 148 149 150 def schema_columns ( kind : DataKind ) -> frozenset [ str ]: \"\"\"Return required column names for a dataset kind. Args: kind: Dataset kind. Returns: Required column names for ``kind``. \"\"\" return REQUIRED_COLUMNS [ kind ]","title":"schema_columns"},{"location":"api/schemas/#mt5cli.schemas.validate_schema","text":"validate_schema ( frame : DataFrame , kind : DataKind , * , extra_required : Iterable [ str ] | None = None , ) -> None Validate that a DataFrame includes required columns for a dataset kind. Parameters: Name Type Description Default frame DataFrame DataFrame to validate. required kind DataKind Expected dataset kind. required extra_required Iterable [ str ] | None Additional columns that must be present (for example symbol and timeframe on stored rate history). None Raises: Type Description Mt5SchemaError If required columns are missing. Source code in mt5cli/schemas.py 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 def validate_schema ( frame : pd . DataFrame , kind : DataKind , * , extra_required : Iterable [ str ] | None = None , ) -> None : \"\"\"Validate that a DataFrame includes required columns for a dataset kind. Args: frame: DataFrame to validate. kind: Expected dataset kind. extra_required: Additional columns that must be present (for example ``symbol`` and ``timeframe`` on stored rate history). Raises: Mt5SchemaError: If required columns are missing. \"\"\" if frame . empty and len ( frame . columns ) == 0 : return required = set ( REQUIRED_COLUMNS [ kind ]) if extra_required is not None : required . update ( extra_required ) missing = required - set ( frame . columns ) if missing : msg = ( f \" { kind . value } schema is missing required columns: \" f \" { ', ' . join ( sorted ( missing )) } .\" ) raise Mt5SchemaError ( msg )","title":"validate_schema"},{"location":"api/sdk/","text":"SDK Module \u00b6 mt5cli.sdk \u00b6 Programmatic SDK for MetaTrader 5 data collection. T module-attribute \u00b6 T = TypeVar ( 'T' ) UpdateHistoryBackend module-attribute \u00b6 UpdateHistoryBackend = Callable [ ... , None ] __all__ module-attribute \u00b6 __all__ = [ \"AccountSpec\" , \"Mt5CliClient\" , \"ThrottledHistoryUpdater\" , \"account_info\" , \"build_config\" , \"collect_history\" , \"collect_latest_closed_rates_by_granularity\" , \"collect_latest_closed_rates_for_accounts\" , \"collect_latest_rates\" , \"collect_latest_rates_for_accounts\" , \"collect_latest_rates_for_accounts_with_retries\" , \"connected_client\" , \"copy_rates_from\" , \"copy_rates_from_pos\" , \"copy_rates_range\" , \"copy_ticks_from\" , \"copy_ticks_range\" , \"fetch_latest_closed_rates\" , \"history_deals\" , \"history_orders\" , \"last_error\" , \"latest_rates\" , \"market_book\" , \"minimum_margins\" , \"mt5_session\" , \"mt5_summary\" , \"mt5_summary_as_df\" , \"orders\" , \"positions\" , \"recent_history_deals\" , \"recent_ticks\" , \"resolve_account_spec\" , \"resolve_account_specs\" , \"substitute_env_placeholders\" , \"substitute_mapping_values\" , \"symbol_info\" , \"symbol_info_tick\" , \"symbols\" , \"terminal_info\" , \"update_history\" , \"update_history_with_config\" , \"version\" , ] logger module-attribute \u00b6 logger = getLogger ( __name__ ) AccountSpec dataclass \u00b6 AccountSpec ( symbols : Sequence [ str ], login : int | str | None = None , password : str | None = None , server : str | None = None , path : str | None = None , timeout : int | None = None , ) Connection parameters and symbols for one MT5 account group. Attributes: Name Type Description symbols Sequence [ str ] Symbols to load latest rates for under this account. login int | str | None Trading account login. String values are coerced to int when non-empty. password str | None Trading account password. server str | None Trading server name. path str | None Path to the MetaTrader5 terminal EXE file. timeout int | None Connection timeout in milliseconds. login class-attribute instance-attribute \u00b6 login : int | str | None = field ( default = None , repr = False ) password class-attribute instance-attribute \u00b6 password : str | None = field ( default = None , repr = False ) path class-attribute instance-attribute \u00b6 path : str | None = None server class-attribute instance-attribute \u00b6 server : str | None = None symbols instance-attribute \u00b6 symbols : Sequence [ str ] timeout class-attribute instance-attribute \u00b6 timeout : int | None = None Mt5CliClient \u00b6 Mt5CliClient ( * , path : str | None = None , login : int | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , retry_count : int = 3 , config : Mt5Config | None = None , client : Mt5DataClient | None = None , ) Programmatic client for read-only MetaTrader 5 data access. Initialize the SDK client. Parameters: Name Type Description Default path str | None Path to MetaTrader5 terminal EXE file. None login int | None Trading account login. None password str | None Trading account password. None server str | None Trading server name. None timeout int | None Connection timeout in milliseconds. None retry_count int Number of MT5 initialization retries for sessions opened by this client. 3 config Mt5Config | None Optional pre-built Mt5Config (overrides other args). None client Mt5DataClient | None Optional already-connected Mt5DataClient . Injected clients are reused as-is and are not initialized or shut down. None Source code in mt5cli/sdk.py 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 def __init__ ( self , * , path : str | None = None , login : int | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , retry_count : int = 3 , config : Mt5Config | None = None , client : Mt5DataClient | None = None , ) -> None : \"\"\"Initialize the SDK client. Args: path: Path to MetaTrader5 terminal EXE file. login: Trading account login. password: Trading account password. server: Trading server name. timeout: Connection timeout in milliseconds. retry_count: Number of MT5 initialization retries for sessions opened by this client. config: Optional pre-built ``Mt5Config`` (overrides other args). client: Optional already-connected ``Mt5DataClient``. Injected clients are reused as-is and are not initialized or shut down. \"\"\" self . _config = config or build_config ( path = path , login = login , password = password , server = server , timeout = timeout , ) self . _retry_count = retry_count self . _client = client self . _owns_client = client is None config property \u00b6 config : Mt5Config Return the underlying MT5 configuration. __enter__ \u00b6 __enter__ () -> Self Open a persistent MT5 connection for multiple calls. Returns: Type Description Self This client instance. Source code in mt5cli/sdk.py 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 def __enter__ ( self ) -> Self : \"\"\"Open a persistent MT5 connection for multiple calls. Returns: This client instance. \"\"\" if self . _client is not None : return self client = Mt5DataClient ( config = self . _config , retry_count = self . _retry_count ) try : client . initialize_and_login_mt5 () except Exception : client . shutdown () raise self . _client = client self . _owns_client = True # only set when this method created the client return self __exit__ \u00b6 __exit__ ( exc_type : type [ BaseException ] | None , exc : BaseException | None , tb : object , ) -> None Shut down the persistent MT5 connection. Source code in mt5cli/sdk.py 486 487 488 489 490 491 492 493 494 495 def __exit__ ( self , exc_type : type [ BaseException ] | None , exc : BaseException | None , tb : object , ) -> None : \"\"\"Shut down the persistent MT5 connection.\"\"\" if self . _client is not None and self . _owns_client : self . _client . shutdown () self . _client = None account_info \u00b6 account_info () -> DataFrame Return account information. Source code in mt5cli/sdk.py 649 650 651 def account_info ( self ) -> pd . DataFrame : \"\"\"Return account information.\"\"\" return self . _fetch ( lambda c : c . account_info_as_df ()) collect_latest_rates \u00b6 collect_latest_rates ( symbols : Sequence [ str ], timeframes : Sequence [ int | str ], * , count : int , start_pos : int = 0 , ) -> dict [ tuple [ str , int ], DataFrame ] Return latest rates for each symbol/timeframe pair. Returns: Type Description dict [ tuple [ str , int ], DataFrame ] Mapping keyed by (symbol, timeframe_int) . Raises: Type Description ValueError If count is not positive or inputs are empty. Source code in mt5cli/sdk.py 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 def collect_latest_rates ( self , symbols : Sequence [ str ], timeframes : Sequence [ int | str ], * , count : int , start_pos : int = 0 , ) -> dict [ tuple [ str , int ], pd . DataFrame ]: \"\"\"Return latest rates for each symbol/timeframe pair. Returns: Mapping keyed by ``(symbol, timeframe_int)``. Raises: ValueError: If ``count`` is not positive or inputs are empty. \"\"\" _require_positive ( count , \"count\" ) if not symbols : msg = \"At least one symbol is required.\" raise ValueError ( msg ) if not timeframes : msg = \"At least one timeframe is required.\" raise ValueError ( msg ) resolved_timeframes = [ _coerce_timeframe ( timeframe ) for timeframe in timeframes ] return self . _fetch_value ( lambda c : { ( symbol , timeframe ): c . copy_rates_from_pos_as_df ( symbol = symbol , timeframe = timeframe , start_pos = start_pos , count = count , ) for symbol in symbols for timeframe in resolved_timeframes }, ) copy_rates_from \u00b6 copy_rates_from ( symbol : str , timeframe : int | str , date_from : datetime | str , count : int , ) -> DataFrame Return rates starting from a date. Source code in mt5cli/sdk.py 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 def copy_rates_from ( self , symbol : str , timeframe : int | str , date_from : datetime | str , count : int , ) -> pd . DataFrame : \"\"\"Return rates starting from a date.\"\"\" tf = _coerce_timeframe ( timeframe ) start = _require_datetime ( date_from ) return self . _fetch ( lambda c : c . copy_rates_from_as_df ( symbol = symbol , timeframe = tf , date_from = start , count = count , ), ) copy_rates_from_pos \u00b6 copy_rates_from_pos ( symbol : str , timeframe : int | str , start_pos : int , count : int , ) -> DataFrame Return rates starting from a bar position. Source code in mt5cli/sdk.py 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 def copy_rates_from_pos ( self , symbol : str , timeframe : int | str , start_pos : int , count : int , ) -> pd . DataFrame : \"\"\"Return rates starting from a bar position.\"\"\" tf = _coerce_timeframe ( timeframe ) return self . _fetch ( lambda c : c . copy_rates_from_pos_as_df ( symbol = symbol , timeframe = tf , start_pos = start_pos , count = count , ), ) copy_rates_range \u00b6 copy_rates_range ( symbol : str , timeframe : int | str , date_from : datetime | str , date_to : datetime | str , ) -> DataFrame Return rates for a date range. Source code in mt5cli/sdk.py 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 def copy_rates_range ( self , symbol : str , timeframe : int | str , date_from : datetime | str , date_to : datetime | str , ) -> pd . DataFrame : \"\"\"Return rates for a date range.\"\"\" tf = _coerce_timeframe ( timeframe ) start = _require_datetime ( date_from ) end = _require_datetime ( date_to ) return self . _fetch ( lambda c : c . copy_rates_range_as_df ( symbol = symbol , timeframe = tf , date_from = start , date_to = end , ), ) copy_ticks_from \u00b6 copy_ticks_from ( symbol : str , date_from : datetime | str , count : int , flags : int | str , ) -> DataFrame Return ticks starting from a date. Source code in mt5cli/sdk.py 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 def copy_ticks_from ( self , symbol : str , date_from : datetime | str , count : int , flags : int | str , ) -> pd . DataFrame : \"\"\"Return ticks starting from a date.\"\"\" start = _require_datetime ( date_from ) tick_flags = _coerce_tick_flags ( flags ) return self . _fetch ( lambda c : c . copy_ticks_from_as_df ( symbol = symbol , date_from = start , count = count , flags = tick_flags , ), ) copy_ticks_range \u00b6 copy_ticks_range ( symbol : str , date_from : datetime | str , date_to : datetime | str , flags : int | str , ) -> DataFrame Return ticks for a date range. Source code in mt5cli/sdk.py 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 def copy_ticks_range ( self , symbol : str , date_from : datetime | str , date_to : datetime | str , flags : int | str , ) -> pd . DataFrame : \"\"\"Return ticks for a date range.\"\"\" start = _require_datetime ( date_from ) end = _require_datetime ( date_to ) tick_flags = _coerce_tick_flags ( flags ) return self . _fetch ( lambda c : c . copy_ticks_range_as_df ( symbol = symbol , date_from = start , date_to = end , flags = tick_flags , ), ) from_connected_client classmethod \u00b6 from_connected_client ( client : Mt5DataClient ) -> Self Bind to an already-connected Mt5DataClient without owning it. The returned Mt5CliClient never initializes or shuts down the injected client, including when used as a context manager. Returns: Type Description Self Client wrapper bound to the injected connection. Source code in mt5cli/sdk.py 451 452 453 454 455 456 457 458 459 460 461 @classmethod def from_connected_client ( cls , client : Mt5DataClient ) -> Self : \"\"\"Bind to an already-connected ``Mt5DataClient`` without owning it. The returned ``Mt5CliClient`` never initializes or shuts down the injected client, including when used as a context manager. Returns: Client wrapper bound to the injected connection. \"\"\" return cls ( client = client ) history_deals \u00b6 history_deals ( date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , ) -> DataFrame Return historical deals. Source code in mt5cli/sdk.py 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 def history_deals ( self , date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , ) -> pd . DataFrame : \"\"\"Return historical deals.\"\"\" start = _coerce_datetime ( date_from ) end = _coerce_datetime ( date_to ) return self . _fetch ( lambda c : c . history_deals_get_as_df ( date_from = start , date_to = end , group = group , symbol = symbol , ticket = ticket , position = position , ), ) history_orders \u00b6 history_orders ( date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , ) -> DataFrame Return historical orders. Source code in mt5cli/sdk.py 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 def history_orders ( self , date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , ) -> pd . DataFrame : \"\"\"Return historical orders.\"\"\" start = _coerce_datetime ( date_from ) end = _coerce_datetime ( date_to ) return self . _fetch ( lambda c : c . history_orders_get_as_df ( date_from = start , date_to = end , group = group , symbol = symbol , ticket = ticket , position = position , ), ) last_error \u00b6 last_error () -> DataFrame Return the last error information. Source code in mt5cli/sdk.py 763 764 765 def last_error ( self ) -> pd . DataFrame : \"\"\"Return the last error information.\"\"\" return self . _fetch ( lambda c : c . last_error_as_df ()) latest_rates \u00b6 latest_rates ( symbol : str , timeframe : int | str , count : int , start_pos : int = 0 , ) -> DataFrame Return the latest rates from a bar position. Source code in mt5cli/sdk.py 542 543 544 545 546 547 548 549 550 551 def latest_rates ( self , symbol : str , timeframe : int | str , count : int , start_pos : int = 0 , ) -> pd . DataFrame : \"\"\"Return the latest rates from a bar position.\"\"\" _require_positive ( count , \"count\" ) return self . copy_rates_from_pos ( symbol , timeframe , start_pos , count ) market_book \u00b6 market_book ( symbol : str ) -> DataFrame Return market depth for a symbol. Source code in mt5cli/sdk.py 771 772 773 def market_book ( self , symbol : str ) -> pd . DataFrame : \"\"\"Return market depth for a symbol.\"\"\" return self . _fetch ( lambda c : c . market_book_get_as_df ( symbol = symbol )) minimum_margins \u00b6 minimum_margins ( symbol : str ) -> DataFrame Return minimum-volume buy and sell margin requirements. Parameters: Name Type Description Default symbol str Symbol name. required Returns: Type Description DataFrame One-row DataFrame with columns symbol , account_currency , DataFrame volume_min , buy_margin , and sell_margin . Source code in mt5cli/sdk.py 814 815 816 817 818 819 820 821 822 823 824 def minimum_margins ( self , symbol : str ) -> pd . DataFrame : \"\"\"Return minimum-volume buy and sell margin requirements. Args: symbol: Symbol name. Returns: One-row DataFrame with columns ``symbol``, ``account_currency``, ``volume_min``, ``buy_margin``, and ``sell_margin``. \"\"\" return self . _fetch ( lambda c : _fetch_minimum_margins ( c , symbol )) mt5_summary \u00b6 mt5_summary () -> dict [ str , object ] Return a compact terminal/account status summary. Source code in mt5cli/sdk.py 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 def mt5_summary ( self ) -> dict [ str , object ]: \"\"\"Return a compact terminal/account status summary.\"\"\" def _summary ( client : Mt5DataClient ) -> dict [ str , object ]: return { \"version\" : _plain_mt5_value ( _call_required_client_method ( client , \"version\" ), ), \"terminal_info\" : _plain_mt5_value ( _call_required_client_method ( client , \"terminal_info\" ), ), \"account_info\" : _plain_mt5_value ( _call_required_client_method ( client , \"account_info\" ), ), \"symbols_total\" : _plain_mt5_value ( _call_required_client_method ( client , \"symbols_total\" ), ), } return self . _fetch_value ( _summary ) mt5_summary_as_df \u00b6 mt5_summary_as_df () -> DataFrame Return an export-safe one-row terminal/account summary DataFrame. Source code in mt5cli/sdk.py 847 848 849 850 851 852 853 854 855 856 857 def mt5_summary_as_df ( self ) -> pd . DataFrame : \"\"\"Return an export-safe one-row terminal/account summary DataFrame.\"\"\" summary = self . mt5_summary () return pd . DataFrame ( [ { key : _mt5_summary_export_value ( value ) for key , value in summary . items () }, ], ) orders \u00b6 orders ( symbol : str | None = None , group : str | None = None , ticket : int | None = None , ) -> DataFrame Return active orders. Source code in mt5cli/sdk.py 665 666 667 668 669 670 671 672 673 674 675 676 677 678 def orders ( self , symbol : str | None = None , group : str | None = None , ticket : int | None = None , ) -> pd . DataFrame : \"\"\"Return active orders.\"\"\" return self . _fetch ( lambda c : c . orders_get_as_df ( symbol = symbol , group = group , ticket = ticket , ), ) positions \u00b6 positions ( symbol : str | None = None , group : str | None = None , ticket : int | None = None , ) -> DataFrame Return open positions. Source code in mt5cli/sdk.py 680 681 682 683 684 685 686 687 688 689 690 691 692 693 def positions ( self , symbol : str | None = None , group : str | None = None , ticket : int | None = None , ) -> pd . DataFrame : \"\"\"Return open positions.\"\"\" return self . _fetch ( lambda c : c . positions_get_as_df ( symbol = symbol , group = group , ticket = ticket , ), ) recent_history_deals \u00b6 recent_history_deals ( hours : float , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ) -> DataFrame Return historical deals from a recent trailing window. Source code in mt5cli/sdk.py 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 def recent_history_deals ( self , hours : float , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ) -> pd . DataFrame : \"\"\"Return historical deals from a recent trailing window.\"\"\" _require_positive ( hours , \"hours\" ) end = _require_datetime ( date_to ) if date_to is not None else datetime . now ( UTC ) start = end - timedelta ( hours = hours ) return self . history_deals ( date_from = start , date_to = end , group = group , symbol = symbol , ) recent_ticks \u00b6 recent_ticks ( symbol : str , seconds : float , * , date_to : datetime | str | None = None , count : int = 10000 , flags : int | str = \"ALL\" , ) -> DataFrame Return ticks from a recent time window. Parameters: Name Type Description Default symbol str Symbol name. required seconds float Lookback window in seconds ending at date_to . required date_to datetime | str | None Window end time. When None , uses the latest symbol_info_tick().time rather than wall-clock now. None count int Maximum ticks to return. Values <= 0 return the full window without trimming. Positive values keep the most recent ticks; when the window is sparse, copy_ticks_from avoids fetching the entire range. 10000 flags int | str Tick flags as ALL , INFO , TRADE , or an integer. 'ALL' Returns: Type Description DataFrame Tick DataFrame with MT5 tick columns such as time , bid , DataFrame ask , last , and volume . Source code in mt5cli/sdk.py 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 def recent_ticks ( self , symbol : str , seconds : float , * , date_to : datetime | str | None = None , count : int = 10000 , flags : int | str = \"ALL\" , ) -> pd . DataFrame : \"\"\"Return ticks from a recent time window. Args: symbol: Symbol name. seconds: Lookback window in seconds ending at ``date_to``. date_to: Window end time. When ``None``, uses the latest ``symbol_info_tick().time`` rather than wall-clock now. count: Maximum ticks to return. Values ``<= 0`` return the full window without trimming. Positive values keep the most recent ticks; when the window is sparse, ``copy_ticks_from`` avoids fetching the entire range. flags: Tick flags as ``ALL``, ``INFO``, ``TRADE``, or an integer. Returns: Tick DataFrame with MT5 tick columns such as ``time``, ``bid``, ``ask``, ``last``, and ``volume``. \"\"\" tick_flags = _coerce_tick_flags ( flags ) end = _coerce_datetime ( date_to ) return self . _fetch ( lambda c : _fetch_recent_ticks ( c , symbol , seconds , end , count , tick_flags , ), ) symbol_info \u00b6 symbol_info ( symbol : str ) -> DataFrame Return details for one symbol. Source code in mt5cli/sdk.py 661 662 663 def symbol_info ( self , symbol : str ) -> pd . DataFrame : \"\"\"Return details for one symbol.\"\"\" return self . _fetch ( lambda c : c . symbol_info_as_df ( symbol = symbol )) symbol_info_tick \u00b6 symbol_info_tick ( symbol : str ) -> DataFrame Return the last tick for a symbol. Source code in mt5cli/sdk.py 767 768 769 def symbol_info_tick ( self , symbol : str ) -> pd . DataFrame : \"\"\"Return the last tick for a symbol.\"\"\" return self . _fetch ( lambda c : c . symbol_info_tick_as_df ( symbol = symbol )) symbols \u00b6 symbols ( group : str | None = None ) -> DataFrame Return the symbol list. Source code in mt5cli/sdk.py 657 658 659 def symbols ( self , group : str | None = None ) -> pd . DataFrame : \"\"\"Return the symbol list.\"\"\" return self . _fetch ( lambda c : c . symbols_get_as_df ( group = group )) terminal_info \u00b6 terminal_info () -> DataFrame Return terminal information. Source code in mt5cli/sdk.py 653 654 655 def terminal_info ( self ) -> pd . DataFrame : \"\"\"Return terminal information.\"\"\" return self . _fetch ( lambda c : c . terminal_info_as_df ()) version \u00b6 version () -> DataFrame Return MetaTrader5 version information. Source code in mt5cli/sdk.py 759 760 761 def version ( self ) -> pd . DataFrame : \"\"\"Return MetaTrader5 version information.\"\"\" return self . _fetch ( lambda c : c . version_as_df ()) ThrottledHistoryUpdater \u00b6 ThrottledHistoryUpdater ( * , output : Path | str , datasets : set [ Dataset ] | None = None , timeframes : Sequence [ int | str ] | None = None , flags : int | str = \"ALL\" , lookback_hours : float = 24.0 , with_views : bool = False , include_account_events : bool = True , interval_seconds : float = 0.0 , suppress_errors : bool = False , update_backend : UpdateHistoryBackend | None = None , ) Throttled incremental SQLite history updater for long-running apps. Wraps :func: update_history (or a custom update_backend ) with a minimum interval between successful updates, so a tight application loop can call :meth: update every iteration without re-fetching MT5 history more often than desired. Timing uses a monotonic clock, so it is unaffected by wall-clock changes. Downstream applications may pass update_backend to substitute the default :func: update_history implementation\u2014for example to add application-specific logging, metrics, or test doubles\u2014without monkey- patching mt5cli.sdk.update_history . Initialize the throttled updater. Parameters: Name Type Description Default output Path | str SQLite database path. required datasets set [ Dataset ] | None Datasets to include (defaults to all). None timeframes Sequence [ int | str ] | None Rate timeframes to update (defaults to all fixed MT5 timeframes). None flags int | str Tick copy flags as integer or name (e.g. ALL ). 'ALL' lookback_hours float First-run lookback when a table has no prior rows. 24.0 with_views bool Create cash_events and positions_reconstructed views. False include_account_events bool Include account-level cash events. True interval_seconds float Minimum seconds between successful updates. Values <= 0 update on every call. 0.0 suppress_errors bool When True, recoverable errors ( Mt5TradingError , Mt5RuntimeError , sqlite3.Error , ValueError , OSError , and MT5 client capability AttributeError / TypeError for history API methods) raised during an update are swallowed and :meth: update returns False without advancing the throttle. Other AttributeError / TypeError values always propagate. When False (default), recoverable errors propagate so callers control logging. False update_backend UpdateHistoryBackend | None Callable invoked instead of :func: update_history when :meth: update runs. Receives the same keyword arguments as :func: update_history ( client , output , symbols , datasets , timeframes , flags , lookback_hours , with_views , include_account_events ). Defaults to :func: update_history . None Source code in mt5cli/sdk.py 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 def __init__ ( self , * , output : Path | str , datasets : set [ Dataset ] | None = None , timeframes : Sequence [ int | str ] | None = None , flags : int | str = \"ALL\" , lookback_hours : float = 24.0 , with_views : bool = False , include_account_events : bool = True , interval_seconds : float = 0.0 , suppress_errors : bool = False , update_backend : UpdateHistoryBackend | None = None , ) -> None : \"\"\"Initialize the throttled updater. Args: output: SQLite database path. datasets: Datasets to include (defaults to all). timeframes: Rate timeframes to update (defaults to all fixed MT5 timeframes). flags: Tick copy flags as integer or name (e.g. ``ALL``). lookback_hours: First-run lookback when a table has no prior rows. with_views: Create ``cash_events`` and ``positions_reconstructed`` views. include_account_events: Include account-level cash events. interval_seconds: Minimum seconds between successful updates. Values ``<= 0`` update on every call. suppress_errors: When True, recoverable errors (``Mt5TradingError``, ``Mt5RuntimeError``, ``sqlite3.Error``, ``ValueError``, ``OSError``, and MT5 client capability ``AttributeError`` / ``TypeError`` for history API methods) raised during an update are swallowed and :meth:`update` returns False without advancing the throttle. Other ``AttributeError`` / ``TypeError`` values always propagate. When False (default), recoverable errors propagate so callers control logging. update_backend: Callable invoked instead of :func:`update_history` when :meth:`update` runs. Receives the same keyword arguments as :func:`update_history` (``client``, ``output``, ``symbols``, ``datasets``, ``timeframes``, ``flags``, ``lookback_hours``, ``with_views``, ``include_account_events``). Defaults to :func:`update_history`. \"\"\" self . output = output self . datasets = datasets self . timeframes = timeframes self . flags = flags self . lookback_hours = lookback_hours self . with_views = with_views self . include_account_events = include_account_events self . interval_seconds = interval_seconds self . suppress_errors = suppress_errors self . update_backend = ( update_history if update_backend is None else update_backend ) self . _last_update_monotonic : float | None = None datasets instance-attribute \u00b6 datasets = datasets flags instance-attribute \u00b6 flags = flags include_account_events instance-attribute \u00b6 include_account_events = include_account_events interval_seconds instance-attribute \u00b6 interval_seconds = interval_seconds last_update_monotonic property \u00b6 last_update_monotonic : float | None Return the monotonic timestamp of the last successful update. lookback_hours instance-attribute \u00b6 lookback_hours = lookback_hours output instance-attribute \u00b6 output = output suppress_errors instance-attribute \u00b6 suppress_errors = suppress_errors timeframes instance-attribute \u00b6 timeframes = timeframes update_backend instance-attribute \u00b6 update_backend = ( update_history if update_backend is None else update_backend ) with_views instance-attribute \u00b6 with_views = with_views should_update \u00b6 should_update () -> bool Return whether enough time has elapsed to run another update. Returns: Type Description bool True when interval_seconds <= 0 , when no update has succeeded bool yet, or when at least interval_seconds have elapsed since the bool last successful update. Source code in mt5cli/sdk.py 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 def should_update ( self ) -> bool : \"\"\"Return whether enough time has elapsed to run another update. Returns: True when ``interval_seconds <= 0``, when no update has succeeded yet, or when at least ``interval_seconds`` have elapsed since the last successful update. \"\"\" if self . interval_seconds <= 0 or self . _last_update_monotonic is None : return True return ( time . monotonic () - self . _last_update_monotonic ) >= self . interval_seconds update \u00b6 update ( client : Mt5DataClient , symbols : Sequence [ str ] ) -> bool Run a throttled incremental history update. Parameters: Name Type Description Default client Mt5DataClient Connected MT5 data client. required symbols Sequence [ str ] Symbols to update. required Returns: Type Description bool True if an update ran successfully, False if it was throttled or bool (when suppress_errors is True) failed with a recoverable error. bool When suppress_errors is False, recoverable update failures bool propagate to the caller. Raises: Type Description AttributeError MT5 client capability mismatch when suppress_errors is False, or any other attribute error. TypeError MT5 client capability mismatch when suppress_errors is False, or any other type error. Source code in mt5cli/sdk.py 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 def update ( self , client : Mt5DataClient , symbols : Sequence [ str ]) -> bool : \"\"\"Run a throttled incremental history update. Args: client: Connected MT5 data client. symbols: Symbols to update. Returns: True if an update ran successfully, False if it was throttled or (when ``suppress_errors`` is True) failed with a recoverable error. When ``suppress_errors`` is False, recoverable update failures propagate to the caller. Raises: AttributeError: MT5 client capability mismatch when ``suppress_errors`` is False, or any other attribute error. TypeError: MT5 client capability mismatch when ``suppress_errors`` is False, or any other type error. \"\"\" if not self . should_update (): return False try : _resolve_update_history_request ( output = self . output , symbols = symbols , datasets = self . datasets , timeframes = self . timeframes , flags = self . flags , lookback_hours = self . lookback_hours , date_to = None , ) self . update_backend ( client = client , output = self . output , symbols = symbols , datasets = self . datasets , timeframes = self . timeframes , flags = self . flags , lookback_hours = self . lookback_hours , with_views = self . with_views , include_account_events = self . include_account_events , ) except _RECOVERABLE_HISTORY_UPDATE_ERRORS : if self . suppress_errors : logger . warning ( \"Suppressed history update error\" , exc_info = True ) return False raise except ( AttributeError , TypeError ) as exc : if self . suppress_errors and _is_mt5_client_capability_error ( exc ): logger . warning ( \"Suppressed history update error\" , exc_info = True ) return False raise self . _last_update_monotonic = time . monotonic () return True account_info \u00b6 account_info ( * , config : Mt5Config | None = None ) -> DataFrame Return account information. Source code in mt5cli/sdk.py 1956 1957 1958 def account_info ( * , config : Mt5Config | None = None ) -> pd . DataFrame : \"\"\"Return account information.\"\"\" return _make_client ( config = config ) . account_info () build_config \u00b6 build_config ( * , path : str | None = None , login : int | str | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , allow_whole_dollar_env : bool = False , ) -> Mt5Config Build an Mt5Config from optional connection parameters. Parameters: Name Type Description Default path str | None Optional terminal executable path. None login int | str | None Optional trading account login. Integers are preserved. String values are coerced: empty or whitespace-only strings become None ; numeric strings such as \"12345\" are converted to int ; non-numeric strings raise ValueError . When allow_whole_dollar_env=True , $ENV_NAME and ${ENV_NAME} placeholders are expanded before coercion. None password str | None Optional trading account password. None server str | None Optional trading server name. None timeout int | None Optional connection timeout in milliseconds. None allow_whole_dollar_env bool When True , string parameters that are exactly $ENV_NAME are expanded from the environment. Applies to path , login , password , and server . Default False preserves existing behavior. False Returns: Type Description Mt5Config Configured Mt5Config instance. Source code in mt5cli/sdk.py 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 def build_config ( * , path : str | None = None , login : int | str | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , allow_whole_dollar_env : bool = False , ) -> Mt5Config : \"\"\"Build an ``Mt5Config`` from optional connection parameters. Args: path: Optional terminal executable path. login: Optional trading account login. Integers are preserved. String values are coerced: empty or whitespace-only strings become ``None``; numeric strings such as ``\"12345\"`` are converted to ``int``; non-numeric strings raise ``ValueError``. When ``allow_whole_dollar_env=True``, ``$ENV_NAME`` and ``${ENV_NAME}`` placeholders are expanded before coercion. password: Optional trading account password. server: Optional trading server name. timeout: Optional connection timeout in milliseconds. allow_whole_dollar_env: When ``True``, string parameters that are exactly ``$ENV_NAME`` are expanded from the environment. Applies to ``path``, ``login``, ``password``, and ``server``. Default ``False`` preserves existing behavior. Returns: Configured ``Mt5Config`` instance. \"\"\" if allow_whole_dollar_env : if path is not None : path = substitute_env_placeholders ( path , allow_whole_dollar_env = True ) if isinstance ( login , str ): login = substitute_env_placeholders ( login , allow_whole_dollar_env = True ) if password is not None : password = substitute_env_placeholders ( password , allow_whole_dollar_env = True ) if server is not None : server = substitute_env_placeholders ( server , allow_whole_dollar_env = True ) return Mt5Config ( path = path , login = _coerce_login ( login ), password = password , server = server , timeout = timeout , ) collect_history \u00b6 collect_history ( output : Path , symbols : list [ str ], date_from : datetime | str , date_to : datetime | str , * , datasets : set [ Dataset ] | None = None , timeframe : int | str = 1 , flags : int | str = \"ALL\" , if_exists : IfExists = FAIL , with_views : bool = False , config : Mt5Config | None = None , ) -> None Collect historical datasets into a single SQLite database. Parameters: Name Type Description Default output Path SQLite database path. required symbols list [ str ] Symbols to collect. required date_from datetime | str Start date. required date_to datetime | str End date. required datasets set [ Dataset ] | None Datasets to include (defaults to all). None timeframe int | str Rates timeframe as integer or name (e.g. M1 ). 1 flags int | str Tick copy flags as integer or name (e.g. ALL ). 'ALL' if_exists IfExists Behavior when a target table already exists. FAIL with_views bool Create cash_events and positions_reconstructed views. False config Mt5Config | None MT5 connection configuration. None Source code in mt5cli/sdk.py 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 def collect_history ( output : Path , symbols : list [ str ], date_from : datetime | str , date_to : datetime | str , * , datasets : set [ Dataset ] | None = None , timeframe : int | str = 1 , flags : int | str = \"ALL\" , if_exists : IfExists = IfExists . FAIL , with_views : bool = False , config : Mt5Config | None = None , ) -> None : \"\"\"Collect historical datasets into a single SQLite database. Args: output: SQLite database path. symbols: Symbols to collect. date_from: Start date. date_to: End date. datasets: Datasets to include (defaults to all). timeframe: Rates timeframe as integer or name (e.g. ``M1``). flags: Tick copy flags as integer or name (e.g. ``ALL``). if_exists: Behavior when a target table already exists. with_views: Create ``cash_events`` and ``positions_reconstructed`` views. config: MT5 connection configuration. \"\"\" start = _require_datetime ( date_from ) end = _require_datetime ( date_to ) selected = datasets if datasets is not None else set ( Dataset ) tf = _coerce_timeframe ( timeframe ) tick_flags = _coerce_tick_flags ( flags ) mt5_config = config or build_config () with connected_client ( mt5_config ) as client , sqlite3 . connect ( output ) as conn : conn . execute ( \"PRAGMA journal_mode=WAL\" ) conn . execute ( \"PRAGMA synchronous=NORMAL\" ) written_tables , written_columns = write_collected_datasets ( conn , client , symbols , selected , tf , tick_flags , start , end , if_exists , ) create_history_indexes ( conn , written_columns ) if with_views and Dataset . history_deals in written_tables : create_cash_events_view ( conn , written_columns [ Dataset . history_deals ]) create_positions_reconstructed_view ( conn , written_columns [ Dataset . history_deals ], ) elif with_views : logger . warning ( \"--with-views ignored: history_deals table was not written\" , ) logger . info ( \"Collected %s for %d symbol(s) into %s \" , \", \" . join ( sorted ( ds . value for ds in selected )), len ( symbols ), output , ) collect_latest_closed_rates_by_granularity \u00b6 collect_latest_closed_rates_by_granularity ( accounts : Sequence [ AccountSpec ], granularities : Sequence [ int | str ], count : int , * , start_pos : int = 0 , base_config : Mt5Config | None = None , retry_count : int = 0 , backoff_base : float = 2.0 , ) -> dict [ tuple [ str , str ], DataFrame ] Collect latest closed rate bars keyed by symbol and granularity name. Thin wrapper around :func: collect_latest_closed_rates_for_accounts that rekeys the result by granularity name (for example M1 ) instead of the integer timeframe. Parameters: Name Type Description Default accounts Sequence [ AccountSpec ] Account groups to read. Each must define at least one symbol. required granularities Sequence [ int | str ] MT5 timeframes as integers or names (for example M1 ). required count int Number of closed bars to return per symbol/timeframe. required start_pos int Initial bar position offset passed to the underlying collector. 0 base_config Mt5Config | None Optional base configuration whose fields fill any value not set on an individual account. None retry_count int Maximum number of retries after the first attempt. 0 disables retries. 0 backoff_base float Base for exponential backoff between retry attempts. 2.0 Returns: Type Description dict [ tuple [ str , str ], DataFrame ] Mapping keyed by (symbol, granularity_name) . Propagates dict [ tuple [ str , str ], DataFrame ] ValueError from :func: collect_latest_closed_rates_for_accounts . Source code in mt5cli/sdk.py 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 def collect_latest_closed_rates_by_granularity ( accounts : Sequence [ AccountSpec ], granularities : Sequence [ int | str ], count : int , * , start_pos : int = 0 , base_config : Mt5Config | None = None , retry_count : int = 0 , backoff_base : float = 2.0 , ) -> dict [ tuple [ str , str ], pd . DataFrame ]: \"\"\"Collect latest closed rate bars keyed by symbol and granularity name. Thin wrapper around :func:`collect_latest_closed_rates_for_accounts` that rekeys the result by granularity name (for example ``M1``) instead of the integer timeframe. Args: accounts: Account groups to read. Each must define at least one symbol. granularities: MT5 timeframes as integers or names (for example ``M1``). count: Number of closed bars to return per symbol/timeframe. start_pos: Initial bar position offset passed to the underlying collector. base_config: Optional base configuration whose fields fill any value not set on an individual account. retry_count: Maximum number of retries after the first attempt. ``0`` disables retries. backoff_base: Base for exponential backoff between retry attempts. Returns: Mapping keyed by ``(symbol, granularity_name)``. Propagates ``ValueError`` from :func:`collect_latest_closed_rates_for_accounts`. \"\"\" loaded = collect_latest_closed_rates_for_accounts ( accounts , granularities , count , start_pos = start_pos , base_config = base_config , retry_count = retry_count , backoff_base = backoff_base , ) return { ( symbol , resolve_granularity_name ( timeframe )): frame for ( symbol , timeframe ), frame in loaded . items () } collect_latest_closed_rates_for_accounts \u00b6 collect_latest_closed_rates_for_accounts ( accounts : Sequence [ AccountSpec ], timeframes : Sequence [ int | str ], count : int , * , start_pos : int = 0 , base_config : Mt5Config | None = None , retry_count : int = 0 , backoff_base : float = 2.0 , ) -> dict [ tuple [ str , int ], DataFrame ] Collect latest closed rate bars across multiple MT5 account groups. When start_pos is 0 (the default), MetaTrader 5 includes the still-forming current bar as the last row. This helper fetches count + 1 bars, drops that bar with :func: drop_forming_rate_bar , and validates that each resulting frame is non-empty. When start_pos is greater than zero the forming bar is not in range, so only count bars are fetched and no row is dropped. Wraps :func: collect_latest_rates_for_accounts_with_retries for transient MT5 error handling. Parameters: Name Type Description Default accounts Sequence [ AccountSpec ] Account groups to read. Each must define at least one symbol. required timeframes Sequence [ int | str ] MT5 timeframes as integers or names (for example M1 ). required count int Number of closed bars to return per symbol/timeframe. required start_pos int Initial bar position offset passed to the underlying collector. 0 base_config Mt5Config | None Optional base configuration whose fields fill any value not set on an individual account. None retry_count int Maximum number of retries after the first attempt. 0 disables retries. 0 backoff_base float Base for exponential backoff between retry attempts. 2.0 Returns: Type Description dict [ tuple [ str , int ], DataFrame ] Mapping keyed by (symbol, timeframe_int) . Raises: Type Description ValueError If inputs are invalid, or any series is empty (after dropping the still-forming bar when start_pos is 0 ). Source code in mt5cli/sdk.py 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 def collect_latest_closed_rates_for_accounts ( accounts : Sequence [ AccountSpec ], timeframes : Sequence [ int | str ], count : int , * , start_pos : int = 0 , base_config : Mt5Config | None = None , retry_count : int = 0 , backoff_base : float = 2.0 , ) -> dict [ tuple [ str , int ], pd . DataFrame ]: \"\"\"Collect latest closed rate bars across multiple MT5 account groups. When ``start_pos`` is ``0`` (the default), MetaTrader 5 includes the still-forming current bar as the last row. This helper fetches ``count + 1`` bars, drops that bar with :func:`drop_forming_rate_bar`, and validates that each resulting frame is non-empty. When ``start_pos`` is greater than zero the forming bar is not in range, so only ``count`` bars are fetched and no row is dropped. Wraps :func:`collect_latest_rates_for_accounts_with_retries` for transient MT5 error handling. Args: accounts: Account groups to read. Each must define at least one symbol. timeframes: MT5 timeframes as integers or names (for example ``M1``). count: Number of closed bars to return per symbol/timeframe. start_pos: Initial bar position offset passed to the underlying collector. base_config: Optional base configuration whose fields fill any value not set on an individual account. retry_count: Maximum number of retries after the first attempt. ``0`` disables retries. backoff_base: Base for exponential backoff between retry attempts. Returns: Mapping keyed by ``(symbol, timeframe_int)``. Raises: ValueError: If inputs are invalid, or any series is empty (after dropping the still-forming bar when ``start_pos`` is ``0``). \"\"\" _require_positive ( count , \"count\" ) _require_non_negative ( start_pos , \"start_pos\" ) fetch_count = count + 1 if start_pos == 0 else count loaded = collect_latest_rates_for_accounts_with_retries ( accounts , timeframes , fetch_count , start_pos = start_pos , base_config = base_config , retry_count = retry_count , backoff_base = backoff_base , ) result : dict [ tuple [ str , int ], pd . DataFrame ] = {} for key , df_rate in loaded . items (): closed = drop_forming_rate_bar ( df_rate ) if start_pos == 0 else df_rate if closed . empty : symbol , timeframe = key msg = f \"Rate data is empty for { symbol !r} at timeframe { timeframe } .\" raise ValueError ( msg ) result [ key ] = closed return result collect_latest_rates \u00b6 collect_latest_rates ( symbols : Sequence [ str ], timeframes : Sequence [ int | str ], * , count : int , start_pos : int = 0 , config : Mt5Config | None = None , ) -> dict [ tuple [ str , int ], DataFrame ] Return latest rates for each symbol/timeframe pair. Source code in mt5cli/sdk.py 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 def collect_latest_rates ( symbols : Sequence [ str ], timeframes : Sequence [ int | str ], * , count : int , start_pos : int = 0 , config : Mt5Config | None = None , ) -> dict [ tuple [ str , int ], pd . DataFrame ]: \"\"\"Return latest rates for each symbol/timeframe pair.\"\"\" return _make_client ( config = config ) . collect_latest_rates ( symbols , timeframes , count = count , start_pos = start_pos , ) collect_latest_rates_for_accounts \u00b6 collect_latest_rates_for_accounts ( accounts : Sequence [ AccountSpec ], timeframes : Sequence [ int | str ], count : int , * , start_pos : int = 0 , base_config : Mt5Config | None = None , ) -> dict [ tuple [ str , int ], DataFrame ] Collect latest rates across multiple MT5 account groups. Each account is connected in turn, its symbols are read for every timeframe, and the resulting frames are merged into a single mapping. Parameters: Name Type Description Default accounts Sequence [ AccountSpec ] Account groups to read. Each must define at least one symbol. required timeframes Sequence [ int | str ] MT5 timeframes as integers or names (for example M1 ). required count int Number of most recent bars to read per symbol/timeframe. required start_pos int Initial bar position offset. 0 base_config Mt5Config | None Optional base configuration whose fields fill any value not set on an individual account. None Returns: Type Description dict [ tuple [ str , int ], DataFrame ] Mapping keyed by (symbol, timeframe_int) . When accounts share a dict [ tuple [ str , int ], DataFrame ] symbol/timeframe pair, the last account processed wins. Raises: Type Description ValueError If accounts , timeframes , or any account's symbols are empty, or count is not positive. Source code in mt5cli/sdk.py 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 def collect_latest_rates_for_accounts ( accounts : Sequence [ AccountSpec ], timeframes : Sequence [ int | str ], count : int , * , start_pos : int = 0 , base_config : Mt5Config | None = None , ) -> dict [ tuple [ str , int ], pd . DataFrame ]: \"\"\"Collect latest rates across multiple MT5 account groups. Each account is connected in turn, its symbols are read for every timeframe, and the resulting frames are merged into a single mapping. Args: accounts: Account groups to read. Each must define at least one symbol. timeframes: MT5 timeframes as integers or names (for example ``M1``). count: Number of most recent bars to read per symbol/timeframe. start_pos: Initial bar position offset. base_config: Optional base configuration whose fields fill any value not set on an individual account. Returns: Mapping keyed by ``(symbol, timeframe_int)``. When accounts share a symbol/timeframe pair, the last account processed wins. Raises: ValueError: If ``accounts``, ``timeframes``, or any account's symbols are empty, or ``count`` is not positive. \"\"\" account_list = list ( accounts ) if not account_list : msg = \"At least one account is required.\" raise ValueError ( msg ) if not timeframes : msg = \"At least one timeframe is required.\" raise ValueError ( msg ) if any ( not account . symbols for account in account_list ): msg = \"Each account requires at least one symbol.\" raise ValueError ( msg ) _require_positive ( count , \"count\" ) result : dict [ tuple [ str , int ], pd . DataFrame ] = {} for account in account_list : config = _build_account_config ( account , base_config ) with Mt5CliClient ( config = config ) as client : result . update ( client . collect_latest_rates ( account . symbols , timeframes , count = count , start_pos = start_pos , ), ) return result collect_latest_rates_for_accounts_with_retries \u00b6 collect_latest_rates_for_accounts_with_retries ( accounts : Sequence [ AccountSpec ], timeframes : Sequence [ int | str ], count : int , * , start_pos : int = 0 , base_config : Mt5Config | None = None , retry_count : int = 0 , backoff_base : float = 2.0 , ) -> dict [ tuple [ str , int ], DataFrame ] Collect latest rates across accounts, retrying transient MT5 failures. Wraps :func: collect_latest_rates_for_accounts with bounded exponential backoff. Only pdmt5.Mt5TradingError and pdmt5.Mt5RuntimeError are retried; other exceptions propagate immediately. The final failure is re-raised once retries are exhausted. Parameters: Name Type Description Default accounts Sequence [ AccountSpec ] Account groups to read. Each must define at least one symbol. required timeframes Sequence [ int | str ] MT5 timeframes as integers or names (for example M1 ). required count int Number of most recent bars to read per symbol/timeframe. required start_pos int Initial bar position offset. 0 base_config Mt5Config | None Optional base configuration whose fields fill any value not set on an individual account. None retry_count int Maximum number of retries after the first attempt. 0 disables retries. 0 backoff_base float Base for exponential backoff. The delay before retry attempt n (1-indexed) is backoff_base ** n seconds. 2.0 Returns: Type Description dict [ tuple [ str , int ], DataFrame ] Mapping keyed by (symbol, timeframe_int) . Propagates ValueError dict [ tuple [ str , int ], DataFrame ] for invalid inputs (see :func: collect_latest_rates_for_accounts ) and dict [ tuple [ str , int ], DataFrame ] re-raises the last pdmt5.Mt5TradingError or pdmt5.Mt5RuntimeError dict [ tuple [ str , int ], DataFrame ] once retries are exhausted. Source code in mt5cli/sdk.py 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 def collect_latest_rates_for_accounts_with_retries ( accounts : Sequence [ AccountSpec ], timeframes : Sequence [ int | str ], count : int , * , start_pos : int = 0 , base_config : Mt5Config | None = None , retry_count : int = 0 , backoff_base : float = 2.0 , ) -> dict [ tuple [ str , int ], pd . DataFrame ]: \"\"\"Collect latest rates across accounts, retrying transient MT5 failures. Wraps :func:`collect_latest_rates_for_accounts` with bounded exponential backoff. Only ``pdmt5.Mt5TradingError`` and ``pdmt5.Mt5RuntimeError`` are retried; other exceptions propagate immediately. The final failure is re-raised once retries are exhausted. Args: accounts: Account groups to read. Each must define at least one symbol. timeframes: MT5 timeframes as integers or names (for example ``M1``). count: Number of most recent bars to read per symbol/timeframe. start_pos: Initial bar position offset. base_config: Optional base configuration whose fields fill any value not set on an individual account. retry_count: Maximum number of retries after the first attempt. ``0`` disables retries. backoff_base: Base for exponential backoff. The delay before retry attempt ``n`` (1-indexed) is ``backoff_base ** n`` seconds. Returns: Mapping keyed by ``(symbol, timeframe_int)``. Propagates ``ValueError`` for invalid inputs (see :func:`collect_latest_rates_for_accounts`) and re-raises the last ``pdmt5.Mt5TradingError`` or ``pdmt5.Mt5RuntimeError`` once retries are exhausted. \"\"\" def _collect () -> dict [ tuple [ str , int ], pd . DataFrame ]: return collect_latest_rates_for_accounts ( accounts , timeframes , count , start_pos = start_pos , base_config = base_config , ) return retry_with_backoff ( _collect , retry_count = retry_count , backoff_base = backoff_base , operation = \"Rate collection\" , ) connected_client \u00b6 connected_client ( config : Mt5Config , ) -> Iterator [ Mt5DataClient ] Initialize MT5, yield a connected client, and always shut down. Parameters: Name Type Description Default config Mt5Config MT5 connection configuration. required Yields: Type Description Mt5DataClient Connected Mt5DataClient instance. Source code in mt5cli/sdk.py 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 @contextmanager def connected_client ( config : Mt5Config ) -> Iterator [ Mt5DataClient ]: \"\"\"Initialize MT5, yield a connected client, and always shut down. Args: config: MT5 connection configuration. Yields: Connected ``Mt5DataClient`` instance. \"\"\" client = Mt5DataClient ( config = config ) try : client . initialize_and_login_mt5 () yield client finally : client . shutdown () copy_rates_from \u00b6 copy_rates_from ( symbol : str , timeframe : int | str , date_from : datetime | str , count : int , * , config : Mt5Config | None = None , ) -> DataFrame Return rates starting from a date. Source code in mt5cli/sdk.py 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 def copy_rates_from ( symbol : str , timeframe : int | str , date_from : datetime | str , count : int , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return rates starting from a date.\"\"\" return _make_client ( config = config ) . copy_rates_from ( symbol , timeframe , date_from , count , ) copy_rates_from_pos \u00b6 copy_rates_from_pos ( symbol : str , timeframe : int | str , start_pos : int , count : int , * , config : Mt5Config | None = None , ) -> DataFrame Return rates starting from a bar position. Source code in mt5cli/sdk.py 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 def copy_rates_from_pos ( symbol : str , timeframe : int | str , start_pos : int , count : int , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return rates starting from a bar position.\"\"\" return _make_client ( config = config ) . copy_rates_from_pos ( symbol , timeframe , start_pos , count , ) copy_rates_range \u00b6 copy_rates_range ( symbol : str , timeframe : int | str , date_from : datetime | str , date_to : datetime | str , * , config : Mt5Config | None = None , ) -> DataFrame Return rates for a date range. Source code in mt5cli/sdk.py 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 def copy_rates_range ( symbol : str , timeframe : int | str , date_from : datetime | str , date_to : datetime | str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return rates for a date range.\"\"\" return _make_client ( config = config ) . copy_rates_range ( symbol , timeframe , date_from , date_to , ) copy_ticks_from \u00b6 copy_ticks_from ( symbol : str , date_from : datetime | str , count : int , flags : int | str , * , config : Mt5Config | None = None , ) -> DataFrame Return ticks starting from a date. Source code in mt5cli/sdk.py 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 def copy_ticks_from ( symbol : str , date_from : datetime | str , count : int , flags : int | str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return ticks starting from a date.\"\"\" return _make_client ( config = config ) . copy_ticks_from ( symbol , date_from , count , flags , ) copy_ticks_range \u00b6 copy_ticks_range ( symbol : str , date_from : datetime | str , date_to : datetime | str , flags : int | str , * , config : Mt5Config | None = None , ) -> DataFrame Return ticks for a date range. Source code in mt5cli/sdk.py 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 def copy_ticks_range ( symbol : str , date_from : datetime | str , date_to : datetime | str , flags : int | str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return ticks for a date range.\"\"\" return _make_client ( config = config ) . copy_ticks_range ( symbol , date_from , date_to , flags , ) fetch_latest_closed_rates \u00b6 fetch_latest_closed_rates ( client : Mt5CliClient , * , symbol : str , granularity : str , count : int , ) -> DataFrame Fetch up to count most recent closed bars, oldest to newest. Returns: Type Description DataFrame Closed rate bars ordered oldest to newest. Raises: Type Description ValueError If count is not positive or no closed bars are returned. Source code in mt5cli/sdk.py 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 def fetch_latest_closed_rates ( client : Mt5CliClient , * , symbol : str , granularity : str , count : int , ) -> pd . DataFrame : \"\"\"Fetch up to ``count`` most recent closed bars, oldest to newest. Returns: Closed rate bars ordered oldest to newest. Raises: ValueError: If ``count`` is not positive or no closed bars are returned. \"\"\" _require_positive ( count , \"count\" ) frame = client . latest_rates ( symbol , granularity , count + 1 , start_pos = 0 ) closed = drop_forming_rate_bar ( frame ) if closed . empty : msg = ( f \"Rate data is empty for { symbol !r} at granularity { granularity !r} \" f \"with count { count } .\" ) raise ValueError ( msg ) return closed . tail ( count ) . reset_index ( drop = True ) history_deals \u00b6 history_deals ( date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , * , config : Mt5Config | None = None , ) -> DataFrame Return historical deals. Source code in mt5cli/sdk.py 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 def history_deals ( date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return historical deals.\"\"\" return _make_client ( config = config ) . history_deals ( date_from = date_from , date_to = date_to , group = group , symbol = symbol , ticket = ticket , position = position , ) history_orders \u00b6 history_orders ( date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , * , config : Mt5Config | None = None , ) -> DataFrame Return historical orders. Source code in mt5cli/sdk.py 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 def history_orders ( date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return historical orders.\"\"\" return _make_client ( config = config ) . history_orders ( date_from = date_from , date_to = date_to , group = group , symbol = symbol , ticket = ticket , position = position , ) last_error \u00b6 last_error ( * , config : Mt5Config | None = None ) -> DataFrame Return the last error information. Source code in mt5cli/sdk.py 2078 2079 2080 def last_error ( * , config : Mt5Config | None = None ) -> pd . DataFrame : \"\"\"Return the last error information.\"\"\" return _make_client ( config = config ) . last_error () latest_rates \u00b6 latest_rates ( symbol : str , timeframe : int | str , count : int , start_pos : int = 0 , * , config : Mt5Config | None = None , ) -> DataFrame Return the latest rates from a bar position. Source code in mt5cli/sdk.py 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 def latest_rates ( symbol : str , timeframe : int | str , count : int , start_pos : int = 0 , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return the latest rates from a bar position.\"\"\" return _make_client ( config = config ) . latest_rates ( symbol , timeframe , count , start_pos = start_pos , ) market_book \u00b6 market_book ( symbol : str , * , config : Mt5Config | None = None ) -> DataFrame Return market depth for a symbol. Source code in mt5cli/sdk.py 2092 2093 2094 2095 2096 2097 2098 def market_book ( symbol : str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return market depth for a symbol.\"\"\" return _make_client ( config = config ) . market_book ( symbol ) minimum_margins \u00b6 minimum_margins ( symbol : str , * , config : Mt5Config | None = None ) -> DataFrame Return minimum-volume buy and sell margin requirements. See Mt5CliClient.minimum_margins for return details. Source code in mt5cli/sdk.py 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 def minimum_margins ( symbol : str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return minimum-volume buy and sell margin requirements. See ``Mt5CliClient.minimum_margins`` for return details. \"\"\" return _make_client ( config = config ) . minimum_margins ( symbol ) mt5_session \u00b6 mt5_session ( config : Mt5Config | None = None , ) -> Iterator [ Mt5CliClient ] Open an MT5 terminal session and yield a connected client. Launches the MetaTrader 5 terminal using Mt5Config.path (when set), logs in, yields a connected :class: Mt5CliClient , and always shuts the terminal down on exit. Parameters: Name Type Description Default config Mt5Config | None MT5 connection configuration. Defaults to an empty config that attaches to a running terminal. None Yields: Type Description Mt5CliClient Connected Mt5CliClient bound to the session. Source code in mt5cli/sdk.py 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 @contextmanager def mt5_session ( config : Mt5Config | None = None ) -> Iterator [ Mt5CliClient ]: \"\"\"Open an MT5 terminal session and yield a connected client. Launches the MetaTrader 5 terminal using ``Mt5Config.path`` (when set), logs in, yields a connected :class:`Mt5CliClient`, and always shuts the terminal down on exit. Args: config: MT5 connection configuration. Defaults to an empty config that attaches to a running terminal. Yields: Connected ``Mt5CliClient`` bound to the session. \"\"\" mt5_config = config or build_config () with connected_client ( mt5_config ) as client : yield Mt5CliClient . from_connected_client ( client ) mt5_summary \u00b6 mt5_summary ( * , config : Mt5Config | None = None ) -> dict [ str , object ] Return a compact terminal/account status summary. Source code in mt5cli/sdk.py 2135 2136 2137 def mt5_summary ( * , config : Mt5Config | None = None ) -> dict [ str , object ]: \"\"\"Return a compact terminal/account status summary.\"\"\" return _make_client ( config = config ) . mt5_summary () mt5_summary_as_df \u00b6 mt5_summary_as_df ( * , config : Mt5Config | None = None ) -> DataFrame Return an export-safe terminal/account status summary DataFrame. Source code in mt5cli/sdk.py 2140 2141 2142 def mt5_summary_as_df ( * , config : Mt5Config | None = None ) -> pd . DataFrame : \"\"\"Return an export-safe terminal/account status summary DataFrame.\"\"\" return _make_client ( config = config ) . mt5_summary_as_df () orders \u00b6 orders ( symbol : str | None = None , group : str | None = None , ticket : int | None = None , * , config : Mt5Config | None = None , ) -> DataFrame Return active orders. Source code in mt5cli/sdk.py 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 def orders ( symbol : str | None = None , group : str | None = None , ticket : int | None = None , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return active orders.\"\"\" return _make_client ( config = config ) . orders ( symbol = symbol , group = group , ticket = ticket , ) positions \u00b6 positions ( symbol : str | None = None , group : str | None = None , ticket : int | None = None , * , config : Mt5Config | None = None , ) -> DataFrame Return open positions. Source code in mt5cli/sdk.py 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 def positions ( symbol : str | None = None , group : str | None = None , ticket : int | None = None , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return open positions.\"\"\" return _make_client ( config = config ) . positions ( symbol = symbol , group = group , ticket = ticket , ) recent_history_deals \u00b6 recent_history_deals ( hours : float , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , * , config : Mt5Config | None = None , ) -> DataFrame Return historical deals from a recent trailing window. Source code in mt5cli/sdk.py 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 def recent_history_deals ( hours : float , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return historical deals from a recent trailing window.\"\"\" return _make_client ( config = config ) . recent_history_deals ( hours , date_to = date_to , group = group , symbol = symbol , ) recent_ticks \u00b6 recent_ticks ( symbol : str , seconds : float , * , date_to : datetime | str | None = None , count : int = 10000 , flags : int | str = \"ALL\" , config : Mt5Config | None = None , ) -> DataFrame Return ticks from a recent time window ending at date_to or now. See Mt5CliClient.recent_ticks for parameter and return details. Source code in mt5cli/sdk.py 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 def recent_ticks ( symbol : str , seconds : float , * , date_to : datetime | str | None = None , count : int = 10000 , flags : int | str = \"ALL\" , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return ticks from a recent time window ending at ``date_to`` or now. See ``Mt5CliClient.recent_ticks`` for parameter and return details. \"\"\" return _make_client ( config = config ) . recent_ticks ( symbol , seconds , date_to = date_to , count = count , flags = flags , ) resolve_account_spec \u00b6 resolve_account_spec ( account : AccountSpec , * , login : int | str | None = None , password : str | None = None , server : str | None = None , path : str | None = None , timeout : int | None = None , allow_whole_dollar_env : bool = False , ) -> AccountSpec Resolve an account's credentials from overrides and ${ENV_VAR} values. Explicit override arguments take precedence over the corresponding :class: AccountSpec fields. The resolved string fields ( login , password , server , path ) have any ${ENV_VAR} placeholders substituted from the environment. Parameters: Name Type Description Default account AccountSpec Source account specification. required login int | str | None Optional explicit login override. None password str | None Optional explicit password override. None server str | None Optional explicit server override. None path str | None Optional explicit terminal path override. None timeout int | None Optional explicit connection timeout override. None allow_whole_dollar_env bool When True , string fields that are exactly $ENV_NAME are also expanded from the environment. Default False preserves existing behavior. False Returns: Type Description AccountSpec A new :class: AccountSpec with resolved credentials and the original AccountSpec symbols preserved. Raises ValueError (via AccountSpec func: substitute_env_placeholders ) if a referenced environment AccountSpec variable is not set. Source code in mt5cli/sdk.py 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 def resolve_account_spec ( account : AccountSpec , * , login : int | str | None = None , password : str | None = None , server : str | None = None , path : str | None = None , timeout : int | None = None , allow_whole_dollar_env : bool = False , ) -> AccountSpec : \"\"\"Resolve an account's credentials from overrides and ``${ENV_VAR}`` values. Explicit override arguments take precedence over the corresponding :class:`AccountSpec` fields. The resolved string fields (``login``, ``password``, ``server``, ``path``) have any ``${ENV_VAR}`` placeholders substituted from the environment. Args: account: Source account specification. login: Optional explicit login override. password: Optional explicit password override. server: Optional explicit server override. path: Optional explicit terminal path override. timeout: Optional explicit connection timeout override. allow_whole_dollar_env: When ``True``, string fields that are exactly ``$ENV_NAME`` are also expanded from the environment. Default ``False`` preserves existing behavior. Returns: A new :class:`AccountSpec` with resolved credentials and the original symbols preserved. Raises ``ValueError`` (via :func:`substitute_env_placeholders`) if a referenced environment variable is not set. \"\"\" return AccountSpec ( symbols = account . symbols , login = _resolve_login ( login , account . login , allow_whole_dollar_env = allow_whole_dollar_env ), password = _resolve_field ( password , account . password , allow_whole_dollar_env = allow_whole_dollar_env ), server = _resolve_field ( server , account . server , allow_whole_dollar_env = allow_whole_dollar_env ), path = _resolve_field ( path , account . path , allow_whole_dollar_env = allow_whole_dollar_env ), timeout = timeout if timeout is not None else account . timeout , ) resolve_account_specs \u00b6 resolve_account_specs ( accounts : Sequence [ AccountSpec ], * , login : int | str | None = None , password : str | None = None , server : str | None = None , path : str | None = None , timeout : int | None = None , allow_whole_dollar_env : bool = False , ) -> list [ AccountSpec ] Resolve credentials for multiple accounts. Applies the same overrides and ${ENV_VAR} substitution as :func: resolve_account_spec to every account. Parameters: Name Type Description Default accounts Sequence [ AccountSpec ] Source account specifications. required login int | str | None Optional explicit login override applied to each account. None password str | None Optional explicit password override applied to each account. None server str | None Optional explicit server override applied to each account. None path str | None Optional explicit terminal path override applied to each account. None timeout int | None Optional explicit timeout override applied to each account. None allow_whole_dollar_env bool When True , string fields that are exactly $ENV_NAME are also expanded from the environment. Default False preserves existing behavior. False Returns: Type Description list [ AccountSpec ] Resolved account specifications in the original order. Raises list [ AccountSpec ] ValueError (via :func: substitute_env_placeholders ) if a referenced list [ AccountSpec ] environment variable is not set. Source code in mt5cli/sdk.py 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 def resolve_account_specs ( accounts : Sequence [ AccountSpec ], * , login : int | str | None = None , password : str | None = None , server : str | None = None , path : str | None = None , timeout : int | None = None , allow_whole_dollar_env : bool = False , ) -> list [ AccountSpec ]: \"\"\"Resolve credentials for multiple accounts. Applies the same overrides and ``${ENV_VAR}`` substitution as :func:`resolve_account_spec` to every account. Args: accounts: Source account specifications. login: Optional explicit login override applied to each account. password: Optional explicit password override applied to each account. server: Optional explicit server override applied to each account. path: Optional explicit terminal path override applied to each account. timeout: Optional explicit timeout override applied to each account. allow_whole_dollar_env: When ``True``, string fields that are exactly ``$ENV_NAME`` are also expanded from the environment. Default ``False`` preserves existing behavior. Returns: Resolved account specifications in the original order. Raises ``ValueError`` (via :func:`substitute_env_placeholders`) if a referenced environment variable is not set. \"\"\" return [ resolve_account_spec ( account , login = login , password = password , server = server , path = path , timeout = timeout , allow_whole_dollar_env = allow_whole_dollar_env , ) for account in accounts ] substitute_env_placeholders \u00b6 substitute_env_placeholders ( value : str , * , allow_whole_dollar_env : bool = False ) -> str Replace ${ENV_VAR} placeholders in a string with environment values. Parameters: Name Type Description Default value str String that may contain one or more ${ENV_VAR} placeholders. required allow_whole_dollar_env bool When True , a string that is exactly $ENV_NAME (the whole value and nothing else) is also expanded from the environment. Partial occurrences such as \"plan$pass\" or \"$ENV-suffix\" are left unchanged. False Returns: Type Description str The string with every placeholder replaced by its environment value. Raises: Type Description ValueError If a referenced environment variable is not set. Source code in mt5cli/sdk.py 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 def substitute_env_placeholders ( value : str , * , allow_whole_dollar_env : bool = False , ) -> str : \"\"\"Replace ``${ENV_VAR}`` placeholders in a string with environment values. Args: value: String that may contain one or more ``${ENV_VAR}`` placeholders. allow_whole_dollar_env: When ``True``, a string that is exactly ``$ENV_NAME`` (the whole value and nothing else) is also expanded from the environment. Partial occurrences such as ``\"plan$pass\"`` or ``\"$ENV-suffix\"`` are left unchanged. Returns: The string with every placeholder replaced by its environment value. Raises: ValueError: If a referenced environment variable is not set. \"\"\" if allow_whole_dollar_env : m = _WHOLE_DOLLAR_PATTERN . match ( value ) if m : name = m . group ( \"name\" ) if name not in os . environ : msg = f \"Environment variable { name !r} is not set.\" raise ValueError ( msg ) return os . environ [ name ] parts : list [ str ] = [] last_end = 0 for match in _ENV_PLACEHOLDER_PATTERN . finditer ( value ): parts . append ( value [ last_end : match . start ()]) name = match . group ( \"name\" ) if name not in os . environ : msg = f \"Environment variable { name !r} is not set.\" raise ValueError ( msg ) parts . append ( os . environ [ name ]) last_end = match . end () parts . append ( value [ last_end :]) return \"\" . join ( parts ) substitute_mapping_values \u00b6 substitute_mapping_values ( data : object , * , keys : Collection [ str ], allow_whole_dollar_env : bool = False , blank_string_keys_as_none : Collection [ str ] = (), ) -> object Recursively substitute environment placeholders for selected mapping keys. Traverses nested dicts and lists, expanding ${ENV_VAR} (and $ENV_NAME when allow_whole_dollar_env=True ) in string values whose immediate parent dict key is in keys . Fields whose key is not in keys are preserved exactly, including literal dollar signs. Strings that are direct elements of a list are never substituted; substitution only applies to strings that are immediate dict values. This is a generic downstream config utility. Key names such as mt5_login or mt5_password must be supplied by the caller; mt5cli does not hard-code any application-specific key names. Callers are responsible for ensuring data has bounded nesting depth; deeply nested or self-referential structures will hit Python's recursion limit. Parameters: Name Type Description Default data object Arbitrarily nested dict/list/scalar value to process. required keys Collection [ str ] Mapping keys whose string values receive placeholder substitution. required allow_whole_dollar_env bool When True , a string that is exactly $ENV_NAME (whole value) is also expanded from the environment in addition to ${ENV_NAME} placeholders. Default False expands ${ENV_NAME} only. False blank_string_keys_as_none Collection [ str ] Mapping keys for which blank strings (after any substitution) are normalised to None . A key may appear in blank_string_keys_as_none without also appearing in keys . () Returns: Type Description object The processed value. Dicts and lists are rebuilt into new object containers with selected string values substituted and object blank-normalised. Scalar inputs (non-dict, non-list) are object returned as-is. Source code in mt5cli/sdk.py 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 def substitute_mapping_values ( data : object , * , keys : Collection [ str ], allow_whole_dollar_env : bool = False , blank_string_keys_as_none : Collection [ str ] = (), ) -> object : \"\"\"Recursively substitute environment placeholders for selected mapping keys. Traverses nested dicts and lists, expanding ``${ENV_VAR}`` (and ``$ENV_NAME`` when ``allow_whole_dollar_env=True``) in string values whose immediate parent dict key is in ``keys``. Fields whose key is not in ``keys`` are preserved exactly, including literal dollar signs. Strings that are direct elements of a list are never substituted; substitution only applies to strings that are immediate dict values. This is a generic downstream config utility. Key names such as ``mt5_login`` or ``mt5_password`` must be supplied by the caller; mt5cli does not hard-code any application-specific key names. Callers are responsible for ensuring ``data`` has bounded nesting depth; deeply nested or self-referential structures will hit Python's recursion limit. Args: data: Arbitrarily nested dict/list/scalar value to process. keys: Mapping keys whose string values receive placeholder substitution. allow_whole_dollar_env: When ``True``, a string that is exactly ``$ENV_NAME`` (whole value) is also expanded from the environment in addition to ``${ENV_NAME}`` placeholders. Default ``False`` expands ``${ENV_NAME}`` only. blank_string_keys_as_none: Mapping keys for which blank strings (after any substitution) are normalised to ``None``. A key may appear in ``blank_string_keys_as_none`` without also appearing in ``keys``. Returns: The processed value. Dicts and lists are rebuilt into new containers with selected string values substituted and blank-normalised. Scalar inputs (non-dict, non-list) are returned as-is. \"\"\" keys_set : frozenset [ str ] = frozenset ( keys ) blank_keys_set : frozenset [ str ] = frozenset ( blank_string_keys_as_none ) def _visit ( node : object , current_key : str | None ) -> object : if isinstance ( node , dict ): typed = cast ( \"dict[object, object]\" , node ) return { k : _visit ( v , k if isinstance ( k , str ) else None ) for k , v in typed . items () } if isinstance ( node , list ): typed_list = cast ( \"list[object]\" , node ) return [ _visit ( item , None ) for item in typed_list ] if not isinstance ( node , str ): return node text = node if current_key in keys_set : text = substitute_env_placeholders ( node , allow_whole_dollar_env = allow_whole_dollar_env ) if current_key in blank_keys_set and not text . strip (): return None return text return _visit ( data , None ) symbol_info \u00b6 symbol_info ( symbol : str , * , config : Mt5Config | None = None ) -> DataFrame Return details for one symbol. Source code in mt5cli/sdk.py 1975 1976 1977 1978 1979 1980 1981 def symbol_info ( symbol : str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return details for one symbol.\"\"\" return _make_client ( config = config ) . symbol_info ( symbol ) symbol_info_tick \u00b6 symbol_info_tick ( symbol : str , * , config : Mt5Config | None = None ) -> DataFrame Return the last tick for a symbol. Source code in mt5cli/sdk.py 2083 2084 2085 2086 2087 2088 2089 def symbol_info_tick ( symbol : str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return the last tick for a symbol.\"\"\" return _make_client ( config = config ) . symbol_info_tick ( symbol ) symbols \u00b6 symbols ( group : str | None = None , * , config : Mt5Config | None = None , ) -> DataFrame Return the symbol list. Source code in mt5cli/sdk.py 1966 1967 1968 1969 1970 1971 1972 def symbols ( group : str | None = None , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return the symbol list.\"\"\" return _make_client ( config = config ) . symbols ( group = group ) terminal_info \u00b6 terminal_info ( * , config : Mt5Config | None = None ) -> DataFrame Return terminal information. Source code in mt5cli/sdk.py 1961 1962 1963 def terminal_info ( * , config : Mt5Config | None = None ) -> pd . DataFrame : \"\"\"Return terminal information.\"\"\" return _make_client ( config = config ) . terminal_info () update_history \u00b6 update_history ( * , client : Mt5DataClient , output : Path | str , symbols : Sequence [ str ], datasets : set [ Dataset ] | None = None , timeframes : Sequence [ int | str ] | None = None , flags : int | str = \"ALL\" , lookback_hours : float = 24.0 , date_to : datetime | str | None = None , deduplicate : bool = True , create_rate_views : bool = True , with_views : bool = False , include_account_events : bool = True , ) -> None Incrementally append MT5 history into a SQLite database. Uses an already-connected Mt5DataClient and does not create or close the MT5 connection. For first-time tables, data is fetched from date_to - lookback_hours . Subsequent runs resume from existing MAX(time) per symbol (and timeframe for rates); when include_account_events=True , account-level deals use a separate cursor over type NOT IN (0, 1) / empty-symbol rows. Parameters: Name Type Description Default client Mt5DataClient Connected MT5 data client. required output Path | str SQLite database path. required symbols Sequence [ str ] Symbols to update. required datasets set [ Dataset ] | None Datasets to include (defaults to all). None timeframes Sequence [ int | str ] | None Rate timeframes to update (defaults to all fixed MT5 timeframes when None). None flags int | str Tick copy flags as integer or name (e.g. ALL ). 'ALL' lookback_hours float First-run lookback when a table has no prior rows. 24.0 date_to datetime | str | None Optional update end datetime. Defaults to now (UTC). None deduplicate bool Remove duplicate rows after append, keeping latest ROWID. True create_rate_views bool Create rate___ views. True with_views bool Create cash_events and positions_reconstructed views. False include_account_events bool Include account-level cash events in history_deals when True. True Source code in mt5cli/sdk.py 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 def update_history ( # noqa: PLR0913 * , client : Mt5DataClient , output : Path | str , symbols : Sequence [ str ], datasets : set [ Dataset ] | None = None , timeframes : Sequence [ int | str ] | None = None , flags : int | str = \"ALL\" , lookback_hours : float = 24.0 , date_to : datetime | str | None = None , deduplicate : bool = True , create_rate_views : bool = True , with_views : bool = False , include_account_events : bool = True , ) -> None : \"\"\"Incrementally append MT5 history into a SQLite database. Uses an already-connected ``Mt5DataClient`` and does not create or close the MT5 connection. For first-time tables, data is fetched from ``date_to - lookback_hours``. Subsequent runs resume from existing ``MAX(time)`` per symbol (and timeframe for rates); when ``include_account_events=True``, account-level deals use a separate cursor over ``type NOT IN (0, 1)`` / empty-symbol rows. Args: client: Connected MT5 data client. output: SQLite database path. symbols: Symbols to update. datasets: Datasets to include (defaults to all). timeframes: Rate timeframes to update (defaults to all fixed MT5 timeframes when None). flags: Tick copy flags as integer or name (e.g. ``ALL``). lookback_hours: First-run lookback when a table has no prior rows. date_to: Optional update end datetime. Defaults to now (UTC). deduplicate: Remove duplicate rows after append, keeping latest ROWID. create_rate_views: Create ``rate___`` views. with_views: Create ``cash_events`` and ``positions_reconstructed`` views. include_account_events: Include account-level cash events in ``history_deals`` when True. \"\"\" request = _resolve_update_history_request ( output = output , symbols = symbols , datasets = datasets , timeframes = timeframes , flags = flags , lookback_hours = lookback_hours , date_to = date_to , ) if request is None : return logger . info ( \"Updating history in SQLite: symbols= %s , datasets= %s , path= %s \" , list ( symbols ), sorted ( dataset . value for dataset in request . selected ), request . output_path , ) with sqlite3 . connect ( request . output_path ) as conn : conn . execute ( \"PRAGMA journal_mode=WAL\" ) conn . execute ( \"PRAGMA synchronous=NORMAL\" ) write_incremental_datasets ( conn , client , symbols , request . selected , request . resolved_timeframes , request . resolved_tick_flags , request . fallback_start , request . end , deduplicate = deduplicate , create_rate_views = create_rate_views , with_views = with_views , include_account_events = include_account_events , ) update_history_with_config \u00b6 update_history_with_config ( * , output : Path | str , symbols : Sequence [ str ], config : Mt5Config | None = None , datasets : set [ Dataset ] | None = None , timeframes : Sequence [ int | str ] | None = None , flags : int | str = \"ALL\" , lookback_hours : float = 24.0 , date_to : datetime | str | None = None , deduplicate : bool = True , create_rate_views : bool = True , with_views : bool = False , include_account_events : bool = True , ) -> None Incrementally append MT5 history, opening and closing the MT5 connection. Convenience wrapper around :func: update_history for standalone use. Source code in mt5cli/sdk.py 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 def update_history_with_config ( # noqa: PLR0913 * , output : Path | str , symbols : Sequence [ str ], config : Mt5Config | None = None , datasets : set [ Dataset ] | None = None , timeframes : Sequence [ int | str ] | None = None , flags : int | str = \"ALL\" , lookback_hours : float = 24.0 , date_to : datetime | str | None = None , deduplicate : bool = True , create_rate_views : bool = True , with_views : bool = False , include_account_events : bool = True , ) -> None : \"\"\"Incrementally append MT5 history, opening and closing the MT5 connection. Convenience wrapper around :func:`update_history` for standalone use. \"\"\" request = _resolve_update_history_request ( output = output , symbols = symbols , datasets = datasets , timeframes = timeframes , flags = flags , lookback_hours = lookback_hours , date_to = date_to , ) if request is None : return mt5_config = config or build_config () with connected_client ( mt5_config ) as client : update_history ( client = client , output = output , symbols = symbols , datasets = datasets , timeframes = timeframes , flags = flags , lookback_hours = lookback_hours , date_to = date_to , deduplicate = deduplicate , create_rate_views = create_rate_views , with_views = with_views , include_account_events = include_account_events , ) version \u00b6 version ( * , config : Mt5Config | None = None ) -> DataFrame Return MetaTrader5 version information. Source code in mt5cli/sdk.py 2073 2074 2075 def version ( * , config : Mt5Config | None = None ) -> pd . DataFrame : \"\"\"Return MetaTrader5 version information.\"\"\" return _make_client ( config = config ) . version () Resilient multi-account orchestration \u00b6 The SDK ships strategy-agnostic helpers for building long-running collectors on top of the read-only client. None of them depend on a particular trading application. Retrying transient rate collection \u00b6 collect_latest_rates_for_accounts_with_retries() wraps collect_latest_rates_for_accounts() with bounded exponential backoff. Only pdmt5.Mt5TradingError and pdmt5.Mt5RuntimeError are retried; the final failure is re-raised once retry_count is exhausted. from mt5cli import AccountSpec , collect_latest_rates_for_accounts_with_retries accounts = [ AccountSpec ( symbols = [ \"EURUSD\" ], login = 12345 )] rates = collect_latest_rates_for_accounts_with_retries ( accounts , [ \"M1\" , \"H1\" ], count = 500 , retry_count = 3 , backoff_base = 2 , # sleeps 2s, 4s, 8s between attempts ) Latest closed rate bars \u00b6 MetaTrader 5 start_pos=0 includes the still-forming current bar as the last row. fetch_latest_closed_rates() handles one connected MT5Client ; use fetch_latest_closed_rates_for_trading_client() from an active Mt5TradingClient session. Multi-account helpers fetch count + 1 bars, drop that row with drop_forming_rate_bar() , and validate each series is non-empty. Returned frames are ordered oldest-to-newest and may contain fewer than count rows only when MT5 returns fewer closed bars. from mt5cli import ( AccountSpec , collect_latest_closed_rates_by_granularity , fetch_latest_closed_rates , ) closed = fetch_latest_closed_rates ( client , symbol = \"EURUSD\" , granularity = \"M1\" , count = 500 , ) rates = collect_latest_closed_rates_by_granularity ( [ AccountSpec ( symbols = [ \"EURUSD\" ], login = 12345 )], [ \"M1\" , \"H1\" ], count = 500 , retry_count = 3 , ) closed_m1 = rates [ \"EURUSD\" , \"M1\" ] Use collect_latest_closed_rates_by_granularity() when callers prefer keys such as (\"EURUSD\", \"M1\") instead of integer timeframes. Resolving credentials and ${ENV_VAR} placeholders \u00b6 resolve_account_spec() / resolve_account_specs() merge explicit override values over AccountSpec fields and expand ${ENV_VAR} placeholders, keeping secrets out of plan/config files. A missing environment variable raises ValueError . import os from mt5cli import AccountSpec , resolve_account_specs os . environ [ \"MT5_LOGIN\" ] = \"12345\" os . environ [ \"MT5_PASSWORD\" ] = \"secret\" accounts = [ AccountSpec ( symbols = [ \"EURUSD\" ], login = \"$ {MT5_LOGIN} \" , password = \"$ {MT5_PASSWORD} \" ) ] resolved = resolve_account_specs ( accounts , server = \"Broker-Demo\" ) # resolved[0].login == \"12345\", resolved[0].server == \"Broker-Demo\" Pass allow_whole_dollar_env=True to also expand strings whose entire value is a bare $ENV_NAME identifier (no braces). This opt-in covers substitute_env_placeholders() , resolve_account_spec() , resolve_account_specs() , and build_config() . Note: build_config cannot expand login because that parameter is int | None ; use resolve_account_spec for a string login placeholder. Partial strings such as \"plan$pass\" , \"abc$ENV\" , or \"$ENV-suffix\" are never expanded \u2014 only an exact $IDENTIFIER whole-string match qualifies. The default is False to preserve backward compatibility. import os from mt5cli import AccountSpec , resolve_account_specs os . environ [ \"MT5_PASSWORD\" ] = \"secret\" accounts = [ AccountSpec ( symbols = [ \"EURUSD\" ], password = \"$MT5_PASSWORD\" )] resolved = resolve_account_specs ( accounts , allow_whole_dollar_env = True ) # resolved[0].password == \"secret\" Throttled incremental history updates \u00b6 ThrottledHistoryUpdater wraps update_history() with a minimum interval between successful runs (using a monotonic clock), so an application loop can call it every iteration without over-fetching. from pdmt5 import Mt5Config , Mt5DataClient from mt5cli import Dataset , ThrottledHistoryUpdater updater = ThrottledHistoryUpdater ( output = \"history.db\" , datasets = { Dataset . rates }, timeframes = [ \"M1\" ], interval_seconds = 60 , # <= 0 updates on every call ) client = Mt5DataClient ( config = Mt5Config ( login = 12345 )) client . initialize_and_login_mt5 () try : while True : updater . update ( client , [ \"EURUSD\" , \"GBPUSD\" ]) # no-op until 60s elapse # ... do other work; break when shutting down ... finally : client . shutdown () Pass update_backend to substitute the default update_history implementation without monkey-patching mt5cli.sdk.update_history . The callable receives the same keyword arguments as update_history ( client , output , symbols , datasets , timeframes , flags , lookback_hours , with_views , include_account_events ). The resolved backend is stored on updater.update_backend for inspection or subclassing. from mt5cli import ThrottledHistoryUpdater , update_history def app_update_history ( ** kwargs ) -> None : update_history ( ** kwargs ) # or delegate to application-specific logic updater = ThrottledHistoryUpdater ( output = \"history.db\" , interval_seconds = 60 , update_backend = app_update_history , ) 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 \u00b6 For order placement and trading calculations, use the dedicated Trading module . Use mt5_session() / MT5Client for read-only collection.","title":"SDK"},{"location":"api/sdk/#sdk-module","text":"","title":"SDK Module"},{"location":"api/sdk/#mt5cli.sdk","text":"Programmatic SDK for MetaTrader 5 data collection.","title":"sdk"},{"location":"api/sdk/#mt5cli.sdk.T","text":"T = TypeVar ( 'T' )","title":"T"},{"location":"api/sdk/#mt5cli.sdk.UpdateHistoryBackend","text":"UpdateHistoryBackend = Callable [ ... , None ]","title":"UpdateHistoryBackend"},{"location":"api/sdk/#mt5cli.sdk.__all__","text":"__all__ = [ \"AccountSpec\" , \"Mt5CliClient\" , \"ThrottledHistoryUpdater\" , \"account_info\" , \"build_config\" , \"collect_history\" , \"collect_latest_closed_rates_by_granularity\" , \"collect_latest_closed_rates_for_accounts\" , \"collect_latest_rates\" , \"collect_latest_rates_for_accounts\" , \"collect_latest_rates_for_accounts_with_retries\" , \"connected_client\" , \"copy_rates_from\" , \"copy_rates_from_pos\" , \"copy_rates_range\" , \"copy_ticks_from\" , \"copy_ticks_range\" , \"fetch_latest_closed_rates\" , \"history_deals\" , \"history_orders\" , \"last_error\" , \"latest_rates\" , \"market_book\" , \"minimum_margins\" , \"mt5_session\" , \"mt5_summary\" , \"mt5_summary_as_df\" , \"orders\" , \"positions\" , \"recent_history_deals\" , \"recent_ticks\" , \"resolve_account_spec\" , \"resolve_account_specs\" , \"substitute_env_placeholders\" , \"substitute_mapping_values\" , \"symbol_info\" , \"symbol_info_tick\" , \"symbols\" , \"terminal_info\" , \"update_history\" , \"update_history_with_config\" , \"version\" , ]","title":"__all__"},{"location":"api/sdk/#mt5cli.sdk.logger","text":"logger = getLogger ( __name__ )","title":"logger"},{"location":"api/sdk/#mt5cli.sdk.AccountSpec","text":"AccountSpec ( symbols : Sequence [ str ], login : int | str | None = None , password : str | None = None , server : str | None = None , path : str | None = None , timeout : int | None = None , ) Connection parameters and symbols for one MT5 account group. Attributes: Name Type Description symbols Sequence [ str ] Symbols to load latest rates for under this account. login int | str | None Trading account login. String values are coerced to int when non-empty. password str | None Trading account password. server str | None Trading server name. path str | None Path to the MetaTrader5 terminal EXE file. timeout int | None Connection timeout in milliseconds.","title":"AccountSpec"},{"location":"api/sdk/#mt5cli.sdk.AccountSpec.login","text":"login : int | str | None = field ( default = None , repr = False )","title":"login"},{"location":"api/sdk/#mt5cli.sdk.AccountSpec.password","text":"password : str | None = field ( default = None , repr = False )","title":"password"},{"location":"api/sdk/#mt5cli.sdk.AccountSpec.path","text":"path : str | None = None","title":"path"},{"location":"api/sdk/#mt5cli.sdk.AccountSpec.server","text":"server : str | None = None","title":"server"},{"location":"api/sdk/#mt5cli.sdk.AccountSpec.symbols","text":"symbols : Sequence [ str ]","title":"symbols"},{"location":"api/sdk/#mt5cli.sdk.AccountSpec.timeout","text":"timeout : int | None = None","title":"timeout"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient","text":"Mt5CliClient ( * , path : str | None = None , login : int | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , retry_count : int = 3 , config : Mt5Config | None = None , client : Mt5DataClient | None = None , ) Programmatic client for read-only MetaTrader 5 data access. Initialize the SDK client. Parameters: Name Type Description Default path str | None Path to MetaTrader5 terminal EXE file. None login int | None Trading account login. None password str | None Trading account password. None server str | None Trading server name. None timeout int | None Connection timeout in milliseconds. None retry_count int Number of MT5 initialization retries for sessions opened by this client. 3 config Mt5Config | None Optional pre-built Mt5Config (overrides other args). None client Mt5DataClient | None Optional already-connected Mt5DataClient . Injected clients are reused as-is and are not initialized or shut down. None Source code in mt5cli/sdk.py 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 def __init__ ( self , * , path : str | None = None , login : int | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , retry_count : int = 3 , config : Mt5Config | None = None , client : Mt5DataClient | None = None , ) -> None : \"\"\"Initialize the SDK client. Args: path: Path to MetaTrader5 terminal EXE file. login: Trading account login. password: Trading account password. server: Trading server name. timeout: Connection timeout in milliseconds. retry_count: Number of MT5 initialization retries for sessions opened by this client. config: Optional pre-built ``Mt5Config`` (overrides other args). client: Optional already-connected ``Mt5DataClient``. Injected clients are reused as-is and are not initialized or shut down. \"\"\" self . _config = config or build_config ( path = path , login = login , password = password , server = server , timeout = timeout , ) self . _retry_count = retry_count self . _client = client self . _owns_client = client is None","title":"Mt5CliClient"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.config","text":"config : Mt5Config Return the underlying MT5 configuration.","title":"config"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.__enter__","text":"__enter__ () -> Self Open a persistent MT5 connection for multiple calls. Returns: Type Description Self This client instance. Source code in mt5cli/sdk.py 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 def __enter__ ( self ) -> Self : \"\"\"Open a persistent MT5 connection for multiple calls. Returns: This client instance. \"\"\" if self . _client is not None : return self client = Mt5DataClient ( config = self . _config , retry_count = self . _retry_count ) try : client . initialize_and_login_mt5 () except Exception : client . shutdown () raise self . _client = client self . _owns_client = True # only set when this method created the client return self","title":"__enter__"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.__exit__","text":"__exit__ ( exc_type : type [ BaseException ] | None , exc : BaseException | None , tb : object , ) -> None Shut down the persistent MT5 connection. Source code in mt5cli/sdk.py 486 487 488 489 490 491 492 493 494 495 def __exit__ ( self , exc_type : type [ BaseException ] | None , exc : BaseException | None , tb : object , ) -> None : \"\"\"Shut down the persistent MT5 connection.\"\"\" if self . _client is not None and self . _owns_client : self . _client . shutdown () self . _client = None","title":"__exit__"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.account_info","text":"account_info () -> DataFrame Return account information. Source code in mt5cli/sdk.py 649 650 651 def account_info ( self ) -> pd . DataFrame : \"\"\"Return account information.\"\"\" return self . _fetch ( lambda c : c . account_info_as_df ())","title":"account_info"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.collect_latest_rates","text":"collect_latest_rates ( symbols : Sequence [ str ], timeframes : Sequence [ int | str ], * , count : int , start_pos : int = 0 , ) -> dict [ tuple [ str , int ], DataFrame ] Return latest rates for each symbol/timeframe pair. Returns: Type Description dict [ tuple [ str , int ], DataFrame ] Mapping keyed by (symbol, timeframe_int) . Raises: Type Description ValueError If count is not positive or inputs are empty. Source code in mt5cli/sdk.py 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 def collect_latest_rates ( self , symbols : Sequence [ str ], timeframes : Sequence [ int | str ], * , count : int , start_pos : int = 0 , ) -> dict [ tuple [ str , int ], pd . DataFrame ]: \"\"\"Return latest rates for each symbol/timeframe pair. Returns: Mapping keyed by ``(symbol, timeframe_int)``. Raises: ValueError: If ``count`` is not positive or inputs are empty. \"\"\" _require_positive ( count , \"count\" ) if not symbols : msg = \"At least one symbol is required.\" raise ValueError ( msg ) if not timeframes : msg = \"At least one timeframe is required.\" raise ValueError ( msg ) resolved_timeframes = [ _coerce_timeframe ( timeframe ) for timeframe in timeframes ] return self . _fetch_value ( lambda c : { ( symbol , timeframe ): c . copy_rates_from_pos_as_df ( symbol = symbol , timeframe = timeframe , start_pos = start_pos , count = count , ) for symbol in symbols for timeframe in resolved_timeframes }, )","title":"collect_latest_rates"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.copy_rates_from","text":"copy_rates_from ( symbol : str , timeframe : int | str , date_from : datetime | str , count : int , ) -> DataFrame Return rates starting from a date. Source code in mt5cli/sdk.py 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 def copy_rates_from ( self , symbol : str , timeframe : int | str , date_from : datetime | str , count : int , ) -> pd . DataFrame : \"\"\"Return rates starting from a date.\"\"\" tf = _coerce_timeframe ( timeframe ) start = _require_datetime ( date_from ) return self . _fetch ( lambda c : c . copy_rates_from_as_df ( symbol = symbol , timeframe = tf , date_from = start , count = count , ), )","title":"copy_rates_from"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.copy_rates_from_pos","text":"copy_rates_from_pos ( symbol : str , timeframe : int | str , start_pos : int , count : int , ) -> DataFrame Return rates starting from a bar position. Source code in mt5cli/sdk.py 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 def copy_rates_from_pos ( self , symbol : str , timeframe : int | str , start_pos : int , count : int , ) -> pd . DataFrame : \"\"\"Return rates starting from a bar position.\"\"\" tf = _coerce_timeframe ( timeframe ) return self . _fetch ( lambda c : c . copy_rates_from_pos_as_df ( symbol = symbol , timeframe = tf , start_pos = start_pos , count = count , ), )","title":"copy_rates_from_pos"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.copy_rates_range","text":"copy_rates_range ( symbol : str , timeframe : int | str , date_from : datetime | str , date_to : datetime | str , ) -> DataFrame Return rates for a date range. Source code in mt5cli/sdk.py 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 def copy_rates_range ( self , symbol : str , timeframe : int | str , date_from : datetime | str , date_to : datetime | str , ) -> pd . DataFrame : \"\"\"Return rates for a date range.\"\"\" tf = _coerce_timeframe ( timeframe ) start = _require_datetime ( date_from ) end = _require_datetime ( date_to ) return self . _fetch ( lambda c : c . copy_rates_range_as_df ( symbol = symbol , timeframe = tf , date_from = start , date_to = end , ), )","title":"copy_rates_range"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.copy_ticks_from","text":"copy_ticks_from ( symbol : str , date_from : datetime | str , count : int , flags : int | str , ) -> DataFrame Return ticks starting from a date. Source code in mt5cli/sdk.py 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 def copy_ticks_from ( self , symbol : str , date_from : datetime | str , count : int , flags : int | str , ) -> pd . DataFrame : \"\"\"Return ticks starting from a date.\"\"\" start = _require_datetime ( date_from ) tick_flags = _coerce_tick_flags ( flags ) return self . _fetch ( lambda c : c . copy_ticks_from_as_df ( symbol = symbol , date_from = start , count = count , flags = tick_flags , ), )","title":"copy_ticks_from"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.copy_ticks_range","text":"copy_ticks_range ( symbol : str , date_from : datetime | str , date_to : datetime | str , flags : int | str , ) -> DataFrame Return ticks for a date range. Source code in mt5cli/sdk.py 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 def copy_ticks_range ( self , symbol : str , date_from : datetime | str , date_to : datetime | str , flags : int | str , ) -> pd . DataFrame : \"\"\"Return ticks for a date range.\"\"\" start = _require_datetime ( date_from ) end = _require_datetime ( date_to ) tick_flags = _coerce_tick_flags ( flags ) return self . _fetch ( lambda c : c . copy_ticks_range_as_df ( symbol = symbol , date_from = start , date_to = end , flags = tick_flags , ), )","title":"copy_ticks_range"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.from_connected_client","text":"from_connected_client ( client : Mt5DataClient ) -> Self Bind to an already-connected Mt5DataClient without owning it. The returned Mt5CliClient never initializes or shuts down the injected client, including when used as a context manager. Returns: Type Description Self Client wrapper bound to the injected connection. Source code in mt5cli/sdk.py 451 452 453 454 455 456 457 458 459 460 461 @classmethod def from_connected_client ( cls , client : Mt5DataClient ) -> Self : \"\"\"Bind to an already-connected ``Mt5DataClient`` without owning it. The returned ``Mt5CliClient`` never initializes or shuts down the injected client, including when used as a context manager. Returns: Client wrapper bound to the injected connection. \"\"\" return cls ( client = client )","title":"from_connected_client"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.history_deals","text":"history_deals ( date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , ) -> DataFrame Return historical deals. Source code in mt5cli/sdk.py 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 def history_deals ( self , date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , ) -> pd . DataFrame : \"\"\"Return historical deals.\"\"\" start = _coerce_datetime ( date_from ) end = _coerce_datetime ( date_to ) return self . _fetch ( lambda c : c . history_deals_get_as_df ( date_from = start , date_to = end , group = group , symbol = symbol , ticket = ticket , position = position , ), )","title":"history_deals"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.history_orders","text":"history_orders ( date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , ) -> DataFrame Return historical orders. Source code in mt5cli/sdk.py 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 def history_orders ( self , date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , ) -> pd . DataFrame : \"\"\"Return historical orders.\"\"\" start = _coerce_datetime ( date_from ) end = _coerce_datetime ( date_to ) return self . _fetch ( lambda c : c . history_orders_get_as_df ( date_from = start , date_to = end , group = group , symbol = symbol , ticket = ticket , position = position , ), )","title":"history_orders"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.last_error","text":"last_error () -> DataFrame Return the last error information. Source code in mt5cli/sdk.py 763 764 765 def last_error ( self ) -> pd . DataFrame : \"\"\"Return the last error information.\"\"\" return self . _fetch ( lambda c : c . last_error_as_df ())","title":"last_error"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.latest_rates","text":"latest_rates ( symbol : str , timeframe : int | str , count : int , start_pos : int = 0 , ) -> DataFrame Return the latest rates from a bar position. Source code in mt5cli/sdk.py 542 543 544 545 546 547 548 549 550 551 def latest_rates ( self , symbol : str , timeframe : int | str , count : int , start_pos : int = 0 , ) -> pd . DataFrame : \"\"\"Return the latest rates from a bar position.\"\"\" _require_positive ( count , \"count\" ) return self . copy_rates_from_pos ( symbol , timeframe , start_pos , count )","title":"latest_rates"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.market_book","text":"market_book ( symbol : str ) -> DataFrame Return market depth for a symbol. Source code in mt5cli/sdk.py 771 772 773 def market_book ( self , symbol : str ) -> pd . DataFrame : \"\"\"Return market depth for a symbol.\"\"\" return self . _fetch ( lambda c : c . market_book_get_as_df ( symbol = symbol ))","title":"market_book"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.minimum_margins","text":"minimum_margins ( symbol : str ) -> DataFrame Return minimum-volume buy and sell margin requirements. Parameters: Name Type Description Default symbol str Symbol name. required Returns: Type Description DataFrame One-row DataFrame with columns symbol , account_currency , DataFrame volume_min , buy_margin , and sell_margin . Source code in mt5cli/sdk.py 814 815 816 817 818 819 820 821 822 823 824 def minimum_margins ( self , symbol : str ) -> pd . DataFrame : \"\"\"Return minimum-volume buy and sell margin requirements. Args: symbol: Symbol name. Returns: One-row DataFrame with columns ``symbol``, ``account_currency``, ``volume_min``, ``buy_margin``, and ``sell_margin``. \"\"\" return self . _fetch ( lambda c : _fetch_minimum_margins ( c , symbol ))","title":"minimum_margins"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.mt5_summary","text":"mt5_summary () -> dict [ str , object ] Return a compact terminal/account status summary. Source code in mt5cli/sdk.py 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 def mt5_summary ( self ) -> dict [ str , object ]: \"\"\"Return a compact terminal/account status summary.\"\"\" def _summary ( client : Mt5DataClient ) -> dict [ str , object ]: return { \"version\" : _plain_mt5_value ( _call_required_client_method ( client , \"version\" ), ), \"terminal_info\" : _plain_mt5_value ( _call_required_client_method ( client , \"terminal_info\" ), ), \"account_info\" : _plain_mt5_value ( _call_required_client_method ( client , \"account_info\" ), ), \"symbols_total\" : _plain_mt5_value ( _call_required_client_method ( client , \"symbols_total\" ), ), } return self . _fetch_value ( _summary )","title":"mt5_summary"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.mt5_summary_as_df","text":"mt5_summary_as_df () -> DataFrame Return an export-safe one-row terminal/account summary DataFrame. Source code in mt5cli/sdk.py 847 848 849 850 851 852 853 854 855 856 857 def mt5_summary_as_df ( self ) -> pd . DataFrame : \"\"\"Return an export-safe one-row terminal/account summary DataFrame.\"\"\" summary = self . mt5_summary () return pd . DataFrame ( [ { key : _mt5_summary_export_value ( value ) for key , value in summary . items () }, ], )","title":"mt5_summary_as_df"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.orders","text":"orders ( symbol : str | None = None , group : str | None = None , ticket : int | None = None , ) -> DataFrame Return active orders. Source code in mt5cli/sdk.py 665 666 667 668 669 670 671 672 673 674 675 676 677 678 def orders ( self , symbol : str | None = None , group : str | None = None , ticket : int | None = None , ) -> pd . DataFrame : \"\"\"Return active orders.\"\"\" return self . _fetch ( lambda c : c . orders_get_as_df ( symbol = symbol , group = group , ticket = ticket , ), )","title":"orders"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.positions","text":"positions ( symbol : str | None = None , group : str | None = None , ticket : int | None = None , ) -> DataFrame Return open positions. Source code in mt5cli/sdk.py 680 681 682 683 684 685 686 687 688 689 690 691 692 693 def positions ( self , symbol : str | None = None , group : str | None = None , ticket : int | None = None , ) -> pd . DataFrame : \"\"\"Return open positions.\"\"\" return self . _fetch ( lambda c : c . positions_get_as_df ( symbol = symbol , group = group , ticket = ticket , ), )","title":"positions"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.recent_history_deals","text":"recent_history_deals ( hours : float , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ) -> DataFrame Return historical deals from a recent trailing window. Source code in mt5cli/sdk.py 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 def recent_history_deals ( self , hours : float , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ) -> pd . DataFrame : \"\"\"Return historical deals from a recent trailing window.\"\"\" _require_positive ( hours , \"hours\" ) end = _require_datetime ( date_to ) if date_to is not None else datetime . now ( UTC ) start = end - timedelta ( hours = hours ) return self . history_deals ( date_from = start , date_to = end , group = group , symbol = symbol , )","title":"recent_history_deals"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.recent_ticks","text":"recent_ticks ( symbol : str , seconds : float , * , date_to : datetime | str | None = None , count : int = 10000 , flags : int | str = \"ALL\" , ) -> DataFrame Return ticks from a recent time window. Parameters: Name Type Description Default symbol str Symbol name. required seconds float Lookback window in seconds ending at date_to . required date_to datetime | str | None Window end time. When None , uses the latest symbol_info_tick().time rather than wall-clock now. None count int Maximum ticks to return. Values <= 0 return the full window without trimming. Positive values keep the most recent ticks; when the window is sparse, copy_ticks_from avoids fetching the entire range. 10000 flags int | str Tick flags as ALL , INFO , TRADE , or an integer. 'ALL' Returns: Type Description DataFrame Tick DataFrame with MT5 tick columns such as time , bid , DataFrame ask , last , and volume . Source code in mt5cli/sdk.py 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 def recent_ticks ( self , symbol : str , seconds : float , * , date_to : datetime | str | None = None , count : int = 10000 , flags : int | str = \"ALL\" , ) -> pd . DataFrame : \"\"\"Return ticks from a recent time window. Args: symbol: Symbol name. seconds: Lookback window in seconds ending at ``date_to``. date_to: Window end time. When ``None``, uses the latest ``symbol_info_tick().time`` rather than wall-clock now. count: Maximum ticks to return. Values ``<= 0`` return the full window without trimming. Positive values keep the most recent ticks; when the window is sparse, ``copy_ticks_from`` avoids fetching the entire range. flags: Tick flags as ``ALL``, ``INFO``, ``TRADE``, or an integer. Returns: Tick DataFrame with MT5 tick columns such as ``time``, ``bid``, ``ask``, ``last``, and ``volume``. \"\"\" tick_flags = _coerce_tick_flags ( flags ) end = _coerce_datetime ( date_to ) return self . _fetch ( lambda c : _fetch_recent_ticks ( c , symbol , seconds , end , count , tick_flags , ), )","title":"recent_ticks"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.symbol_info","text":"symbol_info ( symbol : str ) -> DataFrame Return details for one symbol. Source code in mt5cli/sdk.py 661 662 663 def symbol_info ( self , symbol : str ) -> pd . DataFrame : \"\"\"Return details for one symbol.\"\"\" return self . _fetch ( lambda c : c . symbol_info_as_df ( symbol = symbol ))","title":"symbol_info"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.symbol_info_tick","text":"symbol_info_tick ( symbol : str ) -> DataFrame Return the last tick for a symbol. Source code in mt5cli/sdk.py 767 768 769 def symbol_info_tick ( self , symbol : str ) -> pd . DataFrame : \"\"\"Return the last tick for a symbol.\"\"\" return self . _fetch ( lambda c : c . symbol_info_tick_as_df ( symbol = symbol ))","title":"symbol_info_tick"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.symbols","text":"symbols ( group : str | None = None ) -> DataFrame Return the symbol list. Source code in mt5cli/sdk.py 657 658 659 def symbols ( self , group : str | None = None ) -> pd . DataFrame : \"\"\"Return the symbol list.\"\"\" return self . _fetch ( lambda c : c . symbols_get_as_df ( group = group ))","title":"symbols"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.terminal_info","text":"terminal_info () -> DataFrame Return terminal information. Source code in mt5cli/sdk.py 653 654 655 def terminal_info ( self ) -> pd . DataFrame : \"\"\"Return terminal information.\"\"\" return self . _fetch ( lambda c : c . terminal_info_as_df ())","title":"terminal_info"},{"location":"api/sdk/#mt5cli.sdk.Mt5CliClient.version","text":"version () -> DataFrame Return MetaTrader5 version information. Source code in mt5cli/sdk.py 759 760 761 def version ( self ) -> pd . DataFrame : \"\"\"Return MetaTrader5 version information.\"\"\" return self . _fetch ( lambda c : c . version_as_df ())","title":"version"},{"location":"api/sdk/#mt5cli.sdk.ThrottledHistoryUpdater","text":"ThrottledHistoryUpdater ( * , output : Path | str , datasets : set [ Dataset ] | None = None , timeframes : Sequence [ int | str ] | None = None , flags : int | str = \"ALL\" , lookback_hours : float = 24.0 , with_views : bool = False , include_account_events : bool = True , interval_seconds : float = 0.0 , suppress_errors : bool = False , update_backend : UpdateHistoryBackend | None = None , ) Throttled incremental SQLite history updater for long-running apps. Wraps :func: update_history (or a custom update_backend ) with a minimum interval between successful updates, so a tight application loop can call :meth: update every iteration without re-fetching MT5 history more often than desired. Timing uses a monotonic clock, so it is unaffected by wall-clock changes. Downstream applications may pass update_backend to substitute the default :func: update_history implementation\u2014for example to add application-specific logging, metrics, or test doubles\u2014without monkey- patching mt5cli.sdk.update_history . Initialize the throttled updater. Parameters: Name Type Description Default output Path | str SQLite database path. required datasets set [ Dataset ] | None Datasets to include (defaults to all). None timeframes Sequence [ int | str ] | None Rate timeframes to update (defaults to all fixed MT5 timeframes). None flags int | str Tick copy flags as integer or name (e.g. ALL ). 'ALL' lookback_hours float First-run lookback when a table has no prior rows. 24.0 with_views bool Create cash_events and positions_reconstructed views. False include_account_events bool Include account-level cash events. True interval_seconds float Minimum seconds between successful updates. Values <= 0 update on every call. 0.0 suppress_errors bool When True, recoverable errors ( Mt5TradingError , Mt5RuntimeError , sqlite3.Error , ValueError , OSError , and MT5 client capability AttributeError / TypeError for history API methods) raised during an update are swallowed and :meth: update returns False without advancing the throttle. Other AttributeError / TypeError values always propagate. When False (default), recoverable errors propagate so callers control logging. False update_backend UpdateHistoryBackend | None Callable invoked instead of :func: update_history when :meth: update runs. Receives the same keyword arguments as :func: update_history ( client , output , symbols , datasets , timeframes , flags , lookback_hours , with_views , include_account_events ). Defaults to :func: update_history . None Source code in mt5cli/sdk.py 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 def __init__ ( self , * , output : Path | str , datasets : set [ Dataset ] | None = None , timeframes : Sequence [ int | str ] | None = None , flags : int | str = \"ALL\" , lookback_hours : float = 24.0 , with_views : bool = False , include_account_events : bool = True , interval_seconds : float = 0.0 , suppress_errors : bool = False , update_backend : UpdateHistoryBackend | None = None , ) -> None : \"\"\"Initialize the throttled updater. Args: output: SQLite database path. datasets: Datasets to include (defaults to all). timeframes: Rate timeframes to update (defaults to all fixed MT5 timeframes). flags: Tick copy flags as integer or name (e.g. ``ALL``). lookback_hours: First-run lookback when a table has no prior rows. with_views: Create ``cash_events`` and ``positions_reconstructed`` views. include_account_events: Include account-level cash events. interval_seconds: Minimum seconds between successful updates. Values ``<= 0`` update on every call. suppress_errors: When True, recoverable errors (``Mt5TradingError``, ``Mt5RuntimeError``, ``sqlite3.Error``, ``ValueError``, ``OSError``, and MT5 client capability ``AttributeError`` / ``TypeError`` for history API methods) raised during an update are swallowed and :meth:`update` returns False without advancing the throttle. Other ``AttributeError`` / ``TypeError`` values always propagate. When False (default), recoverable errors propagate so callers control logging. update_backend: Callable invoked instead of :func:`update_history` when :meth:`update` runs. Receives the same keyword arguments as :func:`update_history` (``client``, ``output``, ``symbols``, ``datasets``, ``timeframes``, ``flags``, ``lookback_hours``, ``with_views``, ``include_account_events``). Defaults to :func:`update_history`. \"\"\" self . output = output self . datasets = datasets self . timeframes = timeframes self . flags = flags self . lookback_hours = lookback_hours self . with_views = with_views self . include_account_events = include_account_events self . interval_seconds = interval_seconds self . suppress_errors = suppress_errors self . update_backend = ( update_history if update_backend is None else update_backend ) self . _last_update_monotonic : float | None = None","title":"ThrottledHistoryUpdater"},{"location":"api/sdk/#mt5cli.sdk.ThrottledHistoryUpdater.datasets","text":"datasets = datasets","title":"datasets"},{"location":"api/sdk/#mt5cli.sdk.ThrottledHistoryUpdater.flags","text":"flags = flags","title":"flags"},{"location":"api/sdk/#mt5cli.sdk.ThrottledHistoryUpdater.include_account_events","text":"include_account_events = include_account_events","title":"include_account_events"},{"location":"api/sdk/#mt5cli.sdk.ThrottledHistoryUpdater.interval_seconds","text":"interval_seconds = interval_seconds","title":"interval_seconds"},{"location":"api/sdk/#mt5cli.sdk.ThrottledHistoryUpdater.last_update_monotonic","text":"last_update_monotonic : float | None Return the monotonic timestamp of the last successful update.","title":"last_update_monotonic"},{"location":"api/sdk/#mt5cli.sdk.ThrottledHistoryUpdater.lookback_hours","text":"lookback_hours = lookback_hours","title":"lookback_hours"},{"location":"api/sdk/#mt5cli.sdk.ThrottledHistoryUpdater.output","text":"output = output","title":"output"},{"location":"api/sdk/#mt5cli.sdk.ThrottledHistoryUpdater.suppress_errors","text":"suppress_errors = suppress_errors","title":"suppress_errors"},{"location":"api/sdk/#mt5cli.sdk.ThrottledHistoryUpdater.timeframes","text":"timeframes = timeframes","title":"timeframes"},{"location":"api/sdk/#mt5cli.sdk.ThrottledHistoryUpdater.update_backend","text":"update_backend = ( update_history if update_backend is None else update_backend )","title":"update_backend"},{"location":"api/sdk/#mt5cli.sdk.ThrottledHistoryUpdater.with_views","text":"with_views = with_views","title":"with_views"},{"location":"api/sdk/#mt5cli.sdk.ThrottledHistoryUpdater.should_update","text":"should_update () -> bool Return whether enough time has elapsed to run another update. Returns: Type Description bool True when interval_seconds <= 0 , when no update has succeeded bool yet, or when at least interval_seconds have elapsed since the bool last successful update. Source code in mt5cli/sdk.py 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 def should_update ( self ) -> bool : \"\"\"Return whether enough time has elapsed to run another update. Returns: True when ``interval_seconds <= 0``, when no update has succeeded yet, or when at least ``interval_seconds`` have elapsed since the last successful update. \"\"\" if self . interval_seconds <= 0 or self . _last_update_monotonic is None : return True return ( time . monotonic () - self . _last_update_monotonic ) >= self . interval_seconds","title":"should_update"},{"location":"api/sdk/#mt5cli.sdk.ThrottledHistoryUpdater.update","text":"update ( client : Mt5DataClient , symbols : Sequence [ str ] ) -> bool Run a throttled incremental history update. Parameters: Name Type Description Default client Mt5DataClient Connected MT5 data client. required symbols Sequence [ str ] Symbols to update. required Returns: Type Description bool True if an update ran successfully, False if it was throttled or bool (when suppress_errors is True) failed with a recoverable error. bool When suppress_errors is False, recoverable update failures bool propagate to the caller. Raises: Type Description AttributeError MT5 client capability mismatch when suppress_errors is False, or any other attribute error. TypeError MT5 client capability mismatch when suppress_errors is False, or any other type error. Source code in mt5cli/sdk.py 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 def update ( self , client : Mt5DataClient , symbols : Sequence [ str ]) -> bool : \"\"\"Run a throttled incremental history update. Args: client: Connected MT5 data client. symbols: Symbols to update. Returns: True if an update ran successfully, False if it was throttled or (when ``suppress_errors`` is True) failed with a recoverable error. When ``suppress_errors`` is False, recoverable update failures propagate to the caller. Raises: AttributeError: MT5 client capability mismatch when ``suppress_errors`` is False, or any other attribute error. TypeError: MT5 client capability mismatch when ``suppress_errors`` is False, or any other type error. \"\"\" if not self . should_update (): return False try : _resolve_update_history_request ( output = self . output , symbols = symbols , datasets = self . datasets , timeframes = self . timeframes , flags = self . flags , lookback_hours = self . lookback_hours , date_to = None , ) self . update_backend ( client = client , output = self . output , symbols = symbols , datasets = self . datasets , timeframes = self . timeframes , flags = self . flags , lookback_hours = self . lookback_hours , with_views = self . with_views , include_account_events = self . include_account_events , ) except _RECOVERABLE_HISTORY_UPDATE_ERRORS : if self . suppress_errors : logger . warning ( \"Suppressed history update error\" , exc_info = True ) return False raise except ( AttributeError , TypeError ) as exc : if self . suppress_errors and _is_mt5_client_capability_error ( exc ): logger . warning ( \"Suppressed history update error\" , exc_info = True ) return False raise self . _last_update_monotonic = time . monotonic () return True","title":"update"},{"location":"api/sdk/#mt5cli.sdk.account_info","text":"account_info ( * , config : Mt5Config | None = None ) -> DataFrame Return account information. Source code in mt5cli/sdk.py 1956 1957 1958 def account_info ( * , config : Mt5Config | None = None ) -> pd . DataFrame : \"\"\"Return account information.\"\"\" return _make_client ( config = config ) . account_info ()","title":"account_info"},{"location":"api/sdk/#mt5cli.sdk.build_config","text":"build_config ( * , path : str | None = None , login : int | str | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , allow_whole_dollar_env : bool = False , ) -> Mt5Config Build an Mt5Config from optional connection parameters. Parameters: Name Type Description Default path str | None Optional terminal executable path. None login int | str | None Optional trading account login. Integers are preserved. String values are coerced: empty or whitespace-only strings become None ; numeric strings such as \"12345\" are converted to int ; non-numeric strings raise ValueError . When allow_whole_dollar_env=True , $ENV_NAME and ${ENV_NAME} placeholders are expanded before coercion. None password str | None Optional trading account password. None server str | None Optional trading server name. None timeout int | None Optional connection timeout in milliseconds. None allow_whole_dollar_env bool When True , string parameters that are exactly $ENV_NAME are expanded from the environment. Applies to path , login , password , and server . Default False preserves existing behavior. False Returns: Type Description Mt5Config Configured Mt5Config instance. Source code in mt5cli/sdk.py 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 def build_config ( * , path : str | None = None , login : int | str | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , allow_whole_dollar_env : bool = False , ) -> Mt5Config : \"\"\"Build an ``Mt5Config`` from optional connection parameters. Args: path: Optional terminal executable path. login: Optional trading account login. Integers are preserved. String values are coerced: empty or whitespace-only strings become ``None``; numeric strings such as ``\"12345\"`` are converted to ``int``; non-numeric strings raise ``ValueError``. When ``allow_whole_dollar_env=True``, ``$ENV_NAME`` and ``${ENV_NAME}`` placeholders are expanded before coercion. password: Optional trading account password. server: Optional trading server name. timeout: Optional connection timeout in milliseconds. allow_whole_dollar_env: When ``True``, string parameters that are exactly ``$ENV_NAME`` are expanded from the environment. Applies to ``path``, ``login``, ``password``, and ``server``. Default ``False`` preserves existing behavior. Returns: Configured ``Mt5Config`` instance. \"\"\" if allow_whole_dollar_env : if path is not None : path = substitute_env_placeholders ( path , allow_whole_dollar_env = True ) if isinstance ( login , str ): login = substitute_env_placeholders ( login , allow_whole_dollar_env = True ) if password is not None : password = substitute_env_placeholders ( password , allow_whole_dollar_env = True ) if server is not None : server = substitute_env_placeholders ( server , allow_whole_dollar_env = True ) return Mt5Config ( path = path , login = _coerce_login ( login ), password = password , server = server , timeout = timeout , )","title":"build_config"},{"location":"api/sdk/#mt5cli.sdk.collect_history","text":"collect_history ( output : Path , symbols : list [ str ], date_from : datetime | str , date_to : datetime | str , * , datasets : set [ Dataset ] | None = None , timeframe : int | str = 1 , flags : int | str = \"ALL\" , if_exists : IfExists = FAIL , with_views : bool = False , config : Mt5Config | None = None , ) -> None Collect historical datasets into a single SQLite database. Parameters: Name Type Description Default output Path SQLite database path. required symbols list [ str ] Symbols to collect. required date_from datetime | str Start date. required date_to datetime | str End date. required datasets set [ Dataset ] | None Datasets to include (defaults to all). None timeframe int | str Rates timeframe as integer or name (e.g. M1 ). 1 flags int | str Tick copy flags as integer or name (e.g. ALL ). 'ALL' if_exists IfExists Behavior when a target table already exists. FAIL with_views bool Create cash_events and positions_reconstructed views. False config Mt5Config | None MT5 connection configuration. None Source code in mt5cli/sdk.py 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 def collect_history ( output : Path , symbols : list [ str ], date_from : datetime | str , date_to : datetime | str , * , datasets : set [ Dataset ] | None = None , timeframe : int | str = 1 , flags : int | str = \"ALL\" , if_exists : IfExists = IfExists . FAIL , with_views : bool = False , config : Mt5Config | None = None , ) -> None : \"\"\"Collect historical datasets into a single SQLite database. Args: output: SQLite database path. symbols: Symbols to collect. date_from: Start date. date_to: End date. datasets: Datasets to include (defaults to all). timeframe: Rates timeframe as integer or name (e.g. ``M1``). flags: Tick copy flags as integer or name (e.g. ``ALL``). if_exists: Behavior when a target table already exists. with_views: Create ``cash_events`` and ``positions_reconstructed`` views. config: MT5 connection configuration. \"\"\" start = _require_datetime ( date_from ) end = _require_datetime ( date_to ) selected = datasets if datasets is not None else set ( Dataset ) tf = _coerce_timeframe ( timeframe ) tick_flags = _coerce_tick_flags ( flags ) mt5_config = config or build_config () with connected_client ( mt5_config ) as client , sqlite3 . connect ( output ) as conn : conn . execute ( \"PRAGMA journal_mode=WAL\" ) conn . execute ( \"PRAGMA synchronous=NORMAL\" ) written_tables , written_columns = write_collected_datasets ( conn , client , symbols , selected , tf , tick_flags , start , end , if_exists , ) create_history_indexes ( conn , written_columns ) if with_views and Dataset . history_deals in written_tables : create_cash_events_view ( conn , written_columns [ Dataset . history_deals ]) create_positions_reconstructed_view ( conn , written_columns [ Dataset . history_deals ], ) elif with_views : logger . warning ( \"--with-views ignored: history_deals table was not written\" , ) logger . info ( \"Collected %s for %d symbol(s) into %s \" , \", \" . join ( sorted ( ds . value for ds in selected )), len ( symbols ), output , )","title":"collect_history"},{"location":"api/sdk/#mt5cli.sdk.collect_latest_closed_rates_by_granularity","text":"collect_latest_closed_rates_by_granularity ( accounts : Sequence [ AccountSpec ], granularities : Sequence [ int | str ], count : int , * , start_pos : int = 0 , base_config : Mt5Config | None = None , retry_count : int = 0 , backoff_base : float = 2.0 , ) -> dict [ tuple [ str , str ], DataFrame ] Collect latest closed rate bars keyed by symbol and granularity name. Thin wrapper around :func: collect_latest_closed_rates_for_accounts that rekeys the result by granularity name (for example M1 ) instead of the integer timeframe. Parameters: Name Type Description Default accounts Sequence [ AccountSpec ] Account groups to read. Each must define at least one symbol. required granularities Sequence [ int | str ] MT5 timeframes as integers or names (for example M1 ). required count int Number of closed bars to return per symbol/timeframe. required start_pos int Initial bar position offset passed to the underlying collector. 0 base_config Mt5Config | None Optional base configuration whose fields fill any value not set on an individual account. None retry_count int Maximum number of retries after the first attempt. 0 disables retries. 0 backoff_base float Base for exponential backoff between retry attempts. 2.0 Returns: Type Description dict [ tuple [ str , str ], DataFrame ] Mapping keyed by (symbol, granularity_name) . Propagates dict [ tuple [ str , str ], DataFrame ] ValueError from :func: collect_latest_closed_rates_for_accounts . Source code in mt5cli/sdk.py 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 def collect_latest_closed_rates_by_granularity ( accounts : Sequence [ AccountSpec ], granularities : Sequence [ int | str ], count : int , * , start_pos : int = 0 , base_config : Mt5Config | None = None , retry_count : int = 0 , backoff_base : float = 2.0 , ) -> dict [ tuple [ str , str ], pd . DataFrame ]: \"\"\"Collect latest closed rate bars keyed by symbol and granularity name. Thin wrapper around :func:`collect_latest_closed_rates_for_accounts` that rekeys the result by granularity name (for example ``M1``) instead of the integer timeframe. Args: accounts: Account groups to read. Each must define at least one symbol. granularities: MT5 timeframes as integers or names (for example ``M1``). count: Number of closed bars to return per symbol/timeframe. start_pos: Initial bar position offset passed to the underlying collector. base_config: Optional base configuration whose fields fill any value not set on an individual account. retry_count: Maximum number of retries after the first attempt. ``0`` disables retries. backoff_base: Base for exponential backoff between retry attempts. Returns: Mapping keyed by ``(symbol, granularity_name)``. Propagates ``ValueError`` from :func:`collect_latest_closed_rates_for_accounts`. \"\"\" loaded = collect_latest_closed_rates_for_accounts ( accounts , granularities , count , start_pos = start_pos , base_config = base_config , retry_count = retry_count , backoff_base = backoff_base , ) return { ( symbol , resolve_granularity_name ( timeframe )): frame for ( symbol , timeframe ), frame in loaded . items () }","title":"collect_latest_closed_rates_by_granularity"},{"location":"api/sdk/#mt5cli.sdk.collect_latest_closed_rates_for_accounts","text":"collect_latest_closed_rates_for_accounts ( accounts : Sequence [ AccountSpec ], timeframes : Sequence [ int | str ], count : int , * , start_pos : int = 0 , base_config : Mt5Config | None = None , retry_count : int = 0 , backoff_base : float = 2.0 , ) -> dict [ tuple [ str , int ], DataFrame ] Collect latest closed rate bars across multiple MT5 account groups. When start_pos is 0 (the default), MetaTrader 5 includes the still-forming current bar as the last row. This helper fetches count + 1 bars, drops that bar with :func: drop_forming_rate_bar , and validates that each resulting frame is non-empty. When start_pos is greater than zero the forming bar is not in range, so only count bars are fetched and no row is dropped. Wraps :func: collect_latest_rates_for_accounts_with_retries for transient MT5 error handling. Parameters: Name Type Description Default accounts Sequence [ AccountSpec ] Account groups to read. Each must define at least one symbol. required timeframes Sequence [ int | str ] MT5 timeframes as integers or names (for example M1 ). required count int Number of closed bars to return per symbol/timeframe. required start_pos int Initial bar position offset passed to the underlying collector. 0 base_config Mt5Config | None Optional base configuration whose fields fill any value not set on an individual account. None retry_count int Maximum number of retries after the first attempt. 0 disables retries. 0 backoff_base float Base for exponential backoff between retry attempts. 2.0 Returns: Type Description dict [ tuple [ str , int ], DataFrame ] Mapping keyed by (symbol, timeframe_int) . Raises: Type Description ValueError If inputs are invalid, or any series is empty (after dropping the still-forming bar when start_pos is 0 ). Source code in mt5cli/sdk.py 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 def collect_latest_closed_rates_for_accounts ( accounts : Sequence [ AccountSpec ], timeframes : Sequence [ int | str ], count : int , * , start_pos : int = 0 , base_config : Mt5Config | None = None , retry_count : int = 0 , backoff_base : float = 2.0 , ) -> dict [ tuple [ str , int ], pd . DataFrame ]: \"\"\"Collect latest closed rate bars across multiple MT5 account groups. When ``start_pos`` is ``0`` (the default), MetaTrader 5 includes the still-forming current bar as the last row. This helper fetches ``count + 1`` bars, drops that bar with :func:`drop_forming_rate_bar`, and validates that each resulting frame is non-empty. When ``start_pos`` is greater than zero the forming bar is not in range, so only ``count`` bars are fetched and no row is dropped. Wraps :func:`collect_latest_rates_for_accounts_with_retries` for transient MT5 error handling. Args: accounts: Account groups to read. Each must define at least one symbol. timeframes: MT5 timeframes as integers or names (for example ``M1``). count: Number of closed bars to return per symbol/timeframe. start_pos: Initial bar position offset passed to the underlying collector. base_config: Optional base configuration whose fields fill any value not set on an individual account. retry_count: Maximum number of retries after the first attempt. ``0`` disables retries. backoff_base: Base for exponential backoff between retry attempts. Returns: Mapping keyed by ``(symbol, timeframe_int)``. Raises: ValueError: If inputs are invalid, or any series is empty (after dropping the still-forming bar when ``start_pos`` is ``0``). \"\"\" _require_positive ( count , \"count\" ) _require_non_negative ( start_pos , \"start_pos\" ) fetch_count = count + 1 if start_pos == 0 else count loaded = collect_latest_rates_for_accounts_with_retries ( accounts , timeframes , fetch_count , start_pos = start_pos , base_config = base_config , retry_count = retry_count , backoff_base = backoff_base , ) result : dict [ tuple [ str , int ], pd . DataFrame ] = {} for key , df_rate in loaded . items (): closed = drop_forming_rate_bar ( df_rate ) if start_pos == 0 else df_rate if closed . empty : symbol , timeframe = key msg = f \"Rate data is empty for { symbol !r} at timeframe { timeframe } .\" raise ValueError ( msg ) result [ key ] = closed return result","title":"collect_latest_closed_rates_for_accounts"},{"location":"api/sdk/#mt5cli.sdk.collect_latest_rates","text":"collect_latest_rates ( symbols : Sequence [ str ], timeframes : Sequence [ int | str ], * , count : int , start_pos : int = 0 , config : Mt5Config | None = None , ) -> dict [ tuple [ str , int ], DataFrame ] Return latest rates for each symbol/timeframe pair. Source code in mt5cli/sdk.py 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 def collect_latest_rates ( symbols : Sequence [ str ], timeframes : Sequence [ int | str ], * , count : int , start_pos : int = 0 , config : Mt5Config | None = None , ) -> dict [ tuple [ str , int ], pd . DataFrame ]: \"\"\"Return latest rates for each symbol/timeframe pair.\"\"\" return _make_client ( config = config ) . collect_latest_rates ( symbols , timeframes , count = count , start_pos = start_pos , )","title":"collect_latest_rates"},{"location":"api/sdk/#mt5cli.sdk.collect_latest_rates_for_accounts","text":"collect_latest_rates_for_accounts ( accounts : Sequence [ AccountSpec ], timeframes : Sequence [ int | str ], count : int , * , start_pos : int = 0 , base_config : Mt5Config | None = None , ) -> dict [ tuple [ str , int ], DataFrame ] Collect latest rates across multiple MT5 account groups. Each account is connected in turn, its symbols are read for every timeframe, and the resulting frames are merged into a single mapping. Parameters: Name Type Description Default accounts Sequence [ AccountSpec ] Account groups to read. Each must define at least one symbol. required timeframes Sequence [ int | str ] MT5 timeframes as integers or names (for example M1 ). required count int Number of most recent bars to read per symbol/timeframe. required start_pos int Initial bar position offset. 0 base_config Mt5Config | None Optional base configuration whose fields fill any value not set on an individual account. None Returns: Type Description dict [ tuple [ str , int ], DataFrame ] Mapping keyed by (symbol, timeframe_int) . When accounts share a dict [ tuple [ str , int ], DataFrame ] symbol/timeframe pair, the last account processed wins. Raises: Type Description ValueError If accounts , timeframes , or any account's symbols are empty, or count is not positive. Source code in mt5cli/sdk.py 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 def collect_latest_rates_for_accounts ( accounts : Sequence [ AccountSpec ], timeframes : Sequence [ int | str ], count : int , * , start_pos : int = 0 , base_config : Mt5Config | None = None , ) -> dict [ tuple [ str , int ], pd . DataFrame ]: \"\"\"Collect latest rates across multiple MT5 account groups. Each account is connected in turn, its symbols are read for every timeframe, and the resulting frames are merged into a single mapping. Args: accounts: Account groups to read. Each must define at least one symbol. timeframes: MT5 timeframes as integers or names (for example ``M1``). count: Number of most recent bars to read per symbol/timeframe. start_pos: Initial bar position offset. base_config: Optional base configuration whose fields fill any value not set on an individual account. Returns: Mapping keyed by ``(symbol, timeframe_int)``. When accounts share a symbol/timeframe pair, the last account processed wins. Raises: ValueError: If ``accounts``, ``timeframes``, or any account's symbols are empty, or ``count`` is not positive. \"\"\" account_list = list ( accounts ) if not account_list : msg = \"At least one account is required.\" raise ValueError ( msg ) if not timeframes : msg = \"At least one timeframe is required.\" raise ValueError ( msg ) if any ( not account . symbols for account in account_list ): msg = \"Each account requires at least one symbol.\" raise ValueError ( msg ) _require_positive ( count , \"count\" ) result : dict [ tuple [ str , int ], pd . DataFrame ] = {} for account in account_list : config = _build_account_config ( account , base_config ) with Mt5CliClient ( config = config ) as client : result . update ( client . collect_latest_rates ( account . symbols , timeframes , count = count , start_pos = start_pos , ), ) return result","title":"collect_latest_rates_for_accounts"},{"location":"api/sdk/#mt5cli.sdk.collect_latest_rates_for_accounts_with_retries","text":"collect_latest_rates_for_accounts_with_retries ( accounts : Sequence [ AccountSpec ], timeframes : Sequence [ int | str ], count : int , * , start_pos : int = 0 , base_config : Mt5Config | None = None , retry_count : int = 0 , backoff_base : float = 2.0 , ) -> dict [ tuple [ str , int ], DataFrame ] Collect latest rates across accounts, retrying transient MT5 failures. Wraps :func: collect_latest_rates_for_accounts with bounded exponential backoff. Only pdmt5.Mt5TradingError and pdmt5.Mt5RuntimeError are retried; other exceptions propagate immediately. The final failure is re-raised once retries are exhausted. Parameters: Name Type Description Default accounts Sequence [ AccountSpec ] Account groups to read. Each must define at least one symbol. required timeframes Sequence [ int | str ] MT5 timeframes as integers or names (for example M1 ). required count int Number of most recent bars to read per symbol/timeframe. required start_pos int Initial bar position offset. 0 base_config Mt5Config | None Optional base configuration whose fields fill any value not set on an individual account. None retry_count int Maximum number of retries after the first attempt. 0 disables retries. 0 backoff_base float Base for exponential backoff. The delay before retry attempt n (1-indexed) is backoff_base ** n seconds. 2.0 Returns: Type Description dict [ tuple [ str , int ], DataFrame ] Mapping keyed by (symbol, timeframe_int) . Propagates ValueError dict [ tuple [ str , int ], DataFrame ] for invalid inputs (see :func: collect_latest_rates_for_accounts ) and dict [ tuple [ str , int ], DataFrame ] re-raises the last pdmt5.Mt5TradingError or pdmt5.Mt5RuntimeError dict [ tuple [ str , int ], DataFrame ] once retries are exhausted. Source code in mt5cli/sdk.py 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 def collect_latest_rates_for_accounts_with_retries ( accounts : Sequence [ AccountSpec ], timeframes : Sequence [ int | str ], count : int , * , start_pos : int = 0 , base_config : Mt5Config | None = None , retry_count : int = 0 , backoff_base : float = 2.0 , ) -> dict [ tuple [ str , int ], pd . DataFrame ]: \"\"\"Collect latest rates across accounts, retrying transient MT5 failures. Wraps :func:`collect_latest_rates_for_accounts` with bounded exponential backoff. Only ``pdmt5.Mt5TradingError`` and ``pdmt5.Mt5RuntimeError`` are retried; other exceptions propagate immediately. The final failure is re-raised once retries are exhausted. Args: accounts: Account groups to read. Each must define at least one symbol. timeframes: MT5 timeframes as integers or names (for example ``M1``). count: Number of most recent bars to read per symbol/timeframe. start_pos: Initial bar position offset. base_config: Optional base configuration whose fields fill any value not set on an individual account. retry_count: Maximum number of retries after the first attempt. ``0`` disables retries. backoff_base: Base for exponential backoff. The delay before retry attempt ``n`` (1-indexed) is ``backoff_base ** n`` seconds. Returns: Mapping keyed by ``(symbol, timeframe_int)``. Propagates ``ValueError`` for invalid inputs (see :func:`collect_latest_rates_for_accounts`) and re-raises the last ``pdmt5.Mt5TradingError`` or ``pdmt5.Mt5RuntimeError`` once retries are exhausted. \"\"\" def _collect () -> dict [ tuple [ str , int ], pd . DataFrame ]: return collect_latest_rates_for_accounts ( accounts , timeframes , count , start_pos = start_pos , base_config = base_config , ) return retry_with_backoff ( _collect , retry_count = retry_count , backoff_base = backoff_base , operation = \"Rate collection\" , )","title":"collect_latest_rates_for_accounts_with_retries"},{"location":"api/sdk/#mt5cli.sdk.connected_client","text":"connected_client ( config : Mt5Config , ) -> Iterator [ Mt5DataClient ] Initialize MT5, yield a connected client, and always shut down. Parameters: Name Type Description Default config Mt5Config MT5 connection configuration. required Yields: Type Description Mt5DataClient Connected Mt5DataClient instance. Source code in mt5cli/sdk.py 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 @contextmanager def connected_client ( config : Mt5Config ) -> Iterator [ Mt5DataClient ]: \"\"\"Initialize MT5, yield a connected client, and always shut down. Args: config: MT5 connection configuration. Yields: Connected ``Mt5DataClient`` instance. \"\"\" client = Mt5DataClient ( config = config ) try : client . initialize_and_login_mt5 () yield client finally : client . shutdown ()","title":"connected_client"},{"location":"api/sdk/#mt5cli.sdk.copy_rates_from","text":"copy_rates_from ( symbol : str , timeframe : int | str , date_from : datetime | str , count : int , * , config : Mt5Config | None = None , ) -> DataFrame Return rates starting from a date. Source code in mt5cli/sdk.py 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 def copy_rates_from ( symbol : str , timeframe : int | str , date_from : datetime | str , count : int , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return rates starting from a date.\"\"\" return _make_client ( config = config ) . copy_rates_from ( symbol , timeframe , date_from , count , )","title":"copy_rates_from"},{"location":"api/sdk/#mt5cli.sdk.copy_rates_from_pos","text":"copy_rates_from_pos ( symbol : str , timeframe : int | str , start_pos : int , count : int , * , config : Mt5Config | None = None , ) -> DataFrame Return rates starting from a bar position. Source code in mt5cli/sdk.py 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 def copy_rates_from_pos ( symbol : str , timeframe : int | str , start_pos : int , count : int , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return rates starting from a bar position.\"\"\" return _make_client ( config = config ) . copy_rates_from_pos ( symbol , timeframe , start_pos , count , )","title":"copy_rates_from_pos"},{"location":"api/sdk/#mt5cli.sdk.copy_rates_range","text":"copy_rates_range ( symbol : str , timeframe : int | str , date_from : datetime | str , date_to : datetime | str , * , config : Mt5Config | None = None , ) -> DataFrame Return rates for a date range. Source code in mt5cli/sdk.py 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 def copy_rates_range ( symbol : str , timeframe : int | str , date_from : datetime | str , date_to : datetime | str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return rates for a date range.\"\"\" return _make_client ( config = config ) . copy_rates_range ( symbol , timeframe , date_from , date_to , )","title":"copy_rates_range"},{"location":"api/sdk/#mt5cli.sdk.copy_ticks_from","text":"copy_ticks_from ( symbol : str , date_from : datetime | str , count : int , flags : int | str , * , config : Mt5Config | None = None , ) -> DataFrame Return ticks starting from a date. Source code in mt5cli/sdk.py 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 def copy_ticks_from ( symbol : str , date_from : datetime | str , count : int , flags : int | str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return ticks starting from a date.\"\"\" return _make_client ( config = config ) . copy_ticks_from ( symbol , date_from , count , flags , )","title":"copy_ticks_from"},{"location":"api/sdk/#mt5cli.sdk.copy_ticks_range","text":"copy_ticks_range ( symbol : str , date_from : datetime | str , date_to : datetime | str , flags : int | str , * , config : Mt5Config | None = None , ) -> DataFrame Return ticks for a date range. Source code in mt5cli/sdk.py 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 def copy_ticks_range ( symbol : str , date_from : datetime | str , date_to : datetime | str , flags : int | str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return ticks for a date range.\"\"\" return _make_client ( config = config ) . copy_ticks_range ( symbol , date_from , date_to , flags , )","title":"copy_ticks_range"},{"location":"api/sdk/#mt5cli.sdk.fetch_latest_closed_rates","text":"fetch_latest_closed_rates ( client : Mt5CliClient , * , symbol : str , granularity : str , count : int , ) -> DataFrame Fetch up to count most recent closed bars, oldest to newest. Returns: Type Description DataFrame Closed rate bars ordered oldest to newest. Raises: Type Description ValueError If count is not positive or no closed bars are returned. Source code in mt5cli/sdk.py 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 def fetch_latest_closed_rates ( client : Mt5CliClient , * , symbol : str , granularity : str , count : int , ) -> pd . DataFrame : \"\"\"Fetch up to ``count`` most recent closed bars, oldest to newest. Returns: Closed rate bars ordered oldest to newest. Raises: ValueError: If ``count`` is not positive or no closed bars are returned. \"\"\" _require_positive ( count , \"count\" ) frame = client . latest_rates ( symbol , granularity , count + 1 , start_pos = 0 ) closed = drop_forming_rate_bar ( frame ) if closed . empty : msg = ( f \"Rate data is empty for { symbol !r} at granularity { granularity !r} \" f \"with count { count } .\" ) raise ValueError ( msg ) return closed . tail ( count ) . reset_index ( drop = True )","title":"fetch_latest_closed_rates"},{"location":"api/sdk/#mt5cli.sdk.history_deals","text":"history_deals ( date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , * , config : Mt5Config | None = None , ) -> DataFrame Return historical deals. Source code in mt5cli/sdk.py 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 def history_deals ( date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return historical deals.\"\"\" return _make_client ( config = config ) . history_deals ( date_from = date_from , date_to = date_to , group = group , symbol = symbol , ticket = ticket , position = position , )","title":"history_deals"},{"location":"api/sdk/#mt5cli.sdk.history_orders","text":"history_orders ( date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , * , config : Mt5Config | None = None , ) -> DataFrame Return historical orders. Source code in mt5cli/sdk.py 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 def history_orders ( date_from : datetime | str | None = None , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , ticket : int | None = None , position : int | None = None , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return historical orders.\"\"\" return _make_client ( config = config ) . history_orders ( date_from = date_from , date_to = date_to , group = group , symbol = symbol , ticket = ticket , position = position , )","title":"history_orders"},{"location":"api/sdk/#mt5cli.sdk.last_error","text":"last_error ( * , config : Mt5Config | None = None ) -> DataFrame Return the last error information. Source code in mt5cli/sdk.py 2078 2079 2080 def last_error ( * , config : Mt5Config | None = None ) -> pd . DataFrame : \"\"\"Return the last error information.\"\"\" return _make_client ( config = config ) . last_error ()","title":"last_error"},{"location":"api/sdk/#mt5cli.sdk.latest_rates","text":"latest_rates ( symbol : str , timeframe : int | str , count : int , start_pos : int = 0 , * , config : Mt5Config | None = None , ) -> DataFrame Return the latest rates from a bar position. Source code in mt5cli/sdk.py 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 def latest_rates ( symbol : str , timeframe : int | str , count : int , start_pos : int = 0 , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return the latest rates from a bar position.\"\"\" return _make_client ( config = config ) . latest_rates ( symbol , timeframe , count , start_pos = start_pos , )","title":"latest_rates"},{"location":"api/sdk/#mt5cli.sdk.market_book","text":"market_book ( symbol : str , * , config : Mt5Config | None = None ) -> DataFrame Return market depth for a symbol. Source code in mt5cli/sdk.py 2092 2093 2094 2095 2096 2097 2098 def market_book ( symbol : str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return market depth for a symbol.\"\"\" return _make_client ( config = config ) . market_book ( symbol )","title":"market_book"},{"location":"api/sdk/#mt5cli.sdk.minimum_margins","text":"minimum_margins ( symbol : str , * , config : Mt5Config | None = None ) -> DataFrame Return minimum-volume buy and sell margin requirements. See Mt5CliClient.minimum_margins for return details. Source code in mt5cli/sdk.py 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 def minimum_margins ( symbol : str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return minimum-volume buy and sell margin requirements. See ``Mt5CliClient.minimum_margins`` for return details. \"\"\" return _make_client ( config = config ) . minimum_margins ( symbol )","title":"minimum_margins"},{"location":"api/sdk/#mt5cli.sdk.mt5_session","text":"mt5_session ( config : Mt5Config | None = None , ) -> Iterator [ Mt5CliClient ] Open an MT5 terminal session and yield a connected client. Launches the MetaTrader 5 terminal using Mt5Config.path (when set), logs in, yields a connected :class: Mt5CliClient , and always shuts the terminal down on exit. Parameters: Name Type Description Default config Mt5Config | None MT5 connection configuration. Defaults to an empty config that attaches to a running terminal. None Yields: Type Description Mt5CliClient Connected Mt5CliClient bound to the session. Source code in mt5cli/sdk.py 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 @contextmanager def mt5_session ( config : Mt5Config | None = None ) -> Iterator [ Mt5CliClient ]: \"\"\"Open an MT5 terminal session and yield a connected client. Launches the MetaTrader 5 terminal using ``Mt5Config.path`` (when set), logs in, yields a connected :class:`Mt5CliClient`, and always shuts the terminal down on exit. Args: config: MT5 connection configuration. Defaults to an empty config that attaches to a running terminal. Yields: Connected ``Mt5CliClient`` bound to the session. \"\"\" mt5_config = config or build_config () with connected_client ( mt5_config ) as client : yield Mt5CliClient . from_connected_client ( client )","title":"mt5_session"},{"location":"api/sdk/#mt5cli.sdk.mt5_summary","text":"mt5_summary ( * , config : Mt5Config | None = None ) -> dict [ str , object ] Return a compact terminal/account status summary. Source code in mt5cli/sdk.py 2135 2136 2137 def mt5_summary ( * , config : Mt5Config | None = None ) -> dict [ str , object ]: \"\"\"Return a compact terminal/account status summary.\"\"\" return _make_client ( config = config ) . mt5_summary ()","title":"mt5_summary"},{"location":"api/sdk/#mt5cli.sdk.mt5_summary_as_df","text":"mt5_summary_as_df ( * , config : Mt5Config | None = None ) -> DataFrame Return an export-safe terminal/account status summary DataFrame. Source code in mt5cli/sdk.py 2140 2141 2142 def mt5_summary_as_df ( * , config : Mt5Config | None = None ) -> pd . DataFrame : \"\"\"Return an export-safe terminal/account status summary DataFrame.\"\"\" return _make_client ( config = config ) . mt5_summary_as_df ()","title":"mt5_summary_as_df"},{"location":"api/sdk/#mt5cli.sdk.orders","text":"orders ( symbol : str | None = None , group : str | None = None , ticket : int | None = None , * , config : Mt5Config | None = None , ) -> DataFrame Return active orders. Source code in mt5cli/sdk.py 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 def orders ( symbol : str | None = None , group : str | None = None , ticket : int | None = None , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return active orders.\"\"\" return _make_client ( config = config ) . orders ( symbol = symbol , group = group , ticket = ticket , )","title":"orders"},{"location":"api/sdk/#mt5cli.sdk.positions","text":"positions ( symbol : str | None = None , group : str | None = None , ticket : int | None = None , * , config : Mt5Config | None = None , ) -> DataFrame Return open positions. Source code in mt5cli/sdk.py 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 def positions ( symbol : str | None = None , group : str | None = None , ticket : int | None = None , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return open positions.\"\"\" return _make_client ( config = config ) . positions ( symbol = symbol , group = group , ticket = ticket , )","title":"positions"},{"location":"api/sdk/#mt5cli.sdk.recent_history_deals","text":"recent_history_deals ( hours : float , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , * , config : Mt5Config | None = None , ) -> DataFrame Return historical deals from a recent trailing window. Source code in mt5cli/sdk.py 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 def recent_history_deals ( hours : float , date_to : datetime | str | None = None , group : str | None = None , symbol : str | None = None , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return historical deals from a recent trailing window.\"\"\" return _make_client ( config = config ) . recent_history_deals ( hours , date_to = date_to , group = group , symbol = symbol , )","title":"recent_history_deals"},{"location":"api/sdk/#mt5cli.sdk.recent_ticks","text":"recent_ticks ( symbol : str , seconds : float , * , date_to : datetime | str | None = None , count : int = 10000 , flags : int | str = \"ALL\" , config : Mt5Config | None = None , ) -> DataFrame Return ticks from a recent time window ending at date_to or now. See Mt5CliClient.recent_ticks for parameter and return details. Source code in mt5cli/sdk.py 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 def recent_ticks ( symbol : str , seconds : float , * , date_to : datetime | str | None = None , count : int = 10000 , flags : int | str = \"ALL\" , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return ticks from a recent time window ending at ``date_to`` or now. See ``Mt5CliClient.recent_ticks`` for parameter and return details. \"\"\" return _make_client ( config = config ) . recent_ticks ( symbol , seconds , date_to = date_to , count = count , flags = flags , )","title":"recent_ticks"},{"location":"api/sdk/#mt5cli.sdk.resolve_account_spec","text":"resolve_account_spec ( account : AccountSpec , * , login : int | str | None = None , password : str | None = None , server : str | None = None , path : str | None = None , timeout : int | None = None , allow_whole_dollar_env : bool = False , ) -> AccountSpec Resolve an account's credentials from overrides and ${ENV_VAR} values. Explicit override arguments take precedence over the corresponding :class: AccountSpec fields. The resolved string fields ( login , password , server , path ) have any ${ENV_VAR} placeholders substituted from the environment. Parameters: Name Type Description Default account AccountSpec Source account specification. required login int | str | None Optional explicit login override. None password str | None Optional explicit password override. None server str | None Optional explicit server override. None path str | None Optional explicit terminal path override. None timeout int | None Optional explicit connection timeout override. None allow_whole_dollar_env bool When True , string fields that are exactly $ENV_NAME are also expanded from the environment. Default False preserves existing behavior. False Returns: Type Description AccountSpec A new :class: AccountSpec with resolved credentials and the original AccountSpec symbols preserved. Raises ValueError (via AccountSpec func: substitute_env_placeholders ) if a referenced environment AccountSpec variable is not set. Source code in mt5cli/sdk.py 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 def resolve_account_spec ( account : AccountSpec , * , login : int | str | None = None , password : str | None = None , server : str | None = None , path : str | None = None , timeout : int | None = None , allow_whole_dollar_env : bool = False , ) -> AccountSpec : \"\"\"Resolve an account's credentials from overrides and ``${ENV_VAR}`` values. Explicit override arguments take precedence over the corresponding :class:`AccountSpec` fields. The resolved string fields (``login``, ``password``, ``server``, ``path``) have any ``${ENV_VAR}`` placeholders substituted from the environment. Args: account: Source account specification. login: Optional explicit login override. password: Optional explicit password override. server: Optional explicit server override. path: Optional explicit terminal path override. timeout: Optional explicit connection timeout override. allow_whole_dollar_env: When ``True``, string fields that are exactly ``$ENV_NAME`` are also expanded from the environment. Default ``False`` preserves existing behavior. Returns: A new :class:`AccountSpec` with resolved credentials and the original symbols preserved. Raises ``ValueError`` (via :func:`substitute_env_placeholders`) if a referenced environment variable is not set. \"\"\" return AccountSpec ( symbols = account . symbols , login = _resolve_login ( login , account . login , allow_whole_dollar_env = allow_whole_dollar_env ), password = _resolve_field ( password , account . password , allow_whole_dollar_env = allow_whole_dollar_env ), server = _resolve_field ( server , account . server , allow_whole_dollar_env = allow_whole_dollar_env ), path = _resolve_field ( path , account . path , allow_whole_dollar_env = allow_whole_dollar_env ), timeout = timeout if timeout is not None else account . timeout , )","title":"resolve_account_spec"},{"location":"api/sdk/#mt5cli.sdk.resolve_account_specs","text":"resolve_account_specs ( accounts : Sequence [ AccountSpec ], * , login : int | str | None = None , password : str | None = None , server : str | None = None , path : str | None = None , timeout : int | None = None , allow_whole_dollar_env : bool = False , ) -> list [ AccountSpec ] Resolve credentials for multiple accounts. Applies the same overrides and ${ENV_VAR} substitution as :func: resolve_account_spec to every account. Parameters: Name Type Description Default accounts Sequence [ AccountSpec ] Source account specifications. required login int | str | None Optional explicit login override applied to each account. None password str | None Optional explicit password override applied to each account. None server str | None Optional explicit server override applied to each account. None path str | None Optional explicit terminal path override applied to each account. None timeout int | None Optional explicit timeout override applied to each account. None allow_whole_dollar_env bool When True , string fields that are exactly $ENV_NAME are also expanded from the environment. Default False preserves existing behavior. False Returns: Type Description list [ AccountSpec ] Resolved account specifications in the original order. Raises list [ AccountSpec ] ValueError (via :func: substitute_env_placeholders ) if a referenced list [ AccountSpec ] environment variable is not set. Source code in mt5cli/sdk.py 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 def resolve_account_specs ( accounts : Sequence [ AccountSpec ], * , login : int | str | None = None , password : str | None = None , server : str | None = None , path : str | None = None , timeout : int | None = None , allow_whole_dollar_env : bool = False , ) -> list [ AccountSpec ]: \"\"\"Resolve credentials for multiple accounts. Applies the same overrides and ``${ENV_VAR}`` substitution as :func:`resolve_account_spec` to every account. Args: accounts: Source account specifications. login: Optional explicit login override applied to each account. password: Optional explicit password override applied to each account. server: Optional explicit server override applied to each account. path: Optional explicit terminal path override applied to each account. timeout: Optional explicit timeout override applied to each account. allow_whole_dollar_env: When ``True``, string fields that are exactly ``$ENV_NAME`` are also expanded from the environment. Default ``False`` preserves existing behavior. Returns: Resolved account specifications in the original order. Raises ``ValueError`` (via :func:`substitute_env_placeholders`) if a referenced environment variable is not set. \"\"\" return [ resolve_account_spec ( account , login = login , password = password , server = server , path = path , timeout = timeout , allow_whole_dollar_env = allow_whole_dollar_env , ) for account in accounts ]","title":"resolve_account_specs"},{"location":"api/sdk/#mt5cli.sdk.substitute_env_placeholders","text":"substitute_env_placeholders ( value : str , * , allow_whole_dollar_env : bool = False ) -> str Replace ${ENV_VAR} placeholders in a string with environment values. Parameters: Name Type Description Default value str String that may contain one or more ${ENV_VAR} placeholders. required allow_whole_dollar_env bool When True , a string that is exactly $ENV_NAME (the whole value and nothing else) is also expanded from the environment. Partial occurrences such as \"plan$pass\" or \"$ENV-suffix\" are left unchanged. False Returns: Type Description str The string with every placeholder replaced by its environment value. Raises: Type Description ValueError If a referenced environment variable is not set. Source code in mt5cli/sdk.py 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 def substitute_env_placeholders ( value : str , * , allow_whole_dollar_env : bool = False , ) -> str : \"\"\"Replace ``${ENV_VAR}`` placeholders in a string with environment values. Args: value: String that may contain one or more ``${ENV_VAR}`` placeholders. allow_whole_dollar_env: When ``True``, a string that is exactly ``$ENV_NAME`` (the whole value and nothing else) is also expanded from the environment. Partial occurrences such as ``\"plan$pass\"`` or ``\"$ENV-suffix\"`` are left unchanged. Returns: The string with every placeholder replaced by its environment value. Raises: ValueError: If a referenced environment variable is not set. \"\"\" if allow_whole_dollar_env : m = _WHOLE_DOLLAR_PATTERN . match ( value ) if m : name = m . group ( \"name\" ) if name not in os . environ : msg = f \"Environment variable { name !r} is not set.\" raise ValueError ( msg ) return os . environ [ name ] parts : list [ str ] = [] last_end = 0 for match in _ENV_PLACEHOLDER_PATTERN . finditer ( value ): parts . append ( value [ last_end : match . start ()]) name = match . group ( \"name\" ) if name not in os . environ : msg = f \"Environment variable { name !r} is not set.\" raise ValueError ( msg ) parts . append ( os . environ [ name ]) last_end = match . end () parts . append ( value [ last_end :]) return \"\" . join ( parts )","title":"substitute_env_placeholders"},{"location":"api/sdk/#mt5cli.sdk.substitute_mapping_values","text":"substitute_mapping_values ( data : object , * , keys : Collection [ str ], allow_whole_dollar_env : bool = False , blank_string_keys_as_none : Collection [ str ] = (), ) -> object Recursively substitute environment placeholders for selected mapping keys. Traverses nested dicts and lists, expanding ${ENV_VAR} (and $ENV_NAME when allow_whole_dollar_env=True ) in string values whose immediate parent dict key is in keys . Fields whose key is not in keys are preserved exactly, including literal dollar signs. Strings that are direct elements of a list are never substituted; substitution only applies to strings that are immediate dict values. This is a generic downstream config utility. Key names such as mt5_login or mt5_password must be supplied by the caller; mt5cli does not hard-code any application-specific key names. Callers are responsible for ensuring data has bounded nesting depth; deeply nested or self-referential structures will hit Python's recursion limit. Parameters: Name Type Description Default data object Arbitrarily nested dict/list/scalar value to process. required keys Collection [ str ] Mapping keys whose string values receive placeholder substitution. required allow_whole_dollar_env bool When True , a string that is exactly $ENV_NAME (whole value) is also expanded from the environment in addition to ${ENV_NAME} placeholders. Default False expands ${ENV_NAME} only. False blank_string_keys_as_none Collection [ str ] Mapping keys for which blank strings (after any substitution) are normalised to None . A key may appear in blank_string_keys_as_none without also appearing in keys . () Returns: Type Description object The processed value. Dicts and lists are rebuilt into new object containers with selected string values substituted and object blank-normalised. Scalar inputs (non-dict, non-list) are object returned as-is. Source code in mt5cli/sdk.py 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 def substitute_mapping_values ( data : object , * , keys : Collection [ str ], allow_whole_dollar_env : bool = False , blank_string_keys_as_none : Collection [ str ] = (), ) -> object : \"\"\"Recursively substitute environment placeholders for selected mapping keys. Traverses nested dicts and lists, expanding ``${ENV_VAR}`` (and ``$ENV_NAME`` when ``allow_whole_dollar_env=True``) in string values whose immediate parent dict key is in ``keys``. Fields whose key is not in ``keys`` are preserved exactly, including literal dollar signs. Strings that are direct elements of a list are never substituted; substitution only applies to strings that are immediate dict values. This is a generic downstream config utility. Key names such as ``mt5_login`` or ``mt5_password`` must be supplied by the caller; mt5cli does not hard-code any application-specific key names. Callers are responsible for ensuring ``data`` has bounded nesting depth; deeply nested or self-referential structures will hit Python's recursion limit. Args: data: Arbitrarily nested dict/list/scalar value to process. keys: Mapping keys whose string values receive placeholder substitution. allow_whole_dollar_env: When ``True``, a string that is exactly ``$ENV_NAME`` (whole value) is also expanded from the environment in addition to ``${ENV_NAME}`` placeholders. Default ``False`` expands ``${ENV_NAME}`` only. blank_string_keys_as_none: Mapping keys for which blank strings (after any substitution) are normalised to ``None``. A key may appear in ``blank_string_keys_as_none`` without also appearing in ``keys``. Returns: The processed value. Dicts and lists are rebuilt into new containers with selected string values substituted and blank-normalised. Scalar inputs (non-dict, non-list) are returned as-is. \"\"\" keys_set : frozenset [ str ] = frozenset ( keys ) blank_keys_set : frozenset [ str ] = frozenset ( blank_string_keys_as_none ) def _visit ( node : object , current_key : str | None ) -> object : if isinstance ( node , dict ): typed = cast ( \"dict[object, object]\" , node ) return { k : _visit ( v , k if isinstance ( k , str ) else None ) for k , v in typed . items () } if isinstance ( node , list ): typed_list = cast ( \"list[object]\" , node ) return [ _visit ( item , None ) for item in typed_list ] if not isinstance ( node , str ): return node text = node if current_key in keys_set : text = substitute_env_placeholders ( node , allow_whole_dollar_env = allow_whole_dollar_env ) if current_key in blank_keys_set and not text . strip (): return None return text return _visit ( data , None )","title":"substitute_mapping_values"},{"location":"api/sdk/#mt5cli.sdk.symbol_info","text":"symbol_info ( symbol : str , * , config : Mt5Config | None = None ) -> DataFrame Return details for one symbol. Source code in mt5cli/sdk.py 1975 1976 1977 1978 1979 1980 1981 def symbol_info ( symbol : str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return details for one symbol.\"\"\" return _make_client ( config = config ) . symbol_info ( symbol )","title":"symbol_info"},{"location":"api/sdk/#mt5cli.sdk.symbol_info_tick","text":"symbol_info_tick ( symbol : str , * , config : Mt5Config | None = None ) -> DataFrame Return the last tick for a symbol. Source code in mt5cli/sdk.py 2083 2084 2085 2086 2087 2088 2089 def symbol_info_tick ( symbol : str , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return the last tick for a symbol.\"\"\" return _make_client ( config = config ) . symbol_info_tick ( symbol )","title":"symbol_info_tick"},{"location":"api/sdk/#mt5cli.sdk.symbols","text":"symbols ( group : str | None = None , * , config : Mt5Config | None = None , ) -> DataFrame Return the symbol list. Source code in mt5cli/sdk.py 1966 1967 1968 1969 1970 1971 1972 def symbols ( group : str | None = None , * , config : Mt5Config | None = None , ) -> pd . DataFrame : \"\"\"Return the symbol list.\"\"\" return _make_client ( config = config ) . symbols ( group = group )","title":"symbols"},{"location":"api/sdk/#mt5cli.sdk.terminal_info","text":"terminal_info ( * , config : Mt5Config | None = None ) -> DataFrame Return terminal information. Source code in mt5cli/sdk.py 1961 1962 1963 def terminal_info ( * , config : Mt5Config | None = None ) -> pd . DataFrame : \"\"\"Return terminal information.\"\"\" return _make_client ( config = config ) . terminal_info ()","title":"terminal_info"},{"location":"api/sdk/#mt5cli.sdk.update_history","text":"update_history ( * , client : Mt5DataClient , output : Path | str , symbols : Sequence [ str ], datasets : set [ Dataset ] | None = None , timeframes : Sequence [ int | str ] | None = None , flags : int | str = \"ALL\" , lookback_hours : float = 24.0 , date_to : datetime | str | None = None , deduplicate : bool = True , create_rate_views : bool = True , with_views : bool = False , include_account_events : bool = True , ) -> None Incrementally append MT5 history into a SQLite database. Uses an already-connected Mt5DataClient and does not create or close the MT5 connection. For first-time tables, data is fetched from date_to - lookback_hours . Subsequent runs resume from existing MAX(time) per symbol (and timeframe for rates); when include_account_events=True , account-level deals use a separate cursor over type NOT IN (0, 1) / empty-symbol rows. Parameters: Name Type Description Default client Mt5DataClient Connected MT5 data client. required output Path | str SQLite database path. required symbols Sequence [ str ] Symbols to update. required datasets set [ Dataset ] | None Datasets to include (defaults to all). None timeframes Sequence [ int | str ] | None Rate timeframes to update (defaults to all fixed MT5 timeframes when None). None flags int | str Tick copy flags as integer or name (e.g. ALL ). 'ALL' lookback_hours float First-run lookback when a table has no prior rows. 24.0 date_to datetime | str | None Optional update end datetime. Defaults to now (UTC). None deduplicate bool Remove duplicate rows after append, keeping latest ROWID. True create_rate_views bool Create rate___ views. True with_views bool Create cash_events and positions_reconstructed views. False include_account_events bool Include account-level cash events in history_deals when True. True Source code in mt5cli/sdk.py 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 def update_history ( # noqa: PLR0913 * , client : Mt5DataClient , output : Path | str , symbols : Sequence [ str ], datasets : set [ Dataset ] | None = None , timeframes : Sequence [ int | str ] | None = None , flags : int | str = \"ALL\" , lookback_hours : float = 24.0 , date_to : datetime | str | None = None , deduplicate : bool = True , create_rate_views : bool = True , with_views : bool = False , include_account_events : bool = True , ) -> None : \"\"\"Incrementally append MT5 history into a SQLite database. Uses an already-connected ``Mt5DataClient`` and does not create or close the MT5 connection. For first-time tables, data is fetched from ``date_to - lookback_hours``. Subsequent runs resume from existing ``MAX(time)`` per symbol (and timeframe for rates); when ``include_account_events=True``, account-level deals use a separate cursor over ``type NOT IN (0, 1)`` / empty-symbol rows. Args: client: Connected MT5 data client. output: SQLite database path. symbols: Symbols to update. datasets: Datasets to include (defaults to all). timeframes: Rate timeframes to update (defaults to all fixed MT5 timeframes when None). flags: Tick copy flags as integer or name (e.g. ``ALL``). lookback_hours: First-run lookback when a table has no prior rows. date_to: Optional update end datetime. Defaults to now (UTC). deduplicate: Remove duplicate rows after append, keeping latest ROWID. create_rate_views: Create ``rate___`` views. with_views: Create ``cash_events`` and ``positions_reconstructed`` views. include_account_events: Include account-level cash events in ``history_deals`` when True. \"\"\" request = _resolve_update_history_request ( output = output , symbols = symbols , datasets = datasets , timeframes = timeframes , flags = flags , lookback_hours = lookback_hours , date_to = date_to , ) if request is None : return logger . info ( \"Updating history in SQLite: symbols= %s , datasets= %s , path= %s \" , list ( symbols ), sorted ( dataset . value for dataset in request . selected ), request . output_path , ) with sqlite3 . connect ( request . output_path ) as conn : conn . execute ( \"PRAGMA journal_mode=WAL\" ) conn . execute ( \"PRAGMA synchronous=NORMAL\" ) write_incremental_datasets ( conn , client , symbols , request . selected , request . resolved_timeframes , request . resolved_tick_flags , request . fallback_start , request . end , deduplicate = deduplicate , create_rate_views = create_rate_views , with_views = with_views , include_account_events = include_account_events , )","title":"update_history"},{"location":"api/sdk/#mt5cli.sdk.update_history_with_config","text":"update_history_with_config ( * , output : Path | str , symbols : Sequence [ str ], config : Mt5Config | None = None , datasets : set [ Dataset ] | None = None , timeframes : Sequence [ int | str ] | None = None , flags : int | str = \"ALL\" , lookback_hours : float = 24.0 , date_to : datetime | str | None = None , deduplicate : bool = True , create_rate_views : bool = True , with_views : bool = False , include_account_events : bool = True , ) -> None Incrementally append MT5 history, opening and closing the MT5 connection. Convenience wrapper around :func: update_history for standalone use. Source code in mt5cli/sdk.py 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 def update_history_with_config ( # noqa: PLR0913 * , output : Path | str , symbols : Sequence [ str ], config : Mt5Config | None = None , datasets : set [ Dataset ] | None = None , timeframes : Sequence [ int | str ] | None = None , flags : int | str = \"ALL\" , lookback_hours : float = 24.0 , date_to : datetime | str | None = None , deduplicate : bool = True , create_rate_views : bool = True , with_views : bool = False , include_account_events : bool = True , ) -> None : \"\"\"Incrementally append MT5 history, opening and closing the MT5 connection. Convenience wrapper around :func:`update_history` for standalone use. \"\"\" request = _resolve_update_history_request ( output = output , symbols = symbols , datasets = datasets , timeframes = timeframes , flags = flags , lookback_hours = lookback_hours , date_to = date_to , ) if request is None : return mt5_config = config or build_config () with connected_client ( mt5_config ) as client : update_history ( client = client , output = output , symbols = symbols , datasets = datasets , timeframes = timeframes , flags = flags , lookback_hours = lookback_hours , date_to = date_to , deduplicate = deduplicate , create_rate_views = create_rate_views , with_views = with_views , include_account_events = include_account_events , )","title":"update_history_with_config"},{"location":"api/sdk/#mt5cli.sdk.version","text":"version ( * , config : Mt5Config | None = None ) -> DataFrame Return MetaTrader5 version information. Source code in mt5cli/sdk.py 2073 2074 2075 def version ( * , config : Mt5Config | None = None ) -> pd . DataFrame : \"\"\"Return MetaTrader5 version information.\"\"\" return _make_client ( config = config ) . version ()","title":"version"},{"location":"api/sdk/#resilient-multi-account-orchestration","text":"The SDK ships strategy-agnostic helpers for building long-running collectors on top of the read-only client. None of them depend on a particular trading application.","title":"Resilient multi-account orchestration"},{"location":"api/sdk/#retrying-transient-rate-collection","text":"collect_latest_rates_for_accounts_with_retries() wraps collect_latest_rates_for_accounts() with bounded exponential backoff. Only pdmt5.Mt5TradingError and pdmt5.Mt5RuntimeError are retried; the final failure is re-raised once retry_count is exhausted. from mt5cli import AccountSpec , collect_latest_rates_for_accounts_with_retries accounts = [ AccountSpec ( symbols = [ \"EURUSD\" ], login = 12345 )] rates = collect_latest_rates_for_accounts_with_retries ( accounts , [ \"M1\" , \"H1\" ], count = 500 , retry_count = 3 , backoff_base = 2 , # sleeps 2s, 4s, 8s between attempts )","title":"Retrying transient rate collection"},{"location":"api/sdk/#latest-closed-rate-bars","text":"MetaTrader 5 start_pos=0 includes the still-forming current bar as the last row. fetch_latest_closed_rates() handles one connected MT5Client ; use fetch_latest_closed_rates_for_trading_client() from an active Mt5TradingClient session. Multi-account helpers fetch count + 1 bars, drop that row with drop_forming_rate_bar() , and validate each series is non-empty. Returned frames are ordered oldest-to-newest and may contain fewer than count rows only when MT5 returns fewer closed bars. from mt5cli import ( AccountSpec , collect_latest_closed_rates_by_granularity , fetch_latest_closed_rates , ) closed = fetch_latest_closed_rates ( client , symbol = \"EURUSD\" , granularity = \"M1\" , count = 500 , ) rates = collect_latest_closed_rates_by_granularity ( [ AccountSpec ( symbols = [ \"EURUSD\" ], login = 12345 )], [ \"M1\" , \"H1\" ], count = 500 , retry_count = 3 , ) closed_m1 = rates [ \"EURUSD\" , \"M1\" ] Use collect_latest_closed_rates_by_granularity() when callers prefer keys such as (\"EURUSD\", \"M1\") instead of integer timeframes.","title":"Latest closed rate bars"},{"location":"api/sdk/#resolving-credentials-and-env_var-placeholders","text":"resolve_account_spec() / resolve_account_specs() merge explicit override values over AccountSpec fields and expand ${ENV_VAR} placeholders, keeping secrets out of plan/config files. A missing environment variable raises ValueError . import os from mt5cli import AccountSpec , resolve_account_specs os . environ [ \"MT5_LOGIN\" ] = \"12345\" os . environ [ \"MT5_PASSWORD\" ] = \"secret\" accounts = [ AccountSpec ( symbols = [ \"EURUSD\" ], login = \"$ {MT5_LOGIN} \" , password = \"$ {MT5_PASSWORD} \" ) ] resolved = resolve_account_specs ( accounts , server = \"Broker-Demo\" ) # resolved[0].login == \"12345\", resolved[0].server == \"Broker-Demo\" Pass allow_whole_dollar_env=True to also expand strings whose entire value is a bare $ENV_NAME identifier (no braces). This opt-in covers substitute_env_placeholders() , resolve_account_spec() , resolve_account_specs() , and build_config() . Note: build_config cannot expand login because that parameter is int | None ; use resolve_account_spec for a string login placeholder. Partial strings such as \"plan$pass\" , \"abc$ENV\" , or \"$ENV-suffix\" are never expanded \u2014 only an exact $IDENTIFIER whole-string match qualifies. The default is False to preserve backward compatibility. import os from mt5cli import AccountSpec , resolve_account_specs os . environ [ \"MT5_PASSWORD\" ] = \"secret\" accounts = [ AccountSpec ( symbols = [ \"EURUSD\" ], password = \"$MT5_PASSWORD\" )] resolved = resolve_account_specs ( accounts , allow_whole_dollar_env = True ) # resolved[0].password == \"secret\"","title":"Resolving credentials and ${ENV_VAR} placeholders"},{"location":"api/sdk/#throttled-incremental-history-updates","text":"ThrottledHistoryUpdater wraps update_history() with a minimum interval between successful runs (using a monotonic clock), so an application loop can call it every iteration without over-fetching. from pdmt5 import Mt5Config , Mt5DataClient from mt5cli import Dataset , ThrottledHistoryUpdater updater = ThrottledHistoryUpdater ( output = \"history.db\" , datasets = { Dataset . rates }, timeframes = [ \"M1\" ], interval_seconds = 60 , # <= 0 updates on every call ) client = Mt5DataClient ( config = Mt5Config ( login = 12345 )) client . initialize_and_login_mt5 () try : while True : updater . update ( client , [ \"EURUSD\" , \"GBPUSD\" ]) # no-op until 60s elapse # ... do other work; break when shutting down ... finally : client . shutdown () Pass update_backend to substitute the default update_history implementation without monkey-patching mt5cli.sdk.update_history . The callable receives the same keyword arguments as update_history ( client , output , symbols , datasets , timeframes , flags , lookback_hours , with_views , include_account_events ). The resolved backend is stored on updater.update_backend for inspection or subclassing. from mt5cli import ThrottledHistoryUpdater , update_history def app_update_history ( ** kwargs ) -> None : update_history ( ** kwargs ) # or delegate to application-specific logic updater = ThrottledHistoryUpdater ( output = \"history.db\" , interval_seconds = 60 , update_backend = app_update_history , ) 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.","title":"Throttled incremental history updates"},{"location":"api/sdk/#trading-capable-sessions","text":"For order placement and trading calculations, use the dedicated Trading module . Use mt5_session() / MT5Client for read-only collection.","title":"Trading-capable sessions"},{"location":"api/storage/","text":"Storage \u00b6 mt5cli.storage \u00b6 Generic storage helpers for MT5 market and account history. __all__ module-attribute \u00b6 __all__ = [ \"Dataset\" , \"IfExists\" , \"OutputFormat\" , \"RateTarget\" , \"build_rate_targets\" , \"build_rate_view_name\" , \"collect_history\" , \"detect_format\" , \"drop_forming_rate_bar\" , \"export_dataframe\" , \"export_dataframe_to_sqlite\" , \"load_rate_data\" , \"load_rate_data_from_connection\" , \"load_rate_series_by_granularity\" , \"load_rate_series_from_sqlite\" , \"resolve_rate_tables\" , \"resolve_rate_view_name\" , \"resolve_rate_view_names\" , \"update_history\" , \"update_history_with_config\" , ] Dataset \u00b6 Bases: StrEnum Datasets supported by the collect-history command. history_deals class-attribute instance-attribute \u00b6 history_deals = 'history-deals' history_orders class-attribute instance-attribute \u00b6 history_orders = 'history-orders' rates class-attribute instance-attribute \u00b6 rates = 'rates' table_name property \u00b6 table_name : str Return the SQLite table name for this dataset. ticks class-attribute instance-attribute \u00b6 ticks = 'ticks' IfExists \u00b6 Bases: StrEnum SQLite table conflict behavior for the collect-history command. APPEND class-attribute instance-attribute \u00b6 APPEND = 'append' FAIL class-attribute instance-attribute \u00b6 FAIL = 'fail' REPLACE class-attribute instance-attribute \u00b6 REPLACE = 'replace' OutputFormat \u00b6 Bases: StrEnum Supported output file formats. csv class-attribute instance-attribute \u00b6 csv = 'csv' json class-attribute instance-attribute \u00b6 json = 'json' parquet class-attribute instance-attribute \u00b6 parquet = 'parquet' sqlite3 class-attribute instance-attribute \u00b6 sqlite3 = 'sqlite3' RateTarget dataclass \u00b6 RateTarget ( symbol : str | None , timeframe : int | str ) A single rate series identified by symbol and timeframe. Attributes: Name Type Description symbol str | None MT5 symbol name, or None when the rate series is addressed only by an explicit table (for example a custom SQLite view). timeframe int | str MT5 timeframe as an integer or name (for example M1 ). symbol instance-attribute \u00b6 symbol : str | None timeframe instance-attribute \u00b6 timeframe : int | str timeframe_int property \u00b6 timeframe_int : int Return the timeframe as its integer MT5 value. __post_init__ \u00b6 __post_init__ () -> None Normalize accepted timeframe aliases to the stored integer value. Source code in mt5cli/history.py 544 545 546 547 def __post_init__ ( self ) -> None : \"\"\"Normalize accepted timeframe aliases to the stored integer value.\"\"\" if not isinstance ( self . timeframe , int ): object . __setattr__ ( self , \"timeframe\" , parse_timeframe ( self . timeframe )) build_rate_targets \u00b6 build_rate_targets ( symbols : Sequence [ str ], timeframes : Sequence [ int | str ], * , allow_missing_symbol : bool = False , ) -> list [ RateTarget ] Build rate targets for every symbol and timeframe combination. Parameters: Name Type Description Default symbols Sequence [ str ] MT5 symbol names. May be empty when allow_missing_symbol . required timeframes Sequence [ int | str ] MT5 timeframes as integers or names (for example M1 ). required allow_missing_symbol bool When True and symbols is empty, build targets with symbol=None for each timeframe instead of raising. False Returns: Type Description list [ RateTarget ] Targets in row-major order: every timeframe for the first symbol, then list [ RateTarget ] every timeframe for the next symbol, and so on. Raises: Type Description ValueError If timeframes is empty, or symbols is empty and allow_missing_symbol is False. Source code in mt5cli/history.py 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 def build_rate_targets ( symbols : Sequence [ str ], timeframes : Sequence [ int | str ], * , allow_missing_symbol : bool = False , ) -> list [ RateTarget ]: \"\"\"Build rate targets for every symbol and timeframe combination. Args: symbols: MT5 symbol names. May be empty when ``allow_missing_symbol``. timeframes: MT5 timeframes as integers or names (for example ``M1``). allow_missing_symbol: When True and ``symbols`` is empty, build targets with ``symbol=None`` for each timeframe instead of raising. Returns: Targets in row-major order: every timeframe for the first symbol, then every timeframe for the next symbol, and so on. Raises: ValueError: If ``timeframes`` is empty, or ``symbols`` is empty and ``allow_missing_symbol`` is False. \"\"\" if not timeframes : msg = \"At least one timeframe is required.\" raise ValueError ( msg ) if not symbols : if not allow_missing_symbol : msg = \"At least one symbol is required.\" raise ValueError ( msg ) return [ RateTarget ( symbol = None , timeframe = tf ) for tf in timeframes ] return [ RateTarget ( symbol = symbol , timeframe = tf ) for symbol in symbols for tf in timeframes ] build_rate_view_name \u00b6 build_rate_view_name ( * , symbol : str , granularity : str , granularity_count : int , timeframe : int , ) -> str Return a collision-free offline optimize view name. View names always include the timeframe integer after a __ separator so a symbol such as EURUSD_M1 cannot collide with EURUSD at timeframe M1 . Source code in mt5cli/history.py 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 def build_rate_view_name ( * , symbol : str , granularity : str , granularity_count : int , timeframe : int , ) -> str : \"\"\"Return a collision-free offline optimize view name. View names always include the timeframe integer after a ``__`` separator so a symbol such as ``EURUSD_M1`` cannot collide with ``EURUSD`` at timeframe ``M1``. \"\"\" if granularity_count == 1 : return f \"rate_ { symbol } __ { timeframe } \" return f \"rate_ { symbol } __ { granularity } _ { timeframe } \" collect_history \u00b6 collect_history ( output : Path , symbols : list [ str ], date_from : datetime | str , date_to : datetime | str , * , datasets : set [ Dataset ] | None = None , timeframe : int | str = 1 , flags : int | str = \"ALL\" , if_exists : IfExists = FAIL , with_views : bool = False , config : Mt5Config | None = None , ) -> None Collect historical datasets into a single SQLite database. Parameters: Name Type Description Default output Path SQLite database path. required symbols list [ str ] Symbols to collect. required date_from datetime | str Start date. required date_to datetime | str End date. required datasets set [ Dataset ] | None Datasets to include (defaults to all). None timeframe int | str Rates timeframe as integer or name (e.g. M1 ). 1 flags int | str Tick copy flags as integer or name (e.g. ALL ). 'ALL' if_exists IfExists Behavior when a target table already exists. FAIL with_views bool Create cash_events and positions_reconstructed views. False config Mt5Config | None MT5 connection configuration. None Source code in mt5cli/sdk.py 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 def collect_history ( output : Path , symbols : list [ str ], date_from : datetime | str , date_to : datetime | str , * , datasets : set [ Dataset ] | None = None , timeframe : int | str = 1 , flags : int | str = \"ALL\" , if_exists : IfExists = IfExists . FAIL , with_views : bool = False , config : Mt5Config | None = None , ) -> None : \"\"\"Collect historical datasets into a single SQLite database. Args: output: SQLite database path. symbols: Symbols to collect. date_from: Start date. date_to: End date. datasets: Datasets to include (defaults to all). timeframe: Rates timeframe as integer or name (e.g. ``M1``). flags: Tick copy flags as integer or name (e.g. ``ALL``). if_exists: Behavior when a target table already exists. with_views: Create ``cash_events`` and ``positions_reconstructed`` views. config: MT5 connection configuration. \"\"\" start = _require_datetime ( date_from ) end = _require_datetime ( date_to ) selected = datasets if datasets is not None else set ( Dataset ) tf = _coerce_timeframe ( timeframe ) tick_flags = _coerce_tick_flags ( flags ) mt5_config = config or build_config () with connected_client ( mt5_config ) as client , sqlite3 . connect ( output ) as conn : conn . execute ( \"PRAGMA journal_mode=WAL\" ) conn . execute ( \"PRAGMA synchronous=NORMAL\" ) written_tables , written_columns = write_collected_datasets ( conn , client , symbols , selected , tf , tick_flags , start , end , if_exists , ) create_history_indexes ( conn , written_columns ) if with_views and Dataset . history_deals in written_tables : create_cash_events_view ( conn , written_columns [ Dataset . history_deals ]) create_positions_reconstructed_view ( conn , written_columns [ Dataset . history_deals ], ) elif with_views : logger . warning ( \"--with-views ignored: history_deals table was not written\" , ) logger . info ( \"Collected %s for %d symbol(s) into %s \" , \", \" . join ( sorted ( ds . value for ds in selected )), len ( symbols ), output , ) detect_format \u00b6 detect_format ( output_path : Path , explicit_format : str | None = None ) -> str Detect the output format from a file extension or explicit format string. Parameters: Name Type Description Default output_path Path Path to the output file. required explicit_format str | None Explicitly specified format, if any. None Returns: Type Description str The detected format string. Raises: Type Description ValueError If the format cannot be determined. Source code in mt5cli/utils.py 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 def detect_format ( output_path : Path , explicit_format : str | None = None , ) -> str : \"\"\"Detect the output format from a file extension or explicit format string. Args: output_path: Path to the output file. explicit_format: Explicitly specified format, if any. Returns: The detected format string. Raises: ValueError: If the format cannot be determined. \"\"\" if explicit_format is not None : return explicit_format suffix = output_path . suffix . lower () if suffix in _FORMAT_EXTENSIONS : return _FORMAT_EXTENSIONS [ suffix ] msg = ( f \"Cannot detect format from extension ' { suffix } '.\" \" Use --format to specify the output format.\" ) raise ValueError ( msg ) drop_forming_rate_bar \u00b6 drop_forming_rate_bar ( df_rate : DataFrame ) -> DataFrame Return closed bars from chronologically ordered MT5 rate data. MetaTrader 5 copy_rates_from_pos(start_pos=0) includes the still-forming current bar as the last row. Slice it off so downstream logic only sees completed bars. Empty frames and single-row frames return empty results. Parameters: Name Type Description Default df_rate DataFrame Rate data ordered oldest-to-newest with the forming bar last. required Returns: Type Description DataFrame A new DataFrame with all rows except the last. Index and columns are DataFrame preserved. The input frame is not modified. Source code in mt5cli/history.py 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 def drop_forming_rate_bar ( df_rate : pd . DataFrame ) -> pd . DataFrame : \"\"\"Return closed bars from chronologically ordered MT5 rate data. MetaTrader 5 ``copy_rates_from_pos(start_pos=0)`` includes the still-forming current bar as the last row. Slice it off so downstream logic only sees completed bars. Empty frames and single-row frames return empty results. Args: df_rate: Rate data ordered oldest-to-newest with the forming bar last. Returns: A new DataFrame with all rows except the last. Index and columns are preserved. The input frame is not modified. \"\"\" return df_rate . iloc [: - 1 ] . copy () export_dataframe \u00b6 export_dataframe ( df : DataFrame , output_path : Path , output_format : str , table_name : str = \"data\" , ) -> None Export a pandas DataFrame to the specified file format. Parameters: Name Type Description Default df DataFrame DataFrame to export. required output_path Path Path to the output file. required output_format str Output format (csv, json, parquet, or sqlite3). required table_name str Table name for SQLite3 output. 'data' Raises: Type Description ValueError If the output format is not supported. Source code in mt5cli/utils.py 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 def export_dataframe ( df : pd . DataFrame , output_path : Path , output_format : str , table_name : str = \"data\" , ) -> None : \"\"\"Export a pandas DataFrame to the specified file format. Args: df: DataFrame to export. output_path: Path to the output file. output_format: Output format (csv, json, parquet, or sqlite3). table_name: Table name for SQLite3 output. Raises: ValueError: If the output format is not supported. \"\"\" if output_format == \"csv\" : df . to_csv ( output_path , index = False ) elif output_format == \"json\" : df . to_json ( output_path , orient = \"records\" , date_format = \"iso\" , indent = 2 , ) elif output_format == \"parquet\" : df . to_parquet ( output_path , index = False ) elif output_format == \"sqlite3\" : export_dataframe_to_sqlite ( df , output_path , table_name , if_exists = IfExists . REPLACE , index = False , ) else : msg = f \"Unsupported output format: { output_format } \" raise ValueError ( msg ) export_dataframe_to_sqlite \u00b6 export_dataframe_to_sqlite ( df : DataFrame , output_path : Path , table_name : str = \"data\" , * , if_exists : IfExists = APPEND , index : bool = False , index_label : str | None = None , deduplicate_on : Sequence [ str ] | None = None , ) -> None Write a DataFrame to SQLite with configurable append and deduplication. Parameters: Name Type Description Default df DataFrame DataFrame to export. required output_path Path SQLite database path. required table_name str Target table name. 'data' if_exists IfExists Conflict behavior when the table already exists. APPEND index bool Whether to write the DataFrame index as a column. False index_label str | None Column name for the index when index=True . None deduplicate_on Sequence [ str ] | None Optional key columns to deduplicate after writing, keeping the latest ROWID per key group. Deduplication scans the full table, so repeated appends cost O(table size); index the key columns when appending frequently. None Source code in mt5cli/utils.py 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 def export_dataframe_to_sqlite ( df : pd . DataFrame , output_path : Path , table_name : str = \"data\" , * , if_exists : IfExists = IfExists . APPEND , index : bool = False , index_label : str | None = None , deduplicate_on : Sequence [ str ] | None = None , ) -> None : \"\"\"Write a DataFrame to SQLite with configurable append and deduplication. Args: df: DataFrame to export. output_path: SQLite database path. table_name: Target table name. if_exists: Conflict behavior when the table already exists. index: Whether to write the DataFrame index as a column. index_label: Column name for the index when ``index=True``. deduplicate_on: Optional key columns to deduplicate after writing, keeping the latest ``ROWID`` per key group. Deduplication scans the full table, so repeated appends cost O(table size); index the key columns when appending frequently. \"\"\" with sqlite3 . connect ( output_path ) as conn : df . to_sql ( # type: ignore[reportUnknownMemberType] table_name , conn , if_exists = if_exists . value , index = index , index_label = index_label , ) if deduplicate_on : from .history import drop_duplicates_in_table # noqa: PLC0415 drop_duplicates_in_table ( conn . cursor (), table_name , list ( deduplicate_on ), keep = \"last\" , ) conn . commit () load_rate_data \u00b6 load_rate_data ( conn_or_path : SqliteConnOrPath , table : str , count : int | None = None , ) -> DataFrame Load rate-like data from a SQLite database path or connection. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath SQLite database path or open connection. required table str Source table or view name. required count int | None Optional number of most recent rows to load. None Returns: Type Description DataFrame DataFrame indexed by ascending time . Source code in mt5cli/history.py 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 def load_rate_data ( conn_or_path : SqliteConnOrPath , table : str , count : int | None = None , ) -> pd . DataFrame : \"\"\"Load rate-like data from a SQLite database path or connection. Args: conn_or_path: SQLite database path or open connection. table: Source table or view name. count: Optional number of most recent rows to load. Returns: DataFrame indexed by ascending ``time``. \"\"\" conn , should_close = _open_existing_sqlite_database ( conn_or_path ) try : return load_rate_data_from_connection ( conn , table , count = count ) finally : if should_close : conn . close () load_rate_data_from_connection \u00b6 load_rate_data_from_connection ( connection : Connection , table : str , count : int | None = None , ) -> DataFrame Load rate-like data from a SQLite table or view. Parameters: Name Type Description Default connection Connection Open SQLite connection. required table str Source table or view name. required count int | None Optional number of most recent rows to load. None Returns: Type Description DataFrame DataFrame indexed by ascending time . Raises: Type Description ValueError If inputs, schema, timestamps are invalid, or the table or view contains no rows. Source code in mt5cli/history.py 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 def load_rate_data_from_connection ( connection : sqlite3 . Connection , table : str , count : int | None = None , ) -> pd . DataFrame : \"\"\"Load rate-like data from a SQLite table or view. Args: connection: Open SQLite connection. table: Source table or view name. count: Optional number of most recent rows to load. Returns: DataFrame indexed by ascending ``time``. Raises: ValueError: If inputs, schema, timestamps are invalid, or the table or view contains no rows. \"\"\" table_name = _validate_rate_load_request ( table , count ) columns = get_table_columns ( connection , table_name ) _ensure_rate_columns ( columns , table_name ) quoted_table = quote_sqlite_identifier ( table_name ) if count is None : frame = cast ( \"pd.DataFrame\" , pd . read_sql_query ( # type: ignore[reportUnknownMemberType] f \"SELECT * FROM { quoted_table } ORDER BY time ASC\" , # noqa: S608 connection , ), ) else : frame = cast ( \"pd.DataFrame\" , pd . read_sql_query ( # type: ignore[reportUnknownMemberType] f \"SELECT * FROM { quoted_table } ORDER BY time DESC LIMIT ?\" , # noqa: S608 connection , params = ( count ,), ), ) if frame . empty : msg = f \"SQLite table or view { table_name !r} contains no rows.\" raise ValueError ( msg ) return _parse_rate_time_index ( frame , table_name ) load_rate_series_by_granularity \u00b6 load_rate_series_by_granularity ( conn_or_path : SqliteConnOrPath , symbols : Sequence [ str ], granularities : Sequence [ int | str ], count : int , * , explicit_tables : Sequence [ str ] | None = None , allow_missing_symbol : bool = False , ) -> dict [ tuple [ str | None , str ], DataFrame ] Load rate series keyed by symbol and string granularity name. Builds targets with :func: build_rate_targets and loads them with :func: load_rate_series_from_sqlite , then rekeys the result by granularity name (for example M1 ) instead of the integer timeframe to reduce downstream boilerplate. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath SQLite database path or open connection. required symbols Sequence [ str ] MT5 symbol names. May be empty when allow_missing_symbol . required granularities Sequence [ int | str ] MT5 timeframes as integers or names (for example M1 ). required count int Number of most recent rows to load per series. required explicit_tables Sequence [ str ] | None Optional explicit table or view names matching the built targets in row-major order. Required when symbols are omitted. None allow_missing_symbol bool When True and symbols is empty, build targets with symbol=None for each granularity instead of raising. False Returns: Type Description dict [ tuple [ str | None, str ], DataFrame ] Mapping keyed by (symbol | None, granularity_name) to each rate dict [ tuple [ str | None, str ], DataFrame ] DataFrame. Propagates ValueError (via :func: build_rate_targets and dict [ tuple [ str | None, str ], DataFrame ] func: load_rate_series_from_sqlite ) when inputs are empty or invalid, dict [ tuple [ str | None, str ], DataFrame ] table resolution fails, or duplicate targets are present. Source code in mt5cli/history.py 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 def load_rate_series_by_granularity ( conn_or_path : SqliteConnOrPath , symbols : Sequence [ str ], granularities : Sequence [ int | str ], count : int , * , explicit_tables : Sequence [ str ] | None = None , allow_missing_symbol : bool = False , ) -> dict [ tuple [ str | None , str ], pd . DataFrame ]: \"\"\"Load rate series keyed by symbol and string granularity name. Builds targets with :func:`build_rate_targets` and loads them with :func:`load_rate_series_from_sqlite`, then rekeys the result by granularity name (for example ``M1``) instead of the integer timeframe to reduce downstream boilerplate. Args: conn_or_path: SQLite database path or open connection. symbols: MT5 symbol names. May be empty when ``allow_missing_symbol``. granularities: MT5 timeframes as integers or names (for example ``M1``). count: Number of most recent rows to load per series. explicit_tables: Optional explicit table or view names matching the built targets in row-major order. Required when symbols are omitted. allow_missing_symbol: When True and ``symbols`` is empty, build targets with ``symbol=None`` for each granularity instead of raising. Returns: Mapping keyed by ``(symbol | None, granularity_name)`` to each rate DataFrame. Propagates ``ValueError`` (via :func:`build_rate_targets` and :func:`load_rate_series_from_sqlite`) when inputs are empty or invalid, table resolution fails, or duplicate targets are present. \"\"\" targets = build_rate_targets ( symbols , granularities , allow_missing_symbol = allow_missing_symbol , ) series = load_rate_series_from_sqlite ( conn_or_path , targets , count , explicit_tables = explicit_tables , ) return { ( symbol , resolve_granularity_name ( timeframe )): frame for ( symbol , timeframe ), frame in series . items () } load_rate_series_from_sqlite \u00b6 load_rate_series_from_sqlite ( conn_or_path : SqliteConnOrPath , targets : None = None , count : int | None = None , explicit_tables : None = None , * , table : str , ) -> DataFrame load_rate_series_from_sqlite ( conn_or_path : SqliteConnOrPath , targets : None = None , count : int | None = None , explicit_tables : Sequence [ str ] | None = None , * , table : None = None , ) -> dict [ tuple [ str | None , int ], DataFrame ] load_rate_series_from_sqlite ( conn_or_path : SqliteConnOrPath , targets : Sequence [ RateTarget ], count : int , explicit_tables : Sequence [ str ] | None = None , * , table : None = None , ) -> dict [ tuple [ str | None , int ], DataFrame ] load_rate_series_from_sqlite ( conn_or_path : SqliteConnOrPath , targets : Sequence [ RateTarget ] | None = None , count : int | None = None , explicit_tables : Sequence [ str ] | None = None , * , table : str | None = None , ) -> dict [ tuple [ str | None , int ], DataFrame ] | DataFrame Load one table/view or multiple rate series from a SQLite database. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath SQLite database path or open connection. required targets Sequence [ RateTarget ] | None Rate targets to load. Each (symbol, timeframe_int) pair must be unique. Omit when loading a single explicit table . None count int | None Optional number of most recent rows to load per series. None explicit_tables Sequence [ str ] | None Optional explicit table or view names matching targets. When omitted, managed rate_* compatibility views must already exist in the database. None table str | None Optional single table or view name to load directly. None Returns: Type Description dict [ tuple [ str | None, int ], DataFrame ] | DataFrame A DataFrame when table is provided, otherwise a mapping keyed by dict [ tuple [ str | None, int ], DataFrame ] | DataFrame (symbol, timeframe_int) to each rate DataFrame. Raises: Type Description ValueError If count is not positive, targets are empty, duplicate (symbol, timeframe_int) pairs are present, or table resolution fails. Source code in mt5cli/history.py 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 def load_rate_series_from_sqlite ( conn_or_path : SqliteConnOrPath , targets : Sequence [ RateTarget ] | None = None , count : int | None = None , explicit_tables : Sequence [ str ] | None = None , * , table : str | None = None , ) -> dict [ tuple [ str | None , int ], pd . DataFrame ] | pd . DataFrame : \"\"\"Load one table/view or multiple rate series from a SQLite database. Args: conn_or_path: SQLite database path or open connection. targets: Rate targets to load. Each ``(symbol, timeframe_int)`` pair must be unique. Omit when loading a single explicit ``table``. count: Optional number of most recent rows to load per series. explicit_tables: Optional explicit table or view names matching targets. When omitted, managed ``rate_*`` compatibility views must already exist in the database. table: Optional single table or view name to load directly. Returns: A DataFrame when ``table`` is provided, otherwise a mapping keyed by ``(symbol, timeframe_int)`` to each rate DataFrame. Raises: ValueError: If ``count`` is not positive, targets are empty, duplicate ``(symbol, timeframe_int)`` pairs are present, or table resolution fails. \"\"\" if table is not None : return load_rate_data ( conn_or_path , table , count = count ) if count is None or count <= 0 : msg = \"count must be positive.\" raise ValueError ( msg ) if targets is None : msg = \"targets are required when table is not provided.\" raise ValueError ( msg ) target_list = list ( targets ) if not target_list : msg = \"At least one rate target is required.\" raise ValueError ( msg ) if explicit_tables is None and any ( target . symbol is None for target in target_list ): msg = ( \"Cannot resolve a rate table for a target without a symbol; \" \"provide explicit_tables.\" ) raise ValueError ( msg ) seen_keys : set [ tuple [ str | None , int ]] = set () for target in target_list : key = ( target . symbol , target . timeframe_int ) if key in seen_keys : symbol_repr = repr ( target . symbol ) msg = f \"Duplicate rate target: ( { symbol_repr } , { target . timeframe_int } )\" raise ValueError ( msg ) seen_keys . add ( key ) tables = ( resolve_rate_tables ( None , target_list , explicit_tables ) if explicit_tables is not None else None ) conn , should_close = _open_existing_sqlite_database ( conn_or_path ) try : resolved_tables = tables or resolve_rate_tables ( conn , target_list , require_existing = True , ) return { ( target . symbol , target . timeframe_int ): load_rate_data_from_connection ( conn , table , count = count , ) for target , table in zip ( target_list , resolved_tables , strict = True ) } finally : if should_close : conn . close () resolve_rate_tables \u00b6 resolve_rate_tables ( conn_or_path : SqliteConnOrPath | None , targets : Sequence [ RateTarget ], explicit_tables : Sequence [ str ] | None = None , * , require_existing : bool = False , ) -> list [ str ] Resolve SQLite table or view names for rate targets. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath | None SQLite database path or open connection. May be None when explicit_tables is provided, or when require_existing is False and deterministic default view names are sufficient. required targets Sequence [ RateTarget ] Rate targets to resolve. required explicit_tables Sequence [ str ] | None Optional explicit table or view names. When provided, they are used as-is and must match the number of targets. None require_existing bool When True, require the database and managed views to exist for each symbol target. Ignored when explicit_tables is provided. False Returns: Type Description list [ str ] Table or view names aligned with targets . Raises: Type Description ValueError If targets is empty, explicit_tables length does not match the target count, a target without a symbol is resolved without an explicit table, or require_existing is True and the database or a managed view is missing. Source code in mt5cli/history.py 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 def resolve_rate_tables ( conn_or_path : SqliteConnOrPath | None , targets : Sequence [ RateTarget ], explicit_tables : Sequence [ str ] | None = None , * , require_existing : bool = False , ) -> list [ str ]: \"\"\"Resolve SQLite table or view names for rate targets. Args: conn_or_path: SQLite database path or open connection. May be None when ``explicit_tables`` is provided, or when ``require_existing`` is False and deterministic default view names are sufficient. targets: Rate targets to resolve. explicit_tables: Optional explicit table or view names. When provided, they are used as-is and must match the number of targets. require_existing: When True, require the database and managed views to exist for each symbol target. Ignored when ``explicit_tables`` is provided. Returns: Table or view names aligned with ``targets``. Raises: ValueError: If ``targets`` is empty, ``explicit_tables`` length does not match the target count, a target without a symbol is resolved without an explicit table, or ``require_existing`` is True and the database or a managed view is missing. \"\"\" target_list = list ( targets ) if not target_list : msg = \"At least one rate target is required.\" raise ValueError ( msg ) if explicit_tables is not None : tables = list ( explicit_tables ) if len ( tables ) != len ( target_list ): msg = ( f \"Expected { len ( target_list ) } explicit table(s) \" f \"to match the targets, got { len ( tables ) } .\" ) raise ValueError ( msg ) return tables if any ( target . symbol is None for target in target_list ): msg = ( \"Cannot resolve a rate table for a target without a symbol; \" \"provide explicit_tables.\" ) raise ValueError ( msg ) conn , should_close = _open_history_connection ( conn_or_path ) try : if conn is None : if require_existing : path = ( conn_or_path if isinstance ( conn_or_path , ( Path , str )) else \"database\" ) msg = f \"SQLite database not found: { path } \" raise ValueError ( msg ) timeframe_counts = None existing_views : set [ str ] = set () else : timeframe_counts = _load_rates_timeframe_counts ( conn ) existing_views = _load_existing_rate_views ( conn ) resolved : list [ str ] = [] for target in target_list : symbol = cast ( \"str\" , target . symbol ) timeframe = target . timeframe_int resolved . append ( _resolve_rate_view_name_from_context ( symbol = symbol , timeframe = timeframe , granularity_name = resolve_granularity_name ( timeframe ), timeframe_counts = timeframe_counts , existing_views = existing_views , require_existing = require_existing , ), ) return resolved finally : if should_close and conn is not None : conn . close () resolve_rate_view_name \u00b6 resolve_rate_view_name ( conn_or_path : SqliteConnOrPath | None , symbol : str , granularity : str , * , require_existing : bool = False , ) -> str Resolve the mt5cli-managed rate compatibility view name. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath | None SQLite database path or open connection. When None or a non-existing path and require_existing is False, the deterministic default view name is returned without creating a database file. required symbol str Symbol stored in the normalized rates table. required granularity str Timeframe name (for example M1 ) or integer string. required require_existing bool When True, require the database and a managed view to exist. False Returns: Type Description str View name such as rate_EURUSD__1 or rate_EURUSD__M1_1 . Raises: Type Description ValueError If require_existing is True and the database or view is missing. Source code in mt5cli/history.py 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 def resolve_rate_view_name ( conn_or_path : SqliteConnOrPath | None , symbol : str , granularity : str , * , require_existing : bool = False , ) -> str : \"\"\"Resolve the mt5cli-managed rate compatibility view name. Args: conn_or_path: SQLite database path or open connection. When None or a non-existing path and ``require_existing`` is False, the deterministic default view name is returned without creating a database file. symbol: Symbol stored in the normalized ``rates`` table. granularity: Timeframe name (for example ``M1``) or integer string. require_existing: When True, require the database and a managed view to exist. Returns: View name such as ``rate_EURUSD__1`` or ``rate_EURUSD__M1_1``. Raises: ValueError: If ``require_existing`` is True and the database or view is missing. \"\"\" timeframe = parse_timeframe ( granularity ) granularity_name = resolve_granularity_name ( timeframe ) conn , should_close = _open_history_connection ( conn_or_path ) try : if conn is None : if require_existing : path = ( conn_or_path if isinstance ( conn_or_path , ( Path , str )) else \"database\" ) msg = f \"SQLite database not found: { path } \" raise ValueError ( msg ) return build_rate_view_name ( symbol = symbol , granularity = granularity_name , granularity_count = 1 , timeframe = timeframe , ) return _resolve_rate_view_name_from_context ( symbol = symbol , timeframe = timeframe , granularity_name = granularity_name , timeframe_counts = _load_rates_timeframe_counts ( conn ), existing_views = _load_existing_rate_views ( conn ), require_existing = require_existing , ) finally : if should_close and conn is not None : conn . close () resolve_rate_view_names \u00b6 resolve_rate_view_names ( conn_or_path : SqliteConnOrPath | None , symbols : Sequence [ str ], granularities : Sequence [ str ], * , require_existing : bool = False , ) -> list [ str ] Resolve rate compatibility view names for symbol and granularity pairs. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath | None SQLite database path or open connection. When None or a non-existing path and require_existing is False, deterministic default view names are returned without creating a database file. required symbols Sequence [ str ] Symbols stored in the normalized rates table. required granularities Sequence [ str ] Timeframe names (for example M1 ) or integer strings. required require_existing bool When True, require the database and managed views to exist. False Returns: Type Description list [ str ] View names in row-major order: every granularity for the first list [ str ] symbol, then every granularity for the next symbol, and so on. Source code in mt5cli/history.py 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 def resolve_rate_view_names ( conn_or_path : SqliteConnOrPath | None , symbols : Sequence [ str ], granularities : Sequence [ str ], * , require_existing : bool = False , ) -> list [ str ]: \"\"\"Resolve rate compatibility view names for symbol and granularity pairs. Args: conn_or_path: SQLite database path or open connection. When None or a non-existing path and ``require_existing`` is False, deterministic default view names are returned without creating a database file. symbols: Symbols stored in the normalized ``rates`` table. granularities: Timeframe names (for example ``M1``) or integer strings. require_existing: When True, require the database and managed views to exist. Returns: View names in row-major order: every ``granularity`` for the first symbol, then every granularity for the next symbol, and so on. \"\"\" conn , should_close = _open_history_connection ( conn_or_path ) try : if conn is None : return [ resolve_rate_view_name ( conn_or_path , symbol , granularity , require_existing = require_existing , ) for symbol in symbols for granularity in granularities ] timeframe_counts = _load_rates_timeframe_counts ( conn ) existing_views = _load_existing_rate_views ( conn ) resolved : list [ str ] = [] for symbol in symbols : for granularity in granularities : timeframe = parse_timeframe ( granularity ) resolved . append ( _resolve_rate_view_name_from_context ( symbol = symbol , timeframe = timeframe , granularity_name = resolve_granularity_name ( timeframe ), timeframe_counts = timeframe_counts , existing_views = existing_views , require_existing = require_existing , ), ) return resolved finally : if should_close and conn is not None : conn . close () update_history \u00b6 update_history ( * , client : Mt5DataClient , output : Path | str , symbols : Sequence [ str ], datasets : set [ Dataset ] | None = None , timeframes : Sequence [ int | str ] | None = None , flags : int | str = \"ALL\" , lookback_hours : float = 24.0 , date_to : datetime | str | None = None , deduplicate : bool = True , create_rate_views : bool = True , with_views : bool = False , include_account_events : bool = True , ) -> None Incrementally append MT5 history into a SQLite database. Uses an already-connected Mt5DataClient and does not create or close the MT5 connection. For first-time tables, data is fetched from date_to - lookback_hours . Subsequent runs resume from existing MAX(time) per symbol (and timeframe for rates); when include_account_events=True , account-level deals use a separate cursor over type NOT IN (0, 1) / empty-symbol rows. Parameters: Name Type Description Default client Mt5DataClient Connected MT5 data client. required output Path | str SQLite database path. required symbols Sequence [ str ] Symbols to update. required datasets set [ Dataset ] | None Datasets to include (defaults to all). None timeframes Sequence [ int | str ] | None Rate timeframes to update (defaults to all fixed MT5 timeframes when None). None flags int | str Tick copy flags as integer or name (e.g. ALL ). 'ALL' lookback_hours float First-run lookback when a table has no prior rows. 24.0 date_to datetime | str | None Optional update end datetime. Defaults to now (UTC). None deduplicate bool Remove duplicate rows after append, keeping latest ROWID. True create_rate_views bool Create rate___ views. True with_views bool Create cash_events and positions_reconstructed views. False include_account_events bool Include account-level cash events in history_deals when True. True Source code in mt5cli/sdk.py 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 def update_history ( # noqa: PLR0913 * , client : Mt5DataClient , output : Path | str , symbols : Sequence [ str ], datasets : set [ Dataset ] | None = None , timeframes : Sequence [ int | str ] | None = None , flags : int | str = \"ALL\" , lookback_hours : float = 24.0 , date_to : datetime | str | None = None , deduplicate : bool = True , create_rate_views : bool = True , with_views : bool = False , include_account_events : bool = True , ) -> None : \"\"\"Incrementally append MT5 history into a SQLite database. Uses an already-connected ``Mt5DataClient`` and does not create or close the MT5 connection. For first-time tables, data is fetched from ``date_to - lookback_hours``. Subsequent runs resume from existing ``MAX(time)`` per symbol (and timeframe for rates); when ``include_account_events=True``, account-level deals use a separate cursor over ``type NOT IN (0, 1)`` / empty-symbol rows. Args: client: Connected MT5 data client. output: SQLite database path. symbols: Symbols to update. datasets: Datasets to include (defaults to all). timeframes: Rate timeframes to update (defaults to all fixed MT5 timeframes when None). flags: Tick copy flags as integer or name (e.g. ``ALL``). lookback_hours: First-run lookback when a table has no prior rows. date_to: Optional update end datetime. Defaults to now (UTC). deduplicate: Remove duplicate rows after append, keeping latest ROWID. create_rate_views: Create ``rate___`` views. with_views: Create ``cash_events`` and ``positions_reconstructed`` views. include_account_events: Include account-level cash events in ``history_deals`` when True. \"\"\" request = _resolve_update_history_request ( output = output , symbols = symbols , datasets = datasets , timeframes = timeframes , flags = flags , lookback_hours = lookback_hours , date_to = date_to , ) if request is None : return logger . info ( \"Updating history in SQLite: symbols= %s , datasets= %s , path= %s \" , list ( symbols ), sorted ( dataset . value for dataset in request . selected ), request . output_path , ) with sqlite3 . connect ( request . output_path ) as conn : conn . execute ( \"PRAGMA journal_mode=WAL\" ) conn . execute ( \"PRAGMA synchronous=NORMAL\" ) write_incremental_datasets ( conn , client , symbols , request . selected , request . resolved_timeframes , request . resolved_tick_flags , request . fallback_start , request . end , deduplicate = deduplicate , create_rate_views = create_rate_views , with_views = with_views , include_account_events = include_account_events , ) update_history_with_config \u00b6 update_history_with_config ( * , output : Path | str , symbols : Sequence [ str ], config : Mt5Config | None = None , datasets : set [ Dataset ] | None = None , timeframes : Sequence [ int | str ] | None = None , flags : int | str = \"ALL\" , lookback_hours : float = 24.0 , date_to : datetime | str | None = None , deduplicate : bool = True , create_rate_views : bool = True , with_views : bool = False , include_account_events : bool = True , ) -> None Incrementally append MT5 history, opening and closing the MT5 connection. Convenience wrapper around :func: update_history for standalone use. Source code in mt5cli/sdk.py 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 def update_history_with_config ( # noqa: PLR0913 * , output : Path | str , symbols : Sequence [ str ], config : Mt5Config | None = None , datasets : set [ Dataset ] | None = None , timeframes : Sequence [ int | str ] | None = None , flags : int | str = \"ALL\" , lookback_hours : float = 24.0 , date_to : datetime | str | None = None , deduplicate : bool = True , create_rate_views : bool = True , with_views : bool = False , include_account_events : bool = True , ) -> None : \"\"\"Incrementally append MT5 history, opening and closing the MT5 connection. Convenience wrapper around :func:`update_history` for standalone use. \"\"\" request = _resolve_update_history_request ( output = output , symbols = symbols , datasets = datasets , timeframes = timeframes , flags = flags , lookback_hours = lookback_hours , date_to = date_to , ) if request is None : return mt5_config = config or build_config () with connected_client ( mt5_config ) as client : update_history ( client = client , output = output , symbols = symbols , datasets = datasets , timeframes = timeframes , flags = flags , lookback_hours = lookback_hours , date_to = date_to , deduplicate = deduplicate , create_rate_views = create_rate_views , with_views = with_views , include_account_events = include_account_events , )","title":"Storage"},{"location":"api/storage/#storage","text":"","title":"Storage"},{"location":"api/storage/#mt5cli.storage","text":"Generic storage helpers for MT5 market and account history.","title":"storage"},{"location":"api/storage/#mt5cli.storage.__all__","text":"__all__ = [ \"Dataset\" , \"IfExists\" , \"OutputFormat\" , \"RateTarget\" , \"build_rate_targets\" , \"build_rate_view_name\" , \"collect_history\" , \"detect_format\" , \"drop_forming_rate_bar\" , \"export_dataframe\" , \"export_dataframe_to_sqlite\" , \"load_rate_data\" , \"load_rate_data_from_connection\" , \"load_rate_series_by_granularity\" , \"load_rate_series_from_sqlite\" , \"resolve_rate_tables\" , \"resolve_rate_view_name\" , \"resolve_rate_view_names\" , \"update_history\" , \"update_history_with_config\" , ]","title":"__all__"},{"location":"api/storage/#mt5cli.storage.Dataset","text":"Bases: StrEnum Datasets supported by the collect-history command.","title":"Dataset"},{"location":"api/storage/#mt5cli.storage.Dataset.history_deals","text":"history_deals = 'history-deals'","title":"history_deals"},{"location":"api/storage/#mt5cli.storage.Dataset.history_orders","text":"history_orders = 'history-orders'","title":"history_orders"},{"location":"api/storage/#mt5cli.storage.Dataset.rates","text":"rates = 'rates'","title":"rates"},{"location":"api/storage/#mt5cli.storage.Dataset.table_name","text":"table_name : str Return the SQLite table name for this dataset.","title":"table_name"},{"location":"api/storage/#mt5cli.storage.Dataset.ticks","text":"ticks = 'ticks'","title":"ticks"},{"location":"api/storage/#mt5cli.storage.IfExists","text":"Bases: StrEnum SQLite table conflict behavior for the collect-history command.","title":"IfExists"},{"location":"api/storage/#mt5cli.storage.IfExists.APPEND","text":"APPEND = 'append'","title":"APPEND"},{"location":"api/storage/#mt5cli.storage.IfExists.FAIL","text":"FAIL = 'fail'","title":"FAIL"},{"location":"api/storage/#mt5cli.storage.IfExists.REPLACE","text":"REPLACE = 'replace'","title":"REPLACE"},{"location":"api/storage/#mt5cli.storage.OutputFormat","text":"Bases: StrEnum Supported output file formats.","title":"OutputFormat"},{"location":"api/storage/#mt5cli.storage.OutputFormat.csv","text":"csv = 'csv'","title":"csv"},{"location":"api/storage/#mt5cli.storage.OutputFormat.json","text":"json = 'json'","title":"json"},{"location":"api/storage/#mt5cli.storage.OutputFormat.parquet","text":"parquet = 'parquet'","title":"parquet"},{"location":"api/storage/#mt5cli.storage.OutputFormat.sqlite3","text":"sqlite3 = 'sqlite3'","title":"sqlite3"},{"location":"api/storage/#mt5cli.storage.RateTarget","text":"RateTarget ( symbol : str | None , timeframe : int | str ) A single rate series identified by symbol and timeframe. Attributes: Name Type Description symbol str | None MT5 symbol name, or None when the rate series is addressed only by an explicit table (for example a custom SQLite view). timeframe int | str MT5 timeframe as an integer or name (for example M1 ).","title":"RateTarget"},{"location":"api/storage/#mt5cli.storage.RateTarget.symbol","text":"symbol : str | None","title":"symbol"},{"location":"api/storage/#mt5cli.storage.RateTarget.timeframe","text":"timeframe : int | str","title":"timeframe"},{"location":"api/storage/#mt5cli.storage.RateTarget.timeframe_int","text":"timeframe_int : int Return the timeframe as its integer MT5 value.","title":"timeframe_int"},{"location":"api/storage/#mt5cli.storage.RateTarget.__post_init__","text":"__post_init__ () -> None Normalize accepted timeframe aliases to the stored integer value. Source code in mt5cli/history.py 544 545 546 547 def __post_init__ ( self ) -> None : \"\"\"Normalize accepted timeframe aliases to the stored integer value.\"\"\" if not isinstance ( self . timeframe , int ): object . __setattr__ ( self , \"timeframe\" , parse_timeframe ( self . timeframe ))","title":"__post_init__"},{"location":"api/storage/#mt5cli.storage.build_rate_targets","text":"build_rate_targets ( symbols : Sequence [ str ], timeframes : Sequence [ int | str ], * , allow_missing_symbol : bool = False , ) -> list [ RateTarget ] Build rate targets for every symbol and timeframe combination. Parameters: Name Type Description Default symbols Sequence [ str ] MT5 symbol names. May be empty when allow_missing_symbol . required timeframes Sequence [ int | str ] MT5 timeframes as integers or names (for example M1 ). required allow_missing_symbol bool When True and symbols is empty, build targets with symbol=None for each timeframe instead of raising. False Returns: Type Description list [ RateTarget ] Targets in row-major order: every timeframe for the first symbol, then list [ RateTarget ] every timeframe for the next symbol, and so on. Raises: Type Description ValueError If timeframes is empty, or symbols is empty and allow_missing_symbol is False. Source code in mt5cli/history.py 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 def build_rate_targets ( symbols : Sequence [ str ], timeframes : Sequence [ int | str ], * , allow_missing_symbol : bool = False , ) -> list [ RateTarget ]: \"\"\"Build rate targets for every symbol and timeframe combination. Args: symbols: MT5 symbol names. May be empty when ``allow_missing_symbol``. timeframes: MT5 timeframes as integers or names (for example ``M1``). allow_missing_symbol: When True and ``symbols`` is empty, build targets with ``symbol=None`` for each timeframe instead of raising. Returns: Targets in row-major order: every timeframe for the first symbol, then every timeframe for the next symbol, and so on. Raises: ValueError: If ``timeframes`` is empty, or ``symbols`` is empty and ``allow_missing_symbol`` is False. \"\"\" if not timeframes : msg = \"At least one timeframe is required.\" raise ValueError ( msg ) if not symbols : if not allow_missing_symbol : msg = \"At least one symbol is required.\" raise ValueError ( msg ) return [ RateTarget ( symbol = None , timeframe = tf ) for tf in timeframes ] return [ RateTarget ( symbol = symbol , timeframe = tf ) for symbol in symbols for tf in timeframes ]","title":"build_rate_targets"},{"location":"api/storage/#mt5cli.storage.build_rate_view_name","text":"build_rate_view_name ( * , symbol : str , granularity : str , granularity_count : int , timeframe : int , ) -> str Return a collision-free offline optimize view name. View names always include the timeframe integer after a __ separator so a symbol such as EURUSD_M1 cannot collide with EURUSD at timeframe M1 . Source code in mt5cli/history.py 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 def build_rate_view_name ( * , symbol : str , granularity : str , granularity_count : int , timeframe : int , ) -> str : \"\"\"Return a collision-free offline optimize view name. View names always include the timeframe integer after a ``__`` separator so a symbol such as ``EURUSD_M1`` cannot collide with ``EURUSD`` at timeframe ``M1``. \"\"\" if granularity_count == 1 : return f \"rate_ { symbol } __ { timeframe } \" return f \"rate_ { symbol } __ { granularity } _ { timeframe } \"","title":"build_rate_view_name"},{"location":"api/storage/#mt5cli.storage.collect_history","text":"collect_history ( output : Path , symbols : list [ str ], date_from : datetime | str , date_to : datetime | str , * , datasets : set [ Dataset ] | None = None , timeframe : int | str = 1 , flags : int | str = \"ALL\" , if_exists : IfExists = FAIL , with_views : bool = False , config : Mt5Config | None = None , ) -> None Collect historical datasets into a single SQLite database. Parameters: Name Type Description Default output Path SQLite database path. required symbols list [ str ] Symbols to collect. required date_from datetime | str Start date. required date_to datetime | str End date. required datasets set [ Dataset ] | None Datasets to include (defaults to all). None timeframe int | str Rates timeframe as integer or name (e.g. M1 ). 1 flags int | str Tick copy flags as integer or name (e.g. ALL ). 'ALL' if_exists IfExists Behavior when a target table already exists. FAIL with_views bool Create cash_events and positions_reconstructed views. False config Mt5Config | None MT5 connection configuration. None Source code in mt5cli/sdk.py 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 def collect_history ( output : Path , symbols : list [ str ], date_from : datetime | str , date_to : datetime | str , * , datasets : set [ Dataset ] | None = None , timeframe : int | str = 1 , flags : int | str = \"ALL\" , if_exists : IfExists = IfExists . FAIL , with_views : bool = False , config : Mt5Config | None = None , ) -> None : \"\"\"Collect historical datasets into a single SQLite database. Args: output: SQLite database path. symbols: Symbols to collect. date_from: Start date. date_to: End date. datasets: Datasets to include (defaults to all). timeframe: Rates timeframe as integer or name (e.g. ``M1``). flags: Tick copy flags as integer or name (e.g. ``ALL``). if_exists: Behavior when a target table already exists. with_views: Create ``cash_events`` and ``positions_reconstructed`` views. config: MT5 connection configuration. \"\"\" start = _require_datetime ( date_from ) end = _require_datetime ( date_to ) selected = datasets if datasets is not None else set ( Dataset ) tf = _coerce_timeframe ( timeframe ) tick_flags = _coerce_tick_flags ( flags ) mt5_config = config or build_config () with connected_client ( mt5_config ) as client , sqlite3 . connect ( output ) as conn : conn . execute ( \"PRAGMA journal_mode=WAL\" ) conn . execute ( \"PRAGMA synchronous=NORMAL\" ) written_tables , written_columns = write_collected_datasets ( conn , client , symbols , selected , tf , tick_flags , start , end , if_exists , ) create_history_indexes ( conn , written_columns ) if with_views and Dataset . history_deals in written_tables : create_cash_events_view ( conn , written_columns [ Dataset . history_deals ]) create_positions_reconstructed_view ( conn , written_columns [ Dataset . history_deals ], ) elif with_views : logger . warning ( \"--with-views ignored: history_deals table was not written\" , ) logger . info ( \"Collected %s for %d symbol(s) into %s \" , \", \" . join ( sorted ( ds . value for ds in selected )), len ( symbols ), output , )","title":"collect_history"},{"location":"api/storage/#mt5cli.storage.detect_format","text":"detect_format ( output_path : Path , explicit_format : str | None = None ) -> str Detect the output format from a file extension or explicit format string. Parameters: Name Type Description Default output_path Path Path to the output file. required explicit_format str | None Explicitly specified format, if any. None Returns: Type Description str The detected format string. Raises: Type Description ValueError If the format cannot be determined. Source code in mt5cli/utils.py 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 def detect_format ( output_path : Path , explicit_format : str | None = None , ) -> str : \"\"\"Detect the output format from a file extension or explicit format string. Args: output_path: Path to the output file. explicit_format: Explicitly specified format, if any. Returns: The detected format string. Raises: ValueError: If the format cannot be determined. \"\"\" if explicit_format is not None : return explicit_format suffix = output_path . suffix . lower () if suffix in _FORMAT_EXTENSIONS : return _FORMAT_EXTENSIONS [ suffix ] msg = ( f \"Cannot detect format from extension ' { suffix } '.\" \" Use --format to specify the output format.\" ) raise ValueError ( msg )","title":"detect_format"},{"location":"api/storage/#mt5cli.storage.drop_forming_rate_bar","text":"drop_forming_rate_bar ( df_rate : DataFrame ) -> DataFrame Return closed bars from chronologically ordered MT5 rate data. MetaTrader 5 copy_rates_from_pos(start_pos=0) includes the still-forming current bar as the last row. Slice it off so downstream logic only sees completed bars. Empty frames and single-row frames return empty results. Parameters: Name Type Description Default df_rate DataFrame Rate data ordered oldest-to-newest with the forming bar last. required Returns: Type Description DataFrame A new DataFrame with all rows except the last. Index and columns are DataFrame preserved. The input frame is not modified. Source code in mt5cli/history.py 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 def drop_forming_rate_bar ( df_rate : pd . DataFrame ) -> pd . DataFrame : \"\"\"Return closed bars from chronologically ordered MT5 rate data. MetaTrader 5 ``copy_rates_from_pos(start_pos=0)`` includes the still-forming current bar as the last row. Slice it off so downstream logic only sees completed bars. Empty frames and single-row frames return empty results. Args: df_rate: Rate data ordered oldest-to-newest with the forming bar last. Returns: A new DataFrame with all rows except the last. Index and columns are preserved. The input frame is not modified. \"\"\" return df_rate . iloc [: - 1 ] . copy ()","title":"drop_forming_rate_bar"},{"location":"api/storage/#mt5cli.storage.export_dataframe","text":"export_dataframe ( df : DataFrame , output_path : Path , output_format : str , table_name : str = \"data\" , ) -> None Export a pandas DataFrame to the specified file format. Parameters: Name Type Description Default df DataFrame DataFrame to export. required output_path Path Path to the output file. required output_format str Output format (csv, json, parquet, or sqlite3). required table_name str Table name for SQLite3 output. 'data' Raises: Type Description ValueError If the output format is not supported. Source code in mt5cli/utils.py 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 def export_dataframe ( df : pd . DataFrame , output_path : Path , output_format : str , table_name : str = \"data\" , ) -> None : \"\"\"Export a pandas DataFrame to the specified file format. Args: df: DataFrame to export. output_path: Path to the output file. output_format: Output format (csv, json, parquet, or sqlite3). table_name: Table name for SQLite3 output. Raises: ValueError: If the output format is not supported. \"\"\" if output_format == \"csv\" : df . to_csv ( output_path , index = False ) elif output_format == \"json\" : df . to_json ( output_path , orient = \"records\" , date_format = \"iso\" , indent = 2 , ) elif output_format == \"parquet\" : df . to_parquet ( output_path , index = False ) elif output_format == \"sqlite3\" : export_dataframe_to_sqlite ( df , output_path , table_name , if_exists = IfExists . REPLACE , index = False , ) else : msg = f \"Unsupported output format: { output_format } \" raise ValueError ( msg )","title":"export_dataframe"},{"location":"api/storage/#mt5cli.storage.export_dataframe_to_sqlite","text":"export_dataframe_to_sqlite ( df : DataFrame , output_path : Path , table_name : str = \"data\" , * , if_exists : IfExists = APPEND , index : bool = False , index_label : str | None = None , deduplicate_on : Sequence [ str ] | None = None , ) -> None Write a DataFrame to SQLite with configurable append and deduplication. Parameters: Name Type Description Default df DataFrame DataFrame to export. required output_path Path SQLite database path. required table_name str Target table name. 'data' if_exists IfExists Conflict behavior when the table already exists. APPEND index bool Whether to write the DataFrame index as a column. False index_label str | None Column name for the index when index=True . None deduplicate_on Sequence [ str ] | None Optional key columns to deduplicate after writing, keeping the latest ROWID per key group. Deduplication scans the full table, so repeated appends cost O(table size); index the key columns when appending frequently. None Source code in mt5cli/utils.py 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 def export_dataframe_to_sqlite ( df : pd . DataFrame , output_path : Path , table_name : str = \"data\" , * , if_exists : IfExists = IfExists . APPEND , index : bool = False , index_label : str | None = None , deduplicate_on : Sequence [ str ] | None = None , ) -> None : \"\"\"Write a DataFrame to SQLite with configurable append and deduplication. Args: df: DataFrame to export. output_path: SQLite database path. table_name: Target table name. if_exists: Conflict behavior when the table already exists. index: Whether to write the DataFrame index as a column. index_label: Column name for the index when ``index=True``. deduplicate_on: Optional key columns to deduplicate after writing, keeping the latest ``ROWID`` per key group. Deduplication scans the full table, so repeated appends cost O(table size); index the key columns when appending frequently. \"\"\" with sqlite3 . connect ( output_path ) as conn : df . to_sql ( # type: ignore[reportUnknownMemberType] table_name , conn , if_exists = if_exists . value , index = index , index_label = index_label , ) if deduplicate_on : from .history import drop_duplicates_in_table # noqa: PLC0415 drop_duplicates_in_table ( conn . cursor (), table_name , list ( deduplicate_on ), keep = \"last\" , ) conn . commit ()","title":"export_dataframe_to_sqlite"},{"location":"api/storage/#mt5cli.storage.load_rate_data","text":"load_rate_data ( conn_or_path : SqliteConnOrPath , table : str , count : int | None = None , ) -> DataFrame Load rate-like data from a SQLite database path or connection. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath SQLite database path or open connection. required table str Source table or view name. required count int | None Optional number of most recent rows to load. None Returns: Type Description DataFrame DataFrame indexed by ascending time . Source code in mt5cli/history.py 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 def load_rate_data ( conn_or_path : SqliteConnOrPath , table : str , count : int | None = None , ) -> pd . DataFrame : \"\"\"Load rate-like data from a SQLite database path or connection. Args: conn_or_path: SQLite database path or open connection. table: Source table or view name. count: Optional number of most recent rows to load. Returns: DataFrame indexed by ascending ``time``. \"\"\" conn , should_close = _open_existing_sqlite_database ( conn_or_path ) try : return load_rate_data_from_connection ( conn , table , count = count ) finally : if should_close : conn . close ()","title":"load_rate_data"},{"location":"api/storage/#mt5cli.storage.load_rate_data_from_connection","text":"load_rate_data_from_connection ( connection : Connection , table : str , count : int | None = None , ) -> DataFrame Load rate-like data from a SQLite table or view. Parameters: Name Type Description Default connection Connection Open SQLite connection. required table str Source table or view name. required count int | None Optional number of most recent rows to load. None Returns: Type Description DataFrame DataFrame indexed by ascending time . Raises: Type Description ValueError If inputs, schema, timestamps are invalid, or the table or view contains no rows. Source code in mt5cli/history.py 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 def load_rate_data_from_connection ( connection : sqlite3 . Connection , table : str , count : int | None = None , ) -> pd . DataFrame : \"\"\"Load rate-like data from a SQLite table or view. Args: connection: Open SQLite connection. table: Source table or view name. count: Optional number of most recent rows to load. Returns: DataFrame indexed by ascending ``time``. Raises: ValueError: If inputs, schema, timestamps are invalid, or the table or view contains no rows. \"\"\" table_name = _validate_rate_load_request ( table , count ) columns = get_table_columns ( connection , table_name ) _ensure_rate_columns ( columns , table_name ) quoted_table = quote_sqlite_identifier ( table_name ) if count is None : frame = cast ( \"pd.DataFrame\" , pd . read_sql_query ( # type: ignore[reportUnknownMemberType] f \"SELECT * FROM { quoted_table } ORDER BY time ASC\" , # noqa: S608 connection , ), ) else : frame = cast ( \"pd.DataFrame\" , pd . read_sql_query ( # type: ignore[reportUnknownMemberType] f \"SELECT * FROM { quoted_table } ORDER BY time DESC LIMIT ?\" , # noqa: S608 connection , params = ( count ,), ), ) if frame . empty : msg = f \"SQLite table or view { table_name !r} contains no rows.\" raise ValueError ( msg ) return _parse_rate_time_index ( frame , table_name )","title":"load_rate_data_from_connection"},{"location":"api/storage/#mt5cli.storage.load_rate_series_by_granularity","text":"load_rate_series_by_granularity ( conn_or_path : SqliteConnOrPath , symbols : Sequence [ str ], granularities : Sequence [ int | str ], count : int , * , explicit_tables : Sequence [ str ] | None = None , allow_missing_symbol : bool = False , ) -> dict [ tuple [ str | None , str ], DataFrame ] Load rate series keyed by symbol and string granularity name. Builds targets with :func: build_rate_targets and loads them with :func: load_rate_series_from_sqlite , then rekeys the result by granularity name (for example M1 ) instead of the integer timeframe to reduce downstream boilerplate. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath SQLite database path or open connection. required symbols Sequence [ str ] MT5 symbol names. May be empty when allow_missing_symbol . required granularities Sequence [ int | str ] MT5 timeframes as integers or names (for example M1 ). required count int Number of most recent rows to load per series. required explicit_tables Sequence [ str ] | None Optional explicit table or view names matching the built targets in row-major order. Required when symbols are omitted. None allow_missing_symbol bool When True and symbols is empty, build targets with symbol=None for each granularity instead of raising. False Returns: Type Description dict [ tuple [ str | None, str ], DataFrame ] Mapping keyed by (symbol | None, granularity_name) to each rate dict [ tuple [ str | None, str ], DataFrame ] DataFrame. Propagates ValueError (via :func: build_rate_targets and dict [ tuple [ str | None, str ], DataFrame ] func: load_rate_series_from_sqlite ) when inputs are empty or invalid, dict [ tuple [ str | None, str ], DataFrame ] table resolution fails, or duplicate targets are present. Source code in mt5cli/history.py 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 def load_rate_series_by_granularity ( conn_or_path : SqliteConnOrPath , symbols : Sequence [ str ], granularities : Sequence [ int | str ], count : int , * , explicit_tables : Sequence [ str ] | None = None , allow_missing_symbol : bool = False , ) -> dict [ tuple [ str | None , str ], pd . DataFrame ]: \"\"\"Load rate series keyed by symbol and string granularity name. Builds targets with :func:`build_rate_targets` and loads them with :func:`load_rate_series_from_sqlite`, then rekeys the result by granularity name (for example ``M1``) instead of the integer timeframe to reduce downstream boilerplate. Args: conn_or_path: SQLite database path or open connection. symbols: MT5 symbol names. May be empty when ``allow_missing_symbol``. granularities: MT5 timeframes as integers or names (for example ``M1``). count: Number of most recent rows to load per series. explicit_tables: Optional explicit table or view names matching the built targets in row-major order. Required when symbols are omitted. allow_missing_symbol: When True and ``symbols`` is empty, build targets with ``symbol=None`` for each granularity instead of raising. Returns: Mapping keyed by ``(symbol | None, granularity_name)`` to each rate DataFrame. Propagates ``ValueError`` (via :func:`build_rate_targets` and :func:`load_rate_series_from_sqlite`) when inputs are empty or invalid, table resolution fails, or duplicate targets are present. \"\"\" targets = build_rate_targets ( symbols , granularities , allow_missing_symbol = allow_missing_symbol , ) series = load_rate_series_from_sqlite ( conn_or_path , targets , count , explicit_tables = explicit_tables , ) return { ( symbol , resolve_granularity_name ( timeframe )): frame for ( symbol , timeframe ), frame in series . items () }","title":"load_rate_series_by_granularity"},{"location":"api/storage/#mt5cli.storage.load_rate_series_from_sqlite","text":"load_rate_series_from_sqlite ( conn_or_path : SqliteConnOrPath , targets : None = None , count : int | None = None , explicit_tables : None = None , * , table : str , ) -> DataFrame load_rate_series_from_sqlite ( conn_or_path : SqliteConnOrPath , targets : None = None , count : int | None = None , explicit_tables : Sequence [ str ] | None = None , * , table : None = None , ) -> dict [ tuple [ str | None , int ], DataFrame ] load_rate_series_from_sqlite ( conn_or_path : SqliteConnOrPath , targets : Sequence [ RateTarget ], count : int , explicit_tables : Sequence [ str ] | None = None , * , table : None = None , ) -> dict [ tuple [ str | None , int ], DataFrame ] load_rate_series_from_sqlite ( conn_or_path : SqliteConnOrPath , targets : Sequence [ RateTarget ] | None = None , count : int | None = None , explicit_tables : Sequence [ str ] | None = None , * , table : str | None = None , ) -> dict [ tuple [ str | None , int ], DataFrame ] | DataFrame Load one table/view or multiple rate series from a SQLite database. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath SQLite database path or open connection. required targets Sequence [ RateTarget ] | None Rate targets to load. Each (symbol, timeframe_int) pair must be unique. Omit when loading a single explicit table . None count int | None Optional number of most recent rows to load per series. None explicit_tables Sequence [ str ] | None Optional explicit table or view names matching targets. When omitted, managed rate_* compatibility views must already exist in the database. None table str | None Optional single table or view name to load directly. None Returns: Type Description dict [ tuple [ str | None, int ], DataFrame ] | DataFrame A DataFrame when table is provided, otherwise a mapping keyed by dict [ tuple [ str | None, int ], DataFrame ] | DataFrame (symbol, timeframe_int) to each rate DataFrame. Raises: Type Description ValueError If count is not positive, targets are empty, duplicate (symbol, timeframe_int) pairs are present, or table resolution fails. Source code in mt5cli/history.py 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 def load_rate_series_from_sqlite ( conn_or_path : SqliteConnOrPath , targets : Sequence [ RateTarget ] | None = None , count : int | None = None , explicit_tables : Sequence [ str ] | None = None , * , table : str | None = None , ) -> dict [ tuple [ str | None , int ], pd . DataFrame ] | pd . DataFrame : \"\"\"Load one table/view or multiple rate series from a SQLite database. Args: conn_or_path: SQLite database path or open connection. targets: Rate targets to load. Each ``(symbol, timeframe_int)`` pair must be unique. Omit when loading a single explicit ``table``. count: Optional number of most recent rows to load per series. explicit_tables: Optional explicit table or view names matching targets. When omitted, managed ``rate_*`` compatibility views must already exist in the database. table: Optional single table or view name to load directly. Returns: A DataFrame when ``table`` is provided, otherwise a mapping keyed by ``(symbol, timeframe_int)`` to each rate DataFrame. Raises: ValueError: If ``count`` is not positive, targets are empty, duplicate ``(symbol, timeframe_int)`` pairs are present, or table resolution fails. \"\"\" if table is not None : return load_rate_data ( conn_or_path , table , count = count ) if count is None or count <= 0 : msg = \"count must be positive.\" raise ValueError ( msg ) if targets is None : msg = \"targets are required when table is not provided.\" raise ValueError ( msg ) target_list = list ( targets ) if not target_list : msg = \"At least one rate target is required.\" raise ValueError ( msg ) if explicit_tables is None and any ( target . symbol is None for target in target_list ): msg = ( \"Cannot resolve a rate table for a target without a symbol; \" \"provide explicit_tables.\" ) raise ValueError ( msg ) seen_keys : set [ tuple [ str | None , int ]] = set () for target in target_list : key = ( target . symbol , target . timeframe_int ) if key in seen_keys : symbol_repr = repr ( target . symbol ) msg = f \"Duplicate rate target: ( { symbol_repr } , { target . timeframe_int } )\" raise ValueError ( msg ) seen_keys . add ( key ) tables = ( resolve_rate_tables ( None , target_list , explicit_tables ) if explicit_tables is not None else None ) conn , should_close = _open_existing_sqlite_database ( conn_or_path ) try : resolved_tables = tables or resolve_rate_tables ( conn , target_list , require_existing = True , ) return { ( target . symbol , target . timeframe_int ): load_rate_data_from_connection ( conn , table , count = count , ) for target , table in zip ( target_list , resolved_tables , strict = True ) } finally : if should_close : conn . close ()","title":"load_rate_series_from_sqlite"},{"location":"api/storage/#mt5cli.storage.resolve_rate_tables","text":"resolve_rate_tables ( conn_or_path : SqliteConnOrPath | None , targets : Sequence [ RateTarget ], explicit_tables : Sequence [ str ] | None = None , * , require_existing : bool = False , ) -> list [ str ] Resolve SQLite table or view names for rate targets. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath | None SQLite database path or open connection. May be None when explicit_tables is provided, or when require_existing is False and deterministic default view names are sufficient. required targets Sequence [ RateTarget ] Rate targets to resolve. required explicit_tables Sequence [ str ] | None Optional explicit table or view names. When provided, they are used as-is and must match the number of targets. None require_existing bool When True, require the database and managed views to exist for each symbol target. Ignored when explicit_tables is provided. False Returns: Type Description list [ str ] Table or view names aligned with targets . Raises: Type Description ValueError If targets is empty, explicit_tables length does not match the target count, a target without a symbol is resolved without an explicit table, or require_existing is True and the database or a managed view is missing. Source code in mt5cli/history.py 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 def resolve_rate_tables ( conn_or_path : SqliteConnOrPath | None , targets : Sequence [ RateTarget ], explicit_tables : Sequence [ str ] | None = None , * , require_existing : bool = False , ) -> list [ str ]: \"\"\"Resolve SQLite table or view names for rate targets. Args: conn_or_path: SQLite database path or open connection. May be None when ``explicit_tables`` is provided, or when ``require_existing`` is False and deterministic default view names are sufficient. targets: Rate targets to resolve. explicit_tables: Optional explicit table or view names. When provided, they are used as-is and must match the number of targets. require_existing: When True, require the database and managed views to exist for each symbol target. Ignored when ``explicit_tables`` is provided. Returns: Table or view names aligned with ``targets``. Raises: ValueError: If ``targets`` is empty, ``explicit_tables`` length does not match the target count, a target without a symbol is resolved without an explicit table, or ``require_existing`` is True and the database or a managed view is missing. \"\"\" target_list = list ( targets ) if not target_list : msg = \"At least one rate target is required.\" raise ValueError ( msg ) if explicit_tables is not None : tables = list ( explicit_tables ) if len ( tables ) != len ( target_list ): msg = ( f \"Expected { len ( target_list ) } explicit table(s) \" f \"to match the targets, got { len ( tables ) } .\" ) raise ValueError ( msg ) return tables if any ( target . symbol is None for target in target_list ): msg = ( \"Cannot resolve a rate table for a target without a symbol; \" \"provide explicit_tables.\" ) raise ValueError ( msg ) conn , should_close = _open_history_connection ( conn_or_path ) try : if conn is None : if require_existing : path = ( conn_or_path if isinstance ( conn_or_path , ( Path , str )) else \"database\" ) msg = f \"SQLite database not found: { path } \" raise ValueError ( msg ) timeframe_counts = None existing_views : set [ str ] = set () else : timeframe_counts = _load_rates_timeframe_counts ( conn ) existing_views = _load_existing_rate_views ( conn ) resolved : list [ str ] = [] for target in target_list : symbol = cast ( \"str\" , target . symbol ) timeframe = target . timeframe_int resolved . append ( _resolve_rate_view_name_from_context ( symbol = symbol , timeframe = timeframe , granularity_name = resolve_granularity_name ( timeframe ), timeframe_counts = timeframe_counts , existing_views = existing_views , require_existing = require_existing , ), ) return resolved finally : if should_close and conn is not None : conn . close ()","title":"resolve_rate_tables"},{"location":"api/storage/#mt5cli.storage.resolve_rate_view_name","text":"resolve_rate_view_name ( conn_or_path : SqliteConnOrPath | None , symbol : str , granularity : str , * , require_existing : bool = False , ) -> str Resolve the mt5cli-managed rate compatibility view name. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath | None SQLite database path or open connection. When None or a non-existing path and require_existing is False, the deterministic default view name is returned without creating a database file. required symbol str Symbol stored in the normalized rates table. required granularity str Timeframe name (for example M1 ) or integer string. required require_existing bool When True, require the database and a managed view to exist. False Returns: Type Description str View name such as rate_EURUSD__1 or rate_EURUSD__M1_1 . Raises: Type Description ValueError If require_existing is True and the database or view is missing. Source code in mt5cli/history.py 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 def resolve_rate_view_name ( conn_or_path : SqliteConnOrPath | None , symbol : str , granularity : str , * , require_existing : bool = False , ) -> str : \"\"\"Resolve the mt5cli-managed rate compatibility view name. Args: conn_or_path: SQLite database path or open connection. When None or a non-existing path and ``require_existing`` is False, the deterministic default view name is returned without creating a database file. symbol: Symbol stored in the normalized ``rates`` table. granularity: Timeframe name (for example ``M1``) or integer string. require_existing: When True, require the database and a managed view to exist. Returns: View name such as ``rate_EURUSD__1`` or ``rate_EURUSD__M1_1``. Raises: ValueError: If ``require_existing`` is True and the database or view is missing. \"\"\" timeframe = parse_timeframe ( granularity ) granularity_name = resolve_granularity_name ( timeframe ) conn , should_close = _open_history_connection ( conn_or_path ) try : if conn is None : if require_existing : path = ( conn_or_path if isinstance ( conn_or_path , ( Path , str )) else \"database\" ) msg = f \"SQLite database not found: { path } \" raise ValueError ( msg ) return build_rate_view_name ( symbol = symbol , granularity = granularity_name , granularity_count = 1 , timeframe = timeframe , ) return _resolve_rate_view_name_from_context ( symbol = symbol , timeframe = timeframe , granularity_name = granularity_name , timeframe_counts = _load_rates_timeframe_counts ( conn ), existing_views = _load_existing_rate_views ( conn ), require_existing = require_existing , ) finally : if should_close and conn is not None : conn . close ()","title":"resolve_rate_view_name"},{"location":"api/storage/#mt5cli.storage.resolve_rate_view_names","text":"resolve_rate_view_names ( conn_or_path : SqliteConnOrPath | None , symbols : Sequence [ str ], granularities : Sequence [ str ], * , require_existing : bool = False , ) -> list [ str ] Resolve rate compatibility view names for symbol and granularity pairs. Parameters: Name Type Description Default conn_or_path SqliteConnOrPath | None SQLite database path or open connection. When None or a non-existing path and require_existing is False, deterministic default view names are returned without creating a database file. required symbols Sequence [ str ] Symbols stored in the normalized rates table. required granularities Sequence [ str ] Timeframe names (for example M1 ) or integer strings. required require_existing bool When True, require the database and managed views to exist. False Returns: Type Description list [ str ] View names in row-major order: every granularity for the first list [ str ] symbol, then every granularity for the next symbol, and so on. Source code in mt5cli/history.py 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 def resolve_rate_view_names ( conn_or_path : SqliteConnOrPath | None , symbols : Sequence [ str ], granularities : Sequence [ str ], * , require_existing : bool = False , ) -> list [ str ]: \"\"\"Resolve rate compatibility view names for symbol and granularity pairs. Args: conn_or_path: SQLite database path or open connection. When None or a non-existing path and ``require_existing`` is False, deterministic default view names are returned without creating a database file. symbols: Symbols stored in the normalized ``rates`` table. granularities: Timeframe names (for example ``M1``) or integer strings. require_existing: When True, require the database and managed views to exist. Returns: View names in row-major order: every ``granularity`` for the first symbol, then every granularity for the next symbol, and so on. \"\"\" conn , should_close = _open_history_connection ( conn_or_path ) try : if conn is None : return [ resolve_rate_view_name ( conn_or_path , symbol , granularity , require_existing = require_existing , ) for symbol in symbols for granularity in granularities ] timeframe_counts = _load_rates_timeframe_counts ( conn ) existing_views = _load_existing_rate_views ( conn ) resolved : list [ str ] = [] for symbol in symbols : for granularity in granularities : timeframe = parse_timeframe ( granularity ) resolved . append ( _resolve_rate_view_name_from_context ( symbol = symbol , timeframe = timeframe , granularity_name = resolve_granularity_name ( timeframe ), timeframe_counts = timeframe_counts , existing_views = existing_views , require_existing = require_existing , ), ) return resolved finally : if should_close and conn is not None : conn . close ()","title":"resolve_rate_view_names"},{"location":"api/storage/#mt5cli.storage.update_history","text":"update_history ( * , client : Mt5DataClient , output : Path | str , symbols : Sequence [ str ], datasets : set [ Dataset ] | None = None , timeframes : Sequence [ int | str ] | None = None , flags : int | str = \"ALL\" , lookback_hours : float = 24.0 , date_to : datetime | str | None = None , deduplicate : bool = True , create_rate_views : bool = True , with_views : bool = False , include_account_events : bool = True , ) -> None Incrementally append MT5 history into a SQLite database. Uses an already-connected Mt5DataClient and does not create or close the MT5 connection. For first-time tables, data is fetched from date_to - lookback_hours . Subsequent runs resume from existing MAX(time) per symbol (and timeframe for rates); when include_account_events=True , account-level deals use a separate cursor over type NOT IN (0, 1) / empty-symbol rows. Parameters: Name Type Description Default client Mt5DataClient Connected MT5 data client. required output Path | str SQLite database path. required symbols Sequence [ str ] Symbols to update. required datasets set [ Dataset ] | None Datasets to include (defaults to all). None timeframes Sequence [ int | str ] | None Rate timeframes to update (defaults to all fixed MT5 timeframes when None). None flags int | str Tick copy flags as integer or name (e.g. ALL ). 'ALL' lookback_hours float First-run lookback when a table has no prior rows. 24.0 date_to datetime | str | None Optional update end datetime. Defaults to now (UTC). None deduplicate bool Remove duplicate rows after append, keeping latest ROWID. True create_rate_views bool Create rate___ views. True with_views bool Create cash_events and positions_reconstructed views. False include_account_events bool Include account-level cash events in history_deals when True. True Source code in mt5cli/sdk.py 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 def update_history ( # noqa: PLR0913 * , client : Mt5DataClient , output : Path | str , symbols : Sequence [ str ], datasets : set [ Dataset ] | None = None , timeframes : Sequence [ int | str ] | None = None , flags : int | str = \"ALL\" , lookback_hours : float = 24.0 , date_to : datetime | str | None = None , deduplicate : bool = True , create_rate_views : bool = True , with_views : bool = False , include_account_events : bool = True , ) -> None : \"\"\"Incrementally append MT5 history into a SQLite database. Uses an already-connected ``Mt5DataClient`` and does not create or close the MT5 connection. For first-time tables, data is fetched from ``date_to - lookback_hours``. Subsequent runs resume from existing ``MAX(time)`` per symbol (and timeframe for rates); when ``include_account_events=True``, account-level deals use a separate cursor over ``type NOT IN (0, 1)`` / empty-symbol rows. Args: client: Connected MT5 data client. output: SQLite database path. symbols: Symbols to update. datasets: Datasets to include (defaults to all). timeframes: Rate timeframes to update (defaults to all fixed MT5 timeframes when None). flags: Tick copy flags as integer or name (e.g. ``ALL``). lookback_hours: First-run lookback when a table has no prior rows. date_to: Optional update end datetime. Defaults to now (UTC). deduplicate: Remove duplicate rows after append, keeping latest ROWID. create_rate_views: Create ``rate___`` views. with_views: Create ``cash_events`` and ``positions_reconstructed`` views. include_account_events: Include account-level cash events in ``history_deals`` when True. \"\"\" request = _resolve_update_history_request ( output = output , symbols = symbols , datasets = datasets , timeframes = timeframes , flags = flags , lookback_hours = lookback_hours , date_to = date_to , ) if request is None : return logger . info ( \"Updating history in SQLite: symbols= %s , datasets= %s , path= %s \" , list ( symbols ), sorted ( dataset . value for dataset in request . selected ), request . output_path , ) with sqlite3 . connect ( request . output_path ) as conn : conn . execute ( \"PRAGMA journal_mode=WAL\" ) conn . execute ( \"PRAGMA synchronous=NORMAL\" ) write_incremental_datasets ( conn , client , symbols , request . selected , request . resolved_timeframes , request . resolved_tick_flags , request . fallback_start , request . end , deduplicate = deduplicate , create_rate_views = create_rate_views , with_views = with_views , include_account_events = include_account_events , )","title":"update_history"},{"location":"api/storage/#mt5cli.storage.update_history_with_config","text":"update_history_with_config ( * , output : Path | str , symbols : Sequence [ str ], config : Mt5Config | None = None , datasets : set [ Dataset ] | None = None , timeframes : Sequence [ int | str ] | None = None , flags : int | str = \"ALL\" , lookback_hours : float = 24.0 , date_to : datetime | str | None = None , deduplicate : bool = True , create_rate_views : bool = True , with_views : bool = False , include_account_events : bool = True , ) -> None Incrementally append MT5 history, opening and closing the MT5 connection. Convenience wrapper around :func: update_history for standalone use. Source code in mt5cli/sdk.py 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 def update_history_with_config ( # noqa: PLR0913 * , output : Path | str , symbols : Sequence [ str ], config : Mt5Config | None = None , datasets : set [ Dataset ] | None = None , timeframes : Sequence [ int | str ] | None = None , flags : int | str = \"ALL\" , lookback_hours : float = 24.0 , date_to : datetime | str | None = None , deduplicate : bool = True , create_rate_views : bool = True , with_views : bool = False , include_account_events : bool = True , ) -> None : \"\"\"Incrementally append MT5 history, opening and closing the MT5 connection. Convenience wrapper around :func:`update_history` for standalone use. \"\"\" request = _resolve_update_history_request ( output = output , symbols = symbols , datasets = datasets , timeframes = timeframes , flags = flags , lookback_hours = lookback_hours , date_to = date_to , ) if request is None : return mt5_config = config or build_config () with connected_client ( mt5_config ) as client : update_history ( client = client , output = output , symbols = symbols , datasets = datasets , timeframes = timeframes , flags = flags , lookback_hours = lookback_hours , date_to = date_to , deduplicate = deduplicate , create_rate_views = create_rate_views , with_views = with_views , include_account_events = include_account_events , )","title":"update_history_with_config"},{"location":"api/trading/","text":"Trading Module \u00b6 mt5cli.trading \u00b6 Trading-capable MetaTrader 5 session helpers and operational utilities. ExecutionStatus module-attribute \u00b6 ExecutionStatus = Literal [ \"executed\" , \"dry_run\" , \"skipped\" , \"failed\" ] OrderFillingMode module-attribute \u00b6 OrderFillingMode = Literal [ 'IOC' , 'FOK' , 'RETURN' ] OrderSide module-attribute \u00b6 OrderSide = Literal [ 'BUY' , 'SELL' ] OrderTimeMode module-attribute \u00b6 OrderTimeMode = Literal [ \"GTC\" , \"DAY\" , \"SPECIFIED\" , \"SPECIFIED_DAY\" ] POSITION_COLUMNS module-attribute \u00b6 POSITION_COLUMNS = ( \"ticket\" , \"time\" , \"symbol\" , \"type\" , \"volume\" , \"price_open\" , \"sl\" , \"tp\" , \"price_current\" , \"profit\" , \"swap\" , \"comment\" , ) PositionSide module-attribute \u00b6 PositionSide = Literal [ 'long' , 'short' ] ProjectionMode module-attribute \u00b6 ProjectionMode = Literal [ 'add' , 'replace_symbol' ] __all__ module-attribute \u00b6 __all__ = [ \"POSITION_COLUMNS\" , \"ExecutionStatus\" , \"MarginVolume\" , \"OrderExecutionResult\" , \"OrderFillingMode\" , \"OrderLimits\" , \"OrderSide\" , \"OrderTimeMode\" , \"PositionSide\" , \"ProjectionMode\" , \"calculate_account_projected_margin_ratio\" , \"calculate_margin_and_volume\" , \"calculate_new_position_margin_ratio\" , \"calculate_positions_margin\" , \"calculate_positions_margin_by_symbol\" , \"calculate_positions_margin_safe\" , \"calculate_projected_margin_ratio\" , \"calculate_spread_ratio\" , \"calculate_symbol_group_margin_ratio\" , \"calculate_trailing_stop_updates\" , \"calculate_volume_by_margin\" , \"close_open_positions\" , \"create_trading_client\" , \"detect_position_side\" , \"determine_order_limits\" , \"ensure_symbol_selected\" , \"estimate_order_margin\" , \"extract_tick_price\" , \"fetch_latest_closed_rates_for_trading_client\" , \"fetch_latest_closed_rates_indexed\" , \"get_account_snapshot\" , \"get_positions_frame\" , \"get_symbol_snapshot\" , \"get_tick_snapshot\" , \"mt5_trading_session\" , \"normalize_order_volume\" , \"place_market_order\" , \"update_sltp_for_open_positions\" , \"update_trailing_stop_loss_for_open_positions\" , ] MarginVolume \u00b6 Bases: TypedDict Affordable volume bounds derived from account margin and symbol constraints. available_margin instance-attribute \u00b6 available_margin : float buy_volume instance-attribute \u00b6 buy_volume : float margin_free instance-attribute \u00b6 margin_free : float sell_volume instance-attribute \u00b6 sell_volume : float trade_margin instance-attribute \u00b6 trade_margin : float volume_max instance-attribute \u00b6 volume_max : float volume_min instance-attribute \u00b6 volume_min : float volume_step instance-attribute \u00b6 volume_step : float OrderExecutionResult \u00b6 Bases: TypedDict Normalized result from market-order and position-management helpers. comment instance-attribute \u00b6 comment : str | None dry_run instance-attribute \u00b6 dry_run : bool order_side instance-attribute \u00b6 order_side : OrderSide request instance-attribute \u00b6 request : dict [ str , object ] response instance-attribute \u00b6 response : dict [ str , object ] | None retcode instance-attribute \u00b6 retcode : int | None status instance-attribute \u00b6 status : ExecutionStatus symbol instance-attribute \u00b6 symbol : str volume instance-attribute \u00b6 volume : float OrderLimits \u00b6 Bases: TypedDict Protective order prices derived from current quotes and ratio parameters. entry instance-attribute \u00b6 entry : float stop_loss instance-attribute \u00b6 stop_loss : float | None take_profit instance-attribute \u00b6 take_profit : float | None calculate_account_projected_margin_ratio \u00b6 calculate_account_projected_margin_ratio ( client : Mt5TradingClient , * , symbol : str | None = None , new_position_side : OrderSide | None = None , new_position_volume : float = 0.0 , ) -> float Return account-wide current plus optional new-position margin over equity. Current exposure comes from the broker account snapshot margin field so unrelated open positions remain in the baseline. Optional projected exposure is added via :func: estimate_order_margin only when a symbol, side, and positive volume are all supplied. Source code in mt5cli/trading.py 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 def calculate_account_projected_margin_ratio ( client : Mt5TradingClient , * , symbol : str | None = None , new_position_side : OrderSide | None = None , new_position_volume : float = 0.0 , ) -> float : \"\"\"Return account-wide current plus optional new-position margin over equity. Current exposure comes from the broker account snapshot ``margin`` field so unrelated open positions remain in the baseline. Optional projected exposure is added via :func:`estimate_order_margin` only when a symbol, side, and positive volume are all supplied. \"\"\" account = get_account_snapshot ( client ) equity = _required_account_number ( account , \"equity\" , allow_zero = False ) margin = _required_account_number ( account , \"margin\" , allow_zero = True ) if symbol is not None and new_position_side is not None and new_position_volume > 0 : margin += estimate_order_margin ( client , symbol , new_position_side , new_position_volume , ) return margin / equity calculate_margin_and_volume \u00b6 calculate_margin_and_volume ( client : Mt5TradingClient , symbol : str , unit_margin_ratio : float , preserved_margin_ratio : float , ) -> MarginVolume Calculate tradable margin and volumes from account free margin. Applies preserved_margin_ratio to keep a reserve off margin_free , then allocates unit_margin_ratio of the remainder as the margin budget for proportional volume sizing on both buy and sell sides. A unit_margin_ratio of 0 requests exactly one minimum valid unit per side when the post-reserve margin can afford it. Parameters: Name Type Description Default client Mt5TradingClient Connected Mt5TradingClient instance. required symbol str Symbol used for minimum-lot margin and volume calculations. required unit_margin_ratio float Fraction of post-reserve margin to allocate per unit. required preserved_margin_ratio float Fraction of margin_free to preserve. required Returns: Type Description MarginVolume Dictionary with margin_free , available_margin , trade_margin , MarginVolume buy_volume , and sell_volume . Negative margin_free values are MarginVolume clamped to 0.0 before sizing. Source code in mt5cli/trading.py 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 def calculate_margin_and_volume ( client : Mt5TradingClient , symbol : str , unit_margin_ratio : float , preserved_margin_ratio : float , ) -> MarginVolume : \"\"\"Calculate tradable margin and volumes from account free margin. Applies ``preserved_margin_ratio`` to keep a reserve off ``margin_free``, then allocates ``unit_margin_ratio`` of the remainder as the margin budget for proportional volume sizing on both buy and sell sides. A ``unit_margin_ratio`` of ``0`` requests exactly one minimum valid unit per side when the post-reserve margin can afford it. Args: client: Connected ``Mt5TradingClient`` instance. symbol: Symbol used for minimum-lot margin and volume calculations. unit_margin_ratio: Fraction of post-reserve margin to allocate per unit. preserved_margin_ratio: Fraction of ``margin_free`` to preserve. Returns: Dictionary with ``margin_free``, ``available_margin``, ``trade_margin``, ``buy_volume``, and ``sell_volume``. Negative ``margin_free`` values are clamped to ``0.0`` before sizing. \"\"\" _require_unit_ratio ( unit_margin_ratio , \"unit_margin_ratio\" ) _require_unit_ratio ( preserved_margin_ratio , \"preserved_margin_ratio\" ) account = client . account_info_as_dict () margin_free = max ( 0.0 , float ( account . get ( \"margin_free\" ) or 0.0 )) available_margin = margin_free * ( 1.0 - preserved_margin_ratio ) trade_margin = available_margin * unit_margin_ratio if unit_margin_ratio == 0 : buy_volume = _calculate_min_volume_if_affordable ( client , symbol , available_margin , \"BUY\" , ) sell_volume = _calculate_min_volume_if_affordable ( client , symbol , available_margin , \"SELL\" , ) else : buy_volume = calculate_volume_by_margin ( client , symbol , trade_margin , \"BUY\" ) sell_volume = calculate_volume_by_margin ( client , symbol , trade_margin , \"SELL\" ) try : symbol_info = get_symbol_snapshot ( client , symbol ) volume_min = float ( symbol_info . get ( \"volume_min\" ) or 0.0 ) volume_max = float ( symbol_info . get ( \"volume_max\" ) or 0.0 ) volume_step = float ( symbol_info . get ( \"volume_step\" ) or 0.0 ) except AttributeError : volume_min = volume_max = volume_step = 0.0 return { \"margin_free\" : margin_free , \"available_margin\" : available_margin , \"trade_margin\" : trade_margin , \"buy_volume\" : float ( buy_volume ), \"sell_volume\" : float ( sell_volume ), \"volume_min\" : volume_min , \"volume_max\" : volume_max , \"volume_step\" : volume_step , } calculate_new_position_margin_ratio \u00b6 calculate_new_position_margin_ratio ( client : Mt5TradingClient , * , symbol : str , new_position_side : OrderSide | None = None , new_position_volume : float = 0.0 , ) -> float Return total margin/equity ratio after an optional hypothetical position. Raises: Type Description Mt5TradingError If equity or required tick data is invalid. Source code in mt5cli/trading.py 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 def calculate_new_position_margin_ratio ( client : Mt5TradingClient , * , symbol : str , new_position_side : OrderSide | None = None , new_position_volume : float = 0.0 , ) -> float : \"\"\"Return total margin/equity ratio after an optional hypothetical position. Raises: Mt5TradingError: If equity or required tick data is invalid. \"\"\" account = get_account_snapshot ( client ) equity = float ( account . get ( \"equity\" ) or 0.0 ) if equity <= 0 : msg = \"Account equity must be positive to calculate margin ratio.\" raise Mt5TradingError ( msg ) margin = float ( account . get ( \"margin\" ) or 0.0 ) if new_position_side is not None and new_position_volume > 0 : side = _normalize_order_side ( new_position_side ) price = extract_tick_price ( get_tick_snapshot ( client , symbol ), \"ask\" if side == \"BUY\" else \"bid\" ) if price is None : msg = f \"Tick price is unavailable for { symbol !r} .\" raise Mt5TradingError ( msg ) order_type = ( client . mt5 . ORDER_TYPE_BUY if side == \"BUY\" else client . mt5 . ORDER_TYPE_SELL ) margin += float ( client . order_calc_margin ( order_type , symbol , new_position_volume , price ), ) return margin / equity calculate_positions_margin \u00b6 calculate_positions_margin ( client : Mt5TradingClient , * , symbols : Sequence [ str ] | None = None , ) -> float Return the sum of estimated current margin for open positions. Parameters: Name Type Description Default client Mt5TradingClient Connected Mt5TradingClient instance. required symbols Sequence [ str ] | None Optional symbol filter. When omitted, all open positions are included. None Returns: Type Description float Total estimated margin, or 0.0 when no matching positions exist. Source code in mt5cli/trading.py 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 def calculate_positions_margin ( client : Mt5TradingClient , * , symbols : Sequence [ str ] | None = None , ) -> float : \"\"\"Return the sum of estimated current margin for open positions. Args: client: Connected ``Mt5TradingClient`` instance. symbols: Optional symbol filter. When omitted, all open positions are included. Returns: Total estimated margin, or ``0.0`` when no matching positions exist. \"\"\" frame = get_positions_frame ( client ) if frame . empty or \"symbol\" not in frame . columns : return 0.0 if symbols is not None : frame = frame [ frame [ \"symbol\" ] . isin ( list ( symbols ))] if frame . empty : return 0.0 grouped_volumes : dict [ tuple [ str , OrderSide ], float ] = {} for _ , row in frame . iterrows (): symbol = row . get ( \"symbol\" ) if not isinstance ( symbol , str ) or not symbol : continue volume = row . get ( \"volume\" ) if not _is_positive_finite_number ( volume ): continue order_side = _order_side_from_position_type ( client , row . get ( \"type\" )) if order_side is None : continue key = ( symbol , order_side ) finite_volume = float ( cast ( \"float | int\" , volume )) grouped_volumes [ key ] = grouped_volumes . get ( key , 0.0 ) + finite_volume total = 0.0 for ( symbol , order_side ), volume in grouped_volumes . items (): total += estimate_order_margin ( client , symbol , order_side , volume ) return total calculate_positions_margin_by_symbol \u00b6 calculate_positions_margin_by_symbol ( client : Mt5TradingClient , * , symbols : Sequence [ str ], suppress_errors : bool = True , ) -> dict [ str , float ] Return per-symbol estimated margin for open positions. Computes margin for each unique input symbol independently using the strict :func: calculate_positions_margin helper. Duplicates are deduplicated in first-seen order. Parameters: Name Type Description Default client Mt5TradingClient Connected Mt5TradingClient instance. required symbols Sequence [ str ] Symbols to compute margin for. required suppress_errors bool When True , log and skip symbols that raise Mt5TradingError , Mt5RuntimeError , or AttributeError . When False , re-raise the first failure. True Returns: Type Description dict [ str , float ] Mapping of symbol to margin total in first-seen unique-symbol order. dict [ str , float ] Returns an empty dict when symbols is empty or all symbols fail dict [ str , float ] with suppress_errors=True . Raises: Type Description Mt5TradingError When a symbol raises Mt5TradingError and suppress_errors=False . Mt5RuntimeError When a symbol raises Mt5RuntimeError and suppress_errors=False . AttributeError When a symbol raises AttributeError and suppress_errors=False . Source code in mt5cli/trading.py 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 def calculate_positions_margin_by_symbol ( client : Mt5TradingClient , * , symbols : Sequence [ str ], suppress_errors : bool = True , ) -> dict [ str , float ]: \"\"\"Return per-symbol estimated margin for open positions. Computes margin for each unique input symbol independently using the strict :func:`calculate_positions_margin` helper. Duplicates are deduplicated in first-seen order. Args: client: Connected ``Mt5TradingClient`` instance. symbols: Symbols to compute margin for. suppress_errors: When ``True``, log and skip symbols that raise ``Mt5TradingError``, ``Mt5RuntimeError``, or ``AttributeError``. When ``False``, re-raise the first failure. Returns: Mapping of symbol to margin total in first-seen unique-symbol order. Returns an empty dict when ``symbols`` is empty or all symbols fail with ``suppress_errors=True``. Raises: Mt5TradingError: When a symbol raises ``Mt5TradingError`` and ``suppress_errors=False``. Mt5RuntimeError: When a symbol raises ``Mt5RuntimeError`` and ``suppress_errors=False``. AttributeError: When a symbol raises ``AttributeError`` and ``suppress_errors=False``. \"\"\" result : dict [ str , float ] = {} for symbol in dict . fromkeys ( symbols ): try : result [ symbol ] = calculate_positions_margin ( client , symbols = [ symbol ]) except ( Mt5TradingError , Mt5RuntimeError , AttributeError ) as exc : if not suppress_errors : raise _logger . warning ( \"Skipping margin for %r : %s \" , symbol , exc ) return result calculate_positions_margin_safe \u00b6 calculate_positions_margin_safe ( client : Mt5TradingClient , * , symbols : Sequence [ str ] ) -> float Return the total estimated margin for open positions across symbols. Internally calls :func: calculate_positions_margin_by_symbol with suppress_errors=True . Failed symbols are silently skipped. Parameters: Name Type Description Default client Mt5TradingClient Connected Mt5TradingClient instance. required symbols Sequence [ str ] Symbols to include. required Returns: Type Description float Sum of per-symbol margins; 0.0 when no symbols or all fail. Source code in mt5cli/trading.py 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 def calculate_positions_margin_safe ( client : Mt5TradingClient , * , symbols : Sequence [ str ], ) -> float : \"\"\"Return the total estimated margin for open positions across symbols. Internally calls :func:`calculate_positions_margin_by_symbol` with ``suppress_errors=True``. Failed symbols are silently skipped. Args: client: Connected ``Mt5TradingClient`` instance. symbols: Symbols to include. Returns: Sum of per-symbol margins; ``0.0`` when no symbols or all fail. \"\"\" return sum ( calculate_positions_margin_by_symbol ( client , symbols = symbols ) . values (), 0.0 , ) calculate_projected_margin_ratio \u00b6 calculate_projected_margin_ratio ( client : Mt5TradingClient , * , symbol : str , new_position_side : OrderSide | None = None , new_position_volume : float = 0.0 , ) -> float Return estimated current plus optional new-position margin over equity. Current exposure is estimated from open positions with :func: calculate_positions_margin . Optional projected exposure is added via :func: estimate_order_margin . Thresholds and guard actions are intentionally left to downstream applications. Account equity, position margin, and optional projected margin errors from the composed MT5 helpers propagate to the caller. Source code in mt5cli/trading.py 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 def calculate_projected_margin_ratio ( client : Mt5TradingClient , * , symbol : str , new_position_side : OrderSide | None = None , new_position_volume : float = 0.0 , ) -> float : \"\"\"Return estimated current plus optional new-position margin over equity. Current exposure is estimated from open positions with :func:`calculate_positions_margin`. Optional projected exposure is added via :func:`estimate_order_margin`. Thresholds and guard actions are intentionally left to downstream applications. Account equity, position margin, and optional projected margin errors from the composed MT5 helpers propagate to the caller. \"\"\" equity = _account_equity ( client ) margin = calculate_positions_margin ( client , symbols = [ symbol ]) if new_position_side is not None and new_position_volume > 0 : margin += estimate_order_margin ( client , symbol , new_position_side , new_position_volume , ) return margin / equity calculate_spread_ratio \u00b6 calculate_spread_ratio ( client : Mt5TradingClient , symbol : str ) -> float Return (ask - bid) / ((ask + bid) / 2) for the latest tick. Raises: Type Description Mt5TradingError If bid or ask is unavailable. Source code in mt5cli/trading.py 788 789 790 791 792 793 794 795 796 797 798 799 800 def calculate_spread_ratio ( client : Mt5TradingClient , symbol : str ) -> float : \"\"\"Return ``(ask - bid) / ((ask + bid) / 2)`` for the latest tick. Raises: Mt5TradingError: If bid or ask is unavailable. \"\"\" tick = get_tick_snapshot ( client , symbol ) bid = extract_tick_price ( tick , \"bid\" ) ask = extract_tick_price ( tick , \"ask\" ) if bid is None or ask is None : msg = f \"Tick bid/ask is unavailable for { symbol !r} .\" raise Mt5TradingError ( msg ) return ( ask - bid ) / (( ask + bid ) / 2.0 ) calculate_symbol_group_margin_ratio \u00b6 calculate_symbol_group_margin_ratio ( client : Mt5TradingClient , * , symbols : Sequence [ str ], new_symbol : str | None = None , new_position_side : OrderSide | None = None , new_position_volume : float = 0.0 , suppress_errors : bool = True , projection_mode : ProjectionMode = \"add\" , ) -> float Return estimated symbol-group margin over account equity. Per-symbol current exposure is summed with :func: calculate_positions_margin_by_symbol . When new_symbol is inside the input symbol group and candidate side/volume are provided, projected order margin is applied according to projection_mode : \"add\" (default): adds candidate margin to the group total. \"replace_symbol\" : subtracts current margin for new_symbol , then adds candidate margin. Useful for reversal-style projections where the new order is intended to replace existing exposure for that symbol. If the candidate margin estimation fails, the subtraction is also skipped so the operation is atomic. Invalid equity always raises to fail closed. Raises: Type Description AttributeError When symbol margin lookup or projected margin lookup fails and suppress_errors is False . Mt5RuntimeError When symbol margin lookup or projected margin lookup fails and suppress_errors is False . Mt5TradingError When account equity is invalid, or when symbol margin lookup or projected margin lookup fails and suppress_errors is False . Source code in mt5cli/trading.py 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 def calculate_symbol_group_margin_ratio ( client : Mt5TradingClient , * , symbols : Sequence [ str ], new_symbol : str | None = None , new_position_side : OrderSide | None = None , new_position_volume : float = 0.0 , suppress_errors : bool = True , projection_mode : ProjectionMode = \"add\" , ) -> float : \"\"\"Return estimated symbol-group margin over account equity. Per-symbol current exposure is summed with :func:`calculate_positions_margin_by_symbol`. When ``new_symbol`` is inside the input symbol group and candidate side/volume are provided, projected order margin is applied according to ``projection_mode``: - ``\"add\"`` (default): adds candidate margin to the group total. - ``\"replace_symbol\"``: subtracts current margin for ``new_symbol``, then adds candidate margin. Useful for reversal-style projections where the new order is intended to replace existing exposure for that symbol. If the candidate margin estimation fails, the subtraction is also skipped so the operation is atomic. Invalid equity always raises to fail closed. Raises: AttributeError: When symbol margin lookup or projected margin lookup fails and ``suppress_errors`` is ``False``. Mt5RuntimeError: When symbol margin lookup or projected margin lookup fails and ``suppress_errors`` is ``False``. Mt5TradingError: When account equity is invalid, or when symbol margin lookup or projected margin lookup fails and ``suppress_errors`` is ``False``. \"\"\" equity = _account_equity ( client ) unique_symbols = list ( dict . fromkeys ( symbols )) per_symbol = calculate_positions_margin_by_symbol ( client , symbols = unique_symbols , suppress_errors = suppress_errors , ) margin = sum ( per_symbol . values (), 0.0 ) if ( new_symbol in unique_symbols and new_position_side is not None and new_position_volume > 0 ): try : candidate_margin = estimate_order_margin ( client , new_symbol , new_position_side , new_position_volume , ) except ( Mt5TradingError , Mt5RuntimeError , AttributeError ): if not suppress_errors : raise _logger . warning ( \"Skipping projected margin for %r .\" , new_symbol ) else : if projection_mode == \"replace_symbol\" : margin -= per_symbol . get ( new_symbol , 0.0 ) margin += candidate_margin return margin / equity calculate_trailing_stop_updates \u00b6 calculate_trailing_stop_updates ( client : Mt5TradingClient , * , symbol : str , trailing_stop_ratio : float , ) -> dict [ int , float ] Return per-ticket trailing stop-loss updates for open symbol positions. Buy positions trail from bid using bid * (1 - trailing_stop_ratio) . Sell positions trail from ask using ask * (1 + trailing_stop_ratio) . Existing stop losses are preserved when they are already more favorable. Missing symbol metadata returns an empty update map. Positions with a missing side-specific tick price are skipped. Source code in mt5cli/trading.py 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 def calculate_trailing_stop_updates ( client : Mt5TradingClient , * , symbol : str , trailing_stop_ratio : float , ) -> dict [ int , float ]: \"\"\"Return per-ticket trailing stop-loss updates for open symbol positions. Buy positions trail from bid using ``bid * (1 - trailing_stop_ratio)``. Sell positions trail from ask using ``ask * (1 + trailing_stop_ratio)``. Existing stop losses are preserved when they are already more favorable. Missing symbol metadata returns an empty update map. Positions with a missing side-specific tick price are skipped. \"\"\" _require_protective_ratio ( trailing_stop_ratio , \"trailing_stop_ratio\" ) positions = get_positions_frame ( client , symbol = symbol ) if positions . empty : return {} tick = get_tick_snapshot ( client , symbol ) bid = extract_tick_price ( tick , \"bid\" ) ask = extract_tick_price ( tick , \"ask\" ) digits = _symbol_digits ( client , symbol ) if digits is None : return {} updates : dict [ int , float ] = {} for row in positions . to_dict ( \"records\" ): ticket = _position_ticket ( row . get ( \"ticket\" )) if ticket is None : continue next_sl = _trailing_stop_loss ( client , position_type = row . get ( \"type\" ), current_sl = _current_stop_loss ( row . get ( \"sl\" )), bid = bid , ask = ask , digits = digits , trailing_stop_ratio = trailing_stop_ratio , ) if next_sl is None : continue updates [ ticket ] = next_sl return updates calculate_volume_by_margin \u00b6 calculate_volume_by_margin ( client : Mt5TradingClient , symbol : str , available_margin : float , order_side : OrderSide , ) -> float Calculate max normalized volume affordable for one side. Returns: Type Description float Largest stepped volume whose actual margin (from order_calc_margin ) float fits within available_margin , rounded down to symbol volume float constraints; 0.0 when no affordable step exists. Raises: Type Description Mt5TradingError If symbol volume constraints or tick data are invalid. Source code in mt5cli/trading.py 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 def calculate_volume_by_margin ( client : Mt5TradingClient , symbol : str , available_margin : float , order_side : OrderSide , ) -> float : \"\"\"Calculate max normalized volume affordable for one side. Returns: Largest stepped volume whose actual margin (from ``order_calc_margin``) fits within ``available_margin``, rounded down to symbol volume constraints; ``0.0`` when no affordable step exists. Raises: Mt5TradingError: If symbol volume constraints or tick data are invalid. \"\"\" if available_margin <= 0 : return 0.0 symbol_info = get_symbol_snapshot ( client , symbol ) volume_min = float ( symbol_info . get ( \"volume_min\" ) or 0.0 ) volume_max = float ( symbol_info . get ( \"volume_max\" ) or 0.0 ) volume_step = float ( symbol_info . get ( \"volume_step\" ) or volume_min or 0.0 ) if volume_min <= 0 or volume_step <= 0 : msg = f \"Invalid volume constraints for { symbol !r} .\" raise Mt5TradingError ( msg ) side = _normalize_order_side ( order_side ) price = extract_tick_price ( get_tick_snapshot ( client , symbol ), \"ask\" if side == \"BUY\" else \"bid\" ) if price is None : msg = f \"Tick price is unavailable for { symbol !r} .\" raise Mt5TradingError ( msg ) order_type = ( client . mt5 . ORDER_TYPE_BUY if side == \"BUY\" else client . mt5 . ORDER_TYPE_SELL ) min_margin = float ( client . order_calc_margin ( order_type , symbol , volume_min , price )) if min_margin <= 0 or min_margin > available_margin : return 0.0 lo = 0 hi = int ( max ( 0 , floor ( ( ( min ( available_margin / min_margin * volume_min , volume_max ) if volume_max > 0 else available_margin / min_margin * volume_min ) - volume_min ) / volume_step + 1e-12 ), ) ) best = - 1 while lo <= hi : mid = ( lo + hi ) // 2 normalized = round ( volume_min + mid * volume_step , 10 ) actual = float ( client . order_calc_margin ( order_type , symbol , normalized , price )) if actual > 0 and actual <= available_margin : best = mid lo = mid + 1 else : hi = mid - 1 return round ( volume_min + best * volume_step , 10 ) if best >= 0 else 0.0 close_open_positions \u00b6 close_open_positions ( client : Mt5TradingClient , * , symbols : str | list [ str ] | None = None , tickets : list [ int ] | None = None , dry_run : bool = False , ) -> list [ OrderExecutionResult ] Close matching open positions. Returns: Type Description list [ OrderExecutionResult ] Normalized execution results for matching positions. Source code in mt5cli/trading.py 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 def close_open_positions ( client : Mt5TradingClient , * , symbols : str | list [ str ] | None = None , tickets : list [ int ] | None = None , dry_run : bool = False , ) -> list [ OrderExecutionResult ]: \"\"\"Close matching open positions. Returns: Normalized execution results for matching positions. \"\"\" positions = _filter_positions ( get_positions_frame ( client ), symbols = symbols , tickets = tickets , ) results : list [ OrderExecutionResult ] = [] for row in positions . to_dict ( \"records\" ): pos_type = row [ \"type\" ] side : OrderSide = \"SELL\" if pos_type == client . mt5 . POSITION_TYPE_BUY else \"BUY\" result = place_market_order ( client , symbol = str ( row [ \"symbol\" ]), volume = float ( row [ \"volume\" ]), order_side = side , position = int ( row [ \"ticket\" ]), dry_run = dry_run , ) results . append ( result ) return results create_trading_client \u00b6 create_trading_client ( * , config : Mt5Config | None = None , login : int | str | None = None , password : str | None = None , server : str | None = None , path : str | None = None , timeout : int | None = None , retry_count : int = 0 , ) -> Mt5TradingClient Return an initialized and logged-in trading client. Source code in mt5cli/trading.py 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 def create_trading_client ( * , config : Mt5Config | None = None , login : int | str | None = None , password : str | None = None , server : str | None = None , path : str | None = None , timeout : int | None = None , retry_count : int = 0 , ) -> Mt5TradingClient : \"\"\"Return an initialized and logged-in trading client.\"\"\" mt5_config = _resolve_config ( config = config , login = login , password = password , server = server , path = path , timeout = timeout , ) client = Mt5TradingClient ( config = mt5_config , retry_count = retry_count ) try : client . initialize_and_login_mt5 () except Exception : client . shutdown () raise return client detect_position_side \u00b6 detect_position_side ( client : Mt5TradingClient , symbol : str ) -> PositionSide | None Detect the net open position side for a symbol. Parameters: Name Type Description Default client Mt5TradingClient Connected Mt5TradingClient instance. required symbol str Symbol to inspect. required Returns: Type Description PositionSide | None \"long\" when there are buy positions and no sell positions, PositionSide | None \"short\" when there are sell positions and no buy positions, or PositionSide | None None when no positions or mixed exposure exists. Source code in mt5cli/trading.py 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 def detect_position_side ( client : Mt5TradingClient , symbol : str , ) -> PositionSide | None : \"\"\"Detect the net open position side for a symbol. Args: client: Connected ``Mt5TradingClient`` instance. symbol: Symbol to inspect. Returns: ``\"long\"`` when there are buy positions and no sell positions, ``\"short\"`` when there are sell positions and no buy positions, or ``None`` when no positions or mixed exposure exists. \"\"\" positions = get_positions_frame ( client , symbol = symbol ) if positions . empty : return None buy_type = client . mt5 . POSITION_TYPE_BUY sell_type = client . mt5 . POSITION_TYPE_SELL buy_volume = _sum_position_volume ( positions , buy_type ) sell_volume = _sum_position_volume ( positions , sell_type ) if buy_volume > 0 and sell_volume == 0 : return \"long\" if sell_volume > 0 and buy_volume == 0 : return \"short\" return None determine_order_limits \u00b6 determine_order_limits ( client : Mt5TradingClient , symbol : str , side : PositionSide | str , stop_loss_limit_ratio : float | None = None , take_profit_limit_ratio : float | None = None , ) -> OrderLimits Derive entry and protective order prices from current market quotes. Parameters: Name Type Description Default client Mt5TradingClient Connected Mt5TradingClient instance. required symbol str Symbol used for the quote lookup. required side PositionSide | str Position side as \"long\" / \"short\" ( \"buy\" / \"sell\" aliases are accepted). required stop_loss_limit_ratio float | None Relative distance from entry for stop loss in [0, 1) . A value of 0 omits the stop loss. None take_profit_limit_ratio float | None Relative distance from entry for take profit in [0, 1) . A value of 0 omits the take profit. None Returns: Type Description OrderLimits Dictionary with entry , stop_loss , and take_profit keys. OrderLimits Omitted protective levels are returned as None . Raises: Type Description Mt5TradingError If required tick data is invalid or computed SL/TP prices violate available trade_stops_level pre-validation. Source code in mt5cli/trading.py 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 def determine_order_limits ( client : Mt5TradingClient , symbol : str , side : PositionSide | str , stop_loss_limit_ratio : float | None = None , take_profit_limit_ratio : float | None = None , ) -> OrderLimits : \"\"\"Derive entry and protective order prices from current market quotes. Args: client: Connected ``Mt5TradingClient`` instance. symbol: Symbol used for the quote lookup. side: Position side as ``\"long\"``/``\"short\"`` (``\"buy\"``/``\"sell\"`` aliases are accepted). stop_loss_limit_ratio: Relative distance from entry for stop loss in ``[0, 1)``. A value of ``0`` omits the stop loss. take_profit_limit_ratio: Relative distance from entry for take profit in ``[0, 1)``. A value of ``0`` omits the take profit. Returns: Dictionary with ``entry``, ``stop_loss``, and ``take_profit`` keys. Omitted protective levels are returned as ``None``. Raises: Mt5TradingError: If required tick data is invalid or computed SL/TP prices violate available ``trade_stops_level`` pre-validation. \"\"\" stop_loss_ratio = stop_loss_limit_ratio or 0.0 take_profit_ratio = take_profit_limit_ratio or 0.0 _require_protective_ratio ( stop_loss_ratio , \"stop_loss_limit_ratio\" ) _require_protective_ratio ( take_profit_ratio , \"take_profit_limit_ratio\" ) normalized_side = _position_side_from_order_side ( side ) tick = get_tick_snapshot ( client , symbol ) entry_key = \"ask\" if normalized_side == \"long\" else \"bid\" entry = extract_tick_price ( tick , entry_key ) if entry is None : msg = f \"Tick price is unavailable for { symbol !r} .\" raise Mt5TradingError ( msg ) try : symbol_info = get_symbol_snapshot ( client , symbol ) except ( AttributeError , KeyError , TypeError , ValueError ): symbol_info = {} try : digits = int ( symbol_info . get ( \"digits\" ) or 8 ) except ( TypeError , ValueError ): digits = 8 min_distance = _minimum_stop_distance ( symbol_info ) stop_loss : float | None = None if stop_loss_ratio > 0 : if normalized_side == \"long\" : stop_loss = entry * ( 1.0 - stop_loss_ratio ) else : stop_loss = entry * ( 1.0 + stop_loss_ratio ) stop_loss = round ( stop_loss , digits ) take_profit : float | None = None if take_profit_ratio > 0 : if normalized_side == \"long\" : take_profit = entry * ( 1.0 + take_profit_ratio ) else : take_profit = entry * ( 1.0 - take_profit_ratio ) take_profit = round ( take_profit , digits ) _validate_protective_prices ( symbol = symbol , side = normalized_side , entry = entry , stop_loss = stop_loss , take_profit = take_profit , min_distance = min_distance , ) return { \"entry\" : entry , \"stop_loss\" : stop_loss , \"take_profit\" : take_profit , } ensure_symbol_selected \u00b6 ensure_symbol_selected ( client : Mt5TradingClient , symbol : str ) -> None Ensure a symbol is visible in Market Watch before sending orders. Parameters: Name Type Description Default client Mt5TradingClient Connected Mt5TradingClient instance. required symbol str Symbol to select. required Raises: Type Description Mt5TradingError If the symbol cannot be selected in Market Watch or symbol_select is unavailable on the client. Source code in mt5cli/trading.py 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 def ensure_symbol_selected ( client : Mt5TradingClient , symbol : str ) -> None : \"\"\"Ensure a symbol is visible in Market Watch before sending orders. Args: client: Connected ``Mt5TradingClient`` instance. symbol: Symbol to select. Raises: Mt5TradingError: If the symbol cannot be selected in Market Watch or ``symbol_select`` is unavailable on the client. \"\"\" snapshot = get_symbol_snapshot ( client , symbol ) if snapshot . get ( \"visible\" ): return select = getattr ( client , \"symbol_select\" , None ) if not callable ( select ): msg = \"MT5 client is missing required method: symbol_select\" raise Mt5TradingError ( msg ) if select ( symbol , enable = True ): return last_error = getattr ( client , \"last_error\" , None ) detail = f \" ( { last_error () } )\" if callable ( last_error ) else \"\" msg = f \"Failed to select symbol { symbol !r} in Market Watch { detail } .\" raise Mt5TradingError ( msg ) estimate_order_margin \u00b6 estimate_order_margin ( client : Mt5TradingClient , symbol : str , order_side : OrderSide | str , volume : float , ) -> float Estimate required margin for one order at the current market price. Returns: Type Description float Positive finite margin required for the order at the current quote. Raises: Type Description Mt5TradingError If volume, tick data, or margin estimation is invalid. Source code in mt5cli/trading.py 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 def estimate_order_margin ( client : Mt5TradingClient , symbol : str , order_side : OrderSide | str , volume : float , ) -> float : \"\"\"Estimate required margin for one order at the current market price. Returns: Positive finite margin required for the order at the current quote. Raises: Mt5TradingError: If volume, tick data, or margin estimation is invalid. \"\"\" if not _is_positive_finite_number ( volume ): msg = \"Volume must be a positive finite number to estimate order margin.\" raise Mt5TradingError ( msg ) side = _normalize_order_side ( order_side ) tick = get_tick_snapshot ( client , symbol ) price = extract_tick_price ( tick , \"ask\" if side == \"BUY\" else \"bid\" ) if price is None : msg = f \"Tick price is unavailable for { symbol !r} .\" raise Mt5TradingError ( msg ) order_type = ( client . mt5 . ORDER_TYPE_BUY if side == \"BUY\" else client . mt5 . ORDER_TYPE_SELL ) raw_margin = client . order_calc_margin ( order_type , symbol , volume , price ) try : margin = float ( raw_margin ) except ( TypeError , ValueError ) as exc : msg = f \"Margin estimate is invalid for { symbol !r} .\" raise Mt5TradingError ( msg ) from exc if margin <= 0 or not isfinite ( margin ): msg = f \"Margin estimate is invalid for { symbol !r} .\" raise Mt5TradingError ( msg ) return margin extract_tick_price \u00b6 extract_tick_price ( tick : Mapping [ str , object ], key : str ) -> float | None Return a positive finite float from tick[key], or None if invalid. Accepts int, float, or numeric string values. Returns None when the key is missing, the value is None, non-numeric, NaN, infinite, zero, or negative. Booleans are treated as non-numeric and return None. Source code in mt5cli/trading.py 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 def extract_tick_price ( tick : Mapping [ str , object ], key : str ) -> float | None : \"\"\"Return a positive finite float from tick[key], or None if invalid. Accepts int, float, or numeric string values. Returns None when the key is missing, the value is None, non-numeric, NaN, infinite, zero, or negative. Booleans are treated as non-numeric and return None. \"\"\" value = tick . get ( key ) if value is None or isinstance ( value , bool ): return None if isinstance ( value , int | float ): price = float ( value ) elif isinstance ( value , str ): try : price = float ( value ) except ValueError : return None else : return None if not isfinite ( price ) or price <= 0 : return None return price fetch_latest_closed_rates_for_trading_client \u00b6 fetch_latest_closed_rates_for_trading_client ( client : Mt5TradingClient , * , symbol : str , granularity : str , count : int , ) -> DataFrame Fetch the latest closed bars from a connected trading client. Returns: Type Description DataFrame Up to count closed bars ordered oldest to newest. Raises: Type Description ValueError If count is not positive, rate data is empty or malformed, or the time column is missing. Mt5TradingError If the trading client cannot fetch rate data. Source code in mt5cli/trading.py 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 def fetch_latest_closed_rates_for_trading_client ( client : Mt5TradingClient , * , symbol : str , granularity : str , count : int , ) -> pd . DataFrame : \"\"\"Fetch the latest closed bars from a connected trading client. Returns: Up to ``count`` closed bars ordered oldest to newest. Raises: ValueError: If ``count`` is not positive, rate data is empty or malformed, or the ``time`` column is missing. Mt5TradingError: If the trading client cannot fetch rate data. \"\"\" if count <= 0 : msg = \"count must be positive.\" raise ValueError ( msg ) fetch_method = getattr ( client , \"fetch_latest_rates_as_df\" , None ) if not callable ( fetch_method ): msg = \"MT5 trading client cannot fetch rate data.\" raise Mt5TradingError ( msg ) fetched = fetch_method ( symbol , granularity , count + 1 ) if not isinstance ( fetched , pd . DataFrame ): msg = ( f \"Malformed rate data for { symbol !r} at granularity { granularity !r} : \" \"expected a DataFrame.\" ) raise ValueError ( msg ) # noqa: TRY004 frame = fetched frame = _ensure_rate_time_column ( frame ) if \"time\" not in frame . columns : msg = f \"Rate data is missing a time column for { symbol !r} .\" raise ValueError ( msg ) closed = drop_forming_rate_bar ( frame ) if closed . empty : msg = ( f \"Rate data is empty for { symbol !r} at granularity { granularity !r} \" f \"with count { count } .\" ) raise ValueError ( msg ) return closed . tail ( count ) . reset_index ( drop = True ) fetch_latest_closed_rates_indexed \u00b6 fetch_latest_closed_rates_indexed ( client : Mt5TradingClient , * , symbol : str , granularity : str , count : int , ) -> DataFrame Fetch the latest closed bars with a UTC DatetimeIndex from a trading client. Internally reuses :func: fetch_latest_closed_rates_for_trading_client for closed-bar detection and validation, then converts the time column to a UTC-aware :class: ~pandas.DatetimeIndex named \"time\" and drops the original column. Intended for downstream time-series consumers that require a datetime index rather than a time column. Parameters: Name Type Description Default client Mt5TradingClient Connected trading client with rate-fetch capability. required symbol str Symbol name. required granularity str Timeframe string (for example \"M1\" , \"H1\" ). required count int Maximum number of closed bars to return. required Returns: Type Description DataFrame Up to count closed bars ordered oldest to newest, with a DataFrame UTC-aware DatetimeIndex named \"time\" . The original time DataFrame column is dropped. Raises: Type Description ValueError If count is not positive, rate data is empty or malformed, the time column is missing, or timestamp data is invalid or unparseable. Source code in mt5cli/trading.py 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 def fetch_latest_closed_rates_indexed ( client : Mt5TradingClient , * , symbol : str , granularity : str , count : int , ) -> pd . DataFrame : \"\"\"Fetch the latest closed bars with a UTC DatetimeIndex from a trading client. Internally reuses :func:`fetch_latest_closed_rates_for_trading_client` for closed-bar detection and validation, then converts the ``time`` column to a UTC-aware :class:`~pandas.DatetimeIndex` named ``\"time\"`` and drops the original column. Intended for downstream time-series consumers that require a datetime index rather than a ``time`` column. Args: client: Connected trading client with rate-fetch capability. symbol: Symbol name. granularity: Timeframe string (for example ``\"M1\"``, ``\"H1\"``). count: Maximum number of closed bars to return. Returns: Up to ``count`` closed bars ordered oldest to newest, with a UTC-aware ``DatetimeIndex`` named ``\"time\"``. The original ``time`` column is dropped. Raises: ValueError: If ``count`` is not positive, rate data is empty or malformed, the ``time`` column is missing, or timestamp data is invalid or unparseable. \"\"\" frame = fetch_latest_closed_rates_for_trading_client ( client , symbol = symbol , granularity = granularity , count = count , ) if \"time\" not in frame . columns : msg = f \"Rate data is missing a time column for { symbol !r} .\" raise ValueError ( msg ) idx = _rate_time_to_utc ( frame [ \"time\" ], symbol ) idx . name = \"time\" result = frame . drop ( columns = [ \"time\" ]) result . index = idx return result get_account_snapshot \u00b6 get_account_snapshot ( client : Mt5TradingClient , ) -> dict [ str , float | int | str | None ] Return normalized account state with stable keys. Source code in mt5cli/trading.py 571 572 573 574 575 576 577 578 579 def get_account_snapshot ( client : Mt5TradingClient , ) -> dict [ str , float | int | str | None ]: \"\"\"Return normalized account state with stable keys.\"\"\" value = _call_snapshot_method ( client , \"account_info_as_dict\" , \"account_info\" ) return cast ( \"dict[str, float | int | str | None]\" , _snapshot_from_value ( value , _ACCOUNT_SNAPSHOT_FIELDS ), ) get_positions_frame \u00b6 get_positions_frame ( client : Mt5TradingClient , symbol : str | None = None ) -> DataFrame Return open positions as a DataFrame with stable baseline columns. Source code in mt5cli/trading.py 608 609 610 611 612 613 614 615 616 617 def get_positions_frame ( client : Mt5TradingClient , symbol : str | None = None , ) -> pd . DataFrame : \"\"\"Return open positions as a DataFrame with stable baseline columns.\"\"\" frame = client . positions_get_as_df ( symbol = symbol ) for column in POSITION_COLUMNS : if column not in frame . columns : frame [ column ] = pd . Series ( dtype = \"object\" ) return frame get_symbol_snapshot \u00b6 get_symbol_snapshot ( client : Mt5TradingClient , symbol : str ) -> dict [ str , float | int | str | bool | None ] Return normalized symbol metadata required for trading decisions. Source code in mt5cli/trading.py 582 583 584 585 586 587 588 589 590 591 def get_symbol_snapshot ( client : Mt5TradingClient , symbol : str , ) -> dict [ str , float | int | str | bool | None ]: \"\"\"Return normalized symbol metadata required for trading decisions.\"\"\" method = getattr ( client , \"symbol_info_as_dict\" , None ) value = method ( symbol = symbol ) if callable ( method ) else client . symbol_info ( symbol ) snapshot = _snapshot_from_value ( value , _SYMBOL_SNAPSHOT_FIELDS ) snapshot [ \"symbol\" ] = snapshot . get ( \"symbol\" ) or symbol return cast ( \"dict[str, float | int | str | bool | None]\" , snapshot ) get_tick_snapshot \u00b6 get_tick_snapshot ( client : Mt5TradingClient , symbol : str ) -> dict [ str , float | int | None ] Return normalized latest tick data, including bid, ask, and timestamp. Source code in mt5cli/trading.py 594 595 596 597 598 599 600 601 602 603 604 605 def get_tick_snapshot ( client : Mt5TradingClient , symbol : str , ) -> dict [ str , float | int | None ]: \"\"\"Return normalized latest tick data, including bid, ask, and timestamp.\"\"\" method = getattr ( client , \"symbol_info_tick_as_dict\" , None ) value = ( method ( symbol = symbol ) if callable ( method ) else client . symbol_info_tick ( symbol ) ) snapshot = _snapshot_from_value ( value , _TICK_SNAPSHOT_FIELDS ) snapshot [ \"symbol\" ] = snapshot . get ( \"symbol\" ) or symbol return cast ( \"dict[str, float | int | None]\" , snapshot ) mt5_trading_session \u00b6 mt5_trading_session ( config : Mt5Config | None = None , * , login : int | str | None = None , password : str | None = None , server : str | None = None , path : str | None = None , timeout : int | None = None , retry_count : int = 0 , ) -> Iterator [ Mt5TradingClient ] Open a trading-capable MT5 session and always shut down safely. Launches the MetaTrader 5 terminal using Mt5Config.path when set, initializes and logs in via initialize_and_login_mt5() , yields a connected :class: ~pdmt5.Mt5TradingClient , and calls shutdown() on exit even when an error is raised inside the context. Parameters: Name Type Description Default config Mt5Config | None MT5 connection configuration. Defaults to an empty config that attaches to a running terminal. None login int | str | None Optional trading account login. None password str | None Optional trading account password. None server str | None Optional trading server name. None path str | None Optional terminal executable path. None timeout int | None Optional connection timeout in milliseconds. None retry_count int Number of initialization retries passed to Mt5TradingClient . 0 Yields: Type Description Mt5TradingClient Connected Mt5TradingClient bound to the session. Source code in mt5cli/trading.py 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 @contextmanager def mt5_trading_session ( config : Mt5Config | None = None , * , login : int | str | None = None , password : str | None = None , server : str | None = None , path : str | None = None , timeout : int | None = None , retry_count : int = 0 , ) -> Iterator [ Mt5TradingClient ]: \"\"\"Open a trading-capable MT5 session and always shut down safely. Launches the MetaTrader 5 terminal using ``Mt5Config.path`` when set, initializes and logs in via ``initialize_and_login_mt5()``, yields a connected :class:`~pdmt5.Mt5TradingClient`, and calls ``shutdown()`` on exit even when an error is raised inside the context. Args: config: MT5 connection configuration. Defaults to an empty config that attaches to a running terminal. login: Optional trading account login. password: Optional trading account password. server: Optional trading server name. path: Optional terminal executable path. timeout: Optional connection timeout in milliseconds. retry_count: Number of initialization retries passed to ``Mt5TradingClient``. Yields: Connected ``Mt5TradingClient`` bound to the session. \"\"\" client = create_trading_client ( config = config , login = login , password = password , server = server , path = path , timeout = timeout , retry_count = retry_count , ) try : yield client finally : client . shutdown () normalize_order_volume \u00b6 normalize_order_volume ( volume : float , * , volume_min : float , volume_max : float , volume_step : float , ) -> float Normalize a requested order volume to broker volume constraints. Returns: Type Description float Volume floored to the nearest valid broker step from volume_min , float capped at volume_max when finite and positive, and rounded float deterministically. Returns 0.0 when inputs or constraints are float invalid, non-finite, or the capped request is below volume_min . Source code in mt5cli/trading.py 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 def normalize_order_volume ( volume : float , * , volume_min : float , volume_max : float , volume_step : float , ) -> float : \"\"\"Normalize a requested order volume to broker volume constraints. Returns: Volume floored to the nearest valid broker step from ``volume_min``, capped at ``volume_max`` when finite and positive, and rounded deterministically. Returns ``0.0`` when inputs or constraints are invalid, non-finite, or the capped request is below ``volume_min``. \"\"\" if not _is_finite_number ( volume ): return 0.0 if not _is_positive_finite_number ( volume_min ): return 0.0 if not _is_positive_finite_number ( volume_step ): return 0.0 has_volume_cap = _is_positive_finite_number ( volume_max ) capped = min ( volume , volume_max ) if has_volume_cap else volume if capped < volume_min : return 0.0 steps = floor ((( capped - volume_min ) / volume_step ) + 1e-12 ) normalized = volume_min + max ( 0 , steps ) * volume_step if has_volume_cap : normalized = min ( normalized , volume_max ) return round ( normalized , 10 ) place_market_order \u00b6 place_market_order ( client : Mt5TradingClient , * , symbol : str , volume : float , order_side : OrderSide , order_filling_mode : OrderFillingMode = \"IOC\" , order_time_mode : OrderTimeMode = \"GTC\" , sl : float | None = None , tp : float | None = None , position : int | None = None , dry_run : bool = False , ) -> OrderExecutionResult Place one normalized market order or return a dry-run result. pdmt5.Mt5TradingClient.order_send() raises only when MT5 returns no response. When MT5 returns a response with a known non-success retcode, this helper returns status=\"failed\" and keeps the normalized response details for callers to inspect. Returns: Type Description OrderExecutionResult Normalized execution result containing request and response details. Raises: Type Description Mt5TradingError If volume or required tick data is invalid. Source code in mt5cli/trading.py 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 def place_market_order ( client : Mt5TradingClient , * , symbol : str , volume : float , order_side : OrderSide , order_filling_mode : OrderFillingMode = \"IOC\" , order_time_mode : OrderTimeMode = \"GTC\" , sl : float | None = None , tp : float | None = None , position : int | None = None , dry_run : bool = False , ) -> OrderExecutionResult : \"\"\"Place one normalized market order or return a dry-run result. ``pdmt5.Mt5TradingClient.order_send()`` raises only when MT5 returns no response. When MT5 returns a response with a known non-success retcode, this helper returns ``status=\"failed\"`` and keeps the normalized response details for callers to inspect. Returns: Normalized execution result containing request and response details. Raises: Mt5TradingError: If volume or required tick data is invalid. \"\"\" if volume <= 0 : msg = \"volume must be positive.\" raise Mt5TradingError ( msg ) side = _normalize_order_side ( order_side ) if not dry_run : ensure_symbol_selected ( client , symbol ) tick = get_tick_snapshot ( client , symbol ) price = extract_tick_price ( tick , \"ask\" if side == \"BUY\" else \"bid\" ) if price is None : msg = f \"Tick price is unavailable for { symbol !r} .\" raise Mt5TradingError ( msg ) request = { \"action\" : client . mt5 . TRADE_ACTION_DEAL , \"symbol\" : symbol , \"volume\" : volume , \"type\" : ( client . mt5 . ORDER_TYPE_BUY if side == \"BUY\" else client . mt5 . ORDER_TYPE_SELL ), \"price\" : price , \"type_filling\" : _resolve_mt5_constant ( client . mt5 , \"ORDER_FILLING\" , order_filling_mode , _ORDER_FILLING_MODES , ), \"type_time\" : _resolve_mt5_constant ( client . mt5 , \"ORDER_TIME\" , order_time_mode , _ORDER_TIME_MODES , ), } if sl is not None : request [ \"sl\" ] = sl if tp is not None : request [ \"tp\" ] = tp if position is not None : request [ \"position\" ] = position if dry_run : return { \"status\" : \"dry_run\" , \"symbol\" : symbol , \"order_side\" : side , \"volume\" : volume , \"retcode\" : None , \"comment\" : None , \"request\" : cast ( \"dict[str, object]\" , request ), \"response\" : None , \"dry_run\" : True , } response = client . order_send ( request ) response_dict = _snapshot_from_value ( response , ()) raw_retcode = response_dict . get ( \"retcode\" ) retcode = _optional_int ( raw_retcode ) return { \"status\" : _order_status_from_retcode ( client . mt5 , raw_retcode ), \"symbol\" : symbol , \"order_side\" : side , \"volume\" : volume , \"retcode\" : retcode , \"comment\" : _optional_str ( response_dict . get ( \"comment\" )), \"request\" : cast ( \"dict[str, object]\" , request ), \"response\" : response_dict , \"dry_run\" : False , } update_sltp_for_open_positions \u00b6 update_sltp_for_open_positions ( client : Mt5TradingClient , * , symbol : str | None = None , tickets : list [ int ] | None = None , stop_loss : float | None = None , take_profit : float | None = None , dry_run : bool = False , ) -> list [ OrderExecutionResult ] Update SL/TP for matching open positions. Returns: Type Description list [ OrderExecutionResult ] Normalized execution results for matching positions. Source code in mt5cli/trading.py 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 def update_sltp_for_open_positions ( client : Mt5TradingClient , * , symbol : str | None = None , tickets : list [ int ] | None = None , stop_loss : float | None = None , take_profit : float | None = None , dry_run : bool = False , ) -> list [ OrderExecutionResult ]: \"\"\"Update SL/TP for matching open positions. Returns: Normalized execution results for matching positions. \"\"\" positions = _filter_positions ( get_positions_frame ( client ), symbols = symbol , tickets = tickets , ) results : list [ OrderExecutionResult ] = [] for row in positions . to_dict ( \"records\" ): request = { \"action\" : client . mt5 . TRADE_ACTION_SLTP , \"symbol\" : row [ \"symbol\" ], \"position\" : row [ \"ticket\" ], } sl = _optional_price ( row . get ( \"sl\" ) if stop_loss is None else stop_loss ) tp = _optional_price ( row . get ( \"tp\" ) if take_profit is None else take_profit ) if sl is not None : request [ \"sl\" ] = sl if tp is not None : request [ \"tp\" ] = tp if dry_run : response = None status : ExecutionStatus = \"dry_run\" else : ensure_symbol_selected ( client , str ( row [ \"symbol\" ])) response = _snapshot_from_value ( client . order_send ( request ), ()) status = _order_status_from_retcode ( client . mt5 , response . get ( \"retcode\" ), ) results . append ( { \"status\" : status , \"symbol\" : str ( row [ \"symbol\" ]), \"order_side\" : \"BUY\" if row [ \"type\" ] == client . mt5 . POSITION_TYPE_BUY else \"SELL\" , \"volume\" : float ( row [ \"volume\" ]), \"retcode\" : None if response is None else _optional_int ( response . get ( \"retcode\" )), \"comment\" : None if response is None else _optional_str ( response . get ( \"comment\" )), \"request\" : cast ( \"dict[str, object]\" , request ), \"response\" : response , \"dry_run\" : dry_run , }, ) return results update_trailing_stop_loss_for_open_positions \u00b6 update_trailing_stop_loss_for_open_positions ( client : Mt5TradingClient , * , symbol : str , trailing_stop_ratio : float , dry_run : bool = False , ) -> list [ OrderExecutionResult ] Update open positions whose trailing stop loss should move favorably. Returns: Type Description list [ OrderExecutionResult ] Normalized execution results for positions that need an SL update. Source code in mt5cli/trading.py 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 def update_trailing_stop_loss_for_open_positions ( client : Mt5TradingClient , * , symbol : str , trailing_stop_ratio : float , dry_run : bool = False , ) -> list [ OrderExecutionResult ]: \"\"\"Update open positions whose trailing stop loss should move favorably. Returns: Normalized execution results for positions that need an SL update. \"\"\" updates = calculate_trailing_stop_updates ( client , symbol = symbol , trailing_stop_ratio = trailing_stop_ratio , ) results : list [ OrderExecutionResult ] = [] for ticket , stop_loss in updates . items (): results . extend ( update_sltp_for_open_positions ( client , symbol = symbol , tickets = [ ticket ], stop_loss = stop_loss , dry_run = dry_run , ), ) return results Trading-capable MT5 sessions \u00b6 create_trading_client() and mt5_trading_session() complement the read-only mt5_session() helper in sdk.py . They return or yield an initialized pdmt5.Mt5TradingClient , use Mt5Config.path to launch the terminal when configured, and mt5_trading_session() always calls shutdown() on exit. from mt5cli import create_trading_client , mt5_trading_session with mt5_trading_session ( path = r \"C:\\Program Files\\MetaTrader 5\\terminal64.exe\" , login = \"12345\" , password = \"secret\" , server = \"Broker-Demo\" , retry_count = 2 , ) as client : positions = client . positions_get_as_df ( symbol = \"EURUSD\" ) client = create_trading_client ( login = 12345 , server = \"Broker-Demo\" ) try : account = client . account_info_as_dict () finally : client . shutdown () login accepts int , numeric str , or an empty string; empty strings are treated as unset. path , password , server , and timeout are forwarded to pdmt5.Mt5Config , and omitted timeout values keep the lower-level default. Use mt5_session() / MT5Client for read-only data collection. State and order helpers \u00b6 These helpers are strategy-agnostic and do not depend on signal detection, betting logic, or scheduling code in downstream applications. from mt5cli import ( calculate_positions_margin , calculate_spread_ratio , calculate_margin_and_volume , close_open_positions , detect_position_side , determine_order_limits , estimate_order_margin , fetch_latest_closed_rates_for_trading_client , fetch_latest_closed_rates_indexed , get_account_snapshot , get_positions_frame , get_symbol_snapshot , get_tick_snapshot , normalize_order_volume , place_market_order , ) account = get_account_snapshot ( client ) symbol = get_symbol_snapshot ( client , \"EURUSD\" ) tick = get_tick_snapshot ( client , \"EURUSD\" ) positions = get_positions_frame ( client , \"EURUSD\" ) side = detect_position_side ( client , \"EURUSD\" ) spread_ratio = calculate_spread_ratio ( client , \"EURUSD\" ) volume = normalize_order_volume ( 0.15 , volume_min = symbol [ \"volume_min\" ], volume_max = symbol [ \"volume_max\" ], volume_step = symbol [ \"volume_step\" ], ) buy_margin = ( estimate_order_margin ( client , \"EURUSD\" , \"BUY\" , volume ) if volume > 0 else 0.0 ) open_margin = calculate_positions_margin ( client , symbols = [ \"EURUSD\" ]) closed_bars = fetch_latest_closed_rates_for_trading_client ( client , symbol = \"EURUSD\" , granularity = \"M1\" , count = 100 , ) # Or fetch with a UTC DatetimeIndex instead of a \"time\" column: indexed_bars = fetch_latest_closed_rates_indexed ( client , symbol = \"EURUSD\" , granularity = \"M1\" , count = 100 , ) # indexed_bars.index is a UTC-aware DatetimeIndex named \"time\" 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 , ) preview = place_market_order ( client , symbol = \"EURUSD\" , volume = sizing [ \"buy_volume\" ], order_side = \"BUY\" , sl = limits [ \"stop_loss\" ], tp = limits [ \"take_profit\" ], dry_run = True , ) closed = close_open_positions ( client , symbols = \"EURUSD\" , dry_run = True ) detect_position_side() returns long for buy-only exposure, short for sell-only exposure, and None for no positions or mixed long/short exposure. calculate_spread_ratio() uses (ask - bid) / ((ask + bid) / 2) and raises Mt5TradingError when bid or ask is missing or non-positive. normalize_order_volume() returns 0.0 for invalid constraints or sub-minimum requests; check the result before calling estimate_order_margin() , which requires a positive finite volume. calculate_positions_margin() silently skips rows with missing symbols, non-positive volumes, non-finite volumes, or unsupported position types, but propagates Mt5TradingError from estimate_order_margin() when a valid row encounters invalid tick data or margin results from the broker. SL/TP ratios for determine_order_limits() must satisfy 0 <= ratio < 1 ; 0 omits that level. SL/TP prices are rounded with symbol digits metadata when available. determine_order_limits() pre-validates computed SL/TP prices against available trade_stops_level * point metadata when present; violations raise Mt5TradingError . This is a planning helper only: it does not guarantee broker acceptance because live validation can still depend on price movement, bid/ask side, freeze levels, and server-side rules, and it does not validate trade_freeze_level . When symbol metadata cannot be loaded, protective prices still round with digits=8 and stop-level validation is skipped. unit_margin_ratio and preserved_margin_ratio for calculate_margin_and_volume() accept 0 <= ratio <= 1 ; unit_margin_ratio=0 requests one minimum valid unit when the post-reserve margin can afford it. Negative margin_free is clamped to 0.0 before sizing. Execution helpers return normalized OrderExecutionResult dictionaries containing the request, response, status, retcode, and dry_run flag; dry_run=True never sends an order or mutates Market Watch visibility. ensure_symbol_selected() adds hidden symbols to Market Watch before live order placement and SL/TP updates. Failed, malformed, or unknown broker retcodes are fail-closed and returned as status=\"failed\" while keeping the normalized response for inspection. Order planning return contracts \u00b6 from mt5cli import MarginVolume , OrderLimits , OrderExecutionResult sizing : MarginVolume = calculate_margin_and_volume ( client , \"EURUSD\" , unit_margin_ratio = 0.5 , preserved_margin_ratio = 0.2 , ) limits : OrderLimits = determine_order_limits ( client , \"EURUSD\" , side = \"long\" , stop_loss_limit_ratio = 0.01 , take_profit_limit_ratio = 0.02 , ) preview : OrderExecutionResult = place_market_order ( client , symbol = \"EURUSD\" , volume = sizing [ \"buy_volume\" ], order_side = \"BUY\" , sl = limits [ \"stop_loss\" ], tp = limits [ \"take_profit\" ], dry_run = True , ) updates : list [ OrderExecutionResult ] = update_sltp_for_open_positions ( client , symbol = \"EURUSD\" , stop_loss = limits [ \"stop_loss\" ], dry_run = True , ) Closes issue #33: strategy-neutral order planning and execution helpers exposed through the stable package root without embedding entry/exit policy. Migration from application-local helpers \u00b6 Application-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 broker volume step normalization normalize_order_volume() Local order or position margin estimation estimate_order_margin() , calculate_positions_margin() Local closed-bar fetch from a trading session fetch_latest_closed_rates_for_trading_client() , fetch_latest_closed_rates_indexed() 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() / MT5Client ; use mt5_trading_session() only where order placement or trading calculations are required.","title":"Trading"},{"location":"api/trading/#trading-module","text":"","title":"Trading Module"},{"location":"api/trading/#mt5cli.trading","text":"Trading-capable MetaTrader 5 session helpers and operational utilities.","title":"trading"},{"location":"api/trading/#mt5cli.trading.ExecutionStatus","text":"ExecutionStatus = Literal [ \"executed\" , \"dry_run\" , \"skipped\" , \"failed\" ]","title":"ExecutionStatus"},{"location":"api/trading/#mt5cli.trading.OrderFillingMode","text":"OrderFillingMode = Literal [ 'IOC' , 'FOK' , 'RETURN' ]","title":"OrderFillingMode"},{"location":"api/trading/#mt5cli.trading.OrderSide","text":"OrderSide = Literal [ 'BUY' , 'SELL' ]","title":"OrderSide"},{"location":"api/trading/#mt5cli.trading.OrderTimeMode","text":"OrderTimeMode = Literal [ \"GTC\" , \"DAY\" , \"SPECIFIED\" , \"SPECIFIED_DAY\" ]","title":"OrderTimeMode"},{"location":"api/trading/#mt5cli.trading.POSITION_COLUMNS","text":"POSITION_COLUMNS = ( \"ticket\" , \"time\" , \"symbol\" , \"type\" , \"volume\" , \"price_open\" , \"sl\" , \"tp\" , \"price_current\" , \"profit\" , \"swap\" , \"comment\" , )","title":"POSITION_COLUMNS"},{"location":"api/trading/#mt5cli.trading.PositionSide","text":"PositionSide = Literal [ 'long' , 'short' ]","title":"PositionSide"},{"location":"api/trading/#mt5cli.trading.ProjectionMode","text":"ProjectionMode = Literal [ 'add' , 'replace_symbol' ]","title":"ProjectionMode"},{"location":"api/trading/#mt5cli.trading.__all__","text":"__all__ = [ \"POSITION_COLUMNS\" , \"ExecutionStatus\" , \"MarginVolume\" , \"OrderExecutionResult\" , \"OrderFillingMode\" , \"OrderLimits\" , \"OrderSide\" , \"OrderTimeMode\" , \"PositionSide\" , \"ProjectionMode\" , \"calculate_account_projected_margin_ratio\" , \"calculate_margin_and_volume\" , \"calculate_new_position_margin_ratio\" , \"calculate_positions_margin\" , \"calculate_positions_margin_by_symbol\" , \"calculate_positions_margin_safe\" , \"calculate_projected_margin_ratio\" , \"calculate_spread_ratio\" , \"calculate_symbol_group_margin_ratio\" , \"calculate_trailing_stop_updates\" , \"calculate_volume_by_margin\" , \"close_open_positions\" , \"create_trading_client\" , \"detect_position_side\" , \"determine_order_limits\" , \"ensure_symbol_selected\" , \"estimate_order_margin\" , \"extract_tick_price\" , \"fetch_latest_closed_rates_for_trading_client\" , \"fetch_latest_closed_rates_indexed\" , \"get_account_snapshot\" , \"get_positions_frame\" , \"get_symbol_snapshot\" , \"get_tick_snapshot\" , \"mt5_trading_session\" , \"normalize_order_volume\" , \"place_market_order\" , \"update_sltp_for_open_positions\" , \"update_trailing_stop_loss_for_open_positions\" , ]","title":"__all__"},{"location":"api/trading/#mt5cli.trading.MarginVolume","text":"Bases: TypedDict Affordable volume bounds derived from account margin and symbol constraints.","title":"MarginVolume"},{"location":"api/trading/#mt5cli.trading.MarginVolume.available_margin","text":"available_margin : float","title":"available_margin"},{"location":"api/trading/#mt5cli.trading.MarginVolume.buy_volume","text":"buy_volume : float","title":"buy_volume"},{"location":"api/trading/#mt5cli.trading.MarginVolume.margin_free","text":"margin_free : float","title":"margin_free"},{"location":"api/trading/#mt5cli.trading.MarginVolume.sell_volume","text":"sell_volume : float","title":"sell_volume"},{"location":"api/trading/#mt5cli.trading.MarginVolume.trade_margin","text":"trade_margin : float","title":"trade_margin"},{"location":"api/trading/#mt5cli.trading.MarginVolume.volume_max","text":"volume_max : float","title":"volume_max"},{"location":"api/trading/#mt5cli.trading.MarginVolume.volume_min","text":"volume_min : float","title":"volume_min"},{"location":"api/trading/#mt5cli.trading.MarginVolume.volume_step","text":"volume_step : float","title":"volume_step"},{"location":"api/trading/#mt5cli.trading.OrderExecutionResult","text":"Bases: TypedDict Normalized result from market-order and position-management helpers.","title":"OrderExecutionResult"},{"location":"api/trading/#mt5cli.trading.OrderExecutionResult.comment","text":"comment : str | None","title":"comment"},{"location":"api/trading/#mt5cli.trading.OrderExecutionResult.dry_run","text":"dry_run : bool","title":"dry_run"},{"location":"api/trading/#mt5cli.trading.OrderExecutionResult.order_side","text":"order_side : OrderSide","title":"order_side"},{"location":"api/trading/#mt5cli.trading.OrderExecutionResult.request","text":"request : dict [ str , object ]","title":"request"},{"location":"api/trading/#mt5cli.trading.OrderExecutionResult.response","text":"response : dict [ str , object ] | None","title":"response"},{"location":"api/trading/#mt5cli.trading.OrderExecutionResult.retcode","text":"retcode : int | None","title":"retcode"},{"location":"api/trading/#mt5cli.trading.OrderExecutionResult.status","text":"status : ExecutionStatus","title":"status"},{"location":"api/trading/#mt5cli.trading.OrderExecutionResult.symbol","text":"symbol : str","title":"symbol"},{"location":"api/trading/#mt5cli.trading.OrderExecutionResult.volume","text":"volume : float","title":"volume"},{"location":"api/trading/#mt5cli.trading.OrderLimits","text":"Bases: TypedDict Protective order prices derived from current quotes and ratio parameters.","title":"OrderLimits"},{"location":"api/trading/#mt5cli.trading.OrderLimits.entry","text":"entry : float","title":"entry"},{"location":"api/trading/#mt5cli.trading.OrderLimits.stop_loss","text":"stop_loss : float | None","title":"stop_loss"},{"location":"api/trading/#mt5cli.trading.OrderLimits.take_profit","text":"take_profit : float | None","title":"take_profit"},{"location":"api/trading/#mt5cli.trading.calculate_account_projected_margin_ratio","text":"calculate_account_projected_margin_ratio ( client : Mt5TradingClient , * , symbol : str | None = None , new_position_side : OrderSide | None = None , new_position_volume : float = 0.0 , ) -> float Return account-wide current plus optional new-position margin over equity. Current exposure comes from the broker account snapshot margin field so unrelated open positions remain in the baseline. Optional projected exposure is added via :func: estimate_order_margin only when a symbol, side, and positive volume are all supplied. Source code in mt5cli/trading.py 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 def calculate_account_projected_margin_ratio ( client : Mt5TradingClient , * , symbol : str | None = None , new_position_side : OrderSide | None = None , new_position_volume : float = 0.0 , ) -> float : \"\"\"Return account-wide current plus optional new-position margin over equity. Current exposure comes from the broker account snapshot ``margin`` field so unrelated open positions remain in the baseline. Optional projected exposure is added via :func:`estimate_order_margin` only when a symbol, side, and positive volume are all supplied. \"\"\" account = get_account_snapshot ( client ) equity = _required_account_number ( account , \"equity\" , allow_zero = False ) margin = _required_account_number ( account , \"margin\" , allow_zero = True ) if symbol is not None and new_position_side is not None and new_position_volume > 0 : margin += estimate_order_margin ( client , symbol , new_position_side , new_position_volume , ) return margin / equity","title":"calculate_account_projected_margin_ratio"},{"location":"api/trading/#mt5cli.trading.calculate_margin_and_volume","text":"calculate_margin_and_volume ( client : Mt5TradingClient , symbol : str , unit_margin_ratio : float , preserved_margin_ratio : float , ) -> MarginVolume Calculate tradable margin and volumes from account free margin. Applies preserved_margin_ratio to keep a reserve off margin_free , then allocates unit_margin_ratio of the remainder as the margin budget for proportional volume sizing on both buy and sell sides. A unit_margin_ratio of 0 requests exactly one minimum valid unit per side when the post-reserve margin can afford it. Parameters: Name Type Description Default client Mt5TradingClient Connected Mt5TradingClient instance. required symbol str Symbol used for minimum-lot margin and volume calculations. required unit_margin_ratio float Fraction of post-reserve margin to allocate per unit. required preserved_margin_ratio float Fraction of margin_free to preserve. required Returns: Type Description MarginVolume Dictionary with margin_free , available_margin , trade_margin , MarginVolume buy_volume , and sell_volume . Negative margin_free values are MarginVolume clamped to 0.0 before sizing. Source code in mt5cli/trading.py 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 def calculate_margin_and_volume ( client : Mt5TradingClient , symbol : str , unit_margin_ratio : float , preserved_margin_ratio : float , ) -> MarginVolume : \"\"\"Calculate tradable margin and volumes from account free margin. Applies ``preserved_margin_ratio`` to keep a reserve off ``margin_free``, then allocates ``unit_margin_ratio`` of the remainder as the margin budget for proportional volume sizing on both buy and sell sides. A ``unit_margin_ratio`` of ``0`` requests exactly one minimum valid unit per side when the post-reserve margin can afford it. Args: client: Connected ``Mt5TradingClient`` instance. symbol: Symbol used for minimum-lot margin and volume calculations. unit_margin_ratio: Fraction of post-reserve margin to allocate per unit. preserved_margin_ratio: Fraction of ``margin_free`` to preserve. Returns: Dictionary with ``margin_free``, ``available_margin``, ``trade_margin``, ``buy_volume``, and ``sell_volume``. Negative ``margin_free`` values are clamped to ``0.0`` before sizing. \"\"\" _require_unit_ratio ( unit_margin_ratio , \"unit_margin_ratio\" ) _require_unit_ratio ( preserved_margin_ratio , \"preserved_margin_ratio\" ) account = client . account_info_as_dict () margin_free = max ( 0.0 , float ( account . get ( \"margin_free\" ) or 0.0 )) available_margin = margin_free * ( 1.0 - preserved_margin_ratio ) trade_margin = available_margin * unit_margin_ratio if unit_margin_ratio == 0 : buy_volume = _calculate_min_volume_if_affordable ( client , symbol , available_margin , \"BUY\" , ) sell_volume = _calculate_min_volume_if_affordable ( client , symbol , available_margin , \"SELL\" , ) else : buy_volume = calculate_volume_by_margin ( client , symbol , trade_margin , \"BUY\" ) sell_volume = calculate_volume_by_margin ( client , symbol , trade_margin , \"SELL\" ) try : symbol_info = get_symbol_snapshot ( client , symbol ) volume_min = float ( symbol_info . get ( \"volume_min\" ) or 0.0 ) volume_max = float ( symbol_info . get ( \"volume_max\" ) or 0.0 ) volume_step = float ( symbol_info . get ( \"volume_step\" ) or 0.0 ) except AttributeError : volume_min = volume_max = volume_step = 0.0 return { \"margin_free\" : margin_free , \"available_margin\" : available_margin , \"trade_margin\" : trade_margin , \"buy_volume\" : float ( buy_volume ), \"sell_volume\" : float ( sell_volume ), \"volume_min\" : volume_min , \"volume_max\" : volume_max , \"volume_step\" : volume_step , }","title":"calculate_margin_and_volume"},{"location":"api/trading/#mt5cli.trading.calculate_new_position_margin_ratio","text":"calculate_new_position_margin_ratio ( client : Mt5TradingClient , * , symbol : str , new_position_side : OrderSide | None = None , new_position_volume : float = 0.0 , ) -> float Return total margin/equity ratio after an optional hypothetical position. Raises: Type Description Mt5TradingError If equity or required tick data is invalid. Source code in mt5cli/trading.py 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 def calculate_new_position_margin_ratio ( client : Mt5TradingClient , * , symbol : str , new_position_side : OrderSide | None = None , new_position_volume : float = 0.0 , ) -> float : \"\"\"Return total margin/equity ratio after an optional hypothetical position. Raises: Mt5TradingError: If equity or required tick data is invalid. \"\"\" account = get_account_snapshot ( client ) equity = float ( account . get ( \"equity\" ) or 0.0 ) if equity <= 0 : msg = \"Account equity must be positive to calculate margin ratio.\" raise Mt5TradingError ( msg ) margin = float ( account . get ( \"margin\" ) or 0.0 ) if new_position_side is not None and new_position_volume > 0 : side = _normalize_order_side ( new_position_side ) price = extract_tick_price ( get_tick_snapshot ( client , symbol ), \"ask\" if side == \"BUY\" else \"bid\" ) if price is None : msg = f \"Tick price is unavailable for { symbol !r} .\" raise Mt5TradingError ( msg ) order_type = ( client . mt5 . ORDER_TYPE_BUY if side == \"BUY\" else client . mt5 . ORDER_TYPE_SELL ) margin += float ( client . order_calc_margin ( order_type , symbol , new_position_volume , price ), ) return margin / equity","title":"calculate_new_position_margin_ratio"},{"location":"api/trading/#mt5cli.trading.calculate_positions_margin","text":"calculate_positions_margin ( client : Mt5TradingClient , * , symbols : Sequence [ str ] | None = None , ) -> float Return the sum of estimated current margin for open positions. Parameters: Name Type Description Default client Mt5TradingClient Connected Mt5TradingClient instance. required symbols Sequence [ str ] | None Optional symbol filter. When omitted, all open positions are included. None Returns: Type Description float Total estimated margin, or 0.0 when no matching positions exist. Source code in mt5cli/trading.py 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 def calculate_positions_margin ( client : Mt5TradingClient , * , symbols : Sequence [ str ] | None = None , ) -> float : \"\"\"Return the sum of estimated current margin for open positions. Args: client: Connected ``Mt5TradingClient`` instance. symbols: Optional symbol filter. When omitted, all open positions are included. Returns: Total estimated margin, or ``0.0`` when no matching positions exist. \"\"\" frame = get_positions_frame ( client ) if frame . empty or \"symbol\" not in frame . columns : return 0.0 if symbols is not None : frame = frame [ frame [ \"symbol\" ] . isin ( list ( symbols ))] if frame . empty : return 0.0 grouped_volumes : dict [ tuple [ str , OrderSide ], float ] = {} for _ , row in frame . iterrows (): symbol = row . get ( \"symbol\" ) if not isinstance ( symbol , str ) or not symbol : continue volume = row . get ( \"volume\" ) if not _is_positive_finite_number ( volume ): continue order_side = _order_side_from_position_type ( client , row . get ( \"type\" )) if order_side is None : continue key = ( symbol , order_side ) finite_volume = float ( cast ( \"float | int\" , volume )) grouped_volumes [ key ] = grouped_volumes . get ( key , 0.0 ) + finite_volume total = 0.0 for ( symbol , order_side ), volume in grouped_volumes . items (): total += estimate_order_margin ( client , symbol , order_side , volume ) return total","title":"calculate_positions_margin"},{"location":"api/trading/#mt5cli.trading.calculate_positions_margin_by_symbol","text":"calculate_positions_margin_by_symbol ( client : Mt5TradingClient , * , symbols : Sequence [ str ], suppress_errors : bool = True , ) -> dict [ str , float ] Return per-symbol estimated margin for open positions. Computes margin for each unique input symbol independently using the strict :func: calculate_positions_margin helper. Duplicates are deduplicated in first-seen order. Parameters: Name Type Description Default client Mt5TradingClient Connected Mt5TradingClient instance. required symbols Sequence [ str ] Symbols to compute margin for. required suppress_errors bool When True , log and skip symbols that raise Mt5TradingError , Mt5RuntimeError , or AttributeError . When False , re-raise the first failure. True Returns: Type Description dict [ str , float ] Mapping of symbol to margin total in first-seen unique-symbol order. dict [ str , float ] Returns an empty dict when symbols is empty or all symbols fail dict [ str , float ] with suppress_errors=True . Raises: Type Description Mt5TradingError When a symbol raises Mt5TradingError and suppress_errors=False . Mt5RuntimeError When a symbol raises Mt5RuntimeError and suppress_errors=False . AttributeError When a symbol raises AttributeError and suppress_errors=False . Source code in mt5cli/trading.py 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 def calculate_positions_margin_by_symbol ( client : Mt5TradingClient , * , symbols : Sequence [ str ], suppress_errors : bool = True , ) -> dict [ str , float ]: \"\"\"Return per-symbol estimated margin for open positions. Computes margin for each unique input symbol independently using the strict :func:`calculate_positions_margin` helper. Duplicates are deduplicated in first-seen order. Args: client: Connected ``Mt5TradingClient`` instance. symbols: Symbols to compute margin for. suppress_errors: When ``True``, log and skip symbols that raise ``Mt5TradingError``, ``Mt5RuntimeError``, or ``AttributeError``. When ``False``, re-raise the first failure. Returns: Mapping of symbol to margin total in first-seen unique-symbol order. Returns an empty dict when ``symbols`` is empty or all symbols fail with ``suppress_errors=True``. Raises: Mt5TradingError: When a symbol raises ``Mt5TradingError`` and ``suppress_errors=False``. Mt5RuntimeError: When a symbol raises ``Mt5RuntimeError`` and ``suppress_errors=False``. AttributeError: When a symbol raises ``AttributeError`` and ``suppress_errors=False``. \"\"\" result : dict [ str , float ] = {} for symbol in dict . fromkeys ( symbols ): try : result [ symbol ] = calculate_positions_margin ( client , symbols = [ symbol ]) except ( Mt5TradingError , Mt5RuntimeError , AttributeError ) as exc : if not suppress_errors : raise _logger . warning ( \"Skipping margin for %r : %s \" , symbol , exc ) return result","title":"calculate_positions_margin_by_symbol"},{"location":"api/trading/#mt5cli.trading.calculate_positions_margin_safe","text":"calculate_positions_margin_safe ( client : Mt5TradingClient , * , symbols : Sequence [ str ] ) -> float Return the total estimated margin for open positions across symbols. Internally calls :func: calculate_positions_margin_by_symbol with suppress_errors=True . Failed symbols are silently skipped. Parameters: Name Type Description Default client Mt5TradingClient Connected Mt5TradingClient instance. required symbols Sequence [ str ] Symbols to include. required Returns: Type Description float Sum of per-symbol margins; 0.0 when no symbols or all fail. Source code in mt5cli/trading.py 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 def calculate_positions_margin_safe ( client : Mt5TradingClient , * , symbols : Sequence [ str ], ) -> float : \"\"\"Return the total estimated margin for open positions across symbols. Internally calls :func:`calculate_positions_margin_by_symbol` with ``suppress_errors=True``. Failed symbols are silently skipped. Args: client: Connected ``Mt5TradingClient`` instance. symbols: Symbols to include. Returns: Sum of per-symbol margins; ``0.0`` when no symbols or all fail. \"\"\" return sum ( calculate_positions_margin_by_symbol ( client , symbols = symbols ) . values (), 0.0 , )","title":"calculate_positions_margin_safe"},{"location":"api/trading/#mt5cli.trading.calculate_projected_margin_ratio","text":"calculate_projected_margin_ratio ( client : Mt5TradingClient , * , symbol : str , new_position_side : OrderSide | None = None , new_position_volume : float = 0.0 , ) -> float Return estimated current plus optional new-position margin over equity. Current exposure is estimated from open positions with :func: calculate_positions_margin . Optional projected exposure is added via :func: estimate_order_margin . Thresholds and guard actions are intentionally left to downstream applications. Account equity, position margin, and optional projected margin errors from the composed MT5 helpers propagate to the caller. Source code in mt5cli/trading.py 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 def calculate_projected_margin_ratio ( client : Mt5TradingClient , * , symbol : str , new_position_side : OrderSide | None = None , new_position_volume : float = 0.0 , ) -> float : \"\"\"Return estimated current plus optional new-position margin over equity. Current exposure is estimated from open positions with :func:`calculate_positions_margin`. Optional projected exposure is added via :func:`estimate_order_margin`. Thresholds and guard actions are intentionally left to downstream applications. Account equity, position margin, and optional projected margin errors from the composed MT5 helpers propagate to the caller. \"\"\" equity = _account_equity ( client ) margin = calculate_positions_margin ( client , symbols = [ symbol ]) if new_position_side is not None and new_position_volume > 0 : margin += estimate_order_margin ( client , symbol , new_position_side , new_position_volume , ) return margin / equity","title":"calculate_projected_margin_ratio"},{"location":"api/trading/#mt5cli.trading.calculate_spread_ratio","text":"calculate_spread_ratio ( client : Mt5TradingClient , symbol : str ) -> float Return (ask - bid) / ((ask + bid) / 2) for the latest tick. Raises: Type Description Mt5TradingError If bid or ask is unavailable. Source code in mt5cli/trading.py 788 789 790 791 792 793 794 795 796 797 798 799 800 def calculate_spread_ratio ( client : Mt5TradingClient , symbol : str ) -> float : \"\"\"Return ``(ask - bid) / ((ask + bid) / 2)`` for the latest tick. Raises: Mt5TradingError: If bid or ask is unavailable. \"\"\" tick = get_tick_snapshot ( client , symbol ) bid = extract_tick_price ( tick , \"bid\" ) ask = extract_tick_price ( tick , \"ask\" ) if bid is None or ask is None : msg = f \"Tick bid/ask is unavailable for { symbol !r} .\" raise Mt5TradingError ( msg ) return ( ask - bid ) / (( ask + bid ) / 2.0 )","title":"calculate_spread_ratio"},{"location":"api/trading/#mt5cli.trading.calculate_symbol_group_margin_ratio","text":"calculate_symbol_group_margin_ratio ( client : Mt5TradingClient , * , symbols : Sequence [ str ], new_symbol : str | None = None , new_position_side : OrderSide | None = None , new_position_volume : float = 0.0 , suppress_errors : bool = True , projection_mode : ProjectionMode = \"add\" , ) -> float Return estimated symbol-group margin over account equity. Per-symbol current exposure is summed with :func: calculate_positions_margin_by_symbol . When new_symbol is inside the input symbol group and candidate side/volume are provided, projected order margin is applied according to projection_mode : \"add\" (default): adds candidate margin to the group total. \"replace_symbol\" : subtracts current margin for new_symbol , then adds candidate margin. Useful for reversal-style projections where the new order is intended to replace existing exposure for that symbol. If the candidate margin estimation fails, the subtraction is also skipped so the operation is atomic. Invalid equity always raises to fail closed. Raises: Type Description AttributeError When symbol margin lookup or projected margin lookup fails and suppress_errors is False . Mt5RuntimeError When symbol margin lookup or projected margin lookup fails and suppress_errors is False . Mt5TradingError When account equity is invalid, or when symbol margin lookup or projected margin lookup fails and suppress_errors is False . Source code in mt5cli/trading.py 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 def calculate_symbol_group_margin_ratio ( client : Mt5TradingClient , * , symbols : Sequence [ str ], new_symbol : str | None = None , new_position_side : OrderSide | None = None , new_position_volume : float = 0.0 , suppress_errors : bool = True , projection_mode : ProjectionMode = \"add\" , ) -> float : \"\"\"Return estimated symbol-group margin over account equity. Per-symbol current exposure is summed with :func:`calculate_positions_margin_by_symbol`. When ``new_symbol`` is inside the input symbol group and candidate side/volume are provided, projected order margin is applied according to ``projection_mode``: - ``\"add\"`` (default): adds candidate margin to the group total. - ``\"replace_symbol\"``: subtracts current margin for ``new_symbol``, then adds candidate margin. Useful for reversal-style projections where the new order is intended to replace existing exposure for that symbol. If the candidate margin estimation fails, the subtraction is also skipped so the operation is atomic. Invalid equity always raises to fail closed. Raises: AttributeError: When symbol margin lookup or projected margin lookup fails and ``suppress_errors`` is ``False``. Mt5RuntimeError: When symbol margin lookup or projected margin lookup fails and ``suppress_errors`` is ``False``. Mt5TradingError: When account equity is invalid, or when symbol margin lookup or projected margin lookup fails and ``suppress_errors`` is ``False``. \"\"\" equity = _account_equity ( client ) unique_symbols = list ( dict . fromkeys ( symbols )) per_symbol = calculate_positions_margin_by_symbol ( client , symbols = unique_symbols , suppress_errors = suppress_errors , ) margin = sum ( per_symbol . values (), 0.0 ) if ( new_symbol in unique_symbols and new_position_side is not None and new_position_volume > 0 ): try : candidate_margin = estimate_order_margin ( client , new_symbol , new_position_side , new_position_volume , ) except ( Mt5TradingError , Mt5RuntimeError , AttributeError ): if not suppress_errors : raise _logger . warning ( \"Skipping projected margin for %r .\" , new_symbol ) else : if projection_mode == \"replace_symbol\" : margin -= per_symbol . get ( new_symbol , 0.0 ) margin += candidate_margin return margin / equity","title":"calculate_symbol_group_margin_ratio"},{"location":"api/trading/#mt5cli.trading.calculate_trailing_stop_updates","text":"calculate_trailing_stop_updates ( client : Mt5TradingClient , * , symbol : str , trailing_stop_ratio : float , ) -> dict [ int , float ] Return per-ticket trailing stop-loss updates for open symbol positions. Buy positions trail from bid using bid * (1 - trailing_stop_ratio) . Sell positions trail from ask using ask * (1 + trailing_stop_ratio) . Existing stop losses are preserved when they are already more favorable. Missing symbol metadata returns an empty update map. Positions with a missing side-specific tick price are skipped. Source code in mt5cli/trading.py 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 def calculate_trailing_stop_updates ( client : Mt5TradingClient , * , symbol : str , trailing_stop_ratio : float , ) -> dict [ int , float ]: \"\"\"Return per-ticket trailing stop-loss updates for open symbol positions. Buy positions trail from bid using ``bid * (1 - trailing_stop_ratio)``. Sell positions trail from ask using ``ask * (1 + trailing_stop_ratio)``. Existing stop losses are preserved when they are already more favorable. Missing symbol metadata returns an empty update map. Positions with a missing side-specific tick price are skipped. \"\"\" _require_protective_ratio ( trailing_stop_ratio , \"trailing_stop_ratio\" ) positions = get_positions_frame ( client , symbol = symbol ) if positions . empty : return {} tick = get_tick_snapshot ( client , symbol ) bid = extract_tick_price ( tick , \"bid\" ) ask = extract_tick_price ( tick , \"ask\" ) digits = _symbol_digits ( client , symbol ) if digits is None : return {} updates : dict [ int , float ] = {} for row in positions . to_dict ( \"records\" ): ticket = _position_ticket ( row . get ( \"ticket\" )) if ticket is None : continue next_sl = _trailing_stop_loss ( client , position_type = row . get ( \"type\" ), current_sl = _current_stop_loss ( row . get ( \"sl\" )), bid = bid , ask = ask , digits = digits , trailing_stop_ratio = trailing_stop_ratio , ) if next_sl is None : continue updates [ ticket ] = next_sl return updates","title":"calculate_trailing_stop_updates"},{"location":"api/trading/#mt5cli.trading.calculate_volume_by_margin","text":"calculate_volume_by_margin ( client : Mt5TradingClient , symbol : str , available_margin : float , order_side : OrderSide , ) -> float Calculate max normalized volume affordable for one side. Returns: Type Description float Largest stepped volume whose actual margin (from order_calc_margin ) float fits within available_margin , rounded down to symbol volume float constraints; 0.0 when no affordable step exists. Raises: Type Description Mt5TradingError If symbol volume constraints or tick data are invalid. Source code in mt5cli/trading.py 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 def calculate_volume_by_margin ( client : Mt5TradingClient , symbol : str , available_margin : float , order_side : OrderSide , ) -> float : \"\"\"Calculate max normalized volume affordable for one side. Returns: Largest stepped volume whose actual margin (from ``order_calc_margin``) fits within ``available_margin``, rounded down to symbol volume constraints; ``0.0`` when no affordable step exists. Raises: Mt5TradingError: If symbol volume constraints or tick data are invalid. \"\"\" if available_margin <= 0 : return 0.0 symbol_info = get_symbol_snapshot ( client , symbol ) volume_min = float ( symbol_info . get ( \"volume_min\" ) or 0.0 ) volume_max = float ( symbol_info . get ( \"volume_max\" ) or 0.0 ) volume_step = float ( symbol_info . get ( \"volume_step\" ) or volume_min or 0.0 ) if volume_min <= 0 or volume_step <= 0 : msg = f \"Invalid volume constraints for { symbol !r} .\" raise Mt5TradingError ( msg ) side = _normalize_order_side ( order_side ) price = extract_tick_price ( get_tick_snapshot ( client , symbol ), \"ask\" if side == \"BUY\" else \"bid\" ) if price is None : msg = f \"Tick price is unavailable for { symbol !r} .\" raise Mt5TradingError ( msg ) order_type = ( client . mt5 . ORDER_TYPE_BUY if side == \"BUY\" else client . mt5 . ORDER_TYPE_SELL ) min_margin = float ( client . order_calc_margin ( order_type , symbol , volume_min , price )) if min_margin <= 0 or min_margin > available_margin : return 0.0 lo = 0 hi = int ( max ( 0 , floor ( ( ( min ( available_margin / min_margin * volume_min , volume_max ) if volume_max > 0 else available_margin / min_margin * volume_min ) - volume_min ) / volume_step + 1e-12 ), ) ) best = - 1 while lo <= hi : mid = ( lo + hi ) // 2 normalized = round ( volume_min + mid * volume_step , 10 ) actual = float ( client . order_calc_margin ( order_type , symbol , normalized , price )) if actual > 0 and actual <= available_margin : best = mid lo = mid + 1 else : hi = mid - 1 return round ( volume_min + best * volume_step , 10 ) if best >= 0 else 0.0","title":"calculate_volume_by_margin"},{"location":"api/trading/#mt5cli.trading.close_open_positions","text":"close_open_positions ( client : Mt5TradingClient , * , symbols : str | list [ str ] | None = None , tickets : list [ int ] | None = None , dry_run : bool = False , ) -> list [ OrderExecutionResult ] Close matching open positions. Returns: Type Description list [ OrderExecutionResult ] Normalized execution results for matching positions. Source code in mt5cli/trading.py 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 def close_open_positions ( client : Mt5TradingClient , * , symbols : str | list [ str ] | None = None , tickets : list [ int ] | None = None , dry_run : bool = False , ) -> list [ OrderExecutionResult ]: \"\"\"Close matching open positions. Returns: Normalized execution results for matching positions. \"\"\" positions = _filter_positions ( get_positions_frame ( client ), symbols = symbols , tickets = tickets , ) results : list [ OrderExecutionResult ] = [] for row in positions . to_dict ( \"records\" ): pos_type = row [ \"type\" ] side : OrderSide = \"SELL\" if pos_type == client . mt5 . POSITION_TYPE_BUY else \"BUY\" result = place_market_order ( client , symbol = str ( row [ \"symbol\" ]), volume = float ( row [ \"volume\" ]), order_side = side , position = int ( row [ \"ticket\" ]), dry_run = dry_run , ) results . append ( result ) return results","title":"close_open_positions"},{"location":"api/trading/#mt5cli.trading.create_trading_client","text":"create_trading_client ( * , config : Mt5Config | None = None , login : int | str | None = None , password : str | None = None , server : str | None = None , path : str | None = None , timeout : int | None = None , retry_count : int = 0 , ) -> Mt5TradingClient Return an initialized and logged-in trading client. Source code in mt5cli/trading.py 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 def create_trading_client ( * , config : Mt5Config | None = None , login : int | str | None = None , password : str | None = None , server : str | None = None , path : str | None = None , timeout : int | None = None , retry_count : int = 0 , ) -> Mt5TradingClient : \"\"\"Return an initialized and logged-in trading client.\"\"\" mt5_config = _resolve_config ( config = config , login = login , password = password , server = server , path = path , timeout = timeout , ) client = Mt5TradingClient ( config = mt5_config , retry_count = retry_count ) try : client . initialize_and_login_mt5 () except Exception : client . shutdown () raise return client","title":"create_trading_client"},{"location":"api/trading/#mt5cli.trading.detect_position_side","text":"detect_position_side ( client : Mt5TradingClient , symbol : str ) -> PositionSide | None Detect the net open position side for a symbol. Parameters: Name Type Description Default client Mt5TradingClient Connected Mt5TradingClient instance. required symbol str Symbol to inspect. required Returns: Type Description PositionSide | None \"long\" when there are buy positions and no sell positions, PositionSide | None \"short\" when there are sell positions and no buy positions, or PositionSide | None None when no positions or mixed exposure exists. Source code in mt5cli/trading.py 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 def detect_position_side ( client : Mt5TradingClient , symbol : str , ) -> PositionSide | None : \"\"\"Detect the net open position side for a symbol. Args: client: Connected ``Mt5TradingClient`` instance. symbol: Symbol to inspect. Returns: ``\"long\"`` when there are buy positions and no sell positions, ``\"short\"`` when there are sell positions and no buy positions, or ``None`` when no positions or mixed exposure exists. \"\"\" positions = get_positions_frame ( client , symbol = symbol ) if positions . empty : return None buy_type = client . mt5 . POSITION_TYPE_BUY sell_type = client . mt5 . POSITION_TYPE_SELL buy_volume = _sum_position_volume ( positions , buy_type ) sell_volume = _sum_position_volume ( positions , sell_type ) if buy_volume > 0 and sell_volume == 0 : return \"long\" if sell_volume > 0 and buy_volume == 0 : return \"short\" return None","title":"detect_position_side"},{"location":"api/trading/#mt5cli.trading.determine_order_limits","text":"determine_order_limits ( client : Mt5TradingClient , symbol : str , side : PositionSide | str , stop_loss_limit_ratio : float | None = None , take_profit_limit_ratio : float | None = None , ) -> OrderLimits Derive entry and protective order prices from current market quotes. Parameters: Name Type Description Default client Mt5TradingClient Connected Mt5TradingClient instance. required symbol str Symbol used for the quote lookup. required side PositionSide | str Position side as \"long\" / \"short\" ( \"buy\" / \"sell\" aliases are accepted). required stop_loss_limit_ratio float | None Relative distance from entry for stop loss in [0, 1) . A value of 0 omits the stop loss. None take_profit_limit_ratio float | None Relative distance from entry for take profit in [0, 1) . A value of 0 omits the take profit. None Returns: Type Description OrderLimits Dictionary with entry , stop_loss , and take_profit keys. OrderLimits Omitted protective levels are returned as None . Raises: Type Description Mt5TradingError If required tick data is invalid or computed SL/TP prices violate available trade_stops_level pre-validation. Source code in mt5cli/trading.py 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 def determine_order_limits ( client : Mt5TradingClient , symbol : str , side : PositionSide | str , stop_loss_limit_ratio : float | None = None , take_profit_limit_ratio : float | None = None , ) -> OrderLimits : \"\"\"Derive entry and protective order prices from current market quotes. Args: client: Connected ``Mt5TradingClient`` instance. symbol: Symbol used for the quote lookup. side: Position side as ``\"long\"``/``\"short\"`` (``\"buy\"``/``\"sell\"`` aliases are accepted). stop_loss_limit_ratio: Relative distance from entry for stop loss in ``[0, 1)``. A value of ``0`` omits the stop loss. take_profit_limit_ratio: Relative distance from entry for take profit in ``[0, 1)``. A value of ``0`` omits the take profit. Returns: Dictionary with ``entry``, ``stop_loss``, and ``take_profit`` keys. Omitted protective levels are returned as ``None``. Raises: Mt5TradingError: If required tick data is invalid or computed SL/TP prices violate available ``trade_stops_level`` pre-validation. \"\"\" stop_loss_ratio = stop_loss_limit_ratio or 0.0 take_profit_ratio = take_profit_limit_ratio or 0.0 _require_protective_ratio ( stop_loss_ratio , \"stop_loss_limit_ratio\" ) _require_protective_ratio ( take_profit_ratio , \"take_profit_limit_ratio\" ) normalized_side = _position_side_from_order_side ( side ) tick = get_tick_snapshot ( client , symbol ) entry_key = \"ask\" if normalized_side == \"long\" else \"bid\" entry = extract_tick_price ( tick , entry_key ) if entry is None : msg = f \"Tick price is unavailable for { symbol !r} .\" raise Mt5TradingError ( msg ) try : symbol_info = get_symbol_snapshot ( client , symbol ) except ( AttributeError , KeyError , TypeError , ValueError ): symbol_info = {} try : digits = int ( symbol_info . get ( \"digits\" ) or 8 ) except ( TypeError , ValueError ): digits = 8 min_distance = _minimum_stop_distance ( symbol_info ) stop_loss : float | None = None if stop_loss_ratio > 0 : if normalized_side == \"long\" : stop_loss = entry * ( 1.0 - stop_loss_ratio ) else : stop_loss = entry * ( 1.0 + stop_loss_ratio ) stop_loss = round ( stop_loss , digits ) take_profit : float | None = None if take_profit_ratio > 0 : if normalized_side == \"long\" : take_profit = entry * ( 1.0 + take_profit_ratio ) else : take_profit = entry * ( 1.0 - take_profit_ratio ) take_profit = round ( take_profit , digits ) _validate_protective_prices ( symbol = symbol , side = normalized_side , entry = entry , stop_loss = stop_loss , take_profit = take_profit , min_distance = min_distance , ) return { \"entry\" : entry , \"stop_loss\" : stop_loss , \"take_profit\" : take_profit , }","title":"determine_order_limits"},{"location":"api/trading/#mt5cli.trading.ensure_symbol_selected","text":"ensure_symbol_selected ( client : Mt5TradingClient , symbol : str ) -> None Ensure a symbol is visible in Market Watch before sending orders. Parameters: Name Type Description Default client Mt5TradingClient Connected Mt5TradingClient instance. required symbol str Symbol to select. required Raises: Type Description Mt5TradingError If the symbol cannot be selected in Market Watch or symbol_select is unavailable on the client. Source code in mt5cli/trading.py 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 def ensure_symbol_selected ( client : Mt5TradingClient , symbol : str ) -> None : \"\"\"Ensure a symbol is visible in Market Watch before sending orders. Args: client: Connected ``Mt5TradingClient`` instance. symbol: Symbol to select. Raises: Mt5TradingError: If the symbol cannot be selected in Market Watch or ``symbol_select`` is unavailable on the client. \"\"\" snapshot = get_symbol_snapshot ( client , symbol ) if snapshot . get ( \"visible\" ): return select = getattr ( client , \"symbol_select\" , None ) if not callable ( select ): msg = \"MT5 client is missing required method: symbol_select\" raise Mt5TradingError ( msg ) if select ( symbol , enable = True ): return last_error = getattr ( client , \"last_error\" , None ) detail = f \" ( { last_error () } )\" if callable ( last_error ) else \"\" msg = f \"Failed to select symbol { symbol !r} in Market Watch { detail } .\" raise Mt5TradingError ( msg )","title":"ensure_symbol_selected"},{"location":"api/trading/#mt5cli.trading.estimate_order_margin","text":"estimate_order_margin ( client : Mt5TradingClient , symbol : str , order_side : OrderSide | str , volume : float , ) -> float Estimate required margin for one order at the current market price. Returns: Type Description float Positive finite margin required for the order at the current quote. Raises: Type Description Mt5TradingError If volume, tick data, or margin estimation is invalid. Source code in mt5cli/trading.py 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 def estimate_order_margin ( client : Mt5TradingClient , symbol : str , order_side : OrderSide | str , volume : float , ) -> float : \"\"\"Estimate required margin for one order at the current market price. Returns: Positive finite margin required for the order at the current quote. Raises: Mt5TradingError: If volume, tick data, or margin estimation is invalid. \"\"\" if not _is_positive_finite_number ( volume ): msg = \"Volume must be a positive finite number to estimate order margin.\" raise Mt5TradingError ( msg ) side = _normalize_order_side ( order_side ) tick = get_tick_snapshot ( client , symbol ) price = extract_tick_price ( tick , \"ask\" if side == \"BUY\" else \"bid\" ) if price is None : msg = f \"Tick price is unavailable for { symbol !r} .\" raise Mt5TradingError ( msg ) order_type = ( client . mt5 . ORDER_TYPE_BUY if side == \"BUY\" else client . mt5 . ORDER_TYPE_SELL ) raw_margin = client . order_calc_margin ( order_type , symbol , volume , price ) try : margin = float ( raw_margin ) except ( TypeError , ValueError ) as exc : msg = f \"Margin estimate is invalid for { symbol !r} .\" raise Mt5TradingError ( msg ) from exc if margin <= 0 or not isfinite ( margin ): msg = f \"Margin estimate is invalid for { symbol !r} .\" raise Mt5TradingError ( msg ) return margin","title":"estimate_order_margin"},{"location":"api/trading/#mt5cli.trading.extract_tick_price","text":"extract_tick_price ( tick : Mapping [ str , object ], key : str ) -> float | None Return a positive finite float from tick[key], or None if invalid. Accepts int, float, or numeric string values. Returns None when the key is missing, the value is None, non-numeric, NaN, infinite, zero, or negative. Booleans are treated as non-numeric and return None. Source code in mt5cli/trading.py 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 def extract_tick_price ( tick : Mapping [ str , object ], key : str ) -> float | None : \"\"\"Return a positive finite float from tick[key], or None if invalid. Accepts int, float, or numeric string values. Returns None when the key is missing, the value is None, non-numeric, NaN, infinite, zero, or negative. Booleans are treated as non-numeric and return None. \"\"\" value = tick . get ( key ) if value is None or isinstance ( value , bool ): return None if isinstance ( value , int | float ): price = float ( value ) elif isinstance ( value , str ): try : price = float ( value ) except ValueError : return None else : return None if not isfinite ( price ) or price <= 0 : return None return price","title":"extract_tick_price"},{"location":"api/trading/#mt5cli.trading.fetch_latest_closed_rates_for_trading_client","text":"fetch_latest_closed_rates_for_trading_client ( client : Mt5TradingClient , * , symbol : str , granularity : str , count : int , ) -> DataFrame Fetch the latest closed bars from a connected trading client. Returns: Type Description DataFrame Up to count closed bars ordered oldest to newest. Raises: Type Description ValueError If count is not positive, rate data is empty or malformed, or the time column is missing. Mt5TradingError If the trading client cannot fetch rate data. Source code in mt5cli/trading.py 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 def fetch_latest_closed_rates_for_trading_client ( client : Mt5TradingClient , * , symbol : str , granularity : str , count : int , ) -> pd . DataFrame : \"\"\"Fetch the latest closed bars from a connected trading client. Returns: Up to ``count`` closed bars ordered oldest to newest. Raises: ValueError: If ``count`` is not positive, rate data is empty or malformed, or the ``time`` column is missing. Mt5TradingError: If the trading client cannot fetch rate data. \"\"\" if count <= 0 : msg = \"count must be positive.\" raise ValueError ( msg ) fetch_method = getattr ( client , \"fetch_latest_rates_as_df\" , None ) if not callable ( fetch_method ): msg = \"MT5 trading client cannot fetch rate data.\" raise Mt5TradingError ( msg ) fetched = fetch_method ( symbol , granularity , count + 1 ) if not isinstance ( fetched , pd . DataFrame ): msg = ( f \"Malformed rate data for { symbol !r} at granularity { granularity !r} : \" \"expected a DataFrame.\" ) raise ValueError ( msg ) # noqa: TRY004 frame = fetched frame = _ensure_rate_time_column ( frame ) if \"time\" not in frame . columns : msg = f \"Rate data is missing a time column for { symbol !r} .\" raise ValueError ( msg ) closed = drop_forming_rate_bar ( frame ) if closed . empty : msg = ( f \"Rate data is empty for { symbol !r} at granularity { granularity !r} \" f \"with count { count } .\" ) raise ValueError ( msg ) return closed . tail ( count ) . reset_index ( drop = True )","title":"fetch_latest_closed_rates_for_trading_client"},{"location":"api/trading/#mt5cli.trading.fetch_latest_closed_rates_indexed","text":"fetch_latest_closed_rates_indexed ( client : Mt5TradingClient , * , symbol : str , granularity : str , count : int , ) -> DataFrame Fetch the latest closed bars with a UTC DatetimeIndex from a trading client. Internally reuses :func: fetch_latest_closed_rates_for_trading_client for closed-bar detection and validation, then converts the time column to a UTC-aware :class: ~pandas.DatetimeIndex named \"time\" and drops the original column. Intended for downstream time-series consumers that require a datetime index rather than a time column. Parameters: Name Type Description Default client Mt5TradingClient Connected trading client with rate-fetch capability. required symbol str Symbol name. required granularity str Timeframe string (for example \"M1\" , \"H1\" ). required count int Maximum number of closed bars to return. required Returns: Type Description DataFrame Up to count closed bars ordered oldest to newest, with a DataFrame UTC-aware DatetimeIndex named \"time\" . The original time DataFrame column is dropped. Raises: Type Description ValueError If count is not positive, rate data is empty or malformed, the time column is missing, or timestamp data is invalid or unparseable. Source code in mt5cli/trading.py 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 def fetch_latest_closed_rates_indexed ( client : Mt5TradingClient , * , symbol : str , granularity : str , count : int , ) -> pd . DataFrame : \"\"\"Fetch the latest closed bars with a UTC DatetimeIndex from a trading client. Internally reuses :func:`fetch_latest_closed_rates_for_trading_client` for closed-bar detection and validation, then converts the ``time`` column to a UTC-aware :class:`~pandas.DatetimeIndex` named ``\"time\"`` and drops the original column. Intended for downstream time-series consumers that require a datetime index rather than a ``time`` column. Args: client: Connected trading client with rate-fetch capability. symbol: Symbol name. granularity: Timeframe string (for example ``\"M1\"``, ``\"H1\"``). count: Maximum number of closed bars to return. Returns: Up to ``count`` closed bars ordered oldest to newest, with a UTC-aware ``DatetimeIndex`` named ``\"time\"``. The original ``time`` column is dropped. Raises: ValueError: If ``count`` is not positive, rate data is empty or malformed, the ``time`` column is missing, or timestamp data is invalid or unparseable. \"\"\" frame = fetch_latest_closed_rates_for_trading_client ( client , symbol = symbol , granularity = granularity , count = count , ) if \"time\" not in frame . columns : msg = f \"Rate data is missing a time column for { symbol !r} .\" raise ValueError ( msg ) idx = _rate_time_to_utc ( frame [ \"time\" ], symbol ) idx . name = \"time\" result = frame . drop ( columns = [ \"time\" ]) result . index = idx return result","title":"fetch_latest_closed_rates_indexed"},{"location":"api/trading/#mt5cli.trading.get_account_snapshot","text":"get_account_snapshot ( client : Mt5TradingClient , ) -> dict [ str , float | int | str | None ] Return normalized account state with stable keys. Source code in mt5cli/trading.py 571 572 573 574 575 576 577 578 579 def get_account_snapshot ( client : Mt5TradingClient , ) -> dict [ str , float | int | str | None ]: \"\"\"Return normalized account state with stable keys.\"\"\" value = _call_snapshot_method ( client , \"account_info_as_dict\" , \"account_info\" ) return cast ( \"dict[str, float | int | str | None]\" , _snapshot_from_value ( value , _ACCOUNT_SNAPSHOT_FIELDS ), )","title":"get_account_snapshot"},{"location":"api/trading/#mt5cli.trading.get_positions_frame","text":"get_positions_frame ( client : Mt5TradingClient , symbol : str | None = None ) -> DataFrame Return open positions as a DataFrame with stable baseline columns. Source code in mt5cli/trading.py 608 609 610 611 612 613 614 615 616 617 def get_positions_frame ( client : Mt5TradingClient , symbol : str | None = None , ) -> pd . DataFrame : \"\"\"Return open positions as a DataFrame with stable baseline columns.\"\"\" frame = client . positions_get_as_df ( symbol = symbol ) for column in POSITION_COLUMNS : if column not in frame . columns : frame [ column ] = pd . Series ( dtype = \"object\" ) return frame","title":"get_positions_frame"},{"location":"api/trading/#mt5cli.trading.get_symbol_snapshot","text":"get_symbol_snapshot ( client : Mt5TradingClient , symbol : str ) -> dict [ str , float | int | str | bool | None ] Return normalized symbol metadata required for trading decisions. Source code in mt5cli/trading.py 582 583 584 585 586 587 588 589 590 591 def get_symbol_snapshot ( client : Mt5TradingClient , symbol : str , ) -> dict [ str , float | int | str | bool | None ]: \"\"\"Return normalized symbol metadata required for trading decisions.\"\"\" method = getattr ( client , \"symbol_info_as_dict\" , None ) value = method ( symbol = symbol ) if callable ( method ) else client . symbol_info ( symbol ) snapshot = _snapshot_from_value ( value , _SYMBOL_SNAPSHOT_FIELDS ) snapshot [ \"symbol\" ] = snapshot . get ( \"symbol\" ) or symbol return cast ( \"dict[str, float | int | str | bool | None]\" , snapshot )","title":"get_symbol_snapshot"},{"location":"api/trading/#mt5cli.trading.get_tick_snapshot","text":"get_tick_snapshot ( client : Mt5TradingClient , symbol : str ) -> dict [ str , float | int | None ] Return normalized latest tick data, including bid, ask, and timestamp. Source code in mt5cli/trading.py 594 595 596 597 598 599 600 601 602 603 604 605 def get_tick_snapshot ( client : Mt5TradingClient , symbol : str , ) -> dict [ str , float | int | None ]: \"\"\"Return normalized latest tick data, including bid, ask, and timestamp.\"\"\" method = getattr ( client , \"symbol_info_tick_as_dict\" , None ) value = ( method ( symbol = symbol ) if callable ( method ) else client . symbol_info_tick ( symbol ) ) snapshot = _snapshot_from_value ( value , _TICK_SNAPSHOT_FIELDS ) snapshot [ \"symbol\" ] = snapshot . get ( \"symbol\" ) or symbol return cast ( \"dict[str, float | int | None]\" , snapshot )","title":"get_tick_snapshot"},{"location":"api/trading/#mt5cli.trading.mt5_trading_session","text":"mt5_trading_session ( config : Mt5Config | None = None , * , login : int | str | None = None , password : str | None = None , server : str | None = None , path : str | None = None , timeout : int | None = None , retry_count : int = 0 , ) -> Iterator [ Mt5TradingClient ] Open a trading-capable MT5 session and always shut down safely. Launches the MetaTrader 5 terminal using Mt5Config.path when set, initializes and logs in via initialize_and_login_mt5() , yields a connected :class: ~pdmt5.Mt5TradingClient , and calls shutdown() on exit even when an error is raised inside the context. Parameters: Name Type Description Default config Mt5Config | None MT5 connection configuration. Defaults to an empty config that attaches to a running terminal. None login int | str | None Optional trading account login. None password str | None Optional trading account password. None server str | None Optional trading server name. None path str | None Optional terminal executable path. None timeout int | None Optional connection timeout in milliseconds. None retry_count int Number of initialization retries passed to Mt5TradingClient . 0 Yields: Type Description Mt5TradingClient Connected Mt5TradingClient bound to the session. Source code in mt5cli/trading.py 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 @contextmanager def mt5_trading_session ( config : Mt5Config | None = None , * , login : int | str | None = None , password : str | None = None , server : str | None = None , path : str | None = None , timeout : int | None = None , retry_count : int = 0 , ) -> Iterator [ Mt5TradingClient ]: \"\"\"Open a trading-capable MT5 session and always shut down safely. Launches the MetaTrader 5 terminal using ``Mt5Config.path`` when set, initializes and logs in via ``initialize_and_login_mt5()``, yields a connected :class:`~pdmt5.Mt5TradingClient`, and calls ``shutdown()`` on exit even when an error is raised inside the context. Args: config: MT5 connection configuration. Defaults to an empty config that attaches to a running terminal. login: Optional trading account login. password: Optional trading account password. server: Optional trading server name. path: Optional terminal executable path. timeout: Optional connection timeout in milliseconds. retry_count: Number of initialization retries passed to ``Mt5TradingClient``. Yields: Connected ``Mt5TradingClient`` bound to the session. \"\"\" client = create_trading_client ( config = config , login = login , password = password , server = server , path = path , timeout = timeout , retry_count = retry_count , ) try : yield client finally : client . shutdown ()","title":"mt5_trading_session"},{"location":"api/trading/#mt5cli.trading.normalize_order_volume","text":"normalize_order_volume ( volume : float , * , volume_min : float , volume_max : float , volume_step : float , ) -> float Normalize a requested order volume to broker volume constraints. Returns: Type Description float Volume floored to the nearest valid broker step from volume_min , float capped at volume_max when finite and positive, and rounded float deterministically. Returns 0.0 when inputs or constraints are float invalid, non-finite, or the capped request is below volume_min . Source code in mt5cli/trading.py 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 def normalize_order_volume ( volume : float , * , volume_min : float , volume_max : float , volume_step : float , ) -> float : \"\"\"Normalize a requested order volume to broker volume constraints. Returns: Volume floored to the nearest valid broker step from ``volume_min``, capped at ``volume_max`` when finite and positive, and rounded deterministically. Returns ``0.0`` when inputs or constraints are invalid, non-finite, or the capped request is below ``volume_min``. \"\"\" if not _is_finite_number ( volume ): return 0.0 if not _is_positive_finite_number ( volume_min ): return 0.0 if not _is_positive_finite_number ( volume_step ): return 0.0 has_volume_cap = _is_positive_finite_number ( volume_max ) capped = min ( volume , volume_max ) if has_volume_cap else volume if capped < volume_min : return 0.0 steps = floor ((( capped - volume_min ) / volume_step ) + 1e-12 ) normalized = volume_min + max ( 0 , steps ) * volume_step if has_volume_cap : normalized = min ( normalized , volume_max ) return round ( normalized , 10 )","title":"normalize_order_volume"},{"location":"api/trading/#mt5cli.trading.place_market_order","text":"place_market_order ( client : Mt5TradingClient , * , symbol : str , volume : float , order_side : OrderSide , order_filling_mode : OrderFillingMode = \"IOC\" , order_time_mode : OrderTimeMode = \"GTC\" , sl : float | None = None , tp : float | None = None , position : int | None = None , dry_run : bool = False , ) -> OrderExecutionResult Place one normalized market order or return a dry-run result. pdmt5.Mt5TradingClient.order_send() raises only when MT5 returns no response. When MT5 returns a response with a known non-success retcode, this helper returns status=\"failed\" and keeps the normalized response details for callers to inspect. Returns: Type Description OrderExecutionResult Normalized execution result containing request and response details. Raises: Type Description Mt5TradingError If volume or required tick data is invalid. Source code in mt5cli/trading.py 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 def place_market_order ( client : Mt5TradingClient , * , symbol : str , volume : float , order_side : OrderSide , order_filling_mode : OrderFillingMode = \"IOC\" , order_time_mode : OrderTimeMode = \"GTC\" , sl : float | None = None , tp : float | None = None , position : int | None = None , dry_run : bool = False , ) -> OrderExecutionResult : \"\"\"Place one normalized market order or return a dry-run result. ``pdmt5.Mt5TradingClient.order_send()`` raises only when MT5 returns no response. When MT5 returns a response with a known non-success retcode, this helper returns ``status=\"failed\"`` and keeps the normalized response details for callers to inspect. Returns: Normalized execution result containing request and response details. Raises: Mt5TradingError: If volume or required tick data is invalid. \"\"\" if volume <= 0 : msg = \"volume must be positive.\" raise Mt5TradingError ( msg ) side = _normalize_order_side ( order_side ) if not dry_run : ensure_symbol_selected ( client , symbol ) tick = get_tick_snapshot ( client , symbol ) price = extract_tick_price ( tick , \"ask\" if side == \"BUY\" else \"bid\" ) if price is None : msg = f \"Tick price is unavailable for { symbol !r} .\" raise Mt5TradingError ( msg ) request = { \"action\" : client . mt5 . TRADE_ACTION_DEAL , \"symbol\" : symbol , \"volume\" : volume , \"type\" : ( client . mt5 . ORDER_TYPE_BUY if side == \"BUY\" else client . mt5 . ORDER_TYPE_SELL ), \"price\" : price , \"type_filling\" : _resolve_mt5_constant ( client . mt5 , \"ORDER_FILLING\" , order_filling_mode , _ORDER_FILLING_MODES , ), \"type_time\" : _resolve_mt5_constant ( client . mt5 , \"ORDER_TIME\" , order_time_mode , _ORDER_TIME_MODES , ), } if sl is not None : request [ \"sl\" ] = sl if tp is not None : request [ \"tp\" ] = tp if position is not None : request [ \"position\" ] = position if dry_run : return { \"status\" : \"dry_run\" , \"symbol\" : symbol , \"order_side\" : side , \"volume\" : volume , \"retcode\" : None , \"comment\" : None , \"request\" : cast ( \"dict[str, object]\" , request ), \"response\" : None , \"dry_run\" : True , } response = client . order_send ( request ) response_dict = _snapshot_from_value ( response , ()) raw_retcode = response_dict . get ( \"retcode\" ) retcode = _optional_int ( raw_retcode ) return { \"status\" : _order_status_from_retcode ( client . mt5 , raw_retcode ), \"symbol\" : symbol , \"order_side\" : side , \"volume\" : volume , \"retcode\" : retcode , \"comment\" : _optional_str ( response_dict . get ( \"comment\" )), \"request\" : cast ( \"dict[str, object]\" , request ), \"response\" : response_dict , \"dry_run\" : False , }","title":"place_market_order"},{"location":"api/trading/#mt5cli.trading.update_sltp_for_open_positions","text":"update_sltp_for_open_positions ( client : Mt5TradingClient , * , symbol : str | None = None , tickets : list [ int ] | None = None , stop_loss : float | None = None , take_profit : float | None = None , dry_run : bool = False , ) -> list [ OrderExecutionResult ] Update SL/TP for matching open positions. Returns: Type Description list [ OrderExecutionResult ] Normalized execution results for matching positions. Source code in mt5cli/trading.py 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 def update_sltp_for_open_positions ( client : Mt5TradingClient , * , symbol : str | None = None , tickets : list [ int ] | None = None , stop_loss : float | None = None , take_profit : float | None = None , dry_run : bool = False , ) -> list [ OrderExecutionResult ]: \"\"\"Update SL/TP for matching open positions. Returns: Normalized execution results for matching positions. \"\"\" positions = _filter_positions ( get_positions_frame ( client ), symbols = symbol , tickets = tickets , ) results : list [ OrderExecutionResult ] = [] for row in positions . to_dict ( \"records\" ): request = { \"action\" : client . mt5 . TRADE_ACTION_SLTP , \"symbol\" : row [ \"symbol\" ], \"position\" : row [ \"ticket\" ], } sl = _optional_price ( row . get ( \"sl\" ) if stop_loss is None else stop_loss ) tp = _optional_price ( row . get ( \"tp\" ) if take_profit is None else take_profit ) if sl is not None : request [ \"sl\" ] = sl if tp is not None : request [ \"tp\" ] = tp if dry_run : response = None status : ExecutionStatus = \"dry_run\" else : ensure_symbol_selected ( client , str ( row [ \"symbol\" ])) response = _snapshot_from_value ( client . order_send ( request ), ()) status = _order_status_from_retcode ( client . mt5 , response . get ( \"retcode\" ), ) results . append ( { \"status\" : status , \"symbol\" : str ( row [ \"symbol\" ]), \"order_side\" : \"BUY\" if row [ \"type\" ] == client . mt5 . POSITION_TYPE_BUY else \"SELL\" , \"volume\" : float ( row [ \"volume\" ]), \"retcode\" : None if response is None else _optional_int ( response . get ( \"retcode\" )), \"comment\" : None if response is None else _optional_str ( response . get ( \"comment\" )), \"request\" : cast ( \"dict[str, object]\" , request ), \"response\" : response , \"dry_run\" : dry_run , }, ) return results","title":"update_sltp_for_open_positions"},{"location":"api/trading/#mt5cli.trading.update_trailing_stop_loss_for_open_positions","text":"update_trailing_stop_loss_for_open_positions ( client : Mt5TradingClient , * , symbol : str , trailing_stop_ratio : float , dry_run : bool = False , ) -> list [ OrderExecutionResult ] Update open positions whose trailing stop loss should move favorably. Returns: Type Description list [ OrderExecutionResult ] Normalized execution results for positions that need an SL update. Source code in mt5cli/trading.py 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 def update_trailing_stop_loss_for_open_positions ( client : Mt5TradingClient , * , symbol : str , trailing_stop_ratio : float , dry_run : bool = False , ) -> list [ OrderExecutionResult ]: \"\"\"Update open positions whose trailing stop loss should move favorably. Returns: Normalized execution results for positions that need an SL update. \"\"\" updates = calculate_trailing_stop_updates ( client , symbol = symbol , trailing_stop_ratio = trailing_stop_ratio , ) results : list [ OrderExecutionResult ] = [] for ticket , stop_loss in updates . items (): results . extend ( update_sltp_for_open_positions ( client , symbol = symbol , tickets = [ ticket ], stop_loss = stop_loss , dry_run = dry_run , ), ) return results","title":"update_trailing_stop_loss_for_open_positions"},{"location":"api/trading/#trading-capable-mt5-sessions","text":"create_trading_client() and mt5_trading_session() complement the read-only mt5_session() helper in sdk.py . They return or yield an initialized pdmt5.Mt5TradingClient , use Mt5Config.path to launch the terminal when configured, and mt5_trading_session() always calls shutdown() on exit. from mt5cli import create_trading_client , mt5_trading_session with mt5_trading_session ( path = r \"C:\\Program Files\\MetaTrader 5\\terminal64.exe\" , login = \"12345\" , password = \"secret\" , server = \"Broker-Demo\" , retry_count = 2 , ) as client : positions = client . positions_get_as_df ( symbol = \"EURUSD\" ) client = create_trading_client ( login = 12345 , server = \"Broker-Demo\" ) try : account = client . account_info_as_dict () finally : client . shutdown () login accepts int , numeric str , or an empty string; empty strings are treated as unset. path , password , server , and timeout are forwarded to pdmt5.Mt5Config , and omitted timeout values keep the lower-level default. Use mt5_session() / MT5Client for read-only data collection.","title":"Trading-capable MT5 sessions"},{"location":"api/trading/#state-and-order-helpers","text":"These helpers are strategy-agnostic and do not depend on signal detection, betting logic, or scheduling code in downstream applications. from mt5cli import ( calculate_positions_margin , calculate_spread_ratio , calculate_margin_and_volume , close_open_positions , detect_position_side , determine_order_limits , estimate_order_margin , fetch_latest_closed_rates_for_trading_client , fetch_latest_closed_rates_indexed , get_account_snapshot , get_positions_frame , get_symbol_snapshot , get_tick_snapshot , normalize_order_volume , place_market_order , ) account = get_account_snapshot ( client ) symbol = get_symbol_snapshot ( client , \"EURUSD\" ) tick = get_tick_snapshot ( client , \"EURUSD\" ) positions = get_positions_frame ( client , \"EURUSD\" ) side = detect_position_side ( client , \"EURUSD\" ) spread_ratio = calculate_spread_ratio ( client , \"EURUSD\" ) volume = normalize_order_volume ( 0.15 , volume_min = symbol [ \"volume_min\" ], volume_max = symbol [ \"volume_max\" ], volume_step = symbol [ \"volume_step\" ], ) buy_margin = ( estimate_order_margin ( client , \"EURUSD\" , \"BUY\" , volume ) if volume > 0 else 0.0 ) open_margin = calculate_positions_margin ( client , symbols = [ \"EURUSD\" ]) closed_bars = fetch_latest_closed_rates_for_trading_client ( client , symbol = \"EURUSD\" , granularity = \"M1\" , count = 100 , ) # Or fetch with a UTC DatetimeIndex instead of a \"time\" column: indexed_bars = fetch_latest_closed_rates_indexed ( client , symbol = \"EURUSD\" , granularity = \"M1\" , count = 100 , ) # indexed_bars.index is a UTC-aware DatetimeIndex named \"time\" 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 , ) preview = place_market_order ( client , symbol = \"EURUSD\" , volume = sizing [ \"buy_volume\" ], order_side = \"BUY\" , sl = limits [ \"stop_loss\" ], tp = limits [ \"take_profit\" ], dry_run = True , ) closed = close_open_positions ( client , symbols = \"EURUSD\" , dry_run = True ) detect_position_side() returns long for buy-only exposure, short for sell-only exposure, and None for no positions or mixed long/short exposure. calculate_spread_ratio() uses (ask - bid) / ((ask + bid) / 2) and raises Mt5TradingError when bid or ask is missing or non-positive. normalize_order_volume() returns 0.0 for invalid constraints or sub-minimum requests; check the result before calling estimate_order_margin() , which requires a positive finite volume. calculate_positions_margin() silently skips rows with missing symbols, non-positive volumes, non-finite volumes, or unsupported position types, but propagates Mt5TradingError from estimate_order_margin() when a valid row encounters invalid tick data or margin results from the broker. SL/TP ratios for determine_order_limits() must satisfy 0 <= ratio < 1 ; 0 omits that level. SL/TP prices are rounded with symbol digits metadata when available. determine_order_limits() pre-validates computed SL/TP prices against available trade_stops_level * point metadata when present; violations raise Mt5TradingError . This is a planning helper only: it does not guarantee broker acceptance because live validation can still depend on price movement, bid/ask side, freeze levels, and server-side rules, and it does not validate trade_freeze_level . When symbol metadata cannot be loaded, protective prices still round with digits=8 and stop-level validation is skipped. unit_margin_ratio and preserved_margin_ratio for calculate_margin_and_volume() accept 0 <= ratio <= 1 ; unit_margin_ratio=0 requests one minimum valid unit when the post-reserve margin can afford it. Negative margin_free is clamped to 0.0 before sizing. Execution helpers return normalized OrderExecutionResult dictionaries containing the request, response, status, retcode, and dry_run flag; dry_run=True never sends an order or mutates Market Watch visibility. ensure_symbol_selected() adds hidden symbols to Market Watch before live order placement and SL/TP updates. Failed, malformed, or unknown broker retcodes are fail-closed and returned as status=\"failed\" while keeping the normalized response for inspection.","title":"State and order helpers"},{"location":"api/trading/#order-planning-return-contracts","text":"from mt5cli import MarginVolume , OrderLimits , OrderExecutionResult sizing : MarginVolume = calculate_margin_and_volume ( client , \"EURUSD\" , unit_margin_ratio = 0.5 , preserved_margin_ratio = 0.2 , ) limits : OrderLimits = determine_order_limits ( client , \"EURUSD\" , side = \"long\" , stop_loss_limit_ratio = 0.01 , take_profit_limit_ratio = 0.02 , ) preview : OrderExecutionResult = place_market_order ( client , symbol = \"EURUSD\" , volume = sizing [ \"buy_volume\" ], order_side = \"BUY\" , sl = limits [ \"stop_loss\" ], tp = limits [ \"take_profit\" ], dry_run = True , ) updates : list [ OrderExecutionResult ] = update_sltp_for_open_positions ( client , symbol = \"EURUSD\" , stop_loss = limits [ \"stop_loss\" ], dry_run = True , ) Closes issue #33: strategy-neutral order planning and execution helpers exposed through the stable package root without embedding entry/exit policy.","title":"Order planning return contracts"},{"location":"api/trading/#migration-from-application-local-helpers","text":"Application-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 broker volume step normalization normalize_order_volume() Local order or position margin estimation estimate_order_margin() , calculate_positions_margin() Local closed-bar fetch from a trading session fetch_latest_closed_rates_for_trading_client() , fetch_latest_closed_rates_indexed() 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() / MT5Client ; use mt5_trading_session() only where order placement or trading calculations are required.","title":"Migration from application-local helpers"},{"location":"api/utils/","text":"Utils Module \u00b6 mt5cli.utils \u00b6 Utility constants, types, and functions for the mt5cli package. DATETIME_TYPE module-attribute \u00b6 DATETIME_TYPE = _DateTimeType () REQUEST_TYPE module-attribute \u00b6 REQUEST_TYPE = _RequestType () TICK_FLAGS_TYPE module-attribute \u00b6 TICK_FLAGS_TYPE = _TickFlagsType () TICK_FLAG_MAP module-attribute \u00b6 TICK_FLAG_MAP : dict [ str , int ] = dict ( COPY_TICKS_MAP ) TIMEFRAME_NAMES module-attribute \u00b6 TIMEFRAME_NAMES : tuple [ str , ... ] = tuple ( name for name in TIMEFRAME_MAP if not startswith ( \"TIMEFRAME_\" ) ) TIMEFRAME_TYPE module-attribute \u00b6 TIMEFRAME_TYPE = _TimeframeType () Dataset \u00b6 Bases: StrEnum Datasets supported by the collect-history command. history_deals class-attribute instance-attribute \u00b6 history_deals = 'history-deals' history_orders class-attribute instance-attribute \u00b6 history_orders = 'history-orders' rates class-attribute instance-attribute \u00b6 rates = 'rates' table_name property \u00b6 table_name : str Return the SQLite table name for this dataset. ticks class-attribute instance-attribute \u00b6 ticks = 'ticks' IfExists \u00b6 Bases: StrEnum SQLite table conflict behavior for the collect-history command. APPEND class-attribute instance-attribute \u00b6 APPEND = 'append' FAIL class-attribute instance-attribute \u00b6 FAIL = 'fail' REPLACE class-attribute instance-attribute \u00b6 REPLACE = 'replace' LogLevel \u00b6 Bases: StrEnum Logging verbosity levels. DEBUG class-attribute instance-attribute \u00b6 DEBUG = 'DEBUG' ERROR class-attribute instance-attribute \u00b6 ERROR = 'ERROR' INFO class-attribute instance-attribute \u00b6 INFO = 'INFO' WARNING class-attribute instance-attribute \u00b6 WARNING = 'WARNING' OutputFormat \u00b6 Bases: StrEnum Supported output file formats. csv class-attribute instance-attribute \u00b6 csv = 'csv' json class-attribute instance-attribute \u00b6 json = 'json' parquet class-attribute instance-attribute \u00b6 parquet = 'parquet' sqlite3 class-attribute instance-attribute \u00b6 sqlite3 = 'sqlite3' coerce_login \u00b6 coerce_login ( login : int | str | None ) -> int | None Coerce a login value to int, treating empty strings as unset. Returns: Type Description int | None Integer login, or None when unset or an empty string. Source code in mt5cli/utils.py 244 245 246 247 248 249 250 251 252 253 254 255 def coerce_login ( login : int | str | None ) -> int | None : \"\"\"Coerce a login value to int, treating empty strings as unset. Returns: Integer login, or None when unset or an empty string. \"\"\" if login is None or isinstance ( login , int ): return login text = login . strip () if not text : return None return int ( text ) detect_format \u00b6 detect_format ( output_path : Path , explicit_format : str | None = None ) -> str Detect the output format from a file extension or explicit format string. Parameters: Name Type Description Default output_path Path Path to the output file. required explicit_format str | None Explicitly specified format, if any. None Returns: Type Description str The detected format string. Raises: Type Description ValueError If the format cannot be determined. Source code in mt5cli/utils.py 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 def detect_format ( output_path : Path , explicit_format : str | None = None , ) -> str : \"\"\"Detect the output format from a file extension or explicit format string. Args: output_path: Path to the output file. explicit_format: Explicitly specified format, if any. Returns: The detected format string. Raises: ValueError: If the format cannot be determined. \"\"\" if explicit_format is not None : return explicit_format suffix = output_path . suffix . lower () if suffix in _FORMAT_EXTENSIONS : return _FORMAT_EXTENSIONS [ suffix ] msg = ( f \"Cannot detect format from extension ' { suffix } '.\" \" Use --format to specify the output format.\" ) raise ValueError ( msg ) export_dataframe \u00b6 export_dataframe ( df : DataFrame , output_path : Path , output_format : str , table_name : str = \"data\" , ) -> None Export a pandas DataFrame to the specified file format. Parameters: Name Type Description Default df DataFrame DataFrame to export. required output_path Path Path to the output file. required output_format str Output format (csv, json, parquet, or sqlite3). required table_name str Table name for SQLite3 output. 'data' Raises: Type Description ValueError If the output format is not supported. Source code in mt5cli/utils.py 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 def export_dataframe ( df : pd . DataFrame , output_path : Path , output_format : str , table_name : str = \"data\" , ) -> None : \"\"\"Export a pandas DataFrame to the specified file format. Args: df: DataFrame to export. output_path: Path to the output file. output_format: Output format (csv, json, parquet, or sqlite3). table_name: Table name for SQLite3 output. Raises: ValueError: If the output format is not supported. \"\"\" if output_format == \"csv\" : df . to_csv ( output_path , index = False ) elif output_format == \"json\" : df . to_json ( output_path , orient = \"records\" , date_format = \"iso\" , indent = 2 , ) elif output_format == \"parquet\" : df . to_parquet ( output_path , index = False ) elif output_format == \"sqlite3\" : export_dataframe_to_sqlite ( df , output_path , table_name , if_exists = IfExists . REPLACE , index = False , ) else : msg = f \"Unsupported output format: { output_format } \" raise ValueError ( msg ) export_dataframe_to_sqlite \u00b6 export_dataframe_to_sqlite ( df : DataFrame , output_path : Path , table_name : str = \"data\" , * , if_exists : IfExists = APPEND , index : bool = False , index_label : str | None = None , deduplicate_on : Sequence [ str ] | None = None , ) -> None Write a DataFrame to SQLite with configurable append and deduplication. Parameters: Name Type Description Default df DataFrame DataFrame to export. required output_path Path SQLite database path. required table_name str Target table name. 'data' if_exists IfExists Conflict behavior when the table already exists. APPEND index bool Whether to write the DataFrame index as a column. False index_label str | None Column name for the index when index=True . None deduplicate_on Sequence [ str ] | None Optional key columns to deduplicate after writing, keeping the latest ROWID per key group. Deduplication scans the full table, so repeated appends cost O(table size); index the key columns when appending frequently. None Source code in mt5cli/utils.py 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 def export_dataframe_to_sqlite ( df : pd . DataFrame , output_path : Path , table_name : str = \"data\" , * , if_exists : IfExists = IfExists . APPEND , index : bool = False , index_label : str | None = None , deduplicate_on : Sequence [ str ] | None = None , ) -> None : \"\"\"Write a DataFrame to SQLite with configurable append and deduplication. Args: df: DataFrame to export. output_path: SQLite database path. table_name: Target table name. if_exists: Conflict behavior when the table already exists. index: Whether to write the DataFrame index as a column. index_label: Column name for the index when ``index=True``. deduplicate_on: Optional key columns to deduplicate after writing, keeping the latest ``ROWID`` per key group. Deduplication scans the full table, so repeated appends cost O(table size); index the key columns when appending frequently. \"\"\" with sqlite3 . connect ( output_path ) as conn : df . to_sql ( # type: ignore[reportUnknownMemberType] table_name , conn , if_exists = if_exists . value , index = index , index_label = index_label , ) if deduplicate_on : from .history import drop_duplicates_in_table # noqa: PLC0415 drop_duplicates_in_table ( conn . cursor (), table_name , list ( deduplicate_on ), keep = \"last\" , ) conn . commit () parse_datetime \u00b6 parse_datetime ( value : str ) -> datetime Parse an ISO 8601 datetime string to a timezone-aware datetime. Parameters: Name Type Description Default value str ISO 8601 datetime string (e.g., '2024-01-01' or '2024-01-01T12:00:00+00:00'). required Returns: Type Description datetime Parsed datetime with UTC timezone if no timezone is specified. Raises: Type Description ValueError If the string cannot be parsed. Source code in mt5cli/utils.py 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 def parse_datetime ( value : str ) -> datetime : \"\"\"Parse an ISO 8601 datetime string to a timezone-aware datetime. Args: value: ISO 8601 datetime string (e.g., '2024-01-01' or '2024-01-01T12:00:00+00:00'). Returns: Parsed datetime with UTC timezone if no timezone is specified. Raises: ValueError: If the string cannot be parsed. \"\"\" try : dt = datetime . fromisoformat ( value ) except ValueError : msg = f \"Invalid datetime format: ' { value } '. Use ISO 8601 format.\" raise ValueError ( msg ) from None if dt . tzinfo is None : dt = dt . replace ( tzinfo = UTC ) return dt parse_request \u00b6 parse_request ( value : str ) -> dict [ str , Any ] Parse a JSON-formatted order request string or file reference. Parameters: Name Type Description Default value str JSON object string, or '@path' to read JSON from a file. required Returns: Type Description dict [ str , Any ] Parsed request dictionary. Raises: Type Description ValueError If the request file cannot be read or the value is not a JSON object. Source code in mt5cli/utils.py 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 def parse_request ( value : str ) -> dict [ str , Any ]: \"\"\"Parse a JSON-formatted order request string or file reference. Args: value: JSON object string, or '@path' to read JSON from a file. Returns: Parsed request dictionary. Raises: ValueError: If the request file cannot be read or the value is not a JSON object. \"\"\" if value . startswith ( \"@\" ): path = Path ( value [ 1 :]) try : text = path . read_text ( encoding = \"utf-8\" ) except ( OSError , UnicodeDecodeError ) as exc : msg = f \"Failed to read JSON request file ' { path } ': { exc } \" raise ValueError ( msg ) from exc else : text = value try : parsed : object = json . loads ( text ) except json . JSONDecodeError as exc : msg = f \"Invalid JSON request: { exc } \" raise ValueError ( msg ) from exc if not _is_request_dict ( parsed ): msg = \"Order request must be a JSON object.\" raise ValueError ( msg ) return parsed parse_tick_flags \u00b6 parse_tick_flags ( value : object ) -> int Parse tick flags string or integer value. Parameters: Name Type Description Default value object Tick flag name (ALL, INFO, TRADE, COPY_TICKS_*) or integer value. required Returns: Type Description int Integer tick flag value compatible with MetaTrader 5 COPY_TICKS_* . Raises: Type Description ValueError If the flag is invalid. Source code in mt5cli/utils.py 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 def parse_tick_flags ( value : object ) -> int : \"\"\"Parse tick flags string or integer value. Args: value: Tick flag name (ALL, INFO, TRADE, COPY_TICKS_*) or integer value. Returns: Integer tick flag value compatible with MetaTrader 5 ``COPY_TICKS_*``. Raises: ValueError: If the flag is invalid. \"\"\" try : return _parse_copy_ticks ( value ) except ValueError : display = value if isinstance ( value , str ) else repr ( value ) valid = \", \" . join ( _TICK_FLAG_NAMES ) msg = ( f \"Invalid tick flags: ' { display } '. \" f \"Use one of: { valid } , or a supported integer.\" ) raise ValueError ( msg ) from None parse_timeframe \u00b6 parse_timeframe ( value : object ) -> int Parse a timeframe string or integer value. Parameters: Name Type Description Default value object Timeframe name (e.g., 'M1', 'H1', 'D1') or integer value. required Returns: Type Description int Integer timeframe value. Raises: Type Description ValueError If the timeframe is invalid. Source code in mt5cli/utils.py 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 def parse_timeframe ( value : object ) -> int : \"\"\"Parse a timeframe string or integer value. Args: value: Timeframe name (e.g., 'M1', 'H1', 'D1') or integer value. Returns: Integer timeframe value. Raises: ValueError: If the timeframe is invalid. \"\"\" try : return _parse_timeframe ( value ) except ValueError : display = value if isinstance ( value , str ) else repr ( value ) valid = \", \" . join ( TIMEFRAME_NAMES ) msg = ( f \"Invalid timeframe: ' { display } '. \" f \"Use one of: { valid } , or a supported integer.\" ) raise ValueError ( msg ) from None","title":"Utils"},{"location":"api/utils/#utils-module","text":"","title":"Utils Module"},{"location":"api/utils/#mt5cli.utils","text":"Utility constants, types, and functions for the mt5cli package.","title":"utils"},{"location":"api/utils/#mt5cli.utils.DATETIME_TYPE","text":"DATETIME_TYPE = _DateTimeType ()","title":"DATETIME_TYPE"},{"location":"api/utils/#mt5cli.utils.REQUEST_TYPE","text":"REQUEST_TYPE = _RequestType ()","title":"REQUEST_TYPE"},{"location":"api/utils/#mt5cli.utils.TICK_FLAGS_TYPE","text":"TICK_FLAGS_TYPE = _TickFlagsType ()","title":"TICK_FLAGS_TYPE"},{"location":"api/utils/#mt5cli.utils.TICK_FLAG_MAP","text":"TICK_FLAG_MAP : dict [ str , int ] = dict ( COPY_TICKS_MAP )","title":"TICK_FLAG_MAP"},{"location":"api/utils/#mt5cli.utils.TIMEFRAME_NAMES","text":"TIMEFRAME_NAMES : tuple [ str , ... ] = tuple ( name for name in TIMEFRAME_MAP if not startswith ( \"TIMEFRAME_\" ) )","title":"TIMEFRAME_NAMES"},{"location":"api/utils/#mt5cli.utils.TIMEFRAME_TYPE","text":"TIMEFRAME_TYPE = _TimeframeType ()","title":"TIMEFRAME_TYPE"},{"location":"api/utils/#mt5cli.utils.Dataset","text":"Bases: StrEnum Datasets supported by the collect-history command.","title":"Dataset"},{"location":"api/utils/#mt5cli.utils.Dataset.history_deals","text":"history_deals = 'history-deals'","title":"history_deals"},{"location":"api/utils/#mt5cli.utils.Dataset.history_orders","text":"history_orders = 'history-orders'","title":"history_orders"},{"location":"api/utils/#mt5cli.utils.Dataset.rates","text":"rates = 'rates'","title":"rates"},{"location":"api/utils/#mt5cli.utils.Dataset.table_name","text":"table_name : str Return the SQLite table name for this dataset.","title":"table_name"},{"location":"api/utils/#mt5cli.utils.Dataset.ticks","text":"ticks = 'ticks'","title":"ticks"},{"location":"api/utils/#mt5cli.utils.IfExists","text":"Bases: StrEnum SQLite table conflict behavior for the collect-history command.","title":"IfExists"},{"location":"api/utils/#mt5cli.utils.IfExists.APPEND","text":"APPEND = 'append'","title":"APPEND"},{"location":"api/utils/#mt5cli.utils.IfExists.FAIL","text":"FAIL = 'fail'","title":"FAIL"},{"location":"api/utils/#mt5cli.utils.IfExists.REPLACE","text":"REPLACE = 'replace'","title":"REPLACE"},{"location":"api/utils/#mt5cli.utils.LogLevel","text":"Bases: StrEnum Logging verbosity levels.","title":"LogLevel"},{"location":"api/utils/#mt5cli.utils.LogLevel.DEBUG","text":"DEBUG = 'DEBUG'","title":"DEBUG"},{"location":"api/utils/#mt5cli.utils.LogLevel.ERROR","text":"ERROR = 'ERROR'","title":"ERROR"},{"location":"api/utils/#mt5cli.utils.LogLevel.INFO","text":"INFO = 'INFO'","title":"INFO"},{"location":"api/utils/#mt5cli.utils.LogLevel.WARNING","text":"WARNING = 'WARNING'","title":"WARNING"},{"location":"api/utils/#mt5cli.utils.OutputFormat","text":"Bases: StrEnum Supported output file formats.","title":"OutputFormat"},{"location":"api/utils/#mt5cli.utils.OutputFormat.csv","text":"csv = 'csv'","title":"csv"},{"location":"api/utils/#mt5cli.utils.OutputFormat.json","text":"json = 'json'","title":"json"},{"location":"api/utils/#mt5cli.utils.OutputFormat.parquet","text":"parquet = 'parquet'","title":"parquet"},{"location":"api/utils/#mt5cli.utils.OutputFormat.sqlite3","text":"sqlite3 = 'sqlite3'","title":"sqlite3"},{"location":"api/utils/#mt5cli.utils.coerce_login","text":"coerce_login ( login : int | str | None ) -> int | None Coerce a login value to int, treating empty strings as unset. Returns: Type Description int | None Integer login, or None when unset or an empty string. Source code in mt5cli/utils.py 244 245 246 247 248 249 250 251 252 253 254 255 def coerce_login ( login : int | str | None ) -> int | None : \"\"\"Coerce a login value to int, treating empty strings as unset. Returns: Integer login, or None when unset or an empty string. \"\"\" if login is None or isinstance ( login , int ): return login text = login . strip () if not text : return None return int ( text )","title":"coerce_login"},{"location":"api/utils/#mt5cli.utils.detect_format","text":"detect_format ( output_path : Path , explicit_format : str | None = None ) -> str Detect the output format from a file extension or explicit format string. Parameters: Name Type Description Default output_path Path Path to the output file. required explicit_format str | None Explicitly specified format, if any. None Returns: Type Description str The detected format string. Raises: Type Description ValueError If the format cannot be determined. Source code in mt5cli/utils.py 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 def detect_format ( output_path : Path , explicit_format : str | None = None , ) -> str : \"\"\"Detect the output format from a file extension or explicit format string. Args: output_path: Path to the output file. explicit_format: Explicitly specified format, if any. Returns: The detected format string. Raises: ValueError: If the format cannot be determined. \"\"\" if explicit_format is not None : return explicit_format suffix = output_path . suffix . lower () if suffix in _FORMAT_EXTENSIONS : return _FORMAT_EXTENSIONS [ suffix ] msg = ( f \"Cannot detect format from extension ' { suffix } '.\" \" Use --format to specify the output format.\" ) raise ValueError ( msg )","title":"detect_format"},{"location":"api/utils/#mt5cli.utils.export_dataframe","text":"export_dataframe ( df : DataFrame , output_path : Path , output_format : str , table_name : str = \"data\" , ) -> None Export a pandas DataFrame to the specified file format. Parameters: Name Type Description Default df DataFrame DataFrame to export. required output_path Path Path to the output file. required output_format str Output format (csv, json, parquet, or sqlite3). required table_name str Table name for SQLite3 output. 'data' Raises: Type Description ValueError If the output format is not supported. Source code in mt5cli/utils.py 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 def export_dataframe ( df : pd . DataFrame , output_path : Path , output_format : str , table_name : str = \"data\" , ) -> None : \"\"\"Export a pandas DataFrame to the specified file format. Args: df: DataFrame to export. output_path: Path to the output file. output_format: Output format (csv, json, parquet, or sqlite3). table_name: Table name for SQLite3 output. Raises: ValueError: If the output format is not supported. \"\"\" if output_format == \"csv\" : df . to_csv ( output_path , index = False ) elif output_format == \"json\" : df . to_json ( output_path , orient = \"records\" , date_format = \"iso\" , indent = 2 , ) elif output_format == \"parquet\" : df . to_parquet ( output_path , index = False ) elif output_format == \"sqlite3\" : export_dataframe_to_sqlite ( df , output_path , table_name , if_exists = IfExists . REPLACE , index = False , ) else : msg = f \"Unsupported output format: { output_format } \" raise ValueError ( msg )","title":"export_dataframe"},{"location":"api/utils/#mt5cli.utils.export_dataframe_to_sqlite","text":"export_dataframe_to_sqlite ( df : DataFrame , output_path : Path , table_name : str = \"data\" , * , if_exists : IfExists = APPEND , index : bool = False , index_label : str | None = None , deduplicate_on : Sequence [ str ] | None = None , ) -> None Write a DataFrame to SQLite with configurable append and deduplication. Parameters: Name Type Description Default df DataFrame DataFrame to export. required output_path Path SQLite database path. required table_name str Target table name. 'data' if_exists IfExists Conflict behavior when the table already exists. APPEND index bool Whether to write the DataFrame index as a column. False index_label str | None Column name for the index when index=True . None deduplicate_on Sequence [ str ] | None Optional key columns to deduplicate after writing, keeping the latest ROWID per key group. Deduplication scans the full table, so repeated appends cost O(table size); index the key columns when appending frequently. None Source code in mt5cli/utils.py 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 def export_dataframe_to_sqlite ( df : pd . DataFrame , output_path : Path , table_name : str = \"data\" , * , if_exists : IfExists = IfExists . APPEND , index : bool = False , index_label : str | None = None , deduplicate_on : Sequence [ str ] | None = None , ) -> None : \"\"\"Write a DataFrame to SQLite with configurable append and deduplication. Args: df: DataFrame to export. output_path: SQLite database path. table_name: Target table name. if_exists: Conflict behavior when the table already exists. index: Whether to write the DataFrame index as a column. index_label: Column name for the index when ``index=True``. deduplicate_on: Optional key columns to deduplicate after writing, keeping the latest ``ROWID`` per key group. Deduplication scans the full table, so repeated appends cost O(table size); index the key columns when appending frequently. \"\"\" with sqlite3 . connect ( output_path ) as conn : df . to_sql ( # type: ignore[reportUnknownMemberType] table_name , conn , if_exists = if_exists . value , index = index , index_label = index_label , ) if deduplicate_on : from .history import drop_duplicates_in_table # noqa: PLC0415 drop_duplicates_in_table ( conn . cursor (), table_name , list ( deduplicate_on ), keep = \"last\" , ) conn . commit ()","title":"export_dataframe_to_sqlite"},{"location":"api/utils/#mt5cli.utils.parse_datetime","text":"parse_datetime ( value : str ) -> datetime Parse an ISO 8601 datetime string to a timezone-aware datetime. Parameters: Name Type Description Default value str ISO 8601 datetime string (e.g., '2024-01-01' or '2024-01-01T12:00:00+00:00'). required Returns: Type Description datetime Parsed datetime with UTC timezone if no timezone is specified. Raises: Type Description ValueError If the string cannot be parsed. Source code in mt5cli/utils.py 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 def parse_datetime ( value : str ) -> datetime : \"\"\"Parse an ISO 8601 datetime string to a timezone-aware datetime. Args: value: ISO 8601 datetime string (e.g., '2024-01-01' or '2024-01-01T12:00:00+00:00'). Returns: Parsed datetime with UTC timezone if no timezone is specified. Raises: ValueError: If the string cannot be parsed. \"\"\" try : dt = datetime . fromisoformat ( value ) except ValueError : msg = f \"Invalid datetime format: ' { value } '. Use ISO 8601 format.\" raise ValueError ( msg ) from None if dt . tzinfo is None : dt = dt . replace ( tzinfo = UTC ) return dt","title":"parse_datetime"},{"location":"api/utils/#mt5cli.utils.parse_request","text":"parse_request ( value : str ) -> dict [ str , Any ] Parse a JSON-formatted order request string or file reference. Parameters: Name Type Description Default value str JSON object string, or '@path' to read JSON from a file. required Returns: Type Description dict [ str , Any ] Parsed request dictionary. Raises: Type Description ValueError If the request file cannot be read or the value is not a JSON object. Source code in mt5cli/utils.py 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 def parse_request ( value : str ) -> dict [ str , Any ]: \"\"\"Parse a JSON-formatted order request string or file reference. Args: value: JSON object string, or '@path' to read JSON from a file. Returns: Parsed request dictionary. Raises: ValueError: If the request file cannot be read or the value is not a JSON object. \"\"\" if value . startswith ( \"@\" ): path = Path ( value [ 1 :]) try : text = path . read_text ( encoding = \"utf-8\" ) except ( OSError , UnicodeDecodeError ) as exc : msg = f \"Failed to read JSON request file ' { path } ': { exc } \" raise ValueError ( msg ) from exc else : text = value try : parsed : object = json . loads ( text ) except json . JSONDecodeError as exc : msg = f \"Invalid JSON request: { exc } \" raise ValueError ( msg ) from exc if not _is_request_dict ( parsed ): msg = \"Order request must be a JSON object.\" raise ValueError ( msg ) return parsed","title":"parse_request"},{"location":"api/utils/#mt5cli.utils.parse_tick_flags","text":"parse_tick_flags ( value : object ) -> int Parse tick flags string or integer value. Parameters: Name Type Description Default value object Tick flag name (ALL, INFO, TRADE, COPY_TICKS_*) or integer value. required Returns: Type Description int Integer tick flag value compatible with MetaTrader 5 COPY_TICKS_* . Raises: Type Description ValueError If the flag is invalid. Source code in mt5cli/utils.py 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 def parse_tick_flags ( value : object ) -> int : \"\"\"Parse tick flags string or integer value. Args: value: Tick flag name (ALL, INFO, TRADE, COPY_TICKS_*) or integer value. Returns: Integer tick flag value compatible with MetaTrader 5 ``COPY_TICKS_*``. Raises: ValueError: If the flag is invalid. \"\"\" try : return _parse_copy_ticks ( value ) except ValueError : display = value if isinstance ( value , str ) else repr ( value ) valid = \", \" . join ( _TICK_FLAG_NAMES ) msg = ( f \"Invalid tick flags: ' { display } '. \" f \"Use one of: { valid } , or a supported integer.\" ) raise ValueError ( msg ) from None","title":"parse_tick_flags"},{"location":"api/utils/#mt5cli.utils.parse_timeframe","text":"parse_timeframe ( value : object ) -> int Parse a timeframe string or integer value. Parameters: Name Type Description Default value object Timeframe name (e.g., 'M1', 'H1', 'D1') or integer value. required Returns: Type Description int Integer timeframe value. Raises: Type Description ValueError If the timeframe is invalid. Source code in mt5cli/utils.py 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 def parse_timeframe ( value : object ) -> int : \"\"\"Parse a timeframe string or integer value. Args: value: Timeframe name (e.g., 'M1', 'H1', 'D1') or integer value. Returns: Integer timeframe value. Raises: ValueError: If the timeframe is invalid. \"\"\" try : return _parse_timeframe ( value ) except ValueError : display = value if isinstance ( value , str ) else repr ( value ) valid = \", \" . join ( TIMEFRAME_NAMES ) msg = ( f \"Invalid timeframe: ' { display } '. \" f \"Use one of: { valid } , or a supported integer.\" ) raise ValueError ( msg ) from None","title":"parse_timeframe"}]} \ No newline at end of file