Automated trading webhook server that receives signals from TradingView and executes trades on Binance.
# Clone or create the project directory
mkdir trading-webhook
cd trading-webhook
# Create the project structure (copy the files from the artifacts)
# Make sure you have uv installed: https://github.com/astral-sh/uv# Copy the example environment file
cp .env.example .env
# Edit .env with your actual credentials
nano .envRequired Environment Variables:
BINANCE_API_KEY=your_binance_api_key_here
BINANCE_SECRET_KEY=your_binance_secret_key_here
WEBHOOK_SECRET=your_secure_webhook_password_here
FLASK_ENV=development
FLASK_DEBUG=True
LOG_LEVEL=INFO# Install dependencies using uv
uv sync# Option 1: Using the project script (recommended)
uv run run-webhook
# Option 2: Using Flask directly
uv run flask --app src/trading_webhook.webhook run --host=0.0.0.0 --port=5000
# Option 3: Using the main module
uv run python -m src/trading_webhook.main- Check Status:
curl http://localhost:5000/status- Test Webhook (without placing orders):
curl -X POST http://localhost:5000/test \
-H "Content-Type: application/json" \
-d '{
"secret": "your_webhook_secret",
"ticker": "BTCUSDT",
"action": "buy",
"usdt_amount": 10
}'- Check Balances:
curl http://localhost:5000/balancesGET /- Home/info endpointGET /status- Health check and Binance connectivityGET /balances- Get account balancesPOST /webhook- Main webhook endpoint for TradingViewPOST /test- Test webhook without placing orders
For buying with USDT amount:
{
"secret": "your_webhook_secret",
"ticker": "BTCUSDT",
"action": "buy",
"usdt_amount": 50
}For selling all holdings:
{
"secret": "your_webhook_secret",
"ticker": "BTCUSDT",
"action": "sell"
}For selling percentage:
{
"secret": "your_webhook_secret",
"ticker": "BTCUSDT",
"action": "sell",
"percentage": 50
}-
Create Alert in TradingView:
- Right-click on your chart β "Add Alert"
- Select your strategy as the condition
- Go to "Notifications" tab
- Enable "Webhook URL"
- Enter your webhook URL:
http://your-server.com:5000/webhook - Paste the JSON message in the "Message" field
- Set frequency to "Once Per Bar Close"
-
For Testing with ngrok:
# Install ngrok: https://ngrok.com/ ngrok http 5000 # Use the https URL provided by ngrok in TradingView
trading-webhook/
βββ pyproject.toml # Project configuration
βββ README.md # This file
βββ .env.example # Environment template
βββ .env # Your actual environment variables (not in version control)
βββ .gitignore # Git ignore file
βββ .dockerignore # Docker ignore file
βββ Dockerfile # Docker configuration
βββ src/
β βββ trading_webhook/
β βββ __init__.py # Package init
β βββ main.py # Entry point for uv run
β βββ webhook.py # Main Flask application
β βββ binance_client.py # Binance API client
β βββ config.py # Configuration management
βββ tests/
βββ __init__.py
βββ test_webhook.py # Main tests
βββ test_edge_cases.py # Edge case tests
-
API Keys:
- Use Binance sub-account with limited permissions
- Enable IP whitelist for your server
- Never commit API keys to version control
-
Webhook Security:
- Use strong, unique webhook secret
- Monitor logs for unauthorized attempts
- Use HTTPS in production
-
Server Security:
- Keep dependencies updated
- Use firewall rules
- Monitor server resources
# Add gunicorn to dependencies (already included)
# Run with gunicorn
uv run gunicorn --bind 0.0.0.0:5000 --workers 1 --timeout 30 "trading_webhook.webhook:app"FLASK_ENV=production
FLASK_DEBUG=False
LOG_LEVEL=INFOFROM python:3.11-slim
WORKDIR /app
# Install uv
RUN pip install uv
# Copy project files
COPY . .
# Install dependencies
RUN uv sync --no-dev
# Expose port
EXPOSE 5000
# Run the application
CMD ["uv", "run", "run-webhook"]# Test buy order (test mode)
curl -X POST http://localhost:5000/test \
-H "Content-Type: application/json" \
-d '{
"secret": "your_webhook_secret",
"ticker": "BTCUSDT",
"action": "buy",
"usdt_amount": 10
}'
# Test sell order (test mode)
curl -X POST http://localhost:5000/test \
-H "Content-Type: application/json" \
-d '{
"secret": "your_webhook_secret",
"ticker": "BTCUSDT",
"action": "sell",
"percentage": 25
}'# Run tests
uv run pytest
# Run with coverage
uv run pytest --cov=src/trading_webhook- Logs are written to
logs/trading_webhook.log - All webhook requests are logged with IP addresses
- Successful trades include full order details
- Errors are logged with stack traces
INFO: Normal operations, successful tradesWARNING: Failed trades due to insufficient balanceERROR: API errors, configuration issuesDEBUG: Detailed request/response data (development only)
-
"Missing required environment variables"
- Check your
.envfile exists and has all required variables - Ensure no trailing spaces in environment variable values
- Check your
-
"API request failed"
- Verify Binance API keys are correct
- Check if IP whitelist is properly configured
- Ensure sub-account has trading permissions
-
"Insufficient balance"
- Check account balances with
/balancesendpoint - Verify you're using the correct sub-account
- Check account balances with
-
"Unauthorized"
- Verify webhook secret matches between TradingView and
.env - Check for typos in the JSON message
- Verify webhook secret matches between TradingView and
# Run in debug mode for detailed logging
LOG_LEVEL=DEBUG uv run run-webhookThe webhook supports multiple position sizing methods:
- Fixed USDT Amount:
"usdt_amount": 50 - Percentage of Balance:
"percentage": 25 - Fixed Quantity:
"quantity": 0.001 - All Available: Leave quantity/amount empty
- Currently optimized for USDT pairs (BTCUSDT, ETHUSDT, etc.)
- Can be extended for other quote currencies
- Automatic lot size calculation based on Binance trading rules
# Update dependencies
uv lock --upgrade
# Check for security vulnerabilities (if available)
uv audit
# Format code
uv run ruff format src/
uv run ruff check src/- Check logs in
logs/trading_webhook.logfor detailed error information - Use
/statusendpoint to verify Binance connectivity - Test with
/testendpoint before live trading - Start with small amounts when going live
This software is for educational and research purposes. Trading cryptocurrencies involves substantial risk. Always test thoroughly with small amounts before deploying significant capital. The authors are not responsible for any financial losses.