Skip to main content

Official Python Library for Sysstra Algo Trading

Project description

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)
  • 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, pandas_ta, redis

🎯 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}")

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
)

Supported Brokers

  • India: Zerodha, Upstox, Angel One, Fyers, 5paisa
  • US: Interactive Brokers, Schwab, TD Ameritrade
  • Crypto: Binance, CoinDCX

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.


🔗 Links


📧 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.4.1 (Latest)

  • 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.

Project details


Release history Release notifications | RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

sysstra-0.1.4.5.0.tar.gz (49.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

sysstra-0.1.4.5.0-py3-none-any.whl (96.6 kB view details)

Uploaded Python 3

File details

Details for the file sysstra-0.1.4.5.0.tar.gz.

File metadata

  • Download URL: sysstra-0.1.4.5.0.tar.gz
  • Upload date:
  • Size: 49.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.10

File hashes

Hashes for sysstra-0.1.4.5.0.tar.gz
Algorithm Hash digest
SHA256 46e30ea832ffd8290653038ff0ebfc02c2827b0024bda9b225897dc30e1e53a5
MD5 86b056746e6d3a7b4796795701ce08e6
BLAKE2b-256 25de8dff8050528ec93750f1f38e8a2d1a05ccd34aa7092e22622e4c8c36c123

See more details on using hashes here.

File details

Details for the file sysstra-0.1.4.5.0-py3-none-any.whl.

File metadata

  • Download URL: sysstra-0.1.4.5.0-py3-none-any.whl
  • Upload date:
  • Size: 96.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.10

File hashes

Hashes for sysstra-0.1.4.5.0-py3-none-any.whl
Algorithm Hash digest
SHA256 df2367cdf56c49c3fafed379827fbe5fdaf2b2e0c2e72e7b31e23da360a65a21
MD5 47ff19a8952e9f5130c649753415e342
BLAKE2b-256 48e782cd5c34e5d30d6fa7d6df06117478034493e4f4459e90518bb452f6175a

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page