mt5api 1.0.6__tar.gz → 2.0.1__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {mt5api-1.0.6 → mt5api-2.0.1}/PKG-INFO +16 -8
- {mt5api-1.0.6 → mt5api-2.0.1}/README.md +14 -6
- {mt5api-1.0.6 → mt5api-2.0.1}/mt5api/constants.py +4 -3
- {mt5api-1.0.6 → mt5api-2.0.1}/mt5api/dependencies.py +74 -25
- {mt5api-1.0.6 → mt5api-2.0.1}/mt5api/middleware.py +15 -4
- {mt5api-1.0.6 → mt5api-2.0.1}/mt5api/models.py +118 -23
- {mt5api-1.0.6 → mt5api-2.0.1}/mt5api/routers/connection.py +2 -1
- {mt5api-1.0.6 → mt5api-2.0.1}/mt5api/routers/health.py +1 -1
- {mt5api-1.0.6 → mt5api-2.0.1}/mt5api/routers/trading.py +114 -4
- {mt5api-1.0.6 → mt5api-2.0.1}/pyproject.toml +2 -2
- {mt5api-1.0.6 → mt5api-2.0.1}/.gitignore +0 -0
- {mt5api-1.0.6 → mt5api-2.0.1}/LICENSE +0 -0
- {mt5api-1.0.6 → mt5api-2.0.1}/mt5api/__init__.py +0 -0
- {mt5api-1.0.6 → mt5api-2.0.1}/mt5api/__main__.py +0 -0
- {mt5api-1.0.6 → mt5api-2.0.1}/mt5api/auth.py +0 -0
- {mt5api-1.0.6 → mt5api-2.0.1}/mt5api/config.py +0 -0
- {mt5api-1.0.6 → mt5api-2.0.1}/mt5api/formatters.py +0 -0
- {mt5api-1.0.6 → mt5api-2.0.1}/mt5api/main.py +0 -0
- {mt5api-1.0.6 → mt5api-2.0.1}/mt5api/routers/__init__.py +0 -0
- {mt5api-1.0.6 → mt5api-2.0.1}/mt5api/routers/account.py +0 -0
- {mt5api-1.0.6 → mt5api-2.0.1}/mt5api/routers/calc.py +0 -0
- {mt5api-1.0.6 → mt5api-2.0.1}/mt5api/routers/history.py +0 -0
- {mt5api-1.0.6 → mt5api-2.0.1}/mt5api/routers/market.py +0 -0
- {mt5api-1.0.6 → mt5api-2.0.1}/mt5api/routers/symbols.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: mt5api
|
|
3
|
-
Version:
|
|
3
|
+
Version: 2.0.1
|
|
4
4
|
Summary: MetaTrader 5 REST API
|
|
5
5
|
Project-URL: Repository, https://github.com/dceoy/mt5api.git
|
|
6
6
|
Author-email: dceoy <dceoy@users.noreply.github.com>
|
|
@@ -18,7 +18,7 @@ Classifier: Topic :: Office/Business :: Financial :: Investment
|
|
|
18
18
|
Requires-Python: <3.15,>=3.11
|
|
19
19
|
Requires-Dist: fastapi>=0.115.0
|
|
20
20
|
Requires-Dist: pandas>=3.0.3
|
|
21
|
-
Requires-Dist: pdmt5>=1.2.
|
|
21
|
+
Requires-Dist: pdmt5>=1.2.4
|
|
22
22
|
Requires-Dist: pyarrow>=18.0.0
|
|
23
23
|
Requires-Dist: pydantic>=2.13.4
|
|
24
24
|
Requires-Dist: uvicorn[standard]>=0.32.0
|
|
@@ -37,11 +37,11 @@ provides the core MT5 client, dataframe/order primitives, and canonical MT5
|
|
|
37
37
|
constant parsing. mt5api adds optional API-key auth and JSON/Parquet response
|
|
38
38
|
formatting.
|
|
39
39
|
|
|
40
|
-
The
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
`
|
|
44
|
-
implement strategy orchestration.
|
|
40
|
+
The API supports all MetaTrader5 Python functions through REST operations or
|
|
41
|
+
application-managed connection lifecycle. Live order submission
|
|
42
|
+
(`POST /order/send`) is **disabled by default** and requires both
|
|
43
|
+
`MT5API_ENABLE_ORDER_SEND=true` and `MT5API_SECRET_KEY`. The server does
|
|
44
|
+
not implement strategy orchestration.
|
|
45
45
|
|
|
46
46
|
The API server must run on Windows. pdmt5 connects through the MetaTrader 5
|
|
47
47
|
Python API, which is supported only on Windows, so you must host `mt5api` on a
|
|
@@ -118,7 +118,7 @@ uv sync
|
|
|
118
118
|
After installing from PyPI:
|
|
119
119
|
|
|
120
120
|
```powershell
|
|
121
|
-
$env:MT5API_SECRET_KEY = "your-secret-api-key" #
|
|
121
|
+
$env:MT5API_SECRET_KEY = "your-secret-api-key" # Required for live order sends
|
|
122
122
|
$env:MT5API_ROUTER_PREFIX = "/api/v1" # Optional: omit for root-level routes
|
|
123
123
|
python -m mt5api
|
|
124
124
|
```
|
|
@@ -146,6 +146,14 @@ the same.
|
|
|
146
146
|
Set `MT5API_MAX_MARKET_BOOK_SUBSCRIPTIONS` to cap active market-book
|
|
147
147
|
subscriptions. The default limit is `100`.
|
|
148
148
|
|
|
149
|
+
To explicitly allow live order submission on a trusted Windows host, set
|
|
150
|
+
`MT5API_ENABLE_ORDER_SEND=true` **and** `MT5API_SECRET_KEY` before launching
|
|
151
|
+
the server. Never expose a trading-enabled instance directly to the public
|
|
152
|
+
Internet; use HTTPS, network access controls, and a dedicated least-privilege
|
|
153
|
+
trading account. With either setting missing, `POST /order/send` returns 403.
|
|
154
|
+
The endpoint does not automatically call `order_check` or retry requests;
|
|
155
|
+
clients must examine the MT5 `retcode` and avoid ambiguous duplicate orders.
|
|
156
|
+
|
|
149
157
|
## Example Requests with curl
|
|
150
158
|
|
|
151
159
|
Replace `windows-host` with the DNS name or IP address of the Windows machine
|
|
@@ -11,11 +11,11 @@ provides the core MT5 client, dataframe/order primitives, and canonical MT5
|
|
|
11
11
|
constant parsing. mt5api adds optional API-key auth and JSON/Parquet response
|
|
12
12
|
formatting.
|
|
13
13
|
|
|
14
|
-
The
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
`
|
|
18
|
-
implement strategy orchestration.
|
|
14
|
+
The API supports all MetaTrader5 Python functions through REST operations or
|
|
15
|
+
application-managed connection lifecycle. Live order submission
|
|
16
|
+
(`POST /order/send`) is **disabled by default** and requires both
|
|
17
|
+
`MT5API_ENABLE_ORDER_SEND=true` and `MT5API_SECRET_KEY`. The server does
|
|
18
|
+
not implement strategy orchestration.
|
|
19
19
|
|
|
20
20
|
The API server must run on Windows. pdmt5 connects through the MetaTrader 5
|
|
21
21
|
Python API, which is supported only on Windows, so you must host `mt5api` on a
|
|
@@ -92,7 +92,7 @@ uv sync
|
|
|
92
92
|
After installing from PyPI:
|
|
93
93
|
|
|
94
94
|
```powershell
|
|
95
|
-
$env:MT5API_SECRET_KEY = "your-secret-api-key" #
|
|
95
|
+
$env:MT5API_SECRET_KEY = "your-secret-api-key" # Required for live order sends
|
|
96
96
|
$env:MT5API_ROUTER_PREFIX = "/api/v1" # Optional: omit for root-level routes
|
|
97
97
|
python -m mt5api
|
|
98
98
|
```
|
|
@@ -120,6 +120,14 @@ the same.
|
|
|
120
120
|
Set `MT5API_MAX_MARKET_BOOK_SUBSCRIPTIONS` to cap active market-book
|
|
121
121
|
subscriptions. The default limit is `100`.
|
|
122
122
|
|
|
123
|
+
To explicitly allow live order submission on a trusted Windows host, set
|
|
124
|
+
`MT5API_ENABLE_ORDER_SEND=true` **and** `MT5API_SECRET_KEY` before launching
|
|
125
|
+
the server. Never expose a trading-enabled instance directly to the public
|
|
126
|
+
Internet; use HTTPS, network access controls, and a dedicated least-privilege
|
|
127
|
+
trading account. With either setting missing, `POST /order/send` returns 403.
|
|
128
|
+
The endpoint does not automatically call `order_check` or retry requests;
|
|
129
|
+
clients must examine the MT5 `retcode` and avoid ambiguous duplicate orders.
|
|
130
|
+
|
|
123
131
|
## Example Requests with curl
|
|
124
132
|
|
|
125
133
|
Replace `windows-host` with the DNS name or IP address of the Windows machine
|
|
@@ -4,9 +4,9 @@ from importlib.metadata import version
|
|
|
4
4
|
|
|
5
5
|
API_TITLE = "MT5 REST API"
|
|
6
6
|
API_DESCRIPTION = (
|
|
7
|
-
"REST API for MetaTrader 5 data
|
|
8
|
-
"
|
|
9
|
-
"and
|
|
7
|
+
"REST API for MetaTrader 5 market data, account information, trading history, "
|
|
8
|
+
"calculations, and terminal utilities. Live order submission is disabled "
|
|
9
|
+
"by default and requires explicit opt-in and API-key authentication."
|
|
10
10
|
)
|
|
11
11
|
API_VERSION = version("mt5api")
|
|
12
12
|
API_DOCS_URL = "/docs"
|
|
@@ -22,6 +22,7 @@ ENV_MT5API_PORT = "MT5API_PORT"
|
|
|
22
22
|
ENV_MT5API_LOG_LEVEL = "MT5API_LOG_LEVEL"
|
|
23
23
|
ENV_MT5API_ROUTER_PREFIX = "MT5API_ROUTER_PREFIX"
|
|
24
24
|
ENV_MT5API_MAX_MARKET_BOOK_SUBSCRIPTIONS = "MT5API_MAX_MARKET_BOOK_SUBSCRIPTIONS"
|
|
25
|
+
ENV_MT5API_ENABLE_ORDER_SEND = "MT5API_ENABLE_ORDER_SEND"
|
|
25
26
|
ENV_MT5API_SECRET_KEY = "MT5API_SECRET_KEY" # ruff: ignore[hardcoded-password-string]
|
|
26
27
|
|
|
27
28
|
DEFAULT_API_HOST = "0.0.0.0" # ruff: ignore[hardcoded-bind-all-interfaces]
|
|
@@ -80,37 +80,85 @@ def get_mt5_client_lock(request: Request) -> asyncio.Lock:
|
|
|
80
80
|
return get_mt5_runtime_state(request).client_lock
|
|
81
81
|
|
|
82
82
|
|
|
83
|
-
def
|
|
84
|
-
"""
|
|
83
|
+
def shutdown_mt5_client(state: Mt5RuntimeState) -> None:
|
|
84
|
+
"""Shutdown and clear the application-scoped MT5 client."""
|
|
85
|
+
client = state.client
|
|
86
|
+
if client is None:
|
|
87
|
+
return
|
|
88
|
+
state.client = None
|
|
89
|
+
client.shutdown()
|
|
85
90
|
|
|
86
|
-
|
|
87
|
-
|
|
91
|
+
|
|
92
|
+
async def _initialize_and_install_client(
|
|
93
|
+
state: Mt5RuntimeState,
|
|
94
|
+
client: Mt5DataClient,
|
|
95
|
+
) -> None:
|
|
96
|
+
"""Initialize ``client`` in a thread and install it as the active client.
|
|
97
|
+
|
|
98
|
+
The native initialization cannot be interrupted and changes MetaTrader5's
|
|
99
|
+
process-global connection. If the caller is cancelled, this waits for the
|
|
100
|
+
thread to finish and installs the client when it succeeded, so
|
|
101
|
+
``state.client`` always matches the terminal's connected account before the
|
|
102
|
+
caller releases ``state.client_lock``.
|
|
103
|
+
|
|
104
|
+
Raises:
|
|
105
|
+
asyncio.CancelledError: If cancelled, after the thread has finished.
|
|
106
|
+
"""
|
|
107
|
+
init_task = asyncio.ensure_future(
|
|
108
|
+
asyncio.to_thread(client.initialize_and_login_mt5)
|
|
109
|
+
)
|
|
110
|
+
try:
|
|
111
|
+
await asyncio.shield(init_task)
|
|
112
|
+
except asyncio.CancelledError:
|
|
113
|
+
while not init_task.done():
|
|
114
|
+
await asyncio.wait({init_task})
|
|
115
|
+
if init_task.exception() is None:
|
|
116
|
+
state.client = client
|
|
117
|
+
raise
|
|
118
|
+
state.client = client
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
async def ensure_mt5_client(state: Mt5RuntimeState) -> Mt5DataClient:
|
|
122
|
+
"""Return the active client, initializing the default one if needed.
|
|
123
|
+
|
|
124
|
+
Callers must hold ``state.client_lock`` so initialization cannot overlap an
|
|
125
|
+
account change.
|
|
88
126
|
|
|
89
127
|
Returns:
|
|
90
|
-
|
|
128
|
+
Active initialized MT5 data client.
|
|
91
129
|
|
|
92
130
|
Raises:
|
|
93
131
|
RuntimeError: If MT5 client initialization fails.
|
|
94
132
|
"""
|
|
95
|
-
state
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
return state.client
|
|
133
|
+
if state.client is not None:
|
|
134
|
+
return state.client
|
|
135
|
+
client = Mt5DataClient(config=Mt5Config())
|
|
136
|
+
try:
|
|
137
|
+
await _initialize_and_install_client(state, client)
|
|
138
|
+
except Exception as exc:
|
|
139
|
+
error_message = f"Failed to initialize MT5 client: {exc!s}"
|
|
140
|
+
raise RuntimeError(error_message) from exc
|
|
141
|
+
return client
|
|
105
142
|
|
|
106
143
|
|
|
107
|
-
def
|
|
108
|
-
"""
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
144
|
+
async def get_mt5_client(request: Request) -> Mt5DataClient:
|
|
145
|
+
"""Get or lazily create the application-scoped MT5 client instance.
|
|
146
|
+
|
|
147
|
+
Initialization is serialized with account changes and live order submission
|
|
148
|
+
by ``state.client_lock``. When a client already exists no native
|
|
149
|
+
initialization can occur, so the lock is not taken.
|
|
150
|
+
|
|
151
|
+
Args:
|
|
152
|
+
request: Request whose application owns the MT5 runtime state.
|
|
153
|
+
|
|
154
|
+
Returns:
|
|
155
|
+
Shared initialized MT5 data client.
|
|
156
|
+
"""
|
|
157
|
+
state = get_mt5_runtime_state(request)
|
|
158
|
+
if state.client is not None:
|
|
159
|
+
return state.client
|
|
160
|
+
async with state.client_lock:
|
|
161
|
+
return await ensure_mt5_client(state)
|
|
114
162
|
|
|
115
163
|
|
|
116
164
|
async def replace_mt5_client(
|
|
@@ -121,6 +169,8 @@ async def replace_mt5_client(
|
|
|
121
169
|
|
|
122
170
|
MetaTrader5 connection state is process-global, so the previous wrapper is
|
|
123
171
|
not shut down after success because doing so could close the new session.
|
|
172
|
+
If the caller is cancelled mid-initialization, the call waits for the native
|
|
173
|
+
thread and keeps ``state.client`` consistent with the connected account.
|
|
124
174
|
|
|
125
175
|
Returns:
|
|
126
176
|
Newly initialized and installed client.
|
|
@@ -128,14 +178,13 @@ async def replace_mt5_client(
|
|
|
128
178
|
Raises:
|
|
129
179
|
RuntimeError: If the replacement cannot be initialized.
|
|
130
180
|
"""
|
|
181
|
+
new_client = Mt5DataClient(config=config)
|
|
131
182
|
try:
|
|
132
|
-
|
|
133
|
-
await asyncio.to_thread(new_client.initialize_and_login_mt5)
|
|
183
|
+
await _initialize_and_install_client(state, new_client)
|
|
134
184
|
except Exception as exc:
|
|
135
185
|
logger.exception("Failed to initialize MT5 client")
|
|
136
186
|
error_message = "Failed to initialize MT5 client"
|
|
137
187
|
raise RuntimeError(error_message) from exc
|
|
138
|
-
state.client = new_client
|
|
139
188
|
return new_client
|
|
140
189
|
|
|
141
190
|
|
|
@@ -6,16 +6,17 @@ import logging
|
|
|
6
6
|
import time
|
|
7
7
|
from typing import TYPE_CHECKING, Any, cast
|
|
8
8
|
|
|
9
|
-
from fastapi import
|
|
9
|
+
from fastapi import Request, status
|
|
10
10
|
from fastapi.exceptions import RequestValidationError
|
|
11
11
|
from fastapi.responses import JSONResponse
|
|
12
12
|
from pdmt5.mt5 import Mt5RuntimeError
|
|
13
13
|
from pydantic import ValidationError
|
|
14
|
+
from starlette.exceptions import HTTPException
|
|
14
15
|
|
|
15
16
|
from .models import ErrorResponse
|
|
16
17
|
|
|
17
18
|
if TYPE_CHECKING:
|
|
18
|
-
from collections.abc import Sequence
|
|
19
|
+
from collections.abc import Mapping, Sequence
|
|
19
20
|
|
|
20
21
|
from fastapi import FastAPI
|
|
21
22
|
from starlette.middleware.base import RequestResponseEndpoint
|
|
@@ -60,6 +61,7 @@ def _create_error_response(
|
|
|
60
61
|
status_code: int,
|
|
61
62
|
detail: str,
|
|
62
63
|
instance: str,
|
|
64
|
+
headers: Mapping[str, str] | None = None,
|
|
63
65
|
) -> JSONResponse:
|
|
64
66
|
"""Create a RFC 7807 Problem Details error response.
|
|
65
67
|
|
|
@@ -69,6 +71,7 @@ def _create_error_response(
|
|
|
69
71
|
status_code: HTTP status code.
|
|
70
72
|
detail: Detailed error explanation.
|
|
71
73
|
instance: Request URI that caused the error.
|
|
74
|
+
headers: Optional response headers (e.g. ``Allow`` for 405).
|
|
72
75
|
|
|
73
76
|
Returns:
|
|
74
77
|
JSONResponse with error details.
|
|
@@ -80,7 +83,11 @@ def _create_error_response(
|
|
|
80
83
|
detail=detail,
|
|
81
84
|
instance=instance,
|
|
82
85
|
)
|
|
83
|
-
return JSONResponse(
|
|
86
|
+
return JSONResponse(
|
|
87
|
+
status_code=status_code,
|
|
88
|
+
content=error.model_dump(),
|
|
89
|
+
headers=headers,
|
|
90
|
+
)
|
|
84
91
|
|
|
85
92
|
|
|
86
93
|
async def error_handler_middleware(
|
|
@@ -199,7 +206,10 @@ def http_exception_handler(
|
|
|
199
206
|
request: Request,
|
|
200
207
|
exc: HTTPException,
|
|
201
208
|
) -> JSONResponse:
|
|
202
|
-
"""Convert
|
|
209
|
+
"""Convert HTTP exceptions to flat RFC 7807 responses.
|
|
210
|
+
|
|
211
|
+
Registered for Starlette's base class so router-level errors (404, 405)
|
|
212
|
+
are covered as well as FastAPI ``HTTPException`` subclasses.
|
|
203
213
|
|
|
204
214
|
Returns:
|
|
205
215
|
Problem Details JSON response.
|
|
@@ -220,6 +230,7 @@ def http_exception_handler(
|
|
|
220
230
|
exc.status_code,
|
|
221
231
|
detail,
|
|
222
232
|
str(request.url),
|
|
233
|
+
headers=exc.headers,
|
|
223
234
|
)
|
|
224
235
|
|
|
225
236
|
|
|
@@ -491,6 +491,22 @@ class OrdersRequest(BaseModel):
|
|
|
491
491
|
format: ResponseFormat | None = Field(default=None)
|
|
492
492
|
|
|
493
493
|
|
|
494
|
+
def _validate_date_range(date_from: datetime, date_to: datetime) -> None:
|
|
495
|
+
"""Ensure ``date_from`` precedes ``date_to``.
|
|
496
|
+
|
|
497
|
+
Raises:
|
|
498
|
+
ValueError: If the range is empty or mixes naive and aware datetimes.
|
|
499
|
+
"""
|
|
500
|
+
try:
|
|
501
|
+
is_empty = date_from >= date_to
|
|
502
|
+
except TypeError as error:
|
|
503
|
+
message = "date_from and date_to must both include or both omit a UTC offset"
|
|
504
|
+
raise ValueError(message) from error
|
|
505
|
+
if is_empty:
|
|
506
|
+
range_error = "date_from must be before date_to"
|
|
507
|
+
raise ValueError(range_error)
|
|
508
|
+
|
|
509
|
+
|
|
494
510
|
class HistoryRequestBase(BaseModel):
|
|
495
511
|
"""Shared fields and validation for history endpoints."""
|
|
496
512
|
|
|
@@ -525,13 +541,8 @@ class HistoryRequestBase(BaseModel):
|
|
|
525
541
|
)
|
|
526
542
|
raise ValueError(error_message)
|
|
527
543
|
|
|
528
|
-
if
|
|
529
|
-
self.date_from
|
|
530
|
-
and self.date_to is not None
|
|
531
|
-
and self.date_from >= self.date_to
|
|
532
|
-
):
|
|
533
|
-
range_error = "date_from must be before date_to"
|
|
534
|
-
raise ValueError(range_error)
|
|
544
|
+
if self.date_from is not None and self.date_to is not None:
|
|
545
|
+
_validate_date_range(self.date_from, self.date_to)
|
|
535
546
|
|
|
536
547
|
return self
|
|
537
548
|
|
|
@@ -572,13 +583,8 @@ class HistoryTotalRequest(BaseModel):
|
|
|
572
583
|
|
|
573
584
|
Returns:
|
|
574
585
|
The validated model instance.
|
|
575
|
-
|
|
576
|
-
Raises:
|
|
577
|
-
ValueError: If date_from is not before date_to.
|
|
578
586
|
"""
|
|
579
|
-
|
|
580
|
-
range_error = "date_from must be before date_to"
|
|
581
|
-
raise ValueError(range_error)
|
|
587
|
+
_validate_date_range(self.date_from, self.date_to)
|
|
582
588
|
return self
|
|
583
589
|
|
|
584
590
|
|
|
@@ -651,26 +657,26 @@ class TradeRequest(BaseModel):
|
|
|
651
657
|
ge=0,
|
|
652
658
|
examples=[1],
|
|
653
659
|
)
|
|
654
|
-
symbol: str = Field(
|
|
655
|
-
|
|
656
|
-
description="
|
|
660
|
+
symbol: str | None = Field(
|
|
661
|
+
default=None,
|
|
662
|
+
description="Trade symbol (not required for order removal/modification)",
|
|
657
663
|
min_length=1,
|
|
658
664
|
max_length=32,
|
|
659
665
|
examples=["EURUSD"],
|
|
660
666
|
)
|
|
661
|
-
volume: float = Field(
|
|
662
|
-
|
|
667
|
+
volume: float | None = Field(
|
|
668
|
+
default=None,
|
|
663
669
|
description="Trade volume in lots",
|
|
664
670
|
gt=0,
|
|
665
671
|
examples=[0.1, 1.0],
|
|
666
672
|
)
|
|
667
|
-
type: Mt5OrderType = Field(
|
|
668
|
-
|
|
673
|
+
type: Mt5OrderType | None = Field(
|
|
674
|
+
default=None,
|
|
669
675
|
description=_ORDER_TYPE_DESCRIPTION,
|
|
670
676
|
)
|
|
671
|
-
price: float = Field(
|
|
672
|
-
|
|
673
|
-
description="Requested price",
|
|
677
|
+
price: float | None = Field(
|
|
678
|
+
default=None,
|
|
679
|
+
description="Requested price (optional for market execution)",
|
|
674
680
|
ge=0,
|
|
675
681
|
examples=[1.08500],
|
|
676
682
|
)
|
|
@@ -746,6 +752,95 @@ class TradeRequest(BaseModel):
|
|
|
746
752
|
examples=[654321],
|
|
747
753
|
)
|
|
748
754
|
|
|
755
|
+
@model_validator(mode="after")
|
|
756
|
+
def validate_action_fields(self) -> Self:
|
|
757
|
+
"""Require only fields relevant to the selected MT5 trade action.
|
|
758
|
+
|
|
759
|
+
Returns:
|
|
760
|
+
The validated request for checking or sending to MT5.
|
|
761
|
+
|
|
762
|
+
SLTP and MODIFY replace the whole MT5 trade state, so omitted levels are
|
|
763
|
+
rejected instead of risking a reset to zero/GTC (use ``0`` to clear).
|
|
764
|
+
|
|
765
|
+
Raises:
|
|
766
|
+
ValueError: If the action is unknown or required fields are missing.
|
|
767
|
+
"""
|
|
768
|
+
required = {
|
|
769
|
+
1: ("symbol", "volume", "type"), # TRADE_ACTION_DEAL
|
|
770
|
+
5: ("symbol", "volume", "type", "price"), # PENDING
|
|
771
|
+
6: (), # SLTP: netting symbol or hedging position
|
|
772
|
+
7: ("order", "price", "sl", "tp", "type_time"), # MODIFY (full state)
|
|
773
|
+
8: ("order",), # REMOVE
|
|
774
|
+
10: ("position", "position_by"), # CLOSE_BY
|
|
775
|
+
}.get(self.action)
|
|
776
|
+
if required is None:
|
|
777
|
+
message = "Unsupported MetaTrader5 trade action"
|
|
778
|
+
raise ValueError(message)
|
|
779
|
+
missing = [
|
|
780
|
+
name
|
|
781
|
+
for name in required
|
|
782
|
+
if getattr(self, name) is None
|
|
783
|
+
or (
|
|
784
|
+
name in {"order", "position", "position_by"}
|
|
785
|
+
and getattr(self, name) == 0
|
|
786
|
+
)
|
|
787
|
+
]
|
|
788
|
+
if self.action == 6: # ruff: ignore[magic-value-comparison]
|
|
789
|
+
if not (self.position or self.symbol):
|
|
790
|
+
missing.append("position or symbol")
|
|
791
|
+
missing.extend(name for name in ("sl", "tp") if getattr(self, name) is None)
|
|
792
|
+
if (
|
|
793
|
+
self.action == 7 # ruff: ignore[magic-value-comparison]
|
|
794
|
+
and self.type_time in {2, 3} # ORDER_TIME_SPECIFIED(_DAY)
|
|
795
|
+
and self.expiration is None
|
|
796
|
+
):
|
|
797
|
+
missing.append("expiration")
|
|
798
|
+
if missing:
|
|
799
|
+
message = f"Missing required trade fields: {', '.join(missing)}"
|
|
800
|
+
raise ValueError(message)
|
|
801
|
+
if self.expiration is not None and self.expiration.utcoffset() is None:
|
|
802
|
+
message = "expiration must include a UTC offset"
|
|
803
|
+
raise ValueError(message)
|
|
804
|
+
return self
|
|
805
|
+
|
|
806
|
+
def to_mt5_dict(self) -> dict[str, Any]:
|
|
807
|
+
"""Serialize MT5 fields, converting aware expiration to Unix seconds.
|
|
808
|
+
|
|
809
|
+
Returns:
|
|
810
|
+
Trade request dictionary suitable for the MetaTrader5 Python module.
|
|
811
|
+
"""
|
|
812
|
+
payload: dict[str, Any] = self.model_dump(mode="python", exclude_none=True)
|
|
813
|
+
if self.expiration is not None:
|
|
814
|
+
payload["expiration"] = int(self.expiration.timestamp())
|
|
815
|
+
return payload
|
|
816
|
+
|
|
817
|
+
|
|
818
|
+
class OrderSendRequest(BaseModel):
|
|
819
|
+
"""Request body for an opt-in live trading operation."""
|
|
820
|
+
|
|
821
|
+
request: TradeRequest = Field(
|
|
822
|
+
...,
|
|
823
|
+
description=(
|
|
824
|
+
"MT5 MqlTradeRequest (order_send), including action-specific fields"
|
|
825
|
+
),
|
|
826
|
+
)
|
|
827
|
+
expected_login: int = Field(
|
|
828
|
+
...,
|
|
829
|
+
gt=0,
|
|
830
|
+
description=(
|
|
831
|
+
"MT5 account login the order is intended for. The order is rejected "
|
|
832
|
+
"(HTTP 409) unless the connected account matches."
|
|
833
|
+
),
|
|
834
|
+
)
|
|
835
|
+
expected_server: str | None = Field(
|
|
836
|
+
default=None,
|
|
837
|
+
min_length=1,
|
|
838
|
+
description=(
|
|
839
|
+
"Optional MT5 trade server the order is intended for. When set, the "
|
|
840
|
+
"connected account's server must match exactly."
|
|
841
|
+
),
|
|
842
|
+
)
|
|
843
|
+
|
|
749
844
|
|
|
750
845
|
class OrderCheckRequest(BaseModel):
|
|
751
846
|
"""Request parameters for order check endpoint."""
|
|
@@ -52,10 +52,11 @@ async def post_connection_login(
|
|
|
52
52
|
async with state.client_lock:
|
|
53
53
|
await replace_mt5_client(state, config)
|
|
54
54
|
await release_market_book_subscriptions(state)
|
|
55
|
+
sanitized_server = request.server.replace("\r", "").replace("\n", "")
|
|
55
56
|
logger.info(
|
|
56
57
|
"MT5 client reconnected (login=%d, server=%s)",
|
|
57
58
|
request.login,
|
|
58
|
-
|
|
59
|
+
sanitized_server,
|
|
59
60
|
)
|
|
60
61
|
return LoginResponse(
|
|
61
62
|
login=request.login,
|
|
@@ -49,7 +49,7 @@ async def get_health(request: Request) -> HealthResponse:
|
|
|
49
49
|
mt5_version = None
|
|
50
50
|
|
|
51
51
|
try:
|
|
52
|
-
client = await
|
|
52
|
+
client = await get_mt5_client(request)
|
|
53
53
|
version_dict = await run_in_threadpool(client.version_as_dict)
|
|
54
54
|
if version_dict:
|
|
55
55
|
mt5_version = f"{version_dict.get('mt5_terminal_version', 'unknown')}"
|
|
@@ -2,16 +2,22 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
+
import asyncio
|
|
5
6
|
import logging
|
|
7
|
+
import os
|
|
6
8
|
from typing import TYPE_CHECKING, Annotated, Any
|
|
7
9
|
|
|
8
|
-
from fastapi import APIRouter, Depends, Request, status
|
|
10
|
+
from fastapi import APIRouter, Depends, HTTPException, Request, status
|
|
9
11
|
from fastapi.responses import JSONResponse
|
|
10
12
|
from pdmt5.dataframe import Mt5DataClient # ruff: ignore[typing-only-third-party-import]
|
|
11
13
|
|
|
12
|
-
from mt5api.auth import verify_api_key
|
|
13
|
-
from mt5api.constants import
|
|
14
|
+
from mt5api.auth import is_auth_enabled, verify_api_key
|
|
15
|
+
from mt5api.constants import (
|
|
16
|
+
ENV_MT5API_ENABLE_ORDER_SEND,
|
|
17
|
+
ENV_MT5API_MAX_MARKET_BOOK_SUBSCRIPTIONS,
|
|
18
|
+
)
|
|
14
19
|
from mt5api.dependencies import (
|
|
20
|
+
ensure_mt5_client,
|
|
15
21
|
get_mt5_client,
|
|
16
22
|
get_mt5_runtime_state,
|
|
17
23
|
get_response_format,
|
|
@@ -23,6 +29,7 @@ from mt5api.models import (
|
|
|
23
29
|
ErrorResponse,
|
|
24
30
|
MarketBookSubscriptionRequest,
|
|
25
31
|
OrderCheckRequest,
|
|
32
|
+
OrderSendRequest,
|
|
26
33
|
ResponseFormat,
|
|
27
34
|
SymbolSelectRequest,
|
|
28
35
|
)
|
|
@@ -61,6 +68,109 @@ def _build_market_book_subscription_limit_response(
|
|
|
61
68
|
)
|
|
62
69
|
|
|
63
70
|
|
|
71
|
+
def require_order_send_access() -> None:
|
|
72
|
+
"""Reject live trading unless explicitly enabled with API-key authentication.
|
|
73
|
+
|
|
74
|
+
Raises:
|
|
75
|
+
HTTPException: If the endpoint is disabled or authentication is unconfigured.
|
|
76
|
+
"""
|
|
77
|
+
enabled = os.getenv(ENV_MT5API_ENABLE_ORDER_SEND, "").strip().lower()
|
|
78
|
+
if enabled not in {"1", "true"} or not is_auth_enabled():
|
|
79
|
+
raise HTTPException(
|
|
80
|
+
status_code=status.HTTP_403_FORBIDDEN,
|
|
81
|
+
detail=(
|
|
82
|
+
"Live trading is disabled. Set MT5API_ENABLE_ORDER_SEND=true "
|
|
83
|
+
"and configure MT5API_SECRET_KEY to allow order submission."
|
|
84
|
+
),
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _send_for_expected_account(
|
|
89
|
+
client: Mt5DataClient,
|
|
90
|
+
payload: dict[str, Any],
|
|
91
|
+
*,
|
|
92
|
+
expected_login: int,
|
|
93
|
+
expected_server: str | None,
|
|
94
|
+
) -> dict[str, Any]:
|
|
95
|
+
"""Send an order only if the connected account is the intended one.
|
|
96
|
+
|
|
97
|
+
The account check and the send run back to back in one worker thread, while
|
|
98
|
+
the caller holds ``client_lock``, so the account cannot change in between.
|
|
99
|
+
|
|
100
|
+
Returns:
|
|
101
|
+
MT5 order-send result.
|
|
102
|
+
|
|
103
|
+
Raises:
|
|
104
|
+
HTTPException: If the connected account differs from the expected one.
|
|
105
|
+
"""
|
|
106
|
+
account = client.account_info_as_dict()
|
|
107
|
+
if account.get("login") != expected_login or (
|
|
108
|
+
expected_server is not None and account.get("server") != expected_server
|
|
109
|
+
):
|
|
110
|
+
raise HTTPException(
|
|
111
|
+
status_code=status.HTTP_409_CONFLICT,
|
|
112
|
+
detail=(
|
|
113
|
+
"Connected MT5 account does not match expected_login/"
|
|
114
|
+
"expected_server; the order was not sent."
|
|
115
|
+
),
|
|
116
|
+
)
|
|
117
|
+
return client.order_send_as_dict(request=payload)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
@router.post(
|
|
121
|
+
"/order/send",
|
|
122
|
+
response_model=DataResponse,
|
|
123
|
+
summary="Send live trading order (opt-in)",
|
|
124
|
+
description=(
|
|
125
|
+
"Submit a live MetaTrader5 order. Disabled unless MT5API_ENABLE_ORDER_SEND "
|
|
126
|
+
"is true and API-key authentication is configured. Check the returned "
|
|
127
|
+
"MT5 retcode: HTTP 200 does not imply the order was filled."
|
|
128
|
+
),
|
|
129
|
+
dependencies=[Depends(require_order_send_access)],
|
|
130
|
+
)
|
|
131
|
+
async def post_order_send(
|
|
132
|
+
app_request: Request,
|
|
133
|
+
response_format: Annotated[ResponseFormat, Depends(get_response_format)],
|
|
134
|
+
request: OrderSendRequest,
|
|
135
|
+
) -> DataResponse | Response:
|
|
136
|
+
"""Send a validated order and preserve the MT5 execution result.
|
|
137
|
+
|
|
138
|
+
The send holds the application's client lock so it cannot interleave with
|
|
139
|
+
``/connection/login``. The active client is resolved (and lazily
|
|
140
|
+
initialized) under the lock, and the lock is retained until the native call
|
|
141
|
+
finishes, even if the request is cancelled. The connected account must match
|
|
142
|
+
``expected_login`` (and ``expected_server`` when given); otherwise the order
|
|
143
|
+
is rejected with HTTP 409 before ``order_send`` is invoked.
|
|
144
|
+
|
|
145
|
+
Returns:
|
|
146
|
+
MT5 order-send result, including retcode, in JSON or Parquet format.
|
|
147
|
+
|
|
148
|
+
Raises:
|
|
149
|
+
asyncio.CancelledError: If the request is cancelled after the send ends.
|
|
150
|
+
"""
|
|
151
|
+
payload = request.request.to_mt5_dict()
|
|
152
|
+
state = get_mt5_runtime_state(app_request)
|
|
153
|
+
async with state.client_lock:
|
|
154
|
+
active_client = await ensure_mt5_client(state)
|
|
155
|
+
send_task = asyncio.ensure_future(
|
|
156
|
+
run_in_threadpool(
|
|
157
|
+
_send_for_expected_account,
|
|
158
|
+
active_client,
|
|
159
|
+
payload,
|
|
160
|
+
expected_login=request.expected_login,
|
|
161
|
+
expected_server=request.expected_server,
|
|
162
|
+
)
|
|
163
|
+
)
|
|
164
|
+
try:
|
|
165
|
+
result: dict[str, Any] = await asyncio.shield(send_task)
|
|
166
|
+
except asyncio.CancelledError:
|
|
167
|
+
while not send_task.done():
|
|
168
|
+
await asyncio.wait({send_task})
|
|
169
|
+
send_task.exception()
|
|
170
|
+
raise
|
|
171
|
+
return format_response(result, response_format)
|
|
172
|
+
|
|
173
|
+
|
|
64
174
|
@router.post(
|
|
65
175
|
"/order/check",
|
|
66
176
|
response_model=DataResponse,
|
|
@@ -79,7 +189,7 @@ async def post_order_check(
|
|
|
79
189
|
"""
|
|
80
190
|
result: dict[str, Any] = await run_in_threadpool(
|
|
81
191
|
mt5_client.order_check_as_dict,
|
|
82
|
-
request=request.request.
|
|
192
|
+
request=request.request.to_mt5_dict(),
|
|
83
193
|
)
|
|
84
194
|
return format_response(result, response_format)
|
|
85
195
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "mt5api"
|
|
3
|
-
version = "
|
|
3
|
+
version = "2.0.1"
|
|
4
4
|
description = "MetaTrader 5 REST API"
|
|
5
5
|
authors = [{name = "dceoy", email = "dceoy@users.noreply.github.com"}]
|
|
6
6
|
maintainers = [{name = "dceoy", email = "dceoy@users.noreply.github.com"}]
|
|
@@ -9,7 +9,7 @@ license-files = ["LICENSE"]
|
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">= 3.11, < 3.15"
|
|
11
11
|
dependencies = [
|
|
12
|
-
"pdmt5 >= 1.2.
|
|
12
|
+
"pdmt5 >= 1.2.4",
|
|
13
13
|
"fastapi >= 0.115.0",
|
|
14
14
|
"uvicorn[standard] >= 0.32.0",
|
|
15
15
|
"pandas >= 3.0.3",
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|