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

如何将Pine Script指标脚本的变量值传递至Python脚本或写入文本文件供Python读取?

Hey there! Let's break down your question step by step—both approaches you're considering are totally feasible, and I'll walk you through how to pull them off, plus some general methods for passing/exporting values from Pine Script to Python.

两种实现路径的可行性分析

1. 直接将数值传递至Python脚本

Pine Script doesn’t have a built-in way to call Python directly, but you can use Webhooks (or WebSockets for higher-frequency needs) to send data in real-time to a Python server. This is perfect for live trading or real-time decision logic.

How to implement it:

Step 1: Pine Script side (send data via Webhook)

Set up your indicator to send the calculated value as a JSON payload to your Python server whenever the bar updates (or on a specific condition):

//@version=5
indicator("Send Value to Python", overlay=true)

// Calculate your target indicator value
my_indicator_value = ta.sma(close, 20)

// Send data on the last bar (real-time update)
if barstate.islast
    // Format value into a JSON payload
    payload = '{"indicator_value": ' + str.tostring(my_indicator_value) + '}'
    // Replace the URL with your Python server's endpoint
    request.send(
        url="http://localhost:5000/receive-indicator",
        method=request.method.POST,
        body=payload,
        headers={"Content-Type": "application/json"}
    )

Step 2: Python side (receive data)

Use a lightweight framework like Flask to create a simple endpoint that listens for the Webhook and processes the value:

from flask import Flask, request

app = Flask(__name__)

@app.route('/receive-indicator', methods=['POST'])
def handle_indicator_data():
    data = request.get_json()
    value = data['indicator_value']
    # Insert your decision logic here
    print(f"Got indicator value from Pine Script: {value}")
    return "Data received", 200

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

Pros: Real-time data transfer, no intermediate files.
Cons: Requires your Python server to be online and accessible (use tools like ngrok if you’re testing locally and need to expose your server to TradingView).


2. 将数值写入文本文件,再由Python读取

This approach is simpler for offline analysis or if you don’t need real-time updates. Pine Script can’t write directly to your local files, but you can use a Webhook to send data to a Python script that writes the value to a text file.

How to implement it:

Pine Script side

Use the same Webhook code as above—just point it to your local Python endpoint.

Python side (write to file)

Modify the Flask endpoint to save the received value to a text file instead of processing it immediately:

from flask import Flask, request

app = Flask(__name__)

@app.route('/write-to-file', methods=['POST'])
def write_value_to_file():
    data = request.get_json()
    value = data['indicator_value']
    # Write to a text file (overwrites existing content)
    with open('pine_script_value.txt', 'w') as file:
        file.write(str(value))
    return "Value saved to file", 200

if __name__ == '__main__':
    app.run(host='127.0.0.1', port=5000)

Then, your main Python decision script can read the file periodically:

import time

while True:
    with open('pine_script_value.txt', 'r') as file:
        latest_value = float(file.read())
        # Run your decision logic here
        print(f"Current indicator value: {latest_value}")
    time.sleep(60)  # Check every minute

Pros: Low complexity, works for batch/periodic analysis.
Cons: Not real-time (depends on how often your Python script reads the file).


通用方法总结

传递变量值至Python脚本

  • Webhooks: The most common method for real-time data—works with any Python web framework (Flask, FastAPI).
  • WebSockets: For ultra-low-latency needs (use libraries like websockets in Python and a WebSocket service to bridge Pine Script and Python).
  • MQTT: If you need reliable message queuing (great for unstable networks), use an MQTT broker (like Mosquitto) and send data from Pine Script via Webhook to the broker, then subscribe with Python.

打印变量值至文本文件

  • Webhook + Python file writing: As shown above, the most reliable automated way.
  • Manual CSV export: For backtest data, use TradingView’s "Export Data" feature (right-click on the chart > Export Data) to save indicator values as a CSV, then read it with Python’s pandas library.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 19:08:11