-- Create order_batches table for trading agent service -- Stores generated order batches before submission to trading service CREATE TYPE order_batch_status AS ENUM ('PENDING', 'SUBMITTED', 'EXECUTED', 'FAILED', 'CANCELLED'); CREATE TABLE IF NOT EXISTS order_batches ( batch_id UUID PRIMARY KEY DEFAULT gen_random_uuid(), allocation_id UUID NOT NULL, status order_batch_status NOT NULL DEFAULT 'PENDING', order_generation_strategy JSONB NOT NULL, -- Strategy parameters total_notional NUMERIC(20, 2) NOT NULL, orders_generated INTEGER NOT NULL DEFAULT 0, orders_submitted INTEGER NOT NULL DEFAULT 0, orders_accepted INTEGER NOT NULL DEFAULT 0, orders_rejected INTEGER NOT NULL DEFAULT 0, acceptance_rate NUMERIC(5, 4), created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), submitted_at TIMESTAMPTZ, completed_at TIMESTAMPTZ, error_message TEXT, FOREIGN KEY (allocation_id) REFERENCES portfolio_allocations(allocation_id) ON DELETE CASCADE ); -- Create generated_orders table for individual orders within batch CREATE TABLE IF NOT EXISTS generated_orders ( order_id UUID PRIMARY KEY DEFAULT gen_random_uuid(), batch_id UUID NOT NULL, symbol VARCHAR(50) NOT NULL, side order_side_type NOT NULL, quantity NUMERIC(20, 4) NOT NULL, order_type order_type_enum NOT NULL DEFAULT 'MARKET', price NUMERIC(20, 2), rationale TEXT, metadata JSONB, trading_service_order_id UUID, -- Reference to submitted order in Trading Service success BOOLEAN, error_message TEXT, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), FOREIGN KEY (batch_id) REFERENCES order_batches(batch_id) ON DELETE CASCADE ); -- Indexes for performance CREATE INDEX idx_order_batches_allocation ON order_batches(allocation_id); CREATE INDEX idx_order_batches_status ON order_batches(status); CREATE INDEX idx_order_batches_created ON order_batches(created_at DESC); CREATE INDEX idx_generated_orders_batch ON generated_orders(batch_id); CREATE INDEX idx_generated_orders_symbol ON generated_orders(symbol); -- Comments COMMENT ON TABLE order_batches IS 'Batches of generated orders for trading agent'; COMMENT ON TABLE generated_orders IS 'Individual orders within order batches';