Skip to main content
This guide covers how to deploy your trading bot to Railway for continuous 24/7 operation.

Why Deploy?

Running a bot on your local machine requires:
  • Keeping your computer on 24/7
  • Maintaining a stable internet connection
  • Manual restarts after crashes or updates
Deploying to a cloud platform like Railway eliminates these issues:
  • 24/7 uptime - Bot runs continuously in the cloud
  • Auto-restart - Automatically restarts if it crashes
  • Free tier - Railway offers $5 free credit for 30 days
  • Simple deployment - One command to deploy

Railway Deployment

Railway is the recommended platform for running Turbine bots. It’s simple, affordable, and designed for Python applications.

Prerequisites

  • A working trading bot (see Building Bots)
  • A Railway account (railway.app)
  • Your bot’s private key and API credentials

Quick Deploy

The fastest way to deploy is using the Railway deployment script:
# From the turbine-py-client directory
bash scripts/deploy-railway.sh
This script will:
  1. Check if Railway CLI is installed (installs it if needed)
  2. Create a new Railway project
  3. Set up environment variables
  4. Deploy your bot
  5. Provide you with the deployment URL
Railway offers **5freecreditfor30days.Afterthat,basicbothostingtypicallycosts5 free credit** for 30 days. After that, basic bot hosting typically costs 5-10/month depending on usage.

Manual Railway Setup

If you prefer to deploy manually:
1
Step 1: Install Railway CLI
2
# macOS/Linux
curl -fsSL https://railway.app/install.sh | sh

# Or via npm
npm install -g @railway/cli
3
Step 2: Login to Railway
4
railway login
5
This opens a browser window to authenticate.
6
Step 3: Initialize Project
7
In your bot’s directory:
8
railway init
9
Select “Create new project” and give it a name like turbine-trading-bot.
10
Step 4: Set Environment Variables
11
Add your credentials to Railway:
12
railway variables set TURBINE_PRIVATE_KEY="0xyour_private_key_here"
railway variables set TURBINE_API_KEY_ID="your_api_key_id"
railway variables set TURBINE_API_PRIVATE_KEY="your_api_private_key"
railway variables set CHAIN_ID="137"
railway variables set TURBINE_HOST="https://api.turbinefi.com"
13
Security: Never commit your .env file or private keys to git. Railway stores environment variables securely.
14
Step 5: Create Railway Configuration
15
Create a railway.json file in your project root:
16
{
  "build": {
    "builder": "NIXPACKS"
  },
  "deploy": {
    "startCommand": "python my_bot.py",
    "restartPolicyType": "ON_FAILURE",
    "restartPolicyMaxRetries": 10
  }
}
17
Replace my_bot.py with your bot’s filename.
18
Step 6: Create Procfile (Optional)
19
Alternatively, create a Procfile:
20
worker: python my_bot.py
21
Step 7: Deploy
22
Deploy your bot:
23
railway up
24
Railway will:
25
  • Build your Python environment
  • Install dependencies from requirements.txt
  • Start your bot
  • Provide a deployment URL
  • 26
    Step 8: Monitor Logs
    27
    Watch your bot’s output in real-time:
    28
    railway logs
    

    Project Structure for Deployment

    Your deployed bot should have this structure:
    my-trading-bot/
    ├── bot.py                 # Your bot code
    ├── requirements.txt       # Python dependencies
    ├── railway.json          # Railway config (optional)
    ├── Procfile              # Process definition (optional)
    ├── .gitignore            # Exclude .env, __pycache__, etc.
    └── README.md             # Documentation
    

    requirements.txt

    Create a requirements.txt file with your dependencies:
    requirements.txt
    turbine-py-client>=1.0.0
    python-dotenv>=1.0.0
    httpx>=0.24.0
    
    Generate it automatically:
    pip freeze > requirements.txt
    

    .gitignore

    Don’t commit sensitive files:
    .gitignore
    .env
    *.pyc
    __pycache__/
    .venv/
    venv/
    *.log
    .DS_Store
    

    Environment Variables on Railway

    Railway manages environment variables through its dashboard or CLI.

    Required Variables

    TURBINE_PRIVATE_KEY=0x...
    TURBINE_API_KEY_ID=...
    TURBINE_API_PRIVATE_KEY=...
    CHAIN_ID=137
    TURBINE_HOST=https://api.turbinefi.com
    

    Optional Variables

    # Trading parameters
    ORDER_SIZE_USDC=1.0
    MAX_POSITION_USDC=10.0
    
    # Bot behavior
    CLAIM_ONLY_MODE=false
    PRICE_POLL_SECONDS=10
    
    # Logging
    LOG_LEVEL=INFO
    

    Set via CLI

    railway variables set ORDER_SIZE_USDC="5.0"
    railway variables set MAX_POSITION_USDC="50.0"
    

    Set via Dashboard

    1. Go to railway.app
    2. Select your project
    3. Click “Variables” tab
    4. Add variables using the UI

    Monitoring Your Bot

    View Logs

    # Real-time logs
    railway logs
    
    # Follow logs (like tail -f)
    railway logs --follow
    

    Check Status

    railway status
    

    Restart Bot

    railway restart
    

    Access Railway Dashboard

    railway open
    
    This opens your project in the Railway web dashboard where you can:
    • View real-time logs
    • Monitor resource usage (CPU, memory)
    • Manage environment variables
    • Configure auto-scaling
    • Set up custom domains

    Advanced Configuration

    Auto-Restart on Failure

    Configure automatic restarts in railway.json:
    {
      "deploy": {
        "restartPolicyType": "ON_FAILURE",
        "restartPolicyMaxRetries": 10
      }
    }
    
    This restarts your bot up to 10 times if it crashes.

    Health Checks

    Add a simple HTTP health check endpoint to your bot:
    import asyncio
    from aiohttp import web
    
    class DeployedBot:
        def __init__(self):
            self.healthy = True
            self.last_trade_time = 0
        
        async def health_check(self, request):
            """Health check endpoint for Railway."""
            if not self.healthy:
                return web.Response(status=503, text="Unhealthy")
            return web.Response(text="OK")
        
        async def start_web_server(self):
            """Start health check server."""
            app = web.Application()
            app.router.add_get('/health', self.health_check)
            
            runner = web.AppRunner(app)
            await runner.setup()
            site = web.TCPSite(runner, '0.0.0.0', 8080)
            await site.start()
            print("Health check server running on :8080")
        
        async def run(self):
            # Start health check server
            asyncio.create_task(self.start_web_server())
            
            # Run bot
            while True:
                try:
                    # Your trading logic
                    self.healthy = True
                except Exception as e:
                    print(f"Error: {e}")
                    self.healthy = False
                
                await asyncio.sleep(10)
    
    Update railway.json:
    {
      "deploy": {
        "healthcheckPath": "/health",
        "healthcheckTimeout": 100
      }
    }
    

    Logging Configuration

    Structured logging for production:
    import logging
    import sys
    
    # Configure logging
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        handlers=[
            logging.StreamHandler(sys.stdout)  # Railway captures stdout
        ]
    )
    
    logger = logging.getLogger(__name__)
    
    # In your bot
    logger.info("Bot started")
    logger.warning("Low USDC balance")
    logger.error("Failed to place order", exc_info=True)
    

    Cost Optimization

    Railway Pricing

    Railway charges based on:
    • Execution time - How long your bot runs
    • Memory usage - RAM consumed
    • Network egress - Outbound data transfer
    Typical trading bot costs: $5-10/month

    Reduce Costs

    1. Optimize polling intervals - Don’t poll faster than necessary
    2. Batch API calls - Reduce network requests
    3. Efficient logging - Don’t log every trivial event
    4. Clean up old data - Don’t accumulate logs in memory
    # Good: Efficient polling
    await asyncio.sleep(10)  # Check every 10 seconds
    
    # Bad: Excessive polling
    await asyncio.sleep(0.1)  # Wastes CPU and API quota
    

    Scaling

    Horizontal Scaling

    Run multiple bot instances:
    # Deploy bot #1 (BTC only)
    railway variables set ASSETS="BTC"
    railway up
    
    # Deploy bot #2 (ETH only)
    railway variables set ASSETS="ETH"
    railway up
    
    # Deploy bot #3 (SOL only)
    railway variables set ASSETS="SOL"
    railway up
    

    Resource Limits

    Set memory limits in railway.json:
    {
      "deploy": {
        "resources": {
          "memory": 512
        }
      }
    }
    

    Troubleshooting

    Bot Keeps Crashing

    Check logs for errors:
    railway logs --lines 100
    
    Common issues:
    • Missing environment variables
    • Invalid API credentials
    • Insufficient USDC balance
    • Network timeouts

    ”Build Failed” Error

    Ensure requirements.txt is complete:
    pip freeze > requirements.txt
    git add requirements.txt
    git commit -m "Update dependencies"
    railway up
    

    Environment Variables Not Loading

    Verify variables are set:
    railway variables
    
    Make sure your bot reads from os.getenv(), not just .env file.

    High Memory Usage

    Optimize your bot:
    • Limit orderbook depth in memory
    • Clear old trade data periodically
    • Use generators instead of lists for large datasets
    # Bad: Loads all trades into memory
    trades = client.get_trades(market_id, limit=10000)
    
    # Good: Process in batches
    for i in range(0, 10000, 100):
        batch = client.get_trades(market_id, limit=100, offset=i)
        process_batch(batch)
    

    Alternative Platforms

    While Railway is recommended, you can also deploy to:

    Render

    # Create render.yaml
    services:
      - type: worker
        name: turbine-bot
        env: python
        buildCommand: pip install -r requirements.txt
        startCommand: python bot.py
    
    Deploy via render.com

    Heroku

    # Create Procfile
    worker: python bot.py
    
    # Deploy
    heroku create my-turbine-bot
    git push heroku main
    heroku ps:scale worker=1
    

    DigitalOcean App Platform

    # Create .do/app.yaml
    name: turbine-bot
    services:
      - name: bot
        run_command: python bot.py
        environment_slug: python
    

    AWS / GCP / Azure

    For advanced users, deploy to:
    • AWS Lambda (serverless)
    • Google Cloud Run (containerized)
    • Azure Container Instances
    These require Docker and more complex configuration.

    Next Steps

    Build a Trading Bot

    Create a bot to deploy

    Monitor Performance

    Track your bot’s performance

    WebSocket Streams

    Optimize with real-time data

    Example Bots

    Browse production-ready bots

    Build docs developers (and LLMs) love