Skip to content

AB1903/Portfolio-Trade-Engine

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Portfolio Trade Execution Engine

What This Does

Takes a list of stocks and quantities, connects to your broker, and automatically places the necessary buy/sell orders in one API call.


Supported Brokers

  • Zerodha (Kite Connect)
  • Fyers (API v3)
  • AngelOne (SmartAPI)
  • Groww (Partner API)
  • Upstox (API v2)

Project Structure

app/
├── models/schemas.py        # All data models
├── brokers/
│   ├── base.py              # Broker interface (abstract class)
│   ├── registry.py          # Broker lookup table
│   ├── zerodha.py           # Zerodha adapter
│   ├── fyers.py             # Fyers adapter
│   ├── angelone.py          # AngelOne adapter
│   ├── groww.py             # Groww adapter
│   └── upstox.py            # Upstox adapter
├── core/engine.py           # Main execution logic
├── notifications/notifier.py # Console, Webhook, WebSocket notifications
├── api/routes.py            # API endpoints
└── main.py                  # App entry point

How to Run

Option 1 — Local

# Create virtual environment
python3.10 -m venv venv
source venv/bin/activate

# Install dependencies
pip install -r requirements.txt

# Start the API
uvicorn app.main:app --reload

# Start the frontend (separate terminal)
streamlit run frontend.py

Option 2 — Docker

docker-compose up --build

API Endpoints

Method URL Description
GET /api/v1/health Health check
GET /api/v1/examples Example request payloads
POST /api/v1/execute Execute portfolio trades
WS /api/v1/ws Live notifications

Two Execution Modes

1. First-Time Buy

Send a target portfolio — engine figures out what to buy:

{
  "broker": "zerodha",
  "api_key": "your_key",
  "api_secret": "your_secret",
  "target_portfolio": {
    "RELIANCE": 10,
    "TCS": 5,
    "INFY": 8
  }
}

2. Rebalancing

Send explicit instructions — engine executes them directly:

{
  "broker": "zerodha",
  "api_key": "your_key",
  "api_secret": "your_secret",
  "instructions": [
    {"symbol": "RELIANCE", "instruction": "SELL", "quantity": 3},
    {"symbol": "TCS",      "instruction": "BUY",  "quantity": 5},
    {"symbol": "INFY",     "instruction": "REBALANCE", "quantity": 2}
  ]
}

How the Engine Works

Request comes in
      ↓
Authenticate with broker
      ↓
First-time buy?  → fetch current holdings → compute delta
Rebalancing?     → use instructions directly
      ↓
Execute all orders concurrently
      ↓
Retry failed orders (up to 3 times)
      ↓
Send notifications (console + websocket + webhook)
      ↓
Return summary

Notifications

  • Console — always printed to terminal
  • WebSocket — connect to /api/v1/ws for live updates
  • Webhook — pass ?webhook_url=https://your-url.com to the execute endpoint

Adding a New Broker

  1. Create app/brokers/newbroker.py with your adapter class
  2. Add the broker name to BrokerName enum in schemas.py
  3. Add one line to BROKER_REGISTRY in registry.py

Zero changes needed anywhere else.


Architecture Decisions

Adapter Pattern — each broker has its own adapter class implementing the same interface. The engine never talks to broker-specific code directly.

Concurrent Execution — all orders run simultaneously using asyncio.gather(). A 20-stock portfolio takes the same time as 1 order.

Retry with Backoff — failed orders are retried up to 3 times with increasing wait times (1.5s → 2.25s → 3.37s).

Separation of Concerns — routes handle HTTP, engine handles logic, adapters handle brokers, notifiers handle alerts. No file does more than one job.


Notes

  • All broker calls are mocked for this assignment. Real SDK calls are shown in comments inside each adapter file.
  • Brokers require real credentials and browser-based OAuth login for production use.

About

Portfolio Trade Execution Engine built with FastAPI. Supports 5 Indian brokers (Zerodha, Fyers, AngelOne, Groww, Upstox) with automatic order execution, rebalancing, and real-time notifications.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors