Skip to main content

SYSSTRA

PyPI version Python License: MIT

SYSSTRA is a scalable Python library supporting end-to-end algorithmic trading workflows across Equity & Derivatives, Commodities, and Crypto markets on exchanges worldwide.

Build, backtest, and deploy quantitative trading strategies with unified interfaces for market data, order execution, technical analysis, and performance reporting.


🚀 Features

  • Multi-Asset Support: Trade equities, options, futures, and cryptocurrencies
  • Global Markets: NSE, BSE (India) | NYSE, NASDAQ (US) | Binance, CoinDCX (Crypto) | MetaTrader 5 (Forex, CFD)
  • Historical & Live Data: Fetch OHLCV data with flexible granularity (1min to daily)
  • Order Execution Modes:
    • Live Trading: Direct broker integration (Zerodha, Interactive Brokers, Schwab, etc.)
    • Paper Trading: Virtual orders with real-time simulation
    • Backtesting: Test strategies on historical data with realistic fill models
  • 40+ Technical Indicators: EMA, RSI, MACD, ADX, Bollinger Bands, Stochastic, custom indicators
  • Advanced Analytics:
    • Swing detection algorithm for market structure analysis
    • Brokerage calculation for 5+ brokers with accurate fee modeling
    • MetaTrader-style performance reports (drawdown, win rate, consecutive wins/losses)
  • Granularity Conversion: Transform minute-level data to any timeframe
  • Options Chain Analysis: Fetch and analyze options data by strike, expiry, underlying

📦 Installation

pip install sysstra

Install from source:

git clone https://github.com/sysstra/sysstra.git
cd sysstra
pip install -e .

Requirements:

  • Python 3.9+
  • Dependencies: requests, numpy, pandas, pymongo, numba, tqdm

🎯 Quick Start

1. Configure API Access

import sysstra

# Set your API key for data and order services
sysstra.set_api_key("your-api-key-here")

# Optional: Configure custom endpoints
sysstra.set_data_url("https://api.data.sysstra.com/")
sysstra.set_orders_url("https://api.orders.sysstra.com/")

2. Fetch Historical Data

from sysstra.data import fetch_eod_candles, fetch_index_candles
import datetime

# Get daily candles for a stock
start_date = datetime.date(2024, 1, 1)
end_date = datetime.date(2024, 12, 31)

eod_data = fetch_eod_candles(
    symbol="RELIANCE",
    start_date=start_date,
    end_date=end_date,
    exchange="XNSE"
)

# Get intraday candles for Nifty 50
intraday_data = fetch_index_candles(
    symbol="NIFTY 50",
    start_date=start_date,
    end_date=end_date,
    granularity=5,  # 5-minute candles
    exchange="XNSE"
)

3. Apply Technical Indicators

import pandas as pd
from sysstra.sysstra_utils import apply_indicators

# Convert data to DataFrame
df = pd.DataFrame(intraday_data)

# Define indicators
indicators = {
    "RSI": {"length": 14},
    "EMA": {"length": 20},
    "MACD": {
        "source": "close",
        "fast_length": 12,
        "slow_length": 26,
        "signal_smoothing": 9
    },
    "BBAND": {
        "source": "close",
        "length": 20,
        "std_dev": 2,
        "basis_ma_type": "sma",
        "offset": 0
    }
}

# Apply indicators (modifies DataFrame in-place)
df = apply_indicators(df, indicators)

print(df[['timestamp', 'close', 'rsi', 'ema', 'macd', 'bband_u', 'bband_l']].tail())

4. Calculate Swing Structure

from sysstra.sysstra_utils import calculate_swing

# Add swing detection to identify market structure
df = calculate_swing(df, swing_setup=2)

# Check current swing
print(f"Current Swing: {df['swing'].iloc[-1]}")
print(f"Swing Change: {df['swing_change'].iloc[-1]}")

5. Place Live Orders

from sysstra.orders import place_lt_order

# Place a market order
status, response = place_lt_order(
    symbol="RELIANCE",
    exchange="NSE",
    quantity=1,
    lot_size=1,
    transaction_type="BUY",
    order_type="MARKET",
    asset_type="EQUITY",
    holding_type="INTRADAY",
    credential_id="your-credential-id"
)

if status == "success":
    print(f"Order placed successfully: {response}")
else:
    print(f"Order failed: {response}")

6. Calculate Brokerage & PnL

from sysstra.sysstra_utils import calculate_brokerage

# Calculate brokerage for Zerodha intraday equity trade
total_charges, net_pnl = calculate_brokerage(
    buy_price=2500.00,
    sell_price=2550.00,
    quantity=100,
    broker="zerodha",
    market_type="equity",
    holding_type="intraday",
    position_type="LONG",
    exchange="NSE"
)

print(f"Total Charges: ₹{total_charges}")
print(f"Net P&L: ₹{net_pnl}")

# Calculate for Interactive Brokers options trade
charges, pnl = calculate_brokerage(
    buy_price=5.50,
    sell_price=6.80,
    quantity=100,
    lot_size=100,
    broker="interactive_brokers",
    market_type="options",
    position_type="LONG",
    market="US"
)

print(f"Total Charges: ${charges}")
print(f"Net P&L: ${pnl}")

# Calculate for a MetaTrader 5 forex trade (always pass market_type)
charges, pnl = calculate_brokerage(
    buy_price=1.08432,
    sell_price=1.08542,
    quantity=100000,        # units, not lots
    broker="mt5",
    market_type="equity",
    market="FOREX",
    underlying="EURUSD"
)

print(f"Total Charges: ${charges}")
print(f"Net P&L: ${pnl}")

7. Fetch Options Data

from sysstra.data import fetch_option_candles

# Get option chain data
option_data = fetch_option_candles(
    underlying="NIFTY",
    start_date=start_date,
    end_date=end_date,
    option_type="CE",  # Call Option
    strike_price=18000,
    expiry="current",  # Current expiry
    granularity=5,
    exchange="XNSE"
)

8. Generate Backtest Reports

from sysstra.sysstra_utils import generate_mt_report
import pandas as pd

# Assuming you have a DataFrame with trade results
trades_df = pd.DataFrame([
    {'position_type': 'LONG', 'investment': 100000, 'net_pnl': 2500, 'date': '2024-01-15'},
    {'position_type': 'SHORT', 'investment': 100000, 'net_pnl': -800, 'date': '2024-01-16'},
    # ... more trades
])

# Generate comprehensive report
report = generate_mt_report(trades_df, pnl_column='net_pnl')

print(f"Total Trades: {report['total_trades']}")
print(f"Win Rate: {report['profit_trades_num%']:.2f}%")
print(f"Profit Factor: {report['profit_factor']:.2f}")
print(f"Max Drawdown: {report['maximal_drawdown']:.2f} ({report['maximal_drawdown%']:.2f}%)")
print(f"Expected Payoff: {report['expected_payoff']:.2f}")

📚 Documentation

Market Data Functions

Historical Data

# End-of-Day candles
fetch_eod_candles(symbol, start_date, end_date, exchange="XNSE")

# Index candles (intraday)
fetch_index_candles(symbol, start_date, end_date, granularity=1, exchange="XNSE")

# Futures candles
fetch_futures_candle(underlying, start_date, end_date, granularity=1, exchange="XNSE")

# Options candles by strike/expiry
fetch_option_candles(underlying, start_date, end_date, option_type, strike_price, 
                     expiry="current", granularity=1, exchange="XNSE")

# Options candles by symbol
fetch_option_candles_by_symbol(underlying, symbol, start_date, end_date, 
                                granularity=1, exchange="XNSE")

Granularity Values:

  • 1 = 1 minute
  • 5 = 5 minutes
  • 15 = 15 minutes
  • 60 = 1 hour
  • For daily data, use fetch_eod_candles()

Live Data

from sysstra.data import subscribe_live_data, get_live_quote

# Subscribe to live market data (implementation varies by broker)
subscribe_live_data(symbols=["NIFTY 50", "BANKNIFTY"], credential_id="your-id")

Technical Indicators

The apply_indicators() function supports 40+ indicators. Each indicator requires specific parameters in the indicators_dict:

Trend Indicators:

  • EMA, SMA, DEMA, TEMA, WMA, JMA - Moving averages
  • SUPERTREND - Supertrend indicator
  • PSAR - Parabolic SAR

Momentum Indicators:

  • RSI - Relative Strength Index
  • STOCH - Stochastic Oscillator
  • STOCHRSI - Stochastic RSI
  • MACD - Moving Average Convergence Divergence
  • MOM - Momentum
  • ROC - Rate of Change
  • AO - Awesome Oscillator

Volatility Indicators:

  • ATR - Average True Range
  • BBAND - Bollinger Bands
  • BBW - Bollinger Bandwidth
  • CHAIKIN - Chaikin Volatility

Volume Indicators:

  • VFI - Volume Flow Indicator
  • VWAP - Volume Weighted Average Price
  • EFI - Elder Force Index
  • AVGVOL - Average Volume

Oscillators:

  • ADX - Average Directional Index
  • DMI - Directional Movement Index
  • WILLR - Williams %R
  • RVGI - Relative Vigor Index
  • FISHER - Fisher Transform

Custom Indicators:

  • SWING - Swing structure detection
  • YONO - Zigzag indicator
  • ORB - Opening Range Breakout
  • CHOPZONE - Chop Zone indicator

Order Management

Live Trading

place_lt_order(
    symbol,
    exchange="NSE",
    quantity=1,
    transaction_type="BUY",  # or "SELL"
    order_type="MARKET",      # or "LIMIT", "STOPLOSS"
    lot_size=1,
    credential_id=None,
    trigger_price=None,       # for STOPLOSS orders
    order_price=None,         # for LIMIT orders
    validity="DAY",           # or "IOC", "GTD"
    asset_type="EQUITY",      # or "OPTIONS", "FUTURES"
    holding_type="DELIVERY",  # or "INTRADAY"
    option_type=None,         # "CE" or "PE" for options
    strike_price=None,
    underlying=None,
    expiry_date=None,
    trade_action=None,        # MT5 hedging accounts only: "ENTRY" or "EXIT"
    close_orders=None         # MT5 hedging accounts only, on an EXIT: [{"order_id": <entry's MT5 ticket>, "quantity": <units>}]
)

Supported Brokers

  • India: Zerodha, Upstox, Angel One, Fyers, 5paisa
  • US: Interactive Brokers, Schwab, TD Ameritrade
  • Crypto: Binance, CoinDCX
  • Forex / CFD: MetaTrader 5 (mt5)

Utility Functions

# Change candle granularity
change_granularity(data_df, granularity=5)

# Round to tick size (NSE: 0.05)
round_to_tick_multiple(price)

# Calculate position liquidation price
calculate_liquidation_price(entry_price, leverage=10, position_type="LONG", mmr=0.005)

# Calculate ROI percentage
calculate_roi_percent(entry_price, current_price)

# Get Fibonacci pivot points
get_fibonacci_pivot_points(high, low, close, level1=0.382, level2=0.618, level3=1.0)

# Convert candle patterns
convert_candle_pattern(dataframe, pattern='heikin_ashi')  # or 'ask'

# Calculate entry quantity based on investment
calculate_entry_quantity(investment=100000, unit_price=2500)

# Generate exit quantities for multiple targets/stop losses
calculate_exit_quantity(total_quantity=100, 
                       target_split={'target1': 0.5, 'target2': 0.5},
                       sl_split={'sl1': 1.0})

🏗️ Architecture

Sysstra follows a modular architecture with clear separation of concerns:

sysstra/
├── config.py              # API configuration
├── data/
│   ├── historical.py      # Historical data fetching
│   └── live.py           # Live data streaming
├── orders/
│   ├── live.py           # Live order execution
│   ├── virtual.py        # Paper trading
│   ├── backtest.py       # Backtesting engine
│   └── orders_utils.py   # Order utilities
├── custom_indicators.py   # Custom technical indicators
└── sysstra_utils.py      # Core utility functions

The library acts as a client to backend services:

  • Data API: Provides historical and real-time market data
  • Orders API: Handles order routing, execution, and position tracking

🎓 Examples

Example 1: Simple RSI Strategy

import sysstra
from sysstra.data import fetch_index_candles
from sysstra.sysstra_utils import apply_indicators
import pandas as pd
import datetime

# Configure
sysstra.set_api_key("your-api-key")

# Fetch data
df = pd.DataFrame(fetch_index_candles(
    symbol="NIFTY 50",
    start_date=datetime.date(2024, 1, 1),
    end_date=datetime.date(2024, 12, 31),
    granularity=15
))

# Add indicators
indicators = {
    "RSI": {"length": 14},
    "EMA": {"length": 50}
}
df = apply_indicators(df, indicators)

# Generate signals
df['signal'] = 'NEUTRAL'
df.loc[(df['rsi'] < 30) & (df['close'] > df['ema']), 'signal'] = 'BUY'
df.loc[(df['rsi'] > 70) & (df['close'] < df['ema']), 'signal'] = 'SELL'

# Display signals
signals = df[df['signal'] != 'NEUTRAL'][['timestamp', 'close', 'rsi', 'signal']]
print(signals)

Example 2: Options Strategy with Swing Detection

from sysstra.data import fetch_option_candles
from sysstra.sysstra_utils import calculate_swing, apply_indicators
import pandas as pd

# Fetch options data
option_data = fetch_option_candles(
    underlying="BANKNIFTY",
    start_date=datetime.date(2024, 12, 1),
    end_date=datetime.date(2024, 12, 31),
    option_type="CE",
    strike_price=45000,
    expiry="current",
    granularity=5
)

df = pd.DataFrame(option_data)

# Add swing structure
df = calculate_swing(df, swing_setup=2)

# Add momentum indicators
indicators = {
    "RSI": {"length": 14},
    "MACD": {"source": "close", "fast_length": 12, "slow_length": 26, "signal_smoothing": 9}
}
df = apply_indicators(df, indicators)

# Trade on swing changes with RSI confirmation
df['entry'] = (df['swing_change'] == True) & (df['swing'] == 'UP') & (df['rsi'] < 50)
df['exit'] = (df['swing_change'] == True) & (df['swing'] == 'DOWN')

print(df[df['entry'] | df['exit']][['timestamp', 'close', 'swing', 'rsi', 'entry', 'exit']])

Example 3: Multi-Timeframe Analysis

from sysstra.sysstra_utils import change_granularity

# Get 1-minute data
df_1min = pd.DataFrame(fetch_index_candles("NIFTY 50", start_date, end_date, granularity=1))

# Convert to 5-minute
df_5min = change_granularity(df_1min, granularity=5)

# Convert to 15-minute
df_15min = change_granularity(df_1min, granularity=15)

# Apply different indicators to each timeframe
df_5min = apply_indicators(df_5min, {"EMA": {"length": 20}})
df_15min = apply_indicators(df_15min, {"EMA": {"length": 50}})

# Align timeframes for multi-timeframe analysis
# (implementation depends on your strategy logic)

Example 4: Backtesting with Brokerage

from sysstra.sysstra_utils import calculate_brokerage, generate_mt_report

# Simulate trades
trades = []
positions = [
    {'buy': 18000, 'sell': 18500, 'qty': 50, 'type': 'LONG'},
    {'buy': 18600, 'sell': 18400, 'qty': 50, 'type': 'SHORT'},
    # ... more trades
]

for pos in positions:
    charges, pnl = calculate_brokerage(
        buy_price=pos['buy'],
        sell_price=pos['sell'],
        quantity=pos['qty'],
        broker="zerodha",
        market_type="equity",
        holding_type="intraday",
        position_type=pos['type']
    )
    
    trades.append({
        'position_type': pos['type'],
        'investment': 100000,
        'net_pnl': pnl,
        'charges': charges,
        'date': datetime.datetime.now()
    })

# Generate performance report
df_trades = pd.DataFrame(trades)
report = generate_mt_report(df_trades, pnl_column='net_pnl')

print(f"Total P&L: {df_trades['net_pnl'].sum():.2f}")
print(f"Win Rate: {report['profit_trades_num%']:.2f}%")
print(f"Max Drawdown: {report['maximal_drawdown%']:.2f}%")

🧪 Testing

# Run tests (if available)
python -m pytest tests/

# Run example scripts
python examples/orders_test.py

🤝 Contributing

Contributions are welcome! Please follow these steps:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Development Setup

# Clone the repo
git clone https://github.com/sysstra/sysstra.git
cd sysstra

# Create virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install in editable mode with dev dependencies
pip install -e .
pip install -r requirements.txt

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.



📧 Contact

Author: Anurag Singh Kushwah
Email: anurag@sysstra.com
Website: https://sysstra.com


⭐ Support

If you find this library helpful, please consider giving it a star on GitHub!

For questions, issues, or feature requests, please open an issue on the GitHub repository.


📝 Changelog

v0.1.4.6.5 (Latest)

  • Fixed Python 3.10 syntax error in HMA indicator (f-string nested quote)
  • Added missing dependencies to package: pymongo, numba, tqdm
  • Vendored pandas_ta library directly into the package

v0.1.4.4.1

  • Added Interactive Brokers brokerage calculation
  • Enhanced options data fetching
  • Improved swing calculation algorithm
  • Bug fixes and performance improvements

v0.1.4

  • Multi-broker support (Zerodha, IBKR, Schwab, Binance, CoinDCX)
  • 40+ technical indicators
  • Live trading integration
  • Comprehensive backtesting engine

⚠️ Disclaimer

This software is for educational and research purposes only. Trading in financial markets involves substantial risk of loss. Past performance is not indicative of future results. Always conduct your own research and consult with financial advisors before making trading decisions.

USE AT YOUR OWN RISK. The authors and contributors are not responsible for any financial losses incurred through the use of this software.

Metadata

Release files for sysstra 0.1.4.7.12

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for sysstra 0.1.4.7.12
File Size Uploaded Provenance Actions
sysstra-0.1.4.7.12.tar.gz 205.5 kB Without provenance Details for sysstra-0.1.4.7.12.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for sysstra 0.1.4.7.12
File Interpreter ABI Platform Actions
sysstra-0.1.4.7.12-py3-none-any.whl Python 3 none any Details for sysstra-0.1.4.7.12-py3-none-any.whl

Total release size: 505.2 kB

Release files / sysstra-0.1.4.7.12.tar.gz

Download URL sysstra-0.1.4.7.12.tar.gz
Size 205.5 kB
Tags Source
SHA-256 checksum
How to use checksums
46353238add7d0f76fa23b2a2a929e33d28407adadaa12634b752869e1333b97
BLAKE2b-256 checksum
How to use checksums
7f9ad5147c689a51f5845dcb218847ac6bc6d921a86ef7c8b39e75bacf7f4579
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.10

Release files / sysstra-0.1.4.7.12-py3-none-any.whl

Download URL sysstra-0.1.4.7.12-py3-none-any.whl
Size 299.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
3b7d3029c761eaae96821ac431743a9daebabb9b2eb0c0e3b68d993ebd88f9ef
BLAKE2b-256 checksum
How to use checksums
df0bc22fc2b3190b610b8dfc0719c48fc1e9ad58f1c79a05a0ea87ce3d10edf6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.10

Security for sysstra 0.1.4.7.12

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.4.7.12 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page