DB - trades

abstract

Records every trade opened via MT5 — both LLM-driven and manual — with entry/exit prices, P&L, source strategy, and post-trade analysis.

Table Info

PropertyValue
Table Nametrades
SQLAlchemy Modelbackend/db/models.py :: Trade
Pydantic Schemabackend/api/routes/trades.py
Migration Filealembic/versions/
TimescaleDB HypertableNo
Partition Column

Columns

ColumnSQLAlchemy TypeNullableDefaultDescription
idIntegerNoautoPrimary key
account_idInteger FKNoFK → accounts.id
ticketIntegerNoMT5 order ticket number (indexed)
symbolString(20)NoTrading pair, e.g. EURUSD (indexed)
directionString(4)NoBUY or SELL (underlying position direction)
volumeFloatNoTrade size in lots
entry_priceFloatNoPrice at which trade was opened
stop_lossFloatNoStop-loss price
take_profitFloatNoTake-profit price
close_priceFloatYesnullClosing price; null while trade is open
profitFloatYesnullRealized P&L in account currency; null while open
opened_atDateTime(timezone=True)NoTrade open timestamp (indexed)
closed_atDateTime(timezone=True)YesnullTrade close timestamp; null while open
sourceString(100)No"manual""manual" or strategy class name (e.g., "HarmonicStrategy")
is_paper_tradeBooleanNoFalseTrue if paper trade (not live MT5 order)
maintenance_enabledBooleanNoTrueAllow maintenance agent to manage this trade
order_typeString(6)No"market"market | limit | stop
order_statusString(9)No"filled"pending | filled | cancelled | expired
strategy_idInteger FKYesnullFK → strategies.id (SET NULL on delete)
trade_analysisTextYesnullJSON from post-trade LLM analysis
exclude_from_researchBooleanNoFalseIf True, skip this trade in research cycle

Constraints & Indexes

NameTypeColumnsPurpose
pk_tradesPRIMARY KEYidRow uniqueness
uq_trade_account_ticketUNIQUE(account_id, ticket)No duplicate MT5 tickets per account
idx_trades_account_idINDEXaccount_idFast lookup by account
idx_trades_ticketINDEXticketFast lookup by MT5 ticket
idx_trades_symbolINDEXsymbolFilter by symbol
idx_trades_opened_atINDEXopened_atTime-range queries
fk_trades_accountFOREIGN KEYaccount_id → accounts.idReferential integrity
fk_trades_strategyFOREIGN KEYstrategy_id → strategies.idSET NULL on strategy delete

Entity Relationships

SQLAlchemy Model (reference snapshot)

class Trade(Base):
    __tablename__ = "trades"
 
    id: Mapped[int] = mapped_column(Integer, primary_key=True)
    account_id: Mapped[int] = mapped_column(Integer, ForeignKey("accounts.id"), index=True)
    ticket: Mapped[int] = mapped_column(Integer, index=True)
    symbol: Mapped[str] = mapped_column(String(20), index=True)
    direction: Mapped[str] = mapped_column(String(4))           # BUY | SELL
    volume: Mapped[float] = mapped_column(Float)
    entry_price: Mapped[float] = mapped_column(Float)
    stop_loss: Mapped[float] = mapped_column(Float)
    take_profit: Mapped[float] = mapped_column(Float)
    close_price: Mapped[float | None] = mapped_column(Float, nullable=True)
    profit: Mapped[float | None] = mapped_column(Float, nullable=True)
    opened_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), index=True)
    closed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
    source: Mapped[str] = mapped_column(String(100), default="manual")
    is_paper_trade: Mapped[bool] = mapped_column(Boolean, default=False)
    maintenance_enabled: Mapped[bool] = mapped_column(Boolean, default=True)
    order_type: Mapped[str] = mapped_column(String(6), default="market")
    order_status: Mapped[str] = mapped_column(String(9), default="filled")
    strategy_id: Mapped[int | None] = mapped_column(
        Integer, ForeignKey("strategies.id", ondelete="SET NULL"), nullable=True
    )
    trade_analysis: Mapped[str | None] = mapped_column(Text, nullable=True)
    exclude_from_research: Mapped[bool] = mapped_column(Boolean, default=False, server_default="false")
 
    __table_args__ = (
        UniqueConstraint("account_id", "ticket", name="uq_trade_account_ticket"),
    )

Service Layer

LayerFilePurpose
Routerbackend/api/routes/trades.pyTrade listing, sync, history
Routerbackend/api/routes/accounts.pyHistory sync endpoint
Schedulerbackend/services/scheduler.pyPeriodic sync of MT5 trade history
RoleLink
API EndpointAPI-GET-v1-Trades
Frontend PagePage - Analytics
Related TableDB - accounts
Related TableDB - strategies
Related TableDB - ai_journal