DataFrame

pdmt5.dataframe

MetaTrader5 data client with pandas DataFrame conversion.

__all__ module-attribute

__all__ = ['Mt5Config', 'Mt5DataClient']

logger module-attribute

logger = getLogger(__name__)

Mt5Config

Bases: BaseModel

Configuration for MetaTrader5 connection.

login class-attribute instance-attribute

login: int | None = Field(
    default=None, description="Trading account login"
)

model_config class-attribute instance-attribute

model_config = ConfigDict(frozen=True)

password class-attribute instance-attribute

password: str | SecretStr | None = Field(
    default=None, description="Trading account password"
)

path class-attribute instance-attribute

path: str | None = Field(
    default=None,
    description="Path to MetaTrader5 terminal EXE file",
)

server class-attribute instance-attribute

server: str | None = Field(
    default=None, description="Trading server name"
)

timeout class-attribute instance-attribute

timeout: int | None = Field(
    default=None,
    description="Connection timeout in milliseconds",
)

Mt5DataClient

Bases: Mt5Client

MetaTrader5 data client with pandas DataFrame and dictionary conversion.

This class provides a pandas-friendly interface to MetaTrader5 functions, converting native MetaTrader5 data structures to pandas DataFrames with pydantic validation.

config class-attribute instance-attribute

config: Mt5Config = Field(
    default_factory=Mt5Config,
    description="MetaTrader5 connection configuration",
)

model_config class-attribute instance-attribute

model_config = ConfigDict(arbitrary_types_allowed=True)

retry_count class-attribute instance-attribute

retry_count: int = Field(
    default=3,
    ge=0,
    description="Number of retry attempts for connection initialization",
)

__enter__

__enter__() -> Self

Context manager entry using config-aware initialization.

Returns:

Type Description
Self

The initialized client instance.

Source code in pdmt5/dataframe.py
def __enter__(self) -> Self:
    """Context manager entry using config-aware initialization.

    Returns:
        The initialized client instance.
    """
    self.initialize_and_login_mt5()
    return self

account_info_as_df

account_info_as_df(
    index_keys: str | None = None,
) -> DataFrame

Get info on the current account as a data frame.

Parameters:

Name Type Description Default
index_keys str | None

Column name to set as index if provided.

None

Returns:

Type Description
DataFrame

DataFrame with account information.

Source code in pdmt5/dataframe.py
@set_index_if_possible(index_parameters="index_keys")
def account_info_as_df(self, index_keys: str | None = None) -> pd.DataFrame:  # noqa: ARG002
    """Get info on the current account as a data frame.

    Args:
        index_keys: Column name to set as index if provided.

    Returns:
        DataFrame with account information.
    """
    return self._as_single_row_df(self.account_info_as_dict())

account_info_as_dict

account_info_as_dict() -> dict[str, Any]

Get info on the current account as a dictionary.

Returns:

Type Description
dict[str, Any]

Dictionary with account information.

Source code in pdmt5/dataframe.py
def account_info_as_dict(self) -> dict[str, Any]:
    """Get info on the current account as a dictionary.

    Returns:
        Dictionary with account information.
    """
    return self.account_info()._asdict()

copy_rates_from_as_df

copy_rates_from_as_df(
    symbol: str,
    timeframe: int,
    date_from: datetime,
    count: int,
    skip_to_datetime: bool = False,
    index_keys: str | None = None,
) -> DataFrame

Get bars for a specified date range as a data frame.

Parameters:

Name Type Description Default
symbol str

Symbol name.

required
timeframe int

Timeframe constant.

required
date_from datetime

Start date in trade-server time (not UTC).

required
count int

Number of rates to retrieve.

required
skip_to_datetime bool

Whether to skip converting time to datetime.

False
index_keys str | None

Column name to set as index if provided.

None

Returns:

Type Description
DataFrame

DataFrame with OHLCV data.

Source code in pdmt5/dataframe.py
@set_index_if_possible(index_parameters="index_keys")
@detect_and_convert_time_to_datetime(skip_toggle="skip_to_datetime")
def copy_rates_from_as_df(
    self,
    symbol: str,
    timeframe: int,
    date_from: datetime,
    count: int,
    skip_to_datetime: bool = False,  # noqa: ARG002
    index_keys: str | None = None,  # noqa: ARG002
) -> pd.DataFrame:
    """Get bars for a specified date range as a data frame.

    Args:
        symbol: Symbol name.
        timeframe: Timeframe constant.
        date_from: Start date in trade-server time (not UTC).
        count: Number of rates to retrieve.
        skip_to_datetime: Whether to skip converting time to datetime.
        index_keys: Column name to set as index if provided.

    Returns:
        DataFrame with OHLCV data.
    """
    self._validate_positive_count(count=count)
    return pd.DataFrame(
        self.copy_rates_from(
            symbol=symbol,
            timeframe=timeframe,
            date_from=date_from,
            count=count,
        )
    )

copy_rates_from_as_dicts

copy_rates_from_as_dicts(
    symbol: str,
    timeframe: int,
    date_from: datetime,
    count: int,
    skip_to_datetime: bool = False,
) -> list[dict[str, Any]]

Get bars for a specified date range as a list of dictionaries.

Parameters:

Name Type Description Default
symbol str

Symbol name.

required
timeframe int

Timeframe constant.

required
date_from datetime

Start date in trade-server time (not UTC).

required
count int

Number of rates to retrieve.

required
skip_to_datetime bool

Whether to skip converting time to datetime.

False

Returns:

Type Description
list[dict[str, Any]]

List of dictionaries with OHLCV data.

Source code in pdmt5/dataframe.py
def copy_rates_from_as_dicts(
    self,
    symbol: str,
    timeframe: int,
    date_from: datetime,
    count: int,
    skip_to_datetime: bool = False,
) -> list[dict[str, Any]]:
    """Get bars for a specified date range as a list of dictionaries.

    Args:
        symbol: Symbol name.
        timeframe: Timeframe constant.
        date_from: Start date in trade-server time (not UTC).
        count: Number of rates to retrieve.
        skip_to_datetime: Whether to skip converting time to datetime.

    Returns:
        List of dictionaries with OHLCV data.
    """
    return self._as_record_dicts(
        self.copy_rates_from_as_df(
            symbol=symbol,
            timeframe=timeframe,
            date_from=date_from,
            count=count,
            skip_to_datetime=skip_to_datetime,
            index_keys=None,
        )
    )

copy_rates_from_pos_as_df

copy_rates_from_pos_as_df(
    symbol: str,
    timeframe: int,
    start_pos: int,
    count: int,
    skip_to_datetime: bool = False,
    index_keys: str | None = None,
) -> DataFrame

Get bars from a specified position as a data frame.

Parameters:

Name Type Description Default
symbol str

Symbol name.

required
timeframe int

Timeframe constant.

required
start_pos int

Start position.

required
count int

Number of rates to retrieve.

required
skip_to_datetime bool

Whether to skip converting time to datetime.

False
index_keys str | None

Column name to set as index if provided.

None

Returns:

Type Description
DataFrame

DataFrame with OHLCV data.

Source code in pdmt5/dataframe.py
@set_index_if_possible(index_parameters="index_keys")
@detect_and_convert_time_to_datetime(skip_toggle="skip_to_datetime")
def copy_rates_from_pos_as_df(
    self,
    symbol: str,
    timeframe: int,
    start_pos: int,
    count: int,
    skip_to_datetime: bool = False,  # noqa: ARG002
    index_keys: str | None = None,  # noqa: ARG002
) -> pd.DataFrame:
    """Get bars from a specified position as a data frame.

    Args:
        symbol: Symbol name.
        timeframe: Timeframe constant.
        start_pos: Start position.
        count: Number of rates to retrieve.
        skip_to_datetime: Whether to skip converting time to datetime.
        index_keys: Column name to set as index if provided.

    Returns:
        DataFrame with OHLCV data.
    """
    self._validate_positive_count(count=count)
    self._validate_non_negative_position(position=start_pos)
    return pd.DataFrame(
        self.copy_rates_from_pos(
            symbol=symbol,
            timeframe=timeframe,
            start_pos=start_pos,
            count=count,
        )
    )

copy_rates_from_pos_as_dicts

copy_rates_from_pos_as_dicts(
    symbol: str,
    timeframe: int,
    start_pos: int,
    count: int,
    skip_to_datetime: bool = False,
) -> list[dict[str, Any]]

Get bars from a specified position as a list of dictionaries.

Parameters:

Name Type Description Default
symbol str

Symbol name.

required
timeframe int

Timeframe constant.

required
start_pos int

Start position.

required
count int

Number of rates to retrieve.

required
skip_to_datetime bool

Whether to skip converting time to datetime.

False

Returns:

Type Description
list[dict[str, Any]]

List of dictionaries with OHLCV data.

Source code in pdmt5/dataframe.py
def copy_rates_from_pos_as_dicts(
    self,
    symbol: str,
    timeframe: int,
    start_pos: int,
    count: int,
    skip_to_datetime: bool = False,
) -> list[dict[str, Any]]:
    """Get bars from a specified position as a list of dictionaries.

    Args:
        symbol: Symbol name.
        timeframe: Timeframe constant.
        start_pos: Start position.
        count: Number of rates to retrieve.
        skip_to_datetime: Whether to skip converting time to datetime.

    Returns:
        List of dictionaries with OHLCV data.
    """
    return self._as_record_dicts(
        self.copy_rates_from_pos_as_df(
            symbol=symbol,
            timeframe=timeframe,
            start_pos=start_pos,
            count=count,
            skip_to_datetime=skip_to_datetime,
            index_keys=None,
        )
    )

copy_rates_range_as_df

copy_rates_range_as_df(
    symbol: str,
    timeframe: int,
    date_from: datetime,
    date_to: datetime,
    skip_to_datetime: bool = False,
    index_keys: str | None = None,
) -> DataFrame

Get bars for a specified date range as a data frame.

Parameters:

Name Type Description Default
symbol str

Symbol name.

required
timeframe int

Timeframe constant.

required
date_from datetime

Start date in trade-server time (not UTC).

required
date_to datetime

End date in trade-server time (not UTC).

required
skip_to_datetime bool

Whether to skip converting time to datetime.

False
index_keys str | None

Column name to set as index if provided.

None

Returns:

Type Description
DataFrame

DataFrame with OHLCV data.

Source code in pdmt5/dataframe.py
@set_index_if_possible(index_parameters="index_keys")
@detect_and_convert_time_to_datetime(skip_toggle="skip_to_datetime")
def copy_rates_range_as_df(
    self,
    symbol: str,
    timeframe: int,
    date_from: datetime,
    date_to: datetime,
    skip_to_datetime: bool = False,  # noqa: ARG002
    index_keys: str | None = None,  # noqa: ARG002
) -> pd.DataFrame:
    """Get bars for a specified date range as a data frame.

    Args:
        symbol: Symbol name.
        timeframe: Timeframe constant.
        date_from: Start date in trade-server time (not UTC).
        date_to: End date in trade-server time (not UTC).
        skip_to_datetime: Whether to skip converting time to datetime.
        index_keys: Column name to set as index if provided.

    Returns:
        DataFrame with OHLCV data.
    """
    self._validate_date_range(date_from=date_from, date_to=date_to)
    return pd.DataFrame(
        self.copy_rates_range(
            symbol=symbol,
            timeframe=timeframe,
            date_from=date_from,
            date_to=date_to,
        )
    )

copy_rates_range_as_dicts

copy_rates_range_as_dicts(
    symbol: str,
    timeframe: int,
    date_from: datetime,
    date_to: datetime,
    skip_to_datetime: bool = False,
) -> list[dict[str, Any]]

Get bars for a specified date range as a list of dictionaries.

Parameters:

Name Type Description Default
symbol str

Symbol name.

required
timeframe int

Timeframe constant.

required
date_from datetime

Start date in trade-server time (not UTC).

required
date_to datetime

End date in trade-server time (not UTC).

required
skip_to_datetime bool

Whether to skip converting time to datetime.

False

Returns:

Type Description
list[dict[str, Any]]

List of dictionaries with OHLCV data.

Source code in pdmt5/dataframe.py
def copy_rates_range_as_dicts(
    self,
    symbol: str,
    timeframe: int,
    date_from: datetime,
    date_to: datetime,
    skip_to_datetime: bool = False,
) -> list[dict[str, Any]]:
    """Get bars for a specified date range as a list of dictionaries.

    Args:
        symbol: Symbol name.
        timeframe: Timeframe constant.
        date_from: Start date in trade-server time (not UTC).
        date_to: End date in trade-server time (not UTC).
        skip_to_datetime: Whether to skip converting time to datetime.

    Returns:
        List of dictionaries with OHLCV data.
    """
    return self._as_record_dicts(
        self.copy_rates_range_as_df(
            symbol=symbol,
            timeframe=timeframe,
            date_from=date_from,
            date_to=date_to,
            skip_to_datetime=skip_to_datetime,
            index_keys=None,
        )
    )

copy_ticks_from_as_df

copy_ticks_from_as_df(
    symbol: str,
    date_from: datetime,
    count: int,
    flags: int,
    skip_to_datetime: bool = False,
    index_keys: str | None = None,
) -> DataFrame

Get ticks from a specified date as a data frame.

Parameters:

Name Type Description Default
symbol str

Symbol name.

required
date_from datetime

Start date in trade-server time (not UTC).

required
count int

Number of ticks to retrieve.

required
flags int

Tick flags (use constants from MetaTrader5).

required
skip_to_datetime bool

Whether to skip converting time to datetime.

False
index_keys str | None

Column name to set as index if provided.

None

Returns:

Type Description
DataFrame

DataFrame with tick data.

Source code in pdmt5/dataframe.py
@set_index_if_possible(index_parameters="index_keys")
@detect_and_convert_time_to_datetime(skip_toggle="skip_to_datetime")
def copy_ticks_from_as_df(
    self,
    symbol: str,
    date_from: datetime,
    count: int,
    flags: int,
    skip_to_datetime: bool = False,  # noqa: ARG002
    index_keys: str | None = None,  # noqa: ARG002
) -> pd.DataFrame:
    """Get ticks from a specified date as a data frame.

    Args:
        symbol: Symbol name.
        date_from: Start date in trade-server time (not UTC).
        count: Number of ticks to retrieve.
        flags: Tick flags (use constants from MetaTrader5).
        skip_to_datetime: Whether to skip converting time to datetime.
        index_keys: Column name to set as index if provided.

    Returns:
        DataFrame with tick data.
    """
    self._validate_positive_count(count=count)
    return pd.DataFrame(
        self.copy_ticks_from(
            symbol=symbol,
            date_from=date_from,
            count=count,
            flags=flags,
        )
    )

copy_ticks_from_as_dicts

copy_ticks_from_as_dicts(
    symbol: str,
    date_from: datetime,
    count: int,
    flags: int,
    skip_to_datetime: bool = False,
) -> list[dict[str, Any]]

Get ticks from a specified date as a list of dictionaries.

Parameters:

Name Type Description Default
symbol str

Symbol name.

required
date_from datetime

Start date in trade-server time (not UTC).

required
count int

Number of ticks to retrieve.

required
flags int

Tick flags (use constants from MetaTrader5).

required
skip_to_datetime bool

Whether to skip converting time to datetime.

False

Returns:

Type Description
list[dict[str, Any]]

List of dictionaries with tick data.

Source code in pdmt5/dataframe.py
def copy_ticks_from_as_dicts(
    self,
    symbol: str,
    date_from: datetime,
    count: int,
    flags: int,
    skip_to_datetime: bool = False,
) -> list[dict[str, Any]]:
    """Get ticks from a specified date as a list of dictionaries.

    Args:
        symbol: Symbol name.
        date_from: Start date in trade-server time (not UTC).
        count: Number of ticks to retrieve.
        flags: Tick flags (use constants from MetaTrader5).
        skip_to_datetime: Whether to skip converting time to datetime.

    Returns:
        List of dictionaries with tick data.
    """
    return self._as_record_dicts(
        self.copy_ticks_from_as_df(
            symbol=symbol,
            date_from=date_from,
            count=count,
            flags=flags,
            skip_to_datetime=skip_to_datetime,
            index_keys=None,
        )
    )

copy_ticks_range_as_df

copy_ticks_range_as_df(
    symbol: str,
    date_from: datetime,
    date_to: datetime,
    flags: int,
    skip_to_datetime: bool = False,
    index_keys: str | None = None,
) -> DataFrame

Get ticks for a specified date range as a data frame.

Parameters:

Name Type Description Default
symbol str

Symbol name.

required
date_from datetime

Start date in trade-server time (not UTC).

required
date_to datetime

End date in trade-server time (not UTC).

required
flags int

Tick flags (use constants from MetaTrader5).

required
skip_to_datetime bool

Whether to skip converting time to datetime.

False
index_keys str | None

Column name to set as index if provided.

None

Returns:

Type Description
DataFrame

DataFrame with tick data.

Source code in pdmt5/dataframe.py
@set_index_if_possible(index_parameters="index_keys")
@detect_and_convert_time_to_datetime(skip_toggle="skip_to_datetime")
def copy_ticks_range_as_df(
    self,
    symbol: str,
    date_from: datetime,
    date_to: datetime,
    flags: int,
    skip_to_datetime: bool = False,  # noqa: ARG002
    index_keys: str | None = None,  # noqa: ARG002
) -> pd.DataFrame:
    """Get ticks for a specified date range as a data frame.

    Args:
        symbol: Symbol name.
        date_from: Start date in trade-server time (not UTC).
        date_to: End date in trade-server time (not UTC).
        flags: Tick flags (use constants from MetaTrader5).
        skip_to_datetime: Whether to skip converting time to datetime.
        index_keys: Column name to set as index if provided.

    Returns:
        DataFrame with tick data.
    """
    self._validate_date_range(date_from=date_from, date_to=date_to)
    return pd.DataFrame(
        self.copy_ticks_range(
            symbol=symbol,
            date_from=date_from,
            date_to=date_to,
            flags=flags,
        )
    )

copy_ticks_range_as_dicts

copy_ticks_range_as_dicts(
    symbol: str,
    date_from: datetime,
    date_to: datetime,
    flags: int,
    skip_to_datetime: bool = False,
) -> list[dict[str, Any]]

Get ticks for a specified date range as a list of dictionaries.

Parameters:

Name Type Description Default
symbol str

Symbol name.

required
date_from datetime

Start date in trade-server time (not UTC).

required
date_to datetime

End date in trade-server time (not UTC).

required
flags int

Tick flags (use constants from MetaTrader5).

required
skip_to_datetime bool

Whether to skip converting time to datetime.

False

Returns:

Type Description
list[dict[str, Any]]

List of dictionaries with tick data.

Source code in pdmt5/dataframe.py
def copy_ticks_range_as_dicts(
    self,
    symbol: str,
    date_from: datetime,
    date_to: datetime,
    flags: int,
    skip_to_datetime: bool = False,
) -> list[dict[str, Any]]:
    """Get ticks for a specified date range as a list of dictionaries.

    Args:
        symbol: Symbol name.
        date_from: Start date in trade-server time (not UTC).
        date_to: End date in trade-server time (not UTC).
        flags: Tick flags (use constants from MetaTrader5).
        skip_to_datetime: Whether to skip converting time to datetime.

    Returns:
        List of dictionaries with tick data.
    """
    return self._as_record_dicts(
        self.copy_ticks_range_as_df(
            symbol=symbol,
            date_from=date_from,
            date_to=date_to,
            flags=flags,
            skip_to_datetime=skip_to_datetime,
            index_keys=None,
        )
    )

history_deals_get_as_df

history_deals_get_as_df(
    date_from: datetime | None = None,
    date_to: datetime | None = None,
    group: str | None = None,
    symbol: str | None = None,
    ticket: int | None = None,
    position: int | None = None,
    skip_to_datetime: bool = False,
    index_keys: str | None = None,
) -> DataFrame

Get historical deals with optional filters as a data frame.

Parameters:

Name Type Description Default
date_from datetime | None

Start date in trade-server time, not UTC (required if not using ticket/position).

None
date_to datetime | None

End date in trade-server time, not UTC (required if not using ticket/position).

None
group str | None

Optional group filter. Mutually exclusive with symbol.

None
symbol str | None

Optional symbol filter matching the symbol name exactly. Mutually exclusive with group.

None
ticket int | None

Get deals by order ticket.

None
position int | None

Get deals by position ticket.

None
skip_to_datetime bool

Whether to skip converting time to datetime.

False
index_keys str | None

Column name to set as index if provided.

None

Returns:

Type Description
DataFrame

DataFrame with historical deal information.

Source code in pdmt5/dataframe.py
@set_index_if_possible(index_parameters="index_keys")
@detect_and_convert_time_to_datetime(skip_toggle="skip_to_datetime")
def history_deals_get_as_df(
    self,
    date_from: datetime | None = None,
    date_to: datetime | None = None,
    group: str | None = None,
    symbol: str | None = None,
    ticket: int | None = None,
    position: int | None = None,
    skip_to_datetime: bool = False,  # noqa: ARG002
    index_keys: str | None = None,  # noqa: ARG002
) -> pd.DataFrame:
    """Get historical deals with optional filters as a data frame.

    Args:
        date_from: Start date in trade-server time, not UTC (required if
            not using ticket/position).
        date_to: End date in trade-server time, not UTC (required if not
            using ticket/position).
        group: Optional group filter. Mutually exclusive with symbol.
        symbol: Optional symbol filter matching the symbol name exactly.
            Mutually exclusive with group.
        ticket: Get deals by order ticket.
        position: Get deals by position ticket.
        skip_to_datetime: Whether to skip converting time to datetime.
        index_keys: Column name to set as index if provided.

    Returns:
        DataFrame with historical deal information.
    """
    return pd.DataFrame(
        self.history_deals_get_as_dicts(
            date_from=date_from,
            date_to=date_to,
            group=group,
            symbol=symbol,
            ticket=ticket,
            position=position,
            skip_to_datetime=True,
        )
    )

history_deals_get_as_dicts

history_deals_get_as_dicts(
    date_from: datetime | None = None,
    date_to: datetime | None = None,
    group: str | None = None,
    symbol: str | None = None,
    ticket: int | None = None,
    position: int | None = None,
    skip_to_datetime: bool = False,
) -> list[dict[str, Any]]

Get historical deals with optional filters as a list of dictionaries.

Parameters:

Name Type Description Default
date_from datetime | None

Start date in trade-server time, not UTC (required if not using ticket/position).

None
date_to datetime | None

End date in trade-server time, not UTC (required if not using ticket/position).

None
group str | None

Optional group filter. Mutually exclusive with symbol.

None
symbol str | None

Optional symbol filter matching the symbol name exactly. Mutually exclusive with group.

None
ticket int | None

Get deals by order ticket.

None
position int | None

Get deals by position ticket.

None
skip_to_datetime bool

Whether to skip converting time to datetime.

False

Returns:

Type Description
list[dict[str, Any]]

List of dictionaries with historical deal information.

Source code in pdmt5/dataframe.py
@detect_and_convert_time_to_datetime(skip_toggle="skip_to_datetime")
def history_deals_get_as_dicts(
    self,
    date_from: datetime | None = None,
    date_to: datetime | None = None,
    group: str | None = None,
    symbol: str | None = None,
    ticket: int | None = None,
    position: int | None = None,
    skip_to_datetime: bool = False,  # noqa: ARG002
) -> list[dict[str, Any]]:
    """Get historical deals with optional filters as a list of dictionaries.

    Args:
        date_from: Start date in trade-server time, not UTC (required if
            not using ticket/position).
        date_to: End date in trade-server time, not UTC (required if not
            using ticket/position).
        group: Optional group filter. Mutually exclusive with symbol.
        symbol: Optional symbol filter matching the symbol name exactly.
            Mutually exclusive with group.
        ticket: Get deals by order ticket.
        position: Get deals by position ticket.
        skip_to_datetime: Whether to skip converting time to datetime.

    Returns:
        List of dictionaries with historical deal information.
    """
    self._validate_history_input(
        date_from=date_from,
        date_to=date_to,
        ticket=ticket,
        position=position,
        group=group,
        symbol=symbol,
    )
    dicts = self._as_dicts(
        self.history_deals_get(
            date_from=date_from,
            date_to=date_to,
            group=(f"*{symbol}*" if symbol else group),
            ticket=ticket,
            position=position,
        )
    )
    return [d for d in dicts if d["symbol"] == symbol] if symbol else dicts

history_orders_get_as_df

history_orders_get_as_df(
    date_from: datetime | None = None,
    date_to: datetime | None = None,
    group: str | None = None,
    symbol: str | None = None,
    ticket: int | None = None,
    position: int | None = None,
    skip_to_datetime: bool = False,
    index_keys: str | None = None,
) -> DataFrame

Get historical orders with optional filters as a data frame.

Parameters:

Name Type Description Default
date_from datetime | None

Start date in trade-server time, not UTC (required if not using ticket/position).

None
date_to datetime | None

End date in trade-server time, not UTC (required if not using ticket/position).

None
group str | None

Optional group filter. Mutually exclusive with symbol.

None
symbol str | None

Optional symbol filter matching the symbol name exactly. Mutually exclusive with group.

None
ticket int | None

Get orders by ticket.

None
position int | None

Get orders by position.

None
skip_to_datetime bool

Whether to skip converting time to datetime.

False
index_keys str | None

Column name to set as index if provided.

None

Returns:

Type Description
DataFrame

DataFrame with historical order information.

Source code in pdmt5/dataframe.py
@set_index_if_possible(index_parameters="index_keys")
@detect_and_convert_time_to_datetime(skip_toggle="skip_to_datetime")
def history_orders_get_as_df(
    self,
    date_from: datetime | None = None,
    date_to: datetime | None = None,
    group: str | None = None,
    symbol: str | None = None,
    ticket: int | None = None,
    position: int | None = None,
    skip_to_datetime: bool = False,  # noqa: ARG002
    index_keys: str | None = None,  # noqa: ARG002
) -> pd.DataFrame:
    """Get historical orders with optional filters as a data frame.

    Args:
        date_from: Start date in trade-server time, not UTC (required if
            not using ticket/position).
        date_to: End date in trade-server time, not UTC (required if not
            using ticket/position).
        group: Optional group filter. Mutually exclusive with symbol.
        symbol: Optional symbol filter matching the symbol name exactly.
            Mutually exclusive with group.
        ticket: Get orders by ticket.
        position: Get orders by position.
        skip_to_datetime: Whether to skip converting time to datetime.
        index_keys: Column name to set as index if provided.

    Returns:
        DataFrame with historical order information.
    """
    return pd.DataFrame(
        self.history_orders_get_as_dicts(
            date_from=date_from,
            date_to=date_to,
            group=group,
            symbol=symbol,
            ticket=ticket,
            position=position,
            skip_to_datetime=True,
        )
    )

history_orders_get_as_dicts

history_orders_get_as_dicts(
    date_from: datetime | None = None,
    date_to: datetime | None = None,
    group: str | None = None,
    symbol: str | None = None,
    ticket: int | None = None,
    position: int | None = None,
    skip_to_datetime: bool = False,
) -> list[dict[str, Any]]

Get historical orders with optional filters as a list of dictionaries.

Parameters:

Name Type Description Default
date_from datetime | None

Start date in trade-server time, not UTC (required if not using ticket/position).

None
date_to datetime | None

End date in trade-server time, not UTC (required if not using ticket/position).

None
group str | None

Optional group filter. Mutually exclusive with symbol.

None
symbol str | None

Optional symbol filter matching the symbol name exactly. Mutually exclusive with group.

None
ticket int | None

Get orders by ticket.

None
position int | None

Get orders by position.

None
skip_to_datetime bool

Whether to skip converting time to datetime.

False

Returns:

Type Description
list[dict[str, Any]]

List of dictionaries with historical order information.

Source code in pdmt5/dataframe.py
@detect_and_convert_time_to_datetime(skip_toggle="skip_to_datetime")
def history_orders_get_as_dicts(
    self,
    date_from: datetime | None = None,
    date_to: datetime | None = None,
    group: str | None = None,
    symbol: str | None = None,
    ticket: int | None = None,
    position: int | None = None,
    skip_to_datetime: bool = False,  # noqa: ARG002
) -> list[dict[str, Any]]:
    """Get historical orders with optional filters as a list of dictionaries.

    Args:
        date_from: Start date in trade-server time, not UTC (required if
            not using ticket/position).
        date_to: End date in trade-server time, not UTC (required if not
            using ticket/position).
        group: Optional group filter. Mutually exclusive with symbol.
        symbol: Optional symbol filter matching the symbol name exactly.
            Mutually exclusive with group.
        ticket: Get orders by ticket.
        position: Get orders by position.
        skip_to_datetime: Whether to skip converting time to datetime.

    Returns:
        List of dictionaries with historical order information.
    """
    self._validate_history_input(
        date_from=date_from,
        date_to=date_to,
        ticket=ticket,
        position=position,
        group=group,
        symbol=symbol,
    )
    dicts = self._as_dicts(
        self.history_orders_get(
            date_from=date_from,
            date_to=date_to,
            group=(f"*{symbol}*" if symbol else group),
            ticket=ticket,
            position=position,
        )
    )
    return [d for d in dicts if d["symbol"] == symbol] if symbol else dicts

initialize_and_login_mt5

initialize_and_login_mt5(
    path: str | None = None,
    login: int | None = None,
    password: str | SecretStr | None = None,
    server: str | None = None,
    timeout: int | None = None,
) -> None

Initialize MT5 and ensure the requested account is active.

MetaTrader5.initialize() accepts account credentials and normally connects directly to the requested account. After initialization, this method verifies the active account and only calls login() when the terminal reports a different account, avoiding redundant authentication while preserving account-switch fallback behavior.

Parameters:

Name Type Description Default
path str | None

Path to terminal EXE file (overrides config).

None
login int | None

Account login (overrides config).

None
password str | SecretStr | None

Account password (overrides config).

None
server str | None

Server name (overrides config).

None
timeout int | None

Connection timeout (overrides config).

None

Raises:

Type Description
Mt5RuntimeError

If initialization or account selection fails after retries.

Source code in pdmt5/dataframe.py
def initialize_and_login_mt5(
    self,
    path: str | None = None,
    login: int | None = None,
    password: str | SecretStr | None = None,
    server: str | None = None,
    timeout: int | None = None,
) -> None:
    """Initialize MT5 and ensure the requested account is active.

    ``MetaTrader5.initialize()`` accepts account credentials and normally
    connects directly to the requested account. After initialization, this
    method verifies the active account and only calls ``login()`` when the
    terminal reports a different account, avoiding redundant authentication
    while preserving account-switch fallback behavior.

    Args:
        path: Path to terminal EXE file (overrides config).
        login: Account login (overrides config).
        password: Account password (overrides config).
        server: Server name (overrides config).
        timeout: Connection timeout (overrides config).

    Raises:
        Mt5RuntimeError: If initialization or account selection fails after retries.
    """
    path = path or self.config.path
    login_value = login if login is not None else self.config.login
    password_value = self._unwrap_password(
        password if password is not None else self.config.password
    )
    server_value = server if server is not None else self.config.server
    timeout_value = timeout if timeout is not None else self.config.timeout
    last_error_value: tuple[int, str] | None = None
    for i in range(1 + max(0, self.retry_count)):
        if i:
            logger.warning(
                "Retrying MT5 initialization (%d/%d)...",
                i,
                self.retry_count,
            )
            time.sleep(i)
        if not self.initialize(
            path=path,
            login=login_value,
            password=password_value,
            server=server_value,
            timeout=timeout_value,
        ):
            last_error_value = self.last_error()
            continue
        if login_value is None:
            return
        try:
            active_account = self.account_info()
        except Mt5RuntimeError:
            active_account = None
        if active_account is not None and (
            getattr(active_account, "login", None) == login_value
            and (
                server_value is None
                or getattr(active_account, "server", None) == server_value
            )
        ):
            return
        try:
            if self.login(
                login=login_value,
                password=password_value,
                server=server_value,
                timeout=timeout_value,
            ):
                return
        except Exception:
            self.shutdown()
            raise
        last_error_value = self.last_error()
        self.shutdown()
    error_message = (
        f"MT5 initialize and login failed after {self.retry_count} retries:"
        f" {last_error_value}"
    )
    raise Mt5RuntimeError(error_message)

last_error_as_df

last_error_as_df(
    index_keys: str | None = None,
) -> DataFrame

Get the last error information as a data frame.

Parameters:

Name Type Description Default
index_keys str | None

Column name to set as index if provided.

None

Returns:

Type Description
DataFrame

DataFrame with last error information.

Source code in pdmt5/dataframe.py
@set_index_if_possible(index_parameters="index_keys")
def last_error_as_df(self, index_keys: str | None = None) -> pd.DataFrame:  # noqa: ARG002
    """Get the last error information as a data frame.

    Args:
        index_keys: Column name to set as index if provided.

    Returns:
        DataFrame with last error information.
    """
    return self._as_single_row_df(self.last_error_as_dict())

last_error_as_dict

last_error_as_dict() -> dict[str, Any]

Get the last error information as a dictionary.

Returns:

Type Description
dict[str, Any]

Dictionary with last error information.

Source code in pdmt5/dataframe.py
def last_error_as_dict(self) -> dict[str, Any]:
    """Get the last error information as a dictionary.

    Returns:
        Dictionary with last error information.
    """
    response = self.last_error()
    return {"error_code": response[0], "error_description": response[1]}

market_book_get_as_df

market_book_get_as_df(
    symbol: str,
    skip_to_datetime: bool = False,
    index_keys: str | None = None,
) -> DataFrame

Get market depth for a specified symbol as a data frame.

Parameters:

Name Type Description Default
symbol str

Symbol name.

required
skip_to_datetime bool

Whether to skip converting time to datetime.

False
index_keys str | None

Column name to set as index if provided.

None

Returns:

Type Description
DataFrame

DataFrame with market depth data.

Source code in pdmt5/dataframe.py
@set_index_if_possible(index_parameters="index_keys")
@detect_and_convert_time_to_datetime(skip_toggle="skip_to_datetime")
def market_book_get_as_df(
    self,
    symbol: str,
    skip_to_datetime: bool = False,  # noqa: ARG002
    index_keys: str | None = None,  # noqa: ARG002
) -> pd.DataFrame:
    """Get market depth for a specified symbol as a data frame.

    Args:
        symbol: Symbol name.
        skip_to_datetime: Whether to skip converting time to datetime.
        index_keys: Column name to set as index if provided.

    Returns:
        DataFrame with market depth data.
    """
    return pd.DataFrame(
        self.market_book_get_as_dicts(symbol=symbol, skip_to_datetime=True)
    )

market_book_get_as_dicts

market_book_get_as_dicts(
    symbol: str, skip_to_datetime: bool = False
) -> list[dict[str, Any]]

Get market depth for a specified symbol as a list of dictionaries.

Parameters:

Name Type Description Default
symbol str

Symbol name.

required
skip_to_datetime bool

Whether to skip converting time to datetime.

False

Returns:

Type Description
list[dict[str, Any]]

List of dictionaries with market depth data.

Source code in pdmt5/dataframe.py
@detect_and_convert_time_to_datetime(skip_toggle="skip_to_datetime")
def market_book_get_as_dicts(
    self,
    symbol: str,
    skip_to_datetime: bool = False,  # noqa: ARG002
) -> list[dict[str, Any]]:
    """Get market depth for a specified symbol as a list of dictionaries.

    Args:
        symbol: Symbol name.
        skip_to_datetime: Whether to skip converting time to datetime.

    Returns:
        List of dictionaries with market depth data.
    """
    return self._as_dicts(self.market_book_get(symbol=symbol))

order_check_as_df

order_check_as_df(
    request: dict[str, Any], index_keys: str | None = None
) -> DataFrame

Check funds sufficiency for performing a requested trading operation as a data frame.

Parameters:

Name Type Description Default
request dict[str, Any]

Order request parameters.

required
index_keys str | None

Column name to set as index if provided.

None

Returns:

Type Description
DataFrame

DataFrame with order check results.

Source code in pdmt5/dataframe.py
@set_index_if_possible(index_parameters="index_keys")
def order_check_as_df(
    self,
    request: dict[str, Any],
    index_keys: str | None = None,  # noqa: ARG002
) -> pd.DataFrame:
    """Check funds sufficiency for performing a requested trading operation as a data frame.

    Args:
        request: Order request parameters.
        index_keys: Column name to set as index if provided.

    Returns:
        DataFrame with order check results.
    """  # noqa: E501
    return self._as_single_row_df(
        self._flatten_dict_to_one_level(
            dictionary=self.order_check_as_dict(request=request),
        )
    )

order_check_as_dict

order_check_as_dict(
    request: dict[str, Any],
) -> dict[str, Any]

Check funds sufficiency for performing a requested trading operation as a dictionary.

Parameters:

Name Type Description Default
request dict[str, Any]

Order request parameters.

required

Returns:

Type Description
dict[str, Any]

Dictionary with order check results.

Source code in pdmt5/dataframe.py
def order_check_as_dict(self, request: dict[str, Any]) -> dict[str, Any]:
    """Check funds sufficiency for performing a requested trading operation as a dictionary.

    Args:
        request: Order request parameters.

    Returns:
        Dictionary with order check results.
    """  # noqa: E501
    return self._as_order_result_dict(self.order_check(request=request))

order_send_as_df

order_send_as_df(
    request: dict[str, Any], index_keys: str | None = None
) -> DataFrame

Send a request to perform a trading operation from the terminal to the trade server as a data frame.

Parameters:

Name Type Description Default
request dict[str, Any]

Order request parameters.

required
index_keys str | None

Column name to set as index if provided.

None

Returns:

Type Description
DataFrame

DataFrame with order send results.

Source code in pdmt5/dataframe.py
@set_index_if_possible(index_parameters="index_keys")
def order_send_as_df(
    self,
    request: dict[str, Any],
    index_keys: str | None = None,  # noqa: ARG002
) -> pd.DataFrame:
    """Send a request to perform a trading operation from the terminal to the trade server as a data frame.

    Args:
        request: Order request parameters.
        index_keys: Column name to set as index if provided.

    Returns:
        DataFrame with order send results.
    """  # noqa: E501
    return self._as_single_row_df(
        self._flatten_dict_to_one_level(
            dictionary=self.order_send_as_dict(request=request),
        )
    )

order_send_as_dict

order_send_as_dict(
    request: dict[str, Any],
) -> dict[str, Any]

Send a request to perform a trading operation from the terminal to the trade server as a dictionary.

Parameters:

Name Type Description Default
request dict[str, Any]

Order request parameters.

required

Returns:

Type Description
dict[str, Any]

Dictionary with order send results.

Source code in pdmt5/dataframe.py
def order_send_as_dict(self, request: dict[str, Any]) -> dict[str, Any]:
    """Send a request to perform a trading operation from the terminal to the trade server as a dictionary.

    Args:
        request: Order request parameters.

    Returns:
        Dictionary with order send results.
    """  # noqa: E501
    return self._as_order_result_dict(self.order_send(request=request))

orders_get_as_df

orders_get_as_df(
    symbol: str | None = None,
    group: str | None = None,
    ticket: int | None = None,
    skip_to_datetime: bool = False,
    index_keys: str | None = None,
) -> DataFrame

Get active orders with optional filters as a data frame.

Parameters:

Name Type Description Default
symbol str | None

Optional symbol filter. Mutually exclusive with group and ticket.

None
group str | None

Optional group filter. Mutually exclusive with symbol and ticket.

None
ticket int | None

Optional order ticket filter. Mutually exclusive with symbol and group.

None
skip_to_datetime bool

Whether to skip converting time to datetime.

False
index_keys str | None

Column name to set as index if provided.

None

Returns:

Type Description
DataFrame

DataFrame with order information or empty DataFrame if no orders.

Source code in pdmt5/dataframe.py
@set_index_if_possible(index_parameters="index_keys")
@detect_and_convert_time_to_datetime(skip_toggle="skip_to_datetime")
def orders_get_as_df(
    self,
    symbol: str | None = None,
    group: str | None = None,
    ticket: int | None = None,
    skip_to_datetime: bool = False,  # noqa: ARG002
    index_keys: str | None = None,  # noqa: ARG002
) -> pd.DataFrame:
    """Get active orders with optional filters as a data frame.

    Args:
        symbol: Optional symbol filter. Mutually exclusive with group and
            ticket.
        group: Optional group filter. Mutually exclusive with symbol and
            ticket.
        ticket: Optional order ticket filter. Mutually exclusive with
            symbol and group.
        skip_to_datetime: Whether to skip converting time to datetime.
        index_keys: Column name to set as index if provided.

    Returns:
        DataFrame with order information or empty DataFrame if no orders.
    """
    return pd.DataFrame(
        self.orders_get_as_dicts(
            symbol=symbol,
            group=group,
            ticket=ticket,
            skip_to_datetime=True,
        )
    )

orders_get_as_dicts

orders_get_as_dicts(
    symbol: str | None = None,
    group: str | None = None,
    ticket: int | None = None,
    skip_to_datetime: bool = False,
) -> list[dict[str, Any]]

Get active orders with optional filters as a list of dictionaries.

Parameters:

Name Type Description Default
symbol str | None

Optional symbol filter. Mutually exclusive with group and ticket.

None
group str | None

Optional group filter. Mutually exclusive with symbol and ticket.

None
ticket int | None

Optional order ticket filter. Mutually exclusive with symbol and group.

None
skip_to_datetime bool

Whether to skip converting time to datetime.

False

Returns:

Type Description
list[dict[str, Any]]

List of dictionaries with order information or empty list if no orders.

Source code in pdmt5/dataframe.py
@detect_and_convert_time_to_datetime(skip_toggle="skip_to_datetime")
def orders_get_as_dicts(
    self,
    symbol: str | None = None,
    group: str | None = None,
    ticket: int | None = None,
    skip_to_datetime: bool = False,  # noqa: ARG002
) -> list[dict[str, Any]]:
    """Get active orders with optional filters as a list of dictionaries.

    Args:
        symbol: Optional symbol filter. Mutually exclusive with group and
            ticket.
        group: Optional group filter. Mutually exclusive with symbol and
            ticket.
        ticket: Optional order ticket filter. Mutually exclusive with
            symbol and group.
        skip_to_datetime: Whether to skip converting time to datetime.

    Returns:
        List of dictionaries with order information or empty list if no orders.
    """
    return self._as_dicts(
        self.orders_get(symbol=symbol, group=group, ticket=ticket)
    )

positions_get_as_df

positions_get_as_df(
    symbol: str | None = None,
    group: str | None = None,
    ticket: int | None = None,
    skip_to_datetime: bool = False,
    index_keys: str | None = None,
) -> DataFrame

Get open positions with optional filters as a data frame.

Parameters:

Name Type Description Default
symbol str | None

Optional symbol filter. Mutually exclusive with group and ticket.

None
group str | None

Optional group filter. Mutually exclusive with symbol and ticket.

None
ticket int | None

Optional position ticket filter. Mutually exclusive with symbol and group.

None
skip_to_datetime bool

Whether to skip converting time to datetime.

False
index_keys str | None

Column name to set as index if provided.

None

Returns:

Type Description
DataFrame

DataFrame with position information or empty DataFrame if no positions.

Source code in pdmt5/dataframe.py
@set_index_if_possible(index_parameters="index_keys")
@detect_and_convert_time_to_datetime(skip_toggle="skip_to_datetime")
def positions_get_as_df(
    self,
    symbol: str | None = None,
    group: str | None = None,
    ticket: int | None = None,
    skip_to_datetime: bool = False,  # noqa: ARG002
    index_keys: str | None = None,  # noqa: ARG002
) -> pd.DataFrame:
    """Get open positions with optional filters as a data frame.

    Args:
        symbol: Optional symbol filter. Mutually exclusive with group and
            ticket.
        group: Optional group filter. Mutually exclusive with symbol and
            ticket.
        ticket: Optional position ticket filter. Mutually exclusive with
            symbol and group.
        skip_to_datetime: Whether to skip converting time to datetime.
        index_keys: Column name to set as index if provided.

    Returns:
        DataFrame with position information or empty DataFrame if no positions.
    """
    return pd.DataFrame(
        self.positions_get_as_dicts(
            symbol=symbol,
            group=group,
            ticket=ticket,
            skip_to_datetime=True,
        )
    )

positions_get_as_dicts

positions_get_as_dicts(
    symbol: str | None = None,
    group: str | None = None,
    ticket: int | None = None,
    skip_to_datetime: bool = False,
) -> list[dict[str, Any]]

Get open positions with optional filters as a list of dictionaries.

Parameters:

Name Type Description Default
symbol str | None

Optional symbol filter. Mutually exclusive with group and ticket.

None
group str | None

Optional group filter. Mutually exclusive with symbol and ticket.

None
ticket int | None

Optional position ticket filter. Mutually exclusive with symbol and group.

None
skip_to_datetime bool

Whether to skip converting time to datetime.

False

Returns:

Type Description
list[dict[str, Any]]

List of dictionaries with position information or empty list if no

list[dict[str, Any]]

positions.

Source code in pdmt5/dataframe.py
@detect_and_convert_time_to_datetime(skip_toggle="skip_to_datetime")
def positions_get_as_dicts(
    self,
    symbol: str | None = None,
    group: str | None = None,
    ticket: int | None = None,
    skip_to_datetime: bool = False,  # noqa: ARG002
) -> list[dict[str, Any]]:
    """Get open positions with optional filters as a list of dictionaries.

    Args:
        symbol: Optional symbol filter. Mutually exclusive with group and
            ticket.
        group: Optional group filter. Mutually exclusive with symbol and
            ticket.
        ticket: Optional position ticket filter. Mutually exclusive with
            symbol and group.
        skip_to_datetime: Whether to skip converting time to datetime.

    Returns:
        List of dictionaries with position information or empty list if no
        positions.
    """
    return self._as_dicts(
        self.positions_get(symbol=symbol, group=group, ticket=ticket)
    )

symbol_info_as_df

symbol_info_as_df(
    symbol: str,
    skip_to_datetime: bool = False,
    index_keys: str | None = None,
) -> DataFrame

Get data on a specific symbol as a data frame.

Parameters:

Name Type Description Default
symbol str

Symbol name.

required
skip_to_datetime bool

Whether to skip converting time to datetime.

False
index_keys str | None

Column name to set as index if provided.

None

Returns:

Type Description
DataFrame

DataFrame with symbol information.

Source code in pdmt5/dataframe.py
@set_index_if_possible(index_parameters="index_keys")
@detect_and_convert_time_to_datetime(skip_toggle="skip_to_datetime")
def symbol_info_as_df(
    self,
    symbol: str,
    skip_to_datetime: bool = False,  # noqa: ARG002
    index_keys: str | None = None,  # noqa: ARG002
) -> pd.DataFrame:
    """Get data on a specific symbol as a data frame.

    Args:
        symbol: Symbol name.
        skip_to_datetime: Whether to skip converting time to datetime.
        index_keys: Column name to set as index if provided.

    Returns:
        DataFrame with symbol information.
    """
    return self._as_single_row_df(
        self.symbol_info_as_dict(symbol=symbol, skip_to_datetime=True)
    )

symbol_info_as_dict

symbol_info_as_dict(
    symbol: str, skip_to_datetime: bool = False
) -> dict[str, Any]

Get data on a specific symbol as a dictionary.

Parameters:

Name Type Description Default
symbol str

Symbol name.

required
skip_to_datetime bool

Whether to skip converting time to datetime.

False

Returns:

Type Description
dict[str, Any]

Dictionary with symbol information.

Source code in pdmt5/dataframe.py
@detect_and_convert_time_to_datetime(skip_toggle="skip_to_datetime")
def symbol_info_as_dict(
    self,
    symbol: str,
    skip_to_datetime: bool = False,  # noqa: ARG002
) -> dict[str, Any]:
    """Get data on a specific symbol as a dictionary.

    Args:
        symbol: Symbol name.
        skip_to_datetime: Whether to skip converting time to datetime.

    Returns:
        Dictionary with symbol information.
    """
    return self.symbol_info(symbol=symbol)._asdict()

symbol_info_tick_as_df

symbol_info_tick_as_df(
    symbol: str,
    skip_to_datetime: bool = False,
    index_keys: str | None = None,
) -> DataFrame

Get the last tick for the specified financial instrument as a data frame.

Parameters:

Name Type Description Default
symbol str

Symbol name.

required
skip_to_datetime bool

Whether to skip converting time to datetime.

False
index_keys str | None

Column name to set as index if provided.

None

Returns:

Type Description
DataFrame

DataFrame with tick information.

Source code in pdmt5/dataframe.py
@set_index_if_possible(index_parameters="index_keys")
@detect_and_convert_time_to_datetime(skip_toggle="skip_to_datetime")
def symbol_info_tick_as_df(
    self,
    symbol: str,
    skip_to_datetime: bool = False,  # noqa: ARG002
    index_keys: str | None = None,  # noqa: ARG002
) -> pd.DataFrame:
    """Get the last tick for the specified financial instrument as a data frame.

    Args:
        symbol: Symbol name.
        skip_to_datetime: Whether to skip converting time to datetime.
        index_keys: Column name to set as index if provided.

    Returns:
        DataFrame with tick information.
    """
    return self._as_single_row_df(
        self.symbol_info_tick_as_dict(symbol=symbol, skip_to_datetime=True)
    )

symbol_info_tick_as_dict

symbol_info_tick_as_dict(
    symbol: str, skip_to_datetime: bool = False
) -> dict[str, Any]

Get the last tick for the specified financial instrument as a dictionary.

Parameters:

Name Type Description Default
symbol str

Symbol name.

required
skip_to_datetime bool

Whether to skip converting time to datetime.

False

Returns:

Type Description
dict[str, Any]

Dictionary with tick information.

Source code in pdmt5/dataframe.py
@detect_and_convert_time_to_datetime(skip_toggle="skip_to_datetime")
def symbol_info_tick_as_dict(
    self,
    symbol: str,
    skip_to_datetime: bool = False,  # noqa: ARG002
) -> dict[str, Any]:
    """Get the last tick for the specified financial instrument as a dictionary.

    Args:
        symbol: Symbol name.
        skip_to_datetime: Whether to skip converting time to datetime.

    Returns:
        Dictionary with tick information.
    """
    return self.symbol_info_tick(symbol=symbol)._asdict()

symbols_get_as_df

symbols_get_as_df(
    group: str | None = None,
    skip_to_datetime: bool = False,
    index_keys: str | None = None,
) -> DataFrame

Get symbols as a data frame.

Parameters:

Name Type Description Default
group str | None

Symbol group filter (e.g., "USD", "Forex*").

None
skip_to_datetime bool

Whether to skip converting time to datetime.

False
index_keys str | None

Column name to set as index if provided.

None

Returns:

Type Description
DataFrame

DataFrame with symbol information.

Source code in pdmt5/dataframe.py
@set_index_if_possible(index_parameters="index_keys")
@detect_and_convert_time_to_datetime(skip_toggle="skip_to_datetime")
def symbols_get_as_df(
    self,
    group: str | None = None,
    skip_to_datetime: bool = False,  # noqa: ARG002
    index_keys: str | None = None,  # noqa: ARG002
) -> pd.DataFrame:
    """Get symbols as a data frame.

    Args:
        group: Symbol group filter (e.g., "*USD*", "Forex*").
        skip_to_datetime: Whether to skip converting time to datetime.
        index_keys: Column name to set as index if provided.

    Returns:
        DataFrame with symbol information.
    """
    return pd.DataFrame(
        self.symbols_get_as_dicts(group=group, skip_to_datetime=True)
    )

symbols_get_as_dicts

symbols_get_as_dicts(
    group: str | None = None, skip_to_datetime: bool = False
) -> list[dict[str, Any]]

Get symbols as a list of dictionaries.

Parameters:

Name Type Description Default
group str | None

Symbol group filter (e.g., "USD", "Forex*").

None
skip_to_datetime bool

Whether to skip converting time to datetime.

False

Returns:

Type Description
list[dict[str, Any]]

List of dictionaries with symbol information.

Source code in pdmt5/dataframe.py
@detect_and_convert_time_to_datetime(skip_toggle="skip_to_datetime")
def symbols_get_as_dicts(
    self,
    group: str | None = None,
    skip_to_datetime: bool = False,  # noqa: ARG002
) -> list[dict[str, Any]]:
    """Get symbols as a list of dictionaries.

    Args:
        group: Symbol group filter (e.g., "*USD*", "Forex*").
        skip_to_datetime: Whether to skip converting time to datetime.

    Returns:
        List of dictionaries with symbol information.
    """
    return self._as_dicts(self.symbols_get(group=group))

terminal_info_as_df

terminal_info_as_df(
    index_keys: str | None = None,
) -> DataFrame

Get the connected terminal status and settings as a data frame.

Parameters:

Name Type Description Default
index_keys str | None

Column name to set as index if provided.

None

Returns:

Type Description
DataFrame

DataFrame with terminal information.

Source code in pdmt5/dataframe.py
@set_index_if_possible(index_parameters="index_keys")
def terminal_info_as_df(self, index_keys: str | None = None) -> pd.DataFrame:  # noqa: ARG002
    """Get the connected terminal status and settings as a data frame.

    Args:
        index_keys: Column name to set as index if provided.

    Returns:
        DataFrame with terminal information.
    """
    return self._as_single_row_df(self.terminal_info_as_dict())

terminal_info_as_dict

terminal_info_as_dict() -> dict[str, Any]

Get the connected terminal status and settings as a dictionary.

Returns:

Type Description
dict[str, Any]

Dictionary with terminal information.

Source code in pdmt5/dataframe.py
def terminal_info_as_dict(self) -> dict[str, Any]:
    """Get the connected terminal status and settings as a dictionary.

    Returns:
        Dictionary with terminal information.
    """
    return self.terminal_info()._asdict()

version_as_df

version_as_df(index_keys: str | None = None) -> DataFrame

Return MetaTrader5 version information as a data frame.

Parameters:

Name Type Description Default
index_keys str | None

Column name to set as index if provided.

None

Returns:

Type Description
DataFrame

DataFrame with MetaTrader5 version information.

Source code in pdmt5/dataframe.py
@set_index_if_possible(index_parameters="index_keys")
def version_as_df(self, index_keys: str | None = None) -> pd.DataFrame:  # noqa: ARG002
    """Return MetaTrader5 version information as a data frame.

    Args:
        index_keys: Column name to set as index if provided.

    Returns:
        DataFrame with MetaTrader5 version information.
    """
    return self._as_single_row_df(self.version_as_dict())

version_as_dict

version_as_dict() -> dict[str, int | str]

Return MetaTrader5 version information as a dictionary.

Returns:

Type Description
dict[str, int | str]

Dictionary with MetaTrader5 version information.

Source code in pdmt5/dataframe.py
def version_as_dict(self) -> dict[str, int | str]:
    """Return MetaTrader5 version information as a dictionary.

    Returns:
        Dictionary with MetaTrader5 version information.
    """
    response = self.version()
    return {
        "mt5_terminal_version": response[0],
        "build": response[1],
        "build_release_date": response[2],
    }

Overview

The dataframe module extends the base Mt5Client with pandas-friendly functionality for connecting to MetaTrader 5 and retrieving trading data as pandas DataFrames. It includes configuration management, data conversion helpers, and comprehensive validation utilities.

Use the _as_df/_as_dict methods for pandas conversions; base methods return raw MT5 structures.

Classes

Mt5Config

pdmt5.dataframe.Mt5Config

Bases: BaseModel

Configuration for MetaTrader5 connection.

login class-attribute instance-attribute

login: int | None = Field(
    default=None, description="Trading account login"
)

model_config class-attribute instance-attribute

model_config = ConfigDict(frozen=True)

password class-attribute instance-attribute

password: str | SecretStr | None = Field(
    default=None, description="Trading account password"
)

path class-attribute instance-attribute

path: str | None = Field(
    default=None,
    description="Path to MetaTrader5 terminal EXE file",
)

server class-attribute instance-attribute

server: str | None = Field(
    default=None, description="Trading server name"
)

timeout class-attribute instance-attribute

timeout: int | None = Field(
    default=None,
    description="Connection timeout in milliseconds",
)

options: show_bases: false

Configuration class for MetaTrader 5 connection parameters using pydantic for validation.

Mt5DataClient

pdmt5.dataframe.Mt5DataClient

Bases: Mt5Client

MetaTrader5 data client with pandas DataFrame and dictionary conversion.

This class provides a pandas-friendly interface to MetaTrader5 functions, converting native MetaTrader5 data structures to pandas DataFrames with pydantic validation.

config class-attribute instance-attribute

config: Mt5Config = Field(
    default_factory=Mt5Config,
    description="MetaTrader5 connection configuration",
)

model_config class-attribute instance-attribute

model_config = ConfigDict(arbitrary_types_allowed=True)

retry_count class-attribute instance-attribute

retry_count: int = Field(
    default=3,
    ge=0,
    description="Number of retry attempts for connection initialization",
)

__enter__

__enter__() -> Self

Context manager entry using config-aware initialization.

Returns:

Type Description
Self

The initialized client instance.

Source code in pdmt5/dataframe.py
def __enter__(self) -> Self:
    """Context manager entry using config-aware initialization.

    Returns:
        The initialized client instance.
    """
    self.initialize_and_login_mt5()
    return self

account_info_as_df

account_info_as_df(
    index_keys: str | None = None,
) -> DataFrame

Get info on the current account as a data frame.

Parameters:

Name Type Description Default
index_keys str | None

Column name to set as index if provided.

None

Returns:

Type Description
DataFrame

DataFrame with account information.

Source code in pdmt5/dataframe.py
@set_index_if_possible(index_parameters="index_keys")
def account_info_as_df(self, index_keys: str | None = None) -> pd.DataFrame:  # noqa: ARG002
    """Get info on the current account as a data frame.

    Args:
        index_keys: Column name to set as index if provided.

    Returns:
        DataFrame with account information.
    """
    return self._as_single_row_df(self.account_info_as_dict())

account_info_as_dict

account_info_as_dict() -> dict[str, Any]

Get info on the current account as a dictionary.

Returns:

Type Description
dict[str, Any]

Dictionary with account information.

Source code in pdmt5/dataframe.py
def account_info_as_dict(self) -> dict[str, Any]:
    """Get info on the current account as a dictionary.

    Returns:
        Dictionary with account information.
    """
    return self.account_info()._asdict()

copy_rates_from_as_df

copy_rates_from_as_df(
    symbol: str,
    timeframe: int,
    date_from: datetime,
    count: int,
    skip_to_datetime: bool = False,
    index_keys: str | None = None,
) -> DataFrame

Get bars for a specified date range as a data frame.

Parameters:

Name Type Description Default
symbol str

Symbol name.

required
timeframe int

Timeframe constant.

required
date_from datetime

Start date in trade-server time (not UTC).

required
count int

Number of rates to retrieve.

required
skip_to_datetime bool

Whether to skip converting time to datetime.

False
index_keys str | None

Column name to set as index if provided.

None

Returns:

Type Description
DataFrame

DataFrame with OHLCV data.

Source code in pdmt5/dataframe.py
@set_index_if_possible(index_parameters="index_keys")
@detect_and_convert_time_to_datetime(skip_toggle="skip_to_datetime")
def copy_rates_from_as_df(
    self,
    symbol: str,
    timeframe: int,
    date_from: datetime,
    count: int,
    skip_to_datetime: bool = False,  # noqa: ARG002
    index_keys: str | None = None,  # noqa: ARG002
) -> pd.DataFrame:
    """Get bars for a specified date range as a data frame.

    Args:
        symbol: Symbol name.
        timeframe: Timeframe constant.
        date_from: Start date in trade-server time (not UTC).
        count: Number of rates to retrieve.
        skip_to_datetime: Whether to skip converting time to datetime.
        index_keys: Column name to set as index if provided.

    Returns:
        DataFrame with OHLCV data.
    """
    self._validate_positive_count(count=count)
    return pd.DataFrame(
        self.copy_rates_from(
            symbol=symbol,
            timeframe=timeframe,
            date_from=date_from,
            count=count,
        )
    )

copy_rates_from_as_dicts

copy_rates_from_as_dicts(
    symbol: str,
    timeframe: int,
    date_from: datetime,
    count: int,
    skip_to_datetime: bool = False,
) -> list[dict[str, Any]]

Get bars for a specified date range as a list of dictionaries.

Parameters:

Name Type Description Default
symbol str

Symbol name.

required
timeframe int

Timeframe constant.

required
date_from datetime

Start date in trade-server time (not UTC).

required
count int

Number of rates to retrieve.

required
skip_to_datetime bool

Whether to skip converting time to datetime.

False

Returns:

Type Description
list[dict[str, Any]]

List of dictionaries with OHLCV data.

Source code in pdmt5/dataframe.py
def copy_rates_from_as_dicts(
    self,
    symbol: str,
    timeframe: int,
    date_from: datetime,
    count: int,
    skip_to_datetime: bool = False,
) -> list[dict[str, Any]]:
    """Get bars for a specified date range as a list of dictionaries.

    Args:
        symbol: Symbol name.
        timeframe: Timeframe constant.
        date_from: Start date in trade-server time (not UTC).
        count: Number of rates to retrieve.
        skip_to_datetime: Whether to skip converting time to datetime.

    Returns:
        List of dictionaries with OHLCV data.
    """
    return self._as_record_dicts(
        self.copy_rates_from_as_df(
            symbol=symbol,
            timeframe=timeframe,
            date_from=date_from,
            count=count,
            skip_to_datetime=skip_to_datetime,
            index_keys=None,
        )
    )

copy_rates_from_pos_as_df

copy_rates_from_pos_as_df(
    symbol: str,
    timeframe: int,
    start_pos: int,
    count: int,
    skip_to_datetime: bool = False,
    index_keys: str | None = None,
) -> DataFrame

Get bars from a specified position as a data frame.

Parameters:

Name Type Description Default
symbol str

Symbol name.

required
timeframe int

Timeframe constant.

required
start_pos int

Start position.

required
count int

Number of rates to retrieve.

required
skip_to_datetime bool

Whether to skip converting time to datetime.

False
index_keys str | None

Column name to set as index if provided.

None

Returns:

Type Description
DataFrame

DataFrame with OHLCV data.

Source code in pdmt5/dataframe.py
@set_index_if_possible(index_parameters="index_keys")
@detect_and_convert_time_to_datetime(skip_toggle="skip_to_datetime")
def copy_rates_from_pos_as_df(
    self,
    symbol: str,
    timeframe: int,
    start_pos: int,
    count: int,
    skip_to_datetime: bool = False,  # noqa: ARG002
    index_keys: str | None = None,  # noqa: ARG002
) -> pd.DataFrame:
    """Get bars from a specified position as a data frame.

    Args:
        symbol: Symbol name.
        timeframe: Timeframe constant.
        start_pos: Start position.
        count: Number of rates to retrieve.
        skip_to_datetime: Whether to skip converting time to datetime.
        index_keys: Column name to set as index if provided.

    Returns:
        DataFrame with OHLCV data.
    """
    self._validate_positive_count(count=count)
    self._validate_non_negative_position(position=start_pos)
    return pd.DataFrame(
        self.copy_rates_from_pos(
            symbol=symbol,
            timeframe=timeframe,
            start_pos=start_pos,
            count=count,
        )
    )

copy_rates_from_pos_as_dicts

copy_rates_from_pos_as_dicts(
    symbol: str,
    timeframe: int,
    start_pos: int,
    count: int,
    skip_to_datetime: bool = False,
) -> list[dict[str, Any]]

Get bars from a specified position as a list of dictionaries.

Parameters:

Name Type Description Default
symbol str

Symbol name.

required
timeframe int

Timeframe constant.

required
start_pos int

Start position.

required
count int

Number of rates to retrieve.

required
skip_to_datetime bool

Whether to skip converting time to datetime.

False

Returns:

Type Description
list[dict[str, Any]]

List of dictionaries with OHLCV data.

Source code in pdmt5/dataframe.py
def copy_rates_from_pos_as_dicts(
    self,
    symbol: str,
    timeframe: int,
    start_pos: int,
    count: int,
    skip_to_datetime: bool = False,
) -> list[dict[str, Any]]:
    """Get bars from a specified position as a list of dictionaries.

    Args:
        symbol: Symbol name.
        timeframe: Timeframe constant.
        start_pos: Start position.
        count: Number of rates to retrieve.
        skip_to_datetime: Whether to skip converting time to datetime.

    Returns:
        List of dictionaries with OHLCV data.
    """
    return self._as_record_dicts(
        self.copy_rates_from_pos_as_df(
            symbol=symbol,
            timeframe=timeframe,
            start_pos=start_pos,
            count=count,
            skip_to_datetime=skip_to_datetime,
            index_keys=None,
        )
    )

copy_rates_range_as_df

copy_rates_range_as_df(
    symbol: str,
    timeframe: int,
    date_from: datetime,
    date_to: datetime,
    skip_to_datetime: bool = False,
    index_keys: str | None = None,
) -> DataFrame

Get bars for a specified date range as a data frame.

Parameters:

Name Type Description Default
symbol str

Symbol name.

required
timeframe int

Timeframe constant.

required
date_from datetime

Start date in trade-server time (not UTC).

required
date_to datetime

End date in trade-server time (not UTC).

required
skip_to_datetime bool

Whether to skip converting time to datetime.

False
index_keys str | None

Column name to set as index if provided.

None

Returns:

Type Description
DataFrame

DataFrame with OHLCV data.

Source code in pdmt5/dataframe.py
@set_index_if_possible(index_parameters="index_keys")
@detect_and_convert_time_to_datetime(skip_toggle="skip_to_datetime")
def copy_rates_range_as_df(
    self,
    symbol: str,
    timeframe: int,
    date_from: datetime,
    date_to: datetime,
    skip_to_datetime: bool = False,  # noqa: ARG002
    index_keys: str | None = None,  # noqa: ARG002
) -> pd.DataFrame:
    """Get bars for a specified date range as a data frame.

    Args:
        symbol: Symbol name.
        timeframe: Timeframe constant.
        date_from: Start date in trade-server time (not UTC).
        date_to: End date in trade-server time (not UTC).
        skip_to_datetime: Whether to skip converting time to datetime.
        index_keys: Column name to set as index if provided.

    Returns:
        DataFrame with OHLCV data.
    """
    self._validate_date_range(date_from=date_from, date_to=date_to)
    return pd.DataFrame(
        self.copy_rates_range(
            symbol=symbol,
            timeframe=timeframe,
            date_from=date_from,
            date_to=date_to,
        )
    )

copy_rates_range_as_dicts

copy_rates_range_as_dicts(
    symbol: str,
    timeframe: int,
    date_from: datetime,
    date_to: datetime,
    skip_to_datetime: bool = False,
) -> list[dict[str, Any]]

Get bars for a specified date range as a list of dictionaries.

Parameters:

Name Type Description Default
symbol str

Symbol name.

required
timeframe int

Timeframe constant.

required
date_from datetime

Start date in trade-server time (not UTC).

required
date_to datetime

End date in trade-server time (not UTC).

required
skip_to_datetime bool

Whether to skip converting time to datetime.

False

Returns:

Type Description
list[dict[str, Any]]

List of dictionaries with OHLCV data.

Source code in pdmt5/dataframe.py
def copy_rates_range_as_dicts(
    self,
    symbol: str,
    timeframe: int,
    date_from: datetime,
    date_to: datetime,
    skip_to_datetime: bool = False,
) -> list[dict[str, Any]]:
    """Get bars for a specified date range as a list of dictionaries.

    Args:
        symbol: Symbol name.
        timeframe: Timeframe constant.
        date_from: Start date in trade-server time (not UTC).
        date_to: End date in trade-server time (not UTC).
        skip_to_datetime: Whether to skip converting time to datetime.

    Returns:
        List of dictionaries with OHLCV data.
    """
    return self._as_record_dicts(
        self.copy_rates_range_as_df(
            symbol=symbol,
            timeframe=timeframe,
            date_from=date_from,
            date_to=date_to,
            skip_to_datetime=skip_to_datetime,
            index_keys=None,
        )
    )

copy_ticks_from_as_df

copy_ticks_from_as_df(
    symbol: str,
    date_from: datetime,
    count: int,
    flags: int,
    skip_to_datetime: bool = False,
    index_keys: str | None = None,
) -> DataFrame

Get ticks from a specified date as a data frame.

Parameters:

Name Type Description Default
symbol str

Symbol name.

required
date_from datetime

Start date in trade-server time (not UTC).

required
count int

Number of ticks to retrieve.

required
flags int

Tick flags (use constants from MetaTrader5).

required
skip_to_datetime bool

Whether to skip converting time to datetime.

False
index_keys str | None

Column name to set as index if provided.

None

Returns:

Type Description
DataFrame

DataFrame with tick data.

Source code in pdmt5/dataframe.py
@set_index_if_possible(index_parameters="index_keys")
@detect_and_convert_time_to_datetime(skip_toggle="skip_to_datetime")
def copy_ticks_from_as_df(
    self,
    symbol: str,
    date_from: datetime,
    count: int,
    flags: int,
    skip_to_datetime: bool = False,  # noqa: ARG002
    index_keys: str | None = None,  # noqa: ARG002
) -> pd.DataFrame:
    """Get ticks from a specified date as a data frame.

    Args:
        symbol: Symbol name.
        date_from: Start date in trade-server time (not UTC).
        count: Number of ticks to retrieve.
        flags: Tick flags (use constants from MetaTrader5).
        skip_to_datetime: Whether to skip converting time to datetime.
        index_keys: Column name to set as index if provided.

    Returns:
        DataFrame with tick data.
    """
    self._validate_positive_count(count=count)
    return pd.DataFrame(
        self.copy_ticks_from(
            symbol=symbol,
            date_from=date_from,
            count=count,
            flags=flags,
        )
    )

copy_ticks_from_as_dicts

copy_ticks_from_as_dicts(
    symbol: str,
    date_from: datetime,
    count: int,
    flags: int,
    skip_to_datetime: bool = False,
) -> list[dict[str, Any]]

Get ticks from a specified date as a list of dictionaries.

Parameters:

Name Type Description Default
symbol str

Symbol name.

required
date_from datetime

Start date in trade-server time (not UTC).

required
count int

Number of ticks to retrieve.

required
flags int

Tick flags (use constants from MetaTrader5).

required
skip_to_datetime bool

Whether to skip converting time to datetime.

False

Returns:

Type Description
list[dict[str, Any]]

List of dictionaries with tick data.

Source code in pdmt5/dataframe.py
def copy_ticks_from_as_dicts(
    self,
    symbol: str,
    date_from: datetime,
    count: int,
    flags: int,
    skip_to_datetime: bool = False,
) -> list[dict[str, Any]]:
    """Get ticks from a specified date as a list of dictionaries.

    Args:
        symbol: Symbol name.
        date_from: Start date in trade-server time (not UTC).
        count: Number of ticks to retrieve.
        flags: Tick flags (use constants from MetaTrader5).
        skip_to_datetime: Whether to skip converting time to datetime.

    Returns:
        List of dictionaries with tick data.
    """
    return self._as_record_dicts(
        self.copy_ticks_from_as_df(
            symbol=symbol,
            date_from=date_from,
            count=count,
            flags=flags,
            skip_to_datetime=skip_to_datetime,
            index_keys=None,
        )
    )

copy_ticks_range_as_df

copy_ticks_range_as_df(
    symbol: str,
    date_from: datetime,
    date_to: datetime,
    flags: int,
    skip_to_datetime: bool = False,
    index_keys: str | None = None,
) -> DataFrame

Get ticks for a specified date range as a data frame.

Parameters:

Name Type Description Default
symbol str

Symbol name.

required
date_from datetime

Start date in trade-server time (not UTC).

required
date_to datetime

End date in trade-server time (not UTC).

required
flags int

Tick flags (use constants from MetaTrader5).

required
skip_to_datetime bool

Whether to skip converting time to datetime.

False
index_keys str | None

Column name to set as index if provided.

None

Returns:

Type Description
DataFrame

DataFrame with tick data.

Source code in pdmt5/dataframe.py
@set_index_if_possible(index_parameters="index_keys")
@detect_and_convert_time_to_datetime(skip_toggle="skip_to_datetime")
def copy_ticks_range_as_df(
    self,
    symbol: str,
    date_from: datetime,
    date_to: datetime,
    flags: int,
    skip_to_datetime: bool = False,  # noqa: ARG002
    index_keys: str | None = None,  # noqa: ARG002
) -> pd.DataFrame:
    """Get ticks for a specified date range as a data frame.

    Args:
        symbol: Symbol name.
        date_from: Start date in trade-server time (not UTC).
        date_to: End date in trade-server time (not UTC).
        flags: Tick flags (use constants from MetaTrader5).
        skip_to_datetime: Whether to skip converting time to datetime.
        index_keys: Column name to set as index if provided.

    Returns:
        DataFrame with tick data.
    """
    self._validate_date_range(date_from=date_from, date_to=date_to)
    return pd.DataFrame(
        self.copy_ticks_range(
            symbol=symbol,
            date_from=date_from,
            date_to=date_to,
            flags=flags,
        )
    )

copy_ticks_range_as_dicts

copy_ticks_range_as_dicts(
    symbol: str,
    date_from: datetime,
    date_to: datetime,
    flags: int,
    skip_to_datetime: bool = False,
) -> list[dict[str, Any]]

Get ticks for a specified date range as a list of dictionaries.

Parameters:

Name Type Description Default
symbol str

Symbol name.

required
date_from datetime

Start date in trade-server time (not UTC).

required
date_to datetime

End date in trade-server time (not UTC).

required
flags int

Tick flags (use constants from MetaTrader5).

required
skip_to_datetime bool

Whether to skip converting time to datetime.

False

Returns:

Type Description
list[dict[str, Any]]

List of dictionaries with tick data.

Source code in pdmt5/dataframe.py
def copy_ticks_range_as_dicts(
    self,
    symbol: str,
    date_from: datetime,
    date_to: datetime,
    flags: int,
    skip_to_datetime: bool = False,
) -> list[dict[str, Any]]:
    """Get ticks for a specified date range as a list of dictionaries.

    Args:
        symbol: Symbol name.
        date_from: Start date in trade-server time (not UTC).
        date_to: End date in trade-server time (not UTC).
        flags: Tick flags (use constants from MetaTrader5).
        skip_to_datetime: Whether to skip converting time to datetime.

    Returns:
        List of dictionaries with tick data.
    """
    return self._as_record_dicts(
        self.copy_ticks_range_as_df(
            symbol=symbol,
            date_from=date_from,
            date_to=date_to,
            flags=flags,
            skip_to_datetime=skip_to_datetime,
            index_keys=None,
        )
    )

history_deals_get_as_df

history_deals_get_as_df(
    date_from: datetime | None = None,
    date_to: datetime | None = None,
    group: str | None = None,
    symbol: str | None = None,
    ticket: int | None = None,
    position: int | None = None,
    skip_to_datetime: bool = False,
    index_keys: str | None = None,
) -> DataFrame

Get historical deals with optional filters as a data frame.

Parameters:

Name Type Description Default
date_from datetime | None

Start date in trade-server time, not UTC (required if not using ticket/position).

None
date_to datetime | None

End date in trade-server time, not UTC (required if not using ticket/position).

None
group str | None

Optional group filter. Mutually exclusive with symbol.

None
symbol str | None

Optional symbol filter matching the symbol name exactly. Mutually exclusive with group.

None
ticket int | None

Get deals by order ticket.

None
position int | None

Get deals by position ticket.

None
skip_to_datetime bool

Whether to skip converting time to datetime.

False
index_keys str | None

Column name to set as index if provided.

None

Returns:

Type Description
DataFrame

DataFrame with historical deal information.

Source code in pdmt5/dataframe.py
@set_index_if_possible(index_parameters="index_keys")
@detect_and_convert_time_to_datetime(skip_toggle="skip_to_datetime")
def history_deals_get_as_df(
    self,
    date_from: datetime | None = None,
    date_to: datetime | None = None,
    group: str | None = None,
    symbol: str | None = None,
    ticket: int | None = None,
    position: int | None = None,
    skip_to_datetime: bool = False,  # noqa: ARG002
    index_keys: str | None = None,  # noqa: ARG002
) -> pd.DataFrame:
    """Get historical deals with optional filters as a data frame.

    Args:
        date_from: Start date in trade-server time, not UTC (required if
            not using ticket/position).
        date_to: End date in trade-server time, not UTC (required if not
            using ticket/position).
        group: Optional group filter. Mutually exclusive with symbol.
        symbol: Optional symbol filter matching the symbol name exactly.
            Mutually exclusive with group.
        ticket: Get deals by order ticket.
        position: Get deals by position ticket.
        skip_to_datetime: Whether to skip converting time to datetime.
        index_keys: Column name to set as index if provided.

    Returns:
        DataFrame with historical deal information.
    """
    return pd.DataFrame(
        self.history_deals_get_as_dicts(
            date_from=date_from,
            date_to=date_to,
            group=group,
            symbol=symbol,
            ticket=ticket,
            position=position,
            skip_to_datetime=True,
        )
    )

history_deals_get_as_dicts

history_deals_get_as_dicts(
    date_from: datetime | None = None,
    date_to: datetime | None = None,
    group: str | None = None,
    symbol: str | None = None,
    ticket: int | None = None,
    position: int | None = None,
    skip_to_datetime: bool = False,
) -> list[dict[str, Any]]

Get historical deals with optional filters as a list of dictionaries.

Parameters:

Name Type Description Default
date_from datetime | None

Start date in trade-server time, not UTC (required if not using ticket/position).

None
date_to datetime | None

End date in trade-server time, not UTC (required if not using ticket/position).

None
group str | None

Optional group filter. Mutually exclusive with symbol.

None
symbol str | None

Optional symbol filter matching the symbol name exactly. Mutually exclusive with group.

None
ticket int | None

Get deals by order ticket.

None
position int | None

Get deals by position ticket.

None
skip_to_datetime bool

Whether to skip converting time to datetime.

False

Returns:

Type Description
list[dict[str, Any]]

List of dictionaries with historical deal information.

Source code in pdmt5/dataframe.py
@detect_and_convert_time_to_datetime(skip_toggle="skip_to_datetime")
def history_deals_get_as_dicts(
    self,
    date_from: datetime | None = None,
    date_to: datetime | None = None,
    group: str | None = None,
    symbol: str | None = None,
    ticket: int | None = None,
    position: int | None = None,
    skip_to_datetime: bool = False,  # noqa: ARG002
) -> list[dict[str, Any]]:
    """Get historical deals with optional filters as a list of dictionaries.

    Args:
        date_from: Start date in trade-server time, not UTC (required if
            not using ticket/position).
        date_to: End date in trade-server time, not UTC (required if not
            using ticket/position).
        group: Optional group filter. Mutually exclusive with symbol.
        symbol: Optional symbol filter matching the symbol name exactly.
            Mutually exclusive with group.
        ticket: Get deals by order ticket.
        position: Get deals by position ticket.
        skip_to_datetime: Whether to skip converting time to datetime.

    Returns:
        List of dictionaries with historical deal information.
    """
    self._validate_history_input(
        date_from=date_from,
        date_to=date_to,
        ticket=ticket,
        position=position,
        group=group,
        symbol=symbol,
    )
    dicts = self._as_dicts(
        self.history_deals_get(
            date_from=date_from,
            date_to=date_to,
            group=(f"*{symbol}*" if symbol else group),
            ticket=ticket,
            position=position,
        )
    )
    return [d for d in dicts if d["symbol"] == symbol] if symbol else dicts

history_orders_get_as_df

history_orders_get_as_df(
    date_from: datetime | None = None,
    date_to: datetime | None = None,
    group: str | None = None,
    symbol: str | None = None,
    ticket: int | None = None,
    position: int | None = None,
    skip_to_datetime: bool = False,
    index_keys: str | None = None,
) -> DataFrame

Get historical orders with optional filters as a data frame.

Parameters:

Name Type Description Default
date_from datetime | None

Start date in trade-server time, not UTC (required if not using ticket/position).

None
date_to datetime | None

End date in trade-server time, not UTC (required if not using ticket/position).

None
group str | None

Optional group filter. Mutually exclusive with symbol.

None
symbol str | None

Optional symbol filter matching the symbol name exactly. Mutually exclusive with group.

None
ticket int | None

Get orders by ticket.

None
position int | None

Get orders by position.

None
skip_to_datetime bool

Whether to skip converting time to datetime.

False
index_keys str | None

Column name to set as index if provided.

None

Returns:

Type Description
DataFrame

DataFrame with historical order information.

Source code in pdmt5/dataframe.py
@set_index_if_possible(index_parameters="index_keys")
@detect_and_convert_time_to_datetime(skip_toggle="skip_to_datetime")
def history_orders_get_as_df(
    self,
    date_from: datetime | None = None,
    date_to: datetime | None = None,
    group: str | None = None,
    symbol: str | None = None,
    ticket: int | None = None,
    position: int | None = None,
    skip_to_datetime: bool = False,  # noqa: ARG002
    index_keys: str | None = None,  # noqa: ARG002
) -> pd.DataFrame:
    """Get historical orders with optional filters as a data frame.

    Args:
        date_from: Start date in trade-server time, not UTC (required if
            not using ticket/position).
        date_to: End date in trade-server time, not UTC (required if not
            using ticket/position).
        group: Optional group filter. Mutually exclusive with symbol.
        symbol: Optional symbol filter matching the symbol name exactly.
            Mutually exclusive with group.
        ticket: Get orders by ticket.
        position: Get orders by position.
        skip_to_datetime: Whether to skip converting time to datetime.
        index_keys: Column name to set as index if provided.

    Returns:
        DataFrame with historical order information.
    """
    return pd.DataFrame(
        self.history_orders_get_as_dicts(
            date_from=date_from,
            date_to=date_to,
            group=group,
            symbol=symbol,
            ticket=ticket,
            position=position,
            skip_to_datetime=True,
        )
    )

history_orders_get_as_dicts

history_orders_get_as_dicts(
    date_from: datetime | None = None,
    date_to: datetime | None = None,
    group: str | None = None,
    symbol: str | None = None,
    ticket: int | None = None,
    position: int | None = None,
    skip_to_datetime: bool = False,
) -> list[dict[str, Any]]

Get historical orders with optional filters as a list of dictionaries.

Parameters:

Name Type Description Default
date_from datetime | None

Start date in trade-server time, not UTC (required if not using ticket/position).

None
date_to datetime | None

End date in trade-server time, not UTC (required if not using ticket/position).

None
group str | None

Optional group filter. Mutually exclusive with symbol.

None
symbol str | None

Optional symbol filter matching the symbol name exactly. Mutually exclusive with group.

None
ticket int | None

Get orders by ticket.

None
position int | None

Get orders by position.

None
skip_to_datetime bool

Whether to skip converting time to datetime.

False

Returns:

Type Description
list[dict[str, Any]]

List of dictionaries with historical order information.

Source code in pdmt5/dataframe.py
@detect_and_convert_time_to_datetime(skip_toggle="skip_to_datetime")
def history_orders_get_as_dicts(
    self,
    date_from: datetime | None = None,
    date_to: datetime | None = None,
    group: str | None = None,
    symbol: str | None = None,
    ticket: int | None = None,
    position: int | None = None,
    skip_to_datetime: bool = False,  # noqa: ARG002
) -> list[dict[str, Any]]:
    """Get historical orders with optional filters as a list of dictionaries.

    Args:
        date_from: Start date in trade-server time, not UTC (required if
            not using ticket/position).
        date_to: End date in trade-server time, not UTC (required if not
            using ticket/position).
        group: Optional group filter. Mutually exclusive with symbol.
        symbol: Optional symbol filter matching the symbol name exactly.
            Mutually exclusive with group.
        ticket: Get orders by ticket.
        position: Get orders by position.
        skip_to_datetime: Whether to skip converting time to datetime.

    Returns:
        List of dictionaries with historical order information.
    """
    self._validate_history_input(
        date_from=date_from,
        date_to=date_to,
        ticket=ticket,
        position=position,
        group=group,
        symbol=symbol,
    )
    dicts = self._as_dicts(
        self.history_orders_get(
            date_from=date_from,
            date_to=date_to,
            group=(f"*{symbol}*" if symbol else group),
            ticket=ticket,
            position=position,
        )
    )
    return [d for d in dicts if d["symbol"] == symbol] if symbol else dicts

initialize_and_login_mt5

initialize_and_login_mt5(
    path: str | None = None,
    login: int | None = None,
    password: str | SecretStr | None = None,
    server: str | None = None,
    timeout: int | None = None,
) -> None

Initialize MT5 and ensure the requested account is active.

MetaTrader5.initialize() accepts account credentials and normally connects directly to the requested account. After initialization, this method verifies the active account and only calls login() when the terminal reports a different account, avoiding redundant authentication while preserving account-switch fallback behavior.

Parameters:

Name Type Description Default
path str | None

Path to terminal EXE file (overrides config).

None
login int | None

Account login (overrides config).

None
password str | SecretStr | None

Account password (overrides config).

None
server str | None

Server name (overrides config).

None
timeout int | None

Connection timeout (overrides config).

None

Raises:

Type Description
Mt5RuntimeError

If initialization or account selection fails after retries.

Source code in pdmt5/dataframe.py
def initialize_and_login_mt5(
    self,
    path: str | None = None,
    login: int | None = None,
    password: str | SecretStr | None = None,
    server: str | None = None,
    timeout: int | None = None,
) -> None:
    """Initialize MT5 and ensure the requested account is active.

    ``MetaTrader5.initialize()`` accepts account credentials and normally
    connects directly to the requested account. After initialization, this
    method verifies the active account and only calls ``login()`` when the
    terminal reports a different account, avoiding redundant authentication
    while preserving account-switch fallback behavior.

    Args:
        path: Path to terminal EXE file (overrides config).
        login: Account login (overrides config).
        password: Account password (overrides config).
        server: Server name (overrides config).
        timeout: Connection timeout (overrides config).

    Raises:
        Mt5RuntimeError: If initialization or account selection fails after retries.
    """
    path = path or self.config.path
    login_value = login if login is not None else self.config.login
    password_value = self._unwrap_password(
        password if password is not None else self.config.password
    )
    server_value = server if server is not None else self.config.server
    timeout_value = timeout if timeout is not None else self.config.timeout
    last_error_value: tuple[int, str] | None = None
    for i in range(1 + max(0, self.retry_count)):
        if i:
            logger.warning(
                "Retrying MT5 initialization (%d/%d)...",
                i,
                self.retry_count,
            )
            time.sleep(i)
        if not self.initialize(
            path=path,
            login=login_value,
            password=password_value,
            server=server_value,
            timeout=timeout_value,
        ):
            last_error_value = self.last_error()
            continue
        if login_value is None:
            return
        try:
            active_account = self.account_info()
        except Mt5RuntimeError:
            active_account = None
        if active_account is not None and (
            getattr(active_account, "login", None) == login_value
            and (
                server_value is None
                or getattr(active_account, "server", None) == server_value
            )
        ):
            return
        try:
            if self.login(
                login=login_value,
                password=password_value,
                server=server_value,
                timeout=timeout_value,
            ):
                return
        except Exception:
            self.shutdown()
            raise
        last_error_value = self.last_error()
        self.shutdown()
    error_message = (
        f"MT5 initialize and login failed after {self.retry_count} retries:"
        f" {last_error_value}"
    )
    raise Mt5RuntimeError(error_message)

last_error_as_df

last_error_as_df(
    index_keys: str | None = None,
) -> DataFrame

Get the last error information as a data frame.

Parameters:

Name Type Description Default
index_keys str | None

Column name to set as index if provided.

None

Returns:

Type Description
DataFrame

DataFrame with last error information.

Source code in pdmt5/dataframe.py
@set_index_if_possible(index_parameters="index_keys")
def last_error_as_df(self, index_keys: str | None = None) -> pd.DataFrame:  # noqa: ARG002
    """Get the last error information as a data frame.

    Args:
        index_keys: Column name to set as index if provided.

    Returns:
        DataFrame with last error information.
    """
    return self._as_single_row_df(self.last_error_as_dict())

last_error_as_dict

last_error_as_dict() -> dict[str, Any]

Get the last error information as a dictionary.

Returns:

Type Description
dict[str, Any]

Dictionary with last error information.

Source code in pdmt5/dataframe.py
def last_error_as_dict(self) -> dict[str, Any]:
    """Get the last error information as a dictionary.

    Returns:
        Dictionary with last error information.
    """
    response = self.last_error()
    return {"error_code": response[0], "error_description": response[1]}

market_book_get_as_df

market_book_get_as_df(
    symbol: str,
    skip_to_datetime: bool = False,
    index_keys: str | None = None,
) -> DataFrame

Get market depth for a specified symbol as a data frame.

Parameters:

Name Type Description Default
symbol str

Symbol name.

required
skip_to_datetime bool

Whether to skip converting time to datetime.

False
index_keys str | None

Column name to set as index if provided.

None

Returns:

Type Description
DataFrame

DataFrame with market depth data.

Source code in pdmt5/dataframe.py
@set_index_if_possible(index_parameters="index_keys")
@detect_and_convert_time_to_datetime(skip_toggle="skip_to_datetime")
def market_book_get_as_df(
    self,
    symbol: str,
    skip_to_datetime: bool = False,  # noqa: ARG002
    index_keys: str | None = None,  # noqa: ARG002
) -> pd.DataFrame:
    """Get market depth for a specified symbol as a data frame.

    Args:
        symbol: Symbol name.
        skip_to_datetime: Whether to skip converting time to datetime.
        index_keys: Column name to set as index if provided.

    Returns:
        DataFrame with market depth data.
    """
    return pd.DataFrame(
        self.market_book_get_as_dicts(symbol=symbol, skip_to_datetime=True)
    )

market_book_get_as_dicts

market_book_get_as_dicts(
    symbol: str, skip_to_datetime: bool = False
) -> list[dict[str, Any]]

Get market depth for a specified symbol as a list of dictionaries.

Parameters:

Name Type Description Default
symbol str

Symbol name.

required
skip_to_datetime bool

Whether to skip converting time to datetime.

False

Returns:

Type Description
list[dict[str, Any]]

List of dictionaries with market depth data.

Source code in pdmt5/dataframe.py
@detect_and_convert_time_to_datetime(skip_toggle="skip_to_datetime")
def market_book_get_as_dicts(
    self,
    symbol: str,
    skip_to_datetime: bool = False,  # noqa: ARG002
) -> list[dict[str, Any]]:
    """Get market depth for a specified symbol as a list of dictionaries.

    Args:
        symbol: Symbol name.
        skip_to_datetime: Whether to skip converting time to datetime.

    Returns:
        List of dictionaries with market depth data.
    """
    return self._as_dicts(self.market_book_get(symbol=symbol))

order_check_as_df

order_check_as_df(
    request: dict[str, Any], index_keys: str | None = None
) -> DataFrame

Check funds sufficiency for performing a requested trading operation as a data frame.

Parameters:

Name Type Description Default
request dict[str, Any]

Order request parameters.

required
index_keys str | None

Column name to set as index if provided.

None

Returns:

Type Description
DataFrame

DataFrame with order check results.

Source code in pdmt5/dataframe.py
@set_index_if_possible(index_parameters="index_keys")
def order_check_as_df(
    self,
    request: dict[str, Any],
    index_keys: str | None = None,  # noqa: ARG002
) -> pd.DataFrame:
    """Check funds sufficiency for performing a requested trading operation as a data frame.

    Args:
        request: Order request parameters.
        index_keys: Column name to set as index if provided.

    Returns:
        DataFrame with order check results.
    """  # noqa: E501
    return self._as_single_row_df(
        self._flatten_dict_to_one_level(
            dictionary=self.order_check_as_dict(request=request),
        )
    )

order_check_as_dict

order_check_as_dict(
    request: dict[str, Any],
) -> dict[str, Any]

Check funds sufficiency for performing a requested trading operation as a dictionary.

Parameters:

Name Type Description Default
request dict[str, Any]

Order request parameters.

required

Returns:

Type Description
dict[str, Any]

Dictionary with order check results.

Source code in pdmt5/dataframe.py
def order_check_as_dict(self, request: dict[str, Any]) -> dict[str, Any]:
    """Check funds sufficiency for performing a requested trading operation as a dictionary.

    Args:
        request: Order request parameters.

    Returns:
        Dictionary with order check results.
    """  # noqa: E501
    return self._as_order_result_dict(self.order_check(request=request))

order_send_as_df

order_send_as_df(
    request: dict[str, Any], index_keys: str | None = None
) -> DataFrame

Send a request to perform a trading operation from the terminal to the trade server as a data frame.

Parameters:

Name Type Description Default
request dict[str, Any]

Order request parameters.

required
index_keys str | None

Column name to set as index if provided.

None

Returns:

Type Description
DataFrame

DataFrame with order send results.

Source code in pdmt5/dataframe.py
@set_index_if_possible(index_parameters="index_keys")
def order_send_as_df(
    self,
    request: dict[str, Any],
    index_keys: str | None = None,  # noqa: ARG002
) -> pd.DataFrame:
    """Send a request to perform a trading operation from the terminal to the trade server as a data frame.

    Args:
        request: Order request parameters.
        index_keys: Column name to set as index if provided.

    Returns:
        DataFrame with order send results.
    """  # noqa: E501
    return self._as_single_row_df(
        self._flatten_dict_to_one_level(
            dictionary=self.order_send_as_dict(request=request),
        )
    )

order_send_as_dict

order_send_as_dict(
    request: dict[str, Any],
) -> dict[str, Any]

Send a request to perform a trading operation from the terminal to the trade server as a dictionary.

Parameters:

Name Type Description Default
request dict[str, Any]

Order request parameters.

required

Returns:

Type Description
dict[str, Any]

Dictionary with order send results.

Source code in pdmt5/dataframe.py
def order_send_as_dict(self, request: dict[str, Any]) -> dict[str, Any]:
    """Send a request to perform a trading operation from the terminal to the trade server as a dictionary.

    Args:
        request: Order request parameters.

    Returns:
        Dictionary with order send results.
    """  # noqa: E501
    return self._as_order_result_dict(self.order_send(request=request))

orders_get_as_df

orders_get_as_df(
    symbol: str | None = None,
    group: str | None = None,
    ticket: int | None = None,
    skip_to_datetime: bool = False,
    index_keys: str | None = None,
) -> DataFrame

Get active orders with optional filters as a data frame.

Parameters:

Name Type Description Default
symbol str | None

Optional symbol filter. Mutually exclusive with group and ticket.

None
group str | None

Optional group filter. Mutually exclusive with symbol and ticket.

None
ticket int | None

Optional order ticket filter. Mutually exclusive with symbol and group.

None
skip_to_datetime bool

Whether to skip converting time to datetime.

False
index_keys str | None

Column name to set as index if provided.

None

Returns:

Type Description
DataFrame

DataFrame with order information or empty DataFrame if no orders.

Source code in pdmt5/dataframe.py
@set_index_if_possible(index_parameters="index_keys")
@detect_and_convert_time_to_datetime(skip_toggle="skip_to_datetime")
def orders_get_as_df(
    self,
    symbol: str | None = None,
    group: str | None = None,
    ticket: int | None = None,
    skip_to_datetime: bool = False,  # noqa: ARG002
    index_keys: str | None = None,  # noqa: ARG002
) -> pd.DataFrame:
    """Get active orders with optional filters as a data frame.

    Args:
        symbol: Optional symbol filter. Mutually exclusive with group and
            ticket.
        group: Optional group filter. Mutually exclusive with symbol and
            ticket.
        ticket: Optional order ticket filter. Mutually exclusive with
            symbol and group.
        skip_to_datetime: Whether to skip converting time to datetime.
        index_keys: Column name to set as index if provided.

    Returns:
        DataFrame with order information or empty DataFrame if no orders.
    """
    return pd.DataFrame(
        self.orders_get_as_dicts(
            symbol=symbol,
            group=group,
            ticket=ticket,
            skip_to_datetime=True,
        )
    )

orders_get_as_dicts

orders_get_as_dicts(
    symbol: str | None = None,
    group: str | None = None,
    ticket: int | None = None,
    skip_to_datetime: bool = False,
) -> list[dict[str, Any]]

Get active orders with optional filters as a list of dictionaries.

Parameters:

Name Type Description Default
symbol str | None

Optional symbol filter. Mutually exclusive with group and ticket.

None
group str | None

Optional group filter. Mutually exclusive with symbol and ticket.

None
ticket int | None

Optional order ticket filter. Mutually exclusive with symbol and group.

None
skip_to_datetime bool

Whether to skip converting time to datetime.

False

Returns:

Type Description
list[dict[str, Any]]

List of dictionaries with order information or empty list if no orders.

Source code in pdmt5/dataframe.py
@detect_and_convert_time_to_datetime(skip_toggle="skip_to_datetime")
def orders_get_as_dicts(
    self,
    symbol: str | None = None,
    group: str | None = None,
    ticket: int | None = None,
    skip_to_datetime: bool = False,  # noqa: ARG002
) -> list[dict[str, Any]]:
    """Get active orders with optional filters as a list of dictionaries.

    Args:
        symbol: Optional symbol filter. Mutually exclusive with group and
            ticket.
        group: Optional group filter. Mutually exclusive with symbol and
            ticket.
        ticket: Optional order ticket filter. Mutually exclusive with
            symbol and group.
        skip_to_datetime: Whether to skip converting time to datetime.

    Returns:
        List of dictionaries with order information or empty list if no orders.
    """
    return self._as_dicts(
        self.orders_get(symbol=symbol, group=group, ticket=ticket)
    )

positions_get_as_df

positions_get_as_df(
    symbol: str | None = None,
    group: str | None = None,
    ticket: int | None = None,
    skip_to_datetime: bool = False,
    index_keys: str | None = None,
) -> DataFrame

Get open positions with optional filters as a data frame.

Parameters:

Name Type Description Default
symbol str | None

Optional symbol filter. Mutually exclusive with group and ticket.

None
group str | None

Optional group filter. Mutually exclusive with symbol and ticket.

None
ticket int | None

Optional position ticket filter. Mutually exclusive with symbol and group.

None
skip_to_datetime bool

Whether to skip converting time to datetime.

False
index_keys str | None

Column name to set as index if provided.

None

Returns:

Type Description
DataFrame

DataFrame with position information or empty DataFrame if no positions.

Source code in pdmt5/dataframe.py
@set_index_if_possible(index_parameters="index_keys")
@detect_and_convert_time_to_datetime(skip_toggle="skip_to_datetime")
def positions_get_as_df(
    self,
    symbol: str | None = None,
    group: str | None = None,
    ticket: int | None = None,
    skip_to_datetime: bool = False,  # noqa: ARG002
    index_keys: str | None = None,  # noqa: ARG002
) -> pd.DataFrame:
    """Get open positions with optional filters as a data frame.

    Args:
        symbol: Optional symbol filter. Mutually exclusive with group and
            ticket.
        group: Optional group filter. Mutually exclusive with symbol and
            ticket.
        ticket: Optional position ticket filter. Mutually exclusive with
            symbol and group.
        skip_to_datetime: Whether to skip converting time to datetime.
        index_keys: Column name to set as index if provided.

    Returns:
        DataFrame with position information or empty DataFrame if no positions.
    """
    return pd.DataFrame(
        self.positions_get_as_dicts(
            symbol=symbol,
            group=group,
            ticket=ticket,
            skip_to_datetime=True,
        )
    )

positions_get_as_dicts

positions_get_as_dicts(
    symbol: str | None = None,
    group: str | None = None,
    ticket: int | None = None,
    skip_to_datetime: bool = False,
) -> list[dict[str, Any]]

Get open positions with optional filters as a list of dictionaries.

Parameters:

Name Type Description Default
symbol str | None

Optional symbol filter. Mutually exclusive with group and ticket.

None
group str | None

Optional group filter. Mutually exclusive with symbol and ticket.

None
ticket int | None

Optional position ticket filter. Mutually exclusive with symbol and group.

None
skip_to_datetime bool

Whether to skip converting time to datetime.

False

Returns:

Type Description
list[dict[str, Any]]

List of dictionaries with position information or empty list if no

list[dict[str, Any]]

positions.

Source code in pdmt5/dataframe.py
@detect_and_convert_time_to_datetime(skip_toggle="skip_to_datetime")
def positions_get_as_dicts(
    self,
    symbol: str | None = None,
    group: str | None = None,
    ticket: int | None = None,
    skip_to_datetime: bool = False,  # noqa: ARG002
) -> list[dict[str, Any]]:
    """Get open positions with optional filters as a list of dictionaries.

    Args:
        symbol: Optional symbol filter. Mutually exclusive with group and
            ticket.
        group: Optional group filter. Mutually exclusive with symbol and
            ticket.
        ticket: Optional position ticket filter. Mutually exclusive with
            symbol and group.
        skip_to_datetime: Whether to skip converting time to datetime.

    Returns:
        List of dictionaries with position information or empty list if no
        positions.
    """
    return self._as_dicts(
        self.positions_get(symbol=symbol, group=group, ticket=ticket)
    )

symbol_info_as_df

symbol_info_as_df(
    symbol: str,
    skip_to_datetime: bool = False,
    index_keys: str | None = None,
) -> DataFrame

Get data on a specific symbol as a data frame.

Parameters:

Name Type Description Default
symbol str

Symbol name.

required
skip_to_datetime bool

Whether to skip converting time to datetime.

False
index_keys str | None

Column name to set as index if provided.

None

Returns:

Type Description
DataFrame

DataFrame with symbol information.

Source code in pdmt5/dataframe.py
@set_index_if_possible(index_parameters="index_keys")
@detect_and_convert_time_to_datetime(skip_toggle="skip_to_datetime")
def symbol_info_as_df(
    self,
    symbol: str,
    skip_to_datetime: bool = False,  # noqa: ARG002
    index_keys: str | None = None,  # noqa: ARG002
) -> pd.DataFrame:
    """Get data on a specific symbol as a data frame.

    Args:
        symbol: Symbol name.
        skip_to_datetime: Whether to skip converting time to datetime.
        index_keys: Column name to set as index if provided.

    Returns:
        DataFrame with symbol information.
    """
    return self._as_single_row_df(
        self.symbol_info_as_dict(symbol=symbol, skip_to_datetime=True)
    )

symbol_info_as_dict

symbol_info_as_dict(
    symbol: str, skip_to_datetime: bool = False
) -> dict[str, Any]

Get data on a specific symbol as a dictionary.

Parameters:

Name Type Description Default
symbol str

Symbol name.

required
skip_to_datetime bool

Whether to skip converting time to datetime.

False

Returns:

Type Description
dict[str, Any]

Dictionary with symbol information.

Source code in pdmt5/dataframe.py
@detect_and_convert_time_to_datetime(skip_toggle="skip_to_datetime")
def symbol_info_as_dict(
    self,
    symbol: str,
    skip_to_datetime: bool = False,  # noqa: ARG002
) -> dict[str, Any]:
    """Get data on a specific symbol as a dictionary.

    Args:
        symbol: Symbol name.
        skip_to_datetime: Whether to skip converting time to datetime.

    Returns:
        Dictionary with symbol information.
    """
    return self.symbol_info(symbol=symbol)._asdict()

symbol_info_tick_as_df

symbol_info_tick_as_df(
    symbol: str,
    skip_to_datetime: bool = False,
    index_keys: str | None = None,
) -> DataFrame

Get the last tick for the specified financial instrument as a data frame.

Parameters:

Name Type Description Default
symbol str

Symbol name.

required
skip_to_datetime bool

Whether to skip converting time to datetime.

False
index_keys str | None

Column name to set as index if provided.

None

Returns:

Type Description
DataFrame

DataFrame with tick information.

Source code in pdmt5/dataframe.py
@set_index_if_possible(index_parameters="index_keys")
@detect_and_convert_time_to_datetime(skip_toggle="skip_to_datetime")
def symbol_info_tick_as_df(
    self,
    symbol: str,
    skip_to_datetime: bool = False,  # noqa: ARG002
    index_keys: str | None = None,  # noqa: ARG002
) -> pd.DataFrame:
    """Get the last tick for the specified financial instrument as a data frame.

    Args:
        symbol: Symbol name.
        skip_to_datetime: Whether to skip converting time to datetime.
        index_keys: Column name to set as index if provided.

    Returns:
        DataFrame with tick information.
    """
    return self._as_single_row_df(
        self.symbol_info_tick_as_dict(symbol=symbol, skip_to_datetime=True)
    )

symbol_info_tick_as_dict

symbol_info_tick_as_dict(
    symbol: str, skip_to_datetime: bool = False
) -> dict[str, Any]

Get the last tick for the specified financial instrument as a dictionary.

Parameters:

Name Type Description Default
symbol str

Symbol name.

required
skip_to_datetime bool

Whether to skip converting time to datetime.

False

Returns:

Type Description
dict[str, Any]

Dictionary with tick information.

Source code in pdmt5/dataframe.py
@detect_and_convert_time_to_datetime(skip_toggle="skip_to_datetime")
def symbol_info_tick_as_dict(
    self,
    symbol: str,
    skip_to_datetime: bool = False,  # noqa: ARG002
) -> dict[str, Any]:
    """Get the last tick for the specified financial instrument as a dictionary.

    Args:
        symbol: Symbol name.
        skip_to_datetime: Whether to skip converting time to datetime.

    Returns:
        Dictionary with tick information.
    """
    return self.symbol_info_tick(symbol=symbol)._asdict()

symbols_get_as_df

symbols_get_as_df(
    group: str | None = None,
    skip_to_datetime: bool = False,
    index_keys: str | None = None,
) -> DataFrame

Get symbols as a data frame.

Parameters:

Name Type Description Default
group str | None

Symbol group filter (e.g., "USD", "Forex*").

None
skip_to_datetime bool

Whether to skip converting time to datetime.

False
index_keys str | None

Column name to set as index if provided.

None

Returns:

Type Description
DataFrame

DataFrame with symbol information.

Source code in pdmt5/dataframe.py
@set_index_if_possible(index_parameters="index_keys")
@detect_and_convert_time_to_datetime(skip_toggle="skip_to_datetime")
def symbols_get_as_df(
    self,
    group: str | None = None,
    skip_to_datetime: bool = False,  # noqa: ARG002
    index_keys: str | None = None,  # noqa: ARG002
) -> pd.DataFrame:
    """Get symbols as a data frame.

    Args:
        group: Symbol group filter (e.g., "*USD*", "Forex*").
        skip_to_datetime: Whether to skip converting time to datetime.
        index_keys: Column name to set as index if provided.

    Returns:
        DataFrame with symbol information.
    """
    return pd.DataFrame(
        self.symbols_get_as_dicts(group=group, skip_to_datetime=True)
    )

symbols_get_as_dicts

symbols_get_as_dicts(
    group: str | None = None, skip_to_datetime: bool = False
) -> list[dict[str, Any]]

Get symbols as a list of dictionaries.

Parameters:

Name Type Description Default
group str | None

Symbol group filter (e.g., "USD", "Forex*").

None
skip_to_datetime bool

Whether to skip converting time to datetime.

False

Returns:

Type Description
list[dict[str, Any]]

List of dictionaries with symbol information.

Source code in pdmt5/dataframe.py
@detect_and_convert_time_to_datetime(skip_toggle="skip_to_datetime")
def symbols_get_as_dicts(
    self,
    group: str | None = None,
    skip_to_datetime: bool = False,  # noqa: ARG002
) -> list[dict[str, Any]]:
    """Get symbols as a list of dictionaries.

    Args:
        group: Symbol group filter (e.g., "*USD*", "Forex*").
        skip_to_datetime: Whether to skip converting time to datetime.

    Returns:
        List of dictionaries with symbol information.
    """
    return self._as_dicts(self.symbols_get(group=group))

terminal_info_as_df

terminal_info_as_df(
    index_keys: str | None = None,
) -> DataFrame

Get the connected terminal status and settings as a data frame.

Parameters:

Name Type Description Default
index_keys str | None

Column name to set as index if provided.

None

Returns:

Type Description
DataFrame

DataFrame with terminal information.

Source code in pdmt5/dataframe.py
@set_index_if_possible(index_parameters="index_keys")
def terminal_info_as_df(self, index_keys: str | None = None) -> pd.DataFrame:  # noqa: ARG002
    """Get the connected terminal status and settings as a data frame.

    Args:
        index_keys: Column name to set as index if provided.

    Returns:
        DataFrame with terminal information.
    """
    return self._as_single_row_df(self.terminal_info_as_dict())

terminal_info_as_dict

terminal_info_as_dict() -> dict[str, Any]

Get the connected terminal status and settings as a dictionary.

Returns:

Type Description
dict[str, Any]

Dictionary with terminal information.

Source code in pdmt5/dataframe.py
def terminal_info_as_dict(self) -> dict[str, Any]:
    """Get the connected terminal status and settings as a dictionary.

    Returns:
        Dictionary with terminal information.
    """
    return self.terminal_info()._asdict()

version_as_df

version_as_df(index_keys: str | None = None) -> DataFrame

Return MetaTrader5 version information as a data frame.

Parameters:

Name Type Description Default
index_keys str | None

Column name to set as index if provided.

None

Returns:

Type Description
DataFrame

DataFrame with MetaTrader5 version information.

Source code in pdmt5/dataframe.py
@set_index_if_possible(index_parameters="index_keys")
def version_as_df(self, index_keys: str | None = None) -> pd.DataFrame:  # noqa: ARG002
    """Return MetaTrader5 version information as a data frame.

    Args:
        index_keys: Column name to set as index if provided.

    Returns:
        DataFrame with MetaTrader5 version information.
    """
    return self._as_single_row_df(self.version_as_dict())

version_as_dict

version_as_dict() -> dict[str, int | str]

Return MetaTrader5 version information as a dictionary.

Returns:

Type Description
dict[str, int | str]

Dictionary with MetaTrader5 version information.

Source code in pdmt5/dataframe.py
def version_as_dict(self) -> dict[str, int | str]:
    """Return MetaTrader5 version information as a dictionary.

    Returns:
        Dictionary with MetaTrader5 version information.
    """
    response = self.version()
    return {
        "mt5_terminal_version": response[0],
        "build": response[1],
        "build_release_date": response[2],
    }

options: show_bases: false

Extended client class that inherits from Mt5Client and provides a pandas-friendly interface to MetaTrader 5 functions with automatic DataFrame conversion.

Usage Examples

Basic Connection

import MetaTrader5 as mt5
from pdmt5.dataframe import Mt5DataClient, Mt5Config

# Create configuration
config = Mt5Config(login=123456, password="your_password", server="broker_server")

# Create client
client = Mt5DataClient(mt5=mt5, config=config)

# Use as context manager: entering the block initializes the connection and
# logs in with the config credentials automatically
with client:
    # Get account information
    account_df = client.account_info_as_df()
    print(account_df)

Retrieving Market Data

from datetime import datetime
from pdmt5 import parse_copy_ticks, parse_timeframe

with client:
    # Get OHLCV data
    rates_df = client.copy_rates_from_as_df(
        symbol="EURUSD",
        timeframe=parse_timeframe("H1"),
        date_from=datetime(2024, 1, 1),
        count=1000,
    )

    # Get tick data
    ticks_df = client.copy_ticks_from_as_df(
        symbol="EURUSD",
        date_from=datetime(2024, 1, 1),
        count=1000,
        flags=parse_copy_ticks("ALL"),
    )

Symbol Information

with client:
    # Get all symbols
    symbols_df = client.symbols_get_as_df()

    # Get specific symbol info
    symbol_info_df = client.symbol_info_as_df("EURUSD")

    # Get current tick
    tick_df = client.symbol_info_tick_as_df("EURUSD")

Trading History

from datetime import datetime

with client:
    # Get historical orders
    orders_df = client.history_orders_get_as_df(
        date_from=datetime(2024, 1, 1), date_to=datetime(2024, 1, 31), symbol="EURUSD"
    )

    # Get historical deals
    deals_df = client.history_deals_get_as_df(
        date_from=datetime(2024, 1, 1), date_to=datetime(2024, 1, 31)
    )

Current Positions and Orders

with client:
    # Get current positions
    positions_df = client.positions_get_as_df()

    # Get current orders
    orders_df = client.orders_get_as_df(symbol="EURUSD")

Data Conversion Features

The Mt5DataClient automatically handles:

  • Time Conversion: Converts Unix timestamps to pandas datetime objects
  • Index Setting: Sets appropriate datetime indexes for time-series data
  • DataFrame Creation: Converts MetaTrader 5 named tuples to pandas DataFrames
  • Error Handling: Provides meaningful error messages for failed operations
  • Empty Data: Returns empty DataFrames when no data is available

Error Handling

All methods raise Mt5RuntimeError exceptions with detailed error information when operations fail:

from pdmt5.mt5 import Mt5RuntimeError

try:
    rates_df = client.copy_rates_from_as_df(
        "INVALID", mt5.TIMEFRAME_H1, datetime.now(), 100
    )
except Mt5RuntimeError as e:
    print(f"MetaTrader 5 error: {e}")

Connection Management

The client supports both explicit and context manager usage:

# Explicit initialization
client.initialize()
try:
    # Your trading operations
    pass
finally:
    client.shutdown()

# Context manager (recommended)
with client:
    # Your trading operations
    pass

Type Safety

All methods include comprehensive type hints and use pydantic for configuration validation, ensuring type safety throughout the codebase.