Plus i prepared something special to improve webhooks for high frequency scalpers.
To handle high-volume executions without timing out TradingView's webhook limits (TradingView expects a 200 OK response within 3 seconds) or hitting broker rate limits, the Flask application must decouple the incoming request from the execution logic.
The most robust way to achieve this in a standalone Python application is by implementing a Producer-Consumer pattern using a thread-safe in-memory queue. The Flask route acts as the producer, mathematically slicing the massive position and instantly pushing the chunks to a queue. A background daemon thread acts as the consumer, popping chunks off the queue and executing them with a built-in rate-limiting delay.
from flask import Flask, request, jsonify
import threading
import queue
import time
import math
import logging
# Configure logging for server monitoring
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s')
app = Flask(__name__)
# Thread-safe queue to hold order chunks
order_queue = queue.Queue()
# --- Configuration ---
MAX_CHUNK_LOTS = 50.0
RATE_LIMIT_DELAY = 0.5 # Seconds to wait between broker API calls
MIN_LOT_STEP = 0.01 # Broker minimum volume step
#+------------------------------------------------------------------+
#| Background Worker: Processes chunks sequentially |
#+------------------------------------------------------------------+
def broker_execution_worker():
logging.info("Background broker execution worker started.")
while True:
# Block until a chunk is available in the queue
chunk = order_queue.get()
symbol = chunk.get('symbol')
qty = chunk.get('qty')
action = chunk.get('action')
try:
# ---------------------------------------------------------
# TODO: Insert your specific Broker API execution call here
# Example: requests.post('http://broker-api...', json=chunk)
# ---------------------------------------------------------
logging.info(f"EXECUTING BROKER API: {action} {qty} lots of {symbol}")
except Exception as e:
logging.error(f"Broker API Error for {symbol}: {e}")
# Optional: Implement retry logic and push back to queue on failure
finally:
# Enforce rate limit delay before processing the next chunk
time.sleep(RATE_LIMIT_DELAY)
order_queue.task_done()
# Start the background worker thread (daemon=True ensures it dies when Flask stops)
threading.Thread(target=broker_execution_worker, daemon=True).start()
#+------------------------------------------------------------------+
#| Webhook Route: Catches TV payload and chunks it instantly |
#+------------------------------------------------------------------+
@app.route('/tv-webhook', methods=['POST'])
def tradingview_webhook():
if not request.is_json:
return jsonify({"error": "Payload must be JSON"}), 400
data = request.json
symbol = data.get('symbol')
total_qty = data.get('qty')
action = data.get('action', 'close')
if not symbol or not total_qty:
return jsonify({"error": "Missing symbol or qty"}), 400
try:
total_qty = float(total_qty)
remaining_qty = abs(total_qty)
chunks_queued = 0
# Slice the massive position into broker-safe chunks
while remaining_qty >= MIN_LOT_STEP:
close_qty = min(remaining_qty, MAX_CHUNK_LOTS)
# Normalize to avoid Invalid Volume errors
close_qty = math.floor(close_qty / MIN_LOT_STEP) * MIN_LOT_STEP
if close_qty < MIN_LOT_STEP:
break
# Create the chunk payload
chunk_payload = {
"action": action,
"symbol": symbol,
"qty": round(close_qty, 2)
}
# Push to the background queue instantly
order_queue.put(chunk_payload)
remaining_qty -= close_qty
chunks_queued += 1
logging.info(f"Received webhook for {symbol}. Sliced into {chunks_queued} chunks.")
# Return 202 Accepted immediately so TradingView does not timeout
return jsonify({
"status": "queued",
"symbol": symbol,
"chunks_generated": chunks_queued
}), 202
except ValueError:
return jsonify({"error": "Invalid quantity format"}), 400
if __name__ == '__main__':
# Run the server on port 5000
app.run(host='0.0.0.0', port=5000)
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
When deploying this web stack to your Google Cloud Platform or Alibaba Cloud instances, the Flask development server (app.run()) is not designed to handle raw internet traffic safely.
1.Deploy a WSGI Server:Wrap the Flask application using a production-grade WSGI server like Gunicorn or uWSGI to handle concurrent network connections efficiently.
2.Configure Nginx Reverse Proxy:Set up Nginx to proxy incoming requests on port 80/443 to the Gunicorn socket. This layer absorbs slow-loris attacks and manages SSL termination.
3.Lock Down Firewall Rules:Critical for execution safety.Configure your cloud network security groups to drop all traffic to the webhook route except for TradingView's specific, publicly published IP addresses (e.g., 52.89.214.238, 34.212.75.30, etc.).
4.Implement Secret Tokens:Add an authentication token parameter to your TradingView alert JSON (e.g., {"secret": "YOUR_HASH"}) and validate it at the top of the /tv-webhook route before processing the payload.
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper wrote: Your server should catch that single alert, slice it into 50-lot chunks, and dispatch them to the broker sequentially via the broker's API.
Doing the slicing on the server makes sense. Two things I'd build into the receiver. First, reconciliation after each chunk: query the actual open volume rather than assuming each 50-lot close succeeded. If chunk three of five is rejected or times out, the position is partly closed, and a blind retry can either leave volume open or try to close more than exists. 235.5 lots is four chunks of 50 plus 35.5, so there are five places for that to go wrong.
Second, the market moves between chunks. In a fast market, sequential chunks fill at progressively worse prices, so the first and last might be several pips apart, especially if the close is triggered by a news spike. It's worth logging each chunk's fill so the true average exit price can be measured afterwards.
And make the receiver idempotent. TradingView can occasionally deliver the same alert twice, and a duplicate "close 235.5" shouldn't open anything new.
PTScalper wrote: A background daemon thread acts as the consumer, popping chunks off the queue and executing them with a built-in rate-limiting delay.
What happens to the chunks still sitting in that queue if the process restarts halfway through? queue.Queue lives in memory, and a daemon thread is killed without cleanup when the main process exits, so a Gunicorn worker recycle or a deploy in the middle of a 235-lot exit could silently drop the remaining chunks. Also, if Gunicorn runs more than one worker, each worker gets its own queue and its own consumer thread, so two alerts could be sliced in parallel and the rate limit no longer holds. Are you running a single worker, or persisting the pending chunks somewhere like Redis or SQLite so the consumer can resume after a restart?
The queue approach is a good solution to Error 146 and frozen terminals. One more detail: when processing closures in chunks, re-check the position's existence and current lot size before each OrderClose call, because a stop or take profit may have closed it between ticks. Otherwise the queue can produce invalid ticket errors.
It may also help to log each queue step, so if the terminal disconnects mid-process, the EA can resume from where it stopped rather than starting again.
Two camps argue forever. Price action traders believe that indicators are lagging derivatives of price, adding nothing. Indicator traders believe that price action is subjective, and that indicators provide objective rules.
Both have a point. Indicators are mathematical transformations of price (and sometimes volume), so they contain no new information, but they can present existing information in a form that's easier to act on, and they enforce consistency. Price action reading offers flexibility and context sensitivity, but suffers from subjectivity and hindsight bias.
In practice, many successful traders blend the two. They use a few indicators to define conditions, such as trend direction or volatility, and price structure to time entries and exits.
The most important factor is probably consistency. A method applied the same way every time can be measured and improved. A method that changes with mood can't.
A test: write the rules of a price action method so precisely that a program could execute it. If that's possible, the approach can be tested like any indicator strategy. If it isn't, it remains an art.
An intermediate path: use indicators for context only, like trend direction and volatility regime, and price structure for the actual entry. It reduces the subjectivity of the discretionary part, since the context filter removes a lot of ambiguous situations, and keeps the flexibility of reading price.
Where does the personal approach sit between the two, and how objective are the rules?