0% found this document useful (0 votes)
9 views16 pages

code_1

The document is a source code for a trading indicator called 'BE - Golden Cross Crude Key' designed for use in TradingView. It includes various settings for trade scanning, trend tracking, and trade alerts, allowing users to customize their trading experience. The code also implements features for real-time trade notifications, trade logging, and hedging options for futures trading.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views16 pages

code_1

The document is a source code for a trading indicator called 'BE - Golden Cross Crude Key' designed for use in TradingView. It includes various settings for trade scanning, trend tracking, and trade alerts, allowing users to customize their trading experience. The code also implements features for real-time trade notifications, trade logging, and hedging options for futures trading.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 16

// This source code is subject to the terms of the Mozilla Public License 2.

0 at
https://mozilla.org/MPL/2.0/
// © TradeWiseWithEase

//@version=5
indicator("BE - Golden Cross Crude Key",shorttitle = "BE-CRUDE-V0.1.1", overlay =
true)
import TradeWiseWithEase/BE_CustomFx_Library/93 as BEL

var string GroupText1 = "Trade Scan Settings"


var string GroupText2 = "Trend Tracker Settings"
var string GroupText3 = "Trade Alerts Settings"
var string GroupText4 = "Trade Table Settings"
var string RealtimeTip = "If Enabled Trade 'ENTRIES' & 'EXITS' shall
be on the 'REALTIME' upon 'PRICE' hitting the 'ENTRY ZONE' OR 'SL ZONE' even on the
'yet to complete candle' or trade gets 'CLOSED' Upon specific 'PROFIT BOOKING
ZONES' on realtime basis.\n\nSince It doesn't wait for the close of the candle to
happen, there may be possibility of showing the 'ENTRIES' which would have closed
in realtime but it may still be showing as 'RUNNING' upon 'CHART REFRESH'.\n\nIf
set to True, Trades will be notified while the candle is forming / Yet to complete.
Else Trades will be notified upon CLOSE of the candle."
var string HedgeTTIP = "This Option Allows you to place HEDGE Leg
(options) to avail margin benefit for trades placed in FUTURES.\n\nEnsure to Update
Correct Options Symbols along with Expiry Date in the fields provided\n\nDefault 10
refers to 10 OTM CE & PE & the option Legs are brought during the first trade and
the same shall be squared off when the TRADING SESSION is CLOSED"
var string UseA_NameTTP = "Plz use symbol constructor from NLB
webportal\n\n https://nextlevelbot.com/broker_symbol \n\nIMPORTANT: SPECIFY THE
TRADING ACCOUNT NAME CORRECTLY AND USE ': WITH A SPACE'\n\nUSE 'FORWARDSLASH /' TO
SEPARATE THE SYMBOLS BETWEEN FUTURES AND OPTIONS"
var string SymbolTextA = 'DHANHQ: CRUDEOIL23FEBFUT/CRUDEOIL23FEB' + '\
n' + 'TRADINGVIEW: CRUDEOIL23FEBFUT/CRUDEOIL23FEB'

//#region Trade Scan Settings


var string sess = input.session(
defval = '1800-2330',
title = 'Trade Session',
group = GroupText1,
tooltip = "Default Values refers to -->\n\nTrade Entries Shall be Scanned Post
6 PM and any Open Position Shall be Squared Off Post 11:00 PM or Close of the
Candle Whichever is LATER.")

var string NoFreshEntryTime = "0000-" + input.string(


defval = '2230',
title = 'No Fresh Entry Post',
group = GroupText1)

var bool ShowPlots = input.bool(


defval = true,
title = "Show SMA Line",
inline = "SMA",
group = GroupText1)

var color SMAClr = input.color(


defval = color.orange,
title = "",
inline = "SMA",
group = GroupText1)
var int SMAWidth = input.int(
defval = 1,
title = "",
inline = "SMA",
group = GroupText1)

var int SMALength = input.int(


defval = 42,
title = "",
inline = "SMA",
minval = 1,
group = GroupText1)

SMAValue = ta.sma(close, SMALength)


plot(
ShowPlots ? SMAValue : na,
title = "SMA Value",
linewidth = SMAWidth,
color = SMAClr,
editable = false)
//#endregion

//#region Trend Tracker Settings


var int Mode = input.int(
defval = 2,
title = "Tracker Mode",
minval = 1,
group = GroupText2)

var int Sensitivity = input.int(


defval = 1,
title = "Sensitivity [0 - 2]",
group = GroupText2,
minval = 0,
maxval = 2,
tooltip = "Low Value looks for More confirmed pattern, High value predicts for
Possible Confirmation.")

var bool ShowTrendTracker = input.bool(


defval = true,
title = "Show Trend Tracker",
group = GroupText2)

var color Tr_LongClr = input.color(


defval = #0cd0deed,
title = "Up",
inline = "TT",
group = GroupText2)

var color Tr_ShortClr = input.color(


defval = #cd13db,
title = "Dn",
inline = "TT",
group = GroupText2)

var int Tr_LineWidth = input.int(


defval = 1,
title = "",
inline = "TT",
group = GroupText2)

//#region Trend Tracker Calculation


var int Trend_Direction = 0
var int NxtTrend_Direction = 0
var float MaxLowPrice = nz(low[1], low)
var float MinHighPrice = nz(high[1], high)
var float TrendLevel = 0.0
var float CapUp = 0.0
var float CapDown = 0.0
float ATR2Level = ta.atr(100) / 2
float HighPrice = high[math.abs(ta.highestbars(Mode))]
float LowPrice = low[math.abs(ta.lowestbars(Mode))]
float HighMovAvg = ta.sma(Sensitivity == 0 ? high :
Sensitivity == 1 ? hlc3 : hl2, Mode)
float LowMovAvg = ta.sma(Sensitivity == 0 ? low :
Sensitivity == 1 ? hlc3 : hl2, Mode)
float SMAofATR = ta.sma(ATR2Level[1], 4)
Bars_SMAH_LT_InfoHighestLow = ta.barssince(not (HighMovAvg <
MaxLowPrice))
Bars_SMAL_GT_InfolowestHigh = ta.barssince(not (LowMovAvg >
MinHighPrice))
ConvertHT2Long = (((close - TrendLevel) > SMAofATR * 3.25)
or Bars_SMAL_GT_InfolowestHigh == 3) and NxtTrend_Direction == 1 and close >
TrendLevel and barstate.isconfirmed
ConvertHT2Short = (((TrendLevel - close) > SMAofATR * 3.25)
or Bars_SMAH_LT_InfoHighestLow == 3) and NxtTrend_Direction == -1 and close <
TrendLevel and barstate.isconfirmed

if barstate.isconfirmed
if NxtTrend_Direction == -1
MaxLowPrice := math.max(LowPrice, MaxLowPrice)
if HighMovAvg < MaxLowPrice and close < nz(low[1], low) and (Sensitivity <
1 or (Sensitivity >= 1 and (MaxLowPrice - close) > SMAofATR * 1.75))
Trend_Direction := -1
NxtTrend_Direction := 1
MinHighPrice := HighPrice
else if ConvertHT2Short and Sensitivity >= 1
Trend_Direction := -1
NxtTrend_Direction := 1
MinHighPrice := HighPrice
else
MinHighPrice := math.min(HighPrice, MinHighPrice)
if LowMovAvg > MinHighPrice and close > nz(high[1], high) and (Sensitivity
< 1 or (Sensitivity >= 1 and (close - MinHighPrice) > SMAofATR * 1.75))
Trend_Direction := 1
NxtTrend_Direction := -1
MaxLowPrice := LowPrice
else if ConvertHT2Long and Sensitivity >= 1
Trend_Direction := 1
NxtTrend_Direction := -1
MaxLowPrice := LowPrice

if Trend_Direction == 1
if Trend_Direction[1] == -1 and not na(Trend_Direction[1])
CapUp := na(CapDown[1]) ? CapDown : CapDown[1]
else
CapUp := na(CapUp[1]) ? MaxLowPrice :
math.max(MaxLowPrice, CapUp[1])
else
if Trend_Direction[1] == 1 and not na(Trend_Direction[1])
CapDown := na(CapUp[1]) ? CapUp : CapUp[1]
else
CapDown := na(CapDown[1]) ? MinHighPrice :
math.min(MinHighPrice, CapDown[1])

TrendLevel := Trend_Direction == 1 ? CapUp : CapDown


TrendColor = Trend_Direction == 1 ? Tr_LongClr :
Tr_ShortClr

plot(
ShowTrendTracker ? TrendLevel : na,
title = "Trend Tracker",
linewidth = Tr_LineWidth,
color = TrendColor,
editable = false)
//#endregion

//#endregion

//#region Trade Alerts Settings


var bool IsRealTime = input.bool(
defval = true,
title = "Trade On Realtime ?",
group = GroupText3,
tooltip = RealtimeTip)

var string SymbolText = str.upper(input.text_area(


defval = SymbolTextA,
title = "Symbol Name. Read Tips -->",
group = GroupText3,
tooltip = UseA_NameTTP))

//#region SymbolExtract Procedure


var ListOfTradingAccount = array.new_string(0)
var ListOfFuturePrefix = array.new_string(0)
var ListOfOptionsPrefix = array.new_string(0)
var SplitOfInputList = str.split(SymbolText,"\n")
var CountOfNLB_AccountsProvided = array.size(SplitOfInputList)

if barstate.isfirst and CountOfNLB_AccountsProvided > 0


array.clear(ListOfTradingAccount)
for [index, value] in SplitOfInputList
AccountSplit = str.split(value,": ")
if array.size(AccountSplit) > 0
array.push(ListOfTradingAccount, array.get(AccountSplit, 0))
ScriptSplit = str.split(array.get(AccountSplit, 1),"/")
if array.size(ScriptSplit) > 0
for [index_, value_] in ScriptSplit
if str.endswith(value_,"FUT") or str.endswith(value_,"F")
array.push(ListOfFuturePrefix, array.get(ScriptSplit,
index_))
else
array.push(ListOfOptionsPrefix, array.get(ScriptSplit,
index_))
else
runtime.error("Couldn't Extract the NLB TradingAccount List")
break
//#endregion

var bool AvoidOnWed = input.bool(


defval = true,
title = "Avoid Trade On Wednesday",
group = GroupText3)

var bool TakeTrendConfirmation = input.bool(


defval = true,
title = "Confirm Trade With Trend Direction",
group = GroupText3)

var int TradeQty = input.int(


defval = 100,
title = "Qty Per Trade",
group = GroupText3,
step = 100,
minval = 1)

var string FutOrOps = input.string(


defval = "FUT",
title = "Trade On Type",
group = GroupText3,
options = ["FUT","OPS"])

var string IAO = input.string(


defval = "ATM",
title = "Option Moneyness. ",
group = GroupText3,
options = ["ITM","OTM","ATM"],
inline = "OD")

var int deepness = input.int(


defval = 1,
title = "",
group = GroupText3,
inline = "OD",
step = 1,
minval = 1)

var bool PlayHedge = input.bool(


defval = true,
title = "Hedge Legs ",
group = GroupText3,
inline = "Hedge",
tooltip = HedgeTTIP)

var int HedgeLegDeepness = input.int(


defval = 10,
title = "",
group = GroupText3,
inline = "Hedge",
minval = 1,
maxval = 20)

var string TGTType = input.string(


defval = "Capital",
title = "Target Type ",
group = GroupText3,
inline = "TGT",
options = ["Capital", "Point Based", "Biased"])

var float TGT_Value = input.float(


defval = 12000,
title = "",
group = GroupText3,
inline = "TGT")

var string SLType = input.string(


defval = "Capital DD",
title = "Stop Loss Type ",
group = GroupText3,
inline = "SLT",
options = ["Capital DD", "Point Based", "Biased", "Point Based Trail"])

var float SL_Value = input.float(


defval = 5000,
title = "",
group = GroupText3,
inline = "SLT")

var bool LookForBiasExit = input.bool(


defval = false,
title = "Exit based On Bias Method if Possible",
group = GroupText3)

var float TrailPCT = input.float(


defval = 50,
title = "On ",
group = GroupText3,
minval = 0,
maxval = 100,
inline = "TSL") / 100

var float LockSLAt = input.float(


defval = 10,
title = "% of Target Lock SL at %",
group = GroupText3,
minval = -99,
maxval = 99,
inline = "TSL") / 100

var int StrikeDiff = input.int(


defval = 50,
title = "Strike Difference",
group = GroupText3,
minval = 1,
maxval = 5000)
//#endregion

//#region Trade Table Settings


var bool ShowTradeLogTable = input.bool(
defval = true,
title = "Show Trade Table",
inline = "TL",
group = GroupText4)

var color TableTextColor = input.color(


defval = color.orange,
title = "",
inline = "TL",
group = GroupText4)
//#endregion

//#region Declared Variables


var TradeInfoTable = table.new(position.top_right,2,4,
frame_color = color.aqua, frame_width = 1, border_width = 1, border_color =
color.aqua)
if barstate.isfirst and ShowTradeLogTable
for xrow = 0 to 3
for ycol = 0 to 1
table.cell_set_text_font_family(TradeInfoTable, ycol, xrow,
font.family_monospace)
table.cell_set_text_size(TradeInfoTable, ycol, xrow, size.small)
table.cell_set_text_color(TradeInfoTable, ycol, xrow, TableTextColor)
table.cell_set_text_halign(TradeInfoTable, ycol, xrow, ycol == 0 ?
text.align_left : text.align_center)
table.cell_set_text(TradeInfoTable, 0, 0, "Total Trades")
table.cell_set_text(TradeInfoTable, 0, 1, "Profitable Trades")
table.cell_set_text(TradeInfoTable, 0, 2, "Profitability %")
table.cell_set_text(TradeInfoTable, 0, 3, "Avg Peak Profitiablity")

varip Days_PNL = array.new_float(0)


varip OverAll_PNL = array.new_float(0)
varip MaxTradeROI_Array = array.new_float(0)
varip LogSummary = array.new_string(0)
varip float Last_TradePNL = 0.0
bool BuyShape = false
bool SellShape = false
bool ExitShape = false
type Setup
float ToBreakValue
int CrossCandle
int MaxToTradeCandle
float SLForTheTrade

var LongSetup = Setup.new()


var ShortSetup = Setup.new()
varip Log = BEL.Trade_Info.new()
Log.T_Qty := TradeQty
Log.T_QtyString := str.tostring(TradeQty)
if session.isfirstbar_regular
array.clear(Days_PNL)
Log.T_HasExited := 1
Log.T_HasEntered := 0

var string ScriptName = BEL.ScriptConvertor("Name",


syminfo.ticker)
var bool StartAllThingsWhen = false
var bool RestrictFreshEntry = false
TimeStringCalculation = barstate.isrealtime ? timenow :
time_close - 1
bool NotToTradeToday = dayofweek(TimeStringCalculation) == 4 and
AvoidOnWed
DateTimeString = str.format_time(TimeStringCalculation,
"dd-MM-yyyy HH:mm:ss", syminfo.timezone)
StartAllThingsWhen := BEL.Chk_TradingTime(sess)
RestrictFreshEntry := not
BEL.Chk_TradingTime(NoFreshEntryTime)
ChangeInTradingSession = ta.change(StartAllThingsWhen)
HasCrossOverHappened = ta.crossover(close, SMAValue) and
barstate.isconfirmed and not NotToTradeToday
HasCrossUnderHappened = ta.crossunder(close, SMAValue) and
barstate.isconfirmed and not NotToTradeToday
//#endregion

//#region EntrySetups
if HasCrossOverHappened
LongSetup.ToBreakValue := high + 5
LongSetup.CrossCandle := bar_index + 1
LongSetup.MaxToTradeCandle := bar_index + 2
LongSetup.SLForTheTrade := Log.T_HasEntered == 1 and
Log.T_Direction == -1 and bar_index > Log.NextTradeAfter ? high : na
Log.ExitCandleCheck := if not na(LongSetup.SLForTheTrade)
bar_index

if HasCrossUnderHappened
ShortSetup.ToBreakValue := low - 5
ShortSetup.CrossCandle := bar_index + 1
ShortSetup.MaxToTradeCandle := bar_index + 2
ShortSetup.SLForTheTrade := Log.T_HasEntered == 1 and
Log.T_Direction == 1 and bar_index > Log.NextTradeAfter ? low : na
Log.ExitCandleCheck := if not na(ShortSetup.SLForTheTrade)
bar_index

LongTadeEntry = false
ShortTadeEntry = false

if BEL.OperatorChk(barstate.isrealtime ? close : (TakeTrendConfirmation and


Trend_Direction == -1) ? close : high ,"G", LongSetup.ToBreakValue) and
BEL.OperatorChk(bar_index,"BE", LongSetup.CrossCandle, LongSetup.MaxToTradeCandle)
and StartAllThingsWhen
ExpectedBarstatus = if (TakeTrendConfirmation and Trend_Direction == -1) or not
IsRealTime
barstate.isconfirmed
else
true
LongTadeEntry := if ExpectedBarstatus
true

if BEL.OperatorChk(barstate.isrealtime ? close : (TakeTrendConfirmation and


Trend_Direction == 1) ? close : low ,"L", ShortSetup.ToBreakValue) and
BEL.OperatorChk(bar_index,"BE", ShortSetup.CrossCandle,
ShortSetup.MaxToTradeCandle) and StartAllThingsWhen
ExpectedBarstatus = if (TakeTrendConfirmation and Trend_Direction == 1) or not
IsRealTime
barstate.isconfirmed
else
true
ShortTadeEntry := if ExpectedBarstatus
true
//#endregion

//#region Trade Entry


varip HedgeLegOptions = array.new_string(0)
varip MainLegSymbols = array.new_string(0)
if StartAllThingsWhen and bar_index > Log.NextTradeAfter and not RestrictFreshEntry
string FinalEntryAlertText = ""
EntryAlertLegsArray = array.new_string(0)
if Log.T_HasEntered == 0
if LongTadeEntry
Log.T_EnPrice := if barstate.isrealtime
and IsRealTime
close
else
LongSetup.ToBreakValue

if PlayHedge and Log.IsFirstTradeForTheDay and FutOrOps == "FUT"


Log.IsFirstTradeForTheDay := false
array.clear(HedgeLegOptions)
for [index, value] in ListOfTradingAccount
Otype = value == "TRADINGVIEW" ?
"" : "M"
[Symbol_C, AlertString_C] =
BEL.LegScriptContructor(true, "OTM", HedgeLegDeepness, StrikeDiff,
true, "C", 0.0, 0.0, "NLB", array.get(ListOfOptionsPrefix,
index), 0, "BUY",
Log.T_QtyString, "", "", value, "MCX", Otype)
[Symbol_P, AlertString_P] =
BEL.LegScriptContructor(true, "OTM", HedgeLegDeepness, StrikeDiff,
false, "C", 0.0, 0.0, "NLB", array.get(ListOfOptionsPrefix,
index), 0, "BUY",
Log.T_QtyString, "", "", value, "MCX", Otype)
array.push(HedgeLegOptions, Symbol_C)
array.push(HedgeLegOptions, Symbol_P)
array.push(EntryAlertLegsArray, AlertString_C)
array.push(EntryAlertLegsArray, AlertString_P)
Log.HedgeCEOTM := Symbol_C
Log.HedgePEOTM := Symbol_P

Log.T_Symbol := ScriptName
array.clear(MainLegSymbols)
for [index, value] in ListOfTradingAccount
Otype = value == "TRADINGVIEW" ?
"" : "L"
[Symbol_T, AlertString_T] =
BEL.LegScriptContructor(FutOrOps == "OPS" ? true : false, IAO, deepness,
StrikeDiff,
true, "C", 0.0, 0.75, "NLB", FutOrOps == "OPS" ?
array.get(ListOfOptionsPrefix, index) : array.get(ListOfFuturePrefix, index), 0,
"BUY", Log.T_QtyString, "", "", value, "MCX", Otype, true, "0.1%")
array.push(MainLegSymbols, Symbol_T)
array.push(EntryAlertLegsArray, AlertString_T)
FinalEntryAlertText :=
BEL.LegConstructor(EntryAlertLegsArray, "NLB")
if str.length(FinalEntryAlertText) > 3
alert(FinalEntryAlertText, alert.freq_once_per_bar)
Log.T_En_Date_Time := DateTimeString
Log.T_EnCandle := bar_index
Log.T_Name := "Long | Cross Over Trade
on " + Log.T_Symbol
Log.T_HasEntered := 1
Log.T_Direction := 1
Log.T_HasExited := 0
Log.T_ExCandle := 0
Log.T_ExPrice := 0
Log.T_TGTPrice := TGTType == "Point Based"
? math.round_to_mintick(Log.T_EnPrice + TGT_Value) : TGTType == "Capital" ?
math.round_to_mintick(Log.T_EnPrice + (TGT_Value / Log.T_Qty)) : na
Log.T_SLPrice := (SLType == "Point Based"
or SLType == "Point Based Trail") ? math.round_to_mintick(Log.T_EnPrice - SL_Value)
: SLType == "Capital DD" ? math.round_to_mintick(Log.T_EnPrice - (SL_Value /
Log.T_Qty)) : na
Log.NextTradeAfter := Log.T_EnCandle
Log.LongTrades += 1
Log.AllTrades += 1
Log.DaysTrades += 1
LongSetup.ToBreakValue := na
LongSetup.CrossCandle := na
LongSetup.MaxToTradeCandle := na
Log.Price2MoveForTrailing := if SLType == "Point
Based Trail" and (TGTType == "Point Based" or TGTType == "Capital")
math.round_to_mintick(Log.T_EnPrice + (math.abs(Log.T_TGTPrice -
Log.T_EnPrice) * TrailPCT))
else
na
Log.TrailSL_Val := if not
na(Log.Price2MoveForTrailing)
if LockSLAt == 0
Log.T_EnPrice
else if LockSLAt > 0
math.round_to_mintick(Log.T_EnPrice + (math.abs(Log.T_TGTPrice
- Log.T_EnPrice) * LockSLAt))
else
math.round_to_mintick(Log.T_SLPrice + (math.abs(Log.T_SLPrice -
Log.T_EnPrice) * math.abs(LockSLAt)))
Log.SL_Level := 0
else if ShortTadeEntry
Log.T_EnPrice := if barstate.isrealtime
and IsRealTime
close
else
ShortSetup.ToBreakValue

if PlayHedge and Log.IsFirstTradeForTheDay and FutOrOps == "FUT"


Log.IsFirstTradeForTheDay := false
array.clear(HedgeLegOptions)
for [index, value] in ListOfTradingAccount
Otype = value == "TRADINGVIEW" ?
"" : "M"
[Symbol_C, AlertString_C] =
BEL.LegScriptContructor(true, "OTM", HedgeLegDeepness, StrikeDiff,
true, "C", 0.0, 0.0, "NLB", array.get(ListOfOptionsPrefix,
index), 0, "BUY",
Log.T_QtyString, "", "", value, "MCX", Otype)
[Symbol_P, AlertString_P] =
BEL.LegScriptContructor(true, "OTM", HedgeLegDeepness, StrikeDiff,
false, "C", 0.0, 0.0, "NLB", array.get(ListOfOptionsPrefix,
index), 0, "BUY",
Log.T_QtyString, "", "", value, "MCX", Otype)
array.push(HedgeLegOptions, Symbol_C)
array.push(HedgeLegOptions, Symbol_P)
array.push(EntryAlertLegsArray, AlertString_C)
array.push(EntryAlertLegsArray, AlertString_P)
Log.HedgeCEOTM := Symbol_C
Log.HedgePEOTM := Symbol_P

Log.T_Symbol := ScriptName
array.clear(MainLegSymbols)
for [index, value] in ListOfTradingAccount
Otype = value == "TRADINGVIEW" ?
"" : "L"
DirectionOfTrade = FutOrOps == "OPS" ? "BUY"
: "SELL"
[Symbol_T, AlertString_T] =
BEL.LegScriptContructor(FutOrOps == "OPS" ? true : false, IAO, deepness,
StrikeDiff,
true, "C", 0.0, 0.75, "NLB", FutOrOps == "OPS" ?
array.get(ListOfOptionsPrefix, index) : array.get(ListOfFuturePrefix, index), 0,
DirectionOfTrade, Log.T_QtyString, "", "", value, "MCX", Otype,
true, "0.1%")
array.push(MainLegSymbols, Symbol_T)
array.push(EntryAlertLegsArray, AlertString_T)
FinalEntryAlertText :=
BEL.LegConstructor(EntryAlertLegsArray, "NLB")
if str.length(FinalEntryAlertText) > 3
alert(FinalEntryAlertText, alert.freq_once_per_bar)
Log.T_En_Date_Time := DateTimeString
Log.T_EnCandle := bar_index
Log.T_Name := "Short | Cross Under
Trade on " + Log.T_Symbol
Log.T_HasEntered := 1
Log.T_Direction := -1
Log.T_HasExited := 0
Log.T_ExCandle := 0
Log.T_ExPrice := 0
Log.T_TGTPrice := TGTType == "Point Based"
? math.round_to_mintick(Log.T_EnPrice - TGT_Value) : TGTType == "Capital" ?
math.round_to_mintick(Log.T_EnPrice - (TGT_Value / Log.T_Qty)) : na
Log.T_SLPrice := (SLType == "Point Based"
or SLType == "Point Based Trail") ? math.round_to_mintick(Log.T_EnPrice +
SL_Value) : SLType == "Capital DD" ? math.round_to_mintick(Log.T_EnPrice +
(SL_Value / Log.T_Qty)) : na
Log.NextTradeAfter := Log.T_EnCandle
Log.ShortTrades += 1
Log.AllTrades += 1
Log.DaysTrades += 1
ShortSetup.ToBreakValue := na
ShortSetup.CrossCandle := na
ShortSetup.MaxToTradeCandle := na
Log.Price2MoveForTrailing := if SLType == "Point
Based Trail" and (TGTType == "Point Based" or TGTType == "Capital")
math.round_to_mintick(Log.T_EnPrice - (math.abs(Log.T_TGTPrice -
Log.T_EnPrice) * TrailPCT))
else
na
Log.TrailSL_Val := if not
na(Log.Price2MoveForTrailing)
if LockSLAt == 0
Log.T_EnPrice
else if LockSLAt > 0
math.round_to_mintick(Log.T_EnPrice - (math.abs(Log.T_TGTPrice
- Log.T_EnPrice) * LockSLAt))
else
math.round_to_mintick(Log.T_SLPrice - (math.abs(Log.T_SLPrice -
Log.T_EnPrice) * math.abs(LockSLAt)))
Log.SL_Level := 0
//#endregion

//#region Peforming Regular Exit Check


Log.ExitCandleCheck := not
barstate.isrealtime ? Log.T_EnCandle + 1 : Log.T_EnCandle
if Log.T_Direction == 1 and not na(Log.Price2MoveForTrailing) and SLType == "Point
Based Trail" and Log.SL_Level == 0
if BEL.OperatorChk(close, "GE", Log.Price2MoveForTrailing)
Log.T_SLPrice := Log.TrailSL_Val
Log.SL_Level := 1
else if Log.T_Direction == -1 and not na(Log.Price2MoveForTrailing) and SLType ==
"Point Based Trail" and Log.SL_Level == 0
if BEL.OperatorChk(close, "LE", Log.Price2MoveForTrailing)
Log.T_SLPrice := Log.TrailSL_Val
Log.SL_Level := 1

CloseCrossUnderTrend = ta.crossunder(close,
TrendLevel) and barstate.isconfirmed
CloseCrossOverTrend = ta.crossover(close,
TrendLevel) and barstate.isconfirmed

HasHitTGT = if Log.T_Direction == 1
and not na(Log.T_TGTPrice)
BEL.OperatorChk(barstate.isrealtime and IsRealTime ? close :
barstate.isrealtime and not IsRealTime and barstate.isconfirmed ? close : not
barstate.isrealtime ? high : close ,"GE", Log.T_TGTPrice)
else if Log.T_Direction == -1 and not na(Log.T_TGTPrice)
BEL.OperatorChk(barstate.isrealtime and IsRealTime ? close :
barstate.isrealtime and not IsRealTime and barstate.isconfirmed ? close : not
barstate.isrealtime ? low : close,"LE", Log.T_TGTPrice)
else
false

HasHitSL = if Log.T_Direction == 1
and not na(Log.T_SLPrice)
BEL.OperatorChk(barstate.isrealtime and IsRealTime ? close :
barstate.isrealtime and not IsRealTime and barstate.isconfirmed ? close : not
barstate.isrealtime ? low : close ,"L", Log.T_SLPrice)
else if Log.T_Direction == 1 and not na(ShortSetup.SLForTheTrade) and bar_index >
Log.ExitCandleCheck and (SLType == "Biased" or LookForBiasExit)
BEL.OperatorChk(barstate.isrealtime and IsRealTime ? close :
barstate.isrealtime and not IsRealTime and barstate.isconfirmed ? close : not
barstate.isrealtime ? low : close ,"L", ShortSetup.SLForTheTrade - 1)
else if Log.T_Direction == -1 and not na(Log.T_SLPrice)
BEL.OperatorChk(barstate.isrealtime and IsRealTime ? close :
barstate.isrealtime and not IsRealTime and barstate.isconfirmed ? close : not
barstate.isrealtime ? high : close,"G", Log.T_SLPrice)
else if Log.T_Direction == -1 and not na(LongSetup.SLForTheTrade) and bar_index >
Log.ExitCandleCheck and (SLType == "Biased" or LookForBiasExit)
BEL.OperatorChk(barstate.isrealtime and IsRealTime ? close :
barstate.isrealtime and not IsRealTime and barstate.isconfirmed ? close : not
barstate.isrealtime ? high : close,"G", LongSetup.SLForTheTrade + 1)
else
false
HasHitBias = if Log.T_Direction == 1
and CloseCrossUnderTrend and bar_index > Log.ExitCandleCheck and (SLType ==
"Biased" or LookForBiasExit)
true
else if Log.T_Direction == -1 and CloseCrossOverTrend and bar_index >
Log.ExitCandleCheck and (SLType == "Biased" or LookForBiasExit)
true

//#endregion

//#region Peforming Regular Exit of Trades


string FinalExitAlertMessage = ""
if StartAllThingsWhen
if (Log.T_HasExited == 0 and Log.T_HasEntered == 1) and bar_index >=
Log.ExitCandleCheck and (HasHitSL or HasHitTGT or HasHitBias)
ExitAlertLegsArray = array.new_string(0)
if Log.T_Direction == 1
for [index, value] in ListOfTradingAccount
if FutOrOps == "OPS"
array.push(ExitAlertLegsArray, BEL.CancelClose(true, value,
"MCX", array.get(ListOfOptionsPrefix, index)))
else if FutOrOps == "FUT"
array.push(ExitAlertLegsArray, BEL.CancelClose(false, value,
"MCX", array.get(ListOfFuturePrefix, index), "A", "S"))
FinalExitAlertMessage :=
BEL.LegConstructor(ExitAlertLegsArray, "NLB")
if str.length(FinalExitAlertMessage) > 3
alert(FinalExitAlertMessage, alert.freq_once_per_bar)
Log.T_Ex_Date_Time := DateTimeString
Log.T_ExCandle := bar_index
Log.T_ExPrice := if barstate.isrealtime
close
else if not na(ShortSetup.SLForTheTrade) and SLType == "Biased"
ShortSetup.SLForTheTrade
else if low < Log.T_SLPrice and SLType != "Biased"
Log.T_SLPrice
else if HasHitTGT
Log.T_TGTPrice
else
close
Log.NextTradeAfter := Log.T_ExCandle
Log.T_HasExited := 1
Log.T_HasEntered := 0
Log.T_Direction := 0
PNLCalc = (Log.T_ExPrice - Log.T_EnPrice) *
TradeQty
array.push(Days_PNL, PNLCalc)
array.push(OverAll_PNL, PNLCalc)
array.push(LogSummary, Log.T_En_Date_Time + " | " +
str.tostring(Log.T_EnPrice, format.mintick) + " || " + Log.T_Ex_Date_Time + " | " +
str.tostring(Log.T_ExPrice, format.mintick) + " || PNL : " +
str.tostring(PNLCalc,format.mintick))
Last_TradePNL := PNLCalc
if PNLCalc > 0
Log.ProfitableTrade += 1
if not na(ShortSetup.SLForTheTrade)
ShortSetup.SLForTheTrade := na
float yHigh = high
for x = 0 to (bar_index - Log.T_EnCandle)
yHigh := math.max(yHigh, high[x])
Log.MaxTradeROI := yHigh - Log.T_EnPrice
array.push(MaxTradeROI_Array, math.round_to_mintick(Log.MaxTradeROI))

else if Log.T_Direction == -1
for [index, value] in ListOfTradingAccount
if FutOrOps == "OPS"
array.push(ExitAlertLegsArray, BEL.CancelClose(true, value,
"MCX", array.get(ListOfOptionsPrefix, index)))
else if FutOrOps == "FUT"
array.push(ExitAlertLegsArray, BEL.CancelClose(false, value,
"MCX", array.get(ListOfFuturePrefix, index), "A", "S"))
FinalExitAlertMessage :=
BEL.LegConstructor(ExitAlertLegsArray, "NLB")
if str.length(FinalExitAlertMessage) > 3
alert(FinalExitAlertMessage, alert.freq_once_per_bar)
Log.T_Ex_Date_Time := DateTimeString
Log.T_ExCandle := bar_index
Log.T_ExPrice := if barstate.isrealtime
close
else if not na(LongSetup.SLForTheTrade) and SLType == "Biased"
LongSetup.SLForTheTrade
else if high > Log.T_SLPrice and SLType != "Biased"
Log.T_SLPrice
else if HasHitTGT
Log.T_TGTPrice
else
close
Log.NextTradeAfter := Log.T_ExCandle
Log.T_HasExited := 1
Log.T_HasEntered := 0
Log.T_Direction := 0
PNLCalc = (Log.T_EnPrice - Log.T_ExPrice) *
TradeQty
array.push(Days_PNL, PNLCalc)
array.push(OverAll_PNL, PNLCalc)
array.push(LogSummary, Log.T_En_Date_Time + " | " +
str.tostring(Log.T_EnPrice, format.mintick) + " || " + Log.T_Ex_Date_Time + " | " +
str.tostring(Log.T_ExPrice, format.mintick) + " || PNL : " +
str.tostring(PNLCalc,format.mintick))
Last_TradePNL := PNLCalc
if PNLCalc > 0
Log.ProfitableTrade += 1
if not na(LongSetup.SLForTheTrade)
LongSetup.SLForTheTrade := na
float yLow = low
for x = 0 to (bar_index - Log.T_EnCandle)
yLow := math.min(yLow, low[x])
Log.MaxTradeROI := Log.T_EnPrice - yLow
array.push(MaxTradeROI_Array, math.round_to_mintick(Log.MaxTradeROI))
else
ExitAlertString = array.new_string(0)
if Log.T_HasExited == 0 and Log.T_HasEntered == 1 and Log.T_Direction != 0
for [index, value] in ListOfTradingAccount
array.push(ExitAlertString, BEL.CancelClose(true, value, "MCX",
array.get(ListOfOptionsPrefix, index)))
array.push(ExitAlertString, BEL.CancelClose(true, value, "MCX",
array.get(ListOfFuturePrefix, index)))
AlertMessage =
BEL.LegConstructor(ExitAlertString, "NLB")
alert(AlertMessage, alert.freq_once_per_bar)
Log.T_Ex_Date_Time := DateTimeString
Log.T_ExCandle := bar_index
Log.T_ExPrice := barstate.isrealtime ? close :
ohlc4
Log.NextTradeAfter := bar_index + 100
PNLCalc = if Log.T_Direction == 1
(Log.T_ExPrice - Log.T_EnPrice) * TradeQty
else if Log.T_Direction == -1
(Log.T_EnPrice - Log.T_ExPrice) * TradeQty
float y = Log.T_Direction == 1 ? high : low
for x = 0 to (bar_index - Log.T_EnCandle)
if Log.T_Direction == -1
y := math.min(y, low[x])
else
y := math.max(y, high[x])
Log.MaxTradeROI := Log.T_Direction == -1 ?
Log.T_EnPrice - y : y - Log.T_EnPrice
array.push(MaxTradeROI_Array, math.round_to_mintick(Log.MaxTradeROI))
Log.T_Direction := 0
array.push(Days_PNL, PNLCalc)
array.push(OverAll_PNL, PNLCalc)
array.push(LogSummary, Log.T_En_Date_Time + " | " +
str.tostring(Log.T_EnPrice, format.mintick) + " || " + Log.T_Ex_Date_Time + " | " +
str.tostring(Log.T_ExPrice, format.mintick) + " || PNL : " +
str.tostring(PNLCalc,format.mintick))
Last_TradePNL := PNLCalc
if PNLCalc > 0
Log.ProfitableTrade += 1
LongSetup.SLForTheTrade := na
ShortSetup.SLForTheTrade := na
Log.T_HasExited := 1
Log.T_HasEntered := 0
//#endregion

//#region Trade Entry Exit Plot


if ta.change(Log.T_HasEntered) and Log.T_Direction == -1 and Log.T_HasEntered == 1
SellShape := true
if ta.change(Log.T_HasEntered) and Log.T_Direction == 1 and Log.T_HasEntered == 1
BuyShape := true
if ta.change(Log.T_HasExited) and Log.T_Direction == 0 and Log.T_HasExited == 1
ExitShape := true
//#endregion

plotshape(BuyShape, "Long Trade Entry", shape.triangleup,


location.belowbar, color.green, 0, size = size.tiny, display = display.all -
display.price_scale - display.status_line, text = "LE", textcolor = color.white)
plotshape(SellShape , "Short Trade Entry", shape.triangledown,
location.abovebar, color.red, 0, size = size.tiny, display = display.all -
display.price_scale - display.status_line, text = "SE", textcolor = color.white)
plotshape(ExitShape , "Trade Exit", shape.xcross,
location.abovebar, color.orange, 0, size = size.tiny, display = display.all -
display.price_scale - display.status_line, text = "EX", textcolor = color.white)

if barstate.islast and ShowTradeLogTable


for x = 0 to 3
switch x
0 => table.cell_set_text(TradeInfoTable, 1, x,
str.tostring(Log.AllTrades))
1 =>
table.cell_set_text(TradeInfoTable, 1, x,
str.tostring(Log.ProfitableTrade))
table.cell_set_bgcolor(TradeInfoTable, 1, x, Log.ProfitableTrade >
0 ? color.rgb(25, 56, 26) : color.rgb(109, 42, 42))
table.cell_set_text_color(TradeInfoTable, 1, x, color.white)
2 =>
table.cell_set_text(TradeInfoTable, 1, x,
str.tostring(math.round(Log.ProfitableTrade / Log.AllTrades, 2) * 100) + "%")
table.cell_set_bgcolor(TradeInfoTable, 1, x, Log.ProfitableTrade >
0 ? color.rgb(25, 56, 26) : color.rgb(109, 42, 42))
table.cell_set_text_color(TradeInfoTable, 1, x, color.white)
3 =>
table.cell_set_text(TradeInfoTable, 1, x,
str.tostring(math.round(array.avg(MaxTradeROI_Array),2)))
table.cell_set_text_color(TradeInfoTable, 1, x, color.white)

You might also like