Webhooks
Complete guide to setting up and using webhooks for real-time notifications about trading events, account changes, and system updates.
Overview
Webhooks allow you to receive real-time notifications about events happening in your Vibe Trading account. Instead of polling the API for updates, webhooks push data directly to your application when events occur.
How Webhooks Work
- Event Occurs: Something happens in your account (order filled, position updated, etc.)
- Webhook Triggered: Vibe Trading sends HTTP POST request to your endpoint
- Your Server Responds: Your application processes the webhook data
- Confirmation: Your server responds with HTTP 200 to confirm receipt
Setting Up Webhooks
Step 1: Create Webhook Endpoint
Create a secure endpoint in your application to receive webhook data.
Example Flask Endpoint:
from flask import Flask, request, jsonify
import hmac
import hashlib
app = Flask(__name__)
@app.route('/webhook', methods=['POST'])
def handle_webhook():
# Verify webhook signature
signature = request.headers.get('X-Webhook-Signature')
payload = request.get_data()
if not verify_signature(payload, signature):
return jsonify({'error': 'Invalid signature'}), 401
# Process webhook data
data = request.get_json()
process_webhook_event(data)
return jsonify({'status': 'success'}), 200
def verify_signature(payload, signature):
expected_signature = hmac.new(
WEBHOOK_SECRET.encode(),
payload,
hashlib.sha256
).hexdigest()
return hmac.compare_digest(signature, expected_signature)
def process_webhook_event(data):
event_type = data['event']
if event_type == 'order.updated':
handle_order_update(data['data'])
elif event_type == 'position.updated':
handle_position_update(data['data'])
# Handle other event types...
Step 2: Configure Webhook in Vibe Trading
- Go to Account Settings > Webhooks
- Click "Add Webhook"
- Enter your webhook URL
- Select events you want to receive
- Set webhook secret for signature verification
- Test the webhook connection
Step 3: Verify Webhook Setup
Test your webhook endpoint to ensure it's working correctly.
curl -X POST "https://your-domain.com/webhook" \
-H "Content-Type: application/json" \
-H "X-Webhook-Signature: test_signature" \
-d '{"event": "test", "data": {"message": "webhook test"}}'
Webhook Events
Order Events
order.created
Triggered when a new order is created.
Payload:
{
"event": "order.created",
"timestamp": "2024-01-15T10:30:00Z",
"data": {
"orderId": "12345678-1234-1234-1234-123456789012",
"clientOrderId": "unique_order_id",
"symbol": "BTC/USD",
"side": "buy",
"type": "market",
"quantity": 0.1,
"price": 0,
"status": "pending",
"createdAt": "2024-01-15T10:30:00Z"
}
}
order.updated
Triggered when an order status changes.
Payload:
{
"event": "order.updated",
"timestamp": "2024-01-15T10:30:01Z",
"data": {
"orderId": "12345678-1234-1234-1234-123456789012",
"status": "filled",
"filledQuantity": 0.1,
"averagePrice": 49850.25,
"updatedAt": "2024-01-15T10:30:01Z"
}
}
order.cancelled
Triggered when an order is cancelled.
Payload:
{
"event": "order.cancelled",
"timestamp": "2024-01-15T10:35:00Z",
"data": {
"orderId": "12345678-1234-1234-1234-123456789012",
"status": "cancelled",
"cancelledAt": "2024-01-15T10:35:00Z",
"reason": "user_cancelled"
}
}
Position Events
position.opened
Triggered when a new position is opened.
Payload:
{
"event": "position.opened",
"timestamp": "2024-01-15T10:30:01Z",
"data": {
"symbol": "BTC/USD",
"side": "long",
"quantity": 0.1,
"averagePrice": 49850.25,
"unrealizedPnl": 0,
"marginUsed": 4985.03,
"createdAt": "2024-01-15T10:30:01Z"
}
}
position.updated
Triggered when position values change.
Payload:
{
"event": "position.updated",
"timestamp": "2024-01-15T11:00:00Z",
"data": {
"symbol": "BTC/USD",
"quantity": 0.1,
"unrealizedPnl": 150.75,
"unrealizedPnlPercent": 0.3,
"markPrice": 50000.0,
"marginRatio": 0.1,
"updatedAt": "2024-01-15T11:00:00Z"
}
}
position.closed
Triggered when a position is closed.
Payload:
{
"event": "position.closed",
"timestamp": "2024-01-15T11:30:00Z",
"data": {
"symbol": "BTC/USD",
"quantity": 0.1,
"averagePrice": 49850.25,
"closePrice": 50000.0,
"realizedPnl": 149.75,
"closedAt": "2024-01-15T11:30:00Z"
}
}
Account Events
account.balance_updated
Triggered when account balance changes.
Payload:
{
"event": "account.balance_updated",
"timestamp": "2024-01-15T10:30:01Z",
"data": {
"asset": "USD",
"available": 9500.0,
"locked": 500.0,
"total": 10000.0,
"change": -500.0,
"reason": "order_execution"
}
}
account.deposit_received
Triggered when a deposit is received.
Payload:
{
"event": "account.deposit_received",
"timestamp": "2024-01-15T09:00:00Z",
"data": {
"transactionId": "tx_123456789",
"asset": "USD",
"amount": 1000.0,
"method": "bank_transfer",
"status": "completed",
"receivedAt": "2024-01-15T09:00:00Z"
}
}
account.withdrawal_processed
Triggered when a withdrawal is processed.
Payload:
{
"event": "account.withdrawal_processed",
"timestamp": "2024-01-15T14:00:00Z",
"data": {
"transactionId": "tx_987654321",
"asset": "USD",
"amount": 500.0,
"method": "bank_transfer",
"status": "completed",
"processedAt": "2024-01-15T14:00:00Z"
}
}
AI Signal Events
signal.generated
Triggered when a new AI signal is generated.
Payload:
{
"event": "signal.generated",
"timestamp": "2024-01-15T12:00:00Z",
"data": {
"symbol": "BTC/USD",
"recommendation": "buy",
"confidence": 87,
"timeHorizon": "short_term",
"riskLevel": "medium",
"reasoning": [
"Strong bullish momentum detected",
"High volume confirmation",
"Positive sentiment from social media"
],
"technicalAnalysis": {
"rsi": 35.2,
"macd": "bullish",
"support": 48500.0,
"resistance": 50200.0
}
}
}
System Events
system.maintenance
Triggered before scheduled maintenance.
Payload:
{
"event": "system.maintenance",
"timestamp": "2024-01-15T18:00:00Z",
"data": {
"startTime": "2024-01-15T20:00:00Z",
"endTime": "2024-01-15T22:00:00Z",
"description": "Scheduled maintenance for system updates",
"affectedServices": ["trading", "api", "webhooks"]
}
}
system.alert
Triggered for important system alerts.
Payload:
{
"event": "system.alert",
"timestamp": "2024-01-15T15:30:00Z",
"data": {
"level": "warning",
"title": "High Market Volatility",
"message": "BTC/USD experiencing unusually high volatility",
"affectedSymbols": ["BTC/USD", "ETH/USD"],
"recommendation": "Consider reducing position sizes"
}
}
Webhook Security
Signature Verification
All webhooks include a signature header for verification.
Header: X-Webhook-Signature
Verification Process:
import hmac
import hashlib
def verify_webhook_signature(payload, signature, secret):
expected_signature = hmac.new(
secret.encode(),
payload,
hashlib.sha256
).hexdigest()
return hmac.compare_digest(signature, expected_signature)
# Usage
payload = request.get_data()
signature = request.headers.get('X-Webhook-Signature')
secret = "your_webhook_secret"
if not verify_webhook_signature(payload, signature, secret):
return "Unauthorized", 401
IP Whitelisting
Restrict webhook access to Vibe Trading IP addresses:
Vibe Trading IP Ranges:
203.0.113.0/24(Primary)198.51.100.0/24(Secondary)192.0.2.0/24(Backup)
HTTPS Required
All webhook endpoints must use HTTPS for security.
Webhook Management
Creating Webhooks via API
import requests
def create_webhook(api_key, secret_key, webhook_url, events):
headers = {
"X-API-Key": api_key,
"X-Timestamp": str(int(time.time())),
"X-Signature": generate_signature(secret_key, "POST", "/api/v1/webhooks", webhook_data)
}
webhook_data = {
"url": webhook_url,
"events": events,
"secret": "your_webhook_secret",
"active": True
}
response = requests.post(
"https://api.vibetrading.tech/api/v1/webhooks",
headers=headers,
json=webhook_data
)
return response.json()
# Usage
webhook = create_webhook(
api_key="your_api_key",
secret_key="your_secret_key",
webhook_url="https://your-domain.com/webhook",
events=["order.updated", "position.updated", "signal.generated"]
)
Listing Webhooks
def list_webhooks(api_key, secret_key):
headers = {
"X-API-Key": api_key,
"X-Timestamp": str(int(time.time())),
"X-Signature": generate_signature(secret_key, "GET", "/api/v1/webhooks", "")
}
response = requests.get(
"https://api.vibetrading.tech/api/v1/webhooks",
headers=headers
)
return response.json()
Updating Webhooks
def update_webhook(api_key, secret_key, webhook_id, updates):
headers = {
"X-API-Key": api_key,
"X-Timestamp": str(int(time.time())),
"X-Signature": generate_signature(secret_key, "PUT", f"/api/v1/webhooks/{webhook_id}", update_data)
}
response = requests.put(
f"https://api.vibetrading.tech/api/v1/webhooks/{webhook_id}",
headers=headers,
json=updates
)
return response.json()
# Usage
update_webhook(
api_key="your_api_key",
secret_key="your_secret_key",
webhook_id="webhook_123",
updates={"active": False}
)
Deleting Webhooks
def delete_webhook(api_key, secret_key, webhook_id):
headers = {
"X-API-Key": api_key,
"X-Timestamp": str(int(time.time())),
"X-Signature": generate_signature(secret_key, "DELETE", f"/api/v1/webhooks/{webhook_id}", "")
}
response = requests.delete(
f"https://api.vibetrading.tech/api/v1/webhooks/{webhook_id}",
headers=headers
)
return response.status_code == 204
Error Handling
Webhook Delivery Failures
If your webhook endpoint fails to respond with HTTP 200:
- Retry Logic: We retry failed webhooks up to 5 times
- Exponential Backoff: Increasing delays between retries
- Dead Letter Queue: Failed webhooks are stored for manual review
Common Issues
Timeout Errors
- Response Time: Respond within 30 seconds
- Async Processing: Process webhook data asynchronously
- Quick Acknowledgment: Return 200 immediately, process later
Signature Verification Failures
- Secret Mismatch: Ensure webhook secret matches
- Payload Encoding: Use raw request body for signature verification
- Header Case: Signature header is case-sensitive
Duplicate Events
- Idempotency: Handle duplicate webhook events gracefully
- Event IDs: Use event IDs to detect duplicates
- Database Checks: Check if event was already processed
Testing Webhooks
Webhook Testing Tool
Use our webhook testing tool to verify your endpoint:
curl -X POST "https://api.vibetrading.tech/api/v1/webhooks/test" \
-H "X-API-Key: your_api_key" \
-H "X-Timestamp: $(date +%s)" \
-H "X-Signature: calculated_signature" \
-d '{
"webhookId": "webhook_123",
"testEvent": {
"event": "test",
"timestamp": "2024-01-15T12:00:00Z",
"data": {
"message": "Webhook test successful"
}
}
}'
Local Development
For local development, use ngrok to expose your local server:
# Install ngrok
npm install -g ngrok
# Expose local server
ngrok http 3000
# Use ngrok URL for webhook
https://abc123.ngrok.io/webhook
Best Practices
Webhook Endpoint Design
- Idempotent: Handle duplicate events gracefully
- Fast Response: Respond quickly to avoid timeouts
- Error Handling: Implement proper error handling
- Logging: Log all webhook events for debugging
Security Considerations
- HTTPS Only: Always use encrypted connections
- Signature Verification: Always verify webhook signatures
- IP Whitelisting: Restrict access to known IPs
- Rate Limiting: Implement rate limiting on your endpoint
Monitoring and Alerting
- Health Checks: Monitor webhook endpoint health
- Failure Alerts: Set up alerts for webhook failures
- Performance Metrics: Track response times and success rates
- Dead Letter Queue: Monitor failed webhook deliveries
Troubleshooting
Common Problems
Webhook Not Receiving Events
- Check URL: Verify webhook URL is correct and accessible
- Check Events: Ensure correct events are selected
- Check Status: Verify webhook is active
- Check Logs: Review webhook delivery logs
Signature Verification Failures
- Check Secret: Verify webhook secret is correct
- Check Payload: Use raw request body for verification
- Check Encoding: Ensure proper UTF-8 encoding
- Check Headers: Verify signature header format
Timeout Issues
- Optimize Processing: Reduce processing time
- Async Processing: Process webhook data asynchronously
- Increase Timeout: Request longer timeout if needed
- Health Checks: Ensure endpoint is healthy
Getting Help
- Webhook Logs: Check webhook delivery logs in account settings
- Support Team: Contact support for webhook issues
- Documentation: Review webhook documentation
- Community Forum: Ask questions in the community forum
Ready to set up webhooks? Check out our API Authentication guide or explore WebSocket Feeds for real-time data.