SimuTrade
Sign In
Code Examples

Code Examples

Ready-to-use code snippets in Python, JavaScript, and cURL for all major operations.

Get a Market Quote

Fetch the current price and market data for a symbol.

get_a_market_quote.py
import simutrade

client = simutrade.Client(api_key="ts_live_xxx")

# Get quote for a US stock
quote = client.market.get_quote("AAPL")
print(f"Symbol: {quote.symbol}")
print(f"Price: ${quote.price}")
print(f"Change: {quote.change} ({quote.change_percent}%)")
print(f"Volume: {quote.volume:,}")

# Get quote for HK stock
hk_quote = client.market.get_quote("0700.HK")
print(f"Tencent: HK${hk_quote.price}")

# Get quote for cryptocurrency
btc = client.market.get_quote("BTC-USD")
print(f"Bitcoin: ${btc.price:,.2f}")

Place Orders

Place market, limit, and stop orders across all supported markets.

place_orders.py
import simutrade

client = simutrade.Client(api_key="ts_live_xxx")

# Market buy order
order = client.orders.create(
    symbol="AAPL",
    side="buy",
    type="market",
    quantity=10
)
print(f"Order ID: {order.id}, Status: {order.status}")

# Limit sell order
limit_order = client.orders.create(
    symbol="TSLA",
    side="sell",
    type="limit",
    quantity=5,
    price=260.00
)
print(f"Limit order placed at ${limit_order.price}")

# Stop loss order
stop_order = client.orders.create(
    symbol="NVDA",
    side="sell",
    type="stop",
    quantity=10,
    price=450.00
)

# Buy cryptocurrency
crypto_order = client.orders.create(
    symbol="BTC-USD",
    side="buy",
    type="market",
    quantity=0.1
)
print(f"Bought 0.1 BTC: {crypto_order.id}")

Portfolio Management

View your portfolio, positions, and P&L information.

portfolio_management.py
import simutrade

client = simutrade.Client(api_key="ts_live_xxx")

# Get portfolio summary
portfolio = client.portfolio.get()
print(f"Total Value: ${portfolio.summary.total_value:,.2f}")
print(f"Cash Balance: ${portfolio.summary.cash_balance:,.2f}")
print(f"Today's P&L: ${portfolio.summary.today_pnl:,.2f}")

# List all positions
print("\nPositions:")
for pos in portfolio.positions:
    pnl_emoji = "+" if pos.unrealized_pnl >= 0 else ""
    print(f"  {pos.symbol}: {pos.quantity} shares")
    print(f"    Avg Cost: ${pos.avg_cost:.2f}")
    print(f"    Current: ${pos.current_price:.2f}")
    print(f"    P&L: {pnl_emoji}${pos.unrealized_pnl:.2f} ({pnl_emoji}{pos.unrealized_pnl_percent:.2f}%)")

Order Management

List, filter, and cancel orders.

order_management.py
import simutrade

client = simutrade.Client(api_key="ts_live_xxx")

# List all orders
orders = client.orders.list(limit=10)
for order in orders:
    print(f"{order.id}: {order.side} {order.quantity} {order.symbol} @ ${order.price} [{order.status}]")

# List only pending orders
pending = client.orders.list(status="pending")
print(f"\n{len(pending)} pending orders")

# Filter by market
us_orders = client.orders.list(market="us")
crypto_orders = client.orders.list(market="crypto")

# Cancel a pending order
cancelled = client.orders.cancel("ord-abc123")
print(f"Order {cancelled.id} cancelled at {cancelled.cancelled_at}")

Historical Data

Fetch historical OHLCV data for analysis and charting.

historical_data.py
import simutrade

client = simutrade.Client(api_key="ts_live_xxx")

# Get daily candles
history = client.market.get_history(
    symbol="AAPL",
    interval="1d",
    limit=30
)

for candle in history[-5:]:  # Last 5 days
    print(f"{candle.time}: O={candle.open} H={candle.high} L={candle.low} C={candle.close} V={candle.volume:,}")

# Get 5-minute candles for intraday analysis
intraday = client.market.get_history(
    symbol="BTC-USD",
    interval="5m",
    limit=100
)
print(f"\nBTC 5m candles: {len(intraday)} data points")

Full Example: Simple Trading Strategy

A complete example showing a simple mean-reversion trading strategy:

mean_reversion_strategy.py
import simutrade
import time

client = simutrade.Client(api_key="ts_live_xxx")

# Simple mean-reversion strategy for demonstration
SYMBOL = "AAPL"
BUY_THRESHOLD = -2.0    # Buy when stock is down 2% from previous close
SELL_THRESHOLD = 2.0     # Sell when stock is up 2% from previous close
TRADE_QUANTITY = 10

def run_strategy():
    """Run one iteration of the strategy."""
    # Get current quote
    quote = client.market.get_quote(SYMBOL)
    change_pct = quote.change_percent
    
    print(f"[{SYMBOL}] Price: ${quote.price:.2f} | Change: {change_pct:+.2f}%")
    
    # Get current position
    portfolio = client.portfolio.get()
    position = next(
        (p for p in portfolio.positions if p.symbol == SYMBOL),
        None
    )
    
    # Buy signal: stock is down significantly
    if change_pct <= BUY_THRESHOLD and position is None:
        print(f"  BUY SIGNAL: {SYMBOL} down {change_pct:.2f}%")
        order = client.orders.create(
            symbol=SYMBOL,
            side="buy",
            type="market",
            quantity=TRADE_QUANTITY
        )
        print(f"  Placed buy order: {order.id}")
    
    # Sell signal: stock is up significantly and we have a position
    elif change_pct >= SELL_THRESHOLD and position is not None:
        print(f"  SELL SIGNAL: {SYMBOL} up {change_pct:.2f}%")
        order = client.orders.create(
            symbol=SYMBOL,
            side="sell",
            type="market",
            quantity=position.quantity
        )
        print(f"  Placed sell order: {order.id}")
    
    else:
        print(f"  No signal. Holding.")

# Run strategy in a loop (for demonstration)
print("Starting mean-reversion strategy...")
print(f"Symbol: {SYMBOL}")
print(f"Buy threshold: {BUY_THRESHOLD}%")
print(f"Sell threshold: {SELL_THRESHOLD}%")
print("-" * 40)

for i in range(10):
    run_strategy()
    time.sleep(5)  # Check every 5 seconds

print("\nStrategy complete!")
portfolio = client.portfolio.get()
print(f"Final portfolio value: ${portfolio.summary.total_value:,.2f}")
print(f"Total P&L: ${portfolio.summary.total_pnl:,.2f}")