W&B Integration

Purple Flea for W&B

Weights & Biases (W&B) is the industry standard for ML experiment tracking. Combined with Purple Flea's trading API, your W&B runs don't just track metrics โ€” they power production trading agents that execute real crypto trades.

Get Free API Key โ†’ View API Docs
Sweeps
Hyperparameter Optimization
Registry
Model Version Control
Live
Trade Logging
6
Financial APIs

Integration Architecture

From first experiment to live production trading โ€” every step tracked and versioned in W&B.

1
Instrument Training and Backtesting with wandb.log()
Every call to wandb.log() captures your strategy's performance metrics as it runs. Log Sharpe ratio, max drawdown, total return, and individual trade outcomes across the entire backtest window. W&B stores every run automatically โ€” compare 100 strategy variants side-by-side in the dashboard without writing any storage code.
2
Use W&B Sweeps for Hyperparameter Optimization
Define a sweep configuration specifying which hyperparameters to search (lookback window, entry threshold, leverage, stop loss %) and which metric to maximize (Sharpe ratio). W&B launches dozens of parallel runs, uses Bayesian optimization to navigate the search space efficiently, and surfaces the best combination automatically. What took weeks of manual tuning now takes hours.
3
Register Champion Model and Trigger Live Trading
After sweeps complete, promote the best model to the W&B Model Registry with the "production" alias. A deployment hook detects the new production alias, downloads the model artifact, and starts the Purple Flea live trading loop using the champion configuration. The Registry acts as a gate โ€” only explicitly promoted models ever execute real trades.

W&B Integration Example

A minimal but complete integration: log hyperparameters, track metrics per epoch, and upload trade history as a W&B Table.

import wandb import requests HEADERS = {"Authorization": "Bearer YOUR_PURPLEFLEA_API_KEY"} PF_BASE = "https://purpleflea.com/api" # Initialize a W&B run โ€” visible at wandb.ai/your-team/crypto-trading wandb.init(project="crypto-trading", name="btc-momentum-sweep") # Log hyperparameters โ€” tracked per run, comparable across sweeps wandb.config.update({"lookback": 14, "threshold": 0.02, "leverage": 2}) # Fetch 90 days of market history from Purple Flea history = requests.get( f"{PF_BASE}/v1/markets/BTC-PERP/history", params={"days": 90, "resolution": "1h"}, headers=HEADERS ).json() # Backtest loop โ€” log metrics each epoch (week) trades_df = [] for epoch in range(100): sharpe, max_dd, ret = run_backtest_epoch(history, epoch, wandb.config) wandb.log({"sharpe": sharpe, "drawdown": max_dd, "total_return": ret}) trades_df.extend(get_epoch_trades(epoch)) # Upload full trade log as interactive W&B Table import pandas as pd df = pd.DataFrame(trades_df, columns=["ts", "side", "price", "pnl"]) wandb.log({"trade_history": wandb.Table(dataframe=df)}) # Upload model artifact to W&B Model Registry artifact = wandb.Artifact("btc-momentum-model", type="model") artifact.add_file("model.pkl") wandb.log_artifact(artifact) wandb.finish()

W&B Sweeps for Hyperparameter Optimization

Let W&B find the Sharpe-maximizing parameter combination automatically. Bayesian search over lookback, threshold, and leverage converges faster than grid search.

Sweep Configuration

sweep_config = { "method": "bayes", "metric": { "name": "sharpe", "goal": "maximize" }, "parameters": { "lookback": { "values": [7, 14, 21, 30] }, "threshold": { "min": 0.005, "max": 0.05 }, "leverage": { "values": [1, 2, 3, 5] }, "stop_loss_pct": { "min": 0.02, "max": 0.10 } } } sweep_id = wandb.sweep(sweep_config, project="crypto-trading") wandb.agent(sweep_id, function=train_and_backtest, count=50)

Agent Training Function

def train_and_backtest(): wandb.init() cfg = wandb.config # Pull fresh data for this run history = requests.get( f"{PF_BASE}/v1/markets/BTC-PERP/history", params={"days": 180}, headers=HEADERS ).json() # Run backtest with W&B config params sharpe, max_dd, ret = run_backtest( history, lookback=cfg.lookback, threshold=cfg.threshold, leverage=cfg.leverage, stop_loss=cfg.stop_loss_pct ) wandb.log({ "sharpe": sharpe, "max_drawdown": max_dd, "total_return": ret, "calmar_ratio": ret / abs(max_dd) }) # Tag best runs for registry promotion if sharpe > 1.8: wandb.run.tags = ["production-candidate"]

W&B Model Registry to Production

Use W&B model aliases (production, staging) as the gate controlling which model version executes live trades. Rollback is a single alias update.

Sweep completes
โ†’
Best run identified
โ†’
Promote to "production"
โ†’
Deployment hook fires
โ†’
Live trades begin
Model Registry: btc-momentum-model
production v8 โ€” Sharpe 2.14, Max DD -9.2% โ€” deployed to live trading
staging v9 โ€” Sharpe 1.96, Max DD -11.4% โ€” paper trading validation
archived v7 โ€” Sharpe 1.83, Max DD -14.1% โ€” superseded
import wandb # Deployment script: runs when production alias changes api = wandb.Api() artifact = api.artifact("your-team/crypto-trading/btc-momentum-model:production") artifact.download(root="./model") # Load champion and start live trading loop import joblib, requests, time model = joblib.load("./model/model.pkl") while True: price_data = requests.get(f"{PF_BASE}/v1/markets/BTC-PERP/price", headers=HEADERS).json() signal = model.predict(price_data["features"]) if signal == "long": requests.post(f"{PF_BASE}/v1/trade/open", json={"symbol": "BTC-PERP", "side": "long", "size": 100}, headers=HEADERS) # Log live trade back to W&B for monitoring wandb.log({"live_signal": signal, "price": price_data["price"]}) time.sleep(3600)

Available APIs

Six financial APIs your W&B pipeline runs can call for data, backtesting, and live execution.

๐Ÿ“ˆ
Perpetual futures with 90 days of OHLCV history, funding rates, and real-time mark prices for backtesting and live execution in W&B runs.
๐ŸŽฐ
Provably fair games with defined probability distributions. Log casino outcomes to W&B Tables to analyze agent risk behavior and decision quality.
๐Ÿ‘›
Multi-chain wallet management across BTC, ETH, SOL, XMR, and TRON. Log portfolio value changes alongside your trading model performance in W&B.
๐Ÿค
Trustless agent-to-agent payments. Models can settle inter-agent payments programmatically with 1% fee and 15% referral commission.
๐Ÿช™
Aave and Compound integration. Log lending positions, utilization rates, and liquidation risk alongside your W&B experiment metrics.
๐Ÿšฐ
New agents get free credits. Use faucet funds to generate real trade data for early W&B runs without depositing capital.

Use Cases

Real workflows teams build by connecting W&B experiment tracking to Purple Flea's live crypto financial infrastructure.

๐Ÿ“
Sharpe Maximization Sweeps
Configure W&B Bayesian sweeps to search lookback, leverage, and threshold space simultaneously. Find the combination that maximizes Sharpe over 180 days of real Purple Flea market data in hours rather than weeks.
๐Ÿ“‹
Live Trade Logging to W&B
Send live trade outcomes back to W&B as the model runs in production. Compare live vs. backtest Sharpe in real time. Automated alerts when live performance drifts beyond 1 standard deviation from backtest baseline.
๐ŸŒŠ
Market Regime Detection
Train separate models for bull, bear, and sideways regimes using Purple Flea data labels. Use W&B to track which regime model is active, monitor regime transitions, and log the handoff between models.
๐ŸŽญ
Ensemble Model Tracking
Build ensembles of momentum, mean-reversion, and funding-rate strategies. Use W&B to log each sub-model's contribution, track ensemble weights, and visualize which component dominates in different market conditions.

Related Integrations

Run Your First Trading Sweep

Connect W&B to Purple Flea in minutes. Let Bayesian optimization find your best trading strategy, then deploy it live automatically.