Code Examples

Copy-paste examples for the most common use cases. Every example is a complete, working script.

Python

Get Real-Time Trading Signals

Connect to the Daily AI Agent OS and generate trading signals using technical analysis strategies. This example runs a momentum strategy on AAPL, then retrieves recent high-confidence signals.

python
"""
Get real-time trading signals from Daily AI Agent OS.
Runs a momentum strategy and fetches recent high-confidence signals.
"""
import os
from dailyai import AgentOS

# Initialize with your API key (reads DAILYAI_API_KEY env var by default)
client = AgentOS(api_key=os.getenv("DAILYAI_API_KEY"))

# Run a momentum agent on AAPL
signal = client.agents.trading.run(
    asset="AAPL",
    strategy="momentum",
    timeframe="1h",
    risk_level="medium"
)

print(f"Signal: {signal.direction.upper()} {signal.asset}")
print(f"Confidence: {signal.confidence:.0%}")
print(f"Entry: ${signal.entry_price}")
print(f"Stop Loss: ${signal.stop_loss}")
print(f"Take Profit: ${signal.take_profit}")
print(f"Reasoning: {signal.metadata.reasoning}")

# Fetch recent high-confidence signals
recent_signals = client.signals.list(
    min_confidence=0.8,
    limit=5
)

print(f"\n--- Recent High-Confidence Signals ---")
for s in recent_signals:
    print(f"  {s.direction:5s} {s.asset:8s} | conf={s.confidence:.0%} | {s.strategy}")
Expected Output
Signal: LONG AAPL Confidence: 87% Entry: $198.45 Stop Loss: $195.20 Take Profit: $204.10 Reasoning: Strong momentum with RSI at 65 and MACD crossover --- Recent High-Confidence Signals --- long AAPL | conf=87% | momentum short TSLA | conf=82% | mean_reversion long MSFT | conf=91% | breakout long BTC-USD | conf=85% | sentiment short NVDA | conf=80% | momentum
Python

Monitor Weather Arbitrage Opportunities

Poll for weather-driven market opportunities, filtering by region and commodity. This example continuously monitors for high-severity weather events that impact natural gas prices.

python
"""
Monitor weather arbitrage opportunities in real-time.
Polls every 60 seconds for new weather-driven signals.
"""
import os
import time
from dailyai import AgentOS

client = AgentOS(api_key=os.getenv("DAILYAI_API_KEY"))

print("Monitoring weather arbitrage opportunities...")
print("Press Ctrl+C to stop.\n")

seen_signals = set()

while True:
    try:
        # Fetch weather signals for US natural gas
        signals = client.signals.weather(
            region="us",
            commodity="natural_gas",
            severity="high"
        )

        for signal in signals:
            if signal.signal_id not in seen_signals:
                seen_signals.add(signal.signal_id)
                event = signal.weather_event

                print(f"[NEW] Weather Arbitrage Opportunity")
                print(f"  Commodity:  {signal.commodity}")
                print(f"  Direction:  {signal.direction.upper()}")
                print(f"  Confidence: {signal.confidence:.0%}")
                print(f"  Event:      {event.type} ({event.severity})")
                print(f"  Location:   {event.location}")
                print(f"  Temp Delta: {event.temperature_deviation}°F")
                print(f"  Impact:     {signal.expected_impact}")
                print()

        time.sleep(60)  # Poll every 60 seconds

    except KeyboardInterrupt:
        print("\nStopped monitoring.")
        break
Expected Output
Monitoring weather arbitrage opportunities... Press Ctrl+C to stop. [NEW] Weather Arbitrage Opportunity Commodity: natural_gas Direction: LONG Confidence: 92% Event: cold_snap (high) Location: Northeast US Temp Delta: -12.5°F Impact: +8.3% price increase over 5 days [NEW] Weather Arbitrage Opportunity Commodity: natural_gas Direction: LONG Confidence: 88% Event: polar_vortex (high) Location: Midwest US Temp Delta: -18.2°F Impact: +11.1% price increase over 7 days
Python

Generate SEO Content

Use the SEO agent to generate optimized blog posts, product descriptions, and meta tags for your target keywords.

python
"""
Generate SEO-optimized content using the SEO Content Agent.
Produces a blog post with meta tags for the given keyword.
"""
import os
from dailyai import AgentOS

client = AgentOS(api_key=os.getenv("DAILYAI_API_KEY"))

# Generate a blog post
result = client.agents.seo.run(
    asset="ai-trading-strategies",       # Target keyword
    strategy="blog_post",
    options={
        "word_count": 1500,
        "tone": "professional",
        "include_meta": True,
        "target_audience": "retail traders"
    }
)

print(f"Title: {result.title}")
print(f"Meta Description: {result.meta_description}")
print(f"Word Count: {result.word_count}")
print(f"Readability Score: {result.readability_score}")
print(f"\nContent Preview:\n{result.content[:500]}...")

# Generate meta tags for a product page
meta = client.agents.seo.run(
    asset="automated-trading-bot",
    strategy="meta_tags",
    options={
        "page_type": "product",
        "brand": "Daily AI"
    }
)

print(f"\n--- Meta Tags ---")
print(f"Title Tag: {meta.title_tag}")
print(f"Description: {meta.meta_description}")
print(f"Keywords: {', '.join(meta.keywords)}")
print(f"OG Title: {meta.og_title}")
Expected Output
Title: AI Trading Strategies: A Complete Guide for 2026 Meta Description: Discover proven AI trading strategies that leverage machine learning... Word Count: 1523 Readability Score: 72.4 Content Preview: # AI Trading Strategies: A Complete Guide for 2026 Artificial intelligence has transformed how retail traders approach the market... --- Meta Tags --- Title Tag: Automated Trading Bot | AI-Powered Signals | Daily AI Description: Build and deploy automated trading bots with AI-powered signals... Keywords: automated trading bot, ai trading, algorithmic trading, daily ai OG Title: Automated Trading Bot — Daily AI Agent OS
Python Node.js

Set Up Webhooks for Signal Alerts

Receive real-time notifications when new signals are generated. This example shows both the webhook registration and a simple webhook receiver.

Register the Webhook (Python)

python
"""
Register a webhook to receive signal alerts.
"""
import os
import requests

API_KEY = os.getenv("DAILYAI_API_KEY")
BASE_URL = "https://api.dailyai.dev/v1"

# Register a webhook endpoint
response = requests.post(
    f"{BASE_URL}/webhooks",
    headers={"Authorization": f"Bearer {API_KEY}"},
    json={
        "url": "https://your-app.com/webhooks/signals",
        "events": ["signal.created", "signal.closed", "agent.error"],
        "secret": "whsec_your_signing_secret"
    }
)

webhook = response.json()
print(f"Webhook ID: {webhook['id']}")
print(f"Status: {webhook['status']}")
print(f"Events: {', '.join(webhook['events'])}")

Webhook Receiver (Node.js / Express)

javascript
/**
 * Simple webhook receiver for Daily AI Agent OS signal alerts.
 * Run: npm install express crypto && node webhook_receiver.js
 */
const express = require('express');
const crypto = require('crypto');

const app = express();
const WEBHOOK_SECRET = process.env.WEBHOOK_SECRET || 'whsec_your_signing_secret';

app.use(express.json({
  verify: (req, res, buf) => { req.rawBody = buf; }
}));

// Verify the webhook signature
function verifySignature(payload, signature) {
  const expected = crypto
    .createHmac('sha256', WEBHOOK_SECRET)
    .update(payload)
    .digest('hex');
  return crypto.timingSafeEqual(
    Buffer.from(signature),
    Buffer.from(`sha256=${expected}`)
  );
}

app.post('/webhooks/signals', (req, res) => {
  const signature = req.headers['x-dailyai-signature'];

  if (!verifySignature(req.rawBody, signature)) {
    return res.status(401).json({ error: 'Invalid signature' });
  }

  const event = req.body;
  console.log(`Received: ${event.type}`);

  switch (event.type) {
    case 'signal.created':
      console.log(`New signal: ${event.data.direction} ${event.data.asset}`);
      console.log(`Confidence: ${event.data.confidence}`);
      // Send Slack notification, trigger trade, etc.
      break;
    case 'signal.closed':
      console.log(`Signal closed: ${event.data.signal_id}`);
      console.log(`P&L: ${event.data.pnl_percent}%`);
      break;
    case 'agent.error':
      console.error(`Agent error: ${event.data.message}`);
      break;
  }

  res.json({ received: true });
});

app.listen(3000, () => console.log('Webhook receiver on port 3000'));
Expected Output (Webhook Receiver)
Webhook receiver on port 3000 Received: signal.created New signal: long AAPL Confidence: 0.87 Received: signal.closed Signal closed: sig_abc123 P&L: +3.2%
Python

Build a Custom Agent Pipeline

Chain multiple agents together to create a sophisticated analysis pipeline. This example combines trading signals with weather data and sentiment analysis for a multi-factor strategy.

python
"""
Custom agent pipeline: combines trading, weather, and sentiment signals
into a multi-factor trading decision.
"""
import os
from dailyai import AgentOS

client = AgentOS(api_key=os.getenv("DAILYAI_API_KEY"))

# Define the assets to analyze
ASSETS = ["AAPL", "MSFT", "GOOGL", "AMZN", "TSLA"]

def analyze_asset(asset):
    """Run multiple agents and combine their signals."""

    # 1. Technical analysis
    technical = client.agents.trading.run(
        asset=asset,
        strategy="momentum",
        timeframe="1h"
    )

    # 2. Sentiment analysis
    sentiment = client.agents.trading.run(
        asset=asset,
        strategy="sentiment"
    )

    # 3. Check for weather-related impacts (e.g., energy stocks)
    weather_signals = client.signals.weather(region="us")
    weather_relevant = [
        s for s in weather_signals
        if asset in s.metadata.get("affected_tickers", [])
    ]

    # Combine signals with weighted scoring
    scores = {
        "technical": technical.confidence * (1 if technical.direction == "long" else -1),
        "sentiment": sentiment.confidence * (1 if sentiment.direction == "long" else -1),
        "weather": sum(
            s.confidence * (1 if s.direction == "long" else -1)
            for s in weather_relevant
        ) if weather_relevant else 0
    }

    # Weighted average
    weights = {"technical": 0.5, "sentiment": 0.3, "weather": 0.2}
    composite = sum(scores[k] * weights[k] for k in scores)

    return {
        "asset": asset,
        "composite_score": composite,
        "direction": "long" if composite > 0 else "short",
        "confidence": abs(composite),
        "breakdown": scores
    }


# Run the pipeline
print("Multi-Factor Analysis Pipeline")
print("=" * 50)

results = []
for asset in ASSETS:
    result = analyze_asset(asset)
    results.append(result)

# Sort by confidence
results.sort(key=lambda r: r["confidence"], reverse=True)

for r in results:
    direction = "LONG " if r["direction"] == "long" else "SHORT"
    print(f"\n{direction} {r['asset']}")
    print(f"  Composite Score: {r['composite_score']:+.3f}")
    print(f"  Confidence:      {r['confidence']:.0%}")
    print(f"  Technical:       {r['breakdown']['technical']:+.3f}")
    print(f"  Sentiment:       {r['breakdown']['sentiment']:+.3f}")
    print(f"  Weather:         {r['breakdown']['weather']:+.3f}")
Expected Output
Multi-Factor Analysis Pipeline ================================================== LONG MSFT Composite Score: +0.782 Confidence: 78% Technical: +0.910 Sentiment: +0.680 Weather: +0.000 LONG AAPL Composite Score: +0.654 Confidence: 65% Technical: +0.870 Sentiment: +0.420 Weather: +0.120 SHORT TSLA Composite Score: -0.531 Confidence: 53% Technical: -0.760 Sentiment: -0.380 Weather: +0.000
Python

Integrate with Alpaca for Live Trading

Connect Daily AI Agent OS signals to the Alpaca broker API for automated live trading. This example monitors for high-confidence signals and automatically places orders.

python
"""
Alpaca integration: automatically execute trades based on
Daily AI Agent OS signals.

Requirements:
    pip install dailyai-agents alpaca-trade-api
"""
import os
import asyncio
from dailyai import AgentOS
import alpaca_trade_api as tradeapi

# Initialize clients
ai_client = AgentOS(api_key=os.getenv("DAILYAI_API_KEY"))
alpaca = tradeapi.REST(
    key_id=os.getenv("ALPACA_KEY_ID"),
    secret_key=os.getenv("ALPACA_SECRET_KEY"),
    base_url="https://paper-api.alpaca.markets"  # Use paper trading first!
)

# Configuration
MAX_POSITION_SIZE = 1000   # Maximum dollars per position
MIN_CONFIDENCE = 0.85      # Only trade high-confidence signals
ALLOWED_ASSETS = ["AAPL", "MSFT", "GOOGL", "AMZN", "TSLA", "META", "NVDA"]


def calculate_shares(asset, direction, entry_price):
    """Calculate position size based on risk management rules."""
    shares = int(MAX_POSITION_SIZE / entry_price)
    return max(1, shares)


def place_order(signal):
    """Place an order on Alpaca based on a Daily AI signal."""
    if signal.asset not in ALLOWED_ASSETS:
        print(f"  Skipping {signal.asset} — not in allowed list")
        return None

    if signal.confidence < MIN_CONFIDENCE:
        print(f"  Skipping — confidence {signal.confidence:.0%} below threshold")
        return None

    shares = calculate_shares(signal.asset, signal.direction, signal.entry_price)
    side = "buy" if signal.direction == "long" else "sell"

    # Place a bracket order with stop loss and take profit
    order = alpaca.submit_order(
        symbol=signal.asset,
        qty=shares,
        side=side,
        type="market",
        time_in_force="day",
        order_class="bracket",
        stop_loss={"stop_price": str(signal.stop_loss)},
        take_profit={"limit_price": str(signal.take_profit)}
    )

    print(f"  Order placed: {side.upper()} {shares} x {signal.asset}")
    print(f"  Order ID: {order.id}")
    print(f"  Stop Loss: ${signal.stop_loss} | Take Profit: ${signal.take_profit}")
    return order


async def main():
    print("Daily AI → Alpaca Live Trading Bot")
    print("=" * 50)
    print(f"Mode: Paper Trading")
    print(f"Min Confidence: {MIN_CONFIDENCE:.0%}")
    print(f"Max Position: ${MAX_POSITION_SIZE}")
    print(f"Assets: {', '.join(ALLOWED_ASSETS)}\n")

    # Stream signals in real-time
    async for event in ai_client.dashboard.stream():
        if event.type != "signal.new":
            continue

        signal = event.data
        print(f"\n[SIGNAL] {signal.direction.upper()} {signal.asset}")
        print(f"  Confidence: {signal.confidence:.0%}")
        print(f"  Entry: ${signal.entry_price}")

        order = place_order(signal)
        if order:
            print(f"  Status: Order submitted ✓")


if __name__ == "__main__":
    asyncio.run(main())
Expected Output
Daily AI → Alpaca Live Trading Bot ================================================== Mode: Paper Trading Min Confidence: 85% Max Position: $1000 Assets: AAPL, MSFT, GOOGL, AMZN, TSLA, META, NVDA [SIGNAL] LONG AAPL Confidence: 87% Entry: $198.45 Order placed: BUY 5 x AAPL Order ID: b1e2f3a4-5678-90ab-cdef-123456789abc Stop Loss: $195.20 | Take Profit: $204.10 Status: Order submitted [SIGNAL] SHORT TSLA Confidence: 76% Skipping — confidence 76% below threshold