Pine 脚本 (TradingView) - 如何将止损移至获利水平

2023-12-03

TradingView 上有一个 Pine 脚本代码,其中有 2 个止盈水平和 2 个止损水平:交易视图网。 当实现第一个止盈时,一半仓位被平仓,第一个止损移至入场水平(盈亏平衡)。

您是否有任何想法如何通过以下逻辑设置 3 个止盈水平:

  • 当达到 TP 1 时,SL 将移至盈亏平衡

  • 当达到 TP 2 时,SL 移至 TP 2

  • 当到达 TO 3 时,退出该位置

非常感谢您的帮助!

//@version=4
strategy("SL1 Pips after TP1 (MA)", commission_type=strategy.commission.cash_per_order, overlay=true, default_qty_value=1000, initial_capital=100)

// Strategy
Buy  = input(true)
Sell = input(true)

// Date Range
start_year    = input(title='Start year'   ,defval=2020)
start_month   = input(title='Start month'  ,defval=1)
start_day     = input(title='Start day'    ,defval=1)
start_hour    = input(title='Start hour'   ,defval=0)
start_minute  = input(title='Start minute' ,defval=0)
end_time      = input(title='set end time?',defval=false)
end_year      = input(title='end year'     ,defval=2019)
end_month     = input(title='end month'    ,defval=12)
end_day       = input(title='end day'      ,defval=31)
end_hour      = input(title='end hour'     ,defval=23)
end_minute    = input(title='end minute'   ,defval=59)

// MA
ema_period = input(title='EMA period',defval=10)
wma_period = input(title='WMA period',defval=20)
ema        = ema(close,ema_period)
wma        = wma(close,wma_period)

// Entry Condition
buy =
 crossover(ema,wma) and
 nz(strategy.position_size) == 0 and Buy and
 time > timestamp(start_year, start_month, start_day, start_hour, start_minute) and
 (end_time?(time < timestamp(end_year, end_month, end_day, end_hour, end_minute)):true)
 
sell =
 crossunder(ema,wma) and
 nz(strategy.position_size) == 0 and Sell and
 time > timestamp(start_year, start_month, start_day, start_hour, start_minute) and
 (end_time?(time < timestamp(end_year, end_month, end_day, end_hour, end_minute)):true)

// Pips
pip = input(20)*10*syminfo.mintick

// Trading parameters //
var bool  LS  = na
var bool  SS  = na
var float EP  = na
var float TVL = na
var float TVS = na
var float TSL = na
var float TSS = na
var float TP1 = na
var float TP2 = na
var float SL1 = na
var float SL2 = na

if buy or sell and strategy.position_size == 0
    EP  := close
    SL1 := EP - pip     * (sell?-1:1)
    SL2 := EP - pip     * (sell?-1:1)
    TP1 := EP + pip     * (sell?-1:1)
    TP2 := EP + pip * 2 * (sell?-1:1) 
   
// current trade direction    
LS := buy  or strategy.position_size > 0
SS := sell or strategy.position_size < 0

// adjust trade parameters and trailing stop calculations
TVL := max(TP1,open) - pip[1]
TVS := min(TP1,open) + pip[1]
TSL := open[1] > TSL[1] ? max(TVL,TSL[1]):TVL 
TSS := open[1] < TSS[1] ? min(TVS,TSS[1]):TVS

if LS and high > TP1
    if open <= TP1
        SL2:=min(EP,TSL)
    
if SS and low < TP1
    if open >= TP1
        SL2:=max(EP,TSS)

// Closing conditions
close_long  = LS and open < SL2
close_short = SS and open > SL2

// Buy
strategy.entry("buy"  , strategy.long, when=buy and not SS)
strategy.exit ("exit1", from_entry="buy", stop=SL1, limit=TP1, qty_percent=50)
strategy.exit ("exit2", from_entry="buy", stop=SL2, limit=TP2)

// Sell
strategy.entry("sell" , strategy.short, when=sell and not LS)
strategy.exit ("exit3", from_entry="sell", stop=SL1, limit=TP1, qty_percent=50)
strategy.exit ("exit4", from_entry="sell", stop=SL2, limit=TP2)

// Plots
a=plot(strategy.position_size >  0 ? SL1 : na, color=#dc143c, style=plot.style_linebr)
b=plot(strategy.position_size <  0 ? SL1 : na, color=#dc143c, style=plot.style_linebr) 
c=plot(strategy.position_size >  0 ? TP1 : na, color=#00ced1, style=plot.style_linebr) 
d=plot(strategy.position_size <  0 ? TP1 : na, color=#00ced1, style=plot.style_linebr) 
e=plot(strategy.position_size >  0 ? TP2 : na, color=#00ced1, style=plot.style_linebr) 
f=plot(strategy.position_size <  0 ? TP2 : na, color=#00ced1, style=plot.style_linebr) 
g=plot(strategy.position_size >= 0 ? na  : EP, color=#ffffff, style=plot.style_linebr) 
h=plot(strategy.position_size <= 0 ? na  : EP, color=#ffffff, style=plot.style_linebr) 

plot(ema,title="ema",color=#fff176)
plot(wma,title="wma",color=#00ced1)

非常感谢您的帮助!


这是您需要的示例:

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © adolgov

// @description
// when tp1 is reached, sl is moved to break-even
// when tp2 is reached, sl is moved to tp1
// when tp3 is reached - exit

//@version=4
strategy("Stepped trailing strategy example", overlay=true)

// random entry condition
longCondition = crossover(sma(close, 14), sma(close, 28))
if (longCondition)
    strategy.entry("My Long Entry Id", strategy.long)

// sl & tp in points
sl = input(100)
tp1 = input(100)
tp2 = input(200)
tp3 = input(300)

curProfitInPts() =>
    if strategy.position_size > 0
        (high - strategy.position_avg_price) / syminfo.mintick
    else if strategy.position_size < 0
        (strategy.position_avg_price - low) / syminfo.mintick
    else
        0
        
calcStopLossPrice(OffsetPts) =>
    if strategy.position_size > 0
        strategy.position_avg_price - OffsetPts * syminfo.mintick
    else if strategy.position_size < 0
        strategy.position_avg_price + OffsetPts * syminfo.mintick
    else
        0
        
calcProfitTrgtPrice(OffsetPts) =>
    calcStopLossPrice(-OffsetPts)

getCurrentStage() =>
    var stage = 0
    if strategy.position_size == 0 
        stage := 0
    if stage == 0 and strategy.position_size != 0
        stage := 1
    else if stage == 1 and curProfitInPts() >= tp1
        stage := 2
    else if stage == 2 and curProfitInPts() >= tp2
        stage := 3
    stage

stopLevel = -1.
profitLevel = calcProfitTrgtPrice(tp3)

// based on current stage set up exit
// note: we use same exit ids ("x") consciously, for MODIFY the exit's parameters
curStage = getCurrentStage()
if curStage == 1
    stopLevel := calcStopLossPrice(sl)
    strategy.exit("x", loss = sl, profit = tp3, comment = "sl or tp3")
else if curStage == 2
    stopLevel := calcStopLossPrice(0)
    strategy.exit("x", stop = stopLevel, profit = tp3, comment = "breakeven or tp3")
else if curStage == 3
    stopLevel := calcStopLossPrice(-tp1)
    strategy.exit("x", stop = stopLevel, profit = tp3, comment = "tp1 or tp3")
else
    strategy.cancel("x")

你可以看到它是如何工作的here

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Pine 脚本 (TradingView) - 如何将止损移至获利水平 的相关文章

  • 如何在Tradingview上的pinescript中在某个时间绘制垂直线?

    我想在每天的某个当地时间 例如 08 00 GMT 1 画一条垂直线 自从我的最后发表关于垂直线 pine script 已更新为包括vline 然而 这里的问题是如何把握正确的时间 大多数服务器 针对外汇 似乎都位于美国 并且交易视图本地
  • Pine脚本系列[string]到字符串转换

    我正在尝试从数组中读取符号 字符串 但是array get返回一个Series string 对象 而security只接受简单的字符串 我尝试转换为字符串 但它仍然给出 不接受系列 字符串 参数 错误 有办法让这项工作发挥作用吗 vers
  • pine 脚本中 := 和 = 运算符之间的区别

    我对 TradingView Pine 脚本非常陌生 我没有找到合适的参考来理解两者之间的区别 and 运营商 有人有参考或描述吗 提前致谢 用于声明和初始化变量 用于在初始化后为变量赋值 将其转换为 可变变量 任何不可变变量 follow
  • Pine Script 绘图形状偏移问题

    该脚本将表示高点 左侧条形较低 右侧条形较低 我还希望这个脚本给我 HighofHighs 左高和右高较低 我可以正常工作 但无法让标签显示在正确的栏上 如果我使用 offset 1 它将把它放在最近的高点上 如果我使用 offset hi
  • 有没有办法从数据窗口中隐藏特定的指标值?

    我最近创建了一个脚本 可以在 TradingView 的图表上绘制几个不同的指标 在特定场景下 部分指标不活跃 在数据窗口中显示 n a 我知道 TradingView 允许我们隐藏所有指标值 我想自定义哪些指标值可见 这可能吗 谢谢你的时
  • 标记水平 EMA 线(变量)

    这是我使用 atm 的代码 感谢比约恩 米斯蒂安 len1 input 10 minval 1 title Length len2 input 21 minval 1 title Length len3 input 55 minval 1
  • Tradingview的自动调整比例功能:排除指标的绘图

    我有一个指标 可以自动压缩 Y 轴上的整个价格图表 所以我必须在大多数情况下让它不可见 即使双击 y 尺度 图表自动调整功能 也可以包含所有可见指标 有没有办法阻止一个或所有指标这样做 哦 我刚刚找到了答案 只需右键单击 y 刻度即可调出带
  • 在交易视图上绘制每日开盘水平射线

    尝试在每日开盘时绘制水平射线 我的代码由于某种原因没有绘制任何内容 version 4 study Opens overlay true higherTF1 input D type input resolution dailyopen s
  • Pinescript 重复警报

    我用 pinescript 创建了一个非常基本的脚本 study title Renko Strat w Alerts shorttitle S EURUSD 5 MakisMooz overlay true rc close buy en
  • Pine Script:如何在每次价格更新时在标签上的图表时区中显示当前时间?

    我试图做一些看似微不足道的事情 但却遇到了各种各样的问题 每次当前价格更新时 我都想在标签上绘制某些基本信息 无论我的图表的时间范围如何 我能够准确地显示数量和价格信息 但是显示时间一直是一个挑战 我的第一次尝试是使用以下代码 if bar
  • 函数向全局变量返回 2 个值

    鉴于这个帖子 https stackoverflow com questions 61217589 set 2 series at once我想问为什么下面的脚本适用于 a b 但不适合 c d 找不到任何文档来解释为什么这不起作用 此示例
  • 为什么“style=”上的真/假逻辑不起作用?

    这是有效的代码 plotshape xvalue location location absolute style shape labeldown color red size size tiny text Upper 这是代码不起作用 p
  • 在 Pinescript v5 中发送 Webhook AND 和消息

    It appears that through the alert function you can code a message to be sent but what about the webhook 我想用资本化 ai 并且他们需要
  • 通过代码 tradeview/pine 脚本隐藏图表、数量和信号标签上的交易

    每次我更新策略代码时 样式都会重置 这意味着 图表上的交易 信号标签 Quantity 被重置为显示 有没有办法覆盖该行为 以便我可以隐藏 图表上的交易 非常感谢您对这个看似微不足道的问题的帮助 不 默认情况下没有禁用它们的功能 前段时间我
  • 如何更改 pine 脚本中函数的全局变量?

    我正在尝试编写一个脚本来获得 9 个级别的江恩平方 我已经用其他语言完成了它 但无法理解此处的 pine 脚本 它说无法修改函数中的全局变量 有什么解决方案可以获取这里的值是我的脚本 version 4 study title Volume
  • Pine Script 当前价格指标

    有没有办法在 Pine Script 中创建反映股票当前价格的指标 我需要这个指标 因为我需要在蜡烛收盘前 当存在特定交叉时 输入订单 并且逐条提供回测数据 我认为指标可以让我做到这一点 如果没有 还有其他方法可以解决这个问题 我不是一个经
  • Tradingview Pine-Script:如何仅绘制最后 x 个周期

    我只想绘制最后 x 个周期的指标 我怎么做 如果我可以进行时间操作 从plotStartDate中减去x period 也许我可以使用以下代码 period timeframe ismonthly or timeframe isweekly
  • 如何编写随机 RSI 指标

    我的指标看起来不像 TradingView 中的内置随机 RSI 指标 如何获得熟悉的外观来复制 st RSI 指标 这里是截屏 https www tradingview com x UdahzWrj 这显示了我的代码和 TradingV
  • 如何引用 pinescript 中临时变量中存储的先前入场价格?

    我有一些基本的 MA 交叉策略指标 我想实施更好的策略 仅当价格高于之前购买时才出售 但我不确定如何在 PINE 语法中执行此操作 有什么想法吗 这是简单的代码 工作正常 它打开 LONG 或关闭 LONG 取决于交叉 MA Strateg
  • 从 Tradingview 的 pine 脚本计算/复制 RSI

    我正在尝试将 Tradingviews pine 脚本 RSI 代码重新创建为 Javascript 代码 但很难弄清楚它是如何工作的 我使用正常的移动平均线计算得出了基本 RSI 但pine脚本使用指数加权移动平均线 而且那里的文档对我来

随机推荐

  • 向文本文件 php 中的每一行添加一个字符

    我是新手 我有一个文本文件 文本文件的内容如下 text1 text4 text7 text2 text5 text8 text3 text6 text9 我想做的是添加这个 gt gt gt 使用以下命令将字符添加到文本文件前两垂直列中的
  • 如何修复使用 TreeNode.MoveTo 时 TTreeView 的错误?

    使用 TreeNode MoveTo 方法有时无法正常工作并引发 访问冲突 异常 大多数时候有效 有时无效 大多数情况下 COMCTL32 DLL 模块中存在访问冲突 读取地址 FEEEFEFA 并导致程序崩溃 冻结 这是我的代码 proc
  • 右侧 singleton.getinstance() 分配需要 CodeModel 帮助

    我已经能够使用 CodeModel API 生成 99 的所需内容 但我被难住了 使用各种 directXX 方法不会将导入语句添加到生成的代码中 并且除了生成的类中的一处之外 我可以在没有 directXXX 类型的方法的情况下工作 假设
  • 如何在 C++ 中初始化 3D 数组

    如何在 C 中初始化 3d 数组 int min 1 1 1 100 100 100 this is not the way 您问题中的数组只有一个元素 因此您只需要一个值即可完全初始化它 您需要三组大括号 一组用于数组的每个维度 int
  • 如何在 msHTML 中调用脚本工作

    我正在使用 axWebBrowser 我需要编写一个脚本 该脚本在列表框的选定项目更改时起作用 在默认的 webBrowser 控件中有一个类似的方法 WebBrowserEx1 Document InvokeScript script 但
  • AngularJs 使用 $scope 变量作为 URL 嵌入 MS Word 文档

    如果我对 URL 进行硬编码 则可以嵌入我在互联网上找到的随机 MS Word Word 文档 但是 我想通过AJAX获取URL 所以我将HTML更改为 但即使是硬编码 scope我的 JS 中的变量 sco
  • javascript:函数和对象...?

    可以将函数作为对象来调用吗 例如 function Tip txt this content txt this shown false And var tip new Tip elem attr title 我的问题 你可以打电话吗new对
  • java中将非标准形式解析为标准形式

    我想编写一个Java解析器 将非标准形式 NSF 布尔函数转换为标准形式 SF NSF 示例 A B D A B C A B A B A B D 要将 NSF 转换为 SF 您必须将括号相乘 从上面的函数中可以看出 SF 是这样的 A B
  • 如何创建FindByIndexNameSessionRepository的bean

    我正在尝试创建 FindByIndexNameSessionRepository 的 Bean 我需要让所有用户会话使用它 但即使我已经定义了它 我仍然收到 bean 错误 我正在使用 Spring Boot Starter 1 5 7 E
  • PopViewController 奇怪的行为

    由于我试图拒绝一个奇怪的请求 但它不起作用 我不得不覆盖导航栏的后退按钮 我制作了一个自定义 UINavigationController 子类并破解了 BOOL navigationBar UINavigationBar navigati
  • 无法连接服务器。错误:0x8007000E

    当客户端尝试运行我的安装程序时 他在日志文件中收到此错误 Failed to connect to server Error 0x8007000E 当我在自己的机器上测试时 安装程 序运行良好 这是完整的日志文件 Verbose loggi
  • 如何在 Python 中将 URL 字符串拆分为单独的部分?

    我决定今晚学习 Python 我很了解C 用它写了一个操作系统 所以我不是编程新手 所以Python中的一切看起来都很简单 但我不知道如何解决这个问题 假设我有这个地址 http example com random folder path
  • 如何处理浮动元素?

    如果父元素中有浮动元素 则它们的父元素会失去其形状或没有高度 如何处理这个问题呢 Thanks 解决方案是使用clearfix class
  • 通过linux终端向另一个进程的stdin发送数据

    我一直在尝试将数据发送到正在运行的进程的标准输入 这是我所做的 在终端中 我启动了一个 C 程序 它只读取字符串并打印它 代码摘录 while true cin gt gt s cout lt lt I ve just read lt lt
  • PostgreSQL:命令已在进行中

    我的异步函数尝试从表中选择单个记录 该函数接受从另一个函数传递的一些参数 因此 某些进程 至少 6 个 可以同时使用它 我经常收到消息错误 命令已经在进行中 我知道问题隐藏在阅读器中 因为当另一个进程尝试访问它时 阅读器正忙 让我发布下面的
  • Pandas:查找具有第二高值的行的索引

    我试图在执行 groupby 之后获取具有第二高值的行的索引 但我没有得到正确的结果 df pd DataFrame Sp a b c d e f Mt s1 s1 s2 s2 s2 s3 Value 1 2 3 4 5 6 count 3
  • mysqli 中的 $GLOBALS["___mysqli_ston"] 是什么

    我第一次尝试使用 mysqli 我有一个问题 什么是 GLOBALS mysqli ston 你能告诉我吗 谷歌搜索时我没有得到任何直接答案 MySQLConverter 假定此全局变量设置为等于您的数据库连接对象 如果转换器找到 mysq
  • 捕获 xsl 结果文档的输出流

    我需要一种方法来干扰写入 xsl 结果文档 以避免将它们写入文件系统 现在我的模板正在写入临时目录 然后我压缩该目录 我想在不写入文件系统的情况下执行此操作 我正在使用 saxon 处理器 首选仅使用标准 java 库的解决方案 任何建议表
  • 如何在 Eclipse 中使用点(DOTALL)匹配多行查找正则表达式

    我想转换这个 def getEmployeeReminders employeeId Int page Option Int pageSize Option Int js callback Option String Action val
  • Pine 脚本 (TradingView) - 如何将止损移至获利水平

    TradingView 上有一个 Pine 脚本代码 其中有 2 个止盈水平和 2 个止损水平 交易视图网 当实现第一个止盈时 一半仓位被平仓 第一个止损移至入场水平 盈亏平衡 您是否有任何想法如何通过以下逻辑设置 3 个止盈水平 当达到