如何在 TradingView 中编写指标(附示例和交易设置)
本文将指导您如何在 TradingView 中编写指标并逐步实现。此外,本文还将涵盖有关安全性和连接交易所的重要事项。.

如何在 TradingView 中编写指标(附示例和交易设置)

本文将教您如何在 TradingView 中编写指标,并使用 PineScript 将其连接到交易所。文章还将讨论实现细节、安全性以及安全有效交易的技术技巧。.
0 股票
0
0
0
0

 

如何在 TradingView 中编写指标和策略并将其连接到交易所?

这篇全面而实用的指南将一步步讲解如何使用 PineScript 5 编写指标和策略,如何在 TradingView 中创建 Webhook 警报,如何使用 Flask 和 ccxt 设置安全的 Webhook 服务器,以及如何通过技术/安全技巧和位置选择来降低延迟。本文适用于交易员、开发人员和运维团队。.

 

第一部分——PineScript 入门(版本 5)

PineScript 5 版本新增了多项功能和高级特性。入门指南:

  • 选择版本://@version=5 使用。.
  • 两种主要类型: 指标 (用于图表显示和信号生成) 战略 (用于回测和执行假设订单)。.
  • 输入变量: 从函数 输入 用于用户可修改的参数。.
  • 警报:警报条件 使用它可以在 TradingView 中定义可用的报警条件。.

 

简单指标示例(EMA 交叉 + RSI 滤波器)

//@version=5
indicator("EMA Crossover + RSI Filter", overlay=true)

// Inputs
shortLen = input.int(9, "EMA Short Length")
longLen  = input.int(21, "EMA Long Length")
rsiLen   = input.int(14, "RSI Length")
rsiThresh = input.int(50, "RSI Threshold")

// Price
price = close

// Indicators
emaShort = ta.ema(price, shortLen)
emaLong  = ta.ema(price, longLen)
rsi = ta.rsi(price, rsiLen)

// Signals
bull = ta.crossover(emaShort, emaLong) and rsi > rsiThresh
bear = ta.crossunder(emaShort, emaLong) and rsi < rsiThresh

plot(emaShort, color=color.blue)
plot(emaLong, color=color.orange)
plotshape(bull, title="Long", location=location.belowbar, color=color.green, style=shape.labelup, text="LONG")
plotshape(bear, title="Short", location=location.abovebar, color=color.red, style=shape.labeldown, text="SHORT")

// Alerts
alertcondition(bull, title="Long Alert", message="LONG_SIGNAL")
alertcondition(bear, title="Short Alert", message="SHORT_SIGNAL")

实用技巧: 报警信息应采用 JSON 格式或特定结构,以便 Web 服务器能够轻松解析;例如: {"signal":"LONG","symbol":"BTCUSDT","timeframe":"1m"}.

 

风险管理的简单策略示例

//@version=5
strategy("EMA Crossover Strategy", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=1)

// inputs ...
// (same indicators as above)
shortLen = input.int(9, "EMA Short Length")
longLen  = input.int(21, "EMA Long Length")
rsiLen   = input.int(14, "RSI Length")
rsiThresh = input.int(50, "RSI Threshold")

price = close
emaShort = ta.ema(price, shortLen)
emaLong  = ta.ema(price, longLen)
rsi = ta.rsi(price, rsiLen)

bull = ta.crossover(emaShort, emaLong) and rsi > rsiThresh
bear = ta.crossunder(emaShort, emaLong) and rsi < rsiThresh

if bull
    strategy.entry("Long", strategy.long)
if bear
    strategy.entry("Short", strategy.short)

// Example Stop Loss / Take Profit
strategy.exit("Exit Long", from_entry="Long", loss=100, profit=200)
strategy.exit("Exit Short", from_entry="Short", loss=100, profit=200)

解释: 为了更准确地进行回测 战略 使用和参数 止损获利了结 并调整位置大小。.

 

第二部分——TradingView 中的警报和 Webhook 结构

在图表中添加指标或策略后,从“提醒”菜单创建新提醒。在设置中:

  • 警报类型: 选项 Webhook URL 选择并输入您的服务器地址(例如: https://trade.example.com/webhook).
  • 信息: 使用标准 JSON;包含字段 象征行动价格大体时间UUID时间戳.

报警信息示例:

{"symbol":"BTCUSDT","action":"LONG","price":"${close}","timeframe":"1m","strategy":"EMA_CROSS_V1"}

 

第三部分——设置网络服务器以接收警报并向交易所发送订单

拟建架构:

  • TradingView(提醒)→ HTTPS Webhook(NGINX + Flask/Node)→ 机器人(业务逻辑)→ 交易所 API(ccxt 或 SDK)

安装必备组件(以 Ubuntu 为例)

sudo apt update
sudo apt install -y python3 python3-venv python3-pip
python3 -m venv venv
source venv/bin/activate
pip install flask ccxt

使用 Flask 和 ccxt 的示例 app.py

from flask import Flask, request, jsonify
import ccxt, os, hmac, hashlib, time

app = Flask(__name__)

API_KEY = os.getenv("EXCHANGE_API_KEY")
API_SECRET = os.getenv("EXCHANGE_API_SECRET")

exchange = ccxt.binance({
    'apiKey': API_KEY,
    'secret': API_SECRET,
    'enableRateLimit': True,
})

@app.route('/webhook', methods=['POST'])
def webhook():
    data = request.json
    # simple validation: check data presence (use HMAC in production)
    if not data:
        return jsonify({"error":"no data"}),400

    symbol = data.get("symbol")
    action = data.get("action")
    qty = data.get("qty", 0.001)

    try:
        if action == "LONG":
            order = exchange.create_market_buy_order(symbol, qty)
        elif action == "SHORT":
            order = exchange.create_market_sell_order(symbol, qty)
        else:
            return jsonify({"error":"unknown action"}),400
        return jsonify(order)
    except Exception as e:
        return jsonify({"error":str(e)}),500

 

第四部分——安全服务器部署(Linux/Docker/systemd)

建议:使用 Docker Compose,nginx 作为反向代理,certbot 用于 TLS。.

docker-compose.yml 示例

version: '3.8'
services:
  app:
    build: .
    restart: always
    environment:
      - EXCHANGE_API_KEY
      - EXCHANGE_API_SECRET
  nginx:
    image: nginx:stable
    volumes:
      - ./nginx/conf.d:/etc/nginx/conf.d
      - ./certs:/etc/letsencrypt
    ports:
      - "80:80"
      - "443:443"

无需 Docker 即可运行的示例 systemd 单元

[Unit]
Description=Trading Webhook Bot
After=network.target

[Service]
User=trade
WorkingDirectory=/home/trade/app
Environment=EXCHANGE_API_KEY=your_key_here
Environment=EXCHANGE_API_SECRET=your_secret_here
ExecStart=/home/trade/venv/bin/gunicorn -w 4 -b 127.0.0.1:5000 app:app
Restart=always

[Install]
WantedBy=multi-user.target

管理命令示例:

sudo systemctl daemon-reload
sudo systemctl enable --now tradebot.service
sudo ufw allow 443/tcp
sudo ufw allow 80/tcp

 

第五部分——安全与稳定提示

  • API密钥的安全存储: 从环境变量中,文件 chmod 600 或者使用 Secret Manager。.
  • TLS: 使用有效的证书(certbot + nginx)进行HTTPS连接。.
  • 消息确认: 使用 HMAC-SHA256 验证传入的 TradingView 消息。.
  • 限制和重试: 实现速率限制和重试/退避算法。.
  • 监控和日志记录: 使用 Prometheus + Grafana 或 ELK 来监测健康状况和响应时间。.
  • 抵御攻击: 对于公共端点,请使用 Fail2Ban、iptables 和防 DDoS 或 CDN 服务。.

 

第六节——回测、优化和前向测试

  • 回测: 从函数 战略。* 使用 Pine 进行历史分析,但要注意 Pine 的参数限制。.
  • 优化: 手动或使用外部脚本测试参数(例如,生成具有不同参数的多个图表)。.
  • 前向测试: 回测之后,务必在模拟账户或低延迟VPS上使用小额交易量进行测试。.
  • 滑移和延迟测量: 记录并分析 webhook 的接收时间和交易所订单执行的时间。.

 

第 7 节 — 比较用于交易的数据中心位置

数据中心的位置对于高频策略的成功至关重要,每一毫秒都可能决定成败。位置选择应基于交换机和 BGP 路由。.

  • 欧洲(法兰克福、阿姆斯特丹): 适用于欧洲交易所和部分流动性基金。.
  • 美国东部(纽约州、新泽西州): 适用于 Coinbase 及纽约相关市场。.
  • 亚洲(新加坡、东京、香港): 适用于币安亚洲、OKX 和亚洲市场。.

如果您主要在币安或亚洲交易所进行交易,那么新加坡或东京的 VPS 更合适;对于美国交易所,纽约/新泽西的 VPS 会更合适。.

 

第 8 节 — 交易推荐服务器配置

用于交易的VPS(低延迟)

  • CPU:2-4个高频虚拟CPU
  • 内存:4-8 GB
  • 存储:NVMe SSD 50-100GB
  • 网络:低延迟/1Gbps,必要时支持BGP/任播

重型计算/回测服务器

  • CPU:8 个以上虚拟 CPU
  • 内存:32GB以上
  • 存储:NVMe 1TB
  • GPU:如果需要使用机器学习/人工智能来处理模型

此外,使用防 DDoS、专用网络和防火墙管理等安全功能来提高服务的稳定性和安全性。.

 

第 9 节——降低交易自动化风险的实用技巧

  • 止损和最大风险敞口: 为每笔订单设置止损价和最大交易额。.
  • API账户状态: 查看限制和 KYC 状态。.
  • 断路器: 如果错误率增加或延迟显著增加,请停止机器人运行。.
  • 健康监测: 监控正常运行时间、延迟和填充状态,并设置警报以便支持团队使用。.

 

结论

本指南涵盖了从使用 Pine Script(版本 5)编写指标和策略、在 TradingView 中创建 webhook 警报、使用 Flask/ccxt 设置安全的 webhook 服务器,到重要的安全注意事项、选择数据中心位置以及推荐的服务器配置等主要步骤。.

如果您需要低延迟 VPS、防 DDoS 服务器或用于繁重处理的图形服务器服务等基础设施解决方案,我们公司在全球 85 多个地点提供这些设施,并可以设置和优化您的基础设施。.

 

常见问题解答

您可能也喜欢