/*
 * Copyright (c) 2026 Sensmetry, UAB. All Rights Reserved.
 */

package 'Algorithmic Trading System Design' {
    private import ScalarValues::*;

    alias Requirements for 'Algorithmic Trading Requirements';


    package Sources {
        item 'MiFID-II' {
            attribute title = "Markets in Financial Instruments Directive II";
            attribute version = "2018";
            attribute url = "https://www.esma.europa.eu/policy-rules/mifid-ii-and-mifir";
        }
        item 'SEC-Rule-15c3-5' {
            attribute title = "SEC Market Access Rule";
            attribute version = "2010";
            attribute url = "https://www.sec.gov/rules/final/2010/34-63241.pdf";
        }
        item 'FINRA-Rules' {
            attribute title = "FINRA Algorithmic Trading Rules";
            attribute url = "https://www.finra.org/rules-guidance/key-topics/algorithmic-trading";
        }
        item 'Regulation-NMS' {
            attribute title = "Regulation National Market System";
            attribute url = "https://www.sec.gov/rules/final/34-51808.pdf";
        }
    }

    package 'System Definitions' {
        enum def 'Strategy Type' {
            'Market Making';
            'Statistical Arbitrage';
            'Momentum';
            'Mean Reversion';
            'Arbitrage';
            'VWAP Execution';
            'News Based';
        }

        enum def 'Order Status' {
            Pending;
            Submitted;
            Acknowledged;
            PartiallyFilled;
            Filled;
            Cancelled;
            Rejected;
        }

        enum def 'Risk Severity' {
            Low;
            Medium;
            High;
            Critical;
        }

        port def MarketDataPort {
            attribute protocol : String;
            attribute latency : Real;
            inout item marketData redefines DataItem::MarketQuote [*];
        }

        port def TradingSignalPort {
            inout item signals redefines DataItem::TradingSignal [*];
        }

        port def OrderPort {
            inout item orders redefines DataItem::TradingOrder [*];
        }

        port def RiskDecisionPort {
            inout item decisions redefines DataItem::RiskDecision [*];
        }

        port def ExecutionNotificationPort {
            attribute venue : String;
            inout item acknowledgments redefines DataItem::OrderAck [*];
            inout item fills redefines DataItem::Fill [*];
        }

        port def AlertPort {
            inout item alerts redefines DataItem::RiskAlert [*];
        }

        port def AuditDataPort {
            attribute retentionDays : Integer;
            out item auditRecords redefines DataItem::AuditRecord [*];
        }

        variation item def DataItem {
            variant item MarketQuote {
                attribute symbol : String;
                attribute bidPrice : Real;
                attribute askPrice : Real;
                attribute timestamp : Integer;
            }
            variant item TradeExecution {
                attribute symbol : String;
                attribute price : Real;
                attribute quantity : Integer;
                attribute timestamp : Integer;
            }
            variant item TradingOrder {
                attribute symbol : String;
                attribute side : String;
                attribute quantity : Integer;
                attribute price : Real;
                attribute orderType : String;
            }
            variant item OrderAck {
                attribute orderId : String;
                attribute status : 'Order Status';
            }
            variant item Fill {
                attribute orderId : String;
                attribute fillPrice : Real;
                attribute fillQuantity : Integer;
            }
            variant item RiskDecision {
                attribute orderId : String;
                attribute approved : Boolean;
                attribute reason : String;
            }
            variant item RiskAlert {
                attribute severity : 'Risk Severity';
                attribute alertMessage : String;
            }
            variant item TradingSignal {
                attribute symbol : String;
                attribute signalAction : String;
                attribute confidence : Real;
            }
            variant item AuditRecord {
                attribute timestamp : Integer;
                attribute eventType : String;
                attribute details : String;
            }
        }

        part def 'System Component' {
            attribute componentName : String;
            attribute latencyBudget : Real;
            attribute throughputCapacity : Integer;
        }

        part def 'Market Data Handler' :> 'System Component' {
            doc /*
            * Ingests real-time market data from exchanges, normalizes
            * formats, and distributes to downstream components.
            */

            out port dataOut : MarketDataPort;
            attribute :>> latencyBudget = 0.0001;  // 100 microseconds

            allocate Requirements::'Stakeholder Requirements'::'Executive Stakeholder Requirements'::'STKR-EXEC-002' to self;
            allocate Requirements::'System Requirements'::'Functional Requirements'::'SYS-FUNC-001' to self;
            allocate Requirements::'System Requirements'::'Functional Requirements'::'SYS-FUNC-002' to self;
            allocate Requirements::'System Requirements'::'Performance Requirements'::'SYS-PERF-001' to self;
        }

        part def 'Strategy Engine' :> 'System Component' {
            doc /*
            * Executes trading strategies, analyzes market data, and
            * generates trading signals based on configured algorithms.
            */

            attribute strategyType : 'Strategy Type';
            attribute strategyParameters : String [*];

            in port dataIn : ~MarketDataPort;
            out port signalOut : TradingSignalPort;

            allocate Requirements::'Stakeholder Requirements'::'User Stakeholder Requirements'::'Trading Team Requirements'::'STKR-USER-001' to self;
            allocate Requirements::'Stakeholder Requirements'::'User Stakeholder Requirements'::'Trading Team Requirements'::'STKR-USER-002' to self;
            allocate Requirements::'Stakeholder Requirements'::'User Stakeholder Requirements'::'Trading Team Requirements'::'STKR-USER-003' to self;
        }

        part def 'Order Management System' :> 'System Component' {
            doc /*
            * Creates, routes, modifies, and tracks orders throughout
            * their lifecycle. Maintains order book and state.
            */

            attribute :>> latencyBudget = 0.0005;  // 500 microseconds

            in port signalIn : ~TradingSignalPort;
            out port orderOut : OrderPort;

            allocate Requirements::'System Requirements'::'Functional Requirements'::'SYS-FUNC-003' to self;
            allocate Requirements::'System Requirements'::'Performance Requirements'::'SYS-PERF-002' to self;
        }

        part def 'Risk Management System' :> 'System Component' {
            doc /*
            * Performs pre-trade and post-trade risk checks. Enforces
            * position limits, loss limits, and can halt trading.
            */

            attribute positionLimits : Real [*];
            attribute lossLimits : Real [*];
            attribute :>> latencyBudget = 0.0002;  // 200 microseconds

            in port orderIn : ~OrderPort;
            out port decisionOut : RiskDecisionPort;
            out port alertOut : AlertPort;

            allocate Requirements::'Stakeholder Requirements'::'User Stakeholder Requirements'::'Risk Management Requirements'::'STKR-RISK-001' to self;
            allocate Requirements::'Stakeholder Requirements'::'User Stakeholder Requirements'::'Risk Management Requirements'::'STKR-RISK-002' to self;
            allocate Requirements::'Stakeholder Requirements'::'User Stakeholder Requirements'::'Risk Management Requirements'::'STKR-RISK-003' to self;
            allocate Requirements::'Stakeholder Requirements'::'User Stakeholder Requirements'::'Risk Management Requirements'::'STKR-RISK-004' to self;
            allocate Requirements::'Stakeholder Requirements'::'User Stakeholder Requirements'::'Risk Management Requirements'::'STKR-RISK-005' to self;
            allocate Requirements::'System Requirements'::'Risk Control Requirements'::'SYS-RISK-001' to self;
            allocate Requirements::'System Requirements'::'Risk Control Requirements'::'SYS-RISK-002' to self;
            allocate Requirements::'System Requirements'::'Risk Control Requirements'::'SYS-RISK-003' to self;
            allocate Requirements::'System Requirements'::'Risk Control Requirements'::'SYS-RISK-004' to self;
            allocate Requirements::'System Requirements'::'Risk Control Requirements'::'SYS-RISK-005' to self;
        }

        part def 'Execution Management System' :> 'System Component' {
            doc /*
            * Routes approved orders to exchanges and brokers. Implements
            * smart order routing and execution algorithms.
            */

            attribute :>> latencyBudget = 0.0003;  // 300 microseconds

            in port decisionIn : ~RiskDecisionPort;
            out port notificationOut : ExecutionNotificationPort;

            allocate Requirements::'System Requirements'::'Performance Requirements'::'SYS-PERF-002' to self;
            allocate Requirements::'Stakeholder Requirements'::'User Stakeholder Requirements'::'Compliance Requirements'::'STKR-COMP-004' to self;
            allocate Requirements::'System Requirements'::'Compliance Requirements'::'SYS-COMP-002' to self;
        }

        part def 'Compliance Module' :> 'System Component' {
            doc /*
            * Ensures regulatory compliance through audit logging,
            * trade surveillance, and regulatory reporting.
            */

            attribute auditRetentionDays : Integer = 1825;  // 5 years for MiFID II

            in port orderIn : ~OrderPort;
            in port notificationIn : ~ExecutionNotificationPort;
            in port alertIn : ~AlertPort;
            out port auditOut : AuditDataPort;

            allocate Requirements::'Stakeholder Requirements'::'Executive Stakeholder Requirements'::'STKR-EXEC-002' to self;
            allocate Requirements::'Stakeholder Requirements'::'User Stakeholder Requirements'::'Compliance Requirements'::'STKR-COMP-001' to self;
            allocate Requirements::'Stakeholder Requirements'::'User Stakeholder Requirements'::'Compliance Requirements'::'STKR-COMP-002' to self;
            allocate Requirements::'Stakeholder Requirements'::'User Stakeholder Requirements'::'Compliance Requirements'::'STKR-COMP-003' to self;
            allocate Requirements::'System Requirements'::'Compliance Requirements'::'SYS-COMP-001' to self;
            allocate Requirements::'System Requirements'::'Compliance Requirements'::'SYS-COMP-003' to self;
        }

        part def 'Backtesting Engine' :> 'System Component' {
            doc /*
            * Tests trading strategies on historical market data with
            * realistic execution simulation.
            */

            attribute historicalDataYears : Integer;

            in port dataIn : ~MarketDataPort;
            out port signalOut : TradingSignalPort;

            allocate Requirements::'Stakeholder Requirements'::'User Stakeholder Requirements'::'Trading Team Requirements'::'STKR-USER-001' to self;
        }

        part def 'Monitoring & Alerting' :> 'System Component' {
            doc /*
            * Real-time monitoring of system health, performance metrics,
            * P&L tracking, and alerting on anomalies.
            */

            in port notificationIn : ~ExecutionNotificationPort;
            in port alertIn : ~AlertPort;

            allocate Requirements::'Stakeholder Requirements'::'User Stakeholder Requirements'::'Trading Team Requirements'::'STKR-USER-003' to self;
            allocate Requirements::'Stakeholder Requirements'::'User Stakeholder Requirements'::'Trading Team Requirements'::'STKR-USER-004' to self;
            allocate Requirements::'System Requirements'::'Functional Requirements'::'SYS-FUNC-004' to self;
            allocate Requirements::'System Requirements'::'Performance Requirements'::'SYS-PERF-004' to self;
        }
    }

    package 'System Instances' {
        private import 'Algorithmic Trading System Design'::'System Definitions'::*;

        part 'Algorithmic Trading Platform' {
            doc /*
            * Complete algorithmic trading system integrating market data 
            * ingestion, strategy execution, risk management, order 
            * execution, and regulatory compliance.
            */
            
            part marketDataHandler : 'Market Data Handler' [1];
            part strategyEngine : 'Strategy Engine' [1..*];
            part orderManagement : 'Order Management System' [1];
            part riskManagement : 'Risk Management System' [1];
            part executionManagement : 'Execution Management System' [1];
            part compliance : 'Compliance Module' [1];
            part backtesting : 'Backtesting Engine' [1];
            part monitoring : 'Monitoring & Alerting' [1];
            
            // Data flow connections
            connect marketDataHandler.dataOut to strategyEngine.dataIn;
            connect strategyEngine.signalOut to orderManagement.signalIn;
            connect orderManagement.orderOut to riskManagement.orderIn;
            connect riskManagement.decisionOut to executionManagement.decisionIn;
            connect executionManagement.notificationOut to compliance.notificationIn;
            connect executionManagement.notificationOut to monitoring.notificationIn;
            connect riskManagement.alertOut to compliance.alertIn;
            connect riskManagement.alertOut to monitoring.alertIn;
            connect orderManagement.orderOut to compliance.orderIn;

            connect marketDataHandler.dataOut to backtesting.dataIn;
            

            allocate Requirements::'Stakeholder Requirements'::'Executive Stakeholder Requirements'::'STKR-EXEC-001' to self;
            allocate Requirements::'Stakeholder Requirements'::'Executive Stakeholder Requirements'::'STKR-EXEC-002' to self;
            allocate Requirements::'Stakeholder Requirements'::'Executive Stakeholder Requirements'::'STKR-EXEC-003' to self;
        }
    }
}
