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

TradingView自动交易alert_message配置input.string后失效求助

问题:动态拼接的alert_message移至input.string后自动交易失效

我在Pine Script策略中遇到一个问题:直接在strategy.order()的alert_message参数里动态拼接字符串时,自动交易可以正常运行,但把这段字符串移到input.string的默认值后,自动交易就失效了。

可正常运行的代码:

if entrycondition
   strategy.order("Long", strategy.long, qty=entry_size, limit=r_close, comment="Entry", alert_message='TVM:{"exchange":"binance-futures","account":"*","symbol":"ADA/USDT","type":"market","side":"buy","amount":'+str.tostring(entry_size)+',"token":"1234"}:MVT')

失效的代码:

useentryalert    = input(defval=true, title="Use Entry Alert", group="Alert Messages")
entrystring      = input.string(title="Entry Alert Message", defval='TVM:{"exchange":"binance-futures","account":"*","symbol":"ADA/USDT","type":"market","side":"buy","amount":'+str.tostring(entry_size)+',"token":"1234"}:MVT', confirm=false, group="Alert Messages")

if entry_condition and useentryalert
    strategy.order("Long", strategy.long, qty=entry_size, limit=close, comment="Entry", alert_message=entrystring)

我推测问题出在str.tostring(entry_size)的处理上,但不知道怎么解决,求帮助。


原因分析

input.string的默认值是静态字符串,在脚本初始化阶段就会被解析,而entry_size是动态变量(可能随行情或策略逻辑变化),无法在初始化阶段被正确解析成对应数值。这就导致entrystring里的str.tostring(entry_size)不会被执行,而是被当作普通字符串字面量保留,最终传递给alert的消息里不会包含实际的entry_size数值,导致自动交易系统无法识别有效指令。

解决方案

方案1:保留输入框可配置性,动态替换占位符

先在input.string中定义带占位符的静态模板,在触发订单时再替换为实际变量值:

useentryalert    = input(defval=true, title="Use Entry Alert", group="Alert Messages")
// 用{amount}作为动态数值的占位符
entrytemplate   = input.string(title="Entry Alert Message Template", defval='TVM:{"exchange":"binance-futures","account":"*","symbol":"ADA/USDT","type":"market","side":"buy","amount":{amount},"token":"1234"}:MVT', confirm=false, group="Alert Messages")

if entry_condition and useentryalert
    // 动态替换占位符为当前entry_size的数值
    entrystring = str.replace(entrytemplate, "{amount}", str.tostring(entry_size))
    strategy.order("Long", strategy.long, qty=entry_size, limit=close, comment="Entry", alert_message=entrystring)

方案2:直接在逻辑中动态拼接(无需用户修改模板)

如果不需要让用户自定义alert消息模板,可直接在订单触发时拼接字符串,跳过input.string的静态解析限制:

useentryalert    = input(defval=true, title="Use Entry Alert", group="Alert Messages")

if entry_condition and useentryalert
    entrystring = 'TVM:{"exchange":"binance-futures","account":"*","symbol":"ADA/USDT","type":"market","side":"buy","amount":'+str.tostring(entry_size)+',"token":"1234"}:MVT'
    strategy.order("Long", strategy.long, qty=entry_size, limit=close, comment="Entry", alert_message=entrystring)

两种方案都能保证entry_size的实时数值被正确插入到alert消息中,让自动交易系统识别有效指令。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 12:50:27