Skip to content

Algo Trade Analytics Webhook API

This standard provides:

  • 🎯 Enhanced Analytics - Precise cost attribution with market price context
  • 🏗️ Multi-Platform Support - Works with Alpaca, Interactive Brokers, TD Ameritrade
  • 📊 Order Type Intelligence - Automatic detection and validation
  • 🔄 Broker Transformation - Universal format converts to broker-specific APIs
  • 📈 Risk Management - Built-in take profit and stop loss support
  • 🚀 Future-Proof Design - Extensible for new brokers and features
{
"ticker": "AAPL", // Symbol to trade (required)
"direction": "long", // Trade direction: "long" or "short" (required)
"auth_key": "your_key" // Authentication key (required)
}
{
// REQUIRED FIELDS
"ticker": "AAPL",
"direction": "long",
"auth_key": "your_auth_key",
// MARKET CONTEXT (For Enhanced Analytics)
"marketPrice": 150.25,
// ENTRY ORDER CONFIGURATION
"orderType": "stop_limit",
"qty": 100,
// ENTRY PRICES (Simplified)
"stopPrice": 150.50,
"limitPrice": 151.00,
// EXIT TARGETS (Simplified)
"profitTarget": 155.00,
"stopLossTarget": 145.00,
// TRAILING STOP (Alpaca Compatible)
"trailPrice": 2.00,
"trailPercent": 1.5,
// EXECUTION SETTINGS
"timeInForce": "gtc",
"extendedHours": false,
// METADATA (Grouped)
"metadata": {
"strategy": "Breakout Strategy",
"signal": "Volume Surge",
"timestamp": "2024-01-15T14:30:00Z",
"comment": "Breaking above resistance",
"alertMessage": "Long entry triggered",
"signalPlatform": "tradingview",
"brokerPlatform": "alpaca",
"confidence": "high"
}
}
FieldTypeRequiredDescriptionAlpaca Mapping
tickerstringSymbol to tradesymbol
direction’long’ | ‘short’Trade directionside (‘buy’/‘sell’)
auth_keystringAuthentication key-
qtynumber🔧Quantity to trade (shares)qty
notionalnumber🔧Dollar amount to trade (alternative to qty)notional
orderTypeUniversalOrderType⚠️Entry order typetype + conditional fields
stopPricenumber⚠️Stop trigger pricestop_price
limitPricenumber⚠️Limit pricelimit_price
takeProfitTakeProfitConfigTake profit configurationtake_profit
stopLossStopLossConfigStop loss configurationstop_loss
timeInForceTimeInForceOrder duration: day, gtc, opg, cls, ioc, foktime_in_force
extendedHoursbooleanExtended hours tradingextended_hours
clientOrderIdstringCustom order identifier (≤128 chars)client_order_id
positionIntentstringStrategy intent description (see Position Intent below)position_intent
accountIdstringAccount identifier-
metadataWebhookMetadataStrategy and signal information-

🔧 Either qty OR notional is required - use qty for share-based trading or notional for dollar-based trading

Algo Trade Analytics supports Alpaca’s official position intent values:

ValueDescriptionUse Case
buy_to_openOpening a long positionInitial buy to establish position
buy_to_closeClosing a short positionBuy to cover short position
sell_to_openOpening a short positionInitial short sale
sell_to_closeClosing a long positionSell to close long position

You can also use custom string values for strategy identification:

  • "swing_trade_breakout"
  • "dollar_cost_averaging"
  • "risk_management_exit"
  • "momentum_scalp"
FieldTypeDescription
orderTypestring"market", "limit", "stop", "stop_limit", "trailing_stop"
qtynumberQuantity to trade (shares/contracts)
notionalnumberDollar amount to trade (alternative to qty)
timeInForcestringOrder duration - see Time In Force options below
extendedHoursbooleanAllow extended hours trading
clientOrderIdstringCustom order identifier (≤128 characters, optional)

Algo Trade Analytics supports all Alpaca time-in-force values:

ValueDescriptionUse Case
dayDay order - valid only during regular trading hoursDefault for most strategies
gtcGood Till Canceled - valid until explicitly canceledLong-term orders
opgMarket/Limit on Open - executes only in opening auctionOpening bell strategies
clsMarket/Limit on Close - executes only in closing auctionEnd-of-day strategies
iocImmediate or Cancel - execute immediately, cancel remainderQuick execution with partial fills
fokFill or Kill - execute completely or cancel entirelyAll-or-nothing execution

📝 Alpaca Platform Notes:

  • Equity trading: Supports all TIF options (day, gtc, opg, cls, ioc, fok)
  • Options trading: Only supports day
  • Crypto trading: Only supports gtc and ioc
FieldTypeDescription
stopPricenumberStop trigger price for entry
limitPricenumberLimit price for entry
FieldTypeDescription
profitTargetnumberTake profit price
stopLossTargetnumberStop loss trigger price

Exit Targets (Advanced - for enhanced stop-limit exits)

Section titled “Exit Targets (Advanced - for enhanced stop-limit exits)”
FieldTypeDescription
profitTargetTypestring"limit" or "stop_limit"
profitTargetStopPricenumberStop trigger for stop-limit profit exit
profitTargetLimitPricenumberLimit price for stop-limit profit exit
stopLossTypestring"stop" or "stop_limit"
stopLossStopPricenumberStop trigger for stop loss
stopLossLimitPricenumberLimit price for stop-limit stop loss
FieldTypeDescription
trailPricenumberDollar amount trail (maps to Alpaca trail_price)
trailPercentnumberPercent trail (maps to Alpaca trail_percent)
FieldTypeDescription
strategystringStrategy name
signalstringSignal description
timestampstringSignal generation time (ISO-8601)
commentstringOrder description
alertMessagestringCustom alert text
signalPlatformstringSignal source: "tradingview", "trendspider", "custom"
brokerPlatformstringTarget broker: "alpaca", "interactive_brokers", "td_ameritrade"

Execute immediately at best available price.

{
"ticker": "AAPL",
"direction": "long",
"auth_key": "your_key",
"orderType": "market",
"qty": 100,
"marketPrice": 150.25
}

Execute only at specified price or better.

{
"ticker": "TSLA",
"direction": "long",
"auth_key": "your_key",
"orderType": "limit",
"qty": 50,
"limitPrice": 200.00,
"marketPrice": 201.50
}

Market order triggered when price reaches stop level.

{
"ticker": "NVDA",
"direction": "short",
"auth_key": "your_key",
"orderType": "stop",
"qty": 10,
"stopPrice": 450.00,
"marketPrice": 452.30
}

Limit order triggered when price reaches stop level.

{
"ticker": "SPY",
"direction": "long",
"auth_key": "your_key",
"orderType": "stop_limit",
"qty": 200,
"stopPrice": 450.50,
"limitPrice": 451.00,
"marketPrice": 449.85
}

Dynamic stop that follows favorable price movement.

{
"ticker": "QQQ",
"direction": "short",
"auth_key": "your_key",
"orderType": "trailing_stop",
"qty": 100,
"trailPercent": 2.5,
"marketPrice": 380.20
}
{
"ticker": "MSFT",
"direction": "long",
"auth_key": "your_key",
"orderType": "market",
"qty": 50,
"marketPrice": 350.00,
"profitTarget": 360.00,
"stopLossTarget": 345.00,
"metadata": {
"strategy": "Earnings Play",
"signal": "Bullish Guidance"
}
}
{
"ticker": "GOOGL",
"direction": "long",
"auth_key": "your_key",
"orderType": "stop_limit",
"qty": 5,
"stopPrice": 2800.50,
"limitPrice": 2801.00,
"profitTarget": 2850.00,
"stopLossTarget": 2780.00,
"stopLossLimit": 2779.00,
"marketPrice": 2799.25,
"metadata": {
"strategy": "Resistance Breakout",
"riskRewardRatio": 1.75
}
}

The universal standard provides precise cost attribution:

{
"marketPrice": 150.25, // Market when signal fired
"limitPrice": 151.00, // Intended entry price
"actualFillPrice": 151.12, // Actual execution price
"analytics": {
"setupCost": 0.75, // $151.00 - $150.25 (strategy choice)
"executionSlippage": 0.12, // $151.12 - $151.00 (broker performance)
"totalCost": 0.87, // Complete cost picture
"executionQuality": "good" // Performance rating
}
}
  • Excellent: < 0.1% total cost
  • Good: 0.1% - 0.25% total cost
  • Fair: 0.25% - 0.5% total cost
  • Poor: > 0.5% total cost

Universal Format:

{
"ticker": "AAPL",
"direction": "long",
"orderType": "stop_limit",
"qty": 10,
"stopPrice": 105.00,
"limitPrice": 106.00,
"timeInForce": "gtc"
}

Alpaca API Format:

{
"symbol": "AAPL",
"side": "buy",
"type": "limit",
"qty": "10",
"stop_price": "105",
"limit_price": "106",
"time_in_force": "gtc"
}

💡 Note: Alpaca uses type: "limit" with both stop_price and limit_price fields for stop-limit orders.

Universal Format:

{
"ticker": "TSLA",
"direction": "short",
"orderType": "stop_limit",
"qty": 50,
"stopPrice": 200.50,
"limitPrice": 200.25
}

Interactive Brokers Format:

{
"symbol": "TSLA",
"action": "SELL",
"orderType": "STP LMT",
"totalQuantity": 50,
"auxPrice": 200.50,
"lmtPrice": 200.25
}
strategy.entry("Long Entry", strategy.long,
alert_message='{"ticker":"' + syminfo.ticker + '","direction":"long","auth_key":"your_key","orderType":"market","qty":10,"marketPrice":' + str.tostring(close) + ',"metadata":{"strategy":"Simple Trend","timestamp":"' + str.tostring(time) + '"}}')
stopPrice = high[1]
limitPrice = stopPrice * 1.002
strategy.entry("Breakout Long", strategy.long, stop=stopPrice, limit=limitPrice,
alert_message='{"ticker":"' + syminfo.ticker + '","direction":"long","auth_key":"your_key","orderType":"stop_limit","qty":10,"stopPrice":' + str.tostring(stopPrice) + ',"limitPrice":' + str.tostring(limitPrice) + ',"marketPrice":' + str.tostring(close) + ',"metadata":{"strategy":"Breakout","signal":"High Break","timestamp":"' + str.tostring(time) + '"}}')
entryPrice = close
profitTarget = entryPrice * 1.05
stopLoss = entryPrice * 0.98
strategy.entry("Risk Managed", strategy.long,
alert_message='{"ticker":"' + syminfo.ticker + '","direction":"long","auth_key":"your_key","orderType":"market","qty":10,"marketPrice":' + str.tostring(close) + ',"profitTarget":' + str.tostring(profitTarget) + ',"stopLossTarget":' + str.tostring(stopLoss) + ',"metadata":{"strategy":"Risk Managed","riskReward":"2.5:1","timestamp":"' + str.tostring(time) + '"}}')
// Minimum valid webhook
{
"ticker": "AAPL", // Required
"direction": "long", // Required
"auth_key": "your_key" // Required
}

The system validates order-specific requirements:

  • Limit orders: Must have limitPrice
  • Stop orders: Must have stopPrice
  • Stop-limit orders: Must have both stopPrice and limitPrice
  • Trailing stops: Must have trailPrice OR trailPercent

For stop-limit orders:

  • Long direction: stopPrice < limitPrice
  • Short direction: stopPrice > limitPrice
ErrorCauseSolution
ticker is requiredMissing symbolAdd "ticker": "AAPL"
direction is requiredMissing directionAdd "direction": "long"
limitPrice is required for limit ordersLimit order without priceAdd "limitPrice": 150.00
stopPrice must be less than limitPriceInvalid price relationshipFix price relationship
WarningMeaningAction
Order type 'trailing_stop' not supported on td_ameritradeFeature not availableUse supported order type
Entry stop price is 5.2% from market priceLarge price gapReview order setup
import { UniversalWebhookProcessor } from './utils/webhookProcessor';
// Process webhook with analytics
const result = UniversalWebhookProcessor.processWebhook(webhookData, fillPrice);
if (result.response.success) {
console.log('Webhook processed successfully');
console.log('Order type:', result.analysis.orderType);
console.log('Market price:', result.analysis.marketPrice);
console.log('Setup cost:', result.analysis.setupCost);
console.log('Execution quality:', result.analysis.executionQuality);
console.log('Platform order:', result.platformOrder);
} else {
console.error('Validation errors:', result.response.errors);
}
// Validate webhook format
const normalized = UniversalWebhookProcessor.normalizeWebhook(webhookData);
const validation = UniversalWebhookProcessor.validateWebhook(normalized);
if (!validation.valid) {
console.error('Errors:', validation.errors);
console.warn('Warnings:', validation.warnings);
}
// Generate example webhooks for testing
const marketOrder = UniversalWebhookProcessor.generateExample('market');
const stopLimit = UniversalWebhookProcessor.generateExample('stop_limit');
const trailingStop = UniversalWebhookProcessor.generateExample('trailing_stop');
{
"ticker": "AAPL",
"direction": "long",
"marketPrice": 150.25, // Critical for analytics
"orderType": "limit",
"limitPrice": 149.50
}
{
"ticker": "TSLA",
"direction": "long",
"orderType": "market",
"profitTarget": 220.00, // Always set profit target
"stopLossTarget": 190.00 // Always set stop loss
}
{
"ticker": "NVDA",
"direction": "long",
"metadata": {
"strategy": "AI Momentum",
"signal": "Earnings Beat",
"confidence": "high",
"riskReward": "3:1",
"timeframe": "4h"
}
}
{
"ticker": "QQQ",
"direction": "short",
"metadata": {
"signalPlatform": "tradingview",
"brokerPlatform": "alpaca",
"preferredExecution": "aggressive"
}
}

The processor automatically handles legacy formats:

// Legacy format (still works)
{
"price": 150.25,
"action": "buy",
"ticker": "AAPL",
"extras": {
"stop": 150.50,
"limit": 151.00
}
}
// Automatically converts to universal format
{
"ticker": "AAPL",
"direction": "long",
"marketPrice": 150.25,
"orderType": "stop_limit",
"stopPrice": 150.50,
"limitPrice": 151.00
}
  • Multi-leg option strategies - Complex options trading
  • Portfolio-level risk management - Account-wide position limits
  • Cross-platform arbitrage - Execute across multiple brokers
  • Machine learning analytics - AI-powered execution optimization

Easy to extend for new platforms and features:

{
"ticker": "BTC-USD",
"direction": "long",
"auth_key": "your_key",
"metadata": {
"brokerPlatform": "coinbase",
"cryptoFeatures": {
"stakingEnabled": true,
"margin": 2
}
}
}

This webhook specification provides a solid foundation for automated trading with enhanced analytics while maintaining simplicity and extensibility.

{
// Simple limit profit target (traditional)
"profitTarget": 155.00,
// OR: Advanced stop-limit profit target
"profitTargetType": "stop_limit",
"profitTargetStopPrice": 155.00, // Trigger when price hits this level
"profitTargetLimitPrice": 154.75, // But sell no lower than this (for long)
// OR: Simple limit profit target (explicit)
"profitTargetType": "limit",
"profitTargetLimitPrice": 155.00
}
{
// Simple stop loss (traditional)
"stopLossTarget": 145.00,
// OR: Advanced stop-limit stop loss
"stopLossType": "stop_limit",
"stopLossStopPrice": 145.00, // Trigger when price drops to this level
"stopLossLimitPrice": 144.75, // But sell no lower than this (for long)
// OR: Simple stop loss (explicit)
"stopLossType": "stop",
"stopLossStopPrice": 145.00
}

Example 1: Long Position with Stop-Limit Exits

Section titled “Example 1: Long Position with Stop-Limit Exits”
{
"auth_key": "your_auth_key",
"ticker": "NVDA",
"direction": "long",
"orderType": "limit",
"qty": 100,
"marketPrice": 875.00,
"limitPrice": 876.50,
// Stop-limit profit target
"profitTargetType": "stop_limit",
"profitTargetStopPrice": 890.00, // Trigger when price hits $890
"profitTargetLimitPrice": 889.50, // But sell no lower than $889.50
// Stop-limit stop loss
"stopLossType": "stop_limit",
"stopLossStopPrice": 865.00, // Trigger when price drops to $865
"stopLossLimitPrice": 864.50, // But sell no lower than $864.50
"metadata": {
"strategy": "Earnings Breakout",
"signal": "Volume Surge + MA Cross"
}
}

💡 Why Stop-Limit Exits?

  • Profit Target: Protects against sudden reversals when taking profits
  • Stop Loss: Prevents excessive slippage during market gaps or high volatility
  • Control: You set both the trigger point AND the worst acceptable price

Example 2: Short Position with Mixed Exit Types

Section titled “Example 2: Short Position with Mixed Exit Types”
{
"auth_key": "your_auth_key",
"ticker": "AMZN",
"direction": "short",
"orderType": "stop_limit",
"qty": 50,
"marketPrice": 145.20,
"stopPrice": 144.80,
"limitPrice": 144.50,
// Stop-limit profit target (for short: profit when price drops)
"profitTargetType": "stop_limit",
"profitTargetStopPrice": 140.00, // Trigger when price drops to $140
"profitTargetLimitPrice": 140.25, // But buy back no higher than $140.25
// Regular stop loss (for short: loss when price rises)
"stopLossType": "stop",
"stopLossStopPrice": 148.00, // Stop loss if price rises to $148
"metadata": {
"strategy": "Short Squeeze Protection",
"signal": "Overbought RSI + Resistance"
}
}

Universal Format:

{
"ticker": "QQQ",
"direction": "short",
"orderType": "trailing_stop",
"qty": 100,
"trailPercent": 2.5,
"timeInForce": "gtc"
}

Alpaca API Format:

{
"symbol": "QQQ",
"side": "sell",
"type": "trailing_stop",
"qty": "100",
"trail_percent": "2.5",
"time_in_force": "gtc"
}
{
"ticker": "SPY",
"direction": "long",
"auth_key": "your_auth_key",
"orderType": "market",
"notional": 10000,
"clientOrderId": "monthly-dca-001",
"positionIntent": "dollar_cost_averaging",
"takeProfit": {
"limitPrice": 460.00
}
}
{
"ticker": "AAPL",
"direction": "long",
"auth_key": "your_auth_key",
"orderType": "stop_limit",
"qty": 100,
"stopPrice": 150.50,
"limitPrice": 151.00,
"clientOrderId": "breakout-strategy-001",
"positionIntent": "buy_to_open",
"timeInForce": "gtc",
"extendedHours": false,
"takeProfit": {
"limitPrice": 160.00
},
"stopLoss": {
"stopPrice": 145.00,
"limitPrice": 144.50
}
}
{
"ticker": "SPY",
"direction": "long",
"auth_key": "your_key",
"orderType": "market",
"qty": 100,
"timeInForce": "opg",
"clientOrderId": "opening-momentum-001",
"metadata": {
"strategy": "Opening Gap Play",
"signal": "Pre-market Volume Surge"
}
}
{
"ticker": "QQQ",
"direction": "short",
"auth_key": "your_key",
"orderType": "limit",
"qty": 50,
"limitPrice": 380.50,
"timeInForce": "cls",
"clientOrderId": "close-rebalance-001",
"metadata": {
"strategy": "End of Day Rebalancing",
"signal": "Portfolio Adjustment"
}
}
{
"ticker": "NVDA",
"direction": "long",
"auth_key": "your_key",
"orderType": "limit",
"qty": 100,
"limitPrice": 875.25,
"timeInForce": "ioc",
"clientOrderId": "scalp-entry-001",
"metadata": {
"strategy": "High Frequency Scalping",
"signal": "Level 2 Opportunity"
}
}
{
"ticker": "TSLA",
"direction": "long",
"auth_key": "your_key",
"orderType": "limit",
"qty": 1000,
"limitPrice": 200.00,
"timeInForce": "fok",
"clientOrderId": "block-trade-001",
"metadata": {
"strategy": "Large Block Trade",
"signal": "Institutional Order"
}
}
{
"ticker": "AAPL",
"direction": "long",
"auth_key": "your_key",
"orderType": "market",
"qty": 100,
"positionIntent": "buy_to_open",
"clientOrderId": "long-entry-001",
"metadata": {
"strategy": "Momentum Entry",
"signal": "Breakout Confirmed"
}
}
{
"ticker": "TSLA",
"direction": "long",
"auth_key": "your_key",
"orderType": "limit",
"qty": 50,
"limitPrice": 200.00,
"positionIntent": "buy_to_close",
"clientOrderId": "short-cover-001",
"metadata": {
"strategy": "Short Cover",
"signal": "Oversold Bounce"
}
}
{
"ticker": "SPY",
"direction": "short",
"auth_key": "your_key",
"orderType": "stop_limit",
"qty": 200,
"stopPrice": 450.00,
"limitPrice": 449.50,
"positionIntent": "sell_to_open",
"clientOrderId": "short-entry-001",
"metadata": {
"strategy": "Market Hedge",
"signal": "Technical Breakdown"
}
}
{
"ticker": "NVDA",
"direction": "short",
"auth_key": "your_key",
"orderType": "market",
"qty": 100,
"positionIntent": "sell_to_close",
"clientOrderId": "profit-take-001",
"metadata": {
"strategy": "Profit Taking",
"signal": "Target Reached"
}
}