Quick Start
HiveQ Flow Quick Start Guide
Get started with HiveQ Flow in minutes.
Table of Contents
Installation
Requirements
- Python 3.10 or higher
- pip package manager
Install HiveQ Flow
pip install hiveq-flowVerify Installation
import hiveq.flow as hf
print(hf.__version__)5-Minute Tutorial
Step 1: Set Up Environment Variables
HiveQ Flow auto-initializes from environment variables. Create a .env file or export these:
export HIVEQ_API_KEY="your_api_key"
export HIVEQ_USER_NAME="YourName"
export HIVEQ_USER_ID="your_user_id"
export HIVEQ_ORG_ID="your_org_id"Step 2: Import HiveQ Flow
import hiveq.flow as hf
from hiveq.flow import StrategyConfigStep 3: Define a Simple Strategy
from hiveq.flow.config import EventType, AssetType
class BuyAndHoldStrategy:
"""Simple buy and hold strategy."""
def __init__(self):
self.bought = False
def on_hiveq_event(self, ctx: hf.Context, event):
"""Main event handler."""
if event.type == EventType.START:
# Subscribe to 1-minute bars
ctx.subscribe_bars(
symbols=ctx.strategy_config.symbols,
asset_type=AssetType.EQUITY,
interval='1m'
)
print("Strategy started!")
elif event.type == EventType.BAR:
# Buy on first bar
bar = event.data()
if not self.bought and ctx.is_flat(bar.symbol):
ctx.buy_order(bar.symbol, quantity=100)
print(f"Bought 100 shares at {bar.close}")
self.bought = True
elif event.type == EventType.ORDER_FILLED:
order = event.data()
print(f"Order filled: {order.filled_qty} @ {order.avg_px}")Step 4: Configure and Run
# Configure strategy
strategy_config = StrategyConfig(
name='BuyAndHold',
type='BuyAndHoldStrategy'
)
# Run backtest with HiveQ historical data
report = hf.run_backtest(
strategy_configs=[strategy_config],
symbols=['AAPL'],
start_date='2025-08-01',
end_date='2025-08-02',
data_configs=[{
'type': 'hiveq_historical',
'dataset': 'HIVEQ_US_EQ',
'schema': ['bars_1m'],
}]
)Step 4: View Results
# Print return statistics
print(report.return_stats.to_string())
# Print fills
print(report.fills.to_string())
# Get event logs
events = hf.event_logs()
print(events.to_string())That's it! You've just run your first HiveQ Flow backtest.
Your First Strategy
Let's build a simple moving average crossover strategy.
Complete Code
import numpy as np
import hiveq.flow as hf
from hiveq.flow import StrategyConfig
from hiveq.flow.config import EventType, AssetType
from collections import deque
class SMACrossoverStrategy:
"""
Simple Moving Average Crossover Strategy.
- Buy when fast MA crosses above slow MA
- Sell when fast MA crosses below slow MA
"""
def __init__(self):
# Strategy parameters
self.fast_window = 10
self.slow_window = 30
self.trade_size = 100
# Price history
self.fast_prices = deque(maxlen=self.fast_window)
self.slow_prices = deque(maxlen=self.slow_window)
def on_hiveq_event(self, ctx: hf.Context, event):
"""Main event handler."""
if event.type == EventType.START:
# Initialize: subscribe to data
symbols = ctx.strategy_config.symbols
ctx.subscribe_bars(symbols=symbols, asset_type=AssetType.EQUITY, interval='1m')
print(f"Strategy started for {symbols}")
elif event.type == EventType.BAR:
# Process each bar
bar = event.data()
symbol = bar.symbol
close = bar.close
# Update price history
self.fast_prices.append(close)
self.slow_prices.append(close)
# Wait for enough data
if len(self.slow_prices) < self.slow_window:
return
# Calculate moving averages
fast_ma = np.mean(self.fast_prices)
slow_ma = np.mean(self.slow_prices)
# Get current position
position = ctx.net_position(symbol)
# Trading logic
if fast_ma > slow_ma and position <= 0:
# Golden Cross - Buy signal
print(f"Golden Cross! Fast MA: {fast_ma:.2f}, Slow MA: {slow_ma:.2f}")
ctx.buy_order(symbol=symbol, quantity=self.trade_size)
elif fast_ma < slow_ma and position > 0:
# Death Cross - Sell signal
print(f"Death Cross! Fast MA: {fast_ma:.2f}, Slow MA: {slow_ma:.2f}")
ctx.sell_order(symbol=symbol, quantity=int(position))
elif event.type == EventType.ORDER_FILLED:
# Track order fills
order = event.data()
print(f"Order filled: {order.side} {order.filled_qty} @ {order.avg_px:.2f}")
elif event.type == EventType.STOP:
# Cleanup
print("Strategy stopped")
print(f"Final P&L: ${ctx.portfolio().total_pnl():.2f}")
# Run the strategy
if __name__ == '__main__':
# Configure strategy
strategy_config = StrategyConfig(
name='SMA_10_30',
type='SMACrossoverStrategy',
params={
'fast_window': 10,
'slow_window': 30,
'trade_size': 100
}
)
# Run backtest
report = hf.run_backtest(
strategy_configs=[strategy_config],
symbols=['AAPL'],
start_date='2025-08-01',
end_date='2025-08-30',
data_configs=[{
'type': 'hiveq_historical',
'dataset': 'HIVEQ_US_EQ',
'schema': ['bars_1m'],
}]
)
# Print results
print("\n" + "="*60)
print("BACKTEST RESULTS")
print("="*60)
print(report.return_stats.to_string())
print("\nPositions:")
print(report.positions.to_string())Save as sma_strategy.py and run:
python sma_strategy.pyRunning a Backtest
Basic Backtest
Minimum required parameters:
import hiveq.flow as hf
# Run
report = hf.run_backtest(
strategy_configs=[strategy_config],
symbols=['AAPL'],
start_date='2025-08-01',
end_date='2025-08-30',
data_configs=[{
'type': 'hiveq_historical',
'dataset': 'HIVEQ_US_EQ',
'schema': ['bars_1m'],
}]
)With CSV Data
Use local CSV files:
# Run with CSV data
report = hf.run_backtest(
strategy_configs=[strategy_config],
symbols=['AAPL'],
start_date='2025-08-01',
end_date='2025-08-02',
data_configs=[{
'type': 'csv',
'data_type': 'bars_1m',
'id': '1_MIN_BAR',
'path': 'bars/AAPL_bars.csv'
}]
)CSV Format:
timestamp,symbol,open,high,low,close,volume
2025-08-01 09:30:00,AAPL,180.50,181.00,180.25,180.75,1000000
2025-08-01 09:31:00,AAPL,180.75,181.25,180.50,181.00,1100000With Custom Configuration
Full backtest configuration:
from hiveq.flow import BacktestConfig
# Create detailed config
backtest_config = BacktestConfig(
initial_capital=500000.0, # $500k starting capital
commission=0.002, # 0.2% commission
slippage=0.0005, # 0.05% slippage
risk_free_rate=0.045, # 4.5% risk-free rate
start_date='2025-01-01',
end_date='2025-12-31'
)
# Run with config
report = hf.run_backtest(
strategy_configs=[strategy_config],
symbols=['AAPL', 'GOOGL', 'MSFT'],
data_configs=[{
'type': 'hiveq_historical',
'dataset': 'HIVEQ_US_EQ',
'schema': ['bars_1m'],
}],
backtest_config=backtest_config
)Multiple Strategies
Run multiple strategies together:
strategy_configs = [
StrategyConfig(
name='SMA_Fast',
type='SMACrossoverStrategy',
params={'fast_window': 5, 'slow_window': 20}
),
StrategyConfig(
name='SMA_Slow',
type='SMACrossoverStrategy',
params={'fast_window': 20, 'slow_window': 50}
)
]
report = hf.run_backtest(
strategy_configs=strategy_configs, # Multiple strategies
symbols=['AAPL'],
start_date='2025-08-01',
end_date='2025-08-30',
data_configs=[{
'type': 'hiveq_historical',
'dataset': 'HIVEQ_US_EQ',
'schema': ['bars_1m'],
}]
)Execution Modes (strategy_type and fetch_mode)
Control how your backtest executes with strategy_type and fetch_mode parameters:
| strategy_type | fetch_mode | Data Fetch | Execution | State Reset |
|---|---|---|---|---|
'intraday' (default) | 'daily' (default) | Day-by-day | Day-by-day | Each day |
'intraday' | 'prefetch' | Single fetch | Single run | Never |
'overnight' | (ignored) | Single fetch | Single run | Never |
# Default: Intraday strategy with daily data fetch
# State resets each trading day, memory efficient for long backtests
report = hf.run_backtest(
strategy_configs=[strategy_config],
symbols=['AAPL'],
start_date='2025-01-01',
end_date='2025-06-30',
data_configs=[{
'type': 'hiveq_historical',
'dataset': 'HIVEQ_US_EQ',
'schema': ['bars_1m'],
}]
# strategy_type='intraday' (default)
# fetch_mode='daily' (default)
)
# Prefetch mode: Single data fetch, faster for shorter backtests
report = hf.run_backtest(
strategy_configs=[strategy_config],
symbols=['AAPL'],
start_date='2025-08-01',
end_date='2025-08-30',
data_configs=[{
'type': 'hiveq_historical',
'dataset': 'HIVEQ_US_EQ',
'schema': ['bars_1m'],
}],
strategy_type='intraday',
fetch_mode='prefetch' # All data fetched once, single continuous run
)
# Overnight strategy: For swing trading / position trading
# Positions can be held overnight, continuous state
report = hf.run_backtest(
strategy_configs=[strategy_config],
symbols=['AAPL'],
start_date='2025-08-01',
end_date='2025-08-30',
data_configs=[{
'type': 'hiveq_historical',
'dataset': 'HIVEQ_US_EQ',
'schema': ['bars_1m'],
}],
strategy_type='overnight'
)Viewing Results
Return Statistics
# Get return stats DataFrame
return_stats = results.return_stats
print(return_stats.to_string())Output:
Value
Total Return 12.5%
Annualized Return 15.2%
Sharpe Ratio 1.85
Max Drawdown -8.3%
Win Rate 62.5%
Profit Factor 2.15
Total Trades 48Positions
# Get all positions
positions = results.positions
print(positions.to_string())Output:
Symbol Entry Time Exit Time Qty Entry Px Exit Px P&L Return
AAPL 2025-08-01 09:30 2025-08-01 14:30 100 180.50 182.75 225.00 1.25%
AAPL 2025-08-02 10:15 2025-08-02 15:45 100 181.25 179.80 -145.00 -0.80%Fills
# Get all order fills
fills = results.fills
print(fills.to_string())Output:
Time Symbol Side Qty Price Commission
2025-08-01 09:30:15 AAPL BUY 100 180.52 18.05
2025-08-01 14:30:22 AAPL SELL 100 182.73 18.27Event Logs
# Get custom event logs
events = hf.event_logs()
# Filter by strategy
strategy_events = events[events['strategy_id'] == 'SMA_10_30']
# Filter by event type
filled_orders = events[events['event_type'] == 'ORDER_FILLED']
print(events.to_string())Run Information
# Get run metadata
run_info = results.run_info
print(run_info.to_string())Output:
Parameter Value
Start Date 2025-08-01
End Date 2025-08-30
Symbols ['AAPL']
Initial Capital 1000000.0
Commission 0.001
Total Days 20Create Tearsheet
Generate visual tearsheet (for Jupyter/Marimo):
# In Jupyter notebook
results.create_tearsheet()
# In Marimo
import marimo as mo
mo.md(results.create_tearsheet())Next Steps
Learn More
-
Strategy Development
- Read Strategy Development Guide
- See Examples for patterns and techniques
-
API Reference
- Review API Reference for complete API
- Learn about Data Providers
-
Advanced Topics
- Multi-asset strategies
- Futures and options trading
- Custom data integration
- Live trading
Common Patterns
Multi-Symbol Strategy
class MultiSymbolStrategy:
def __init__(self):
self.symbol_data = {}
def on_hiveq_event(self, ctx: hf.Context, event):
if event.type == EventType.START:
ctx.subscribe_bars(
symbols=['AAPL', 'GOOGL', 'MSFT'],
asset_type=AssetType.EQUITY,
interval='1m'
)
elif event.type == EventType.BAR:
bar = event.data()
# Per-symbol logic
if bar.symbol not in self.symbol_data:
self.symbol_data[bar.symbol] = []
self.symbol_data[bar.symbol].append(bar.close)
# Trade each symbol independently
if len(self.symbol_data[bar.symbol]) >= 20:
# Your strategy logic here
passPosition Sizing
def on_bar(self, ctx: hf.Context, event):
bar = event.data()
# Get portfolio info
portfolio = ctx.portfolio()
balance = portfolio.cash()
# Calculate position size (2% risk)
risk_per_trade = balance * 0.02
price = bar.close
quantity = int(risk_per_trade / price)
# Place order
if quantity > 0:
ctx.buy_order(bar.symbol, quantity=quantity)Stop Loss
def on_bar(self, ctx: hf.Context, event):
bar = event.data()
symbol = bar.symbol
# Check if we have a position
if ctx.is_net_long(symbol):
position = ctx.net_position(symbol)
# Get entry price (track in strategy state)
entry_price = self.entry_prices.get(symbol)
if entry_price:
# Calculate stop loss (2% below entry)
stop_price = entry_price * 0.98
# Exit if stop hit
if bar.close <= stop_price:
ctx.sell_order(symbol, quantity=position)
print(f"Stop loss hit! Exiting at {bar.close}")Timer Example
def on_start(self, ctx: hf.Context, event):
# Set 5-minute status timer
ctx.set_timer('status', pd.Timedelta(minutes=5))
def on_hiveq_event(self, ctx: hf.Context, event):
if event.type == EventType.TIMER:
timer = event.data()
if timer.timer_id == 'status':
# Print status every 5 minutes
portfolio = ctx.portfolio()
print(f"Status: P&L = ${portfolio.total_pnl():.2f}")Get Help
- Documentation: Review all docs in
docs/flow/ - Examples: Check
examples/directory - Issues: Report bugs at GitHub issues
- Community: Join our Discord/Slack
Troubleshooting
Import Error
Problem: ModuleNotFoundError: No module named 'hiveq'
Solution:
pip install hiveq-flowAPI Key Error
Problem: ValueError: api_key is required
Solution:
# Make sure to call init() with valid credentialsData Not Found
Problem: FileNotFoundError: bars/AAPL_bars.csv
Solution:
- Place CSV files in
~/.hiveq/data/bars/ - Or use
'type': 'hiveq_historical'for managed data
Strategy Not Found
Problem: Strategy class 'MyStrategy' not found
Solution:
- Ensure class name in
typematches actual class name - Check class is defined before
run_backtest()call
Quick Reference
Essential Imports
import hiveq.flow as hf
from hiveq.flow import Context, StrategyConfig
from hiveq.flow.config import EventType, AssetType, BacktestConfig
from hiveq.flow.trading_types import OrderType
from hiveq.flow.logger import loggerInitialization
Strategy Template
class MyStrategy:
def __init__(self):
self.param = 10
def on_hiveq_event(self, ctx: hf.Context, event):
if event.type == EventType.START:
ctx.subscribe_bars(symbols=['AAPL'], asset_type=AssetType.EQUITY, interval='1m')
elif event.type == EventType.BAR:
bar = event.data()
# Trading logic
elif event.type == EventType.STOP:
# Cleanup
passRun Backtest
report = hf.run_backtest(
strategy_configs=[config],
symbols=['AAPL'],
start_date='2025-08-01',
end_date='2025-08-30',
data_configs=[{
'type': 'hiveq_historical',
'dataset': 'HIVEQ_US_EQ',
'schema': ['bars_1m'],
}]
)Common Context Methods
# Subscriptions
ctx.subscribe_bars(['AAPL'], asset_type=AssetType.EQUITY, interval='1m')
ctx.subscribe_data(data_id='signals')
# Orders
ctx.buy_order('AAPL', quantity=100)
ctx.sell_order('AAPL', quantity=100)
ctx.cancel_order(order_id)
# Positions
ctx.net_position('AAPL')
ctx.is_flat('AAPL')
ctx.is_net_long('AAPL')
ctx.has_open_order('AAPL')
# Portfolio
portfolio = ctx.portfolio()
portfolio.total_pnl()
portfolio.cash()
# Instrument
inst = ctx.instrument('AAPL')
inst.last_bar.close
# Logging
ctx.add_event_log(message='Signal detected', symbol='AAPL')You're now ready to build trading strategies with HiveQ Flow!
For more details, see: