mt5api 1.0.3__tar.gz → 1.0.4__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.
Files changed (69) hide show
  1. {mt5api-1.0.3 → mt5api-1.0.4}/.agents/skills/local-qa/scripts/qa.sh +1 -0
  2. {mt5api-1.0.3 → mt5api-1.0.4}/PKG-INFO +1 -1
  3. {mt5api-1.0.3 → mt5api-1.0.4}/docs/api/rest-api.md +6 -3
  4. {mt5api-1.0.3 → mt5api-1.0.4}/mt5api/constants.py +1 -3
  5. mt5api-1.0.4/mt5api/dependencies.py +210 -0
  6. mt5api-1.0.4/mt5api/formatters.py +163 -0
  7. {mt5api-1.0.3 → mt5api-1.0.4}/mt5api/main.py +100 -58
  8. {mt5api-1.0.3 → mt5api-1.0.4}/mt5api/middleware.py +5 -4
  9. {mt5api-1.0.3 → mt5api-1.0.4}/mt5api/routers/connection.py +9 -16
  10. {mt5api-1.0.3 → mt5api-1.0.4}/mt5api/routers/health.py +6 -3
  11. {mt5api-1.0.3 → mt5api-1.0.4}/mt5api/routers/trading.py +32 -63
  12. {mt5api-1.0.3 → mt5api-1.0.4}/pyproject.toml +3 -7
  13. {mt5api-1.0.3 → mt5api-1.0.4}/tests/conftest.py +15 -79
  14. mt5api-1.0.4/tests/test_connection.py +318 -0
  15. mt5api-1.0.4/tests/test_dependencies.py +205 -0
  16. {mt5api-1.0.3 → mt5api-1.0.4}/tests/test_formatters.py +2 -4
  17. {mt5api-1.0.3 → mt5api-1.0.4}/tests/test_health.py +60 -9
  18. {mt5api-1.0.3 → mt5api-1.0.4}/tests/test_lifespan.py +1 -1
  19. mt5api-1.0.4/tests/test_main.py +215 -0
  20. mt5api-1.0.4/tests/test_trading.py +308 -0
  21. {mt5api-1.0.3 → mt5api-1.0.4}/uv.lock +51 -21
  22. mt5api-1.0.3/mt5api/dependencies.py +0 -229
  23. mt5api-1.0.3/mt5api/formatters.py +0 -159
  24. mt5api-1.0.3/tests/test_connection.py +0 -494
  25. mt5api-1.0.3/tests/test_dependencies.py +0 -157
  26. mt5api-1.0.3/tests/test_main.py +0 -179
  27. mt5api-1.0.3/tests/test_trading.py +0 -537
  28. {mt5api-1.0.3 → mt5api-1.0.4}/.agents/skills/local-qa/SKILL.md +0 -0
  29. {mt5api-1.0.3 → mt5api-1.0.4}/.agents/skills/mt5api/SKILL.md +0 -0
  30. {mt5api-1.0.3 → mt5api-1.0.4}/.github/CODEOWNERS +0 -0
  31. {mt5api-1.0.3 → mt5api-1.0.4}/.github/FUNDING.yml +0 -0
  32. {mt5api-1.0.3 → mt5api-1.0.4}/.github/dependabot.yml +0 -0
  33. {mt5api-1.0.3 → mt5api-1.0.4}/.github/renovate.json +0 -0
  34. {mt5api-1.0.3 → mt5api-1.0.4}/.github/workflows/ci.yml +0 -0
  35. {mt5api-1.0.3 → mt5api-1.0.4}/.github/workflows/claude.yml +0 -0
  36. {mt5api-1.0.3 → mt5api-1.0.4}/.github/workflows/release.yml +0 -0
  37. {mt5api-1.0.3 → mt5api-1.0.4}/.gitignore +0 -0
  38. {mt5api-1.0.3 → mt5api-1.0.4}/AGENTS.md +0 -0
  39. {mt5api-1.0.3 → mt5api-1.0.4}/CLAUDE.md +0 -0
  40. {mt5api-1.0.3 → mt5api-1.0.4}/LICENSE +0 -0
  41. {mt5api-1.0.3 → mt5api-1.0.4}/README.md +0 -0
  42. {mt5api-1.0.3 → mt5api-1.0.4}/docs/api/deployment.md +0 -0
  43. {mt5api-1.0.3 → mt5api-1.0.4}/docs/api/index.md +0 -0
  44. {mt5api-1.0.3 → mt5api-1.0.4}/docs/index.md +0 -0
  45. {mt5api-1.0.3 → mt5api-1.0.4}/mkdocs.yml +0 -0
  46. {mt5api-1.0.3 → mt5api-1.0.4}/mt5api/__init__.py +0 -0
  47. {mt5api-1.0.3 → mt5api-1.0.4}/mt5api/__main__.py +0 -0
  48. {mt5api-1.0.3 → mt5api-1.0.4}/mt5api/auth.py +0 -0
  49. {mt5api-1.0.3 → mt5api-1.0.4}/mt5api/config.py +0 -0
  50. {mt5api-1.0.3 → mt5api-1.0.4}/mt5api/models.py +0 -0
  51. {mt5api-1.0.3 → mt5api-1.0.4}/mt5api/routers/__init__.py +0 -0
  52. {mt5api-1.0.3 → mt5api-1.0.4}/mt5api/routers/account.py +0 -0
  53. {mt5api-1.0.3 → mt5api-1.0.4}/mt5api/routers/calc.py +0 -0
  54. {mt5api-1.0.3 → mt5api-1.0.4}/mt5api/routers/history.py +0 -0
  55. {mt5api-1.0.3 → mt5api-1.0.4}/mt5api/routers/market.py +0 -0
  56. {mt5api-1.0.3 → mt5api-1.0.4}/mt5api/routers/symbols.py +0 -0
  57. {mt5api-1.0.3 → mt5api-1.0.4}/tests/__init__.py +0 -0
  58. {mt5api-1.0.3 → mt5api-1.0.4}/tests/mt5_constants.py +0 -0
  59. {mt5api-1.0.3 → mt5api-1.0.4}/tests/openapi_mt5_constants.py +0 -0
  60. {mt5api-1.0.3 → mt5api-1.0.4}/tests/test_account.py +0 -0
  61. {mt5api-1.0.3 → mt5api-1.0.4}/tests/test_auth.py +0 -0
  62. {mt5api-1.0.3 → mt5api-1.0.4}/tests/test_calc.py +0 -0
  63. {mt5api-1.0.3 → mt5api-1.0.4}/tests/test_cli.py +0 -0
  64. {mt5api-1.0.3 → mt5api-1.0.4}/tests/test_config.py +0 -0
  65. {mt5api-1.0.3 → mt5api-1.0.4}/tests/test_history.py +0 -0
  66. {mt5api-1.0.3 → mt5api-1.0.4}/tests/test_market.py +0 -0
  67. {mt5api-1.0.3 → mt5api-1.0.4}/tests/test_middleware.py +0 -0
  68. {mt5api-1.0.3 → mt5api-1.0.4}/tests/test_models.py +0 -0
  69. {mt5api-1.0.3 → mt5api-1.0.4}/tests/test_symbols.py +0 -0
@@ -9,6 +9,7 @@ export NPM_CONFIG_MIN_RELEASE_AGE="${COOLDOWN_DAYS}"
9
9
  export PNPM_CONFIG_MINIMUM_RELEASE_AGE=$((COOLDOWN_DAYS * 24 * 60))
10
10
 
11
11
  # Python
12
+ uv sync
12
13
  uv run ruff format .
13
14
  uv run ruff check --fix .
14
15
  uv run pyright .
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mt5api
3
- Version: 1.0.3
3
+ Version: 1.0.4
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>
@@ -166,9 +166,12 @@ with typed validation for core fields such as `action`, `symbol`, `volume`,
166
166
 
167
167
  - `POST /connection/login` (body: `{"login": ..., "password": "...",
168
168
  "server": "...", "timeout": ...}`) — Reconnect the MT5 terminal with the
169
- supplied credentials. Any active market-book subscriptions are released and
170
- the previous MT5 client is shut down before the new connection is
171
- established. The supplied password is never echoed in responses or logs.
169
+ supplied credentials. The replacement client is initialized and installed
170
+ before active market-book subscriptions are released and cleared. The old
171
+ wrapper is not shut down after a successful replacement because MetaTrader5
172
+ connection state is process-global; shutting it down could close the newly
173
+ established session. If replacement fails, existing subscription tracking is
174
+ preserved. The supplied password is never echoed in responses or logs.
172
175
 
173
176
  ## Response Formatter Utilities
174
177
 
@@ -15,9 +15,7 @@ API_OPENAPI_URL = "/openapi.json"
15
15
  API_APP_IMPORT = "mt5api.main:app"
16
16
  API_KEY_HEADER_NAME = "X-API-Key"
17
17
  API_KEY_SECURITY_SCHEME_NAME = "APIKeyHeader"
18
- ACTIVE_MARKET_BOOK_SUBSCRIPTIONS_STATE_KEY = "active_market_book_subscriptions"
19
- MARKET_BOOK_CLEANUP_CLIENT_STATE_KEY = "market_book_cleanup_client"
20
- MAX_MARKET_BOOK_SUBSCRIPTIONS_STATE_KEY = "max_market_book_subscriptions"
18
+ MT5_RUNTIME_STATE_KEY = "mt5_runtime"
21
19
 
22
20
  ENV_MT5API_HOST = "MT5API_HOST"
23
21
  ENV_MT5API_PORT = "MT5API_PORT"
@@ -0,0 +1,210 @@
1
+ """FastAPI dependency injection for MT5 client and format negotiation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import logging
7
+ from dataclasses import dataclass, field
8
+ from typing import TYPE_CHECKING, Annotated, Any, TypeVar
9
+
10
+ from fastapi import Header, Query, Request
11
+ from pdmt5.dataframe import Mt5Config, Mt5DataClient
12
+
13
+ from .config import get_configured_max_market_book_subscriptions
14
+ from .constants import MT5_RUNTIME_STATE_KEY
15
+ from .models import ResponseFormat
16
+
17
+ if TYPE_CHECKING:
18
+ from collections.abc import Callable
19
+
20
+ from fastapi import FastAPI
21
+
22
+ logger = logging.getLogger(__name__)
23
+ T = TypeVar("T")
24
+
25
+
26
+ @dataclass(slots=True)
27
+ class Mt5RuntimeState:
28
+ """Application-scoped owner for MT5 connection and subscription state."""
29
+
30
+ client: Mt5DataClient | None = None
31
+ client_lock: asyncio.Lock = field(default_factory=asyncio.Lock)
32
+ market_book_subscriptions: set[str] = field(default_factory=set[str])
33
+ market_book_cleanup_client: Mt5DataClient | None = None
34
+ max_market_book_subscriptions: int = 0
35
+
36
+
37
+ def initialize_mt5_runtime_state(
38
+ app: FastAPI,
39
+ *,
40
+ max_market_book_subscriptions: int | None = None,
41
+ ) -> Mt5RuntimeState:
42
+ """Create and install the application-scoped MT5 runtime state.
43
+
44
+ Args:
45
+ app: FastAPI application that owns the state.
46
+ max_market_book_subscriptions: Optional explicit subscription limit.
47
+
48
+ Returns:
49
+ Newly installed runtime state.
50
+ """
51
+ state = Mt5RuntimeState(
52
+ max_market_book_subscriptions=(
53
+ get_configured_max_market_book_subscriptions()
54
+ if max_market_book_subscriptions is None
55
+ else max_market_book_subscriptions
56
+ )
57
+ )
58
+ setattr(app.state, MT5_RUNTIME_STATE_KEY, state)
59
+ return state
60
+
61
+
62
+ def get_mt5_runtime_state(request: Request) -> Mt5RuntimeState:
63
+ """Return the request application's MT5 runtime state.
64
+
65
+ Returns:
66
+ Existing state or a lazily installed state for direct ASGI usage.
67
+ """
68
+ state = getattr(request.app.state, MT5_RUNTIME_STATE_KEY, None)
69
+ if isinstance(state, Mt5RuntimeState):
70
+ return state
71
+ return initialize_mt5_runtime_state(request.app)
72
+
73
+
74
+ def get_mt5_client_lock(request: Request) -> asyncio.Lock:
75
+ """Return the application-scoped MT5 replacement lock.
76
+
77
+ Returns:
78
+ Lock guarding client replacement and subscription cleanup.
79
+ """
80
+ return get_mt5_runtime_state(request).client_lock
81
+
82
+
83
+ def get_mt5_client(request: Request) -> Mt5DataClient:
84
+ """Get or create the application-scoped MT5 client instance.
85
+
86
+ Args:
87
+ request: Request whose application owns the MT5 runtime state.
88
+
89
+ Returns:
90
+ Shared initialized MT5 data client.
91
+
92
+ Raises:
93
+ RuntimeError: If MT5 client initialization fails.
94
+ """
95
+ state = get_mt5_runtime_state(request)
96
+ if state.client is None:
97
+ client = Mt5DataClient(config=Mt5Config())
98
+ try:
99
+ client.initialize_and_login_mt5()
100
+ except Exception as exc:
101
+ error_message = f"Failed to initialize MT5 client: {exc!s}"
102
+ raise RuntimeError(error_message) from exc
103
+ state.client = client
104
+ return state.client
105
+
106
+
107
+ def shutdown_mt5_client(state: Mt5RuntimeState) -> None:
108
+ """Shutdown and clear the application-scoped MT5 client."""
109
+ client = state.client
110
+ if client is None:
111
+ return
112
+ state.client = None
113
+ client.shutdown()
114
+
115
+
116
+ async def replace_mt5_client(
117
+ state: Mt5RuntimeState,
118
+ config: Mt5Config,
119
+ ) -> Mt5DataClient:
120
+ """Replace the application's client after successful initialization.
121
+
122
+ MetaTrader5 connection state is process-global, so the previous wrapper is
123
+ not shut down after success because doing so could close the new session.
124
+
125
+ Returns:
126
+ Newly initialized and installed client.
127
+
128
+ Raises:
129
+ RuntimeError: If the replacement cannot be initialized.
130
+ """
131
+ try:
132
+ new_client = Mt5DataClient(config=config)
133
+ await asyncio.to_thread(new_client.initialize_and_login_mt5)
134
+ except Exception as exc:
135
+ logger.exception("Failed to initialize MT5 client")
136
+ error_message = "Failed to initialize MT5 client"
137
+ raise RuntimeError(error_message) from exc
138
+ state.client = new_client
139
+ return new_client
140
+
141
+
142
+ async def release_market_book_subscriptions(state: Mt5RuntimeState) -> None:
143
+ """Release and clear all market-book subscriptions owned by ``state``."""
144
+ subscriptions = state.market_book_subscriptions
145
+ if not subscriptions:
146
+ state.market_book_cleanup_client = None
147
+ return
148
+ cleanup_client = state.market_book_cleanup_client
149
+ if cleanup_client is None:
150
+ logger.warning("Active market-book subscriptions found without cleanup client")
151
+ subscriptions.clear()
152
+ return
153
+
154
+ def release_subscriptions() -> None:
155
+ for symbol in tuple(subscriptions):
156
+ try:
157
+ cleanup_client.market_book_release(symbol=symbol)
158
+ except Exception:
159
+ logger.exception("Failed to release market book for %s", symbol)
160
+
161
+ await asyncio.to_thread(release_subscriptions)
162
+ subscriptions.clear()
163
+ state.market_book_cleanup_client = None
164
+
165
+
166
+ async def run_in_threadpool(
167
+ func: Callable[..., T],
168
+ *args: Any, # noqa: ANN401
169
+ **kwargs: Any, # noqa: ANN401
170
+ ) -> T:
171
+ """Run a synchronous MT5 function without blocking the event loop.
172
+
173
+ Returns:
174
+ Result returned by ``func``.
175
+ """
176
+ return await asyncio.to_thread(func, *args, **kwargs)
177
+
178
+
179
+ def get_response_format(
180
+ accept: Annotated[str | None, Header()] = None,
181
+ format_param: Annotated[ResponseFormat | None, Query(alias="format")] = None,
182
+ ) -> ResponseFormat:
183
+ """Determine response format from query parameter or Accept header.
184
+
185
+ Returns:
186
+ Selected response format, defaulting to JSON.
187
+ """
188
+ if format_param is not None:
189
+ return format_param
190
+ if accept:
191
+ accept_lower = accept.lower()
192
+ if "application/parquet" in accept_lower:
193
+ return ResponseFormat.PARQUET
194
+ if "application/json" in accept_lower:
195
+ return ResponseFormat.JSON
196
+ return ResponseFormat.JSON
197
+
198
+
199
+ def get_request_info(request: Request) -> dict[str, Any]:
200
+ """Extract request information for logging.
201
+
202
+ Returns:
203
+ Request method, URL, client address, and user agent.
204
+ """
205
+ return {
206
+ "method": request.method,
207
+ "url": str(request.url),
208
+ "client": request.client.host if request.client else None,
209
+ "user_agent": request.headers.get("user-agent"),
210
+ }
@@ -0,0 +1,163 @@
1
+ """Response formatters for JSON and Apache Parquet formats."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import io
6
+ from typing import TYPE_CHECKING, Any, cast, overload
7
+
8
+ import pandas as pd
9
+ import pyarrow as pa # type: ignore[import-untyped]
10
+ import pyarrow.parquet as pq # type: ignore[import-untyped]
11
+ from fastapi.responses import Response
12
+
13
+ from .models import DataResponse, ResponseFormat
14
+
15
+ _SUPPORTED_RESPONSE_FORMATS = {ResponseFormat.JSON, ResponseFormat.PARQUET}
16
+ _INVALID_DATA_MESSAGE = "data must be a pandas DataFrame or dict[str, Any]"
17
+
18
+ if TYPE_CHECKING: # pragma: no cover
19
+ from typing import Protocol
20
+
21
+ class _PyArrowTable(Protocol):
22
+ """Structural type for the PyArrow table passed to Parquet output."""
23
+
24
+ class _PyArrowTableFactory(Protocol):
25
+ """Structural type for the supported PyArrow table factory API."""
26
+
27
+ @staticmethod
28
+ def from_pandas(
29
+ dataframe: pd.DataFrame,
30
+ *,
31
+ preserve_index: bool = True,
32
+ ) -> _PyArrowTable: ...
33
+
34
+ class _PyArrowModule(Protocol):
35
+ """Structural type for the supported PyArrow module API."""
36
+
37
+ Table: _PyArrowTableFactory
38
+
39
+ class _PyArrowParquetModule(Protocol):
40
+ """Structural type for the supported PyArrow Parquet API."""
41
+
42
+ def write_table(
43
+ self,
44
+ table: _PyArrowTable,
45
+ where: io.BytesIO,
46
+ *,
47
+ compression: str = "snappy",
48
+ use_dictionary: bool = True,
49
+ write_statistics: bool = True,
50
+ ) -> None: ...
51
+
52
+ @overload
53
+ def format_response(
54
+ data: pd.DataFrame,
55
+ response_format: ResponseFormat,
56
+ ) -> DataResponse | Response: ...
57
+
58
+ @overload
59
+ def format_response(
60
+ data: dict[str, Any],
61
+ response_format: ResponseFormat,
62
+ ) -> DataResponse | Response: ...
63
+
64
+
65
+ def format_dataframe_to_json(
66
+ dataframe: pd.DataFrame,
67
+ *,
68
+ orient: str = "records",
69
+ ) -> DataResponse:
70
+ """Format DataFrame as JSON response.
71
+
72
+ Returns:
73
+ JSON data response.
74
+ """
75
+ if orient == "records":
76
+ data_value: list[dict[str, Any]] | dict[str, Any] = cast(
77
+ "list[dict[str, Any]] | dict[str, Any]",
78
+ dataframe.to_dict(orient=orient), # type: ignore[arg-type]
79
+ )
80
+ else:
81
+ data_value = cast(
82
+ "list[dict[str, Any]] | dict[str, Any]",
83
+ dataframe.to_dict(orient=orient), # type: ignore[arg-type]
84
+ )
85
+ return DataResponse(
86
+ data=data_value, count=len(dataframe), format=ResponseFormat.JSON
87
+ )
88
+
89
+
90
+ def format_dict_to_json(data: dict[str, Any]) -> DataResponse:
91
+ """Format dictionary as JSON response.
92
+
93
+ Returns:
94
+ Single-record JSON data response.
95
+ """
96
+ return DataResponse(data=data, count=1, format=ResponseFormat.JSON)
97
+
98
+
99
+ def format_dataframe_to_parquet(dataframe: pd.DataFrame) -> Response:
100
+ """Format DataFrame as a materialized Apache Parquet response.
101
+
102
+ Returns:
103
+ Binary Parquet HTTP response.
104
+ """
105
+ arrow_module = cast(
106
+ "_PyArrowModule",
107
+ pa, # pyright: ignore[reportUnknownArgumentType]
108
+ )
109
+ parquet_module = cast(
110
+ "_PyArrowParquetModule",
111
+ pq, # pyright: ignore[reportUnknownArgumentType]
112
+ )
113
+ table = arrow_module.Table.from_pandas(dataframe, preserve_index=False)
114
+ buffer = io.BytesIO()
115
+ parquet_module.write_table(
116
+ table,
117
+ buffer,
118
+ compression="snappy",
119
+ use_dictionary=True,
120
+ write_statistics=True,
121
+ )
122
+ return Response(
123
+ content=buffer.getvalue(),
124
+ media_type="application/parquet",
125
+ headers={"Content-Disposition": "attachment; filename=data.parquet"},
126
+ )
127
+
128
+
129
+ def format_dict_to_parquet(data: dict[str, Any]) -> Response:
130
+ """Format a dictionary as a single-row Apache Parquet response.
131
+
132
+ Returns:
133
+ Binary Parquet HTTP response.
134
+ """
135
+ return format_dataframe_to_parquet(pd.DataFrame([data]))
136
+
137
+
138
+ def format_response(
139
+ data: object,
140
+ response_format: ResponseFormat,
141
+ ) -> DataResponse | Response:
142
+ """Format a DataFrame or mapping as JSON or Parquet.
143
+
144
+ Returns:
145
+ JSON model or binary Parquet response.
146
+
147
+ Raises:
148
+ ValueError: If the response format is unsupported.
149
+ TypeError: If ``data`` is not a DataFrame or mapping.
150
+ """
151
+ if response_format not in _SUPPORTED_RESPONSE_FORMATS:
152
+ message = f"Unsupported response format: {response_format}"
153
+ raise ValueError(message)
154
+ if isinstance(data, pd.DataFrame):
155
+ if response_format == ResponseFormat.PARQUET:
156
+ return format_dataframe_to_parquet(data)
157
+ return format_dataframe_to_json(data)
158
+ if isinstance(data, dict):
159
+ data = cast("dict[str, Any]", data)
160
+ if response_format == ResponseFormat.PARQUET:
161
+ return format_dict_to_parquet(data)
162
+ return format_dict_to_json(data)
163
+ raise TypeError(_INVALID_DATA_MESSAGE)