PrimeTrader Class

Main interface for interacting with the PRIME trading system.

Initialization

from prime import PrimeTrader

trader = PrimeTrader(
    mode='paper',           # 'paper' | 'live' | 'backtest'
    api_key='YOUR_KEY',     # Optional for paper mode
    api_secret='YOUR_SECRET',
    risk_level='moderate',  # 'conservative' | 'moderate' | 'aggressive'
    strategies=['momentum', 'mean_reversion']
)

Methods

start() async

Starts the trading system and begins monitoring markets.

Returns bool - Success status
await trader.start()
# Trading system is now active
stop() async

Stops the trading system and closes all positions if specified.

Parameter Type Description
close_positions bool Whether to close all open positions (default: False)
get_positions() method

Returns all current open positions.

Returns List[Position] - List of position objects
positions = trader.get_positions()
for pos in positions:
    print(f"{pos.symbol}: {pos.quantity} @ ${pos.entry_price}")
set_risk_params() method

Configure risk management parameters.

Parameter Type Description
max_position_size float Maximum position size as fraction of portfolio
stop_loss float Stop loss percentage
take_profit float Take profit percentage
max_drawdown float Maximum allowed drawdown

Strategy Class

Base class for implementing custom trading strategies.

Creating Custom Strategies

from prime import Strategy

class MyStrategy(Strategy):
    def __init__(self):
        super().__init__(
            name="My Custom Strategy",
            timeframe="1h",
            indicators=["RSI", "MACD"]
        )
    
    def generate_signal(self, data):
        # Your signal logic here
        if data.rsi < 30:
            return Signal("BUY", confidence=0.8)
        elif data.rsi > 70:
            return Signal("SELL", confidence=0.8)
        return None

Methods

generate_signal() abstract

Must be implemented in custom strategies to generate trading signals.

data MarketData Current market data including price and indicators
calculate_position_size() method

Calculates optimal position size based on Kelly criterion or custom logic.

Signal Class

Represents a trading signal generated by strategies.

Signal Properties

signal = Signal(
    action="BUY",        # "BUY" | "SELL" | "HOLD"
    symbol="AAPL",
    confidence=0.85,     # 0.0 to 1.0
    quantity=100,
    strategy="momentum",
    metadata={
        "indicators": ["RSI", "MACD"],
        "timeframe": "1h"
    }
)

Portfolio Class

Manages portfolio state, positions, and performance metrics.

Methods

get_equity() property

Returns current portfolio equity.

current_equity = portfolio.get_equity()
print(f"Portfolio Value: ${current_equity:,.2f}")
get_performance() method

Returns comprehensive performance metrics.

Returns PerformanceMetrics - Object containing Sharpe, returns, drawdown, etc.

RiskManager Class

Handles all risk management operations and position sizing.

Configuration

risk_manager = RiskManager(
    max_position_size=0.05,      # 5% max per position
    max_portfolio_risk=0.15,      # 15% max portfolio risk
    correlation_limit=0.7,        # Max correlation between positions
    use_circuit_breaker=True,
    circuit_breaker_levels=[-0.05, -0.10, -0.15]
)

Backtester Class

Comprehensive backtesting engine with walk-forward analysis.

Running Backtests

from prime import Backtester

backtester = Backtester(
    strategies=[my_strategy],
    start_date="2020-01-01",
    end_date="2024-01-01",
    initial_capital=100000
)

results = backtester.run()
print(f"Total Return: {results.total_return}%")
print(f"Sharpe Ratio: {results.sharpe_ratio}")
print(f"Max Drawdown: {results.max_drawdown}%")

WebSocket Streams

Real-time data streaming for live market updates.

Subscribing to Streams

from prime import WebSocketClient

ws = WebSocketClient()

@ws.on('trade')
def on_trade(data):
    print(f"Trade: {data.symbol} @ ${data.price}")

@ws.on('signal')
def on_signal(signal):
    print(f"New Signal: {signal.action} {signal.symbol}")

ws.subscribe(['AAPL', 'TSLA', 'SPY'])
ws.start()

Error Handling

PRIME uses custom exceptions for different error scenarios:

from prime.exceptions import (
    InsufficientCapitalError,
    StrategyError,
    DataError,
    RiskLimitError
)

try:
    trader.execute_trade(signal)
except InsufficientCapitalError as e:
    print(f"Not enough capital: {e}")
except RiskLimitError as e:
    print(f"Risk limit exceeded: {e}")