首页 > 编程问答 >我如何结合这个 pinescript 程序的 2 个指标

我如何结合这个 pinescript 程序的 2 个指标

时间:2024-07-28 15:20:54浏览次数:8  
标签:python pine-script tradingview-api trading

我正在尝试将这两个指标结合起来。 1 个指标用于期权行权,第二个指标用于突破线。

编译这些 2 时出现函数错误

//指标 1:

//@version=5
   indicator("All-in-One Multi-Indicator Options Strategy",shorttitle = "All-in-One", overlay=false)


// Input for Index and Expiry Date
   spot = input.string("BANKNIFTY", title = "Spot Symbol", options = ["NIFTY", "BANKNIFTY", "FINNIFTY", "MIDCPNIFTY"], group = "Index")

   tooltip_day = "Enter the day of the expiry. Add 0 in front if the day is a single digit. For    example: 05 instead of 5"
   tooltip_month = "Enter the month of the expiry. Add 0 in front if the month is a single digit.   For example: 06 instead of 6"
   tooltip_year = "Enter the year of the expiry. Use the last two digits of the year. For example: 24 instead of 2024"

   _day = input.string("24", title = "Expiry Day", tooltip = tooltip_day, group="Expiry Date")
   _month = input.string("07", title = "Expiry Month", tooltip = tooltip_month, group="Expiry Date")
   _year = input.string("24", title = "Expiry Year", tooltip = tooltip_year, group="Expiry Date")

// Input for Strikes
   tooltip_ = "You can select any Strike, and choose to include both strikes or just one"
   strike_ce = input.int(52300, "Call Strike", tooltip = tooltip_, group = "Select Strike")
   strike_pe = input.int(52300, "Put Strike", tooltip = tooltip_, group = "Select Strike")

// Option to include both strikes
   strike_choice = input.string("Combined", title = "Select Strike", options = ["Combined", "Only    Call", "Only Put"], group = "Select Strike")

// Generate symbols for Call and Put options
   var string symbol_CE = spot + _year + _month + _day + "C" + str.tostring(strike_ce)
   var string symbol_PE = spot + _year + _month + _day + "P" + str.tostring(strike_pe)

// Request security data for both Call and Put options
   [call_open, call_high, call_low, call_close] = request.security(symbol_CE, timeframe.period,   [open, high, low, close])
   [put_open, put_high, put_low, put_close] = request.security(symbol_PE, timeframe.period, [open, high, low, close])

   call_volume = request.security( symbol_CE, timeframe.period , volume ) 
   put_volume = request.security( symbol_PE, timeframe.period , volume ) 

   var float combined_open = 0
   var float combined_high = 0
   var float combined_low = 0
   var float combined_close = 0
   var float combined_vol = 0

// Calculate combined premium based on strike choice
   if strike_choice == "Combined"
    combined_open := call_open + put_open
    combined_close := call_close + put_close
    combined_high := math.max(combined_open, combined_close)
    combined_low := math.min(combined_open, combined_close)
    combined_vol := call_volume + put_volume

   else if strike_choice == "Only Call"
       combined_open := call_open
       combined_close := call_close
       combined_high := call_high
       combined_low := call_low
       combined_vol := call_volume

else
    combined_open := put_open
    combined_close := put_close
    combined_high := put_high
    combined_low := put_low
    combined_vol := put_volume

// Plot combined premium as a candle
plotcandle(combined_open, combined_high, combined_low, combined_close, title = "Combined Premium", color = combined_close > combined_open ? color.green : color.red)

// Indicator selection
use_ema_crossover = input.bool(true, title = "Use EMA Crossover", group = "Indicators")
use_supertrend = input.bool(false, title = "Use Supertrend", group = "Indicators")
use_vwap = input.bool(false, title = "Use VWAP", group = "Indicators")
use_rsi = input.bool(false, title = "Use RSI", group = "Indicators")
use_sma = input.bool(false, title = "Use SMA", group = "Indicators")

pine_supertrend_value(factor, atrPeriod) =>
    src = combined_close
    atr = ta.atr(atrPeriod)
    upperBand = src + factor * atr
    lowerBand = src - factor * atr
    prevLowerBand = nz(lowerBand[1])
    prevUpperBand = nz(upperBand[1])

    lowerBand := lowerBand > prevLowerBand or combined_close[1] < prevLowerBand ? lowerBand : prevLowerBand
    upperBand := upperBand < prevUpperBand or combined_close[1] > prevUpperBand ? upperBand : prevUpperBand
    int _direction = na
    float superTrend = na
    prevSuperTrend = superTrend[1]
    if na(atr[1])
        _direction := 1
    else if prevSuperTrend == prevUpperBand
        _direction := combined_close > upperBand ? -1 : 1
    else
        _direction := combined_close < lowerBand ? 1 : -1
    superTrend := _direction == -1 ? lowerBand : upperBand
    superTrend

pine_supertrend_dir(factor, atrPeriod) =>
    src = combined_close
    atr = ta.atr(atrPeriod)
    upperBand = src + factor * atr
    lowerBand = src - factor * atr
    prevLowerBand = nz(lowerBand[1])
    prevUpperBand = nz(upperBand[1])

    lowerBand := lowerBand > prevLowerBand or combined_close[1] < prevLowerBand ? lowerBand : prevLowerBand
    upperBand := upperBand < prevUpperBand or combined_close[1] > prevUpperBand ? upperBand : prevUpperBand
    int _direction = na
    float superTrend = na
    prevSuperTrend = superTrend[1]
    if na(atr[1])
        _direction := 1
    else if prevSuperTrend == prevUpperBand
        _direction := combined_close > upperBand ? -1 : 1
    else
        _direction := combined_close < lowerBand ? 1 : -1
    superTrend := _direction == -1 ? lowerBand : upperBand
    _direction


// Input for EMA lengths
fastLength = input.int(7, 'Fast EMA Length', group = "EMA")
slowLength = input.int(12, 'Slow EMA Length', group = "EMA")

// Input for SuperTrend
atrLength = input.int(7, 'ATR Length', group = "SuperTrend")
fac = input.float(2, 'Factor', group = "SuperTrend")

// Input for RSI
rsi_length = input.int(7, 'Length', group="RSI")
rsi_ob_level = input.int(80, 'Overbought', group="RSI")
rsi_os_level = input.int(20, 'Oversold', group="RSI")

// Input for SMA
sma_length = input.int(7, 'SMA Length', group = "SMA")


var float fast_ema = na 
var float slow_ema = na 
var float supertrend = na 
var int direction = na 
var float rsi_val = na 
var float sma_val = na 

var float sumPriceVolume = na
var float sumVolume = na
var float vwap = na


// Fast EMA
if use_ema_crossover
    fast_ema := ta.ema(combined_close, fastLength)
    slow_ema := ta.ema(combined_close, slowLength)

// Supertrend
if use_supertrend
    supertrend := pine_supertrend_value( fac, atrLength)
    direction := pine_supertrend_dir( fac, atrLength)

// VWAP
if use_vwap
    if (dayofweek != dayofweek[1])  
        sumPriceVolume := na
        sumVolume := na
        vwap := na

    sumPriceVolume += combined_close * combined_vol
    sumVolume += combined_vol
    vwap := sumPriceVolume / sumVolume

// RSI
if use_rsi
    rsi_val := ta.rsi(combined_close, rsi_length)

// SMA
if use_sma
    sma_val := ta.sma(combined_close, sma_length)

plot(fast_ema, title='Fast EMA', color=color.blue, linewidth=2)
plot(slow_ema, title='Slow EMA', color=color.yellow, linewidth=2)
plot(direction < 0 ? supertrend : na, "Up direction", color = color.green, style=plot.style_linebr)
plot(direction > 0 ? supertrend : na, "Down direction", color = color.red, style=plot.style_linebr)
plot(vwap, title='VWAP', color=color.purple, linewidth=2)
plot(sma_val, title='SMA', color=color.maroon, linewidth=2)

// Define buy and sell conditions based on selected indicators
var bool buy = false
var bool sell = false
var int buyC = 0
var int sellC = 0

if dayofweek != dayofweek[1]
    buyC := 0
    sellC := 0

if use_ema_crossover
    buy := ( ta.crossover(fast_ema, slow_ema) ) and buyC == 0
    sell := ( ta.crossunder(fast_ema, slow_ema) ) and sellC == 0

if use_vwap
    buy := ( buy ? buy and ta.crossover(combined_close, vwap) : ta.crossover(combined_close, vwap) ) and buyC == 0
    sell := ( sell ? sell and ta.crossunder(combined_close, vwap) : ta.crossunder(combined_close, vwap) ) and sellC == 0

if use_rsi
    buy := ( buy ? buy and ta.crossover(rsi_val, rsi_ob_level) : ta.crossover(rsi_val, rsi_ob_level) ) and buyC == 0
    sell := ( sell ? sell and ta.crossunder(rsi_val, rsi_os_level) : ta.crossunder(rsi_val, rsi_os_level) ) and sellC == 0

if use_sma
    buy := ( buy ? buy and ta.crossover(combined_close, sma_val) : ta.crossover(combined_close, sma_val) ) and buyC == 0
    sell := ( sell ? sell and ta.crossunder(combined_close, sma_val) : ta.crossunder(combined_close, sma_val) ) and sellC == 0

if use_supertrend
    buy := ( buy ? direction == -1 : direction == -1 and direction[1] == 1 ) and buyC == 0
    sell := ( sell ? direction == 1 : direction == 1 and direction[1] == -1 ) and sellC == 0

if buy 
    buyC := 1
    sellC := 0

if sell 
    sellC := 1
    buyC := 0

// Plot buy and sell signals
plotshape(buy, title = "Buy", text = 'Buy', style = shape.labeldown, location = location.top, color= color.green, textcolor = color.white, size = size.small)
plotshape(sell, title = "Sell", text = 'Sell', style = shape.labelup, location = location.bottom, color= color.red, textcolor = color.white, size = size.small)

// Alert conditions
alertcondition(buy, "Buy", "Buy")
alertcondition(sell, "Sell", "Sell")

//Indicator 2:

//@version=2
study("Breakout",overlay=true)
res1 = input(title="Close Time Frame", type=resolution, defval="D")
cld=security(tickerid, res1, close[1])
opd=security(tickerid,res1, open[1])
tu=(cld +opd)/2 
plot( tu, "Breakout",color=black ,style=line,linewidth=2,transp=0) 

我已将代码 1 粘贴到另一个下方。我已将代码 1 粘贴到另一个代码下面。我已将代码 1 粘贴到另一个代码下面。


两个指标代码合并并修复了错误:

//@version=5
indicator("All-in-One Multi-Indicator Options Strategy",shorttitle = "All-in-One", overlay=true)

// Input for Index and Expiry Date
spot = input.string("BANKNIFTY", title = "Spot Symbol", options = ["NIFTY", "BANKNIFTY", "FINNIFTY", "MIDCPNIFTY"], group = "Index")

tooltip_day = "Enter the day of the expiry. Add 0 in front if the day is a single digit. For    example: 05 instead of 5"
tooltip_month = "Enter the month of the expiry. Add 0 in front if the month is a single digit.   For example: 06 instead of 6"
tooltip_year = "Enter the year of the expiry. Use the last two digits of the year. For example: 24 instead of 2024"

_day = input.string("24", title = "Expiry Day", tooltip = tooltip_day, group="Expiry Date")
_month = input.string("07", title = "Expiry Month", tooltip = tooltip_month, group="Expiry Date")
_year = input.string("24", title = "Expiry Year", tooltip = tooltip_year, group="Expiry Date")

// Input for Strikes
tooltip_ = "You can select any Strike, and choose to include both strikes or just one"
strike_ce = input.int(52300, "Call Strike", tooltip = tooltip_, group = "Select Strike")
strike_pe = input.int(52300, "Put Strike", tooltip = tooltip_, group = "Select Strike")

// Option to include both strikes
strike_choice = input.string("Combined", title = "Select Strike", options = ["Combined", "Only    Call", "Only Put"], group = "Select Strike")

// Generate symbols for Call and Put options
var string symbol_CE = spot + _year + _month + _day + "C" + str.tostring(strike_ce)
var string symbol_PE = spot + _year + _month + _day + "P" + str.tostring(strike_pe)

// Request security data for both Call and Put options
[call_open, call_high, call_low, call_close] = request.security(symbol_CE, timeframe.period,   [open, high, low, close])
[put_open, put_high, put_low, put_close] = request.security(symbol_PE, timeframe.period, [open, high, low, close])

call_volume = request.security( symbol_CE, timeframe.period , volume ) 
put_volume = request.security( symbol_PE, timeframe.period , volume ) 

var float combined_open = 0
var float combined_high = 0
var float combined_low = 0
var float combined_close = 0
var float combined_vol = 0

// Calculate combined premium based on strike choice
if strike_choice == "Combined"
    combined_open := call_open + put_open
    combined_close := call_close + put_close
    combined_high := math.max(combined_open, combined_close)
    combined_low := math.min(combined_open, combined_close)
    combined_vol := call_volume + put_volume

else if strike_choice == "Only Call"
    combined_open := call_open
    combined_close := call_close
    combined_high := call_high
    combined_low := call_low
    combined_vol := call_volume

else
    combined_open := put_open
    combined_close := put_close
    combined_high := put_high
    combined_low := put_low
    combined_vol := put_volume

// Plot combined premium as a candle
plotcandle(combined_open, combined_high, combined_low, combined_close, title = "Combined Premium", color = combined_close > combined_open ? color.green : color.red)

// Indicator selection
use_ema_crossover = input.bool(true, title = "Use EMA Crossover", group = "Indicators")
use_supertrend = input.bool(false, title = "Use Supertrend", group = "Indicators")
use_vwap = input.bool(false, title = "Use VWAP", group = "Indicators")
use_rsi = input.bool(false, title = "Use RSI", group = "Indicators")
use_sma = input.bool(false, title = "Use SMA", group = "Indicators")

pine_supertrend_value(factor, atrPeriod) =>
    src = combined_close
    atr = ta.atr(atrPeriod)
    upperBand = src + factor * atr
    lowerBand = src - factor * atr
    prevLowerBand = nz(lowerBand[1])
    prevUpperBand = nz(upperBand[1])

    lowerBand := lowerBand > prevLowerBand or combined_close[1] < prevLowerBand ? lowerBand : prevLowerBand
    upperBand := upperBand < prevUpperBand or combined_close[1] > prevUpperBand ? upperBand : prevUpperBand
    int _direction = na
    float superTrend = na
    prevSuperTrend = superTrend[1]
    if na(atr[1])
        _direction := 1
    else if prevSuperTrend == prevUpperBand
        _direction := combined_close > upperBand ? -1 : 1
    else
        _direction := combined_close < lowerBand ? 1 : -1
    superTrend := _direction == -1 ? lowerBand : upperBand
    superTrend

pine_supertrend_dir(factor, atrPeriod) =>
    src = combined_close
    atr = ta.atr(atrPeriod)
    upperBand = src + factor * atr
    lowerBand = src - factor * atr
    prevLowerBand = nz(lowerBand[1])
    prevUpperBand = nz(upperBand[1])

    lowerBand := lowerBand > prevLowerBand or combined_close[1] < prevLowerBand ? lowerBand : prevLowerBand
    upperBand := upperBand < prevUpperBand or combined_close[1] > prevUpperBand ? upperBand : prevUpperBand
    int _direction = na
    float superTrend = na
    prevSuperTrend = superTrend[1]
    if na(atr[1])
        _direction := 1
    else if prevSuperTrend == prevUpperBand
        _direction := combined_close > upperBand ? -1 : 1
    else
        _direction := combined_close < lowerBand ? 1 : -1
    superTrend := _direction == -1 ? lowerBand : upperBand
    _direction


// Input for EMA lengths
fastLength = input.int(7, 'Fast EMA Length', group = "EMA")
slowLength = input.int(12, 'Slow EMA Length', group = "EMA")

// Input for SuperTrend
atrLength = input.int(7, 'ATR Length', group = "SuperTrend")
fac = input.float(2, 'Factor', group = "SuperTrend")

// Input for RSI
rsi_length = input.int(7, 'Length', group="RSI")
rsi_ob_level = input.int(80, 'Overbought', group="RSI")
rsi_os_level = input.int(20, 'Oversold', group="RSI")

// Input for SMA
sma_length = input.int(7, 'SMA Length', group = "SMA")


var float fast_ema = na 
var float slow_ema = na 
var float supertrend = na 
var int direction = na 
var float rsi_val = na 
var float sma_val = na 

var float sumPriceVolume = na
var float sumVolume = na
var float vwap = na


// Fast EMA
if use_ema_crossover
    fast_ema := ta.ema(combined_close, fastLength)
    slow_ema := ta.ema(combined_close, slowLength)

// Supertrend
if use_supertrend
    supertrend := pine_supertrend_value( fac, atrLength)
    direction := pine_supertrend_dir( fac, atrLength)

// VWAP
if use_vwap
    if (dayofweek != dayofweek[1])  
        sumPriceVolume := na
        sumVolume := na
        vwap := na

    sumPriceVolume += combined_close * combined_vol
    sumVolume += combined_vol
    vwap := sumPriceVolume / sumVolume

// RSI
if use_rsi
    rsi_val := ta.rsi(combined_close, rsi_length)

// SMA
if use_sma
    sma_val := ta.sma(combined_close, sma_length)

plot(fast_ema, title='Fast EMA', color=color.blue, linewidth=2)
plot(slow_ema, title='Slow EMA', color=color.yellow, linewidth=2)
plot(direction < 0 ? supertrend : na, "Up direction", color = color.green, style=plot.style_linebr)
plot(direction > 0 ? supertrend : na, "Down direction", color = color.red, style=plot.style_linebr)
plot(vwap, title='VWAP', color=color.purple, linewidth=2)
plot(sma_val, title='SMA', color=color.maroon, linewidth=2)

// Define buy and sell conditions based on selected indicators
var bool buy = false
var bool sell = false
var int buyC = 0
var int sellC = 0

if dayofweek != dayofweek[1]
    buyC := 0
    sellC := 0

if use_ema_crossover
    buy := ( ta.crossover(fast_ema, slow_ema) ) and buyC == 0
    sell := ( ta.crossunder(fast_ema, slow_ema) ) and sellC == 0

if use_vwap
    buy := ( buy ? buy and ta.crossover(combined_close, vwap) : ta.crossover(combined_close, vwap) ) and buyC == 0
    sell := ( sell ? sell and ta.crossunder(combined_close, vwap) : ta.crossunder(combined_close, vwap) ) and sellC == 0

if use_rsi
    buy := ( buy ? buy and ta.crossover(rsi_val, rsi_ob_level) : ta.crossover(rsi_val, rsi_ob_level) ) and buyC == 0
    sell := ( sell ? sell and ta.crossunder(rsi_val, rsi_os_level) : ta.crossunder(rsi_val, rsi_os_level) ) and sellC == 0

if use_sma
    buy := ( buy ? buy and ta.crossover(combined_close, sma_val) : ta.crossover(combined_close, sma_val) ) and buyC == 0
    sell := ( sell ? sell and ta.crossunder(combined_close, sma_val) : ta.crossunder(combined_close, sma_val) ) and sellC == 0

if use_supertrend
    buy := ( buy ? direction == -1 : direction == -1 and direction[1] == 1 ) and buyC == 0
    sell := ( sell ? direction == 1 : direction == 1 and direction[1] == -1 ) and sellC == 0

if buy 
    buyC := 1
    sellC := 0

if sell 
    sellC := 1
    buyC := 0

// Plot buy and sell signals
plotshape(buy, title = "Buy", text = 'Buy', style = shape.labeldown, location = location.top, color= color.green, textcolor = color.white, size = size.small)
plotshape(sell, title = "Sell", text = 'Sell', style = shape.labelup, location = location.bottom, color= color.red, textcolor = color.white, size = size.small)

// Alert conditions
alertcondition(buy, "Buy", "Buy")
alertcondition(sell, "Sell", "Sell")

// *** Indicator 2: Breakout ***
res1 = input(title="Close Time Frame", type=resolution, defval="D")
cld = security(syminfo.tickerid, res1, close[1])
opd = security(syminfo.tickerid, res1, open[1])
tu = (cld + opd) / 2 
plot(tu, "Breakout", color=color.black, style=plot.style_line, linewidth=2, transp=0) 

主要修改:

  1. 合并代码: 将第二个指标的代码直接放在第一个指标代码的末尾。
  2. 修复 security 函数错误: 在第二个指标中,将 tickerid 替换为 syminfo.tickerid 。这是因为在 Pine Script 的较新版本中, tickerid 已被弃用,需要使用 syminfo.tickerid 来获取当前图表交易对的信息。
  3. 调整 overlay 参数: 将第一个指标的 overlay 参数设置为 true ,以便两个指标都显示在主图表窗口中。

现在,这个合并的代码应该可以正常工作,并将两个指标的信号都显示在图表上。

标签:python,pine-script,tradingview-api,trading
From: 78802093

相关文章

  • 如何在 Python 中从 Milesight TrafficX 摄像头、Post(MQTT、TCP/IP、HTTP) 获取数据?
    你好,祝你度过愉快的一天或一夜,我有这个MilesightTrafficX摄像头已启动并正在运行,仪表板中有一个名为POST的设置,您可以在下图中看到:我想要的是知道如何设置这些设置(基于实际上我的意思是)能够在我的Python代码中接收数据。无论协议如何,数据都将如下所示:......
  • 如何循环使用按钮输入,在python中的不同选项之间循环?
    我有一个循环,它采用三路开关输入并在相机开机时选择一个选项:#SetGPIOinputswitchColorOne=pyb.Pin("P9",pyb.Pin.IN,pyb.Pin.PULL_UP)switchColorTwo=pyb.Pin("P7",pyb.Pin.IN,pyb.Pin.PULL_UP)#SetcolorpalletebyswitchifswitchColorOne.value()==0:......
  • SSL 证书验证失败 - 雅虎财经 API - Python
    我正在尝试从雅虎财经获取数据,但收到SSL错误。代码如下:importrequestsresponse=requests.get("https://query1.finance.yahoo.com/v8/finance/chart/META",verify=True)print(response.status_code)出现以下错误:urllib3.exceptions.SSLError:[SSL:CERTIFICATE_......
  • 【学习笔记】Matlab和python双语言的学习(熵权法)
    提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档文章目录前言一、熵权法的基本概念二、熵权法的基本步骤1、构建决策矩阵2、数据标准化3、计算指标的比重4、计算信息熵5、计算权重6、计算综合得分三、代码实现----Matlab四、代码实现----python总结......
  • 【python】网络通信编程例子
    以下是一个简单的Python示例,展示了如何在Linux下使用套接字进行基本的网络通信,包括创建服务器和客户端。服务器端代码importsocket#创建一个IPv4TCP套接字server_socket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)#绑定服务器地址和端口server_addr......
  • 如何将Python版本从3.9降级到3.7?
    我正在开发RaspberryPi。这些是我的操作系统信息:pi@raspberrypi:~$uname-marmv7lpi@raspberrypi:~$cat/etc/os-releasePRETTY_NAME="RaspbianGNU/Linux11(bullseye)"NAME="RaspbianGNU/Linux"VERSION_ID="11"VERSION="11(bullseye)......
  • Python终端输出彩色字符方法
    colorama是一个python专门用来在控制台、命令行输出彩色文字的模块,完全兼容linux和windows各个版本。 1.Python3.x中安装colorama模块: pipinstallcolorama'''可用格式常数:【颜色RED,GREEN都需要大写】Fore:BLACK,RED,GREEN,YELLOW,BLUE,MAGENTA,CYAN,WHI......
  • 我无法安装 pygame 模块,所以我尝试观看视频,它告诉我这样做。在那个视频中他得到了 pyt
    c:\User\admin>piplistSyntaxError:unexpectedcharacterafterlinecontinuationcharacter我试图获取python模块列表,但出现语法错误出现SyntaxError:unexpectedcharacterafterlinecontinuationcharacter错误是因为你的用户名中包含一个特殊字符......
  • python第五节--conda命令
    这里写自定义目录标题基本命令环境管理包管理环境文件环境变量Conda配置高级操作常见问题基本命令检查Conda版本:conda--version更新Conda:condaupdateconda环境管理创建新环境:condacreate--namemyenv创建包含特定Python版本的新环境:conda......
  • 如何使用python向另一台计算机发送请求
    基本上我有一个聊天室,我将把它变成一个网络(我知道这听起来没有多大意义),但基本上我想知道是否可以让python脚本捕获计算机上的所有传出请求并将其发送到另一台计算机(c2)。然后我希望c2自己发出请求。这是对我正在做的事情的淡化解释,但任何帮助都会很棒!当然可以!虽然从头......