Recommended resources
The freely available resources this lesson will direct you to.
Welcome. This course builds toward a practical automated trading workflow: research a strategy, test it honestly, control its risk, and eventually run it through a broker without treating “place an order” as the whole system.
Before writing Python or designing signals, you need a map of the system. An automated strategy is not a single formula connected directly to a broker API. It is a chain of specialized components that turn market information into controlled decisions, record what actually happened, and make failures visible. In this lesson, you will learn to separate those responsibilities into data, signal, portfolio, risk, execution, and monitoring.
For a swing-trading system, this decomposition may initially live in one small codebase and run once per day. The boundaries still matter: they are what make the system testable now and safer to extend later.
Study time: about 40 minutes.
Think in decisions, intentions, and facts
A useful first distinction is between three kinds of information:
- A signal is a forecast or opinion, such as “RELIANCE has relatively strong momentum over the next 10 sessions.”
- A target position is an intended portfolio outcome, such as “hold 150 shares of RELIANCE.”
- A fill is a fact reported by the market or broker, such as “80 shares were bought at an average price of ₹2,945.”
Confusing these is a common source of dangerous trading code. A signal does not imply a particular order quantity. A submitted order does not imply a fill. And a fill does not automatically mean your internal records agree with the broker.
The central system question is therefore not merely “Should I buy?” It is:
Given reliable information, current holdings, capital, constraints, and market conditions, what portfolio should I hold, what orders are safe to send, and what actually happened afterward?
The QuantConnect tutorial gives a clear modular view of the middle of this process: a model produces a forecast, portfolio construction turns forecasts into position targets, risk adjusts or rejects those targets, and execution trades toward the approved targets.
Algorithm Framework Tutorial - Building Robust Models in QuantConnect
Watch “Algorithm Framework Tutorial - Building Robust Models in QuantConnect” by QuantConnect for a concise walk-through of modular strategy responsibilities. Although this course will build its own Python workflow rather than depend on QuantConnect, the component boundaries are directly useful.
Begin with the framework overview to see why separation of concerns makes components reusable and testable. Then watch signal generation, focusing on the distinction between a forecast and a trade. Continue with portfolio targets, risk controls, and execution. Notice that execution compares a target with current holdings; it does not blindly submit a new order whenever a signal appears.
For an individual Indian-equity swing strategy, the components will normally work in daily batches rather than respond to every market tick. The architecture is still the same. What changes later, when moving toward intraday trading, is the required speed and the complexity of handling live events.
The six components
The following architecture is a useful conceptual map. In a small system, some boxes may initially be implemented in the same process. Their responsibilities, inputs, and outputs should nevertheless remain distinct.

Quant Trading Systems: Architecture & Infrastructure - Interactive ...
Read the “Trading Pipeline” overview in this article to reinforce the operational role of each major component, including data infrastructure, strategy, risk, order management, execution, portfolio state, and logging.
In the “The Trading Pipeline” section, read from the pipeline explanation and component list. Focus especially on the difference between the Strategy Engine, Risk Management System, Execution Management System, Order Management System, Portfolio Management System, and Monitoring and Logging. Treat the diagram as a conceptual map rather than a prescription for a particular technology stack.
1. Data: establish what the system is allowed to know
The data component acquires, validates, timestamps, and stores the information used elsewhere. For a daily swing system, this might include:
- Daily OHLCV bars: open, high, low, close, and volume.
- Instrument metadata: symbol, exchange, and broker-specific instrument identifier.
- Corporate-action information, such as splits and dividends.
- Market-calendar information: whether a session occurred and whether a bar is complete.
- Later, broker account data, order updates, and current positions.
The data component has two jobs that are easy to underestimate.
First, it must make information usable. Raw vendor or broker responses may have missing bars, duplicate records, wrong time zones, stale values, or changed symbols. Downstream components should receive a clean, consistent data contract rather than each having to repair raw data in its own way.
Second, it must make availability explicit. A bar dated Monday may be useful for a decision made after Monday’s market close, but not for a decision supposedly made before that close. This “what was known when?” discipline prevents accidental use of future information in both backtests and live systems.
A data component should not decide that a stock is attractive or decide how much capital to allocate. Its output is evidence, not a trading recommendation.
2. Signal: express a forecast, not an order
The signal component, often called the alpha model or strategy engine, transforms available data into a standardized statement of expected opportunity.
A signal might contain:
- Symbol:
RELIANCE - Direction: bullish, bearish, or neutral
- Strength: a score, rank, expected return, or confidence
- Holding horizon: for example, 5 or 10 sessions
- Time of decision: when the signal was created
- Data version: the dataset snapshot used to create it
For example, a cross-sectional momentum strategy might calculate six-month returns for every stock in a liquid universe and assign a score to each. The signal component can state that RELIANCE ranks near the top and another stock ranks near the bottom. It should not decide that RELIANCE gets ₹80,000 of capital. That decision depends on the rest of the portfolio, cash, diversification rules, volatility, and risk limits.
Keeping signals free of order details provides a powerful test: you can test whether your signal logic ranks stocks correctly without needing a brokerage connection, account balance, or fill simulator.
3. Portfolio: convert views into a coherent desired portfolio
The portfolio component answers: given all valid signals together, what should we hold?
It has two closely related responsibilities:
- Portfolio construction converts signals into desired targets.
- Portfolio state records actual cash, quantities, cost basis, market value, and profit and loss.
The first is an optimization or allocation problem. Suppose a strategy selects the top 10 names from a liquid stock universe. Portfolio construction might assign equal weights, allocate more to lower-volatility stocks, or keep a fixed cash reserve. Its output is a set of target positions, such as:
| Symbol | Current quantity | Desired target | Interpretation |
|---|---|---|---|
| RELIANCE | 60 | 150 | Increase the holding |
| INFY | 100 | 0 | Exit the holding |
| TCS | 0 | 80 | Open a position |
A target is a desired end state, not a trade instruction. This distinction matters because the execution component must consider the current quantity, pending orders, lot or quantity constraints, cash, and the price available at the time of trading.
The second responsibility, portfolio state, answers a different question: what do we actually own right now? It should be based on confirmed fills and reconciled broker data, not on what the strategy wished to own. A portfolio can be “targeted” to hold 150 shares while actually holding only 60 because an order was rejected, partially filled, or never sent.
4. Risk: constrain decisions before capital is committed
The risk component is the system’s independent safety gate. It receives proposed targets, current portfolio state, prices, and system-health information. It can approve, resize, replace, or reject proposed targets.
For a swing system, early risk controls commonly include:
- Maximum allocation to one stock.
- Maximum allocation to one sector.
- Maximum total invested capital or gross exposure.
- Maximum number of positions.
- Minimum liquidity requirements.
- Maximum turnover at a rebalance.
- A drawdown or daily-loss circuit breaker.
- A stale-data rule that blocks new trading when required inputs are old or missing.
Risk is deliberately separate from the signal. A strong momentum score may be perfectly valid while the corresponding trade is still unsafe. For example, a stock could already represent too much of the portfolio, or a data-quality check could have failed.
The critical design rule is:
The signal component may propose. The risk component has authority to prevent or reduce exposure.
Risk should also run close to order submission. A target approved in the morning may become unsafe later if prices gap sharply, account cash changes, an earlier order fills unexpectedly, or data becomes stale.
5. Execution: turn approved targets into controlled orders
The execution component compares approved target positions with actual positions and determines the order changes required to move toward the targets.
If the approved target is 150 shares and the confirmed current position is 60 shares, the desired change is an additional 90 shares. That is still not quite enough to safely send an order. Execution must select practical details such as:
- Buy or sell side.
- Quantity after rounding rules.
- Market or limit order.
- Price limits and validity.
- Timing and any schedule for splitting an order.
- How to handle an order that is pending, partially filled, rejected, cancelled, or timed out.
Execution interfaces with the broker, so it crosses an important failure boundary. Network calls can time out. A request may have reached the broker even when your application received no response. A safe system must not interpret a timeout as “the order definitely did not exist” and blindly submit a duplicate.
In a small application, execution and an order management system may live together. The order-management responsibility is to preserve the lifecycle of every order: created, submitted, open, partially filled, filled, cancelled, or rejected. The execution responsibility is to choose and place orders. Later lessons will treat those distinctions in much more detail.
6. Monitoring: make operations explainable and observable
The monitoring component watches the system rather than generating market forecasts. It records enough evidence to answer questions such as:
- Did today’s data arrive and pass validation?
- Did the scheduled strategy job run exactly once?
- Which signals produced which targets?
- Which risk rules modified or blocked a target?
- Which orders were submitted, rejected, or only partially filled?
- Do internal positions and broker positions agree?
- Is a feed, job, or broker request stale?
Monitoring is not merely a dashboard. It includes structured logs, metrics, alerts, and audit records. A useful monitoring record carries a shared identifier, such as a decision_id, through the decision process. That identifier lets you trace a position change back to a specific dataset, strategy run, signal, risk decision, order, and fill.
Monitoring and risk are related but different:
- Risk management makes or blocks exposure decisions.
- Monitoring detects, records, communicates, and helps diagnose operational conditions.
A stale-data alert, for example, is monitoring. The rule that blocks trading when data is stale is risk control.
Use explicit contracts between components
A component boundary becomes real when it has a defined input and output. You do not need microservices or a complex cloud deployment to gain this benefit. Simple Python objects, files, or database tables can serve as contracts.
Here is a deliberately small example:
from dataclasses import dataclass
from datetime import datetime
@dataclass(frozen=True)
class Signal:
symbol: str
as_of: datetime
score: float
horizon_sessions: int
data_version: str
@dataclass(frozen=True)
class TargetPosition:
symbol: str
target_quantity: int
decision_id: str
as_of: datetime
@dataclass(frozen=True)
class OrderIntent:
symbol: str
side: str
quantity: int
decision_id: str
created_at: datetime
Notice what is absent from Signal: no order type, no number of shares, and no claim that a trade happened. Notice what is absent from TargetPosition: no claim that a broker accepted an order. The target is a portfolio decision; the order intent is an execution request.
A reliable system will eventually record additional facts, including:
- a broker order identifier;
- an order status;
- one or more fill records;
- fill quantity and average price;
- broker charges;
- a portfolio snapshot after reconciliation.
This separation produces a traceable chain from an idea to a real financial outcome. It also makes replacements easier. You could improve the signal model without rewriting risk controls, or replace a market-order executor with a limit-order executor without changing the portfolio-construction logic.
A daily swing-trading walkthrough
Consider a simple end-of-day momentum strategy across a liquid Indian-equity universe. The exact indicators and broker details will come later; for now, follow the component ownership.
-
Data retrieves the completed daily market data and instrument information. It validates that the bars are present, internally consistent, and available at the time of the decision. If required data is missing or stale, it publishes that fact.
-
Signal calculates momentum scores using only the valid, available history. It may rank stocks and emit bullish signals for the strongest candidates. At this stage, it has made no claim about position sizes or tradability.
-
Portfolio construction considers all signals at once, together with the actual portfolio state. It might choose the top 10 valid candidates and create target quantities consistent with a defined capital-allocation policy.
-
Risk checks the targets against rules such as stock concentration, sector concentration, liquidity, turnover, available cash, and any circuit breakers. It may reduce a target, set it to zero, or halt the run entirely.
-
Execution compares approved targets with confirmed current positions and creates an order plan for the next permitted trading opportunity. It submits orders through the broker only after final pre-trade checks.
-
Monitoring records every stage, including the data snapshot, rankings, target changes, risk decisions, broker responses, fills, and reconciliation result. It alerts you when something requires review.
The same workflow applies in a backtest, paper-trading run, and controlled live deployment. The implementation differs, but the interfaces should remain recognizable. That continuity is one of the main reasons to decompose the system early.
Failure boundaries and fail-safe behavior
The architecture becomes valuable when something goes wrong. Markets, APIs, clocks, data vendors, and your own code will all fail occasionally. A well-designed system limits the blast radius.
| Failure | Component primarily responsible | Safe system response |
|---|---|---|
| Missing or malformed price data | Data | Reject the data and mark it unusable |
| Strategy calculation error | Signal | Produce no new signal; preserve existing confirmed portfolio state |
| Proposed concentration is too high | Risk | Resize or reject the target before orders exist |
| Broker request times out | Execution and order management | Treat order state as uncertain; reconcile before retrying |
| Broker reports a partial fill | Order management and portfolio state | Record the fill, update actual exposure, retain the remaining order state |
| Internal holdings disagree with broker holdings | Portfolio and monitoring | Block further automated action until reconciliation or a defined recovery process completes |
| Logging or alerting is unavailable | Monitoring | Escalate the operational problem; use a documented policy on whether trading must pause |
The default response to uncertainty should usually be conservative. Missing one trade is generally less damaging than trading on bad data, doubling an order after a timeout, or continuing while you do not know your actual position.
This does not mean every component must halt the entire application whenever it encounters a minor problem. It means the system needs an explicit policy for what it knows, what it does not know, and which unknowns are severe enough to block trading.
Design rules to carry forward
As you build the rest of this course, use these rules to evaluate every feature:
-
One component, one primary responsibility.
Do not bury broker API calls inside indicator code or calculate moving averages inside an order-submission function. -
Pass structured records, not vague assumptions.
Include symbols, timestamps, identifiers, quantities, and data versions in the objects exchanged between components. -
Keep intent separate from reality.
Signals, targets, orders, and fills are different records with different meanings. -
Make portfolio state authoritative and reconcilable.
A strategy’s desired position cannot substitute for confirmed holdings and cash. -
Let risk independently constrain the strategy.
A profitable-looking signal must not be able to bypass exposure limits or data-health checks. -
Treat every external call as fallible.
Data feeds and broker APIs can fail, delay, duplicate, or return incomplete information. -
Make the decision trail observable.
You should be able to explain why a trade was considered, approved or blocked, submitted, and filled.
Key takeaways
An automated trading system is a coordinated set of components, not a strategy formula connected directly to an order API.
- Data provides validated, time-correct market and reference information.
- Signals express forecasts or rankings, not order instructions.
- Portfolio construction and state turn signals into desired holdings while tracking what is actually held.
- Risk independently constrains or rejects proposed exposure.
- Execution translates approved target differences into broker orders and handles real order outcomes.
- Monitoring creates the audit trail and alerts needed to operate safely.
The most important conceptual distinction is between signal, target, order, and fill. Preserving it will make your research more trustworthy and your future live system much safer.
Next, you will create a reproducible Python project structure with isolated dependencies, source modules, notebooks, tests, and version control. That project will give these architectural components a practical home.