Skip to content
TheChatArchiveThe Chat Archive
gpt-4-0125-preview· openaiHugging Face Suzhen/CodeChat

//@version=5 strategy("Unique PSAR + Volatility Filter Strategy", shorttitle="Unique…

  1. User

    //@version=5 strategy("Unique PSAR + Volatility Filter Strategy", shorttitle="Unique PSAR Strat", overlay=true)

    // Unique parameters for customization unique_start = input.float(0.015, title="Unique PSAR Start", minval=0.001, maxval=0.1, step=0.001) unique_increment = input.float(0.015, title="Unique PSAR Increment", minval=0.001, maxval=0.1, step=0.001) unique_maximum = input.float(0.25, title="Unique PSAR Maximum", minval=0.1, maxval=0.5, step=0.01) unique_spread_ratio = input.float(0.85, title="Unique Open Spread Ratio Threshold", minval=0.1, maxval=1.0, step=0.05)

    // Calculation of PSAR with unique parameters unique_psar = ta.sar(unique_start, unique_increment, unique_maximum)

    // Logic for buy signal based on unique PSAR and spread ratio unique_last_falling_sar = ta.valuewhen(ta.crossover(close, unique_psar), unique_psar[1], 0) unique_init_rising_sar = ta.valuewhen(ta.crossover(unique_psar, close), unique_psar, 0) unique_open_spread = unique_last_falling_sar - unique_init_rising_sar unique_buy_signal = close > unique_psar and close[1] <= unique_psar[1] and unique_open_spread <= unique_spread_ratio * unique_open_spread[1]

    // Bollinger Bands settings lengthBB = input.int(20, title="BB Length", minval=1, maxval=100) multBB = input.float(2.0, title="BB Multiplier", minval=1.0, maxval=5.0, step=0.1) basisBB = ta.sma(close, lengthBB) devBB = multBB * ta.stdev(close, lengthBB) upperBB = basisBB + devBB lowerBB = basisBB - devBB bbWidth = (upperBB - lowerBB) / basisBB * 100 // BB width indicator

    // Strategy execution with dynamic take profit and stop loss if (unique_buy_signal) strategy.entry("Buy", strategy.long) strategy.exit("Take Profit / Stop Loss", "Buy", profit = bbWidth * close, loss = bbWidth / 2 * close)

    // Plotting the unique buy signal and PSAR plotshape(series=unique_buy_signal ? unique_psar[1] : na, title="Unique Buy Signal", location=location.belowbar, color=color.blue, style=shape.labelup, size=size.small) plot(series=unique_psar, title="Unique PSAR", style=plot.style_cross, linewidth=1, color=color.red) plot(series=upperBB, title="Upper BB", color=color.purple) plot(series=lowerBB, title="Lower BB", color=color.purple)

    // Alert condition for the unique buy signal alertcondition(condition=unique_buy_signal, title="Unique Buy Alert [PSAR]", message="Unique Buy Signal based on PSAR detected!")

  2. Assistant

    This Pine Script code defines a trading strategy for the TradingView platform that combines a custom Parabolic SAR (PSAR) indicator with a volatility filter based on Bollinger Bands (BB) for buy signals. It is designed to run on financial markets charts and it visually overlays signals and indicators on the chart for easy analysis. Here is a line-by-line explanation of the script:

    1-3. The script begins with metadata, including the script's name and version declaration for the Pine Script interpreter.

    4-9. It requests user input for customizing the PSAR indicator's start value, increment, maximum value, and a unique ratio threshold for the open spread, providing flexibility to adapt the strategy to different markets or preferences.

    1. The PSAR with customized parameters is calculated.

    13-17. The script then calculates specific variables to determine when to generate a buy signal based on specific conditions involving the crossover of the close price and the PSAR, and comparing the spread between specific PSAR values to a threshold derived from user input.

    19-24. Input settings for Bollinger Bands are defined, including the length of the moving average, the multiplier for the standard deviation to calculate the upper and lower bands, and the calculation of these bands.

    1. The width of the Bollinger Bands is calculated and expressed as a percentage of the basis (simple moving average) to measure market volatility.

    27-30. The script defines a condition to enter a long position (buy) when a unique buy signal is detected, and dynamically sets the levels for taking profit and stopping losses based on the Bollinger Bands' width.

    32-33. The script plots a shape (label up) below the bar where a unique buy signal occurs and the custom PSAR values, which allows traders to visually identify potential trade signals.

    34-36. The Bollinger Bands (upper and lower) are plotted for reference, which helps in visualizing market volatility and potential dynamic support and resistance levels.

    38-39. Finally, an alert condition is defined for the unique buy signal, enabling users to set up notifications when the specific buy conditions are met, facilitating real-time reaction to trading opportunities.

    This script is designed for traders who wish to incorporate a combination of trend-following and volatility-based decision-making into their strategies. Customization options allow the user to calibrate the strategy according to market conditions and personal trading preferences.

  3. User

    Ошибка на 32:53 Syntax error at input 'end of line without line continuation'
    //@version=5 strategy("Unique PSAR + Volatility Filter Strategy", shorttitle="Unique PSAR Strat", overlay=true)

    // Unique parameters for customization unique_start = input.float(0.015, title="Unique PSAR Start", minval=0.001, maxval=0.1, step=0.001) unique_increment = input.float(0.015, title="Unique PSAR Increment", minval=0.001, maxval=0.1, step=0.001) unique_maximum = input.float(0.25, title="Unique PSAR Maximum", minval=0.1, maxval=0.5, step=0.01) unique_spread_ratio = input.float(0.85, title="Unique Open Spread Ratio Threshold", minval=0.1, maxval=1.0, step=0.05)

    // Calculation of PSAR with unique parameters unique_psar = ta.sar(unique_start, unique_increment, unique_maximum)

    // Logic for buy signal based on unique PSAR and spread ratio unique_last_falling_sar = ta.valuewhen(ta.crossover(close, unique_psar), unique_psar[1], 0) unique_init_rising_sar = ta.valuewhen(ta.crossover(unique_psar, close), unique_psar, 0) unique_open_spread = unique_last_falling_sar - unique_init_rising_sar unique_buy_signal = close > unique_psar and close[1] <= unique_psar[1] and unique_open_spread <= unique_spread_ratio * unique_open_spread[1]

    // Bollinger Bands settings lengthBB = input.int(20, title="BB Length", minval=1, maxval=100) multBB = input.float(2.0, title="BB Multiplier", minval=1.0, maxval=5.0, step=0.1) basisBB = ta.sma(close, lengthBB) devBB = multBB * ta.stdev(close, lengthBB) upperBB = basisBB + devBB lowerBB = basisBB - devBB bbWidth = (upperBB - lowerBB) / basisBB * 100 // BB width indicator

    // Strategy execution with dynamic take profit and stop loss if (unique_buy_signal) strategy.entry("Buy", strategy.long) strategy.exit("Take Profit / Stop Loss", "Buy", profit = bbWidth * close, loss = bbWidth / 2 * close)

    // Plotting the unique buy signal and PSAR plotshape(series=unique_buy_signal ? unique_psar[1] : na, title="Unique Buy Signal", location=location.belowbar, color=color.blue, style=shape.labelup, size=size.small) plot(series=unique_psar, title="Unique PSAR", style=plot.style_cross, linewidth=1, color=color.red) plot(series=upperBB, title="Upper BB", color=color.purple) plot(series=lowerBB, title="Lower BB", color=color.purple)

    // Alert condition for the unique buy signal alertcondition(condition=unique_buy_signal, title="Unique Buy Alert [PSAR]", message="Unique Buy Signal based on PSAR detected!") исправьте пожалуйста

  4. Assistant

    Исправление ошибки в вашем Pine Script коде было сосредоточено на строке, где вы используете условие для входа в позицию и выхода из нее. Ошибка "end of line without line continuation" часто происходит, когда код неправильно форматирован или когда требуемое выражение разбито на несколько строк без должного продолжения. Давайте исправим это:

    //@version=5
    strategy("Unique PSAR + Volatility Filter Strategy", shorttitle="Unique PSAR Strat", overlay=true)
    
    // Unique parameters for customization
    unique_start = input.float(0.015, title="Unique PSAR Start", minval=0.001, maxval=0.1, step=0.001)
    unique_increment = input.float(0.015, title="Unique PSAR Increment", minval=0.001, maxval=0.1, step=0.001)
    unique_maximum = input.float(0.25, title="Unique PSAR Maximum", minval=0.1, maxval=0.5, step=0.01)
    unique_spread_ratio = input.float(0.85, title="Unique Open Spread Ratio Threshold", minval=0.1, maxval=1.0, step=0.05)
    
    // Calculation of PSAR with unique parameters
    unique_psar = ta.sar(unique_start, unique_increment, unique_maximum)
    
    // Logic for buy signal based on unique PSAR and spread ratio
    unique_last_falling_sar = ta.valuewhen(ta.crossover(close, unique_psar), unique_psar[1], 0)
    unique_init_rising_sar = ta.valuewhen(ta.crossover(unique_psar, close), unique_psar, 0)
    unique_open_spread = unique_last_falling_sar - unique_init_rising_sar
    unique_buy_signal = close > unique_psar and close[1] <= unique_psar[1] and unique_open_spread <= unique_spread_ratio * unique_open_spread[1]
    
    // Bollinger Bands settings
    lengthBB = input.int(20, title="BB Length", minval=1, maxval=100)
    multBB = input.float(2.0, title="BB Multiplier", minval=1.0, maxval=5.0, step=0.1)
    basisBB = ta.sma(close, lengthBB)
    devBB = multBB * ta.stdev(close, lengthBB)
    upperBB = basisBB + devBB
    lowerBB = basisBB - devBB
    bbWidth = (upperBB - lowerBB) / basisBB * 100 // BB width indicator
    
    // Strategy execution with dynamic take profit and stop loss
    if (unique_buy_signal)
        strategy.entry("Buy", strategy.long)
        // The below line might have contained syntax issues, make sure the format here is correct:
        strategy.exit("Take Profit / Stop Loss", "Buy", profit = bbWidth * close, loss = bbWidth / 2 * close)
    
    // Plotting the unique buy signal and PSAR
    plotshape(series=unique_buy_signal ? unique_psar[1] : na, title="Unique Buy Signal", location=location.belowbar, color=color.blue, style=shape.labelup, size=size.small)
    plot(series=unique_psar, title="Unique PSAR", style=plot.style_cross, linewidth=1, color=color.red)
    plot(series=upperBB, title="Upper BB", color=color.purple)
    plot(series=lowerBB, title="Lower BB", color=color.purple)
    
    // Alert condition for the unique buy signal
    alertcondition(condition=unique_buy_signal, title="Unique Buy Alert [PSAR]", message="Unique Buy Signal based on PSAR detected!")
    

    Ключевым изменением является форматирование блока кода, осуществляемого после условия if (unique_buy_signal), где функции strategy.entry и strategy.exit теперь содержатся в правильной структуре, без перехода на новую строку внутри аргументов. Это исправление должно устранить ошибку синтаксиса, возникшую из-за разрыва строки внутри аргументов функции strategy.exit.

  5. User

    Ошибка на 2:10 no viable alternative at character '“'

  6. Assistant

    Ошибка "no viable alternative at character '“'" в вашем Pine Script указывает на использование неподдерживаемого символа кавычки. Pine Script использует стандартные символы кавычек (" ") для строк, а символы "умных" кавычек (такие как “ ”) не поддерживаются и вызывают ошибки. Давайте найдем и заменим эти символы на правильные в вашем скрипте:

    Я не вижу прямого использования “умных” кавычек в предоставленном коде, но ошибки подобного рода часто возникают из-за копирования кода из текстовых редакторов, таких как Microsoft Word, которые автоматически преобразуют простые кавычки в “умные”. Для исправления просто замените все “умные” кавычки на стандартные, как показано ниже:

    //@version=5
    strategy("Unique PSAR + Volatility Filter Strategy", shorttitle="Unique PSAR Strat", overlay=true)
    
    // Unique parameters for customization
    unique_start = input.float(0.015, title="Unique PSAR Start", minval=0.001, maxval=0.1, step=0.001)
    unique_increment = input.float(0.015, title="Unique PSAR Increment", minval=0.001, maxval=0.1, step=0.001)
    unique_maximum = input.float(0.25, title="Unique PSAR Maximum", minval=0.1, maxval=0.5, step=0.01)
    unique_spread_ratio = input.float(0.85, title="Unique Open Spread Ratio Threshold", minval=0.1, maxval=1.0, step=0.05)
    ...
    

    Убедитесь, что весь текст в вашем скрипте, особенно те места, где вы использовали кавычки для определения строк (например, в параметрах title), содержит правильные стандартные символы кавычек ". Если у вас в коде есть комментарии или строки с кавычками, проверьте и их тоже.

    Если после этого ошибка все еще возникает, проверьте каждую строку кода на наличие “умных” кавычек в комментариях или строковых литералах и замените их на стандартные кавычки ". Это должно исправить ошибку.

  7. User

    //@version=4 strategy("Unique PSAR + Volatility Filter Strategy", shorttitle="Unique PSAR Strat", overlay=true)

    // Unique parameters for customization unique_start = input(0.015, title="Unique PSAR Start") unique_increment = input(0.015, title="Unique PSAR Increment") unique_maximum = input(0.25, title="Unique PSAR Maximum") unique_spread_ratio = input(0.85, title="Unique Open Spread Ratio Threshold", minval=0.1, maxval=1.0)

    // Calculation of PSAR with unique parameters unique_psar = sar(unique_start, unique_increment, unique_maximum)

    // Logic for buy signal based on unique PSAR and spread ratio unique_last_falling_sar = valuewhen(crossover(close, unique_psar), unique_psar[1], 0) unique_init_rising_sar = valuewhen(crossover(close, unique_psar), unique_psar, 0) unique_open_spread = unique_last_falling_sar - unique_init_rising_sar unique_buy_signal = close > unique_psar and close[1] <= unique_psar[1] and unique_open_spread <= unique_spread_ratio * unique_open_spread[1]

    // Bollinger Bands settings lengthBB = input(20, title="BB Length") multBB = input(2.0, title="BB Multiplier") basisBB = sma(close, lengthBB) devBB = multBB * stdev(close, lengthBB) upperBB = basisBB + devBB lowerBB = basisBB - devBB bbWidth = (upperBB - lowerBB) / basisBB * 100 // BB width indicator

    // Strategy execution if (unique_buy_signal) strategy.entry("Buy", strategy.long) strategy.exit("Take Profit / Stop Loss", "Buy", profit = bbWidth, loss = bbWidth / 2)

    // Plotting the unique buy signal and PSAR plotshape(unique_buy_signal ? unique_psar[1] : na, title="Unique Buy Signal", location=location.belowbar, color=color.blue, style=shape.labelup, size=size.small) plot(unique_psar, title="Unique PSAR", style=plot.style_cross, linewidth=1, color=color.red) plot(upperBB, "Upper BB", color=color.purple) plot(lowerBB, "Lower BB", color=color.purple)

    // Alert condition for the unique buy signal alertcondition(unique_buy_signal, title="Unique Buy Alert [PSAR]", message="Unique Buy Signal based on PSAR detected!") почините тейки и стопы

  8. Assistant

    В вашем коде для Pine Script версии 4 замечена небольшая ошибка в логике для strategy.exit() для динамической настройки стоп-лосса и тейк-профита. В текущем виде, значения profit и loss в strategy.exit() указаны некорректно, так как значения bbWidth и bbWidth / 2 не умножаются на текущую цену закрытия close, что необходимо для динамической регуляции уровней тейк-профита и стоп-лосса в зависимости от волатильности рынка.

    Чтобы исправить ошибку, нужно установить значения profit и loss так, чтобы они учитывали текущую цену и волатильность. Давайте это исправим:

    //@version=4
    strategy("Unique PSAR + Volatility Filter Strategy", shorttitle="Unique PSAR Strat", overlay=true)
    
    // Unique parameters for customization
    unique_start = input(0.015, title="Unique PSAR Start")
    unique_increment = input(0.015, title="Unique PSAR Increment")
    unique_maximum = input(0.25, title="Unique PSAR Maximum")
    unique_spread_ratio = input(0.85, title="Unique Open Spread Ratio Threshold", minval=0.1, maxval=1.0)
    
    // Calculation of PSAR with unique parameters
    unique_psar = sar(unique_start, unique_increment, unique_maximum)
    
    // Logic for buy signal based on unique PSAR and spread ratio
    unique_last_falling_sar = valuewhen(crossover(close, unique_psar), unique_psar[1], 0)
    unique_init_rising_sar = valuewhen(crossover(close, unique_psar), unique_psar, 0)
    unique_open_spread = unique_last_falling_sar - unique_init_rising_sar
    unique_buy_signal = close > unique_psar and close[1] <= unique_psar[1] and unique_open_spread <= unique_spread_ratio * unique_open_spread[1]
    
    // Bollinger Bands settings
    lengthBB = input(20, title="BB Length")
    multBB = input(2.0, title="BB Multiplier")
    basisBB = sma(close, lengthBB)
    devBB = multBB * stdev(close, lengthBB)
    upperBB = basisBB + devBB
    lowerBB = basisBB - devBB
    bbWidth = (upperBB - lowerBB) / basisBB * 100 // BB width indicator
    
    // Strategy execution with corrected take profit and stop loss
    if (unique_buy_signal)
        strategy.entry("Buy", strategy.long)
        strategy.exit("Take Profit / Stop Loss", "Buy", 
            profit = math.round(bbWidth * close / 100), 
            loss = math.round((bbWidth / 2) * close / 100))
    
    // Plotting the unique buy signal and PSAR
    plotshape(unique_buy_signal ? unique_psar[1] : na, title="Unique Buy Signal", location=location.belowbar, color=color.blue, style=shape.labelup, size=size.small)
    plot(unique_psar, title="Unique PSAR", style=plot.style_cross, linewidth=1, color=color.red)
    plot(upperBB, "Upper BB", color=color.purple)
    plot(lowerBB, "Lower BB", color=color.purple)
    
    // Alert condition for the unique buy signal
    alertcondition(unique_buy_signal, title="Unique Buy Alert [PSAR]", message="Unique Buy Signal based on PSAR detected!")
    

    Обратите внимание на изменения в strategy.exit() - уровни тейк-профита и стоп-лосса теперь корректно рассчитываются путем умножения ширины Bollinger Bands (указанных в процентах) на текущую цену close и добавления математического округления math.round() для получения целых значений уровней цен, что более практично для большинства трейдинговых платформ.

  9. User

    Ошибка на 2:0 no viable alternative at character '“'

  10. Assistant

    Ошибку "no viable alternative at character '“'" вызвано использованием неподдерживаемого типа кавычек в вашем Pine Script. Pine Script, как и большинство программных языков, требует использования стандартных двойных кавычек (") для строковых литералов, а не типографских (умных) кавычек (таких как “ или ”).

    К сожалению, в предоставленном коде прямого использования этих кавычек нет, но они могут быть введены в скрипт случайно, например, при копировании и вставке текста из текстовых процессоров (например, Microsoft Word) или веб-страниц, которые автоматически преобразуют стандартные кавычки в типографские.

    Чтобы исправить ошибку, вам необходимо заменить все типографские кавычки на стандартные. Если ваш текстовый редактор или IDE поддерживает функцию поиска и замены, вы можете использовать ее для замены всех встреч типографских кавычек “ и ” на стандартные кавычки ". Если в коде есть комментарии или строки, где могли быть использованы эти кавычки, убедитесь, что они заменены на корректные символы.

    Например, строка или комментарий, в котором может возникнуть ошибка:

    // Incorrect: Using “smart” quotes
    title=“Unique PSAR Start”
    

    Исправленный вариант:

    // Correct: Using standard quotes
    title="Unique PSAR Start"
    

    Убедитесь, что весь ваш скрипт не содержит неподдерживаемых символов, особенно в строках и комментариях.

  11. User

    замените весь код на ковычки " вместо тех

  12. Assistant

    Конечно, я преобразую ваш последний предоставленный код, заменив типографские кавычки на стандартные двойные кавычки " для корректной обработки Pine Script:

    //@version=4
    strategy("Unique PSAR + Volatility Filter Strategy", shorttitle="Unique PSAR Strat", overlay=true)
    
    // Unique parameters for customization
    unique_start = input(0.015, title="Unique PSAR Start")
    unique_increment = input(0.015, title="Unique PSAR Increment")
    unique_maximum = input(0.25, title="Unique PSAR Maximum")
    unique_spread_ratio = input(0.85, title="Unique Open Spread Ratio Threshold", minval=0.1, maxval=1.0)
    
    // Calculation of PSAR with unique parameters
    unique_psar = sar(unique_start, unique_increment, unique_maximum)
    
    // Logic for buy signal based on unique PSAR and spread ratio
    unique_last_falling_sar = valuewhen(crossover(close, unique_psar), unique_psar[1], 0)
    unique_init_rising_sar = valuewhen(crossover(close, unique_psar), unique_psar, 0)
    unique_open_spread = unique_last_falling_sar - unique_init_rising_sar
    unique_buy_signal = close > unique_psar and close[1] <= unique_psar[1] and unique_open_spread <= unique_spread_ratio * unique_open_spread[1]
    
    // Bollinger Bands settings
    lengthBB = input(20, title="BB Length")
    multBB = input(2.0, title="BB Multiplier")
    basisBB = sma(close, lengthBB)
    devBB = multBB * stdev(close, lengthBB)
    upperBB = basisBB + devBB
    lowerBB = basisBB - devBB
    bbWidth = (upperBB - lowerBB) / basisBB * 100 // BB width indicator
    
    // Strategy execution with corrected take profit and stop loss
    if (unique_buy_signal)
        strategy.entry("Buy", strategy.long)
        strategy.exit("Take Profit / Stop Loss", "Buy", 
            profit = math.round(bbWidth * close / 100), 
            loss = math.round((bbWidth / 2) * close / 100))
    
    // Plotting the unique buy signal and PSAR
    plotshape(unique_buy_signal ? unique_psar[1] : na, title="Unique Buy Signal", location=location.belowbar, color=color.blue, style=shape.labelup, size=size.small)
    plot(unique_psar, title="Unique PSAR", style=plot.style_cross, linewidth=1, color=color.red)
    plot(upperBB, "Upper BB", color=color.purple)
    plot(lowerBB, "Lower BB", color=color.purple)
    
    // Alert condition for the unique buy signal
    alertcondition(unique_buy_signal, title="Unique Buy Alert [PSAR]", message="Unique Buy Signal based on PSAR detected!")
    

    Теперь весь код использует стандартные двойные кавычки ", которые являются корректными для Pine Script во всех используемых строковых литералах и параметрах. Это должно решить проблему с ошибкой "no viable alternative at character '“'", связанную с неправильным типом кавычек.

  13. User

    исправьте ошибки только не пишите в спойлере кода а просто еткстом //@version=4 strategy("Unique PSAR + Volatility Filter Strategy", shorttitle="Unique PSAR Strat", overlay=true)

    // Unique parameters for customization unique_start = input(0.015, title="Unique PSAR Start") unique_increment = input(0.015, title="Unique PSAR Increment") unique_maximum = input(0.25, title="Unique PSAR Maximum") unique_spread_ratio = input(0.85, title="Unique Open Spread Ratio Threshold", minval=0.1, maxval=1.0)

    // Initialize the take profit percentages array before the strategy block take_profit_percentages = array.new_float() array.push(take_profit_percentages, 0.005) array.push(take_profit_percentages, 0.01) array.push(take_profit_percentages, 0.02) array.push(take_profit_percentages, 0.03) array.push(take_profit_percentages, 0.04)

    // Calculation of PSAR with unique parameters unique_psar = sar(unique_start, unique_increment, unique_maximum)

    // Logic for buy signal based on unique PSAR and spread ratio unique_last_falling_sar = valuewhen(crossover(close, unique_psar), unique_psar[1], 0) unique_init_rising_sar = valuewhen(crossover(close, unique_psar), unique_psar, 0) unique_open_spread = unique_last_falling_sar - unique_init_rising_sar unique_buy_signal = close > unique_psar and close[1] <= unique_psar[1] and unique_open_spread <= unique_spread_ratio * unique_open_spread[1]

    // Bollinger Bands settings lengthBB = input(20, title="BB Length") multBB = input(2.0, title="BB Multiplier") basisBB = sma(close, lengthBB) devBB = multBB * stdev(close, lengthBB) upperBB = basisBB + devBB lowerBB = basisBB - devBB bbWidth = (upperBB - lowerBB) / basisBB * 100 // BB width indicator

    // Strategy execution with multiple take profits and dynamic stop loss long_entry_price = 0.0 if (unique_buy_signal) long_entry_price := close strategy.entry("Buy", strategy.long) strategy.exit("Stop Loss", "Buy", stop=lowerBB)

    // Take profit levels take_profit_percentages = array.new_float(5, 0.005, 0.01, 0.02, 0.03, 0.04) for i = 0 to array.size(take_profit_percentages) - 1 take_profit_price = long_entry_price * (1 + array.get(take_profit_percentages, i)) strategy.exit("Take Profit " + tostring(i+1), "Buy", limit=take_profit_price)

    // Move to break-even after first take profit if (strategy.position_size > 0 and strategy.opentrades.profit(0) >= long_entry_price * 0.005) strategy.exit("Break-Even", "Buy", stop=long_entry_price * 1.001) // Corrected for loop for take profit levels for i = 0 to array.size(take_profit_percentages) - 1 take_profit_price = long_entry_price * (1 + array.get(take_profit_percentages, i)) strategy.exit("Take Profit " + tostring(i+1), "Buy", limit=take_profit_price)

    // Plotting the unique buy signal and PSAR plotshape(unique_buy_signal ? unique_psar[1] : na, title="Unique Buy Signal", location=location.belowbar, color=color.blue, style=shape.labelup, size=size.small) plot(unique_psar, title="Unique PSAR", style=plot.style_cross, linewidth=1, color=color.red) plot(upperBB, "Upper BB", color=color.purple) plot(lowerBB, "Lower BB", color=color.purple)

    // Alert condition for the unique buy signal alertcondition(unique_buy_signal, title="Unique Buy Alert [PSAR]", message="Unique Buy Signal based on PSAR detected!")

  14. Assistant

    В вашем скрипте есть несколько моментов для исправления и улучшения. Вот подробности по каждому из них:

    1. Дублирование кода: Вы дважды инициализируете и наполняете массив take_profit_percentages. Лучше сделать это один раз. Удалите первоначальные строки с array.new_float() и array.push() в начале скрипта, оставив только одну инициализацию массива перед блоком стратегии.

    2. Неправильное использование long_entry_price: Ваше текущее определение long_entry_price не будет работать как ожидается из-за того, что присваивание long_entry_price := close будет происходить каждый раз при проверке условия if (unique_buy_signal), что в Pine Script не совсем корректно из-за специфики выполнения. Чтобы это исправить, можно использовать функцию strategy.position_avg_price для получения средней цены покупки текущей открытой позиции, которую в дальнейшем можно использовать для расчета уровней тейк-профита.

    3. Ошибка в логике выхода на безубыток: Проверка условия if (strategy.position_size > 0 and strategy.opentrades.profit(0) >= long_entry_price * 0.005) может не работать должным образом, так как strategy.opentrades.profit(0) не совсем то, что нужно для проверки достижения первого уровня тейк-профита. Вместо этого, стоит использовать системные переменные Pine Script для детекции закрытых сделок по тейк-профиту. Однако, реализация зависит от конкретных задач и ограничений стратегии.

    Исправленный фрагмент кода с учетом указанных моментов:

    // ... предыдущий код до стратегии ...
    // Strategy execution with multiple take profits and dynamic stop loss
    if (unique_buy_signal)
        strategy.entry("Buy", strategy.long)
        strategy.exit("Stop Loss", "Buy", stop=lowerBB)
    
    take_profit_percentages = array.new_float(5, 0.005, 0.01, 0.02, 0.03, 0.04)
    for i = 0 to array.size(take_profit_percentages) - 1
        take_profit_price = strategy.position_avg_price * (1 + array.get(take_profit_percentages, i))
        strategy.exit("Take Profit " + tostring(i+1), "Buy", limit=take_profit_price)
    
    // Добавьте правильную логику для безубытка после достижения первого тейк-профита в соответствии с вашими требованиями
    // ...
    
    // ... код для плотинга и оповещений ...
    

    Обратите внимание, что вы должны адаптировать логику выхода на безубыток в соответствии с вашей стратегией и доступными функциями Pine Script, так как прямой способ реализации будет зависеть от структуры вашей торговой стратегии и платформы.

  15. User

    вы должны адаптировать логику выхода на безубыток в соответствии с вашей стратегией и доступными функциями Pine Script

  16. Assistant

    Адаптируем логику выхода на безубыток для вашей стратегии в Pine Script. Для выхода на безубыток после достижения определенного профита можно использовать блок if для проверки условий и изменения уровня стоп-лосса на уровень входа или другой уровень, который считается за безубыточный.

    Ваш начальный код не совсем корректно реализовывает выход на безубыток, особенно если рассматривать моменты обновления стоп-лосса после выполнения входной стратегии strategy.entry("Buy", strategy.long). Давайте переформулируем логику с использованием средней цены позиции strategy.position_avg_price как условие для выставления стопа на уровне безубытка.

    Важно! Pine Script не позволяет напрямую изменять уровень стоп-лосса уже положенной в рынок заявки, поэтому "выход на безубыток" потребует отмены предыдущего стопа и установки нового. В этом примере для упрощения мы будем считать, что для выхода на безубыток достаточно одного трейда, и стоп-лосс будет выставлен только один раз при достижении определенного условия.

    //@version=4
    strategy("Unique PSAR + Volatility Filter Strategy", shorttitle="Unique PSAR Strat", overlay=true)
    // Ваши параметры и логика стратегии...
    
    if (unique_buy_signal)
        strategy.entry("Buy", strategy.long)
    
    // Предположим, что lowerBB ваш начальный уровень стоп-лосса
    strategy.exit("Stop Loss", "Buy", stop=lowerBB)
    
    // Логика для выхода на безубыток
    var float break_even_stop_price = na // Используйте переменную для хранения цены выхода на безубыток
    if (strategy.position_size > 0) // Проверяем, что у нас открыта длинная позиция
        // Проверяем, достиг ли первый тейк-профит
        if (close > strategy.position_avg_price * (1 + array.get(take_profit_percentages, 0)))
            break_even_stop_price := strategy.position_avg_price // Устанавливаем цену безубытка в размере средней цены входа
            
        if not na(break_even_stop_price)
            // Используем обновленный стоп для выхода на безубыток
            strategy.exit("Break-Even Stop", "Buy", stop=break_even_stop_price)
    
    // Продолжение вашего кода...
    

    Этот код проверяет, был ли достигнут первый уровень тейк-профита и, в случае успеха, устанавливает стоп-лосс на уровень средней цены позиции для выхода на безубыток. Важно отметить, что конкретная реализация будет зависеть от структуры вашей торговой стратегии и её целей.

    Пожалуйста, адаптируйте этот код с учетом вашей логики и условий торговой стратегии, так как Pine Script предоставляет много инструментов, но одновременно требует точной настройки под конкретные требования и условия стратегии.

  17. User

    19:39:33 Ошибка на 12:0 Undeclared identifier 'lowerBB'; 19:39:33 Ошибка на 18:0 Undeclared identifier 'take_profit_percentages'; 19:39:33 Ошибка на 59:0 Too much arguments; 19:39:33 Ошибка на 59:0 'take_profit_percentages' is already defined. //@version=4 strategy("Unique PSAR + Volatility Filter Strategy", shorttitle="Unique PSAR Strat", overlay=true)

    // Unique parameters for customization unique_start = input(0.015, title="Unique PSAR Start") unique_increment = input(0.015, title="Unique PSAR Increment") unique_maximum = input(0.25, title="Unique PSAR Maximum") unique_spread_ratio = input(0.85, title="Unique Open Spread Ratio Threshold", minval=0.1, maxval=1.0)

    // Assuming lowerBB is your initial stop-loss level strategy.exit("Stop Loss", "Buy", stop=lowerBB)

    // Logic for moving to break-even var float break_even_stop_price = na // Use a variable to store the break-even stop price if (strategy.position_size > 0) // Check that we have a long position open // Check if the first take-profit has been reached if (close > strategy.position_avg_price * (1 + array.get(take_profit_percentages, 0))) break_even_stop_price := strategy.position_avg_price // Set the break-even price to the average entry price

    if not na(break_even_stop_price)
        // Use the updated stop for the break-even exit
        strategy.exit("Break-Even Stop", "Buy", stop=break_even_stop_price)
    

    // Initialize the take profit percentages array before the strategy block take_profit_percentages = array.new_float() array.push(take_profit_percentages, 0.005) array.push(take_profit_percentages, 0.01) array.push(take_profit_percentages, 0.02) array.push(take_profit_percentages, 0.03) array.push(take_profit_percentages, 0.04)

    // Calculation of PSAR with unique parameters unique_psar = sar(unique_start, unique_increment, unique_maximum)

    // Logic for buy signal based on unique PSAR and spread ratio unique_last_falling_sar = valuewhen(crossover(close, unique_psar), unique_psar[1], 0) unique_init_rising_sar = valuewhen(crossover(close, unique_psar), unique_psar, 0) unique_open_spread = unique_last_falling_sar - unique_init_rising_sar unique_buy_signal = close > unique_psar and close[1] <= unique_psar[1] and unique_open_spread <= unique_spread_ratio * unique_open_spread[1]

    // Bollinger Bands settings lengthBB = input(20, title="BB Length") multBB = input(2.0, title="BB Multiplier") basisBB = sma(close, lengthBB) devBB = multBB * stdev(close, lengthBB) upperBB = basisBB + devBB lowerBB = basisBB - devBB bbWidth = (upperBB - lowerBB) / basisBB * 100 // BB width indicator

    // Strategy execution with multiple take profits and dynamic stop loss long_entry_price = 0.0 if (unique_buy_signal) long_entry_price := close strategy.entry("Buy", strategy.long) strategy.exit("Stop Loss", "Buy", stop=lowerBB)

    // Take profit levels take_profit_percentages = array.new_float(5, 0.005, 0.01, 0.02, 0.03, 0.04) for i = 0 to array.size(take_profit_percentages) - 1 take_profit_price = long_entry_price * (1 + array.get(take_profit_percentages, i)) strategy.exit("Take Profit " + tostring(i+1), "Buy", limit=take_profit_price)

    // Move to break-even after first take profit if (strategy.position_size > 0 and strategy.opentrades.profit(0) >= long_entry_price * 0.005) strategy.exit("Break-Even", "Buy", stop=long_entry_price * 1.001)

    // Plotting the unique buy signal and PSAR plotshape(unique_buy_signal ? unique_psar[1] : na, title="Unique Buy Signal", location=location.belowbar, color=color.blue, style=shape.labelup, size=size.small) plot(unique_psar, title="Unique PSAR", style=plot.style_cross, linewidth=1, color=color.red) plot(upperBB, "Upper BB", color=color.purple) plot(lowerBB, "Lower BB", color=color.purple)

    // Alert condition for the unique buy signal alertcondition(unique_buy_signal, title="Unique Buy Alert [PSAR]", message="Unique Buy Signal based on PSAR detected!")

  18. Assistant

    Из вашего кода видно несколько областей, требующих внимания и исправлений. Давайте проанализируем ошибки по одной и предложим решения:

    1. Ошибка "Undeclared identifier 'lowerBB'"

    Эта ошибка возникает, потому что код пытается использовать переменную lowerBB, которая еще не была объявлена на момент её использования. Чтобы исправить это, необходимо убедиться, что строка strategy.exit("Stop Loss", "Buy", stop=lowerBB) располагается после раздела, где lowerBB объявляется и рассчитывается.

    2. Ошибка "Undeclared identifier 'take_profit_percentages'"

    Подобно первой ошибке, take_profit_percentages используется до того, как массив был инициализирован. Однако, проблема на самом деле в некорректной структуре кода - вы дважды определяете take_profit_percentages: один раз до, а второй раз после начала реализации стратегии.

    3. Ошибка "Too much arguments"

    Эта ошибка указывает на неправильное количество аргументов в функции или методе. Я предполагаю, что ошибка связана с другими строками, так как в указанных строках нет явной проблемы с количеством аргументов. Нужно проверить, верно ли интерпретированы ошибки.

    4. Ошибка "'take_profit_percentages' is already defined."

    Ошибку вызывает повторное объявление переменной take_profit_percentages. В вашем коде вы инициализируете массив дважды, что вызывает ошибку.

    Исправленный код:

    //@version=4
    strategy("Unique PSAR + Volatility Filter Strategy", shorttitle="Unique PSAR Strat", overlay=true)
    
    // Unique parameters for customization
    unique_start = input(0.015, title="Unique PSAR Start")
    unique_increment = input(0.015, title="Unique PSAR Increment")
    unique_maximum = input(0.25, title="Unique PSAR Maximum")
    unique_spread_ratio = input(0.85, title="Unique Open Spread Ratio Threshold", minval=0.1, maxval=1.0)
    
    // Calculation of PSAR with unique parameters
    unique_psar = sar(unique_start, unique_increment, unique_maximum)
    
    // Logic for buy signal based on unique PSAR and spread ratio
    unique_last_falling_sar = valuewhen(crossover(close, unique_psar), unique_psar[1], 0)
    unique_init_rising_sar = valuewhen(crossover(close, unique_psar), unique_psar, 0)
    unique_open_spread = unique_last_falling_sar - unique_init_rising_sar
    unique_buy_signal = close > unique_psar and close[1] <= unique_psar[1] and unique_open_spread <= unique_spread_ratio * unique_open_spread[1]
    
    // Bollinger Bands settings
    lengthBB = input(20, title="BB Length")
    multBB = input(2.0, title="BB Multiplier")
    basisBB = sma(close, lengthBB)
    devBB = multBB * stdev(close, lengthBB)
    upperBB = basisBB + devBB
    lowerBB = basisBB - devBB
    bbWidth = (upperBB - lowerBB) / basisBB * 100 // BB width indicator
    
    // Initialize the take profit percentages array
    take_profit_percentages = array.new_float(5, 0.005, 0.01, 0.02, 0.03, 0.04)
    
    // Strategy execution with multiple take profits and dynamic stop loss
    if (unique_buy_signal)
        strategy.entry("Buy", strategy.long)
        strategy.exit("Stop Loss", "Buy", stop=lowerBB)
    
    // Take profit levels
    for i = 0 to array.size(take_profit_percentages) - 1
        take_profit_price = close * (1 + array.get(take_profit_percentages, i))
        strategy.exit("Take Profit " + tostring(i+1), "Buy", limit=take_profit_price)
    
    // Move to break-even after first take profit
    // Требуется адаптация, основанная на условиях вашей стратегии
    
    // Plotting the unique buy signal and PSAR
    plotshape(unique_buy_signal ? unique_psar[1] : na, title="Unique Buy Signal", location=location.belowbar, color=color.blue, style=shape.labelup, size=size.small)
    plot(unique_psar, title="Unique PSAR", style=plot.style_cross, linewidth=1, color=color.red)
    plot(upperBB, "Upper BB", color=color.purple)
    plot(lowerBB, "Lower BB", color=color.purple)
    
    // Alert condition for the unique buy signal
    alertcondition(unique_buy_signal, title="Unique Buy Alert [PSAR]", message="Unique Buy Signal based on PSAR detected!")
    

    Обратите внимание на некоторые элементы, такие как "Move to break-even after first take profit", которые могут потребовать конкретной адаптации под вашу стратегию и логику в Pine Script.

  19. User

    Аватар Пользователя // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © tanayroy

    //@version=4 study("Binary Option Strategy Tester with Martingale", shorttitle="BOST V.1")

    gp="Strategy Information" i_trade_call_put=input('BOTH',title="Trade Call/Put",type=input.string,options=['BOTH','CALL','PUT'],group=gp) //input on martingale level i_martingale_level=input(1,title="Martingale Level",type=input.integer,minval=1,maxval=5,group=gp) i_martingle_trade=input('SAME',title="Type of Trade",type=input.string, options=['SAME','OPPOSITE','FOLLOW CANDLE COLOR','OPPOSITE CANDLE COLOR'],group=gp) //trading time i_trading_session= input("0930-1600", type=input.session,group=gp) i_use_session=input(false,"Use Specific Session",type=input.bool,group=gp) //check if in session InSession() => time(timeframe.period, i_trading_session) != 0 in_sess=i_use_session?InSession():true long_allowed=i_trade_call_put == 'BOTH' or i_trade_call_put == 'CALL' short_allowed=i_trade_call_put == 'BOTH' or i_trade_call_put == 'PUT' //check martingale way martingale_way(call,put,type)=> out=false if call and type=='NA' out:=close>open else if put and type=='NA' out:=open>close else if type=='SAME' and call out:=close>open else if type=='SAME' and put out:=open>close else if type=='OPPOSITE' and call out:=open>close else if type=='OPPOSITE' and put out:=close>open else if type=='FOLLOW CANDLE COLOR' out:=close[1]>open[1]?close>open:open>close else if type=='OPPOSITE CANDLE COLOR' out:=close[1]>open[1]?close<open:open<close out

    //variable for strategy testing var can_buy_call=false var can_buy_put=false var in_martingale=false var in_trade=false var buy_condition=false var sell_condition=false var int count_call=0 var int count_put=0 var bool cl1win=na var bool cl2win=na var bool cl3win=na var bool cl4win=na var bool cl5win=na var bool closs=na var int count_cl1win=0 var int count_cl2win=0 var int count_cl3win=0 var int count_cl4win=0 var int count_cl5win=0 var int count_closs=0

    var bool pl1win=na var bool pl2win=na var bool pl3win=na var bool pl4win=na var bool pl5win=na var bool ploss=na var int count_pl1win=0 var int count_pl2win=0 var int count_pl3win=0 var int count_pl4win=0 var int count_pl5win=0 var int count_ploss=0 var bool in_profit=false var bool in_loss=false var int max_loss=0 var int consecutive_loss=0 var int max_profit=0 var int consecutive_profit=0

    //// //// //YOUR STRATEGY// //// ////

    //strategy Vdub Binary Options SniperVX v1 by vdubus len = 8 src = close out = sma(src, len) last8h = highest(close, 13) lastl8 = lowest(close, 13) bearish = cross(close,out) == 1 and close[1] > close bullish = cross(close,out) == 1 and close[1] < close channel2=false src0 = close, len0 = 13//input(13, minval=1, title="Trend Change EMA") ema0 = ema(src0, len0)

    //--Modified vyacheslav.shindin-------------------------------------------------// Signal 1 //Configured ema signal output slow = 8 fast = 5 vh1 = ema(highest(avg(low, close), fast), 5) vl1 = ema(lowest(avg(high, close), slow), 8) // e_ema1 = ema(close, 1) e_ema2 = ema(e_ema1, 1) e_ema3 = ema(e_ema2, 1) tema = 1 * (e_ema1 - e_ema2) + e_ema3 // e_e1 = ema(close, 8) e_e2 = ema(e_e1, 5) dema = 2 * e_e1 - e_e2 signal = tema > dema ? max(vh1, vl1) : min(vh1, vl1)

    //strategy for buying call is_call=tema > dema and signal > low and (signal-signal[1] > signal[1]-signal[2])

    //strategy fo selling call is_put=tema < dema and signal < high and (signal[1]-signal > signal[2]-signal[1])

    //*****************************************************************************//

    if is_call and long_allowed can_buy_call:=true can_buy_put:=false

    if is_put and short_allowed can_buy_call:=false can_buy_put:=true

    if can_buy_call and not can_buy_call[1] and not in_trade and in_sess buy_condition:=true in_trade:=true count_call:=count_call+1 else if buy_condition[1] buy_condition:=false

    if can_buy_put and not can_buy_put[1] and not in_trade and in_sess sell_condition:=true in_trade:=true count_put:=count_put+1

    else if sell_condition[1] sell_condition:=false

    call_profit=martingale_way(true,false,'NA') mart_call_profit=martingale_way(true,false,i_martingle_trade) put_profit=martingale_way(false,true,'NA') mart_put_profit=martingale_way(false,true,i_martingle_trade)

    if i_martingale_level==1 if buy_condition[1] and not buy_condition and in_trade and call_profit
    and not sell_condition[1] and not sell_condition count_cl1win:=count_cl1win+1 in_trade:=false cl1win:=true buy_condition:=false sell_condition:=false in_profit:=true in_loss:=false can_buy_call:=false can_buy_put:=false

    else if buy_condition[1] and not buy_condition and not sell_condition[1]  
     and not sell_condition and in_trade and  not call_profit
        count_closs:=count_closs+1
        in_trade:=false
        closs:=true
        buy_condition:=false
        sell_condition:=false
        can_buy_call:=false
        can_buy_put:=false
    

    else if i_martingale_level==2 if buy_condition[1] and not buy_condition and in_trade and call_profit and not sell_condition[1] and not sell_condition[2] and not sell_condition count_cl1win:=count_cl1win+1 in_trade:=false cl1win:=true buy_condition:=false sell_condition:=false in_profit:=true in_loss:=false can_buy_call:=false can_buy_put:=false

    if buy_condition[2] and not buy_condition  and in_trade 
     and  mart_call_profit and not sell_condition[1] and not 
     sell_condition[2] and not sell_condition
        count_cl2win:=count_cl2win+1
        in_trade:=false
        cl2win:=true
        buy_condition:=false
        sell_condition:=false
        in_profit:=true
        in_loss:=false
        can_buy_call:=false
        can_buy_put:=false
        
        
    else if buy_condition[2] and not buy_condition[1] and not buy_condition 
     and not sell_condition[1] and not sell_condition[2]  and 
     not sell_condition and in_trade and  not mart_call_profit
        count_closs:=count_closs+1
        in_trade:=false
        closs:=true
        buy_condition:=false
        sell_condition:=false
        can_buy_call:=false
        can_buy_put:=false
        
    

    else if i_martingale_level==3 if buy_condition[1] and not buy_condition and in_trade and call_profit and not sell_condition[1] and not sell_condition[2] and not sell_condition[3] and not sell_condition count_cl1win:=count_cl1win+1 in_trade:=false cl1win:=true buy_condition:=false sell_condition:=false in_profit:=true in_loss:=false can_buy_call:=false can_buy_put:=false

    if buy_condition[2] and not buy_condition  and in_trade and 
     mart_call_profit and not sell_condition[1] and not sell_condition[2] 
     and not sell_condition[3]  and not sell_condition
        count_cl2win:=count_cl2win+1
        in_trade:=false
        cl2win:=true
        buy_condition:=false
        sell_condition:=false
        in_profit:=true
        in_loss:=false
        can_buy_call:=false
        can_buy_put:=false
        
    if buy_condition[3] and not buy_condition and in_trade and  mart_call_profit 
     and not sell_condition[1] and not sell_condition[2] and not 
     sell_condition[3]  and not sell_condition
        count_cl3win:=count_cl3win+1
        in_trade:=false
        cl3win:=true
        buy_condition:=false
        sell_condition:=false
        in_profit:=true
        in_loss:=false
        can_buy_call:=false
        can_buy_put:=false
        
    else if buy_condition[3] and not buy_condition[2] and not buy_condition[1] 
     and not buy_condition and not sell_condition[1] and not sell_condition[2] 
     and not sell_condition[3]  and not sell_condition and in_trade and 
     not mart_call_profit
        count_closs:=count_closs+1
        in_trade:=false
        closs:=true
        buy_condition:=false
        sell_condition:=false
        can_buy_call:=false
        can_buy_put:=false
    

    else if i_martingale_level==4 if buy_condition[1] and not buy_condition and in_trade and call_profit and not sell_condition[1] and not sell_condition[2] and not sell_condition[3] and not sell_condition[4] and not sell_condition count_cl1win:=count_cl1win+1 in_trade:=false cl1win:=true buy_condition:=false sell_condition:=false in_profit:=true in_loss:=false can_buy_call:=false can_buy_put:=false

    if buy_condition[2] and not buy_condition  and in_trade and  
     mart_call_profit and not sell_condition[1] and not sell_condition[2] 
     and not sell_condition[3] and not sell_condition[4]  and not sell_condition
        count_cl2win:=count_cl2win+1
        in_trade:=false
        cl2win:=true
        buy_condition:=false
        sell_condition:=false
        in_profit:=true
        in_loss:=false
        can_buy_call:=false
        can_buy_put:=false
        
    if buy_condition[3] and not buy_condition and in_trade and  mart_call_profit 
     and not sell_condition[1] and not sell_condition[2] and not sell_condition[3] 
     and not sell_condition[4]  and not sell_condition
        count_cl3win:=count_cl3win+1
        in_trade:=false
        cl3win:=true
        buy_condition:=false
        sell_condition:=false
        in_profit:=true
        in_loss:=false
        can_buy_call:=false
        can_buy_put:=false
        
        
    if buy_condition[4] and not buy_condition and in_trade and  mart_call_profit 
     and not sell_condition[1] and not sell_condition[2] and not sell_condition[3] 
     and not sell_condition[4]  and not sell_condition
        count_cl4win:=count_cl4win+1
        in_trade:=false
        cl4win:=true
        buy_condition:=false
        sell_condition:=false
        in_profit:=true
        in_loss:=false
        can_buy_call:=false
        can_buy_put:=false
        
    else if buy_condition[4] and not buy_condition[3] and not buy_condition[2] 
     and not buy_condition[1] and not buy_condition and not sell_condition[1] 
     and not sell_condition[2] and not sell_condition[3] and not sell_condition[4]  
     and not sell_condition and in_trade and  not mart_call_profit
        count_closs:=count_closs+1
        in_trade:=false
        closs:=true
        buy_condition:=false
        sell_condition:=false
        can_buy_call:=false
        can_buy_put:=false
    

    if i_martingale_level==5 if buy_condition[1] and not buy_condition and in_trade and call_profit and not sell_condition[1] and not sell_condition[2] and not sell_condition[3] and not sell_condition[4] and not sell_condition[5] and not sell_condition count_cl1win:=count_cl1win+1 in_trade:=false cl1win:=true buy_condition:=false sell_condition:=false in_profit:=true in_loss:=false can_buy_call:=false can_buy_put:=false

    if buy_condition[2] and not buy_condition  and in_trade and mart_call_profit 
     and not sell_condition[1] and not sell_condition[2] and not sell_condition[3]
     and not sell_condition[4] and not sell_condition[5] and not sell_condition
        count_cl2win:=count_cl2win+1
        in_trade:=false
        cl2win:=true
        buy_condition:=false
        sell_condition:=false
        in_profit:=true
        in_loss:=false
        can_buy_call:=false
        can_buy_put:=false
        
    if buy_condition[3] and not buy_condition and in_trade and  mart_call_profit
     and not sell_condition[1] and not sell_condition[2] and not sell_condition[3]
     and not sell_condition[4] and not sell_condition[5] and not sell_condition
        count_cl3win:=count_cl3win+1
        in_trade:=false
        cl3win:=true
        buy_condition:=false
        sell_condition:=false
        in_profit:=true
        in_loss:=false
        can_buy_call:=false
        can_buy_put:=false
        
        
    if buy_condition[4] and not buy_condition and in_trade and  mart_call_profit 
     and not sell_condition[1] and not sell_condition[2] and not sell_condition[3] 
     and not sell_condition[4] and not sell_condition[5] and not sell_condition
        count_cl4win:=count_cl4win+1
        in_trade:=false
        cl4win:=true
        buy_condition:=false
        sell_condition:=false
        in_profit:=true
        in_loss:=false
        can_buy_call:=false
        can_buy_put:=false
        
        
    if buy_condition[5] and not buy_condition and not sell_condition[1] and not 
     sell_condition[2] and not sell_condition[3] and not sell_condition[4] and 
     not sell_condition[5] and not sell_condition and in_trade and  mart_call_profit
        count_cl5win:=count_cl5win+1
        in_trade:=false
        cl5win:=true
        buy_condition:=false
        sell_condition:=false
        in_profit:=true
        in_loss:=false
        can_buy_call:=false
        can_buy_put:=false
        
    
    else if buy_condition[5] and not buy_condition[4] and not buy_condition[3] 
     and not buy_condition[2] and not buy_condition[1] and not buy_condition 
     and not sell_condition[1] and not sell_condition[2] and not sell_condition[3] 
     and not sell_condition[4] and not sell_condition[5] and not sell_condition 
     and in_trade and  not mart_call_profit
        count_closs:=count_closs+1
        in_trade:=false
        closs:=true
        buy_condition:=false
        sell_condition:=false
        can_buy_call:=false
        can_buy_put:=false
    
    
    

    if cl1win[1] cl1win:=false if cl2win[1] cl2win:=false if cl3win[1] cl3win:=false if cl4win[1] cl4win:=false if cl5win[1] cl5win:=false if closs[1] closs:=false

    if i_martingale_level==1 if sell_condition[1] and not sell_condition and in_trade and
    put_profit and not buy_condition[1] and not buy_condition count_pl1win:=count_pl1win+1 in_trade:=false pl1win:=true buy_condition:=false sell_condition:=false in_profit:=true in_loss:=false can_buy_call:=false can_buy_put:=false

    else if sell_condition[1] and not sell_condition and not buy_condition[1] 
     and not buy_condition and in_trade and  not put_profit
        count_ploss:=count_ploss+1
        in_trade:=false
        ploss:=true
        buy_condition:=false
        sell_condition:=false
        in_loss:=true
        in_profit:=false
        can_buy_call:=false
        can_buy_put:=false
        
    

    else if i_martingale_level==2 if sell_condition[1] and not sell_condition and in_trade and
    put_profit and not buy_condition[1] and not buy_condition[2]
    and not buy_condition count_pl1win:=count_pl1win+1 in_trade:=false pl1win:=true buy_condition:=false sell_condition:=false in_profit:=true in_loss:=false can_buy_call:=false can_buy_put:=false

    if sell_condition[2] and not sell_condition  and in_trade and mart_put_profit
     and not buy_condition[1] and not buy_condition[2]  and not buy_condition
        count_pl2win:=count_pl2win+1
        in_trade:=false
        pl2win:=true
        buy_condition:=false
        sell_condition:=false
        in_profit:=true
        in_loss:=false
        can_buy_call:=false
        can_buy_put:=false
        
    else if sell_condition[2] and not sell_condition[1] and not sell_condition 
     and not buy_condition[1] and not buy_condition[2]  and not buy_condition 
     and in_trade and  not mart_put_profit
        count_ploss:=count_ploss+1
        in_trade:=false
        ploss:=true
        buy_condition:=false
        sell_condition:=false 
        in_loss:=true
        in_profit:=false
        can_buy_call:=false
        can_buy_put:=false
    
    

    else if i_martingale_level==3 if sell_condition[1] and not sell_condition and in_trade and put_profit and not buy_condition[1] and not buy_condition[2] and not buy_condition[3] and not buy_condition count_pl1win:=count_pl1win+1 in_trade:=false pl1win:=true buy_condition:=false sell_condition:=false in_profit:=true in_loss:=false can_buy_call:=false can_buy_put:=false

    if sell_condition[2] and not sell_condition  and in_trade and  
     mart_put_profit and not buy_condition[1] and not 
     buy_condition[2] and not buy_condition[3]  and not buy_condition
        count_pl2win:=count_pl2win+1
        in_trade:=false
        pl2win:=true
        buy_condition:=false
        sell_condition:=false
        in_profit:=true
        in_loss:=false
        can_buy_call:=false
        can_buy_put:=false
        
        
    if sell_condition[3] and not sell_condition and in_trade and  
     mart_put_profit and not buy_condition[1] and not buy_condition[2] 
     and not buy_condition[3]  and not buy_condition
        count_pl3win:=count_pl3win+1
        in_trade:=false
        pl3win:=true
        buy_condition:=false
        sell_condition:=false
        in_profit:=true
        in_loss:=false
        can_buy_call:=false
        can_buy_put:=false
        
    else if sell_condition[3] and not sell_condition[2] and not 
     sell_condition[1] and not sell_condition and not buy_condition[1] 
     and not buy_condition[2] and not buy_condition[3]  and not buy_condition 
     and in_trade and  not mart_put_profit
        count_ploss:=count_ploss+1
        in_trade:=false
        ploss:=true
        buy_condition:=false
        sell_condition:=false
        in_loss:=true
        in_profit:=false
        can_buy_call:=false
        can_buy_put:=false
    

    else if i_martingale_level==4 if sell_condition[1] and not sell_condition and in_trade and put_profit and not buy_condition[1] and not buy_condition[2] and not buy_condition[3] and not buy_condition[4] and not buy_condition count_pl1win:=count_pl1win+1 in_trade:=false pl1win:=true buy_condition:=false sell_condition:=false in_profit:=true in_loss:=false can_buy_call:=false can_buy_put:=false

    if sell_condition[2] and not sell_condition  and in_trade and  
     mart_put_profit and not buy_condition[1] and not buy_condition[2] 
     and not buy_condition[3] and not buy_condition[4]  and not buy_condition
        count_pl2win:=count_pl2win+1
        in_trade:=false
        pl2win:=true
        buy_condition:=false
        sell_condition:=false
        in_profit:=true
        in_loss:=false
        can_buy_call:=false
        can_buy_put:=false
        
        
    if sell_condition[3] and not sell_condition and in_trade and  mart_put_profit 
     and not buy_condition[1] and not buy_condition[2] and not buy_condition[3] 
     and not buy_condition[4]  and not buy_condition
        count_pl3win:=count_pl3win+1
        in_trade:=false
        pl3win:=true
        buy_condition:=false
        sell_condition:=false
        in_profit:=true
        in_loss:=false
        can_buy_call:=false
        can_buy_put:=false
        
        
    if sell_condition[4] and not sell_condition and in_trade and  mart_put_profit 
     and not buy_condition[1] and not buy_condition[2] and not buy_condition[3] 
     and not buy_condition[4]  and not buy_condition
        count_pl4win:=count_pl4win+1
        in_trade:=false
        pl4win:=true
        buy_condition:=false
        sell_condition:=false
        in_profit:=true
        in_loss:=false
        can_buy_call:=false
        can_buy_put:=false
        
    else if sell_condition[4] and not sell_condition[3] and not sell_condition[2] 
     and not sell_condition[1] and not sell_condition and not buy_condition[1] 
     and not buy_condition[2] and not buy_condition[3] and not buy_condition[4] 
     and not buy_condition and in_trade and  not mart_put_profit
        count_ploss:=count_ploss+1
        in_trade:=false
        ploss:=true
        buy_condition:=false
        sell_condition:=false
        in_loss:=true
        in_profit:=false
        can_buy_call:=false
        can_buy_put:=false
        
    

    else if i_martingale_level==5
    if sell_condition[1] and not sell_condition and in_trade and put_profit and not buy_condition[1] and not buy_condition[2] and not buy_condition[3] and not buy_condition[4] and not buy_condition[5] and not buy_condition count_pl1win:=count_pl1win+1 in_trade:=false pl1win:=true buy_condition:=false sell_condition:=false in_profit:=true in_loss:=false can_buy_call:=false can_buy_put:=false

    if sell_condition[2] and not sell_condition  and in_trade and  mart_put_profit 
     and not buy_condition[1] and not buy_condition[2] and not buy_condition[3] 
     and not buy_condition[4] and not buy_condition[5] and not buy_condition
        count_pl2win:=count_pl2win+1
        in_trade:=false
        pl2win:=true
        buy_condition:=false
        sell_condition:=false
        in_profit:=true
        in_loss:=false
        can_buy_call:=false
        can_buy_put:=false
        
        
    if sell_condition[3] and not sell_condition and in_trade and  mart_put_profit 
     and not buy_condition[1] and not buy_condition[2] and not buy_condition[3] 
     and not buy_condition[4] and not buy_condition[5] and not buy_condition
        count_pl3win:=count_pl3win+1
        in_trade:=false
        pl3win:=true
        buy_condition:=false
        sell_condition:=false
        in_profit:=true
        in_loss:=false
        can_buy_call:=false
        can_buy_put:=false
        
        
    if sell_condition[4] and not sell_condition and in_trade and  mart_put_profit 
     and not buy_condition[1] and not buy_condition[2] and not buy_condition[3] 
     and not buy_condition[4] and not buy_condition[5] and not buy_condition
        count_pl4win:=count_pl4win+1
        in_trade:=false
        pl4win:=true
        buy_condition:=false
        sell_condition:=false
        in_profit:=true
        in_loss:=false
        can_buy_call:=false
        can_buy_put:=false
        
        
    if sell_condition[5] and not sell_condition  and in_trade and  mart_put_profit 
     and not buy_condition[1] and not buy_condition[2] and not buy_condition[3] 
     and not buy_condition[4] and not buy_condition[5] and not buy_condition
        count_pl5win:=count_pl5win+1
        in_trade:=false
        pl5win:=true
        buy_condition:=false
        sell_condition:=false
        in_profit:=true
        in_loss:=false
        can_buy_call:=false
        can_buy_put:=false
        
        
    
    else if sell_condition[5] and not sell_condition[4] and not sell_condition[3] 
     and not sell_condition[2] and not sell_condition[1] and not sell_condition 
     and not buy_condition[1] and not buy_condition[2] and not buy_condition[3] 
     and not buy_condition[4] and not buy_condition[5] and not buy_condition 
     and in_trade and  not mart_put_profit
        count_ploss:=count_ploss+1
        in_trade:=false
        ploss:=true
        buy_condition:=false
        sell_condition:=false
        in_loss:=true
        in_profit:=false
        can_buy_call:=false
        can_buy_put:=false
    

    if in_profit max_profit:=max_profit+1 max_loss:=0 in_profit:=false if in_loss max_loss:=max_loss+1 max_profit:=0 in_loss:=false

    if max_profit>consecutive_profit consecutive_profit:=max_profit

    if max_loss>consecutive_loss consecutive_loss:=max_loss

    if pl1win[1] pl1win:=false if pl2win[1] pl2win:=false if pl3win[1] pl3win:=false if pl4win[1] pl4win:=false if pl5win[1] pl5win:=false if ploss[1] ploss:=false

    plot(buy_condition ?5:0,style=plot.style_columns,color=color.teal) plot(sell_condition ?5:0,style=plot.style_columns,color=color.maroon) // plot(buy_condition?5:0,style=plot.style_columns,color=color.orange)
    plotchar(buy_condition ?5:0, char='C',location=location.absolute) plotchar(sell_condition?5:0, char='P',location=location.absolute)

    plot(cl1win?5:0,style=plot.style_columns,color=color.green) plotchar(cl1win?5:0, char='1',location=location.absolute) plot(cl2win?4:0,style=plot.style_columns,color=color.green) plotchar(cl2win?4:0, char='2',location=location.absolute) plot(cl3win?3:0,style=plot.style_columns,color=color.green) plotchar(cl3win?3:0, char='3',location=location.absolute) plot(cl4win?2:0,style=plot.style_columns,color=color.green) plotchar(cl4win?2:0, char='4',location=location.absolute) plot(cl5win?1:0,style=plot.style_columns,color=color.green) plotchar(cl5win?1:0, char='5',location=location.absolute) plot(closs?5:0,style=plot.style_columns,color=color.red) plotchar(closs?5:0, char='L',location=location.absolute)

    plot(pl1win?5:0,style=plot.style_columns,color=color.green) plotchar(pl1win?5:0, char='1',location=location.absolute) plot(pl2win?4:0,style=plot.style_columns,color=color.green) plotchar(pl2win?4:0, char='2',location=location.absolute) plot(pl3win?3:0,style=plot.style_columns,color=color.green) plotchar(pl3win?3:0, char='3',location=location.absolute) plot(pl4win?2:0,style=plot.style_columns,color=color.green) plotchar(pl4win?2:0, char='4',location=location.absolute) plot(pl5win?1:0,style=plot.style_columns,color=color.green) plotchar(pl5win?1:0, char='5',location=location.absolute) plot(ploss?5:0,style=plot.style_columns,color=color.red) plotchar(ploss?5:0, char='L',location=location.absolute)

    var table _table = table.new(position.bottom_right, 3, 19, border_color=color.black,border_width = 2)

    if barstate.islast table.cell(_table,0,0,"Number of bar Tested",text_color=color.white,bgcolor=#1848CC) table.cell(_table,1,0,tostring(bar_index),text_color=color.white,bgcolor=#1848CC) table.cell(_table,2,0,'100%',text_color=color.white,bgcolor=#1848CC)

    table.cell(_table,0,1,"Number of Call",text_color=color.white,bgcolor=#1848CC)
    table.cell(_table,1,1,tostring(count_call),text_color=color.white,bgcolor=#1848CC)
    table.cell(_table,2,1,tostring((count_call/bar_index)*100,'#.##'),text_color=color.white,bgcolor=#1848CC)
    
    table.cell(_table,0,2,"Level 1 Win",text_color=color.white,bgcolor=#1848CC)
    table.cell(_table,1,2,tostring(count_cl1win),text_color=color.white,bgcolor=#1848CC)
    table.cell(_table,2,2,tostring((count_cl1win/count_call)*100,'#.##'),text_color=color.white,bgcolor=#1848CC)
    
    table.cell(_table,0,3,"Level 2 Win",text_color=color.white,bgcolor=#1848CC)
    table.cell(_table,1,3,tostring(count_cl2win),text_color=color.white,bgcolor=#1848CC)
    table.cell(_table,2,3,tostring((count_cl2win/count_call)*100,'#.##'),text_color=color.white,bgcolor=#1848CC)
    
    table.cell(_table,0,4,"Level 3 Win",text_color=color.white,bgcolor=#1848CC)
    table.cell(_table,1,4,tostring(count_cl3win),text_color=color.white,bgcolor=#1848CC)
    table.cell(_table,2,4,tostring((count_cl3win/count_call)*100,'#.##'),text_color=color.white,bgcolor=#1848CC)
    
    table.cell(_table,0,5,"Level 4 Win",text_color=color.white,bgcolor=#1848CC)
    table.cell(_table,1,5,tostring(count_cl4win),text_color=color.white,bgcolor=#1848CC)
    table.cell(_table,2,5,tostring((count_cl4win/count_call)*100,'#.##'),text_color=color.white,bgcolor=#1848CC)
    
    table.cell(_table,0,6,"Level 5 Win",text_color=color.white,bgcolor=#1848CC)
    table.cell(_table,1,6,tostring(count_cl5win),text_color=color.white,bgcolor=#1848CC)
    table.cell(_table,2,6,tostring((count_cl5win/count_call)*100,'#.##'),text_color=color.white,bgcolor=#1848CC)
    
    table.cell(_table,0,7,"Total Call Profit",text_color=color.white,bgcolor=#1848CC)
    table.cell(_table,1,7,tostring(count_cl1win+count_cl2win+count_cl3win+count_cl4win+count_cl5win),text_color=color.white,bgcolor=#1848CC)
    table.cell(_table,2,7,tostring(((count_cl1win+count_cl2win+count_cl3win+count_cl4win+count_cl5win)/count_call)*100,'#.##'),
     text_color=color.white,bgcolor=#1848CC)
    
    table.cell(_table,0,8,"Loss",text_color=color.white,bgcolor=#1848CC)
    table.cell(_table,1,8,tostring(count_closs),text_color=color.white,bgcolor=#1848CC)
    table.cell(_table,2,8,tostring((count_closs/count_call)*100,'#.##'),text_color=color.white,bgcolor=#1848CC)
    
    table.cell(_table,0,9,"Number of Put",text_color=color.white,bgcolor=#ff4a68)
    table.cell(_table,1,9,tostring(count_put),text_color=color.white,bgcolor=#ff4a68)
    table.cell(_table,2,9,tostring((count_put/bar_index)*100,'#.##'),text_color=color.white,bgcolor=#ff4a68)
    
    table.cell(_table,0,10,"Level 1 Win",text_color=color.white,bgcolor=#ff4a68)
    table.cell(_table,1,10,tostring(count_pl1win),text_color=color.white,bgcolor=#ff4a68)
    table.cell(_table,2,10,tostring((count_pl1win/count_put)*100,'#.##'),text_color=color.white,bgcolor=#ff4a68)
    
    table.cell(_table,0,11,"Level 2 Win",text_color=color.white,bgcolor=#ff4a68)
    table.cell(_table,1,11,tostring(count_pl2win),text_color=color.white,bgcolor=#ff4a68)
    table.cell(_table,2,11,tostring((count_pl2win/count_put)*100,'#.##'),text_color=color.white,bgcolor=#ff4a68)
    
    table.cell(_table,0,12,"Level 3 Win",text_color=color.white,bgcolor=#ff4a68)
    table.cell(_table,1,12,tostring(count_pl3win),text_color=color.white,bgcolor=#ff4a68)
    table.cell(_table,2,12,tostring((count_pl3win/count_put)*100,'#.##'),text_color=color.white,bgcolor=#ff4a68)
    
    table.cell(_table,0,13,"Level4 Win",text_color=color.white,bgcolor=#ff4a68)
    table.cell(_table,1,13,tostring(count_pl4win),text_color=color.white,bgcolor=#ff4a68)
    table.cell(_table,2,13,tostring((count_pl4win/count_put)*100,'#.##'),text_color=color.white,bgcolor=#ff4a68)
    
    table.cell(_table,0,14,"Level 5 Win",text_color=color.white,bgcolor=#ff4a68)
    table.cell(_table,1,14,tostring(count_pl5win),text_color=color.white,bgcolor=#ff4a68)
    table.cell(_table,2,14,tostring((count_pl5win/count_put)*100,'#.##'),text_color=color.white,bgcolor=#ff4a68)
    
    table.cell(_table,0,15,"Total Put Profit",text_color=color.white,bgcolor=#ff4a68)
    table.cell(_table,1,15,tostring(count_pl1win+count_pl2win+count_pl3win+count_pl4win+count_pl5win),text_color=color.white,bgcolor=#ff4a68)
    table.cell(_table,2,15,tostring(((count_pl1win+count_pl2win+count_pl3win+count_pl4win+count_pl5win)/count_put)*100,'#.##'),
     text_color=color.white,bgcolor=#ff4a68)
    
    table.cell(_table,0,16,"Loss",text_color=color.white,bgcolor=#ff4a68)
    table.cell(_table,1,16,tostring(count_ploss),text_color=color.white,bgcolor=#ff4a68)
    table.cell(_table,2,16,tostring((count_ploss/count_put)*100,'#.##'),text_color=color.white,bgcolor=#ff4a68)
    
    table.cell(_table,0,17,"Profit in a row",text_color=color.white,bgcolor=#056b60)
    table.cell(_table,1,17,tostring(consecutive_profit),text_color=color.white,bgcolor=#056b60)
    table.cell(_table,2,17,tostring((consecutive_profit/(count_call+count_put))*100,'#.##'),text_color=color.white,bgcolor=#056b60)
    
    table.cell(_table,0,18,"Loss in a row",text_color=color.white,bgcolor=#c71c69)
    table.cell(_table,1,18,tostring(consecutive_loss),text_color=color.white,bgcolor=#c71c69)
    table.cell(_table,2,18,tostring((consecutive_loss/(count_call+count_put))*100,'#.##'),text_color=color.white,bgcolor=#c71c69)
    
    
    
    
    
    здравствуйте замените сигнал так чтобы прикасания боллинджера было.. типа коснулось один раз боллинджера и если не зошло то в таблице тоже отображается количество дн
    
  20. Assistant

    Для изменения сигнала на основе прикосновения к линиям Боллинджера и последующего его отображения в таблице, мы можем изменить логику сигнала и способ подсчета результатов в вашем Pine Script коде. Будем исходить из предположения, что "прикосновением" считается момент, когда цена закрытия бара оказывается за пределами линий Боллинджера. В качестве образца возьмем простую систему, в которой:

    • Сигнал на покупку (Call) генерируется, когда цена закрытия предыдущего бара касается или выходит за верхнюю линию Боллинджера.
    • Сигнал на продажу (Put) генерируется, когда цена закрытия предыдущего бара касается или выходит за нижнюю линию Боллинджера.

    Добавим в код определение сигнала прикосновения к линиям Боллинджера и внесем изменения в логику подсчета результатов. Учтите, что ваша стратегия требует конкретизации условий "если не зашло", чтобы точно выполнять подсчет.

    //@version=4
    study("Binary Option Strategy Tester with Martingale", shorttitle="BOST V.1")
    
    // Ваши настройки и определения ...
    
    // Расчет линий Боллинджера
    basis = sma(close, lengthBB)
    dev = multBB * stdev(close, lengthBB)
    upperBB = basis + dev
    lowerBB = basis - dev
    
    // Новая логика для сигналов на основании прикосновения к Боллинджеру
    is_call = close[1] > upperBB[1] // Используйте [1] для рассмотрения предыдущего бара
    is_put = close[1] < lowerBB[1] 
    
    // Следующий код остается без изменений до блоков подсчета результатов ...
    
    // Модификации ваших блоков подсчета результатов и вывода
    
    // Пример реализации для счетчика "если не зашло"
    var int touchBollingerCount = 0
    if (is_call or is_put)
        touchBollingerCount := touchBollingerCount + 1
        // Дополнительная логика для определения, "вошло" ли прикосновение в соответствии с вашими условиями
        // Это может включать проверку результатов сделки
        // В трейдинге опционами "если не зашло" может означать, что прогноз по направлению цены был неверен
        // Например, если вы ожидаете роста цены после прикосновения к нижней линии Боллинджера, но цена падает
    
    // Для отображения в таблице добавьте переменную touchBollingerCount к соответствующим ячейкам
    
    // Продолжение вашего кода ...
    

    Этот фрагмент демонстрирует, как можно начать адаптацию вашего скрипта под новые требования. Важно продумать логику определения "если не зашло" в контексте вашей стратегии, а также корректно отразить все необходимые изменения в таблице результатов. Поскольку полный код вашей стратегии и детали ожидаемого поведения после прикосновения к Боллинджеру не предоставлены, предложенное изменение должно рассматриваться как отправная точка для дальнейших модификаций.

  21. User

    In Binary options, strategy testing is a bit different. The script is just a try to test Binary options strategies. Assumption: We are opening position at next candle after signal come We are taking the position at opening price Our call will be profitable if we get a green candle and put will be profitable if we get a red candle We can open only one trade at a time. So if we are in trade, subsequent signals will be ignored. The script is not counting your profit or loss, it just counting the winning and losing trades.

    Input Options: Choose long only or short only test. Default is both. You can continue your trade with Martingale Level, up to 5. Default is 1 (no Martingale) You can choose Martingale trade type SAME: if call subsequent trade will be call only and vice versa OPPOSITE: if call subsequent trade will be put FOLLOW CANDLE COLOR: Subsequent trade will follow previous candle color OPPOSITE CANDLE COLOR: Subsequent trade will opposite of previous candle color You can choose trading session to test. Default is false. надо чтобы боллинджер был как вход и напиши полностью код в таблице отображается если не зашло просто в красную зону по истечению 4 минуты короче эксперация опциона бинарного 4 минуты надо чтобы при касании болинджера и если через 4 минуты цена ниже закрытия свечи то опцион зашел если наоборот то нет используя мартингейл таблицы

  22. Assistant

    Ваш запрос включает в себя разработку полного скрипта стратегии для тестирования вариантов двоичных опционов с использованием линий Боллинджера, а также мартингейловой системы для управления ставками при убыточных сделках. Давайте сформулируем скрипт, который будет соответствовать вашему описанию.

    Следует заметить, что напрямую реализовать "экспирацию опциона" через 4 минуты в Pine Script нельзя, так как Pine Script работает на основе тиков данных (баров/свечей), а не реального времени. Вместо этого мы будем использовать бары, чтобы аппроксимировать это время. Например, если вы используете таймфрейм в 1 минуту, то 4 бара будут эквивалентны 4 минутам.

    Я создам базовый скрипт для начала, который можно дополнительно модифицировать с течением времени:

    //@version=4
    strategy("Binary Option Strategy Tester with Bollinger Bands Martingale", shorttitle="BOST BB Martingale V.1", overlay=true)
    
    // Входы
    i_trade_call_put = input('BOTH', title="Trade Call/Put", type=input.string, options=['BOTH', 'CALL', 'PUT'])
    i_martingale_level = input(1, title="Martingale Level", type=input.integer, minval=1, maxval=5)
    i_martingle_trade = input('SAME', title="Type of Martingale Trade", type=input.string, options=['SAME', 'OPPOSITE', 'FOLLOW CANDLE COLOR', 'OPPOSITE CANDLE COLOR'])
    
    // Параметры для Bollinger Bands
    lengthBB = input(20, title="BB Length")
    multBB = input(2.0, title="BB Multiplier")
    basisBB = sma(close, lengthBB)
    devBB = multBB * stdev(close, lengthBB)
    upperBB = basisBB + devBB
    lowerBB = basisBB - devBB
    
    // Логика торговли
    var trade_counter = 0
    var win_counter = 0
    var loss_counter = 0
    var martingale_counter = 0
    var in_trade = false
    
    touchUpperBB() => close[1] > upperBB[1] and not in_trade
    touchLowerBB() => close[1] < lowerBB[1] and not in_trade
    
    processTrade(result) =>
        if result
            win_counter := win_counter + 1
            martingale_counter := 0
        else
            loss_counter := loss_counter + 1
            martingale_counter := martingale_counter < i_martingale_level ? martingale_counter + 1 : 0
        in_trade := false
    
    if touchUpperBB()
        trade_counter := trade_counter + 1
        in_trade := true
        strategy.entry("Call Entry", strategy.long)
        
    if touchLowerBB()
        trade_counter := trade_counter + 1
        in_trade := true
        strategy.entry("Put Entry", strategy.short)
        
    // Экспирация на 4 бара позже
    if (in_trade and bar_index - strategy.opentrades.entry_bar_index(strategy.opentrades - 1) == 4)
        if (i_trade_call_put == 'CALL' and close > strategy.opentrades.entry_price(strategy.opentrades - 1)) or (i_trade_call_put == 'PUT' and close < strategy.opentrades.entry_price(strategy.opentrades - 1))
            processTrade(true)
        else
            processTrade(false)
        
        
    // Вывод
    plotshape(series=touchUpperBB(), style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small, title="Call Signal")
    plotshape(series=touchLowerBB(), style=shape.triangledown, location=location.abovebar, color=color.red, size=size.small, title="Put Signal")
    hline(y=win_counter, color=color.green, linestyle=hline.style_solid, title="Wins")
    hline(y=loss_counter, color=color.red, linestyle=hline.style_solid, title="Losses")
    

    Этот код задает основу для тестирования стратегии бинарных опционов с использованием линий Боллинджера для генерации торговых сигналов и мартингейловой системы для нарастания ставок после проигрышных сделок. Важно отметить, что реальная торговля бинарными опционами влечет значительные риски, и использование мартингейла может привести к быстрым и значительным потерям.