From 19df5ea4dcb7786686c0537ef1492e90db5037a1 Mon Sep 17 00:00:00 2001 From: dceoy Date: Mon, 8 Jun 2026 13:55:22 +0000 Subject: [PATCH] deploy: 5b44318d5579b64c6c81137b60af3e871fde2aa3 --- 404.html | 8 + api/cli/index.html | 3351 +++++++++----------------------------- api/index.html | 55 +- api/sdk/index.html | 2778 +++++++++++++++++++++++++++++++ api/utils/index.html | 1925 ++++++++++++++++++++++ index.html | 93 +- objects.inv | Bin 629 -> 1138 bytes search/search_index.json | 2 +- sitemap.xml | 14 +- sitemap.xml.gz | Bin 203 -> 214 bytes 10 files changed, 5641 insertions(+), 2585 deletions(-) create mode 100644 api/sdk/index.html create mode 100644 api/utils/index.html diff --git a/404.html b/404.html index cd0a8e9..bfcba32 100644 --- a/404.html +++ b/404.html @@ -49,6 +49,14 @@
  • CLI
  • + +
  • + SDK +
  • + +
  • + Utils +
  • diff --git a/api/cli/index.html b/api/cli/index.html index f241f22..6196da5 100644 --- a/api/cli/index.html +++ b/api/cli/index.html @@ -49,6 +49,14 @@
  • CLI
  • + +
  • + SDK +
  • + +
  • + Utils +
  • @@ -65,7 +73,7 @@ @@ -138,164 +146,6 @@ -
    - - - -

    - DATETIME_TYPE - - - - module-attribute - - -

    -
    DATETIME_TYPE = _DateTimeType()
    -
    - -
    - -
    - -
    - -
    - - - -

    - REQUEST_TYPE - - - - module-attribute - - -

    -
    REQUEST_TYPE = _RequestType()
    -
    - -
    - -
    - -
    - -
    - - - -

    - TICK_FLAGS_TYPE - - - - module-attribute - - -

    -
    TICK_FLAGS_TYPE = _TickFlagsType()
    -
    - -
    - -
    - -
    - -
    - - - -

    - TICK_FLAG_MAP - - - - module-attribute - - -

    -
    TICK_FLAG_MAP: dict[str, int] = {
    -    "ALL": 1,
    -    "INFO": 2,
    -    "TRADE": 4,
    -}
    -
    - -
    - -
    - -
    - -
    - - - -

    - TIMEFRAME_MAP - - - - module-attribute - - -

    -
    TIMEFRAME_MAP: dict[str, int] = {
    -    "M1": 1,
    -    "M2": 2,
    -    "M3": 3,
    -    "M4": 4,
    -    "M5": 5,
    -    "M6": 6,
    -    "M10": 10,
    -    "M12": 12,
    -    "M15": 15,
    -    "M20": 20,
    -    "M30": 30,
    -    "H1": 16385,
    -    "H2": 16386,
    -    "H3": 16387,
    -    "H4": 16388,
    -    "H6": 16390,
    -    "H8": 16392,
    -    "H12": 16396,
    -    "D1": 16408,
    -    "W1": 32769,
    -    "MN1": 49153,
    -}
    -
    - -
    - -
    - -
    - -
    - - - -

    - TIMEFRAME_TYPE - - - - module-attribute - - -

    -
    TIMEFRAME_TYPE = _TimeframeType()
    -
    - -
    - -
    - -
    -
    @@ -345,543 +195,6 @@ -
    - - - -

    - Dataset - - -

    - - -
    -

    - Bases: StrEnum

    - - - -

    Datasets supported by the collect-history command.

    - - - - - - - - - - - -
    - - - - - - - -
    - - - -

    - history_deals - - - - class-attribute - instance-attribute - - -

    -
    history_deals = 'history-deals'
    -
    - -
    - -
    - -
    - -
    - - - -

    - history_orders - - - - class-attribute - instance-attribute - - -

    -
    history_orders = 'history-orders'
    -
    - -
    - -
    - -
    - -
    - - - -

    - rates - - - - class-attribute - instance-attribute - - -

    -
    rates = 'rates'
    -
    - -
    - -
    - -
    - -
    - - - -

    - ticks - - - - class-attribute - instance-attribute - - -

    -
    ticks = 'ticks'
    -
    - -
    - -
    - -
    - - - - - - -
    - -
    - -
    - -
    - - - -

    - IfExists - - -

    - - -
    -

    - Bases: StrEnum

    - - - -

    SQLite table conflict behavior for the collect-history command.

    - - - - - - - - - - - -
    - - - - - - - -
    - - - -

    - APPEND - - - - class-attribute - instance-attribute - - -

    -
    APPEND = 'append'
    -
    - -
    - -
    - -
    - -
    - - - -

    - FAIL - - - - class-attribute - instance-attribute - - -

    -
    FAIL = 'fail'
    -
    - -
    - -
    - -
    - -
    - - - -

    - REPLACE - - - - class-attribute - instance-attribute - - -

    -
    REPLACE = 'replace'
    -
    - -
    - -
    - -
    - - - - - - -
    - -
    - -
    - -
    - - - -

    - LogLevel - - -

    - - -
    -

    - Bases: StrEnum

    - - - -

    Logging verbosity levels.

    - - - - - - - - - - - -
    - - - - - - - -
    - - - -

    - DEBUG - - - - class-attribute - instance-attribute - - -

    -
    DEBUG = 'DEBUG'
    -
    - -
    - -
    - -
    - -
    - - - -

    - ERROR - - - - class-attribute - instance-attribute - - -

    -
    ERROR = 'ERROR'
    -
    - -
    - -
    - -
    - -
    - - - -

    - INFO - - - - class-attribute - instance-attribute - - -

    -
    INFO = 'INFO'
    -
    - -
    - -
    - -
    - -
    - - - -

    - WARNING - - - - class-attribute - instance-attribute - - -

    -
    WARNING = 'WARNING'
    -
    - -
    - -
    - -
    - - - - - - -
    - -
    - -
    - -
    - - - -

    - OutputFormat - - -

    - - -
    -

    - Bases: StrEnum

    - - - -

    Supported output file formats.

    - - - - - - - - - - - -
    - - - - - - - -
    - - - -

    - csv - - - - class-attribute - instance-attribute - - -

    -
    csv = 'csv'
    -
    - -
    - -
    - -
    - -
    - - - -

    - json - - - - class-attribute - instance-attribute - - -

    -
    json = 'json'
    -
    - -
    - -
    - -
    - -
    - - - -

    - parquet - - - - class-attribute - instance-attribute - - -

    -
    parquet = 'parquet'
    -
    - -
    - -
    - -
    - -
    - - - -

    - sqlite3 - - - - class-attribute - instance-attribute - - -

    -
    sqlite3 = 'sqlite3'
    -
    - -
    - -
    - -
    - - - - - - -
    - -
    - -
    -
    @@ -901,13 +214,13 @@
    Source code in mt5cli/cli.py -
    @app.command()
    -def account_info(ctx: typer.Context) -> None:
    -    """Export account information."""
    -    _execute_export(ctx, lambda c: c.account_info_as_df())
    +              
    @app.command()
    +def account_info(ctx: typer.Context) -> None:
    +    """Export account information."""
    +    _execute_export(ctx, _sdk_client(ctx).account_info)
     
    @@ -940,7 +253,7 @@ module-attribute - (mt5cli.cli.DATETIME_TYPE)" href="#mt5cli.cli.DATETIME_TYPE">DATETIME_TYPE, help="Start date." + (mt5cli.utils.DATETIME_TYPE)" href="../utils/#mt5cli.utils.DATETIME_TYPE">DATETIME_TYPE, help="Start date." ), ], date_to: Annotated[ @@ -950,10 +263,10 @@ module-attribute - (mt5cli.cli.DATETIME_TYPE)" href="#mt5cli.cli.DATETIME_TYPE">DATETIME_TYPE, help="End date."), + (mt5cli.utils.DATETIME_TYPE)" href="../utils/#mt5cli.utils.DATETIME_TYPE">DATETIME_TYPE, help="End date."), ], dataset: Annotated[ - list[Dataset] | None, + list[Dataset] | None, Option( "--dataset", help="Dataset to include (repeat for multiple). Defaults to all: rates, ticks, history-orders, history-deals.", @@ -967,7 +280,7 @@ module-attribute - (mt5cli.cli.TIMEFRAME_TYPE)" href="#mt5cli.cli.TIMEFRAME_TYPE">TIMEFRAME_TYPE, + (mt5cli.utils.TIMEFRAME_TYPE)" href="../utils/#mt5cli.utils.TIMEFRAME_TYPE">TIMEFRAME_TYPE, help="Rates timeframe (e.g., M1, H1, D1).", ), ] = 1, @@ -979,12 +292,12 @@ module-attribute - (mt5cli.cli.TICK_FLAGS_TYPE)" href="#mt5cli.cli.TICK_FLAGS_TYPE">TICK_FLAGS_TYPE, + (mt5cli.utils.TICK_FLAGS_TYPE)" href="../utils/#mt5cli.utils.TICK_FLAGS_TYPE">TICK_FLAGS_TYPE, help="Tick copy flags (ALL, INFO, TRADE, or integer).", ), ] = 1, if_exists: Annotated[ - IfExists, + IfExists, Option( "--if-exists", help="Behavior when a target table already exists.", @@ -995,7 +308,7 @@ class-attribute instance-attribute - (mt5cli.cli.IfExists.FAIL)" href="#mt5cli.cli.IfExists.FAIL">FAIL, + (mt5cli.utils.IfExists.FAIL)" href="../utils/#mt5cli.utils.IfExists.FAIL">FAIL, with_views: Annotated[ bool, Option( @@ -1043,621 +356,195 @@ views cash_events and positions_reconstructed are deri
    Source code in mt5cli/cli.py -
    @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).",
    -        ),
    -    ] = 1,
    -    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)
    -    client = Mt5DataClient(config=export_ctx.config)
    -    client.initialize_and_login_mt5()
    -    try:
    -        with sqlite3.connect(export_ctx.output) as conn:
    -            conn.execute("PRAGMA journal_mode=WAL")
    -            conn.execute("PRAGMA synchronous=NORMAL")
    -            written_tables, written_columns = _write_collected_datasets(
    -                conn,
    -                client,
    -                symbol,
    -                datasets,
    -                timeframe,
    -                flags,
    -                date_from,
    -                date_to,
    -                if_exists,
    -            )
    -            _create_collect_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 datasets)),
    -            len(symbol),
    -            export_ctx.output,
    -        )
    -    finally:
    -        client.shutdown()
    -
    -
    - - - - -
    - - -

    - detect_format - - -

    -
    detect_format(
    -    output_path: Path, explicit_format: str | None = None
    -) -> str
    -
    - -
    - -

    Detect the output format from a file extension or explicit format string.

    - - -

    Parameters:

    - - - - - - - - - - - - - - - - - - - - - - - -
    NameTypeDescriptionDefault
    - output_path - - Path - -
    -

    Path to the output file.

    -
    -
    - required -
    - explicit_format - - str | None - -
    -

    Explicitly specified format, if any.

    -
    -
    - None -
    - - -

    Returns:

    - - - - - - - - - - - - - -
    TypeDescription
    - str - -
    -

    The detected format string.

    -
    -
    - - -

    Raises:

    - - - - - - - - - - - - - -
    TypeDescription
    - ValueError - -
    -

    If the format cannot be determined.

    -
    -
    - - -
    - Source code in mt5cli/cli.py -
    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 - - -

    -
    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:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    NameTypeDescriptionDefault
    - 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:

    - - - - - - - - - - - - - -
    TypeDescription
    - ValueError - -
    -

    If the output format is not supported.

    -
    -
    - - -
    - Source code in mt5cli/cli.py -
    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":
    -        with sqlite3.connect(output_path) as conn:
    -            df.to_sql(  # type: ignore[reportUnknownMemberType]
    -                table_name,
    -                conn,
    -                if_exists="replace",
    -                index=False,
    -            )
    -    else:
    -        msg = f"Unsupported output format: {output_format}"
    -        raise ValueError(msg)
    +              
    @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).",
    +        ),
    +    ] = 1,
    +    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,
    +    )
     
    @@ -1682,7 +569,7 @@ views cash_events and positions_reconstructed are deri module-attribute - (mt5cli.cli.DATETIME_TYPE)" href="#mt5cli.cli.DATETIME_TYPE">DATETIME_TYPE, help="Start date." + (mt5cli.utils.DATETIME_TYPE)" href="../utils/#mt5cli.utils.DATETIME_TYPE">DATETIME_TYPE, help="Start date." ), ] = None, date_to: Annotated[ @@ -1692,7 +579,7 @@ views cash_events and positions_reconstructed are deri module-attribute - (mt5cli.cli.DATETIME_TYPE)" href="#mt5cli.cli.DATETIME_TYPE">DATETIME_TYPE, help="End date."), + (mt5cli.utils.DATETIME_TYPE)" href="../utils/#mt5cli.utils.DATETIME_TYPE">DATETIME_TYPE, help="End date."), ] = None, group: Annotated[ str | None, Option(help="Group filter.") @@ -1716,61 +603,63 @@ views cash_events and positions_reconstructed are deri
    Source code in mt5cli/cli.py -
    @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."""
    -    _execute_export(
    -        ctx,
    -        lambda c: c.history_deals_get_as_df(
    -            date_from=date_from,
    -            date_to=date_to,
    -            group=group,
    -            symbol=symbol,
    -            ticket=ticket,
    -            position=position,
    -        ),
    -    )
    +              
    @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."""
    +    client = _sdk_client(ctx)
    +    _execute_export(
    +        ctx,
    +        lambda: client.history_deals(
    +            date_from=date_from,
    +            date_to=date_to,
    +            group=group,
    +            symbol=symbol,
    +            ticket=ticket,
    +            position=position,
    +        ),
    +    )
     
    @@ -1795,7 +684,7 @@ views cash_events and positions_reconstructed are deri module-attribute - (mt5cli.cli.DATETIME_TYPE)" href="#mt5cli.cli.DATETIME_TYPE">DATETIME_TYPE, help="Start date." + (mt5cli.utils.DATETIME_TYPE)" href="../utils/#mt5cli.utils.DATETIME_TYPE">DATETIME_TYPE, help="Start date." ), ] = None, date_to: Annotated[ @@ -1805,7 +694,7 @@ views cash_events and positions_reconstructed are deri module-attribute - (mt5cli.cli.DATETIME_TYPE)" href="#mt5cli.cli.DATETIME_TYPE">DATETIME_TYPE, help="End date."), + (mt5cli.utils.DATETIME_TYPE)" href="../utils/#mt5cli.utils.DATETIME_TYPE">DATETIME_TYPE, help="End date."), ] = None, group: Annotated[ str | None, Option(help="Group filter.") @@ -1829,61 +718,63 @@ views cash_events and positions_reconstructed are deri
    Source code in mt5cli/cli.py -
    @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."""
    -    _execute_export(
    -        ctx,
    -        lambda c: c.history_orders_get_as_df(
    -            date_from=date_from,
    -            date_to=date_to,
    -            group=group,
    -            symbol=symbol,
    -            ticket=ticket,
    -            position=position,
    -        ),
    -    )
    +              
    @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."""
    +    client = _sdk_client(ctx)
    +    _execute_export(
    +        ctx,
    +        lambda: client.history_orders(
    +            date_from=date_from,
    +            date_to=date_to,
    +            group=group,
    +            symbol=symbol,
    +            ticket=ticket,
    +            position=position,
    +        ),
    +    )
     
    @@ -1908,13 +799,13 @@ views cash_events and positions_reconstructed are deri
    Source code in mt5cli/cli.py -
    @app.command()
    -def last_error(ctx: typer.Context) -> None:
    -    """Export the last error information."""
    -    _execute_export(ctx, lambda c: c.last_error_as_df())
    +              
    @app.command()
    +def last_error(ctx: typer.Context) -> None:
    +    """Export the last error information."""
    +    _execute_export(ctx, _sdk_client(ctx).last_error)
     
    @@ -1939,11 +830,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()
     
    @@ -1971,25 +862,21 @@ views cash_events and positions_reconstructed are deri
    Source code in mt5cli/cli.py -
    @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."""
    -    _execute_export(
    -        ctx,
    -        lambda c: c.market_book_get_as_df(symbol=symbol),
    -    )
    +              
    @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."""
    +    client = _sdk_client(ctx)
    +    _execute_export(ctx, lambda: client.market_book(symbol))
     
    @@ -2014,7 +901,7 @@ views cash_events and positions_reconstructed are deri module-attribute - (mt5cli.cli.REQUEST_TYPE)" href="#mt5cli.cli.REQUEST_TYPE">REQUEST_TYPE, + (mt5cli.utils.REQUEST_TYPE)" href="../utils/#mt5cli.utils.REQUEST_TYPE">REQUEST_TYPE, help=_REQUEST_OPTION_HELP, ), ], @@ -2028,31 +915,41 @@ views cash_events and positions_reconstructed are deri
    Source code in mt5cli/cli.py -
    @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."""
    -    _execute_export(
    -        ctx,
    -        lambda c: c.order_check_as_df(request=request),
    -    )
    +              
    @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_ctx = _get_export_context(ctx)
    +
    +    def _fetch() -> pd.DataFrame:
    +        return sdk._run_with_client(  # noqa: SLF001  # pyright: ignore[reportPrivateUsage]
    +            export_ctx.config,
    +            lambda c: c.order_check_as_df(request=request),
    +        )
    +
    +    _execute_export(ctx, _fetch)
     
    @@ -2077,7 +974,7 @@ views cash_events and positions_reconstructed are deri module-attribute - (mt5cli.cli.REQUEST_TYPE)" href="#mt5cli.cli.REQUEST_TYPE">REQUEST_TYPE, + (mt5cli.utils.REQUEST_TYPE)" href="../utils/#mt5cli.utils.REQUEST_TYPE">REQUEST_TYPE, help=_REQUEST_OPTION_HELP, ), ], @@ -2120,53 +1017,63 @@ views cash_events and positions_reconstructed are deri
    Source code in mt5cli/cli.py -
    @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")
    -    _execute_export(
    -        ctx,
    -        lambda c: c.order_send_as_df(request=request),
    -    )
    +              
    @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_ctx = _get_export_context(ctx)
    +
    +    def _fetch() -> pd.DataFrame:
    +        return sdk._run_with_client(  # noqa: SLF001  # pyright: ignore[reportPrivateUsage]
    +            export_ctx.config,
    +            lambda c: c.order_send_as_df(request=request),
    +        )
    +
    +    _execute_export(ctx, _fetch)
     
    @@ -2202,627 +1109,31 @@ views cash_events and positions_reconstructed are deri
    Source code in mt5cli/cli.py -
    @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."""
    -    _execute_export(
    -        ctx,
    -        lambda c: c.orders_get_as_df(
    -            symbol=symbol,
    -            group=group,
    -            ticket=ticket,
    -        ),
    -    )
    -
    -
    - - - - -
    - - -

    - parse_datetime - - -

    -
    parse_datetime(value: str) -> datetime
    -
    - -
    - -

    Parse an ISO 8601 datetime string to a timezone-aware datetime.

    - - -

    Parameters:

    - - - - - - - - - - - - - - - - - -
    NameTypeDescriptionDefault
    - value - - str - -
    -

    ISO 8601 datetime string (e.g., '2024-01-01' or -'2024-01-01T12:00:00+00:00').

    -
    -
    - required -
    - - -

    Returns:

    - - - - - - - - - - - - - -
    TypeDescription
    - datetime - -
    -

    Parsed datetime with UTC timezone if no timezone is specified.

    -
    -
    - - -

    Raises:

    - - - - - - - - - - - - - -
    TypeDescription
    - ValueError - -
    -

    If the string cannot be parsed.

    -
    -
    - - -
    - Source code in mt5cli/cli.py -
    343
    +              
    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 - - -

    -
    parse_request(value: str) -> dict[str, Any]
    -
    - -
    - -

    Parse a JSON-formatted order request string or file reference.

    - - -

    Parameters:

    - - - - - - - - - - - - - - - - - -
    NameTypeDescriptionDefault
    - value - - str - -
    -

    JSON object string, or '@path' to read JSON from a file.

    -
    -
    - required -
    - - -

    Returns:

    - - - - - - - - - - - - - -
    TypeDescription
    - dict[str, Any] - -
    -

    Parsed request dictionary.

    -
    -
    - - -

    Raises:

    - - - - - - - - - - - - - -
    TypeDescription
    - ValueError - -
    -

    If the request file cannot be read or the value is not a -JSON object.

    -
    -
    - - -
    - Source code in mt5cli/cli.py -
    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 - - -

    -
    parse_tick_flags(value: str) -> int
    -
    - -
    - -

    Parse tick flags string or integer value.

    - - -

    Parameters:

    - - - - - - - - - - - - - - - - - -
    NameTypeDescriptionDefault
    - value - - str - -
    -

    Tick flag name (ALL, INFO, TRADE) or integer value.

    -
    -
    - required -
    - - -

    Returns:

    - - - - - - - - - - - - - -
    TypeDescription
    - int - -
    -

    Integer tick flag value.

    -
    -
    - - -

    Raises:

    - - - - - - - - - - - - - -
    TypeDescription
    - ValueError - -
    -

    If the flag is invalid.

    -
    -
    - - -
    - Source code in mt5cli/cli.py -
    def parse_tick_flags(value: str) -> int:
    -    """Parse tick flags string or integer value.
    -
    -    Args:
    -        value: Tick flag name (ALL, INFO, TRADE) or integer value.
    -
    -    Returns:
    -        Integer tick flag value.
    -
    -    Raises:
    -        ValueError: If the flag is invalid.
    -    """
    -    upper = value.upper()
    -    if upper in TICK_FLAG_MAP:
    -        return TICK_FLAG_MAP[upper]
    -    try:
    -        return int(value)
    -    except ValueError:
    -        valid = ", ".join(TICK_FLAG_MAP)
    -        msg = f"Invalid tick flags: '{value}'. Use one of: {valid}, or an integer."
    -        raise ValueError(msg) from None
    -
    -
    -
    - -
    - -
    - - -

    - parse_timeframe - - -

    -
    parse_timeframe(value: str) -> int
    -
    - -
    - -

    Parse a timeframe string or integer value.

    - - -

    Parameters:

    - - - - - - - - - - - - - - - - - -
    NameTypeDescriptionDefault
    - value - - str - -
    -

    Timeframe name (e.g., 'M1', 'H1', 'D1') or integer value.

    -
    -
    - required -
    - - -

    Returns:

    - - - - - - - - - - - - - -
    TypeDescription
    - int - -
    -

    Integer timeframe value.

    -
    -
    - - -

    Raises:

    - - - - - - - - - - - - - -
    TypeDescription
    - ValueError - -
    -

    If the timeframe is invalid.

    -
    -
    - - -
    - Source code in mt5cli/cli.py -
    def parse_timeframe(value: str) -> 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.
    -    """
    -    upper = value.upper()
    -    if upper in TIMEFRAME_MAP:
    -        return TIMEFRAME_MAP[upper]
    -    try:
    -        return int(value)
    -    except ValueError:
    -        valid = ", ".join(TIMEFRAME_MAP)
    -        msg = f"Invalid timeframe: '{value}'. Use one of: {valid}, or an integer."
    -        raise ValueError(msg) from None
    +350
    @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."""
    +    client = _sdk_client(ctx)
    +    _execute_export(
    +        ctx,
    +        lambda: client.orders(symbol=symbol, group=group, ticket=ticket),
    +    )
     
    @@ -2858,37 +1169,31 @@ JSON object.

    Source code in mt5cli/cli.py -
    @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."""
    -    _execute_export(
    -        ctx,
    -        lambda c: c.positions_get_as_df(
    -            symbol=symbol,
    -            group=group,
    -            ticket=ticket,
    -        ),
    -    )
    +              
    @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."""
    +    client = _sdk_client(ctx)
    +    _execute_export(
    +        ctx,
    +        lambda: client.positions(symbol=symbol, group=group, ticket=ticket),
    +    )
     
    @@ -2914,7 +1219,7 @@ JSON object.

    module-attribute - (mt5cli.cli.TIMEFRAME_TYPE)" href="#mt5cli.cli.TIMEFRAME_TYPE">TIMEFRAME_TYPE, + (mt5cli.utils.TIMEFRAME_TYPE)" href="../utils/#mt5cli.utils.TIMEFRAME_TYPE">TIMEFRAME_TYPE, help="Timeframe (e.g., M1, H1, D1, or integer).", ), ], @@ -2926,7 +1231,7 @@ JSON object.

    module-attribute - (mt5cli.cli.DATETIME_TYPE)" href="#mt5cli.cli.DATETIME_TYPE">DATETIME_TYPE, + (mt5cli.utils.DATETIME_TYPE)" href="../utils/#mt5cli.utils.DATETIME_TYPE">DATETIME_TYPE, help="Start date in ISO 8601 format.", ), ], @@ -2943,65 +1248,57 @@ JSON object.

    Source code in mt5cli/cli.py -
    @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."""
    -    _execute_export(
    -        ctx,
    -        lambda c: c.copy_rates_from_as_df(
    -            symbol=symbol,
    -            timeframe=timeframe,
    -            date_from=date_from,
    -            count=count,
    -        ),
    -    )
    +              
    @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."""
    +    client = _sdk_client(ctx)
    +    _execute_export(
    +        ctx,
    +        lambda: client.copy_rates_from(symbol, timeframe, date_from, count),
    +    )
     
    @@ -3027,7 +1324,7 @@ JSON object.

    module-attribute - (mt5cli.cli.TIMEFRAME_TYPE)" href="#mt5cli.cli.TIMEFRAME_TYPE">TIMEFRAME_TYPE, help="Timeframe." + (mt5cli.utils.TIMEFRAME_TYPE)" href="../utils/#mt5cli.utils.TIMEFRAME_TYPE">TIMEFRAME_TYPE, help="Timeframe." ), ], start_pos: Annotated[ @@ -3047,53 +1344,45 @@ JSON object.

    Source code in mt5cli/cli.py -
    @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."""
    -    _execute_export(
    -        ctx,
    -        lambda c: c.copy_rates_from_pos_as_df(
    -            symbol=symbol,
    -            timeframe=timeframe,
    -            start_pos=start_pos,
    -            count=count,
    -        ),
    -    )
    +              
    @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."""
    +    client = _sdk_client(ctx)
    +    _execute_export(
    +        ctx,
    +        lambda: client.copy_rates_from_pos(symbol, timeframe, start_pos, count),
    +    )
     
    @@ -3119,7 +1408,7 @@ JSON object.

    module-attribute - (mt5cli.cli.TIMEFRAME_TYPE)" href="#mt5cli.cli.TIMEFRAME_TYPE">TIMEFRAME_TYPE, help="Timeframe." + (mt5cli.utils.TIMEFRAME_TYPE)" href="../utils/#mt5cli.utils.TIMEFRAME_TYPE">TIMEFRAME_TYPE, help="Timeframe." ), ], date_from: Annotated[ @@ -3130,7 +1419,7 @@ JSON object.

    module-attribute - (mt5cli.cli.DATETIME_TYPE)" href="#mt5cli.cli.DATETIME_TYPE">DATETIME_TYPE, help="Start date." + (mt5cli.utils.DATETIME_TYPE)" href="../utils/#mt5cli.utils.DATETIME_TYPE">DATETIME_TYPE, help="Start date." ), ], date_to: Annotated[ @@ -3140,7 +1429,7 @@ JSON object.

    module-attribute - (mt5cli.cli.DATETIME_TYPE)" href="#mt5cli.cli.DATETIME_TYPE">DATETIME_TYPE, help="End date."), + (mt5cli.utils.DATETIME_TYPE)" href="../utils/#mt5cli.utils.DATETIME_TYPE">DATETIME_TYPE, help="End date."), ], ) -> None
    @@ -3152,65 +1441,57 @@ JSON object.

    Source code in mt5cli/cli.py -
    @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."""
    -    _execute_export(
    -        ctx,
    -        lambda c: c.copy_rates_range_as_df(
    -            symbol=symbol,
    -            timeframe=timeframe,
    -            date_from=date_from,
    -            date_to=date_to,
    -        ),
    -    )
    +              
    @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."""
    +    client = _sdk_client(ctx)
    +    _execute_export(
    +        ctx,
    +        lambda: client.copy_rates_range(symbol, timeframe, date_from, date_to),
    +    )
     
    @@ -3238,25 +1519,21 @@ JSON object.

    Source code in mt5cli/cli.py -
    @app.command()
    -def symbol_info(
    -    ctx: typer.Context,
    -    symbol: Annotated[str, typer.Option(help="Symbol name.")],
    -) -> None:
    -    """Export symbol details."""
    -    _execute_export(
    -        ctx,
    -        lambda c: c.symbol_info_as_df(symbol=symbol),
    -    )
    +              
    @app.command()
    +def symbol_info(
    +    ctx: typer.Context,
    +    symbol: Annotated[str, typer.Option(help="Symbol name.")],
    +) -> None:
    +    """Export symbol details."""
    +    client = _sdk_client(ctx)
    +    _execute_export(ctx, lambda: client.symbol_info(symbol))
     
    @@ -3284,25 +1561,21 @@ JSON object.

    Source code in mt5cli/cli.py -
    @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."""
    -    _execute_export(
    -        ctx,
    -        lambda c: c.symbol_info_tick_as_df(symbol=symbol),
    -    )
    +              
    @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."""
    +    client = _sdk_client(ctx)
    +    _execute_export(ctx, lambda: client.symbol_info_tick(symbol))
     
    @@ -3333,31 +1606,27 @@ JSON object.

    Source code in mt5cli/cli.py -
    @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."""
    -    _execute_export(
    -        ctx,
    -        lambda c: c.symbols_get_as_df(group=group),
    -    )
    +              
    @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."""
    +    client = _sdk_client(ctx)
    +    _execute_export(ctx, lambda: client.symbols(group=group))
     
    @@ -3382,13 +1651,13 @@ JSON object.

    Source code in mt5cli/cli.py -
    @app.command()
    -def terminal_info(ctx: typer.Context) -> None:
    -    """Export terminal information."""
    -    _execute_export(ctx, lambda c: c.terminal_info_as_df())
    +              
    @app.command()
    +def terminal_info(ctx: typer.Context) -> None:
    +    """Export terminal information."""
    +    _execute_export(ctx, _sdk_client(ctx).terminal_info)
     
    @@ -3414,7 +1683,7 @@ JSON object.

    module-attribute - (mt5cli.cli.DATETIME_TYPE)" href="#mt5cli.cli.DATETIME_TYPE">DATETIME_TYPE, help="Start date." + (mt5cli.utils.DATETIME_TYPE)" href="../utils/#mt5cli.utils.DATETIME_TYPE">DATETIME_TYPE, help="Start date." ), ], count: Annotated[int, Option(help="Number of ticks.")], @@ -3426,7 +1695,7 @@ JSON object.

    module-attribute - (mt5cli.cli.TICK_FLAGS_TYPE)" href="#mt5cli.cli.TICK_FLAGS_TYPE">TICK_FLAGS_TYPE, + (mt5cli.utils.TICK_FLAGS_TYPE)" href="../utils/#mt5cli.utils.TICK_FLAGS_TYPE">TICK_FLAGS_TYPE, help="Tick flags (ALL, INFO, TRADE, or integer).", ), ], @@ -3440,59 +1709,51 @@ JSON object.

    Source code in mt5cli/cli.py -
    @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."""
    -    _execute_export(
    -        ctx,
    -        lambda c: c.copy_ticks_from_as_df(
    -            symbol=symbol,
    -            date_from=date_from,
    -            count=count,
    -            flags=flags,
    -        ),
    -    )
    +              
    @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."""
    +    client = _sdk_client(ctx)
    +    _execute_export(
    +        ctx,
    +        lambda: client.copy_ticks_from(symbol, date_from, count, flags),
    +    )
     
    @@ -3518,7 +1779,7 @@ JSON object.

    module-attribute - (mt5cli.cli.DATETIME_TYPE)" href="#mt5cli.cli.DATETIME_TYPE">DATETIME_TYPE, help="Start date." + (mt5cli.utils.DATETIME_TYPE)" href="../utils/#mt5cli.utils.DATETIME_TYPE">DATETIME_TYPE, help="Start date." ), ], date_to: Annotated[ @@ -3528,7 +1789,7 @@ JSON object.

    module-attribute - (mt5cli.cli.DATETIME_TYPE)" href="#mt5cli.cli.DATETIME_TYPE">DATETIME_TYPE, help="End date."), + (mt5cli.utils.DATETIME_TYPE)" href="../utils/#mt5cli.utils.DATETIME_TYPE">DATETIME_TYPE, help="End date."), ], flags: Annotated[ int, @@ -3538,7 +1799,7 @@ JSON object.

    module-attribute - (mt5cli.cli.TICK_FLAGS_TYPE)" href="#mt5cli.cli.TICK_FLAGS_TYPE">TICK_FLAGS_TYPE, help="Tick flags." + (mt5cli.utils.TICK_FLAGS_TYPE)" href="../utils/#mt5cli.utils.TICK_FLAGS_TYPE">TICK_FLAGS_TYPE, help="Tick flags." ), ], ) -> None @@ -3551,59 +1812,51 @@ JSON object.

    Source code in mt5cli/cli.py -
    @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."""
    -    _execute_export(
    -        ctx,
    -        lambda c: c.copy_ticks_range_as_df(
    -            symbol=symbol,
    -            date_from=date_from,
    -            date_to=date_to,
    -            flags=flags,
    -        ),
    -    )
    +              
    @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."""
    +    client = _sdk_client(ctx)
    +    _execute_export(
    +        ctx,
    +        lambda: client.copy_ticks_range(symbol, date_from, date_to, flags),
    +    )
     
    @@ -3628,13 +1881,13 @@ JSON object.

    Source code in mt5cli/cli.py -
    @app.command()
    -def version(ctx: typer.Context) -> None:
    -    """Export MetaTrader5 version information."""
    -    _execute_export(ctx, lambda c: c.version_as_df())
    +              
    @app.command()
    +def version(ctx: typer.Context) -> None:
    +    """Export MetaTrader5 version information."""
    +    _execute_export(ctx, _sdk_client(ctx).version)
     
    diff --git a/api/index.html b/api/index.html index 56c28d2..7acf56e 100644 --- a/api/index.html +++ b/api/index.html @@ -49,6 +49,14 @@
  • CLI
  • + +
  • + SDK +
  • + +
  • + Utils +
  • @@ -130,10 +138,16 @@

    The mt5cli package consists of the following modules:

    CLI

    Command-line interface module providing typer-based commands for exporting MetaTrader 5 data to CSV, JSON, Parquet, and SQLite3 formats.

    +

    Utils

    +

    Utility module providing constants, enums, Click parameter types, and helper functions for parsing and exporting data.

    +

    SDK

    +

    Programmatic SDK for read-only MetaTrader 5 data collection. Returns pandas DataFrames and provides collect_history for SQLite bulk collection.

    Architecture Overview

    The package follows a simple architecture built on top of pdmt5:

      -
    1. CLI Layer (cli.py): Typer application with subcommands for each data type, custom Click parameter types for datetime/timeframe/tick flags parsing, and format detection/export utilities.
    2. +
    3. CLI Layer (cli.py): Typer application with subcommands that delegate to the SDK and export results.
    4. +
    5. SDK Layer (sdk.py): Read-only data access functions, Mt5CliClient, and collect_history orchestration.
    6. +
    7. Utils Layer (utils.py): Constants, enums, custom Click parameter types, parsing helpers, and format detection/export utilities.
    8. Data Layer (via pdmt5): Uses Mt5DataClient and Mt5Config from the pdmt5 package for all MetaTrader 5 data access.

    Usage Guidelines

    @@ -160,15 +174,38 @@ mt5cli -o data.db --table symbols symbols --group "*USD*"

    Python API

    -
    from mt5cli import detect_format, export_dataframe
    -import pandas as pd
    +
    from datetime import UTC, datetime
    +from pathlib import Path
     
    -# Detect output format from file extension
    -fmt = detect_format(Path("output.parquet"))  # Returns "parquet"
    -
    -# Export a DataFrame
    -df = pd.DataFrame({"symbol": ["EURUSD"], "bid": [1.1234]})
    -export_dataframe(df, Path("output.csv"), "csv")
    +from mt5cli import (
    +    Mt5CliClient,
    +    collect_history,
    +    copy_rates_range,
    +    detect_format,
    +    export_dataframe,
    +)
    +
    +# Fetch rates programmatically
    +rates = copy_rates_range(
    +    "EURUSD",
    +    timeframe="H1",
    +    date_from="2024-01-01",
    +    date_to="2024-02-01",
    +)
    +
    +# Detect output format from file extension
    +fmt = detect_format(Path("output.parquet"))  # Returns "parquet"
    +
    +# Export a DataFrame
    +export_dataframe(rates, Path("output.csv"), "csv")
    +
    +# Collect history into SQLite
    +collect_history(
    +    Path("history.db"),
    +    symbols=["EURUSD"],
    +    date_from=datetime(2024, 1, 1, tzinfo=UTC),
    +    date_to=datetime(2024, 2, 1, tzinfo=UTC),
    +)
     

    Examples

    See individual module pages for detailed usage examples and code samples.

    diff --git a/api/sdk/index.html b/api/sdk/index.html new file mode 100644 index 0000000..b93462a --- /dev/null +++ b/api/sdk/index.html @@ -0,0 +1,2778 @@ + + + + + + + + + + + SDK - mt5cli API Documentation + + + + + + + + + + + + + + + + +
    +
    +
    +
    + +

    SDK Module

    + + +
    + + + +

    + mt5cli.sdk + + +

    + +
    + +

    Programmatic SDK for MetaTrader 5 data collection.

    + + + + + + + + + + +
    + + + + + + + +
    + + + +

    + T + + + + module-attribute + + +

    +
    T = TypeVar('T')
    +
    + +
    + +
    + +
    + +
    + + + +

    + __all__ + + + + module-attribute + + +

    +
    __all__ = [
    +    "Mt5CliClient",
    +    "account_info",
    +    "build_config",
    +    "collect_history",
    +    "copy_rates_from",
    +    "copy_rates_from_pos",
    +    "copy_rates_range",
    +    "copy_ticks_from",
    +    "copy_ticks_range",
    +    "history_deals",
    +    "history_orders",
    +    "last_error",
    +    "market_book",
    +    "orders",
    +    "positions",
    +    "symbol_info",
    +    "symbol_info_tick",
    +    "symbols",
    +    "terminal_info",
    +    "version",
    +]
    +
    + +
    + +
    + +
    + +
    + + + +

    + logger + + + + module-attribute + + +

    +
    logger = getLogger(__name__)
    +
    + +
    + +
    + +
    + + + +
    + + + +

    + Mt5CliClient + + +

    +
    Mt5CliClient(
    +    *,
    +    path: str | None = None,
    +    login: int | None = None,
    +    password: str | None = None,
    +    server: str | None = None,
    +    timeout: int | None = None,
    +    config: Mt5Config | None = None,
    +)
    +
    + +
    + + + +

    Programmatic client for read-only MetaTrader 5 data access.

    + +

    Initialize the SDK client.

    + + +

    Parameters:

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameTypeDescriptionDefault
    + 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 +
    + config + + Mt5Config | None + +
    +

    Optional pre-built Mt5Config (overrides other args).

    +
    +
    + None +
    + + + + + + + + +
    + Source code in mt5cli/sdk.py +
    def __init__(
    +    self,
    +    *,
    +    path: str | None = None,
    +    login: int | None = None,
    +    password: str | None = None,
    +    server: str | None = None,
    +    timeout: int | None = None,
    +    config: Mt5Config | 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.
    +        config: Optional pre-built ``Mt5Config`` (overrides other args).
    +    """
    +    self._config = config or build_config(
    +        path=path,
    +        login=login,
    +        password=password,
    +        server=server,
    +        timeout=timeout,
    +    )
    +    self._client: Mt5DataClient | None = None
    +
    +
    + + + +
    + + + + + + + +
    + + + +

    + config + + + + property + + +

    +
    config: Mt5Config
    +
    + +
    + +

    Return the underlying MT5 configuration.

    + +
    + +
    + + + + +
    + + +

    + __enter__ + + +

    +
    __enter__() -> Self
    +
    + +
    + +

    Open a persistent MT5 connection for multiple calls.

    + + +

    Returns:

    + + + + + + + + + + + + + +
    TypeDescription
    + Self + +
    +

    This client instance.

    +
    +
    + + +
    + Source code in mt5cli/sdk.py +
    def __enter__(self) -> Self:
    +    """Open a persistent MT5 connection for multiple calls.
    +
    +    Returns:
    +        This client instance.
    +    """
    +    client = Mt5DataClient(config=self._config)
    +    try:
    +        client.initialize_and_login_mt5()
    +    except Exception:
    +        client.shutdown()
    +        raise
    +    self._client = client
    +    return self
    +
    +
    +
    + +
    + +
    + + +

    + __exit__ + + +

    +
    __exit__(
    +    exc_type: type[BaseException] | None,
    +    exc: BaseException | None,
    +    tb: object,
    +) -> None
    +
    + +
    + +

    Shut down the persistent MT5 connection.

    + + +
    + Source code in mt5cli/sdk.py +
    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:
    +        self._client.shutdown()
    +        self._client = None
    +
    +
    +
    + +
    + +
    + + +

    + account_info + + +

    +
    account_info() -> DataFrame
    +
    + +
    + +

    Return account information.

    + + +
    + Source code in mt5cli/sdk.py +
    def account_info(self) -> pd.DataFrame:
    +    """Return account information."""
    +    return self._fetch(lambda c: c.account_info_as_df())
    +
    +
    +
    + +
    + +
    + + +

    + copy_rates_from + + +

    +
    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 +
    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 + + +

    +
    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 +
    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 + + +

    +
    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 +
    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 + + +

    +
    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 +
    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 + + +

    +
    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 +
    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,
    +        ),
    +    )
    +
    +
    +
    + +
    + +
    + + +

    + history_deals + + +

    +
    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 +
    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 + + +

    +
    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 +
    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 + + +

    +
    last_error() -> DataFrame
    +
    + +
    + +

    Return the last error information.

    + + +
    + Source code in mt5cli/sdk.py +
    def last_error(self) -> pd.DataFrame:
    +    """Return the last error information."""
    +    return self._fetch(lambda c: c.last_error_as_df())
    +
    +
    +
    + +
    + +
    + + +

    + market_book + + +

    +
    market_book(symbol: str) -> DataFrame
    +
    + +
    + +

    Return market depth for a symbol.

    + + +
    + Source code in mt5cli/sdk.py +
    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))
    +
    +
    +
    + +
    + +
    + + +

    + orders + + +

    +
    orders(
    +    symbol: str | None = None,
    +    group: str | None = None,
    +    ticket: int | None = None,
    +) -> DataFrame
    +
    + +
    + +

    Return active orders.

    + + +
    + Source code in mt5cli/sdk.py +
    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 + + +

    +
    positions(
    +    symbol: str | None = None,
    +    group: str | None = None,
    +    ticket: int | None = None,
    +) -> DataFrame
    +
    + +
    + +

    Return open positions.

    + + +
    + Source code in mt5cli/sdk.py +
    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,
    +        ),
    +    )
    +
    +
    +
    + +
    + +
    + + +

    + symbol_info + + +

    +
    symbol_info(symbol: str) -> DataFrame
    +
    + +
    + +

    Return details for one symbol.

    + + +
    + Source code in mt5cli/sdk.py +
    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 + + +

    +
    symbol_info_tick(symbol: str) -> DataFrame
    +
    + +
    + +

    Return the last tick for a symbol.

    + + +
    + Source code in mt5cli/sdk.py +
    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 + + +

    +
    symbols(group: str | None = None) -> DataFrame
    +
    + +
    + +

    Return the symbol list.

    + + +
    + Source code in mt5cli/sdk.py +
    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 + + +

    +
    terminal_info() -> DataFrame
    +
    + +
    + +

    Return terminal information.

    + + +
    + Source code in mt5cli/sdk.py +
    def terminal_info(self) -> pd.DataFrame:
    +    """Return terminal information."""
    +    return self._fetch(lambda c: c.terminal_info_as_df())
    +
    +
    +
    + +
    + +
    + + +

    + version + + +

    +
    version() -> DataFrame
    +
    + +
    + +

    Return MetaTrader5 version information.

    + + +
    + Source code in mt5cli/sdk.py +
    def version(self) -> pd.DataFrame:
    +    """Return MetaTrader5 version information."""
    +    return self._fetch(lambda c: c.version_as_df())
    +
    +
    +
    + +
    + + + +
    + +
    + +
    + + +
    + + +

    + account_info + + +

    +
    account_info(
    +    *, config: Mt5Config | None = None
    +) -> DataFrame
    +
    + +
    + +

    Return account information.

    + + +
    + Source code in mt5cli/sdk.py +
    def account_info(*, config: Mt5Config | None = None) -> pd.DataFrame:
    +    """Return account information."""
    +    return _make_client(config=config).account_info()
    +
    +
    +
    + +
    + +
    + + +

    + build_config + + +

    +
    build_config(
    +    *,
    +    path: str | None = None,
    +    login: int | None = None,
    +    password: str | None = None,
    +    server: str | None = None,
    +    timeout: int | None = None,
    +) -> Mt5Config
    +
    + +
    + +

    Build an Mt5Config from optional connection parameters.

    + + +

    Returns:

    + + + + + + + + + + + + + +
    TypeDescription
    + Mt5Config + +
    +

    Configured Mt5Config instance.

    +
    +
    + + +
    + Source code in mt5cli/sdk.py +
    def build_config(
    +    *,
    +    path: str | None = None,
    +    login: int | None = None,
    +    password: str | None = None,
    +    server: str | None = None,
    +    timeout: int | None = None,
    +) -> Mt5Config:
    +    """Build an ``Mt5Config`` from optional connection parameters.
    +
    +    Returns:
    +        Configured ``Mt5Config`` instance.
    +    """
    +    return Mt5Config(
    +        path=path,
    +        login=login,
    +        password=password,
    +        server=server,
    +        timeout=timeout,
    +    )
    +
    +
    +
    + +
    + +
    + + +

    + collect_history + + +

    +
    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 = 1,
    +    if_exists: IfExists = FAIL,
    +    with_views: bool = False,
    +    config: Mt5Config | None = None,
    +) -> None
    +
    + +
    + +

    Collect historical datasets into a single SQLite database.

    + + +

    Parameters:

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameTypeDescriptionDefault
    + 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).

    +
    +
    + 1 +
    + 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 +
    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 = 1,
    +    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_collect_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,
    +    )
    +
    +
    +
    + +
    + +
    + + +

    + copy_rates_from + + +

    +
    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 +
    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 + + +

    +
    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 +
    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 + + +

    +
    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 +
    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 + + +

    +
    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 +
    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 + + +

    +
    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 +
    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,
    +    )
    +
    +
    +
    + +
    + +
    + + +

    + history_deals + + +

    +
    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 +
    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 + + +

    +
    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 +
    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 + + +

    +
    last_error(*, config: Mt5Config | None = None) -> DataFrame
    +
    + +
    + +

    Return the last error information.

    + + +
    + Source code in mt5cli/sdk.py +
    def last_error(*, config: Mt5Config | None = None) -> pd.DataFrame:
    +    """Return the last error information."""
    +    return _make_client(config=config).last_error()
    +
    +
    +
    + +
    + +
    + + +

    + market_book + + +

    +
    market_book(
    +    symbol: str, *, config: Mt5Config | None = None
    +) -> DataFrame
    +
    + +
    + +

    Return market depth for a symbol.

    + + +
    + Source code in mt5cli/sdk.py +
    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)
    +
    +
    +
    + +
    + +
    + + +

    + orders + + +

    +
    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 +
    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 + + +

    +
    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 +
    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,
    +    )
    +
    +
    +
    + +
    + +
    + + +

    + symbol_info + + +

    +
    symbol_info(
    +    symbol: str, *, config: Mt5Config | None = None
    +) -> DataFrame
    +
    + +
    + +

    Return details for one symbol.

    + + +
    + Source code in mt5cli/sdk.py +
    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 + + +

    +
    symbol_info_tick(
    +    symbol: str, *, config: Mt5Config | None = None
    +) -> DataFrame
    +
    + +
    + +

    Return the last tick for a symbol.

    + + +
    + Source code in mt5cli/sdk.py +
    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 + + +

    +
    symbols(
    +    group: str | None = None,
    +    *,
    +    config: Mt5Config | None = None,
    +) -> DataFrame
    +
    + +
    + +

    Return the symbol list.

    + + +
    + Source code in mt5cli/sdk.py +
    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 + + +

    +
    terminal_info(
    +    *, config: Mt5Config | None = None
    +) -> DataFrame
    +
    + +
    + +

    Return terminal information.

    + + +
    + Source code in mt5cli/sdk.py +
    def terminal_info(*, config: Mt5Config | None = None) -> pd.DataFrame:
    +    """Return terminal information."""
    +    return _make_client(config=config).terminal_info()
    +
    +
    +
    + +
    + +
    + + +

    + version + + +

    +
    version(*, config: Mt5Config | None = None) -> DataFrame
    +
    + +
    + +

    Return MetaTrader5 version information.

    + + +
    + Source code in mt5cli/sdk.py +
    def version(*, config: Mt5Config | None = None) -> pd.DataFrame:
    +    """Return MetaTrader5 version information."""
    +    return _make_client(config=config).version()
    +
    +
    +
    + +
    + + + +
    + +
    + +
    +
    +
    + +
    +
    +

    Documentation built with MkDocs.

    +
    + + + + + + + + + diff --git a/api/utils/index.html b/api/utils/index.html new file mode 100644 index 0000000..ebe75a2 --- /dev/null +++ b/api/utils/index.html @@ -0,0 +1,1925 @@ + + + + + + + + + + + Utils - mt5cli API Documentation + + + + + + + + + + + + + + + + +
    +
    +
    +
    + +

    Utils Module

    + + +
    + + + +

    + mt5cli.utils + + +

    + +
    + +

    Utility constants, types, and functions for the mt5cli package.

    + + + + + + + + + + +
    + + + + + + + +
    + + + +

    + DATETIME_TYPE + + + + module-attribute + + +

    +
    DATETIME_TYPE = _DateTimeType()
    +
    + +
    + +
    + +
    + +
    + + + +

    + REQUEST_TYPE + + + + module-attribute + + +

    +
    REQUEST_TYPE = _RequestType()
    +
    + +
    + +
    + +
    + +
    + + + +

    + TICK_FLAGS_TYPE + + + + module-attribute + + +

    +
    TICK_FLAGS_TYPE = _TickFlagsType()
    +
    + +
    + +
    + +
    + +
    + + + +

    + TICK_FLAG_MAP + + + + module-attribute + + +

    +
    TICK_FLAG_MAP: dict[str, int] = {
    +    "ALL": 1,
    +    "INFO": 2,
    +    "TRADE": 4,
    +}
    +
    + +
    + +
    + +
    + +
    + + + +

    + TIMEFRAME_MAP + + + + module-attribute + + +

    +
    TIMEFRAME_MAP: dict[str, int] = {
    +    "M1": 1,
    +    "M2": 2,
    +    "M3": 3,
    +    "M4": 4,
    +    "M5": 5,
    +    "M6": 6,
    +    "M10": 10,
    +    "M12": 12,
    +    "M15": 15,
    +    "M20": 20,
    +    "M30": 30,
    +    "H1": 16385,
    +    "H2": 16386,
    +    "H3": 16387,
    +    "H4": 16388,
    +    "H6": 16390,
    +    "H8": 16392,
    +    "H12": 16396,
    +    "D1": 16408,
    +    "W1": 32769,
    +    "MN1": 49153,
    +}
    +
    + +
    + +
    + +
    + +
    + + + +

    + TIMEFRAME_TYPE + + + + module-attribute + + +

    +
    TIMEFRAME_TYPE = _TimeframeType()
    +
    + +
    + +
    + +
    + + + +
    + + + +

    + Dataset + + +

    + + +
    +

    + Bases: StrEnum

    + + + +

    Datasets supported by the collect-history command.

    + + + + + + + + + + + +
    + + + + + + + +
    + + + +

    + history_deals + + + + class-attribute + instance-attribute + + +

    +
    history_deals = 'history-deals'
    +
    + +
    + +
    + +
    + +
    + + + +

    + history_orders + + + + class-attribute + instance-attribute + + +

    +
    history_orders = 'history-orders'
    +
    + +
    + +
    + +
    + +
    + + + +

    + rates + + + + class-attribute + instance-attribute + + +

    +
    rates = 'rates'
    +
    + +
    + +
    + +
    + +
    + + + +

    + table_name + + + + property + + +

    +
    table_name: str
    +
    + +
    + +

    Return the SQLite table name for this dataset.

    + +
    + +
    + +
    + + + +

    + ticks + + + + class-attribute + instance-attribute + + +

    +
    ticks = 'ticks'
    +
    + +
    + +
    + +
    + + + + + + +
    + +
    + +
    + +
    + + + +

    + IfExists + + +

    + + +
    +

    + Bases: StrEnum

    + + + +

    SQLite table conflict behavior for the collect-history command.

    + + + + + + + + + + + +
    + + + + + + + +
    + + + +

    + APPEND + + + + class-attribute + instance-attribute + + +

    +
    APPEND = 'append'
    +
    + +
    + +
    + +
    + +
    + + + +

    + FAIL + + + + class-attribute + instance-attribute + + +

    +
    FAIL = 'fail'
    +
    + +
    + +
    + +
    + +
    + + + +

    + REPLACE + + + + class-attribute + instance-attribute + + +

    +
    REPLACE = 'replace'
    +
    + +
    + +
    + +
    + + + + + + +
    + +
    + +
    + +
    + + + +

    + LogLevel + + +

    + + +
    +

    + Bases: StrEnum

    + + + +

    Logging verbosity levels.

    + + + + + + + + + + + +
    + + + + + + + +
    + + + +

    + DEBUG + + + + class-attribute + instance-attribute + + +

    +
    DEBUG = 'DEBUG'
    +
    + +
    + +
    + +
    + +
    + + + +

    + ERROR + + + + class-attribute + instance-attribute + + +

    +
    ERROR = 'ERROR'
    +
    + +
    + +
    + +
    + +
    + + + +

    + INFO + + + + class-attribute + instance-attribute + + +

    +
    INFO = 'INFO'
    +
    + +
    + +
    + +
    + +
    + + + +

    + WARNING + + + + class-attribute + instance-attribute + + +

    +
    WARNING = 'WARNING'
    +
    + +
    + +
    + +
    + + + + + + +
    + +
    + +
    + +
    + + + +

    + OutputFormat + + +

    + + +
    +

    + Bases: StrEnum

    + + + +

    Supported output file formats.

    + + + + + + + + + + + +
    + + + + + + + +
    + + + +

    + csv + + + + class-attribute + instance-attribute + + +

    +
    csv = 'csv'
    +
    + +
    + +
    + +
    + +
    + + + +

    + json + + + + class-attribute + instance-attribute + + +

    +
    json = 'json'
    +
    + +
    + +
    + +
    + +
    + + + +

    + parquet + + + + class-attribute + instance-attribute + + +

    +
    parquet = 'parquet'
    +
    + +
    + +
    + +
    + +
    + + + +

    + sqlite3 + + + + class-attribute + instance-attribute + + +

    +
    sqlite3 = 'sqlite3'
    +
    + +
    + +
    + +
    + + + + + + +
    + +
    + +
    + + +
    + + +

    + detect_format + + +

    +
    detect_format(
    +    output_path: Path, explicit_format: str | None = None
    +) -> str
    +
    + +
    + +

    Detect the output format from a file extension or explicit format string.

    + + +

    Parameters:

    + + + + + + + + + + + + + + + + + + + + + + + +
    NameTypeDescriptionDefault
    + output_path + + Path + +
    +

    Path to the output file.

    +
    +
    + required +
    + explicit_format + + str | None + +
    +

    Explicitly specified format, if any.

    +
    +
    + None +
    + + +

    Returns:

    + + + + + + + + + + + + + +
    TypeDescription
    + str + +
    +

    The detected format string.

    +
    +
    + + +

    Raises:

    + + + + + + + + + + + + + +
    TypeDescription
    + ValueError + +
    +

    If the format cannot be determined.

    +
    +
    + + +
    + Source code in mt5cli/utils.py +
    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 + + +

    +
    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:

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameTypeDescriptionDefault
    + 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:

    + + + + + + + + + + + + + +
    TypeDescription
    + ValueError + +
    +

    If the output format is not supported.

    +
    +
    + + +
    + Source code in mt5cli/utils.py +
    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":
    +        sqlite3 = cast("Any", importlib.import_module("sqlite3"))
    +        with sqlite3.connect(output_path) as conn:
    +            df.to_sql(  # type: ignore[reportUnknownMemberType]
    +                table_name,
    +                conn,
    +                if_exists="replace",
    +                index=False,
    +            )
    +    else:
    +        msg = f"Unsupported output format: {output_format}"
    +        raise ValueError(msg)
    +
    +
    +
    + +
    + +
    + + +

    + parse_datetime + + +

    +
    parse_datetime(value: str) -> datetime
    +
    + +
    + +

    Parse an ISO 8601 datetime string to a timezone-aware datetime.

    + + +

    Parameters:

    + + + + + + + + + + + + + + + + + +
    NameTypeDescriptionDefault
    + value + + str + +
    +

    ISO 8601 datetime string (e.g., '2024-01-01' or +'2024-01-01T12:00:00+00:00').

    +
    +
    + required +
    + + +

    Returns:

    + + + + + + + + + + + + + +
    TypeDescription
    + datetime + +
    +

    Parsed datetime with UTC timezone if no timezone is specified.

    +
    +
    + + +

    Raises:

    + + + + + + + + + + + + + +
    TypeDescription
    + ValueError + +
    +

    If the string cannot be parsed.

    +
    +
    + + +
    + Source code in mt5cli/utils.py +
    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 + + +

    +
    parse_request(value: str) -> dict[str, Any]
    +
    + +
    + +

    Parse a JSON-formatted order request string or file reference.

    + + +

    Parameters:

    + + + + + + + + + + + + + + + + + +
    NameTypeDescriptionDefault
    + value + + str + +
    +

    JSON object string, or '@path' to read JSON from a file.

    +
    +
    + required +
    + + +

    Returns:

    + + + + + + + + + + + + + +
    TypeDescription
    + dict[str, Any] + +
    +

    Parsed request dictionary.

    +
    +
    + + +

    Raises:

    + + + + + + + + + + + + + +
    TypeDescription
    + ValueError + +
    +

    If the request file cannot be read or the value is not a +JSON object.

    +
    +
    + + +
    + Source code in mt5cli/utils.py +
    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 + + +

    +
    parse_tick_flags(value: str) -> int
    +
    + +
    + +

    Parse tick flags string or integer value.

    + + +

    Parameters:

    + + + + + + + + + + + + + + + + + +
    NameTypeDescriptionDefault
    + value + + str + +
    +

    Tick flag name (ALL, INFO, TRADE) or integer value.

    +
    +
    + required +
    + + +

    Returns:

    + + + + + + + + + + + + + +
    TypeDescription
    + int + +
    +

    Integer tick flag value.

    +
    +
    + + +

    Raises:

    + + + + + + + + + + + + + +
    TypeDescription
    + ValueError + +
    +

    If the flag is invalid.

    +
    +
    + + +
    + Source code in mt5cli/utils.py +
    def parse_tick_flags(value: str) -> int:
    +    """Parse tick flags string or integer value.
    +
    +    Args:
    +        value: Tick flag name (ALL, INFO, TRADE) or integer value.
    +
    +    Returns:
    +        Integer tick flag value.
    +
    +    Raises:
    +        ValueError: If the flag is invalid.
    +    """
    +    upper = value.upper()
    +    if upper in TICK_FLAG_MAP:
    +        return TICK_FLAG_MAP[upper]
    +    try:
    +        return int(value)
    +    except ValueError:
    +        valid = ", ".join(TICK_FLAG_MAP)
    +        msg = f"Invalid tick flags: '{value}'. Use one of: {valid}, or an integer."
    +        raise ValueError(msg) from None
    +
    +
    +
    + +
    + +
    + + +

    + parse_timeframe + + +

    +
    parse_timeframe(value: str) -> int
    +
    + +
    + +

    Parse a timeframe string or integer value.

    + + +

    Parameters:

    + + + + + + + + + + + + + + + + + +
    NameTypeDescriptionDefault
    + value + + str + +
    +

    Timeframe name (e.g., 'M1', 'H1', 'D1') or integer value.

    +
    +
    + required +
    + + +

    Returns:

    + + + + + + + + + + + + + +
    TypeDescription
    + int + +
    +

    Integer timeframe value.

    +
    +
    + + +

    Raises:

    + + + + + + + + + + + + + +
    TypeDescription
    + ValueError + +
    +

    If the timeframe is invalid.

    +
    +
    + + +
    + Source code in mt5cli/utils.py +
    def parse_timeframe(value: str) -> 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.
    +    """
    +    upper = value.upper()
    +    if upper in TIMEFRAME_MAP:
    +        return TIMEFRAME_MAP[upper]
    +    try:
    +        return int(value)
    +    except ValueError:
    +        valid = ", ".join(TIMEFRAME_MAP)
    +        msg = f"Invalid timeframe: '{value}'. Use one of: {valid}, or an integer."
    +        raise ValueError(msg) from None
    +
    +
    +
    + +
    + + + +
    + +
    + +
    +
    +
    + +
    +
    +

    Documentation built with MkDocs.

    +
    + + + + + + + + + diff --git a/index.html b/index.html index 22d65ff..4536461 100644 --- a/index.html +++ b/index.html @@ -49,6 +49,14 @@
  • CLI
  • + +
  • + SDK +
  • + +
  • + Utils +
  • @@ -105,6 +113,10 @@ +
    -
    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
    +
    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:

    @@ -426,7 +471,9 @@

    API Reference

    Browse the API documentation for detailed module information:

      -
    • CLI Module - CLI application with export commands and utility functions
    • +
    • 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

    This project follows strict code quality standards:

    @@ -519,5 +566,5 @@ diff --git a/objects.inv b/objects.inv index 44181120f50268e434e6ea99e392bc4d2ea5c721..b93d308f0de9d8e12cbe3326c6de8300e4a08b1c 100644 GIT binary patch delta 1013 zcmVWcN_c_N&rmn&?@fPapI!&rCma9qe_9INGl#_20S|k@Tdb&8v z4!Y{IuKoJu_#YaEyv!9z@|f2SahZoI;km^`lQ$;YGD#y6@_#%|b^sGi-k4P1HJkCM zOxfgePgZ}sI6K!g-i^NrHnT-QHh)(^O+-}DV@stwB@&FuOY zna=&&d#G2J=zrKPg6Z0auXqR0%&hy}zTs$5G>zI-Ax~2lD)Lw@G8b<^?}(`yiks!@ z939i}bVjpduLT#1)Lo4Q%^1+JhiRtA5s`?|R07BK&TtVi0fnlas|XW<3n;*MJ0<{& zlhGsxdS+BSF-5kVKLLsT7)kiZLL4Dk9$^6JG!|SYwSNSv7gRAxV!<;sK&rM-kf8aF z0f{PAv=V|bm2`l&Y|B&3(QXk$CE)ctV9=2(CbA@_sE*a0L9NLFz)bH;wWDeUKs^xJ z%o)B*w5*CZV%cyuE1j@e^|m6&Zcmvk`!hM}cR+MA%Q_BtwFr|Hs$XrSG5f@n^Xciv zo@&ga)PMCo8$;L}_BjHLktHLUOuo(}ZQvIxwIWfdh2>hBTH+H0u9pz8AHL8?= zQ}+1nW??BIFgCWV2lE(AwHOQMZj2S!U;}HJIDhIeSbC4r!!`3L?%wU8Qg;*{E*CMl zt#$-@IQ4$4svI@2*MBB-)464tG=$JJJw&q+r9<$tK4Y>Y<5zMs2zMZZVZBr&PU%jfEL)h-G-H^0y-Vqq z$bS%wkGhV578hGx!YLwxS_W;drrTT{*z9*!?}BjL zedisW<(dBo)4f=L4uDwyr3*~&-2^`$Zf=o{c)@yox5h%V<@65A{PEYz*%I16^LryW zC#P-4qNRfrV0yFQgwp+urWke-RGD_QSe7f% zLG$*LlQu2TH6stc*#Ae7l=#aQzv<2-@tF;~@7C302eZ#JHJHoz?()<5?BdKGHOV|( zi*>#ba{ap$6HzNvr}Xi20GyP%Qz86cnmm|*&hKOmstXgS5Pv;`bG`=80lh-t=+Wp6 zMV~j~DdrR?#lL8iv@FGP&WN65XP3Gdq-8Cb4BC2Xt zae#c8tvLE$X|>Fkl$=&04kKpHTSYpuZ}o`|TjmnUpWu2fGbsN!9wv%|g~!eyd?jF& z_<1L8*VGAL=YLl>GAq*STQ(sVX-U#AL{_EIbhvtALP~2l_9#u?xJllOy+#wa<^(bf zguvQ$9cYx#)icb*Ekwgpe< zu~nug#}Nd5E?Vki|?looqVQ z1}0{Ka|#C+%p{?%vcIrpIQt7VzPgd&a`zwr diff --git a/search/search_index.json b/search/search_index.json index 0333110..d5ced93 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 Command-line tool for MetaTrader 5 data export. Overview \u00b6 mt5cli is a CLI application that exports MetaTrader 5 trading data to multiple file formats. It is built on top of pdmt5 , a pandas-based data handler for MetaTrader 5. 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 Installation \u00b6 pip install mt5cli 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 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 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 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 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 . 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 and utility functions 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":"Command-line tool for MetaTrader 5 data export.","title":"mt5cli"},{"location":"#overview","text":"mt5cli is a CLI application that exports MetaTrader 5 trading data to multiple file formats. It is built on top of pdmt5 , a pandas-based data handler for MetaTrader 5.","title":"Overview"},{"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","title":"Features"},{"location":"#installation","text":"pip install mt5cli","title":"Installation"},{"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 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","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 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 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 .","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 and utility functions","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 contains the complete API documentation for mt5cli. Modules \u00b6 The mt5cli package consists of the following modules: CLI \u00b6 Command-line interface module providing typer-based commands for exporting MetaTrader 5 data to CSV, JSON, Parquet, and SQLite3 formats. Architecture Overview \u00b6 The package follows a simple architecture built on top of pdmt5: CLI Layer ( cli.py ): Typer application with subcommands for each data type, custom Click parameter types for datetime/timeframe/tick flags parsing, and format detection/export utilities. Data Layer (via pdmt5 ): Uses Mt5DataClient and Mt5Config from the pdmt5 package for all MetaTrader 5 data access. Usage Guidelines \u00b6 All modules follow these conventions: Type Safety : All functions include comprehensive type hints Error Handling : User-friendly error messages via typer Documentation : Google-style docstrings with examples Validation : Custom Click parameter types for input validation Quick Start \u00b6 # Export account information to CSV mt5cli -o account.csv account-info # Export EURUSD H1 rates to Parquet mt5cli -o rates.parquet rates-from --symbol EURUSD --timeframe H1 \\ --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 to SQLite3 with custom table name mt5cli -o data.db --table symbols symbols --group \"*USD*\" Python API \u00b6 from mt5cli import detect_format , export_dataframe import pandas as pd # Detect output format from file extension fmt = detect_format ( Path ( \"output.parquet\" )) # Returns \"parquet\" # Export a DataFrame df = pd . DataFrame ({ \"symbol\" : [ \"EURUSD\" ], \"bid\" : [ 1.1234 ]}) export_dataframe ( df , Path ( \"output.csv\" ), \"csv\" ) Examples \u00b6 See individual module pages for detailed usage examples and code samples.","title":"Overview"},{"location":"api/#api-reference","text":"This section contains the complete API documentation for mt5cli.","title":"API Reference"},{"location":"api/#modules","text":"The mt5cli package consists of the following modules:","title":"Modules"},{"location":"api/#cli","text":"Command-line interface module providing typer-based commands for exporting MetaTrader 5 data to CSV, JSON, Parquet, and SQLite3 formats.","title":"CLI"},{"location":"api/#architecture-overview","text":"The package follows a simple architecture built on top of pdmt5: CLI Layer ( cli.py ): Typer application with subcommands for each data type, custom Click parameter types for datetime/timeframe/tick flags parsing, and format detection/export utilities. Data Layer (via pdmt5 ): Uses Mt5DataClient and Mt5Config from the pdmt5 package for all MetaTrader 5 data access.","title":"Architecture Overview"},{"location":"api/#usage-guidelines","text":"All modules follow these conventions: Type Safety : All functions include comprehensive type hints Error Handling : User-friendly error messages via typer Documentation : Google-style docstrings with examples Validation : Custom Click parameter types for input validation","title":"Usage Guidelines"},{"location":"api/#quick-start","text":"# Export account information to CSV mt5cli -o account.csv account-info # Export EURUSD H1 rates to Parquet mt5cli -o rates.parquet rates-from --symbol EURUSD --timeframe H1 \\ --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 to SQLite3 with custom table name mt5cli -o data.db --table symbols symbols --group \"*USD*\"","title":"Quick Start"},{"location":"api/#python-api","text":"from mt5cli import detect_format , export_dataframe import pandas as pd # Detect output format from file extension fmt = detect_format ( Path ( \"output.parquet\" )) # Returns \"parquet\" # Export a DataFrame df = pd . DataFrame ({ \"symbol\" : [ \"EURUSD\" ], \"bid\" : [ 1.1234 ]}) export_dataframe ( df , Path ( \"output.csv\" ), \"csv\" )","title":"Python API"},{"location":"api/#examples","text":"See individual module pages for detailed usage examples and code samples.","title":"Examples"},{"location":"api/cli/","text":"CLI Module \u00b6 mt5cli.cli \u00b6 Command-line interface for MetaTrader 5 data export. 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 ] = { \"ALL\" : 1 , \"INFO\" : 2 , \"TRADE\" : 4 , } TIMEFRAME_MAP module-attribute \u00b6 TIMEFRAME_MAP : dict [ str , int ] = { \"M1\" : 1 , \"M2\" : 2 , \"M3\" : 3 , \"M4\" : 4 , \"M5\" : 5 , \"M6\" : 6 , \"M10\" : 10 , \"M12\" : 12 , \"M15\" : 15 , \"M20\" : 20 , \"M30\" : 30 , \"H1\" : 16385 , \"H2\" : 16386 , \"H3\" : 16387 , \"H4\" : 16388 , \"H6\" : 16390 , \"H8\" : 16392 , \"H12\" : 16396 , \"D1\" : 16408 , \"W1\" : 32769 , \"MN1\" : 49153 , } TIMEFRAME_TYPE module-attribute \u00b6 TIMEFRAME_TYPE = _TimeframeType () 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__ ) 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' 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' account_info \u00b6 account_info ( ctx : Context ) -> None Export account information. Source code in mt5cli/cli.py 723 724 725 726 @app . command () def account_info ( ctx : typer . Context ) -> None : \"\"\"Export account information.\"\"\" _execute_export ( ctx , lambda c : c . account_info_as_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).\" , ), ] = 1 , 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 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 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 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 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 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 @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).\" , ), ] = 1 , 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 ) client = Mt5DataClient ( config = export_ctx . config ) client . initialize_and_login_mt5 () try : with sqlite3 . connect ( export_ctx . output ) as conn : conn . execute ( \"PRAGMA journal_mode=WAL\" ) conn . execute ( \"PRAGMA synchronous=NORMAL\" ) written_tables , written_columns = _write_collected_datasets ( conn , client , symbol , datasets , timeframe , flags , date_from , date_to , if_exists , ) _create_collect_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 datasets )), len ( symbol ), export_ctx . output , ) finally : client . shutdown () 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/cli.py 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 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/cli.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\" : with sqlite3 . connect ( output_path ) as conn : df . to_sql ( # type: ignore[reportUnknownMemberType] table_name , conn , if_exists = \"replace\" , index = False , ) else : msg = f \"Unsupported output format: { output_format } \" raise ValueError ( msg ) 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 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 @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.\"\"\" _execute_export ( ctx , lambda c : c . history_deals_get_as_df ( 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 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 @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.\"\"\" _execute_export ( ctx , lambda c : c . history_orders_get_as_df ( 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 864 865 866 867 @app . command () def last_error ( ctx : typer . Context ) -> None : \"\"\"Export the last error information.\"\"\" _execute_export ( ctx , lambda c : c . last_error_as_df ()) main \u00b6 main () -> None Run the mt5cli CLI. Source code in mt5cli/cli.py 1450 1451 1452 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 882 883 884 885 886 887 888 889 890 891 @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.\"\"\" _execute_export ( ctx , lambda c : c . market_book_get_as_df ( symbol = symbol ), ) 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 894 895 896 897 898 899 900 901 902 903 904 905 906 @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.\"\"\" _execute_export ( ctx , lambda c : c . order_check_as_df ( request = 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 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 @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\" ) _execute_export ( ctx , lambda c : c . order_send_as_df ( request = 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 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 @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.\"\"\" _execute_export ( ctx , lambda c : c . orders_get_as_df ( symbol = symbol , group = group , ticket = ticket , ), ) 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/cli.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/cli.py 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 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 : str ) -> int Parse tick flags string or integer value. Parameters: Name Type Description Default value str Tick flag name (ALL, INFO, TRADE) or integer value. required Returns: Type Description int Integer tick flag value. Raises: Type Description ValueError If the flag is invalid. Source code in mt5cli/cli.py 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 def parse_tick_flags ( value : str ) -> int : \"\"\"Parse tick flags string or integer value. Args: value: Tick flag name (ALL, INFO, TRADE) or integer value. Returns: Integer tick flag value. Raises: ValueError: If the flag is invalid. \"\"\" upper = value . upper () if upper in TICK_FLAG_MAP : return TICK_FLAG_MAP [ upper ] try : return int ( value ) except ValueError : valid = \", \" . join ( TICK_FLAG_MAP ) msg = f \"Invalid tick flags: ' { value } '. Use one of: { valid } , or an integer.\" raise ValueError ( msg ) from None parse_timeframe \u00b6 parse_timeframe ( value : str ) -> int Parse a timeframe string or integer value. Parameters: Name Type Description Default value str 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/cli.py 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 def parse_timeframe ( value : str ) -> 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. \"\"\" upper = value . upper () if upper in TIMEFRAME_MAP : return TIMEFRAME_MAP [ upper ] try : return int ( value ) except ValueError : valid = \", \" . join ( TIMEFRAME_MAP ) msg = f \"Invalid timeframe: ' { value } '. Use one of: { valid } , or an integer.\" raise ValueError ( msg ) from None 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 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 @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.\"\"\" _execute_export ( ctx , lambda c : c . positions_get_as_df ( 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 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 @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.\"\"\" _execute_export ( ctx , lambda c : c . copy_rates_from_as_df ( symbol = symbol , timeframe = timeframe , date_from = date_from , count = 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 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 @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.\"\"\" _execute_export ( ctx , lambda c : c . copy_rates_from_pos_as_df ( symbol = symbol , timeframe = timeframe , start_pos = start_pos , count = 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 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 @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.\"\"\" _execute_export ( ctx , lambda c : c . copy_rates_range_as_df ( symbol = symbol , timeframe = timeframe , date_from = date_from , date_to = date_to , ), ) symbol_info \u00b6 symbol_info ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], ) -> None Export symbol details. Source code in mt5cli/cli.py 750 751 752 753 754 755 756 757 758 759 @app . command () def symbol_info ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], ) -> None : \"\"\"Export symbol details.\"\"\" _execute_export ( ctx , lambda c : c . symbol_info_as_df ( symbol = 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 870 871 872 873 874 875 876 877 878 879 @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.\"\"\" _execute_export ( ctx , lambda c : c . symbol_info_tick_as_df ( symbol = 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 735 736 737 738 739 740 741 742 743 744 745 746 747 @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.\"\"\" _execute_export ( ctx , lambda c : c . symbols_get_as_df ( group = group ), ) terminal_info \u00b6 terminal_info ( ctx : Context ) -> None Export terminal information. Source code in mt5cli/cli.py 729 730 731 732 @app . command () def terminal_info ( ctx : typer . Context ) -> None : \"\"\"Export terminal information.\"\"\" _execute_export ( ctx , lambda c : c . terminal_info_as_df ()) 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 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 @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.\"\"\" _execute_export ( ctx , lambda c : c . copy_ticks_from_as_df ( symbol = symbol , date_from = date_from , count = count , flags = 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 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 @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.\"\"\" _execute_export ( ctx , lambda c : c . copy_ticks_range_as_df ( symbol = symbol , date_from = date_from , date_to = date_to , flags = flags , ), ) version \u00b6 version ( ctx : Context ) -> None Export MetaTrader5 version information. Source code in mt5cli/cli.py 858 859 860 861 @app . command () def version ( ctx : typer . Context ) -> None : \"\"\"Export MetaTrader5 version information.\"\"\" _execute_export ( ctx , lambda c : c . version_as_df ())","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.DATETIME_TYPE","text":"DATETIME_TYPE = _DateTimeType ()","title":"DATETIME_TYPE"},{"location":"api/cli/#mt5cli.cli.REQUEST_TYPE","text":"REQUEST_TYPE = _RequestType ()","title":"REQUEST_TYPE"},{"location":"api/cli/#mt5cli.cli.TICK_FLAGS_TYPE","text":"TICK_FLAGS_TYPE = _TickFlagsType ()","title":"TICK_FLAGS_TYPE"},{"location":"api/cli/#mt5cli.cli.TICK_FLAG_MAP","text":"TICK_FLAG_MAP : dict [ str , int ] = { \"ALL\" : 1 , \"INFO\" : 2 , \"TRADE\" : 4 , }","title":"TICK_FLAG_MAP"},{"location":"api/cli/#mt5cli.cli.TIMEFRAME_MAP","text":"TIMEFRAME_MAP : dict [ str , int ] = { \"M1\" : 1 , \"M2\" : 2 , \"M3\" : 3 , \"M4\" : 4 , \"M5\" : 5 , \"M6\" : 6 , \"M10\" : 10 , \"M12\" : 12 , \"M15\" : 15 , \"M20\" : 20 , \"M30\" : 30 , \"H1\" : 16385 , \"H2\" : 16386 , \"H3\" : 16387 , \"H4\" : 16388 , \"H6\" : 16390 , \"H8\" : 16392 , \"H12\" : 16396 , \"D1\" : 16408 , \"W1\" : 32769 , \"MN1\" : 49153 , }","title":"TIMEFRAME_MAP"},{"location":"api/cli/#mt5cli.cli.TIMEFRAME_TYPE","text":"TIMEFRAME_TYPE = _TimeframeType ()","title":"TIMEFRAME_TYPE"},{"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.Dataset","text":"Bases: StrEnum Datasets supported by the collect-history command.","title":"Dataset"},{"location":"api/cli/#mt5cli.cli.Dataset.history_deals","text":"history_deals = 'history-deals'","title":"history_deals"},{"location":"api/cli/#mt5cli.cli.Dataset.history_orders","text":"history_orders = 'history-orders'","title":"history_orders"},{"location":"api/cli/#mt5cli.cli.Dataset.rates","text":"rates = 'rates'","title":"rates"},{"location":"api/cli/#mt5cli.cli.Dataset.ticks","text":"ticks = 'ticks'","title":"ticks"},{"location":"api/cli/#mt5cli.cli.IfExists","text":"Bases: StrEnum SQLite table conflict behavior for the collect-history command.","title":"IfExists"},{"location":"api/cli/#mt5cli.cli.IfExists.APPEND","text":"APPEND = 'append'","title":"APPEND"},{"location":"api/cli/#mt5cli.cli.IfExists.FAIL","text":"FAIL = 'fail'","title":"FAIL"},{"location":"api/cli/#mt5cli.cli.IfExists.REPLACE","text":"REPLACE = 'replace'","title":"REPLACE"},{"location":"api/cli/#mt5cli.cli.LogLevel","text":"Bases: StrEnum Logging verbosity levels.","title":"LogLevel"},{"location":"api/cli/#mt5cli.cli.LogLevel.DEBUG","text":"DEBUG = 'DEBUG'","title":"DEBUG"},{"location":"api/cli/#mt5cli.cli.LogLevel.ERROR","text":"ERROR = 'ERROR'","title":"ERROR"},{"location":"api/cli/#mt5cli.cli.LogLevel.INFO","text":"INFO = 'INFO'","title":"INFO"},{"location":"api/cli/#mt5cli.cli.LogLevel.WARNING","text":"WARNING = 'WARNING'","title":"WARNING"},{"location":"api/cli/#mt5cli.cli.OutputFormat","text":"Bases: StrEnum Supported output file formats.","title":"OutputFormat"},{"location":"api/cli/#mt5cli.cli.OutputFormat.csv","text":"csv = 'csv'","title":"csv"},{"location":"api/cli/#mt5cli.cli.OutputFormat.json","text":"json = 'json'","title":"json"},{"location":"api/cli/#mt5cli.cli.OutputFormat.parquet","text":"parquet = 'parquet'","title":"parquet"},{"location":"api/cli/#mt5cli.cli.OutputFormat.sqlite3","text":"sqlite3 = 'sqlite3'","title":"sqlite3"},{"location":"api/cli/#mt5cli.cli.account_info","text":"account_info ( ctx : Context ) -> None Export account information. Source code in mt5cli/cli.py 723 724 725 726 @app . command () def account_info ( ctx : typer . Context ) -> None : \"\"\"Export account information.\"\"\" _execute_export ( ctx , lambda c : c . account_info_as_df ())","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).\" , ), ] = 1 , 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 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 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 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 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 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 @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).\" , ), ] = 1 , 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 ) client = Mt5DataClient ( config = export_ctx . config ) client . initialize_and_login_mt5 () try : with sqlite3 . connect ( export_ctx . output ) as conn : conn . execute ( \"PRAGMA journal_mode=WAL\" ) conn . execute ( \"PRAGMA synchronous=NORMAL\" ) written_tables , written_columns = _write_collected_datasets ( conn , client , symbol , datasets , timeframe , flags , date_from , date_to , if_exists , ) _create_collect_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 datasets )), len ( symbol ), export_ctx . output , ) finally : client . shutdown ()","title":"collect_history"},{"location":"api/cli/#mt5cli.cli.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/cli.py 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 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/cli/#mt5cli.cli.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/cli.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\" : with sqlite3 . connect ( output_path ) as conn : df . to_sql ( # type: ignore[reportUnknownMemberType] table_name , conn , if_exists = \"replace\" , index = False , ) else : msg = f \"Unsupported output format: { output_format } \" raise ValueError ( msg )","title":"export_dataframe"},{"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 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 @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.\"\"\" _execute_export ( ctx , lambda c : c . history_deals_get_as_df ( 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 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 @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.\"\"\" _execute_export ( ctx , lambda c : c . history_orders_get_as_df ( 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 864 865 866 867 @app . command () def last_error ( ctx : typer . Context ) -> None : \"\"\"Export the last error information.\"\"\" _execute_export ( ctx , lambda c : c . last_error_as_df ())","title":"last_error"},{"location":"api/cli/#mt5cli.cli.main","text":"main () -> None Run the mt5cli CLI. Source code in mt5cli/cli.py 1450 1451 1452 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 882 883 884 885 886 887 888 889 890 891 @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.\"\"\" _execute_export ( ctx , lambda c : c . market_book_get_as_df ( symbol = symbol ), )","title":"market_book"},{"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 894 895 896 897 898 899 900 901 902 903 904 905 906 @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.\"\"\" _execute_export ( ctx , lambda c : c . order_check_as_df ( request = 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 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 @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\" ) _execute_export ( ctx , lambda c : c . order_send_as_df ( request = 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 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 @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.\"\"\" _execute_export ( ctx , lambda c : c . orders_get_as_df ( symbol = symbol , group = group , ticket = ticket , ), )","title":"orders"},{"location":"api/cli/#mt5cli.cli.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/cli.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/cli/#mt5cli.cli.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/cli.py 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 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/cli/#mt5cli.cli.parse_tick_flags","text":"parse_tick_flags ( value : str ) -> int Parse tick flags string or integer value. Parameters: Name Type Description Default value str Tick flag name (ALL, INFO, TRADE) or integer value. required Returns: Type Description int Integer tick flag value. Raises: Type Description ValueError If the flag is invalid. Source code in mt5cli/cli.py 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 def parse_tick_flags ( value : str ) -> int : \"\"\"Parse tick flags string or integer value. Args: value: Tick flag name (ALL, INFO, TRADE) or integer value. Returns: Integer tick flag value. Raises: ValueError: If the flag is invalid. \"\"\" upper = value . upper () if upper in TICK_FLAG_MAP : return TICK_FLAG_MAP [ upper ] try : return int ( value ) except ValueError : valid = \", \" . join ( TICK_FLAG_MAP ) msg = f \"Invalid tick flags: ' { value } '. Use one of: { valid } , or an integer.\" raise ValueError ( msg ) from None","title":"parse_tick_flags"},{"location":"api/cli/#mt5cli.cli.parse_timeframe","text":"parse_timeframe ( value : str ) -> int Parse a timeframe string or integer value. Parameters: Name Type Description Default value str 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/cli.py 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 def parse_timeframe ( value : str ) -> 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. \"\"\" upper = value . upper () if upper in TIMEFRAME_MAP : return TIMEFRAME_MAP [ upper ] try : return int ( value ) except ValueError : valid = \", \" . join ( TIMEFRAME_MAP ) msg = f \"Invalid timeframe: ' { value } '. Use one of: { valid } , or an integer.\" raise ValueError ( msg ) from None","title":"parse_timeframe"},{"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 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 @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.\"\"\" _execute_export ( ctx , lambda c : c . positions_get_as_df ( 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 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 @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.\"\"\" _execute_export ( ctx , lambda c : c . copy_rates_from_as_df ( symbol = symbol , timeframe = timeframe , date_from = date_from , count = 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 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 @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.\"\"\" _execute_export ( ctx , lambda c : c . copy_rates_from_pos_as_df ( symbol = symbol , timeframe = timeframe , start_pos = start_pos , count = 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 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 @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.\"\"\" _execute_export ( ctx , lambda c : c . copy_rates_range_as_df ( symbol = symbol , timeframe = timeframe , date_from = date_from , date_to = date_to , ), )","title":"rates_range"},{"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 750 751 752 753 754 755 756 757 758 759 @app . command () def symbol_info ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], ) -> None : \"\"\"Export symbol details.\"\"\" _execute_export ( ctx , lambda c : c . symbol_info_as_df ( symbol = 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 870 871 872 873 874 875 876 877 878 879 @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.\"\"\" _execute_export ( ctx , lambda c : c . symbol_info_tick_as_df ( symbol = 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 735 736 737 738 739 740 741 742 743 744 745 746 747 @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.\"\"\" _execute_export ( ctx , lambda c : c . symbols_get_as_df ( 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 729 730 731 732 @app . command () def terminal_info ( ctx : typer . Context ) -> None : \"\"\"Export terminal information.\"\"\" _execute_export ( ctx , lambda c : c . terminal_info_as_df ())","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 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 @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.\"\"\" _execute_export ( ctx , lambda c : c . copy_ticks_from_as_df ( symbol = symbol , date_from = date_from , count = count , flags = 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 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 @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.\"\"\" _execute_export ( ctx , lambda c : c . copy_ticks_range_as_df ( symbol = symbol , date_from = date_from , date_to = date_to , flags = flags , ), )","title":"ticks_range"},{"location":"api/cli/#mt5cli.cli.version","text":"version ( ctx : Context ) -> None Export MetaTrader5 version information. Source code in mt5cli/cli.py 858 859 860 861 @app . command () def version ( ctx : typer . Context ) -> None : \"\"\"Export MetaTrader5 version information.\"\"\" _execute_export ( ctx , lambda c : c . version_as_df ())","title":"version"}]} \ 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 Command-line tool for MetaTrader 5 data export. Overview \u00b6 mt5cli is a CLI application that exports MetaTrader 5 trading data to multiple file formats. It is built on top of pdmt5 , a pandas-based data handler for MetaTrader 5. 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 Installation \u00b6 pip install mt5cli Programmatic usage / SDK usage \u00b6 mt5cli can be used as a small Python SDK for read-only MetaTrader 5 data collection. SDK functions return pandas DataFrames without writing files. Use export_dataframe when you need to persist results. from datetime import UTC , datetime from pathlib import Path from mt5cli import Mt5CliClient , collect_history , copy_rates_range , export_dataframe # One-off fetch with module-level helpers rates = copy_rates_range ( \"EURUSD\" , timeframe = \"H1\" , date_from = \"2024-01-01\" , date_to = \"2024-02-01\" , ) export_dataframe ( rates , Path ( \"rates.csv\" ), \"csv\" ) # Reuse one MT5 connection for multiple calls with Mt5CliClient ( login = 12345 , password = \"secret\" , server = \"Broker-Demo\" ) as client : account = client . account_info () positions = client . positions () # Bulk SQLite collection (same behavior as the collect-history CLI command) collect_history ( Path ( \"history.db\" ), symbols = [ \"EURUSD\" , \"GBPUSD\" ], date_from = datetime ( 2024 , 1 , 1 , tzinfo = UTC ), date_to = datetime ( 2024 , 2 , 1 , tzinfo = UTC ), timeframe = \"M1\" , flags = \"ALL\" , with_views = True , ) Timeframes, tick flags, and ISO 8601 date strings are accepted wherever noted in the SDK API. 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 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 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 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 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 . 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":"Command-line tool for MetaTrader 5 data export.","title":"mt5cli"},{"location":"#overview","text":"mt5cli is a CLI application that exports MetaTrader 5 trading data to multiple file formats. It is built on top of pdmt5 , a pandas-based data handler for MetaTrader 5.","title":"Overview"},{"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","title":"Features"},{"location":"#installation","text":"pip install mt5cli","title":"Installation"},{"location":"#programmatic-usage-sdk-usage","text":"mt5cli can be used as a small Python SDK for read-only MetaTrader 5 data collection. SDK functions return pandas DataFrames without writing files. Use export_dataframe when you need to persist results. from datetime import UTC , datetime from pathlib import Path from mt5cli import Mt5CliClient , collect_history , copy_rates_range , export_dataframe # One-off fetch with module-level helpers rates = copy_rates_range ( \"EURUSD\" , timeframe = \"H1\" , date_from = \"2024-01-01\" , date_to = \"2024-02-01\" , ) export_dataframe ( rates , Path ( \"rates.csv\" ), \"csv\" ) # Reuse one MT5 connection for multiple calls with Mt5CliClient ( login = 12345 , password = \"secret\" , server = \"Broker-Demo\" ) as client : account = client . account_info () positions = client . positions () # Bulk SQLite collection (same behavior as the collect-history CLI command) collect_history ( Path ( \"history.db\" ), symbols = [ \"EURUSD\" , \"GBPUSD\" ], date_from = datetime ( 2024 , 1 , 1 , tzinfo = UTC ), date_to = datetime ( 2024 , 2 , 1 , tzinfo = UTC ), timeframe = \"M1\" , flags = \"ALL\" , with_views = True , ) Timeframes, tick flags, and ISO 8601 date strings are accepted wherever noted in the SDK API.","title":"Programmatic usage / SDK usage"},{"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 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","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 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 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 .","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 contains the complete API documentation for mt5cli. Modules \u00b6 The mt5cli package consists of the following modules: CLI \u00b6 Command-line interface module providing typer-based commands for exporting MetaTrader 5 data to CSV, JSON, Parquet, and SQLite3 formats. Utils \u00b6 Utility module providing constants, enums, Click parameter types, and helper functions for parsing and exporting data. SDK \u00b6 Programmatic SDK for read-only MetaTrader 5 data collection. Returns pandas DataFrames and provides collect_history for SQLite bulk collection. Architecture Overview \u00b6 The package follows a simple architecture built on top of pdmt5: CLI Layer ( cli.py ): Typer application with subcommands that delegate to the SDK and export results. SDK Layer ( sdk.py ): Read-only data access functions, Mt5CliClient , and collect_history orchestration. Utils Layer ( utils.py ): Constants, enums, custom Click parameter types, parsing helpers, and format detection/export utilities. Data Layer (via pdmt5 ): Uses Mt5DataClient and Mt5Config from the pdmt5 package for all MetaTrader 5 data access. Usage Guidelines \u00b6 All modules follow these conventions: Type Safety : All functions include comprehensive type hints Error Handling : User-friendly error messages via typer Documentation : Google-style docstrings with examples Validation : Custom Click parameter types for input validation Quick Start \u00b6 # Export account information to CSV mt5cli -o account.csv account-info # Export EURUSD H1 rates to Parquet mt5cli -o rates.parquet rates-from --symbol EURUSD --timeframe H1 \\ --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 to SQLite3 with custom table name mt5cli -o data.db --table symbols symbols --group \"*USD*\" Python API \u00b6 from datetime import UTC , datetime from pathlib import Path from mt5cli import ( Mt5CliClient , collect_history , copy_rates_range , detect_format , export_dataframe , ) # Fetch rates programmatically rates = copy_rates_range ( \"EURUSD\" , timeframe = \"H1\" , date_from = \"2024-01-01\" , date_to = \"2024-02-01\" , ) # Detect output format from file extension fmt = detect_format ( Path ( \"output.parquet\" )) # Returns \"parquet\" # Export a DataFrame export_dataframe ( rates , Path ( \"output.csv\" ), \"csv\" ) # Collect history into SQLite collect_history ( Path ( \"history.db\" ), symbols = [ \"EURUSD\" ], date_from = datetime ( 2024 , 1 , 1 , tzinfo = UTC ), date_to = datetime ( 2024 , 2 , 1 , tzinfo = UTC ), ) Examples \u00b6 See individual module pages for detailed usage examples and code samples.","title":"Overview"},{"location":"api/#api-reference","text":"This section contains the complete API documentation for mt5cli.","title":"API Reference"},{"location":"api/#modules","text":"The mt5cli package consists of the following modules:","title":"Modules"},{"location":"api/#cli","text":"Command-line interface module providing typer-based commands for exporting MetaTrader 5 data to CSV, JSON, Parquet, and SQLite3 formats.","title":"CLI"},{"location":"api/#utils","text":"Utility module providing constants, enums, Click parameter types, and helper functions for parsing and exporting data.","title":"Utils"},{"location":"api/#sdk","text":"Programmatic SDK for read-only MetaTrader 5 data collection. Returns pandas DataFrames and provides collect_history for SQLite bulk collection.","title":"SDK"},{"location":"api/#architecture-overview","text":"The package follows a simple architecture built on top of pdmt5: CLI Layer ( cli.py ): Typer application with subcommands that delegate to the SDK and export results. SDK Layer ( sdk.py ): Read-only data access functions, Mt5CliClient , and collect_history orchestration. Utils Layer ( utils.py ): Constants, enums, custom Click parameter types, parsing helpers, and format detection/export utilities. Data Layer (via pdmt5 ): Uses Mt5DataClient and Mt5Config from the pdmt5 package for all MetaTrader 5 data access.","title":"Architecture Overview"},{"location":"api/#usage-guidelines","text":"All modules follow these conventions: Type Safety : All functions include comprehensive type hints Error Handling : User-friendly error messages via typer Documentation : Google-style docstrings with examples Validation : Custom Click parameter types for input validation","title":"Usage Guidelines"},{"location":"api/#quick-start","text":"# Export account information to CSV mt5cli -o account.csv account-info # Export EURUSD H1 rates to Parquet mt5cli -o rates.parquet rates-from --symbol EURUSD --timeframe H1 \\ --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 to SQLite3 with custom table name mt5cli -o data.db --table symbols symbols --group \"*USD*\"","title":"Quick Start"},{"location":"api/#python-api","text":"from datetime import UTC , datetime from pathlib import Path from mt5cli import ( Mt5CliClient , collect_history , copy_rates_range , detect_format , export_dataframe , ) # Fetch rates programmatically rates = copy_rates_range ( \"EURUSD\" , timeframe = \"H1\" , date_from = \"2024-01-01\" , date_to = \"2024-02-01\" , ) # Detect output format from file extension fmt = detect_format ( Path ( \"output.parquet\" )) # Returns \"parquet\" # Export a DataFrame export_dataframe ( rates , Path ( \"output.csv\" ), \"csv\" ) # Collect history into SQLite collect_history ( Path ( \"history.db\" ), symbols = [ \"EURUSD\" ], date_from = datetime ( 2024 , 1 , 1 , tzinfo = UTC ), date_to = datetime ( 2024 , 2 , 1 , tzinfo = UTC ), )","title":"Python API"},{"location":"api/#examples","text":"See individual module pages for detailed usage examples and code samples.","title":"Examples"},{"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 303 304 305 306 @app . command () def account_info ( ctx : typer . Context ) -> None : \"\"\"Export account information.\"\"\" _execute_export ( ctx , _sdk_client ( ctx ) . 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).\" , ), ] = 1 , 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 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 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 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 @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).\" , ), ] = 1 , 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 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 @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.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : 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 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 @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.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : 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 436 437 438 439 @app . command () def last_error ( ctx : typer . Context ) -> None : \"\"\"Export the last error information.\"\"\" _execute_export ( ctx , _sdk_client ( ctx ) . last_error ) main \u00b6 main () -> None Run the mt5cli CLI. Source code in mt5cli/cli.py 610 611 612 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 452 453 454 455 456 457 458 459 @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.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . market_book ( symbol )) 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 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 @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_ctx = _get_export_context ( ctx ) def _fetch () -> pd . DataFrame : return sdk . _run_with_client ( # noqa: SLF001 # pyright: ignore[reportPrivateUsage] export_ctx . config , lambda c : c . order_check_as_df ( request = request ), ) _execute_export ( ctx , _fetch ) 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 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 @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_ctx = _get_export_context ( ctx ) def _fetch () -> pd . DataFrame : return sdk . _run_with_client ( # noqa: SLF001 # pyright: ignore[reportPrivateUsage] export_ctx . config , lambda c : c . order_send_as_df ( request = request ), ) _execute_export ( ctx , _fetch ) 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 338 339 340 341 342 343 344 345 346 347 348 349 350 @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.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : 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 353 354 355 356 357 358 359 360 361 362 363 364 365 @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.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : 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 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 @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.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : 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 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 @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.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : 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 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 @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.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . copy_rates_range ( symbol , timeframe , date_from , date_to ), ) symbol_info \u00b6 symbol_info ( ctx : Context , symbol : Annotated [ str , Option ( help = \"Symbol name.\" )], ) -> None Export symbol details. Source code in mt5cli/cli.py 328 329 330 331 332 333 334 335 @app . command () def symbol_info ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], ) -> None : \"\"\"Export symbol details.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : 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 442 443 444 445 446 447 448 449 @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.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : 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 315 316 317 318 319 320 321 322 323 324 325 @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.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . symbols ( group = group )) terminal_info \u00b6 terminal_info ( ctx : Context ) -> None Export terminal information. Source code in mt5cli/cli.py 309 310 311 312 @app . command () def terminal_info ( ctx : typer . Context ) -> None : \"\"\"Export terminal information.\"\"\" _execute_export ( ctx , _sdk_client ( ctx ) . 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 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 @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.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : 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 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 @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.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . copy_ticks_range ( symbol , date_from , date_to , flags ), ) version \u00b6 version ( ctx : Context ) -> None Export MetaTrader5 version information. Source code in mt5cli/cli.py 430 431 432 433 @app . command () def version ( ctx : typer . Context ) -> None : \"\"\"Export MetaTrader5 version information.\"\"\" _execute_export ( ctx , _sdk_client ( ctx ) . 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 303 304 305 306 @app . command () def account_info ( ctx : typer . Context ) -> None : \"\"\"Export account information.\"\"\" _execute_export ( ctx , _sdk_client ( ctx ) . 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).\" , ), ] = 1 , 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 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 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 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 @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).\" , ), ] = 1 , 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 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 @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.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : 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 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 @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.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : 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 436 437 438 439 @app . command () def last_error ( ctx : typer . Context ) -> None : \"\"\"Export the last error information.\"\"\" _execute_export ( ctx , _sdk_client ( ctx ) . last_error )","title":"last_error"},{"location":"api/cli/#mt5cli.cli.main","text":"main () -> None Run the mt5cli CLI. Source code in mt5cli/cli.py 610 611 612 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 452 453 454 455 456 457 458 459 @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.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . market_book ( symbol ))","title":"market_book"},{"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 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 @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_ctx = _get_export_context ( ctx ) def _fetch () -> pd . DataFrame : return sdk . _run_with_client ( # noqa: SLF001 # pyright: ignore[reportPrivateUsage] export_ctx . config , lambda c : c . order_check_as_df ( request = request ), ) _execute_export ( ctx , _fetch )","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 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 @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_ctx = _get_export_context ( ctx ) def _fetch () -> pd . DataFrame : return sdk . _run_with_client ( # noqa: SLF001 # pyright: ignore[reportPrivateUsage] export_ctx . config , lambda c : c . order_send_as_df ( request = request ), ) _execute_export ( ctx , _fetch )","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 338 339 340 341 342 343 344 345 346 347 348 349 350 @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.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : 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 353 354 355 356 357 358 359 360 361 362 363 364 365 @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.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : 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 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 @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.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : 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 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 @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.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : 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 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 @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.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . copy_rates_range ( symbol , timeframe , date_from , date_to ), )","title":"rates_range"},{"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 328 329 330 331 332 333 334 335 @app . command () def symbol_info ( ctx : typer . Context , symbol : Annotated [ str , typer . Option ( help = \"Symbol name.\" )], ) -> None : \"\"\"Export symbol details.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : 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 442 443 444 445 446 447 448 449 @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.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : 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 315 316 317 318 319 320 321 322 323 324 325 @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.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : 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 309 310 311 312 @app . command () def terminal_info ( ctx : typer . Context ) -> None : \"\"\"Export terminal information.\"\"\" _execute_export ( ctx , _sdk_client ( ctx ) . 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 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 @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.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : 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 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 @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.\"\"\" client = _sdk_client ( ctx ) _execute_export ( ctx , lambda : client . copy_ticks_range ( symbol , date_from , date_to , flags ), )","title":"ticks_range"},{"location":"api/cli/#mt5cli.cli.version","text":"version ( ctx : Context ) -> None Export MetaTrader5 version information. Source code in mt5cli/cli.py 430 431 432 433 @app . command () def version ( ctx : typer . Context ) -> None : \"\"\"Export MetaTrader5 version information.\"\"\" _execute_export ( ctx , _sdk_client ( ctx ) . version )","title":"version"},{"location":"api/sdk/","text":"SDK Module \u00b6 mt5cli.sdk \u00b6 Programmatic SDK for MetaTrader 5 data collection. T module-attribute \u00b6 T = TypeVar ( 'T' ) __all__ module-attribute \u00b6 __all__ = [ \"Mt5CliClient\" , \"account_info\" , \"build_config\" , \"collect_history\" , \"copy_rates_from\" , \"copy_rates_from_pos\" , \"copy_rates_range\" , \"copy_ticks_from\" , \"copy_ticks_range\" , \"history_deals\" , \"history_orders\" , \"last_error\" , \"market_book\" , \"orders\" , \"positions\" , \"symbol_info\" , \"symbol_info_tick\" , \"symbols\" , \"terminal_info\" , \"version\" , ] logger module-attribute \u00b6 logger = getLogger ( __name__ ) Mt5CliClient \u00b6 Mt5CliClient ( * , path : str | None = None , login : int | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , config : Mt5Config | 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 config Mt5Config | None Optional pre-built Mt5Config (overrides other args). None Source code in mt5cli/sdk.py 152 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 def __init__ ( self , * , path : str | None = None , login : int | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , config : Mt5Config | 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. config: Optional pre-built ``Mt5Config`` (overrides other args). \"\"\" self . _config = config or build_config ( path = path , login = login , password = password , server = server , timeout = timeout , ) self . _client : Mt5DataClient | None = 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 186 187 188 189 190 191 192 193 194 195 196 197 198 199 def __enter__ ( self ) -> Self : \"\"\"Open a persistent MT5 connection for multiple calls. Returns: This client instance. \"\"\" client = Mt5DataClient ( config = self . _config ) try : client . initialize_and_login_mt5 () except Exception : client . shutdown () raise self . _client = 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 201 202 203 204 205 206 207 208 209 210 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 : self . _client . shutdown () self . _client = None account_info \u00b6 account_info () -> DataFrame Return account information. Source code in mt5cli/sdk.py 313 314 315 def account_info ( self ) -> pd . DataFrame : \"\"\"Return account information.\"\"\" return self . _fetch ( lambda c : c . account_info_as_df ()) 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 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 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 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 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 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 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 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 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 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 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 , ), ) 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 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 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 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 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 409 410 411 def last_error ( self ) -> pd . DataFrame : \"\"\"Return the last error information.\"\"\" return self . _fetch ( lambda c : c . last_error_as_df ()) market_book \u00b6 market_book ( symbol : str ) -> DataFrame Return market depth for a symbol. Source code in mt5cli/sdk.py 417 418 419 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 )) 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 329 330 331 332 333 334 335 336 337 338 339 340 341 342 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 344 345 346 347 348 349 350 351 352 353 354 355 356 357 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 , ), ) symbol_info \u00b6 symbol_info ( symbol : str ) -> DataFrame Return details for one symbol. Source code in mt5cli/sdk.py 325 326 327 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 413 414 415 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 321 322 323 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 317 318 319 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 405 406 407 def version ( self ) -> pd . DataFrame : \"\"\"Return MetaTrader5 version information.\"\"\" return self . _fetch ( lambda c : c . version_as_df ()) account_info \u00b6 account_info ( * , config : Mt5Config | None = None ) -> DataFrame Return account information. Source code in mt5cli/sdk.py 898 899 900 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 | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , ) -> Mt5Config Build an Mt5Config from optional connection parameters. Returns: Type Description Mt5Config Configured Mt5Config instance. Source code in mt5cli/sdk.py 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 def build_config ( * , path : str | None = None , login : int | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , ) -> Mt5Config : \"\"\"Build an ``Mt5Config`` from optional connection parameters. Returns: Configured ``Mt5Config`` instance. \"\"\" return Mt5Config ( path = path , 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 = 1 , 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 ). 1 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 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 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 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 = 1 , 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_collect_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 , ) 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 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 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 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 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 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 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 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 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 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 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 , ) 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 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 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 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 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 1003 1004 1005 def last_error ( * , config : Mt5Config | None = None ) -> pd . DataFrame : \"\"\"Return the last error information.\"\"\" return _make_client ( config = config ) . last_error () market_book \u00b6 market_book ( symbol : str , * , config : Mt5Config | None = None ) -> DataFrame Return market depth for a symbol. Source code in mt5cli/sdk.py 1017 1018 1019 1020 1021 1022 1023 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 ) 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 926 927 928 929 930 931 932 933 934 935 936 937 938 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 941 942 943 944 945 946 947 948 949 950 951 952 953 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 , ) symbol_info \u00b6 symbol_info ( symbol : str , * , config : Mt5Config | None = None ) -> DataFrame Return details for one symbol. Source code in mt5cli/sdk.py 917 918 919 920 921 922 923 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 1008 1009 1010 1011 1012 1013 1014 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 908 909 910 911 912 913 914 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 903 904 905 def terminal_info ( * , config : Mt5Config | None = None ) -> pd . DataFrame : \"\"\"Return terminal information.\"\"\" return _make_client ( config = config ) . terminal_info () version \u00b6 version ( * , config : Mt5Config | None = None ) -> DataFrame Return MetaTrader5 version information. Source code in mt5cli/sdk.py 998 999 1000 def version ( * , config : Mt5Config | None = None ) -> pd . DataFrame : \"\"\"Return MetaTrader5 version information.\"\"\" return _make_client ( config = config ) . version ()","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.__all__","text":"__all__ = [ \"Mt5CliClient\" , \"account_info\" , \"build_config\" , \"collect_history\" , \"copy_rates_from\" , \"copy_rates_from_pos\" , \"copy_rates_range\" , \"copy_ticks_from\" , \"copy_ticks_range\" , \"history_deals\" , \"history_orders\" , \"last_error\" , \"market_book\" , \"orders\" , \"positions\" , \"symbol_info\" , \"symbol_info_tick\" , \"symbols\" , \"terminal_info\" , \"version\" , ]","title":"__all__"},{"location":"api/sdk/#mt5cli.sdk.logger","text":"logger = getLogger ( __name__ )","title":"logger"},{"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 , config : Mt5Config | 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 config Mt5Config | None Optional pre-built Mt5Config (overrides other args). None Source code in mt5cli/sdk.py 152 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 def __init__ ( self , * , path : str | None = None , login : int | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , config : Mt5Config | 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. config: Optional pre-built ``Mt5Config`` (overrides other args). \"\"\" self . _config = config or build_config ( path = path , login = login , password = password , server = server , timeout = timeout , ) self . _client : Mt5DataClient | None = 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 186 187 188 189 190 191 192 193 194 195 196 197 198 199 def __enter__ ( self ) -> Self : \"\"\"Open a persistent MT5 connection for multiple calls. Returns: This client instance. \"\"\" client = Mt5DataClient ( config = self . _config ) try : client . initialize_and_login_mt5 () except Exception : client . shutdown () raise self . _client = 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 201 202 203 204 205 206 207 208 209 210 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 : 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 313 314 315 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.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 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 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 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 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 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 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 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 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 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 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.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 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 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 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 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 409 410 411 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.market_book","text":"market_book ( symbol : str ) -> DataFrame Return market depth for a symbol. Source code in mt5cli/sdk.py 417 418 419 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.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 329 330 331 332 333 334 335 336 337 338 339 340 341 342 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 344 345 346 347 348 349 350 351 352 353 354 355 356 357 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.symbol_info","text":"symbol_info ( symbol : str ) -> DataFrame Return details for one symbol. Source code in mt5cli/sdk.py 325 326 327 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 413 414 415 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 321 322 323 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 317 318 319 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 405 406 407 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.account_info","text":"account_info ( * , config : Mt5Config | None = None ) -> DataFrame Return account information. Source code in mt5cli/sdk.py 898 899 900 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 | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , ) -> Mt5Config Build an Mt5Config from optional connection parameters. Returns: Type Description Mt5Config Configured Mt5Config instance. Source code in mt5cli/sdk.py 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 def build_config ( * , path : str | None = None , login : int | None = None , password : str | None = None , server : str | None = None , timeout : int | None = None , ) -> Mt5Config : \"\"\"Build an ``Mt5Config`` from optional connection parameters. Returns: Configured ``Mt5Config`` instance. \"\"\" return Mt5Config ( path = path , 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 = 1 , 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 ). 1 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 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 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 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 = 1 , 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_collect_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.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 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 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 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 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 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 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 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 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 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 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.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 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 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 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 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 1003 1004 1005 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.market_book","text":"market_book ( symbol : str , * , config : Mt5Config | None = None ) -> DataFrame Return market depth for a symbol. Source code in mt5cli/sdk.py 1017 1018 1019 1020 1021 1022 1023 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.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 926 927 928 929 930 931 932 933 934 935 936 937 938 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 941 942 943 944 945 946 947 948 949 950 951 952 953 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.symbol_info","text":"symbol_info ( symbol : str , * , config : Mt5Config | None = None ) -> DataFrame Return details for one symbol. Source code in mt5cli/sdk.py 917 918 919 920 921 922 923 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 1008 1009 1010 1011 1012 1013 1014 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 908 909 910 911 912 913 914 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 903 904 905 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.version","text":"version ( * , config : Mt5Config | None = None ) -> DataFrame Return MetaTrader5 version information. Source code in mt5cli/sdk.py 998 999 1000 def version ( * , config : Mt5Config | None = None ) -> pd . DataFrame : \"\"\"Return MetaTrader5 version information.\"\"\" return _make_client ( config = config ) . version ()","title":"version"},{"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 ] = { \"ALL\" : 1 , \"INFO\" : 2 , \"TRADE\" : 4 , } TIMEFRAME_MAP module-attribute \u00b6 TIMEFRAME_MAP : dict [ str , int ] = { \"M1\" : 1 , \"M2\" : 2 , \"M3\" : 3 , \"M4\" : 4 , \"M5\" : 5 , \"M6\" : 6 , \"M10\" : 10 , \"M12\" : 12 , \"M15\" : 15 , \"M20\" : 20 , \"M30\" : 30 , \"H1\" : 16385 , \"H2\" : 16386 , \"H3\" : 16387 , \"H4\" : 16388 , \"H6\" : 16390 , \"H8\" : 16392 , \"H12\" : 16396 , \"D1\" : 16408 , \"W1\" : 32769 , \"MN1\" : 49153 , } 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' 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 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 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 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 300 301 302 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\" : sqlite3 = cast ( \"Any\" , importlib . import_module ( \"sqlite3\" )) with sqlite3 . connect ( output_path ) as conn : df . to_sql ( # type: ignore[reportUnknownMemberType] table_name , conn , if_exists = \"replace\" , index = False , ) else : msg = f \"Unsupported output format: { output_format } \" raise ValueError ( msg ) 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 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 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 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 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 : str ) -> int Parse tick flags string or integer value. Parameters: Name Type Description Default value str Tick flag name (ALL, INFO, TRADE) or integer value. required Returns: Type Description int Integer tick flag value. Raises: Type Description ValueError If the flag is invalid. Source code in mt5cli/utils.py 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 def parse_tick_flags ( value : str ) -> int : \"\"\"Parse tick flags string or integer value. Args: value: Tick flag name (ALL, INFO, TRADE) or integer value. Returns: Integer tick flag value. Raises: ValueError: If the flag is invalid. \"\"\" upper = value . upper () if upper in TICK_FLAG_MAP : return TICK_FLAG_MAP [ upper ] try : return int ( value ) except ValueError : valid = \", \" . join ( TICK_FLAG_MAP ) msg = f \"Invalid tick flags: ' { value } '. Use one of: { valid } , or an integer.\" raise ValueError ( msg ) from None parse_timeframe \u00b6 parse_timeframe ( value : str ) -> int Parse a timeframe string or integer value. Parameters: Name Type Description Default value str 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 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 def parse_timeframe ( value : str ) -> 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. \"\"\" upper = value . upper () if upper in TIMEFRAME_MAP : return TIMEFRAME_MAP [ upper ] try : return int ( value ) except ValueError : valid = \", \" . join ( TIMEFRAME_MAP ) msg = f \"Invalid timeframe: ' { value } '. Use one of: { valid } , or an 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 ] = { \"ALL\" : 1 , \"INFO\" : 2 , \"TRADE\" : 4 , }","title":"TICK_FLAG_MAP"},{"location":"api/utils/#mt5cli.utils.TIMEFRAME_MAP","text":"TIMEFRAME_MAP : dict [ str , int ] = { \"M1\" : 1 , \"M2\" : 2 , \"M3\" : 3 , \"M4\" : 4 , \"M5\" : 5 , \"M6\" : 6 , \"M10\" : 10 , \"M12\" : 12 , \"M15\" : 15 , \"M20\" : 20 , \"M30\" : 30 , \"H1\" : 16385 , \"H2\" : 16386 , \"H3\" : 16387 , \"H4\" : 16388 , \"H6\" : 16390 , \"H8\" : 16392 , \"H12\" : 16396 , \"D1\" : 16408 , \"W1\" : 32769 , \"MN1\" : 49153 , }","title":"TIMEFRAME_MAP"},{"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.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 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 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 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 300 301 302 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\" : sqlite3 = cast ( \"Any\" , importlib . import_module ( \"sqlite3\" )) with sqlite3 . connect ( output_path ) as conn : df . to_sql ( # type: ignore[reportUnknownMemberType] table_name , conn , if_exists = \"replace\" , index = False , ) else : msg = f \"Unsupported output format: { output_format } \" raise ValueError ( msg )","title":"export_dataframe"},{"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 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 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 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 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 : str ) -> int Parse tick flags string or integer value. Parameters: Name Type Description Default value str Tick flag name (ALL, INFO, TRADE) or integer value. required Returns: Type Description int Integer tick flag value. Raises: Type Description ValueError If the flag is invalid. Source code in mt5cli/utils.py 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 def parse_tick_flags ( value : str ) -> int : \"\"\"Parse tick flags string or integer value. Args: value: Tick flag name (ALL, INFO, TRADE) or integer value. Returns: Integer tick flag value. Raises: ValueError: If the flag is invalid. \"\"\" upper = value . upper () if upper in TICK_FLAG_MAP : return TICK_FLAG_MAP [ upper ] try : return int ( value ) except ValueError : valid = \", \" . join ( TICK_FLAG_MAP ) msg = f \"Invalid tick flags: ' { value } '. Use one of: { valid } , or an integer.\" raise ValueError ( msg ) from None","title":"parse_tick_flags"},{"location":"api/utils/#mt5cli.utils.parse_timeframe","text":"parse_timeframe ( value : str ) -> int Parse a timeframe string or integer value. Parameters: Name Type Description Default value str 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 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 def parse_timeframe ( value : str ) -> 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. \"\"\" upper = value . upper () if upper in TIMEFRAME_MAP : return TIMEFRAME_MAP [ upper ] try : return int ( value ) except ValueError : valid = \", \" . join ( TIMEFRAME_MAP ) msg = f \"Invalid timeframe: ' { value } '. Use one of: { valid } , or an integer.\" raise ValueError ( msg ) from None","title":"parse_timeframe"}]} \ No newline at end of file diff --git a/sitemap.xml b/sitemap.xml index b1ccae0..260933d 100644 --- a/sitemap.xml +++ b/sitemap.xml @@ -2,14 +2,22 @@ https://github.com/dceoy/mt5cli/ - 2026-06-07 + 2026-06-08 https://github.com/dceoy/mt5cli/api/ - 2026-06-07 + 2026-06-08 https://github.com/dceoy/mt5cli/api/cli/ - 2026-06-07 + 2026-06-08 + + + https://github.com/dceoy/mt5cli/api/sdk/ + 2026-06-08 + + + https://github.com/dceoy/mt5cli/api/utils/ + 2026-06-08 \ No newline at end of file diff --git a/sitemap.xml.gz b/sitemap.xml.gz index 6dadaaec2cad7d957773a5a84f6cdf2eb586191e..d12fb459ea79dc8dd42567739a86305d49a01116 100644 GIT binary patch literal 214 zcmV;{04e_;iwFn+1}16(|8r?{Wo=<_E_iKh0L79`3WG2Zh4-E!WN*d_Ew;qC>j~Ne z*cdc4G2+D9-oEjN(zP2OflP)s?_(gmcw0kWsz>eGoE}(0iE5>*bX({2e!IpQEkwkJ z-k|a%m|M(g<9&Al7{`&J_R5wWGS}CDvI!4_wFwD3QxTD%DPXB)apRgOs@Z-61{bmNR#vwC*fqlvi24V{4iU9Ww#S_w{5X{?gJjYHn<%< QU*SWFFUg)y8^8hp09=Y>L;wH) literal 203 zcmV;+05ty}iwFpSv?OW*|8r?{Wo=<_E_iKh0L4*B3d1lAyyq3h_gHD5D~@yP3)%;y zj!6t&LgX~<@9Qj-p4&qQffhzH2=Ve^4Y{ixwRZ*Gu#6Jrq_4GW3VOYq(*rF