IC Markets

Broker Execution Speed Matters More for Scalpers Than Anyone Else

Document your personal trading journey. Track daily equity curves, review winning and losing streaks, share trade screenshots, and get constructive feedback.
PTScalper
Site Admin
Posts: 1023
Joined: Mon Jul 20, 2026 1:28 pm

Re: Broker Execution Speed Matters More for Scalpers Than Anyone Else

Post by PTScalper »

Building a local webhook listener on your VPS is the absolute best way to minimize the structural latency of TradingView. By cutting out third-party bridges, you eliminate their server processing queues, database lookups, and the physical network hop between their servers and your broker.

Since you are running MT5 and cTrader, your VPS is likely a Windows Server environment. The cleanest, most performant stack for this is a Python FastAPI server running locally on the VPS, communicating directly with the trading terminal.

For MT5, you can use MetaQuotes' native Python integration, which executes orders directly through the terminal's memory space with near-zero local latency.

Here is the complete architectural blueprint and implementation.

The Architecture

TradingView Alert: Sends a JSON payload via HTTPS POST.

[b1.) ]Cloud Firewall:[/b] GCP or Alibaba network security groups allow inbound traffic on port 443 strictly from TradingView's IP blocks.

2.) Nginx (Reverse Proxy): Terminates SSL (via Let's Encrypt) and forwards the request to your local Python port.

3.) FastAPI Listener: Validates the payload token and parses the trade data.

Terminal Execution: Executes the trade natively in MT5, or pushes it to a local TCP socket for cTrader.
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 1023
Joined: Mon Jul 20, 2026 1:28 pm

Re: Broker Execution Speed Matters More for Scalpers Than Anyone Else

Post by PTScalper »

1. The FastAPI Webhook Listener (Python)

FastAPI is highly asynchronous, meaning it won't queue incoming requests if TradingView fires multiple alerts simultaneously across different pairs.

Save this as webhook.py on your VPS.

Code: Select all

import uvicorn
from fastapi import FastAPI, HTTPException, Request
from pydantic import BaseModel
import MetaTrader5 as mt5

app = FastAPI()

# A secret token you will include in your TradingView alert message
# e.g., {"token": "YOUR_SECURE_TOKEN_HERE", "action": "buy", "volume": 0.1, "symbol": "EURUSD"}
SECRET_TOKEN = "YOUR_SECURE_TOKEN_HERE"

class TradePayload(BaseModel):
    token: str
    action: str
    volume: float
    symbol: str

@app.on_event("startup")
def startup_event():
    # Initialize connection to the local MT5 terminal
    if not mt5.initialize():
        print("MT5 initialization failed")
        mt5.shutdown()

@app.post("/tv-webhook")
async def execute_trade(payload: TradePayload):
    # 1. Validate the source
    if payload.token != SECRET_TOKEN:
        raise HTTPException(status_code=401, detail="Unauthorized")

    # 2. Prepare the MT5 order request
    symbol = payload.symbol
    action = payload.action.lower()
    
    # Ensure symbol is visible in market watch
    if not mt5.symbol_select(symbol, True):
        raise HTTPException(status_code=400, detail=f"Symbol {symbol} not found")

    symbol_info = mt5.symbol_info(symbol)
    
    if action == "buy":
        order_type = mt5.ORDER_TYPE_BUY
        price = symbol_info.ask
    elif action == "sell":
        order_type = mt5.ORDER_TYPE_SELL
        price = symbol_info.bid
    else:
        raise HTTPException(status_code=400, detail="Invalid action")

    request = {
        "action": mt5.TRADE_ACTION_DEAL,
        "symbol": symbol,
        "volume": payload.volume,
        "type": order_type,
        "price": price,
        "deviation": 5,
        "magic": 123456,
        "comment": "TV Webhook",
        "type_time": mt5.ORDER_TIME_GTC,
        "type_filling": mt5.ORDER_FILLING_FOK,
    }

    # 3. Fire the order natively into the MT5 terminal
    result = mt5.order_send(request)
    
    if result.retcode != mt5.TRADE_RETCODE_DONE:
        return {"status": "error", "message": result.comment, "retcode": result.retcode}
        
    return {"status": "success", "ticket": result.deal}

if __name__ == "__main__":
    # Run locally, exposed only to Nginx
    uvicorn.run(app, host="127.0.0.1", port=8000)
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 1023
Joined: Mon Jul 20, 2026 1:28 pm

Re: Broker Execution Speed Matters More for Scalpers Than Anyone Else

Post by PTScalper »

2. Adapting for cTrader (Local TCP Socket)

Because cTrader does not have a native Python memory-space execution library like MT5, you need to pass the signal from FastAPI to a cBot running inside cTrader.

1.) The lowest-latency way to do this locally is a TCP Socket.

2.) In Python (FastAPI): Instead of mt5.order_send(), use the native Python socket library to instantly push a raw JSON string to 127.0.0.1:9000.

3.) In cTrader (C#): Write a cBot utilizing System.Net.Sockets.TcpListener on port 9000.

Execution: The moment the cBot receives the JSON string over the local loopback interface, it parses the action and fires ExecuteMarketOrderAsync. Because it never leaves the VPS motherboard, the latency between Python and C# is measured in microseconds.

3. Network Security & Routing

Exposing a trading execution endpoint directly to the web is highly dangerous. You must lock this down at both the web-server and infrastructure levels.

The Reverse Proxy (Nginx): Do not expose Uvicorn directly to the web. Install Nginx on your Windows VPS, configure a server block to listen on 443 with your SSL certificate, and proxy pass traffic to 127.0.0.1:8000.

Cloud Firewall (GCP/Alibaba): Drop all traffic to port 443 by default. Create a specific inbound allow rule exclusively for TradingView's static IP addresses (they publish a list of four subnets specifically for webhooks, such as 52.89.214.238, 34.212.75.30, etc.).

Payload Authentication: The SECRET_TOKEN in the JSON payload ensures that even if someone spoofs a TradingView IP, they cannot execute trades without your private key.
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
Post Reply