Code Examples
Copy-paste examples for the most common use cases. Every example is a complete, working script.
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.
"""
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}")
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.
"""
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
Generate SEO Content
Use the SEO agent to generate optimized blog posts, product descriptions, and meta tags for your target keywords.
"""
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}")
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)
"""
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)
/**
* 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'));
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.
"""
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}")
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.
"""
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())