pdmt5


Namepdmt5 JSON
Version 0.1.2 PyPI version JSON
download
home_pageNone
SummaryPandas-based data handler for MetaTrader 5
upload_time2025-07-21 12:31:00
maintainerNone
docs_urlNone
authorNone
requires_python>=3.11
licenseNone
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # pdmt5

Pandas-based data handler for MetaTrader 5

[![CI/CD](https://github.com/dceoy/pdmt5/actions/workflows/ci.yml/badge.svg)](https://github.com/dceoy/pdmt5/actions/workflows/ci.yml)
[![Python Version](https://img.shields.io/badge/python-3.11%2B-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Platform](https://img.shields.io/badge/platform-Windows-blue.svg)](https://www.microsoft.com/windows)

## Overview

**pdmt5** is a Python package that provides a pandas-based interface for MetaTrader 5 (MT5), making it easier to work with financial market data in Python. It automatically converts MT5's native data structures into pandas DataFrames, enabling seamless integration with data science workflows.

### Key Features

- 📊 **Pandas Integration**: All data returned as pandas DataFrames for easy analysis
- 🔧 **Type Safety**: Full type hints with strict pyright checking and pydantic validation
- 🏦 **Comprehensive MT5 Coverage**: Account info, market data, tick data, orders, positions, and more
- 🚀 **Context Manager Support**: Clean initialization and cleanup with `with` statements
- 📈 **Time Series Ready**: OHLCV data with proper datetime indexing
- 🛡️ **Robust Error Handling**: Custom exceptions with detailed MT5 error information

## Requirements

- **Operating System**: Windows (required by MetaTrader5 API)
- **Python**: 3.11 or higher
- **MetaTrader 5**: Terminal must be installed

## Installation

### From GitHub

```bash
git clone https://github.com/dceoy/pdmt5.git
pip install -U --no-cache-dir ./pdmt5
```

### Using uv (recommended for development)

```bash
git clone https://github.com/dceoy/pdmt5.git
cd pdmt5
uv sync
```

## Quick Start

```python
import MetaTrader5 as mt5
from datetime import datetime
from pdmt5 import Mt5DataClient, Mt5Config

# Configure connection
config = Mt5Config(
    login=12345678,
    password="your_password",
    server="YourBroker-Server",
    timeout=60000,
    portable=False
)

# Use as context manager
with Mt5DataClient(config=config) as client:
    # Get account information as DataFrame
    account_info = client.get_account_info_as_df()
    print(account_info)

    # Get OHLCV data as DataFrame
    rates = client.copy_rates_from_as_df(
        symbol="EURUSD",
        timeframe=mt5.TIMEFRAME_H1,
        date_from=datetime(2024, 1, 1),
        count=100
    )
    print(rates.head())

    # Get current positions as DataFrame
    positions = client.get_positions_as_df()
    print(positions)
```

## Core Components

### Mt5Client

The base client for MT5 operations with context manager support:

- **Connection Management**: `initialize()`, `login()`, `shutdown()`
- **Account & Terminal Info**: Access account details and terminal information
- **Symbol Operations**: Get symbol information and market data
- **Trading Operations**: Execute orders, manage positions and deals
- **History Access**: Retrieve historical orders and deals

### Mt5DataClient

Extends Mt5Client with pandas DataFrame conversions:

- **DataFrame Methods**: All data methods have `_as_df` variants returning DataFrames
- **Dictionary Methods**: All data methods have `_as_dict` variants returning dictionaries
- **Account Operations**: `get_account_info()`, `get_terminal_info()`
- **Market Data**: `copy_rates_*()` methods for OHLCV data
- **Tick Data**: `copy_ticks_*()` methods for tick-level data
- **Trading Info**: `get_orders()`, `get_positions()`, `get_deals()`
- **Symbol Info**: `get_symbols()`, `get_symbol_info()`

### Mt5TradingClient

Advanced trading operations interface that extends Mt5DataClient:

- **Position Management**: `close_open_positions()` - Close positions by symbol
- **Order Filling Modes**: IOC (Immediate or Cancel), FOK (Fill or Kill), or RETURN
- **Dry Run Mode**: Test trading logic without executing real trades
- **Full Trading Operations**: Includes all Mt5DataClient capabilities plus trading features

### Configuration

```python
from pdmt5 import Mt5Config

config = Mt5Config(
    login=12345678,          # MT5 account number
    password="password",     # MT5 password
    server="Broker-Server",  # MT5 server name
    timeout=60000,          # Connection timeout in ms
    portable=False          # Use portable mode
)
```

## Examples

### Getting Historical Data

```python
import MetaTrader5 as mt5
from datetime import datetime

with Mt5DataClient(config=config) as client:
    # Get last 1000 H1 bars for EURUSD as DataFrame
    df = client.copy_rates_from_as_df(
        symbol="EURUSD",
        timeframe=mt5.TIMEFRAME_H1,
        date_from=datetime.now(),
        count=1000
    )

    # Data includes: time, open, high, low, close, tick_volume, spread, real_volume
    print(df.columns)
    print(df.describe())
```

### Working with Tick Data

```python
from datetime import datetime, timedelta

with Mt5DataClient(config=config) as client:
    # Get ticks for the last hour as DataFrame
    ticks = client.copy_ticks_from_as_df(
        symbol="EURUSD",
        date_from=datetime.now() - timedelta(hours=1),
        count=10000,
        flags=mt5.COPY_TICKS_ALL
    )

    # Tick data includes: time, bid, ask, last, volume, flags
    print(ticks.head())
```

### Analyzing Positions

```python
with Mt5DataClient(config=config) as client:
    # Get all open positions as DataFrame
    positions = client.get_positions_as_df()

    if not positions.empty:
        # Calculate summary statistics
        summary = positions.groupby('symbol').agg({
            'volume': 'sum',
            'profit': 'sum',
            'price_open': 'mean'
        })
        print(summary)
```

### Trading Operations

```python
from pdmt5 import Mt5TradingClient

# Create trading client with specific order filling mode
with Mt5TradingClient(config=config, order_filling_mode="IOC") as trader:
    # Close all EURUSD positions
    results = trader.close_open_positions(symbols="EURUSD")

    if results:
        for result in results:
            print(f"Closed position {result['position']} with result: {result['retcode']}")

    # Using dry run mode for testing
    trader_dry = Mt5TradingClient(config=config, dry_run=True)
    with trader_dry:
        # Test closing positions without actual execution
        test_results = trader_dry.close_open_positions(symbols=["EURUSD", "GBPUSD"])
```

## Development

### Setup Development Environment

```bash
# Clone repository
git clone https://github.com/dceoy/pdmt5.git
cd pdmt5

# Install with uv
uv sync

# Run tests
uv run pytest test/ -v

# Run type checking
uv run pyright .

# Run linting
uv run ruff check --fix .
uv run ruff format .
```

### Code Quality

This project maintains high code quality standards:

- **Type Checking**: Strict mode with pyright
- **Linting**: Comprehensive ruff configuration with 40+ rule categories
- **Testing**: pytest with coverage tracking (minimum 90%)
- **Documentation**: Google-style docstrings

## Error Handling

The package provides detailed error information:

```python
from pdmt5 import Mt5RuntimeError

try:
    with Mt5DataClient(config=config) as client:
        data = client.copy_rates_from("INVALID", mt5.TIMEFRAME_H1, datetime.now(), 100)
except Mt5RuntimeError as e:
    print(f"MT5 Error: {e}")
    print(f"Error code: {e.error_code}")
    print(f"Description: {e.description}")
```

## Limitations

- **Windows Only**: Due to MetaTrader5 API requirements
- **MT5 Terminal Required**: The MetaTrader 5 terminal must be installed
- **Single Thread**: MT5 API is not thread-safe

## Contributing

Contributions are welcome! Please:

1. Fork the repository
2. Create a feature branch
3. Ensure tests pass and coverage is maintained
4. Submit a pull request

See [CLAUDE.md](CLAUDE.md) for development guidelines.

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## Author

Daichi Narushima, Ph.D.

## Acknowledgments

- MetaTrader 5 for providing the Python API
- The pandas community for the excellent data manipulation tools

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "pdmt5",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.11",
    "maintainer_email": "dceoy <dceoy@users.noreply.github.com>",
    "keywords": null,
    "author": null,
    "author_email": "dceoy <dceoy@users.noreply.github.com>",
    "download_url": "https://files.pythonhosted.org/packages/0a/ba/c176537f68085681d8ac8781e7231d3fce5732c200279d6222c348cb23be/pdmt5-0.1.2.tar.gz",
    "platform": null,
    "description": "# pdmt5\n\nPandas-based data handler for MetaTrader 5\n\n[![CI/CD](https://github.com/dceoy/pdmt5/actions/workflows/ci.yml/badge.svg)](https://github.com/dceoy/pdmt5/actions/workflows/ci.yml)\n[![Python Version](https://img.shields.io/badge/python-3.11%2B-blue.svg)](https://www.python.org/downloads/)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n[![Platform](https://img.shields.io/badge/platform-Windows-blue.svg)](https://www.microsoft.com/windows)\n\n## Overview\n\n**pdmt5** is a Python package that provides a pandas-based interface for MetaTrader 5 (MT5), making it easier to work with financial market data in Python. It automatically converts MT5's native data structures into pandas DataFrames, enabling seamless integration with data science workflows.\n\n### Key Features\n\n- \ud83d\udcca **Pandas Integration**: All data returned as pandas DataFrames for easy analysis\n- \ud83d\udd27 **Type Safety**: Full type hints with strict pyright checking and pydantic validation\n- \ud83c\udfe6 **Comprehensive MT5 Coverage**: Account info, market data, tick data, orders, positions, and more\n- \ud83d\ude80 **Context Manager Support**: Clean initialization and cleanup with `with` statements\n- \ud83d\udcc8 **Time Series Ready**: OHLCV data with proper datetime indexing\n- \ud83d\udee1\ufe0f **Robust Error Handling**: Custom exceptions with detailed MT5 error information\n\n## Requirements\n\n- **Operating System**: Windows (required by MetaTrader5 API)\n- **Python**: 3.11 or higher\n- **MetaTrader 5**: Terminal must be installed\n\n## Installation\n\n### From GitHub\n\n```bash\ngit clone https://github.com/dceoy/pdmt5.git\npip install -U --no-cache-dir ./pdmt5\n```\n\n### Using uv (recommended for development)\n\n```bash\ngit clone https://github.com/dceoy/pdmt5.git\ncd pdmt5\nuv sync\n```\n\n## Quick Start\n\n```python\nimport MetaTrader5 as mt5\nfrom datetime import datetime\nfrom pdmt5 import Mt5DataClient, Mt5Config\n\n# Configure connection\nconfig = Mt5Config(\n    login=12345678,\n    password=\"your_password\",\n    server=\"YourBroker-Server\",\n    timeout=60000,\n    portable=False\n)\n\n# Use as context manager\nwith Mt5DataClient(config=config) as client:\n    # Get account information as DataFrame\n    account_info = client.get_account_info_as_df()\n    print(account_info)\n\n    # Get OHLCV data as DataFrame\n    rates = client.copy_rates_from_as_df(\n        symbol=\"EURUSD\",\n        timeframe=mt5.TIMEFRAME_H1,\n        date_from=datetime(2024, 1, 1),\n        count=100\n    )\n    print(rates.head())\n\n    # Get current positions as DataFrame\n    positions = client.get_positions_as_df()\n    print(positions)\n```\n\n## Core Components\n\n### Mt5Client\n\nThe base client for MT5 operations with context manager support:\n\n- **Connection Management**: `initialize()`, `login()`, `shutdown()`\n- **Account & Terminal Info**: Access account details and terminal information\n- **Symbol Operations**: Get symbol information and market data\n- **Trading Operations**: Execute orders, manage positions and deals\n- **History Access**: Retrieve historical orders and deals\n\n### Mt5DataClient\n\nExtends Mt5Client with pandas DataFrame conversions:\n\n- **DataFrame Methods**: All data methods have `_as_df` variants returning DataFrames\n- **Dictionary Methods**: All data methods have `_as_dict` variants returning dictionaries\n- **Account Operations**: `get_account_info()`, `get_terminal_info()`\n- **Market Data**: `copy_rates_*()` methods for OHLCV data\n- **Tick Data**: `copy_ticks_*()` methods for tick-level data\n- **Trading Info**: `get_orders()`, `get_positions()`, `get_deals()`\n- **Symbol Info**: `get_symbols()`, `get_symbol_info()`\n\n### Mt5TradingClient\n\nAdvanced trading operations interface that extends Mt5DataClient:\n\n- **Position Management**: `close_open_positions()` - Close positions by symbol\n- **Order Filling Modes**: IOC (Immediate or Cancel), FOK (Fill or Kill), or RETURN\n- **Dry Run Mode**: Test trading logic without executing real trades\n- **Full Trading Operations**: Includes all Mt5DataClient capabilities plus trading features\n\n### Configuration\n\n```python\nfrom pdmt5 import Mt5Config\n\nconfig = Mt5Config(\n    login=12345678,          # MT5 account number\n    password=\"password\",     # MT5 password\n    server=\"Broker-Server\",  # MT5 server name\n    timeout=60000,          # Connection timeout in ms\n    portable=False          # Use portable mode\n)\n```\n\n## Examples\n\n### Getting Historical Data\n\n```python\nimport MetaTrader5 as mt5\nfrom datetime import datetime\n\nwith Mt5DataClient(config=config) as client:\n    # Get last 1000 H1 bars for EURUSD as DataFrame\n    df = client.copy_rates_from_as_df(\n        symbol=\"EURUSD\",\n        timeframe=mt5.TIMEFRAME_H1,\n        date_from=datetime.now(),\n        count=1000\n    )\n\n    # Data includes: time, open, high, low, close, tick_volume, spread, real_volume\n    print(df.columns)\n    print(df.describe())\n```\n\n### Working with Tick Data\n\n```python\nfrom datetime import datetime, timedelta\n\nwith Mt5DataClient(config=config) as client:\n    # Get ticks for the last hour as DataFrame\n    ticks = client.copy_ticks_from_as_df(\n        symbol=\"EURUSD\",\n        date_from=datetime.now() - timedelta(hours=1),\n        count=10000,\n        flags=mt5.COPY_TICKS_ALL\n    )\n\n    # Tick data includes: time, bid, ask, last, volume, flags\n    print(ticks.head())\n```\n\n### Analyzing Positions\n\n```python\nwith Mt5DataClient(config=config) as client:\n    # Get all open positions as DataFrame\n    positions = client.get_positions_as_df()\n\n    if not positions.empty:\n        # Calculate summary statistics\n        summary = positions.groupby('symbol').agg({\n            'volume': 'sum',\n            'profit': 'sum',\n            'price_open': 'mean'\n        })\n        print(summary)\n```\n\n### Trading Operations\n\n```python\nfrom pdmt5 import Mt5TradingClient\n\n# Create trading client with specific order filling mode\nwith Mt5TradingClient(config=config, order_filling_mode=\"IOC\") as trader:\n    # Close all EURUSD positions\n    results = trader.close_open_positions(symbols=\"EURUSD\")\n\n    if results:\n        for result in results:\n            print(f\"Closed position {result['position']} with result: {result['retcode']}\")\n\n    # Using dry run mode for testing\n    trader_dry = Mt5TradingClient(config=config, dry_run=True)\n    with trader_dry:\n        # Test closing positions without actual execution\n        test_results = trader_dry.close_open_positions(symbols=[\"EURUSD\", \"GBPUSD\"])\n```\n\n## Development\n\n### Setup Development Environment\n\n```bash\n# Clone repository\ngit clone https://github.com/dceoy/pdmt5.git\ncd pdmt5\n\n# Install with uv\nuv sync\n\n# Run tests\nuv run pytest test/ -v\n\n# Run type checking\nuv run pyright .\n\n# Run linting\nuv run ruff check --fix .\nuv run ruff format .\n```\n\n### Code Quality\n\nThis project maintains high code quality standards:\n\n- **Type Checking**: Strict mode with pyright\n- **Linting**: Comprehensive ruff configuration with 40+ rule categories\n- **Testing**: pytest with coverage tracking (minimum 90%)\n- **Documentation**: Google-style docstrings\n\n## Error Handling\n\nThe package provides detailed error information:\n\n```python\nfrom pdmt5 import Mt5RuntimeError\n\ntry:\n    with Mt5DataClient(config=config) as client:\n        data = client.copy_rates_from(\"INVALID\", mt5.TIMEFRAME_H1, datetime.now(), 100)\nexcept Mt5RuntimeError as e:\n    print(f\"MT5 Error: {e}\")\n    print(f\"Error code: {e.error_code}\")\n    print(f\"Description: {e.description}\")\n```\n\n## Limitations\n\n- **Windows Only**: Due to MetaTrader5 API requirements\n- **MT5 Terminal Required**: The MetaTrader 5 terminal must be installed\n- **Single Thread**: MT5 API is not thread-safe\n\n## Contributing\n\nContributions are welcome! Please:\n\n1. Fork the repository\n2. Create a feature branch\n3. Ensure tests pass and coverage is maintained\n4. Submit a pull request\n\nSee [CLAUDE.md](CLAUDE.md) for development guidelines.\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n## Author\n\nDaichi Narushima, Ph.D.\n\n## Acknowledgments\n\n- MetaTrader 5 for providing the Python API\n- The pandas community for the excellent data manipulation tools\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "Pandas-based data handler for MetaTrader 5",
    "version": "0.1.2",
    "project_urls": {
        "Repository": "https://github.com/dceoy/pdmt5.git"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "9915c7142acb29e5848e505e75e4cebf284c4be2de651731cb7168256f049b64",
                "md5": "4732b724e441f6d18f40132b302b6cea",
                "sha256": "5283ba30c5dcdb0ad7e5f259457034633d3abf4cf4a030743c407532c4708d54"
            },
            "downloads": -1,
            "filename": "pdmt5-0.1.2-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "4732b724e441f6d18f40132b302b6cea",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.11",
            "size": 17916,
            "upload_time": "2025-07-21T12:30:59",
            "upload_time_iso_8601": "2025-07-21T12:30:59.286027Z",
            "url": "https://files.pythonhosted.org/packages/99/15/c7142acb29e5848e505e75e4cebf284c4be2de651731cb7168256f049b64/pdmt5-0.1.2-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "0abac176537f68085681d8ac8781e7231d3fce5732c200279d6222c348cb23be",
                "md5": "1b5748a3eae408b0f87c10a1b5d7b828",
                "sha256": "a3537f71be63a30d363e50709e1e4496aae3abdc3c56b7090d11efa36ed4ffd7"
            },
            "downloads": -1,
            "filename": "pdmt5-0.1.2.tar.gz",
            "has_sig": false,
            "md5_digest": "1b5748a3eae408b0f87c10a1b5d7b828",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.11",
            "size": 108153,
            "upload_time": "2025-07-21T12:31:00",
            "upload_time_iso_8601": "2025-07-21T12:31:00.480671Z",
            "url": "https://files.pythonhosted.org/packages/0a/ba/c176537f68085681d8ac8781e7231d3fce5732c200279d6222c348cb23be/pdmt5-0.1.2.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-07-21 12:31:00",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "dceoy",
    "github_project": "pdmt5",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "pdmt5"
}
        
Elapsed time: 0.51810s