You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

部署在GCF的Flask Webhook无法接收处理TradingView告警问题

解决GCF托管Flask Webhook无法接收TradingView告警的问题

问题核心修复

1. 函数参数错误修正

出现TypeError: webhook() takes 0 positional arguments but 1 was given是因为Google Cloud Functions要求Flask视图函数必须接收request参数,GCF会自动将请求对象传入,所以必须定义为def webhook(request),这一步你已经做对了,但还有其他隐藏问题。

2. 请求解析兼容TradingView格式

TradingView发送的Webhook可能未设置标准application/json Content-Type,导致request.get_json()解析失败。修改解析逻辑,强制读取并解析请求体:

@app.route('/', methods=['POST'])
def webhook(request):
    try:
        # 兼容TradingView可能的非标准Content-Type
        if request.is_json:
            data = request.get_json()
        else:
            import json
            data = json.loads(request.data.decode('utf-8'))
        
        ticker = data.get('ticker')
        quantity = data.get('quantity')
        action = data.get('action')
        passphrase = data.get('security_passphrase')

        if passphrase != PASS_PHRASE:
            raise ValueError("Invalid security passphrase")

        if not ticker or not quantity or not action:
            raise ValueError("Invalid TradingView alert data")
            
        side = 'BUY' if action.lower() == 'buy' else 'SELL'
            
        response = cb_create_market_order(ticker, quantity, side)
        
        # 移到try块内,确保状态码检查能执行
        if response.status_code != 200:
            response_data = response.text
            raise Exception(f"Error placing order: {response_data}")
            
        return flask.jsonify({'success': True}), 200
    
    except Exception as e:
        logger.error("Error processing trading data: %s", e, exc_info=True)
        return flask.jsonify({'error': str(e)}), 500

3. 代码逻辑漏洞修复

原代码中response.status_code的判断位于try-except块外部,由于try块内已有return或raise语句,这段代码永远不会被执行。必须将其移到try块内部,在调用下单接口后立即检查。

额外验证步骤

检查TradingWebhook配置

  • 确认URL是GCF函数的完整触发地址(格式:https://<区域>-<项目ID>.cloudfunctions.net/<函数名>)
  • 告警的Message字段必须严格填写指定JSON,无多余换行、空格或注释
  • 若TradingView有Send as JSON开关,确保已启用

排查GCF日志

  • 若GCF日志中无TradingView的请求记录:说明TradingView未发送请求,检查URL正确性、是否有网络拦截(比如GCF的访问权限设置)
  • 若有请求记录但返回错误:根据日志中的错误信息定位问题(比如解析失败、密钥错误等)

模拟请求测试

用curl模拟TradingView请求,验证函数逻辑:

curl -X POST <你的GCF函数URL> \
  -H "Content-Type: application/json" \
  -d '{
    "ticker": "SOL-USD",
    "quantity": "0.005",
    "action": "buy",
    "security_passphrase": "PASSTHISALERT"
  }'

内容的提问来源于stack exchange,提问作者Acerb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 13:16:14