Discussing the article: "Building a Trade Analytics System (Part 3): Storing MetaTrader 5 Trades in SQLite"

 

Check out the new article: Building a Trade Analytics System (Part 3): Storing MetaTrader 5 Trades in SQLite.

This article extends a Flask backend to reliably receive, validate, and store closed trade data from MetaTrader 5 using SQLite and Flask‑SQLAlchemy. It implements required‑field checks, timestamp conversion, transaction‑safe persistence, and working retrieval endpoints for all trades and single records, plus a basic summary. The result is a complete data pipeline with local testing that records trades and exposes them through a structured API for further analysis.

At this stage, the MetaTrader 5 Expert Advisor reliably detects closed trades and sends them to the Flask API, which acknowledges each request. However, these incoming events are not persisted. The backend returns a successful response, but no records are written to the SQLite database.

This prevents verification of the pipeline. There is no way to retrieve stored trades through the API, confirm that data is being preserved, or build any form of analysis on top of it.

In this part, the backend is extended to ensure that each trade sent by the EA is stored as a durable record in SQLite. The implementation focuses on establishing a clear, testable API behaviour. The system will:

  • Accept only valid JSON payloads at POST /api/v1/trades and return 4xx responses for malformed requests.
  • Validate required fields such as symbol, order_ticket, deal_ticket, position_ticket, position_type, lot_size, entry_price, profit, open_time, and close_time.
  • Convert incoming values to the correct types, including parsing time values using the format YYYY.MM.DD HH:MM:SS and converting numeric fields.
  • Create a Trade record in SQLite using transactional commits, with db.session.rollback() applied on failure;
  • Return 201 Created with a generated trade_id on success, and 5xx responses for unexpected server errors.

By the end of this part, a closed trade sent from MetaTrader 5 will result in a stored record that can be retrieved through the API, completing the core data pipeline.

Author: Chacha Ian Maroa