Getting Started
Welcome to the pyPSX developer platform — Pakistan's algorithmic trading infrastructure for the Pakistan Stock Exchange (PSX). This guide walks you through installation, authentication, and your first trade.
What is pyPSX?
pyPSX provides two Python libraries:
- pypsx — Fetch historical OHLCV data, intraday ticks, sector constituents, company fundamentals, dividends, and more.
- pytrader — Algorithmic trading SDK for PSX. Supports paper trading, backtesting, and strategy execution.
Installation
Install both libraries with a single command:
pip install pypsx pytrader-sdk
Requirements: Python 3.9–3.13. Always use a virtual environment — it avoids permission errors and keeps your project dependencies isolated:
python -m venv .venv
source .venv/bin/activate # Linux/macOS
.venv\Scripts\activate # Windows
pip install pypsx pytrader-sdk
Windows tip: If you see "normal site-packages is not writeable", you are not inside a virtual environment. Run the commands above first, then install.
Verify Installation
import pypsx
import pytrader
print(pypsx.__version__) # e.g. 3.0.0
print(pytrader.__version__) # e.g. 1.0.0
# Quick test — fetch OGDC price
t = pypsx.Ticker("OGDC")
print(t.fast_info)
Get Your API Keys
pypsx works without authentication. pytrader requires an API key.
- Sign up at markets.pypsx.com
- Log in and go to your Dashboard
- Click Generate New Keys in the API Keys section — you'll receive a Key ID and Secret Key (shown once)
- Your paper trading key starts with
PK_
Environment Variables
Store your credentials as environment variables (never hardcode them):
# Linux/macOS — add to ~/.bashrc or ~/.zshrc
export PYPSX_API_KEY_ID="PK_xxxxxxxxxxxxxxxx"
export PYPSX_API_SECRET_KEY="your_secret_here"
# Windows PowerShell
$env:PYPSX_API_KEY_ID = "PK_xxxxxxxxxxxxxxxx"
$env:PYPSX_API_SECRET_KEY = "your_secret_here"
Or create a .env file and load it with python-dotenv:
from dotenv import load_dotenv
load_dotenv()
from pytrader import TradingClient
client = TradingClient.from_env(paper=True)
Quick Start — 5 Minutes to First Trade
1. Fetch historical data with pypsx
import pypsx
# Get 1 year of daily OHLCV data for OGDC
df = pypsx.download("OGDC", period="1y")
print(df.tail())
# Open High Low Close Volume
# 2024-12-26 183.0 187.5 181.0 185.5 3_450_000
# 2024-12-27 185.0 190.0 184.0 189.0 2_870_000
2. Check live market data
# Full market watch (all symbols)
mw = pypsx.market_watch()
top_gainers = mw.nlargest(10, "Change%")
print(top_gainers[["Symbol", "Current", "Change%"]])
3. Connect to your paper trading account
from pytrader import TradingClient
client = TradingClient.from_env(paper=True)
account = client.get_account()
print(f"Paper account equity: PKR {account['equity']:,.0f}")
4. Place a paper trade
order = client.place_manual_order(
symbol="OGDC",
side="BUY",
quantity=100,
order_type="MARKET",
)
print(f"Order placed: {order['order_id']} | Status: {order['status']}")
5. Check your portfolio
portfolio = client.get_portfolio_valuation()
print(f"Cash: PKR {portfolio['cash']:,.0f}")
print(f"Positions value: PKR {portfolio['positions_value']:,.0f}")
print(f"Unrealised P&L: PKR {portfolio['unrealized_pnl']:,.0f}")
6. Stream live prices with LiveFeed
from pytrader import TradingClient, LiveFeed
client = TradingClient.from_env(paper=True)
feed = LiveFeed(
api_key=client.api_key,
secret_key=client.secret_key,
symbols=["OGDC", "HBL", "PSO"],
paper=True,
)
def on_tick(tick):
print(f"{tick.symbol} {tick.price} bid={tick.bid} ask={tick.ask}")
feed.on_tick(on_tick)
feed.start() # blocks — Ctrl+C to stop
LiveFeed connects to the WebSocket backend, subscribes to your symbols, and fires on_tick for every price update. It reconnects automatically if the connection drops.
Using these docs with AI tools
Every page on this site is readable by AI assistants and LLMs — just paste a page URL directly into ChatGPT, Claude, or any AI with browsing capability and it will read the content without any workarounds.
If you want to give an AI the entire documentation library at once (all 19 pages in a single file), paste this URL instead:
https://markets.pypsx.com/llms.txt
This is a plain-text file containing every doc page concatenated in order — useful for priming an AI with full context before asking deep questions about the API.
Next Steps
- Live Feed & WebSocket — Real-time price streaming, connection callbacks, raw WS protocol
- TradingClient — Full API client reference
- Historical Data — Download years of OHLCV data
- Backtesting — Test your strategy on historical data
- REST API Reference — Raw endpoint documentation