Strategy · Pine Script v5 · On the chart

Order strgy SA SOT

by DaniilOkrug· code credited to ic3walk

This strategy identifies SA signals for long entries and SOT signals for short entries.

View on GitHub

Repaints

GitHub stars2on the repository
Pine versionv5runs as is
Lines of code205
Settings6inputs
LicenceMIT
Last update4 years ago15 Dec 2021

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new strategy, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart. The trades and results appear in the Strategy Tester tab; adjust the settings with the gear icon.

Source Code

205 lines of Pine Script v5 from [Order] strgy_SS_SOT.txt, published under MIT. Keep the author's credit and licence lines when you reuse it.

[Order] strgy_SS_SOT.txt

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ©ic3walk
//@version=5

// Описание стратегии. Желательно, не удалять. Описание необходимо для напоминания о том, что делает скрипт.
// Стратегия ориентирована на потиковую торговлю.
// Стратегия определяет сигнала SA(вход в лонг) и SOT(вход в шорт). 
// В ней присутствует 2 режим. Стандартный - всегда открыта 1 сделка и может быть закрыта только при достижении стоп-лосса или тейк-профита.
// Закрытие на противоположном сигнале - открыта 1 позиция и при появлении противоположного сигнала она зывкрывается и появляется новый ордер. Сигналы в том же направлении игнорируются.
// После появления сигнала(SA/SOT) выставляется отложенный ордер на вход в сделку(чуть выше/ниже свечи).
// Стоп-лосс выставляется чусть ниже/выше свечи.
// Тейк-профит определяется колчиством рассоянии от цены входа в позцию(отложенный ордер) до стоплосса. Данное количесвто задается во входном параметре.
// Если после сигнала проходит определенное количество баров(входной параметр) и ордер не открыт, то сигнал игнорируется.

strategy("[Order] strgy_SA_SOT", overlay=true, calc_on_every_tick=true, pyramiding=10)

//--INPUT--

difference = input.float(0.005, title="Разница", tooltip="Значение, которое используется при расчете SL и цены открытия позиции.")/100
tp_count = input.int(3, title="TP", tooltip="Количество размеров расстаяние от цены открытия до стоплосса для TP.")
bars = input(2, title="Количество баров", tooltip="Количество баров после которого сигнал перестает быть действительным.")

tradingMode_tooltpMesssage = "Cтандартный - только одна позиция может быть открытой. Следующая позиция может быть открыта только после закрытия текущей. Закрытие на противоположном сигнале - при появлении проивоположного сигнала, старая закрывается."
tradingMode = input.string("Cтандартный", title="Торговый режим", options=["Cтандартный", "Закрытие на противоположном сигнале"], tooltip=tradingMode_tooltpMesssage)

liveTrading = input.bool(true, title="Живая торговля", tooltip="Сигналы на истории игнорируются")

showSL_TP = input.bool(false, title="Показать SL и TP", group="Визуальная часть")

//--INPUT END--

part = (high - low) / 3
_sa_part1 = high - part
_sot_part3 = low + part

//Условие SA сигнала
SA = close >= close [1] and ta.crossover(close, _sa_part1) and  open > _sa_part1

//Усливие SOT сигнала
SOT = close <= close[1] and ta.crossunder(close, _sot_part3) and open < _sot_part3

//Задание цвета сигнальному бару
barcolor (SA ? color.green : na)
barcolor(SOT ? color.red : na)

//Основные переменные
varip float openPrice = na                  //Entry price
varip float takeProfit = na                 //TP price of the current opened position
varip float stopLoss = na                   //SL price of the current opened position
varip float takeProfit_tmp = na             //TP of the signal position
varip float stopLoss_tmp = na               //SL of the signal position

varip int initialIndexOfBar = na            //Bar index of the signal position

var bool isSA = na                          //Determine type of the signla SA/SOT

//Closing orders by TP or SL
//Закрытие ордеров по тейк-профиту
// if strategy.position_size > 0 and close > takeProfit
//     strategy.close_all(comment="TakeProfit")
    
// if strategy.position_size < 0 and close < takeProfit
//     strategy.close_all(comment="TakeProfit")

// //Закрытие ордеров по стоп-лоссу
// if strategy.position_size < 0 and close > stopLoss
//     strategy.close_all(comment="StopLoss")
    
// if strategy.position_size > 0 and close < stopLoss
    // strategy.close_all(comment="StopLoss")
if strategy.position_size > 0
    strategy.exit("Close long", "Long", limit=takeProfit, stop=stopLoss)
else if strategy.position_size < 0
    strategy.exit("Close short", "Short", limit=takeProfit, stop=stopLoss)

if strategy.opentrades == 0
    takeProfit := na
    stopLoss := na
    
//Определение сигналов
//SA сигнал
if SA and barstate.isconfirmed
    alert("SA")

    // При 2 режиме торговли приходит противоположный сигнал, то мы закрываем ордер
    if tradingMode == "Закрытие на противоположном сигнале" and strategy.position_size < 0
        strategy.entry("Long", strategy.long)
        
        openPrice := high + high * difference
        stopLoss := low - low * difference
        takeProfit := openPrice + math.abs(openPrice - stopLoss) * tp_count
        
        openPrice := na
    
    if strategy.opentrades == 0
        isSA := true
    
        openPrice := high + high * difference //Определяем цену открытия ордера для сигнала
    
        stopLoss_tmp := low - low * difference
        takeProfit_tmp := openPrice + math.abs(openPrice - stopLoss_tmp) * tp_count
        
        initialIndexOfBar := bar_index

//SOT сигнал
if SOT and barstate.isconfirmed
    alert("SOT")
    
    // При 2 режиме торговли приходит противоположный сигнал, то мы закрываем ордер
    if tradingMode == "Закрытие на противоположном сигнале" and strategy.position_size > 0
        strategy.entry("Short", strategy.short)
        
        openPrice := low - low * difference
        stopLoss := high + high * difference
        takeProfit := openPrice - math.abs(stopLoss - openPrice) * tp_count
        openPrice := na
    
    if strategy.opentrades == 0
        isSA := false
        openPrice := low - low * difference //Определяем цену открытия ордера для сигнала
        
        stopLoss_tmp := high + high * difference
        takeProfit_tmp := openPrice - math.abs(stopLoss_tmp - openPrice) * tp_count
        
        initialIndexOfBar := bar_index
        

//Подсчет количество баров после сигнала
if bar_index - initialIndexOfBar >= bars
    openPrice := na
  
//Открытие ордеров
if (liveTrading and barstate.isrealtime) or not liveTrading
    //Услвовия откртия позиций
    openLong_condition = close >= openPrice and isSA and not na(openPrice)
    openShort_condition = close <= openPrice and not isSA and not na(openPrice)
    
    //Определяем торговый режим
    if tradingMode == "Cтандартный"
        if openLong_condition and strategy.opentrades == 0
            strategy.entry("Long", strategy.long)
            
            stopLoss := stopLoss_tmp
            takeProfit := takeProfit_tmp
            
            openPrice := na
            stopLoss_tmp := na
            takeProfit_tmp := na
    
        if openShort_condition and strategy.opentrades == 0
            strategy.entry("Short", strategy.short)
            
            stopLoss := stopLoss_tmp
            takeProfit := takeProfit_tmp
            
            openPrice := na
            stopLoss_tmp := na
            takeProfit_tmp := na

    else //"Закрытие на противоположном сигнале" mode
        if openLong_condition
            if strategy.opentrades == 0
                strategy.entry("Long", strategy.long)
                
                stopLoss := stopLoss_tmp
                takeProfit := takeProfit_tmp
                initialIndexOfBar := bar_index
            else if strategy.position_size < 0
                strategy.entry("Long", strategy.long)
                
                stopLoss := stopLoss_tmp
                takeProfit := takeProfit_tmp
                initialIndexOfBar := bar_index
            
            openPrice := na
            stopLoss_tmp := na
            takeProfit_tmp := na
        
        if openShort_condition
            if strategy.opentrades == 0
                strategy.entry("Short", strategy.short)
                
                stopLoss := stopLoss_tmp
                takeProfit := takeProfit_tmp
                initialIndexOfBar := bar_index
            else if strategy.position_size > 0
                strategy.entry("Short", strategy.short)
                
                stopLoss := stopLoss_tmp
                takeProfit := takeProfit_tmp
                initialIndexOfBar := bar_index
            
            openPrice := na
            stopLoss_tmp := na
            takeProfit_tmp := na

//--VISUAL PART--//
plot(showSL_TP ? stopLoss : na, color=color.red)
plot(showSL_TP ? takeProfit : na, color=color.green)

plotshape(SA and barstate.isconfirmed, style=shape.triangleup, color=color.green, size = size.auto, location=location.belowbar)
plotchar(SA and barstate.isconfirmed, text="SA",char="", color=color.green, location=location.belowbar)
plotshape(SOT and barstate.isconfirmed, style=shape.triangledown, color=color.red, size = size.auto, location=location.abovebar)
plotchar(SOT and barstate.isconfirmed, text="SOT",char="", color=color.red, location=location.abovebar)

Overview

Order strgy SA SOT places pending orders with stop loss and take profit. The take profit distance equals tp_count multiplied by the distance from entry to stop loss. The difference input sets both the stop loss offset and pending order price. Signals remain valid for the number of bars specified. Two trading modes exist: standard opens one position only or closes on opposite signal. Historical signals are ignored when live trading is enabled. The strategy repaints on the live bar and draws stop loss and take profit lines on the price chart when enabled.

Details

Published by

DaniilOkrug on GitHub

Code credit

ic3walk, as written in the script's header

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

SMC / ICT / price action, Support & resistance

Markets

Forex

Timeframes

Any timeframe

Risk Notes

  • Signals can change on the live bar or after it closes (repainting)
  • The strategy can add several entries in the same direction

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Разницаfloat0.005difference
TPint3tp_count
Количество баровint2bars
Торговый режимstringCтандартныйtradingMode
Живая торговляbooltrueliveTrading
Показать SL и TPboolfalseshowSL_TP
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

Daily Bias + FVG Strategy

by TradersPost
218 stars

This overlay strategy plots previous-day high and low, the daily open, and fair value gap zones on the price chart. It takes entries on a selectable timeframe when the FVG requirement and an optional session window allow them, then uses an ATR or fixed pip sto

Strategy v6 SMC / ICT / price actionSupport & resistance Repaints
Updated 3 months ago · None stated GitHub repository of Daily Bias + FVG Strategy
105 stars

Gold Scalping BOS & CHoCH is an overlay strategy designed for detecting market structure shifts. It calculates rolling swing highs and lows to identify Break of Structure (BOS) and Change of Character (CHoCH) events. Long signals trigger when bullish BOS and C

Strategy v6 SMC / ICT / price actionSupport & resistance
Updated 1 year ago · None stated GitHub repository of Gold Scalping BOS & CHoCH

P404 Smoke

by Musyimi97
16 stars

P404 Smoke is a price-chart strategy that sequences an optional higher-timeframe EMA bias, a liquidity range from recent pivots, a sweep of buy-side or sell-side liquidity, and a market structure shift within a set bar window. Comments state it then looks for

Strategy v5 SMC / ICT / price actionSupport & resistance
Updated 6 months ago · MIT GitHub repository of P404 Smoke

FairValueGap C003

by ruckard
13 stars

FairValueGap C003 is an overlay strategy that identifies Fair Value Gaps (FVG) and opens trades expecting price to return and fill the gap. It calculates the distance between current price levels and recent gap boundaries to aim for partial or full gap fills.

Strategy v5 SMC / ICT / price actionSupport & resistance
Updated 1 year ago · None stated GitHub repository of FairValueGap C003

SMC Strategy

by tsunafire
10 stars

SMC Strategy is a Pine Script v5 overlay strategy based on smart money concepts. It flags market structure shifts from ten-bar highs and lows, draws bullish and bearish order blocks as rectangles when that option is on, and marks liquidity sweeps with short li

Strategy v5 SMC / ICT / price actionSupport & resistance Repaints
Updated 2 years ago · None stated GitHub repository of SMC Strategy

This strategy identifies reversal opportunities based on liquidity sweeps and multi-gate confluence scoring. It evaluates setups using mandatory conditions such as swing sweeps, body and ATR filters, and dual EMA higher-timeframe trend alignment, alongside opt

Strategy v6 SMC / ICT / price actionTrend
Updated yesterday · MIT GitHub repository of Reversal Engine Score [WavesUnchained] Strategy

More strategys

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers