首页 > 解决方案 > Max Price since last Buy / Sell

问题描述

The goal is to store and plot the max price value since the last buy / sell.

The following method compares the current high with the historical high in the past candles since the last long / short. If current high is larger, it will become the historical high.

Somehow the plot does computes, but it doesn’t seem to be correct or as expected. Any advices?

//@version=4
strategy(title="Max since last buy/sell", overlay=true, process_orders_on_close=true)


// —————————— STATES

hasOpenTrade = strategy.opentrades != 0
notHasOpenTrade = strategy.opentrades == 0
isLong = strategy.position_size > 0
isShort = strategy.position_size < 0


// —————————— VARIABLES

var entryPrice = close


// —————————— MAIN

maxSinceLastBuySell = hasOpenTrade ? high > highest(bar_index) ? high : highest(bar_index) : na


// —————————— EXECUTIONS

longCondition = crossover(sma(close, 14), sma(close, 28))
if (longCondition)
    entryPrice := close
    candle := 1
    strategy.entry("My Long Entry Id", strategy.long)

shortCondition = crossunder(sma(close, 14), sma(close, 28))
if (shortCondition)
    entryPrice := close
    candle := 1
    strategy.entry("My Short Entry Id", strategy.short)
 

// —————————— DEBUG

plot(entryPrice, color = color.green)
plot(candle, color = color.black)
plot(maxSinceLastBuySell, color = color.red)

标签: pine-script

解决方案


只需保留所需的代码,以便更容易查看增量。区别在于:

  • 用于var声明变量,以便在整个条形图中保留状态。
  • 在交易开始时重置 var。
//@version=4
strategy(title = "Max since last buy/sell", overlay = true, pyramiding = 0, calc_on_order_fills = false, calc_on_every_tick = false, default_qty_type = strategy.percent_of_equity, default_qty_value = 98, commission_type = strategy.commission.percent, commission_value = 0.075, process_orders_on_close = true, initial_capital = 100)

// State
hasOpenTrade() => strategy.opentrades != 0

// Variables
var maxSinceLastBuySell = 0.

// Execution
longCondition = crossover(sma(close, 14), sma(close, 28))
if (longCondition)
    maxSinceLastBuySell := high
    strategy.entry("My Long Entry Id", strategy.long)

shortCondition = crossunder(sma(close, 14), sma(close, 28))
if (shortCondition)
    maxSinceLastBuySell := high
    strategy.entry("My Short Entry Id", strategy.short)

// Trade is open: check for higher high.
if hasOpenTrade()
    maxSinceLastBuySell := max(maxSinceLastBuySell, high)

// Debug
plot(maxSinceLastBuySell, color = color.red)

在此处输入图像描述


推荐阅读