Skip to content

Add calculation and MT5 utility endpoints#18

Merged
dceoy merged 5 commits intomainfrom
claude/implement-mt5-functions-KzyRG
Mar 16, 2026
Merged

Add calculation and MT5 utility endpoints#18
dceoy merged 5 commits intomainfrom
claude/implement-mt5-functions-KzyRG

Conversation

@dceoy
Copy link
Copy Markdown
Owner

@dceoy dceoy commented Mar 16, 2026

Summary

This PR adds non-executing MT5 utility endpoints while preserving the service read-only boundary. It introduces calculation endpoints, order validation via /order/check, symbol selection and market-book subscription management, and several diagnostic/count endpoints.

Key Changes

Non-executing operational endpoints

  • POST /order/check - Validate a trade request without executing it
  • POST /symbols/{symbol}/select - Show or hide symbols in MarketWatch
  • POST /market-book/{symbol}/subscribe - Subscribe to DOM events
  • POST /market-book/{symbol}/unsubscribe - Unsubscribe from DOM events

Calculation endpoints

  • GET /calc/margin - Calculate required margin for a trade
  • GET /calc/profit - Calculate profit/loss for a trade

Count and diagnostic endpoints

  • GET /orders/total - Get active orders count
  • GET /positions/total - Get open positions count
  • GET /history/orders/total - Get historical orders count with date range
  • GET /history/deals/total - Get historical deals count with date range
  • GET /symbols/total - Get total symbol count
  • GET /last-error - Get last MT5 error information

Safety and validation updates

  • Removed the live trade execution endpoint (POST /order/send) to keep the API read-only
  • Replaced raw order-check payloads with a typed TradeRequest model for core field validation
  • Added symbol length validation for market-book subscription routes
  • Track active market-book subscriptions and release them during application shutdown

Tests and docs

  • Updated contract tests and shutdown coverage for the new validation and cleanup behavior
  • Revised README.md and docs/api/rest-api.md to remove trade execution and describe the remaining operational endpoints

Expose all remaining read-only pdmt5.Mt5DataClient and Mt5Client
functions, plus write operations (order_send, order_check,
symbol_select, market_book_add/release).

New read-only endpoints:
- GET /last-error: last MT5 error info
- GET /symbols/total: total symbol count
- GET /orders/total: active orders count
- GET /positions/total: open positions count
- GET /history/orders/total: historical orders count by date range
- GET /history/deals/total: historical deals count by date range
- GET /calc/margin: margin calculation for a trading operation
- GET /calc/profit: profit calculation for a trading operation

New write endpoints:
- POST /order/check: validate funds sufficiency for a trade
- POST /order/send: execute a trade request
- POST /symbols/{symbol}/select: show/hide symbol in MarketWatch
- POST /market-book/{symbol}/subscribe: subscribe to market depth
- POST /market-book/{symbol}/unsubscribe: unsubscribe from market depth

https://claude.ai/code/session_01SJQJzQNfkFizmofhvFEByB
@dceoy dceoy self-assigned this Mar 16, 2026
Update README, docs/index.md, docs/api/index.md, and docs/api/rest-api.md
to cover all new endpoints added in the previous commit:
read-only endpoints (last-error, symbols/total, orders/total,
positions/total, history totals, calc/margin, calc/profit) and
write endpoints (order/check, order/send, symbol select,
market-book subscribe/unsubscribe).

Also revise the "read-only" framing to reflect that the API now
includes trading write operations.

https://claude.ai/code/session_01SJQJzQNfkFizmofhvFEByB
@dceoy dceoy marked this pull request as ready for review March 16, 2026 15:29
Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c728814d71

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Copy link
Copy Markdown

@claude claude bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review Summary

Well-structured PR that cleanly extends existing patterns (Mt5ConstantSpec, router conventions, test fixtures). The new endpoints follow established async/threadpool patterns and the ORDER_TYPE constant support mirrors the existing TIMEFRAME/COPY_TICKS implementation nicely.

However, there are several issues that should be addressed before merging, primarily around security and input validation for the new write endpoints.

Critical

  1. OrderCheckRequest/OrderSendRequest accept unvalidated dict[str, Any] — Every other request model in the codebase uses strongly-typed, validated fields. These two models pass an arbitrary dict directly to the MT5 client, bypassing all input validation and making the OpenAPI schema useless for consumers. At minimum, type the core fields (action, symbol, volume, type, price). Consider ConfigDict(extra="allow") to preserve flexibility for less common fields.

  2. Write endpoints are unprotected when MT5API_SECRET_KEY is unsetverify_api_key silently passes through when no key is configured. This was acceptable for a read-only API but is dangerous for /order/send, which executes real trades. Write endpoints should require auth unconditionally, or the trading router should refuse to register when auth is disabled.

  3. CLAUDE.md contradicts this PR — The project's own architecture doc states "The service is intentionally read-only" and lists only the original five routers. This must be updated in the same PR.

Important

  1. No symbol path parameter validation on market-book endpointspost_market_book_subscribe and post_market_book_unsubscribe accept bare str with no constraints, unlike every other symbol parameter in the codebase which uses min_length=1, max_length=32.

  2. Market book subscription resource leak — No tracking of active subscriptions and no cleanup on shutdown. Leaked subscriptions accumulate MT5 server-side resources.

  3. Missing test coverage — No Parquet tests for any of the 5 trading endpoints (pattern required by every other router). No failure-path tests for symbol_select, market_book_add/release returning False. No validation error tests for calc endpoints (invalid action, zero/negative values). No auth-rejection tests for new routers.

Minor

  1. API_DESCRIPTION in constants.py still says "Provides read-only access" — needs updating.
  2. Duplicated date-range validation in HistoryTotalRequest vs HistoryRequestBase — consider extracting a shared helper.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@dceoy dceoy changed the title Add trading operations and calculation endpoints Add calculation and MT5 utility endpoints Mar 16, 2026
@dceoy dceoy marked this pull request as draft March 16, 2026 16:42
@dceoy dceoy marked this pull request as ready for review March 16, 2026 16:42
@chatgpt-codex-connector
Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, you can upgrade your account or add credits to your account and enable them for code reviews in your settings.

Copy link
Copy Markdown

@claude claude bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PR Review: Add calculation and MT5 utility endpoints

Overall this is a well-structured PR. The new routers, models, and tests integrate cleanly with established patterns. The Mt5ConstantSpec / Mt5OrderType reuse is particularly clean. A few noteworthy items below (inline comments on specific files, and general observations here).

Positive:

  • Consistent use of run_in_threadpool, dependency injection, and format_response across all new endpoints
  • Good test coverage of the subscription lifecycle including the full lifespan round-trip shutdown test
  • Defensive shutdown handling with try/finally ensuring shutdown_mt5_client() runs even if subscription cleanup fails
  • Clean separation of read-only vs operational endpoints in docs

Test gaps to close (project targets 100%):

  • No Parquet output tests for orders/total, positions/total, history/orders/total, history/deals/total (other similar endpoints like symbols/total do have them)
  • No test for _release_market_book_subscriptions when the subscriptions attribute is missing or is an empty set (early-return branch)
  • No equal-dates boundary test for HistoryTotalRequest (validator uses >= but only reversed dates are tested)
  • No validation edge-case tests for TradeRequest field constraints (empty symbol, zero volume, negative action, invalid ORDER_TYPE)
  • Missing date-range validation test for GET /history/deals/total (exists for orders/total but not deals/total)
  • No test for MT5 returning None from order_calc_margin / order_calc_profit

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@dceoy dceoy merged commit e12714a into main Mar 16, 2026
5 checks passed
@dceoy dceoy deleted the claude/implement-mt5-functions-KzyRG branch March 16, 2026 17:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants