Skip to main content

REST API

FreqUI

FreqUI now has its own dedicated documentation section - please refer to that section for all information regarding the FreqUI.

Configuration

Enable the REST API by adding the api_server section to your configuration and setting api_server.enabled to true.

Basic Configuration

{
"api_server": {
"enabled": true,
"listen_ip_address": "127.0.0.1",
"listen_port": 8080,
"verbosity": "error",
"enable_openapi": false,
"jwt_secret_key": "somethingrandom",
"CORS_origins": [],
"username": "Freqtrader",
"password": "SuperSecret1!",
"ws_token": "secret_Ws_t0ken"
}
}
Security Warning

By default, the configuration listens on localhost only (so it's not reachable from other systems). We strongly recommend to not expose this API to the internet and choose a strong, unique password, since others will potentially be able to control your bot.

API/UI Access on Remote Servers

If you're running on a VPS, you should consider using either a SSH tunnel, or set up a VPN (OpenVPN, WireGuard) to connect to your bot.

This will ensure that FreqUI is not directly exposed to the internet, which is not recommended for security reasons (FreqUI does not support HTTPS out of the box).

Setup of these tools is not part of this tutorial, however many good tutorials can be found on the internet.

Test API Connection

You can test the API by going to http://127.0.0.1:8080/api/v1/ping in a browser to check if the API is running correctly.

This should return the response:

{"status":"pong"}

All other endpoints return sensitive info and require authentication and are therefore not available through a web browser.

Security

To generate a secure password, best use a password manager, or use the below code:

import secrets
secrets.token_hex()
JWT Token

Use the same method to also generate a JWT secret key (jwt_secret_key).

Password Selection

Please make sure to select a very strong, unique password to protect your bot from unauthorized access.

Also change jwt_secret_key to something random (no need to remember this, but it'll be used to encrypt your session, so it better be something unique!).

Configuration with Docker

If you run your bot using Docker, you'll need to have the bot listen to incoming connections. The security is then handled by Docker.

{
"api_server": {
"enabled": true,
"listen_ip_address": "0.0.0.0",
"listen_port": 8080,
"username": "Freqtrader",
"password": "SuperSecret1!"
}
}

Make sure that the following 2 lines are available in your docker-compose file:

ports:
- "127.0.0.1:8080:8080"
Docker Security Warning

By using "8080:8080" (or "0.0.0.0:8080:8080") in the docker port mapping, the API will be available to everyone connecting to the server under the correct port, so others may be able to control your bot.

This may be safe if you're running the bot in a secure environment (like your home network), but it's not recommended to expose the API to the internet.

Consuming the API

Using freqtrade-client

We advise consuming the API by using the supported freqtrade-client package.

This command can be installed independent of any running freqtrade bot by using:

pip install freqtrade-client

This module is designed to be lightweight, and only depends on the requests and python-rapidjson modules, skipping all heavy dependencies freqtrade otherwise needs.

Basic Usage

# Basic command
freqtrade-client <command> [optional parameters]

# With custom config
freqtrade-client --config rest_config.json <command> [optional parameters]

# With keyword arguments
freqtrade-client --config rest_config.json forceenter BTC/USDT long enter_tag=GutFeeling

Client Configuration

Create a minimalistic client config:

{
"api_server": {
"enabled": true,
"listen_ip_address": "127.0.0.1",
"listen_port": 8080,
"username": "Freqtrader",
"password": "SuperSecret1!"
}
}

Programmatic Usage

The freqtrade-client package can be used in your own scripts:

from freqtrade_client import FtRestClient

client = FtRestClient(server_url, username, password)

# Get the status of the bot
ping = client.ping()
print(ping)

# Get balance
balance = client.balance()
print(balance)

# Get open trades
status = client.status()
print(status)

Available Commands

System Commands

# Check API status
freqtrade-client ping

# Get bot version
freqtrade-client version

# Show configuration
freqtrade-client show_config

# Get logs
freqtrade-client logs --limit 50

Trading Commands

# Get open trades
freqtrade-client status

# Get trade count
freqtrade-client count

# Force enter trade
freqtrade-client forceenter BTC/USDT long

# Force exit trade
freqtrade-client forceexit 1

# Cancel open order
freqtrade-client cancel_open_order 1

# Delete trade
freqtrade-client delete_trade 1

Information Commands

# Get balance
freqtrade-client balance

# Get performance
freqtrade-client performance

# Get profit summary
freqtrade-client profit

# Get daily profit
freqtrade-client daily

# Get available pairs
freqtrade-client available_pairs

# Get whitelist
freqtrade-client whitelist

# Get blacklist
freqtrade-client blacklist

Control Commands

# Start bot
freqtrade-client start

# Stop bot
freqtrade-client stop

# Reload configuration
freqtrade-client reload_config

# Stop buying (pause)
freqtrade-client stopbuy

API Endpoints

Authentication

All endpoints except /ping require authentication. The API uses HTTP Basic Authentication with the username and password configured in your settings.

Common Endpoints

GET /api/v1/ping

Test API connectivity.

Response:

{"status": "pong"}

GET /api/v1/version

Get bot version information.

Response:

{"version": "2024.1"}

GET /api/v1/status

Get current bot status and open trades.

Response:

[
{
"trade_id": 1,
"pair": "BTC/USDT",
"is_open": true,
"amount": 0.001,
"stake_amount": 50.0,
"open_rate": 50000.0,
"current_rate": 51000.0,
"profit_pct": 2.0
}
]

GET /api/v1/balance

Get account balance.

Response:

{
"currencies": [
{
"currency": "USDT",
"free": 1000.0,
"balance": 1000.0,
"used": 0.0
}
],
"total": 1000.0
}

POST /api/v1/forceenter

Force enter a trade.

Request Body:

{
"pair": "BTC/USDT",
"side": "long",
"price": 50000.0
}

POST /api/v1/forceexit

Force exit a trade.

Request Body:

{
"tradeid": "1"
}

WebSocket API

The API also provides WebSocket endpoints for real-time data:

WebSocket Configuration

{
"api_server": {
"enabled": true,
"ws_token": "your_websocket_token"
}
}

WebSocket Endpoints

  • /api/v1/message/ws - Real-time bot messages
  • /api/v1/message/ws_token - Token-authenticated messages

WebSocket Usage

const ws = new WebSocket('ws://localhost:8080/api/v1/message/ws_token');

ws.onopen = function(event) {
// Send authentication token
ws.send(JSON.stringify({token: 'your_websocket_token'}));
};

ws.onmessage = function(event) {
const data = JSON.parse(event.data);
console.log('Received:', data);
};

Error Handling

HTTP Status Codes

  • 200 - Success
  • 400 - Bad Request
  • 401 - Unauthorized
  • 404 - Not Found
  • 500 - Internal Server Error

Error Response Format

{
"error": "Error description",
"detail": "Detailed error message"
}

Best Practices

Security

  1. Use strong passwords - Generate secure passwords and JWT secrets
  2. Limit network access - Use localhost or VPN connections
  3. Regular token rotation - Change passwords and tokens periodically
  4. Monitor access logs - Check for unauthorized access attempts

Performance

  1. Rate limiting - Don't overwhelm the API with requests
  2. Efficient polling - Use WebSockets for real-time data
  3. Batch operations - Combine multiple operations when possible
  4. Cache responses - Cache static data locally

Development

  1. Use the client library - Prefer freqtrade-client over raw HTTP
  2. Handle errors gracefully - Implement proper error handling
  3. Test thoroughly - Test API integration before production use
  4. Document your usage - Keep track of API usage patterns

Troubleshooting

Common Issues

API not responding:

  • Check if API is enabled in configuration
  • Verify correct IP address and port
  • Check firewall settings
  • Ensure bot is running

Authentication failures:

  • Verify username and password
  • Check JWT secret key configuration
  • Ensure credentials match configuration
  • Try regenerating passwords

Connection timeouts:

  • Check network connectivity
  • Verify server is accessible
  • Increase timeout values
  • Check for rate limiting

Getting Help

Next Steps

After setting up the REST API:

  1. FreqUI - Web-based user interface
  2. Bot Usage - Learn to operate the bot
  3. Configuration - Advanced configuration options
  4. Strategy Development - Create trading strategies

Resources