Javed Iqbal Securities (Pvt.) Limited
Javed Iqbal Securities (Pvt) Ltd.Accounts & trading process / Topic 76

Introduction to Algorithmic Trading

Design a reproducible research system before considering authorised execution.

Advanced5 chaptersCharts & tablesReviewed 22 Oct 2026
Read this topic in Urdu ↗
Topic introduction

The big picture

Algorithmic trading translates decisions or execution instructions into explicit machine-readable rules. Automation can improve consistency, but it can also repeat a mistake faster than a person can intervene. This topic develops a paper research and control workflow. It does not establish that JISPL offers a retail API, that a personal script may access an exchange gateway, or that a proposed regulatory framework is already binding law. Live access requires current written confirmation from the relevant authorised provider and applicable rules.

Core concepts

Signal research and order execution are separate systems.A backtest reconstructs what could have been known and traded.Order acknowledgements and confirmed fills require a persistent state model.Operational controls and human governance remain necessary under automation.

Learning objectives

  1. Specify a deterministic moving-average strategy without ambiguity.
  2. Build a dated, reproducible and bias-aware test protocol.
  3. Explain TWAP, VWAP and participation execution concepts.
  4. Design limits, reconciliation and emergency shutdown tests.
Chapter 01

1. Convert an idea into exact rules

1.1 Inputs, decisions and timing

A rule such as “buy when momentum improves” cannot be implemented consistently until its inputs, calculation, observation time and action are defined. A paper crossover experiment might use a 20-observation and 50-observation simple average of adjusted daily closes. Specify a signal only when the short average moves from at or below the long average to above it, using completed data. These illustrative lengths are research choices, not proven optimal settings.

1.2 State and exception handling

Define target exposure, maximum holdings, cash treatment, exit conditions and what happens when data is missing or a security is suspended. A signal should produce an intended position, not repeated buy orders every time the program checks the same condition. Keep model versions and human overrides in an audit trail. Automation shifts emotion into rule selection and override decisions; it does not eliminate human judgement or behavioural bias.

Step-by-step method

  1. Write input fields, calculation and exact crossover conditions.
  2. Set observation time and earliest feasible execution time.
  3. Define position state, missing-data policy and exit conditions.
Practical application / case study

A program checks a positive crossover every minute and submits a fresh buy each time. Changing the design to compare current holdings with one target position prevents repeated accumulation from an unchanged signal.

Chapter 02

2. Establish data lineage and a fair backtest

2.1 Point-in-time observations

A backtest is a controlled reconstruction, not a screenshot of a profitable chart. Store source, retrieval date, adjustments, calendar and transformation steps. Corporate actions require consistent prices, quantities and cash-flow treatment. Point-in-time universe selection means including companies that were then eligible, including later failures or delistings. Using today’s index constituents throughout history introduces survivorship bias.

2.2 Universe, corporate actions and splits

An index level can test a market-timing signal but is not automatically a tradeable share with the same return. A five-year KSE-100 study must explain whether it uses a price or total-return series, how an investable implementation would be obtained and how distributions are treated. Signal calculation and execution timestamps must prevent look-ahead. A final close cannot generate a signal and then guarantee a fill at that same already-observed close.

Step-by-step method

  1. Record data provenance and adjustment conventions.
  2. Construct the universe known at each historical date.
  3. Separate signal data from feasible execution and cash accounting.
Practical application / case study

A researcher tests today’s strongest constituents over five years and reports a large gain. Reconstructing historical membership adds weaker and removed firms, revealing that the first result partly measured hindsight selection.

Chapter 03

3. Validate beyond one attractive history

3.1 Development and untouched testing

Use development data to design rules, a validation segment to assess revisions and an untouched final segment for evaluation. Walk-forward tests repeatedly fit using past data and evaluate later data. Log all parameter trials: trying hundreds of settings and displaying only the best creates selection bias. One poor year does not prove permanent failure, and one profitable period does not prove a durable advantage.

3.2 Costs, capacity and benchmarks

Model commission, taxes where applicable, spreads, slippage, order-size constraints and unfilled orders. Calculate net returns, drawdown, turnover and exposure against an appropriate benchmark with consistent dividends and cash returns. Stress delayed fills, missing sessions and wider costs. A strategy whose paper edge disappears after modest friction should not be rescued by assuming perfect execution. Historical measurements remain estimates of a particular experiment, not promised future outcomes.

Step-by-step method

  1. Lock rules before final testing and record unsuccessful trials.
  2. Apply explicit costs and plausible capacity restrictions.
  3. Compare net outcomes and stress cases with a consistent benchmark.
Practical application / case study

An invented test earns PKR 12,000 gross on PKR 100,000 capital. Assumed total trading frictions of PKR 8,000 leave PKR 4,000, before any additional unmodelled tax or funding. A large gross return can conceal a small, fragile net result.

Chapter 04

4. Separate execution algorithms from investment signals

4.1 TWAP, VWAP and participation

A signal algorithm decides desired exposure; an execution algorithm works a given instruction through time. TWAP divides activity across time intervals. VWAP-oriented execution follows an expected volume profile, while participation algorithms seek a share of observed market volume. These are benchmarks and scheduling ideas, not guarantees of a particular price. Urgency, thin liquidity and price movement create a trade-off between market impact and non-completion.

4.2 Order state, permissions and access

A FIX gateway is a communication facility within an authorised market-access structure, not evidence of public retail API entitlement. Obtain current documentation, provider permission, account/product eligibility and required approvals before any live integration. The SECP May 2025 concept paper is a proposal, not by itself an enacted universal approval rule. This topic supplies no live credentials, bypass instructions or assertion that JISPL supports automated retail orders.

Step-by-step method

  1. Distinguish the target-position engine from the execution scheduler.
  2. Verify written access permission and applicable current rules.
  3. Model acknowledgement, rejection, partial fill and cancellation states.
Practical application / case study

A research script produces a target of 1,000 shares. A paper TWAP plan schedules five 200-share slices, but a thin-book scenario leaves slices unfilled. The learner reports non-completion rather than assuming every scheduled slice executes.

Chapter 05

5. Engineer controls and accountable operation

5.1 Pre-trade limits and safe failure

Controls should constrain order quantity, price deviation, exposure, submission rate and total loss tolerance under an approved policy. Reject stale prices, invalid symbols and impossible quantities. Unique instruction identifiers and persistent order state reduce duplicate orders after a timeout. A failed connection means the result is unknown until reconciled, not that the exchange never received an order. Test these controls in a disconnected or authorised simulation environment.

5.2 Reconciliation, shutdown and recovery

A kill switch should stop new submissions and invoke a documented process for existing orders and positions; merely closing the program does not cancel exchange orders. Assign an accountable operator, monitor alerts and reconcile broker records with internal state. Recovery requires confirmation of live orders, fills and holdings before restarting. Periodic review should cover model drift, system changes and permissions. A profitable backtest cannot compensate for a system that cannot establish its actual exposure.

Step-by-step method

  1. Test stale data, duplicate messages, rejections and interrupted connections.
  2. Specify who can halt activity and how open orders are resolved.
  3. Reconcile independently before restart and preserve incident logs.
Practical application / case study

A timeout occurs after an order submission. The simulator restarts with no memory and would submit again. Persisting the instruction and checking confirmed broker state prevents the second order; shutdown procedures separately address any still-open first order.

Visual learning

Research does not bypass the permission and control gates

  1. Specify deterministic rules
  2. Validate dated data and net results
  3. Verify authorised access and requirements
  4. Test order controls in simulation
  5. Monitor and reconcile any permitted operation
This is a governance workflow, not a statement that JISPL provides live retail API access.

Reference table

Research success and operational permission are separate gates
GateEvidence neededFailure response
DataDated source, adjustments and historical universeStop and repair lineage
ResearchLocked rules and untouched net testsReject or revise hypothesis
AccessWritten provider permission and current requirementsRemain in paper simulation
Pre-tradePrice, quantity, exposure and freshness checksReject instruction
RecoveryConfirmed broker orders, fills and holdingsDo not restart until reconciled
Comprehensive knowledge base

Glossary of key terms

Algorithm
A specified sequence of rules for processing inputs and producing actions.
Backtest
A historical reconstruction under explicit data and execution assumptions.
FIX
A financial messaging protocol used within authorised connectivity arrangements.
Kill switch
A control and procedure for halting activity and managing outstanding instructions.
Participation rate
Intended trading quantity as a fraction of relevant market volume.
Point-in-time data
Information represented as it was available at the decision date.
TWAP
Time-weighted average price; also an execution scheduling reference.
VWAP
Volume-weighted average price; also an execution benchmark.

Frequently asked questions

Does automation remove emotion?

It can enforce rules, but humans still choose, modify and override those rules.

Does a profitable backtest authorise live trading access?

No. Access permissions, current rules and operational readiness are separate requirements.

Does the SECP concept paper prove every algorithm already requires the same approval?

No. A proposal must be distinguished from effective rules and provider-specific requirements.

Does stopping software cancel live orders?

No. Outstanding exchange instructions must be separately confirmed and managed.

Common pitfalls

Common pitfalls
Common mistakeA better approach
Using present constituents for all historical datesReconstruct the eligible universe at each date.
Repeatedly buying while one condition remains trueGenerate orders from target versus actual exposure.
Treating unknown submission state as failureReconcile the existing reference before retrying.
Assuming API permission from technical connectivityObtain written authorised access and current requirements.
Apply your learning

Your learner task

Write a paper-only moving-average specification, data dictionary, dated universe policy and train/validation/test split. Include costs and a benchmark, a five-state order diagram, and tests for stale data, duplicate submission, partial fill, shutdown and restart. Record any live-access or legal question as unresolved until verified.

Sources & verification

Use the linked documents to check the factual and regulatory context. Source dates and limitations are stated where relevant. Educational examples and analytical frameworks are not personalised recommendations.

  1. JISPL · Knowledge curriculum ↗

    Course identity and subject coverage; factual corrections are explained in this expanded lesson.

  2. SECP algorithmic trading concept paper ↗

    May 2025 consultation; distinguish proposals from currently effective obligations.

  3. SECP proposed framework announcement ↗

    Official description as proposed framework; does not establish retail API access.

  4. PSX Rulebook and gateway procedures ↗

    Check current trading, connectivity and provider requirements.

Editorial review: 22 October 2026