Skip to content

Order Functions API Reference ​

Learn how to place buy and sell orders in your trading strategies.

Order Format ​

All orders are returned as dictionaries with the following structure:

python
{
    "symbol": "AAPL",        # Required: Stock symbol
    "action": "buy",         # Required: "buy" or "sell"  
    "quantity": 100,         # Required: Number of shares or "all"
    "order_type": "market"   # Optional: Defaults to "market"
}

Basic Orders ​

Market Buy Order ​

python
def strategy(data_contexts, portfolio, state):
    return {
        "symbol": "AAPL",
        "action": "buy", 
        "quantity": 100
    }

Market Sell Order ​

python
def strategy(data_contexts, portfolio, state):
    return {
        "symbol": "AAPL",
        "action": "sell",
        "quantity": 50  # Sell 50 shares
    }

Sell All Shares ​

python
def strategy(data_contexts, portfolio, state):
    return {
        "symbol": "AAPL", 
        "action": "sell",
        "quantity": "all"  # Sell entire position
    }

Multiple Orders ​

Return a list to place multiple orders in the same bar:

python
def strategy(data_contexts, portfolio, state):
    orders = []
    
    # Buy AAPL
    orders.append({
        "symbol": "AAPL",
        "action": "buy",
        "quantity": 100
    })
    
    # Sell GOOGL
    orders.append({
        "symbol": "GOOGL", 
        "action": "sell",
        "quantity": "all"
    })
    
    return orders

Order Execution ​

Timing ​

  • Orders execute at the next bar's open price
  • This prevents look-ahead bias (realistic trading simulation)
  • Current bar data → make decision → execute next bar

Example Timeline ​

python
# Minute 10:30 AM - Strategy sees:
# - AAPL current price: $150.00
# - RSI: 25 (oversold)
# - Decision: BUY 100 shares

# Minute 10:31 AM - Order executes:
# - AAPL opens at: $150.25  
# - Buy 100 shares @ $150.25
# - Total cost: $15,025

Position Sizing Examples ​

Fixed Dollar Amount ​

python
def strategy(data_contexts, portfolio, state):
    data = data_contexts['AAPL']
    
    if buy_signal:
        # Buy $10,000 worth
        target_value = 10000
        shares = int(target_value / data.close)
        
        return {'symbol': 'AAPL', 'action': 'buy', 'quantity': shares}

Percentage of Portfolio ​

python
def strategy(data_contexts, portfolio, state):
    if buy_signal:
        # Risk 20% of portfolio
        risk_amount = portfolio.equity * 0.20
        shares = int(risk_amount / data.close)
        
        return {'symbol': 'AAPL', 'action': 'buy', 'quantity': shares}

Risk-Based Sizing ​

python
def strategy(data_contexts, portfolio, state):
    data = data_contexts['AAPL']
    
    if buy_signal:
        # Risk 2% of portfolio per trade
        account_risk = portfolio.equity * 0.02
        
        # Stop loss at 5% below entry
        entry_price = data.close
        stop_price = entry_price * 0.95
        risk_per_share = entry_price - stop_price
        
        # Calculate position size
        shares = int(account_risk / risk_per_share)
        
        return {'symbol': 'AAPL', 'action': 'buy', 'quantity': shares}

Order Validation ​

The system validates orders before execution:

Valid Orders ✅ ​

  • Symbol exists in available data
  • Sufficient cash for buy orders
  • Sufficient shares for sell orders
  • Positive quantity values

Invalid Orders ❌ ​

  • Unknown symbols → Ignored
  • Insufficient funds → Partial fill or skip
  • Negative quantities → Ignored
  • Invalid actions → Ignored

Best Practices ​

1. Check Available Cash ​

python
if portfolio.cash >= (shares * price * 1.01):  # 1% buffer
    return buy_order

2. Validate Positions ​

python
current_pos = portfolio.position('AAPL')
if current_pos >= shares_to_sell:
    return sell_order

3. Use Position Sizing ​

python
# Don't risk more than you can afford
max_position_value = portfolio.equity * 0.25
shares = min(desired_shares, int(max_position_value / price))

4. Handle Edge Cases ​

python
def strategy(data_contexts, portfolio, state):
    # Always return None, single order dict, or list of orders
    if no_signals:
        return None  # No action
    elif single_order:
        return order_dict
    else:
        return [order1, order2]  # Multiple orders

See also: DataContext API | Portfolio API | Strategy Examples

Test your trading strategies risk-free with professional backtesting.